pub struct Bucket { /* private fields */ }Expand description
An object-storage bucket.
Implementations§
Source§impl Bucket
impl Bucket
Sourcepub const fn new(name: &'static str) -> Self
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();Sourcepub const fn public(self) -> Self
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.
Sourcepub const fn versioned(self) -> Self
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.
Sourcepub const fn storage_class(self, class: StorageClass) -> Self
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.
Sourcepub const fn lifecycle(self, rules: &'static [LifecycleRule]) -> Self
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),
]);Sourcepub const fn retention(self, retention: Retention) -> Self
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));Sourcepub const fn object_retention(self) -> Self
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.
Sourcepub const fn tag(self, _key: &'static str, _value: &'static str) -> Self
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");Sourcepub const fn named(name: &'static str) -> Self
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");Sourcepub const fn reference<P: BucketPerms>(&'static self) -> BucketRef<P::Id>
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();Sourcepub fn list(&self) -> ListRequest<'_>
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);
}
}Sourcepub fn list_versions(&self) -> ListVersionsRequest<'_>
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);
}Sourcepub fn exists(&self, key: &str) -> ExistsRequest<'_>
pub fn exists(&self, key: &str) -> ExistsRequest<'_>
Checks whether an object with key exists.
Sourcepub fn attrs(&self, key: &str) -> AttrsRequest<'_>
pub fn attrs(&self, key: &str) -> AttrsRequest<'_>
Fetches the attributes of the object key (size, content type, version,
ETag, custom metadata, and so on).
Sourcepub fn upload(
&self,
key: &str,
data: impl Into<UploadBody>,
) -> UploadRequest<'_>
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?;Sourcepub fn upload_if_match(
&self,
key: &str,
data: impl Into<UploadBody>,
revision: Revision,
) -> UploadIfMatchRequest<'_>
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?;Sourcepub fn update_attrs(&self, key: &str) -> UpdateAttrsRequest<'_>
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?;Sourcepub fn extend_retention(
&self,
key: &str,
until: SystemTime,
) -> ExtendRetentionRequest<'_>
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.
Sourcepub fn download(&self, key: &str) -> DownloadRequest<'_>
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?;Sourcepub fn remove(&self, key: &str) -> RemoveRequest<'_>
pub fn remove(&self, key: &str) -> RemoveRequest<'_>
Removes key, or a specific version of it.
Sourcepub async fn remove_if_match(
&self,
key: &str,
revision: Revision,
) -> Result<(), Error>
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?;Sourcepub fn signed_upload_url(&self, key: &str) -> SignedUploadUrlRequest<'_>
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).
Sourcepub fn signed_download_url(&self, key: &str) -> SignedDownloadUrlRequest<'_>
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).
Sourcepub fn public_url(&self, key: &str) -> Result<String, Error>
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
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> BorrowMut<T> for Twhere
T: ?Sized,
impl<T> BorrowMut<T> for Twhere
T: ?Sized,
Source§fn borrow_mut(&mut self) -> &mut T
fn borrow_mut(&mut self) -> &mut T
impl<ST, DT> CastableFrom<ST, Initialized, Initialized> for DT
impl<ST, DT> CastableFrom<ST, Uninit, Uninit> for DT
Source§impl<T> FutureExt for T
impl<T> FutureExt for T
Source§fn with_context(self, otel_cx: Context) -> WithContext<Self> ⓘ
fn with_context(self, otel_cx: Context) -> WithContext<Self> ⓘ
Source§fn with_current_context(self) -> WithContext<Self> ⓘ
fn with_current_context(self) -> WithContext<Self> ⓘ
Source§impl<T> Instrument for T
impl<T> Instrument for T
Source§fn instrument(self, span: Span) -> Instrumented<Self> ⓘ
fn instrument(self, span: Span) -> Instrumented<Self> ⓘ
Source§fn in_current_span(self) -> Instrumented<Self> ⓘ
fn in_current_span(self) -> Instrumented<Self> ⓘ
Source§impl<T> IntoEither for T
impl<T> IntoEither for T
Source§fn into_either(self, into_left: bool) -> Either<Self, Self> ⓘ
fn into_either(self, into_left: bool) -> Either<Self, Self> ⓘ
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 moreSource§fn into_either_with<F>(self, into_left: F) -> Either<Self, Self> ⓘ
fn into_either_with<F>(self, into_left: F) -> Either<Self, Self> ⓘ
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 moreSource§impl<T> IntoRequest<T> for T
impl<T> IntoRequest<T> for T
Source§fn into_request(self) -> Request<T>
fn into_request(self) -> Request<T>
T in a tonic::Request