encore-dev 2.0.0-beta.18

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
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
//! Bucket operations through a real runtime, against the GCS emulator
//! `encore run` serves buckets from: what the SDK hands the core, and what
//! comes back, errors included.
//!
//! The emulator runs in this process, so the tests need nothing outside it.
//! They share it, and one runtime, so each works under keys of its own.

use std::collections::BTreeMap;
use std::future::Future;
use std::sync::OnceLock;
use std::time::{Duration, SystemTime};

use encore::objects::{perms, Bucket, Download, Error, ListEntry, ObjectVersion, StorageClass};
use encore_runtimecfg::pb;

/// Versioned.
static UPLOADS: Bucket = Bucket::named("uploads");
static ARCHIVE: Bucket = Bucket::named("archive");
/// With object retention.
static EVIDENCE: Bucket = Bucket::named("evidence");

/// Runs `f` on the runtime the emulator serves from, which every test shares:
/// the core's provider clients keep connections on the runtime that opened
/// them.
fn run<F: Future>(f: F) -> F::Output {
    static RUNTIME: OnceLock<tokio::runtime::Runtime> = OnceLock::new();
    let rt = RUNTIME.get_or_init(|| {
        let rt = tokio::runtime::Builder::new_multi_thread()
            .enable_all()
            .build()
            .expect("runtime");
        let endpoint = rt.block_on(start_emulator());
        configure(&endpoint);
        rt
    });
    rt.block_on(f)
}

async fn start_emulator() -> String {
    use encore_infra_emu::gcs::{Options, Server};
    let server = Server::start(Options::default()).await.expect("emulator");
    let emu = server.emu();
    for bucket in ["uploads", "archive"] {
        emu.init_bucket(bucket).await.expect("bucket");
    }
    emu.store()
        .set_versioning("uploads", true)
        .await
        .expect("versioning");
    let settings = encore_infra_emu::gcs::BucketSettings {
        object_retention: Some(encore_infra_emu::gcs::ObjectRetentionConfig::enabled()),
        ..Default::default()
    };
    emu.store()
        .set_bucket_settings("evidence", settings)
        .await
        .expect("object retention");
    let endpoint = server.endpoint();
    // Serves until the process exits.
    std::mem::forget(server);
    endpoint
}

/// Points the runtime at the emulator, before anything starts it.
fn configure(endpoint: &str) {
    let bucket = |name: &str, versioned: bool| pb::Bucket {
        rid: name.into(),
        encore_name: name.into(),
        cloud_name: name.into(),
        versioned: Some(versioned),
        ..Default::default()
    };
    let cfg = pb::RuntimeConfig {
        environment: Some(pb::Environment {
            app_id: "app".into(),
            env_name: "local".into(),
            ..Default::default()
        }),
        deployment: Some(pb::Deployment {
            hosted_services: vec![pb::HostedService {
                name: "svc".into(),
                ..Default::default()
            }],
            ..Default::default()
        }),
        infra: Some(pb::Infrastructure {
            resources: Some(pb::infrastructure::Resources {
                bucket_clusters: vec![pb::BucketCluster {
                    rid: "emulator".into(),
                    buckets: vec![
                        bucket("uploads", true),
                        bucket("archive", false),
                        bucket("evidence", false),
                    ],
                    provider: Some(pb::bucket_cluster::Provider::Gcs(pb::bucket_cluster::Gcs {
                        endpoint: Some(endpoint.into()),
                        anonymous: true,
                        local_sign: None,
                    })),
                }],
                ..Default::default()
            }),
            ..Default::default()
        }),
        ..Default::default()
    };
    std::env::set_var(
        "ENCORE_RUNTIME_CONFIG",
        encore_runtimecfg::encoding::encode_env_value(&cfg),
    );
}

async fn entries(bucket: &Bucket, prefix: &str, delimiter: &str) -> Vec<ListEntry> {
    let mut it = bucket
        .list()
        .prefix(prefix)
        .delimiter(delimiter)
        .await
        .expect("list");
    let mut entries = Vec::new();
    while let Some(entry) = it.next().await {
        entries.push(entry.expect("entry"));
    }
    entries
}

async fn versions(bucket: &Bucket, prefix: &str) -> Vec<ObjectVersion> {
    let mut it = bucket
        .list_versions()
        .prefix(prefix)
        .await
        .expect("list versions");
    let mut versions = Vec::new();
    while let Some(version) = it.next().await {
        versions.push(version.expect("version"));
    }
    versions
}

#[test]
fn attributes_are_written_with_an_upload_and_changed_later() {
    run(async {
        let attrs = UPLOADS
            .upload("attrs/a.pdf", b"%PDF".to_vec())
            .content_type("application/pdf")
            .cache_control("public, max-age=3600")
            .content_disposition(r#"attachment; filename="a.pdf""#)
            .metadata([("owner", "42")])
            .await
            .expect("upload");
        let read = UPLOADS.attrs("attrs/a.pdf").await.expect("attrs");
        for attrs in [&attrs, &read] {
            assert_eq!(attrs.content_type.as_deref(), Some("application/pdf"));
            assert_eq!(attrs.cache_control.as_deref(), Some("public, max-age=3600"));
            assert_eq!(
                attrs.content_disposition.as_deref(),
                Some(r#"attachment; filename="a.pdf""#)
            );
            assert_eq!(attrs.metadata["owner"], "42");
        }

        // Left out stays, empty clears, and the metadata is replaced whole.
        let updated = UPLOADS
            .update_attrs("attrs/a.pdf")
            .cache_control("no-store")
            .content_disposition("")
            .metadata([("source", "import")])
            .await
            .expect("update attrs");
        assert_eq!(updated.content_type.as_deref(), Some("application/pdf"));
        assert_eq!(updated.cache_control.as_deref(), Some("no-store"));
        assert_eq!(updated.content_disposition, None);
        assert_eq!(
            updated.metadata,
            BTreeMap::from([("source".into(), "import".into())])
        );

        // Through a reference that grants it.
        let updater = UPLOADS.reference::<perms::AttrsUpdater>();
        let res = updater
            .update_attrs("attrs/a.pdf")
            .if_match(updated.revision())
            .await;
        assert!(res.is_ok(), "{res:?}");
        // Changing attributes is no new revision of the contents.
        let res = UPLOADS
            .upload_if_match("attrs/a.pdf", b"%PDF-2".to_vec(), updated.revision())
            .await;
        assert!(res.is_ok(), "{res:?}");
        // Metadata the provider can't keep is the call's mistake, saying so.
        let err = UPLOADS
            .update_attrs("attrs/a.pdf")
            .metadata([("Owner", "42")])
            .await
            .unwrap_err();
        assert!(
            matches!(&err, Error::InvalidArgument(m) if !m.is_empty()),
            "{err:?}"
        );
    });
}

#[test]
fn if_match_holds_writes_and_removes_to_the_revision_seen() {
    run(async {
        let first = UPLOADS
            .upload("match/state.json", b"1".to_vec())
            .await
            .expect("upload");
        let second = UPLOADS
            .upload_if_match("match/state.json", b"2".to_vec(), first.revision())
            .content_type("application/json")
            .await
            .expect("upload if match");
        assert_eq!(second.content_type.as_deref(), Some("application/json"));

        // What was read first is no longer the object.
        let err = UPLOADS
            .upload_if_match("match/state.json", b"3".to_vec(), first.revision())
            .await
            .unwrap_err();
        assert!(matches!(err, Error::PreconditionFailed), "{err:?}");
        let err = UPLOADS
            .remove_if_match("match/state.json", first.revision())
            .await
            .unwrap_err();
        assert!(matches!(err, Error::PreconditionFailed), "{err:?}");

        // Through references that grant them.
        let replace = UPLOADS.reference::<(perms::IfMatchUploader, perms::IfMatchRemover)>();
        let third = replace
            .upload_if_match("match/state.json", b"3".to_vec(), second.revision())
            .await
            .expect("upload if match");
        replace
            .remove_if_match("match/state.json", third.revision())
            .await
            .expect("remove if match");
        let err = UPLOADS.attrs("match/state.json").await.unwrap_err();
        assert!(matches!(err, Error::NotFound), "{err:?}");

        // A removed object matches no revision.
        let err = UPLOADS
            .upload_if_match("match/state.json", b"4".to_vec(), third.revision())
            .await
            .unwrap_err();
        assert!(matches!(err, Error::PreconditionFailed), "{err:?}");
    });
}

#[test]
fn not_exists_writes_only_a_new_object() {
    run(async {
        UPLOADS
            .upload("new/a", b"1".to_vec())
            .not_exists()
            .await
            .expect("upload");
        let err = UPLOADS
            .upload("new/a", b"2".to_vec())
            .not_exists()
            .await
            .unwrap_err();
        assert!(matches!(err, Error::PreconditionFailed), "{err:?}");
        assert_eq!(read(&UPLOADS, "new/a").await, b"1");
    });
}

/// The object's contents, whole.
async fn read(bucket: &Bucket, key: &str) -> Vec<u8> {
    let download = bucket.download(key).await.expect("download");
    download.bytes().await.expect("bytes")
}

/// The download's contents, as its stream of chunks gives them.
async fn chunks(download: Download) -> Vec<u8> {
    use futures_core::Stream;
    let mut stream = download.bytes_stream();
    let mut read = Vec::new();
    while let Some(chunk) =
        std::future::poll_fn(|cx| std::pin::Pin::new(&mut stream).poll_next(cx)).await
    {
        read.extend_from_slice(&chunk.expect("chunk"));
    }
    read
}

#[test]
fn a_download_reads_a_range_or_a_version() {
    run(async {
        let first = UPLOADS
            .upload("range/a", b"hello, world".to_vec())
            .await
            .expect("upload");
        UPLOADS
            .upload("range/a", b"goodbye".to_vec())
            .await
            .expect("upload");
        let part = UPLOADS
            .download("range/a")
            .range(0..4)
            .await
            .expect("range");
        // The size is the whole object's, whatever part of it is read.
        assert_eq!(part.size(), 7);
        assert_eq!(part.bytes().await.expect("bytes"), b"good");
        let rest = UPLOADS.download("range/a").range(4..).await.expect("range");
        assert_eq!(rest.size(), 7);
        assert_eq!(chunks(rest).await, b"bye");
        let version = first.version.clone().expect("a versioned bucket");
        let old = UPLOADS
            .download("range/a")
            .version(version.clone())
            .range(7..=11)
            .await
            .expect("version");
        // An older version is read as what it was.
        assert_eq!((old.size(), old.revision()), (12, first.revision()));
        assert_eq!(old.bytes().await.expect("bytes"), b"world");
        let attrs = UPLOADS
            .attrs("range/a")
            .version(version)
            .await
            .expect("attrs");
        assert_eq!(attrs.size, 12);
        // An empty range is the call's mistake, and so is one past the end.
        let err = UPLOADS.download("range/a").range(3..3).await.unwrap_err();
        assert!(matches!(err, Error::InvalidArgument(_)), "{err:?}");
        let err = UPLOADS.download("range/a").range(7..).await.unwrap_err();
        assert!(matches!(err, Error::InvalidArgument(_)), "{err:?}");
    });
}

#[test]
fn a_listing_says_when_each_object_was_written() {
    run(async {
        for key in ["when/a", "when/sub/b"] {
            ARCHIVE.upload(key, b"x".to_vec()).await.expect("upload");
        }
        let listed = entries(&ARCHIVE, "when/", "/").await;
        let seen: Vec<_> = listed
            .iter()
            .map(|e| (e.name.as_str(), e.is_prefix, e.last_modified.is_some()))
            .collect();
        // An object has the time its attributes give; a prefix has none.
        assert_eq!(seen, [("when/a", false, true), ("when/sub/", true, false)]);
        let attrs = ARCHIVE.attrs("when/a").await.expect("attrs");
        assert_eq!(listed[0].last_modified, attrs.last_modified);
    });
}

#[test]
fn a_download_reads_the_last_bytes_without_knowing_the_size() {
    run(async {
        for bucket in [&UPLOADS, &ARCHIVE] {
            bucket
                .upload("last/a", b"hello, world".to_vec())
                .await
                .expect("upload");
            let tail = bucket.download("last/a").last(5).await.expect("last");
            // With the size, where the bytes sit in the object: from 7 on.
            assert_eq!(tail.size(), 12);
            assert_eq!(tail.bytes().await.expect("bytes"), b"world");
            // Asked for more than there is, it is all there is.
            let all = bucket.download("last/a").last(100).await.expect("last");
            assert_eq!(all.size(), 12);
            assert_eq!(chunks(all).await, b"hello, world");
            // The last none is no range.
            let err = bucket.download("last/a").last(0).await.unwrap_err();
            assert!(matches!(err, Error::InvalidArgument(_)), "{err:?}");
        }
    });
}

#[test]
fn a_download_gives_the_revision_of_what_it_reads() {
    run(async {
        // Versioned or not, the revision is the attributes' own.
        for bucket in [&UPLOADS, &ARCHIVE] {
            let written = bucket
                .upload("read/state.json", b"1".to_vec())
                .content_type("application/json")
                .await
                .expect("upload");
            let seen = bucket.download("read/state.json").await.expect("download");
            assert_eq!(seen.revision(), written.revision());
            let attrs = bucket.attrs("read/state.json").await.expect("attrs");
            assert_eq!(seen.revision(), attrs.revision());
            assert_eq!(seen.size(), 1);
            assert_eq!(seen.content_type(), Some("application/json"));
            let since = seen.last_modified().expect("when it was written");
            assert!(since.elapsed().expect("in the past") < Duration::from_secs(60));

            // What was read is what a write may replace...
            let revision = seen.revision();
            assert_eq!(seen.bytes().await.expect("bytes"), b"1");
            let next = bucket
                .upload_if_match("read/state.json", b"2".to_vec(), revision.clone())
                .await
                .expect("upload if match");
            assert_ne!(next.revision(), revision);
            // ...once: another reader of the same is refused, writing or
            // removing.
            let err = bucket
                .upload_if_match("read/state.json", b"3".to_vec(), revision.clone())
                .await
                .unwrap_err();
            assert!(matches!(err, Error::PreconditionFailed), "{err:?}");
            let err = bucket
                .remove_if_match("read/state.json", revision)
                .await
                .unwrap_err();
            assert!(matches!(err, Error::PreconditionFailed), "{err:?}");

            // A range of the object is of the same revision, and through a
            // reference too.
            let reader = bucket.reference::<(perms::Downloader, perms::IfMatchRemover)>();
            let part = reader
                .download("read/state.json")
                .range(..1)
                .await
                .expect("range");
            assert_eq!(part.revision(), next.revision());
            reader
                .remove_if_match("read/state.json", part.revision())
                .await
                .expect("remove if match");
        }
    });
}

#[test]
fn a_download_is_read_as_a_stream_or_a_reader() {
    use tokio::io::AsyncReadExt;
    run(async {
        // Larger than one chunk arrives in.
        let data: Vec<u8> = (0..300_000u32).flat_map(u32::to_le_bytes).collect();
        ARCHIVE
            .upload("stream/a", data.clone())
            .await
            .expect("upload");
        let download = ARCHIVE.download("stream/a").await.expect("download");
        assert_eq!(download.size(), data.len() as u64);
        assert!(chunks(download).await == data);

        let mut reader = ARCHIVE
            .download("stream/a")
            .range(4..12)
            .await
            .expect("range")
            .into_async_read();
        let mut part = Vec::new();
        reader.read_to_end(&mut part).await.expect("read");
        assert_eq!(part, data[4..12]);

        // One left unread is dropped, and the next is none the worse.
        drop(ARCHIVE.download("stream/a").await.expect("download"));
        assert!(read(&ARCHIVE, "stream/a").await == data);
    });
}

#[test]
fn a_delimited_listing_groups_names_into_prefixes() {
    run(async {
        for key in ["dir/a", "dir/sub/b", "dir/sub/c", "dir/z", "dirt"] {
            UPLOADS.upload(key, b"x".to_vec()).await.expect("upload");
        }
        let listed: Vec<(String, bool)> = entries(&UPLOADS, "dir/", "/")
            .await
            .into_iter()
            .map(|e| (e.name, e.is_prefix))
            .collect();
        assert_eq!(
            listed,
            [
                ("dir/a".to_string(), false),
                ("dir/sub/".to_string(), true),
                ("dir/z".to_string(), false),
            ]
        );
    });
}

#[test]
fn versions_are_listed_newest_first() {
    run(async {
        let first = UPLOADS
            .upload("versions/a", b"1".to_vec())
            .await
            .expect("upload");
        let second = UPLOADS
            .upload("versions/a", b"2".to_vec())
            .await
            .expect("upload");
        let listed: Vec<(Option<String>, bool)> = versions(&UPLOADS, "versions/")
            .await
            .into_iter()
            .map(|v| (v.version, v.latest))
            .collect();
        assert_eq!(listed, [(second.version, true), (first.version, false)]);

        // Through a reference, and limited.
        let mut limited = UPLOADS
            .reference::<perms::Lister>()
            .list_versions()
            .prefix("versions/")
            .limit(1)
            .await
            .expect("list versions");
        assert!(limited.next().await.is_some());
        assert!(limited.next().await.is_none());

        // An unversioned bucket lists each object once.
        ARCHIVE
            .upload("versions/b", b"1".to_vec())
            .await
            .expect("upload");
        ARCHIVE
            .upload("versions/b", b"2".to_vec())
            .await
            .expect("upload");
        let listed = versions(&ARCHIVE, "versions/").await;
        assert_eq!(listed.len(), 1, "{listed:?}");
        assert!(listed[0].latest);
    });
}

#[test]
fn an_upload_names_its_storage_class() {
    run(async {
        let attrs = UPLOADS
            .upload("class/cold.bin", b"x".to_vec())
            .storage_class(StorageClass::Cold)
            .await
            .expect("upload");
        assert_eq!(attrs.storage_class, Some(StorageClass::Cold));

        // `Auto` is a bucket's class only.
        let err = UPLOADS
            .upload("class/auto.bin", b"x".to_vec())
            .storage_class(StorageClass::Auto)
            .await
            .unwrap_err();
        assert!(matches!(err, Error::InvalidArgument(_)), "{err:?}");
    });
}

#[test]
fn a_retained_object_is_kept_until_its_time() {
    run(async {
        let until = SystemTime::now() + Duration::from_secs(24 * 60 * 60);
        let attrs = EVIDENCE
            .upload("case-42.pdf", b"%PDF".to_vec())
            .retain_until(until)
            .await
            .expect("upload");
        let kept = attrs.retain_until.expect("retained");
        assert!(
            kept + Duration::from_secs(1) >= until,
            "{kept:?} < {until:?}"
        );

        let err = EVIDENCE.remove("case-42.pdf").await.unwrap_err();
        assert!(matches!(err, Error::Retained), "{err:?}");
        let err = EVIDENCE
            .upload("case-42.pdf", b"overwrite".to_vec())
            .await
            .unwrap_err();
        assert!(matches!(err, Error::Retained), "{err:?}");

        // Only ever later.
        let updater = EVIDENCE.reference::<perms::AttrsUpdater>();
        let err = updater
            .extend_retention("case-42.pdf", kept - Duration::from_secs(60 * 60))
            .await
            .unwrap_err();
        assert!(matches!(err, Error::InvalidArgument(_)), "{err:?}");
        let later = kept + Duration::from_secs(24 * 60 * 60);
        let attrs = updater
            .extend_retention("case-42.pdf", later)
            .await
            .expect("extend retention");
        let kept = attrs.retain_until.expect("retained");
        assert!(
            kept + Duration::from_secs(1) >= later,
            "{kept:?} < {later:?}"
        );
    });
}

#[test]
fn a_missing_object_is_not_found() {
    run(async {
        let err = UPLOADS.download("missing/a").await.unwrap_err();
        assert!(matches!(err, Error::NotFound), "{err:?}");
        let err = UPLOADS.attrs("missing/a").await.unwrap_err();
        assert!(matches!(err, Error::NotFound), "{err:?}");
        assert!(!UPLOADS.exists("missing/a").await.expect("exists"));
    });
}

#[test]
fn a_bucket_with_no_provider_fails_with_another_error() {
    // Not in the runtime config: the core gives it a bucket that does nothing.
    static UNKNOWN: Bucket = Bucket::named("unknown");
    run(async {
        let err = UNKNOWN.attrs("a").await.unwrap_err();
        assert!(matches!(err, Error::Other(_)), "{err:?}");
        let err = UNKNOWN.public_url("a").unwrap_err();
        assert!(matches!(err, Error::Other(_)), "{err:?}");
    });
}