encore-dev 2.0.0-beta.15

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
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
1708
1709
1710
1711
1712
1713
1714
1715
1716
1717
1718
1719
1720
1721
1722
1723
1724
1725
1726
1727
1728
1729
1730
1731
1732
1733
1734
1735
1736
1737
1738
1739
1740
1741
1742
1743
1744
1745
1746
1747
1748
1749
1750
1751
1752
1753
1754
1755
1756
1757
1758
1759
1760
1761
1762
1763
1764
1765
1766
1767
1768
1769
1770
1771
1772
1773
1774
1775
1776
1777
1778
1779
1780
1781
1782
1783
1784
1785
1786
1787
1788
1789
1790
1791
1792
1793
1794
1795
1796
1797
1798
1799
1800
1801
1802
1803
1804
1805
1806
1807
1808
1809
1810
1811
1812
1813
1814
1815
1816
1817
1818
1819
1820
1821
1822
1823
1824
1825
1826
1827
1828
1829
1830
1831
1832
1833
1834
1835
1836
1837
1838
1839
1840
1841
1842
1843
1844
1845
1846
1847
1848
1849
1850
1851
1852
1853
1854
1855
1856
1857
1858
1859
1860
1861
1862
1863
1864
1865
1866
1867
1868
1869
1870
1871
1872
1873
1874
1875
1876
1877
1878
1879
1880
1881
1882
1883
1884
1885
1886
1887
1888
1889
1890
1891
1892
1893
1894
1895
1896
1897
1898
1899
1900
1901
1902
1903
1904
1905
1906
1907
1908
1909
1910
1911
1912
1913
1914
1915
1916
1917
1918
1919
1920
1921
1922
1923
1924
1925
1926
1927
1928
1929
1930
1931
1932
1933
1934
1935
1936
1937
1938
1939
1940
1941
1942
1943
1944
1945
1946
1947
1948
1949
1950
1951
1952
1953
1954
1955
1956
1957
1958
1959
1960
1961
1962
1963
1964
1965
1966
1967
1968
1969
1970
1971
1972
1973
1974
1975
1976
1977
1978
1979
1980
1981
1982
1983
1984
1985
1986
1987
1988
1989
1990
1991
1992
1993
1994
1995
1996
1997
1998
1999
2000
2001
2002
2003
2004
2005
2006
2007
2008
2009
2010
2011
2012
2013
2014
2015
2016
2017
2018
2019
2020
2021
2022
2023
2024
2025
2026
2027
2028
2029
2030
2031
2032
2033
2034
2035
2036
2037
2038
2039
2040
2041
2042
2043
2044
2045
2046
2047
2048
2049
2050
2051
2052
2053
2054
2055
2056
2057
2058
2059
2060
2061
2062
2063
2064
2065
2066
2067
2068
2069
2070
2071
2072
2073
2074
2075
2076
2077
2078
2079
2080
2081
2082
2083
2084
2085
2086
2087
2088
2089
2090
2091
2092
2093
2094
2095
2096
2097
2098
2099
2100
2101
2102
2103
2104
2105
2106
2107
2108
2109
2110
2111
2112
2113
2114
2115
2116
2117
2118
2119
2120
2121
2122
2123
2124
2125
2126
2127
2128
2129
2130
2131
2132
2133
2134
2135
2136
2137
2138
2139
2140
2141
2142
2143
2144
2145
2146
2147
2148
2149
2150
2151
2152
2153
2154
2155
2156
2157
2158
2159
2160
2161
2162
2163
2164
2165
2166
2167
2168
2169
2170
2171
2172
2173
2174
2175
2176
2177
2178
2179
2180
2181
2182
2183
2184
2185
2186
2187
2188
2189
2190
2191
2192
2193
2194
2195
2196
2197
2198
2199
2200
2201
2202
2203
2204
2205
2206
2207
2208
2209
2210
2211
2212
2213
2214
2215
2216
2217
2218
2219
2220
2221
2222
2223
2224
2225
2226
2227
2228
2229
2230
2231
2232
2233
2234
2235
2236
2237
2238
2239
2240
2241
2242
2243
2244
2245
2246
2247
2248
2249
2250
2251
2252
2253
2254
2255
2256
2257
2258
2259
2260
2261
2262
2263
2264
2265
2266
2267
2268
2269
2270
2271
2272
2273
2274
2275
2276
2277
2278
2279
2280
2281
2282
2283
2284
2285
2286
2287
2288
2289
2290
2291
2292
2293
2294
2295
2296
2297
2298
2299
2300
2301
2302
2303
2304
2305
2306
2307
2308
2309
2310
2311
2312
2313
2314
2315
2316
2317
2318
2319
2320
2321
2322
2323
2324
2325
2326
2327
2328
2329
2330
2331
2332
2333
2334
2335
2336
2337
2338
2339
2340
2341
2342
2343
2344
2345
2346
2347
2348
2349
2350
2351
2352
2353
2354
2355
2356
2357
2358
2359
2360
2361
2362
2363
2364
2365
2366
2367
2368
2369
2370
2371
2372
2373
2374
2375
2376
2377
2378
2379
2380
2381
2382
2383
2384
2385
2386
2387
2388
2389
2390
2391
2392
2393
2394
2395
2396
2397
2398
2399
2400
2401
2402
2403
2404
2405
2406
2407
2408
2409
2410
2411
2412
2413
2414
2415
2416
2417
2418
2419
2420
2421
2422
2423
2424
2425
2426
2427
2428
2429
2430
2431
2432
2433
2434
2435
2436
2437
2438
2439
2440
2441
2442
2443
2444
2445
2446
2447
2448
2449
2450
2451
2452
2453
2454
2455
2456
2457
2458
2459
2460
2461
2462
2463
2464
2465
2466
2467
2468
2469
2470
2471
2472
2473
2474
2475
2476
2477
2478
2479
2480
2481
2482
2483
2484
2485
2486
2487
2488
2489
2490
2491
2492
2493
2494
2495
2496
2497
2498
2499
2500
2501
2502
2503
2504
2505
2506
2507
2508
2509
2510
2511
2512
2513
2514
2515
2516
2517
2518
2519
2520
2521
2522
2523
2524
2525
2526
2527
2528
2529
2530
2531
2532
2533
2534
2535
2536
2537
2538
2539
2540
2541
2542
2543
2544
//! 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.
//!
//! An operation that takes options returns a request: each option is a
//! method of it, and awaiting it runs the operation.
//!
//! ```no_run
//! use encore::objects::{Bucket, StorageClass};
//!
//! static UPLOADS: Bucket = Bucket::named("uploads");
//!
//! async fn save(data: Vec<u8>) -> Result<(), encore::objects::Error> {
//!     UPLOADS.upload("a.pdf", data.clone()).await?;
//!     UPLOADS
//!         .upload("b.pdf", data)
//!         .content_type("application/pdf")
//!         .metadata([("owner", "42")])
//!         .storage_class(StorageClass::Cold)
//!         .await?;
//!     let head = UPLOADS.download("b.pdf").range(0..1024).await?.bytes().await?;
//!     Ok(())
//! }
//! ```
//!
//! # 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::{self, 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<(), objects::Error> {
//!     bucket.upload(key, b"hello".to_vec()).await?;
//!     Ok(())
//! }
//!
//! async fn greet() -> Result<(), objects::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.
//!
//! # Declaring a bucket
//!
//! Options follow the name, each a `const` method of its own. Encore reads
//! them from the declaration and provisions the bucket with them:
//!
//! ```no_run
//! use encore::objects::{Bucket, LifecycleRule, Retention, StorageClass};
//!
//! static UPLOADS: Bucket = Bucket::new("uploads")
//!     .versioned()
//!     .storage_class(StorageClass::Infrequent)
//!     .lifecycle(&[
//!         LifecycleRule::new().prefix("tmp/").delete_after_days(1),
//!         LifecycleRule::new()
//!             .move_to_infrequent_after_days(30)
//!             .move_to_cold_after_days(90),
//!         LifecycleRule::new()
//!             .delete_noncurrent_after_days(30)
//!             .keep_noncurrent_versions(5),
//!     ])
//!     .retention(Retention::days(2555))
//!     .object_retention();
//! ```
//!
//! # Errors
//!
//! Every operation fails with this module's [`Error`]:
//!
//! - [`Error::NotFound`]: the object, or the version asked for, does not
//!   exist.
//! - [`Error::PreconditionFailed`]: a precondition does not hold: `not_exists`,
//!   or the revision `upload_if_match`, `remove_if_match` or `if_match` names.
//! - [`Error::Retained`]: retention keeps the object from being deleted or
//!   overwritten yet.
//! - [`Error::InvalidArgument`]: a mistake in the call, saying what it is.
//! - [`Error::Other`]: anything else, such as a failure to reach the provider.
//!
//! The error is this module's own, and doesn't convert into
//! [`encore::Error`](crate::Error). Match on it where the kind matters:
//!
//! ```no_run
//! use encore::objects::{self, Bucket};
//!
//! static UPLOADS: Bucket = Bucket::named("uploads");
//!
//! // Writes `state.json` only if no one else has since it was read.
//! async fn save(next: Vec<u8>) -> Result<bool, objects::Error> {
//!     let seen = UPLOADS.attrs("state.json").await?;
//!     match UPLOADS.upload_if_match("state.json", next, seen.revision()).await {
//!         Ok(_) => Ok(true),
//!         Err(objects::Error::PreconditionFailed) => Ok(false),
//!         Err(err) => Err(err),
//!     }
//! }
//! ```
//!
//! Where a function returns an [`encore::Error`](crate::Error), such as a
//! Pub/Sub handler, convert it there with the code that fits:
//!
//! ```no_run
//! # use encore::objects::Bucket;
//! # static UPLOADS: Bucket = Bucket::named("uploads");
//! async fn on_upload(key: &str) -> Result<(), encore::Error> {
//!     let attrs = UPLOADS
//!         .attrs(key)
//!         .await
//!         .map_err(|e| encore::Error::internal(e.to_string()))?;
//!     println!("{} is {} bytes", attrs.name, attrs.size);
//!     Ok(())
//! }
//! ```

use std::collections::BTreeMap;
use std::future::{poll_fn, Future, IntoFuture};
use std::marker::PhantomData;
use std::ops::{Bound, RangeBounds};
use std::pin::Pin;
use std::task::{Context, Poll};
use std::time::{Duration, SystemTime};

use bytes::Bytes;
use encore_sdk_core::objects;
use futures_core::future::BoxFuture;
use futures_core::Stream;
use tokio::io::AsyncRead;
use tokio_util::io::StreamReader;

use crate::perm::{Flag, Granted, No};
use crate::runtime::core;

/// Re-exported types the bucket operations take and return.
pub use encore_sdk_core::objects::{
    ByteRange, ListEntry, ObjectAttrs, ObjectVersion, Revision, StorageClass,
};

/// What a bucket operation failed with. See the [module docs](self#errors).
///
/// It is this module's own error and doesn't convert into
/// [`encore::Error`](crate::Error): where a function returns one, map it with
/// the code that fits the caller.
#[derive(Debug, thiserror::Error)]
#[non_exhaustive]
pub enum Error {
    /// The object, or the version of it asked for, does not exist.
    #[error("object not found")]
    NotFound,
    /// A precondition of the call does not hold: the object exists already
    /// (`not_exists`), or is no longer the revision named (`upload_if_match`,
    /// `remove_if_match`, `if_match`).
    #[error("precondition failed")]
    PreconditionFailed,
    /// Retention keeps the object from being deleted or overwritten yet: the
    /// bucket's retention period, or the object's own retain-until time.
    #[error("object is retained")]
    Retained,
    /// A mistake in the call itself, saying what it is: a malformed version,
    /// metadata the provider can't keep, a retain-until time earlier than the
    /// object's, …
    #[error("invalid argument: {0}")]
    InvalidArgument(String),
    /// Anything else, such as a failure to reach the provider.
    #[error(transparent)]
    Other(Box<dyn std::error::Error + Send + Sync>),
}

impl Error {
    /// An [`Error::Other`] with `message`.
    fn other(message: impl Into<String>) -> Self {
        Error::Other(message.into().into())
    }
}

/// The core's error as this module's. Its `Internal` and `Other` are both
/// [`Error::Other`], which keeps the core's error.
fn obj_err(err: objects::Error) -> Error {
    match err {
        objects::Error::NotFound => Error::NotFound,
        objects::Error::PreconditionFailed => Error::PreconditionFailed,
        objects::Error::Retained => Error::Retained,
        objects::Error::InvalidArgument(message) => Error::InvalidArgument(message.into_owned()),
        err @ (objects::Error::Internal(_) | objects::Error::Other(_)) => {
            Error::Other(Box::new(err))
        }
    }
}

/// `err`, from setting up the current test's instance of a bucket under
/// `encore test`, as this module's error.
fn test_err(err: crate::Error) -> Error {
    Error::Other(Box::new(err))
}

/// A download of an object, begun: returned by [`Bucket::download`], once
/// the provider has answered. It knows what the provider said of the object
/// — its [`revision`](Download::revision), [`size`](Download::size),
/// [`content_type`](Download::content_type) and
/// [`last_modified`](Download::last_modified) — and its contents are still
/// to come: take them all at once with [`Download::bytes`], as they arrive
/// with [`Download::bytes_stream`], or as an [`AsyncRead`] with
/// [`Download::into_async_read`].
///
/// ```no_run
/// # use encore::objects::Bucket;
/// # static UPLOADS: Bucket = Bucket::named("uploads");
/// # async fn f(mut file: tokio::fs::File) -> Result<(), Box<dyn std::error::Error>> {
/// // In one piece.
/// let bytes = UPLOADS.download("a.pdf").await?.bytes().await?;
///
/// // Or as it arrives, straight into a file.
/// let mut reader = UPLOADS.download("big.bin").await?.into_async_read();
/// tokio::io::copy(&mut reader, &mut file).await?;
/// # Ok(())
/// # }
/// ```
///
/// The revision is of the very bytes read, which is what replacing an object
/// only if nobody else has since takes:
///
/// ```no_run
/// # use encore::objects::{self, Bucket};
/// # static STATE: Bucket = Bucket::named("state");
/// # fn advance(seen: &[u8]) -> Vec<u8> { seen.to_vec() }
/// async fn step() -> Result<bool, objects::Error> {
///     let read = STATE.download("head").await?;
///     let revision = read.revision();
///     let next = advance(&read.bytes().await?);
///     match STATE.upload_if_match("head", next, revision).await {
///         Ok(_) => Ok(true),
///         Err(objects::Error::PreconditionFailed) => Ok(false),
///         Err(err) => Err(err),
///     }
/// }
/// ```
///
/// A download not read to its end holds its connection until it is dropped,
/// which cancels what is left of it.
pub struct Download {
    inner: objects::Download,
}

impl Download {
    /// A download of `data`, as the contents of an object with `attrs`: what
    /// a fake of [`Downloader`] answers with.
    pub fn of(attrs: &ObjectAttrs, data: impl Into<Bytes>) -> Self {
        let data: Bytes = data.into();
        Download {
            inner: objects::Download {
                info: objects::DownloadInfo {
                    revision: attrs.revision(),
                    size: attrs.size,
                    content_type: attrs.content_type.clone(),
                    last_modified: attrs.last_modified,
                },
                length: data.len() as u64,
                stream: Box::pin(Once(Some(data))),
            },
        }
    }

    /// The revision the contents are of, for
    /// [`upload_if_match`](Bucket::upload_if_match),
    /// [`remove_if_match`](Bucket::remove_if_match) or an `if_match`: the
    /// same as [`ObjectAttrs::revision`] gives for it.
    pub fn revision(&self) -> Revision {
        self.inner.info.revision.clone()
    }

    /// The size of the whole object in bytes, also when only a range of it
    /// is downloaded.
    pub fn size(&self) -> u64 {
        self.inner.info.size
    }

    /// The object's content type, if it has one.
    pub fn content_type(&self) -> Option<&str> {
        self.inner.info.content_type.as_deref()
    }

    /// When the object last changed; `None` if the provider didn't say.
    pub fn last_modified(&self) -> Option<SystemTime> {
        self.inner.info.last_modified
    }

    /// The contents, in one piece.
    pub async fn bytes(self) -> Result<Vec<u8>, Error> {
        self.inner.bytes().await.map_err(obj_err)
    }

    /// The contents as they arrive: a stream of chunks, each as large as it
    /// happened to arrive.
    pub fn bytes_stream(self) -> impl Stream<Item = Result<Bytes, Error>> + Send + Unpin + 'static {
        Chunks(self.inner.stream)
    }

    /// The contents 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(Chunks(self.inner.stream)))
    }
}

impl std::fmt::Debug for Download {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        self.inner.fmt(f)
    }
}

/// A download's chunks, its errors this module's.
struct Chunks(objects::DownloadStream);

impl Stream for Chunks {
    type Item = Result<Bytes, Error>;

    fn poll_next(self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<Option<Self::Item>> {
        self.get_mut()
            .0
            .as_mut()
            .poll_next(cx)
            .map(|chunk| chunk.map(|chunk| chunk.map_err(obj_err)))
    }
}

/// A download whose errors are `io::Error`s, as a reader's are.
struct ChunkErrors(Chunks);

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)))
    }
}

/// A stream of one chunk.
struct Once(Option<Bytes>);

impl Stream for Once {
    type Item = Result<Bytes, objects::Error>;

    fn poll_next(self: Pin<&mut Self>, _: &mut Context<'_>) -> Poll<Option<Self::Item>> {
        Poll::Ready(self.get_mut().0.take().map(Ok))
    }
}

/// 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(obj_err)))
    }
}

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

impl VersionIterator {
    /// The next version, or `None` once there are no more.
    pub async fn next(&mut self) -> Option<Result<ObjectVersion, Error>> {
        poll_fn(|cx| Pin::new(&mut *self).poll_next(cx)).await
    }
}

impl Stream for VersionIterator {
    type Item = Result<ObjectVersion, 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(|version| version.map(|version| version.map_err(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)))
    }
}

/// What an upload writes: bytes held in memory — a `Vec<u8>`, `Bytes`,
/// `&'static [u8]` or `String` — or contents streamed from a
/// [`reader`](Self::reader) or a stream of [`chunks`](Self::chunks).
pub struct UploadBody(Body);

enum Body {
    Bytes(Bytes),
    Reader(Box<dyn AsyncRead + Unpin + Send + Sync + 'static>),
}

impl UploadBody {
    /// The contents of `reader`, streamed rather than buffered.
    pub fn reader(reader: impl AsyncRead + Unpin + Send + Sync + 'static) -> Self {
        UploadBody(Body::Reader(Box::new(reader)))
    }

    /// The contents of 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]`. An error in the stream
    /// fails the upload, which then stores nothing.
    ///
    /// ```ignore
    /// let chunks = futures::stream::iter([Ok::<_, std::io::Error>(Bytes::from("hello"))]);
    /// UPLOADS.upload("greeting.txt", UploadBody::chunks(chunks)).await?;
    /// ```
    pub fn chunks<S, B, E>(chunks: S) -> Self
    where
        S: Stream<Item = Result<B, E>> + Send + 'static,
        B: Into<Bytes> + 'static,
        E: Into<Box<dyn std::error::Error + Send + Sync>> + 'static,
    {
        Self::reader(StreamReader::new(ChunkReader(std::sync::Mutex::new(
            Box::pin(chunks),
        ))))
    }

    /// The contents as a reader, as an upload reads them: for a fake
    /// [`Uploader`] that wants them.
    pub fn into_async_read(self) -> impl AsyncRead + Unpin + Send + Sync + 'static {
        self.into_reader()
    }

    fn into_reader(self) -> Box<dyn AsyncRead + Unpin + Send + Sync + 'static> {
        match self.0 {
            Body::Bytes(bytes) => Box::new(std::io::Cursor::new(bytes)),
            Body::Reader(reader) => reader,
        }
    }
}

impl From<Bytes> for UploadBody {
    fn from(bytes: Bytes) -> Self {
        UploadBody(Body::Bytes(bytes))
    }
}

impl From<Vec<u8>> for UploadBody {
    fn from(bytes: Vec<u8>) -> Self {
        Bytes::from(bytes).into()
    }
}

impl From<&'static [u8]> for UploadBody {
    fn from(bytes: &'static [u8]) -> Self {
        Bytes::from_static(bytes).into()
    }
}

impl From<String> for UploadBody {
    fn from(text: String) -> Self {
        Bytes::from(text).into()
    }
}

/// 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,
}

/// A rule of a bucket's [lifecycle](Bucket::lifecycle): an optional
/// [`prefix`](Self::prefix) and at least one action. The provider applies
/// it, usually within a day of an object becoming due, never early.
///
/// Days count from when an object was written or, for the noncurrent
/// actions, from when a version was replaced or removed. They are whole
/// numbers from 1 to 36500, written as literals: Encore reads them from the
/// declaration.
///
/// ```no_run
/// use encore::objects::{Bucket, LifecycleRule};
///
/// static LOGS: Bucket = Bucket::new("logs").lifecycle(&[LifecycleRule::new()
///     .prefix("app/")
///     .move_to_infrequent_after_days(30)
///     .move_to_cold_after_days(90)
///     .delete_after_days(365)]);
/// ```
#[derive(Debug, Clone, Copy)]
// Read by Encore's parser from the declaration, not by the runtime.
#[allow(dead_code)]
pub struct LifecycleRule {
    prefix: Option<&'static str>,
    move_to_infrequent_after_days: Option<u32>,
    move_to_cold_after_days: Option<u32>,
    delete_after_days: Option<u32>,
    delete_noncurrent_after_days: Option<u32>,
    keep_noncurrent_versions: Option<u32>,
}

impl LifecycleRule {
    /// A rule for every object in the bucket, with no actions yet: add at
    /// least one.
    pub const fn new() -> Self {
        Self {
            prefix: None,
            move_to_infrequent_after_days: None,
            move_to_cold_after_days: None,
            delete_after_days: None,
            delete_noncurrent_after_days: None,
            keep_noncurrent_versions: None,
        }
    }

    /// Applies the rule only to objects whose names start with `prefix`.
    pub const fn prefix(mut self, prefix: &'static str) -> Self {
        self.prefix = Some(prefix);
        self
    }

    /// Moves an object to [`StorageClass::Infrequent`] this many days after
    /// it was written: at least 30.
    pub const fn move_to_infrequent_after_days(mut self, days: u32) -> Self {
        self.move_to_infrequent_after_days = Some(days);
        self
    }

    /// Moves an object to [`StorageClass::Cold`] this many days after it was
    /// written: with [`move_to_infrequent_after_days`](Self::move_to_infrequent_after_days),
    /// at least 30 days after that.
    pub const fn move_to_cold_after_days(mut self, days: u32) -> Self {
        self.move_to_cold_after_days = Some(days);
        self
    }

    /// Deletes an object this many days after it was written, later than
    /// the rule's moves. In a versioned bucket it becomes a noncurrent
    /// version, as [`Bucket::remove`] makes it.
    pub const fn delete_after_days(mut self, days: u32) -> Self {
        self.delete_after_days = Some(days);
        self
    }

    /// Versioned buckets: deletes a noncurrent version this many days after
    /// it was replaced or removed.
    pub const fn delete_noncurrent_after_days(mut self, days: u32) -> Self {
        self.delete_noncurrent_after_days = Some(days);
        self
    }

    /// Versioned buckets: never deletes the newest `count` noncurrent
    /// versions of an object. On its own, deletes the noncurrent versions
    /// beyond them.
    pub const fn keep_noncurrent_versions(mut self, count: u32) -> Self {
        self.keep_noncurrent_versions = Some(count);
        self
    }
}

impl Default for LifecycleRule {
    fn default() -> Self {
        Self::new()
    }
}

/// How long a bucket keeps every object it is written, at least: see
/// [`Bucket::retention`].
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub struct Retention {
    /// Read by Encore's parser from the declaration, not by the runtime.
    #[allow(dead_code)]
    days: u32,
}

impl Retention {
    /// Keeps each object for `days` days after it was written: from 1 to
    /// 36500, as a literal.
    pub const fn days(days: u32) -> Self {
        Self { days }
    }
}

/// 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,
    #[allow(dead_code)]
    storage_class: Option<StorageClass>,
    #[allow(dead_code)]
    lifecycle: &'static [LifecycleRule],
    #[allow(dead_code)]
    retention: Option<Retention>,
    #[allow(dead_code)]
    object_retention: 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,
            storage_class: None,
            lifecycle: &[],
            retention: None,
            object_retention: 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
    /// an operation's `version` option can name.
    ///
    /// Part of the declaration, like [`Bucket::public`].
    pub const fn versioned(mut self) -> Self {
        self.versioned = true;
        self
    }

    /// The storage class an upload gets when it names none, and so how the
    /// provider prices the bucket's objects. [`StorageClass::Auto`] lets the
    /// provider move each object by how often it is read; it is a bucket's
    /// class only, and allows no lifecycle moves. Standard if not given.
    ///
    /// Part of the declaration, like [`Bucket::public`].
    pub const fn storage_class(mut self, class: StorageClass) -> Self {
        self.storage_class = Some(class);
        self
    }

    /// Rules the provider applies to the bucket's objects: moving them to a
    /// colder class, or deleting them, some days after they were written.
    /// A rule applies to the objects already in the bucket too. At most 100.
    ///
    /// Part of the declaration, like [`Bucket::public`].
    ///
    /// ```no_run
    /// use encore::objects::{Bucket, LifecycleRule};
    ///
    /// static UPLOADS: Bucket = Bucket::new("uploads").versioned().lifecycle(&[
    ///     LifecycleRule::new().prefix("tmp/").delete_after_days(1),
    ///     LifecycleRule::new().delete_noncurrent_after_days(30).keep_noncurrent_versions(5),
    /// ]);
    /// ```
    pub const fn lifecycle(mut self, rules: &'static [LifecycleRule]) -> Self {
        self.lifecycle = rules;
        self
    }

    /// Keeps every object at least this long after it was written: until
    /// then it can't be deleted or overwritten, which fails with
    /// [`Error::Retained`]. On AWS such a delete or overwrite succeeds, but
    /// the version written is kept underneath until its retention ends.
    ///
    /// Part of the declaration, like [`Bucket::public`].
    ///
    /// ```no_run
    /// use encore::objects::{Bucket, Retention};
    ///
    /// static INVOICES: Bucket = Bucket::new("invoices").retention(Retention::days(2555));
    /// ```
    pub const fn retention(mut self, retention: Retention) -> Self {
        self.retention = Some(retention);
        self
    }

    /// Lets objects carry their own retain-until time: set on upload with
    /// [`UploadRequest::retain_until`], and later with
    /// [`Bucket::extend_retention`]. Not supported on Cloudflare R2.
    ///
    /// Part of the declaration, like [`Bucket::public`].
    pub const fn object_retention(mut self) -> Self {
        self.object_retention = true;
        self
    }

    /// Tags the bucket with `key` and `value`: key/value classification, such
    /// as `.tag("data", "pci")`, for policies to read. One call per tag, each
    /// with its own key. Encore reads them from the source, so both are string
    /// literals. A key is lowercase letters, digits, `_` and `-`, starting with
    /// a letter and not with `encore`, which is kept for Encore's own tags; a
    /// value is the same characters, or empty. Each is at most 63 characters,
    /// and a bucket has at most 32 tags.
    ///
    /// Part of the declaration: it takes the bucket by value, so it cannot be
    /// called on the `static`.
    ///
    /// ```no_run
    /// use encore::objects::Bucket;
    ///
    /// static RECEIPTS: Bucket = Bucket::new("receipts").tag("data", "pci");
    /// ```
    pub const fn tag(self, _key: &'static str, _value: &'static str) -> Self {
        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().map_err(test_err)? {
            return test.bucket(self.name).map_err(test_err);
        }
        core()
            .objects()
            .bucket(self.name.into())
            .ok_or_else(|| Error::other(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, as an iterator of entries: all of
    /// them, or those the request's options select.
    ///
    /// With a [`delimiter`](ListRequest::delimiter), names are grouped by the
    /// part after the prefix up to the delimiter, as a directory listing does:
    /// each group is one entry with [`ListEntry::is_prefix`] set, whose name
    /// ends in the delimiter. Groups and objects are listed in order, and the
    /// limit counts both.
    ///
    /// ```no_run
    /// # use encore::objects::Bucket;
    /// # static UPLOADS: Bucket = Bucket::named("uploads");
    /// # async fn f() -> Result<(), encore::objects::Error> {
    /// let mut entries = UPLOADS.list().prefix("users/42/").delimiter("/").await?;
    /// while let Some(entry) = entries.next().await {
    ///     let entry = entry?;
    ///     if entry.is_prefix {
    ///         println!("{}  (folder)", entry.name); // users/42/photos/
    ///     } else {
    ///         println!("{}", entry.name);
    ///     }
    /// }
    /// # Ok(())
    /// # }
    /// ```
    pub fn list(&self) -> ListRequest<'_> {
        ListRequest::new(self)
    }

    /// List every stored version of the bucket's objects: by name, then
    /// newest first. A removed object has no
    /// [`latest`](ObjectVersion::latest) version. An unversioned bucket lists
    /// each object's one version.
    ///
    /// ```no_run
    /// # use encore::objects::Bucket;
    /// # static UPLOADS: Bucket = Bucket::named("uploads");
    /// # async fn f() -> Result<(), encore::objects::Error> {
    /// let mut versions = UPLOADS.list_versions().prefix("invoices/").await?;
    /// while let Some(v) = versions.next().await {
    ///     let v = v?;
    ///     println!("{} {:?} latest={}", v.name, v.version, v.latest);
    /// }
    /// # Ok(())
    /// # }
    /// ```
    pub fn list_versions(&self) -> ListVersionsRequest<'_> {
        ListVersionsRequest::new(self)
    }

    /// Whether an object with `key` exists.
    pub fn exists(&self, key: &str) -> ExistsRequest<'_> {
        ExistsRequest::new(self, key)
    }

    /// The attributes of the object `key`: its size, content type, version,
    /// etag, metadata, …
    pub fn attrs(&self, key: &str) -> AttrsRequest<'_> {
        AttrsRequest::new(self, key)
    }

    /// Upload `data` to the object `key`, returning its stored attributes.
    /// `data` is bytes, or [`UploadBody::reader`] or [`UploadBody::chunks`]
    /// to stream them.
    ///
    /// ```no_run
    /// # use encore::objects::{Bucket, StorageClass, UploadBody};
    /// # static UPLOADS: Bucket = Bucket::named("uploads");
    /// # async fn f(data: Vec<u8>, file: tokio::fs::File) -> Result<(), encore::objects::Error> {
    /// UPLOADS
    ///     .upload("a.pdf", data)
    ///     .content_type("application/pdf")
    ///     .cache_control("public, max-age=3600")
    ///     .metadata([("owner", "42")])
    ///     .storage_class(StorageClass::Cold)
    ///     .await?;
    ///
    /// // Streamed, and only if there is no such object yet.
    /// UPLOADS
    ///     .upload("b.pdf", UploadBody::reader(file))
    ///     .not_exists()
    ///     .await?;
    /// # Ok(())
    /// # }
    /// ```
    pub fn upload(&self, key: &str, data: impl Into<UploadBody>) -> UploadRequest<'_> {
        UploadRequest::new(self, key, data.into())
    }

    /// Upload `data` to the object `key` only if it is still the revision
    /// `revision` names, from [`ObjectAttrs::revision`] or, for what was read
    /// of it, [`Download::revision`]: if another write
    /// came first, or the object is gone, it is
    /// [`Error::PreconditionFailed`]. Takes the options of
    /// [`upload`](Self::upload) but `not_exists`.
    ///
    /// The match compares the object's contents, not its attributes:
    /// [`update_attrs`](Self::update_attrs) doesn't break it. On AWS it needs
    /// read access to the bucket too, which Encore grants for it.
    ///
    /// ```no_run
    /// # use encore::objects::Bucket;
    /// # static UPLOADS: Bucket = Bucket::named("uploads");
    /// # async fn f(next: Vec<u8>) -> Result<(), encore::objects::Error> {
    /// let seen = UPLOADS.attrs("state.json").await?;
    /// UPLOADS
    ///     .upload_if_match("state.json", next, seen.revision())
    ///     .content_type("application/json")
    ///     .await?;
    /// # Ok(())
    /// # }
    /// ```
    pub fn upload_if_match(
        &self,
        key: &str,
        data: impl Into<UploadBody>,
        revision: Revision,
    ) -> UploadIfMatchRequest<'_> {
        UploadIfMatchRequest::new(self, key, data.into(), revision)
    }

    /// Change the attributes of the object `key`: its content type, cache
    /// control, content disposition or metadata, each a method of the
    /// request. One not set stays as it is. Returns the object's attributes
    /// after.
    ///
    /// On S3 this writes the object anew, so in a versioned bucket it makes a
    /// new version.
    ///
    /// ```no_run
    /// # use encore::objects::Bucket;
    /// # static UPLOADS: Bucket = Bucket::named("uploads");
    /// # async fn f() -> Result<(), encore::objects::Error> {
    /// let attrs = UPLOADS.attrs("a.pdf").await?;
    /// UPLOADS
    ///     .update_attrs("a.pdf")
    ///     .cache_control("no-store")
    ///     .if_match(attrs.revision())
    ///     .await?;
    /// # Ok(())
    /// # }
    /// ```
    pub fn update_attrs(&self, key: &str) -> UpdateAttrsRequest<'_> {
        UpdateAttrsRequest::new(self, key)
    }

    /// Keep the object `key` until `until` at least, in a bucket declared
    /// with [`Bucket::object_retention`]. Retention can only be extended: a
    /// time earlier than the object's is [`Error::InvalidArgument`]. Returns
    /// the object's attributes after.
    pub fn extend_retention(&self, key: &str, until: SystemTime) -> ExtendRetentionRequest<'_> {
        ExtendRetentionRequest::new(self, key, until)
    }

    /// Download the object `key`, or a version of it, or a byte range.
    /// Awaited, it is a [`Download`] as soon as the provider has answered:
    /// an object that isn't there is [`Error::NotFound`] here, and what the
    /// provider says of the object is known, before any of its contents.
    /// They are read from the [`Download`], whole or as they arrive.
    ///
    /// ```no_run
    /// # use encore::objects::Bucket;
    /// # static UPLOADS: Bucket = Bucket::named("uploads");
    /// # async fn f() -> Result<(), encore::objects::Error> {
    /// let whole = UPLOADS.download("a.pdf").await?.bytes().await?;
    ///
    /// // The 256 bytes starting at offset 1024.
    /// let part = UPLOADS.download("big.bin").range(1024..1280).await?;
    /// let (size, bytes) = (part.size(), part.bytes().await?);
    ///
    /// // The last 64 bytes, however large the object is.
    /// let tail = UPLOADS.download("big.bin").last(64).await?.bytes().await?;
    /// # Ok(())
    /// # }
    /// ```
    pub fn download(&self, key: &str) -> DownloadRequest<'_> {
        DownloadRequest::new(self, key)
    }

    /// Remove the object `key`, or a version of it.
    pub fn remove(&self, key: &str) -> RemoveRequest<'_> {
        RemoveRequest::new(self, key)
    }

    /// Remove the object `key` only if it is still the revision `revision`
    /// names, from [`ObjectAttrs::revision`] or [`Download::revision`]: if
    /// another write came first,
    /// or it is gone already, it is [`Error::PreconditionFailed`].
    ///
    /// The match compares the object's contents, not its attributes. On AWS
    /// it needs read access to the bucket too, which Encore grants for it.
    /// Cloudflare R2 can't remove conditionally: there it is
    /// [`Error::InvalidArgument`].
    ///
    /// ```no_run
    /// # use encore::objects::Bucket;
    /// # static UPLOADS: Bucket = Bucket::named("uploads");
    /// # async fn f() -> Result<(), encore::objects::Error> {
    /// let attrs = UPLOADS.attrs("lock.json").await?;
    /// UPLOADS.remove_if_match("lock.json", attrs.revision()).await?;
    /// # Ok(())
    /// # }
    /// ```
    pub async fn remove_if_match(&self, key: &str, revision: Revision) -> Result<(), Error> {
        let options = objects::DeleteOptions {
            version: None,
            if_match: Some(revision),
        };
        self.object(key)?.delete(options).await.map_err(obj_err)
    }

    /// A URL through which anyone holding it can upload the object `key`:
    /// valid for an hour, or the request's [`ttl`](SignedUploadUrlRequest::ttl).
    pub fn signed_upload_url(&self, key: &str) -> SignedUploadUrlRequest<'_> {
        SignedUploadUrlRequest::new(self, key)
    }

    /// A URL through which anyone holding it can download the object `key`:
    /// valid for an hour, or the request's
    /// [`ttl`](SignedDownloadUrlRequest::ttl).
    pub fn signed_download_url(&self, key: &str) -> SignedDownloadUrlRequest<'_> {
        SignedDownloadUrlRequest::new(self, key)
    }

    /// The public URL of the object `key`. Only a bucket declared `public`
    /// has one: for another it is [`Error::InvalidArgument`].
    pub fn public_url(&self, key: &str) -> Result<String, Error> {
        self.object(key)?.public_url().map_err(public_url_err)
    }
}

/// Why an object has no public URL, as this module's error.
fn public_url_err(err: objects::PublicUrlError) -> Error {
    match err {
        objects::PublicUrlError::PrivateBucket | objects::PublicUrlError::InvalidObjectName => {
            Error::InvalidArgument(err.to_string())
        }
        objects::PublicUrlError::NoopBucket => Error::Other(Box::new(err)),
    }
}

/// A request's two ways to run when awaited: on a [`Bucket`], and on what
/// implements the trait of its permission — a [`BucketRef`], or a fake —
/// through the trait's `run_` method.
macro_rules! into_future {
    ($request:ident => $output:ty, $trait:ident::$run:ident) => {
        impl<'a> IntoFuture for $request<'a, Bucket> {
            type Output = Result<$output, Error>;
            type IntoFuture = BoxFuture<'a, Self::Output>;

            fn into_future(self) -> Self::IntoFuture {
                let bucket = self.on;
                self.send(bucket)
            }
        }

        impl<'a, T: $trait + ?Sized> IntoFuture for $request<'a, T> {
            type Output = Result<$output, Error>;
            type IntoFuture = BoxFuture<'a, Self::Output>;

            fn into_future(self) -> Self::IntoFuture {
                let on = self.on;
                Box::pin(on.$run(self))
            }
        }
    };
}

/// The setter of a request's `version`: the operation is on that version of
/// the object rather than the current one.
macro_rules! version_setter {
    () => {
        /// On this version of the object, in a versioned bucket, rather than
        /// the current one.
        pub fn version(mut self, version: impl Into<String>) -> Self {
            self.version = Some(version.into());
            self
        }
    };
}

/// The setters of the attributes an upload writes, which an upload if it
/// matches shares.
macro_rules! upload_setters {
    () => {
        /// The object's content type, such as `application/pdf`.
        pub fn content_type(mut self, content_type: impl Into<String>) -> Self {
            self.content_type = Some(content_type.into());
            self
        }

        /// The `Cache-Control` the object is served with, such as
        /// `public, max-age=3600`.
        pub fn cache_control(mut self, cache_control: impl Into<String>) -> Self {
            self.cache_control = Some(cache_control.into());
            self
        }

        /// The `Content-Disposition` the object is served with, such as
        /// `attachment; filename="a.pdf"`.
        pub fn content_disposition(mut self, content_disposition: impl Into<String>) -> Self {
            self.content_disposition = Some(content_disposition.into());
            self
        }

        /// Adds custom metadata, replacing that of the same names: a map, or
        /// pairs such as `[("owner", "42")]`. Keys are lowercase letters,
        /// digits, `-` and `_`, not starting with `-` or `_`; values are
        /// printable ASCII.
        pub fn metadata<K, V>(mut self, metadata: impl IntoIterator<Item = (K, V)>) -> Self
        where
            K: Into<String>,
            V: Into<String>,
        {
            extend(&mut self.metadata, metadata);
            self
        }

        /// The object's storage class, rather than the bucket's. Never
        /// [`StorageClass::Auto`], which is a bucket's class only.
        pub fn storage_class(mut self, class: StorageClass) -> Self {
            self.storage_class = Some(class);
            self
        }

        /// Keeps the object until `until` at least, in a bucket declared with
        /// [`Bucket::object_retention`].
        pub fn retain_until(mut self, until: SystemTime) -> Self {
            self.retain_until = Some(until);
            self
        }
    };
}

/// Adds `pairs` to `into`, replacing those of the same names.
fn extend<K: Into<String>, V: Into<String>>(
    into: &mut BTreeMap<String, String>,
    pairs: impl IntoIterator<Item = (K, V)>,
) {
    into.extend(pairs.into_iter().map(|(k, v)| (k.into(), v.into())));
}

/// A Rust range of bytes as the core's: `0..1024`, `1024..`, `..=99`. An
/// empty one is empty there too, which the core refuses.
fn byte_range(range: impl RangeBounds<u64>) -> ByteRange {
    let offset = match range.start_bound() {
        Bound::Included(&start) => start,
        Bound::Excluded(&start) => start.saturating_add(1),
        Bound::Unbounded => 0,
    };
    let length = match range.end_bound() {
        Bound::Included(&end) => Some(end.saturating_sub(offset).saturating_add(1)),
        Bound::Excluded(&end) => Some(end.saturating_sub(offset)),
        Bound::Unbounded => None,
    };
    // `5..=3` is as empty as `5..3`.
    let length = match range.end_bound() {
        Bound::Included(&end) if end < offset => Some(0),
        _ => length,
    };
    ByteRange::from(offset, length)
}

/// How long a signed URL is valid for when its request sets no `ttl`.
const SIGNED_URL_TTL: Duration = Duration::from_secs(60 * 60);

/// The upload [`Bucket::upload`] makes: set its options with its methods,
/// then await it. Returns the object's stored attributes.
///
/// Its fields are what the request asks for, for a fake [`Uploader`] to read.
pub struct UploadRequest<'a, T: ?Sized = Bucket> {
    on: &'a T,
    pub key: String,
    pub data: UploadBody,
    pub content_type: Option<String>,
    pub cache_control: Option<String>,
    pub content_disposition: Option<String>,
    pub metadata: BTreeMap<String, String>,
    pub storage_class: Option<StorageClass>,
    pub retain_until: Option<SystemTime>,
    pub not_exists: bool,
}

impl<'a, T: ?Sized> UploadRequest<'a, T> {
    fn new(on: &'a T, key: &str, data: UploadBody) -> Self {
        Self {
            on,
            key: key.to_string(),
            data,
            content_type: None,
            cache_control: None,
            content_disposition: None,
            metadata: BTreeMap::new(),
            storage_class: None,
            retain_until: None,
            not_exists: false,
        }
    }

    upload_setters!();

    /// Only if there is no object with the key yet: if there is, it is
    /// [`Error::PreconditionFailed`].
    pub fn not_exists(mut self) -> Self {
        self.not_exists = true;
        self
    }

    fn send<'b>(self, bucket: &'b Bucket) -> BoxFuture<'b, Result<ObjectAttrs, Error>> {
        let preconditions = self.not_exists.then_some(objects::UploadPreconditions {
            not_exists: Some(true),
            if_match: None,
        });
        let options = objects::UploadOptions {
            content_type: self.content_type,
            cache_control: self.cache_control,
            content_disposition: self.content_disposition,
            metadata: self.metadata,
            storage_class: self.storage_class,
            retain_until: self.retain_until,
            preconditions,
        };
        upload(bucket, self.key, self.data, options)
    }
}

into_future!(UploadRequest => ObjectAttrs, Uploader::run_upload);

/// The upload [`Bucket::upload_if_match`] makes: set its options with its
/// methods, then await it. Returns the object's stored attributes.
///
/// It takes an upload's options but `not_exists`:
///
/// ```compile_fail,E0599
/// # use encore::objects::{Bucket, Revision};
/// # static UPLOADS: Bucket = Bucket::named("uploads");
/// async fn upload(seen: Revision) {
///     let _ = UPLOADS.upload_if_match("a", vec![], seen).not_exists().await;
/// }
/// ```
///
/// Its fields are what the request asks for, for a fake [`IfMatchUploader`]
/// to read.
pub struct UploadIfMatchRequest<'a, T: ?Sized = Bucket> {
    on: &'a T,
    pub key: String,
    pub data: UploadBody,
    pub revision: Revision,
    pub content_type: Option<String>,
    pub cache_control: Option<String>,
    pub content_disposition: Option<String>,
    pub metadata: BTreeMap<String, String>,
    pub storage_class: Option<StorageClass>,
    pub retain_until: Option<SystemTime>,
}

impl<'a, T: ?Sized> UploadIfMatchRequest<'a, T> {
    fn new(on: &'a T, key: &str, data: UploadBody, revision: Revision) -> Self {
        Self {
            on,
            key: key.to_string(),
            data,
            revision,
            content_type: None,
            cache_control: None,
            content_disposition: None,
            metadata: BTreeMap::new(),
            storage_class: None,
            retain_until: None,
        }
    }

    upload_setters!();

    fn send<'b>(self, bucket: &'b Bucket) -> BoxFuture<'b, Result<ObjectAttrs, Error>> {
        let options = objects::UploadOptions {
            content_type: self.content_type,
            cache_control: self.cache_control,
            content_disposition: self.content_disposition,
            metadata: self.metadata,
            storage_class: self.storage_class,
            retain_until: self.retain_until,
            preconditions: Some(objects::UploadPreconditions {
                not_exists: None,
                if_match: Some(self.revision),
            }),
        };
        upload(bucket, self.key, self.data, options)
    }
}

into_future!(UploadIfMatchRequest => ObjectAttrs, IfMatchUploader::run_upload_if_match);

/// Uploads `data` to the object `key` of `bucket`.
fn upload(
    bucket: &Bucket,
    key: String,
    data: UploadBody,
    options: objects::UploadOptions,
) -> BoxFuture<'_, Result<ObjectAttrs, Error>> {
    Box::pin(async move {
        bucket
            .object(&key)?
            .upload(data.into_reader(), options)
            .await
            .map_err(obj_err)
    })
}

/// The change [`Bucket::update_attrs`] makes: set the attributes to change
/// with its methods, then await it. An attribute not set stays as it is, and
/// an empty string clears it; a cleared content type is
/// `application/octet-stream`, as S3 keeps no object without one. Returns
/// the object's attributes after.
///
/// Its fields are what the request asks for, for a fake [`AttrsUpdater`] to
/// read.
pub struct UpdateAttrsRequest<'a, T: ?Sized = Bucket> {
    on: &'a T,
    pub key: String,
    pub content_type: Option<String>,
    pub cache_control: Option<String>,
    pub content_disposition: Option<String>,
    pub metadata: Option<BTreeMap<String, String>>,
    pub version: Option<String>,
    pub if_match: Option<Revision>,
}

impl<'a, T: ?Sized> UpdateAttrsRequest<'a, T> {
    fn new(on: &'a T, key: &str) -> Self {
        Self {
            on,
            key: key.to_string(),
            content_type: None,
            cache_control: None,
            content_disposition: None,
            metadata: None,
            version: None,
            if_match: None,
        }
    }

    /// The object's content type, such as `application/pdf`.
    pub fn content_type(mut self, content_type: impl Into<String>) -> Self {
        self.content_type = Some(content_type.into());
        self
    }

    /// The `Cache-Control` the object is served with.
    pub fn cache_control(mut self, cache_control: impl Into<String>) -> Self {
        self.cache_control = Some(cache_control.into());
        self
    }

    /// The `Content-Disposition` the object is served with.
    pub fn content_disposition(mut self, content_disposition: impl Into<String>) -> Self {
        self.content_disposition = Some(content_disposition.into());
        self
    }

    /// Replaces the object's metadata with these pairs, as many as are
    /// given: `[]` clears it.
    pub fn metadata<K, V>(mut self, metadata: impl IntoIterator<Item = (K, V)>) -> Self
    where
        K: Into<String>,
        V: Into<String>,
    {
        extend(self.metadata.get_or_insert_default(), metadata);
        self
    }

    version_setter!();

    /// Only if the object is still the revision `revision` names: if not, it
    /// is [`Error::PreconditionFailed`].
    pub fn if_match(mut self, revision: Revision) -> Self {
        self.if_match = Some(revision);
        self
    }

    fn send<'b>(self, bucket: &'b Bucket) -> BoxFuture<'b, Result<ObjectAttrs, Error>> {
        let attrs = objects::UpdateAttrs {
            content_type: self.content_type,
            cache_control: self.cache_control,
            content_disposition: self.content_disposition,
            metadata: self.metadata,
        };
        let options = objects::UpdateAttrsOptions {
            version: self.version,
            if_match: self.if_match,
        };
        let key = self.key;
        Box::pin(async move {
            bucket
                .object(&key)?
                .update_attrs(attrs, options)
                .await
                .map_err(obj_err)
        })
    }
}

into_future!(UpdateAttrsRequest => ObjectAttrs, AttrsUpdater::run_update_attrs);

/// The extension [`Bucket::extend_retention`] makes: await it. Returns the
/// object's attributes after.
pub struct ExtendRetentionRequest<'a, T: ?Sized = Bucket> {
    on: &'a T,
    pub key: String,
    pub until: SystemTime,
    pub version: Option<String>,
}

impl<'a, T: ?Sized> ExtendRetentionRequest<'a, T> {
    fn new(on: &'a T, key: &str, until: SystemTime) -> Self {
        Self {
            on,
            key: key.to_string(),
            until,
            version: None,
        }
    }

    version_setter!();

    fn send<'b>(self, bucket: &'b Bucket) -> BoxFuture<'b, Result<ObjectAttrs, Error>> {
        let (key, until) = (self.key, self.until);
        let options = objects::ExtendRetentionOptions {
            version: self.version,
        };
        Box::pin(async move {
            bucket
                .object(&key)?
                .extend_retention(until, options)
                .await
                .map_err(obj_err)
        })
    }
}

into_future!(ExtendRetentionRequest => ObjectAttrs, AttrsUpdater::run_extend_retention);

/// The download [`Bucket::download`] makes: await it for the [`Download`].
pub struct DownloadRequest<'a, T: ?Sized = Bucket> {
    on: &'a T,
    pub key: String,
    pub version: Option<String>,
    pub range: Option<ByteRange>,
}

impl<'a, T: ?Sized> DownloadRequest<'a, T> {
    fn new(on: &'a T, key: &str) -> Self {
        Self {
            on,
            key: key.to_string(),
            version: None,
            range: None,
        }
    }

    version_setter!();

    /// Only these bytes of the object: `1024..1280`, `1024..`, `..=99`.
    /// An empty range is [`Error::InvalidArgument`], and so is one that
    /// starts beyond the object's end.
    pub fn range(mut self, range: impl RangeBounds<u64>) -> Self {
        self.range = Some(byte_range(range));
        self
    }

    /// Only the last `length` bytes of the object, or all of it if it has
    /// fewer. None is [`Error::InvalidArgument`]. [`Download::size`] says how
    /// large the object is, and so where in it the bytes sit.
    pub fn last(mut self, length: u64) -> Self {
        self.range = Some(ByteRange::last(length));
        self
    }

    fn send<'b>(self, bucket: &'b Bucket) -> BoxFuture<'b, Result<Download, Error>> {
        let options = objects::DownloadOptions {
            version: self.version,
            range: self.range,
        };
        let key = self.key;
        Box::pin(async move {
            bucket
                .object(&key)?
                .download(options)
                .await
                .map(|inner| Download { inner })
                .map_err(obj_err)
        })
    }
}

into_future!(DownloadRequest => Download, Downloader::run_download);

/// The request [`Bucket::attrs`] makes: await it for the object's
/// attributes.
pub struct AttrsRequest<'a, T: ?Sized = Bucket> {
    on: &'a T,
    pub key: String,
    pub version: Option<String>,
}

impl<'a, T: ?Sized> AttrsRequest<'a, T> {
    fn new(on: &'a T, key: &str) -> Self {
        Self {
            on,
            key: key.to_string(),
            version: None,
        }
    }

    version_setter!();

    fn send<'b>(self, bucket: &'b Bucket) -> BoxFuture<'b, Result<ObjectAttrs, Error>> {
        let key = self.key;
        let options = objects::AttrsOptions {
            version: self.version,
        };
        Box::pin(async move { bucket.object(&key)?.attrs(options).await.map_err(obj_err) })
    }
}

into_future!(AttrsRequest => ObjectAttrs, Attrser::run_attrs);

/// The request [`Bucket::exists`] makes: await it for whether the object
/// exists.
pub struct ExistsRequest<'a, T: ?Sized = Bucket> {
    on: &'a T,
    pub key: String,
    pub version: Option<String>,
}

impl<'a, T: ?Sized> ExistsRequest<'a, T> {
    fn new(on: &'a T, key: &str) -> Self {
        Self {
            on,
            key: key.to_string(),
            version: None,
        }
    }

    version_setter!();

    fn send<'b>(self, bucket: &'b Bucket) -> BoxFuture<'b, Result<bool, Error>> {
        let key = self.key;
        let options = objects::ExistsOptions {
            version: self.version,
        };
        Box::pin(async move { bucket.object(&key)?.exists(options).await.map_err(obj_err) })
    }
}

into_future!(ExistsRequest => bool, Attrser::run_exists);

/// The removal [`Bucket::remove`] makes: await it.
pub struct RemoveRequest<'a, T: ?Sized = Bucket> {
    on: &'a T,
    pub key: String,
    pub version: Option<String>,
}

impl<'a, T: ?Sized> RemoveRequest<'a, T> {
    fn new(on: &'a T, key: &str) -> Self {
        Self {
            on,
            key: key.to_string(),
            version: None,
        }
    }

    version_setter!();

    fn send<'b>(self, bucket: &'b Bucket) -> BoxFuture<'b, Result<(), Error>> {
        let key = self.key;
        let options = objects::DeleteOptions {
            version: self.version,
            if_match: None,
        };
        Box::pin(async move { bucket.object(&key)?.delete(options).await.map_err(obj_err) })
    }
}

into_future!(RemoveRequest => (), Remover::run_remove);

/// The listing [`Bucket::list`] makes: await it for the [`ListIterator`].
pub struct ListRequest<'a, T: ?Sized = Bucket> {
    on: &'a T,
    pub prefix: Option<String>,
    pub limit: Option<u64>,
    pub delimiter: Option<String>,
}

impl<'a, T: ?Sized> ListRequest<'a, T> {
    fn new(on: &'a T) -> Self {
        Self {
            on,
            prefix: None,
            limit: None,
            delimiter: None,
        }
    }

    /// Only the objects whose names start with `prefix`.
    pub fn prefix(mut self, prefix: impl Into<String>) -> Self {
        self.prefix = Some(prefix.into());
        self
    }

    /// At most `limit` entries, groups included.
    pub fn limit(mut self, limit: u64) -> Self {
        self.limit = Some(limit);
        self
    }

    /// Groups names by the part after the prefix up to the first
    /// `delimiter`, as a directory listing does: see [`Bucket::list`].
    pub fn delimiter(mut self, delimiter: impl Into<String>) -> Self {
        self.delimiter = Some(delimiter.into());
        self
    }

    fn send<'b>(self, bucket: &'b Bucket) -> BoxFuture<'b, Result<ListIterator, Error>> {
        let options = objects::ListOptions {
            prefix: self.prefix,
            limit: self.limit,
            delimiter: self.delimiter,
        };
        Box::pin(async move {
            bucket
                .resolve()?
                .list(options)
                .await
                .map(|inner| ListIterator { inner })
                .map_err(obj_err)
        })
    }
}

into_future!(ListRequest => ListIterator, Lister::run_list);

/// The listing [`Bucket::list_versions`] makes: await it for the
/// [`VersionIterator`].
pub struct ListVersionsRequest<'a, T: ?Sized = Bucket> {
    on: &'a T,
    pub prefix: Option<String>,
    pub limit: Option<u64>,
}

impl<'a, T: ?Sized> ListVersionsRequest<'a, T> {
    fn new(on: &'a T) -> Self {
        Self {
            on,
            prefix: None,
            limit: None,
        }
    }

    /// Only the versions of the objects whose names start with `prefix`.
    pub fn prefix(mut self, prefix: impl Into<String>) -> Self {
        self.prefix = Some(prefix.into());
        self
    }

    /// At most `limit` versions.
    pub fn limit(mut self, limit: u64) -> Self {
        self.limit = Some(limit);
        self
    }

    fn send<'b>(self, bucket: &'b Bucket) -> BoxFuture<'b, Result<VersionIterator, Error>> {
        let options = objects::ListOptions {
            prefix: self.prefix,
            limit: self.limit,
            delimiter: None,
        };
        Box::pin(async move {
            bucket
                .resolve()?
                .list_versions(options)
                .await
                .map(|inner| VersionIterator { inner })
                .map_err(obj_err)
        })
    }
}

into_future!(ListVersionsRequest => VersionIterator, Lister::run_list_versions);

/// The URL [`Bucket::signed_upload_url`] makes: await it.
pub struct SignedUploadUrlRequest<'a, T: ?Sized = Bucket> {
    on: &'a T,
    pub key: String,
    pub ttl: Option<Duration>,
}

impl<'a, T: ?Sized> SignedUploadUrlRequest<'a, T> {
    fn new(on: &'a T, key: &str) -> Self {
        Self {
            on,
            key: key.to_string(),
            ttl: None,
        }
    }

    /// How long the URL is valid for, rather than an hour: at most seven
    /// days.
    pub fn ttl(mut self, ttl: Duration) -> Self {
        self.ttl = Some(ttl);
        self
    }

    fn send<'b>(self, bucket: &'b Bucket) -> BoxFuture<'b, Result<SignedUploadUrl, Error>> {
        let key = self.key;
        let options = objects::UploadUrlOptions {
            ttl: self.ttl.unwrap_or(SIGNED_URL_TTL),
        };
        Box::pin(async move {
            bucket
                .object(&key)?
                .signed_upload_url(options)
                .await
                .map(|url| SignedUploadUrl { url })
                .map_err(obj_err)
        })
    }
}

into_future!(SignedUploadUrlRequest => SignedUploadUrl, SignedUploader::run_signed_upload_url);

/// The URL [`Bucket::signed_download_url`] makes: await it.
pub struct SignedDownloadUrlRequest<'a, T: ?Sized = Bucket> {
    on: &'a T,
    pub key: String,
    pub ttl: Option<Duration>,
}

impl<'a, T: ?Sized> SignedDownloadUrlRequest<'a, T> {
    fn new(on: &'a T, key: &str) -> Self {
        Self {
            on,
            key: key.to_string(),
            ttl: None,
        }
    }

    /// How long the URL is valid for, rather than an hour: at most seven
    /// days.
    pub fn ttl(mut self, ttl: Duration) -> Self {
        self.ttl = Some(ttl);
        self
    }

    fn send<'b>(self, bucket: &'b Bucket) -> BoxFuture<'b, Result<SignedDownloadUrl, Error>> {
        let key = self.key;
        let options = objects::DownloadUrlOptions {
            ttl: self.ttl.unwrap_or(SIGNED_URL_TTL),
        };
        Box::pin(async move {
            bucket
                .object(&key)?
                .signed_download_url(options)
                .await
                .map(|url| SignedDownloadUrl { url })
                .map_err(obj_err)
        })
    }
}

into_future!(
    SignedDownloadUrlRequest => SignedDownloadUrl,
    SignedDownloader::run_signed_download_url
);

/// 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,
         $update_attrs:ident, $if_match_upload:ident, $if_match_remove: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;
                type UpdateAttrs = $update_attrs;
                type IfMatchUpload = $if_match_upload;
                type IfMatchRemove = $if_match_remove;
            }
        };
    }

    // The flags each sets, in `BucketPerms`' order: Upload, SignedUpload,
    // Download, SignedDownload, Attrs, List, Remove, PublicUrl, UpdateAttrs,
    // IfMatchUpload, IfMatchRemove.
    perm!(
        /// Upload objects: [`Uploader`](super::Uploader).
        Uploader: Yes, No, No, No, No, No, No, No, No, No, No
    );
    perm!(
        /// Make signed upload URLs: [`SignedUploader`](super::SignedUploader).
        SignedUploader: No, Yes, No, No, No, No, No, No, No, No, No
    );
    perm!(
        /// Download objects: [`Downloader`](super::Downloader).
        Downloader: No, No, Yes, No, No, No, No, No, No, No, No
    );
    perm!(
        /// Make signed download URLs:
        /// [`SignedDownloader`](super::SignedDownloader).
        SignedDownloader: No, No, No, Yes, No, No, No, No, No, No, No
    );
    perm!(
        /// Read objects' attributes, and whether they exist:
        /// [`Attrser`](super::Attrser).
        Attrser: No, No, No, No, Yes, No, No, No, No, No, No
    );
    perm!(
        /// List objects and their versions: [`Lister`](super::Lister).
        Lister: No, No, No, No, No, Yes, No, No, No, No, No
    );
    perm!(
        /// Remove objects: [`Remover`](super::Remover).
        Remover: No, No, No, No, No, No, Yes, No, No, No, No
    );
    perm!(
        /// Resolve objects' public URLs: [`PublicUrler`](super::PublicUrler).
        PublicUrler: No, No, No, No, No, No, No, Yes, No, No, No
    );
    perm!(
        /// Change objects' attributes and extend their retention:
        /// [`AttrsUpdater`](super::AttrsUpdater).
        AttrsUpdater: No, No, No, No, No, No, No, No, Yes, No, No
    );
    perm!(
        /// Upload objects only over the revision named:
        /// [`IfMatchUploader`](super::IfMatchUploader). On AWS it reads too,
        /// which Encore grants for it.
        IfMatchUploader: No, No, No, No, No, No, No, No, No, Yes, No
    );
    perm!(
        /// Remove objects only if they are the revision named:
        /// [`IfMatchRemover`](super::IfMatchRemover). On AWS it reads too,
        /// which Encore grants for it.
        IfMatchRemover: No, No, No, 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, Yes, Yes, Yes
    );
}

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;
    #[doc(hidden)]
    type UpdateAttrs: Flag;
    #[doc(hidden)]
    type IfMatchUpload: Flag;
    #[doc(hidden)]
    type IfMatchRemove: 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;
    type UpdateAttrs = No;
    type IfMatchUpload = No;
    type IfMatchRemove = 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>;
            type UpdateAttrs =
                <$first::UpdateAttrs as Flag>::Or<<($($rest,)*) as BucketPerms>::UpdateAttrs>;
            type IfMatchUpload =
                <$first::IfMatchUpload as Flag>::Or<<($($rest,)*) as BucketPerms>::IfMatchUpload>;
            type IfMatchRemove =
                <$first::IfMatchRemove as Flag>::Or<<($($rest,)*) as BucketPerms>::IfMatchRemove>;
        }
        tuple_perms!($($rest),*);
    };
}

tuple_perms!(A, B, C, D, E, F, G, H, I, J, K, L);

/// 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;
/// }
/// ```
///
/// ```compile_fail,E0277
/// # use encore::objects::{perms, Bucket};
/// # static UPLOADS: Bucket = Bucket::named("uploads");
/// async fn update() {
///     // Uploading is not changing attributes: that is `AttrsUpdater`.
///     let r = UPLOADS.reference::<perms::Uploader>();
///     let _ = r.update_attrs("a").cache_control("no-store").await;
/// }
/// ```
///
/// ```compile_fail,E0277
/// # use encore::objects::{perms, Bucket, Revision};
/// # static UPLOADS: Bucket = Bucket::named("uploads");
/// async fn replace(seen: Revision) {
///     // Uploading over a revision is `IfMatchUploader`.
///     let r = UPLOADS.reference::<perms::Uploader>();
///     let _ = r.upload_if_match("a", vec![], seen).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 fn list(&self) -> ListRequest<'static>
    where
        P::List: Granted<perms::Lister>,
    {
        self.bucket.list()
    }

    /// See [`Bucket::list_versions`].
    pub fn list_versions(&self) -> ListVersionsRequest<'static>
    where
        P::List: Granted<perms::Lister>,
    {
        self.bucket.list_versions()
    }

    /// See [`Bucket::exists`].
    pub fn exists(&self, key: &str) -> ExistsRequest<'static>
    where
        P::Attrs: Granted<perms::Attrser>,
    {
        self.bucket.exists(key)
    }

    /// See [`Bucket::attrs`].
    pub fn attrs(&self, key: &str) -> AttrsRequest<'static>
    where
        P::Attrs: Granted<perms::Attrser>,
    {
        self.bucket.attrs(key)
    }

    /// See [`Bucket::upload`].
    pub fn upload(&self, key: &str, data: impl Into<UploadBody>) -> UploadRequest<'static>
    where
        P::Upload: Granted<perms::Uploader>,
    {
        self.bucket.upload(key, data)
    }

    /// See [`Bucket::upload_if_match`].
    pub fn upload_if_match(
        &self,
        key: &str,
        data: impl Into<UploadBody>,
        revision: Revision,
    ) -> UploadIfMatchRequest<'static>
    where
        P::IfMatchUpload: Granted<perms::IfMatchUploader>,
    {
        self.bucket.upload_if_match(key, data, revision)
    }

    /// See [`Bucket::update_attrs`].
    pub fn update_attrs(&self, key: &str) -> UpdateAttrsRequest<'static>
    where
        P::UpdateAttrs: Granted<perms::AttrsUpdater>,
    {
        self.bucket.update_attrs(key)
    }

    /// See [`Bucket::extend_retention`].
    pub fn extend_retention(&self, key: &str, until: SystemTime) -> ExtendRetentionRequest<'static>
    where
        P::UpdateAttrs: Granted<perms::AttrsUpdater>,
    {
        self.bucket.extend_retention(key, until)
    }

    /// See [`Bucket::download`].
    pub fn download(&self, key: &str) -> DownloadRequest<'static>
    where
        P::Download: Granted<perms::Downloader>,
    {
        self.bucket.download(key)
    }

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

    /// See [`Bucket::remove_if_match`].
    pub async fn remove_if_match(&self, key: &str, revision: Revision) -> Result<(), Error>
    where
        P::IfMatchRemove: Granted<perms::IfMatchRemover>,
    {
        self.bucket.remove_if_match(key, revision).await
    }

    /// See [`Bucket::signed_upload_url`].
    pub fn signed_upload_url(&self, key: &str) -> SignedUploadUrlRequest<'static>
    where
        P::SignedUpload: Granted<perms::SignedUploader>,
    {
        self.bucket.signed_upload_url(key)
    }

    /// See [`Bucket::signed_download_url`].
    pub fn signed_download_url(&self, key: &str) -> SignedDownloadUrlRequest<'static>
    where
        P::SignedDownload: Granted<perms::SignedDownloader>,
    {
        self.bucket.signed_download_url(key)
    }

    /// 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)
    }
}

// The permissions' traits. Each operation that takes options is a method
// making its request, and a `run_` method running it, which is what an
// implementation provides: a `BucketRef` runs it on its bucket, and a fake as
// it likes.

/// Upload objects. Implemented by a [`BucketRef`] granting
/// [`perms::Uploader`].
pub trait Uploader: Send + Sync {
    /// See [`Bucket::upload`].
    fn upload(&self, key: &str, data: impl Into<UploadBody>) -> UploadRequest<'_, Self> {
        UploadRequest::new(self, key, data.into())
    }

    /// Runs the upload [`upload`](Self::upload) made, when it is awaited.
    fn run_upload(
        &self,
        request: UploadRequest<'_, Self>,
    ) -> impl Future<Output = Result<ObjectAttrs, Error>> + Send;
}

/// Upload objects only over the revision named. Implemented by a
/// [`BucketRef`] granting [`perms::IfMatchUploader`].
pub trait IfMatchUploader: Send + Sync {
    /// See [`Bucket::upload_if_match`].
    fn upload_if_match(
        &self,
        key: &str,
        data: impl Into<UploadBody>,
        revision: Revision,
    ) -> UploadIfMatchRequest<'_, Self> {
        UploadIfMatchRequest::new(self, key, data.into(), revision)
    }

    /// Runs the upload [`upload_if_match`](Self::upload_if_match) made, when
    /// it is awaited.
    fn run_upload_if_match(
        &self,
        request: UploadIfMatchRequest<'_, Self>,
    ) -> impl Future<Output = Result<ObjectAttrs, Error>> + Send;
}

/// 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) -> SignedUploadUrlRequest<'_, Self> {
        SignedUploadUrlRequest::new(self, key)
    }

    /// Runs the request [`signed_upload_url`](Self::signed_upload_url) made,
    /// when it is awaited.
    fn run_signed_upload_url(
        &self,
        request: SignedUploadUrlRequest<'_, Self>,
    ) -> 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) -> DownloadRequest<'_, Self> {
        DownloadRequest::new(self, key)
    }

    /// Runs the download [`download`](Self::download) made, when it is
    /// awaited. A fake answers with [`Download::of`].
    fn run_download(
        &self,
        request: DownloadRequest<'_, Self>,
    ) -> 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) -> SignedDownloadUrlRequest<'_, Self> {
        SignedDownloadUrlRequest::new(self, key)
    }

    /// Runs the request [`signed_download_url`](Self::signed_download_url)
    /// made, when it is awaited.
    fn run_signed_download_url(
        &self,
        request: SignedDownloadUrlRequest<'_, Self>,
    ) -> 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) -> ExistsRequest<'_, Self> {
        ExistsRequest::new(self, key)
    }

    /// See [`Bucket::attrs`].
    fn attrs(&self, key: &str) -> AttrsRequest<'_, Self> {
        AttrsRequest::new(self, key)
    }

    /// Runs the request [`exists`](Self::exists) made, when it is awaited.
    fn run_exists(
        &self,
        request: ExistsRequest<'_, Self>,
    ) -> impl Future<Output = Result<bool, Error>> + Send;

    /// Runs the request [`attrs`](Self::attrs) made, when it is awaited.
    fn run_attrs(
        &self,
        request: AttrsRequest<'_, Self>,
    ) -> impl Future<Output = Result<ObjectAttrs, Error>> + Send;
}

/// List objects and their versions. Implemented by a [`BucketRef`] granting
/// [`perms::Lister`].
pub trait Lister: Send + Sync {
    /// See [`Bucket::list`].
    fn list(&self) -> ListRequest<'_, Self> {
        ListRequest::new(self)
    }

    /// See [`Bucket::list_versions`].
    fn list_versions(&self) -> ListVersionsRequest<'_, Self> {
        ListVersionsRequest::new(self)
    }

    /// Runs the listing [`list`](Self::list) made, when it is awaited.
    fn run_list(
        &self,
        request: ListRequest<'_, Self>,
    ) -> impl Future<Output = Result<ListIterator, Error>> + Send;

    /// Runs the listing [`list_versions`](Self::list_versions) made, when it
    /// is awaited.
    fn run_list_versions(
        &self,
        request: ListVersionsRequest<'_, Self>,
    ) -> impl Future<Output = Result<VersionIterator, Error>> + Send;
}

/// Remove objects. Implemented by a [`BucketRef`] granting [`perms::Remover`].
pub trait Remover: Send + Sync {
    /// See [`Bucket::remove`].
    fn remove(&self, key: &str) -> RemoveRequest<'_, Self> {
        RemoveRequest::new(self, key)
    }

    /// Runs the removal [`remove`](Self::remove) made, when it is awaited.
    fn run_remove(
        &self,
        request: RemoveRequest<'_, Self>,
    ) -> impl Future<Output = Result<(), Error>> + Send;
}

/// Remove objects only if they are the revision named. Implemented by a
/// [`BucketRef`] granting [`perms::IfMatchRemover`].
pub trait IfMatchRemover: Send + Sync {
    /// See [`Bucket::remove_if_match`].
    fn remove_if_match(
        &self,
        key: &str,
        revision: Revision,
    ) -> 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>;
}

/// Change objects' attributes and extend their retention. Implemented by a
/// [`BucketRef`] granting [`perms::AttrsUpdater`].
pub trait AttrsUpdater: Send + Sync {
    /// See [`Bucket::update_attrs`].
    fn update_attrs(&self, key: &str) -> UpdateAttrsRequest<'_, Self> {
        UpdateAttrsRequest::new(self, key)
    }

    /// See [`Bucket::extend_retention`].
    fn extend_retention(&self, key: &str, until: SystemTime) -> ExtendRetentionRequest<'_, Self> {
        ExtendRetentionRequest::new(self, key, until)
    }

    /// Runs the change [`update_attrs`](Self::update_attrs) made, when it is
    /// awaited.
    fn run_update_attrs(
        &self,
        request: UpdateAttrsRequest<'_, Self>,
    ) -> impl Future<Output = Result<ObjectAttrs, Error>> + Send;

    /// Runs the extension [`extend_retention`](Self::extend_retention) made,
    /// when it is awaited.
    fn run_extend_retention(
        &self,
        request: ExtendRetentionRequest<'_, Self>,
    ) -> impl Future<Output = Result<ObjectAttrs, Error>> + Send;
}

/// Every permission but [`PublicUrler`]. Implemented by whatever implements
/// them all, such as a [`BucketRef`] granting [`perms::ReadWriter`].
pub trait ReadWriter:
    Uploader
    + IfMatchUploader
    + SignedUploader
    + Downloader
    + SignedDownloader
    + Attrser
    + Lister
    + Remover
    + IfMatchRemover
    + AttrsUpdater
{
}

impl<T> ReadWriter for T where
    T: Uploader
        + IfMatchUploader
        + SignedUploader
        + Downloader
        + SignedDownloader
        + Attrser
        + Lister
        + Remover
        + IfMatchRemover
        + AttrsUpdater
{
}

impl<P: BucketPerms> Uploader for BucketRef<P>
where
    P::Upload: Granted<perms::Uploader>,
{
    fn run_upload(
        &self,
        request: UploadRequest<'_, Self>,
    ) -> impl Future<Output = Result<ObjectAttrs, Error>> + Send {
        request.send(self.bucket)
    }
}

impl<P: BucketPerms> IfMatchUploader for BucketRef<P>
where
    P::IfMatchUpload: Granted<perms::IfMatchUploader>,
{
    fn run_upload_if_match(
        &self,
        request: UploadIfMatchRequest<'_, Self>,
    ) -> impl Future<Output = Result<ObjectAttrs, Error>> + Send {
        request.send(self.bucket)
    }
}

impl<P: BucketPerms> SignedUploader for BucketRef<P>
where
    P::SignedUpload: Granted<perms::SignedUploader>,
{
    fn run_signed_upload_url(
        &self,
        request: SignedUploadUrlRequest<'_, Self>,
    ) -> impl Future<Output = Result<SignedUploadUrl, Error>> + Send {
        request.send(self.bucket)
    }
}

impl<P: BucketPerms> Downloader for BucketRef<P>
where
    P::Download: Granted<perms::Downloader>,
{
    fn run_download(
        &self,
        request: DownloadRequest<'_, Self>,
    ) -> impl Future<Output = Result<Download, Error>> + Send {
        request.send(self.bucket)
    }
}

impl<P: BucketPerms> SignedDownloader for BucketRef<P>
where
    P::SignedDownload: Granted<perms::SignedDownloader>,
{
    fn run_signed_download_url(
        &self,
        request: SignedDownloadUrlRequest<'_, Self>,
    ) -> impl Future<Output = Result<SignedDownloadUrl, Error>> + Send {
        request.send(self.bucket)
    }
}

impl<P: BucketPerms> Attrser for BucketRef<P>
where
    P::Attrs: Granted<perms::Attrser>,
{
    fn run_exists(
        &self,
        request: ExistsRequest<'_, Self>,
    ) -> impl Future<Output = Result<bool, Error>> + Send {
        request.send(self.bucket)
    }

    fn run_attrs(
        &self,
        request: AttrsRequest<'_, Self>,
    ) -> impl Future<Output = Result<ObjectAttrs, Error>> + Send {
        request.send(self.bucket)
    }
}

impl<P: BucketPerms> Lister for BucketRef<P>
where
    P::List: Granted<perms::Lister>,
{
    fn run_list(
        &self,
        request: ListRequest<'_, Self>,
    ) -> impl Future<Output = Result<ListIterator, Error>> + Send {
        request.send(self.bucket)
    }

    fn run_list_versions(
        &self,
        request: ListVersionsRequest<'_, Self>,
    ) -> impl Future<Output = Result<VersionIterator, Error>> + Send {
        request.send(self.bucket)
    }
}

impl<P: BucketPerms> Remover for BucketRef<P>
where
    P::Remove: Granted<perms::Remover>,
{
    fn run_remove(
        &self,
        request: RemoveRequest<'_, Self>,
    ) -> impl Future<Output = Result<(), Error>> + Send {
        request.send(self.bucket)
    }
}

impl<P: BucketPerms> IfMatchRemover for BucketRef<P>
where
    P::IfMatchRemove: Granted<perms::IfMatchRemover>,
{
    fn remove_if_match(
        &self,
        key: &str,
        revision: Revision,
    ) -> impl Future<Output = Result<(), Error>> + Send {
        BucketRef::remove_if_match(self, key, revision)
    }
}

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)
    }
}

impl<P: BucketPerms> AttrsUpdater for BucketRef<P>
where
    P::UpdateAttrs: Granted<perms::AttrsUpdater>,
{
    fn run_update_attrs(
        &self,
        request: UpdateAttrsRequest<'_, Self>,
    ) -> impl Future<Output = Result<ObjectAttrs, Error>> + Send {
        request.send(self.bucket)
    }

    fn run_extend_retention(
        &self,
        request: ExtendRetentionRequest<'_, Self>,
    ) -> impl Future<Output = Result<ObjectAttrs, Error>> + Send {
        request.send(self.bucket)
    }
}

#[cfg(test)]
mod tests;