Repository navigation
Conversation
e1c5f01 to
3644828
Compare
|
@coderabbitai review |
✅ Actions performedReview triggered.
|
📝 WalkthroughWalkthroughThis PR implements cloud storage architectural improvements and a new health check system. It introduces a layered S3-compatible storage architecture with shared base abstractions, provider-specific implementations for AWS, GCP, and R2, and a native Google Cloud Storage integration. Additionally, it establishes a modular, orchestrator-friendly health check framework with caching, per-indicator timeouts, and Kubernetes-style endpoints. Changes
Sequence DiagramssequenceDiagram
participant Client as Client Application
participant Upload as Upload Strategy
participant Endpoint as Endpoint Config
participant S3 as S3Client
participant Provider as Cloud Provider
Client->>Upload: uploadData(credentials, bucket, region, path, data)
activate Upload
Upload->>Endpoint: buildBucketUri(bucket, region)
Endpoint-->>Upload: bucket endpoint URI
alt Multipart Strategy
Upload->>Upload: Build presigned policy (SigV4)
Upload->>S3: Sign policy
else Presigned PUT Strategy
Upload->>S3: buildSignedParams(key, method=PUT)
S3-->>Upload: SignedRequestParams
end
Upload->>Provider: HTTP POST/PUT (with signature)
Provider-->>Upload: 200/204 Success
Upload-->>Client: Public file URL
deactivate Upload
sequenceDiagram
participant HTTP as HTTP Request
participant Server as Serverpod Server
participant Service as HealthCheckService
participant Indicators as Health Indicators
participant Cache as Result Cache
HTTP->>Server: GET /readyz
activate Server
Server->>Service: checkReadiness()
activate Service
Service->>Cache: Check cached results (TTL)
alt Cache Hit
Cache-->>Service: Cached results
else Cache Miss
Service->>Indicators: Execute all indicators in parallel
activate Indicators
loop Per Indicator
Indicators->>Indicators: runWithTimeout(5s default)
Indicators-->>Service: HealthCheckResult (pass/fail)
end
deactivate Indicators
Service->>Cache: Store results with TTL
end
Service->>Service: Aggregate results by name
Service-->>Server: HealthResponse (status, checks, notes)
deactivate Service
alt Authenticated
Server-->>HTTP: 200/503 + JSON body
else Unauthenticated
Server-->>HTTP: 200/503 (empty body)
end
deactivate Server
Estimated code review effort🎯 4 (Complex) | ⏱️ ~60 minutes The changes span multiple subsystems (cloud storage refactoring with 4 provider integrations, new health check framework, client updates) with heterogeneous patterns including design docs, new abstractions, legacy cleanup, configuration changes, and extensive test coverage. While individual files follow consistent patterns, the scope requires understanding interactions between storage strategies/endpoints, health indicator lifecycle management, and server integration points. Possibly related PRs
🚥 Pre-merge checks | ✅ 4 | ❌ 1❌ Failed checks (1 warning)
✅ Passed checks (4 passed)
✏️ Tip: You can configure your own custom pre-merge checks in the settings. ✨ Finishing Touches
🧪 Generate unit tests (beta)
Thanks for using CodeRabbit! It's free for OSS, and your support helps us grow. If you like it, consider giving us a shout-out. Comment |
There was a problem hiding this comment.
Actionable comments posted: 19
🤖 Fix all issues with AI agents
In `@docs/design/cloud_storage.md`:
- Around line 38-76: Update the markdown to satisfy markdownlint by labeling the
leading code fence with a language (e.g., replace the unlabeled ``` with ```text
for the integrations tree) and normalize the table separator row in the
S3UploadStrategy table to include spaces around pipes (e.g., change
"|----------|--------------|----------------|" to "| -------- | ------------- |
-------------- |") so the fenced block and the table separators conform to lint
rules; apply these edits where S3EndpointConfig and S3UploadStrategy are defined
in the document.
In `@docs/design/health_check.md`:
- Line 182: Replace the bare URL in the sentence "Health endpoints should return
JSON following the draft RFC: _Health Check Response Format for HTTP APIs_
(https://datatracker.ietf.org/doc/html/draft-inadarei-api-health-check-06)" with
a markdown link; change the parenthetical URL to a markdown link like [_Health
Check Response Format for HTTP
APIs_](https://datatracker.ietf.org/doc/html/draft-inadarei-api-health-check-06)
so the reference satisfies the linter and preserves the existing text and
emphasis.
In
`@integrations/serverpod_cloud_storage_gcp/lib/src/native/native_google_cloud_storage.dart`:
- Around line 337-338: The canonicalUri is built using raw path which breaks for
spaces/Unicode; update the construction in native_google_cloud_storage.dart to
URL-encode path segments before joining them into the canonicalUri (e.g. split
path on '/', encode each segment with Uri.encodeComponent and rejoin with '/');
also encode the bucket name similarly (use Uri.encodeComponent(bucket)) so
canonicalUri becomes '/{encodedBucket}/{encodedPathSegments}'. This ensures
special characters are correctly percent-encoded while preserving segment
separators.
- Around line 289-299: The TOCTOU occurs in createDirectFileUploadDescription
where it checks _signingCredentialsCompleter.isCompleted; instead await the
completer instead of short-circuiting: await _signingCredentialsCompleter.future
(or await with a short timeout) to obtain credentials set up by
_initializeAsync, and wrap that await in try/catch to return null only on
timeout or initialization errors rather than whenever isCompleted was false at
call time; update references to _signingCredentialsCompleter and any code that
reads the credentials in createDirectFileUploadDescription to use the awaited
result.
In
`@integrations/serverpod_cloud_storage_gcp/test/native/native_google_cloud_storage_test.dart`:
- Around line 275-284: The test title is misleading:
createDirectFileUploadDescription on storage (constructed via withStorageApi)
returns null because withStorageApi does not supply signing credentials, not
because the feature is unimplemented; update the test to reflect that (e.g.,
"returns null when signing credentials are not provided") or change the setup to
provide signing credentials so the call to
createDirectFileUploadDescription(session: mockSession, path: 'upload.txt')
returns a real description; adjust the test name and/or setup accordingly and
keep references to createDirectFileUploadDescription, withStorageApi,
mockSession, and storage to locate the code.
In
`@integrations/serverpod_cloud_storage_s3_compat/lib/src/client/s3_client.dart`:
- Around line 70-98: The canonical path used for SigV4 signing is built as
encodedPath from unencodedPath but currently prepends an extra '/' causing a
double-leading-slash and invalid signatures; update the construction of
encodedPath in s3_client.dart (the variable encodedPath that feeds SigV4
canonical request creation) to avoid adding an extra leading '/' — instead
URL-encode each segment of unencodedPath and join them with '/', preserving a
single leading slash (i.e., use the segments of unencodedPath and only add a
leading slash if unencodedPath does not already start with one) so the canonical
request used by SigV4.hashCanonicalRequest('') and
SigV4.buildCanonicalQueryString(...) is correct.
In
`@integrations/serverpod_cloud_storage_s3_compat/lib/src/endpoints/aws_endpoint_config.dart`:
- Around line 18-48: The _joinPaths used by buildPublicUri can produce double
slashes when callers pass a path that starts with '/', so update _joinPaths
(and/or call-site in buildPublicUri) to normalize the incoming path by removing
any leading '/' (and treating empty or '/' as empty) before concatenation;
specifically, in _joinPaths ensure you trim a single leading slash from the
parameter `path` and then join with the normalized basePath so the returned path
never contains '//' while still preserving a single leading '/' for the final
URI.
In
`@integrations/serverpod_cloud_storage_s3_compat/lib/src/s3_compat_cloud_storage.dart`:
- Around line 108-145: The code currently treats any non-200 response as
"missing" — update retrieveFile, getPublicUrl (which calls fileExists),
fileExists, and deleteFile to distinguish 404/not-found from other errors: call
_client.getObject/_client.headObject/_client.deleteObject and if statusCode ==
200 (or success for delete) proceed as now; if statusCode == 404 return null
(for retrieveFile/getPublicUrl) or false (for fileExists); for any other
statusCode throw a descriptive exception that includes response.statusCode and
response body (or message) so permission/config/server errors surface; ensure
deleteFile similarly throws on non-404 non-success responses instead of silently
ignoring failures.
In
`@integrations/serverpod_cloud_storage_s3_compat/lib/src/upload/multipart_post_strategy.dart`:
- Around line 74-76: The returned object URL construction drops the bucket path
for path-style endpoints; in the response handling where you check
response.statusCode == 204, instead of uploadUri.replace(path:
'/${policy.key}'), build the new path by preserving uploadUri.path and appending
policy.key (handling slashes to avoid duplicates) and call
uploadUri.replace(path: newPath). Update the code around the response.statusCode
== 204 branch that uses uploadUri and policy.key so path-style endpoints keep
the original path segment(s) and only append the object key.
In `@integrations/serverpod_cloud_storage_s3_compat/lib/src/upload/policy.dart`:
- Around line 92-106: The toString override builds the policy JSON via manual
string interpolation which can break with quotes/control chars; instead
construct a Dart Map representing the policy using the same keys (expiration,
conditions) and the field names used in this class (expiration, bucket, key,
public, maxFileSize, credential, datetime) and return jsonEncode(map) so all
values are safely escaped; update the toString method to build that Map
(including the ["starts-with", "$key" ...] and content-length-range entries and
the acl computed from public) and call jsonEncode to produce the final string.
In
`@integrations/serverpod_cloud_storage_s3_compat/lib/src/upload/presigned_put_strategy.dart`:
- Around line 41-43: The code uses data.buffer.asUint8List() which exposes the
entire underlying buffer; instead slice the buffer to the ByteData view bounds
to avoid including unrelated bytes — replace the payloadBytes assignment to use
data.buffer.asUint8List(data.offsetInBytes, data.lengthInBytes) (keep the
payloadHash computation unchanged) so the SHA256 is computed only over the
ByteData view referenced by data.
- Around line 46-55: The canonical request currently injects objectPath raw into
the string (symbol: canonicalRequest in presigned_put_strategy.dart), which
breaks SigV4 signing for paths with spaces or reserved/UTF-8 chars; change to
percent-encode each path segment before building the canonical request (split
objectPath on '/', encode each segment with Uri.encodeComponent(), then rejoin
with '/' to preserve delimiters), and replace raw objectPath usage in both
places where canonicalRequest is constructed (the PUT canonicalRequest and the
second occurrence around the later string build) so the signed string matches S3
SigV4 expectations (use the same encoding approach as s3_client.dart).
In
`@integrations/serverpod_cloud_storage_s3_compat/test/upload/multipart_post_strategy_test.dart`:
- Around line 6-12: The test description misses the "when" clause; update the
test case for MultipartPostUploadStrategy (the test with the expect on
strategy.uploadType) to follow "Given ... when ... then ..." — for example
change the test name to include a when clause like "when constructed" or "when
created" so it reads: Given a MultipartPostUploadStrategy when constructed then
uploadType is multipart; keep the assert on strategy.uploadType unchanged.
In
`@integrations/serverpod_cloud_storage_s3_compat/test/upload/presigned_put_strategy_test.dart`:
- Around line 6-12: The test description omits the "when" clause in the
Given/When/Then chain; update the test title inside the test(...) that asserts
strategy.uploadType to include a "when" action (e.g., "when accessing
uploadType") so the full phrase reads "Given a PresignedPutUploadStrategy when
accessing uploadType then uploadType is binary"; locate the test in
main/group('Given a PresignedPutUploadStrategy', ...) that creates final
strategy = PresignedPutUploadStrategy() and change the test name accordingly to
follow the Given/When/Then pattern.
In `@packages/serverpod_client/lib/src/file_uploader.dart`:
- Around line 46-65: The code must explicitly reject presigned PUT uploads
without a known content length instead of implicitly buffering; before creating
or sending the http.StreamedRequest (i.e., before using
_uploadDescription.method, request, stream.pipe or request.send), check if
_uploadDescription.method (case-insensitive) is 'PUT' and length is null and
throw an ArgumentError with a clear message like "PUT uploads require a known
content length" so the library avoids buffering and fails fast for S3/GCS/R2
presigned PUTs.
In `@packages/serverpod_client/test/file_uploader_test.dart`:
- Around line 7-81: Update the test descriptions to follow "Given, When, Then"
by adding an explicit "when" clause to each test name while keeping each phrase
only once; e.g. change the test strings inside the groups like "then
FileUploader parses it without error" to "when parsing the description then
FileUploader parses it without error" (apply similarly for the binary POST/PUT
and invalid-description tests), ensuring you edit the test() description
arguments in the file_uploader_test.dart tests that reference the FileUploader
parsing scenarios.
In `@packages/serverpod/lib/src/redis/controller.dart`:
- Around line 315-330: The ping() method currently returns false for non-PONG
results but leaves the cached _command intact; change ping() so that after
awaiting _command?.send_object(['PING']) you check the result and if it is not
exactly 'PONG' call _invalidateCommand() before returning false, ensuring that
subsequent calls to _connect() will re-establish a fresh connection; keep the
existing try/catch behavior (also call _invalidateCommand() in the catch block
as it already does).
In `@packages/serverpod/lib/src/server/health/health_indicator.dart`:
- Around line 27-35: The example implementation of HealthIndicator<double>
returns an enum value for the componentType getter which is declared to return
String; update the componentType getter in the example (in the
HealthIndicator<double> snippet) to return HealthComponentType.component.name
(use the enum's .name) so the getter returns a String and avoids copy‑paste
compile errors.
In `@packages/serverpod/test/server/health/health_response_test.dart`:
- Around line 31-236: Reorder the test groups that call
HealthResponse.fromResults so success cases appear before failure cases: move
the groups titled "Given empty results when HealthResponse.fromResults is
called" and "Given multiple results with same name when
HealthResponse.fromResults is called" (and the "Given all passing results when
HealthResponse.fromResults is called" group if not already before failures) to
precede the groups "Given one failing result when HealthResponse.fromResults is
called", "Given multiple failing results when HealthResponse.fromResults is
called", and "Given failing result without output when
HealthResponse.fromResults is called"; keep the HealthResponse.alive() group
as-is. Ensure grouping and usage of HealthResponse.fromResults, and the helper
functions (_pass, _fail) remain unchanged.
🧹 Nitpick comments (6)
integrations/serverpod_cloud_storage_s3_compat/lib/src/endpoints/r2_endpoint_config.dart (1)
52-60: Consider centralizing_joinPathsto avoid drift across endpoint configs.The helper is duplicated in other endpoint configs; a shared utility keeps path normalization consistent.
packages/serverpod/lib/src/server/health/health_check_service.dart (1)
134-134: Remove unnecessaryunawaitedwrapper.
Map.remove()returns the removed value synchronously, not aFuture. Theunawaited()function is intended forFutureobjects to suppress theunawaited_futureslint. Here it serves no purpose.♻️ Proposed fix
} finally { - unawaited(_pendingChecks.remove(indicator.name)); + _pendingChecks.remove(indicator.name); }integrations/serverpod_cloud_storage_gcp/lib/src/native/native_google_cloud_storage.dart (4)
87-96: Consider documenting test-mode limitation in a more prominent way.The
withStorageApiconstructor silently disables direct uploads. Users might be surprised whencreateDirectFileUploadDescriptionreturns null.📝 Proposed documentation improvement
/// Creates a [NativeGoogleCloudStorage] with an already-initialized /// [StorageApi]. /// /// This constructor is primarily intended for testing purposes. /// /// Note: Direct upload via signed URLs is not available when using this /// constructor, as signing credentials are not provided. + /// [createDirectFileUploadDescription] will return `null`. NativeGoogleCloudStorage.withStorageApi({
158-187: Consider adding validation for unexpected ASN.1 structures.The parser assumes specific element counts and types. Malformed PEM could cause index-out-of-bounds or cast errors with unclear messages.
🛡️ Proposed defensive validation
RSAPrivateKey _parsePrivateKeyFromPem(String pem) { final lines = pem .split('\n') .where((line) => !line.startsWith('-----')) .join(); final bytes = base64.decode(lines); final asn1Parser = ASN1Parser(Uint8List.fromList(bytes)); final topLevelSeq = asn1Parser.nextObject() as ASN1Sequence; + if (topLevelSeq.elements == null || topLevelSeq.elements!.isEmpty) { + throw FormatException('Invalid private key PEM: empty ASN.1 sequence'); + } + // PKCS#8 format: PrivateKeyInfo ::= SEQUENCE { version, algorithm, privateKey } // The privateKey is an OCTET STRING containing the RSA private key ASN1Sequence rsaSeq; if (topLevelSeq.elements!.length == 3) { // PKCS#8 format final privateKeyOctet = topLevelSeq.elements![2] as ASN1OctetString; final pkParser = ASN1Parser(privateKeyOctet.valueBytes); rsaSeq = pkParser.nextObject() as ASN1Sequence; } else { // PKCS#1 format (raw RSA key) rsaSeq = topLevelSeq; } + if (rsaSeq.elements == null || rsaSeq.elements!.length < 6) { + throw FormatException( + 'Invalid RSA private key: expected at least 6 elements, ' + 'got ${rsaSeq.elements?.length ?? 0}', + ); + } + final modulus = (rsaSeq.elements![1] as ASN1Integer).integer!;
244-256: Potential performance concern:fileExistscall for public URL generation.
getPublicUrlmakes a network call to check file existence. If callers already know the file exists, this is an unnecessary round-trip. Consider documenting this behavior or providing an unchecked variant.
410-413:_uriEncodereplaces+unnecessarily.
Uri.encodeComponentdoes not produce+for spaces (it uses%20). ThereplaceAll('+', '%2B')is a no-op and suggests a misunderstanding of the encoding behavior.📝 Simplify or clarify the encoding
/// URI-encodes a string according to RFC 3986. String _uriEncode(String input) { - return Uri.encodeComponent(input).replaceAll('+', '%2B'); + // Uri.encodeComponent is RFC 3986 compliant; '+' is already encoded as %2B + return Uri.encodeComponent(input); }
6e99c99 to
d137cf1
Compare
a9bebe3 to
512c3af
Compare
512c3af to
2a7646b
Compare
0e60c21 to
35e50ea
Compare
| final authClient = await clientViaServiceAccount( | ||
| credentials, | ||
| [gcs.StorageApi.devstorageFullControlScope], | ||
| ); |
There was a problem hiding this comment.
Hey, just saw the draft and wanted to give my 2 cents here.
I would suggest changing this to use clientViaApplicationDefaultCredentials instead, e.g. something like:
final client = auth.clientViaApplicationDefaultCredentials(
scopes: ['https://www.googleapis.com/auth/cloud-platform'],
);The reason is that clientViaApplicationDefaultCredentials has an internal logical order for checking credentials and will call the meta server in a kubernetes cluster for access, meaning you can do a keyless setup. But it will also work nicely if you have local credentials from your gcloud cli, meaning by using clientViaApplicationDefaultCredentials you can both have a very clean production setup and a simple dev setup. There are also environment variables this method is looking for for service accounts.
Additionally, I would argue for allowing to pass in an HttpClient into the constructor to override the default one, this is a convenient way to configure the bucket integration to talk with a mock server such as https://github.com/fsouza/fake-gcs-server or just use a mock http client.
There was a problem hiding this comment.
@Isakdl What about signing? Application Default Credentials don't allow for that, do they?
There was a problem hiding this comment.
I guess we could look into the IAM signBlob API 🤔
There was a problem hiding this comment.
Yeah precisely, I pinged you on slack already, but to keep the history
This type of call can be used to sign the payload:
await _iamCredentials.projects.serviceAccounts.signBlob(
SignBlobRequest(payload: base64.encode(stringToSignList)),
'projects/-/serviceAccounts/$_serviceAccountEmail',
);There is one drawback with this approach, in that the user must provide the service account email. In the JSON credential blob this is usually included, but when using the applicationDefault, you cannot get the service account email, at least not in all the auth paths.
Add comprehensive unit tests for the native GCP cloud storage implementation using mocktail to mock the StorageApi. Tests cover: - File existence checking (exists, not found, error handling) - File storage (public and private ACLs) - File retrieval (success and not found) - Public URL generation (default and custom hosts) - File deletion (success, already deleted, error handling) - Direct upload (returns null - not yet implemented) - Upload verification Also adds withStorageApi constructor for testing purposes.
Add the new serverpod_cloud_storage_s3_compat package as a dependency override in test server pubspecs to resolve package resolution errors. Updated: - tests/serverpod_test_server/pubspec.yaml - tests/serverpod_test_nonvector/serverpod_test_nonvector_server/pubspec.yaml - tests/serverpod_auth_test/serverpod_auth_test_server/pubspec.yaml - Corresponding template files
The URL returned by uploadData was never used by callers. Removing it avoids returning potentially incorrect URLs for path-style endpoints.
- Move setup code from group level into setUp() callbacks - Use groups with setUp() when tests share common setup - Use standalone multiline tests when no shared setup needed - Fix When-Then ordering (was Then-When in some places) - Remove redundant 'for X tests' from group descriptions
…criptions The createDirectFileUploadDescription method was ignoring the public configuration flag, causing all direct uploads to use the default ACL. This fix: - Sets x-goog-acl header based on public setting (public-read or private) - Includes content-type and x-goog-acl in the signed URL headers - Returns the ACL header in the upload description for clients to send
Add real integration tests for AWS S3, Cloudflare R2, and GCP cloud storage that run against actual cloud services with credentials from environment variables or GitHub secrets. - Add shared test helper in s3_compat package for all S3-compatible providers - Add integration tests for AWS S3, Cloudflare R2, and GCP (HMAC) - Add GitHub Actions workflow with matrix for all providers - Add local test runner script (util/run_tests_integration_cloud) - Add INTEGRATION_TESTING.md with setup instructions Tests automatically skip when credentials are not configured.
…orageAccess Add optional maxFileSize, expirationDuration, and contentLength parameters to StorageAccess.createDirectFileUploadDescription, forwarding them to the underlying CloudStorage implementations. When contentLength is provided: - Validated against maxFileSize (throws if exceeded) - Signed into presigned PUT URLs for R2 and NativeGCS, enabling server-side enforcement of exact file size - For S3/GCP HMAC (multipart POST), content-length-range policy already enforces maxFileSize When contentLength is omitted, behavior is unchanged (backwards compatible). Closes: serverpod#4733
…ctFileUpload integration tests
Replace googleapis_auth 2.1.0 built-in signing with: - pointycastle RSA-SHA256 for service account credentials (local signing) - IAM signBlob API for Application Default Credentials (remote signing) - GCE metadata server for service account email discovery This avoids the googleapis_auth ^2.1.0 -> google_cloud ^0.3.0 -> meta ^1.18.1 transitive dependency chain that forces Flutter 3.38.1+.
Add optional named preventOverwrite parameter to both storeFile and createDirectFileUploadDescription. If set to `true` it prevents uploading to a path where an object already exists, if supported by the specific provider. - GCS native: ifGenerationMatch: '0' (storeFile) / x-goog-if-generation-match: 0 (direct upload) - S3 presigned PUT (AWS, R2): If-None-Match: * header - S3 multipart POST: not supported (flag is accepted but ignored)
Constructors that perform async initialization (service account JSON, ADC) are now static async factory methods that return a fully-initialized instance. This eliminates the race between isCompleted checks and async init, and removes the ambiguity between "not configured" and "still initializing". - create(): loads credentials from Serverpod password system - fromServiceAccountJson(): authenticates with explicit JSON - fromApplicationDefaultCredentials(): uses ADC - withStorageApi / withSigningCredentials: remain sync (test-only) - withAuthClient: new test constructor for ADC signing path Also add unit tests for the IAM signBlob signing path via the withAuthClient constructor and a MockAuthClient.
Replace _detectMimeType in both NativeGoogleCloudStorage and PresignedPutUploadStrategy with lookupMimeType from the mime package. The mime package was already a transitive dependency and provides a more comprehensive and maintained MIME type database. Also fix integration test to use async fromServiceAccountJson factory.
- Fix silent error swallowing: retrieveFile, fileExists, and deleteFile now properly distinguish 404 from server errors (5xx) instead of treating all non-200 responses as 'not found' - Add public check to getPublicUrl to skip HEAD request for non-public storage (matching NativeGoogleCloudStorage behavior) - Fix HTTP client leak in PresignedPutUploadStrategy.uploadData by properly creating and closing an http.Client instead of using the global http.put() function - Add close() to S3Client and S3CompatCloudStorage for resource cleanup - Fix ByteData buffer aliasing in retrieveFile by using ByteData.sublistView instead of ByteData.view(bytes.buffer) - Fix Policy expiration to use proper ISO 8601 formatting instead of relying on DateTime.toString() which produces microsecond precision - Rename misnamed cloud_storage.dart directory to cloud_storage in S3 package and replace placeholder library docs - Improve GCP HMAC credential error messages to include env var hints - Document MultipartPostUploadStrategy preventOverwrite limitation
bafa42e to
bb9d73c
Compare
|
Closing this to open again in serverpod (this will (/should) allow cloud storage integration tests to run. |
|
Superseded by #4766 |
Refactor cloud storage with shared S3-compatible base package
Introduces a layered architecture for cloud storage integrations, eliminating ~98% code duplication between S3 and GCP packages while adding support for new providers.
Shared base package (
serverpod_cloud_storage_s3_compat)S3CompatCloudStoragebase implementation using configurable abstractionsS3EndpointConfiginterface with implementations for AWS, GCP, R2, and custom endpointsS3UploadStrategyinterface with multipart POST (AWS/GCP/MinIO) and presigned PUT (R2) strategiesS3Clientfor signed S3 API requests with proper resource lifecycle (close())Native Google Cloud Storage (
NativeGoogleCloudStorage)signBlobAPI and GCE metadata serverpointycastle(avoidsgoogleapis_auth^2.1.0 dependency chain that forces Flutter 3.38.1+)create(),fromServiceAccountJson(),fromApplicationDefaultCredentials()New features
preventOverwriteparameter onstoreFileandcreateDirectFileUploadDescription— prevents uploading to an existing path (GCS native:ifGenerationMatch: '0'; S3 presigned PUT:If-None-Match: *; S3 multipart POST: not supported)maxFileSize,expirationDuration, andcontentLengthexposed onStorageAccess.createDirectFileUploadDescription. WhencontentLengthis provided it is validated againstmaxFileSizeand signed into presigned PUT URLs, enabling server-side enforcement of exact file sizeserverpod_cloud_storage_r2package for Cloudflare R2 supportFileUploaderupdated to support PUT method and custom headers for R2-style uploadsHardening & cleanup
retrieveFile,fileExists, anddeleteFilenow properly distinguish 404 from 5xx errorsPresignedPutUploadStrategy.uploadDataByteDatabuffer aliasing inretrieveFileusingByteData.sublistViewPolicyexpiration to use proper ISO 8601 formattingclose()toS3ClientandS3CompatCloudStoragefor resource cleanupmimepackageCompleterpattern with async factory constructors (eliminates race betweenisCompletedchecks and async init)Fixes #4623
Fixes #4588
Fixes #4733
Related:
Pre-launch Checklist
///), and made sure that the documentation follows the same style as other Serverpod documentation. I checked spelling and grammar.If you need help, consider asking for advice on the discussion board.
Breaking changes
None. Refactored packages maintain full backwards compatibility with same constructor parameters and environment variable names.
NativeGoogleCloudStorageconstructors changed from sync+Completer to async factories, but this is a new class with no existing users.