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?;
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:
Error::NotFound: the object, or the version asked for, does not exist.Error::PreconditionFailed: a precondition does not hold:not_exists, or the revisionupload_if_match,remove_if_matchorif_matchnames.Error::Retained: retention keeps the object from being deleted or overwritten yet.Error::InvalidArgument: a mistake in the call, saying what it is.Error::Other: anything else, such as a failure to reach the provider.
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
BucketRefcan grant, as types for its type argument. Each has a trait of the same name inobjects, with the methods it grants.
Structs§
- Attrs
Request - The request
Bucket::attrsmakes: await it for the object’s attributes. - Bucket
- An object-storage bucket.
- Bucket
Ref - A reference to a
Bucketthat grants only the permissionsP, made byBucket::reference.Copy, and free to pass to other code. - Byte
Range - Re-exported types the bucket operations take and return. A contiguous byte range within an object.
- Download
- The contents of an object, as they arrive: returned by
Bucket::download_stream. Take them chunk by chunk withDownload::next— or as aStream— all at once withDownload::bytes, or as anAsyncReadwithDownload::into_async_read. - Download
Request - The download
Bucket::downloadmakes: await it for the object’s contents. - Download
Stream Request - The download
Bucket::download_streammakes: await it for theDownload. - Exists
Request - The request
Bucket::existsmakes: await it for whether the object exists. - Extend
Retention Request - The extension
Bucket::extend_retentionmakes: await it. Returns the object’s attributes after. - Lifecycle
Rule - A rule of a bucket’s lifecycle: an optional
prefixand at least one action. The provider applies it, usually within a day of an object becoming due, never early. - List
Entry - Re-exported types the bucket operations take and return.
- List
Iterator - The objects of a bucket, as they are listed: returned by
Bucket::list. Take them one at a time withListIterator::next, or as aStream. - List
Request - The listing
Bucket::listmakes: await it for theListIterator. - List
Versions Request - The listing
Bucket::list_versionsmakes: await it for theVersionIterator. - Object
Attrs - Re-exported types the bucket operations take and return.
- Object
Version - Re-exported types the bucket operations take and return.
One stored version of an object, as
Bucket::list_versionslists it. - Remove
Request - The removal
Bucket::removemakes: 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.
What an
if_matchprecondition compares: one revision of an object, asObjectAttrs::revisiongives it. - Signed
Download Url - A URL through which anyone holding it can download an object, made by
Bucket::signed_download_url. - Signed
Download UrlRequest - The URL
Bucket::signed_download_urlmakes: await it. - Signed
Upload Url - A URL through which anyone holding it can upload an object, made by
Bucket::signed_upload_url. - Signed
Upload UrlRequest - The URL
Bucket::signed_upload_urlmakes: await it. - Update
Attrs Request - The change
Bucket::update_attrsmakes: 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 isapplication/octet-stream, as S3 keeps no object without one. Returns the object’s attributes after. - Upload
Body - What an upload writes: bytes held in memory — a
Vec<u8>,Bytes,&'static [u8]orString— or contents streamed from areaderor a stream ofchunks. - Upload
IfMatch Request - The upload
Bucket::upload_if_matchmakes: set its options with its methods, then await it. Returns the object’s stored attributes. - Upload
Request - The upload
Bucket::uploadmakes: set its options with its methods, then await it. Returns the object’s stored attributes. - Version
Iterator - The stored versions of a bucket’s objects, as they are listed: returned
by
Bucket::list_versions. Take them one at a time withVersionIterator::next, or as aStream.
Enums§
- Error
- What a bucket operation failed with. See the module docs.
- Storage
Class - 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§
- 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: 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
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.