encore/objects.rs
1//! Object storage buckets, declared at module scope and resolved from the
2//! runtime on use.
3//!
4//! ```no_run
5//! use encore::objects::Bucket;
6//!
7//! static UPLOADS: Bucket = Bucket::new("uploads");
8//! static AVATARS: Bucket = Bucket::new("avatars").public().versioned();
9//! ```
10//!
11//! Bucket operations (`upload`, `download`, `list`, `attrs`, `remove`, and so
12//! on) are methods directly on [`Bucket`], matching Encore's TypeScript and Go
13//! SDKs. Because each operation is called directly on the bucket, Encore can
14//! statically analyze your code and grant each service only the permissions it
15//! uses.
16//!
17//! Operations that accept options return a request builder. Configure options
18//! with chained methods and `.await` the request to execute it.
19//!
20//! ```no_run
21//! use encore::objects::{Bucket, StorageClass};
22//!
23//! static UPLOADS: Bucket = Bucket::named("uploads");
24//!
25//! async fn save(data: Vec<u8>) -> Result<(), encore::objects::Error> {
26//! UPLOADS.upload("a.pdf", data.clone()).await?;
27//! UPLOADS
28//! .upload("b.pdf", data)
29//! .content_type("application/pdf")
30//! .metadata([("owner", "42")])
31//! .storage_class(StorageClass::Cold)
32//! .await?;
33//! let head = UPLOADS.download("b.pdf").range(0..1024).await?.bytes().await?;
34//! Ok(())
35//! }
36//! ```
37//!
38//! # References
39//!
40//! Because Encore tracks bucket permissions statically, a [`Bucket`] cannot be
41//! passed around as a value. To pass a bucket to helper functions or libraries,
42//! create a [`BucketRef`] that grants only the permissions specified in its
43//! type argument:
44//!
45//! ```no_run
46//! use encore::objects::{self, perms, Bucket, Uploader};
47//!
48//! static UPLOADS: Bucket = Bucket::named("uploads");
49//!
50//! // Library code asks for the permissions it needs, as traits.
51//! async fn save(bucket: &impl Uploader, key: &str) -> Result<(), objects::Error> {
52//! bucket.upload(key, b"hello".to_vec()).await?;
53//! Ok(())
54//! }
55//!
56//! async fn greet() -> Result<(), objects::Error> {
57//! save(&UPLOADS.reference::<perms::Uploader>(), "greeting.txt").await
58//! }
59//! ```
60//!
61//! Permissions can be a single type from [`perms`] or a tuple of them (such as
62//! `(perms::Uploader, perms::Lister)`). Each permission has a matching trait in
63//! this module exposing the methods it grants. Library code should accept those
64//! traits (`&impl Uploader`, `&(impl Uploader + Lister)`) so it works with any
65//! compatible [`BucketRef`] and can easily be tested with fakes.
66//!
67//! # Declaring a bucket
68//!
69//! Chain `const` configuration methods after [`Bucket::new`]. Encore parses
70//! these statically from the declaration and provisions the bucket accordingly:
71//!
72//! ```no_run
73//! use encore::objects::{Bucket, LifecycleRule, Retention, StorageClass};
74//!
75//! static UPLOADS: Bucket = Bucket::new("uploads")
76//! .versioned()
77//! .storage_class(StorageClass::Infrequent)
78//! .lifecycle(&[
79//! LifecycleRule::new().prefix("tmp/").delete_after_days(1),
80//! LifecycleRule::new()
81//! .move_to_infrequent_after_days(30)
82//! .move_to_cold_after_days(90),
83//! LifecycleRule::new()
84//! .delete_noncurrent_after_days(30)
85//! .keep_noncurrent_versions(5),
86//! ])
87//! .retention(Retention::days(2555))
88//! .object_retention();
89//! ```
90//!
91//! # Errors
92//!
93//! All bucket operations return this module's [`Error`]:
94//!
95//! - [`Error::NotFound`]: the object or requested version does not exist.
96//! - [`Error::PreconditionFailed`]: a precondition (`not_exists`,
97//! `upload_if_match`, `remove_if_match`, or `if_match`) was not met.
98//! - [`Error::Retained`]: a retention policy prevents deleting or overwriting
99//! the object.
100//! - [`Error::InvalidArgument`]: invalid input was passed to the operation.
101//! - [`Error::Other`]: another failure occurred, such as being unable to reach
102//! the storage provider.
103//!
104//! [`Error`] does not automatically convert into
105//! [`encore::Error`](crate::Error). Match on it when you need to handle
106//! specific failure cases:
107//!
108//! ```no_run
109//! use encore::objects::{self, Bucket};
110//!
111//! static UPLOADS: Bucket = Bucket::named("uploads");
112//!
113//! // Writes `state.json` only if no one else has since it was read.
114//! async fn save(next: Vec<u8>) -> Result<bool, objects::Error> {
115//! let seen = UPLOADS.attrs("state.json").await?;
116//! match UPLOADS.upload_if_match("state.json", next, seen.revision()).await {
117//! Ok(_) => Ok(true),
118//! Err(objects::Error::PreconditionFailed) => Ok(false),
119//! Err(err) => Err(err),
120//! }
121//! }
122//! ```
123//!
124//! When a function returns [`encore::Error`](crate::Error) (such as a Pub/Sub
125//! handler), map the error explicitly with an appropriate error code:
126//!
127//! ```no_run
128//! # use encore::objects::Bucket;
129//! # static UPLOADS: Bucket = Bucket::named("uploads");
130//! async fn on_upload(key: &str) -> Result<(), encore::Error> {
131//! let attrs = UPLOADS
132//! .attrs(key)
133//! .await
134//! .map_err(|e| encore::Error::internal(e.to_string()))?;
135//! println!("{} is {} bytes", attrs.name, attrs.size);
136//! Ok(())
137//! }
138//! ```
139
140use std::collections::BTreeMap;
141use std::future::{poll_fn, Future, IntoFuture};
142use std::marker::PhantomData;
143use std::ops::{Bound, RangeBounds};
144use std::pin::Pin;
145use std::task::{Context, Poll};
146use std::time::{Duration, SystemTime};
147
148use bytes::Bytes;
149use encore_sdk_core::objects;
150use futures_core::future::BoxFuture;
151use futures_core::Stream;
152use tokio::io::AsyncRead;
153use tokio_util::io::StreamReader;
154
155use crate::perm::{Flag, Granted, No};
156use crate::runtime::core;
157
158/// Re-exported types used by bucket operations.
159pub use encore_sdk_core::objects::{
160 ByteRange, ListEntry, ObjectAttrs, ObjectVersion, Revision, StorageClass,
161};
162
163/// Error returned by object storage bucket operations. See
164/// [Errors](self#errors).
165///
166/// This type does not automatically convert into
167/// [`encore::Error`](crate::Error); map it explicitly with the appropriate
168/// error code for your caller.
169#[derive(Debug, thiserror::Error)]
170#[non_exhaustive]
171pub enum Error {
172 /// The object or requested version does not exist.
173 #[error("object not found")]
174 NotFound,
175 /// A precondition was not met: the object already exists (`not_exists`), or
176 /// its current revision no longer matches the expected revision
177 /// (`upload_if_match`, `remove_if_match`, or `if_match`).
178 #[error("precondition failed")]
179 PreconditionFailed,
180 /// The object cannot be deleted or overwritten because of the bucket's
181 /// retention period or the object's own retain-until timestamp.
182 #[error("object is retained")]
183 Retained,
184 /// The call passed invalid input (such as a malformed version, unsupported
185 /// metadata, or a retain-until time earlier than the object's current
186 /// retention).
187 #[error("invalid argument: {0}")]
188 InvalidArgument(String),
189 /// Any other failure, such as being unable to reach the storage provider.
190 #[error(transparent)]
191 Other(Box<dyn std::error::Error + Send + Sync>),
192}
193
194impl Error {
195 /// An [`Error::Other`] with `message`.
196 fn other(message: impl Into<String>) -> Self {
197 Error::Other(message.into().into())
198 }
199}
200
201/// The core's error as this module's. Its `Internal` and `Other` are both
202/// [`Error::Other`], which keeps the core's error.
203fn obj_err(err: objects::Error) -> Error {
204 match err {
205 objects::Error::NotFound => Error::NotFound,
206 objects::Error::PreconditionFailed => Error::PreconditionFailed,
207 objects::Error::Retained => Error::Retained,
208 objects::Error::InvalidArgument(message) => Error::InvalidArgument(message.into_owned()),
209 err @ (objects::Error::Internal(_) | objects::Error::Other(_)) => {
210 Error::Other(Box::new(err))
211 }
212 }
213}
214
215/// `err`, from setting up the current test's instance of a bucket under
216/// `encore test`, as this module's error.
217fn test_err(err: crate::Error) -> Error {
218 Error::Other(Box::new(err))
219}
220
221/// An active object download returned by [`Bucket::download`] once the storage
222/// provider responds.
223///
224/// Object metadata — [`revision`](Download::revision),
225/// [`size`](Download::size), [`content_type`](Download::content_type), and
226/// [`last_modified`](Download::last_modified) — is available immediately. Read
227/// the body all at once with [`Download::bytes`], as a stream of chunks with
228/// [`Download::bytes_stream`], or as an [`AsyncRead`] with
229/// [`Download::into_async_read`].
230///
231/// ```no_run
232/// # use encore::objects::Bucket;
233/// # static UPLOADS: Bucket = Bucket::named("uploads");
234/// # async fn f(mut file: tokio::fs::File) -> Result<(), Box<dyn std::error::Error>> {
235/// // In one piece.
236/// let bytes = UPLOADS.download("a.pdf").await?.bytes().await?;
237///
238/// // Or as it arrives, straight into a file.
239/// let mut reader = UPLOADS.download("big.bin").await?.into_async_read();
240/// tokio::io::copy(&mut reader, &mut file).await?;
241/// # Ok(())
242/// # }
243/// ```
244///
245/// [`Download::revision`] identifies the exact revision being read, so you can
246/// perform an optimistic read-modify-write:
247///
248/// ```no_run
249/// # use encore::objects::{self, Bucket};
250/// # static STATE: Bucket = Bucket::named("state");
251/// # fn advance(seen: &[u8]) -> Vec<u8> { seen.to_vec() }
252/// async fn step() -> Result<bool, objects::Error> {
253/// let read = STATE.download("head").await?;
254/// let revision = read.revision();
255/// let next = advance(&read.bytes().await?);
256/// match STATE.upload_if_match("head", next, revision).await {
257/// Ok(_) => Ok(true),
258/// Err(objects::Error::PreconditionFailed) => Ok(false),
259/// Err(err) => Err(err),
260/// }
261/// }
262/// ```
263///
264/// A download holds its underlying connection until it is read to completion or
265/// dropped (which cancels the remaining transfer).
266pub struct Download {
267 inner: objects::Download,
268}
269
270impl Download {
271 /// Constructs an in-memory [`Download`] from `attrs` and `data`, useful
272 /// when implementing a fake [`Downloader`] in tests.
273 pub fn of(attrs: &ObjectAttrs, data: impl Into<Bytes>) -> Self {
274 let data: Bytes = data.into();
275 Download {
276 inner: objects::Download {
277 info: objects::DownloadInfo {
278 revision: attrs.revision(),
279 size: attrs.size,
280 content_type: attrs.content_type.clone(),
281 last_modified: attrs.last_modified,
282 },
283 length: data.len() as u64,
284 stream: Box::pin(Once(Some(data))),
285 },
286 }
287 }
288
289 /// Returns the revision of the downloaded object, matching
290 /// [`ObjectAttrs::revision`]. Pass this to
291 /// [`upload_if_match`](Bucket::upload_if_match),
292 /// [`remove_if_match`](Bucket::remove_if_match), or `if_match`.
293 pub fn revision(&self) -> Revision {
294 self.inner.info.revision.clone()
295 }
296
297 /// Returns the total size of the object in bytes, even when downloading a
298 /// byte range.
299 pub fn size(&self) -> u64 {
300 self.inner.info.size
301 }
302
303 /// Returns the object's content type, if set.
304 pub fn content_type(&self) -> Option<&str> {
305 self.inner.info.content_type.as_deref()
306 }
307
308 /// Returns when the object was last modified, or `None` if the provider did
309 /// not report it.
310 pub fn last_modified(&self) -> Option<SystemTime> {
311 self.inner.info.last_modified
312 }
313
314 /// Reads the entire download body into memory.
315 pub async fn bytes(self) -> Result<Vec<u8>, Error> {
316 self.inner.bytes().await.map_err(obj_err)
317 }
318
319 /// Returns the download body as a stream of byte chunks as they arrive.
320 pub fn bytes_stream(self) -> impl Stream<Item = Result<Bytes, Error>> + Send + Unpin + 'static {
321 Chunks(self.inner.stream)
322 }
323
324 /// Converts the download body into an [`AsyncRead`], suitable for parsers,
325 /// decompressors, or `tokio::io::copy`.
326 pub fn into_async_read(self) -> impl AsyncRead + Unpin + Send + 'static {
327 StreamReader::new(ChunkErrors(Chunks(self.inner.stream)))
328 }
329}
330
331impl std::fmt::Debug for Download {
332 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
333 self.inner.fmt(f)
334 }
335}
336
337/// A download's chunks, its errors this module's.
338struct Chunks(objects::DownloadStream);
339
340impl Stream for Chunks {
341 type Item = Result<Bytes, Error>;
342
343 fn poll_next(self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<Option<Self::Item>> {
344 self.get_mut()
345 .0
346 .as_mut()
347 .poll_next(cx)
348 .map(|chunk| chunk.map(|chunk| chunk.map_err(obj_err)))
349 }
350}
351
352/// A download whose errors are `io::Error`s, as a reader's are.
353struct ChunkErrors(Chunks);
354
355impl Stream for ChunkErrors {
356 type Item = std::io::Result<Bytes>;
357
358 fn poll_next(self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<Option<Self::Item>> {
359 Pin::new(&mut self.get_mut().0)
360 .poll_next(cx)
361 .map(|chunk| chunk.map(|chunk| chunk.map_err(std::io::Error::other)))
362 }
363}
364
365/// A stream of one chunk.
366struct Once(Option<Bytes>);
367
368impl Stream for Once {
369 type Item = Result<Bytes, objects::Error>;
370
371 fn poll_next(self: Pin<&mut Self>, _: &mut Context<'_>) -> Poll<Option<Self::Item>> {
372 Poll::Ready(self.get_mut().0.take().map(Ok))
373 }
374}
375
376/// An async iterator over objects in a bucket, returned by [`Bucket::list`].
377///
378/// Consume entries with [`ListIterator::next`] or via its [`Stream`]
379/// implementation.
380pub struct ListIterator {
381 inner: objects::ListIterator,
382}
383
384impl ListIterator {
385 /// Returns the next object entry, or `None` when the listing is complete.
386 pub async fn next(&mut self) -> Option<Result<ListEntry, Error>> {
387 poll_fn(|cx| Pin::new(&mut *self).poll_next(cx)).await
388 }
389}
390
391impl Stream for ListIterator {
392 type Item = Result<ListEntry, Error>;
393
394 fn poll_next(self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<Option<Self::Item>> {
395 Pin::new(&mut self.get_mut().inner)
396 .poll_next(cx)
397 .map(|entry| entry.map(|entry| entry.map_err(obj_err)))
398 }
399}
400
401/// An async iterator over stored object versions in a bucket, returned by
402/// [`Bucket::list_versions`].
403///
404/// Consume versions with [`VersionIterator::next`] or via its [`Stream`]
405/// implementation.
406pub struct VersionIterator {
407 inner: objects::VersionIterator,
408}
409
410impl VersionIterator {
411 /// Returns the next object version, or `None` when the listing is complete.
412 pub async fn next(&mut self) -> Option<Result<ObjectVersion, Error>> {
413 poll_fn(|cx| Pin::new(&mut *self).poll_next(cx)).await
414 }
415}
416
417impl Stream for VersionIterator {
418 type Item = Result<ObjectVersion, Error>;
419
420 fn poll_next(self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<Option<Self::Item>> {
421 Pin::new(&mut self.get_mut().inner)
422 .poll_next(cx)
423 .map(|version| version.map(|version| version.map_err(obj_err)))
424 }
425}
426
427/// A stream of chunks as the reader an upload takes. The runtime shares the
428/// reader between threads, which a stream need not allow: the lock is what
429/// makes it shareable, and is never contended, as only one reads at a time.
430struct ChunkReader<S>(std::sync::Mutex<Pin<Box<S>>>);
431
432impl<S, B, E> Stream for ChunkReader<S>
433where
434 S: Stream<Item = Result<B, E>>,
435 B: Into<Bytes>,
436 E: Into<Box<dyn std::error::Error + Send + Sync>>,
437{
438 type Item = std::io::Result<Bytes>;
439
440 fn poll_next(self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<Option<Self::Item>> {
441 let stream = self
442 .get_mut()
443 .0
444 .get_mut()
445 .unwrap_or_else(|e| e.into_inner());
446 stream
447 .as_mut()
448 .poll_next(cx)
449 .map(|chunk| chunk.map(|chunk| chunk.map(Into::into).map_err(std::io::Error::other)))
450 }
451}
452
453/// Data to upload to an object.
454///
455/// Accepts in-memory buffers (`Vec<u8>`, `Bytes`, `&'static [u8]`, or `String`)
456/// as well as streamed content via [`UploadBody::reader`] or
457/// [`UploadBody::chunks`].
458pub struct UploadBody(Body);
459
460enum Body {
461 Bytes(Bytes),
462 Reader(Box<dyn AsyncRead + Unpin + Send + Sync + 'static>),
463}
464
465impl UploadBody {
466 /// Streams upload data directly from `reader` without buffering it in
467 /// memory.
468 pub fn reader(reader: impl AsyncRead + Unpin + Send + Sync + 'static) -> Self {
469 UploadBody(Body::Reader(Box::new(reader)))
470 }
471
472 /// Streams upload data from a stream of byte chunks (such as a forwarded
473 /// request body).
474 ///
475 /// Each chunk can be any type convertible to `Bytes` (`Bytes`, `Vec<u8>`,
476 /// `String`, or `&'static [u8]`). If the stream yields an error, the upload
477 /// fails and nothing is stored.
478 ///
479 /// ```ignore
480 /// let chunks = futures::stream::iter([Ok::<_, std::io::Error>(Bytes::from("hello"))]);
481 /// UPLOADS.upload("greeting.txt", UploadBody::chunks(chunks)).await?;
482 /// ```
483 pub fn chunks<S, B, E>(chunks: S) -> Self
484 where
485 S: Stream<Item = Result<B, E>> + Send + 'static,
486 B: Into<Bytes> + 'static,
487 E: Into<Box<dyn std::error::Error + Send + Sync>> + 'static,
488 {
489 Self::reader(StreamReader::new(ChunkReader(std::sync::Mutex::new(
490 Box::pin(chunks),
491 ))))
492 }
493
494 /// Converts the upload body into an [`AsyncRead`], useful when implementing
495 /// a fake [`Uploader`] in tests.
496 pub fn into_async_read(self) -> impl AsyncRead + Unpin + Send + Sync + 'static {
497 self.into_reader()
498 }
499
500 fn into_reader(self) -> Box<dyn AsyncRead + Unpin + Send + Sync + 'static> {
501 match self.0 {
502 Body::Bytes(bytes) => Box::new(std::io::Cursor::new(bytes)),
503 Body::Reader(reader) => reader,
504 }
505 }
506}
507
508impl From<Bytes> for UploadBody {
509 fn from(bytes: Bytes) -> Self {
510 UploadBody(Body::Bytes(bytes))
511 }
512}
513
514impl From<Vec<u8>> for UploadBody {
515 fn from(bytes: Vec<u8>) -> Self {
516 Bytes::from(bytes).into()
517 }
518}
519
520impl From<&'static [u8]> for UploadBody {
521 fn from(bytes: &'static [u8]) -> Self {
522 Bytes::from_static(bytes).into()
523 }
524}
525
526impl From<String> for UploadBody {
527 fn from(text: String) -> Self {
528 Bytes::from(text).into()
529 }
530}
531
532/// A pre-signed URL granting temporary permission to upload an object, returned
533/// by [`Bucket::signed_upload_url`].
534#[derive(Debug, Clone, PartialEq, Eq)]
535pub struct SignedUploadUrl {
536 pub url: String,
537}
538
539/// A pre-signed URL granting temporary permission to download an object,
540/// returned by [`Bucket::signed_download_url`].
541#[derive(Debug, Clone, PartialEq, Eq)]
542pub struct SignedDownloadUrl {
543 pub url: String,
544}
545
546/// A lifecycle rule for a bucket (see [`Bucket::lifecycle`]).
547///
548/// Each rule has an optional [`prefix`](Self::prefix) and at least one action.
549/// The storage provider applies rules asynchronously — typically within a day
550/// after an object becomes eligible, and never earlier.
551///
552/// Day counts are measured from when an object was written (or, for noncurrent
553/// actions, from when a version was replaced or deleted). Specify them as
554/// integer literals between 1 and 36500 so Encore can parse them statically.
555///
556/// ```no_run
557/// use encore::objects::{Bucket, LifecycleRule};
558///
559/// static LOGS: Bucket = Bucket::new("logs").lifecycle(&[LifecycleRule::new()
560/// .prefix("app/")
561/// .move_to_infrequent_after_days(30)
562/// .move_to_cold_after_days(90)
563/// .delete_after_days(365)]);
564/// ```
565#[derive(Debug, Clone, Copy)]
566// Read by Encore's parser from the declaration, not by the runtime.
567#[allow(dead_code)]
568pub struct LifecycleRule {
569 prefix: Option<&'static str>,
570 move_to_infrequent_after_days: Option<u32>,
571 move_to_cold_after_days: Option<u32>,
572 delete_after_days: Option<u32>,
573 delete_noncurrent_after_days: Option<u32>,
574 keep_noncurrent_versions: Option<u32>,
575}
576
577impl LifecycleRule {
578 /// Creates a rule matching all objects in the bucket. Add at least one
579 /// action before attaching it to a bucket.
580 pub const fn new() -> Self {
581 Self {
582 prefix: None,
583 move_to_infrequent_after_days: None,
584 move_to_cold_after_days: None,
585 delete_after_days: None,
586 delete_noncurrent_after_days: None,
587 keep_noncurrent_versions: None,
588 }
589 }
590
591 /// Applies the rule only to objects whose names start with `prefix`.
592 pub const fn prefix(mut self, prefix: &'static str) -> Self {
593 self.prefix = Some(prefix);
594 self
595 }
596
597 /// Transitions matching objects to [`StorageClass::Infrequent`] after
598 /// `days` days (must be at least 30).
599 pub const fn move_to_infrequent_after_days(mut self, days: u32) -> Self {
600 self.move_to_infrequent_after_days = Some(days);
601 self
602 }
603
604 /// Transitions matching objects to [`StorageClass::Cold`] after `days`
605 /// days.
606 ///
607 /// When combined with
608 /// [`move_to_infrequent_after_days`](Self::move_to_infrequent_after_days),
609 /// this must be at least 30 days after the infrequent transition.
610 pub const fn move_to_cold_after_days(mut self, days: u32) -> Self {
611 self.move_to_cold_after_days = Some(days);
612 self
613 }
614
615 /// Deletes matching objects `days` days after they are written (must be
616 /// later than any storage-class transition in the same rule).
617 ///
618 /// In a versioned bucket, deletion turns the object into a noncurrent
619 /// version, matching [`Bucket::remove`].
620 pub const fn delete_after_days(mut self, days: u32) -> Self {
621 self.delete_after_days = Some(days);
622 self
623 }
624
625 /// For versioned buckets: deletes noncurrent versions `days` days after
626 /// they are replaced or removed.
627 pub const fn delete_noncurrent_after_days(mut self, days: u32) -> Self {
628 self.delete_noncurrent_after_days = Some(days);
629 self
630 }
631
632 /// For versioned buckets: retains at least the `count` newest noncurrent
633 /// versions of each object, deleting older noncurrent versions.
634 pub const fn keep_noncurrent_versions(mut self, count: u32) -> Self {
635 self.keep_noncurrent_versions = Some(count);
636 self
637 }
638}
639
640impl Default for LifecycleRule {
641 fn default() -> Self {
642 Self::new()
643 }
644}
645
646/// Minimum retention period for objects written to a bucket (see
647/// [`Bucket::retention`]).
648#[derive(Debug, Clone, Copy, PartialEq, Eq)]
649pub struct Retention {
650 /// Read by Encore's parser from the declaration, not by the runtime.
651 #[allow(dead_code)]
652 days: u32,
653}
654
655impl Retention {
656 /// Retains each object for `days` days after it is written.
657 ///
658 /// `days` must be an integer literal between 1 and 36500.
659 pub const fn days(days: u32) -> Self {
660 Self { days }
661 }
662}
663
664/// An object-storage bucket.
665pub struct Bucket {
666 name: &'static str,
667 /// Read by Encore's parser from the declaration, not by the runtime.
668 #[allow(dead_code)]
669 versioned: bool,
670 #[allow(dead_code)]
671 public: bool,
672 #[allow(dead_code)]
673 storage_class: Option<StorageClass>,
674 #[allow(dead_code)]
675 lifecycle: &'static [LifecycleRule],
676 #[allow(dead_code)]
677 retention: Option<Retention>,
678 #[allow(dead_code)]
679 object_retention: bool,
680}
681
682impl Bucket {
683 /// Declares a new object storage bucket.
684 ///
685 /// This function is `const` so it can initialize a module-level `static`.
686 /// Chain configuration methods after `new`:
687 ///
688 /// ```no_run
689 /// use encore::objects::Bucket;
690 ///
691 /// static AVATARS: Bucket = Bucket::new("avatars").public().versioned();
692 /// ```
693 pub const fn new(name: &'static str) -> Self {
694 Self {
695 name,
696 versioned: false,
697 public: false,
698 storage_class: None,
699 lifecycle: &[],
700 retention: None,
701 object_retention: false,
702 }
703 }
704
705 /// Makes the bucket publicly readable at the URL returned by
706 /// [`Bucket::public_url`].
707 ///
708 /// This method takes `self` by value so it can only be called as part of
709 /// the `static` declaration.
710 pub const fn public(mut self) -> Self {
711 self.public = true;
712 self
713 }
714
715 /// Enables object versioning so earlier versions of an object are kept and
716 /// can be targeted with a request's `.version(...)` option.
717 ///
718 /// Must be called as part of the `static` declaration.
719 pub const fn versioned(mut self) -> Self {
720 self.versioned = true;
721 self
722 }
723
724 /// Sets the default storage class for objects uploaded to this bucket
725 /// (defaults to standard storage).
726 ///
727 /// [`StorageClass::Auto`] lets the provider tier objects automatically
728 /// based on access frequency; it can only be set at the bucket level and
729 /// cannot be combined with lifecycle storage-class transitions.
730 ///
731 /// Must be called as part of the `static` declaration.
732 pub const fn storage_class(mut self, class: StorageClass) -> Self {
733 self.storage_class = Some(class);
734 self
735 }
736
737 /// Configures lifecycle rules for transitioning objects to colder storage
738 /// classes or deleting them after a given age.
739 ///
740 /// Rules also apply to objects already in the bucket. A bucket may have at
741 /// most 100 rules. Must be called as part of the `static` declaration.
742 ///
743 /// ```no_run
744 /// use encore::objects::{Bucket, LifecycleRule};
745 ///
746 /// static UPLOADS: Bucket = Bucket::new("uploads").versioned().lifecycle(&[
747 /// LifecycleRule::new().prefix("tmp/").delete_after_days(1),
748 /// LifecycleRule::new().delete_noncurrent_after_days(30).keep_noncurrent_versions(5),
749 /// ]);
750 /// ```
751 pub const fn lifecycle(mut self, rules: &'static [LifecycleRule]) -> Self {
752 self.lifecycle = rules;
753 self
754 }
755
756 /// Sets a minimum retention period for every object written to the bucket.
757 ///
758 /// Until the retention period expires, deleting or overwriting an object
759 /// fails with [`Error::Retained`] (on AWS S3, the request creates a new
760 /// version or delete marker while the retained version remains protected
761 /// until expiry). Must be called as part of the `static` declaration.
762 ///
763 /// ```no_run
764 /// use encore::objects::{Bucket, Retention};
765 ///
766 /// static INVOICES: Bucket = Bucket::new("invoices").retention(Retention::days(2555));
767 /// ```
768 pub const fn retention(mut self, retention: Retention) -> Self {
769 self.retention = Some(retention);
770 self
771 }
772
773 /// Enables per-object retention timestamps, configured on upload via
774 /// [`UploadRequest::retain_until`] and extended via
775 /// [`Bucket::extend_retention`].
776 ///
777 /// Not supported on Cloudflare R2. Must be called as part of the `static`
778 /// declaration.
779 pub const fn object_retention(mut self) -> Self {
780 self.object_retention = true;
781 self
782 }
783
784 /// Attaches a key/value classification tag (such as `.tag("data", "pci")`)
785 /// for policy evaluation.
786 ///
787 /// Call `.tag` once per tag with unique keys. Both arguments must be string
788 /// literals so Encore can parse them statically. Keys must start with a
789 /// lowercase letter, contain only lowercase letters, digits, `_`, and `-`,
790 /// and must not start with `encore` (reserved for Encore's own tags).
791 /// Values use the same character set or may be empty. Each key and value
792 /// may be at most 63 characters, and a bucket may have at most 32 tags.
793 ///
794 /// Must be called as part of the `static` declaration.
795 ///
796 /// ```no_run
797 /// use encore::objects::Bucket;
798 ///
799 /// static RECEIPTS: Bucket = Bucket::new("receipts").tag("data", "pci");
800 /// ```
801 pub const fn tag(self, _key: &'static str, _value: &'static str) -> Self {
802 self
803 }
804
805 /// References an existing bucket by name. To declare a new bucket, use
806 /// [`Bucket::new`] instead.
807 ///
808 /// `name` must be a string literal so Encore can resolve it statically.
809 /// Because the bucket is configured where it is declared, do not chain
810 /// declaration options on `named`.
811 ///
812 /// ```no_run
813 /// static UPLOADS: encore::objects::Bucket = encore::objects::Bucket::named("uploads");
814 /// ```
815 pub const fn named(name: &'static str) -> Self {
816 Self::new(name)
817 }
818
819 /// Creates a [`BucketRef`] granting only the permissions `P` (a single type
820 /// from [`perms`] or a tuple of them).
821 ///
822 /// Unlike [`Bucket`], a [`BucketRef`] can be passed to helper functions and
823 /// libraries, and Encore grants the service the permissions named in `P`.
824 /// Because permissions must be explicit in source code, `P` cannot be
825 /// inferred by the compiler. This function is `const` so it can initialize
826 /// a module-level `static`.
827 ///
828 /// ```no_run
829 /// use encore::objects::{perms, Bucket, BucketRef};
830 ///
831 /// static UPLOADS: Bucket = Bucket::named("uploads");
832 /// static AVATARS: BucketRef<(perms::Uploader, perms::Lister)> =
833 /// UPLOADS.reference::<(perms::Uploader, perms::Lister)>();
834 /// ```
835 ///
836 /// ```compile_fail,E0284
837 /// # use encore::objects::{perms, Bucket, BucketRef};
838 /// # static UPLOADS: Bucket = Bucket::named("uploads");
839 /// // Not even from the type it is assigned to.
840 /// static AVATARS: BucketRef<perms::Uploader> = UPLOADS.reference();
841 /// ```
842 pub const fn reference<P: BucketPerms>(&'static self) -> BucketRef<P::Id> {
843 BucketRef {
844 bucket: self,
845 perms: PhantomData,
846 }
847 }
848
849 /// The bucket operations run on: the app's own, or under `encore test`
850 /// the current test's instance of it (see [`crate::testing`]).
851 fn resolve(&self) -> Result<objects::Bucket, Error> {
852 if let Some(test) = crate::testing::active().map_err(test_err)? {
853 return test.bucket(self.name).map_err(test_err);
854 }
855 core()
856 .objects()
857 .bucket(self.name.into())
858 .ok_or_else(|| Error::other(format!("bucket {:?} is not configured", self.name)))
859 }
860
861 fn object(&self, key: &str) -> Result<objects::Object, Error> {
862 Ok(self.resolve()?.object(key.to_string()))
863 }
864
865 /// Lists objects in the bucket, returning a [`ListRequest`] that resolves
866 /// to a [`ListIterator`].
867 ///
868 /// When [`delimiter`](ListRequest::delimiter) is set, object names are
869 /// grouped up to the first occurrence of the delimiter (like a directory
870 /// listing). Each group is returned as a single [`ListEntry`] with
871 /// [`ListEntry::is_prefix`] set and a name ending with the delimiter.
872 /// Groups and objects are returned in order, and
873 /// [`limit`](ListRequest::limit) counts both.
874 ///
875 /// ```no_run
876 /// # use encore::objects::Bucket;
877 /// # static UPLOADS: Bucket = Bucket::named("uploads");
878 /// # async fn f() -> Result<(), encore::objects::Error> {
879 /// let mut entries = UPLOADS.list().prefix("users/42/").delimiter("/").await?;
880 /// while let Some(entry) = entries.next().await {
881 /// let entry = entry?;
882 /// if entry.is_prefix {
883 /// println!("{} (folder)", entry.name); // users/42/photos/
884 /// } else {
885 /// println!("{}", entry.name);
886 /// }
887 /// }
888 /// # Ok(())
889 /// # }
890 /// ```
891 pub fn list(&self) -> ListRequest<'_> {
892 ListRequest::new(self)
893 }
894
895 /// Lists stored versions of objects in the bucket, ordered by name and then
896 /// newest first.
897 ///
898 /// A removed object has no version with [`ObjectVersion::latest`] set. For
899 /// an unversioned bucket, each object appears as a single version.
900 ///
901 /// ```no_run
902 /// # use encore::objects::Bucket;
903 /// # static UPLOADS: Bucket = Bucket::named("uploads");
904 /// # async fn f() -> Result<(), encore::objects::Error> {
905 /// let mut versions = UPLOADS.list_versions().prefix("invoices/").await?;
906 /// while let Some(v) = versions.next().await {
907 /// let v = v?;
908 /// println!("{} {:?} latest={}", v.name, v.version, v.latest);
909 /// }
910 /// # Ok(())
911 /// # }
912 /// ```
913 pub fn list_versions(&self) -> ListVersionsRequest<'_> {
914 ListVersionsRequest::new(self)
915 }
916
917 /// Checks whether an object with `key` exists.
918 pub fn exists(&self, key: &str) -> ExistsRequest<'_> {
919 ExistsRequest::new(self, key)
920 }
921
922 /// Fetches the attributes of the object `key` (size, content type, version,
923 /// ETag, custom metadata, and so on).
924 pub fn attrs(&self, key: &str) -> AttrsRequest<'_> {
925 AttrsRequest::new(self, key)
926 }
927
928 /// Uploads `data` to `key` and returns the stored [`ObjectAttrs`].
929 ///
930 /// Pass an in-memory buffer directly, or use [`UploadBody::reader`] /
931 /// [`UploadBody::chunks`] to stream large payloads.
932 ///
933 /// ```no_run
934 /// # use encore::objects::{Bucket, StorageClass, UploadBody};
935 /// # static UPLOADS: Bucket = Bucket::named("uploads");
936 /// # async fn f(data: Vec<u8>, file: tokio::fs::File) -> Result<(), encore::objects::Error> {
937 /// UPLOADS
938 /// .upload("a.pdf", data)
939 /// .content_type("application/pdf")
940 /// .cache_control("public, max-age=3600")
941 /// .metadata([("owner", "42")])
942 /// .storage_class(StorageClass::Cold)
943 /// .await?;
944 ///
945 /// // Streamed, and only if there is no such object yet.
946 /// UPLOADS
947 /// .upload("b.pdf", UploadBody::reader(file))
948 /// .not_exists()
949 /// .await?;
950 /// # Ok(())
951 /// # }
952 /// ```
953 pub fn upload(&self, key: &str, data: impl Into<UploadBody>) -> UploadRequest<'_> {
954 UploadRequest::new(self, key, data.into())
955 }
956
957 /// Uploads `data` to `key` only if the object still matches `revision`
958 /// (from [`ObjectAttrs::revision`] or [`Download::revision`]).
959 ///
960 /// If another write occurred first or the object no longer exists, the
961 /// upload fails with [`Error::PreconditionFailed`]. Supports all
962 /// [`upload`](Self::upload) options except `not_exists`.
963 ///
964 /// The revision check compares object contents rather than attributes, so
965 /// [`update_attrs`](Self::update_attrs) does not invalidate it. On AWS,
966 /// this operation also requires read permission, which Encore grants
967 /// automatically.
968 ///
969 /// ```no_run
970 /// # use encore::objects::Bucket;
971 /// # static UPLOADS: Bucket = Bucket::named("uploads");
972 /// # async fn f(next: Vec<u8>) -> Result<(), encore::objects::Error> {
973 /// let seen = UPLOADS.attrs("state.json").await?;
974 /// UPLOADS
975 /// .upload_if_match("state.json", next, seen.revision())
976 /// .content_type("application/json")
977 /// .await?;
978 /// # Ok(())
979 /// # }
980 /// ```
981 pub fn upload_if_match(
982 &self,
983 key: &str,
984 data: impl Into<UploadBody>,
985 revision: Revision,
986 ) -> UploadIfMatchRequest<'_> {
987 UploadIfMatchRequest::new(self, key, data.into(), revision)
988 }
989
990 /// Updates attributes on `key` (content type, cache control, content
991 /// disposition, or custom metadata) and returns the updated
992 /// [`ObjectAttrs`].
993 ///
994 /// Unspecified attributes remain unchanged. On S3, updating attributes
995 /// rewrites the object, which creates a new version in versioned buckets.
996 ///
997 /// ```no_run
998 /// # use encore::objects::Bucket;
999 /// # static UPLOADS: Bucket = Bucket::named("uploads");
1000 /// # async fn f() -> Result<(), encore::objects::Error> {
1001 /// let attrs = UPLOADS.attrs("a.pdf").await?;
1002 /// UPLOADS
1003 /// .update_attrs("a.pdf")
1004 /// .cache_control("no-store")
1005 /// .if_match(attrs.revision())
1006 /// .await?;
1007 /// # Ok(())
1008 /// # }
1009 /// ```
1010 pub fn update_attrs(&self, key: &str) -> UpdateAttrsRequest<'_> {
1011 UpdateAttrsRequest::new(self, key)
1012 }
1013
1014 /// Extends the retention timestamp of `key` to at least `until` in a bucket
1015 /// declared with [`Bucket::object_retention`], returning the updated
1016 /// [`ObjectAttrs`].
1017 ///
1018 /// Retention can only be extended; passing a timestamp earlier than the
1019 /// object's current retain-until time returns [`Error::InvalidArgument`].
1020 pub fn extend_retention(&self, key: &str, until: SystemTime) -> ExtendRetentionRequest<'_> {
1021 ExtendRetentionRequest::new(self, key, until)
1022 }
1023
1024 /// Downloads `key` (optionally a specific version or byte range).
1025 ///
1026 /// Awaiting the returned [`DownloadRequest`] resolves to a [`Download`] as
1027 /// soon as the provider responds with headers (or fails with
1028 /// [`Error::NotFound`] if the object does not exist). Read the body from
1029 /// the [`Download`] all at once or as a stream.
1030 ///
1031 /// ```no_run
1032 /// # use encore::objects::Bucket;
1033 /// # static UPLOADS: Bucket = Bucket::named("uploads");
1034 /// # async fn f() -> Result<(), encore::objects::Error> {
1035 /// let whole = UPLOADS.download("a.pdf").await?.bytes().await?;
1036 ///
1037 /// // The 256 bytes starting at offset 1024.
1038 /// let part = UPLOADS.download("big.bin").range(1024..1280).await?;
1039 /// let (size, bytes) = (part.size(), part.bytes().await?);
1040 ///
1041 /// // The last 64 bytes, however large the object is.
1042 /// let tail = UPLOADS.download("big.bin").last(64).await?.bytes().await?;
1043 /// # Ok(())
1044 /// # }
1045 /// ```
1046 pub fn download(&self, key: &str) -> DownloadRequest<'_> {
1047 DownloadRequest::new(self, key)
1048 }
1049
1050 /// Removes `key`, or a specific version of it.
1051 pub fn remove(&self, key: &str) -> RemoveRequest<'_> {
1052 RemoveRequest::new(self, key)
1053 }
1054
1055 /// Removes `key` only if the object still matches `revision` (from
1056 /// [`ObjectAttrs::revision`] or [`Download::revision`]).
1057 ///
1058 /// If another write occurred first or the object no longer exists, this
1059 /// fails with [`Error::PreconditionFailed`]. The check compares object
1060 /// contents rather than attributes. On AWS, this operation also requires
1061 /// read permission, which Encore grants automatically. Conditional removal
1062 /// is not supported on Cloudflare R2 and returns [`Error::InvalidArgument`].
1063 ///
1064 /// ```no_run
1065 /// # use encore::objects::Bucket;
1066 /// # static UPLOADS: Bucket = Bucket::named("uploads");
1067 /// # async fn f() -> Result<(), encore::objects::Error> {
1068 /// let attrs = UPLOADS.attrs("lock.json").await?;
1069 /// UPLOADS.remove_if_match("lock.json", attrs.revision()).await?;
1070 /// # Ok(())
1071 /// # }
1072 /// ```
1073 pub async fn remove_if_match(&self, key: &str, revision: Revision) -> Result<(), Error> {
1074 let options = objects::DeleteOptions {
1075 version: None,
1076 if_match: Some(revision),
1077 };
1078 self.object(key)?.delete(options).await.map_err(obj_err)
1079 }
1080
1081 /// Generates a pre-signed URL for uploading `key`, valid for one hour by
1082 /// default (override with [`SignedUploadUrlRequest::ttl`]).
1083 pub fn signed_upload_url(&self, key: &str) -> SignedUploadUrlRequest<'_> {
1084 SignedUploadUrlRequest::new(self, key)
1085 }
1086
1087 /// Generates a pre-signed URL for downloading `key`, valid for one hour by
1088 /// default (override with [`SignedDownloadUrlRequest::ttl`]).
1089 pub fn signed_download_url(&self, key: &str) -> SignedDownloadUrlRequest<'_> {
1090 SignedDownloadUrlRequest::new(self, key)
1091 }
1092
1093 /// Returns the public URL for `key`.
1094 ///
1095 /// Only available for buckets declared with [`Bucket::public`]; returns
1096 /// [`Error::InvalidArgument`] for private buckets.
1097 pub fn public_url(&self, key: &str) -> Result<String, Error> {
1098 self.object(key)?.public_url().map_err(public_url_err)
1099 }
1100}
1101
1102/// Why an object has no public URL, as this module's error.
1103fn public_url_err(err: objects::PublicUrlError) -> Error {
1104 match err {
1105 objects::PublicUrlError::PrivateBucket | objects::PublicUrlError::InvalidObjectName => {
1106 Error::InvalidArgument(err.to_string())
1107 }
1108 objects::PublicUrlError::NoopBucket => Error::Other(Box::new(err)),
1109 }
1110}
1111
1112/// A request's two ways to run when awaited: on a [`Bucket`], and on what
1113/// implements the trait of its permission — a [`BucketRef`], or a fake —
1114/// through the trait's `run_` method.
1115macro_rules! into_future {
1116 ($request:ident => $output:ty, $trait:ident::$run:ident) => {
1117 impl<'a> IntoFuture for $request<'a, Bucket> {
1118 type Output = Result<$output, Error>;
1119 type IntoFuture = BoxFuture<'a, Self::Output>;
1120
1121 fn into_future(self) -> Self::IntoFuture {
1122 let bucket = self.on;
1123 self.send(bucket)
1124 }
1125 }
1126
1127 impl<'a, T: $trait + ?Sized> IntoFuture for $request<'a, T> {
1128 type Output = Result<$output, Error>;
1129 type IntoFuture = BoxFuture<'a, Self::Output>;
1130
1131 fn into_future(self) -> Self::IntoFuture {
1132 let on = self.on;
1133 Box::pin(on.$run(self))
1134 }
1135 }
1136 };
1137}
1138
1139/// The setter of a request's `version`: the operation is on that version of
1140/// the object rather than the current one.
1141macro_rules! version_setter {
1142 () => {
1143 /// Targets a specific `version` of the object in a versioned bucket
1144 /// instead of the current version.
1145 pub fn version(mut self, version: impl Into<String>) -> Self {
1146 self.version = Some(version.into());
1147 self
1148 }
1149 };
1150}
1151
1152/// The setters of the attributes an upload writes, which an upload if it
1153/// matches shares.
1154macro_rules! upload_setters {
1155 () => {
1156 /// Sets the object's `Content-Type` header (for example,
1157 /// `application/pdf`).
1158 pub fn content_type(mut self, content_type: impl Into<String>) -> Self {
1159 self.content_type = Some(content_type.into());
1160 self
1161 }
1162
1163 /// Sets the `Cache-Control` header the object is served with (for
1164 /// example, `public, max-age=3600`).
1165 pub fn cache_control(mut self, cache_control: impl Into<String>) -> Self {
1166 self.cache_control = Some(cache_control.into());
1167 self
1168 }
1169
1170 /// Sets the `Content-Disposition` header the object is served with (for
1171 /// example, `attachment; filename="a.pdf"`).
1172 pub fn content_disposition(mut self, content_disposition: impl Into<String>) -> Self {
1173 self.content_disposition = Some(content_disposition.into());
1174 self
1175 }
1176
1177 /// Adds custom metadata key/value pairs (such as `[("owner", "42")]`),
1178 /// replacing any existing entries with the same keys.
1179 ///
1180 /// Keys must contain only lowercase letters, digits, `-`, and `_`, and
1181 /// cannot start with `-` or `_`. Values must be printable ASCII.
1182 pub fn metadata<K, V>(mut self, metadata: impl IntoIterator<Item = (K, V)>) -> Self
1183 where
1184 K: Into<String>,
1185 V: Into<String>,
1186 {
1187 extend(&mut self.metadata, metadata);
1188 self
1189 }
1190
1191 /// Overrides the bucket's default storage class for this object.
1192 ///
1193 /// [`StorageClass::Auto`] is only valid at the bucket level and is
1194 /// rejected here.
1195 pub fn storage_class(mut self, class: StorageClass) -> Self {
1196 self.storage_class = Some(class);
1197 self
1198 }
1199
1200 /// Retains the object until at least `until` in a bucket declared with
1201 /// [`Bucket::object_retention`].
1202 pub fn retain_until(mut self, until: SystemTime) -> Self {
1203 self.retain_until = Some(until);
1204 self
1205 }
1206 };
1207}
1208
1209/// Adds `pairs` to `into`, replacing those of the same names.
1210fn extend<K: Into<String>, V: Into<String>>(
1211 into: &mut BTreeMap<String, String>,
1212 pairs: impl IntoIterator<Item = (K, V)>,
1213) {
1214 into.extend(pairs.into_iter().map(|(k, v)| (k.into(), v.into())));
1215}
1216
1217/// A Rust range of bytes as the core's: `0..1024`, `1024..`, `..=99`. An
1218/// empty one is empty there too, which the core refuses.
1219fn byte_range(range: impl RangeBounds<u64>) -> ByteRange {
1220 let offset = match range.start_bound() {
1221 Bound::Included(&start) => start,
1222 Bound::Excluded(&start) => start.saturating_add(1),
1223 Bound::Unbounded => 0,
1224 };
1225 let length = match range.end_bound() {
1226 Bound::Included(&end) => Some(end.saturating_sub(offset).saturating_add(1)),
1227 Bound::Excluded(&end) => Some(end.saturating_sub(offset)),
1228 Bound::Unbounded => None,
1229 };
1230 // `5..=3` is as empty as `5..3`.
1231 let length = match range.end_bound() {
1232 Bound::Included(&end) if end < offset => Some(0),
1233 _ => length,
1234 };
1235 ByteRange::from(offset, length)
1236}
1237
1238/// How long a signed URL is valid for when its request sets no `ttl`.
1239const SIGNED_URL_TTL: Duration = Duration::from_secs(60 * 60);
1240
1241/// Request builder returned by [`Bucket::upload`].
1242///
1243/// Configure upload options with builder methods and `.await` to execute and
1244/// receive the stored [`ObjectAttrs`]. Fields are public for inspecting
1245/// requests in fake [`Uploader`] implementations.
1246pub struct UploadRequest<'a, T: ?Sized = Bucket> {
1247 on: &'a T,
1248 pub key: String,
1249 pub data: UploadBody,
1250 pub content_type: Option<String>,
1251 pub cache_control: Option<String>,
1252 pub content_disposition: Option<String>,
1253 pub metadata: BTreeMap<String, String>,
1254 pub storage_class: Option<StorageClass>,
1255 pub retain_until: Option<SystemTime>,
1256 pub not_exists: bool,
1257}
1258
1259impl<'a, T: ?Sized> UploadRequest<'a, T> {
1260 fn new(on: &'a T, key: &str, data: UploadBody) -> Self {
1261 Self {
1262 on,
1263 key: key.to_string(),
1264 data,
1265 content_type: None,
1266 cache_control: None,
1267 content_disposition: None,
1268 metadata: BTreeMap::new(),
1269 storage_class: None,
1270 retain_until: None,
1271 not_exists: false,
1272 }
1273 }
1274
1275 upload_setters!();
1276
1277 /// Fails with [`Error::PreconditionFailed`] if an object with this key
1278 /// already exists.
1279 pub fn not_exists(mut self) -> Self {
1280 self.not_exists = true;
1281 self
1282 }
1283
1284 fn send<'b>(self, bucket: &'b Bucket) -> BoxFuture<'b, Result<ObjectAttrs, Error>> {
1285 let preconditions = self.not_exists.then_some(objects::UploadPreconditions {
1286 not_exists: Some(true),
1287 if_match: None,
1288 });
1289 let options = objects::UploadOptions {
1290 content_type: self.content_type,
1291 cache_control: self.cache_control,
1292 content_disposition: self.content_disposition,
1293 metadata: self.metadata,
1294 storage_class: self.storage_class,
1295 retain_until: self.retain_until,
1296 preconditions,
1297 };
1298 upload(bucket, self.key, self.data, options)
1299 }
1300}
1301
1302into_future!(UploadRequest => ObjectAttrs, Uploader::run_upload);
1303
1304/// Request builder returned by [`Bucket::upload_if_match`].
1305///
1306/// Supports all upload options except `not_exists`:
1307///
1308/// ```compile_fail,E0599
1309/// # use encore::objects::{Bucket, Revision};
1310/// # static UPLOADS: Bucket = Bucket::named("uploads");
1311/// async fn upload(seen: Revision) {
1312/// let _ = UPLOADS.upload_if_match("a", vec![], seen).not_exists().await;
1313/// }
1314/// ```
1315///
1316/// Fields are public for inspecting requests in fake [`IfMatchUploader`]
1317/// implementations.
1318pub struct UploadIfMatchRequest<'a, T: ?Sized = Bucket> {
1319 on: &'a T,
1320 pub key: String,
1321 pub data: UploadBody,
1322 pub revision: Revision,
1323 pub content_type: Option<String>,
1324 pub cache_control: Option<String>,
1325 pub content_disposition: Option<String>,
1326 pub metadata: BTreeMap<String, String>,
1327 pub storage_class: Option<StorageClass>,
1328 pub retain_until: Option<SystemTime>,
1329}
1330
1331impl<'a, T: ?Sized> UploadIfMatchRequest<'a, T> {
1332 fn new(on: &'a T, key: &str, data: UploadBody, revision: Revision) -> Self {
1333 Self {
1334 on,
1335 key: key.to_string(),
1336 data,
1337 revision,
1338 content_type: None,
1339 cache_control: None,
1340 content_disposition: None,
1341 metadata: BTreeMap::new(),
1342 storage_class: None,
1343 retain_until: None,
1344 }
1345 }
1346
1347 upload_setters!();
1348
1349 fn send<'b>(self, bucket: &'b Bucket) -> BoxFuture<'b, Result<ObjectAttrs, Error>> {
1350 let options = objects::UploadOptions {
1351 content_type: self.content_type,
1352 cache_control: self.cache_control,
1353 content_disposition: self.content_disposition,
1354 metadata: self.metadata,
1355 storage_class: self.storage_class,
1356 retain_until: self.retain_until,
1357 preconditions: Some(objects::UploadPreconditions {
1358 not_exists: None,
1359 if_match: Some(self.revision),
1360 }),
1361 };
1362 upload(bucket, self.key, self.data, options)
1363 }
1364}
1365
1366into_future!(UploadIfMatchRequest => ObjectAttrs, IfMatchUploader::run_upload_if_match);
1367
1368/// Uploads `data` to the object `key` of `bucket`.
1369fn upload(
1370 bucket: &Bucket,
1371 key: String,
1372 data: UploadBody,
1373 options: objects::UploadOptions,
1374) -> BoxFuture<'_, Result<ObjectAttrs, Error>> {
1375 Box::pin(async move {
1376 bucket
1377 .object(&key)?
1378 .upload(data.into_reader(), options)
1379 .await
1380 .map_err(obj_err)
1381 })
1382}
1383
1384/// Request builder returned by [`Bucket::update_attrs`].
1385///
1386/// Unspecified attributes remain unchanged; passing an empty string clears an
1387/// attribute (clearing content type resets it to `application/octet-stream`,
1388/// since S3 requires every object to have one). Awaiting returns the updated
1389/// [`ObjectAttrs`]. Fields are public for inspecting requests in fake
1390/// [`AttrsUpdater`] implementations.
1391pub struct UpdateAttrsRequest<'a, T: ?Sized = Bucket> {
1392 on: &'a T,
1393 pub key: String,
1394 pub content_type: Option<String>,
1395 pub cache_control: Option<String>,
1396 pub content_disposition: Option<String>,
1397 pub metadata: Option<BTreeMap<String, String>>,
1398 pub version: Option<String>,
1399 pub if_match: Option<Revision>,
1400}
1401
1402impl<'a, T: ?Sized> UpdateAttrsRequest<'a, T> {
1403 fn new(on: &'a T, key: &str) -> Self {
1404 Self {
1405 on,
1406 key: key.to_string(),
1407 content_type: None,
1408 cache_control: None,
1409 content_disposition: None,
1410 metadata: None,
1411 version: None,
1412 if_match: None,
1413 }
1414 }
1415
1416 /// The object's content type, such as `application/pdf`.
1417 pub fn content_type(mut self, content_type: impl Into<String>) -> Self {
1418 self.content_type = Some(content_type.into());
1419 self
1420 }
1421
1422 /// The `Cache-Control` the object is served with.
1423 pub fn cache_control(mut self, cache_control: impl Into<String>) -> Self {
1424 self.cache_control = Some(cache_control.into());
1425 self
1426 }
1427
1428 /// The `Content-Disposition` the object is served with.
1429 pub fn content_disposition(mut self, content_disposition: impl Into<String>) -> Self {
1430 self.content_disposition = Some(content_disposition.into());
1431 self
1432 }
1433
1434 /// Replaces the object's custom metadata with `metadata`. Pass an empty
1435 /// iterator (`[]`) to clear all metadata.
1436 pub fn metadata<K, V>(mut self, metadata: impl IntoIterator<Item = (K, V)>) -> Self
1437 where
1438 K: Into<String>,
1439 V: Into<String>,
1440 {
1441 extend(self.metadata.get_or_insert_default(), metadata);
1442 self
1443 }
1444
1445 version_setter!();
1446
1447 /// Updates attributes only if the object still matches `revision`, failing
1448 /// with [`Error::PreconditionFailed`] otherwise.
1449 pub fn if_match(mut self, revision: Revision) -> Self {
1450 self.if_match = Some(revision);
1451 self
1452 }
1453
1454 fn send<'b>(self, bucket: &'b Bucket) -> BoxFuture<'b, Result<ObjectAttrs, Error>> {
1455 let attrs = objects::UpdateAttrs {
1456 content_type: self.content_type,
1457 cache_control: self.cache_control,
1458 content_disposition: self.content_disposition,
1459 metadata: self.metadata,
1460 };
1461 let options = objects::UpdateAttrsOptions {
1462 version: self.version,
1463 if_match: self.if_match,
1464 };
1465 let key = self.key;
1466 Box::pin(async move {
1467 bucket
1468 .object(&key)?
1469 .update_attrs(attrs, options)
1470 .await
1471 .map_err(obj_err)
1472 })
1473 }
1474}
1475
1476into_future!(UpdateAttrsRequest => ObjectAttrs, AttrsUpdater::run_update_attrs);
1477
1478/// Request builder returned by [`Bucket::extend_retention`]. Await it to
1479/// extend retention and receive the updated [`ObjectAttrs`].
1480pub struct ExtendRetentionRequest<'a, T: ?Sized = Bucket> {
1481 on: &'a T,
1482 pub key: String,
1483 pub until: SystemTime,
1484 pub version: Option<String>,
1485}
1486
1487impl<'a, T: ?Sized> ExtendRetentionRequest<'a, T> {
1488 fn new(on: &'a T, key: &str, until: SystemTime) -> Self {
1489 Self {
1490 on,
1491 key: key.to_string(),
1492 until,
1493 version: None,
1494 }
1495 }
1496
1497 version_setter!();
1498
1499 fn send<'b>(self, bucket: &'b Bucket) -> BoxFuture<'b, Result<ObjectAttrs, Error>> {
1500 let (key, until) = (self.key, self.until);
1501 let options = objects::ExtendRetentionOptions {
1502 version: self.version,
1503 };
1504 Box::pin(async move {
1505 bucket
1506 .object(&key)?
1507 .extend_retention(until, options)
1508 .await
1509 .map_err(obj_err)
1510 })
1511 }
1512}
1513
1514into_future!(ExtendRetentionRequest => ObjectAttrs, AttrsUpdater::run_extend_retention);
1515
1516/// Request builder returned by [`Bucket::download`]. Await it to start the
1517/// [`Download`].
1518pub struct DownloadRequest<'a, T: ?Sized = Bucket> {
1519 on: &'a T,
1520 pub key: String,
1521 pub version: Option<String>,
1522 pub range: Option<ByteRange>,
1523}
1524
1525impl<'a, T: ?Sized> DownloadRequest<'a, T> {
1526 fn new(on: &'a T, key: &str) -> Self {
1527 Self {
1528 on,
1529 key: key.to_string(),
1530 version: None,
1531 range: None,
1532 }
1533 }
1534
1535 version_setter!();
1536
1537 /// Downloads only the specified byte range (such as `1024..1280`, `1024..`,
1538 /// or `..=99`).
1539 ///
1540 /// Returns [`Error::InvalidArgument`] if the range is empty or starts past
1541 /// the end of the object.
1542 pub fn range(mut self, range: impl RangeBounds<u64>) -> Self {
1543 self.range = Some(byte_range(range));
1544 self
1545 }
1546
1547 /// Downloads only the last `length` bytes of the object (or the whole
1548 /// object if it is shorter).
1549 ///
1550 /// Passing `0` returns [`Error::InvalidArgument`]. Use [`Download::size`]
1551 /// to determine the total size of the object.
1552 pub fn last(mut self, length: u64) -> Self {
1553 self.range = Some(ByteRange::last(length));
1554 self
1555 }
1556
1557 fn send<'b>(self, bucket: &'b Bucket) -> BoxFuture<'b, Result<Download, Error>> {
1558 let options = objects::DownloadOptions {
1559 version: self.version,
1560 range: self.range,
1561 };
1562 let key = self.key;
1563 Box::pin(async move {
1564 bucket
1565 .object(&key)?
1566 .download(options)
1567 .await
1568 .map(|inner| Download { inner })
1569 .map_err(obj_err)
1570 })
1571 }
1572}
1573
1574into_future!(DownloadRequest => Download, Downloader::run_download);
1575
1576/// Request builder returned by [`Bucket::attrs`]. Await it to fetch
1577/// [`ObjectAttrs`].
1578pub struct AttrsRequest<'a, T: ?Sized = Bucket> {
1579 on: &'a T,
1580 pub key: String,
1581 pub version: Option<String>,
1582}
1583
1584impl<'a, T: ?Sized> AttrsRequest<'a, T> {
1585 fn new(on: &'a T, key: &str) -> Self {
1586 Self {
1587 on,
1588 key: key.to_string(),
1589 version: None,
1590 }
1591 }
1592
1593 version_setter!();
1594
1595 fn send<'b>(self, bucket: &'b Bucket) -> BoxFuture<'b, Result<ObjectAttrs, Error>> {
1596 let key = self.key;
1597 let options = objects::AttrsOptions {
1598 version: self.version,
1599 };
1600 Box::pin(async move { bucket.object(&key)?.attrs(options).await.map_err(obj_err) })
1601 }
1602}
1603
1604into_future!(AttrsRequest => ObjectAttrs, Attrser::run_attrs);
1605
1606/// Request builder returned by [`Bucket::exists`]. Await it to check whether
1607/// the object exists.
1608pub struct ExistsRequest<'a, T: ?Sized = Bucket> {
1609 on: &'a T,
1610 pub key: String,
1611 pub version: Option<String>,
1612}
1613
1614impl<'a, T: ?Sized> ExistsRequest<'a, T> {
1615 fn new(on: &'a T, key: &str) -> Self {
1616 Self {
1617 on,
1618 key: key.to_string(),
1619 version: None,
1620 }
1621 }
1622
1623 version_setter!();
1624
1625 fn send<'b>(self, bucket: &'b Bucket) -> BoxFuture<'b, Result<bool, Error>> {
1626 let key = self.key;
1627 let options = objects::ExistsOptions {
1628 version: self.version,
1629 };
1630 Box::pin(async move { bucket.object(&key)?.exists(options).await.map_err(obj_err) })
1631 }
1632}
1633
1634into_future!(ExistsRequest => bool, Attrser::run_exists);
1635
1636/// Request builder returned by [`Bucket::remove`]. Await it to delete the
1637/// object.
1638pub struct RemoveRequest<'a, T: ?Sized = Bucket> {
1639 on: &'a T,
1640 pub key: String,
1641 pub version: Option<String>,
1642}
1643
1644impl<'a, T: ?Sized> RemoveRequest<'a, T> {
1645 fn new(on: &'a T, key: &str) -> Self {
1646 Self {
1647 on,
1648 key: key.to_string(),
1649 version: None,
1650 }
1651 }
1652
1653 version_setter!();
1654
1655 fn send<'b>(self, bucket: &'b Bucket) -> BoxFuture<'b, Result<(), Error>> {
1656 let key = self.key;
1657 let options = objects::DeleteOptions {
1658 version: self.version,
1659 if_match: None,
1660 };
1661 Box::pin(async move { bucket.object(&key)?.delete(options).await.map_err(obj_err) })
1662 }
1663}
1664
1665into_future!(RemoveRequest => (), Remover::run_remove);
1666
1667/// Request builder returned by [`Bucket::list`]. Await it to obtain a
1668/// [`ListIterator`].
1669pub struct ListRequest<'a, T: ?Sized = Bucket> {
1670 on: &'a T,
1671 pub prefix: Option<String>,
1672 pub limit: Option<u64>,
1673 pub delimiter: Option<String>,
1674}
1675
1676impl<'a, T: ?Sized> ListRequest<'a, T> {
1677 fn new(on: &'a T) -> Self {
1678 Self {
1679 on,
1680 prefix: None,
1681 limit: None,
1682 delimiter: None,
1683 }
1684 }
1685
1686 /// Lists only objects whose names start with `prefix`.
1687 pub fn prefix(mut self, prefix: impl Into<String>) -> Self {
1688 self.prefix = Some(prefix.into());
1689 self
1690 }
1691
1692 /// Caps the listing at `limit` entries (including prefix groups).
1693 pub fn limit(mut self, limit: u64) -> Self {
1694 self.limit = Some(limit);
1695 self
1696 }
1697
1698 /// Groups object names after the prefix up to the first occurrence of
1699 /// `delimiter`, like a directory listing. See [`Bucket::list`].
1700 pub fn delimiter(mut self, delimiter: impl Into<String>) -> Self {
1701 self.delimiter = Some(delimiter.into());
1702 self
1703 }
1704
1705 fn send<'b>(self, bucket: &'b Bucket) -> BoxFuture<'b, Result<ListIterator, Error>> {
1706 let options = objects::ListOptions {
1707 prefix: self.prefix,
1708 limit: self.limit,
1709 delimiter: self.delimiter,
1710 };
1711 Box::pin(async move {
1712 bucket
1713 .resolve()?
1714 .list(options)
1715 .await
1716 .map(|inner| ListIterator { inner })
1717 .map_err(obj_err)
1718 })
1719 }
1720}
1721
1722into_future!(ListRequest => ListIterator, Lister::run_list);
1723
1724/// Request builder returned by [`Bucket::list_versions`]. Await it to obtain
1725/// a [`VersionIterator`].
1726pub struct ListVersionsRequest<'a, T: ?Sized = Bucket> {
1727 on: &'a T,
1728 pub prefix: Option<String>,
1729 pub limit: Option<u64>,
1730}
1731
1732impl<'a, T: ?Sized> ListVersionsRequest<'a, T> {
1733 fn new(on: &'a T) -> Self {
1734 Self {
1735 on,
1736 prefix: None,
1737 limit: None,
1738 }
1739 }
1740
1741 /// Only the versions of the objects whose names start with `prefix`.
1742 pub fn prefix(mut self, prefix: impl Into<String>) -> Self {
1743 self.prefix = Some(prefix.into());
1744 self
1745 }
1746
1747 /// At most `limit` versions.
1748 pub fn limit(mut self, limit: u64) -> Self {
1749 self.limit = Some(limit);
1750 self
1751 }
1752
1753 fn send<'b>(self, bucket: &'b Bucket) -> BoxFuture<'b, Result<VersionIterator, Error>> {
1754 let options = objects::ListOptions {
1755 prefix: self.prefix,
1756 limit: self.limit,
1757 delimiter: None,
1758 };
1759 Box::pin(async move {
1760 bucket
1761 .resolve()?
1762 .list_versions(options)
1763 .await
1764 .map(|inner| VersionIterator { inner })
1765 .map_err(obj_err)
1766 })
1767 }
1768}
1769
1770into_future!(ListVersionsRequest => VersionIterator, Lister::run_list_versions);
1771
1772/// Request builder returned by [`Bucket::signed_upload_url`]. Await it to
1773/// generate the [`SignedUploadUrl`].
1774pub struct SignedUploadUrlRequest<'a, T: ?Sized = Bucket> {
1775 on: &'a T,
1776 pub key: String,
1777 pub ttl: Option<Duration>,
1778}
1779
1780impl<'a, T: ?Sized> SignedUploadUrlRequest<'a, T> {
1781 fn new(on: &'a T, key: &str) -> Self {
1782 Self {
1783 on,
1784 key: key.to_string(),
1785 ttl: None,
1786 }
1787 }
1788
1789 /// Sets how long the signed URL remains valid (defaults to 1 hour; maximum
1790 /// 7 days).
1791 pub fn ttl(mut self, ttl: Duration) -> Self {
1792 self.ttl = Some(ttl);
1793 self
1794 }
1795
1796 fn send<'b>(self, bucket: &'b Bucket) -> BoxFuture<'b, Result<SignedUploadUrl, Error>> {
1797 let key = self.key;
1798 let options = objects::UploadUrlOptions {
1799 ttl: self.ttl.unwrap_or(SIGNED_URL_TTL),
1800 };
1801 Box::pin(async move {
1802 bucket
1803 .object(&key)?
1804 .signed_upload_url(options)
1805 .await
1806 .map(|url| SignedUploadUrl { url })
1807 .map_err(obj_err)
1808 })
1809 }
1810}
1811
1812into_future!(SignedUploadUrlRequest => SignedUploadUrl, SignedUploader::run_signed_upload_url);
1813
1814/// Request builder returned by [`Bucket::signed_download_url`]. Await it to
1815/// generate the [`SignedDownloadUrl`].
1816pub struct SignedDownloadUrlRequest<'a, T: ?Sized = Bucket> {
1817 on: &'a T,
1818 pub key: String,
1819 pub ttl: Option<Duration>,
1820}
1821
1822impl<'a, T: ?Sized> SignedDownloadUrlRequest<'a, T> {
1823 fn new(on: &'a T, key: &str) -> Self {
1824 Self {
1825 on,
1826 key: key.to_string(),
1827 ttl: None,
1828 }
1829 }
1830
1831 /// Sets how long the signed URL remains valid (defaults to 1 hour; maximum
1832 /// 7 days).
1833 pub fn ttl(mut self, ttl: Duration) -> Self {
1834 self.ttl = Some(ttl);
1835 self
1836 }
1837
1838 fn send<'b>(self, bucket: &'b Bucket) -> BoxFuture<'b, Result<SignedDownloadUrl, Error>> {
1839 let key = self.key;
1840 let options = objects::DownloadUrlOptions {
1841 ttl: self.ttl.unwrap_or(SIGNED_URL_TTL),
1842 };
1843 Box::pin(async move {
1844 bucket
1845 .object(&key)?
1846 .signed_download_url(options)
1847 .await
1848 .map(|url| SignedDownloadUrl { url })
1849 .map_err(obj_err)
1850 })
1851 }
1852}
1853
1854into_future!(
1855 SignedDownloadUrlRequest => SignedDownloadUrl,
1856 SignedDownloader::run_signed_download_url
1857);
1858
1859/// Permission marker types for [`BucketRef`].
1860///
1861/// Each marker type has a matching trait in [`objects`](super) exposing the
1862/// operations it grants.
1863pub mod perms {
1864 use super::{sealed::Sealed, BucketPerms};
1865 use crate::perm::{No, Yes};
1866
1867 macro_rules! perm {
1868 ($(#[$doc:meta])* $name:ident: $upload:ident, $signed_upload:ident, $download:ident,
1869 $signed_download:ident, $attrs:ident, $list:ident, $remove:ident, $public_url:ident,
1870 $update_attrs:ident, $if_match_upload:ident, $if_match_remove:ident) => {
1871 $(#[$doc])*
1872 pub enum $name {}
1873 impl Sealed for $name {}
1874 impl BucketPerms for $name {
1875 type Id = Self;
1876 type Upload = $upload;
1877 type SignedUpload = $signed_upload;
1878 type Download = $download;
1879 type SignedDownload = $signed_download;
1880 type Attrs = $attrs;
1881 type List = $list;
1882 type Remove = $remove;
1883 type PublicUrl = $public_url;
1884 type UpdateAttrs = $update_attrs;
1885 type IfMatchUpload = $if_match_upload;
1886 type IfMatchRemove = $if_match_remove;
1887 }
1888 };
1889 }
1890
1891 // The flags each sets, in `BucketPerms`' order: Upload, SignedUpload,
1892 // Download, SignedDownload, Attrs, List, Remove, PublicUrl, UpdateAttrs,
1893 // IfMatchUpload, IfMatchRemove.
1894 perm!(
1895 /// Upload objects: [`Uploader`](super::Uploader).
1896 Uploader: Yes, No, No, No, No, No, No, No, No, No, No
1897 );
1898 perm!(
1899 /// Make signed upload URLs: [`SignedUploader`](super::SignedUploader).
1900 SignedUploader: No, Yes, No, No, No, No, No, No, No, No, No
1901 );
1902 perm!(
1903 /// Download objects: [`Downloader`](super::Downloader).
1904 Downloader: No, No, Yes, No, No, No, No, No, No, No, No
1905 );
1906 perm!(
1907 /// Make signed download URLs:
1908 /// [`SignedDownloader`](super::SignedDownloader).
1909 SignedDownloader: No, No, No, Yes, No, No, No, No, No, No, No
1910 );
1911 perm!(
1912 /// Read objects' attributes, and whether they exist:
1913 /// [`Attrser`](super::Attrser).
1914 Attrser: No, No, No, No, Yes, No, No, No, No, No, No
1915 );
1916 perm!(
1917 /// List objects and their versions: [`Lister`](super::Lister).
1918 Lister: No, No, No, No, No, Yes, No, No, No, No, No
1919 );
1920 perm!(
1921 /// Remove objects: [`Remover`](super::Remover).
1922 Remover: No, No, No, No, No, No, Yes, No, No, No, No
1923 );
1924 perm!(
1925 /// Resolve objects' public URLs: [`PublicUrler`](super::PublicUrler).
1926 PublicUrler: No, No, No, No, No, No, No, Yes, No, No, No
1927 );
1928 perm!(
1929 /// Change objects' attributes and extend their retention:
1930 /// [`AttrsUpdater`](super::AttrsUpdater).
1931 AttrsUpdater: No, No, No, No, No, No, No, No, Yes, No, No
1932 );
1933 perm!(
1934 /// Upload objects only over the revision named:
1935 /// [`IfMatchUploader`](super::IfMatchUploader). On AWS it reads too,
1936 /// which Encore grants for it.
1937 IfMatchUploader: No, No, No, No, No, No, No, No, No, Yes, No
1938 );
1939 perm!(
1940 /// Remove objects only if they are the revision named:
1941 /// [`IfMatchRemover`](super::IfMatchRemover). On AWS it reads too,
1942 /// which Encore grants for it.
1943 IfMatchRemover: No, No, No, No, No, No, No, No, No, No, Yes
1944 );
1945 perm!(
1946 /// Every permission but [`PublicUrler`]: [`ReadWriter`](super::ReadWriter).
1947 ReadWriter: Yes, Yes, Yes, Yes, Yes, Yes, Yes, No, Yes, Yes, Yes
1948 );
1949}
1950
1951mod sealed {
1952 pub trait Sealed {}
1953}
1954
1955/// A set of bucket permissions: either a single type from [`perms`] or a tuple
1956/// of them granting the union of their permissions.
1957///
1958/// This trait is sealed.
1959pub trait BucketPerms: sealed::Sealed {
1960 /// Always `Self`. [`Bucket::reference`] returns `BucketRef<P::Id>`, which
1961 /// the compiler cannot work back from to `P`, so `P` is never inferred.
1962 #[doc(hidden)]
1963 type Id: BucketPerms;
1964 #[doc(hidden)]
1965 type Upload: Flag;
1966 #[doc(hidden)]
1967 type SignedUpload: Flag;
1968 #[doc(hidden)]
1969 type Download: Flag;
1970 #[doc(hidden)]
1971 type SignedDownload: Flag;
1972 #[doc(hidden)]
1973 type Attrs: Flag;
1974 #[doc(hidden)]
1975 type List: Flag;
1976 #[doc(hidden)]
1977 type Remove: Flag;
1978 #[doc(hidden)]
1979 type PublicUrl: Flag;
1980 #[doc(hidden)]
1981 type UpdateAttrs: Flag;
1982 #[doc(hidden)]
1983 type IfMatchUpload: Flag;
1984 #[doc(hidden)]
1985 type IfMatchRemove: Flag;
1986}
1987
1988impl sealed::Sealed for () {}
1989
1990/// The empty set, which the tuples build on. Grants nothing.
1991impl BucketPerms for () {
1992 type Id = Self;
1993 type Upload = No;
1994 type SignedUpload = No;
1995 type Download = No;
1996 type SignedDownload = No;
1997 type Attrs = No;
1998 type List = No;
1999 type Remove = No;
2000 type PublicUrl = No;
2001 type UpdateAttrs = No;
2002 type IfMatchUpload = No;
2003 type IfMatchRemove = No;
2004}
2005
2006/// A tuple grants what its first member or the rest of it does.
2007macro_rules! tuple_perms {
2008 () => {};
2009 ($first:ident $(, $rest:ident)*) => {
2010 impl<$first: BucketPerms, $($rest: BucketPerms),*> sealed::Sealed for ($first, $($rest,)*) {}
2011 impl<$first: BucketPerms, $($rest: BucketPerms),*> BucketPerms for ($first, $($rest,)*) {
2012 type Id = Self;
2013 type Upload = <$first::Upload as Flag>::Or<<($($rest,)*) as BucketPerms>::Upload>;
2014 type SignedUpload =
2015 <$first::SignedUpload as Flag>::Or<<($($rest,)*) as BucketPerms>::SignedUpload>;
2016 type Download = <$first::Download as Flag>::Or<<($($rest,)*) as BucketPerms>::Download>;
2017 type SignedDownload =
2018 <$first::SignedDownload as Flag>::Or<<($($rest,)*) as BucketPerms>::SignedDownload>;
2019 type Attrs = <$first::Attrs as Flag>::Or<<($($rest,)*) as BucketPerms>::Attrs>;
2020 type List = <$first::List as Flag>::Or<<($($rest,)*) as BucketPerms>::List>;
2021 type Remove = <$first::Remove as Flag>::Or<<($($rest,)*) as BucketPerms>::Remove>;
2022 type PublicUrl =
2023 <$first::PublicUrl as Flag>::Or<<($($rest,)*) as BucketPerms>::PublicUrl>;
2024 type UpdateAttrs =
2025 <$first::UpdateAttrs as Flag>::Or<<($($rest,)*) as BucketPerms>::UpdateAttrs>;
2026 type IfMatchUpload =
2027 <$first::IfMatchUpload as Flag>::Or<<($($rest,)*) as BucketPerms>::IfMatchUpload>;
2028 type IfMatchRemove =
2029 <$first::IfMatchRemove as Flag>::Or<<($($rest,)*) as BucketPerms>::IfMatchRemove>;
2030 }
2031 tuple_perms!($($rest),*);
2032 };
2033}
2034
2035tuple_perms!(A, B, C, D, E, F, G, H, I, J, K, L);
2036
2037/// A `Copy` reference to a [`Bucket`] that grants only the permissions `P`,
2038/// created with [`Bucket::reference`].
2039///
2040/// Only operations allowed by `P` can be called on a `BucketRef` (for example,
2041/// `BucketRef<perms::Uploader>` can `upload` but cannot `download`). Library
2042/// code should accept the corresponding permission traits (such as
2043/// `&impl Uploader`) rather than `BucketRef` directly.
2044///
2045/// ```compile_fail,E0277
2046/// # use encore::objects::{perms, Bucket};
2047/// # static UPLOADS: Bucket = Bucket::named("uploads");
2048/// async fn upload() {
2049/// // A `Lister` reference cannot upload.
2050/// let _ = UPLOADS.reference::<perms::Lister>().upload("a", vec![]).await;
2051/// }
2052/// ```
2053///
2054/// ```compile_fail,E0277
2055/// # use encore::objects::{perms, Bucket};
2056/// # static UPLOADS: Bucket = Bucket::named("uploads");
2057/// async fn update() {
2058/// // Uploading is not changing attributes: that is `AttrsUpdater`.
2059/// let r = UPLOADS.reference::<perms::Uploader>();
2060/// let _ = r.update_attrs("a").cache_control("no-store").await;
2061/// }
2062/// ```
2063///
2064/// ```compile_fail,E0277
2065/// # use encore::objects::{perms, Bucket, Revision};
2066/// # static UPLOADS: Bucket = Bucket::named("uploads");
2067/// async fn replace(seen: Revision) {
2068/// // Uploading over a revision is `IfMatchUploader`.
2069/// let r = UPLOADS.reference::<perms::Uploader>();
2070/// let _ = r.upload_if_match("a", vec![], seen).await;
2071/// }
2072/// ```
2073pub struct BucketRef<P> {
2074 bucket: &'static Bucket,
2075 perms: PhantomData<fn() -> P>,
2076}
2077
2078impl<P> Clone for BucketRef<P> {
2079 fn clone(&self) -> Self {
2080 *self
2081 }
2082}
2083
2084impl<P> Copy for BucketRef<P> {}
2085
2086impl<P: BucketPerms> BucketRef<P> {
2087 /// See [`Bucket::list`].
2088 pub fn list(&self) -> ListRequest<'static>
2089 where
2090 P::List: Granted<perms::Lister>,
2091 {
2092 self.bucket.list()
2093 }
2094
2095 /// See [`Bucket::list_versions`].
2096 pub fn list_versions(&self) -> ListVersionsRequest<'static>
2097 where
2098 P::List: Granted<perms::Lister>,
2099 {
2100 self.bucket.list_versions()
2101 }
2102
2103 /// See [`Bucket::exists`].
2104 pub fn exists(&self, key: &str) -> ExistsRequest<'static>
2105 where
2106 P::Attrs: Granted<perms::Attrser>,
2107 {
2108 self.bucket.exists(key)
2109 }
2110
2111 /// See [`Bucket::attrs`].
2112 pub fn attrs(&self, key: &str) -> AttrsRequest<'static>
2113 where
2114 P::Attrs: Granted<perms::Attrser>,
2115 {
2116 self.bucket.attrs(key)
2117 }
2118
2119 /// See [`Bucket::upload`].
2120 pub fn upload(&self, key: &str, data: impl Into<UploadBody>) -> UploadRequest<'static>
2121 where
2122 P::Upload: Granted<perms::Uploader>,
2123 {
2124 self.bucket.upload(key, data)
2125 }
2126
2127 /// See [`Bucket::upload_if_match`].
2128 pub fn upload_if_match(
2129 &self,
2130 key: &str,
2131 data: impl Into<UploadBody>,
2132 revision: Revision,
2133 ) -> UploadIfMatchRequest<'static>
2134 where
2135 P::IfMatchUpload: Granted<perms::IfMatchUploader>,
2136 {
2137 self.bucket.upload_if_match(key, data, revision)
2138 }
2139
2140 /// See [`Bucket::update_attrs`].
2141 pub fn update_attrs(&self, key: &str) -> UpdateAttrsRequest<'static>
2142 where
2143 P::UpdateAttrs: Granted<perms::AttrsUpdater>,
2144 {
2145 self.bucket.update_attrs(key)
2146 }
2147
2148 /// See [`Bucket::extend_retention`].
2149 pub fn extend_retention(&self, key: &str, until: SystemTime) -> ExtendRetentionRequest<'static>
2150 where
2151 P::UpdateAttrs: Granted<perms::AttrsUpdater>,
2152 {
2153 self.bucket.extend_retention(key, until)
2154 }
2155
2156 /// See [`Bucket::download`].
2157 pub fn download(&self, key: &str) -> DownloadRequest<'static>
2158 where
2159 P::Download: Granted<perms::Downloader>,
2160 {
2161 self.bucket.download(key)
2162 }
2163
2164 /// See [`Bucket::remove`].
2165 pub fn remove(&self, key: &str) -> RemoveRequest<'static>
2166 where
2167 P::Remove: Granted<perms::Remover>,
2168 {
2169 self.bucket.remove(key)
2170 }
2171
2172 /// See [`Bucket::remove_if_match`].
2173 pub async fn remove_if_match(&self, key: &str, revision: Revision) -> Result<(), Error>
2174 where
2175 P::IfMatchRemove: Granted<perms::IfMatchRemover>,
2176 {
2177 self.bucket.remove_if_match(key, revision).await
2178 }
2179
2180 /// See [`Bucket::signed_upload_url`].
2181 pub fn signed_upload_url(&self, key: &str) -> SignedUploadUrlRequest<'static>
2182 where
2183 P::SignedUpload: Granted<perms::SignedUploader>,
2184 {
2185 self.bucket.signed_upload_url(key)
2186 }
2187
2188 /// See [`Bucket::signed_download_url`].
2189 pub fn signed_download_url(&self, key: &str) -> SignedDownloadUrlRequest<'static>
2190 where
2191 P::SignedDownload: Granted<perms::SignedDownloader>,
2192 {
2193 self.bucket.signed_download_url(key)
2194 }
2195
2196 /// See [`Bucket::public_url`].
2197 pub fn public_url(&self, key: &str) -> Result<String, Error>
2198 where
2199 P::PublicUrl: Granted<perms::PublicUrler>,
2200 {
2201 self.bucket.public_url(key)
2202 }
2203}
2204
2205// The permissions' traits. Each operation that takes options is a method
2206// making its request, and a `run_` method running it, which is what an
2207// implementation provides: a `BucketRef` runs it on its bucket, and a fake as
2208// it likes.
2209
2210/// Upload objects. Implemented by a [`BucketRef`] granting
2211/// [`perms::Uploader`].
2212pub trait Uploader: Send + Sync {
2213 /// See [`Bucket::upload`].
2214 fn upload(&self, key: &str, data: impl Into<UploadBody>) -> UploadRequest<'_, Self> {
2215 UploadRequest::new(self, key, data.into())
2216 }
2217
2218 /// Runs the upload [`upload`](Self::upload) made, when it is awaited.
2219 fn run_upload(
2220 &self,
2221 request: UploadRequest<'_, Self>,
2222 ) -> impl Future<Output = Result<ObjectAttrs, Error>> + Send;
2223}
2224
2225/// Upload objects only over the revision named. Implemented by a
2226/// [`BucketRef`] granting [`perms::IfMatchUploader`].
2227pub trait IfMatchUploader: Send + Sync {
2228 /// See [`Bucket::upload_if_match`].
2229 fn upload_if_match(
2230 &self,
2231 key: &str,
2232 data: impl Into<UploadBody>,
2233 revision: Revision,
2234 ) -> UploadIfMatchRequest<'_, Self> {
2235 UploadIfMatchRequest::new(self, key, data.into(), revision)
2236 }
2237
2238 /// Runs the upload [`upload_if_match`](Self::upload_if_match) made, when
2239 /// it is awaited.
2240 fn run_upload_if_match(
2241 &self,
2242 request: UploadIfMatchRequest<'_, Self>,
2243 ) -> impl Future<Output = Result<ObjectAttrs, Error>> + Send;
2244}
2245
2246/// Make signed upload URLs. Implemented by a [`BucketRef`] granting
2247/// [`perms::SignedUploader`].
2248pub trait SignedUploader: Send + Sync {
2249 /// See [`Bucket::signed_upload_url`].
2250 fn signed_upload_url(&self, key: &str) -> SignedUploadUrlRequest<'_, Self> {
2251 SignedUploadUrlRequest::new(self, key)
2252 }
2253
2254 /// Runs the request [`signed_upload_url`](Self::signed_upload_url) made,
2255 /// when it is awaited.
2256 fn run_signed_upload_url(
2257 &self,
2258 request: SignedUploadUrlRequest<'_, Self>,
2259 ) -> impl Future<Output = Result<SignedUploadUrl, Error>> + Send;
2260}
2261
2262/// Download objects. Implemented by a [`BucketRef`] granting
2263/// [`perms::Downloader`].
2264pub trait Downloader: Send + Sync {
2265 /// See [`Bucket::download`].
2266 fn download(&self, key: &str) -> DownloadRequest<'_, Self> {
2267 DownloadRequest::new(self, key)
2268 }
2269
2270 /// Runs the download [`download`](Self::download) made, when it is
2271 /// awaited. A fake answers with [`Download::of`].
2272 fn run_download(
2273 &self,
2274 request: DownloadRequest<'_, Self>,
2275 ) -> impl Future<Output = Result<Download, Error>> + Send;
2276}
2277
2278/// Make signed download URLs. Implemented by a [`BucketRef`] granting
2279/// [`perms::SignedDownloader`].
2280pub trait SignedDownloader: Send + Sync {
2281 /// See [`Bucket::signed_download_url`].
2282 fn signed_download_url(&self, key: &str) -> SignedDownloadUrlRequest<'_, Self> {
2283 SignedDownloadUrlRequest::new(self, key)
2284 }
2285
2286 /// Runs the request [`signed_download_url`](Self::signed_download_url)
2287 /// made, when it is awaited.
2288 fn run_signed_download_url(
2289 &self,
2290 request: SignedDownloadUrlRequest<'_, Self>,
2291 ) -> impl Future<Output = Result<SignedDownloadUrl, Error>> + Send;
2292}
2293
2294/// Read objects' attributes, and whether they exist. Implemented by a
2295/// [`BucketRef`] granting [`perms::Attrser`].
2296pub trait Attrser: Send + Sync {
2297 /// See [`Bucket::exists`].
2298 fn exists(&self, key: &str) -> ExistsRequest<'_, Self> {
2299 ExistsRequest::new(self, key)
2300 }
2301
2302 /// See [`Bucket::attrs`].
2303 fn attrs(&self, key: &str) -> AttrsRequest<'_, Self> {
2304 AttrsRequest::new(self, key)
2305 }
2306
2307 /// Runs the request [`exists`](Self::exists) made, when it is awaited.
2308 fn run_exists(
2309 &self,
2310 request: ExistsRequest<'_, Self>,
2311 ) -> impl Future<Output = Result<bool, Error>> + Send;
2312
2313 /// Runs the request [`attrs`](Self::attrs) made, when it is awaited.
2314 fn run_attrs(
2315 &self,
2316 request: AttrsRequest<'_, Self>,
2317 ) -> impl Future<Output = Result<ObjectAttrs, Error>> + Send;
2318}
2319
2320/// List objects and their versions. Implemented by a [`BucketRef`] granting
2321/// [`perms::Lister`].
2322pub trait Lister: Send + Sync {
2323 /// See [`Bucket::list`].
2324 fn list(&self) -> ListRequest<'_, Self> {
2325 ListRequest::new(self)
2326 }
2327
2328 /// See [`Bucket::list_versions`].
2329 fn list_versions(&self) -> ListVersionsRequest<'_, Self> {
2330 ListVersionsRequest::new(self)
2331 }
2332
2333 /// Runs the listing [`list`](Self::list) made, when it is awaited.
2334 fn run_list(
2335 &self,
2336 request: ListRequest<'_, Self>,
2337 ) -> impl Future<Output = Result<ListIterator, Error>> + Send;
2338
2339 /// Runs the listing [`list_versions`](Self::list_versions) made, when it
2340 /// is awaited.
2341 fn run_list_versions(
2342 &self,
2343 request: ListVersionsRequest<'_, Self>,
2344 ) -> impl Future<Output = Result<VersionIterator, Error>> + Send;
2345}
2346
2347/// Remove objects. Implemented by a [`BucketRef`] granting [`perms::Remover`].
2348pub trait Remover: Send + Sync {
2349 /// See [`Bucket::remove`].
2350 fn remove(&self, key: &str) -> RemoveRequest<'_, Self> {
2351 RemoveRequest::new(self, key)
2352 }
2353
2354 /// Runs the removal [`remove`](Self::remove) made, when it is awaited.
2355 fn run_remove(
2356 &self,
2357 request: RemoveRequest<'_, Self>,
2358 ) -> impl Future<Output = Result<(), Error>> + Send;
2359}
2360
2361/// Remove objects only if they are the revision named. Implemented by a
2362/// [`BucketRef`] granting [`perms::IfMatchRemover`].
2363pub trait IfMatchRemover: Send + Sync {
2364 /// See [`Bucket::remove_if_match`].
2365 fn remove_if_match(
2366 &self,
2367 key: &str,
2368 revision: Revision,
2369 ) -> impl Future<Output = Result<(), Error>> + Send;
2370}
2371
2372/// Resolve objects' public URLs. Implemented by a [`BucketRef`] granting
2373/// [`perms::PublicUrler`].
2374pub trait PublicUrler: Send + Sync {
2375 /// See [`Bucket::public_url`].
2376 fn public_url(&self, key: &str) -> Result<String, Error>;
2377}
2378
2379/// Change objects' attributes and extend their retention. Implemented by a
2380/// [`BucketRef`] granting [`perms::AttrsUpdater`].
2381pub trait AttrsUpdater: Send + Sync {
2382 /// See [`Bucket::update_attrs`].
2383 fn update_attrs(&self, key: &str) -> UpdateAttrsRequest<'_, Self> {
2384 UpdateAttrsRequest::new(self, key)
2385 }
2386
2387 /// See [`Bucket::extend_retention`].
2388 fn extend_retention(&self, key: &str, until: SystemTime) -> ExtendRetentionRequest<'_, Self> {
2389 ExtendRetentionRequest::new(self, key, until)
2390 }
2391
2392 /// Runs the change [`update_attrs`](Self::update_attrs) made, when it is
2393 /// awaited.
2394 fn run_update_attrs(
2395 &self,
2396 request: UpdateAttrsRequest<'_, Self>,
2397 ) -> impl Future<Output = Result<ObjectAttrs, Error>> + Send;
2398
2399 /// Runs the extension [`extend_retention`](Self::extend_retention) made,
2400 /// when it is awaited.
2401 fn run_extend_retention(
2402 &self,
2403 request: ExtendRetentionRequest<'_, Self>,
2404 ) -> impl Future<Output = Result<ObjectAttrs, Error>> + Send;
2405}
2406
2407/// Every permission but [`PublicUrler`]. Implemented by whatever implements
2408/// them all, such as a [`BucketRef`] granting [`perms::ReadWriter`].
2409pub trait ReadWriter:
2410 Uploader
2411 + IfMatchUploader
2412 + SignedUploader
2413 + Downloader
2414 + SignedDownloader
2415 + Attrser
2416 + Lister
2417 + Remover
2418 + IfMatchRemover
2419 + AttrsUpdater
2420{
2421}
2422
2423impl<T> ReadWriter for T where
2424 T: Uploader
2425 + IfMatchUploader
2426 + SignedUploader
2427 + Downloader
2428 + SignedDownloader
2429 + Attrser
2430 + Lister
2431 + Remover
2432 + IfMatchRemover
2433 + AttrsUpdater
2434{
2435}
2436
2437impl<P: BucketPerms> Uploader for BucketRef<P>
2438where
2439 P::Upload: Granted<perms::Uploader>,
2440{
2441 fn run_upload(
2442 &self,
2443 request: UploadRequest<'_, Self>,
2444 ) -> impl Future<Output = Result<ObjectAttrs, Error>> + Send {
2445 request.send(self.bucket)
2446 }
2447}
2448
2449impl<P: BucketPerms> IfMatchUploader for BucketRef<P>
2450where
2451 P::IfMatchUpload: Granted<perms::IfMatchUploader>,
2452{
2453 fn run_upload_if_match(
2454 &self,
2455 request: UploadIfMatchRequest<'_, Self>,
2456 ) -> impl Future<Output = Result<ObjectAttrs, Error>> + Send {
2457 request.send(self.bucket)
2458 }
2459}
2460
2461impl<P: BucketPerms> SignedUploader for BucketRef<P>
2462where
2463 P::SignedUpload: Granted<perms::SignedUploader>,
2464{
2465 fn run_signed_upload_url(
2466 &self,
2467 request: SignedUploadUrlRequest<'_, Self>,
2468 ) -> impl Future<Output = Result<SignedUploadUrl, Error>> + Send {
2469 request.send(self.bucket)
2470 }
2471}
2472
2473impl<P: BucketPerms> Downloader for BucketRef<P>
2474where
2475 P::Download: Granted<perms::Downloader>,
2476{
2477 fn run_download(
2478 &self,
2479 request: DownloadRequest<'_, Self>,
2480 ) -> impl Future<Output = Result<Download, Error>> + Send {
2481 request.send(self.bucket)
2482 }
2483}
2484
2485impl<P: BucketPerms> SignedDownloader for BucketRef<P>
2486where
2487 P::SignedDownload: Granted<perms::SignedDownloader>,
2488{
2489 fn run_signed_download_url(
2490 &self,
2491 request: SignedDownloadUrlRequest<'_, Self>,
2492 ) -> impl Future<Output = Result<SignedDownloadUrl, Error>> + Send {
2493 request.send(self.bucket)
2494 }
2495}
2496
2497impl<P: BucketPerms> Attrser for BucketRef<P>
2498where
2499 P::Attrs: Granted<perms::Attrser>,
2500{
2501 fn run_exists(
2502 &self,
2503 request: ExistsRequest<'_, Self>,
2504 ) -> impl Future<Output = Result<bool, Error>> + Send {
2505 request.send(self.bucket)
2506 }
2507
2508 fn run_attrs(
2509 &self,
2510 request: AttrsRequest<'_, Self>,
2511 ) -> impl Future<Output = Result<ObjectAttrs, Error>> + Send {
2512 request.send(self.bucket)
2513 }
2514}
2515
2516impl<P: BucketPerms> Lister for BucketRef<P>
2517where
2518 P::List: Granted<perms::Lister>,
2519{
2520 fn run_list(
2521 &self,
2522 request: ListRequest<'_, Self>,
2523 ) -> impl Future<Output = Result<ListIterator, Error>> + Send {
2524 request.send(self.bucket)
2525 }
2526
2527 fn run_list_versions(
2528 &self,
2529 request: ListVersionsRequest<'_, Self>,
2530 ) -> impl Future<Output = Result<VersionIterator, Error>> + Send {
2531 request.send(self.bucket)
2532 }
2533}
2534
2535impl<P: BucketPerms> Remover for BucketRef<P>
2536where
2537 P::Remove: Granted<perms::Remover>,
2538{
2539 fn run_remove(
2540 &self,
2541 request: RemoveRequest<'_, Self>,
2542 ) -> impl Future<Output = Result<(), Error>> + Send {
2543 request.send(self.bucket)
2544 }
2545}
2546
2547impl<P: BucketPerms> IfMatchRemover for BucketRef<P>
2548where
2549 P::IfMatchRemove: Granted<perms::IfMatchRemover>,
2550{
2551 fn remove_if_match(
2552 &self,
2553 key: &str,
2554 revision: Revision,
2555 ) -> impl Future<Output = Result<(), Error>> + Send {
2556 BucketRef::remove_if_match(self, key, revision)
2557 }
2558}
2559
2560impl<P: BucketPerms> PublicUrler for BucketRef<P>
2561where
2562 P::PublicUrl: Granted<perms::PublicUrler>,
2563{
2564 fn public_url(&self, key: &str) -> Result<String, Error> {
2565 BucketRef::public_url(self, key)
2566 }
2567}
2568
2569impl<P: BucketPerms> AttrsUpdater for BucketRef<P>
2570where
2571 P::UpdateAttrs: Granted<perms::AttrsUpdater>,
2572{
2573 fn run_update_attrs(
2574 &self,
2575 request: UpdateAttrsRequest<'_, Self>,
2576 ) -> impl Future<Output = Result<ObjectAttrs, Error>> + Send {
2577 request.send(self.bucket)
2578 }
2579
2580 fn run_extend_retention(
2581 &self,
2582 request: ExtendRetentionRequest<'_, Self>,
2583 ) -> impl Future<Output = Result<ObjectAttrs, Error>> + Send {
2584 request.send(self.bucket)
2585 }
2586}
2587
2588#[cfg(test)]
2589mod tests;