Skip to main content

Module objects

Module objects 

Source
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 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§

perms
Permission marker types for BucketRef.

Structs§

AttrsRequest
Request builder returned by Bucket::attrs. Await it to fetch ObjectAttrs.
Bucket
An object-storage bucket.
BucketRef
A Copy reference to a Bucket that grants only the permissions P, created with Bucket::reference.
Download
An active object download returned by Bucket::download once the storage provider responds.
DownloadRequest
Request builder returned by Bucket::download. Await it to start the Download.
ExistsRequest
Request builder returned by Bucket::exists. Await it to check whether the object exists.
ExtendRetentionRequest
Request builder returned by Bucket::extend_retention. Await it to extend retention and receive the updated ObjectAttrs.
LifecycleRule
A lifecycle rule for a bucket (see Bucket::lifecycle).
ListEntry
Re-exported types used by bucket operations.
ListIterator
An async iterator over objects in a bucket, returned by Bucket::list.
ListRequest
Request builder returned by Bucket::list. Await it to obtain a ListIterator.
ListVersionsRequest
Request builder returned by Bucket::list_versions. Await it to obtain a VersionIterator.
ObjectAttrs
Re-exported types used by bucket operations.
ObjectVersion
Re-exported types used by bucket operations. One stored version of an object, as Bucket::list_versions lists it.
RemoveRequest
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_match precondition compares. An object’s attributes give it (ObjectAttrs::revision), and so does a download, of the bytes it reads (DownloadInfo::revision).
SignedDownloadUrl
A pre-signed URL granting temporary permission to download an object, returned by Bucket::signed_download_url.
SignedDownloadUrlRequest
Request builder returned by Bucket::signed_download_url. Await it to generate the SignedDownloadUrl.
SignedUploadUrl
A pre-signed URL granting temporary permission to upload an object, returned by Bucket::signed_upload_url.
SignedUploadUrlRequest
Request builder returned by Bucket::signed_upload_url. Await it to generate the SignedUploadUrl.
UpdateAttrsRequest
Request builder returned by Bucket::update_attrs.
UploadBody
Data to upload to an object.
UploadIfMatchRequest
Request builder returned by Bucket::upload_if_match.
UploadRequest
Request builder returned by Bucket::upload.
VersionIterator
An async iterator over stored object versions in a bucket, returned by Bucket::list_versions.

Enums§

ByteRange
Re-exported types used by bucket operations. A contiguous byte range within an object.
Error
Error returned by object storage bucket operations. See Errors.
StorageClass
Re-exported types used by bucket operations. How often an object is expected to be read, which the provider prices its storage by.

Traits§

AttrsUpdater
Change objects’ attributes and extend their retention. Implemented by a BucketRef granting perms::AttrsUpdater.
Attrser
Read objects’ attributes, and whether they exist. Implemented by a BucketRef granting perms::Attrser.
BucketPerms
A set of bucket permissions: either a single type from perms or a tuple of them granting the union of their permissions.
Downloader
Download objects. Implemented by a BucketRef granting perms::Downloader.
IfMatchRemover
Remove objects only if they are the revision named. Implemented by a BucketRef granting perms::IfMatchRemover.
IfMatchUploader
Upload objects only over the revision named. Implemented by a BucketRef granting perms::IfMatchUploader.
Lister
List objects and their versions. Implemented by a BucketRef granting perms::Lister.
PublicUrler
Resolve objects’ public URLs. Implemented by a BucketRef granting perms::PublicUrler.
ReadWriter
Every permission but PublicUrler. Implemented by whatever implements them all, such as a BucketRef granting perms::ReadWriter.
Remover
Remove objects. Implemented by a BucketRef granting perms::Remover.
SignedDownloader
Make signed download URLs. Implemented by a BucketRef granting perms::SignedDownloader.
SignedUploader
Make signed upload URLs. Implemented by a BucketRef granting perms::SignedUploader.
Uploader
Upload objects. Implemented by a BucketRef granting perms::Uploader.