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 Go SDKs.
13//! That is what lets Encore grant each service exactly the permissions it
14//! uses: the operation is visible at the call, so the parser can read it.
15//!
16//! # References
17//!
18//! For the same reason, a bucket cannot be passed around as a value. To hand
19//! it to other code, make a [`BucketRef`], which grants only the permissions
20//! its type argument names:
21//!
22//! ```no_run
23//! use encore::objects::{perms, Bucket, Uploader};
24//!
25//! static UPLOADS: Bucket = Bucket::named("uploads");
26//!
27//! // Library code asks for the permissions it needs, as traits.
28//! async fn save(bucket: &impl Uploader, key: &str) -> Result<(), encore::Error> {
29//!     bucket.upload(key, b"hello".to_vec()).await?;
30//!     Ok(())
31//! }
32//!
33//! async fn greet() -> Result<(), encore::Error> {
34//!     save(&UPLOADS.reference::<perms::Uploader>(), "greeting.txt").await
35//! }
36//! ```
37//!
38//! The permissions are one of the [`perms`], or a tuple of them
39//! (`(perms::Uploader, perms::Lister)`). Each has a trait of the same name
40//! here, with the methods it grants. Library code takes the traits —
41//! `&impl Uploader`, `&(impl Uploader + Lister)` — so it works with any
42//! reference that grants them, and can be tested against a fake.
43
44use std::future::{poll_fn, Future};
45use std::marker::PhantomData;
46use std::pin::Pin;
47use std::task::{Context, Poll};
48use std::time::Duration;
49
50use bytes::Bytes;
51use encore_sdk_core::objects;
52use futures_core::Stream;
53use tokio::io::AsyncRead;
54use tokio_util::io::StreamReader;
55
56use crate::error::{ErrCode, Error};
57use crate::perm::{Flag, Granted, No};
58use crate::runtime::core;
59
60/// Re-exported option and result types of the bucket operations.
61pub use encore_sdk_core::objects::{
62    AttrsOptions, ByteRange, DeleteOptions as RemoveOptions, DownloadOptions, ExistsOptions,
63    ListEntry, ListOptions, ObjectAttrs, UploadOptions, UploadPreconditions,
64};
65
66/// The contents of an object, as they arrive: returned by
67/// [`Bucket::download_stream`]. Take them chunk by chunk with
68/// [`Download::next`] — or as a [`Stream`] — all at once with
69/// [`Download::bytes`], or as an [`AsyncRead`] with
70/// [`Download::into_async_read`].
71///
72/// ```ignore
73/// let mut download = UPLOADS.download_stream("big.bin", DownloadOptions::default()).await?;
74/// while let Some(chunk) = download.next().await {
75///     hasher.update(&chunk?);
76/// }
77///
78/// // Or straight into a file.
79/// let mut reader = UPLOADS
80///     .download_stream("big.bin", DownloadOptions::default())
81///     .await?
82///     .into_async_read();
83/// tokio::io::copy(&mut reader, &mut file).await?;
84/// ```
85pub struct Download {
86    inner: objects::DownloadStream,
87}
88
89impl Download {
90    /// The next chunk of the object, or `None` once it has all arrived. A
91    /// chunk is as large as it happened to arrive.
92    pub async fn next(&mut self) -> Option<Result<Bytes, Error>> {
93        poll_fn(|cx| Pin::new(&mut *self).poll_next(cx)).await
94    }
95
96    /// The rest of the object, in one piece.
97    pub async fn bytes(mut self) -> Result<Vec<u8>, Error> {
98        let mut bytes = Vec::new();
99        while let Some(chunk) = self.next().await {
100            bytes.extend_from_slice(&chunk?);
101        }
102        Ok(bytes)
103    }
104
105    /// The rest of the object as a reader, for what takes one: a parser, a
106    /// decompressor, `tokio::io::copy`.
107    pub fn into_async_read(self) -> impl AsyncRead + Unpin + Send + 'static {
108        StreamReader::new(ChunkErrors(self))
109    }
110}
111
112impl Stream for Download {
113    type Item = Result<Bytes, Error>;
114
115    fn poll_next(self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<Option<Self::Item>> {
116        self.get_mut()
117            .inner
118            .as_mut()
119            .poll_next(cx)
120            .map(|chunk| chunk.map(|chunk| chunk.map_err(map_obj_err)))
121    }
122}
123
124/// A download whose errors are `io::Error`s, as a reader's are.
125struct ChunkErrors(Download);
126
127impl Stream for ChunkErrors {
128    type Item = std::io::Result<Bytes>;
129
130    fn poll_next(self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<Option<Self::Item>> {
131        Pin::new(&mut self.get_mut().0)
132            .poll_next(cx)
133            .map(|chunk| chunk.map(|chunk| chunk.map_err(std::io::Error::other)))
134    }
135}
136
137/// The objects of a bucket, as they are listed: returned by [`Bucket::list`].
138/// Take them one at a time with [`ListIterator::next`], or as a [`Stream`].
139pub struct ListIterator {
140    inner: objects::ListIterator,
141}
142
143impl ListIterator {
144    /// The next object, or `None` once there are no more.
145    pub async fn next(&mut self) -> Option<Result<ListEntry, Error>> {
146        poll_fn(|cx| Pin::new(&mut *self).poll_next(cx)).await
147    }
148}
149
150impl Stream for ListIterator {
151    type Item = Result<ListEntry, Error>;
152
153    fn poll_next(self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<Option<Self::Item>> {
154        Pin::new(&mut self.get_mut().inner)
155            .poll_next(cx)
156            .map(|entry| entry.map(|entry| entry.map_err(map_obj_err)))
157    }
158}
159
160/// A stream of chunks as the reader an upload takes. The runtime shares the
161/// reader between threads, which a stream need not allow: the lock is what
162/// makes it shareable, and is never contended, as only one reads at a time.
163struct ChunkReader<S>(std::sync::Mutex<Pin<Box<S>>>);
164
165impl<S, B, E> Stream for ChunkReader<S>
166where
167    S: Stream<Item = Result<B, E>>,
168    B: Into<Bytes>,
169    E: Into<Box<dyn std::error::Error + Send + Sync>>,
170{
171    type Item = std::io::Result<Bytes>;
172
173    fn poll_next(self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<Option<Self::Item>> {
174        let stream = self
175            .get_mut()
176            .0
177            .get_mut()
178            .unwrap_or_else(|e| e.into_inner());
179        stream
180            .as_mut()
181            .poll_next(cx)
182            .map(|chunk| chunk.map(|chunk| chunk.map(Into::into).map_err(std::io::Error::other)))
183    }
184}
185
186/// A URL through which anyone holding it can upload an object, made by
187/// [`Bucket::signed_upload_url`].
188#[derive(Debug, Clone, PartialEq, Eq)]
189pub struct SignedUploadUrl {
190    pub url: String,
191}
192
193/// A URL through which anyone holding it can download an object, made by
194/// [`Bucket::signed_download_url`].
195#[derive(Debug, Clone, PartialEq, Eq)]
196pub struct SignedDownloadUrl {
197    pub url: String,
198}
199
200/// Options for a signed URL.
201#[derive(Debug, Clone, Copy, Default)]
202pub struct SignedUrlOptions {
203    /// How long the URL is valid for: at most seven days, and one hour if not
204    /// given.
205    pub ttl: Option<Duration>,
206}
207
208impl SignedUrlOptions {
209    fn ttl(self) -> Duration {
210        self.ttl.unwrap_or(Duration::from_secs(60 * 60))
211    }
212}
213
214/// An object-storage bucket.
215pub struct Bucket {
216    name: &'static str,
217    /// Read by Encore's parser from the declaration, not by the runtime.
218    #[allow(dead_code)]
219    versioned: bool,
220    #[allow(dead_code)]
221    public: bool,
222}
223
224impl Bucket {
225    /// Declare a bucket. `const` so it can initialize a module-scope `static`.
226    ///
227    /// Options follow the name, each a method of its own:
228    ///
229    /// ```no_run
230    /// use encore::objects::Bucket;
231    ///
232    /// static AVATARS: Bucket = Bucket::new("avatars").public().versioned();
233    /// ```
234    pub const fn new(name: &'static str) -> Self {
235        Self {
236            name,
237            versioned: false,
238            public: false,
239        }
240    }
241
242    /// Makes the bucket public: its objects are readable by anyone, at the URL
243    /// [`Bucket::public_url`] gives.
244    ///
245    /// Part of the declaration: it takes the bucket by value, so it cannot be
246    /// called on the `static`.
247    pub const fn public(mut self) -> Self {
248        self.public = true;
249        self
250    }
251
252    /// Makes the bucket versioned: an object keeps its earlier versions, which
253    /// the `_with` operations can name.
254    ///
255    /// Part of the declaration, like [`Bucket::public`].
256    pub const fn versioned(mut self) -> Self {
257        self.versioned = true;
258        self
259    }
260
261    /// Reference an existing bucket by name. To declare a new bucket, use
262    /// [`Bucket::new`] instead.
263    ///
264    /// The name must be a string literal, so Encore can resolve it statically.
265    /// `const` so it can initialize a module-scope `static`. A named bucket
266    /// takes no options: it is configured where it is declared.
267    ///
268    /// ```no_run
269    /// static UPLOADS: encore::objects::Bucket = encore::objects::Bucket::named("uploads");
270    /// ```
271    pub const fn named(name: &'static str) -> Self {
272        Self::new(name)
273    }
274
275    /// A reference to the bucket that grants only the permissions `P`: one of
276    /// the [`perms`], or a tuple of them. Unlike the bucket, a reference can be
277    /// passed to other code; the service is granted the permissions it names.
278    ///
279    /// The permissions must be written as the type argument, since they are
280    /// what the service is granted: the compiler never infers them. `const`,
281    /// so a reference can initialize a module-scope `static`.
282    ///
283    /// ```no_run
284    /// use encore::objects::{perms, Bucket, BucketRef};
285    ///
286    /// static UPLOADS: Bucket = Bucket::named("uploads");
287    /// static AVATARS: BucketRef<(perms::Uploader, perms::Lister)> =
288    ///     UPLOADS.reference::<(perms::Uploader, perms::Lister)>();
289    /// ```
290    ///
291    /// ```compile_fail,E0284
292    /// # use encore::objects::{perms, Bucket, BucketRef};
293    /// # static UPLOADS: Bucket = Bucket::named("uploads");
294    /// // Not even from the type it is assigned to.
295    /// static AVATARS: BucketRef<perms::Uploader> = UPLOADS.reference();
296    /// ```
297    pub const fn reference<P: BucketPerms>(&'static self) -> BucketRef<P::Id> {
298        BucketRef {
299            bucket: self,
300            perms: PhantomData,
301        }
302    }
303
304    /// The bucket operations run on: the app's own, or under `encore test`
305    /// the current test's instance of it (see [`crate::testing`]).
306    fn resolve(&self) -> Result<objects::Bucket, Error> {
307        if let Some(test) = crate::testing::active()? {
308            return test.bucket(self.name);
309        }
310        core()
311            .objects()
312            .bucket(self.name.into())
313            .ok_or_else(|| Error::not_found(format!("bucket {:?} is not configured", self.name)))
314    }
315
316    fn object(&self, key: &str) -> Result<objects::Object, Error> {
317        Ok(self.resolve()?.object(key.to_string()))
318    }
319
320    /// List the objects in the bucket — those under `options.prefix`, up to
321    /// `options.limit` — as an iterator of entries.
322    ///
323    /// ```ignore
324    /// let mut entries = UPLOADS.list(ListOptions { prefix: Some("avatars/".into()), ..Default::default() }).await?;
325    /// while let Some(entry) = entries.next().await {
326    ///     println!("{}", entry?.name);
327    /// }
328    /// ```
329    pub async fn list(&self, options: ListOptions) -> Result<ListIterator, Error> {
330        self.resolve()?
331            .list(options)
332            .await
333            .map(|inner| ListIterator { inner })
334            .map_err(map_obj_err)
335    }
336
337    /// Whether an object with `key` exists.
338    pub async fn exists(&self, key: &str) -> Result<bool, Error> {
339        self.exists_with(key, ExistsOptions::default()).await
340    }
341
342    /// Whether an object exists, with explicit options (a specific version).
343    pub async fn exists_with(&self, key: &str, options: ExistsOptions) -> Result<bool, Error> {
344        self.object(key)?.exists(options).await.map_err(map_obj_err)
345    }
346
347    /// The attributes of the object `key`: its size, content type, version
348    /// and etag.
349    pub async fn attrs(&self, key: &str) -> Result<ObjectAttrs, Error> {
350        self.attrs_with(key, AttrsOptions::default()).await
351    }
352
353    /// An object's attributes, with explicit options (a specific version).
354    pub async fn attrs_with(&self, key: &str, options: AttrsOptions) -> Result<ObjectAttrs, Error> {
355        self.object(key)?.attrs(options).await.map_err(map_obj_err)
356    }
357
358    /// Upload `data` to the object `key`, returning its stored attributes.
359    pub async fn upload(&self, key: &str, data: Vec<u8>) -> Result<ObjectAttrs, Error> {
360        self.upload_with(key, data, UploadOptions::default()).await
361    }
362
363    /// Upload `data` with explicit options — a content type, or a
364    /// precondition such as "only if it does not exist yet".
365    pub async fn upload_with(
366        &self,
367        key: &str,
368        data: Vec<u8>,
369        options: UploadOptions,
370    ) -> Result<ObjectAttrs, Error> {
371        self.upload_stream(key, std::io::Cursor::new(data), options)
372            .await
373    }
374
375    /// Upload the object `key` from a reader, streaming its contents rather
376    /// than buffering them.
377    pub async fn upload_stream(
378        &self,
379        key: &str,
380        reader: impl AsyncRead + Unpin + Send + Sync + 'static,
381        options: UploadOptions,
382    ) -> Result<ObjectAttrs, Error> {
383        self.object(key)?
384            .upload(Box::new(reader), options)
385            .await
386            .map_err(map_obj_err)
387    }
388
389    /// Upload the object `key` from a stream of chunks, such as the body of a
390    /// request being forwarded. A chunk is anything that becomes `Bytes`:
391    /// `Bytes` itself, `Vec<u8>`, `String`, `&'static [u8]`.
392    ///
393    /// ```ignore
394    /// let chunks = futures::stream::iter([Ok::<_, std::io::Error>(Bytes::from("hello"))]);
395    /// UPLOADS.upload_chunks("greeting.txt", chunks, UploadOptions::default()).await?;
396    /// ```
397    pub async fn upload_chunks<S, B, E>(
398        &self,
399        key: &str,
400        chunks: S,
401        options: UploadOptions,
402    ) -> Result<ObjectAttrs, Error>
403    where
404        S: Stream<Item = Result<B, E>> + Send + 'static,
405        B: Into<Bytes> + 'static,
406        E: Into<Box<dyn std::error::Error + Send + Sync>> + 'static,
407    {
408        let reader = StreamReader::new(ChunkReader(std::sync::Mutex::new(Box::pin(chunks))));
409        self.upload_stream(key, reader, options).await
410    }
411
412    /// Download the full contents of the object `key`.
413    pub async fn download(&self, key: &str) -> Result<Vec<u8>, Error> {
414        self.download_with(key, DownloadOptions::default()).await
415    }
416
417    /// Download the object `key` with explicit options — a specific version, or
418    /// only a byte range of the object.
419    ///
420    /// ```ignore
421    /// // The 256 bytes starting at offset 1024.
422    /// let head = UPLOADS.download_with("big.bin", DownloadOptions {
423    ///     range: Some(ByteRange { offset: 1024, length: Some(256) }),
424    ///     ..Default::default()
425    /// }).await?;
426    /// ```
427    pub async fn download_with(
428        &self,
429        key: &str,
430        options: DownloadOptions,
431    ) -> Result<Vec<u8>, Error> {
432        self.object(key)?
433            .download_all(options)
434            .await
435            .map_err(map_obj_err)
436    }
437
438    /// Download the object `key` as it arrives, rather than buffering it
439    /// whole: see [`Download`].
440    pub async fn download_stream(
441        &self,
442        key: &str,
443        options: DownloadOptions,
444    ) -> Result<Download, Error> {
445        self.object(key)?
446            .download_stream(options)
447            .await
448            .map(|inner| Download { inner })
449            .map_err(map_obj_err)
450    }
451
452    /// Remove the object `key`.
453    pub async fn remove(&self, key: &str) -> Result<(), Error> {
454        self.remove_with(key, RemoveOptions::default()).await
455    }
456
457    /// Remove an object, with explicit options (a specific version).
458    pub async fn remove_with(&self, key: &str, options: RemoveOptions) -> Result<(), Error> {
459        self.object(key)?.delete(options).await.map_err(map_obj_err)
460    }
461
462    /// A URL through which anyone holding it can upload the object `key`,
463    /// valid for an hour.
464    pub async fn signed_upload_url(&self, key: &str) -> Result<SignedUploadUrl, Error> {
465        self.signed_upload_url_with(key, SignedUrlOptions::default())
466            .await
467    }
468
469    /// A signed upload URL, with explicit options (how long it is valid for).
470    ///
471    /// ```ignore
472    /// let upload = UPLOADS.signed_upload_url_with("report.pdf", SignedUrlOptions {
473    ///     ttl: Some(Duration::from_secs(5 * 60)),
474    /// }).await?;
475    /// ```
476    pub async fn signed_upload_url_with(
477        &self,
478        key: &str,
479        options: SignedUrlOptions,
480    ) -> Result<SignedUploadUrl, Error> {
481        self.object(key)?
482            .signed_upload_url(objects::UploadUrlOptions { ttl: options.ttl() })
483            .await
484            .map(|url| SignedUploadUrl { url })
485            .map_err(map_obj_err)
486    }
487
488    /// A URL through which anyone holding it can download the object `key`,
489    /// valid for an hour.
490    pub async fn signed_download_url(&self, key: &str) -> Result<SignedDownloadUrl, Error> {
491        self.signed_download_url_with(key, SignedUrlOptions::default())
492            .await
493    }
494
495    /// A signed download URL, with explicit options (how long it is valid for).
496    pub async fn signed_download_url_with(
497        &self,
498        key: &str,
499        options: SignedUrlOptions,
500    ) -> Result<SignedDownloadUrl, Error> {
501        self.object(key)?
502            .signed_download_url(objects::DownloadUrlOptions { ttl: options.ttl() })
503            .await
504            .map(|url| SignedDownloadUrl { url })
505            .map_err(map_obj_err)
506    }
507
508    /// The public URL of the object `key`. Only a bucket declared `public`
509    /// has one.
510    pub fn public_url(&self, key: &str) -> Result<String, Error> {
511        self.object(key)?.public_url().map_err(|err| {
512            let code = match err {
513                objects::PublicUrlError::PrivateBucket => ErrCode::FailedPrecondition,
514                objects::PublicUrlError::InvalidObjectName => ErrCode::InvalidArgument,
515                objects::PublicUrlError::NoopBucket => ErrCode::Unavailable,
516            };
517            Error::wrap(code, err)
518        })
519    }
520}
521
522/// The permissions a [`BucketRef`] can grant, as types for its type argument.
523/// Each has a trait of the same name in [`objects`](super), with the methods
524/// it grants.
525pub mod perms {
526    use super::{sealed::Sealed, BucketPerms};
527    use crate::perm::{No, Yes};
528
529    macro_rules! perm {
530        ($(#[$doc:meta])* $name:ident: $upload:ident, $signed_upload:ident, $download:ident,
531         $signed_download:ident, $attrs:ident, $list:ident, $remove:ident, $public_url:ident) => {
532            $(#[$doc])*
533            pub enum $name {}
534            impl Sealed for $name {}
535            impl BucketPerms for $name {
536                type Id = Self;
537                type Upload = $upload;
538                type SignedUpload = $signed_upload;
539                type Download = $download;
540                type SignedDownload = $signed_download;
541                type Attrs = $attrs;
542                type List = $list;
543                type Remove = $remove;
544                type PublicUrl = $public_url;
545            }
546        };
547    }
548
549    // The flags each sets, in `BucketPerms`' order: Upload, SignedUpload,
550    // Download, SignedDownload, Attrs, List, Remove, PublicUrl.
551    perm!(
552        /// Upload objects: [`Uploader`](super::Uploader).
553        Uploader: Yes, No, No, No, No, No, No, No
554    );
555    perm!(
556        /// Make signed upload URLs: [`SignedUploader`](super::SignedUploader).
557        SignedUploader: No, Yes, No, No, No, No, No, No
558    );
559    perm!(
560        /// Download objects: [`Downloader`](super::Downloader).
561        Downloader: No, No, Yes, No, No, No, No, No
562    );
563    perm!(
564        /// Make signed download URLs:
565        /// [`SignedDownloader`](super::SignedDownloader).
566        SignedDownloader: No, No, No, Yes, No, No, No, No
567    );
568    perm!(
569        /// Read objects' attributes, and whether they exist:
570        /// [`Attrser`](super::Attrser).
571        Attrser: No, No, No, No, Yes, No, No, No
572    );
573    perm!(
574        /// List objects: [`Lister`](super::Lister).
575        Lister: No, No, No, No, No, Yes, No, No
576    );
577    perm!(
578        /// Remove objects: [`Remover`](super::Remover).
579        Remover: No, No, No, No, No, No, Yes, No
580    );
581    perm!(
582        /// Resolve objects' public URLs: [`PublicUrler`](super::PublicUrler).
583        PublicUrler: No, No, No, No, No, No, No, Yes
584    );
585    perm!(
586        /// Every permission but [`PublicUrler`]: [`ReadWriter`](super::ReadWriter).
587        ReadWriter: Yes, Yes, Yes, Yes, Yes, Yes, Yes, No
588    );
589}
590
591mod sealed {
592    pub trait Sealed {}
593}
594
595/// A set of bucket permissions: one of the [`perms`], or a tuple of them,
596/// which grants what any of its members does. Sealed: the SDK's permissions
597/// are the only ones.
598pub trait BucketPerms: sealed::Sealed {
599    /// Always `Self`. [`Bucket::reference`] returns `BucketRef<P::Id>`, which
600    /// the compiler cannot work back from to `P`, so `P` is never inferred.
601    #[doc(hidden)]
602    type Id: BucketPerms;
603    #[doc(hidden)]
604    type Upload: Flag;
605    #[doc(hidden)]
606    type SignedUpload: Flag;
607    #[doc(hidden)]
608    type Download: Flag;
609    #[doc(hidden)]
610    type SignedDownload: Flag;
611    #[doc(hidden)]
612    type Attrs: Flag;
613    #[doc(hidden)]
614    type List: Flag;
615    #[doc(hidden)]
616    type Remove: Flag;
617    #[doc(hidden)]
618    type PublicUrl: Flag;
619}
620
621impl sealed::Sealed for () {}
622
623/// The empty set, which the tuples build on. Grants nothing.
624impl BucketPerms for () {
625    type Id = Self;
626    type Upload = No;
627    type SignedUpload = No;
628    type Download = No;
629    type SignedDownload = No;
630    type Attrs = No;
631    type List = No;
632    type Remove = No;
633    type PublicUrl = No;
634}
635
636/// A tuple grants what its first member or the rest of it does.
637macro_rules! tuple_perms {
638    () => {};
639    ($first:ident $(, $rest:ident)*) => {
640        impl<$first: BucketPerms, $($rest: BucketPerms),*> sealed::Sealed for ($first, $($rest,)*) {}
641        impl<$first: BucketPerms, $($rest: BucketPerms),*> BucketPerms for ($first, $($rest,)*) {
642            type Id = Self;
643            type Upload = <$first::Upload as Flag>::Or<<($($rest,)*) as BucketPerms>::Upload>;
644            type SignedUpload =
645                <$first::SignedUpload as Flag>::Or<<($($rest,)*) as BucketPerms>::SignedUpload>;
646            type Download = <$first::Download as Flag>::Or<<($($rest,)*) as BucketPerms>::Download>;
647            type SignedDownload =
648                <$first::SignedDownload as Flag>::Or<<($($rest,)*) as BucketPerms>::SignedDownload>;
649            type Attrs = <$first::Attrs as Flag>::Or<<($($rest,)*) as BucketPerms>::Attrs>;
650            type List = <$first::List as Flag>::Or<<($($rest,)*) as BucketPerms>::List>;
651            type Remove = <$first::Remove as Flag>::Or<<($($rest,)*) as BucketPerms>::Remove>;
652            type PublicUrl =
653                <$first::PublicUrl as Flag>::Or<<($($rest,)*) as BucketPerms>::PublicUrl>;
654        }
655        tuple_perms!($($rest),*);
656    };
657}
658
659tuple_perms!(A, B, C, D, E, F, G, H, I);
660
661/// A reference to a [`Bucket`] that grants only the permissions `P`, made by
662/// [`Bucket::reference`]. `Copy`, and free to pass to other code.
663///
664/// Its methods are the bucket's, for the permissions it grants: a
665/// `BucketRef<perms::Uploader>` can `upload` but not `download`. Each is also
666/// a method of its permission's trait, which library code takes instead of a
667/// `BucketRef`.
668///
669/// ```compile_fail,E0277
670/// # use encore::objects::{perms, Bucket};
671/// # static UPLOADS: Bucket = Bucket::named("uploads");
672/// async fn upload() {
673///     // A `Lister` reference cannot upload.
674///     let _ = UPLOADS.reference::<perms::Lister>().upload("a", vec![]).await;
675/// }
676/// ```
677pub struct BucketRef<P> {
678    bucket: &'static Bucket,
679    perms: PhantomData<fn() -> P>,
680}
681
682impl<P> Clone for BucketRef<P> {
683    fn clone(&self) -> Self {
684        *self
685    }
686}
687
688impl<P> Copy for BucketRef<P> {}
689
690impl<P: BucketPerms> BucketRef<P> {
691    /// See [`Bucket::list`].
692    pub async fn list(&self, options: ListOptions) -> Result<ListIterator, Error>
693    where
694        P::List: Granted<perms::Lister>,
695    {
696        self.bucket.list(options).await
697    }
698
699    /// See [`Bucket::exists`].
700    pub async fn exists(&self, key: &str) -> Result<bool, Error>
701    where
702        P::Attrs: Granted<perms::Attrser>,
703    {
704        self.bucket.exists(key).await
705    }
706
707    /// See [`Bucket::exists_with`].
708    pub async fn exists_with(&self, key: &str, options: ExistsOptions) -> Result<bool, Error>
709    where
710        P::Attrs: Granted<perms::Attrser>,
711    {
712        self.bucket.exists_with(key, options).await
713    }
714
715    /// See [`Bucket::attrs`].
716    pub async fn attrs(&self, key: &str) -> Result<ObjectAttrs, Error>
717    where
718        P::Attrs: Granted<perms::Attrser>,
719    {
720        self.bucket.attrs(key).await
721    }
722
723    /// See [`Bucket::attrs_with`].
724    pub async fn attrs_with(&self, key: &str, options: AttrsOptions) -> Result<ObjectAttrs, Error>
725    where
726        P::Attrs: Granted<perms::Attrser>,
727    {
728        self.bucket.attrs_with(key, options).await
729    }
730
731    /// See [`Bucket::upload`].
732    pub async fn upload(&self, key: &str, data: Vec<u8>) -> Result<ObjectAttrs, Error>
733    where
734        P::Upload: Granted<perms::Uploader>,
735    {
736        self.bucket.upload(key, data).await
737    }
738
739    /// See [`Bucket::upload_with`].
740    pub async fn upload_with(
741        &self,
742        key: &str,
743        data: Vec<u8>,
744        options: UploadOptions,
745    ) -> Result<ObjectAttrs, Error>
746    where
747        P::Upload: Granted<perms::Uploader>,
748    {
749        self.bucket.upload_with(key, data, options).await
750    }
751
752    /// See [`Bucket::upload_stream`].
753    pub async fn upload_stream(
754        &self,
755        key: &str,
756        reader: impl AsyncRead + Unpin + Send + Sync + 'static,
757        options: UploadOptions,
758    ) -> Result<ObjectAttrs, Error>
759    where
760        P::Upload: Granted<perms::Uploader>,
761    {
762        self.bucket.upload_stream(key, reader, options).await
763    }
764
765    /// See [`Bucket::upload_chunks`].
766    pub async fn upload_chunks<S, B, E>(
767        &self,
768        key: &str,
769        chunks: S,
770        options: UploadOptions,
771    ) -> Result<ObjectAttrs, Error>
772    where
773        P::Upload: Granted<perms::Uploader>,
774        S: Stream<Item = Result<B, E>> + Send + 'static,
775        B: Into<Bytes> + 'static,
776        E: Into<Box<dyn std::error::Error + Send + Sync>> + 'static,
777    {
778        self.bucket.upload_chunks(key, chunks, options).await
779    }
780
781    /// See [`Bucket::download`].
782    pub async fn download(&self, key: &str) -> Result<Vec<u8>, Error>
783    where
784        P::Download: Granted<perms::Downloader>,
785    {
786        self.bucket.download(key).await
787    }
788
789    /// See [`Bucket::download_with`].
790    pub async fn download_with(&self, key: &str, options: DownloadOptions) -> Result<Vec<u8>, Error>
791    where
792        P::Download: Granted<perms::Downloader>,
793    {
794        self.bucket.download_with(key, options).await
795    }
796
797    /// See [`Bucket::download_stream`].
798    pub async fn download_stream(
799        &self,
800        key: &str,
801        options: DownloadOptions,
802    ) -> Result<Download, Error>
803    where
804        P::Download: Granted<perms::Downloader>,
805    {
806        self.bucket.download_stream(key, options).await
807    }
808
809    /// See [`Bucket::remove`].
810    pub async fn remove(&self, key: &str) -> Result<(), Error>
811    where
812        P::Remove: Granted<perms::Remover>,
813    {
814        self.bucket.remove(key).await
815    }
816
817    /// See [`Bucket::remove_with`].
818    pub async fn remove_with(&self, key: &str, options: RemoveOptions) -> Result<(), Error>
819    where
820        P::Remove: Granted<perms::Remover>,
821    {
822        self.bucket.remove_with(key, options).await
823    }
824
825    /// See [`Bucket::signed_upload_url`].
826    pub async fn signed_upload_url(&self, key: &str) -> Result<SignedUploadUrl, Error>
827    where
828        P::SignedUpload: Granted<perms::SignedUploader>,
829    {
830        self.bucket.signed_upload_url(key).await
831    }
832
833    /// See [`Bucket::signed_upload_url_with`].
834    pub async fn signed_upload_url_with(
835        &self,
836        key: &str,
837        options: SignedUrlOptions,
838    ) -> Result<SignedUploadUrl, Error>
839    where
840        P::SignedUpload: Granted<perms::SignedUploader>,
841    {
842        self.bucket.signed_upload_url_with(key, options).await
843    }
844
845    /// See [`Bucket::signed_download_url`].
846    pub async fn signed_download_url(&self, key: &str) -> Result<SignedDownloadUrl, Error>
847    where
848        P::SignedDownload: Granted<perms::SignedDownloader>,
849    {
850        self.bucket.signed_download_url(key).await
851    }
852
853    /// See [`Bucket::signed_download_url_with`].
854    pub async fn signed_download_url_with(
855        &self,
856        key: &str,
857        options: SignedUrlOptions,
858    ) -> Result<SignedDownloadUrl, Error>
859    where
860        P::SignedDownload: Granted<perms::SignedDownloader>,
861    {
862        self.bucket.signed_download_url_with(key, options).await
863    }
864
865    /// See [`Bucket::public_url`].
866    pub fn public_url(&self, key: &str) -> Result<String, Error>
867    where
868        P::PublicUrl: Granted<perms::PublicUrler>,
869    {
870        self.bucket.public_url(key)
871    }
872}
873
874/// Upload objects. Implemented by a [`BucketRef`] granting
875/// [`perms::Uploader`].
876pub trait Uploader: Send + Sync {
877    /// See [`Bucket::upload`].
878    fn upload(
879        &self,
880        key: &str,
881        data: Vec<u8>,
882    ) -> impl Future<Output = Result<ObjectAttrs, Error>> + Send {
883        self.upload_with(key, data, UploadOptions::default())
884    }
885
886    /// See [`Bucket::upload_with`].
887    fn upload_with(
888        &self,
889        key: &str,
890        data: Vec<u8>,
891        options: UploadOptions,
892    ) -> impl Future<Output = Result<ObjectAttrs, Error>> + Send;
893
894    /// See [`Bucket::upload_stream`].
895    fn upload_stream(
896        &self,
897        key: &str,
898        reader: impl AsyncRead + Unpin + Send + Sync + 'static,
899        options: UploadOptions,
900    ) -> impl Future<Output = Result<ObjectAttrs, Error>> + Send;
901
902    /// See [`Bucket::upload_chunks`].
903    fn upload_chunks<S, B, E>(
904        &self,
905        key: &str,
906        chunks: S,
907        options: UploadOptions,
908    ) -> impl Future<Output = Result<ObjectAttrs, Error>> + Send
909    where
910        S: Stream<Item = Result<B, E>> + Send + 'static,
911        B: Into<Bytes> + 'static,
912        E: Into<Box<dyn std::error::Error + Send + Sync>> + 'static,
913    {
914        let reader = StreamReader::new(ChunkReader(std::sync::Mutex::new(Box::pin(chunks))));
915        self.upload_stream(key, reader, options)
916    }
917}
918
919/// Make signed upload URLs. Implemented by a [`BucketRef`] granting
920/// [`perms::SignedUploader`].
921pub trait SignedUploader: Send + Sync {
922    /// See [`Bucket::signed_upload_url`].
923    fn signed_upload_url(
924        &self,
925        key: &str,
926    ) -> impl Future<Output = Result<SignedUploadUrl, Error>> + Send {
927        self.signed_upload_url_with(key, SignedUrlOptions::default())
928    }
929
930    /// See [`Bucket::signed_upload_url_with`].
931    fn signed_upload_url_with(
932        &self,
933        key: &str,
934        options: SignedUrlOptions,
935    ) -> impl Future<Output = Result<SignedUploadUrl, Error>> + Send;
936}
937
938/// Download objects. Implemented by a [`BucketRef`] granting
939/// [`perms::Downloader`].
940pub trait Downloader: Send + Sync {
941    /// See [`Bucket::download`].
942    fn download(&self, key: &str) -> impl Future<Output = Result<Vec<u8>, Error>> + Send {
943        self.download_with(key, DownloadOptions::default())
944    }
945
946    /// See [`Bucket::download_with`].
947    fn download_with(
948        &self,
949        key: &str,
950        options: DownloadOptions,
951    ) -> impl Future<Output = Result<Vec<u8>, Error>> + Send;
952
953    /// See [`Bucket::download_stream`].
954    fn download_stream(
955        &self,
956        key: &str,
957        options: DownloadOptions,
958    ) -> impl Future<Output = Result<Download, Error>> + Send;
959}
960
961/// Make signed download URLs. Implemented by a [`BucketRef`] granting
962/// [`perms::SignedDownloader`].
963pub trait SignedDownloader: Send + Sync {
964    /// See [`Bucket::signed_download_url`].
965    fn signed_download_url(
966        &self,
967        key: &str,
968    ) -> impl Future<Output = Result<SignedDownloadUrl, Error>> + Send {
969        self.signed_download_url_with(key, SignedUrlOptions::default())
970    }
971
972    /// See [`Bucket::signed_download_url_with`].
973    fn signed_download_url_with(
974        &self,
975        key: &str,
976        options: SignedUrlOptions,
977    ) -> impl Future<Output = Result<SignedDownloadUrl, Error>> + Send;
978}
979
980/// Read objects' attributes, and whether they exist. Implemented by a
981/// [`BucketRef`] granting [`perms::Attrser`].
982pub trait Attrser: Send + Sync {
983    /// See [`Bucket::exists`].
984    fn exists(&self, key: &str) -> impl Future<Output = Result<bool, Error>> + Send {
985        self.exists_with(key, ExistsOptions::default())
986    }
987
988    /// See [`Bucket::exists_with`].
989    fn exists_with(
990        &self,
991        key: &str,
992        options: ExistsOptions,
993    ) -> impl Future<Output = Result<bool, Error>> + Send;
994
995    /// See [`Bucket::attrs`].
996    fn attrs(&self, key: &str) -> impl Future<Output = Result<ObjectAttrs, Error>> + Send {
997        self.attrs_with(key, AttrsOptions::default())
998    }
999
1000    /// See [`Bucket::attrs_with`].
1001    fn attrs_with(
1002        &self,
1003        key: &str,
1004        options: AttrsOptions,
1005    ) -> impl Future<Output = Result<ObjectAttrs, Error>> + Send;
1006}
1007
1008/// List objects. Implemented by a [`BucketRef`] granting [`perms::Lister`].
1009pub trait Lister: Send + Sync {
1010    /// See [`Bucket::list`].
1011    fn list(
1012        &self,
1013        options: ListOptions,
1014    ) -> impl Future<Output = Result<ListIterator, Error>> + Send;
1015}
1016
1017/// Remove objects. Implemented by a [`BucketRef`] granting [`perms::Remover`].
1018pub trait Remover: Send + Sync {
1019    /// See [`Bucket::remove`].
1020    fn remove(&self, key: &str) -> impl Future<Output = Result<(), Error>> + Send {
1021        self.remove_with(key, RemoveOptions::default())
1022    }
1023
1024    /// See [`Bucket::remove_with`].
1025    fn remove_with(
1026        &self,
1027        key: &str,
1028        options: RemoveOptions,
1029    ) -> impl Future<Output = Result<(), Error>> + Send;
1030}
1031
1032/// Resolve objects' public URLs. Implemented by a [`BucketRef`] granting
1033/// [`perms::PublicUrler`].
1034pub trait PublicUrler: Send + Sync {
1035    /// See [`Bucket::public_url`].
1036    fn public_url(&self, key: &str) -> Result<String, Error>;
1037}
1038
1039/// Every permission but [`PublicUrler`]. Implemented by whatever implements
1040/// them all, such as a [`BucketRef`] granting [`perms::ReadWriter`].
1041pub trait ReadWriter:
1042    Uploader + SignedUploader + Downloader + SignedDownloader + Attrser + Lister + Remover
1043{
1044}
1045
1046impl<T> ReadWriter for T where
1047    T: Uploader + SignedUploader + Downloader + SignedDownloader + Attrser + Lister + Remover
1048{
1049}
1050
1051impl<P: BucketPerms> Uploader for BucketRef<P>
1052where
1053    P::Upload: Granted<perms::Uploader>,
1054{
1055    fn upload_with(
1056        &self,
1057        key: &str,
1058        data: Vec<u8>,
1059        options: UploadOptions,
1060    ) -> impl Future<Output = Result<ObjectAttrs, Error>> + Send {
1061        BucketRef::upload_with(self, key, data, options)
1062    }
1063
1064    fn upload_stream(
1065        &self,
1066        key: &str,
1067        reader: impl AsyncRead + Unpin + Send + Sync + 'static,
1068        options: UploadOptions,
1069    ) -> impl Future<Output = Result<ObjectAttrs, Error>> + Send {
1070        BucketRef::upload_stream(self, key, reader, options)
1071    }
1072}
1073
1074impl<P: BucketPerms> SignedUploader for BucketRef<P>
1075where
1076    P::SignedUpload: Granted<perms::SignedUploader>,
1077{
1078    fn signed_upload_url_with(
1079        &self,
1080        key: &str,
1081        options: SignedUrlOptions,
1082    ) -> impl Future<Output = Result<SignedUploadUrl, Error>> + Send {
1083        BucketRef::signed_upload_url_with(self, key, options)
1084    }
1085}
1086
1087impl<P: BucketPerms> Downloader for BucketRef<P>
1088where
1089    P::Download: Granted<perms::Downloader>,
1090{
1091    fn download_with(
1092        &self,
1093        key: &str,
1094        options: DownloadOptions,
1095    ) -> impl Future<Output = Result<Vec<u8>, Error>> + Send {
1096        BucketRef::download_with(self, key, options)
1097    }
1098
1099    fn download_stream(
1100        &self,
1101        key: &str,
1102        options: DownloadOptions,
1103    ) -> impl Future<Output = Result<Download, Error>> + Send {
1104        BucketRef::download_stream(self, key, options)
1105    }
1106}
1107
1108impl<P: BucketPerms> SignedDownloader for BucketRef<P>
1109where
1110    P::SignedDownload: Granted<perms::SignedDownloader>,
1111{
1112    fn signed_download_url_with(
1113        &self,
1114        key: &str,
1115        options: SignedUrlOptions,
1116    ) -> impl Future<Output = Result<SignedDownloadUrl, Error>> + Send {
1117        BucketRef::signed_download_url_with(self, key, options)
1118    }
1119}
1120
1121impl<P: BucketPerms> Attrser for BucketRef<P>
1122where
1123    P::Attrs: Granted<perms::Attrser>,
1124{
1125    fn exists_with(
1126        &self,
1127        key: &str,
1128        options: ExistsOptions,
1129    ) -> impl Future<Output = Result<bool, Error>> + Send {
1130        BucketRef::exists_with(self, key, options)
1131    }
1132
1133    fn attrs_with(
1134        &self,
1135        key: &str,
1136        options: AttrsOptions,
1137    ) -> impl Future<Output = Result<ObjectAttrs, Error>> + Send {
1138        BucketRef::attrs_with(self, key, options)
1139    }
1140}
1141
1142impl<P: BucketPerms> Lister for BucketRef<P>
1143where
1144    P::List: Granted<perms::Lister>,
1145{
1146    fn list(
1147        &self,
1148        options: ListOptions,
1149    ) -> impl Future<Output = Result<ListIterator, Error>> + Send {
1150        BucketRef::list(self, options)
1151    }
1152}
1153
1154impl<P: BucketPerms> Remover for BucketRef<P>
1155where
1156    P::Remove: Granted<perms::Remover>,
1157{
1158    fn remove_with(
1159        &self,
1160        key: &str,
1161        options: RemoveOptions,
1162    ) -> impl Future<Output = Result<(), Error>> + Send {
1163        BucketRef::remove_with(self, key, options)
1164    }
1165}
1166
1167impl<P: BucketPerms> PublicUrler for BucketRef<P>
1168where
1169    P::PublicUrl: Granted<perms::PublicUrler>,
1170{
1171    fn public_url(&self, key: &str) -> Result<String, Error> {
1172        BucketRef::public_url(self, key)
1173    }
1174}
1175
1176/// Object storage failures are transport problems by default, but the caller's
1177/// own arguments (an empty or out-of-bounds byte range, a malformed version)
1178/// are their fault, not the backend's.
1179fn map_obj_err(err: objects::Error) -> Error {
1180    let code = match &err {
1181        objects::Error::NotFound => ErrCode::NotFound,
1182        objects::Error::PreconditionFailed => ErrCode::FailedPrecondition,
1183        objects::Error::InvalidArgument => ErrCode::InvalidArgument,
1184        objects::Error::Internal(_) => ErrCode::Internal,
1185        objects::Error::Other(_) => ErrCode::Unavailable,
1186    };
1187    Error::wrap(code, err)
1188}
1189
1190#[cfg(test)]
1191mod tests {
1192    use std::collections::VecDeque;
1193
1194    use tokio::io::AsyncReadExt;
1195
1196    use super::*;
1197
1198    /// A stream of what it is given, one item per poll.
1199    struct Items<T>(VecDeque<T>);
1200
1201    impl<T: Unpin> Stream for Items<T> {
1202        type Item = T;
1203
1204        fn poll_next(self: Pin<&mut Self>, _: &mut Context<'_>) -> Poll<Option<T>> {
1205            Poll::Ready(self.get_mut().0.pop_front())
1206        }
1207    }
1208
1209    fn download(chunks: Vec<Result<&'static str, objects::Error>>) -> Download {
1210        let chunks = chunks
1211            .into_iter()
1212            .map(|chunk| chunk.map(Bytes::from))
1213            .collect();
1214        Download {
1215            inner: Box::pin(Items(chunks)),
1216        }
1217    }
1218
1219    #[tokio::test]
1220    async fn a_download_is_read_chunk_by_chunk_whole_or_as_a_reader() {
1221        let mut chunks = download(vec![Ok("hello, "), Ok("world")]);
1222        assert_eq!(chunks.next().await.unwrap().unwrap(), "hello, ");
1223        // The rest, after what was taken.
1224        assert_eq!(chunks.bytes().await.unwrap(), b"world");
1225
1226        let mut read = String::new();
1227        download(vec![Ok("hello, "), Ok(""), Ok("world")])
1228            .into_async_read()
1229            .read_to_string(&mut read)
1230            .await
1231            .unwrap();
1232        assert_eq!(read, "hello, world");
1233    }
1234
1235    #[tokio::test]
1236    async fn a_failed_download_is_an_sdk_error_whichever_way_it_is_read() {
1237        let failing = || download(vec![Ok("hel"), Err(objects::Error::NotFound)]);
1238
1239        let mut chunks = failing();
1240        assert!(chunks.next().await.unwrap().is_ok());
1241        let err = chunks.next().await.unwrap().unwrap_err();
1242        assert_eq!(err.code, ErrCode::NotFound);
1243
1244        assert_eq!(failing().bytes().await.unwrap_err().code, ErrCode::NotFound);
1245
1246        let mut read = Vec::new();
1247        let err = failing()
1248            .into_async_read()
1249            .read_to_end(&mut read)
1250            .await
1251            .unwrap_err();
1252        assert_eq!(read, b"hel");
1253        // The SDK's error is inside the reader's.
1254        let inner = err.get_ref().unwrap().downcast_ref::<Error>().unwrap();
1255        assert_eq!(inner.code, ErrCode::NotFound);
1256    }
1257
1258    #[tokio::test]
1259    async fn a_stream_of_chunks_is_read_as_an_upload() {
1260        let chunks: VecDeque<Result<Vec<u8>, std::io::Error>> =
1261            [Ok(b"hello, ".to_vec()), Ok(b"world".to_vec())].into();
1262        let mut reader =
1263            StreamReader::new(ChunkReader(std::sync::Mutex::new(Box::pin(Items(chunks)))));
1264        // What an upload needs of its reader.
1265        fn uploadable(_: &(impl AsyncRead + Unpin + Send + Sync + 'static)) {}
1266        uploadable(&reader);
1267        let mut read = String::new();
1268        reader.read_to_string(&mut read).await.unwrap();
1269        assert_eq!(read, "hello, world");
1270
1271        // A stream that fails fails the upload, with its own error.
1272        let chunks: VecDeque<Result<Bytes, String>> =
1273            [Ok(Bytes::from("hel")), Err("connection lost".to_string())].into();
1274        let mut reader =
1275            StreamReader::new(ChunkReader(std::sync::Mutex::new(Box::pin(Items(chunks)))));
1276        let err = reader.read_to_end(&mut Vec::new()).await.unwrap_err();
1277        assert!(err.to_string().contains("connection lost"), "{err}");
1278    }
1279}