You signed in with another tab or window. Reload to refresh your session.You signed out in another tab or window. Reload to refresh your session.You switched accounts on another tab or window. Reload to refresh your session.Dismiss alert
{{ message }}
Repository navigation
Better documentation on how to create custom CloudStorage #3081
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
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? 🤷
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
@overrideFuture<String?> createDirectFileUploadDescription({
requiredSession session,
requiredString path,
Duration expirationDuration =constDuration(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',
};
returnSerializationManager.encode(uploadDescriptionData);
}
The auth key looks like this
staticString_generateAuthKey() {
const len =16;
const chars ='AaBbCcDdEeFfGgHhIiJjKkLlMmNnOoPpQqRrSsTtUuVvWwXxYyZz1234567890';
var rnd =Random();
returnString.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.
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.
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.
classLocalStorageextendsDatabaseCloudStorage {
finalString? publicStorageUrl;
finalString pathPrefix;
LocalStorage({
requiredLocalStorageId storageId,
requiredthis.pathPrefix,
this.publicStorageUrl,
}) :super(storageId.storageId);
File_getFileByPath(String path) =>File(
join(pathPrefix, path),
);
@overrideFuture<void> deleteFile({
requiredSession session,
requiredString path,
}) async {
final file =_getFileByPath(path);
if (!file.existsSync()) {
throwLocalizedError(
message:LocalizedMessage(en:'File not found'),
statusCode:404,
);
}
file.deleteSync();
}
@overrideFuture<bool> fileExists({
requiredSession session,
requiredString path,
}) async {
final file =_getFileByPath(path);
return file.existsSync();
}
@overrideFuture<Uri?> getPublicUrl({
requiredSession session,
requiredString path,
}) async {
final prefix = publicStorageUrl;
if (prefix ==null) {
throwLocalizedError(
message:LocalizedMessage(en:'Public storage URL is allowed for LocalStorage with id $storageId'),
statusCode:400,
);
}
final file =_getFileByPath(path);
if (!file.existsSync()) {
throwLocalizedError(
message:LocalizedMessage(en:'File not found'),
statusCode:404,
);
}
if (prefix.startsWith('http')) {
returnUri.parse('$prefix$path');
}
returnUri.file('$prefix$path');
}
@overrideFuture<ByteData?> retrieveFile({
requiredSession session,
requiredString path,
}) async {
final file =_getFileByPath(path);
if (!file.existsSync()) {
throwLocalizedError(
message:LocalizedMessage(en:'File not found'),
statusCode:404,
);
}
final data = file.readAsBytesSync();
returnByteData.view(data.buffer);
}
@overrideFuture<void> storeFile({
requiredSession session,
requiredString path,
requiredByteData byteData,
DateTime? expiration,
bool verified =true,
}) async {
print('Storing file to $path');
final file =_getFileByPath(path);
final data = byteData.buffer.asUint8List();
file.writeAsBytesSync(data);
}
@overrideFuture<bool> verifyDirectFileUpload({requiredSession session, requiredString path}) async {
final file =_getFileByPath(path);
return file.existsSync();
}
}
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.
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?
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"
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.
So for future reference these are the changes I did
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
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';
enumLocalStorageId {
public('public'),
private('private');
finalString storageId;
constLocalStorageId(
this.storageId,
);
}
classLocalStorageextendsDatabaseCloudStorage {
finalString? publicStorageUrl;
finalString pathPrefix;
LocalStorage({
requiredLocalStorageId storageId,
requiredthis.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);
}
returnFile(join(directoryPath, fileName));
}
@overrideFuture<void> deleteFile({
requiredSession session,
requiredString path,
}) async {
final file =_getFileByPath(path);
if (!file.existsSync()) {
throwLocalizedError(
message:LocalizedMessage(en:'File not found'),
statusCode:404,
);
}
file.deleteSync();
}
@overrideFuture<bool> fileExists({
requiredSession session,
requiredString path,
}) async {
print('Checking if file exists at $path');
final file =_getFileByPath(path);
return file.existsSync();
}
@overrideFuture<Uri?> getPublicUrl({
requiredSession session,
requiredString path,
}) async {
final prefix = publicStorageUrl;
if (prefix ==null) {
throwLocalizedError(
message:LocalizedMessage(en:'Public storage URL is allowed for LocalStorage with id $storageId'),
statusCode:400,
);
}
final file =_getFileByPath(path);
if (!file.existsSync()) {
throwLocalizedError(
message:LocalizedMessage(
en:'File not found',
),
statusCode:404,
);
}
if (prefix.startsWith('http')) {
returnUri.parse('$prefix$path');
}
returnUri.file('$prefix$path');
}
@overrideFuture<ByteData?> retrieveFile({
requiredSession session,
requiredString path,
}) async {
final file =_getFileByPath(path);
if (!file.existsSync()) {
throwLocalizedError(
message:LocalizedMessage(en:'File not found'),
statusCode:404,
);
}
final data = file.readAsBytesSync();
returnByteData.view(data.buffer);
}
@overrideFuture<void> storeFile({
requiredSession session,
requiredString path,
requiredByteData byteData,
DateTime? expiration,
bool verified =true,
}) async {
final file =_getFileByPath(path);
final data = byteData.buffer.asUint8List();
file.writeAsBytesSync(data);
}
@overrideFuture<bool> verifyDirectFileUpload({requiredSession session, requiredString path}) async {
final file =_getFileByPath(path);
return file.existsSync();
}
}
Register the LocalStorage on your server
I am saving it in my repository (in the root under storage)
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
Activity
vanlooverenkoen commentedon Dec 24, 2024
the files of GPC in the gpc package also still contain aws which makes is more confusing how everything actually works
vanlooverenkoen commentedon Jan 6, 2025
@SandPod this is my
LocalStorageBut for some reason the
print('Storing file to $path');is never called instoreFilewhat am I still missing here?Isakdl commentedon Jan 7, 2025
@vanlooverenkoen Are you calling storeFile anywhere? How are you registering this cloud storage with Serverpod?
FYI the method:
createDirectFileUploadDescriptionwith GCP and AWS the URLs are signed to make sure that end users are not able to modify the values.vanlooverenkoen commentedon Jan 7, 2025
Yes indeed it is registered like this:
And in the app it is uploaded like this
Isakdl commentedon Jan 7, 2025
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
DatabaseCloudStorageThe auth key looks like this
If you modify your
createDirectFileUploadDescriptionmethod to create such an entry ofCloudStorageDirectUploadEntrylike in the above code the built in upload endpoint will work.There is one caveat, you have to have at least one instance of
DatabaseCloudStorageregistered on somestorageIdin Serverpod or else the upload endpoint will not be added.It is okay to have it on another random id than the default
privateandpublic.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.
Isakdl commentedon Jan 7, 2025
On second thought you can probably extend
DatabaseCloudStorageinstead of the interface and override all methods except thecreateDirectFileUploadDescriptionand use that instead. This way you shouldn't need the additional unusedDatabaseCloudStorageentry either.E.g.
vanlooverenkoen commentedon Jan 7, 2025
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.
vanlooverenkoen commentedon Jan 7, 2025
@Isakdl still the
print('Storing file to $path');is never calledThis is the description:
Server logs:
Nothing is added to the databse, also the request is not added, is that to be expected?
Isakdl commentedon Jan 7, 2025
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_uploadafter callingcreateDirectFileUploadDescription. If there is not the upload will not work.Could you validate if there is an entry created there?
vanlooverenkoen commentedon Jan 7, 2025
@Isakdl
await uploader.upload(fileStream, length);returnsfalseRelated to the
serverpod_cloud_storage_direct_uploadan item is indeed created aftercreateDirectFileUploadDescriptionvanlooverenkoen commentedon Jan 7, 2025
If I set a breakpoint in the catch I get this error:
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"
vanlooverenkoen commentedon Jan 7, 2025
According to the logs everything is fine? 🤷
vanlooverenkoen commentedon Jan 7, 2025
Maybe some extra context:
Isakdl commentedon Jan 7, 2025
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
DatabaseCloudStorageimplementation. Instead the value in theconfig/development.yamlis 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
Two things to note for this issue:
vanlooverenkoen commentedon Jan 7, 2025
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!
vanlooverenkoen commentedon Jan 8, 2025
@Isakdl yes this seem to be working!
I will now do the full implementation and let you know if any other issues are still happening.
this is the config I used
vanlooverenkoen commentedon Jan 8, 2025
🎉 file is saved!!
So for future reference these are the changes I did
I set it to 200mb because I don't know what the file size will be for now
You change this in
config/development.yamland the other configuration filesI am saving it in my repository (in the root under
storage)@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.
Isakdl commentedon Jan 8, 2025
@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!
itsJoKr commentedon Jan 13, 2025
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
vanlooverenkoen commentedon Jan 13, 2025
Seems similar, although I have not tested it. I documented my full setup here: #3106
abdulawalarif commentedon Sep 4, 2026
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