Skip to main content

encore/
objects.rs

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