
# Storage

`StorageTemplate` (the bean `storageTemplate`) reads and writes the objects of Supabase Storage. A `@StorageBucket` interface declares the objects of one bucket, with their paths in one place. Both act as the current user, so the policies of row-level security on `storage.objects` decide what a call may do.

## Why

The policies of a bucket depend on the shape of the path: "a user writes under a folder named by their id". When every caller builds that path from a parameter, one of them will take the user's id from the wrong place. A declared bucket writes each path once, and can take the user from the security context instead of a parameter a caller could set to another user's.

## Example

```dart
@StorageBucket('avatars')
abstract interface class Avatars {
  @Upload('#{authentication.name}/avatar.png', upsert: true)
  Future<void> put(Uint8List bytes);

  @Download('{userId}/avatar.png')
  Stream<List<int>> get(String userId);

  @SignedUrl('{userId}/avatar.png', expiresIn: Duration(minutes: 5))
  Future<Uri> link(String userId);

  @PublicUrl('{userId}/avatar.png')
  Uri publicLink(String userId);

  @StorageObject('{userId}/settings.json')
  Future<Settings?> settings(String userId);

  @StorageObject('{userId}/settings.json')
  Future<void> saveSettings(String userId, Settings settings);

  @DeleteObject('{userId}/avatar.png')
  Future<void> remove(String userId);
}
```

`put` needs no user id: the path is the signed-in user's. The same with the template:

```dart
await storage.upload('avatars', 'u1/avatar.png', bytes,
    contentType: 'image/png', upsert: true);
final link = await storage.signedUrl('avatars', 'u1/avatar.png');
final settings = await storage.read<Settings>('config', 'app.json');
```

## The template

| Method | What it does |
|---|---|
| `upload(bucket, path, content, contentType:, upsert:, cacheControl:)` | Writes bytes, a `String` (as UTF-8) or a `Stream<List<int>>`. With `upsert` an object already there is replaced; without it, it is a `StorageObjectAlreadyExistsException`. The content type is `application/octet-stream` (`text/plain;charset=utf-8` for a `String`) unless given. |
| `download(bucket, path)` | The bytes of the object, as they arrive (`Stream<List<int>>`). |
| `downloadBytes(bucket, path)` | The whole object in memory. |
| `read<T>(bucket, path)` | The object read as JSON into a `T` through the `ObjectMapper`; `null` when there is no such object. |
| `store(bucket, path, value, upsert:)` | Writes a value as JSON, replacing what is there unless `upsert` is `false`. |
| `publicUrl(bucket, path, download:)` | The address of an object of a public bucket. Nothing is asked of Storage: the address exists whether the object does or not. |
| `signedUrl(bucket, path, expiresIn:)` | An address that reads the object without a token, for `expiresIn` (`spring.supabase.storage.signed-url-expiry` unless given). |
| `signedUploadUrl(bucket, path)` | A `SignedUpload`: an address the object can be uploaded to once, with a `PUT`, without a token (for a browser, given by a server). |
| `list(bucket, prefix:, limit:, offset:, sortBy:, descending:, search:)` | The objects and folders directly under a prefix: `StorageObjectInfo`s, 100 by default, ordered by `name`. A folder has no `id` (`isFolder`). |
| `delete(bucket, path)`, `deleteAll(bucket, paths)` | Removes objects; nothing there is no error. `deleteAll` tells how many there were. |
| `move(bucket, from, to, toBucket:)`, `copy(…)` | Moves or copies an object, to another bucket when given. |
| `exists(bucket, path)`, `info(bucket, path)` | Whether there is an object the caller may see; what Storage knows about it (`size`, `contentType`, `etag`, `updatedAt`…), or `null`. |
| `buckets()`, `bucket(id)`, `createBucket(id, isPublic:, fileSizeLimit:, allowedMimeTypes:)`, `updateBucket`, `emptyBucket`, `deleteBucket` | The buckets of the project. |
| `asServiceRole()` | The same template with every call made as the service role, which passes the policies and is the one that manages buckets. Needs `spring.supabase.service-role-key`. |

```dart
await storage.asServiceRole().createBucket('avatars', isPublic: true);
```

## Declared buckets

`@StorageBucket('avatars')` marks an interface whose methods read and write the objects of one bucket; the bucket's id may be a `${property}`. Each method has one of these:

| Annotation | The method |
|---|---|
| `@Upload(path, contentType:, upsert:, cacheControl:)` | takes the content and returns `Future<void>`. The content is a `Uint8List`, a `List<int>`, a `Stream<List<int>>` or a `String`: the only parameter the path does not use, or the one marked `@RequestBody()`. |
| `@Download(path)` | returns `Stream<List<int>>` (the bytes as they arrive) or `Future<Uint8List>`; a nullable `Future<Uint8List?>` is `null` when there is no such object. |
| `@SignedUrl(path, expiresIn:)` | returns `Future<Uri>` or `Future<String>`. |
| `@PublicUrl(path, download:)` | returns `Uri` or `String`, without asking Storage. |
| `@StorageObject(path, upsert:)` | reads JSON when it returns a value (`Future<Settings?>` is `null` for no object; a non-nullable type is an error then); writes it when it takes a value and returns `Future<void>`. |
| `@DeleteObject(path)` | returns `Future<void>`; nothing there is no error. |

- **The bean** is named after the interface and takes AOP like any other: `@PreAuthorize`, `@Cacheable`.
- **Checked at startup.** A method without one of the annotations, or with a wrong return type or content, stops the start; the message names every problem of the interface.
- **A kind of method of your own** is a bean that implements `StorageBucketOperation`; it is asked before the built-in ones.
- For what is not known when the application is built (listings, moves, buckets), use the template.

## Path rules

A path of a declared bucket takes three kinds of placeholders:

| In the path | Filled from |
|---|---|
| `${app.folder}` | the configuration, once, when the application starts |
| `{userId}` | the method's parameter of that name, at each call |
| `#{authentication.name}` | SpEL, at each call: the parameters as `#name`, `authentication` and `principal` as in `@PreAuthorize`, beans as `@name` |

```dart
@Download('{userId}/#{#kind.name}.png')
Stream<List<int>> get(String userId, AvatarKind kind);
```

**A value is one segment of the path, never a path.** What a parameter or an expression gives is refused, with an `ArgumentError`, when it:

- is empty, `.` or `..`;
- has a `/` or a `\` in it;
- has a control character in it.

So `'{userId}/avatar.png'` with `userId = '../admin'` is refused, and no call leaves its folder. The fixed text of a path may not have a `.` or `..` segment either.

The template checks every path again, also one given in code: a path with an empty, `.` or `..` segment, a backslash or a control character is an `ArgumentError`, and each segment is percent-encoded. A bucket id is one segment.

## Errors

| Exception | When |
|---|---|
| `StorageObjectNotFoundException` | The object or the bucket does not exist, or the caller may not see it; Storage does not tell the two apart. |
| `StorageObjectAlreadyExistsException` | There is an object (or a bucket) at that place already. |
| `StoragePermissionDeniedException` | A policy on `storage.objects` refused the call, or the token was not accepted. |
| `StorageObjectTooLargeException` | The object is larger than the bucket or the project allows. |
| `StorageException` | Any other failure of Storage. |
| `SupabaseUnavailableException` | No answer from the project. |

All are `SupabaseException`s with `statusCode`, `code` and `message`.

```dart
try {
  await storage.upload('avatars', 'u1.png', bytes);
} on StorageObjectAlreadyExistsException {
  // upload(..., upsert: true) would have replaced it
}
```

A stream of `download` fails with the exception when it is listened to.

## Limits

- **An upload is read whole before it is sent**, a stream too: the transport takes a request's body as bytes. Downloads are streamed.
- **No resumable uploads** (TUS).
- **No `Resource` of an object**: there is no `resource(bucket, path)`.
- **No image transformations.**

## The properties

| Key | Type | Default | Meaning |
|---|---|---|---|
| `spring.supabase.storage.signed-url-expiry` | `Duration` | `1h` | How long a signed URL is valid when the call does not say. |

## In Spring (Java)

Spring itself has no counterpart. Spring Cloud AWS has `S3Template` of the same shape as `StorageTemplate`; declared buckets have none.

## See also

- [Who a call is made as](credentials.md)
- [Caches](cache.md)
- [SpEL](../spring-core-dart/spel/index.md)
- [Method security](../spring-security-core/method-security.md)
