Skip to main content

Bucket

Struct Bucket 

Source
pub struct Bucket { /* private fields */ }
Expand description

An object-storage bucket.

Implementations§

Source§

impl Bucket

Source

pub const fn new(name: &'static str) -> Self

Declare a bucket. const so it can initialize a module-scope static.

Options follow the name, each a method of its own:

use encore::objects::Bucket;

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

pub const fn public(self) -> Self

Makes the bucket public: its objects are readable by anyone, at the URL Bucket::public_url gives.

Part of the declaration: it takes the bucket by value, so it cannot be called on the static.

Source

pub const fn versioned(self) -> Self

Makes the bucket versioned: an object keeps its earlier versions, which an operation’s version option can name.

Part of the declaration, like Bucket::public.

Source

pub const fn storage_class(self, class: StorageClass) -> Self

The storage class an upload gets when it names none, and so how the provider prices the bucket’s objects. StorageClass::Auto lets the provider move each object by how often it is read; it is a bucket’s class only, and allows no lifecycle moves. Standard if not given.

Part of the declaration, like Bucket::public.

Source

pub const fn lifecycle(self, rules: &'static [LifecycleRule]) -> Self

Rules the provider applies to the bucket’s objects: moving them to a colder class, or deleting them, some days after they were written. A rule applies to the objects already in the bucket too. At most 100.

Part of the declaration, like Bucket::public.

use encore::objects::{Bucket, LifecycleRule};

static UPLOADS: Bucket = Bucket::new("uploads").versioned().lifecycle(&[
    LifecycleRule::new().prefix("tmp/").delete_after_days(1),
    LifecycleRule::new().delete_noncurrent_after_days(30).keep_noncurrent_versions(5),
]);
Source

pub const fn retention(self, retention: Retention) -> Self

Keeps every object at least this long after it was written: until then it can’t be deleted or overwritten, which fails with Error::Retained. On AWS such a delete or overwrite succeeds, but the version written is kept underneath until its retention ends.

Part of the declaration, like Bucket::public.

use encore::objects::{Bucket, Retention};

static INVOICES: Bucket = Bucket::new("invoices").retention(Retention::days(2555));
Source

pub const fn object_retention(self) -> Self

Lets objects carry their own retain-until time: set on upload with UploadRequest::retain_until, and later with Bucket::extend_retention. Not supported on Cloudflare R2.

Part of the declaration, like Bucket::public.

Source

pub const fn tag(self, _key: &'static str, _value: &'static str) -> Self

Tags the bucket with key and value: key/value classification, such as .tag("data", "pci"), for policies to read. One call per tag, each with its own key. Encore reads them from the source, so both are string literals. A key is lowercase letters, digits, _ and -, starting with a letter and not with encore, which is kept for Encore’s own tags; a value is the same characters, or empty. Each is at most 63 characters, and a bucket has at most 32 tags.

Part of the declaration: it takes the bucket by value, so it cannot be called on the static.

use encore::objects::Bucket;

static RECEIPTS: Bucket = Bucket::new("receipts").tag("data", "pci");
Source

pub const fn named(name: &'static str) -> Self

Reference an existing bucket by name. To declare a new bucket, use Bucket::new instead.

The name must be a string literal, so Encore can resolve it statically. const so it can initialize a module-scope static. A named bucket takes no options: it is configured where it is declared.

static UPLOADS: encore::objects::Bucket = encore::objects::Bucket::named("uploads");
Source

pub const fn reference<P: BucketPerms>(&'static self) -> BucketRef<P::Id>

A reference to the bucket that grants only the permissions P: one of the perms, or a tuple of them. Unlike the bucket, a reference can be passed to other code; the service is granted the permissions it names.

The permissions must be written as the type argument, since they are what the service is granted: the compiler never infers them. const, so a reference can initialize a module-scope static.

use encore::objects::{perms, Bucket, BucketRef};

static UPLOADS: Bucket = Bucket::named("uploads");
static AVATARS: BucketRef<(perms::Uploader, perms::Lister)> =
    UPLOADS.reference::<(perms::Uploader, perms::Lister)>();
ⓘ
// Not even from the type it is assigned to.
static AVATARS: BucketRef<perms::Uploader> = UPLOADS.reference();
Source

pub fn list(&self) -> ListRequest<'_>

List the objects in the bucket, as an iterator of entries: all of them, or those the request’s options select.

With a delimiter, names are grouped by the part after the prefix up to the delimiter, as a directory listing does: each group is one entry with ListEntry::is_prefix set, whose name ends in the delimiter. Groups and objects are listed in order, and the limit counts both.

let mut entries = UPLOADS.list().prefix("users/42/").delimiter("/").await?;
while let Some(entry) = entries.next().await {
    let entry = entry?;
    if entry.is_prefix {
        println!("{}  (folder)", entry.name); // users/42/photos/
    } else {
        println!("{}", entry.name);
    }
}
Source

pub fn list_versions(&self) -> ListVersionsRequest<'_>

List every stored version of the bucket’s objects: by name, then newest first. A removed object has no latest version. An unversioned bucket lists each object’s one version.

let mut versions = UPLOADS.list_versions().prefix("invoices/").await?;
while let Some(v) = versions.next().await {
    let v = v?;
    println!("{} {:?} latest={}", v.name, v.version, v.latest);
}
Source

pub fn exists(&self, key: &str) -> ExistsRequest<'_>

Whether an object with key exists.

Source

pub fn attrs(&self, key: &str) -> AttrsRequest<'_>

The attributes of the object key: its size, content type, version, etag, metadata, …

Source

pub fn upload( &self, key: &str, data: impl Into<UploadBody>, ) -> UploadRequest<'_>

Upload data to the object key, returning its stored attributes. data is bytes, or UploadBody::reader or UploadBody::chunks to stream them.

UPLOADS
    .upload("a.pdf", data)
    .content_type("application/pdf")
    .cache_control("public, max-age=3600")
    .metadata([("owner", "42")])
    .storage_class(StorageClass::Cold)
    .await?;

// Streamed, and only if there is no such object yet.
UPLOADS
    .upload("b.pdf", UploadBody::reader(file))
    .not_exists()
    .await?;
Source

pub fn upload_if_match( &self, key: &str, data: impl Into<UploadBody>, revision: Revision, ) -> UploadIfMatchRequest<'_>

Upload data to the object key only if it is still the revision revision names, from ObjectAttrs::revision: if another write came first, or the object is gone, it is Error::PreconditionFailed. Takes the options of upload but not_exists.

The match compares the object’s contents, not its attributes: update_attrs doesn’t break it. On AWS it needs read access to the bucket too, which Encore grants for it.

let seen = UPLOADS.attrs("state.json").await?;
UPLOADS
    .upload_if_match("state.json", next, seen.revision())
    .content_type("application/json")
    .await?;
Source

pub fn update_attrs(&self, key: &str) -> UpdateAttrsRequest<'_>

Change the attributes of the object key: its content type, cache control, content disposition or metadata, each a method of the request. One not set stays as it is. Returns the object’s attributes after.

On S3 this writes the object anew, so in a versioned bucket it makes a new version.

let attrs = UPLOADS.attrs("a.pdf").await?;
UPLOADS
    .update_attrs("a.pdf")
    .cache_control("no-store")
    .if_match(attrs.revision())
    .await?;
Source

pub fn extend_retention( &self, key: &str, until: SystemTime, ) -> ExtendRetentionRequest<'_>

Keep the object key until until at least, in a bucket declared with Bucket::object_retention. Retention can only be extended: a time earlier than the object’s is Error::InvalidArgument. Returns the object’s attributes after.

Source

pub fn download(&self, key: &str) -> DownloadRequest<'_>

Download the full contents of the object key, or of a version of it, or a byte range.

// The 256 bytes starting at offset 1024.
let head = UPLOADS.download("big.bin").range(1024..1280).await?;
Source

pub fn download_stream(&self, key: &str) -> DownloadStreamRequest<'_>

Download the object key as it arrives, rather than buffering it whole: see Download.

Source

pub fn remove(&self, key: &str) -> RemoveRequest<'_>

Remove the object key, or a version of it.

Source

pub async fn remove_if_match( &self, key: &str, revision: Revision, ) -> Result<(), Error>

Remove the object key only if it is still the revision revision names, from ObjectAttrs::revision: if another write came first, or it is gone already, it is Error::PreconditionFailed.

The match compares the object’s contents, not its attributes. On AWS it needs read access to the bucket too, which Encore grants for it. Cloudflare R2 can’t remove conditionally: there it is Error::InvalidArgument.

let attrs = UPLOADS.attrs("lock.json").await?;
UPLOADS.remove_if_match("lock.json", attrs.revision()).await?;
Source

pub fn signed_upload_url(&self, key: &str) -> SignedUploadUrlRequest<'_>

A URL through which anyone holding it can upload the object key: valid for an hour, or the request’s ttl.

Source

pub fn signed_download_url(&self, key: &str) -> SignedDownloadUrlRequest<'_>

A URL through which anyone holding it can download the object key: valid for an hour, or the request’s ttl.

Source

pub fn public_url(&self, key: &str) -> Result<String, Error>

The public URL of the object key. Only a bucket declared public has one: for another it is Error::InvalidArgument.

Auto Trait Implementations§

§

impl Forget for Bucket

§

impl Freeze for Bucket

§

impl Move for Bucket

§

impl RefUnwindSafe for Bucket

§

impl Send for Bucket

§

impl Sync for Bucket

§

impl Unpin for Bucket

§

impl UnsafeUnpin for Bucket

§

impl UnwindSafe for Bucket

Blanket Implementations§

Source§

impl<T> Any for T
where T: 'static + ?Sized,

Source§

fn type_id(&self) -> TypeId

Gets the TypeId of self. Read more
Source§

impl<T> Borrow<T> for T
where T: ?Sized,

Source§

fn borrow(&self) -> &T

Immutably borrows from an owned value. Read more
Source§

impl<T> BorrowMut<T> for T
where T: ?Sized,

Source§

fn borrow_mut(&mut self) -> &mut T

Mutably borrows from an owned value. Read more
Source§

impl<ST, DT> CastableFrom<ST, Initialized, Initialized> for DT
where ST: ?Sized, DT: ?Sized,

Source§

impl<ST, DT> CastableFrom<ST, Uninit, Uninit> for DT
where ST: ?Sized, DT: ?Sized,

Source§

impl<T, U> ExactFrom<T> for U
where U: TryFrom<T>,

Source§

fn exact_from(value: T) -> U

Source§

impl<T, U> ExactInto<U> for T
where U: ExactFrom<T>,

Source§

fn exact_into(self) -> U

Source§

impl<T> From<T> for T

Source§

fn from(t: T) -> T

Returns the argument unchanged.

Source§

impl<T> FutureExt for T

Source§

fn with_context(self, otel_cx: Context) -> WithContext<Self> ⓘ

Attaches the provided Context to this type, returning a WithContext wrapper. Read more
Source§

fn with_current_context(self) -> WithContext<Self> ⓘ

Attaches the current Context to this type, returning a WithContext wrapper. Read more
Source§

impl<T> Instrument for T

Source§

fn instrument(self, span: Span) -> Instrumented<Self> ⓘ

Instruments this type with the provided Span, returning an Instrumented wrapper. Read more
Source§

fn in_current_span(self) -> Instrumented<Self> ⓘ

Instruments this type with the current Span, returning an Instrumented wrapper. Read more
Source§

impl<T, U> Into<U> for T
where U: From<T>,

Source§

fn into(self) -> U

Calls U::from(self).

That is, this conversion is whatever the implementation of From<T> for U chooses to do.

Source§

impl<T> IntoEither for T

Source§

fn into_either(self, into_left: bool) -> Either<Self, Self> ⓘ

Converts self into a Left variant of Either<Self, Self> if into_left is true. Converts self into a Right variant of Either<Self, Self> otherwise. Read more
Source§

fn into_either_with<F>(self, into_left: F) -> Either<Self, Self> ⓘ
where F: FnOnce(&Self) -> bool,

Converts self into a Left variant of Either<Self, Self> if into_left(&self) returns true. Converts self into a Right variant of Either<Self, Self> otherwise. Read more
Source§

impl<T> IntoRequest<T> for T

Source§

fn into_request(self) -> Request<T>

Wrap the input message T in a tonic::Request
Source§

impl<Unshared, Shared> IntoShared<Shared> for Unshared
where Shared: FromUnshared<Unshared>,

Source§

fn into_shared(self) -> Shared

Creates a shared type from an unshared type.
Source§

impl<L> LayerExt<L> for L

Source§

fn named_layer<S>(&self, service: S) -> Layered<<L as Layer<S>>::Service, S>
where L: Layer<S>,

Applies the layer to a service and wraps it in Layered.
Source§

impl<T, U> OverflowingInto<U> for T
where U: OverflowingFrom<T>,

Source§

impl<T> PolicyExt for T
where T: ?Sized,

Source§

fn and<P, B, E>(self, other: P) -> And<T, P>
where T: Sized + Policy<B, E>, P: Policy<B, E>,

Create a new Policy that returns Action::Follow only if self and other return Action::Follow. Read more
Source§

fn or<P, B, E>(self, other: P) -> Or<T, P>
where T: Sized + Policy<B, E>, P: Policy<B, E>,

Create a new Policy that returns Action::Follow if either self or other returns Action::Follow. Read more
Source§

impl<T> Read<Exclusive, BecauseExclusive> for T
where T: ?Sized,

Source§

impl<T, U> RoundingInto<U> for T
where U: RoundingFrom<T>,

Source§

impl<T> Same for T

Source§

type Output = T

Should always be Self
Source§

impl<T, U> SaturatingInto<U> for T
where U: SaturatingFrom<T>,

Source§

impl<T, U> TryFrom<U> for T
where U: Into<T>,

Source§

type Error = !

The type returned in the event of a conversion error.
Source§

fn try_from(value: U) -> Result<T, !>

Performs the conversion.
Source§

impl<T, U> TryInto<U> for T
where U: TryFrom<T>,

Source§

type Error = <U as TryFrom<T>>::Error

The type returned in the event of a conversion error.
Source§

fn try_into(self) -> Result<U, <U as TryFrom<T>>::Error>

Performs the conversion.
Source§

impl<V, T> VZip<V> for T
where V: MultiLane<T>,

Source§

fn vzip(self) -> V

Source§

impl<T> WithSubscriber for T

Source§

fn with_subscriber<S>(self, subscriber: S) -> WithDispatch<Self> ⓘ
where S: Into<Dispatch>,

Attaches the provided Subscriber to this type, returning a WithDispatch wrapper. Read more
Source§

fn with_current_subscriber(self) -> WithDispatch<Self> ⓘ

Attaches the current default Subscriber to this type, returning a WithDispatch wrapper. Read more
Source§

impl<T, U> WrappingInto<U> for T
where U: WrappingFrom<T>,

Source§

fn wrapping_into(self) -> U