use std::future::{poll_fn, Future};
use std::marker::PhantomData;
use std::pin::Pin;
use std::task::{Context, Poll};
use std::time::Duration;
use bytes::Bytes;
use encore_sdk_core::objects;
use futures_core::Stream;
use tokio::io::AsyncRead;
use tokio_util::io::StreamReader;
use crate::error::{ErrCode, Error};
use crate::perm::{Flag, Granted, No};
use crate::runtime::core;
pub use encore_sdk_core::objects::{
AttrsOptions, ByteRange, DeleteOptions as RemoveOptions, DownloadOptions, ExistsOptions,
ListEntry, ListOptions, ObjectAttrs, UploadOptions, UploadPreconditions,
};
pub struct Download {
inner: objects::DownloadStream,
}
impl Download {
pub async fn next(&mut self) -> Option<Result<Bytes, Error>> {
poll_fn(|cx| Pin::new(&mut *self).poll_next(cx)).await
}
pub async fn bytes(mut self) -> Result<Vec<u8>, Error> {
let mut bytes = Vec::new();
while let Some(chunk) = self.next().await {
bytes.extend_from_slice(&chunk?);
}
Ok(bytes)
}
pub fn into_async_read(self) -> impl AsyncRead + Unpin + Send + 'static {
StreamReader::new(ChunkErrors(self))
}
}
impl Stream for Download {
type Item = Result<Bytes, Error>;
fn poll_next(self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<Option<Self::Item>> {
self.get_mut()
.inner
.as_mut()
.poll_next(cx)
.map(|chunk| chunk.map(|chunk| chunk.map_err(map_obj_err)))
}
}
struct ChunkErrors(Download);
impl Stream for ChunkErrors {
type Item = std::io::Result<Bytes>;
fn poll_next(self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<Option<Self::Item>> {
Pin::new(&mut self.get_mut().0)
.poll_next(cx)
.map(|chunk| chunk.map(|chunk| chunk.map_err(std::io::Error::other)))
}
}
pub struct ListIterator {
inner: objects::ListIterator,
}
impl ListIterator {
pub async fn next(&mut self) -> Option<Result<ListEntry, Error>> {
poll_fn(|cx| Pin::new(&mut *self).poll_next(cx)).await
}
}
impl Stream for ListIterator {
type Item = Result<ListEntry, Error>;
fn poll_next(self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<Option<Self::Item>> {
Pin::new(&mut self.get_mut().inner)
.poll_next(cx)
.map(|entry| entry.map(|entry| entry.map_err(map_obj_err)))
}
}
struct ChunkReader<S>(std::sync::Mutex<Pin<Box<S>>>);
impl<S, B, E> Stream for ChunkReader<S>
where
S: Stream<Item = Result<B, E>>,
B: Into<Bytes>,
E: Into<Box<dyn std::error::Error + Send + Sync>>,
{
type Item = std::io::Result<Bytes>;
fn poll_next(self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<Option<Self::Item>> {
let stream = self
.get_mut()
.0
.get_mut()
.unwrap_or_else(|e| e.into_inner());
stream
.as_mut()
.poll_next(cx)
.map(|chunk| chunk.map(|chunk| chunk.map(Into::into).map_err(std::io::Error::other)))
}
}
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct SignedUploadUrl {
pub url: String,
}
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct SignedDownloadUrl {
pub url: String,
}
#[derive(Debug, Clone, Copy, Default)]
pub struct SignedUrlOptions {
pub ttl: Option<Duration>,
}
impl SignedUrlOptions {
fn ttl(self) -> Duration {
self.ttl.unwrap_or(Duration::from_secs(60 * 60))
}
}
pub struct Bucket {
name: &'static str,
#[allow(dead_code)]
versioned: bool,
#[allow(dead_code)]
public: bool,
}
impl Bucket {
pub const fn new(name: &'static str) -> Self {
Self {
name,
versioned: false,
public: false,
}
}
pub const fn public(mut self) -> Self {
self.public = true;
self
}
pub const fn versioned(mut self) -> Self {
self.versioned = true;
self
}
pub const fn named(name: &'static str) -> Self {
Self::new(name)
}
pub const fn reference<P: BucketPerms>(&'static self) -> BucketRef<P::Id> {
BucketRef {
bucket: self,
perms: PhantomData,
}
}
fn resolve(&self) -> Result<objects::Bucket, Error> {
if let Some(test) = crate::testing::active()? {
return test.bucket(self.name);
}
core()
.objects()
.bucket(self.name.into())
.ok_or_else(|| Error::not_found(format!("bucket {:?} is not configured", self.name)))
}
fn object(&self, key: &str) -> Result<objects::Object, Error> {
Ok(self.resolve()?.object(key.to_string()))
}
pub async fn list(&self, options: ListOptions) -> Result<ListIterator, Error> {
self.resolve()?
.list(options)
.await
.map(|inner| ListIterator { inner })
.map_err(map_obj_err)
}
pub async fn exists(&self, key: &str) -> Result<bool, Error> {
self.exists_with(key, ExistsOptions::default()).await
}
pub async fn exists_with(&self, key: &str, options: ExistsOptions) -> Result<bool, Error> {
self.object(key)?.exists(options).await.map_err(map_obj_err)
}
pub async fn attrs(&self, key: &str) -> Result<ObjectAttrs, Error> {
self.attrs_with(key, AttrsOptions::default()).await
}
pub async fn attrs_with(&self, key: &str, options: AttrsOptions) -> Result<ObjectAttrs, Error> {
self.object(key)?.attrs(options).await.map_err(map_obj_err)
}
pub async fn upload(&self, key: &str, data: Vec<u8>) -> Result<ObjectAttrs, Error> {
self.upload_with(key, data, UploadOptions::default()).await
}
pub async fn upload_with(
&self,
key: &str,
data: Vec<u8>,
options: UploadOptions,
) -> Result<ObjectAttrs, Error> {
self.upload_stream(key, std::io::Cursor::new(data), options)
.await
}
pub async fn upload_stream(
&self,
key: &str,
reader: impl AsyncRead + Unpin + Send + Sync + 'static,
options: UploadOptions,
) -> Result<ObjectAttrs, Error> {
self.object(key)?
.upload(Box::new(reader), options)
.await
.map_err(map_obj_err)
}
pub async fn upload_chunks<S, B, E>(
&self,
key: &str,
chunks: S,
options: UploadOptions,
) -> Result<ObjectAttrs, Error>
where
S: Stream<Item = Result<B, E>> + Send + 'static,
B: Into<Bytes> + 'static,
E: Into<Box<dyn std::error::Error + Send + Sync>> + 'static,
{
let reader = StreamReader::new(ChunkReader(std::sync::Mutex::new(Box::pin(chunks))));
self.upload_stream(key, reader, options).await
}
pub async fn download(&self, key: &str) -> Result<Vec<u8>, Error> {
self.download_with(key, DownloadOptions::default()).await
}
pub async fn download_with(
&self,
key: &str,
options: DownloadOptions,
) -> Result<Vec<u8>, Error> {
self.object(key)?
.download_all(options)
.await
.map_err(map_obj_err)
}
pub async fn download_stream(
&self,
key: &str,
options: DownloadOptions,
) -> Result<Download, Error> {
self.object(key)?
.download_stream(options)
.await
.map(|inner| Download { inner })
.map_err(map_obj_err)
}
pub async fn remove(&self, key: &str) -> Result<(), Error> {
self.remove_with(key, RemoveOptions::default()).await
}
pub async fn remove_with(&self, key: &str, options: RemoveOptions) -> Result<(), Error> {
self.object(key)?.delete(options).await.map_err(map_obj_err)
}
pub async fn signed_upload_url(&self, key: &str) -> Result<SignedUploadUrl, Error> {
self.signed_upload_url_with(key, SignedUrlOptions::default())
.await
}
pub async fn signed_upload_url_with(
&self,
key: &str,
options: SignedUrlOptions,
) -> Result<SignedUploadUrl, Error> {
self.object(key)?
.signed_upload_url(objects::UploadUrlOptions { ttl: options.ttl() })
.await
.map(|url| SignedUploadUrl { url })
.map_err(map_obj_err)
}
pub async fn signed_download_url(&self, key: &str) -> Result<SignedDownloadUrl, Error> {
self.signed_download_url_with(key, SignedUrlOptions::default())
.await
}
pub async fn signed_download_url_with(
&self,
key: &str,
options: SignedUrlOptions,
) -> Result<SignedDownloadUrl, Error> {
self.object(key)?
.signed_download_url(objects::DownloadUrlOptions { ttl: options.ttl() })
.await
.map(|url| SignedDownloadUrl { url })
.map_err(map_obj_err)
}
pub fn public_url(&self, key: &str) -> Result<String, Error> {
self.object(key)?.public_url().map_err(|err| {
let code = match err {
objects::PublicUrlError::PrivateBucket => ErrCode::FailedPrecondition,
objects::PublicUrlError::InvalidObjectName => ErrCode::InvalidArgument,
objects::PublicUrlError::NoopBucket => ErrCode::Unavailable,
};
Error::wrap(code, err)
})
}
}
pub mod perms {
use super::{sealed::Sealed, BucketPerms};
use crate::perm::{No, Yes};
macro_rules! perm {
($(#[$doc:meta])* $name:ident: $upload:ident, $signed_upload:ident, $download:ident,
$signed_download:ident, $attrs:ident, $list:ident, $remove:ident, $public_url:ident) => {
$(#[$doc])*
pub enum $name {}
impl Sealed for $name {}
impl BucketPerms for $name {
type Id = Self;
type Upload = $upload;
type SignedUpload = $signed_upload;
type Download = $download;
type SignedDownload = $signed_download;
type Attrs = $attrs;
type List = $list;
type Remove = $remove;
type PublicUrl = $public_url;
}
};
}
perm!(
Uploader: Yes, No, No, No, No, No, No, No
);
perm!(
SignedUploader: No, Yes, No, No, No, No, No, No
);
perm!(
Downloader: No, No, Yes, No, No, No, No, No
);
perm!(
SignedDownloader: No, No, No, Yes, No, No, No, No
);
perm!(
Attrser: No, No, No, No, Yes, No, No, No
);
perm!(
Lister: No, No, No, No, No, Yes, No, No
);
perm!(
Remover: No, No, No, No, No, No, Yes, No
);
perm!(
PublicUrler: No, No, No, No, No, No, No, Yes
);
perm!(
ReadWriter: Yes, Yes, Yes, Yes, Yes, Yes, Yes, No
);
}
mod sealed {
pub trait Sealed {}
}
pub trait BucketPerms: sealed::Sealed {
#[doc(hidden)]
type Id: BucketPerms;
#[doc(hidden)]
type Upload: Flag;
#[doc(hidden)]
type SignedUpload: Flag;
#[doc(hidden)]
type Download: Flag;
#[doc(hidden)]
type SignedDownload: Flag;
#[doc(hidden)]
type Attrs: Flag;
#[doc(hidden)]
type List: Flag;
#[doc(hidden)]
type Remove: Flag;
#[doc(hidden)]
type PublicUrl: Flag;
}
impl sealed::Sealed for () {}
impl BucketPerms for () {
type Id = Self;
type Upload = No;
type SignedUpload = No;
type Download = No;
type SignedDownload = No;
type Attrs = No;
type List = No;
type Remove = No;
type PublicUrl = No;
}
macro_rules! tuple_perms {
() => {};
($first:ident $(, $rest:ident)*) => {
impl<$first: BucketPerms, $($rest: BucketPerms),*> sealed::Sealed for ($first, $($rest,)*) {}
impl<$first: BucketPerms, $($rest: BucketPerms),*> BucketPerms for ($first, $($rest,)*) {
type Id = Self;
type Upload = <$first::Upload as Flag>::Or<<($($rest,)*) as BucketPerms>::Upload>;
type SignedUpload =
<$first::SignedUpload as Flag>::Or<<($($rest,)*) as BucketPerms>::SignedUpload>;
type Download = <$first::Download as Flag>::Or<<($($rest,)*) as BucketPerms>::Download>;
type SignedDownload =
<$first::SignedDownload as Flag>::Or<<($($rest,)*) as BucketPerms>::SignedDownload>;
type Attrs = <$first::Attrs as Flag>::Or<<($($rest,)*) as BucketPerms>::Attrs>;
type List = <$first::List as Flag>::Or<<($($rest,)*) as BucketPerms>::List>;
type Remove = <$first::Remove as Flag>::Or<<($($rest,)*) as BucketPerms>::Remove>;
type PublicUrl =
<$first::PublicUrl as Flag>::Or<<($($rest,)*) as BucketPerms>::PublicUrl>;
}
tuple_perms!($($rest),*);
};
}
tuple_perms!(A, B, C, D, E, F, G, H, I);
pub struct BucketRef<P> {
bucket: &'static Bucket,
perms: PhantomData<fn() -> P>,
}
impl<P> Clone for BucketRef<P> {
fn clone(&self) -> Self {
*self
}
}
impl<P> Copy for BucketRef<P> {}
impl<P: BucketPerms> BucketRef<P> {
pub async fn list(&self, options: ListOptions) -> Result<ListIterator, Error>
where
P::List: Granted<perms::Lister>,
{
self.bucket.list(options).await
}
pub async fn exists(&self, key: &str) -> Result<bool, Error>
where
P::Attrs: Granted<perms::Attrser>,
{
self.bucket.exists(key).await
}
pub async fn exists_with(&self, key: &str, options: ExistsOptions) -> Result<bool, Error>
where
P::Attrs: Granted<perms::Attrser>,
{
self.bucket.exists_with(key, options).await
}
pub async fn attrs(&self, key: &str) -> Result<ObjectAttrs, Error>
where
P::Attrs: Granted<perms::Attrser>,
{
self.bucket.attrs(key).await
}
pub async fn attrs_with(&self, key: &str, options: AttrsOptions) -> Result<ObjectAttrs, Error>
where
P::Attrs: Granted<perms::Attrser>,
{
self.bucket.attrs_with(key, options).await
}
pub async fn upload(&self, key: &str, data: Vec<u8>) -> Result<ObjectAttrs, Error>
where
P::Upload: Granted<perms::Uploader>,
{
self.bucket.upload(key, data).await
}
pub async fn upload_with(
&self,
key: &str,
data: Vec<u8>,
options: UploadOptions,
) -> Result<ObjectAttrs, Error>
where
P::Upload: Granted<perms::Uploader>,
{
self.bucket.upload_with(key, data, options).await
}
pub async fn upload_stream(
&self,
key: &str,
reader: impl AsyncRead + Unpin + Send + Sync + 'static,
options: UploadOptions,
) -> Result<ObjectAttrs, Error>
where
P::Upload: Granted<perms::Uploader>,
{
self.bucket.upload_stream(key, reader, options).await
}
pub async fn upload_chunks<S, B, E>(
&self,
key: &str,
chunks: S,
options: UploadOptions,
) -> Result<ObjectAttrs, Error>
where
P::Upload: Granted<perms::Uploader>,
S: Stream<Item = Result<B, E>> + Send + 'static,
B: Into<Bytes> + 'static,
E: Into<Box<dyn std::error::Error + Send + Sync>> + 'static,
{
self.bucket.upload_chunks(key, chunks, options).await
}
pub async fn download(&self, key: &str) -> Result<Vec<u8>, Error>
where
P::Download: Granted<perms::Downloader>,
{
self.bucket.download(key).await
}
pub async fn download_with(&self, key: &str, options: DownloadOptions) -> Result<Vec<u8>, Error>
where
P::Download: Granted<perms::Downloader>,
{
self.bucket.download_with(key, options).await
}
pub async fn download_stream(
&self,
key: &str,
options: DownloadOptions,
) -> Result<Download, Error>
where
P::Download: Granted<perms::Downloader>,
{
self.bucket.download_stream(key, options).await
}
pub async fn remove(&self, key: &str) -> Result<(), Error>
where
P::Remove: Granted<perms::Remover>,
{
self.bucket.remove(key).await
}
pub async fn remove_with(&self, key: &str, options: RemoveOptions) -> Result<(), Error>
where
P::Remove: Granted<perms::Remover>,
{
self.bucket.remove_with(key, options).await
}
pub async fn signed_upload_url(&self, key: &str) -> Result<SignedUploadUrl, Error>
where
P::SignedUpload: Granted<perms::SignedUploader>,
{
self.bucket.signed_upload_url(key).await
}
pub async fn signed_upload_url_with(
&self,
key: &str,
options: SignedUrlOptions,
) -> Result<SignedUploadUrl, Error>
where
P::SignedUpload: Granted<perms::SignedUploader>,
{
self.bucket.signed_upload_url_with(key, options).await
}
pub async fn signed_download_url(&self, key: &str) -> Result<SignedDownloadUrl, Error>
where
P::SignedDownload: Granted<perms::SignedDownloader>,
{
self.bucket.signed_download_url(key).await
}
pub async fn signed_download_url_with(
&self,
key: &str,
options: SignedUrlOptions,
) -> Result<SignedDownloadUrl, Error>
where
P::SignedDownload: Granted<perms::SignedDownloader>,
{
self.bucket.signed_download_url_with(key, options).await
}
pub fn public_url(&self, key: &str) -> Result<String, Error>
where
P::PublicUrl: Granted<perms::PublicUrler>,
{
self.bucket.public_url(key)
}
}
pub trait Uploader: Send + Sync {
fn upload(
&self,
key: &str,
data: Vec<u8>,
) -> impl Future<Output = Result<ObjectAttrs, Error>> + Send {
self.upload_with(key, data, UploadOptions::default())
}
fn upload_with(
&self,
key: &str,
data: Vec<u8>,
options: UploadOptions,
) -> impl Future<Output = Result<ObjectAttrs, Error>> + Send;
fn upload_stream(
&self,
key: &str,
reader: impl AsyncRead + Unpin + Send + Sync + 'static,
options: UploadOptions,
) -> impl Future<Output = Result<ObjectAttrs, Error>> + Send;
fn upload_chunks<S, B, E>(
&self,
key: &str,
chunks: S,
options: UploadOptions,
) -> impl Future<Output = Result<ObjectAttrs, Error>> + Send
where
S: Stream<Item = Result<B, E>> + Send + 'static,
B: Into<Bytes> + 'static,
E: Into<Box<dyn std::error::Error + Send + Sync>> + 'static,
{
let reader = StreamReader::new(ChunkReader(std::sync::Mutex::new(Box::pin(chunks))));
self.upload_stream(key, reader, options)
}
}
pub trait SignedUploader: Send + Sync {
fn signed_upload_url(
&self,
key: &str,
) -> impl Future<Output = Result<SignedUploadUrl, Error>> + Send {
self.signed_upload_url_with(key, SignedUrlOptions::default())
}
fn signed_upload_url_with(
&self,
key: &str,
options: SignedUrlOptions,
) -> impl Future<Output = Result<SignedUploadUrl, Error>> + Send;
}
pub trait Downloader: Send + Sync {
fn download(&self, key: &str) -> impl Future<Output = Result<Vec<u8>, Error>> + Send {
self.download_with(key, DownloadOptions::default())
}
fn download_with(
&self,
key: &str,
options: DownloadOptions,
) -> impl Future<Output = Result<Vec<u8>, Error>> + Send;
fn download_stream(
&self,
key: &str,
options: DownloadOptions,
) -> impl Future<Output = Result<Download, Error>> + Send;
}
pub trait SignedDownloader: Send + Sync {
fn signed_download_url(
&self,
key: &str,
) -> impl Future<Output = Result<SignedDownloadUrl, Error>> + Send {
self.signed_download_url_with(key, SignedUrlOptions::default())
}
fn signed_download_url_with(
&self,
key: &str,
options: SignedUrlOptions,
) -> impl Future<Output = Result<SignedDownloadUrl, Error>> + Send;
}
pub trait Attrser: Send + Sync {
fn exists(&self, key: &str) -> impl Future<Output = Result<bool, Error>> + Send {
self.exists_with(key, ExistsOptions::default())
}
fn exists_with(
&self,
key: &str,
options: ExistsOptions,
) -> impl Future<Output = Result<bool, Error>> + Send;
fn attrs(&self, key: &str) -> impl Future<Output = Result<ObjectAttrs, Error>> + Send {
self.attrs_with(key, AttrsOptions::default())
}
fn attrs_with(
&self,
key: &str,
options: AttrsOptions,
) -> impl Future<Output = Result<ObjectAttrs, Error>> + Send;
}
pub trait Lister: Send + Sync {
fn list(
&self,
options: ListOptions,
) -> impl Future<Output = Result<ListIterator, Error>> + Send;
}
pub trait Remover: Send + Sync {
fn remove(&self, key: &str) -> impl Future<Output = Result<(), Error>> + Send {
self.remove_with(key, RemoveOptions::default())
}
fn remove_with(
&self,
key: &str,
options: RemoveOptions,
) -> impl Future<Output = Result<(), Error>> + Send;
}
pub trait PublicUrler: Send + Sync {
fn public_url(&self, key: &str) -> Result<String, Error>;
}
pub trait ReadWriter:
Uploader + SignedUploader + Downloader + SignedDownloader + Attrser + Lister + Remover
{
}
impl<T> ReadWriter for T where
T: Uploader + SignedUploader + Downloader + SignedDownloader + Attrser + Lister + Remover
{
}
impl<P: BucketPerms> Uploader for BucketRef<P>
where
P::Upload: Granted<perms::Uploader>,
{
fn upload_with(
&self,
key: &str,
data: Vec<u8>,
options: UploadOptions,
) -> impl Future<Output = Result<ObjectAttrs, Error>> + Send {
BucketRef::upload_with(self, key, data, options)
}
fn upload_stream(
&self,
key: &str,
reader: impl AsyncRead + Unpin + Send + Sync + 'static,
options: UploadOptions,
) -> impl Future<Output = Result<ObjectAttrs, Error>> + Send {
BucketRef::upload_stream(self, key, reader, options)
}
}
impl<P: BucketPerms> SignedUploader for BucketRef<P>
where
P::SignedUpload: Granted<perms::SignedUploader>,
{
fn signed_upload_url_with(
&self,
key: &str,
options: SignedUrlOptions,
) -> impl Future<Output = Result<SignedUploadUrl, Error>> + Send {
BucketRef::signed_upload_url_with(self, key, options)
}
}
impl<P: BucketPerms> Downloader for BucketRef<P>
where
P::Download: Granted<perms::Downloader>,
{
fn download_with(
&self,
key: &str,
options: DownloadOptions,
) -> impl Future<Output = Result<Vec<u8>, Error>> + Send {
BucketRef::download_with(self, key, options)
}
fn download_stream(
&self,
key: &str,
options: DownloadOptions,
) -> impl Future<Output = Result<Download, Error>> + Send {
BucketRef::download_stream(self, key, options)
}
}
impl<P: BucketPerms> SignedDownloader for BucketRef<P>
where
P::SignedDownload: Granted<perms::SignedDownloader>,
{
fn signed_download_url_with(
&self,
key: &str,
options: SignedUrlOptions,
) -> impl Future<Output = Result<SignedDownloadUrl, Error>> + Send {
BucketRef::signed_download_url_with(self, key, options)
}
}
impl<P: BucketPerms> Attrser for BucketRef<P>
where
P::Attrs: Granted<perms::Attrser>,
{
fn exists_with(
&self,
key: &str,
options: ExistsOptions,
) -> impl Future<Output = Result<bool, Error>> + Send {
BucketRef::exists_with(self, key, options)
}
fn attrs_with(
&self,
key: &str,
options: AttrsOptions,
) -> impl Future<Output = Result<ObjectAttrs, Error>> + Send {
BucketRef::attrs_with(self, key, options)
}
}
impl<P: BucketPerms> Lister for BucketRef<P>
where
P::List: Granted<perms::Lister>,
{
fn list(
&self,
options: ListOptions,
) -> impl Future<Output = Result<ListIterator, Error>> + Send {
BucketRef::list(self, options)
}
}
impl<P: BucketPerms> Remover for BucketRef<P>
where
P::Remove: Granted<perms::Remover>,
{
fn remove_with(
&self,
key: &str,
options: RemoveOptions,
) -> impl Future<Output = Result<(), Error>> + Send {
BucketRef::remove_with(self, key, options)
}
}
impl<P: BucketPerms> PublicUrler for BucketRef<P>
where
P::PublicUrl: Granted<perms::PublicUrler>,
{
fn public_url(&self, key: &str) -> Result<String, Error> {
BucketRef::public_url(self, key)
}
}
fn map_obj_err(err: objects::Error) -> Error {
let code = match &err {
objects::Error::NotFound => ErrCode::NotFound,
objects::Error::PreconditionFailed => ErrCode::FailedPrecondition,
objects::Error::InvalidArgument => ErrCode::InvalidArgument,
objects::Error::Internal(_) => ErrCode::Internal,
objects::Error::Other(_) => ErrCode::Unavailable,
};
Error::wrap(code, err)
}
#[cfg(test)]
mod tests {
use std::collections::VecDeque;
use tokio::io::AsyncReadExt;
use super::*;
struct Items<T>(VecDeque<T>);
impl<T: Unpin> Stream for Items<T> {
type Item = T;
fn poll_next(self: Pin<&mut Self>, _: &mut Context<'_>) -> Poll<Option<T>> {
Poll::Ready(self.get_mut().0.pop_front())
}
}
fn download(chunks: Vec<Result<&'static str, objects::Error>>) -> Download {
let chunks = chunks
.into_iter()
.map(|chunk| chunk.map(Bytes::from))
.collect();
Download {
inner: Box::pin(Items(chunks)),
}
}
#[tokio::test]
async fn a_download_is_read_chunk_by_chunk_whole_or_as_a_reader() {
let mut chunks = download(vec![Ok("hello, "), Ok("world")]);
assert_eq!(chunks.next().await.unwrap().unwrap(), "hello, ");
assert_eq!(chunks.bytes().await.unwrap(), b"world");
let mut read = String::new();
download(vec![Ok("hello, "), Ok(""), Ok("world")])
.into_async_read()
.read_to_string(&mut read)
.await
.unwrap();
assert_eq!(read, "hello, world");
}
#[tokio::test]
async fn a_failed_download_is_an_sdk_error_whichever_way_it_is_read() {
let failing = || download(vec![Ok("hel"), Err(objects::Error::NotFound)]);
let mut chunks = failing();
assert!(chunks.next().await.unwrap().is_ok());
let err = chunks.next().await.unwrap().unwrap_err();
assert_eq!(err.code, ErrCode::NotFound);
assert_eq!(failing().bytes().await.unwrap_err().code, ErrCode::NotFound);
let mut read = Vec::new();
let err = failing()
.into_async_read()
.read_to_end(&mut read)
.await
.unwrap_err();
assert_eq!(read, b"hel");
let inner = err.get_ref().unwrap().downcast_ref::<Error>().unwrap();
assert_eq!(inner.code, ErrCode::NotFound);
}
#[tokio::test]
async fn a_stream_of_chunks_is_read_as_an_upload() {
let chunks: VecDeque<Result<Vec<u8>, std::io::Error>> =
[Ok(b"hello, ".to_vec()), Ok(b"world".to_vec())].into();
let mut reader =
StreamReader::new(ChunkReader(std::sync::Mutex::new(Box::pin(Items(chunks)))));
fn uploadable(_: &(impl AsyncRead + Unpin + Send + Sync + 'static)) {}
uploadable(&reader);
let mut read = String::new();
reader.read_to_string(&mut read).await.unwrap();
assert_eq!(read, "hello, world");
let chunks: VecDeque<Result<Bytes, String>> =
[Ok(Bytes::from("hel")), Err("connection lost".to_string())].into();
let mut reader =
StreamReader::new(ChunkReader(std::sync::Mutex::new(Box::pin(Items(chunks)))));
let err = reader.read_to_end(&mut Vec::new()).await.unwrap_err();
assert!(err.to_string().contains("connection lost"), "{err}");
}
}