Expand description
Object storage buckets, declared at module scope and resolved from the runtime on use.
use encore::objects::Bucket;
static UPLOADS: Bucket = Bucket::new("uploads");
static AVATARS: Bucket = Bucket::new("avatars").public().versioned();Bucket operations (upload, download, list, attrs, remove, and so
on) are methods directly on Bucket, matching Encore’s TypeScript and Go
SDKs. Because each operation is called directly on the bucket, Encore can
statically analyze your code and grant each service only the permissions it
uses.
Operations that accept options return a request builder. Configure options
with chained methods and .await the request to execute it.
use encore::objects::{Bucket, StorageClass};
static UPLOADS: Bucket = Bucket::named("uploads");
async fn save(data: Vec<u8>) -> Result<(), encore::objects::Error> {
UPLOADS.upload("a.pdf", data.clone()).await?;
UPLOADS
.upload("b.pdf", data)
.content_type("application/pdf")
.metadata([("owner", "42")])
.storage_class(StorageClass::Cold)
.await?;
let head = UPLOADS.download("b.pdf").range(0..1024).await?.bytes().await?;
Ok(())
}§References
Because Encore tracks bucket permissions statically, a Bucket cannot be
passed around as a value. To pass a bucket to helper functions or libraries,
create a BucketRef that grants only the permissions specified in its
type argument:
use encore::objects::{self, perms, Bucket, Uploader};
static UPLOADS: Bucket = Bucket::named("uploads");
// Library code asks for the permissions it needs, as traits.
async fn save(bucket: &impl Uploader, key: &str) -> Result<(), objects::Error> {
bucket.upload(key, b"hello".to_vec()).await?;
Ok(())
}
async fn greet() -> Result<(), objects::Error> {
save(&UPLOADS.reference::<perms::Uploader>(), "greeting.txt").await
}Permissions can be a single type from perms or a tuple of them (such as
(perms::Uploader, perms::Lister)). Each permission has a matching trait in
this module exposing the methods it grants. Library code should accept those
traits (&impl Uploader, &(impl Uploader + Lister)) so it works with any
compatible BucketRef and can easily be tested with fakes.
§Declaring a bucket
Chain const configuration methods after Bucket::new. Encore parses
these statically from the declaration and provisions the bucket accordingly:
use encore::objects::{Bucket, LifecycleRule, Retention, StorageClass};
static UPLOADS: Bucket = Bucket::new("uploads")
.versioned()
.storage_class(StorageClass::Infrequent)
.lifecycle(&[
LifecycleRule::new().prefix("tmp/").delete_after_days(1),
LifecycleRule::new()
.move_to_infrequent_after_days(30)
.move_to_cold_after_days(90),
LifecycleRule::new()
.delete_noncurrent_after_days(30)
.keep_noncurrent_versions(5),
])
.retention(Retention::days(2555))
.object_retention();§Errors
All bucket operations return this module’s Error:
Error::NotFound: the object or requested version does not exist.Error::PreconditionFailed: a precondition (not_exists,upload_if_match,remove_if_match, orif_match) was not met.Error::Retained: a retention policy prevents deleting or overwriting the object.Error::InvalidArgument: invalid input was passed to the operation.Error::Other: another failure occurred, such as being unable to reach the storage provider.
Error does not automatically convert into
encore::Error. Match on it when you need to handle
specific failure cases:
use encore::objects::{self, Bucket};
static UPLOADS: Bucket = Bucket::named("uploads");
// Writes `state.json` only if no one else has since it was read.
async fn save(next: Vec<u8>) -> Result<bool, objects::Error> {
let seen = UPLOADS.attrs("state.json").await?;
match UPLOADS.upload_if_match("state.json", next, seen.revision()).await {
Ok(_) => Ok(true),
Err(objects::Error::PreconditionFailed) => Ok(false),
Err(err) => Err(err),
}
}When a function returns encore::Error (such as a Pub/Sub
handler), map the error explicitly with an appropriate error code:
async fn on_upload(key: &str) -> Result<(), encore::Error> {
let attrs = UPLOADS
.attrs(key)
.await
.map_err(|e| encore::Error::internal(e.to_string()))?;
println!("{} is {} bytes", attrs.name, attrs.size);
Ok(())
}Modules§
Structs§
- Attrs
Request - Request builder returned by
Bucket::attrs. Await it to fetchObjectAttrs. - Bucket
- An object-storage bucket.
- Bucket
Ref - A
Copyreference to aBucketthat grants only the permissionsP, created withBucket::reference. - Download
- An active object download returned by
Bucket::downloadonce the storage provider responds. - Download
Request - Request builder returned by
Bucket::download. Await it to start theDownload. - Exists
Request - Request builder returned by
Bucket::exists. Await it to check whether the object exists. - Extend
Retention Request - Request builder returned by
Bucket::extend_retention. Await it to extend retention and receive the updatedObjectAttrs. - Lifecycle
Rule - A lifecycle rule for a bucket (see
Bucket::lifecycle). - List
Entry - Re-exported types used by bucket operations.
- List
Iterator - An async iterator over objects in a bucket, returned by
Bucket::list. - List
Request - Request builder returned by
Bucket::list. Await it to obtain aListIterator. - List
Versions Request - Request builder returned by
Bucket::list_versions. Await it to obtain aVersionIterator. - Object
Attrs - Re-exported types used by bucket operations.
- Object
Version - Re-exported types used by bucket operations.
One stored version of an object, as
Bucket::list_versionslists it. - Remove
Request - Request builder returned by
Bucket::remove. Await it to delete the object. - Retention
- Minimum retention period for objects written to a bucket (see
Bucket::retention). - Revision
- Re-exported types used by bucket operations.
One revision of an object: what an
if_matchprecondition compares. An object’s attributes give it (ObjectAttrs::revision), and so does a download, of the bytes it reads (DownloadInfo::revision). - Signed
Download Url - A pre-signed URL granting temporary permission to download an object,
returned by
Bucket::signed_download_url. - Signed
Download UrlRequest - Request builder returned by
Bucket::signed_download_url. Await it to generate theSignedDownloadUrl. - Signed
Upload Url - A pre-signed URL granting temporary permission to upload an object, returned
by
Bucket::signed_upload_url. - Signed
Upload UrlRequest - Request builder returned by
Bucket::signed_upload_url. Await it to generate theSignedUploadUrl. - Update
Attrs Request - Request builder returned by
Bucket::update_attrs. - Upload
Body - Data to upload to an object.
- Upload
IfMatch Request - Request builder returned by
Bucket::upload_if_match. - Upload
Request - Request builder returned by
Bucket::upload. - Version
Iterator - An async iterator over stored object versions in a bucket, returned by
Bucket::list_versions.
Enums§
- Byte
Range - Re-exported types used by bucket operations. A contiguous byte range within an object.
- Error
- Error returned by object storage bucket operations. See Errors.
- Storage
Class - Re-exported types used by bucket operations. How often an object is expected to be read, which the provider prices its storage by.
Traits§
- Attrs
Updater - Change objects’ attributes and extend their retention. Implemented by a
BucketRefgrantingperms::AttrsUpdater. - Attrser
- Read objects’ attributes, and whether they exist. Implemented by a
BucketRefgrantingperms::Attrser. - Bucket
Perms - A set of bucket permissions: either a single type from
permsor a tuple of them granting the union of their permissions. - Downloader
- Download objects. Implemented by a
BucketRefgrantingperms::Downloader. - IfMatch
Remover - Remove objects only if they are the revision named. Implemented by a
BucketRefgrantingperms::IfMatchRemover. - IfMatch
Uploader - Upload objects only over the revision named. Implemented by a
BucketRefgrantingperms::IfMatchUploader. - Lister
- List objects and their versions. Implemented by a
BucketRefgrantingperms::Lister. - Public
Urler - Resolve objects’ public URLs. Implemented by a
BucketRefgrantingperms::PublicUrler. - Read
Writer - Every permission but
PublicUrler. Implemented by whatever implements them all, such as aBucketRefgrantingperms::ReadWriter. - Remover
- Remove objects. Implemented by a
BucketRefgrantingperms::Remover. - Signed
Downloader - Make signed download URLs. Implemented by a
BucketRefgrantingperms::SignedDownloader. - Signed
Uploader - Make signed upload URLs. Implemented by a
BucketRefgrantingperms::SignedUploader. - Uploader
- Upload objects. Implemented by a
BucketRefgrantingperms::Uploader.