use std::collections::{BTreeMap, VecDeque};
use tokio::io::AsyncReadExt;
use super::*;
use crate::perm::Yes;
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: VecDeque<Result<Bytes, objects::Error>> = chunks
.into_iter()
.map(|chunk| chunk.map(Bytes::from))
.collect();
Download {
inner: objects::Download {
info: objects::DownloadInfo {
revision: Revision::from_parts("etag".into(), Some("7".into())),
size: 100,
content_type: Some("text/plain".into()),
last_modified: Some(SystemTime::UNIX_EPOCH),
},
length: 12,
stream: Box::pin(Items(chunks)),
},
}
}
async fn next<S: Stream + Unpin>(stream: &mut S) -> Option<S::Item> {
poll_fn(|cx| Pin::new(&mut *stream).poll_next(cx)).await
}
#[tokio::test]
async fn a_download_is_read_whole_chunk_by_chunk_or_as_a_reader() {
assert_eq!(
download(vec![Ok("hello, "), Ok("world")])
.bytes()
.await
.unwrap(),
b"hello, world"
);
let mut chunks = download(vec![Ok("hello, "), Ok("world")]).bytes_stream();
assert_eq!(next(&mut chunks).await.unwrap().unwrap(), "hello, ");
assert_eq!(next(&mut chunks).await.unwrap().unwrap(), "world");
assert!(next(&mut chunks).await.is_none());
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_download_says_what_the_provider_said_of_the_object() {
let read = download(vec![Ok("hello, "), Ok("world")]);
assert_eq!(
read.revision(),
Revision::from_parts("etag".into(), Some("7".into()))
);
assert_eq!(read.size(), 100);
assert_eq!(read.content_type(), Some("text/plain"));
assert_eq!(read.last_modified(), Some(SystemTime::UNIX_EPOCH));
assert_eq!(read.bytes().await.unwrap(), b"hello, world");
}
#[tokio::test]
async fn a_fakes_download_is_an_objects_contents_and_attributes() {
let attrs = ObjectAttrs {
name: "a.txt".into(),
version: Some("3".into()),
size: 5,
content_type: Some("text/plain".into()),
etag: "abc".into(),
cache_control: None,
content_disposition: None,
metadata: BTreeMap::new(),
last_modified: Some(SystemTime::UNIX_EPOCH),
storage_class: None,
retain_until: None,
};
let read = Download::of(&attrs, "hello");
assert_eq!(read.revision(), attrs.revision());
assert_eq!((read.size(), read.content_type()), (5, Some("text/plain")));
assert_eq!(read.last_modified(), Some(SystemTime::UNIX_EPOCH));
assert_eq!(read.bytes().await.unwrap(), b"hello");
let mut chunks = Download::of(&attrs, &b"hello"[..]).bytes_stream();
assert_eq!(next(&mut chunks).await.unwrap().unwrap(), "hello");
assert!(next(&mut chunks).await.is_none());
}
#[tokio::test]
async fn a_failed_download_is_an_objects_error_whichever_way_it_is_read() {
let failing = || download(vec![Ok("hel"), Err(objects::Error::NotFound)]);
let mut chunks = failing().bytes_stream();
assert!(next(&mut chunks).await.unwrap().is_ok());
let err = next(&mut chunks).await.unwrap().unwrap_err();
assert!(matches!(err, Error::NotFound), "{err:?}");
assert!(matches!(
failing().bytes().await.unwrap_err(),
Error::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!(matches!(inner, Error::NotFound), "{inner:?}");
}
#[tokio::test]
async fn an_upload_body_is_bytes_a_reader_or_chunks() {
async fn read(body: impl Into<UploadBody>) -> String {
let mut read = String::new();
body.into()
.into_async_read()
.read_to_string(&mut read)
.await
.unwrap();
read
}
assert_eq!(read(b"bytes".to_vec()).await, "bytes");
assert_eq!(read(Bytes::from("bytes")).await, "bytes");
assert_eq!(read(&b"static"[..]).await, "static");
assert_eq!(read("text".to_string()).await, "text");
assert_eq!(read(UploadBody::reader(&b"reader"[..])).await, "reader");
let chunks: VecDeque<Result<&'static str, std::io::Error>> = [Ok("chu"), Ok("nks")].into();
assert_eq!(read(UploadBody::chunks(Items(chunks))).await, "chunks");
}
#[test]
fn a_rust_range_is_the_byte_range_it_spans() {
let range = ByteRange::from;
assert_eq!(byte_range(1024..1280), range(1024, Some(256)));
assert_eq!(byte_range(1024..=1279), range(1024, Some(256)));
assert_eq!(byte_range(1024..), range(1024, None));
assert_eq!(byte_range(..100), range(0, Some(100)));
assert_eq!(byte_range(..=99), range(0, Some(100)));
assert_eq!(byte_range(..), range(0, None));
assert_eq!(byte_range(0..=u64::MAX), range(0, Some(u64::MAX)));
assert_eq!(byte_range(5..5), range(5, Some(0)));
#[allow(clippy::reversed_empty_ranges)]
let backwards = [byte_range(5..3), byte_range(5..=3)];
assert_eq!(backwards, [range(5, Some(0)); 2]);
}
#[test]
fn a_request_collects_its_options() {
static BUCKET: Bucket = Bucket::named("uploads");
let upload = BUCKET
.upload("a.pdf", b"%PDF".to_vec())
.content_type("application/pdf")
.metadata([("owner", "42"), ("source", "web")])
.metadata([("owner".to_string(), "43".to_string())])
.not_exists();
assert_eq!(upload.key, "a.pdf");
assert_eq!(upload.content_type.as_deref(), Some("application/pdf"));
assert_eq!(upload.cache_control, None);
assert_eq!(
upload.metadata,
BTreeMap::from([
("owner".to_string(), "43".to_string()),
("source".to_string(), "web".to_string()),
])
);
assert!(upload.not_exists);
assert_eq!(BUCKET.update_attrs("a").metadata, None);
let cleared = BUCKET
.update_attrs("a")
.metadata(std::iter::empty::<(String, String)>());
assert_eq!(cleared.metadata, Some(BTreeMap::new()));
let download = BUCKET.download("a").version("7").range(10..20);
assert_eq!(download.version.as_deref(), Some("7"));
assert_eq!(download.range, Some(ByteRange::from(10, Some(20 - 10))));
let tail = BUCKET.download("a").range(10..20).last(64);
assert_eq!(tail.range, Some(ByteRange::last(64)));
assert_eq!(
BUCKET.download("a").last(64).range(..8).range,
Some(ByteRange::from(0, Some(8)))
);
let list = BUCKET.list().prefix("2026/").delimiter("/").limit(100);
assert_eq!(
(
list.prefix.as_deref(),
list.delimiter.as_deref(),
list.limit
),
(Some("2026/"), Some("/"), Some(100))
);
let url = BUCKET.signed_upload_url("a").ttl(Duration::from_secs(60));
assert_eq!(url.ttl, Some(Duration::from_secs(60)));
}
#[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}");
}
#[test]
fn the_cores_errors_keep_their_kind() {
assert!(matches!(obj_err(objects::Error::NotFound), Error::NotFound));
assert!(matches!(
obj_err(objects::Error::PreconditionFailed),
Error::PreconditionFailed
));
assert!(matches!(obj_err(objects::Error::Retained), Error::Retained));
let err = obj_err(objects::Error::InvalidArgument(
"metadata is 3.1 KiB; S3 buckets allow 2 KiB".into(),
));
let Error::InvalidArgument(message) = &err else {
panic!("{err:?}");
};
assert_eq!(message, "metadata is 3.1 KiB; S3 buckets allow 2 KiB");
assert_eq!(
err.to_string(),
"invalid argument: metadata is 3.1 KiB; S3 buckets allow 2 KiB"
);
}
#[test]
fn the_cores_internal_and_other_errors_are_other_and_keep_it() {
for core_err in [
objects::Error::Internal(anyhow::anyhow!("token expired")),
objects::Error::Other(anyhow::anyhow!("connection reset")),
] {
let shown = core_err.to_string();
let err = obj_err(core_err);
let Error::Other(inner) = &err else {
panic!("{err:?}");
};
assert!(
inner.downcast_ref::<objects::Error>().is_some(),
"{inner:?}"
);
assert_eq!(err.to_string(), shown);
}
}
#[test]
fn a_public_url_that_cannot_be_is_an_invalid_argument() {
let err = public_url_err(objects::PublicUrlError::PrivateBucket);
assert!(
matches!(&err, Error::InvalidArgument(m) if m == "bucket is not public"),
"{err:?}"
);
let err = public_url_err(objects::PublicUrlError::InvalidObjectName);
assert!(matches!(err, Error::InvalidArgument(_)), "{err:?}");
let err = public_url_err(objects::PublicUrlError::NoopBucket);
assert!(matches!(err, Error::Other(_)), "{err:?}");
}
#[test]
fn the_error_is_a_std_error_that_crosses_threads() {
fn std_error<E: std::error::Error + Send + Sync + 'static>() {}
std_error::<Error>();
fn boxed() -> Result<(), Box<dyn std::error::Error + Send + Sync>> {
Err(Error::NotFound)?
}
assert_eq!(boxed().unwrap_err().to_string(), "object not found");
}
static DECLARED: Bucket = Bucket::new("uploads")
.versioned()
.public()
.storage_class(StorageClass::Auto)
.lifecycle(&[
LifecycleRule::new().prefix("tmp/").delete_after_days(1),
LifecycleRule::new()
.prefix("logs/")
.move_to_infrequent_after_days(30)
.move_to_cold_after_days(90)
.delete_after_days(365),
LifecycleRule::new()
.delete_noncurrent_after_days(30)
.keep_noncurrent_versions(5),
])
.retention(Retention::days(2555))
.object_retention();
#[test]
fn a_declaration_records_its_options() {
assert!(DECLARED.versioned && DECLARED.public && DECLARED.object_retention);
assert_eq!(DECLARED.storage_class, Some(StorageClass::Auto));
assert_eq!(DECLARED.retention, Some(Retention::days(2555)));
let [tmp, logs, noncurrent] = DECLARED.lifecycle else {
panic!("{:?}", DECLARED.lifecycle);
};
assert_eq!(tmp.prefix, Some("tmp/"));
assert_eq!(tmp.delete_after_days, Some(1));
assert_eq!(tmp.move_to_infrequent_after_days, None);
assert_eq!(logs.move_to_infrequent_after_days, Some(30));
assert_eq!(logs.move_to_cold_after_days, Some(90));
assert_eq!(logs.delete_after_days, Some(365));
assert_eq!(noncurrent.prefix, None);
assert_eq!(noncurrent.delete_noncurrent_after_days, Some(30));
assert_eq!(noncurrent.keep_noncurrent_versions, Some(5));
let plain = Bucket::new("plain");
assert!(!plain.versioned && !plain.public && !plain.object_retention);
assert_eq!(plain.storage_class, None);
assert!(plain.lifecycle.is_empty());
assert_eq!(plain.retention, None);
}
fn matches<P: BucketPerms<IfMatchUpload = Yes, IfMatchRemove = Yes>>() {}
fn does_not_match<P: BucketPerms<IfMatchUpload = No, IfMatchRemove = No>>() {}
fn updates<P: BucketPerms<UpdateAttrs = Yes>>() {}
fn does_not_update<P: BucketPerms<UpdateAttrs = No>>() {}
#[test]
fn the_new_permissions_are_their_own_flags() {
updates::<perms::ReadWriter>();
updates::<perms::AttrsUpdater>();
updates::<(perms::Lister, perms::AttrsUpdater)>();
does_not_update::<(perms::Uploader, perms::Downloader)>();
does_not_update::<(perms::Attrser, perms::Lister, perms::Remover)>();
does_not_update::<perms::PublicUrler>();
fn only_update<P: BucketPerms<UpdateAttrs = Yes, Upload = No, Attrs = No>>() {}
only_update::<perms::AttrsUpdater>();
updates::<(
perms::Uploader,
perms::SignedUploader,
perms::Downloader,
perms::SignedDownloader,
perms::Attrser,
perms::Lister,
perms::Remover,
perms::PublicUrler,
perms::AttrsUpdater,
perms::IfMatchUploader,
perms::IfMatchRemover,
perms::ReadWriter,
)>();
matches::<perms::ReadWriter>();
matches::<(perms::IfMatchUploader, perms::IfMatchRemover)>();
does_not_match::<(perms::Uploader, perms::Remover, perms::Attrser)>();
fn only_upload_if_match<
P: BucketPerms<IfMatchUpload = Yes, IfMatchRemove = No, Upload = No, Attrs = No>,
>() {
}
only_upload_if_match::<perms::IfMatchUploader>();
fn only_remove_if_match<
P: BucketPerms<IfMatchRemove = Yes, IfMatchUpload = No, Remove = No, Attrs = No>,
>() {
}
only_remove_if_match::<perms::IfMatchRemover>();
}