encore-dev 2.0.0-beta.20

Rust SDK for Encore applications
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
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: 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)),
        },
    }
}

/// The stream's next item.
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));
    // Asking changes nothing of what is read.
    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");
    // 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 = 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)));
    // 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::from(10, Some(20 - 10))));
    // The last bytes are a range too, and the one asked for last is the one.
    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)))));
    // 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>();
}