Skip to content

Better documentation on how to create custom CloudStorage #3081

Closed
serverpod/serverpod_docs
#783

Description

@vanlooverenkoen

Is your feature request related to a problem? Please describe.
Right now it is unclear how you should actually create a custom cloud storage. The only documentation is for AWS & GPC

related to this one: #3080

Describe the solution you'd like
Clear documentation on how a custom CloudStorage should be created (for example a LocalStorage)

What I am trying to achieve is the following

I want to have a file upload that I can use for development that just saves the files on my pc and serves them from my pc so I can test everything without an actual cloud provider.

I also am planning to host the staging version on a synology nas where I want to host the files as well for staging only. So I want to have custom support for that. But for some reason the storeFile is never called? 🤷

Activity

  1. vanlooverenkoen commented on Dec 24, 2024

    @vanlooverenkoen
    ContributorAuthor

    the files of GPC in the gpc package also still contain aws which makes is more confusing how everything actually works

  2. added
    area: storage
    documentation
    on Jan 2, 2025
  3. vanlooverenkoen commented on Jan 6, 2025

    @vanlooverenkoen
    ContributorAuthor

    @SandPod this is my LocalStorage

    import 'dart:convert';
    import 'dart:io';
    import 'dart:typed_data';
    
    import 'package:path/path.dart';
    import 'package:impaktfull_dashboard_server/src/generated/protocol.dart';
    import 'package:serverpod/serverpod.dart';
    
    enum LocalStorageId {
      public('public'),
      private('private');
    
      final String storageId;
    
      const LocalStorageId(
        this.storageId,
      );
    }
    
    class LocalStorage extends CloudStorage {
      final String? publicStorageUrl;
      final String pathPrefix;
    
      LocalStorage({
        required LocalStorageId storageId,
        required this.pathPrefix,
        this.publicStorageUrl,
      }) : super(storageId.storageId);
    
      File _getFileByPath(String path) => File(
            join(pathPrefix, path),
          );
    
      @override
      Future<String?> createDirectFileUploadDescription({
        required Session session,
        required String path,
        Duration expirationDuration = const Duration(minutes: 10),
        int maxFileSize = 10 * 1024 * 1024,
      }) async {
        final data = {
          "type": "binary",
          "path": path,
          "url": path,
          "expiration": DateTime.now().add(expirationDuration).toIso8601String(),
          "maxFileSize": maxFileSize,
        };
        return jsonEncode(data);
      }
    
      @override
      Future<void> deleteFile({
        required Session session,
        required String path,
      }) async {
        final file = _getFileByPath(path);
        if (!file.existsSync()) {
          throw LocalizedError(
            message: LocalizedMessage(en: 'File not found'),
            statusCode: 404,
          );
        }
        file.deleteSync();
      }
    
      @override
      Future<bool> fileExists({
        required Session session,
        required String path,
      }) async {
        final file = _getFileByPath(path);
        return file.existsSync();
      }
    
      @override
      Future<Uri?> getPublicUrl({
        required Session session,
        required String path,
      }) async {
        final prefix = publicStorageUrl;
        if (prefix == null) {
          throw LocalizedError(
            message: LocalizedMessage(en: 'Public storage URL is allowed for LocalStorage with id $storageId'),
            statusCode: 400,
          );
        }
    
        final file = _getFileByPath(path);
        if (!file.existsSync()) {
          throw LocalizedError(
            message: LocalizedMessage(en: 'File not found'),
            statusCode: 404,
          );
        }
        if (prefix.startsWith('http')) {
          return Uri.parse('$prefix$path');
        }
        return Uri.file('$prefix$path');
      }
    
      @override
      Future<ByteData?> retrieveFile({
        required Session session,
        required String path,
      }) async {
        final file = _getFileByPath(path);
        if (!file.existsSync()) {
          throw LocalizedError(
            message: LocalizedMessage(en: 'File not found'),
            statusCode: 404,
          );
        }
        final data = file.readAsBytesSync();
        return ByteData.view(data.buffer);
      }
    
      @override
      Future<void> storeFile({
        required Session session,
        required String path,
        required ByteData byteData,
        DateTime? expiration,
        bool verified = true,
      }) async {
        print('Storing file to $path');
        final file = _getFileByPath(path);
        final data = byteData.buffer.asUint8List();
        file.writeAsBytesSync(data);
      }
    
      @override
      Future<bool> verifyDirectFileUpload({required Session session, required String path}) async {
        final file = _getFileByPath(path);
        return file.existsSync();
      }
    }
    

    But for some reason the print('Storing file to $path'); is never called in storeFile what am I still missing here?

  4. Isakdl commented on Jan 7, 2025

    @Isakdl
    Collaborator

    @vanlooverenkoen Are you calling storeFile anywhere? How are you registering this cloud storage with Serverpod?

    FYI the method: createDirectFileUploadDescription with GCP and AWS the URLs are signed to make sure that end users are not able to modify the values.

  5. vanlooverenkoen commented on Jan 7, 2025

    @vanlooverenkoen
    ContributorAuthor

    Yes indeed it is registered like this:

        final publicStorageUrl = EnvVariables.instance.publicStorageUrl;
        pod.addCloudStorage(LocalStorage(
          publicStorageUrl: publicStorageUrl,
          storageId: LocalStorageId.public,
          pathPrefix: '~/testing/private',
        ));
        pod.addCloudStorage(LocalStorage(
          storageId: LocalStorageId.private,
          pathPrefix: '~/testing/private',
        ));

    And in the app it is uploaded like this

        final prepareResult = await _appTestingAppService.prepareAppVersionUpload(request);
        final uploadDescription = prepareResult.uploadDescription;
        var uploader = FileUploader(uploadDescription);
        final fileStream = Stream.value(fileBytes);
        final length = fileBytes.length;
        await uploader.upload(fileStream, length);
        final validateRequest = ValidateAppTestingVersionUploadRequest(
          appTestingAppUuid: appTestingAppUuid,
          type: type,
          environmentName: environmentName,
          appTestingVersionUuid: prepareResult.appTestingVersionUuid,
        );
        await _appTestingAppService.validateAppVersionUpload(validateRequest);
  6. Isakdl commented on Jan 7, 2025

    @Isakdl
    Collaborator

    I see, I understand your confusion and the necessity to add some docs here.

    In short you are not mimicking the GCP upload but rather the default "DatabaseCloudStorage" API as you are uploading directly to the server. For this to work there has to be a valid entry in the database that is used to validate that the user is allowed to upload the file.

    This is the code for creating a upload description with a valid db entry (this is copied from the class DatabaseCloudStorage

    @override
      Future<String?> createDirectFileUploadDescription({
        required Session session,
        required String path,
        Duration expirationDuration = const Duration(minutes: 10),
        int maxFileSize = 10 * 1024 * 1024,
      }) async {
        var config = session.server.serverpod.config;
    
        var expiration = DateTime.now().add(expirationDuration);
    
        var uploadEntry = CloudStorageDirectUploadEntry(
          storageId: storageId,
          path: path,
          expiration: expiration,
          authKey: _generateAuthKey(),
        );
        var inserted =
            await session.db.insertRow<CloudStorageDirectUploadEntry>(uploadEntry);
    
        var uri = Uri(
          scheme: config.apiServer.publicScheme,
          host: config.apiServer.publicHost,
          port: config.apiServer.publicPort,
          path: '/serverpod_cloud_storage',
          queryParameters: {
            'method': 'upload',
            'storage': storageId,
            'path': path,
            'key': inserted.authKey,
          },
        );
    
        var uploadDescriptionData = {
          'url': uri.toString(),
          'type': 'binary',
        };
    
        return SerializationManager.encode(uploadDescriptionData);
      }

    The auth key looks like this

    static String _generateAuthKey() {
        const len = 16;
        const chars =
            'AaBbCcDdEeFfGgHhIiJjKkLlMmNnOoPpQqRrSsTtUuVvWwXxYyZz1234567890';
        var rnd = Random();
        return String.fromCharCodes(Iterable.generate(
            len, (_) => chars.codeUnitAt(rnd.nextInt(chars.length))));
      }

    If you modify your createDirectFileUploadDescription method to create such an entry of CloudStorageDirectUploadEntry like in the above code the built in upload endpoint will work.

    There is one caveat, you have to have at least one instance of DatabaseCloudStorage registered on some storageId in Serverpod or else the upload endpoint will not be added.

    It is okay to have it on another random id than the default private and public.

    pod.addCloudStorage(DatabaseCloudStorage(
          ...
          storageId: 'unused',
        ));

    We have discussed this topic internally and we want to streamline this process and document it properly as it is hard to work with today without diving into the implementation if you want to build your own integration.

  7. Isakdl commented on Jan 7, 2025

    @Isakdl
    Collaborator

    On second thought you can probably extend DatabaseCloudStorage instead of the interface and override all methods except the createDirectFileUploadDescription and use that instead. This way you shouldn't need the additional unused DatabaseCloudStorage entry either.

    E.g.

    class LocalStorage extends DatabaseCloudStorage {
      final String? publicStorageUrl;
      final String pathPrefix;
    
      LocalStorage({
        required LocalStorageId storageId,
        required this.pathPrefix,
        this.publicStorageUrl,
      }) : super(storageId.storageId);
    
      File _getFileByPath(String path) => File(
            join(pathPrefix, path),
          );
    
      @override
      Future<void> deleteFile({
        required Session session,
        required String path,
      }) async {
        final file = _getFileByPath(path);
        if (!file.existsSync()) {
          throw LocalizedError(
            message: LocalizedMessage(en: 'File not found'),
            statusCode: 404,
          );
        }
        file.deleteSync();
      }
    
      @override
      Future<bool> fileExists({
        required Session session,
        required String path,
      }) async {
        final file = _getFileByPath(path);
        return file.existsSync();
      }
    
      @override
      Future<Uri?> getPublicUrl({
        required Session session,
        required String path,
      }) async {
        final prefix = publicStorageUrl;
        if (prefix == null) {
          throw LocalizedError(
            message: LocalizedMessage(en: 'Public storage URL is allowed for LocalStorage with id $storageId'),
            statusCode: 400,
          );
        }
    
        final file = _getFileByPath(path);
        if (!file.existsSync()) {
          throw LocalizedError(
            message: LocalizedMessage(en: 'File not found'),
            statusCode: 404,
          );
        }
        if (prefix.startsWith('http')) {
          return Uri.parse('$prefix$path');
        }
        return Uri.file('$prefix$path');
      }
    
      @override
      Future<ByteData?> retrieveFile({
        required Session session,
        required String path,
      }) async {
        final file = _getFileByPath(path);
        if (!file.existsSync()) {
          throw LocalizedError(
            message: LocalizedMessage(en: 'File not found'),
            statusCode: 404,
          );
        }
        final data = file.readAsBytesSync();
        return ByteData.view(data.buffer);
      }
    
      @override
      Future<void> storeFile({
        required Session session,
        required String path,
        required ByteData byteData,
        DateTime? expiration,
        bool verified = true,
      }) async {
        print('Storing file to $path');
        final file = _getFileByPath(path);
        final data = byteData.buffer.asUint8List();
        file.writeAsBytesSync(data);
      }
    
      @override
      Future<bool> verifyDirectFileUpload({required Session session, required String path}) async {
        final file = _getFileByPath(path);
        return file.existsSync();
      }
    }
  8. vanlooverenkoen commented on Jan 7, 2025

    @vanlooverenkoen
    ContributorAuthor

    Indeed I am sending the file directly to the server. I have my own Synology NAS running for other internal projects, so having staging environments on there reduces cost a lot!

    I will test this out right now! Thanks already for your support. Let me know if you need any other information about this matter.

  9. vanlooverenkoen commented on Jan 7, 2025

    @vanlooverenkoen
    ContributorAuthor

    @Isakdl still the print('Storing file to $path'); is never called

    This is the description:

    {"url":"http://localhost:8080/serverpod_cloud_storage?method=upload&storage=public&path=50896b29-60ee-4130-b2a2-eab81cabea03%2F4b117a1a-918c-4040-ad51-d5aa1f8f8423%2Fb350f582-74f3-4671-9afd-a66f0845c93f%2F907f6390-3c5f-4871-8482-09247d109edf&key=EtcCxkeSrIXEOeda","type":"binary"}
    

    Server logs:

    CALL: appTestingApp.prepareAppVersionUpload duration: 49ms numQueries: 6 authenticatedUser: 1
    CALL: serverpod_cloud_storage.upload duration: 11ms numQueries: 2 authenticatedUser: null
    CALL: appTestingApp.validateAppVersionUpload duration: 13ms numQueries: 5 authenticatedUser: 1
    

    Nothing is added to the databse, also the request is not added, is that to be expected?

  10. Isakdl commented on Jan 7, 2025

    @Isakdl
    Collaborator

    That is strange, your log indicates that we have called upload and as long as we pass the internal check the storeFile method should be called.

    Just to validate what is the method await uploader.upload(fileStream, length); returning? This method should return "true" when successful.

    No entries in the database is very strange too, you should see an entry in the table: serverpod_cloud_storage_direct_upload after calling createDirectFileUploadDescription. If there is not the upload will not work.

    Could you validate if there is an entry created there?

  11. vanlooverenkoen commented on Jan 7, 2025

    @vanlooverenkoen
    ContributorAuthor

    @Isakdl

    await uploader.upload(fileStream, length); returns false

    Related to the serverpod_cloud_storage_direct_upload an item is indeed created after createDirectFileUploadDescription

  12. vanlooverenkoen commented on Jan 7, 2025

    @vanlooverenkoen
    ContributorAuthor

    If I set a breakpoint in the catch I get this error:

    _ClientSocketException (ClientException with SocketException: Connection reset by peer (OS Error: Connection reset by peer, errno = 54), address = localhost, port = 53427, uri=http://localhost:8080/serverpod_cloud_storage?method=upload&storage=public&path=50896b29-60ee-4130-b2a2-eab81cabea03%2F4b117a1a-918c-4040-ad51-d5aa1f8f8423%2Fb350f582-74f3-4671-9afd-a66f0845c93f%2Fa1268258-e919-4672-8bde-5054666f5a02&key=iL0kLPdDfbScTbzm)
    

    Not sure if this is tracked somewhere already. But I think the error handling should be better and not just return false because it fails. We should have a some way to catch the underlying error. and show propper feedback to the user. it might be because the user has no internet or something else. Which is something we want to show our users. Not a generic error like "Something went wrong"

  13. vanlooverenkoen commented on Jan 7, 2025

    @vanlooverenkoen
    ContributorAuthor

    image

    According to the logs everything is fine? 🤷

  14. vanlooverenkoen commented on Jan 7, 2025

    @vanlooverenkoen
    ContributorAuthor

    Maybe some extra context:

    • I am using the filepicker package to upload the file.
    • The data of the file ends up in a List byte array which I add to a Stream.value()
  15. added
    bug
    on Jan 7, 2025
  16. Isakdl commented on Jan 7, 2025

    @Isakdl
    Collaborator

    Got it, I dived into the code a bit I suspect this has to do with the file size. There is a check for the max bytes allowed to be uploaded, by default this is set to 0.5 MB, question now is, do you think you are exceeding this value? The maxFileSize in the interface is not used in the DatabaseCloudStorage implementation. Instead the value in the config/development.yaml is used in this check.

    Could you try to increase this value or upload a file that is smaller than the max limit and verify if that works.

    See the docs for the configuration options: https://docs.serverpod.dev/concepts/configuration

    # config/development.yaml
    ...
    maxRequestSize: 524288 # Size in bytes

    Two things to note for this issue:

    • This behavior is not documented.
    • The maxFileSize should be used instead of the maxRequestSize.
  17. vanlooverenkoen commented on Jan 7, 2025

    @vanlooverenkoen
    ContributorAuthor

    Ah yes this could be the case, i am uploading an apk which is 25mb I think, I will check this tomorrow! Thanks a lot for your investigating!

  18. vanlooverenkoen commented on Jan 8, 2025

    @vanlooverenkoen
    ContributorAuthor

    @Isakdl yes this seem to be working!

    CALL: appTestingApp.prepareAppVersionUpload duration: 28ms numQueries: 6 authenticatedUser: 1
    Storing file to 50896b29-60ee-4130-b2a2-eab81cabea03/4b117a1a-918c-4040-ad51-d5aa1f8f8423/b350f582-74f3-4671-9afd-a66f0845c93f/3d5927d7-447c-4b99-910a-caffdc47e030
    CALL: serverpod_cloud_storage.upload duration: 2186ms numQueries: 2 authenticatedUser: null
    

    I will now do the full implementation and let you know if any other issues are still happening.

    this is the config I used

    maxRequestSize: 200000000
    
  19. vanlooverenkoen commented on Jan 8, 2025

    @vanlooverenkoen
    ContributorAuthor

    🎉 file is saved!!

    So for future reference these are the changes I did

    1. Change the max request size to the size of your file
      I set it to 200mb because I don't know what the file size will be for now
      You change this in config/development.yaml and the other configuration files
    maxRequestSize: 200000000
    1. Create a LocalStorage class that extends CloudDatabase
    import 'dart:io';
    import 'dart:typed_data';
    
    import 'package:path/path.dart';
    import 'package:app_server/src/generated/protocol.dart';
    import 'package:serverpod/serverpod.dart';
    
    enum LocalStorageId {
      public('public'),
      private('private');
    
      final String storageId;
    
      const LocalStorageId(
        this.storageId,
      );
    }
    
    class LocalStorage extends DatabaseCloudStorage {
      final String? publicStorageUrl;
      final String pathPrefix;
    
      LocalStorage({
        required LocalStorageId storageId,
        required this.pathPrefix,
        this.publicStorageUrl,
      }) : super(storageId.storageId);
    
      File _getFileByPath(String path) {
        final fileName = basename(path);
        final parentDirectoryPath = dirname(path);
        final directoryPath = join(pathPrefix, parentDirectoryPath);
        final directory = Directory(directoryPath);
        if (!directory.existsSync()) {
          directory.createSync(recursive: true);
        }
        return File(join(directoryPath, fileName));
      }
    
      @override
      Future<void> deleteFile({
        required Session session,
        required String path,
      }) async {
        final file = _getFileByPath(path);
        if (!file.existsSync()) {
          throw LocalizedError(
            message: LocalizedMessage(en: 'File not found'),
            statusCode: 404,
          );
        }
        file.deleteSync();
      }
    
      @override
      Future<bool> fileExists({
        required Session session,
        required String path,
      }) async {
        print('Checking if file exists at $path');
        final file = _getFileByPath(path);
        return file.existsSync();
      }
    
      @override
      Future<Uri?> getPublicUrl({
        required Session session,
        required String path,
      }) async {
        final prefix = publicStorageUrl;
        if (prefix == null) {
          throw LocalizedError(
            message: LocalizedMessage(en: 'Public storage URL is allowed for LocalStorage with id $storageId'),
            statusCode: 400,
          );
        }
    
        final file = _getFileByPath(path);
        if (!file.existsSync()) {
          throw LocalizedError(
            message: LocalizedMessage(
              en: 'File not found',
            ),
            statusCode: 404,
          );
        }
        if (prefix.startsWith('http')) {
          return Uri.parse('$prefix$path');
        }
        return Uri.file('$prefix$path');
      }
    
      @override
      Future<ByteData?> retrieveFile({
        required Session session,
        required String path,
      }) async {
        final file = _getFileByPath(path);
        if (!file.existsSync()) {
          throw LocalizedError(
            message: LocalizedMessage(en: 'File not found'),
            statusCode: 404,
          );
        }
        final data = file.readAsBytesSync();
        return ByteData.view(data.buffer);
      }
    
      @override
      Future<void> storeFile({
        required Session session,
        required String path,
        required ByteData byteData,
        DateTime? expiration,
        bool verified = true,
      }) async {
        final file = _getFileByPath(path);
        final data = byteData.buffer.asUint8List();
        file.writeAsBytesSync(data);
      }
    
      @override
      Future<bool> verifyDirectFileUpload({required Session session, required String path}) async {
        final file = _getFileByPath(path);
        return file.existsSync();
      }
    }
    
    1. Register the LocalStorage on your server

    I am saving it in my repository (in the root under storage)

        pod.addCloudStorage(LocalStorage(
          publicStorageUrl: publicStorageUrl,
          storageId: LocalStorageId.public,
          pathPrefix: join(Directory.current.path, '..', 'storage', 'private'),
        ));
        pod.addCloudStorage(LocalStorage(
          storageId: LocalStorageId.private,
          pathPrefix: join(Directory.current.path, '..', 'storage', 'public'),
        ));

    @Isakdl let me know if I need to test something else to get better error handling or if you need more impormation to improve this.

    It would be nice maybe just to have this type of storage provided by serverpod as well.

  20. Isakdl commented on Jan 8, 2025

    @Isakdl
    Collaborator

    @vanlooverenkoen Happy that this solved your problem :)

    Yeah agreed, I very much want to add this feature natively, we will do that together with some hardening and better documentation of this feature!

  21. itsJoKr commented on Jan 13, 2025

    @itsJoKr

    I just found about this PR: #2571

    And it looks like exactly what you needed, right? I just want to gather more info, as I need something similar.

    cc @vanlooverenkoen

  22. vanlooverenkoen commented on Jan 13, 2025

    @vanlooverenkoen
    ContributorAuthor

    Seems similar, although I have not tested it. I documented my full setup here: #3106

  23. abdulawalarif commented on Sep 4, 2026

    @abdulawalarif
    Contributor

    Opened a PR that documents how to implement a custom CloudStorage (including the local/direct-to-server upload path) so this is no longer a guess-from-the-implementation problem: serverpod/serverpod_docs#783

  24. moved this from Backlog 🗂️ to Done 🚀 in Serverpod Frameworkson Sep 18, 2026
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

Labels

area: storagebugdocumentation

Type

No type

Projects

Milestone

No milestone

Relationships

None yet

Development

No branches or pull requests

Issue actions