encore-dev 2.0.0-alpha.12

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
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
//! Object storage buckets. Declared at module scope; resolved from the runtime
//! on use.
//!
//! ```no_run
//! use encore::objects::Bucket;
//!
//! static UPLOADS: Bucket = Bucket::new("uploads");
//! static AVATARS: Bucket = Bucket::new("avatars").public().versioned();
//! ```
//!
//! Every operation is a method of the [`Bucket`] — `upload`, `download`,
//! `list`, `attrs`, `remove`, … — named as in Encore's TypeScript and Go SDKs.
//! That is what lets Encore grant each service exactly the permissions it
//! uses: the operation is visible at the call, so the parser can read it.
//!
//! # References
//!
//! For the same reason, a bucket cannot be passed around as a value. To hand
//! it to other code, make a [`BucketRef`], which grants only the permissions
//! its type argument names:
//!
//! ```no_run
//! use encore::objects::{perms, Bucket, Uploader};
//!
//! static UPLOADS: Bucket = Bucket::named("uploads");
//!
//! // Library code asks for the permissions it needs, as traits.
//! async fn save(bucket: &impl Uploader, key: &str) -> Result<(), encore::Error> {
//!     bucket.upload(key, b"hello".to_vec()).await?;
//!     Ok(())
//! }
//!
//! async fn greet() -> Result<(), encore::Error> {
//!     save(&UPLOADS.reference::<perms::Uploader>(), "greeting.txt").await
//! }
//! ```
//!
//! The permissions are one of the [`perms`], or a tuple of them
//! (`(perms::Uploader, perms::Lister)`). Each has a trait of the same name
//! here, with the methods it grants. Library code takes the traits —
//! `&impl Uploader`, `&(impl Uploader + Lister)` — so it works with any
//! reference that grants them, and can be tested against a fake.

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;

/// Re-exported option and result types of the bucket operations.
pub use encore_sdk_core::objects::{
    AttrsOptions, ByteRange, DeleteOptions as RemoveOptions, DownloadOptions, ExistsOptions,
    ListEntry, ListOptions, ObjectAttrs, UploadOptions, UploadPreconditions,
};

/// The contents of an object, as they arrive: returned by
/// [`Bucket::download_stream`]. Take them chunk by chunk with
/// [`Download::next`] — or as a [`Stream`] — all at once with
/// [`Download::bytes`], or as an [`AsyncRead`] with
/// [`Download::into_async_read`].
///
/// ```ignore
/// let mut download = UPLOADS.download_stream("big.bin", DownloadOptions::default()).await?;
/// while let Some(chunk) = download.next().await {
///     hasher.update(&chunk?);
/// }
///
/// // Or straight into a file.
/// let mut reader = UPLOADS
///     .download_stream("big.bin", DownloadOptions::default())
///     .await?
///     .into_async_read();
/// tokio::io::copy(&mut reader, &mut file).await?;
/// ```
pub struct Download {
    inner: objects::DownloadStream,
}

impl Download {
    /// The next chunk of the object, or `None` once it has all arrived. A
    /// chunk is as large as it happened to arrive.
    pub async fn next(&mut self) -> Option<Result<Bytes, Error>> {
        poll_fn(|cx| Pin::new(&mut *self).poll_next(cx)).await
    }

    /// The rest of the object, in one piece.
    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)
    }

    /// The rest of the object as a reader, for what takes one: a parser, a
    /// decompressor, `tokio::io::copy`.
    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)))
    }
}

/// A download whose errors are `io::Error`s, as a reader's are.
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)))
    }
}

/// The objects of a bucket, as they are listed: returned by [`Bucket::list`].
/// Take them one at a time with [`ListIterator::next`], or as a [`Stream`].
pub struct ListIterator {
    inner: objects::ListIterator,
}

impl ListIterator {
    /// The next object, or `None` once there are no more.
    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)))
    }
}

/// A stream of chunks as the reader an upload takes. The runtime shares the
/// reader between threads, which a stream need not allow: the lock is what
/// makes it shareable, and is never contended, as only one reads at a time.
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)))
    }
}

/// A URL through which anyone holding it can upload an object, made by
/// [`Bucket::signed_upload_url`].
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct SignedUploadUrl {
    pub url: String,
}

/// A URL through which anyone holding it can download an object, made by
/// [`Bucket::signed_download_url`].
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct SignedDownloadUrl {
    pub url: String,
}

/// Options for a signed URL.
#[derive(Debug, Clone, Copy, Default)]
pub struct SignedUrlOptions {
    /// How long the URL is valid for: at most seven days, and one hour if not
    /// given.
    pub ttl: Option<Duration>,
}

impl SignedUrlOptions {
    fn ttl(self) -> Duration {
        self.ttl.unwrap_or(Duration::from_secs(60 * 60))
    }
}

/// An object-storage bucket.
pub struct Bucket {
    name: &'static str,
    /// Read by Encore's parser from the declaration, not by the runtime.
    #[allow(dead_code)]
    versioned: bool,
    #[allow(dead_code)]
    public: bool,
}

impl Bucket {
    /// Declare a bucket. `const` so it can initialize a module-scope `static`.
    ///
    /// Options follow the name, each a method of its own:
    ///
    /// ```no_run
    /// use encore::objects::Bucket;
    ///
    /// static AVATARS: Bucket = Bucket::new("avatars").public().versioned();
    /// ```
    pub const fn new(name: &'static str) -> Self {
        Self {
            name,
            versioned: false,
            public: false,
        }
    }

    /// Makes the bucket public: its objects are readable by anyone, at the URL
    /// [`Bucket::public_url`] gives.
    ///
    /// Part of the declaration: it takes the bucket by value, so it cannot be
    /// called on the `static`.
    pub const fn public(mut self) -> Self {
        self.public = true;
        self
    }

    /// Makes the bucket versioned: an object keeps its earlier versions, which
    /// the `_with` operations can name.
    ///
    /// Part of the declaration, like [`Bucket::public`].
    pub const fn versioned(mut self) -> Self {
        self.versioned = true;
        self
    }

    /// Reference an existing bucket by name. To declare a new bucket, use
    /// [`Bucket::new`] instead.
    ///
    /// The name must be a string literal, so Encore can resolve it statically.
    /// `const` so it can initialize a module-scope `static`. A named bucket
    /// takes no options: it is configured where it is declared.
    ///
    /// ```no_run
    /// static UPLOADS: encore::objects::Bucket = encore::objects::Bucket::named("uploads");
    /// ```
    pub const fn named(name: &'static str) -> Self {
        Self::new(name)
    }

    /// A reference to the bucket that grants only the permissions `P`: one of
    /// the [`perms`], or a tuple of them. Unlike the bucket, a reference can be
    /// passed to other code; the service is granted the permissions it names.
    ///
    /// The permissions must be written as the type argument, since they are
    /// what the service is granted: the compiler never infers them. `const`,
    /// so a reference can initialize a module-scope `static`.
    ///
    /// ```no_run
    /// use encore::objects::{perms, Bucket, BucketRef};
    ///
    /// static UPLOADS: Bucket = Bucket::named("uploads");
    /// static AVATARS: BucketRef<(perms::Uploader, perms::Lister)> =
    ///     UPLOADS.reference::<(perms::Uploader, perms::Lister)>();
    /// ```
    ///
    /// ```compile_fail,E0284
    /// # use encore::objects::{perms, Bucket, BucketRef};
    /// # static UPLOADS: Bucket = Bucket::named("uploads");
    /// // Not even from the type it is assigned to.
    /// static AVATARS: BucketRef<perms::Uploader> = UPLOADS.reference();
    /// ```
    pub const fn reference<P: BucketPerms>(&'static self) -> BucketRef<P::Id> {
        BucketRef {
            bucket: self,
            perms: PhantomData,
        }
    }

    /// The bucket operations run on: the app's own, or under `encore test`
    /// the current test's instance of it (see [`crate::testing`]).
    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()))
    }

    /// List the objects in the bucket — those under `options.prefix`, up to
    /// `options.limit` — as an iterator of entries.
    ///
    /// ```ignore
    /// let mut entries = UPLOADS.list(ListOptions { prefix: Some("avatars/".into()), ..Default::default() }).await?;
    /// while let Some(entry) = entries.next().await {
    ///     println!("{}", entry?.name);
    /// }
    /// ```
    pub async fn list(&self, options: ListOptions) -> Result<ListIterator, Error> {
        self.resolve()?
            .list(options)
            .await
            .map(|inner| ListIterator { inner })
            .map_err(map_obj_err)
    }

    /// Whether an object with `key` exists.
    pub async fn exists(&self, key: &str) -> Result<bool, Error> {
        self.exists_with(key, ExistsOptions::default()).await
    }

    /// Whether an object exists, with explicit options (a specific version).
    pub async fn exists_with(&self, key: &str, options: ExistsOptions) -> Result<bool, Error> {
        self.object(key)?.exists(options).await.map_err(map_obj_err)
    }

    /// The attributes of the object `key`: its size, content type, version
    /// and etag.
    pub async fn attrs(&self, key: &str) -> Result<ObjectAttrs, Error> {
        self.attrs_with(key, AttrsOptions::default()).await
    }

    /// An object's attributes, with explicit options (a specific version).
    pub async fn attrs_with(&self, key: &str, options: AttrsOptions) -> Result<ObjectAttrs, Error> {
        self.object(key)?.attrs(options).await.map_err(map_obj_err)
    }

    /// Upload `data` to the object `key`, returning its stored attributes.
    pub async fn upload(&self, key: &str, data: Vec<u8>) -> Result<ObjectAttrs, Error> {
        self.upload_with(key, data, UploadOptions::default()).await
    }

    /// Upload `data` with explicit options — a content type, or a
    /// precondition such as "only if it does not exist yet".
    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
    }

    /// Upload the object `key` from a reader, streaming its contents rather
    /// than buffering them.
    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)
    }

    /// Upload the object `key` from a stream of chunks, such as the body of a
    /// request being forwarded. A chunk is anything that becomes `Bytes`:
    /// `Bytes` itself, `Vec<u8>`, `String`, `&'static [u8]`.
    ///
    /// ```ignore
    /// let chunks = futures::stream::iter([Ok::<_, std::io::Error>(Bytes::from("hello"))]);
    /// UPLOADS.upload_chunks("greeting.txt", chunks, UploadOptions::default()).await?;
    /// ```
    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
    }

    /// Download the full contents of the object `key`.
    pub async fn download(&self, key: &str) -> Result<Vec<u8>, Error> {
        self.download_with(key, DownloadOptions::default()).await
    }

    /// Download the object `key` with explicit options — a specific version, or
    /// only a byte range of the object.
    ///
    /// ```ignore
    /// // The 256 bytes starting at offset 1024.
    /// let head = UPLOADS.download_with("big.bin", DownloadOptions {
    ///     range: Some(ByteRange { offset: 1024, length: Some(256) }),
    ///     ..Default::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)
    }

    /// Download the object `key` as it arrives, rather than buffering it
    /// whole: see [`Download`].
    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)
    }

    /// Remove the object `key`.
    pub async fn remove(&self, key: &str) -> Result<(), Error> {
        self.remove_with(key, RemoveOptions::default()).await
    }

    /// Remove an object, with explicit options (a specific version).
    pub async fn remove_with(&self, key: &str, options: RemoveOptions) -> Result<(), Error> {
        self.object(key)?.delete(options).await.map_err(map_obj_err)
    }

    /// A URL through which anyone holding it can upload the object `key`,
    /// valid for an hour.
    pub async fn signed_upload_url(&self, key: &str) -> Result<SignedUploadUrl, Error> {
        self.signed_upload_url_with(key, SignedUrlOptions::default())
            .await
    }

    /// A signed upload URL, with explicit options (how long it is valid for).
    ///
    /// ```ignore
    /// let upload = UPLOADS.signed_upload_url_with("report.pdf", SignedUrlOptions {
    ///     ttl: Some(Duration::from_secs(5 * 60)),
    /// }).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)
    }

    /// A URL through which anyone holding it can download the object `key`,
    /// valid for an hour.
    pub async fn signed_download_url(&self, key: &str) -> Result<SignedDownloadUrl, Error> {
        self.signed_download_url_with(key, SignedUrlOptions::default())
            .await
    }

    /// A signed download URL, with explicit options (how long it is valid for).
    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)
    }

    /// The public URL of the object `key`. Only a bucket declared `public`
    /// has one.
    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)
        })
    }
}

/// The permissions a [`BucketRef`] can grant, as types for its type argument.
/// Each has a trait of the same name in [`objects`](super), with the methods
/// it grants.
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;
            }
        };
    }

    // The flags each sets, in `BucketPerms`' order: Upload, SignedUpload,
    // Download, SignedDownload, Attrs, List, Remove, PublicUrl.
    perm!(
        /// Upload objects: [`Uploader`](super::Uploader).
        Uploader: Yes, No, No, No, No, No, No, No
    );
    perm!(
        /// Make signed upload URLs: [`SignedUploader`](super::SignedUploader).
        SignedUploader: No, Yes, No, No, No, No, No, No
    );
    perm!(
        /// Download objects: [`Downloader`](super::Downloader).
        Downloader: No, No, Yes, No, No, No, No, No
    );
    perm!(
        /// Make signed download URLs:
        /// [`SignedDownloader`](super::SignedDownloader).
        SignedDownloader: No, No, No, Yes, No, No, No, No
    );
    perm!(
        /// Read objects' attributes, and whether they exist:
        /// [`Attrser`](super::Attrser).
        Attrser: No, No, No, No, Yes, No, No, No
    );
    perm!(
        /// List objects: [`Lister`](super::Lister).
        Lister: No, No, No, No, No, Yes, No, No
    );
    perm!(
        /// Remove objects: [`Remover`](super::Remover).
        Remover: No, No, No, No, No, No, Yes, No
    );
    perm!(
        /// Resolve objects' public URLs: [`PublicUrler`](super::PublicUrler).
        PublicUrler: No, No, No, No, No, No, No, Yes
    );
    perm!(
        /// Every permission but [`PublicUrler`]: [`ReadWriter`](super::ReadWriter).
        ReadWriter: Yes, Yes, Yes, Yes, Yes, Yes, Yes, No
    );
}

mod sealed {
    pub trait Sealed {}
}

/// A set of bucket permissions: one of the [`perms`], or a tuple of them,
/// which grants what any of its members does. Sealed: the SDK's permissions
/// are the only ones.
pub trait BucketPerms: sealed::Sealed {
    /// Always `Self`. [`Bucket::reference`] returns `BucketRef<P::Id>`, which
    /// the compiler cannot work back from to `P`, so `P` is never inferred.
    #[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 () {}

/// The empty set, which the tuples build on. Grants nothing.
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;
}

/// A tuple grants what its first member or the rest of it does.
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);

/// A reference to a [`Bucket`] that grants only the permissions `P`, made by
/// [`Bucket::reference`]. `Copy`, and free to pass to other code.
///
/// Its methods are the bucket's, for the permissions it grants: a
/// `BucketRef<perms::Uploader>` can `upload` but not `download`. Each is also
/// a method of its permission's trait, which library code takes instead of a
/// `BucketRef`.
///
/// ```compile_fail,E0277
/// # use encore::objects::{perms, Bucket};
/// # static UPLOADS: Bucket = Bucket::named("uploads");
/// async fn upload() {
///     // A `Lister` reference cannot upload.
///     let _ = UPLOADS.reference::<perms::Lister>().upload("a", vec![]).await;
/// }
/// ```
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> {
    /// See [`Bucket::list`].
    pub async fn list(&self, options: ListOptions) -> Result<ListIterator, Error>
    where
        P::List: Granted<perms::Lister>,
    {
        self.bucket.list(options).await
    }

    /// See [`Bucket::exists`].
    pub async fn exists(&self, key: &str) -> Result<bool, Error>
    where
        P::Attrs: Granted<perms::Attrser>,
    {
        self.bucket.exists(key).await
    }

    /// See [`Bucket::exists_with`].
    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
    }

    /// See [`Bucket::attrs`].
    pub async fn attrs(&self, key: &str) -> Result<ObjectAttrs, Error>
    where
        P::Attrs: Granted<perms::Attrser>,
    {
        self.bucket.attrs(key).await
    }

    /// See [`Bucket::attrs_with`].
    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
    }

    /// See [`Bucket::upload`].
    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
    }

    /// See [`Bucket::upload_with`].
    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
    }

    /// See [`Bucket::upload_stream`].
    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
    }

    /// See [`Bucket::upload_chunks`].
    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
    }

    /// See [`Bucket::download`].
    pub async fn download(&self, key: &str) -> Result<Vec<u8>, Error>
    where
        P::Download: Granted<perms::Downloader>,
    {
        self.bucket.download(key).await
    }

    /// See [`Bucket::download_with`].
    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
    }

    /// See [`Bucket::download_stream`].
    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
    }

    /// See [`Bucket::remove`].
    pub async fn remove(&self, key: &str) -> Result<(), Error>
    where
        P::Remove: Granted<perms::Remover>,
    {
        self.bucket.remove(key).await
    }

    /// See [`Bucket::remove_with`].
    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
    }

    /// See [`Bucket::signed_upload_url`].
    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
    }

    /// See [`Bucket::signed_upload_url_with`].
    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
    }

    /// See [`Bucket::signed_download_url`].
    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
    }

    /// See [`Bucket::signed_download_url_with`].
    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
    }

    /// See [`Bucket::public_url`].
    pub fn public_url(&self, key: &str) -> Result<String, Error>
    where
        P::PublicUrl: Granted<perms::PublicUrler>,
    {
        self.bucket.public_url(key)
    }
}

/// Upload objects. Implemented by a [`BucketRef`] granting
/// [`perms::Uploader`].
pub trait Uploader: Send + Sync {
    /// See [`Bucket::upload`].
    fn upload(
        &self,
        key: &str,
        data: Vec<u8>,
    ) -> impl Future<Output = Result<ObjectAttrs, Error>> + Send {
        self.upload_with(key, data, UploadOptions::default())
    }

    /// See [`Bucket::upload_with`].
    fn upload_with(
        &self,
        key: &str,
        data: Vec<u8>,
        options: UploadOptions,
    ) -> impl Future<Output = Result<ObjectAttrs, Error>> + Send;

    /// See [`Bucket::upload_stream`].
    fn upload_stream(
        &self,
        key: &str,
        reader: impl AsyncRead + Unpin + Send + Sync + 'static,
        options: UploadOptions,
    ) -> impl Future<Output = Result<ObjectAttrs, Error>> + Send;

    /// See [`Bucket::upload_chunks`].
    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)
    }
}

/// Make signed upload URLs. Implemented by a [`BucketRef`] granting
/// [`perms::SignedUploader`].
pub trait SignedUploader: Send + Sync {
    /// See [`Bucket::signed_upload_url`].
    fn signed_upload_url(
        &self,
        key: &str,
    ) -> impl Future<Output = Result<SignedUploadUrl, Error>> + Send {
        self.signed_upload_url_with(key, SignedUrlOptions::default())
    }

    /// See [`Bucket::signed_upload_url_with`].
    fn signed_upload_url_with(
        &self,
        key: &str,
        options: SignedUrlOptions,
    ) -> impl Future<Output = Result<SignedUploadUrl, Error>> + Send;
}

/// Download objects. Implemented by a [`BucketRef`] granting
/// [`perms::Downloader`].
pub trait Downloader: Send + Sync {
    /// See [`Bucket::download`].
    fn download(&self, key: &str) -> impl Future<Output = Result<Vec<u8>, Error>> + Send {
        self.download_with(key, DownloadOptions::default())
    }

    /// See [`Bucket::download_with`].
    fn download_with(
        &self,
        key: &str,
        options: DownloadOptions,
    ) -> impl Future<Output = Result<Vec<u8>, Error>> + Send;

    /// See [`Bucket::download_stream`].
    fn download_stream(
        &self,
        key: &str,
        options: DownloadOptions,
    ) -> impl Future<Output = Result<Download, Error>> + Send;
}

/// Make signed download URLs. Implemented by a [`BucketRef`] granting
/// [`perms::SignedDownloader`].
pub trait SignedDownloader: Send + Sync {
    /// See [`Bucket::signed_download_url`].
    fn signed_download_url(
        &self,
        key: &str,
    ) -> impl Future<Output = Result<SignedDownloadUrl, Error>> + Send {
        self.signed_download_url_with(key, SignedUrlOptions::default())
    }

    /// See [`Bucket::signed_download_url_with`].
    fn signed_download_url_with(
        &self,
        key: &str,
        options: SignedUrlOptions,
    ) -> impl Future<Output = Result<SignedDownloadUrl, Error>> + Send;
}

/// Read objects' attributes, and whether they exist. Implemented by a
/// [`BucketRef`] granting [`perms::Attrser`].
pub trait Attrser: Send + Sync {
    /// See [`Bucket::exists`].
    fn exists(&self, key: &str) -> impl Future<Output = Result<bool, Error>> + Send {
        self.exists_with(key, ExistsOptions::default())
    }

    /// See [`Bucket::exists_with`].
    fn exists_with(
        &self,
        key: &str,
        options: ExistsOptions,
    ) -> impl Future<Output = Result<bool, Error>> + Send;

    /// See [`Bucket::attrs`].
    fn attrs(&self, key: &str) -> impl Future<Output = Result<ObjectAttrs, Error>> + Send {
        self.attrs_with(key, AttrsOptions::default())
    }

    /// See [`Bucket::attrs_with`].
    fn attrs_with(
        &self,
        key: &str,
        options: AttrsOptions,
    ) -> impl Future<Output = Result<ObjectAttrs, Error>> + Send;
}

/// List objects. Implemented by a [`BucketRef`] granting [`perms::Lister`].
pub trait Lister: Send + Sync {
    /// See [`Bucket::list`].
    fn list(
        &self,
        options: ListOptions,
    ) -> impl Future<Output = Result<ListIterator, Error>> + Send;
}

/// Remove objects. Implemented by a [`BucketRef`] granting [`perms::Remover`].
pub trait Remover: Send + Sync {
    /// See [`Bucket::remove`].
    fn remove(&self, key: &str) -> impl Future<Output = Result<(), Error>> + Send {
        self.remove_with(key, RemoveOptions::default())
    }

    /// See [`Bucket::remove_with`].
    fn remove_with(
        &self,
        key: &str,
        options: RemoveOptions,
    ) -> impl Future<Output = Result<(), Error>> + Send;
}

/// Resolve objects' public URLs. Implemented by a [`BucketRef`] granting
/// [`perms::PublicUrler`].
pub trait PublicUrler: Send + Sync {
    /// See [`Bucket::public_url`].
    fn public_url(&self, key: &str) -> Result<String, Error>;
}

/// Every permission but [`PublicUrler`]. Implemented by whatever implements
/// them all, such as a [`BucketRef`] granting [`perms::ReadWriter`].
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)
    }
}

/// Object storage failures are transport problems by default, but the caller's
/// own arguments (an empty or out-of-bounds byte range, a malformed version)
/// are their fault, not the backend's.
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::*;

    /// 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_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");
        // The SDK's error is inside the reader's.
        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)))));
        // 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}");
    }
}