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