Skip to content

feat: Add local filesystem cloud storage adapter - #5305

Open
realmeylisdev wants to merge 2 commits into
serverpod:mainfrom
realmeylisdev:feature/local-cloud-storage
Open

realmeylisdev wants to merge 2 commits into
serverpod:mainfrom
realmeylisdev:feature/local-cloud-storage

Conversation

@realmeylisdev

Copy link
Copy Markdown
Contributor

Closes #1817

Supersedes #4525 — rebuilt from scratch on current main instead of rebasing, since main has since restructured the integrations (s3_compat/r2, generated pubspecs, shared testing conventions) and the old branch was conflicting. All review feedback from #4525 is addressed (details below).

Summary

Adds serverpod_cloud_storage_local, a CloudStorage adapter that stores files on the server's local filesystem — no external cloud provider and no database tables. Useful for development, testing, and self-hosted deployments.

pod.addCloudStorage(LocalCloudStorage(
  'public',
  storagePath: '/var/serverpod/storage',
));
  • Mirrors DatabaseCloudStorage where possible: no Serverpod constructor dependency, public URLs keyed on storageId == 'public' and served by the built-in /serverpod_cloud_storage endpoint, same exception conventions.
  • Implements the CloudStorageWithOptions mixin (preventOverwrite, contentLength) with the same semantics as DatabaseCloudStorage.
  • Streaming helpers (storeFileStream / retrieveFileStream / getFileSize) for memory-efficient large-file handling. These are extra public API beyond the CloudStorage interface — happy to trim them if you prefer the minimal surface.
  • Opt-in expiration cleanup (startCleanupScheduler / cleanupExpiredFiles).

How the .meta files work (answering the question from #4525)

Expiration and verification state live in a small JSON sidecar (<file>.meta) next to the data file:

  • A sidecar is written only when needed (expiration set or verified: false). A plain store removes any stale sidecar, so re-storing a path cannot inherit old expiration/verification state.
  • The sidecar is written before the data file, so a failure between the two writes fails closed (the file stays hidden) instead of exposing an unverified file. A failed store also cleans up the partial data file.
  • Read paths (retrieveFile, fileExists, getPublicUrl, streams) treat files without a sidecar as verified and non-expiring, unverified or expired files as absent, and corrupt/unparseable sidecars as unavailable (fail closed).
  • verifyDirectFileUpload flips a pending verified: false sidecar to verified (keeping the expiration), mirroring DatabaseCloudStorage (returns false for missing or already-verified files).
  • The .meta suffix is reserved: user paths ending in .meta are rejected — in any casing, since macOS/Windows filesystems are case-insensitive — so metadata cannot be forged or read through the public API.
  • cleanupExpiredFiles walks the storage directory and deletes expired data+sidecar pairs. The optional scheduler runs it periodically; runs are reentrancy-guarded and errors never escape to the timer.

Path safety

Paths are sanitized with package:path (normalize + rootPrefix/relative, as suggested in the previous review): backslashes are treated as separators, absolute paths become relative, and anything that would escape the storage directory throws a CloudStorageException — the silent 'file' fallback questioned in #4525 is gone. Segments containing : or ending in ./space are rejected (Windows drive letters, NTFS alternate data streams, trailing-dot aliasing), and a final p.isWithin guard catches Windows drive-qualified edge cases. Covered by tests for ../ chains, mixed separators, absolute paths, and .meta casing variants.

Feedback from #4525 addressed

  • ✅ Package CHANGELOG.md/README.md are the root copies maintained by util/update_pubspecs (cp lines added); the pubspec is generated from templates/pubspecs/ like all siblings
  • ✅ Registered in util/all_packages, util/run_tests_analyze, and PUBLISHABLE_PACKAGES
  • ✅ LICENSE copied verbatim from the sibling integration packages (they all use the same 2020 text — happy to update the year if you'd rather)
  • ✅ p.rootPrefix/p.relative sanitization; redundant manual filtering removed; escaping paths throw
  • ✅ Fully async file IO (zero *Sync() calls, no constructor IO)
  • ✅ Uint8List.sublistView(byteData) for writes (and ByteData.sublistView for reads, which also fixes a latent offset bug)
  • ✅ No un-awaited futures: the cleanup timer callback is explicitly unawaited(...) and cleanup contains its own errors
  • ✅ Short mention added next to S3/GCP in the main README.md; docs/design/cloud_storage.md diagram updated. I'll prepare a serverpod_docs PR with usage documentation once this lands.

Notes for reviewers / open questions

  1. Public endpoint registration: core registers CloudStoragePublicEndpoint only when a DatabaseCloudStorage is registered (_unguardedStart in serverpod.dart). That holds in the default setup via the 'private' storage, but if a user replaces both storages with LocalCloudStorage (or disables the database feature), getPublicUrl URLs would 404. This is documented on the class; if you'd like, I can extend the core registration condition in this PR — the endpoint's file method is already storage-agnostic.
  2. Traversal probes against the public endpoint now surface as a thrown CloudStorageException (→ error log) rather than a 404, since invalid paths throw by design. If that's a concern, CloudStoragePublicEndpoint.file could map CloudStorageException to EndpointNotFoundException — say the word and I'll include it.
  3. Direct file uploads are intentionally unsupported (createDirectFileUploadDescription returns null): they require database-backed upload-entry tracking, which contradicts this package's no-database premise. Documented, with storeFile through an endpoint as the alternative.
  4. fileExists reports availability (verified and not expired), which is slightly stricter than DatabaseCloudStorage; the consequence for preventOverwrite (expired/unverified files get replaced) is documented and pinned by tests.

Test plan

  • 84 unit tests pass (dart test)
  • dart analyze --fatal-infos clean
  • dart format clean
  • util/update_pubspecs + util/ensure_no_changes idempotent (generated pubspec matches the template)

Adds serverpod_cloud_storage_local, a CloudStorage adapter that stores
files on the server's local filesystem without external services or
database tables. Closes serverpod#1817.
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

Feature Request - Direct File Upload to Server in Serverpod

1 participant