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

Declares a new object storage bucket.

This function is const so it can initialize a module-level static. Chain configuration methods after new:

use encore::objects::Bucket;

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

pub const fn public(self) -> Self

Makes the bucket publicly readable at the URL returned by Bucket::public_url.

This method takes self by value so it can only be called as part of the static declaration.

Source

pub const fn versioned(self) -> Self

Enables object versioning so earlier versions of an object are kept and can be targeted with a request’s .version(...) option.

Must be called as part of the static declaration.

Source

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

Sets the default storage class for objects uploaded to this bucket (defaults to standard storage).

StorageClass::Auto lets the provider tier objects automatically based on access frequency; it can only be set at the bucket level and cannot be combined with lifecycle storage-class transitions.

Must be called as part of the static declaration.

Source

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

Configures lifecycle rules for transitioning objects to colder storage classes or deleting them after a given age.

Rules also apply to objects already in the bucket. A bucket may have at most 100 rules. Must be called as part of the static declaration.

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

Sets a minimum retention period for every object written to the bucket.

Until the retention period expires, deleting or overwriting an object fails with Error::Retained (on AWS S3, the request creates a new version or delete marker while the retained version remains protected until expiry). Must be called as part of the static declaration.

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

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

pub const fn object_retention(self) -> Self

Enables per-object retention timestamps, configured on upload via UploadRequest::retain_until and extended via Bucket::extend_retention.

Not supported on Cloudflare R2. Must be called as part of the static declaration.

Source

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

Attaches a key/value classification tag (such as .tag("data", "pci")) for policy evaluation.

Call .tag once per tag with unique keys. Both arguments must be string literals so Encore can parse them statically. Keys must start with a lowercase letter, contain only lowercase letters, digits, _, and -, and must not start with encore (reserved for Encore’s own tags). Values use the same character set or may be empty. Each key and value may be at most 63 characters, and a bucket may have at most 32 tags.

Must be called as part of the static declaration.

use encore::objects::Bucket;

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

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

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

name must be a string literal so Encore can resolve it statically. Because the bucket is configured where it is declared, do not chain declaration options on named.

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

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

Creates a BucketRef granting only the permissions P (a single type from perms or a tuple of them).

Unlike Bucket, a BucketRef can be passed to helper functions and libraries, and Encore grants the service the permissions named in P. Because permissions must be explicit in source code, P cannot be inferred by the compiler. This function is const so it can initialize a module-level 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<'_>

Lists objects in the bucket, returning a ListRequest that resolves to a ListIterator.

When delimiter is set, object names are grouped up to the first occurrence of the delimiter (like a directory listing). Each group is returned as a single ListEntry with ListEntry::is_prefix set and a name ending with the delimiter. Groups and objects are returned in order, and 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<'_>

Lists stored versions of objects in the bucket, ordered by name and then newest first.

A removed object has no version with ObjectVersion::latest set. For an unversioned bucket, each object appears as a single 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<'_>

Checks whether an object with key exists.

Source

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

Fetches the attributes of the object key (size, content type, version, ETag, custom metadata, and so on).

Source

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

Uploads data to key and returns the stored ObjectAttrs.

Pass an in-memory buffer directly, or use UploadBody::reader / UploadBody::chunks to stream large payloads.

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<'_>

Uploads data to key only if the object still matches revision (from ObjectAttrs::revision or Download::revision).

If another write occurred first or the object no longer exists, the upload fails with Error::PreconditionFailed. Supports all upload options except not_exists.

The revision check compares object contents rather than attributes, so update_attrs does not invalidate it. On AWS, this operation also requires read permission, which Encore grants automatically.

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<'_>

Updates attributes on key (content type, cache control, content disposition, or custom metadata) and returns the updated ObjectAttrs.

Unspecified attributes remain unchanged. On S3, updating attributes rewrites the object, which creates a new version in versioned buckets.

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<'_>

Extends the retention timestamp of key to at least until in a bucket declared with Bucket::object_retention, returning the updated ObjectAttrs.

Retention can only be extended; passing a timestamp earlier than the object’s current retain-until time returns Error::InvalidArgument.

Source

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

Downloads key (optionally a specific version or byte range).

Awaiting the returned DownloadRequest resolves to a Download as soon as the provider responds with headers (or fails with Error::NotFound if the object does not exist). Read the body from the Download all at once or as a stream.

let whole = UPLOADS.download("a.pdf").await?.bytes().await?;

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

// The last 64 bytes, however large the object is.
let tail = UPLOADS.download("big.bin").last(64).await?.bytes().await?;
Source

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

Removes key, or a specific version of it.

Source

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

Removes key only if the object still matches revision (from ObjectAttrs::revision or Download::revision).

If another write occurred first or the object no longer exists, this fails with Error::PreconditionFailed. The check compares object contents rather than attributes. On AWS, this operation also requires read permission, which Encore grants automatically. Conditional removal is not supported on Cloudflare R2 and returns 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<'_>

Generates a pre-signed URL for uploading key, valid for one hour by default (override with SignedUploadUrlRequest::ttl).

Source

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

Generates a pre-signed URL for downloading key, valid for one hour by default (override with SignedDownloadUrlRequest::ttl).

Source

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

Returns the public URL for key.

Only available for buckets declared with Bucket::public; returns Error::InvalidArgument for private buckets.

Auto Trait Implementations§

§

impl Forget for Bucket

§

impl Freeze for Bucket
where &'static str: Freeze, &'static [LifecycleRule]: Freeze,

§

impl Move for Bucket

§

impl RefUnwindSafe for Bucket

§

impl Send for Bucket
where &'static str: Send, &'static [LifecycleRule]: Send,

§

impl Sync for Bucket

§

impl Unpin for Bucket
where &'static str: Unpin, &'static [LifecycleRule]: Unpin,

§

impl UnsafeUnpin for Bucket
where &'static str: UnsafeUnpin, &'static [LifecycleRule]: UnsafeUnpin,

§

impl UnwindSafe for Bucket
where &'static str: UnwindSafe, &'static [LifecycleRule]: UnwindSafe,

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