1use 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
60pub use encore_sdk_core::objects::{
62 AttrsOptions, ByteRange, DeleteOptions as RemoveOptions, DownloadOptions, ExistsOptions,
63 ListEntry, ListOptions, ObjectAttrs, UploadOptions, UploadPreconditions,
64};
65
66pub struct Download {
86 inner: objects::DownloadStream,
87}
88
89impl Download {
90 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 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 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
124struct 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
137pub struct ListIterator {
140 inner: objects::ListIterator,
141}
142
143impl ListIterator {
144 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
160struct 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#[derive(Debug, Clone, PartialEq, Eq)]
189pub struct SignedUploadUrl {
190 pub url: String,
191}
192
193#[derive(Debug, Clone, PartialEq, Eq)]
196pub struct SignedDownloadUrl {
197 pub url: String,
198}
199
200#[derive(Debug, Clone, Copy, Default)]
202pub struct SignedUrlOptions {
203 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
214pub struct Bucket {
216 name: &'static str,
217 #[allow(dead_code)]
219 versioned: bool,
220 #[allow(dead_code)]
221 public: bool,
222}
223
224impl Bucket {
225 pub const fn new(name: &'static str) -> Self {
235 Self {
236 name,
237 versioned: false,
238 public: false,
239 }
240 }
241
242 pub const fn public(mut self) -> Self {
248 self.public = true;
249 self
250 }
251
252 pub const fn versioned(mut self) -> Self {
257 self.versioned = true;
258 self
259 }
260
261 pub const fn named(name: &'static str) -> Self {
272 Self::new(name)
273 }
274
275 pub const fn reference<P: BucketPerms>(&'static self) -> BucketRef<P::Id> {
298 BucketRef {
299 bucket: self,
300 perms: PhantomData,
301 }
302 }
303
304 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 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 pub async fn exists(&self, key: &str) -> Result<bool, Error> {
339 self.exists_with(key, ExistsOptions::default()).await
340 }
341
342 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 pub async fn attrs(&self, key: &str) -> Result<ObjectAttrs, Error> {
350 self.attrs_with(key, AttrsOptions::default()).await
351 }
352
353 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 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 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 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 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 pub async fn download(&self, key: &str) -> Result<Vec<u8>, Error> {
414 self.download_with(key, DownloadOptions::default()).await
415 }
416
417 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 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 pub async fn remove(&self, key: &str) -> Result<(), Error> {
454 self.remove_with(key, RemoveOptions::default()).await
455 }
456
457 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 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 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 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 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 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
522pub 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 perm!(
552 Uploader: Yes, No, No, No, No, No, No, No
554 );
555 perm!(
556 SignedUploader: No, Yes, No, No, No, No, No, No
558 );
559 perm!(
560 Downloader: No, No, Yes, No, No, No, No, No
562 );
563 perm!(
564 SignedDownloader: No, No, No, Yes, No, No, No, No
567 );
568 perm!(
569 Attrser: No, No, No, No, Yes, No, No, No
572 );
573 perm!(
574 Lister: No, No, No, No, No, Yes, No, No
576 );
577 perm!(
578 Remover: No, No, No, No, No, No, Yes, No
580 );
581 perm!(
582 PublicUrler: No, No, No, No, No, No, No, Yes
584 );
585 perm!(
586 ReadWriter: Yes, Yes, Yes, Yes, Yes, Yes, Yes, No
588 );
589}
590
591mod sealed {
592 pub trait Sealed {}
593}
594
595pub trait BucketPerms: sealed::Sealed {
599 #[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
623impl 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
636macro_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
661pub 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 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 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 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 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 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 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 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 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 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 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 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 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 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 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 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 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 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 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 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
874pub trait Uploader: Send + Sync {
877 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 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 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 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
919pub trait SignedUploader: Send + Sync {
922 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 fn signed_upload_url_with(
932 &self,
933 key: &str,
934 options: SignedUrlOptions,
935 ) -> impl Future<Output = Result<SignedUploadUrl, Error>> + Send;
936}
937
938pub trait Downloader: Send + Sync {
941 fn download(&self, key: &str) -> impl Future<Output = Result<Vec<u8>, Error>> + Send {
943 self.download_with(key, DownloadOptions::default())
944 }
945
946 fn download_with(
948 &self,
949 key: &str,
950 options: DownloadOptions,
951 ) -> impl Future<Output = Result<Vec<u8>, Error>> + Send;
952
953 fn download_stream(
955 &self,
956 key: &str,
957 options: DownloadOptions,
958 ) -> impl Future<Output = Result<Download, Error>> + Send;
959}
960
961pub trait SignedDownloader: Send + Sync {
964 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 fn signed_download_url_with(
974 &self,
975 key: &str,
976 options: SignedUrlOptions,
977 ) -> impl Future<Output = Result<SignedDownloadUrl, Error>> + Send;
978}
979
980pub trait Attrser: Send + Sync {
983 fn exists(&self, key: &str) -> impl Future<Output = Result<bool, Error>> + Send {
985 self.exists_with(key, ExistsOptions::default())
986 }
987
988 fn exists_with(
990 &self,
991 key: &str,
992 options: ExistsOptions,
993 ) -> impl Future<Output = Result<bool, Error>> + Send;
994
995 fn attrs(&self, key: &str) -> impl Future<Output = Result<ObjectAttrs, Error>> + Send {
997 self.attrs_with(key, AttrsOptions::default())
998 }
999
1000 fn attrs_with(
1002 &self,
1003 key: &str,
1004 options: AttrsOptions,
1005 ) -> impl Future<Output = Result<ObjectAttrs, Error>> + Send;
1006}
1007
1008pub trait Lister: Send + Sync {
1010 fn list(
1012 &self,
1013 options: ListOptions,
1014 ) -> impl Future<Output = Result<ListIterator, Error>> + Send;
1015}
1016
1017pub trait Remover: Send + Sync {
1019 fn remove(&self, key: &str) -> impl Future<Output = Result<(), Error>> + Send {
1021 self.remove_with(key, RemoveOptions::default())
1022 }
1023
1024 fn remove_with(
1026 &self,
1027 key: &str,
1028 options: RemoveOptions,
1029 ) -> impl Future<Output = Result<(), Error>> + Send;
1030}
1031
1032pub trait PublicUrler: Send + Sync {
1035 fn public_url(&self, key: &str) -> Result<String, Error>;
1037}
1038
1039pub 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
1176fn 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 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 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 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 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 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}