Skip to content

RFC: Cloud storage improvements #3128

Open

Description

@Isakdl

Cloud Storage Integration Improvement

Image


Summary

This proposal outlines improvements to the cloud storage integration in Serverpod. Current integrations face several challenges, including a lack of testing, unclear documentation, and limited flexibility. This RFC proposes changes to the CloudStorage interface, enhancements, and new features such as metadata handling, new storage implementations, etc to address these issues comprehensively.


Motivation

The current state of cloud storage integration has notable deficiencies:

  • Frequent bug reports indicating confusing or broken functionality.
  • Absence of tests, increasing the likelihood of introducing undetected bugs.
  • Missing features such as support for metadata.
  • Reliance on database validation for uploads.
  • Sparse documentation, making it difficult for developers to extend or use the feature effectively.

This proposal addresses these issues to improve reliability, flexibility, and developer experience.


Current Pain Points

  • Bugs and Inconsistencies: Lack of tests leads to regressions.
  • Sparse Documentation: Insufficient guidance for implementing custom extensions.
  • No Metadata Support: Inability to associate metadata with files.
  • No Local Disk Storage: No integration to store files on the local machine.
  • AWS Compatibility Layer for GCP: The current GCP integration relies on AWS compatibility rather than a native implementation, limiting features and user control.

Detailed Design

Interface Changes to CloudStorage

The complete interface after proposed chanages

abstract class CloudStorage {
  /// Identifies the storage. You can used multiple types cloud storages in a
  /// single Serverpod.
  String storageId;

  /// Creates a [CloudStorage] with the specified [storageId]. By default,
  /// two storages are used by Serverpod `public` and `private`. The public
  /// should be accessible to everyone (usually through a web interface),
  /// while the private is accessed internally only.
  CloudStorage(this.storageId);

  Future<void> storeFile({
    required Session session,
    required String path,
    required ByteData byteData,
    DateTime? expiration,
  });

  Future<ByteData> retrieveFile({
    required Session session,
    required String path,
  });

  Future<Uri> getPublicUrl({
    required Session session,
    required String path,
  });

  Future<bool> fileExists({
    required Session session,
    required String path,
  });

  Future<void> deleteFile({
    required Session session,
    required String path,
  });

  Future<UploadDescription> createDirectFileUploadDescription({
    required Session session,
    required String path,
    Duration expiration = const Duration(minutes: 10),
    int maxFileSize = 10 * 1024 * 1024,
    Map<String, String> metadata,
  });

  Future<Map<String, String>> retrieveMetadata({
    required Session session,
    required String path,
  });

  Future<void> storeMetadata({
    required Session session,
    required String path,
    Map<String, String> metadata,
  });
}

Remove Unnecessary Method

/// Call this method once a direct file upload is completed. Failure to call
/// this method will cause the uploaded file to be deleted.
Future<bool> verifyDirectFileUpload({
  required Session session,
  required String path,
});

This method is redundant and misleading; it will be removed.

Modify Method Signatures

  • Non-nullable Returns: Methods retrieveFile, getPublicUrl, and createDirectFileUploadDescription will throw exceptions on failure instead of returning nullable results.
  • Typed Return for createDirectFileUploadDescription: Replace string-based JSON responses with a strongly typed object:
    class UploadDescription {
      late UploadType type;
      late Uri url;
      String? field;
      String? fileName;
      Map<String, String> requestFields = {};
      Map<String, String> headerFields = {};
    }
    headerFields are added as a way to set additional header values on the upload request. This is necessary to support metadata during the initial upload to GCP and other providers.

Add Metadata Support

  • Modify createDirectFileUploadDescription to accept Map<String, String> metadata.
    Future<UploadDescription> createDirectFileUploadDescription({
      required Session session,
      required String path,
      Duration expirationDuration = const Duration(minutes: 10),
      int maxFileSize = 10 * 1024 * 1024,
      Map<String, String> metadata = const {},
    });
  • Add new methods:
    Future<Map<String, String>> retrieveMetadata({
      required Session session,
      required String path,
    });
    
    Future<void> storeMetadata({
      required Session session,
      required String path,
      Map<String, String> metadata,
    });

Improve Upload Mechanisms

  • Explore multipart upload solutions based on file size.
  • Replace database validation with signed requests using RSA or HMAC. Refer to Google Cloud Storage Signing for inspiration.
  • Use the key from password.yaml or the SERVERPOD_STORAGE_KEY environment variable to use for signing urls.

Enhance getPublicUrl

  • Support signed read URLs for private buckets with temporary access. Will allow read requests to specific objects for a subset of end users.

Native GCP Integration

Replace AWS Compatibility Layer

  • Develop a native implementation for GCP, leveraging its full feature set.

Support for GCP Authentication Client

  • Integrate compatibility with the GCP authentication client to give users complete control over how they authenticate with GCP.
  • Provide examples for setting up service accounts, using environment-based credentials, or other custom authentication methods.
  • By default authenticate with GCP using the built in clientViaApplicationDefaultCredentials from the googleapis_auth package.
clientViaApplicationDefaultCredentials(scopes: [
  'https://www.googleapis.com/auth/cloud-platform',
]);

New Implementations

  1. Base Implementation:
    • Abstract base class for storage solutions supporting signed URLs.
  2. Local Disk Storage:
    • Files stored on disk, suitable for VPS setups or volume-mounted containers.
  3. In-Memory Storage:
    • Ephemeral storage for testing and mock solutions.
  4. Storage module:
    • Convert current upload and file retrieval endpoints into a module, locate the base abstract class implementation in this module.

Imagine the following dependency graph between the packages. Core means it is located in the "serverpod" package.

Image

Server file endpoints

These endpoints will be moved from Serverpod core, into the new storage module.

Upload file endpoint
  • The upload endpoint expects the storage id in the request header to select which storage to upload the file to.
  • Trigger server-side code upon successful uploads by registering a callback:
    void onFileStored(Session session, String storageId, String path);
Read file endpoint
  • Allow reading non-public files using signed URLs for validation.

Testing

  1. Contract Test Suite:
    • Validate the CloudStorage interface.
    • Ensure consistent behavior across all storage implementations.

The core idea is to create a generic test suite that can be used against any concrete interface implementation. This way we can add new integration with full test coverage without writing new test cases.


Documentation

  1. Layered Approach:

    • High-level usage examples for GCP, AWS, and local storage.
    • Detailed guide for implementing custom storage solutions.
  2. Implementation Examples:

    • Walkthroughs for configuring and using metadata, multipart uploads, and signed URLs.

Impact

Benefits

  • Enhanced security through signed URLs.
  • Improved reliability with a robust test suite.
  • Increased flexibility via metadata and multipart upload support.
  • Easier adoption with detailed documentation.

Risks

  • Migration effort for existing users due to API changes.

Related Issues

Community PRs

Activity

  1. converted this from a draft issue on Jan 16, 2025
  2. added
    rfc
    area: storage
    on Jan 16, 2025
  3. itsJoKr commented on Jan 17, 2025

    @itsJoKr

    Very well written.

    In-Memory Storage:
    Ephemeral storage for testing and mock solutions

    Just want to note that I had a use case where you upload the file and then parse it into some result, without the need to save the file anywhere. So I think In-memory storage is a valid use case, not something only for testing/mock.

  4. vanlooverenkoen commented on Jan 17, 2025

    @vanlooverenkoen
    Contributor

    @itsJoKr valid point! Something I also noticed is that it would be nice to preprocess the file. So we can make sure that the file is of a certain format and aligns with specifications needed for your product

  5. dkbast commented on Jan 24, 2025

    @dkbast
    Contributor

    I feel like S3 compatible storage is the "gold standard" for cloud buckets and would like to see how to integrate with non AWS buckets (e.g. using https://www.backblaze.com/cloud-storage or https://www.digitalocean.com/products/spaces ) - not sure if thats documentation only, or if that needs some changes for credentials (currently the passwords.yaml keys are AWS specific)

  6. iampopal commented on Jan 24, 2025

    @iampopal

    looking into this...

  7. vanlooverenkoen commented on Jan 28, 2025

    @vanlooverenkoen
    Contributor

    I have noticed that uploading a large file (20+ mb) results in the serverpod instance not accepting new requests. It looks like the backend is frozen and released after the file is fully uploaded.

    I use this implementation:
    #3106

  8. Isakdl commented on Jan 29, 2025

    @Isakdl
    CollaboratorAuthor

    @itsJoKr Cool! Yes I think an in memory solution could be used in many ways, my top of mind was for testing.

    @vanlooverenkoen Interesting good find! It sounds like we have to put the receiver in an isolate.

  9. vanlooverenkoen commented on Jan 29, 2025

    @vanlooverenkoen
    Contributor

    @Isakdl an important note is that the files are saved directly on the server so no GCP or AWS is used here.

    Maybe this has something to do with it? Or are all the files to GCP & AWS also passed through the serverpod instance?

  10. Isakdl commented on Jan 29, 2025

    @Isakdl
    CollaboratorAuthor

    @vanlooverenkoen No the GCP and AWS integrations upload directly to their respective cloud endpoints, Serverpod is not involved there.

    But this means that the upload endpoint in Serverpod is not playing nice, if it is locking the entire thread.

  11. KristijanZic commented on Jan 29, 2025

    @KristijanZic
    Contributor

    @Isakdl an important note is that the files are saved directly on the server so no GCP or AWS is used here.

    Maybe this has something to do with it? Or are all the files to GCP & AWS also passed through the serverpod instance?

    No, the files are uploaded to the object storage directly from the flutter app using the upload description obtained from the serverpod server.

  12. nielsenko commented on Jan 31, 2025

    @nielsenko
    Collaborator

    @Isakdl I think it is important to support byte-range fetches. Not all blobs are small enough to be read efficiently in full.

  13. Isakdl commented on Mar 11, 2025

    @Isakdl
    CollaboratorAuthor

    Referencing issue: #3293

    Support for generic "AWS compatible" storage integration. There are many storage solutions that have built a compatibility layer with the AWS apis. It would be nice with a module that made it possible to configure it in such a way that it can work with any such service.

  14. iampopal commented on Mar 11, 2025

    @iampopal

    Thank you @Isakdl referencing the issue

    https://pub.dev/packages/minio is a great package and has the ability of custom upload and works all great.

    final minio = Minio(
      endPoint: 'play.min.io',
      accessKey: 'Q3AM3UQ867SPQQA43P2F',
      secretKey: 'zuf+tfteSlswRu7BJ86wekitnifILbZam1KYY3TG',
    );
    

    We can even use that too.

  15. christerswahn commented on Apr 14, 2025

    @christerswahn
    Contributor

    It would perhaps be valuable to design the code with an abstract interface and allow for test / mock / other implementations as well.

  16. dkbast commented on Apr 30, 2025

    @dkbast
    Contributor

    I would like to have a good interface to let the server create a path for the client, ideally I don't want to do this in two calls, so a way pass back the path alongside the UploadDescription.
    Not sure if thats a part of this or an individual design decision.
    Example:

      Future<(String? description, String path)> getUploadDescription(
          Session session, String filename) async {
        Uuid uuid = Uuid();
    
        // Generate a unique path for the file
        // Using a uuid prevents collisions and enumeration attacks
        final path = 'uploads/${uuid.v4()}/$filename';
    
        final description = await session.storage.createDirectFileUploadDescription(
          storageId: 'public',
          path: path,
        );
    
        return (description, path);
      }

    It would also be great if we could have a quicker way to access the public url of an uploaded file - ideally directly in the "upload" process.

  17. added
    stake: onboarding
    on May 22, 2025
  18. modified the milestone: Project Windex on Jun 18, 2025
  19. nielsenko commented on Jun 23, 2025

    @nielsenko
    Collaborator

    Having recently worked a bit in this area to address a bug, I noticed that an abstraction over S3 and GCS is complicated by the following gaps:

    • S3 offers a managed MPU service where the provider tracks upload state. GCS requires a manual, client-driven process of uploading parts as separate objects and then composing them, with a limit of 32 objects per compose operation and 1024 total parts.

    • S3 provides a native API for attaching key-value tags to objects. GCS lacks this feature entirely.

    • The services have fundamentally different versioning models. S3 uses a version stack with "delete markers," while GCS uses a "master" and "archive" system with different deletion semantics. They are not interchangeable.

    • S3 provides a flexible, API-driven Cross-Region Replication (CRR) feature. GCS offers geo-redundancy via Multi-Regional bucket configurations but lacks a comparable API for granular replication control.

    Just some food for thoughts.

  20. moved this from Planned 🔭 to Backlog 🗂️ in Serverpod Frameworkson Aug 12, 2025
  21. Isakdl commented on Oct 10, 2025

    @Isakdl
    CollaboratorAuthor

    S3 provides a native API for attaching key-value tags to objects. GCS lacks this feature entirely.

    That is incorrect GCS supports metadata that can be set via header params in the request, and can be protected by signing the URL. In fact, I'm using that feature currently.

    S3 provides a flexible, API-driven Cross-Region Replication (CRR) feature. GCS offers geo-redundancy via Multi-Regional bucket configurations but lacks a comparable API for granular replication control.

    Seems to have more to do with how you configure your infrastructure rather than something that would touch the Serverpod integration.

    The other two points I'm not sure about, but it should be possible to layer some abstraction on top of these differences, even if you need to track which provider was used to generate the upload description.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

No one assigned

    Labels

    area: storagerfcstake: onboarding

    Type

    No type

    Projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions