Skip to main content

Module objects

Module objects 

Source
Expand description

Object storage buckets. Declared at module scope; resolved from the runtime on use.

use encore::objects::Bucket;

static UPLOADS: Bucket = Bucket::new("uploads");
static AVATARS: Bucket = Bucket::new("avatars").public().versioned();

Every operation is a method of the Bucket — upload, download, list, attrs, remove, … — named as in Encore’s TypeScript and Go SDKs. That is what lets Encore grant each service exactly the permissions it uses: the operation is visible at the call, so the parser can read it.

An operation that takes options returns a request: each option is a method of it, and awaiting it runs the operation.

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

For the same reason, a bucket cannot be passed around as a value. To hand it to other code, make a BucketRef, which grants only the permissions its type argument names:

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
}

The permissions are one of the perms, or a tuple of them ((perms::Uploader, perms::Lister)). Each has a trait of the same name here, with the methods it grants. Library code takes the traits — &impl Uploader, &(impl Uploader + Lister) — so it works with any reference that grants them, and can be tested against a fake.

§Declaring a bucket

Options follow the name, each a const method of its own. Encore reads them from the declaration and provisions the bucket with them:

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

Every operation fails with this module’s Error:

The error is this module’s own, and doesn’t convert into encore::Error. Match on it where the kind matters:

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),
    }
}

Where a function returns an encore::Error, such as a Pub/Sub handler, convert it there with the code that fits:

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
The permissions a BucketRef can grant, as types for its type argument. Each has a trait of the same name in objects, with the methods it grants.

Structs§

AttrsRequest
The request Bucket::attrs makes: await it for the object’s attributes.
Bucket
An object-storage bucket.
BucketRef
A reference to a Bucket that grants only the permissions P, made by Bucket::reference. Copy, and free to pass to other code.
Download
A download of an object, begun: returned by Bucket::download, once the provider has answered. It knows what the provider said of the object — its revision, size, content_type and last_modified — and its contents are still to come: take them all at once with Download::bytes, as they arrive with Download::bytes_stream, or as an AsyncRead with Download::into_async_read.
DownloadRequest
The download Bucket::download makes: await it for the Download.
ExistsRequest
The request Bucket::exists makes: await it for whether the object exists.
ExtendRetentionRequest
The extension Bucket::extend_retention makes: await it. Returns the object’s attributes after.
LifecycleRule
A rule of a bucket’s lifecycle: an optional prefix and at least one action. The provider applies it, usually within a day of an object becoming due, never early.
ListEntry
Re-exported types the bucket operations take and return.
ListIterator
The objects of a bucket, as they are listed: returned by Bucket::list. Take them one at a time with ListIterator::next, or as a Stream.
ListRequest
The listing Bucket::list makes: await it for the ListIterator.
ListVersionsRequest
The listing Bucket::list_versions makes: await it for the VersionIterator.
ObjectAttrs
Re-exported types the bucket operations take and return.
ObjectVersion
Re-exported types the bucket operations take and return. One stored version of an object, as Bucket::list_versions lists it.
RemoveRequest
The removal Bucket::remove makes: await it.
Retention
How long a bucket keeps every object it is written, at least: see Bucket::retention.
Revision
Re-exported types the bucket operations take and return. 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 URL through which anyone holding it can download an object, made by Bucket::signed_download_url.
SignedDownloadUrlRequest
The URL Bucket::signed_download_url makes: await it.
SignedUploadUrl
A URL through which anyone holding it can upload an object, made by Bucket::signed_upload_url.
SignedUploadUrlRequest
The URL Bucket::signed_upload_url makes: await it.
UpdateAttrsRequest
The change Bucket::update_attrs makes: set the attributes to change with its methods, then await it. An attribute not set stays as it is, and an empty string clears it; a cleared content type is application/octet-stream, as S3 keeps no object without one. Returns the object’s attributes after.
UploadBody
What an upload writes: bytes held in memory — a Vec<u8>, Bytes, &'static [u8] or String — or contents streamed from a reader or a stream of chunks.
UploadIfMatchRequest
The upload Bucket::upload_if_match makes: set its options with its methods, then await it. Returns the object’s stored attributes.
UploadRequest
The upload Bucket::upload makes: set its options with its methods, then await it. Returns the object’s stored attributes.
VersionIterator
The stored versions of a bucket’s objects, as they are listed: returned by Bucket::list_versions. Take them one at a time with VersionIterator::next, or as a Stream.

Enums§

ByteRange
Re-exported types the bucket operations take and return. A contiguous byte range within an object.
Error
What a bucket operation failed with. See the module docs.
StorageClass
Re-exported types the bucket operations take and return. 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: one of the perms, or a tuple of them, which grants what any of its members does. Sealed: the SDK’s permissions are the only ones.
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.