ostrya 0.2.4

Pure-Rust async reimplementation of the ostree repository library
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
//! HTTP pull: importing refs and their objects from a remote over HTTP.
//!
//! [`Repo::pull`] fetches a set of refs, the commits they name, and every object
//! those commits reach from a remote named in this repository's config, into one
//! transaction. What the transaction publishes, when the refs are written, and
//! what the `.commitpartial` markers mean is the local pull's contract
//! unchanged; what this module adds is where the objects come from and how many
//! are fetched at once.
//!
//! What a pull asks the remote for, in the order it first asks: `summary.sig`,
//! `summary`, `config`, then the objects. A remote with no summary answers 404
//! and each requested ref is resolved through `refs/heads/<ref>` instead.
//!
//! The remote is an archive repository. A content object is requested as
//! `objects/<..>.filez` whatever the remote stores on its own disk, since that
//! is the one form of a content object an HTTP client can read: the framed,
//! deflated payload behind its header. `config` is fetched to establish that
//! before the first object is requested, so a non-archive remote is refused with
//! [`Error::Unsupported`] naming its mode rather than surfacing as a 404 on the
//! first content object. A remote serving no `config` is treated as archive.
//!
//! Concurrency. A pull holds up to
//! [`max_outstanding_fetches`](PullOptions::max_outstanding_fetches) steps in
//! flight, each a future that fetches one object and stores it. The plan those
//! slots are refilled from holds three classes, drained in this order and
//! carrying the matching fetch priority:
//!
//! - the commits: the requested tips, and their parents under
//!   [`depth`](PullOptions::depth);
//! - the scan: the dirtree and dirmeta objects the walk is blocked on;
//! - the content: the file objects, which nothing waits on.
//!
//! That drain order is what orders a pull's requests. The fetcher admits as many
//! requests at once as the pull has slots, and a slot has one fetch outstanding
//! at a time, so the admission gate a priority is weighed at never queues inside
//! one pull. The priority a class carries decides the order where a [`Fetcher`]
//! is shared by more callers than it admits.
//!
//! The plan is owned by the loop, so it needs no lock. Nothing is spawned: the
//! step futures borrow the repository, the transaction, and the fetcher, so a
//! failure returns from the loop and drops every step still in flight, closing
//! their connections and releasing their fetcher permits. The transaction reaps
//! its staging directory and no ref is written.
//!
//! A commit object is fetched before the objects it references, since its tree
//! is unknown until it arrives, and staged where it arrives: the write path
//! hashes the bytes there and compares the result against the name they were
//! requested by, so a commit stored under the wrong name fails the pull before
//! its tree is asked for, and nothing is held in memory past the step. A reader
//! is covered against a commit whose tree is not yet complete by the commit's
//! `.commitpartial` marker, which is written when the commit is fetched and
//! removed after the transaction publishes. A pull that fails removes the
//! markers it wrote for commits this repository does not hold, so a refused
//! commit leaves the destination as it stood. An object several commits reach is
//! fetched once, and the step that fetches a commit makes the ref-binding and
//! timestamp checks of every requested ref naming it, so two refs at one commit
//! are both checked. A commit this repository already holds complete has no
//! object of its tree queued, since what it references is present; its parent is
//! followed all the same, so a pull extends the history a shallower pull left.
//!
//! A commit's `.commitmeta` is requested ahead of the commit object and written
//! once that object is here, which keeps the detached metadata ahead of the ref
//! that names its commit and leaves none behind for a parent the remote answers
//! 404 for. The file is outside the transaction, so a pull that fails after a
//! commit object landed leaves the copy it wrote, which prune sweeps.
//!
//! Above one slot the request order is not fixed: which queued object a freed
//! slot takes depends on which step finished. What is fixed is the set of
//! requests and the class order between them.
//!
//! Writing is throttled separately. A content step takes one of three write
//! permits once the response head has arrived and holds it for the whole body:
//! the archive header read, the payload streaming into the object store, and the
//! read that settles the end of the stream. A fast remote therefore cannot put
//! more concurrent writers on the destination filesystem than that. The permit is
//! taken before the body is read, which keeps a step waiting for one off the
//! fetcher's progress clock: that clock measures silence since a read wanted
//! bytes, and no read has yet wanted any. The header arrives inside the first
//! frame in the ordinary case, so what the permit spans beside the payload is
//! that frame and the byte that ends the stream. A body waiting for a permit
//! holds what it has received unread, and over HTTP/2 that is flow-control
//! credit: the fetcher gives a connection one stream window for every request it
//! admits, so the credit a parked body holds is its own and the metadata stream a
//! scan is blocked on receives over a window of its own.
//!
//! What a step holds in memory follows the object class it fetches. A content
//! object streams into the object store through its slot's 128 KiB read buffer
//! and buffers its header alone, which `MAX_FILE_HEADER_SIZE` caps at 1 MiB; the
//! read buffer belongs to the slot rather than to the object, so the objects a
//! slot stores share it whether they come from the remote or from a localcache
//! repository. What each in-flight object does allocate for itself is the 16 KiB
//! the decoder reads its compressed input through. A metadata object -- a commit,
//! a dirtree, a dirmeta, or a `.commitmeta` -- is read whole under the format's
//! 128 MiB metadata cap, one buffer per step sized from the length the remote
//! declares, so the metadata a pull holds is that cap times the slot count.
//!
//! Verification. Every fetched object is stored under the name it was requested
//! by, and the write path hashes what it stores and compares the result against
//! that name, so a corrupt or substituted object fails the pull with
//! [`Error::ChecksumMismatch`] and publishes nothing. There is no flag to skip
//! it: the write path cannot store an object without naming it, which is why an
//! HTTP pull ignores [`UNTRUSTED`](PullFlags::UNTRUSTED) -- it verifies either
//! way.
//!
//! The mode checks are the local pull's, made over the header a content object
//! arrives with: [`BAREUSERONLY_FILES`](PullFlags::BAREUSERONLY_FILES) rejects a
//! regular file whose mode has bits outside `0775`, and a bare-user-only
//! destination rejects one whose header is not the canonical form it stores.
//!
//! Signatures are a policy of their own, described in
//! `verify`: the remote's configuration states it and
//! [`PullVerify`](super::PullVerify) overrides it. The summary is checked as
//! soon as it and its signature are here, before the refs it resolves or the
//! deltas it advertises are read; a commit is checked in the step that fetched
//! it, before its bytes are staged and before its tree is asked for.
//!
//! That header also declares what the payload decompresses to, which bounds the
//! stream on both sides. A payload that outgrows the declaration is refused with
//! [`Error::InvalidFormat`], so what a corrupt or expanding stream can write
//! before the checksum comparison at the end of the payload is what the object
//! declared. A payload that takes more off the connection than a compressed form
//! of that declaration occupies is refused the same way, which bounds the time and
//! the bandwidth a stream of empty DEFLATE blocks would otherwise take.
//!
//! After the payload, a content step reads its response to the end. One byte
//! settles it, since nothing follows an object's final DEFLATE block. That read
//! returns the connection to the pool, so a pull reuses one connection per slot
//! rather than opening one per object; at one slot that is one connection for the
//! whole pull, and at the default eight it is up to eight, since HTTP/1.1 carries
//! one request at a time. Bytes after the payload are refused with
//! [`Error::InvalidFormat`], and a symlink's stored form is held to the same
//! rule.
//!
//! Sources. A [`localcache_repos`](PullOptions::localcache_repos) repository is
//! consulted before the network, per object, through the local pull's import
//! path with its checksum verified.
//!
//! Static deltas. A remote that publishes them delivers a commit as one delta
//! instead of one request per object, which a pull looks for before it asks for
//! the first object: the delta index for the target commit, then the summary's own
//! `ostree.static-deltas` map where the remote serves no index. One delta is
//! considered per tip -- from the commit the ref names in this repository, or from
//! scratch where it names none -- and the superblock is checked against the digest
//! the advertisement carried. The target commit rides in that superblock, so no
//! `.commit` is requested; the objects the delta hands over loose are queued at
//! once, two part fetches run at a time, and the commit's tree is walked once the
//! last part is applied, so an object no part delivered is fetched loose.
//! [`disable_static_deltas`](PullOptions::disable_static_deltas) asks for no
//! delta, and [`require_static_deltas`](PullOptions::require_static_deltas)
//! refuses a remote that advertises none. What a delta costs in memory per part
//! in flight is one xz decoder and two blobs: the verified part body, which is
//! hashed against the superblock's entry for it before the decoder runs, and the
//! payload it decompresses to. Each blob is on the heap while it is small and a
//! mapped temp file past its heap threshold.

use std::collections::{HashMap, HashSet, VecDeque};
use std::pin::Pin;
use std::sync::Arc;
use std::task::{Context, Poll, ready};

use async_compression::futures::bufread::DeflateDecoder;
use futures_io::AsyncRead;
use futures_lite::{AsyncReadExt, AsyncWriteExt};
use ostrya_core::{
    Checksum, Commit, DirTree, FileHeader, ObjectName, ObjectType, RepoMode, loose_path,
};

use crate::config::RepoConfig;
use crate::error::{Error, Result};
use crate::fetch::gate::Gate;
use crate::fetch::{
    Body, ClientIdentity, FetchRequest, Fetched, Fetcher, FetcherOptions, Priority, TlsOptions,
    TrustRoots,
};
use crate::inflate::BufSource;
use crate::object::{MAX_FILE_HEADER_SIZE, MAX_METADATA_SIZE};
use crate::read::CommitState;
use crate::repo::Repo;
use crate::summary::{SUMMARY_FILE, SUMMARY_SIG_FILE, Summary};
use crate::transaction::Transaction;
use crate::traverse::reaches_at_least;
use crate::write::FileMeta;

use super::delta::{self, DeltaJob, PART_CAP};
use super::drive::Slots;
use super::verify::{Defaults, Verification};
use super::{
    DetachedMetadataFilter, ModeChecks, PullFlags, PullOptions, PullStats, READ_CHUNK,
    TimestampCheck, check_ref_binding, refspec,
};

/// How many fetches are in flight when the caller names no limit.
const DEFAULT_OUTSTANDING: usize = 8;
/// How many times a round of mirrors is repeated when the caller names no count.
const DEFAULT_RETRIES: u32 = 5;
/// How many fetched content objects stream into the object store at once.
const WRITE_THROTTLE: usize = 3;

/// The cap on the repository-root files a pull fetches (`summary`,
/// `summary.sig`, `config`), matching the cap the local summary reader applies.
const MAX_ROOT_FILE: u64 = 64 * 1024 * 1024;
/// The cap on a fetched `refs/heads/<ref>` file, which holds 64 hex characters
/// and a newline.
const MAX_REF_FILE: u64 = 1024;

/// The repository config file name at the repository root.
const CONFIG_FILE: &str = "config";

impl Repo {
    /// Pull refs and their objects from an HTTP remote.
    ///
    /// `remote` names a `[remote "<name>"]` section of this repository's config,
    /// which supplies the base URL and the TLS material;
    /// [`url`](PullOptions::url) overrides the URL, which lets a caller pull from
    /// a remote the config does not describe.
    ///
    /// Every requested ref is resolved against the remote's summary and then
    /// against `refs/heads/<ref>`; a ref neither yields fails with
    /// [`Error::RefNotFound`] before anything is fetched. An empty
    /// [`refs`](PullOptions::refs) list takes every ref the summary lists under
    /// [`MIRROR`](PullFlags::MIRROR), and the remote's configured `branches`
    /// otherwise; neither being available fails with [`Error::Pull`].
    ///
    /// The refs are written after the objects are published, under
    /// `refs/remotes/<remote>/<ref>` -- or under
    /// [`PullOptions::remote`](PullOptions::remote) when that names a different
    /// prefix, and as local refs under [`MIRROR`](PullFlags::MIRROR). A mirror
    /// pull that took every ref the summary lists also copies the remote's
    /// summary bytes to this repository's `summary`, and its `summary.sig` bytes
    /// where the remote holds them.
    pub async fn pull(&self, remote: &str, opts: PullOptions) -> Result<PullStats> {
        // The fetcher is built first, so a remote the config does not describe
        // reports that before a policy is resolved for it. `remote_fetcher`
        // reads the config section, the URL, and the TLS material; it sends no
        // request, so a refused policy still stops the pull before its first
        // fetch.
        let fetcher = self.remote_fetcher(remote, &opts).await?;
        let verification =
            Verification::build(self, Some(remote), &opts.verify, Defaults::Config).await?;
        let (summary_bytes, signature) = fetch_summary(&fetcher).await?;
        // The summary is checked before it is read: the refs it resolves and the
        // deltas it advertises are what a pull acts on, so a summary the policy
        // refuses stops the pull before its first object request.
        verification
            .check_summary(summary_bytes.as_deref(), signature.as_deref())
            .await?;
        let summary = match summary_bytes.as_deref() {
            Some(bytes) => Some(Summary::parse(bytes)?),
            None => None,
        };
        check_remote_mode(&fetcher).await?;
        let targets = self
            .remote_targets(remote, &opts, summary.as_ref(), &fetcher)
            .await?;

        let mirror = opts.flags.contains(PullFlags::MIRROR);
        let prefix = if mirror {
            None
        } else {
            Some(opts.remote.as_deref().unwrap_or(remote))
        };

        // The deltas the remote can deliver these commits with, found before the
        // first object is asked for: a commit a delta carries has no `.commit`
        // request of its own.
        let deltas = delta::discover(
            self,
            &fetcher,
            summary.as_ref(),
            &targets,
            &opts,
            prefix,
            &verification,
        )
        .await?;

        let txn = self.transaction().await?;
        // The markers the pull writes, held outside the span that writes them so
        // a failure in that span clears the ones it left behind.
        let mut marked = Vec::new();
        let published = async {
            self.drive(
                &txn,
                &fetcher,
                &opts,
                prefix,
                &targets,
                &deltas,
                &verification,
                &mut marked,
            )
            .await?;
            for (name, tip) in &targets {
                txn.set_ref(&refspec(prefix, name), Some(tip));
            }
            txn.commit().await
        }
        .await;
        let stats = match published {
            Ok(stats) => stats,
            Err(e) => {
                self.clear_markers_for_absent_commits(&marked).await;
                return Err(e);
            }
        };

        // The content a marker guarded is published; a commit-only pull keeps
        // its markers, since the trees were never fetched.
        if !opts.flags.contains(PullFlags::COMMIT_ONLY) {
            for commit in &marked {
                self.remove_partial_marker(commit).await?;
            }
        }

        // A mirror pull of every ref holds the whole of what the remote
        // publishes, so the remote's summary describes this repository too and
        // is copied verbatim. A mirror pull of named refs holds part of it and
        // writes no summary.
        if mirror
            && opts.refs.is_empty()
            && let Some(bytes) = summary_bytes
        {
            let fsync = self.config().fsync()?;
            self.write_root_file(SUMMARY_FILE, bytes, fsync).await?;
            // The signature covers those bytes, so it is copied with them: a
            // client pulling from this repository with `gpg-verify-summary=true`
            // reads the pair. A remote holding no `summary.sig` leaves this
            // repository's own file as it stands, which is what the tool does.
            if let Some(sig) = signature {
                self.write_root_file(SUMMARY_SIG_FILE, sig, fsync).await?;
            }
        }

        Ok(PullStats {
            metadata_imported: stats.metadata_written,
            content_imported: stats.content_written,
            content_bytes_written: stats.content_bytes_written,
        })
    }

    /// The remote's `summary` and `summary.sig` bytes, an absent one as `None`.
    ///
    /// The remote is reached the way [`pull`](Repo::pull) reaches it: its
    /// configured URL and TLS material, with no override.
    pub async fn remote_fetch_summary(
        &self,
        remote: &str,
    ) -> Result<(Option<Vec<u8>>, Option<Vec<u8>>)> {
        let fetcher = self.remote_fetcher(remote, &PullOptions::default()).await?;
        fetch_summary(&fetcher).await
    }

    /// Build the fetcher for one remote from its config section and `opts`.
    async fn remote_fetcher(&self, remote: &str, opts: &PullOptions) -> Result<Fetcher> {
        let section = self.config().remote(remote);
        let url = match &opts.url {
            Some(url) => url.clone(),
            None => {
                let section = section
                    .as_ref()
                    .ok_or_else(|| Error::Pull(format!("no remote '{remote}' is configured")))?;
                section
                    .url()?
                    .ok_or_else(|| Error::Pull(format!("remote '{remote}' has no url")))?
            }
        };
        let tls = match &section {
            Some(section) => remote_tls(remote, section).await?,
            None => TlsOptions::default(),
        };
        Fetcher::new(FetcherOptions {
            headers: opts.http_headers.clone(),
            tls,
            max_retries: opts.n_network_retries.unwrap_or(DEFAULT_RETRIES),
            max_outstanding: opts.max_outstanding_fetches.unwrap_or(DEFAULT_OUTSTANDING),
            ..FetcherOptions::new(url)
        })
        .await
    }

    /// Resolve what to pull: the requested refs, the remote's summary refs under
    /// [`MIRROR`](PullFlags::MIRROR), or the remote's configured `branches`.
    async fn remote_targets(
        &self,
        remote: &str,
        opts: &PullOptions,
        summary: Option<&Summary>,
        fetcher: &Fetcher,
    ) -> Result<Vec<(String, Checksum)>> {
        let names = if !opts.refs.is_empty() {
            opts.refs.clone()
        } else if opts.flags.contains(PullFlags::MIRROR) {
            let Some(summary) = summary else {
                return Err(Error::Pull(
                    "fetching all refs was requested in mirror mode, but the remote \
                     repository does not have a summary"
                        .into(),
                ));
            };
            // A summary name becomes a ref this pull writes, so it is held to
            // the ref store's rule here, before the first object is requested,
            // rather than when the transaction resolves it at publication.
            for entry in &summary.refs {
                crate::refs::check_ref_path(&entry.name)?;
            }
            return Ok(summary
                .refs
                .iter()
                .map(|entry| (entry.name.clone(), entry.commit))
                .collect());
        } else {
            let branches = match self.config().remote(remote) {
                Some(section) => section.branches()?.unwrap_or_default(),
                None => Vec::new(),
            };
            if branches.is_empty() {
                return Err(Error::Pull(format!(
                    "no configured branches for remote {remote}"
                )));
            }
            branches
        };

        let mut out = Vec::with_capacity(names.len());
        for name in names {
            // The name reaches the wire as a request path, so it is held to the
            // rule the ref store holds it to: a traversal component would ask
            // the server for a resource the ref does not name.
            crate::refs::check_ref_path(&name)?;
            let checksum = match summary.and_then(|summary| summary.lookup(&name)) {
                Some(checksum) => checksum,
                None => fetch_remote_ref(fetcher, &name)
                    .await?
                    .ok_or_else(|| Error::RefNotFound(name.clone()))?,
            };
            out.push((name, checksum));
        }
        Ok(out)
    }

    /// Run the plan to completion, collecting into `marked` the commits whose
    /// `.commitpartial` marker this pull wrote and has to clear.
    ///
    /// `marked` is an argument rather than the return value so the caller holds
    /// what was written when a step fails.
    #[allow(clippy::too_many_arguments)]
    async fn drive(
        &self,
        txn: &Transaction,
        fetcher: &Fetcher,
        opts: &PullOptions,
        ref_prefix: Option<&str>,
        targets: &[(String, Checksum)],
        deltas: &HashMap<Checksum, DeltaJob>,
        verification: &Verification,
        marked: &mut Vec<Checksum>,
    ) -> Result<()> {
        // The refs each requested tip is the tip of. The binding and timestamp
        // checks are per ref, and the plan fetches one commit once however many
        // refs name it, so the step that fetches a commit runs the checks of every
        // ref in its entry here.
        let mut tips: HashMap<Checksum, Vec<String>> = HashMap::new();
        for (name, tip) in targets {
            tips.entry(*tip).or_default().push(name.clone());
        }
        let ctx = StepCtx {
            txn,
            fetcher,
            writes: Arc::new(Gate::new(WRITE_THROTTLE)),
            sources: &opts.localcache_repos,
            flags: opts.flags,
            checks: ModeChecks::new(opts.flags, self.mode()),
            ref_prefix,
            timestamp_check: &opts.timestamp_check,
            tips: &tips,
            deltas,
            verification,
            detached_filter: &opts.detached_metadata_filter,
        };
        let mut plan = Plan::default();
        for (_, tip) in targets {
            plan.push_commit(CommitItem {
                checksum: *tip,
                depth: opts.depth,
                optional: false,
            });
        }

        let mut slots = Slots::new(opts.max_outstanding_fetches.unwrap_or(DEFAULT_OUTSTANDING));
        // The read buffers a content object passes through, whichever source it
        // comes from: a localcache import verifies its payload through one, and a
        // fetched payload streams into the object store through one. A step takes
        // a buffer where it starts and hands it back with its outcome, so a pull
        // holds one buffer per slot however many objects it stores. A step that
        // fails takes its buffer with it, which ends the pull anyway.
        let mut buffers: Vec<Vec<u8>> = Vec::new();
        loop {
            while slots.has_room()
                && let Some(item) = plan.next()
            {
                let buffer = buffers.pop().unwrap_or_default();
                slots.push(self.step(&ctx, item, buffer));
            }
            let Some(outcome) = slots.next_ready().await else {
                break;
            };
            let (step, buffer) = outcome?;
            buffers.push(buffer);
            plan.apply(step, marked);
        }
        Ok(())
    }

    /// Run one unit of work: fetch an object and store it.
    ///
    /// `read_buf` is the slot's read buffer, returned with the outcome for the
    /// next step in that slot to reuse. A content object reads through it: the
    /// payload of one fetched from the remote, and the verification of one taken
    /// from a localcache repository.
    async fn step(
        &self,
        ctx: &StepCtx<'_>,
        item: Item,
        mut read_buf: Vec<u8>,
    ) -> Result<(Step, Vec<u8>)> {
        let step = match item {
            Item::Commit(commit) => self.fetch_commit(ctx, commit, &mut read_buf).await?,
            Item::Object(name) if name.ty == ObjectType::File => {
                self.fetch_content(ctx, name, &mut read_buf).await?
            }
            Item::Object(name) => self.fetch_metadata(ctx, name, &mut read_buf).await?,
            Item::Part(part) => {
                let job = ctx
                    .deltas
                    .get(&part.commit)
                    .expect("a queued part belongs to a delta this pull found");
                delta::fetch_part(ctx.txn, ctx.fetcher, job, part.index, ctx.checks).await?;
                Step::Part(part.commit)
            }
        };
        Ok((step, read_buf))
    }

    /// Fetch one commit: its detached metadata, then the object itself, then the
    /// checks each requested ref naming it is subject to. The detached metadata is
    /// written once the commit object is here.
    async fn fetch_commit(
        &self,
        ctx: &StepCtx<'_>,
        item: CommitItem,
        read_buf: &mut Vec<u8>,
    ) -> Result<Step> {
        let checksum = item.checksum;
        let name = ObjectName::new(checksum, ObjectType::Commit);

        // Detached metadata travels with its commit and is fetched ahead of it,
        // the order the tool was observed to request the pair in. The bytes are
        // held until the commit object is here, so a commit the remote does not
        // hold leaves none behind.
        let detached = self.fetch_detached_metadata(ctx, &checksum).await?;

        let present = self.has_object(ObjectType::Commit, &checksum).await?;
        let complete = present && self.commit_state(&checksum).await? == CommitState::Normal;
        // How the commit object reaches the object store, acted on once the
        // checks have passed. A commit this repository holds is there already.
        let mut staging = CommitStaging::Held;
        let bytes = if present {
            self.load_object_bytes(ObjectType::Commit, &checksum)
                .await?
        } else if let Some(src) = cached_source(ctx.sources, name).await? {
            // A localcache source holds the object, so the bytes are read from
            // there and the import runs after the checks, the order the fetched
            // branches take.
            staging = CommitStaging::Import(src);
            src.load_object_bytes(ObjectType::Commit, &checksum).await?
        } else if let Some(job) = ctx.deltas.get(&checksum) {
            // A delta carries the target commit inside its superblock, which is
            // where these bytes come from; the superblock's own parse has already
            // established that they hash to this checksum, and staging them
            // establishes it again.
            staging = CommitStaging::Write;
            job.commit_bytes.clone()
        } else {
            let path = object_path(&checksum, ObjectType::Commit);
            match fetch_whole(ctx.fetcher, &path, Priority::High, MAX_METADATA_SIZE).await {
                Ok(bytes) => {
                    staging = CommitStaging::Write;
                    bytes
                }
                // A parent the remote does not hold ends that chain, the way a
                // source with truncated history does for a local pull. Its
                // detached metadata is dropped: this repository holds no commit
                // for it to belong to.
                Err(Error::HttpStatus { status: 404, .. }) if item.optional => {
                    return Ok(Step::Done);
                }
                Err(e) => return Err(object_not_found(e, name)),
            }
        };

        let commit = Commit::parse(&bytes)?;
        // The signature check runs before the commit is staged and before its
        // tree is asked for, so a commit the policy refuses costs no object
        // fetch. It reads the detached metadata this pull puts in place: the
        // remote's copy where it served one, and this repository's own where it
        // did not, which is the metadata a later verify of the stored commit
        // reads.
        if ctx.verification.checks_commits() {
            let dict = match &detached {
                Some(bytes) => crate::summary::parse_signature_dict(bytes)?,
                None => self.read_commit_detached_metadata(&checksum).await?,
            };
            ctx.verification
                .check_commit(&checksum, &bytes, dict.as_ref())
                .await?;
        }
        // Every requested ref naming this commit is checked here. The plan fetches
        // one commit once, so a second ref at the same commit has no step of its
        // own to be checked in.
        for ref_name in ctx.tips.get(&checksum).into_iter().flatten() {
            if !ctx.flags.contains(PullFlags::DISABLE_VERIFY_BINDINGS) {
                check_ref_binding(&checksum, &commit, ref_name)?;
            }
            self.check_timestamp(ctx, ref_name, &checksum, &commit)
                .await?;
        }

        // A commit this repository already holds intact is not marked partial: a
        // pull that fails elsewhere must not demote it.
        if !complete {
            self.write_partial_marker(&checksum).await?;
        }
        // The commit is staged where it arrived, behind its own marker and ahead
        // of its tree. Either path hashes the bytes and compares the result
        // against the name they were requested by -- the write path for bytes in
        // hand, the untrusted import for a localcache source's object -- so a
        // commit stored under the wrong name fails here rather than after its tree
        // has been fetched, and nothing is held past the step. What covers a
        // reader against a commit whose tree is not yet complete is the marker,
        // cleared once the transaction has published.
        match staging {
            CommitStaging::Held => {}
            CommitStaging::Import(src) => {
                self.import_from(
                    ctx.txn,
                    src,
                    name,
                    ctx.flags | PullFlags::UNTRUSTED,
                    read_buf,
                )
                .await?;
            }
            CommitStaging::Write => {
                ctx.txn
                    .write_metadata(ObjectType::Commit, Some(&checksum), &bytes)
                    .await?;
            }
        }
        // The commit object is here, so its detached metadata is written now,
        // ahead of the ref that names it, which is what a verifier reading the
        // signatures alongside the commit requires. A commit this repository
        // already holds has the remote's copy written over its own, which is
        // what re-reading a mutable file on every pull is for. The filter runs
        // here, after the checks above read the metadata as the remote holds it,
        // so what a filter drops is dropped from what is stored and not from
        // what was verified. A filter that allows no property writes nothing,
        // which leaves the copy this repository holds as it stands.
        if let Some(meta) = detached
            && let Some(meta) = ctx.detached_filter.apply(&checksum, meta)?
        {
            self.write_commit_detached_bytes(&checksum, meta).await?;
        }
        // Where the commit's objects come from. A commit already complete here
        // needs none of them: what it references is present. Its parent is a
        // separate question, since the depth an earlier pull ran at may be
        // shallower than this one's, so the chain walks on and the parent's own
        // step decides what it needs.
        let tree = vec![
            ObjectName::new(commit.root_dirmeta, ObjectType::DirMeta),
            ObjectName::new(commit.root_dirtree, ObjectType::DirTree),
        ];
        let next = if complete || ctx.flags.contains(PullFlags::COMMIT_ONLY) {
            CommitNext::Nothing
        } else if let Some(job) = ctx.deltas.get(&checksum) {
            // A delta delivers the tree: its parts, and the objects it names but
            // hands over loose. The tree walk follows the last part, so what no
            // part delivered is found there and fetched loose.
            CommitNext::Delta {
                parts: job.parts(),
                fallbacks: job.fallbacks(),
                tree,
            }
        } else {
            CommitNext::Scan(tree)
        };
        Ok(Step::Commit(CommitOutcome {
            checksum,
            next,
            parent: commit.parent,
            marked: !complete,
        }))
    }

    /// Read a commit's `.commitmeta` from the first localcache source holding it
    /// and from the remote otherwise, returning the bytes for the caller to write
    /// once the commit object is here. A 404 is the commit carrying none, which
    /// leaves this repository's copy as it stands.
    async fn fetch_detached_metadata(
        &self,
        ctx: &StepCtx<'_>,
        commit: &Checksum,
    ) -> Result<Option<Vec<u8>>> {
        for src in ctx.sources {
            match src.load_object_bytes(ObjectType::CommitMeta, commit).await {
                Ok(bytes) => return Ok(Some(bytes)),
                Err(Error::ObjectNotFound { .. }) => continue,
                Err(e) => return Err(e),
            }
        }
        let path = object_path(commit, ObjectType::CommitMeta);
        fetch_optional(ctx.fetcher, &path, Priority::High, MAX_METADATA_SIZE).await
    }

    /// Fetch one dirtree or dirmeta object and store it. A dirtree also reports
    /// what it references, which is what the scan walks on from.
    async fn fetch_metadata(
        &self,
        ctx: &StepCtx<'_>,
        name: ObjectName,
        read_buf: &mut Vec<u8>,
    ) -> Result<Step> {
        // An object already here is not fetched again. A dirtree is still read:
        // what it references may be missing, and the walk is what finds that
        // out.
        if ctx.txn.is_staged(&name.checksum, name.ty)
            || self.has_object(name.ty, &name.checksum).await?
        {
            // An object this transaction staged lives in the staging directory
            // until the transaction publishes, so the read checks the staged set
            // before `objects/`.
            return self
                .walked(name, || ctx.txn.load_dirtree_staged_first(&name.checksum))
                .await;
        }
        if let Some(src) = cached_source(ctx.sources, name).await? {
            self.import_from(
                ctx.txn,
                src,
                name,
                ctx.flags | PullFlags::UNTRUSTED,
                read_buf,
            )
            .await?;
            return self.walked(name, || src.load_dirtree(&name.checksum)).await;
        }
        let path = object_path(&name.checksum, name.ty);
        let bytes = fetch_whole(ctx.fetcher, &path, Priority::High, MAX_METADATA_SIZE)
            .await
            .map_err(|e| object_not_found(e, name))?;
        // The write path hashes the bytes and compares the result against the
        // name they were requested by, so a substituted object fails here.
        ctx.txn
            .write_metadata(name.ty, Some(&name.checksum), &bytes)
            .await?;
        match name.ty {
            ObjectType::DirTree => Ok(Step::DirTree(children_of(&DirTree::parse(&bytes)?))),
            _ => Ok(Step::Done),
        }
    }

    /// The step a stored metadata object produces: a dirtree reports what it
    /// references, and anything else is a leaf, so `load` is called only for a
    /// dirtree.
    async fn walked<F>(&self, name: ObjectName, load: impl FnOnce() -> F) -> Result<Step>
    where
        F: Future<Output = Result<DirTree>>,
    {
        if name.ty != ObjectType::DirTree {
            return Ok(Step::Done);
        }
        Ok(Step::DirTree(children_of(&load().await?)))
    }

    /// Fetch one content object and store it.
    async fn fetch_content(
        &self,
        ctx: &StepCtx<'_>,
        name: ObjectName,
        read_buf: &mut Vec<u8>,
    ) -> Result<Step> {
        if ctx.txn.is_staged(&name.checksum, ObjectType::File)
            || self.has_object(ObjectType::File, &name.checksum).await?
        {
            return Ok(Step::Done);
        }
        if let Some(src) = cached_source(ctx.sources, name).await? {
            self.import_from(
                ctx.txn,
                src,
                name,
                ctx.flags | PullFlags::UNTRUSTED,
                read_buf,
            )
            .await?;
            return Ok(Step::Done);
        }
        // A content object is requested as `.filez` whatever the remote stores
        // on its own disk: the framed, deflated form is the one an HTTP client
        // can read.
        let path = object_path(&name.checksum, ObjectType::File);
        let body = match ctx
            .fetcher
            .fetch(FetchRequest {
                priority: Priority::Low,
                ..FetchRequest::path(&path)
            })
            .await
        {
            Ok(Fetched::Body(body)) => body,
            Ok(Fetched::NotModified) => {
                return Err(Error::Fetch(format!(
                    "{path}: the remote answered 304 to an unconditional request"
                )));
            }
            Err(e) => return Err(object_not_found(e, name)),
        };
        // The write permit is taken before the body is read: a step waiting for
        // one has not yet asked the connection for bytes, so the fetcher's
        // progress window is not running against it. It covers the whole body --
        // the header read and the end-of-stream read along with the payload --
        // and is released where the step returns.
        let _permit = ctx.writes.acquire(Priority::Normal).await;
        self.store_content(ctx, &name.checksum, body, read_buf)
            .await?;
        Ok(Step::Done)
    }

    /// Store one fetched content object under the name it was requested by.
    ///
    /// The payload streams through `read_buf`, the slot's buffer, so the objects
    /// a slot stores share one allocation.
    async fn store_content(
        &self,
        ctx: &StepCtx<'_>,
        expected: &Checksum,
        body: Body,
        read_buf: &mut Vec<u8>,
    ) -> Result<()> {
        let (header, declared, framed_header, mut body) = read_archive_header(body).await?;
        let symlink = header.is_symlink();
        let FileHeader {
            uid,
            gid,
            mode,
            symlink_target,
            xattrs,
        } = header.clone();
        let meta = FileMeta {
            uid,
            gid,
            mode,
            xattrs,
        };
        // The same mode checks a local pull makes, over the metadata the object
        // arrives with rather than the one a source repository stored.
        ctx.checks.check(expected, &meta)?;
        if symlink {
            check_stream_end(expected, "symlink header", &mut body).await?;
            ctx.txn
                .write_symlink(&symlink_target, &meta, Some(expected))
                .await?;
            return Ok(());
        }
        // The declared size bounds both sides of the payload: what it may
        // decompress to, and what may come off the connection to produce that.
        let source = BoundedInput::new(body, *expected, compressed_bound(declared));
        if ctx.txn.repo().mode().is_archive() {
            // The remote already stores this object deflated in the same wire
            // form this destination writes: store the fetched bytes verbatim
            // instead of inflating and recompressing them.
            ctx.txn
                .write_archive_payload(
                    expected,
                    &header,
                    &framed_header,
                    declared,
                    source,
                    read_buf,
                )
                .await
                .map_err(payload_refusal)?;
            return Ok(());
        }
        let mut writer = ctx.txn.content_writer(Some(expected), &meta).await?;
        let mut payload = DeflateDecoder::new(BufSource::new(source));
        copy_bounded(&mut payload, &mut writer, read_buf, expected, declared)
            .await
            .map_err(payload_refusal)?;
        writer.finish().await?;
        // The decoder stops at the DEFLATE end-of-stream marker and asks its
        // input for nothing more, so the response has to be read to its end
        // here: that read is what returns the connection to the pool for the
        // next object.
        check_stream_end(expected, "deflated payload", payload.into_inner())
            .await
            .map_err(payload_refusal)?;
        Ok(())
    }

    /// Refuse a fetched tip that is older than what it is checked against.
    async fn check_timestamp(
        &self,
        ctx: &StepCtx<'_>,
        ref_name: &str,
        tip: &Checksum,
        fetched: &Commit,
    ) -> Result<()> {
        let against = match ctx.timestamp_check {
            TimestampCheck::Off => return Ok(()),
            TimestampCheck::CurrentRef => {
                let current = self
                    .resolve_ref_tip(&refspec(ctx.ref_prefix, ref_name))
                    .await?;
                // A ref this repository does not hold yet has nothing to be
                // older than.
                let Some(current) = current else {
                    return Ok(());
                };
                current
            }
            TimestampCheck::Rev(rev) => *rev,
        };
        let bytes = self.load_object_bytes(ObjectType::Commit, &against).await?;
        let current = Commit::parse(&bytes)?;
        if fetched.timestamp >= current.timestamp {
            return Ok(());
        }
        Err(Error::Pull(format!(
            "commit {tip} (timestamp {}) is chronologically older than \
             {against} (timestamp {})",
            fetched.timestamp, current.timestamp
        )))
    }
}

/// What every step of one pull shares.
struct StepCtx<'a> {
    txn: &'a Transaction,
    fetcher: &'a Fetcher,
    /// The write throttle: how many fetched content objects stream into the
    /// object store at once.
    writes: Arc<Gate>,
    /// Repositories consulted for an object before the network, in order.
    sources: &'a [Repo],
    flags: PullFlags,
    /// The mode checks every content object this pull writes is held to,
    /// whichever path it arrives by: a loose fetch, a localcache import, or a
    /// static delta's parts.
    checks: ModeChecks,
    /// The prefix the pulled refs are written under, which the timestamp check
    /// resolves the ref's current tip through. `None` is a local ref.
    ref_prefix: Option<&'a str>,
    timestamp_check: &'a TimestampCheck,
    /// The requested refs each tip commit is the tip of, which the binding and
    /// timestamp checks are made against. A commit with no entry is a parent
    /// reached under `depth`, which no ref names.
    tips: &'a HashMap<Checksum, Vec<String>>,
    /// The static delta each target commit is delivered by, where the remote
    /// publishes one. A commit with no entry is fetched object by object.
    deltas: &'a HashMap<Checksum, DeltaJob>,
    /// The signature checks this pull makes, which every commit a step carries
    /// is held to before its bytes are staged.
    verification: &'a Verification,
    /// Which properties of a commit's detached metadata this pull stores,
    /// applied once the commit's checks have passed.
    detached_filter: &'a DetachedMetadataFilter,
}

/// One commit to fetch.
struct CommitItem {
    checksum: Checksum,
    /// How many more parents to follow from here, `-1` for all of them.
    depth: i32,
    /// Whether a remote that does not hold this commit ends the chain rather
    /// than failing the pull, which is what a parent under `depth` does.
    optional: bool,
}

/// One part of one commit's delta.
struct PartItem {
    /// The commit the delta produces, which the job is keyed by.
    commit: Checksum,
    /// The part's index, which is both its position in the superblock's entry
    /// list and its file name on the remote.
    index: usize,
}

/// One unit of work a slot runs.
enum Item {
    Commit(CommitItem),
    Object(ObjectName),
    Part(PartItem),
}

/// What one step produced.
enum Step {
    /// A commit object arrived, or was already here.
    Commit(CommitOutcome),
    /// A dirtree is stored; these are the objects it references.
    DirTree(Vec<ObjectName>),
    /// A delta part is applied; this is the commit it belongs to.
    Part(Checksum),
    /// Nothing follows: a dirmeta or content object is stored, or a parent the
    /// remote does not hold ended its chain.
    Done,
}

/// What a commit contributes to the plan.
struct CommitOutcome {
    checksum: Checksum,
    /// What the commit's objects are fetched by.
    next: CommitNext,
    /// The parent to follow under `depth`.
    parent: Option<Checksum>,
    /// Whether this pull wrote the commit's `.commitpartial` marker.
    marked: bool,
}

/// How a commit object reaches the object store, once the commit has passed the
/// checks its step makes.
enum CommitStaging<'a> {
    /// This repository holds it.
    Held,
    /// A localcache repository holds it, to import from there.
    Import(&'a Repo),
    /// Its bytes are in hand, to write into the transaction.
    Write,
}

/// How a commit's objects reach this repository.
enum CommitNext {
    /// Object by object: the commit's root dirmeta and dirtree, walked from
    /// there.
    Scan(Vec<ObjectName>),
    /// By static delta: the delta's parts, the objects it hands over loose, and
    /// the tree walk that follows the last part.
    Delta {
        parts: usize,
        fallbacks: Vec<ObjectName>,
        tree: Vec<ObjectName>,
    },
    /// Nothing: the commit is complete here, or the pull is commit-only.
    Nothing,
}

/// What the pull still has to do, and what it has done.
///
/// The loop owns this, so nothing here is shared or locked.
#[derive(Default)]
struct Plan {
    /// The commits, drained first and fetched at high priority.
    commits: VecDeque<CommitItem>,
    /// The delta parts, drained second, fetched at high priority, and held to
    /// [`PART_CAP`] in flight whatever the pull's slot count is.
    parts: VecDeque<PartItem>,
    /// How many part fetches are in flight.
    parts_in_flight: usize,
    /// How many parts of each commit's delta have still to be applied, and the
    /// tree walk queued once that count reaches zero.
    delta_parts: HashMap<Checksum, usize>,
    delta_trees: HashMap<Checksum, Vec<ObjectName>>,
    /// The dirtree and dirmeta objects the walk is blocked on, drained third
    /// and fetched at high priority.
    scan: VecDeque<ObjectName>,
    /// The content objects, drained last and fetched at low priority.
    content: VecDeque<ObjectName>,
    /// The objects this pull has queued, so an object several commits reach is
    /// fetched once.
    queued: HashSet<ObjectName>,
    /// The remaining depth each commit was reached at, which is what decides
    /// whether a chain arriving at it again walks on from it.
    seen: HashMap<Checksum, i32>,
    /// The parent each fetched commit named, so a chain reaching it again with
    /// further to go resumes without refetching it.
    parents: HashMap<Checksum, Option<Checksum>>,
}

impl Plan {
    /// Queue a commit unless it has already been reached at least this deep.
    ///
    /// A commit reached again with further to go is not fetched again: the walk
    /// resumes at the parent it named. A commit still in flight has not named
    /// one yet, and its own outcome follows the parent to the depth recorded
    /// here.
    fn push_commit(&mut self, mut item: CommitItem) {
        loop {
            if let Some(&prev) = self.seen.get(&item.checksum)
                && reaches_at_least(prev, item.depth)
            {
                return;
            }
            let depth = item.depth;
            if self.seen.insert(item.checksum, depth).is_none() {
                self.commits.push_back(item);
                return;
            }
            if depth == 0 {
                return;
            }
            let Some(Some(parent)) = self.parents.get(&item.checksum).copied() else {
                return;
            };
            item = CommitItem {
                checksum: parent,
                depth: one_less(depth),
                optional: true,
            };
        }
    }

    /// Queue an object this pull has not queued already.
    fn push_object(&mut self, name: ObjectName) {
        if !self.queued.insert(name) {
            return;
        }
        match name.ty {
            ObjectType::File => self.content.push_back(name),
            _ => self.scan.push_back(name),
        }
    }

    /// The next unit of work: the commits, then the delta parts, then the scan,
    /// then the content.
    ///
    /// A queued part is held back while [`PART_CAP`] of them are in flight, so a
    /// pull with more slots than that spends the rest on the scan and the content
    /// rather than on a third part. The loop can therefore run out of work while
    /// parts are queued, which is safe: a part is held back only when one is in
    /// flight, and that one occupies a slot the loop is waiting on.
    fn next(&mut self) -> Option<Item> {
        if let Some(commit) = self.commits.pop_front() {
            return Some(Item::Commit(commit));
        }
        if self.parts_in_flight < PART_CAP
            && let Some(part) = self.parts.pop_front()
        {
            self.parts_in_flight += 1;
            return Some(Item::Part(part));
        }
        if let Some(name) = self.scan.pop_front() {
            return Some(Item::Object(name));
        }
        self.content.pop_front().map(Item::Object)
    }

    /// Fold one step's outcome back into the plan.
    fn apply(&mut self, step: Step, marked: &mut Vec<Checksum>) {
        match step {
            Step::Commit(outcome) => self.apply_commit(outcome, marked),
            Step::DirTree(children) => {
                for child in children {
                    self.push_object(child);
                }
            }
            Step::Part(commit) => self.apply_part(commit),
            Step::Done => {}
        }
    }

    /// Record an applied delta part, and queue its commit's tree walk once the
    /// delta's last part is applied.
    fn apply_part(&mut self, commit: Checksum) {
        self.parts_in_flight -= 1;
        let left = self
            .delta_parts
            .get_mut(&commit)
            .expect("an applied part belongs to a commit whose delta is counted");
        *left -= 1;
        if *left > 0 {
            return;
        }
        self.delta_parts.remove(&commit);
        // Every object the delta carries is staged now, so the walk reads what is
        // here and asks the network only for what the delta left out.
        for name in self.delta_trees.remove(&commit).unwrap_or_default() {
            self.push_object(name);
        }
    }

    /// Record a commit and queue what it needs.
    fn apply_commit(&mut self, outcome: CommitOutcome, marked: &mut Vec<Checksum>) {
        if outcome.marked {
            marked.push(outcome.checksum);
        }
        self.parents.insert(outcome.checksum, outcome.parent);
        match outcome.next {
            CommitNext::Nothing => {}
            CommitNext::Scan(tree) => {
                for name in tree {
                    self.push_object(name);
                }
            }
            CommitNext::Delta {
                parts,
                fallbacks,
                tree,
            } => {
                // The objects the delta hands over loose are queued at once, so
                // they travel alongside the parts rather than after them.
                for name in fallbacks {
                    self.push_object(name);
                }
                if parts == 0 {
                    // A delta of fallbacks alone has no part to wait for.
                    for name in tree {
                        self.push_object(name);
                    }
                } else {
                    self.delta_parts.insert(outcome.checksum, parts);
                    self.delta_trees.insert(outcome.checksum, tree);
                    for index in 0..parts {
                        self.parts.push_back(PartItem {
                            commit: outcome.checksum,
                            index,
                        });
                    }
                }
            }
        }
        // The depth comes from the plan and not from the item: a later chain may
        // have reached this commit with further to go while it was in flight.
        let depth = self.seen.get(&outcome.checksum).copied().unwrap_or(0);
        if depth != 0
            && let Some(parent) = outcome.parent
        {
            self.push_commit(CommitItem {
                checksum: parent,
                depth: one_less(depth),
                optional: true,
            });
        }
    }
}

/// One parent followed: a finite depth counts down, and `-1` stays `-1`.
fn one_less(depth: i32) -> i32 {
    if depth > 0 { depth - 1 } else { depth }
}

/// The objects a dirtree references: its files, and the dirmeta and dirtree of
/// each subdirectory.
fn children_of(dirtree: &DirTree) -> Vec<ObjectName> {
    let mut out = Vec::with_capacity(dirtree.files.len() + 2 * dirtree.dirs.len());
    for (_, file) in &dirtree.files {
        out.push(ObjectName::new(*file, ObjectType::File));
    }
    for (_, subtree, submeta) in &dirtree.dirs {
        out.push(ObjectName::new(*submeta, ObjectType::DirMeta));
        out.push(ObjectName::new(*subtree, ObjectType::DirTree));
    }
    out
}

/// The request path of a loose object. The remote is an archive repository, so a
/// content object is named `.filez` there whatever this repository stores.
fn object_path(checksum: &Checksum, ty: ObjectType) -> String {
    format!("objects/{}", loose_path(checksum, ty, RepoMode::Archive))
}

/// The first localcache repository holding `name`.
async fn cached_source(sources: &[Repo], name: ObjectName) -> Result<Option<&Repo>> {
    for src in sources {
        if src.has_object(name.ty, &name.checksum).await? {
            return Ok(Some(src));
        }
    }
    Ok(None)
}

/// Report a 404 for an object as the object being absent; anything else stands.
fn object_not_found(error: Error, name: ObjectName) -> Error {
    match error {
        Error::HttpStatus { status: 404, .. } => Error::ObjectNotFound {
            checksum: name.checksum,
            ty: name.ty,
        },
        other => other,
    }
}

/// The remote's summary and its signature, an absent one as `None`.
///
/// The signature is fetched first, which is the order the tool asks in: it
/// covers the summary that follows, and asking the other way round would pair a
/// summary with the signature of one the remote had already replaced.
async fn fetch_summary(fetcher: &Fetcher) -> Result<(Option<Vec<u8>>, Option<Vec<u8>>)> {
    let signature =
        fetch_optional(fetcher, SUMMARY_SIG_FILE, Priority::High, MAX_ROOT_FILE).await?;
    let summary = fetch_optional(fetcher, SUMMARY_FILE, Priority::High, MAX_ROOT_FILE).await?;
    Ok((summary, signature))
}

/// Refuse a remote whose `[core] mode` is not archive.
async fn check_remote_mode(fetcher: &Fetcher) -> Result<()> {
    let Some(bytes) = fetch_optional(fetcher, CONFIG_FILE, Priority::High, MAX_ROOT_FILE).await?
    else {
        // A remote that serves no config is taken at its word as an archive,
        // which is what the `.filez` objects it serves say it is.
        return Ok(());
    };
    let text = String::from_utf8(bytes)
        .map_err(|_| Error::InvalidFormat("the remote config is not valid utf-8".into()))?;
    let config = RepoConfig::parse(&text)?;
    if config.mode().is_archive() {
        return Ok(());
    }
    Err(Error::Unsupported(format!(
        "can't pull from a remote in mode {}: an http pull reads an archive \
         repository, whose content objects are served in the framed, deflated \
         form a client can store",
        config.mode().as_mode_str()
    )))
}

/// The commit a remote's `refs/heads/<name>` names, or `None` when the remote
/// serves no such ref.
async fn fetch_remote_ref(fetcher: &Fetcher, name: &str) -> Result<Option<Checksum>> {
    let path = ref_request_path(name);
    let Some(bytes) = fetch_optional(fetcher, &path, Priority::High, MAX_REF_FILE).await? else {
        return Ok(None);
    };
    let text = std::str::from_utf8(&bytes)
        .map_err(|_| Error::InvalidFormat(format!("the remote ref {name} is not valid utf-8")))?;
    Ok(Some(Checksum::from_hex(text.trim())?))
}

/// The request path of a remote ref: `refs/heads/` and the percent-encoded name.
///
/// A request path reaches the wire as written, so the name is encoded where it
/// is built. Everything outside the unreserved set of RFC 3986 -- the ASCII
/// letters and digits, `-`, `.`, `_`, and `~` -- is encoded, `/` excepted, which
/// separates the name's components as it does the path's. A name carrying `?`,
/// `#`, or `%` therefore names the ref rather than a query, a fragment, or an
/// escape the server decodes into a different name.
fn ref_request_path(name: &str) -> String {
    const HEX: &[u8; 16] = b"0123456789ABCDEF";
    let mut out = String::from("refs/heads/");
    for byte in name.bytes() {
        match byte {
            b'A'..=b'Z' | b'a'..=b'z' | b'0'..=b'9' | b'-' | b'.' | b'_' | b'~' | b'/' => {
                out.push(char::from(byte));
            }
            other => {
                out.push('%');
                out.push(char::from(HEX[usize::from(other >> 4)]));
                out.push(char::from(HEX[usize::from(other & 0x0f)]));
            }
        }
    }
    out
}

/// Fetch a path whole, or `None` when the remote answers 404.
pub(crate) async fn fetch_optional(
    fetcher: &Fetcher,
    path: &str,
    priority: Priority,
    max_size: u64,
) -> Result<Option<Vec<u8>>> {
    match fetch_whole(fetcher, path, priority, max_size).await {
        Ok(bytes) => Ok(Some(bytes)),
        Err(Error::HttpStatus { status: 404, .. }) => Ok(None),
        Err(e) => Err(e),
    }
}

/// Fetch a path whole, under a size cap.
///
/// The fetcher refuses a declared `Content-Length` above the cap before the body
/// is read and stops a body that passes the cap as the bytes arrive. One buffer
/// belongs to each fetch in flight, so the cap a caller names bounds the memory
/// of one step: [`MAX_METADATA_SIZE`] for a metadata object,
/// [`MAX_ROOT_FILE`] for a repository-root file, [`MAX_REF_FILE`] for a
/// `refs/heads/<ref>` file.
///
/// The buffer is sized from the declared length, which the fetcher has already
/// held to the cap, so the body lands in one allocation of its own size and the
/// resident peak is what the cap states. The one spare byte is where the final
/// read finds the end of the stream: a buffer filled to its capacity is grown
/// before that read, which would double it. A remote declaring no length grows
/// its buffer as it reads, under the same cap.
async fn fetch_whole(
    fetcher: &Fetcher,
    path: &str,
    priority: Priority,
    max_size: u64,
) -> Result<Vec<u8>> {
    let fetched = fetcher
        .fetch(FetchRequest {
            priority,
            max_size: Some(max_size),
            ..FetchRequest::path(path)
        })
        .await?;
    let Fetched::Body(mut body) = fetched else {
        return Err(Error::Fetch(format!(
            "{path}: the remote answered 304 to an unconditional request"
        )));
    };
    let declared = body.content_length().unwrap_or(0).min(max_size);
    let mut out = Vec::with_capacity(usize::try_from(declared).unwrap_or(0).saturating_add(1));
    body.read_to_end(&mut out).await?;
    Ok(out)
}

/// Read the archive framing off the front of a content object's stream: a
/// four-byte big-endian header length, four zero bytes, then the header itself.
/// What remains of the stream is the raw-DEFLATE payload.
///
/// The size the header declares for that payload is returned with it, and bounds
/// what the payload is allowed to decompress to. The raw framed bytes -- the
/// length prefix and the header variant, exactly as the remote sent them -- are
/// returned too, for a caller that stores them verbatim rather than
/// re-serializing the parsed header.
///
/// The remote states the header length and supplies the bytes behind it, so a
/// length above [`MAX_FILE_HEADER_SIZE`] is refused before the buffer for it is
/// allocated. That bound holds for each fetch in flight, since one header is
/// read per content object.
async fn read_archive_header<R: AsyncRead + Unpin>(
    mut stream: R,
) -> Result<(FileHeader, u64, Vec<u8>, R)> {
    let mut prefix = [0u8; 8];
    stream.read_exact(&mut prefix).await?;
    if prefix[4..] != [0u8; 4] {
        return Err(Error::InvalidFormat(
            "content framing padding is not zero".into(),
        ));
    }
    let header_len =
        u32::from_be_bytes(prefix[..4].try_into().expect("four bytes of a length")) as u64;
    if header_len > MAX_FILE_HEADER_SIZE {
        return Err(Error::InvalidFormat(
            "content header exceeds the size cap".into(),
        ));
    }
    let mut bytes = vec![0u8; header_len as usize];
    stream.read_exact(&mut bytes).await?;
    let (header, uncompressed) = FileHeader::parse_archive(&bytes)?;
    let mut framed = prefix.to_vec();
    framed.extend_from_slice(&bytes);
    Ok((header, uncompressed, framed, stream))
}

/// Stream a content object's payload into `writer`, stopping if it outgrows the
/// size its header declared.
///
/// A correct object decompresses to exactly `declared`, so a stream that passes
/// it is corrupt or built to expand, and either way there is nothing to be gained
/// from reading the rest of it. The declared size is not covered by the object's
/// checksum, which is compared at the end of the payload: this bounds what has to
/// be written before that comparison is reached. Each read is clamped to what is
/// left plus the byte that settles it, so at most one byte past the declaration
/// is stored before the refusal.
///
/// `buf` is the slot's read buffer, grown to [`READ_CHUNK`] on its first use and
/// reused by every object that slot stores after it.
///
/// The compressed side of the same declaration is bounded by [`BoundedInput`],
/// under the decoder.
async fn copy_bounded<R, W>(
    mut reader: R,
    writer: &mut W,
    buf: &mut Vec<u8>,
    expected: &Checksum,
    declared: u64,
) -> Result<()>
where
    R: AsyncRead + Unpin,
    W: futures_io::AsyncWrite + Unpin,
{
    if buf.len() < READ_CHUNK {
        buf.resize(READ_CHUNK, 0);
    }
    let mut left = declared;
    loop {
        let window = buf.len().min(
            usize::try_from(left)
                .unwrap_or(usize::MAX)
                .saturating_add(1),
        );
        let n = reader.read(&mut buf[..window]).await?;
        if n == 0 {
            return Ok(());
        }
        if n as u64 > left {
            return Err(Error::InvalidFormat(format!(
                "content object {expected}: the payload outgrew the {declared} \
                 byte(s) its header declares"
            )));
        }
        left -= n as u64;
        writer.write_all(&buf[..n]).await?;
    }
}

/// How many bytes a payload declaring `declared` uncompressed bytes may take off
/// the connection.
///
/// A stored block is the form a DEFLATE compressor falls back to for data it
/// cannot shrink: five bytes of framing per 65535 bytes of input, which is one
/// part in thirteen thousand. A part in a thousand covers that with room to spare.
/// The fixed 64 KiB covers a small object, whose framing outweighs its content.
/// A stream past this bound is not a compressed form of what the header declares,
/// whatever it decompresses to.
fn compressed_bound(declared: u64) -> u64 {
    declared
        .saturating_add(declared / 1024)
        .saturating_add(64 * 1024)
}

/// A content object's compressed stream, bounded against the size its header
/// declares.
///
/// [`copy_bounded`] bounds what the payload decompresses to. That says nothing
/// about how many compressed bytes produce it: an empty non-final DEFLATE block is
/// five bytes that decompress to nothing, so a stream of them decompresses to
/// nothing for as long as the remote sends it, and memory and disk stay bounded
/// while time and bandwidth do not. The decoder does not return to its caller
/// while its input keeps yielding bytes, so the bound on that input belongs in the
/// read the decoder itself makes, which is this one.
///
/// The refusal travels as an [`Error::InvalidFormat`] inside the `io::Error` the
/// decoder passes up, which [`payload_refusal`] takes back out: the bound comes
/// from the object's own declaration, so the refusal names the object as the
/// decompressed-size refusal does.
struct BoundedInput<R> {
    inner: R,
    /// The object the bound is stated for.
    checksum: Checksum,
    bound: u64,
    /// What has been taken from `inner`, which passes the bound by at most the one
    /// read that trips it.
    taken: u64,
}

impl<R> BoundedInput<R> {
    fn new(inner: R, checksum: Checksum, bound: u64) -> BoundedInput<R> {
        BoundedInput {
            inner,
            checksum,
            bound,
            taken: 0,
        }
    }
}

impl<R: AsyncRead + Unpin> AsyncRead for BoundedInput<R> {
    fn poll_read(
        self: Pin<&mut Self>,
        cx: &mut Context<'_>,
        buf: &mut [u8],
    ) -> Poll<std::io::Result<usize>> {
        let me = self.get_mut();
        let n = ready!(Pin::new(&mut me.inner).poll_read(cx, buf))?;
        me.taken += n as u64;
        if me.taken > me.bound {
            return Poll::Ready(Err(std::io::Error::other(Error::InvalidFormat(format!(
                "content object {}: the compressed payload passed the {} byte(s) \
                 its declared size allows",
                me.checksum, me.bound
            )))));
        }
        Poll::Ready(Ok(n))
    }
}

/// Take back the refusal a bounded read reported.
///
/// The decoder returns its input's failure as its own, so a bound [`BoundedInput`]
/// enforced arrives here inside an `io::Error`. Unwrapping it puts that refusal on
/// the footing of one [`copy_bounded`] raises itself. Any other failure stands as
/// it is.
fn payload_refusal(error: Error) -> Error {
    match error {
        Error::Io(io) => io.downcast::<Error>().unwrap_or_else(Error::Io),
        other => other,
    }
}

/// Establish that a content object's stream ends after `after`, and reach that
/// end.
///
/// One byte settles it. The framing that selects the caller's check arrives from
/// the remote, so the bytes a remote sends instead of an end of stream are of a
/// length that remote chose; reading them out would hold all of them. An object
/// that ends where it should reaches the end of its response in this read, which
/// returns the connection to the pool for the next object.
///
/// The payload's stream is the decoder's input buffer, which hands back
/// read-ahead the decoder left before it asks the body for more. A correct
/// object leaves none: nothing follows its final DEFLATE block.
async fn check_stream_end<R: AsyncRead + Unpin>(
    expected: &Checksum,
    after: &str,
    mut stream: R,
) -> Result<()> {
    let mut byte = [0u8; 1];
    if stream.read(&mut byte).await? != 0 {
        return Err(Error::InvalidFormat(format!(
            "content object {expected}: bytes follow the {after}"
        )));
    }
    Ok(())
}

/// Read the trust anchors and the client identity a remote's TLS keys name.
async fn remote_tls(remote: &str, section: &crate::config::Remote<'_>) -> Result<TlsOptions> {
    // `tls-permissive` keeps the host name check and ignores `tls-ca-path`.
    // Both are measured of the reference tool (`docs/port-plan.md`, Phase 23,
    // "tls-permissive on a remote"): a CA that signed nothing in the chain
    // serves, and so does a path naming a file that is absent. The path is
    // therefore left unread here rather than read and discarded, so an absent
    // one is no failure. `DangerousAcceptAnyChain` holds the name check and
    // takes the chain as presented, so it is the setting that mapping asks
    // for. It drops the expiry check as well, which is the port's own reading
    // and not a measurement: a peer verification that ignores the CA path is
    // libcurl peer verification switched off, and that setting takes the
    // validity dates with it.
    let roots = if section.tls_permissive()? {
        TrustRoots::DangerousAcceptAnyChain
    } else {
        match section.tls_ca_path()? {
            Some(path) => TrustRoots::Pem(read_pem(&path).await?),
            None => TrustRoots::System,
        }
    };
    let client_identity = match (
        section.tls_client_cert_path()?,
        section.tls_client_key_path()?,
    ) {
        (Some(cert), Some(key)) => Some(ClientIdentity {
            cert_chain_pem: read_pem(&cert).await?,
            key_pem: read_pem(&key).await?,
            // A remote carries no config key for a passphrase, so a remote
            // client key has to be one that needs none.
            key_passphrase: None,
        }),
        (None, None) => None,
        _ => {
            return Err(Error::Pull(format!(
                "remote '{remote}': a client certificate needs both \
                 tls-client-cert-path and tls-client-key-path"
            )));
        }
    };
    Ok(TlsOptions {
        roots,
        client_identity,
    })
}

/// Read a PEM file named by the config.
async fn read_pem(path: &str) -> Result<Vec<u8>> {
    let path = path.to_owned();
    ostrya_rt::unblock(move || std::fs::read(&path).map_err(Error::from)).await
}

#[cfg(test)]
mod tests {
    use super::*;
    use async_compression::futures::bufread::DeflateEncoder;
    use futures_lite::io::Cursor;
    use ostrya_core::Xattrs;
    use ostrya_rt::block_on;
    use std::pin::Pin;
    use std::task::{Context, Poll};

    /// The archive stored form of a content object: the framed header, then the
    /// payload the caller supplies.
    fn framed(header: &FileHeader, uncompressed: u64, payload: &[u8]) -> Vec<u8> {
        let bytes = header.serialize_archive(uncompressed).unwrap();
        let mut out = Vec::new();
        out.extend_from_slice(&(bytes.len() as u32).to_be_bytes());
        out.extend_from_slice(&[0u8; 4]);
        out.extend_from_slice(&bytes);
        out.extend_from_slice(payload);
        out
    }

    fn regular_header() -> FileHeader {
        FileHeader {
            uid: 0,
            gid: 0,
            mode: 0o100644,
            symlink_target: String::new(),
            xattrs: Xattrs::default(),
        }
    }

    /// The header comes off the front of the stream and the payload is what is
    /// left, which is what the decoder is handed.
    #[test]
    fn the_header_is_read_off_the_front_and_the_payload_is_left() {
        block_on(async {
            let stored = framed(&regular_header(), 4, b"payload bytes");
            let (header, declared, raw, mut rest) =
                read_archive_header(Cursor::new(stored.clone()))
                    .await
                    .unwrap();
            assert_eq!(header, regular_header());
            assert_eq!(declared, 4);
            assert_eq!(raw, stored[..stored.len() - b"payload bytes".len()]);
            let mut payload = Vec::new();
            rest.read_to_end(&mut payload).await.unwrap();
            assert_eq!(payload, b"payload bytes");
        });
    }

    /// A symlink's header names its target, and its stored form carries no
    /// payload at all.
    #[test]
    fn a_symlink_header_names_its_target() {
        block_on(async {
            let header = FileHeader {
                uid: 0,
                gid: 0,
                mode: 0o120777,
                symlink_target: "hello.txt".to_owned(),
                xattrs: Xattrs::default(),
            };
            let stored = framed(&header, 0, b"");
            let (parsed, _declared, _raw, mut rest) =
                read_archive_header(Cursor::new(stored)).await.unwrap();
            assert!(parsed.is_symlink());
            assert_eq!(parsed.symlink_target, "hello.txt");
            let mut payload = Vec::new();
            rest.read_to_end(&mut payload).await.unwrap();
            assert!(payload.is_empty());
        });
    }

    /// The four bytes after the length are padding and must be zero: anything
    /// else is not the framing this reader is looking at.
    #[test]
    fn nonzero_framing_padding_is_rejected() {
        block_on(async {
            let mut stored = framed(&regular_header(), 0, b"");
            stored[5] = 1;
            let err = read_archive_header(Cursor::new(stored)).await.unwrap_err();
            assert!(err.to_string().contains("padding"), "{err}");
        });
    }

    /// A stream that ends inside the framing is a truncated object, not an empty
    /// one.
    #[test]
    fn a_truncated_stream_fails_rather_than_ending() {
        block_on(async {
            let stored = framed(&regular_header(), 0, b"");
            for cut in [4, 8, stored.len() - 1] {
                let err = read_archive_header(Cursor::new(stored[..cut].to_vec()))
                    .await
                    .unwrap_err();
                assert!(matches!(err, Error::Io(_)), "cut at {cut}: {err}");
            }
        });
    }

    /// A stream that never ends. Past a small budget it fails, so a check that
    /// reads for an end fails this test rather than running until the process
    /// runs out of memory.
    struct Endless {
        handed_out: usize,
    }

    impl AsyncRead for Endless {
        fn poll_read(
            mut self: Pin<&mut Self>,
            _cx: &mut Context<'_>,
            buf: &mut [u8],
        ) -> Poll<std::io::Result<usize>> {
            if self.handed_out >= 4096 {
                return Poll::Ready(Err(std::io::Error::other("the check read past the header")));
            }
            buf.fill(0);
            self.handed_out += buf.len();
            Poll::Ready(Ok(buf.len()))
        }
    }

    /// A symlink whose stored form carries a payload is refused, and the refusal
    /// reads one byte of it: the length the remote chose to send is not held.
    #[test]
    fn a_symlink_payload_is_refused_without_reading_it() {
        block_on(async {
            let mut stream = Endless { handed_out: 0 };
            let err = check_stream_end(&csum(1), "symlink header", &mut stream)
                .await
                .unwrap_err();
            assert!(err.to_string().contains("bytes follow"), "{err}");
            assert_eq!(stream.handed_out, 1);
        });
    }

    /// The decoder stops at the end of the DEFLATE stream without reading what
    /// follows it, so the end-of-stream check runs over the decoder's input
    /// buffer: a payload that ends the stream ends the check, and trailing bytes
    /// the decoder never consumed are refused.
    #[test]
    fn the_check_sees_what_the_decoder_left_behind() {
        block_on(async {
            let mut encoder = DeflateEncoder::new(Cursor::new(b"hello ostree\n".to_vec()));
            let mut compressed = Vec::new();
            encoder.read_to_end(&mut compressed).await.unwrap();

            for (trailing, expect_end) in [(&b""[..], true), (b"junk", false)] {
                let mut stored = compressed.clone();
                stored.extend_from_slice(trailing);
                let mut decoder = DeflateDecoder::new(BufSource::new(Cursor::new(stored)));
                let mut out = Vec::new();
                copy_bounded(&mut decoder, &mut out, &mut Vec::new(), &csum(1), 13)
                    .await
                    .unwrap();
                assert_eq!(out, b"hello ostree\n");
                let result =
                    check_stream_end(&csum(1), "deflated payload", decoder.into_inner()).await;
                assert_eq!(
                    result.is_ok(),
                    expect_end,
                    "trailing {trailing:?}: {result:?}"
                );
            }
        });
    }

    /// A payload that decompresses past the size its header declares is refused,
    /// and the refusal reads one byte past the declaration rather than the rest
    /// of a stream that never ends.
    #[test]
    fn a_payload_outgrowing_its_declared_size_is_refused() {
        block_on(async {
            let mut stream = Endless { handed_out: 0 };
            let mut out = Vec::new();
            let err = copy_bounded(&mut stream, &mut out, &mut Vec::new(), &csum(1), 4)
                .await
                .unwrap_err();
            assert!(err.to_string().contains("outgrew the 4 byte"), "{err}");
            assert_eq!(stream.handed_out, 5);
        });
    }

    /// A stream of empty non-final DEFLATE blocks: five bytes that decompress to
    /// nothing, repeated. Past a budget well above the bound under test it fails,
    /// so a compressed stream nothing bounds fails this test rather than running
    /// until the process runs out of memory.
    struct EmptyBlocks {
        handed_out: usize,
    }

    impl AsyncRead for EmptyBlocks {
        fn poll_read(
            mut self: Pin<&mut Self>,
            _cx: &mut Context<'_>,
            buf: &mut [u8],
        ) -> Poll<std::io::Result<usize>> {
            const BLOCK: [u8; 5] = [0x00, 0x00, 0x00, 0xff, 0xff];
            if self.handed_out >= 1024 * 1024 {
                return Poll::Ready(Err(std::io::Error::other(
                    "the payload read past its compressed bound",
                )));
            }
            let base = self.handed_out;
            for (i, byte) in buf.iter_mut().enumerate() {
                *byte = BLOCK[(base + i) % BLOCK.len()];
            }
            self.handed_out += buf.len();
            Poll::Ready(Ok(buf.len()))
        }
    }

    /// A payload that decompresses to nothing for as long as it is sent is refused
    /// against the bound its declared size sets, since the decompressed bound never
    /// trips against it. The refusal reaches the caller as the refusal it is, and
    /// what the stream delivered is the bound plus the one read that tripped it.
    #[test]
    fn a_compressed_payload_passing_its_bound_is_refused() {
        block_on(async {
            let mut source = EmptyBlocks { handed_out: 0 };
            let mut out = Vec::new();
            let bound = compressed_bound(13);
            let err = {
                let source = BoundedInput::new(&mut source, csum(1), bound);
                let mut payload = DeflateDecoder::new(BufSource::new(source));
                copy_bounded(&mut payload, &mut out, &mut Vec::new(), &csum(1), 13)
                    .await
                    .unwrap_err()
            };
            let err = payload_refusal(err);
            assert!(matches!(err, Error::InvalidFormat(_)), "{err}");
            assert!(
                err.to_string()
                    .contains(&format!("passed the {bound} byte")),
                "{err}"
            );
            assert!(out.is_empty());
            assert!(
                source.handed_out <= bound as usize + 16 * 1024,
                "{} bytes taken for a {bound}-byte bound",
                source.handed_out
            );
        });
    }

    /// The bound refuses no object of the size it is stated for: data a compressor
    /// cannot shrink is the worst case, and its compressed form sits inside the
    /// bound its uncompressed size sets.
    #[test]
    fn the_compressed_bound_holds_incompressible_data() {
        block_on(async {
            // A linear congruential sequence, which deflate cannot shrink.
            let mut state = 1u32;
            let data: Vec<u8> = (0..200_000)
                .map(|_| {
                    state = state.wrapping_mul(1_664_525).wrapping_add(1_013_904_223);
                    (state >> 24) as u8
                })
                .collect();
            let mut encoder = DeflateEncoder::new(Cursor::new(data.clone()));
            let mut compressed = Vec::new();
            encoder.read_to_end(&mut compressed).await.unwrap();
            let declared = data.len() as u64;
            let bound = compressed_bound(declared);
            assert!(
                compressed.len() as u64 <= bound,
                "{} compressed bytes for a {bound}-byte bound",
                compressed.len()
            );

            let source = BoundedInput::new(Cursor::new(compressed), csum(1), bound);
            let mut payload = DeflateDecoder::new(BufSource::new(source));
            let mut out = Vec::new();
            copy_bounded(&mut payload, &mut out, &mut Vec::new(), &csum(1), declared)
                .await
                .unwrap();
            assert_eq!(out, data);
        });
    }

    /// The declaration is a ceiling, not an equality: a payload that reaches it
    /// is stored whole, and a shorter one is left to the checksum comparison.
    #[test]
    fn a_payload_within_its_declared_size_is_stored() {
        block_on(async {
            // One buffer serves both objects, the way a slot's does.
            let mut buf = Vec::new();
            for payload in [&b"four"[..], b"two"] {
                let mut out = Vec::new();
                copy_bounded(
                    Cursor::new(payload.to_vec()),
                    &mut out,
                    &mut buf,
                    &csum(1),
                    4,
                )
                .await
                .unwrap();
                assert_eq!(out, payload);
            }
            // The buffer the first object grew is the one the second read
            // through, and it is the slot's read chunk.
            assert_eq!(buf.len(), READ_CHUNK);
        });
    }

    /// A declared header length past the header cap is refused before the buffer
    /// for it is allocated, so a remote directs at most that cap for each fetch
    /// in flight. The first byte past the cap is refused, as is the largest
    /// length the four-byte field holds.
    #[test]
    fn an_oversized_header_length_is_refused() {
        block_on(async {
            for header_len in [MAX_FILE_HEADER_SIZE as u32 + 1, u32::MAX] {
                let mut stored = Vec::new();
                stored.extend_from_slice(&header_len.to_be_bytes());
                stored.extend_from_slice(&[0u8; 4]);
                let err = read_archive_header(Cursor::new(stored)).await.unwrap_err();
                assert!(err.to_string().contains("size cap"), "{header_len}: {err}");
            }
        });
    }

    /// A ref name reaches the wire encoded: its `/` separators stand, and every
    /// character that would name something else does not.
    #[test]
    fn a_ref_request_path_encodes_the_name() {
        assert_eq!(ref_request_path("test/main"), "refs/heads/test/main");
        // The unreserved set passes through as itself.
        assert_eq!(ref_request_path("a-b.c_d~e"), "refs/heads/a-b.c_d~e");
        // A query, a fragment, and an escape name the ref, not a request target.
        assert_eq!(ref_request_path("a?b"), "refs/heads/a%3Fb");
        assert_eq!(ref_request_path("a#b"), "refs/heads/a%23b");
        assert_eq!(ref_request_path("a%2fb"), "refs/heads/a%252fb");
        // A space and a CRLF are bytes of the name.
        assert_eq!(ref_request_path("a b\r\n"), "refs/heads/a%20b%0D%0A");
        // A non-ASCII name is encoded as its UTF-8 bytes.
        assert_eq!(ref_request_path("é"), "refs/heads/%C3%A9");
    }

    // --- the plan ---------------------------------------------------------

    fn csum(byte: u8) -> Checksum {
        Checksum::from_bytes([byte; 32])
    }

    fn object(byte: u8, ty: ObjectType) -> ObjectName {
        ObjectName::new(csum(byte), ty)
    }

    /// The outcome of a commit that was fetched and holds `tree`.
    fn fetched(checksum: Checksum, tree: Vec<ObjectName>, parent: Option<Checksum>) -> Step {
        Step::Commit(CommitOutcome {
            checksum,
            next: CommitNext::Scan(tree),
            parent,
            marked: true,
        })
    }

    /// The outcome of a commit a delta delivers.
    fn by_delta(
        checksum: Checksum,
        parts: usize,
        fallbacks: Vec<ObjectName>,
        tree: Vec<ObjectName>,
    ) -> Step {
        Step::Commit(CommitOutcome {
            checksum,
            next: CommitNext::Delta {
                parts,
                fallbacks,
                tree,
            },
            parent: None,
            marked: true,
        })
    }

    /// Drain the plan by applying a stored outcome for each queued object, whose
    /// dirtrees reference nothing further.
    fn drain(plan: &mut Plan, marked: &mut Vec<Checksum>) {
        while let Some(item) = plan.next() {
            let step = match item {
                Item::Object(name) if name.ty == ObjectType::DirTree => Step::DirTree(Vec::new()),
                Item::Object(_) => Step::Done,
                Item::Part(part) => Step::Part(part.commit),
                Item::Commit(_) => panic!("the test queues no further commits"),
            };
            plan.apply(step, marked);
        }
    }

    /// A commit queues the objects it references, and reports that this pull
    /// marked it partial.
    #[test]
    fn a_commit_queues_the_objects_it_references() {
        let mut plan = Plan::default();
        let mut marked = Vec::new();
        plan.push_commit(CommitItem {
            checksum: csum(1),
            depth: 0,
            optional: false,
        });
        assert!(matches!(plan.next(), Some(Item::Commit(_))));
        plan.apply(
            fetched(
                csum(1),
                vec![
                    object(2, ObjectType::DirMeta),
                    object(3, ObjectType::DirTree),
                ],
                None,
            ),
            &mut marked,
        );
        assert_eq!(plan.scan.len(), 2);
        drain(&mut plan, &mut marked);
        assert!(plan.next().is_none());
        assert_eq!(marked, [csum(1)]);
    }

    /// An object several commits reach is queued once, whether the others reach
    /// it while it is still queued or after it was fetched.
    #[test]
    fn an_object_several_commits_reach_is_queued_once() {
        let mut plan = Plan::default();
        let mut marked = Vec::new();
        let shared = object(9, ObjectType::DirMeta);
        for byte in [1u8, 2] {
            plan.apply(fetched(csum(byte), vec![shared], None), &mut marked);
        }
        assert_eq!(plan.scan.len(), 1);
        drain(&mut plan, &mut marked);
        plan.apply(fetched(csum(3), vec![shared], None), &mut marked);
        assert!(plan.next().is_none());
    }

    /// A commit reached again with further to go is not fetched again: the walk
    /// resumes at the parent it named.
    #[test]
    fn a_commit_reached_deeper_resumes_at_its_parent() {
        let mut plan = Plan::default();
        let mut marked = Vec::new();
        let tip = CommitItem {
            checksum: csum(1),
            depth: 0,
            optional: false,
        };
        plan.push_commit(tip);
        assert!(matches!(plan.next(), Some(Item::Commit(_))));
        // Its parent is recorded, but depth 0 followed none of it.
        plan.apply(fetched(csum(1), Vec::new(), Some(csum(2))), &mut marked);
        assert!(plan.next().is_none());

        // A second ref reaches the same commit with one parent to follow.
        plan.push_commit(CommitItem {
            checksum: csum(1),
            depth: 1,
            optional: false,
        });
        let Some(Item::Commit(next)) = plan.next() else {
            panic!("the parent was not queued");
        };
        assert_eq!(next.checksum, csum(2));
        assert_eq!(next.depth, 0);
        assert!(next.optional);
        assert!(plan.next().is_none());
    }

    /// The drain order is the fetch order the pull relies on: the commits, then
    /// the objects the scan is blocked on, then the content.
    #[test]
    fn the_plan_drains_commits_then_scan_then_content() {
        let mut plan = Plan::default();
        let mut marked = Vec::new();
        plan.apply(
            fetched(
                csum(1),
                vec![
                    object(4, ObjectType::File),
                    object(2, ObjectType::DirMeta),
                    object(3, ObjectType::DirTree),
                ],
                None,
            ),
            &mut marked,
        );
        plan.push_commit(CommitItem {
            checksum: csum(5),
            depth: 0,
            optional: false,
        });
        let mut drained = Vec::new();
        while let Some(item) = plan.next() {
            drained.push(match item {
                Item::Commit(commit) => commit.checksum,
                Item::Object(name) => name.checksum,
                Item::Part(part) => part.commit,
            });
        }
        assert_eq!(drained, [csum(5), csum(2), csum(3), csum(4)]);
    }

    /// A delta queues its parts and the objects it hands over loose, and the
    /// commit's tree walk waits for the last part.
    #[test]
    fn a_delta_queues_its_parts_before_the_tree() {
        let mut plan = Plan::default();
        let mut marked = Vec::new();
        let fallback = object(7, ObjectType::File);
        let tree = vec![
            object(2, ObjectType::DirMeta),
            object(3, ObjectType::DirTree),
        ];
        plan.apply(by_delta(csum(1), 2, vec![fallback], tree), &mut marked);

        // The parts come before the fallback, which is content.
        assert!(matches!(plan.next(), Some(Item::Part(_))));
        assert!(matches!(plan.next(), Some(Item::Part(_))));
        let Some(Item::Object(name)) = plan.next() else {
            panic!("the fallback was not queued");
        };
        assert_eq!(name, fallback);
        // The tree is not queued while a part is outstanding.
        assert!(plan.next().is_none());

        plan.apply(Step::Part(csum(1)), &mut marked);
        assert!(plan.next().is_none());
        plan.apply(Step::Part(csum(1)), &mut marked);
        let Some(Item::Object(name)) = plan.next() else {
            panic!("the tree was not queued after the last part");
        };
        assert_eq!(name, object(2, ObjectType::DirMeta));
    }

    /// No more than [`PART_CAP`] parts are handed out at once, however many the
    /// delta has and however many slots the pull holds.
    #[test]
    fn the_part_cap_holds_however_many_parts_a_delta_has() {
        let mut plan = Plan::default();
        let mut marked = Vec::new();
        plan.apply(by_delta(csum(1), 5, Vec::new(), Vec::new()), &mut marked);

        let mut in_flight = 0;
        let mut high_water = 0;
        let mut applied = 0;
        loop {
            while let Some(item) = plan.next() {
                assert!(matches!(item, Item::Part(_)));
                in_flight += 1;
                high_water = high_water.max(in_flight);
            }
            if in_flight == 0 {
                break;
            }
            plan.apply(Step::Part(csum(1)), &mut marked);
            in_flight -= 1;
            applied += 1;
        }
        assert_eq!(high_water, PART_CAP);
        assert_eq!(applied, 5);
    }

    /// A remote setting `tls-permissive` maps onto the bypass that holds the
    /// host name check, and the `tls-ca-path` alongside it is never opened:
    /// the path here names no file, so reading it would fail the call.
    #[test]
    fn tls_permissive_leaves_the_ca_path_unread() {
        let cfg = RepoConfig::parse(
            "[core]\nrepo_version=1\nmode=archive-z2\n\
             [remote \"origin\"]\nurl=https://example.invalid/repo\n\
             tls-permissive=true\ntls-ca-path=/nonexistent/ca.pem\n",
        )
        .unwrap();
        let section = cfg.remote("origin").unwrap();
        let tls = block_on(remote_tls("origin", &section)).unwrap();
        assert_eq!(tls.roots, TrustRoots::DangerousAcceptAnyChain);
        assert!(tls.client_identity.is_none());
    }

    /// A delta whose objects all went to fallbacks has no part to wait for, so
    /// its tree walk is queued at once.
    #[test]
    fn a_delta_with_no_parts_queues_its_tree_at_once() {
        let mut plan = Plan::default();
        let mut marked = Vec::new();
        plan.apply(
            by_delta(
                csum(1),
                0,
                vec![object(7, ObjectType::File)],
                vec![object(2, ObjectType::DirMeta)],
            ),
            &mut marked,
        );
        assert_eq!(plan.scan.len(), 1);
        assert_eq!(plan.content.len(), 1);
        assert!(plan.parts.is_empty());
    }
}