encore-dev 2.0.0-beta.11

Rust SDK for Encore applications
Documentation
use std::collections::{BTreeMap, VecDeque};

use tokio::io::AsyncReadExt;

use super::*;
use crate::perm::Yes;

/// A stream of what it is given, one item per poll.
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, ");
    // The rest, after what was taken.
    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_objects_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!(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");
    // The module's error is inside the reader's.
    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 = |offset, length| ByteRange { offset, length };
    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)));
    // An empty or backwards range is empty, which the core refuses.
    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);
    // Pairs are added, replacing those of the same names.
    assert_eq!(
        upload.metadata,
        BTreeMap::from([
            ("owner".to_string(), "43".to_string()),
            ("source".to_string(), "web".to_string()),
        ])
    );
    assert!(upload.not_exists);

    // An update's metadata replaces the object's: none set is none given.
    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 {
            offset: 10,
            length: Some(20 - 10)
        })
    );
    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)))));
    // What an upload needs of its reader.
    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");

    // A stream that fails fails the upload, with its own error.
    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));

    // An invalid argument says what is wrong.
    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:?}");
        };
        // The core's error itself, shown as it is.
        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:?}");
    // A bucket with no provider is no mistake of the call's.
    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>();
    // So `?` takes it into a boxed error.
    fn boxed() -> Result<(), Box<dyn std::error::Error + Send + Sync>> {
        Err(Error::NotFound)?
    }
    assert_eq!(boxed().unwrap_err().to_string(), "object not found");
}

// Everything a declaration takes, in a `static`.
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));

    // Nothing but the name, by default.
    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);
}

/// Holds when `P` grants uploading and removing over a revision.
fn matches<P: BucketPerms<IfMatchUpload = Yes, IfMatchRemove = Yes>>() {}

/// Holds when `P` grants neither.
fn does_not_match<P: BucketPerms<IfMatchUpload = No, IfMatchRemove = No>>() {}

/// Holds when `P` grants changing attributes.
fn updates<P: BucketPerms<UpdateAttrs = Yes>>() {}

/// Holds when `P` does not.
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)>();
    // Uploading is not changing attributes.
    does_not_update::<(perms::Uploader, perms::Downloader)>();
    does_not_update::<(perms::Attrser, perms::Lister, perms::Remover)>();
    does_not_update::<perms::PublicUrler>();
    // It sets only its own.
    fn only_update<P: BucketPerms<UpdateAttrs = Yes, Upload = No, Attrs = No>>() {}
    only_update::<perms::AttrsUpdater>();
    // A tuple as long as there are permissions.
    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,
    )>();

    // Uploading or removing over a revision: one flag each.
    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>();
}