encore-dev 2.0.0-beta.18

Rust SDK for Encore applications
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
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
2545
2546
2547
2548
2549
2550
2551
2552
2553
2554
2555
2556
2557
2558
2559
2560
2561
2562
2563
2564
2565
2566
2567
2568
2569
2570
2571
2572
2573
2574
2575
2576
2577
2578
2579
2580
2581
2582
2583
2584
2585
2586
2587
2588
2589
//! Object storage buckets, declared at module scope and 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();
//! ```
//!
//! Bucket operations (`upload`, `download`, `list`, `attrs`, `remove`, and so
//! on) are methods directly on [`Bucket`], matching Encore's TypeScript and Go
//! SDKs. Because each operation is called directly on the bucket, Encore can
//! statically analyze your code and grant each service only the permissions it
//! uses.
//!
//! Operations that accept options return a request builder. Configure options
//! with chained methods and `.await` the request to execute it.
//!
//! ```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
//!
//! Because Encore tracks bucket permissions statically, a [`Bucket`] cannot be
//! passed around as a value. To pass a bucket to helper functions or libraries,
//! create a [`BucketRef`] that grants only the permissions specified in its
//! type argument:
//!
//! ```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
//! }
//! ```
//!
//! Permissions can be a single type from [`perms`] or a tuple of them (such as
//! `(perms::Uploader, perms::Lister)`). Each permission has a matching trait in
//! this module exposing the methods it grants. Library code should accept those
//! traits (`&impl Uploader`, `&(impl Uploader + Lister)`) so it works with any
//! compatible [`BucketRef`] and can easily be tested with fakes.
//!
//! # Declaring a bucket
//!
//! Chain `const` configuration methods after [`Bucket::new`]. Encore parses
//! these statically from the declaration and provisions the bucket accordingly:
//!
//! ```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
//!
//! All bucket operations return this module's [`Error`]:
//!
//! - [`Error::NotFound`]: the object or requested version does not exist.
//! - [`Error::PreconditionFailed`]: a precondition (`not_exists`,
//!   `upload_if_match`, `remove_if_match`, or `if_match`) was not met.
//! - [`Error::Retained`]: a retention policy prevents deleting or overwriting
//!   the object.
//! - [`Error::InvalidArgument`]: invalid input was passed to the operation.
//! - [`Error::Other`]: another failure occurred, such as being unable to reach
//!   the storage provider.
//!
//! [`Error`] does not automatically convert into
//! [`encore::Error`](crate::Error). Match on it when you need to handle
//! specific failure cases:
//!
//! ```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),
//!     }
//! }
//! ```
//!
//! When a function returns [`encore::Error`](crate::Error) (such as a Pub/Sub
//! handler), map the error explicitly with an appropriate error code:
//!
//! ```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 used by bucket operations.
pub use encore_sdk_core::objects::{
    ByteRange, ListEntry, ObjectAttrs, ObjectVersion, Revision, StorageClass,
};

/// Error returned by object storage bucket operations. See
/// [Errors](self#errors).
///
/// This type does not automatically convert into
/// [`encore::Error`](crate::Error); map it explicitly with the appropriate
/// error code for your caller.
#[derive(Debug, thiserror::Error)]
#[non_exhaustive]
pub enum Error {
    /// The object or requested version does not exist.
    #[error("object not found")]
    NotFound,
    /// A precondition was not met: the object already exists (`not_exists`), or
    /// its current revision no longer matches the expected revision
    /// (`upload_if_match`, `remove_if_match`, or `if_match`).
    #[error("precondition failed")]
    PreconditionFailed,
    /// The object cannot be deleted or overwritten because of the bucket's
    /// retention period or the object's own retain-until timestamp.
    #[error("object is retained")]
    Retained,
    /// The call passed invalid input (such as a malformed version, unsupported
    /// metadata, or a retain-until time earlier than the object's current
    /// retention).
    #[error("invalid argument: {0}")]
    InvalidArgument(String),
    /// Any other failure, such as being unable to reach the storage 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))
}

/// An active object download returned by [`Bucket::download`] once the storage
/// provider responds.
///
/// Object metadata — [`revision`](Download::revision),
/// [`size`](Download::size), [`content_type`](Download::content_type), and
/// [`last_modified`](Download::last_modified) — is available immediately. Read
/// the body all at once with [`Download::bytes`], as a stream of chunks 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(())
/// # }
/// ```
///
/// [`Download::revision`] identifies the exact revision being read, so you can
/// perform an optimistic read-modify-write:
///
/// ```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 holds its underlying connection until it is read to completion or
/// dropped (which cancels the remaining transfer).
pub struct Download {
    inner: objects::Download,
}

impl Download {
    /// Constructs an in-memory [`Download`] from `attrs` and `data`, useful
    /// when implementing a fake [`Downloader`] in tests.
    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))),
            },
        }
    }

    /// Returns the revision of the downloaded object, matching
    /// [`ObjectAttrs::revision`]. Pass this to
    /// [`upload_if_match`](Bucket::upload_if_match),
    /// [`remove_if_match`](Bucket::remove_if_match), or `if_match`.
    pub fn revision(&self) -> Revision {
        self.inner.info.revision.clone()
    }

    /// Returns the total size of the object in bytes, even when downloading a
    /// byte range.
    pub fn size(&self) -> u64 {
        self.inner.info.size
    }

    /// Returns the object's content type, if set.
    pub fn content_type(&self) -> Option<&str> {
        self.inner.info.content_type.as_deref()
    }

    /// Returns when the object was last modified, or `None` if the provider did
    /// not report it.
    pub fn last_modified(&self) -> Option<SystemTime> {
        self.inner.info.last_modified
    }

    /// Reads the entire download body into memory.
    pub async fn bytes(self) -> Result<Vec<u8>, Error> {
        self.inner.bytes().await.map_err(obj_err)
    }

    /// Returns the download body as a stream of byte chunks as they arrive.
    pub fn bytes_stream(self) -> impl Stream<Item = Result<Bytes, Error>> + Send + Unpin + 'static {
        Chunks(self.inner.stream)
    }

    /// Converts the download body into an [`AsyncRead`], suitable for parsers,
    /// decompressors, or `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))
    }
}

/// An async iterator over objects in a bucket, returned by [`Bucket::list`].
///
/// Consume entries with [`ListIterator::next`] or via its [`Stream`]
/// implementation.
pub struct ListIterator {
    inner: objects::ListIterator,
}

impl ListIterator {
    /// Returns the next object entry, or `None` when the listing is complete.
    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)))
    }
}

/// An async iterator over stored object versions in a bucket, returned by
/// [`Bucket::list_versions`].
///
/// Consume versions with [`VersionIterator::next`] or via its [`Stream`]
/// implementation.
pub struct VersionIterator {
    inner: objects::VersionIterator,
}

impl VersionIterator {
    /// Returns the next object version, or `None` when the listing is complete.
    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)))
    }
}

/// Data to upload to an object.
///
/// Accepts in-memory buffers (`Vec<u8>`, `Bytes`, `&'static [u8]`, or `String`)
/// as well as streamed content via [`UploadBody::reader`] or
/// [`UploadBody::chunks`].
pub struct UploadBody(Body);

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

impl UploadBody {
    /// Streams upload data directly from `reader` without buffering it in
    /// memory.
    pub fn reader(reader: impl AsyncRead + Unpin + Send + Sync + 'static) -> Self {
        UploadBody(Body::Reader(Box::new(reader)))
    }

    /// Streams upload data from a stream of byte chunks (such as a forwarded
    /// request body).
    ///
    /// Each chunk can be any type convertible to `Bytes` (`Bytes`, `Vec<u8>`,
    /// `String`, or `&'static [u8]`). If the stream yields an error, the upload
    /// fails and nothing is stored.
    ///
    /// ```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),
        ))))
    }

    /// Converts the upload body into an [`AsyncRead`], useful when implementing
    /// a fake [`Uploader`] in tests.
    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 pre-signed URL granting temporary permission to upload an object, returned
/// by [`Bucket::signed_upload_url`].
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct SignedUploadUrl {
    pub url: String,
}

/// A pre-signed URL granting temporary permission to download an object,
/// returned by [`Bucket::signed_download_url`].
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct SignedDownloadUrl {
    pub url: String,
}

/// A lifecycle rule for a bucket (see [`Bucket::lifecycle`]).
///
/// Each rule has an optional [`prefix`](Self::prefix) and at least one action.
/// The storage provider applies rules asynchronously — typically within a day
/// after an object becomes eligible, and never earlier.
///
/// Day counts are measured from when an object was written (or, for noncurrent
/// actions, from when a version was replaced or deleted). Specify them as
/// integer literals between 1 and 36500 so Encore can parse them statically.
///
/// ```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 {
    /// Creates a rule matching all objects in the bucket. Add at least one
    /// action before attaching it to a bucket.
    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
    }

    /// Transitions matching objects to [`StorageClass::Infrequent`] after
    /// `days` days (must be 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
    }

    /// Transitions matching objects to [`StorageClass::Cold`] after `days`
    /// days.
    ///
    /// When combined with
    /// [`move_to_infrequent_after_days`](Self::move_to_infrequent_after_days),
    /// this must be at least 30 days after the infrequent transition.
    pub const fn move_to_cold_after_days(mut self, days: u32) -> Self {
        self.move_to_cold_after_days = Some(days);
        self
    }

    /// Deletes matching objects `days` days after they are written (must be
    /// later than any storage-class transition in the same rule).
    ///
    /// In a versioned bucket, deletion turns the object into a noncurrent
    /// version, matching [`Bucket::remove`].
    pub const fn delete_after_days(mut self, days: u32) -> Self {
        self.delete_after_days = Some(days);
        self
    }

    /// For versioned buckets: deletes noncurrent versions `days` days after
    /// they are replaced or removed.
    pub const fn delete_noncurrent_after_days(mut self, days: u32) -> Self {
        self.delete_noncurrent_after_days = Some(days);
        self
    }

    /// For versioned buckets: retains at least the `count` newest noncurrent
    /// versions of each object, deleting older noncurrent versions.
    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()
    }
}

/// Minimum retention period for objects written to a bucket (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 {
    /// Retains each object for `days` days after it is written.
    ///
    /// `days` must be an integer literal between 1 and 36500.
    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 {
    /// Declares a new object storage bucket.
    ///
    /// This function is `const` so it can initialize a module-level `static`.
    /// Chain configuration methods after `new`:
    ///
    /// ```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 publicly readable at the URL returned by
    /// [`Bucket::public_url`].
    ///
    /// This method takes `self` by value so it can only be called as part of
    /// the `static` declaration.
    pub const fn public(mut self) -> Self {
        self.public = true;
        self
    }

    /// Enables object versioning so earlier versions of an object are kept and
    /// can be targeted with a request's `.version(...)` option.
    ///
    /// Must be called as part of the `static` declaration.
    pub const fn versioned(mut self) -> Self {
        self.versioned = true;
        self
    }

    /// Sets the default storage class for objects uploaded to this bucket
    /// (defaults to standard storage).
    ///
    /// [`StorageClass::Auto`] lets the provider tier objects automatically
    /// based on access frequency; it can only be set at the bucket level and
    /// cannot be combined with lifecycle storage-class transitions.
    ///
    /// Must be called as part of the `static` declaration.
    pub const fn storage_class(mut self, class: StorageClass) -> Self {
        self.storage_class = Some(class);
        self
    }

    /// Configures lifecycle rules for transitioning objects to colder storage
    /// classes or deleting them after a given age.
    ///
    /// Rules also apply to objects already in the bucket. A bucket may have at
    /// most 100 rules. Must be called as part of the `static` declaration.
    ///
    /// ```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
    }

    /// Sets a minimum retention period for every object written to the bucket.
    ///
    /// Until the retention period expires, deleting or overwriting an object
    /// fails with [`Error::Retained`] (on AWS S3, the request creates a new
    /// version or delete marker while the retained version remains protected
    /// until expiry). Must be called as part of the `static` declaration.
    ///
    /// ```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
    }

    /// Enables per-object retention timestamps, configured on upload via
    /// [`UploadRequest::retain_until`] and extended via
    /// [`Bucket::extend_retention`].
    ///
    /// Not supported on Cloudflare R2. Must be called as part of the `static`
    /// declaration.
    pub const fn object_retention(mut self) -> Self {
        self.object_retention = true;
        self
    }

    /// Attaches a key/value classification tag (such as `.tag("data", "pci")`)
    /// for policy evaluation.
    ///
    /// Call `.tag` once per tag with unique keys. Both arguments must be string
    /// literals so Encore can parse them statically. Keys must start with a
    /// lowercase letter, contain only lowercase letters, digits, `_`, and `-`,
    /// and must not start with `encore` (reserved for Encore's own tags).
    /// Values use the same character set or may be empty. Each key and value
    /// may be at most 63 characters, and a bucket may have at most 32 tags.
    ///
    /// Must be called as part of the `static` declaration.
    ///
    /// ```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
    }

    /// References an existing bucket by name. To declare a new bucket, use
    /// [`Bucket::new`] instead.
    ///
    /// `name` must be a string literal so Encore can resolve it statically.
    /// Because the bucket is configured where it is declared, do not chain
    /// declaration options on `named`.
    ///
    /// ```no_run
    /// static UPLOADS: encore::objects::Bucket = encore::objects::Bucket::named("uploads");
    /// ```
    pub const fn named(name: &'static str) -> Self {
        Self::new(name)
    }

    /// Creates a [`BucketRef`] granting only the permissions `P` (a single type
    /// from [`perms`] or a tuple of them).
    ///
    /// Unlike [`Bucket`], a [`BucketRef`] can be passed to helper functions and
    /// libraries, and Encore grants the service the permissions named in `P`.
    /// Because permissions must be explicit in source code, `P` cannot be
    /// inferred by the compiler. This function is `const` so it can initialize
    /// a module-level `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()))
    }

    /// Lists objects in the bucket, returning a [`ListRequest`] that resolves
    /// to a [`ListIterator`].
    ///
    /// When [`delimiter`](ListRequest::delimiter) is set, object names are
    /// grouped up to the first occurrence of the delimiter (like a directory
    /// listing). Each group is returned as a single [`ListEntry`] with
    /// [`ListEntry::is_prefix`] set and a name ending with the delimiter.
    /// Groups and objects are returned in order, and
    /// [`limit`](ListRequest::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)
    }

    /// Lists stored versions of objects in the bucket, ordered by name and then
    /// newest first.
    ///
    /// A removed object has no version with [`ObjectVersion::latest`] set. For
    /// an unversioned bucket, each object appears as a single 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)
    }

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

    /// Fetches the attributes of the object `key` (size, content type, version,
    /// ETag, custom metadata, and so on).
    pub fn attrs(&self, key: &str) -> AttrsRequest<'_> {
        AttrsRequest::new(self, key)
    }

    /// Uploads `data` to `key` and returns the stored [`ObjectAttrs`].
    ///
    /// Pass an in-memory buffer directly, or use [`UploadBody::reader`] /
    /// [`UploadBody::chunks`] to stream large payloads.
    ///
    /// ```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())
    }

    /// Uploads `data` to `key` only if the object still matches `revision`
    /// (from [`ObjectAttrs::revision`] or [`Download::revision`]).
    ///
    /// If another write occurred first or the object no longer exists, the
    /// upload fails with [`Error::PreconditionFailed`]. Supports all
    /// [`upload`](Self::upload) options except `not_exists`.
    ///
    /// The revision check compares object contents rather than attributes, so
    /// [`update_attrs`](Self::update_attrs) does not invalidate it. On AWS,
    /// this operation also requires read permission, which Encore grants
    /// automatically.
    ///
    /// ```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)
    }

    /// Updates attributes on `key` (content type, cache control, content
    /// disposition, or custom metadata) and returns the updated
    /// [`ObjectAttrs`].
    ///
    /// Unspecified attributes remain unchanged. On S3, updating attributes
    /// rewrites the object, which creates a new version in versioned buckets.
    ///
    /// ```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)
    }

    /// Extends the retention timestamp of `key` to at least `until` in a bucket
    /// declared with [`Bucket::object_retention`], returning the updated
    /// [`ObjectAttrs`].
    ///
    /// Retention can only be extended; passing a timestamp earlier than the
    /// object's current retain-until time returns [`Error::InvalidArgument`].
    pub fn extend_retention(&self, key: &str, until: SystemTime) -> ExtendRetentionRequest<'_> {
        ExtendRetentionRequest::new(self, key, until)
    }

    /// Downloads `key` (optionally a specific version or byte range).
    ///
    /// Awaiting the returned [`DownloadRequest`] resolves to a [`Download`] as
    /// soon as the provider responds with headers (or fails with
    /// [`Error::NotFound`] if the object does not exist). Read the body from
    /// the [`Download`] all at once or as a stream.
    ///
    /// ```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)
    }

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

    /// Removes `key` only if the object still matches `revision` (from
    /// [`ObjectAttrs::revision`] or [`Download::revision`]).
    ///
    /// If another write occurred first or the object no longer exists, this
    /// fails with [`Error::PreconditionFailed`]. The check compares object
    /// contents rather than attributes. On AWS, this operation also requires
    /// read permission, which Encore grants automatically. Conditional removal
    /// is not supported on Cloudflare R2 and returns [`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)
    }

    /// Generates a pre-signed URL for uploading `key`, valid for one hour by
    /// default (override with [`SignedUploadUrlRequest::ttl`]).
    pub fn signed_upload_url(&self, key: &str) -> SignedUploadUrlRequest<'_> {
        SignedUploadUrlRequest::new(self, key)
    }

    /// Generates a pre-signed URL for downloading `key`, valid for one hour by
    /// default (override with [`SignedDownloadUrlRequest::ttl`]).
    pub fn signed_download_url(&self, key: &str) -> SignedDownloadUrlRequest<'_> {
        SignedDownloadUrlRequest::new(self, key)
    }

    /// Returns the public URL for `key`.
    ///
    /// Only available for buckets declared with [`Bucket::public`]; returns
    /// [`Error::InvalidArgument`] for private buckets.
    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 {
    () => {
        /// Targets a specific `version` of the object in a versioned bucket
        /// instead of the current version.
        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 {
    () => {
        /// Sets the object's `Content-Type` header (for example,
        /// `application/pdf`).
        pub fn content_type(mut self, content_type: impl Into<String>) -> Self {
            self.content_type = Some(content_type.into());
            self
        }

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

        /// Sets the `Content-Disposition` header the object is served with (for
        /// example, `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 key/value pairs (such as `[("owner", "42")]`),
        /// replacing any existing entries with the same keys.
        ///
        /// Keys must contain only lowercase letters, digits, `-`, and `_`, and
        /// cannot start with `-` or `_`. Values must be 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
        }

        /// Overrides the bucket's default storage class for this object.
        ///
        /// [`StorageClass::Auto`] is only valid at the bucket level and is
        /// rejected here.
        pub fn storage_class(mut self, class: StorageClass) -> Self {
            self.storage_class = Some(class);
            self
        }

        /// Retains the object until at least `until` 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);

/// Request builder returned by [`Bucket::upload`].
///
/// Configure upload options with builder methods and `.await` to execute and
/// receive the stored [`ObjectAttrs`]. Fields are public for inspecting
/// requests in fake [`Uploader`] implementations.
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!();

    /// Fails with [`Error::PreconditionFailed`] if an object with this key
    /// already exists.
    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);

/// Request builder returned by [`Bucket::upload_if_match`].
///
/// Supports all upload options except `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;
/// }
/// ```
///
/// Fields are public for inspecting requests in fake [`IfMatchUploader`]
/// implementations.
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)
    })
}

/// Request builder returned by [`Bucket::update_attrs`].
///
/// Unspecified attributes remain unchanged; passing an empty string clears an
/// attribute (clearing content type resets it to `application/octet-stream`,
/// since S3 requires every object to have one). Awaiting returns the updated
/// [`ObjectAttrs`]. Fields are public for inspecting requests in fake
/// [`AttrsUpdater`] implementations.
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 custom metadata with `metadata`. Pass an empty
    /// iterator (`[]`) to clear all metadata.
    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!();

    /// Updates attributes only if the object still matches `revision`, failing
    /// with [`Error::PreconditionFailed`] otherwise.
    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);

/// Request builder returned by [`Bucket::extend_retention`]. Await it to
/// extend retention and receive the updated [`ObjectAttrs`].
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);

/// Request builder returned by [`Bucket::download`]. Await it to start 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!();

    /// Downloads only the specified byte range (such as `1024..1280`, `1024..`,
    /// or `..=99`).
    ///
    /// Returns [`Error::InvalidArgument`] if the range is empty or starts past
    /// the end of the object.
    pub fn range(mut self, range: impl RangeBounds<u64>) -> Self {
        self.range = Some(byte_range(range));
        self
    }

    /// Downloads only the last `length` bytes of the object (or the whole
    /// object if it is shorter).
    ///
    /// Passing `0` returns [`Error::InvalidArgument`]. Use [`Download::size`]
    /// to determine the total size of the object.
    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);

/// Request builder returned by [`Bucket::attrs`]. Await it to fetch
/// [`ObjectAttrs`].
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);

/// Request builder returned by [`Bucket::exists`]. Await it to check 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);

/// Request builder returned by [`Bucket::remove`]. Await it to delete the
/// object.
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);

/// Request builder returned by [`Bucket::list`]. Await it to obtain a
/// [`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,
        }
    }

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

    /// Caps the listing at `limit` entries (including prefix groups).
    pub fn limit(mut self, limit: u64) -> Self {
        self.limit = Some(limit);
        self
    }

    /// Groups object names after the prefix up to the first occurrence of
    /// `delimiter`, like a directory listing. 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);

/// Request builder returned by [`Bucket::list_versions`]. Await it to obtain
/// a [`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);

/// Request builder returned by [`Bucket::signed_upload_url`]. Await it to
/// generate the [`SignedUploadUrl`].
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,
        }
    }

    /// Sets how long the signed URL remains valid (defaults to 1 hour; maximum
    /// 7 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);

/// Request builder returned by [`Bucket::signed_download_url`]. Await it to
/// generate the [`SignedDownloadUrl`].
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,
        }
    }

    /// Sets how long the signed URL remains valid (defaults to 1 hour; maximum
    /// 7 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
);

/// Permission marker types for [`BucketRef`].
///
/// Each marker type has a matching trait in [`objects`](super) exposing the
/// operations 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: either a single type from [`perms`] or a tuple
/// of them granting the union of their permissions.
///
/// This trait is sealed.
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 `Copy` reference to a [`Bucket`] that grants only the permissions `P`,
/// created with [`Bucket::reference`].
///
/// Only operations allowed by `P` can be called on a `BucketRef` (for example,
/// `BucketRef<perms::Uploader>` can `upload` but cannot `download`). Library
/// code should accept the corresponding permission traits (such as
/// `&impl Uploader`) rather than `BucketRef` directly.
///
/// ```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;