ostrya 0.4.0

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
2271
2272
2273
2274
2275
2276
2277
2278
2279
2280
2281
2282
2283
2284
2285
2286
2287
2288
2289
2290
2291
2292
2293
2294
2295
2296
2297
2298
2299
2300
2301
2302
2303
2304
2305
2306
2307
2308
2309
2310
2311
2312
2313
2314
2315
2316
2317
2318
2319
2320
2321
2322
2323
2324
2325
2326
2327
2328
2329
2330
2331
2332
2333
2334
2335
2336
2337
2338
2339
2340
2341
2342
2343
2344
2345
2346
2347
2348
2349
2350
2351
2352
2353
2354
2355
2356
2357
2358
2359
2360
2361
2362
2363
2364
2365
2366
2367
2368
2369
2370
2371
2372
2373
2374
2375
2376
2377
2378
2379
2380
2381
2382
2383
2384
2385
2386
2387
2388
2389
2390
2391
2392
2393
2394
2395
2396
2397
2398
2399
2400
2401
2402
2403
2404
2405
2406
2407
2408
2409
2410
2411
2412
2413
2414
2415
2416
2417
2418
2419
2420
2421
2422
2423
2424
2425
2426
2427
2428
2429
2430
2431
2432
2433
2434
2435
2436
2437
2438
2439
2440
2441
2442
2443
2444
2445
2446
2447
2448
2449
2450
2451
2452
2453
2454
2455
2456
2457
2458
2459
2460
2461
2462
2463
2464
2465
2466
2467
2468
2469
2470
2471
2472
2473
2474
2475
2476
2477
2478
2479
2480
2481
2482
2483
2484
2485
2486
2487
2488
2489
2490
2491
2492
2493
2494
2495
2496
2497
2498
2499
2500
2501
2502
2503
2504
2505
2506
2507
2508
2509
2510
2511
2512
2513
2514
2515
2516
2517
2518
2519
2520
2521
2522
2523
2524
2525
2526
2527
2528
2529
2530
2531
2532
2533
2534
2535
2536
2537
2538
2539
2540
2541
2542
2543
2544
2545
2546
2547
2548
2549
2550
2551
2552
2553
2554
2555
2556
2557
2558
2559
2560
2561
2562
2563
2564
2565
2566
2567
2568
2569
2570
2571
2572
2573
2574
2575
2576
2577
2578
2579
2580
2581
2582
2583
2584
2585
2586
2587
2588
2589
2590
2591
2592
2593
2594
2595
2596
2597
2598
2599
2600
2601
2602
2603
2604
2605
2606
2607
2608
2609
2610
2611
2612
2613
2614
2615
2616
2617
2618
2619
2620
2621
2622
2623
2624
2625
2626
2627
2628
2629
2630
2631
2632
2633
2634
2635
2636
2637
2638
2639
2640
2641
2642
2643
2644
2645
2646
2647
2648
2649
2650
2651
2652
2653
2654
2655
2656
2657
2658
2659
2660
2661
2662
2663
2664
2665
2666
2667
2668
2669
2670
2671
2672
2673
2674
2675
2676
2677
2678
2679
2680
2681
2682
2683
2684
2685
2686
2687
2688
2689
2690
2691
2692
2693
2694
2695
2696
2697
2698
2699
2700
2701
2702
2703
2704
2705
2706
2707
2708
2709
2710
2711
2712
2713
2714
2715
2716
2717
2718
2719
2720
2721
2722
2723
2724
2725
2726
2727
2728
2729
2730
2731
2732
2733
2734
2735
2736
2737
2738
2739
2740
2741
2742
2743
2744
2745
2746
2747
2748
2749
2750
2751
2752
2753
2754
2755
2756
2757
2758
2759
2760
2761
2762
2763
2764
2765
2766
2767
2768
2769
2770
2771
2772
2773
2774
2775
2776
2777
2778
2779
2780
2781
2782
2783
2784
2785
2786
2787
2788
2789
2790
2791
2792
2793
2794
2795
2796
2797
2798
2799
2800
2801
2802
2803
2804
2805
2806
2807
2808
2809
2810
2811
2812
2813
2814
2815
2816
2817
2818
2819
2820
2821
2822
2823
2824
2825
2826
2827
2828
2829
2830
2831
2832
2833
2834
2835
2836
2837
2838
2839
2840
2841
2842
2843
2844
2845
2846
2847
2848
2849
2850
2851
2852
2853
2854
2855
2856
2857
2858
2859
2860
2861
2862
2863
2864
2865
2866
2867
2868
2869
2870
2871
2872
2873
2874
2875
2876
2877
2878
2879
2880
2881
2882
2883
2884
2885
2886
2887
2888
2889
2890
2891
2892
2893
2894
2895
2896
2897
2898
2899
2900
2901
2902
2903
2904
2905
2906
2907
2908
2909
2910
2911
2912
2913
2914
2915
2916
2917
2918
2919
2920
2921
2922
2923
2924
2925
2926
2927
2928
2929
2930
2931
2932
2933
2934
2935
2936
2937
2938
2939
2940
2941
2942
2943
2944
2945
2946
2947
2948
2949
2950
2951
2952
2953
2954
2955
2956
2957
2958
2959
2960
2961
2962
2963
2964
2965
2966
2967
2968
2969
2970
2971
2972
2973
2974
2975
2976
2977
2978
2979
2980
2981
2982
2983
2984
2985
2986
2987
2988
2989
2990
2991
2992
2993
2994
2995
2996
2997
2998
2999
3000
3001
3002
3003
3004
3005
3006
3007
3008
3009
3010
3011
3012
3013
3014
3015
3016
3017
3018
3019
3020
3021
3022
3023
3024
3025
3026
3027
3028
3029
3030
3031
3032
3033
3034
3035
3036
3037
3038
3039
3040
3041
3042
3043
3044
3045
3046
3047
3048
3049
3050
3051
3052
3053
3054
3055
3056
3057
3058
3059
3060
3061
3062
3063
3064
3065
3066
3067
3068
3069
3070
3071
3072
3073
3074
3075
3076
3077
3078
3079
3080
3081
3082
3083
3084
3085
3086
3087
3088
3089
3090
3091
3092
3093
3094
3095
3096
3097
3098
3099
3100
3101
3102
3103
3104
3105
3106
3107
3108
3109
3110
3111
3112
3113
3114
3115
3116
3117
3118
3119
3120
3121
3122
3123
3124
3125
3126
3127
3128
3129
3130
3131
3132
3133
3134
3135
3136
3137
3138
3139
3140
3141
3142
3143
3144
3145
3146
3147
3148
3149
3150
3151
3152
3153
3154
3155
3156
3157
3158
3159
3160
3161
3162
3163
3164
3165
3166
3167
3168
3169
3170
3171
3172
3173
3174
3175
3176
3177
3178
3179
3180
3181
3182
3183
3184
3185
3186
3187
3188
3189
3190
3191
3192
3193
3194
3195
3196
3197
3198
3199
3200
3201
3202
3203
3204
3205
3206
3207
3208
3209
3210
3211
3212
3213
3214
3215
3216
3217
3218
3219
3220
3221
3222
3223
3224
3225
3226
3227
3228
3229
3230
3231
3232
3233
3234
3235
3236
3237
3238
3239
3240
3241
3242
3243
3244
3245
3246
3247
3248
3249
3250
3251
3252
3253
3254
3255
3256
3257
3258
3259
3260
3261
3262
3263
3264
3265
3266
3267
3268
3269
3270
3271
3272
3273
3274
3275
3276
3277
3278
3279
3280
3281
3282
3283
3284
3285
3286
3287
3288
3289
3290
3291
3292
3293
3294
3295
3296
3297
3298
3299
3300
3301
3302
3303
3304
3305
3306
3307
3308
3309
3310
3311
3312
3313
3314
3315
3316
3317
3318
3319
3320
3321
3322
3323
3324
3325
3326
3327
3328
3329
3330
3331
3332
3333
3334
3335
3336
3337
3338
3339
3340
3341
3342
3343
3344
3345
3346
3347
3348
3349
3350
3351
3352
3353
3354
3355
3356
3357
3358
3359
3360
3361
3362
3363
3364
3365
3366
3367
3368
3369
3370
3371
3372
3373
3374
3375
3376
3377
3378
3379
3380
3381
3382
3383
3384
3385
3386
3387
3388
3389
3390
3391
3392
3393
3394
3395
3396
3397
3398
3399
3400
3401
3402
3403
3404
3405
3406
3407
3408
3409
3410
3411
3412
3413
3414
3415
3416
3417
3418
3419
3420
3421
3422
3423
3424
3425
3426
3427
3428
3429
3430
3431
3432
3433
3434
3435
3436
3437
3438
3439
3440
3441
3442
3443
3444
3445
3446
3447
3448
3449
3450
3451
3452
3453
3454
3455
3456
3457
3458
3459
3460
3461
3462
3463
3464
3465
3466
3467
3468
3469
3470
3471
3472
3473
3474
3475
3476
3477
3478
3479
3480
3481
3482
3483
3484
3485
3486
3487
3488
3489
3490
3491
3492
3493
3494
3495
3496
3497
3498
3499
3500
3501
3502
3503
3504
3505
3506
3507
3508
3509
3510
3511
3512
3513
3514
3515
3516
3517
3518
3519
3520
3521
3522
3523
3524
3525
3526
3527
3528
3529
3530
3531
3532
3533
3534
3535
3536
3537
3538
3539
3540
3541
3542
3543
3544
3545
3546
3547
3548
3549
3550
3551
3552
3553
3554
3555
3556
3557
3558
3559
3560
3561
3562
3563
3564
3565
3566
3567
3568
3569
3570
3571
3572
3573
3574
3575
3576
3577
3578
3579
3580
3581
3582
3583
3584
3585
3586
3587
3588
3589
3590
3591
3592
3593
3594
3595
3596
3597
3598
3599
3600
3601
3602
3603
3604
3605
3606
3607
3608
3609
3610
3611
3612
3613
3614
3615
3616
3617
3618
3619
3620
3621
3622
3623
3624
3625
3626
3627
3628
3629
3630
3631
3632
3633
3634
3635
3636
3637
3638
3639
3640
3641
3642
3643
3644
3645
3646
3647
3648
3649
3650
3651
3652
3653
3654
3655
3656
3657
3658
3659
3660
3661
3662
3663
3664
3665
3666
3667
3668
3669
3670
3671
3672
3673
3674
3675
3676
3677
3678
3679
3680
3681
3682
3683
3684
3685
3686
3687
3688
3689
3690
3691
3692
3693
3694
3695
3696
3697
3698
//! The pull from a remote, over HTTP or over ssh.
//!
//! [`Repo::pull`], [`Repo::pull_with_session`], and
//! [`Repo::remote_fetch_summary`] are the entry points. [`Repo::pull`] holds
//! the rules of the pull. [`Repo::pull`] and [`Repo::pull_with_session`] run
//! one engine.
//!
//! The loop that drives the steps owns the plan, so the plan needs no lock.
//! The pull spawns no task: the step futures borrow the repository, the
//! transaction, and the fetcher. The walk of a subpath pull obeys the rules in
//! `subpath`.
//!
//! The plan walks a dirtree when it applies the step of the dirtree, under
//! each position that reached the dirtree by then. If a later position widens
//! that scope, the plan walks the dirtree again from the transaction.
//!
//! With a list of static deltas, the loop runs the plan one time for each
//! level of intermediate commits, and then one time for the targets, in one
//! transaction. Each run starts from the objects that the earlier runs
//! queued.

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

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::delta::IO_CHUNK;
use crate::endpoint::{EndpointOverrides, resolve_pull};
use crate::error::{Error, Result};
use crate::fetch::gate::Gate;
use crate::fetch::{FetchRequest, Fetched, Fetcher, Priority};
use crate::inflate::BufSource;
use crate::object::{MAX_FILE_HEADER_SIZE, MAX_METADATA_SIZE};
use crate::read::CommitState;
use crate::remote::{Endpoint, PullSession, StreamSessionOptions};
use crate::repo::Repo;
use crate::summary::{
    SUMMARY_FILE, SUMMARY_SIG_FILE, Summary, put_root_file_blocking,
    remove_anonymous_access_blocking,
};
use crate::transaction::Transaction;
use crate::traverse::reaches_at_least;
use crate::verify::PullTrust;
use crate::write::FileMeta;

use super::chain::Edges;
use super::delta::{self, CommitCheck, DeltaJob, DeltaPlan, DeltaSource, PART_CAP};
use super::drive::Slots;
use super::source::{RemoteSource, RootFiles, Transfer, http_error, session_error};
use super::subpath::{Scope, Subpaths};
use super::verify::Verification;
use super::{
    CheckedMeta, DetachedMetadataFilter, ModeChecks, PullCounters, PullFlags, PullOptions,
    PullStats, PullVerify, READ_CHUNK, RefPlace, TimestampBase, TipChecks, apply_durability,
    check_commit_signatures_filtered, check_depth, check_remote_option, check_static_deltas,
    check_tip_refs, refuse_remote_collection, take_static_deltas,
};

/// The number of fetched content objects that stream into the object store at
/// once.
const WRITE_THROTTLE: usize = 3;

/// The cap on the repository-root files that a pull fetches (`summary`,
/// `summary.sig`, `config`). The local summary reader applies the same cap.
pub(super) 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 name of the config file at the repository root.
pub(super) const CONFIG_FILE: &str = "config";

/// Methods that pull from a remote over HTTP or ssh.
impl Repo {
    /// Pulls refs and their objects from a remote over HTTP or over ssh.
    ///
    /// `remote` names a `[remote "<name>"]` section of the config of this
    /// repository. The section gives the signature policy and the `branches`
    /// key. By default, the name gives the prefix of the written refs.
    /// [`remote`](PullOptions::remote) and [`MIRROR`](PullFlags::MIRROR)
    /// change this. The section also gives the address, the TLS material, and
    /// the proxy, and [`overrides`](PullOptions::overrides) changes them. The
    /// pull fetches the objects into one transaction, publishes them, and then
    /// writes the refs. It returns the statistics of the pull.
    ///
    /// The module [`pull`](mod@crate::pull) states the rules of the
    /// `.commitpartial` markers. It also states the concurrency, the write
    /// permits, the memory, the connections, and the retries of this pull.
    ///
    /// [`pull_local`](Repo::pull_local) states the write order of the detached
    /// metadata and the mode checks of a content object. These rules apply to
    /// this pull too.
    ///
    /// [`PullOptions`] states which fields each pull reads, and
    /// [`PullVerify`] holds the signature policy.
    ///
    /// # Address
    ///
    /// The pull calls [`resolve_pull`] with
    /// [`overrides`](PullOptions::overrides), and reads the remote at the
    /// endpoint that it returns. `resolve_pull` reads the address from
    /// [`EndpointOverrides::url`], or else from the remote key `pull-url` or
    /// `url`, and states the rules of the address.
    ///
    /// An [`Endpoint::Http`] gives an HTTP pull through the fetcher, and an
    /// [`Endpoint::Ssh`] gives a pull over ssh. The fetcher gets each mirror
    /// as written, and it refuses a scheme other than `http` and `https`.
    ///
    /// The pull reads the trust of the remote with
    /// [`PullTrust::from_remote`] before it opens the session. So a refused
    /// policy starts no fetcher and no ssh client. Then the pull runs as
    /// [`pull_with_session`](Repo::pull_with_session) with that session and
    /// that trust, with the `branches` key and the summary copy of this
    /// method.
    ///
    /// # Refs
    ///
    /// The pull resolves each requested ref against the summary of the remote.
    /// If the summary does not list the ref, or the remote serves no summary,
    /// the pull reads `refs/heads/<ref>` of the remote.
    /// [`refs`](PullOptions::refs) states what an empty list takes.
    ///
    /// [`remote`](PullOptions::remote) and [`MIRROR`](PullFlags::MIRROR)
    /// select the prefix of the written refs.
    /// [`no_ref_writes`](PullOptions::no_ref_writes) turns the ref writes off.
    ///
    /// # Proxy
    ///
    /// An HTTP pull connects through the proxy of the endpoint.
    /// [`resolve_pull`] reads it from the
    /// remote key `proxy`. With the `http://` proxy URL of that key, the pull
    /// connects through the proxy for every origin, and ignores `no_proxy`. If
    /// the key is absent or empty, the pull reads the proxy environment
    /// variables.
    ///
    /// # Pull over ssh
    ///
    /// For an ssh endpoint, the pull runs the ssh client after it resolves the
    /// signature policy. The [`SshOptions`](crate::remote::SshOptions) of the
    /// endpoint give the commands of the client, by the rules of
    /// [`StreamSession::connect`](crate::remote::StreamSession::connect).
    ///
    /// `resolve_pull` reads no remote key that applies to HTTP alone for an
    /// ssh address: `contenturl`, `metalink`, `proxy`, and the `tls-*` keys.
    /// For an HTTP address, it reads neither `ssh-command` nor
    /// `send-command`.
    ///
    /// The pull reads the remote through a source: the HTTP source over the
    /// fetcher, or the stream source over a stream session.
    /// [`PullSession::over_stream`] opens a stream session over a pair of
    /// streams, for [`pull_with_session`](Repo::pull_with_session). The two
    /// sources serve the same paths under the same caps. Each rule of this
    /// method applies to both sources, with these differences:
    ///
    /// - The stream source requests a ref by its name as written, with no
    ///   percent-encoding.
    /// - The stream source never sends a request again. A failure ends its
    ///   session and the pull.
    /// - The stream source keeps the requests of `summary.sig`, `summary`, and
    ///   `config` in flight together, in the order of the HTTP source. It does
    ///   the same for a `.commitmeta` and its commit, so a parent commit costs
    ///   one round trip. It also does the same for the superblock of a step of
    ///   a [`static_deltas`](PullOptions::static_deltas) chain and the
    ///   `.commitmeta` of the commit of the step, the superblock first, as
    ///   `# Static deltas` states. The HTTP source sends these requests one at
    ///   a time.
    /// - The stream source ends its session before the transaction commits.
    ///   It closes the input of the server and, over ssh, waits for the ssh
    ///   client.
    ///
    /// # Requests
    ///
    /// The pull first requests `summary.sig`, `summary`, and `config`, in this
    /// order, and then the objects. A remote with no summary answers 404. The
    /// HTTP source percent-encodes each byte of a ref name outside the
    /// unreserved set of RFC 3986, except `/`.
    ///
    /// The remote must be an `archive` repository. The pull requests each
    /// content object as `objects/<..>.filez`, whatever the remote stores on
    /// its disk. That is the one form of a content object that an HTTP client
    /// can read: the framed, deflated payload behind its header.
    ///
    /// The pull reads `config` before the first object request. If `config`
    /// states a different mode, the pull fails. If the remote serves no
    /// `config`, the pull reads the remote as `archive`.
    ///
    /// # Commits
    ///
    /// The pull fetches a commit object before the objects that it references,
    /// because its tree is unknown until it arrives. The pull stages the commit
    /// when it arrives, so the verification of its name fails a wrong commit
    /// before the request of its tree. Nothing of the commit stays in memory
    /// after the step.
    ///
    /// The step that fetches a commit writes its `.commitpartial` marker. The
    /// module [`pull`](mod@crate::pull) states the rules of the markers.
    ///
    /// The pull fetches each object once, also if several commits reach it.
    /// The step that fetches a commit makes the ref-binding check and the
    /// timestamp check of each requested ref that names the commit. So two
    /// refs at one commit get both checks. For a commit of a chain of a
    /// [`static_deltas`](PullOptions::static_deltas) list, discovery makes
    /// these checks before the transaction opens, as `# Static deltas`
    /// states.
    ///
    /// The pull queues no object of the tree of a commit that this repository
    /// holds complete. It follows the parent of that commit all the same, so a
    /// pull extends the history that a shallower pull left.
    ///
    /// # Detached metadata
    ///
    /// The pull requests the `.commitmeta` of a commit before the commit
    /// object. It stages the `.commitmeta` in the transaction when the commit
    /// object arrives, so no `.commitmeta` stays for a parent that the remote
    /// answers 404 for. [`pull_local`](Repo::pull_local) states when the
    /// transaction writes it and what a failure leaves.
    ///
    /// # Verification
    ///
    /// The pull stores each fetched object under the name that it requested.
    /// The write path hashes what it stores and compares the result with that
    /// name. So a corrupt or substituted object fails the pull, and the pull
    /// publishes nothing. No flag turns this verification off, so the pull
    /// ignores [`UNTRUSTED`](PullFlags::UNTRUSTED).
    ///
    /// The pull makes the mode checks of
    /// [`BAREUSERONLY_FILES`](PullFlags::BAREUSERONLY_FILES) and of a
    /// `bare-user-only` destination over the header of a content object.
    ///
    /// The header also declares the size of the decompressed payload. This
    /// size bounds the stream on both sides:
    ///
    /// - A payload larger than the declared size fails the pull. So a corrupt
    ///   or expanding stream writes at most the declared size before the
    ///   checksum comparison at the end of the payload.
    /// - A payload that takes more bytes off the connection than a compressed
    ///   form of that size fails the pull too. The limit is the declared size,
    ///   plus one byte for each 1024, plus 64 KiB. This limit bounds the time
    ///   and the bandwidth of a stream of empty DEFLATE blocks.
    ///
    /// # Static deltas
    ///
    /// A remote that publishes static deltas delivers a commit as one delta,
    /// with no request for each object. Before the pull requests the first
    /// object, it looks for a delta:
    ///
    /// 1. If the remote serves a summary that states `indexed-deltas` or
    ///    omits the key, the pull fetches the delta index of the target
    ///    commit, `delta-indexes/<to_b64[0:2]>/<to_b64[2:]>.index`.
    /// 2. If the remote serves no index, the pull reads the
    ///    `ostree.static-deltas` map of the summary.
    ///
    /// Both map a delta name to the SHA-256 of the `superblock` of that delta.
    /// The pull fetches no delta that the map does not name. So a client that
    /// holds a commit with no published delta from it fetches loose.
    ///
    /// If the remote serves no summary, nothing advertises a delta. The pull
    /// then requests the `superblock` of one delta by name, with no digest to
    /// verify it against. That delta is `<from>-<to>` if this repository holds
    /// the commit of the ref complete, and the from-scratch `<to>` otherwise.
    ///
    /// The pull takes at most one delta for each target commit. It takes the
    /// first of these that the map names:
    ///
    /// - `<from>-<to>`, where `from` is the commit that the pulled ref names in
    ///   this repository
    /// - `<c>-<to>`, for each other commit `c` that this repository holds
    ///   complete
    /// - the from-scratch `<to>`, if the ref names no commit
    ///
    /// A from-to delta patches against the objects of the source commit, so
    /// this repository must hold the source commit complete. A ref whose
    /// commit is absent or partial counts as a ref that names no commit.
    ///
    /// If the ref names a commit that this repository holds complete, the pull
    /// takes no from-scratch delta, which delivers each object of the target
    /// again. It fetches the missing objects loose. With a map, a ref that
    /// names the target commit, held here partial, also leaves the
    /// from-scratch delta alone. The `ostree` command does the same.
    ///
    /// The pull looks for no delta to a target commit that this repository
    /// holds complete. It looks for a delta to a target commit held partial
    /// as for a commit that it does not hold. A
    /// [`COMMIT_ONLY`](PullFlags::COMMIT_ONLY) pull takes no delta.
    /// [`subpaths`](PullOptions::subpaths) states the delta rules of a
    /// subpath pull.
    ///
    /// If the remote advertised a digest for a superblock, the pull hashes the
    /// superblock and compares the result with the digest before the parse.
    /// So a delta swapped under a signed summary fails the pull. The parsed
    /// superblock must name the pulled commit and the source commit that the
    /// delta name states.
    ///
    /// Before any part request, the pull verifies the signatures of the delta
    /// over the raw superblock bytes, under the policy of
    /// [`PullVerify`]. Also before any part request, it
    /// verifies each inline part against the size and the checksum of its
    /// meta-entry. A superblock that the remote does not hold (a stale
    /// advertisement) is a 404, and the pull fetches the objects loose.
    ///
    /// The superblock holds the target commit, so the pull requests no
    /// `.commit`. A part that the superblock carries inline needs no request.
    /// The pull queues the objects that the delta hands over loose at once.
    /// Two part fetches run at a time, whatever the step count.
    ///
    /// The pull takes each part off the connection under the size that its
    /// meta-entry declares. It verifies the part against the checksum of that
    /// entry before decompression. So the remote puts at most the size that
    /// the superblock states onto the staging file system for one part. The
    /// pull writes each object of a part with its expected checksum asserted.
    ///
    /// The pull applies the parts of one delta in the order that they arrive.
    /// The format allows this order: a part patches against the objects of the
    /// source commit, which are present before the delta applies. A part never
    /// patches against the output of another part of the same delta.
    ///
    /// After the last part, the pull walks the tree of the commit and fetches
    /// loose each object that no part delivered. The `ostree` command takes
    /// the delta and its loose objects as the whole commit. If the delta was
    /// complete, the walk reads what the delta staged and requests nothing.
    ///
    /// Each part in flight costs one xz decoder and two blobs: the verified
    /// part body and the payload that it decompresses to. Each blob is on the
    /// heap while it is small. After a blob passes its heap threshold, it is a
    /// mapped temp file.
    ///
    /// [`static_deltas`](PullOptions::static_deltas) replaces this search with
    /// a list. The pull then reads no delta index and no `ostree.static-deltas`
    /// map, and it needs no summary for the deltas. For each target commit, it
    /// plans the chain with the fewest steps. A chain starts at a commit that
    /// this repository holds complete, or with a delta from scratch if the
    /// rules above for a map allow a from-scratch delta to the target. Of two
    /// chains with the same number of steps, the chain from a complete commit
    /// wins.
    ///
    /// Before the transaction opens, the pull fetches the superblock of each
    /// step and compares its SHA-256 with the digest in the list. It verifies
    /// the signatures and the inline parts of each superblock, as stated
    /// above, before it checks the commit of the step. For each commit of a
    /// chain, the target included, it also fetches the `.commitmeta` and
    /// checks the signatures of the commit. For each requested ref that names
    /// a commit of a chain, it makes the ref-binding check and the timestamp
    /// check, in the order of the refs. So a target that the policy, its ref
    /// binding, or the timestamp check refuses costs the superblocks that
    /// discovery fetched, and the pull requests no part.
    /// The pull does not request these files again, and does not check these
    /// commits again. A commit that has no record in the last plan gets its
    /// checks when the pull fetches it, and the pull requests its
    /// `.commitmeta` again. This is a target whose chain the pull drops, or a
    /// dropped intermediate commit that a depth walk reaches as a parent.
    ///
    /// Over a stream session, if no localcache repository holds the
    /// `.commitmeta` of the commit of a step, the pull sends the request of
    /// the superblock and the request of the `.commitmeta` as one pair. The
    /// reply of the `.commitmeta` arrives while the pull parses and verifies
    /// the superblock. So discovery then holds one superblock and one
    /// `.commitmeta` on the heap, up to 128 MiB each, and the parse of the
    /// superblock. A superblock that the remote does not hold costs its paired
    /// `.commitmeta` request. If a later plan reaches the same commit through
    /// another delta, the pull requests the `.commitmeta` again and counts it
    /// again. So for the same pull, the metadata count over a stream session
    /// can be higher than over HTTP: one more for each superblock that the
    /// remote does not hold, if the remote holds the `.commitmeta` of its
    /// commit.
    ///
    /// The pull keeps the verified superblocks and `.commitmeta` files of
    /// discovery in one temp file in `tmp/` of this repository until it ends.
    /// The file holds at most 1 GiB, the bytes of the steps that discovery
    /// drops included. A list whose steps pass this limit fails the pull with
    /// [`Error::Pull`], and the pull does not fetch loose.
    ///
    /// The pull applies a chain one level at a time, in its one transaction. A
    /// part of a later step can patch against an object that an earlier step
    /// wrote, also an object that the earlier step hands over loose. So the
    /// parts, the loose objects, and the tree walk of one level end before the
    /// next level starts. Each intermediate commit ends complete, with no
    /// `.commitpartial` marker. The pull writes a ref for an intermediate
    /// commit only if a requested ref names it.
    ///
    /// Discovery checks only the signatures of an intermediate commit that
    /// no requested ref names. It makes no ref-binding check and no timestamp
    /// check on it, so a chain can go through a commit whose ref binding
    /// names another ref. If a requested ref names an intermediate commit,
    /// discovery makes both checks for that ref.
    ///
    /// If the remote does not hold a superblock of a chain, the pull plans
    /// again without that delta. If no chain reaches a target, the pull
    /// fetches its objects loose, or fails under `require_static_deltas`. A
    /// listed delta from scratch to the target that the rules above refuse
    /// counts as found: the pull does not fail, and fetches that target loose.
    /// A [`COMMIT_ONLY`](PullFlags::COMMIT_ONLY) pull ignores the list.
    ///
    /// [`disable_static_deltas`](PullOptions::disable_static_deltas) and
    /// [`require_static_deltas`](PullOptions::require_static_deltas) control
    /// the search.
    ///
    /// # Failure
    ///
    /// The steps borrow the repository, the transaction, and the fetcher. A
    /// failure drops each step in flight, which closes its connection and
    /// releases its fetcher permit. The transaction removes its staging
    /// directory, and the pull writes no ref.
    ///
    /// # Errors
    ///
    /// These errors stop the pull before its first request:
    ///
    /// - [`Error::InvalidInput`] if [`depth`](PullOptions::depth) is below
    ///   `-1`.
    /// - [`Error::Unsupported`] if
    ///   [`collection_id`](PullOptions::collection_id) is set. The pull reads
    ///   no collection ref. [`pull_collection`](Repo::pull_collection) pulls
    ///   collection refs.
    /// - [`Error::InvalidInput`] if [`remote`](PullOptions::remote) holds a
    ///   name that [`valid_remote_name`](crate::config::valid_remote_name)
    ///   refuses, also under [`MIRROR`](PullFlags::MIRROR).
    /// - [`Error::Pull`] if a subpath does not start with `/`.
    /// - [`Error::InvalidInput`] if
    ///   [`static_deltas`](PullOptions::static_deltas) holds two digests for
    ///   one delta, or is set together with
    ///   [`disable_static_deltas`](PullOptions::disable_static_deltas) or with
    ///   [`subpaths`](PullOptions::subpaths).
    /// - The errors of [`resolve_pull`]. Among them, [`Error::Io`] names the
    ///   key and the path of a PEM file that cannot be read, and a PEM file
    ///   over 1 MiB is [`Error::InvalidInput`].
    /// - [`Error::Remote`] with
    ///   [`InvalidInput`](crate::remote::Error::InvalidInput) if the ssh
    ///   command or the send command of an [`Endpoint::Ssh`] is empty or holds
    ///   only white space.
    /// - [`Error::Unsupported`] if the scheme of a mirror is neither `http`
    ///   nor `https`, or if the fetcher refuses the proxy URL or a proxy
    ///   environment variable.
    /// - [`Error::Fetch`] if a mirror is not a valid absolute URL, if a header
    ///   is invalid, or if the TLS material does not parse.
    /// - The errors of [`PullTrust::from_remote`]. Among them,
    ///   [`Error::InvalidInput`] if
    ///   [`valid_remote_name`](crate::config::valid_remote_name) refuses
    ///   `remote`.
    ///
    /// These errors stop the pull before it fetches an object:
    ///
    /// - [`Error::Signature`] if the policy of
    ///   [`PullVerify`] refuses the summary.
    /// - [`Error::Unsupported`] if the `config` of the remote states a mode
    ///   other than `archive`.
    /// - [`Error::InvalidFormat`] if the `config` of the remote is not valid
    ///   UTF-8 or has no valid `[core]` group.
    /// - [`Error::InvalidFormat`] if a `refs/heads/<ref>` file is not valid
    ///   UTF-8.
    /// - [`Error::Core`] if the `config` of the remote does not parse as a key
    ///   file, or if a `refs/heads/<ref>` file holds no checksum.
    /// - [`Error::InvalidRefspec`] if a requested ref, a ref of the summary
    ///   under `MIRROR`, or a name of the `branches` key of the remote is not
    ///   a valid ref name. A `MIRROR` pull of every ref
    ///   fails with this error if the summary lists one name that the ref-name
    ///   rule refuses. The pull does not skip the name.
    /// - [`Error::RefNotFound`] if neither the summary nor `refs/heads/<ref>`
    ///   names a requested ref.
    /// - [`Error::Pull`] if [`refs`](PullOptions::refs) is empty and the remote
    ///   serves no summary under `MIRROR`, or the remote has no `branches`.
    /// - These errors of the commit of
    ///   [`TimestampCheck::Rev`](crate::TimestampCheck::Rev), if
    ///   [`timestamp_check`](PullOptions::timestamp_check) is that check and
    ///   the pull has at least one target. The pull reads the commit after the
    ///   ref files of the remote and before it fetches a delta index or a
    ///   static delta superblock.
    ///   - [`Error::ObjectNotFound`] if this repository does not hold the
    ///     commit.
    ///   - [`Error::Io`] if the commit object is larger than
    ///     [`MAX_METADATA_SIZE`], is not a regular file, or a read of it fails.
    ///   - [`Error::Core`] if the tuple frame, the subject, or the body of the
    ///     commit is not in normal form, or if its parent, root dirtree, or
    ///     root dirmeta checksum has a wrong length.
    /// - [`Error::Pull`] if
    ///   [`require_static_deltas`](PullOptions::require_static_deltas) is set
    ///   and the pull finds no delta, or no chain to a target under a list. A
    ///   listed delta from scratch to the target that the from-scratch rules
    ///   of `# Static deltas` refuse counts as found, and the pull fetches
    ///   that target loose.
    /// - [`Error::Pull`] if a superblock names other commits than its delta
    ///   name.
    /// - [`Error::Pull`] if the superblocks and the `.commitmeta` files of the
    ///   chains of a list pass the limit of 1 GiB.
    /// - [`Error::Signature`] if the policy refuses a commit of a chain of a
    ///   list, or the superblock of a step.
    /// - [`Error::Pull`] if a requested ref that names a commit of a chain of
    ///   a list fails the ref-binding check or the timestamp check.
    ///
    /// These errors stop the pull while it fetches:
    ///
    /// - [`Error::Signature`] if the policy refuses a commit or a static delta.
    /// - [`Error::Pull`] if the `ostree.ref-binding` of a commit does not list
    ///   the ref.
    /// - [`Error::Pull`] if a tip is older than the
    ///   [`timestamp_check`](PullOptions::timestamp_check) allows, or if a
    ///   content object fails a mode check.
    /// - [`Error::ObjectNotFound`] if the remote does not hold a requested
    ///   commit or an object of a tree.
    /// - [`Error::ChecksumMismatch`] if a fetched object does not hash to its
    ///   name, or a superblock does not hash to its advertised digest.
    /// - [`Error::Core`] if a fetched commit or the header of a content object
    ///   does not parse.
    /// - [`Error::InvalidFormat`] if a content object breaks its framing, or
    ///   passes its declared size or its compressed limit.
    /// - [`Error::InvalidFormat`] if a content object inflates to fewer bytes
    ///   than declared, or has bytes after its end. A malformed static delta
    ///   has the same error.
    /// - [`Error::InsufficientFreeSpace`] if a stored object needs more space
    ///   than the free-space budget of the transaction holds.
    ///
    /// These errors can stop the pull at any request or write:
    ///
    /// - [`Error::Fetch`], [`Error::HttpStatus`], [`Error::FetchTooLarge`],
    ///   [`Error::ContentEncoded`], or [`Error::RedirectLimit`] if an HTTP
    ///   request fails after its retries.
    /// - [`Error::Remote`] if the session of a pull over ssh fails.
    /// - [`Error::LockTimeout`] if the wait for the repository lock or the
    ///   update lock passes `[core] lock-timeout-secs`.
    /// - [`Error::Io`] for an I/O error of the file system.
    ///
    /// # Examples
    ///
    /// Pull one ref from the remote `origin` of the config:
    ///
    /// ```no_run
    /// # async fn run() -> ostrya::Result<()> {
    /// let repo = ostrya::Repo::open("/srv/repo".as_ref()).await?;
    /// let opts = ostrya::PullOptions {
    ///     refs: vec!["exampleos/stable".to_owned()],
    ///     ..Default::default()
    /// };
    /// let stats = repo.pull("origin", opts).await?;
    /// println!("{} content objects fetched", stats.content_fetched);
    /// # Ok(()) }
    /// ```
    pub async fn pull(&self, remote: &str, mut opts: PullOptions) -> Result<PullStats> {
        let started = Instant::now();
        // A subpath the walk cannot read is refused before anything else, so it
        // costs no request and opens no transaction.
        let subpaths = Subpaths::parse(&opts.subpaths)?;
        check_depth(opts.depth)?;
        refuse_remote_collection(&opts)?;
        check_remote_option(&opts)?;
        check_static_deltas(&opts)?;
        let edges = take_static_deltas(&mut opts).await?;
        // The endpoint is resolved first, so a remote the config does not
        // describe reports that before a policy is resolved for it.
        let overrides = std::mem::take(&mut opts.overrides);
        let endpoint = resolve_pull(Some(self.config()), remote, overrides).await?;
        // The trust comes before the session, so a refused policy starts no
        // fetcher and no ssh client.
        let trust = PullTrust::from_remote(self, remote, &opts.verify).await?;
        let (endpoint, stream) = session_options(endpoint, opts.max_outstanding_fetches);
        let session = connect(endpoint, stream).await?;
        // The trust and the session now hold what these fields gave.
        opts.verify = PullVerify::default();
        opts.max_outstanding_fetches = None;
        opts.remote = opts.remote.or_else(|| Some(remote.to_owned()));
        self.run_session(
            session,
            trust,
            opts,
            Wanted::Config(remote),
            subpaths,
            edges,
            started,
        )
        .await
    }

    /// Pulls refs and their objects through a session that the caller opened.
    ///
    /// `session` reads the remote, and `trust` holds each key that the pull
    /// checks a signature against. The pull obeys the rules of
    /// [`pull`](Repo::pull) that do not come from the config of a remote: the
    /// transaction, the commit walk, [`depth`](PullOptions::depth), the
    /// subpaths, the verification of signatures, the static deltas, and the
    /// statistics.
    ///
    /// The pull reads no remote section of the config of this repository. It
    /// reads the `[core]` keys that each transaction reads.
    ///
    /// # Refs
    ///
    /// The pull takes the refs in [`refs`](PullOptions::refs) alone, and
    /// resolves each one as [`pull`](Repo::pull) does. The prefix of the
    /// written refs comes from [`remote`](PullOptions::remote):
    ///
    /// - `None` writes local refs, `refs/heads/<ref>`, as
    ///   [`pull_local`](Repo::pull_local) does.
    /// - `Some(name)` writes `refs/remotes/<name>/<ref>`.
    /// - [`MIRROR`](PullFlags::MIRROR) writes local refs, whatever `remote`
    ///   holds.
    ///
    /// The pull does not protect the local refs of this repository. Under
    /// [`no_ref_writes`](PullOptions::no_ref_writes), the pull writes no ref,
    /// and the rules above select the ref that the pull reads for delta
    /// discovery and for
    /// [`TimestampCheck::CurrentRef`](crate::TimestampCheck::CurrentRef).
    ///
    /// A `MIRROR` pull copies no `summary` and no `summary.sig`, because the
    /// pull refuses an empty `refs`.
    ///
    /// # Session
    ///
    /// The pull keeps as many steps in flight as the session admits:
    /// [`PullSession::max_outstanding`]. It takes the session by value. A
    /// stream session ends before the transaction commits, as in
    /// [`pull`](Repo::pull).
    ///
    /// # Counters
    ///
    /// [`PullStats::elapsed`] starts at the call of this method.
    /// [`PullStats::bytes_transferred`] and [`progress`](PullOptions::progress)
    /// count as for [`pull`](Repo::pull): the count starts after the
    /// `summary`, the `config`, and the ref files of the remote.
    ///
    /// The caller can attach its own counters to the fetcher of an
    /// [`Http`](PullSession::Http) session with
    /// [`Fetcher::counted`](crate::fetch::Fetcher::counted). Those counters
    /// get the bytes of each body that the fetcher reads, the `summary`, the
    /// `config`, and the ref files included. So their count can be larger
    /// than `bytes_transferred`.
    ///
    /// # Errors
    ///
    /// These errors stop the pull before its first request, before the
    /// transaction opens, and before the pull counts into
    /// [`progress`](PullOptions::progress). The pull writes no object and no
    /// ref. It calls [`PullSession::finish`] before it returns the error, and
    /// ignores the result of that call.
    ///
    /// - [`Error::Pull`] if a subpath does not start with `/`.
    /// - [`Error::InvalidInput`] if [`depth`](PullOptions::depth) is below
    ///   `-1`.
    /// - [`Error::Unsupported`] if
    ///   [`collection_id`](PullOptions::collection_id) is set. The pull reads
    ///   no collection ref.
    /// - [`Error::InvalidInput`] if [`remote`](PullOptions::remote) holds a
    ///   name that [`valid_remote_name`](crate::config::valid_remote_name)
    ///   refuses, also under `MIRROR`.
    /// - [`Error::InvalidInput`] if
    ///   [`static_deltas`](PullOptions::static_deltas) holds two digests for
    ///   one delta, or is set together with
    ///   [`disable_static_deltas`](PullOptions::disable_static_deltas) or with
    ///   [`subpaths`](PullOptions::subpaths).
    /// - [`Error::InvalidInput`] if [`refs`](PullOptions::refs) is empty, also
    ///   under `MIRROR`.
    /// - [`Error::InvalidInput`] if [`verify`](PullOptions::verify) is not the
    ///   default. `trust` holds the keys.
    /// - [`Error::InvalidInput`] if
    ///   [`max_outstanding_fetches`](PullOptions::max_outstanding_fetches) is
    ///   set. The limit of the session applies.
    /// - [`Error::InvalidInput`] if [`overrides`](PullOptions::overrides) is
    ///   not the default. The session selects the server.
    ///
    /// After these checks, the pull has the errors of [`pull`](Repo::pull)
    /// that stop it before it fetches an object, while it fetches, and at any
    /// request or write. A stream session that fails is [`Error::Remote`].
    ///
    /// # Examples
    ///
    /// Pull one ref over HTTP with no check of signatures, into the local ref
    /// `exampleos/stable`:
    ///
    /// ```no_run
    /// use ostrya::fetch::{Fetcher, FetcherOptions};
    /// use ostrya::remote::PullSession;
    /// use ostrya::verify::PullTrust;
    ///
    /// # async fn run() -> ostrya::Result<()> {
    /// let repo = ostrya::Repo::open("/srv/repo".as_ref()).await?;
    /// let fetcher = Fetcher::new(FetcherOptions::new("https://example.com/repo")).await?;
    /// let opts = ostrya::PullOptions {
    ///     refs: vec!["exampleos/stable".to_owned()],
    ///     ..Default::default()
    /// };
    /// let stats = repo
    ///     .pull_with_session(PullSession::Http(fetcher), PullTrust::unverified(), opts)
    ///     .await?;
    /// println!("{} content objects fetched", stats.content_fetched);
    /// # Ok(()) }
    /// ```
    pub async fn pull_with_session(
        &self,
        session: PullSession,
        trust: PullTrust,
        mut opts: PullOptions,
    ) -> Result<PullStats> {
        let started = Instant::now();
        let (subpaths, edges) = match check_session_pull(&mut opts).await {
            Ok(checked) => checked,
            Err(e) => {
                // The refusal comes before the first request. The result of
                // the session end does not change it.
                let _ = session.finish().await;
                return Err(e);
            }
        };
        self.run_session(
            session,
            trust,
            opts,
            Wanted::Named,
            subpaths,
            edges,
            started,
        )
        .await
    }

    /// Runs a pull through `session` to its end, under `trust`.
    ///
    /// The caller made each check of `opts` that applies to its entry.
    /// [`remote`](PullOptions::remote) gives the prefix of the written refs,
    /// and the session gives the number of steps in flight. `edges` is the
    /// index of the list of static deltas that the caller took out of `opts`.
    /// `started` is the start of [`PullStats::elapsed`].
    #[allow(clippy::too_many_arguments)]
    pub(super) async fn run_session(
        &self,
        session: PullSession,
        trust: PullTrust,
        opts: PullOptions,
        wanted: Wanted<'_>,
        subpaths: Option<Subpaths>,
        edges: Option<Edges>,
        started: Instant,
    ) -> Result<PullStats> {
        let counters = PullCounters::new(opts.progress.as_ref());
        let source = RemoteSource::new(session, counters.transferred_sinks());
        let verification = Verification::from_trust(trust);
        // The state of `pull_from` is on the heap, which keeps the future of
        // each entry small.
        Box::pin(self.pull_from(
            wanted,
            source,
            &opts,
            &verification,
            subpaths,
            edges,
            &counters,
            started,
        ))
        .await
    }

    /// Runs a pull from `source` to its end: fetches what the refs reach into
    /// a transaction, ends the source, commits the transaction, and writes the
    /// refs.
    #[allow(clippy::too_many_arguments)]
    async fn pull_from(
        &self,
        wanted: Wanted<'_>,
        source: RemoteSource,
        opts: &PullOptions,
        verification: &Verification,
        subpaths: Option<Subpaths>,
        edges: Option<Edges>,
        counters: &PullCounters,
        started: Instant,
    ) -> Result<PullStats> {
        let mirror = opts.flags.contains(PullFlags::MIRROR);
        let place = match wanted {
            Wanted::Pinned(pinned) => pinned.place,
            _ if mirror => RefPlace::Heads,
            _ => RefPlace::of_remote(opts.remote.as_deref()),
        };

        // The markers that the pull writes. They stay outside the span that
        // writes them, so a failure in that span clears the markers it left.
        let mut marked = Vec::new();
        let fetched = self
            .fetch_from(
                &source,
                wanted,
                opts,
                place,
                verification,
                subpaths,
                edges,
                counters,
                &mut marked,
            )
            .await;
        // The source ends before the transaction commits. The stream source
        // closes the input of the server and, over ssh, waits for the ssh
        // client. As a result, a failure of the session fails the pull before
        // anything publishes.
        let fetched = source.finish(fetched).await;
        let published = match fetched {
            Ok(fetched) => {
                let FetchedPull {
                    txn,
                    targets,
                    summary,
                    signature,
                } = fetched;
                if !opts.no_ref_writes {
                    for (name, tip) in &targets {
                        place.queue(&txn, name, tip);
                    }
                }
                txn.commit().await.map(|stats| (stats, summary, signature))
            }
            Err(e) => Err(e),
        };
        let (stats, summary_bytes, signature) = match published {
            Ok(published) => published,
            Err(e) => {
                self.clear_markers_for_absent_commits(&marked).await;
                return Err(e);
            }
        };

        // The content that a marker guarded is published. A commit-only pull
        // keeps its markers, because it fetched no tree. A pull with subpaths
        // keeps them too, because it fetched part of each tree.
        if !opts.flags.contains(PullFlags::COMMIT_ONLY) && opts.subpaths.is_empty() {
            for commit in &marked {
                self.remove_partial_marker(commit).await?;
            }
        }

        // A mirror pull of every ref holds all that the remote publishes, so
        // the summary of the remote also describes this repository. The pull
        // copies it byte for byte. A mirror pull of named refs holds part of
        // it and writes no summary. A pull that writes no ref writes no
        // summary, because the summary lists refs that the pull did not write.
        if mirror
            && opts.refs.is_empty()
            && !opts.no_ref_writes
            && let Some(bytes) = summary_bytes
        {
            let fsync = self.config().fsync()? && !opts.disable_fsync;
            // The pull writes both files under one hold of the update lock. It
            // takes the lock after the transaction commit released its own
            // hold, so no other writer of the summary lands between the files.
            // The hold can time out after the transaction commit wrote the
            // refs and the `.commitmeta` files. The pull then fails with those
            // files in place and the summary as it was.
            self.write_locked(move |repo| {
                // The client groups of this repository did not build the
                // summary of the remote, so the `.access` file of the
                // `anonymous` item goes first. A server of this repository
                // then serves no summary until the next summary write.
                remove_anonymous_access_blocking(repo.repo_fd(), fsync)?;
                put_root_file_blocking(repo.repo_fd(), SUMMARY_FILE, &bytes, fsync)?;
                // The signature covers those bytes, so the pull copies it with
                // them. A client that pulls from this repository with
                // `gpg-verify-summary=true` reads the pair. If the remote holds
                // no `summary.sig`, the file of this repository stays as it
                // is. The `ostree` command does the same.
                if let Some(sig) = signature {
                    put_root_file_blocking(repo.repo_fd(), SUMMARY_SIG_FILE, &sig, fsync)?;
                }
                // One sync of the root directory makes both renames durable.
                if fsync {
                    rustix::fs::fsync(repo.repo_fd())?;
                }
                Ok(())
            })
            .await?;
        }

        Ok(PullStats {
            metadata_imported: stats.metadata_written,
            content_imported: stats.content_written,
            content_bytes_written: stats.content_bytes_written,
            content_bytes_unpacked: stats.content_bytes_unpacked,
            metadata_fetched: counters.metadata(),
            content_fetched: counters.content(),
            delta_parts: counters.parts(),
            bytes_transferred: counters.bytes(),
            elapsed: started.elapsed(),
        })
    }

    /// Fetches what a pull from `source` reaches into a new transaction: the
    /// summary and its checks, the refs, the deltas, and then the plan, to
    /// its end. With a list of static deltas, the plan runs one time for each
    /// level of intermediate commits, and then one time for the targets. The
    /// commits whose `.commitpartial` marker the pull wrote go into `marked`.
    #[allow(clippy::too_many_arguments)]
    async fn fetch_from(
        &self,
        source: &RemoteSource,
        wanted: Wanted<'_>,
        opts: &PullOptions,
        place: RefPlace<'_>,
        verification: &Verification,
        subpaths: Option<Subpaths>,
        edges: Option<Edges>,
        counters: &PullCounters,
        marked: &mut Vec<Checksum>,
    ) -> Result<FetchedPull> {
        let mut root;
        // The probe of a collection pull read this summary and checked it
        // under the trust of this pull, so the pull does not fetch it again.
        // The pull takes the bytes, so they drop after the parse.
        let probed = match wanted {
            Wanted::Pinned(pinned) => pinned
                .summary
                .lock()
                .unwrap_or_else(PoisonError::into_inner)
                .take(),
            _ => None,
        };
        let summary = if let Some(bytes) = probed {
            // The parse runs on the blocking pool, as below.
            root = RootFiles::default();
            Some(ostrya_rt::unblock(move || Summary::parse(&bytes)).await?)
        } else {
            root = source.root_files().await?;
            // A mirror pull of every ref that writes refs copies the `summary`
            // and the `summary.sig` of the remote. Each other pull drops the
            // bytes after their checks.
            let copies_summary = opts.flags.contains(PullFlags::MIRROR)
                && opts.refs.is_empty()
                && !opts.no_ref_writes;
            // The pull checks the summary before it reads it. The pull acts on
            // the refs that the summary resolves and the deltas that it
            // advertises. As a result, a summary that the policy refuses stops
            // the pull before its first object request.
            root.signature = verification
                .check_summary(root.summary.as_deref(), root.signature.take())
                .await?
                .filter(|_| copies_summary);
            // A summary can be as large as its read cap, so the parse runs on
            // the blocking pool. The bytes come back only for the write of a
            // mirror pull, and else drop there.
            match root.summary.take() {
                Some(bytes) => {
                    let (parsed, bytes) = ostrya_rt::unblock(move || {
                        let parsed = Summary::parse(&bytes);
                        (parsed, copies_summary.then_some(bytes))
                    })
                    .await;
                    root.summary = bytes;
                    Some(parsed?)
                }
                None => None,
            }
        };
        check_remote_mode(root.config(source).await?)?;
        let targets = self
            .remote_targets(wanted, opts, summary.as_ref(), source)
            .await?;
        // The transferred count starts after the summary, the config, and the
        // ref files that a pull reads from a remote with no summary. The
        // `ostree` command reports the same count.
        counters.restart_transferred();

        // The timestamp check reads a commit that it names one time, before
        // discovery. A commit that this repository does not hold stops the
        // pull before its first superblock request. A pull with no target
        // checks no timestamp, so it reads no commit.
        let timestamp = if targets.is_empty() {
            TimestampBase::Off
        } else {
            TimestampBase::resolve(self, &opts.timestamp_check).await?
        };
        // The checks of each requested ref. A collection pull adds the check
        // of the collection binding and of the timestamp that the remote
        // listed.
        let tip_checks = match wanted {
            Wanted::Pinned(pinned) => TipChecks {
                collection: Some(pinned.collection),
                listed: Some(&pinned.listed),
                ..TipChecks::new(opts.flags, timestamp, place)
            },
            _ => TipChecks::new(opts.flags, timestamp, place),
        };

        // The deltas that can deliver these commits, found before the first
        // object request. A commit that a delta carries has no `.commit`
        // request of its own.
        let delta_source = DeltaSource::Remote(source);
        let mut deltas = delta::discover(
            self,
            &delta_source,
            summary.as_ref(),
            &targets,
            opts,
            tip_checks,
            edges,
            verification,
            counters,
        )
        .await?;
        // Discovery is the last reader of the parsed summary.
        drop(summary);
        deltas.plan_parts(counters);

        let mut txn = self.transaction().await?;
        apply_durability(&mut txn, opts);
        // A part of a later step of a chain can patch against an object that
        // an earlier step wrote. So the run of each level of intermediate
        // commits ends before the next run starts. The jobs of a level live
        // for its run alone.
        let none = HashMap::new();
        let mut done = HashSet::new();
        let mut carry = Carry::default();
        for level in deltas.levels() {
            let jobs = deltas.parse_level(self, &delta_source, level).await?;
            let phase = Phase {
                roots: level,
                tips: &none,
                depth: 0,
                subpaths: None,
                deltas: &jobs,
                done: &done,
                last: false,
            };
            self.drive(
                &txn,
                source,
                opts,
                tip_checks,
                phase,
                &deltas,
                verification,
                counters,
                &mut carry,
                marked,
            )
            .await?;
            drop(jobs);
            done.extend(level.iter().copied());
        }
        let jobs = deltas.target_jobs(self, &delta_source).await?;
        // The refs of each requested tip. The binding check and the timestamp
        // check apply to each ref. The plan fetches a commit once, whatever the
        // number of refs that 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 roots: Vec<Checksum> = targets.iter().map(|(_, tip)| *tip).collect();
        let phase = Phase {
            roots: &roots,
            tips: &tips,
            depth: opts.depth,
            subpaths,
            deltas: &jobs,
            done: &done,
            last: true,
        };
        self.drive(
            &txn,
            source,
            opts,
            tip_checks,
            phase,
            &deltas,
            verification,
            counters,
            &mut carry,
            marked,
        )
        .await?;
        Ok(FetchedPull {
            txn,
            targets,
            summary: root.summary,
            signature: root.signature,
        })
    }

    /// Fetches the `summary` and `summary.sig` files of a remote.
    ///
    /// Returns the bytes of `summary` and of `summary.sig`, in this order. A
    /// file that the remote does not serve is `None`. Each file has a cap of
    /// 64 MiB.
    ///
    /// The call reaches the remote as [`pull`](Repo::pull) does. It resolves
    /// the endpoint of `remote` with [`resolve_pull`] and the default
    /// overrides. It then reads the address from `pull-url` or `url`, and
    /// over HTTP it uses the TLS material and the proxy of the remote. Over
    /// ssh, the remote keys `ssh-command` and `send-command` give the
    /// commands. The `OSTRYA_SSH_COMMAND` environment variable has precedence
    /// over `ssh-command`.
    ///
    /// Over HTTP, the call requests `summary.sig` and then `summary`. Over
    /// ssh, the two requests are in flight together, and the session ends
    /// before the call returns.
    ///
    /// # Errors
    ///
    /// - The errors of [`resolve_pull`].
    /// - [`Error::Remote`] with
    ///   [`InvalidInput`](crate::remote::Error::InvalidInput) if the ssh
    ///   command or the send command of an [`Endpoint::Ssh`] is empty or holds
    ///   only white space.
    /// - [`Error::Unsupported`] if the scheme of a mirror is neither `http`
    ///   nor `https`, or if the fetcher refuses the proxy URL or a proxy
    ///   environment variable.
    /// - [`Error::FetchTooLarge`] if an HTTP response declares a file larger
    ///   than 64 MiB.
    /// - [`Error::Fetch`], [`Error::HttpStatus`] other than 404,
    ///   [`Error::ContentEncoded`], or [`Error::RedirectLimit`] if an HTTP
    ///   request fails after its retries.
    /// - [`Error::Remote`] if the ssh session fails.
    pub async fn remote_fetch_summary(
        &self,
        remote: &str,
    ) -> Result<(Option<Vec<u8>>, Option<Vec<u8>>)> {
        let endpoint =
            resolve_pull(Some(self.config()), remote, EndpointOverrides::default()).await?;
        let session = connect(endpoint, StreamSessionOptions::default()).await?;
        let source = RemoteSource::new(session, Vec::new());
        let read = source.summary_files().await;
        source.finish(read).await
    }

    /// Resolves what to pull: the requested refs, the summary refs of the
    /// remote under [`MIRROR`](PullFlags::MIRROR), or the `branches` key of
    /// the remote that `wanted` names.
    async fn remote_targets(
        &self,
        wanted: Wanted<'_>,
        opts: &PullOptions,
        summary: Option<&Summary>,
        source: &RemoteSource,
    ) -> Result<Vec<(String, Checksum)>> {
        if let Wanted::Pinned(pinned) = wanted {
            return Ok(pinned.targets.clone());
        }
        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 that this pull writes. The pull
            // checks it against the rule of the ref store here, before the
            // first object request. Without this check, the first check comes
            // when the transaction resolves the ref 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 Wanted::Config(remote) = wanted else {
                return Err(no_refs());
            };
            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 goes on the wire as a request path, so the pull checks
            // it against the rule of the ref store. A component that the rule
            // refuses, such as a traversal, can ask the server for a resource
            // that 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(source, &name)
                    .await?
                    .ok_or_else(|| Error::RefNotFound(name.clone()))?,
            };
            out.push((name, checksum));
        }
        Ok(out)
    }

    /// Runs one run of the plan to its end, from the roots of `phase`. The
    /// commits whose `.commitpartial` marker this pull wrote, and must clear,
    /// go into `marked`.
    ///
    /// The run starts from the objects that the earlier runs of this pull
    /// queued, and gives them back in `carry` when it ends. So the pull
    /// fetches an object once over all runs. `carry` also keeps a running
    /// count of the units of work, for the progress total. `delta_plan` holds
    /// the checks that discovery made on the commits of the chains.
    ///
    /// `marked` is an argument, so the caller holds the written markers when a
    /// step fails.
    #[allow(clippy::too_many_arguments)]
    async fn drive(
        &self,
        txn: &Transaction,
        source: &RemoteSource,
        opts: &PullOptions,
        tip_checks: TipChecks<'_>,
        phase: Phase<'_>,
        delta_plan: &DeltaPlan,
        verification: &Verification,
        progress: &PullCounters,
        carry: &mut Carry,
        marked: &mut Vec<Checksum>,
    ) -> Result<()> {
        let ctx = StepCtx {
            txn,
            source,
            writes: Arc::new(Gate::new(WRITE_THROTTLE)),
            sources: &opts.localcache_repos,
            flags: opts.flags,
            checks: ModeChecks::new(opts.flags, self.mode()),
            tip_checks,
            tips: phase.tips,
            deltas: phase.deltas,
            done: phase.done,
            delta_plan,
            verification,
            detached_filter: &opts.detached_metadata_filter,
            progress,
        };
        let mut plan = Plan::new(phase.subpaths);
        plan.queued = std::mem::take(&mut carry.queued);
        for root in phase.roots {
            plan.push_commit(CommitItem {
                checksum: *root,
                depth: phase.depth,
                optional: false,
            });
        }

        // The pull keeps as many steps in flight as the session admits.
        let mut slots = Slots::new(source.max_outstanding());
        // The read buffers for content objects, from each source. A localcache
        // import verifies its payload through one, and a fetched payload
        // streams into the object store through one. A step takes a buffer at
        // its start and gives it back with its outcome. So a pull holds one
        // buffer for each slot, whatever the number of objects it stores. A
        // step that fails takes its buffer with it, and the failure ends the
        // pull.
        let mut buffers: Vec<Vec<u8>> = Vec::new();
        // The units of work given to a slot by this pull, for the progress
        // total.
        let mut started = carry.started;
        loop {
            while slots.has_room()
                && let Some(item) = plan.next()
            {
                let buffer = buffers.pop().unwrap_or_default();
                slots.push(self.step(&ctx, item, buffer));
                started += 1;
            }
            plan.report(progress, started, !phase.last);
            let Some(outcome) = slots.next_ready().await else {
                break;
            };
            let (step, buffer) = outcome?;
            buffers.push(buffer);
            progress.object_done();
            plan.apply(step, marked);
        }
        carry.queued = plan.queued;
        carry.started = started;
        Ok(())
    }

    /// Runs one unit of work: fetches an object and stores it.
    ///
    /// `read_buf` is the read buffer of the slot. The step returns it with the
    /// outcome, for the next step in that slot. A content object reads through
    /// it: the payload of an object from the remote, and the verification of
    /// an object 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::apply_job_part(
                    ctx.txn,
                    &DeltaSource::Remote(ctx.source),
                    job,
                    part.index,
                    ctx.checks,
                    ctx.progress,
                )
                .await?;
                Step::Part(part.commit)
            }
        };
        Ok((step, read_buf))
    }

    /// Fetches one commit: its detached metadata, then the object, then the
    /// checks of each requested ref that names it. The step stages the
    /// detached metadata when 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);
        if ctx.done.contains(&checksum) {
            return self.done_commit(ctx, checksum).await;
        }
        // Discovery checked the signatures of each commit of a chain, and kept
        // the verified `.commitmeta`: the result of the filter if the check
        // parsed it, else the bytes of the source. The step stages these bytes
        // and does not request them again.
        let (prechecked, filtered, mut known) = match ctx.delta_plan.commit_check(&checksum).await?
        {
            CommitCheck::NotChecked => (false, false, None),
            CommitCheck::Checked { detached, filtered } => (true, filtered, Some(detached)),
        };

        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, after the checks
        // pass. A commit that this repository holds is there already.
        let mut staging = CommitStaging::Held;
        // Detached metadata goes with its commit, and the pull fetches it
        // before the commit. The `ostree` command was observed to request the
        // pair in this order. The pull holds the bytes until the commit object
        // is here, so a commit that the remote does not hold leaves none.
        //
        // The commit bytes are shared, so the bytes of a delta job need no
        // copy.
        let (detached, bytes) = if present {
            let detached = match known.take() {
                Some(detached) => detached,
                None => {
                    fetch_detached_metadata(ctx.source, ctx.sources, ctx.progress, &checksum)
                        .await?
                }
            };
            let bytes = self
                .load_object_bytes(ObjectType::Commit, &checksum)
                .await?;
            (detached, Arc::new(bytes))
        } else if let Some(src) = cached_source(ctx.sources, name).await? {
            // A localcache source holds the object. The pull reads the bytes
            // from there, and the import runs after the checks, in the order of
            // the fetched branches.
            staging = CommitStaging::Import(src);
            let detached = match known.take() {
                Some(detached) => detached,
                None => {
                    fetch_detached_metadata(ctx.source, ctx.sources, ctx.progress, &checksum)
                        .await?
                }
            };
            (
                detached,
                Arc::new(src.load_object_bytes(ObjectType::Commit, &checksum).await?),
            )
        } else if let Some(job) = ctx.deltas.get(&checksum) {
            // A delta carries the target commit in its superblock, and these
            // bytes come from there. The parse of the superblock verified that
            // they hash to this checksum. The write at staging verifies it
            // again.
            staging = CommitStaging::Write(Arc::clone(&job.commit_bytes));
            let detached = match known.take() {
                Some(detached) => detached,
                None => {
                    fetch_detached_metadata(ctx.source, ctx.sources, ctx.progress, &checksum)
                        .await?
                }
            };
            (detached, Arc::clone(&job.commit_bytes))
        } else {
            match self.fetch_remote_commit(ctx, &checksum).await? {
                (detached, Some(bytes)) => {
                    ctx.progress.metadata_fetched();
                    let bytes = Arc::new(bytes);
                    staging = CommitStaging::Write(Arc::clone(&bytes));
                    (detached, bytes)
                }
                // A parent that the remote does not hold ends that chain, as a
                // source with truncated history does for a local pull. The pull
                // drops its detached metadata: this repository holds no commit
                // for it.
                (_, None) if item.optional => return Ok(Step::Done),
                (_, None) => {
                    return Err(Error::ObjectNotFound {
                        checksum,
                        ty: ObjectType::Commit,
                    });
                }
            }
        };

        // A commit object can be as large as `MAX_METADATA_SIZE`, so the parse
        // runs on the blocking pool.
        let shared = Arc::clone(&bytes);
        let commit = ostrya_rt::unblock(move || Commit::parse(&shared)).await?;
        // The signature verification runs before the pull stages the commit
        // and requests its tree, so a commit that the policy refuses costs no
        // fetch of its own objects. Discovery checked each commit of a chain
        // before the transaction opened: its signatures, and the checks of
        // each requested ref that names it. The step does not check that
        // commit again. The verification reads the detached metadata that
        // this pull puts in place. That is the copy of the remote if it served
        // one, else the copy of this repository. A later verification of the
        // stored commit reads the same metadata.
        // If the verification parses the metadata, the filter reads that parse
        // right after the verification, and the step keeps only its result.
        // The bytes that discovery filtered pass as they are. The step filters
        // the other bytes that discovery kept, and a `.commitmeta` that it
        // fetched itself.
        let detached = if prechecked {
            match known {
                None if filtered => Some(CheckedMeta::Filtered(detached)),
                _ => detached.map(CheckedMeta::Source),
            }
        } else {
            let detached = check_commit_signatures_filtered(
                self,
                ctx.verification,
                ctx.detached_filter,
                &checksum,
                &bytes,
                detached,
            )
            .await?;
            self.check_tips(ctx, &checksum, &commit).await?;
            detached
        };
        // The checks are the last readers of these bytes. A write keeps its
        // own reference in `staging`, so the other stagings drop the bytes
        // here.
        drop(bytes);

        // The pull writes no partial marker for a commit that this repository
        // holds complete: a pull that fails elsewhere must not demote it.
        if !complete {
            self.write_partial_marker(&checksum).await?;
        }
        // The pull stages the commit here, after its marker and before its
        // tree. Each path hashes the bytes and compares the result with the
        // requested name. The write path does this for bytes in memory, and the
        // untrusted import for an object of a localcache source. So a commit
        // stored under a wrong name fails here, before the pull fetches its
        // tree, and nothing stays after the step. The marker guards a reader
        // against a commit whose tree is not yet complete. The pull clears the
        // marker after the transaction publishes.
        match staging {
            CommitStaging::Held => {}
            CommitStaging::Import(src) => {
                self.import_from(
                    ctx.txn,
                    src,
                    name,
                    ctx.flags | PullFlags::UNTRUSTED,
                    read_buf,
                )
                .await?;
            }
            CommitStaging::Write(bytes) => {
                ctx.txn
                    .write_metadata(ObjectType::Commit, Some(&checksum), &bytes)
                    .await?;
            }
        }
        // The commit object is here, so the pull stages its detached metadata
        // now. The transaction commit writes it before the ref that names the
        // commit. A verifier that reads the signatures with the commit needs
        // this order. For a commit that this repository already holds, the
        // copy of the remote replaces the copy here. That is the purpose of a
        // new read of a mutable file on each pull.
        //
        // The filter runs after the checks read the metadata as the remote
        // holds it: here, after the verification that parsed it, or in
        // discovery after the verification of a commit of a chain that parsed
        // it. So a filter drops a property from
        // what the pull stores, and the verified metadata stays whole. A
        // filter that allows no property stages nothing, and the copy of this
        // repository stays as it is.
        if let Some(meta) = detached
            && let Some(meta) = meta.filtered(ctx.detached_filter, &checksum).await?
        {
            ctx.txn.stage_commit_detached_bytes(&checksum, meta).await?;
        }
        // Where the objects of the commit come from. A commit that is complete
        // here needs none of them: what it references is present. Its parent
        // is a different case. The depth of an earlier pull can be smaller
        // than the depth of this pull. So the chain walks on, and the step of
        // the parent 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 that it
            // names and hands over loose. The tree walk comes after the last
            // part. It finds each object that no part delivered and fetches it
            // 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,
        }))
    }

    /// Makes the ref-binding check and the timestamp check of each requested
    /// ref that names `checksum`.
    ///
    /// The plan fetches a commit once, so a second ref at the same commit has
    /// no step of its own for its checks.
    async fn check_tips(
        &self,
        ctx: &StepCtx<'_>,
        checksum: &Checksum,
        commit: &Commit,
    ) -> Result<()> {
        let refs: Vec<&str> = ctx
            .tips
            .get(checksum)
            .into_iter()
            .flatten()
            .map(String::as_str)
            .collect();
        check_tip_refs(self, ctx.tip_checks, checksum, commit, &refs).await
    }

    /// Runs the step of a commit that an earlier run of this pull made
    /// complete in the transaction.
    ///
    /// The step reads and parses the commit from the transaction in one call
    /// on the blocking pool. It then makes the checks of each requested ref
    /// that names the commit, unless discovery made them. It checks no
    /// signature, requests nothing, and stages nothing. The plan follows the
    /// parent of the commit under `depth`.
    async fn done_commit(&self, ctx: &StepCtx<'_>, checksum: Checksum) -> Result<Step> {
        let commit = ctx.txn.load_commit_staged_first(&checksum).await?;
        if !ctx.delta_plan.checked(&checksum) {
            self.check_tips(ctx, &checksum, &commit).await?;
        }
        Ok(Step::Commit(CommitOutcome {
            checksum,
            next: CommitNext::Nothing,
            parent: commit.parent,
            marked: false,
        }))
    }

    /// Fetches a commit that only the remote can give, with its detached
    /// metadata. The `.commitmeta` comes from the first localcache source that
    /// holds it, else from the remote. The commit object comes after it.
    /// `None` in either place is a file that the remote does not serve.
    ///
    /// From the stream source, the two remote requests are in flight together,
    /// in the order of an HTTP pull, so the pair costs one round trip. From the
    /// HTTP source, the pull requests the commit after the `.commitmeta`
    /// arrives.
    async fn fetch_remote_commit(
        &self,
        ctx: &StepCtx<'_>,
        commit: &Checksum,
    ) -> Result<(Option<Vec<u8>>, Option<Vec<u8>>)> {
        let path = object_path(commit, ObjectType::Commit);
        let fetch = || {
            ctx.source
                .read_optional(&path, Priority::High, MAX_METADATA_SIZE)
        };
        match cached_detached_metadata(ctx.sources, commit).await? {
            Some(detached) => Ok((Some(detached), fetch().await?)),
            None if matches!(ctx.source.transfer(), Transfer::Stream(_)) => {
                let (detached, fetched) = futures_lite::future::zip(
                    fetch_remote_detached(ctx.source, ctx.progress, commit),
                    fetch(),
                )
                .await;
                Ok((detached?, fetched?))
            }
            None => {
                let detached = fetch_remote_detached(ctx.source, ctx.progress, commit).await?;
                Ok((detached, fetch().await?))
            }
        }
    }

    /// Fetches one dirtree or dirmeta object and stores it. A dirtree also
    /// reports what it references, for the scan to walk on from.
    async fn fetch_metadata(
        &self,
        ctx: &StepCtx<'_>,
        name: ObjectName,
        read_buf: &mut Vec<u8>,
    ) -> Result<Step> {
        // The pull does not fetch an object that is here. It still reads a
        // dirtree: an object that it references can be missing, and the walk
        // finds that.
        if ctx.txn.is_staged(&name.checksum, name.ty)
            || self.has_object(name.ty, &name.checksum).await?
        {
            // An object that this transaction staged stays in the staging
            // directory until the transaction publishes. So the read looks in
            // 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 = ctx
            .source
            .read_optional(&path, Priority::High, MAX_METADATA_SIZE)
            .await?
            .ok_or(Error::ObjectNotFound {
                checksum: name.checksum,
                ty: name.ty,
            })?;
        // The write path hashes the bytes and compares the result with the
        // requested name, so a substituted object fails here.
        ctx.txn
            .write_metadata(name.ty, Some(&name.checksum), &bytes)
            .await?;
        ctx.progress.metadata_fetched();
        match name.ty {
            ObjectType::DirTree => Ok(Step::DirTree(name.checksum, DirTree::parse(&bytes)?)),
            _ => Ok(Step::Done),
        }
    }

    /// Returns the step of a stored metadata object. A dirtree reports itself,
    /// for the plan to walk on from. Any other object is a leaf, so the method
    /// calls `load` 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(name.checksum, load().await?))
    }

    /// Fetches one content object and stores 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);
        }
        // The pull requests a content object as `.filez`, whatever the remote
        // stores on its disk. The framed, deflated form is the one form that an
        // HTTP client can read.
        let path = object_path(&name.checksum, ObjectType::File);
        let fetcher = match ctx.source.transfer() {
            Transfer::Http(fetcher) => fetcher,
            Transfer::Stream(stream) => {
                // A `.filez` has no whole read. The header read caps its header,
                // and the size that the header declares caps its payload.
                let body = stream
                    .get(&path, u64::MAX)
                    .await?
                    .ok_or(Error::ObjectNotFound {
                        checksum: name.checksum,
                        ty: name.ty,
                    })?;
                // The stream source takes no write permit. The session streams
                // one body at a time, and the depth of the pipeline bounds the
                // stores that finish after the end of their body. If the step
                // took a permit here, the permit holds the one reader of the
                // session while other stores finish.
                self.store_content(ctx, &name.checksum, body, read_buf)
                    .await
                    .map_err(session_error)?;
                ctx.progress.content_fetched();
                return Ok(Step::Done);
            }
        };
        // If a body fails in transit, the pull fetches it again from the
        // start, and the retry count of the fetcher pays for it. The write that
        // failed with it stages nothing, because an object is staged only
        // after the checksum comparison. The write removes its temp file when
        // it fails.
        let mut refetch = fetcher.refetching(FetchRequest {
            priority: Priority::Low,
            ..FetchRequest::path(&path)
        });
        loop {
            let body = match refetch.fetch().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.into(), name)),
            };
            // The step takes the write permit before it reads the body. A step
            // that waits for a permit did not ask the connection for bytes yet,
            // so the progress window of the fetcher does not run against it.
            // The permit covers the whole body: the header read, the payload,
            // and the end-of-stream read. The step releases it before a refetch
            // waits for its delay.
            let permit = ctx.writes.acquire(Priority::Normal).await;
            let stored = self
                .store_content(ctx, &name.checksum, body, read_buf)
                .await;
            drop(permit);
            match stored {
                Ok(()) => {
                    ctx.progress.content_fetched();
                    return Ok(Step::Done);
                }
                Err(e) => refetch.retry(e).await?,
            }
        }
    }

    /// Stores one fetched content object under the requested name.
    ///
    /// The payload streams through `read_buf`, the buffer of the slot, so the
    /// objects that a slot stores share one allocation.
    async fn store_content<R: AsyncRead + Unpin>(
        &self,
        ctx: &StepCtx<'_>,
        expected: &Checksum,
        body: R,
        read_buf: &mut Vec<u8>,
    ) -> Result<()> {
        let (header, declared, framed_header, body) = read_archive_header(body).await?;
        let FileHeader {
            uid,
            gid,
            mode,
            symlink_target: _,
            xattrs,
        } = header.clone();
        let meta = FileMeta {
            uid,
            gid,
            mode,
            xattrs,
        };
        // The mode checks of a local pull, over the metadata in the header that
        // arrives with the object.
        ctx.checks.check(expected, &meta)?;
        store_filez_payload(
            ctx.txn,
            expected,
            &header,
            &meta,
            declared,
            &framed_header,
            body,
            read_buf,
        )
        .await
    }
}

/// What a pull fetched into its transaction, for the transaction commit.
struct FetchedPull {
    txn: Transaction,
    /// The refs to write, and the commit each names.
    targets: Vec<(String, Checksum)>,
    /// The `summary` and `summary.sig` of the remote, which a mirror pull of
    /// every ref copies. Each other pull keeps neither.
    summary: Option<Vec<u8>>,
    signature: Option<Vec<u8>>,
}

/// Returns `endpoint` with the request limit `max_outstanding` of the caller,
/// and the options of a stream session to it.
///
/// A limit of the caller replaces the limit of the endpoint. The pull keeps as
/// many steps in flight as the session admits.
pub(super) fn session_options(
    endpoint: Endpoint,
    max_outstanding: Option<usize>,
) -> (Endpoint, StreamSessionOptions) {
    match endpoint {
        Endpoint::Http(mut http) => {
            if let Some(n) = max_outstanding {
                http.max_outstanding = n;
            }
            (Endpoint::Http(http), StreamSessionOptions::default())
        }
        ssh @ Endpoint::Ssh { .. } => (
            ssh,
            StreamSessionOptions {
                agent: None,
                max_outstanding,
            },
        ),
    }
}

/// Opens the session of a pull to `endpoint`.
///
/// Over ssh, the session takes the options `stream`. Over HTTP, the options
/// of the endpoint give the request limit, and `stream` must be the default.
pub(super) async fn connect(
    endpoint: Endpoint,
    stream: StreamSessionOptions,
) -> Result<PullSession> {
    match endpoint {
        Endpoint::Http(http) => PullSession::connect(Endpoint::Http(http), stream)
            .await
            .map_err(http_error),
        ssh @ Endpoint::Ssh { .. } => Ok(PullSession::connect(ssh, stream).await?),
    }
}

/// Makes the checks of [`Repo::pull_with_session`] over `opts`, and returns
/// the parsed subpaths and the index of the list of static deltas.
///
/// Each check reads `opts` alone, so a refusal sends no request and opens no
/// transaction. The call takes the list out of `opts`, as
/// [`take_static_deltas`] states.
async fn check_session_pull(opts: &mut PullOptions) -> Result<(Option<Subpaths>, Option<Edges>)> {
    let subpaths = Subpaths::parse(&opts.subpaths)?;
    check_depth(opts.depth)?;
    refuse_remote_collection(opts)?;
    check_remote_option(opts)?;
    check_static_deltas(opts)?;
    if opts.refs.is_empty() {
        return Err(no_refs());
    }
    if opts.verify != PullVerify::default() {
        return Err(Error::InvalidInput(
            "a pull with a session takes its signature policy from its trust, and \
             takes no verify option"
                .into(),
        ));
    }
    if opts.max_outstanding_fetches.is_some() {
        return Err(Error::InvalidInput(
            "a pull with a session takes its request limit from the session, and \
             takes no max_outstanding_fetches option"
                .into(),
        ));
    }
    if opts.overrides != EndpointOverrides::default() {
        return Err(Error::InvalidInput(
            "a pull with a session takes its server from the session, and takes \
             no endpoint overrides"
                .into(),
        ));
    }
    let edges = take_static_deltas(opts).await?;
    Ok((subpaths, edges))
}

/// Returns the refusal of a pull with a session that names no ref.
fn no_refs() -> Error {
    Error::InvalidInput("a pull with a session needs at least one ref name".into())
}

/// The refs that a pull from a remote takes if
/// [`refs`](PullOptions::refs) is empty, or the refs of a collection pull.
#[derive(Clone, Copy)]
pub(super) enum Wanted<'a> {
    /// No other ref. [`Repo::pull_with_session`] refuses an empty list.
    Named,
    /// Under [`MIRROR`](PullFlags::MIRROR), each ref of the summary of the
    /// remote. Otherwise, the `branches` key of the remote section of this
    /// name.
    Config(&'a str),
    /// The refs of a collection pull, each at the commit that the pull
    /// selected. The pull reads no ref of the remote, and does not read
    /// [`refs`](PullOptions::refs).
    Pinned(&'a Pinned<'a>),
}

/// The refs of a collection pull from one remote, and the checks of their
/// commits.
pub(super) struct Pinned<'a> {
    /// Each ref name, and the commit that the pull selected for it.
    pub(super) targets: Vec<(String, Checksum)>,
    /// The timestamp that the remote listed for each ref of `targets`.
    pub(super) listed: HashMap<String, u64>,
    /// The collection id that the `ostree.collection-binding` of each tip
    /// must state.
    pub(super) collection: &'a str,
    /// The place of the written refs.
    pub(super) place: RefPlace<'a>,
    /// The `summary` of the remote, if the probe of the collection pull read
    /// the refs from it. The probe checked it under the trust of this pull,
    /// so the pull reads these bytes in place of the remote file. The pull
    /// takes them out before the parse.
    pub(super) summary: Mutex<Option<Arc<Vec<u8>>>>,
}

/// The state that every step of one pull shares.
struct StepCtx<'a> {
    txn: &'a Transaction,
    source: &'a RemoteSource,
    /// The write throttle: the number of fetched content objects that stream
    /// into the object store at once.
    writes: Arc<Gate>,
    /// The repositories that the pull reads for an object before the network,
    /// in order.
    sources: &'a [Repo],
    flags: PullFlags,
    /// The mode checks for each content object that this pull writes, on each
    /// path: a loose fetch, a localcache import, or the parts of a static
    /// delta.
    checks: ModeChecks,
    /// The checks of each requested ref: the ref-binding check, the timestamp
    /// check that the pull resolved before discovery, and the place of the
    /// pulled refs, where the timestamp check reads the current tip of a ref.
    tip_checks: TipChecks<'a>,
    /// The requested refs of each tip commit, for the binding check and the
    /// timestamp check. A commit with no entry is a parent under `depth`,
    /// which no ref names. The map is empty in the run of a level of
    /// intermediate commits.
    tips: &'a HashMap<Checksum, Vec<String>>,
    /// The static delta that delivers each commit of this run, if the remote
    /// publishes one. The pull fetches a commit with no entry object by
    /// object.
    deltas: &'a HashMap<Checksum, DeltaJob>,
    /// The commits that an earlier run of this pull made complete in the
    /// transaction. The step stages nothing for them and checks no signature
    /// again.
    done: &'a HashSet<Checksum>,
    /// The checks that discovery made on the commit of each step of a chain.
    delta_plan: &'a DeltaPlan,
    /// The signature policy of this pull. The pull verifies each commit of a
    /// step before it stages its bytes.
    verification: &'a Verification,
    /// The filter of the properties of detached metadata that this pull
    /// stores. It applies after the checks of the commit pass.
    detached_filter: &'a DetachedMetadataFilter,
    /// The live counters of the pull.
    progress: &'a PullCounters,
}

/// The commits of one run of the plan, and how the pull fetches them.
struct Phase<'a> {
    /// The commits that the run starts from.
    roots: &'a [Checksum],
    /// The requested refs of each tip commit, as [`StepCtx`] holds them.
    tips: &'a HashMap<Checksum, Vec<String>>,
    /// The number of parents to follow from each root, `-1` for all of them.
    depth: i32,
    /// The subpaths of the walk. `None` walks every tree whole.
    subpaths: Option<Subpaths>,
    /// The static delta of each commit of this run.
    deltas: &'a HashMap<Checksum, DeltaJob>,
    /// The commits that an earlier run made complete in the transaction.
    done: &'a HashSet<Checksum>,
    /// `true` for the last run of the pull.
    last: bool,
}

/// What one run of the plan leaves for the next run.
#[derive(Default)]
struct Carry {
    /// The objects that the runs queued, so that the pull fetches an object
    /// once over all runs.
    queued: HashSet<ObjectName>,
    /// The units of work that the runs gave to a slot, for the progress total.
    started: usize,
}

/// One commit to fetch.
struct CommitItem {
    checksum: Checksum,
    /// The number of parents to follow from here, `-1` for all of them.
    depth: i32,
    /// `true` if a remote that does not hold this commit ends the chain, and
    /// the pull goes on. A parent under `depth` has this value.
    optional: bool,
}

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

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

/// The outcome of one step.
enum Step {
    /// A commit object arrived, or was already here.
    Commit(CommitOutcome),
    /// A dirtree is stored: its checksum and its entries, which the plan walks
    /// on from.
    DirTree(Checksum, DirTree),
    /// A delta part is applied. The value is the commit of the part.
    Part(Checksum),
    /// Nothing follows: a dirmeta or content object is stored, or a parent
    /// that the remote does not hold ended its chain.
    Done,
}

/// What a commit adds to the plan.
struct CommitOutcome {
    checksum: Checksum,
    /// How the pull fetches the objects of the commit.
    next: CommitNext,
    /// The parent to follow under `depth`.
    parent: Option<Checksum>,
    /// `true` if this pull wrote the `.commitpartial` marker of the commit.
    marked: bool,
}

/// How a commit object reaches the object store, after the commit passes the
/// checks of its step.
enum CommitStaging<'a> {
    /// This repository holds it.
    Held,
    /// A localcache repository holds it, and the pull imports it from there.
    Import(&'a Repo),
    /// Its bytes are in memory, and the pull writes them into the transaction.
    Write(Arc<Vec<u8>>),
}

/// How the objects of a commit reach this repository.
enum CommitNext {
    /// Object by object: the root dirmeta and dirtree of the commit, and the
    /// walk from there.
    Scan(Vec<ObjectName>),
    /// By static delta: the parts of the delta, the objects that it hands over
    /// loose, and the tree walk after 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,
}

/// The work that the pull must still do, and the work that it did.
///
/// The loop owns the plan, 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 and fetched at high priority. At most
    /// [`PART_CAP`] are in flight, whatever the slot count of the pull.
    parts: VecDeque<PartItem>,
    /// The number of part fetches in flight.
    parts_in_flight: usize,
    /// The number of parts of the delta of each commit that are not applied
    /// yet. When that count is zero, the plan queues the tree walk that
    /// `delta_trees` holds.
    delta_parts: HashMap<Checksum, usize>,
    delta_trees: HashMap<Checksum, Vec<ObjectName>>,
    /// The dirtree and dirmeta objects that the walk waits for, 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 that this pull queued, so that the pull fetches an object
    /// once, also if several commits reach it.
    queued: HashSet<ObjectName>,
    /// The subpaths of the walk. `None` walks every tree whole.
    subpaths: Option<Subpaths>,
    /// The scope of the walk of the root dirtree of each commit.
    root: Scope,
    /// The dirtrees queued under a scope smaller than the whole tree. Each
    /// entry holds the scope of the walk, and a flag that tells if the plan
    /// applied that walk.
    ///
    /// If the plan reaches a dirtree again under a scope that its scope does
    /// not cover, the plan widens its scope. A dirtree that is still queued or
    /// in flight gets the walk under the wider scope when the plan applies its
    /// step. The plan queues a walked dirtree again, and that second step reads
    /// the dirtree that this pull stored.
    partial_trees: HashMap<Checksum, PartialTree>,
    /// The remaining depth at which the plan reached each commit. It decides
    /// if a chain that reaches the commit again walks on from it.
    seen: HashMap<Checksum, i32>,
    /// The parent that each fetched commit named. A chain that reaches the
    /// commit again, with more depth, resumes at the parent and does not fetch
    /// the commit again.
    parents: HashMap<Checksum, Option<Checksum>>,
}

/// A dirtree walked under a scope smaller than the whole tree.
struct PartialTree {
    scope: Scope,
    walked: bool,
}

impl Plan {
    /// Creates a plan whose walk keeps to `subpaths`.
    fn new(subpaths: Option<Subpaths>) -> Plan {
        Plan {
            root: subpaths.as_ref().map(Subpaths::root).unwrap_or_default(),
            subpaths,
            ..Plan::default()
        }
    }

    /// Queues a commit, unless the plan reached it at this depth or deeper.
    ///
    /// The plan does not fetch again a commit that it reaches again with more
    /// depth: the walk resumes at the parent that the commit named. A commit
    /// still in flight named no parent yet. 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,
            };
        }
    }

    /// Queues an object that this pull did not queue yet, and a dirtree that it
    /// queued under a scope that does not cover `scope`.
    fn push_object(&mut self, name: ObjectName, scope: Scope) {
        if self.queued.insert(name) {
            if name.ty == ObjectType::DirTree && scope != Scope::All {
                self.partial_trees.insert(
                    name.checksum,
                    PartialTree {
                        scope,
                        walked: false,
                    },
                );
            }
            match name.ty {
                ObjectType::File => self.content.push_back(name),
                _ => self.scan.push_back(name),
            }
            return;
        }
        if name.ty != ObjectType::DirTree {
            return;
        }
        // A dirtree with no entry here was queued whole.
        let Some(tree) = self.partial_trees.get_mut(&name.checksum) else {
            return;
        };
        if tree.scope.covers(&scope) {
            return;
        }
        tree.scope.widen(&scope);
        if tree.walked {
            tree.walked = false;
            self.scan.push_back(name);
        }
    }

    /// Queues one object of the tree of a commit: the root dirtree under the
    /// root scope, or the root dirmeta.
    fn push_root(&mut self, name: ObjectName) {
        let scope = if name.ty == ObjectType::DirTree {
            self.root.clone()
        } else {
            Scope::All
        };
        self.push_object(name, scope);
    }

    /// Queues the objects that a stored dirtree references, under the scope of
    /// its walk.
    fn apply_dirtree(&mut self, checksum: Checksum, dirtree: &DirTree) {
        let Some(subpaths) = &self.subpaths else {
            for name in children_of(dirtree) {
                self.push_object(name, Scope::All);
            }
            return;
        };
        let scope = match self.partial_trees.get_mut(&checksum) {
            Some(tree) => {
                tree.walked = true;
                tree.scope.clone()
            }
            None => Scope::All,
        };
        for (name, scope) in subpaths.children(dirtree, &scope) {
            self.push_object(name, scope);
        }
    }

    /// Returns the next unit of work: the commits, then the delta parts, then
    /// the scan, then the content.
    ///
    /// The plan holds back a queued part while [`PART_CAP`] parts are in
    /// flight. A pull with more slots spends the other slots on the scan and
    /// the content. The loop can run out of work while parts are queued. This
    /// is safe: the plan holds back a part only while a part is in flight, in a
    /// slot that the loop waits 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)
    }

    /// Stores the progress total and the scan state: the `started` units of
    /// work given to a slot, and the queued work. `more` is `true` if a later
    /// run of the plan follows this run. The pull then still scans.
    fn report(&self, progress: &PullCounters, started: usize, more: bool) {
        let queued = self.commits.len() + self.parts.len() + self.scan.len() + self.content.len();
        let total = u32::try_from(started + queued).unwrap_or(u32::MAX);
        progress.report(
            total,
            more || !self.commits.is_empty() || !self.scan.is_empty(),
        );
    }

    /// Adds the outcome of one step to the plan.
    fn apply(&mut self, step: Step, marked: &mut Vec<Checksum>) {
        match step {
            Step::Commit(outcome) => self.apply_commit(outcome, marked),
            Step::DirTree(checksum, dirtree) => self.apply_dirtree(checksum, &dirtree),
            Step::Part(commit) => self.apply_part(commit),
            Step::Done => {}
        }
    }

    /// Records an applied delta part. After the last part of the delta, queues
    /// the tree walk of its commit.
    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);
        // Each object of the delta is staged now. The walk reads what is here,
        // and requests from the network only what the delta left out.
        for name in self.delta_trees.remove(&commit).unwrap_or_default() {
            self.push_root(name);
        }
    }

    /// Records a commit and queues 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_root(name);
                }
            }
            CommitNext::Delta {
                parts,
                fallbacks,
                tree,
            } => {
                // The plan queues the objects that the delta hands over loose at
                // once, so they travel together with the parts.
                for name in fallbacks {
                    self.push_object(name, Scope::All);
                }
                if parts == 0 {
                    // A delta of fallbacks alone has no part to wait for.
                    for name in tree {
                        self.push_root(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. A later chain can reach this commit
        // with more depth while the commit is 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,
            });
        }
    }
}

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

/// Returns the objects that 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
}

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

/// Reads the `.commitmeta` of a commit from the first localcache source in
/// `sources` that holds it, else from `source`, the remote.
///
/// The caller writes the bytes when the commit object is here. A 404 means
/// that the commit has none, and the copy of this repository stays as it is.
pub(super) async fn fetch_detached_metadata(
    source: &RemoteSource,
    sources: &[Repo],
    progress: &PullCounters,
    commit: &Checksum,
) -> Result<Option<Vec<u8>>> {
    if let Some(bytes) = cached_detached_metadata(sources, commit).await? {
        return Ok(Some(bytes));
    }
    fetch_remote_detached(source, progress, commit).await
}

/// Fetches the `.commitmeta` of a commit from the remote, or `None` if the
/// remote serves none. A file that the remote serves adds one to the metadata
/// count in `progress`.
pub(super) async fn fetch_remote_detached(
    source: &RemoteSource,
    progress: &PullCounters,
    commit: &Checksum,
) -> Result<Option<Vec<u8>>> {
    let path = object_path(commit, ObjectType::CommitMeta);
    let fetched = source
        .read_optional(&path, Priority::High, MAX_METADATA_SIZE)
        .await?;
    if fetched.is_some() {
        progress.metadata_fetched();
    }
    Ok(fetched)
}

/// Returns the `.commitmeta` of a commit from the first localcache repository
/// that holds it.
async fn cached_detached_metadata(sources: &[Repo], commit: &Checksum) -> Result<Option<Vec<u8>>> {
    for src in 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),
        }
    }
    Ok(None)
}

/// Returns the first localcache repository that holds `name`.
pub(super) 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)
}

/// Maps a 404 for an object to [`Error::ObjectNotFound`]. Any other error
/// stays as it is.
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,
    }
}

/// Refuses a remote whose `[core] mode` is not archive, from the bytes of its
/// `config`.
fn check_remote_mode(config: Option<Vec<u8>>) -> Result<()> {
    let Some(bytes) = config else {
        // The pull reads a remote that serves no config as an archive,
        // because the remote serves `.filez` objects.
        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()
    )))
}

/// Returns the commit that `refs/heads/<name>` of the remote names, or `None`
/// if the remote serves no such ref.
async fn fetch_remote_ref(source: &RemoteSource, name: &str) -> Result<Option<Checksum>> {
    let path = source.ref_path(name);
    let Some(bytes) = source
        .read_optional(&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())?))
}

/// Returns the request path of a remote ref: `refs/heads/` and the
/// percent-encoded name.
///
/// A request path goes on the wire as written, so this function encodes the
/// name. It encodes each byte outside the unreserved set of RFC 3986: the
/// ASCII letters and digits, `-`, `.`, `_`, and `~`. It keeps `/`, which
/// separates the components of the name and of the path.
///
/// A `?`, `#`, or `%` in a name is so part of the ref name. The server cannot
/// read it as a query, a fragment, or an escape that decodes into a different
/// name.
pub(super) 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
}

/// Fetches a path whole, or returns `None` if 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),
    }
}

/// Fetches a path whole, under a size cap.
///
/// The fetcher refuses a declared `Content-Length` above the cap before it
/// reads the body. It stops a body that passes the cap when the bytes arrive.
/// Each fetch in flight has one buffer, so the cap of the caller 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 size of the buffer comes from the declared length, which the fetcher
/// held to the cap. The body so goes into one allocation of its own size, and
/// the resident peak is the cap. Each read goes into a chunk of at most
/// 128 KiB, and the function appends the chunk to the buffer.
///
/// No read touches the rest of the buffer, also if the body arrives slowly and
/// a read waits many times. The final read, which finds the end of the stream,
/// goes into the chunk, so a buffer filled to its declared length does not
/// grow. If the remote declares no length, the buffer grows as the function
/// reads, under the same cap.
///
/// If a body fails in transit, the function fetches it again from the start,
/// into a new buffer. It does so while the retry count of the fetcher has a
/// repeat left.
async fn fetch_whole(
    fetcher: &Fetcher,
    path: &str,
    priority: Priority,
    max_size: u64,
) -> Result<Vec<u8>> {
    let mut refetch = fetcher.refetching(FetchRequest {
        priority,
        max_size: Some(max_size),
        ..FetchRequest::path(path)
    });
    loop {
        let Fetched::Body(body) = refetch.fetch().await? else {
            return Err(Error::Fetch(format!(
                "{path}: the remote answered 304 to an unconditional request"
            )));
        };
        let declared = body.content_length();
        match read_whole(body, declared, max_size).await {
            Ok(out) => return Ok(out),
            Err(e) => refetch.retry(Error::from(e)).await?,
        }
    }
}

/// Reads `body` to its end into one buffer. The size of the buffer comes from
/// `declared`, the declared length, which the source held to `max_size`. Each
/// read goes into a bounded chunk, also the read that finds the end of the
/// body. So a buffer filled to its declared length does not grow.
pub(super) async fn read_whole<R: AsyncRead + Unpin>(
    mut body: R,
    declared: Option<u64>,
    max_size: u64,
) -> std::io::Result<Vec<u8>> {
    let declared = usize::try_from(declared.unwrap_or(0).min(max_size)).unwrap_or(0);
    let mut out = Vec::with_capacity(declared);
    let mut chunk = vec![0u8; declared.saturating_add(1).clamp(4096, IO_CHUNK)];
    loop {
        let n = body.read(&mut chunk).await?;
        if n == 0 {
            return Ok(out);
        }
        out.extend_from_slice(&chunk[..n]);
    }
}

/// Reads the archive framing off the front of the stream of a content object.
///
/// The framing is a four-byte big-endian header length, four zero bytes, and
/// then the header. The rest of the stream is the raw-DEFLATE payload.
///
/// The function also returns the size that the header declares for the
/// payload. This size bounds the decompressed payload. The function also
/// returns the raw framed bytes: the length prefix and the header variant, as
/// the remote sent them. A caller can store these bytes as they are, with no
/// new serialization of the parsed header.
///
/// The remote states the header length and supplies the bytes after it. So the
/// function refuses a length above [`MAX_FILE_HEADER_SIZE`] before it
/// allocates the buffer. That bound holds for each fetch in flight, because
/// each content object has one header.
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))
}

/// Stores one content object in the archive wire form, from the stream after
/// its framed header.
///
/// `header` and `declared` come from [`read_archive_header`], and
/// `framed_header` is the framing that it read. `meta` is the logical metadata
/// of `header`, which the caller checked against the destination mode.
///
/// A symlink carries no payload, so its stream must end after the header. An
/// archive destination stores the compressed bytes as they arrive. Each other
/// mode inflates them into a content writer. Both sides of the payload are
/// held to `declared`.
///
/// On each of the three paths, the function reads the stream to its end
/// before it stores the object. Each destination refuses a payload that
/// inflates to fewer bytes than `declared`.
#[allow(clippy::too_many_arguments)]
pub(crate) async fn store_filez_payload<R: AsyncRead + Unpin>(
    txn: &Transaction,
    expected: &Checksum,
    header: &FileHeader,
    meta: &FileMeta,
    declared: u64,
    framed_header: &[u8],
    mut body: R,
    read_buf: &mut Vec<u8>,
) -> Result<()> {
    if header.is_symlink() {
        check_stream_end(expected, "symlink header", &mut body).await?;
        txn.write_symlink(&header.symlink_target, meta, Some(expected))
            .await?;
        return Ok(());
    }
    // The declared size bounds both sides of the payload: the decompressed
    // size, and the bytes that come off the connection to produce it.
    let source = BoundedInput::new(body, *expected, compressed_bound(declared));
    if txn.repo().mode().is_archive() {
        // The remote stores this object deflated, in the wire form that this
        // destination writes. So the fetched bytes go to disk as they are,
        // with no inflate and no new compression.
        txn.write_archive_payload(expected, header, framed_header, declared, source, read_buf)
            .await
            .map_err(payload_refusal)?;
        return Ok(());
    }
    let mut writer = txn.content_writer(Some(expected), meta).await?;
    let mut payload = DeflateDecoder::new(BufSource::new(source));
    let short = copy_bounded(&mut payload, &mut writer, read_buf, expected, declared)
        .await
        .map_err(payload_refusal)?;
    if short != 0 {
        return Err(Error::InvalidFormat(format!(
            "content object {expected}: the payload inflates to {} byte(s), not the \
             {declared} its header declares",
            declared - short
        )));
    }
    // The decoder stops at the DEFLATE end-of-stream marker and asks its
    // input for no more bytes. So the function must read the stream to its
    // end here. That read returns the connection to the pool for the next
    // object, and moves a stream session to its next reply. It comes before
    // the finish of the writer, so the next reply arrives while this object
    // is stored.
    check_stream_end(expected, "deflated payload", payload.into_inner())
        .await
        .map_err(payload_refusal)?;
    writer.finish().await?;
    Ok(())
}

/// Streams the payload of a content object into `writer`, and stops if the
/// payload grows past the size that its header declared. Returns the number of
/// declared bytes that the payload did not hold.
///
/// A correct object decompresses to exactly `declared`. A stream that passes
/// it is corrupt or built to expand, so the rest of it has no value. The
/// checksum of the object covers the declared size only at the comparison at
/// the end of the payload. This bound limits the bytes written before that
/// comparison.
///
/// Each read is clamped to the bytes left plus the one byte that decides the
/// result. So at most one byte past the declaration is stored before the
/// refusal.
///
/// `buf` is the read buffer of the slot. It grows to [`READ_CHUNK`] on its
/// first use, and each later object of that slot uses it again.
///
/// [`BoundedInput`], under the decoder, bounds the compressed side of the same
/// declaration.
async fn copy_bounded<R, W>(
    mut reader: R,
    writer: &mut W,
    buf: &mut Vec<u8>,
    expected: &Checksum,
    declared: u64,
) -> Result<u64>
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(left);
        }
        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?;
    }
}

/// Returns the number of bytes that a payload of `declared` uncompressed bytes
/// can take off the connection.
///
/// A DEFLATE compressor uses a stored block for data that it cannot shrink:
/// five bytes of framing for each 65535 bytes of input. That is one part in
/// thirteen thousand, and one part in 1024 covers it with a margin. The fixed
/// 64 KiB covers a small object, whose framing is larger than its content. A
/// stream past this bound is not a compressed form of the declared size,
/// whatever it decompresses to.
pub(crate) fn compressed_bound(declared: u64) -> u64 {
    declared
        .saturating_add(declared / 1024)
        .saturating_add(64 * 1024)
}

/// The compressed stream of a content object, bounded by the size that its
/// header declares.
///
/// [`copy_bounded`] bounds the decompressed payload. That bound does not limit
/// the compressed bytes that produce it. An empty non-final DEFLATE block is
/// five bytes that decompress to nothing. A stream of these blocks
/// decompresses to nothing for as long as the remote sends it.
///
/// Memory and disk then stay bounded, and time and bandwidth do not. The
/// decoder does not return to its caller while its input gives bytes. So the
/// bound on that input must be in the read of the decoder, which is this read.
///
/// The refusal is an [`Error::InvalidFormat`] in the `io::Error` that the
/// decoder passes up. [`payload_refusal`] takes it back out. The bound comes
/// from the declaration of the object, so the refusal names the object, as the
/// refusal of the decompressed size does.
pub(crate) struct BoundedInput<R> {
    inner: R,
    /// The object of the bound.
    checksum: Checksum,
    bound: u64,
    /// The bytes taken from `inner`. This count passes the bound by at most the
    /// one read that trips it.
    taken: u64,
}

impl<R> BoundedInput<R> {
    pub(crate) 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))
    }
}

/// Takes back the refusal that a bounded read reported.
///
/// The decoder returns the failure of its input as its own failure. So a
/// refusal of [`BoundedInput`] arrives here in an `io::Error`. The unwrap gives
/// that refusal the same form as a refusal of [`copy_bounded`]. Any other error
/// stays as it is.
pub(crate) fn payload_refusal(error: Error) -> Error {
    match error {
        Error::Io(io) => io.downcast::<Error>().unwrap_or_else(Error::Io),
        other => other,
    }
}

/// Checks that the stream of a content object ends after `after`, and reads to
/// that end.
///
/// One byte decides it. The remote sends the framing that selects the check of
/// the caller. If bytes follow, the remote chose their length, and a read of
/// all of them holds all of them. If the object ends at the correct point,
/// this read reaches the end of its response. The read then returns the
/// connection to the pool for the next object.
///
/// The stream of the payload is the input buffer of the decoder. It gives back
/// the read-ahead that the decoder left before it asks the body for more
/// bytes. A correct object leaves none: nothing follows its final DEFLATE
/// block.
pub(crate) 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(())
}

/// A compile-time check that the future of a pull is `Send`: from a remote,
/// through a session of the caller, and from a local repository.
const _: fn() = || {
    fn assert_send<T: Send>(_: &T) {}
    let _ = |repo: &Repo| assert_send(&repo.pull("origin", PullOptions::default()));
    let _ = |repo: &Repo, session: PullSession| {
        assert_send(&repo.pull_with_session(
            session,
            PullTrust::unverified(),
            PullOptions::default(),
        ))
    };
    let _ = |repo: &Repo, src: &Repo| assert_send(&repo.pull_local(src, PullOptions::default()));
};

#[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};

    /// Returns the archive stored form of a content object: the framed header,
    /// then the payload that 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 rest is the
    /// payload, which goes to the decoder.
    #[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");
        });
    }

    /// The header of a symlink names its target, and its stored form carries no
    /// payload.
    #[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. Other
    /// bytes are not the framing that this reader reads.
    #[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, and the
    /// read fails.
    #[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 to an end fails this test, and the process does not run 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. The refusal
    /// reads one byte of the payload, and holds none of the length that the
    /// remote chose to send.
    #[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 and does not read the
    /// bytes after it. So the end-of-stream check runs over the input buffer of
    /// the decoder. A payload that ends the stream passes the check, and the
    /// check refuses trailing bytes that the decoder did not consume.
    #[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 that its header declares is
    /// refused. The refusal reads one byte past the declaration, and no more 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 an unbounded compressed stream fails this test, and the
    /// process does not run 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 that its declared size sets. The decompressed
    /// bound never trips against it. The refusal reaches the caller as the
    /// refusal that it is. The stream delivered 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 that it is stated for. Data that
    /// a compressor cannot shrink is the worst case, and its compressed form is
    /// inside the bound that 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. A payload that reaches it is stored
    /// whole, and the checksum comparison decides a shorter one.
    #[test]
    fn a_payload_within_its_declared_size_is_stored() {
        block_on(async {
            // One buffer serves both objects, as the buffer of a slot 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 second object reads through the buffer that the first object
            // grew, and that buffer is the read chunk of the slot.
            assert_eq!(buf.len(), READ_CHUNK);
        });
    }

    /// A declared header length past the header cap is refused before the
    /// buffer is allocated. So a remote controls at most that cap for each
    /// fetch in flight. The test refuses the first byte past the cap and the
    /// largest length that 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 goes on the wire encoded. Its `/` separators stay, and each
    /// character that names something else in a URL is encoded.
    #[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)
    }

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

    /// Returns the outcome of a commit that 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,
        })
    }

    /// Drains the plan: applies a stored outcome for each queued object. The
    /// dirtrees reference no more objects.
    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(name.checksum, DirTree::default())
                }
                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 that 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 that several commits reach is queued once. This holds if the
    /// other commits reach it while it is queued, and after it is 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 more depth is not fetched again: the walk
    /// resumes at the parent that 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 of the pull: the commits, then the
    /// objects that the scan waits for, 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 that it hands over loose. The
    /// tree walk of the commit 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));
    }

    /// The plan gives out no more than [`PART_CAP`] parts at once, whatever the
    /// number of parts of the delta and of slots of the pull.
    #[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 stream that checks, at its end, that the transaction did not stage the
    /// object yet.
    struct EndBeforeStore<'a> {
        inner: Cursor<Vec<u8>>,
        txn: &'a Transaction,
        checksum: Checksum,
        ended: bool,
    }

    impl AsyncRead for EndBeforeStore<'_> {
        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))?;
            if n == 0 && !buf.is_empty() {
                assert!(
                    !me.txn.is_staged(&me.checksum, ObjectType::File),
                    "the object was stored before its stream ended"
                );
                me.ended = true;
            }
            Poll::Ready(Ok(n))
        }
    }

    /// Each destination reads the end of the stream of a content object before
    /// it stores the object. So a stream session moves to its next reply while
    /// the store finishes. The test covers the regular-file path of an archive
    /// and of a bare-user destination, and the symlink path.
    #[test]
    fn the_stream_ends_before_the_object_is_stored() {
        let dir =
            std::env::temp_dir().join(format!("ostrya-pull-stream-end-{}", std::process::id()));
        let _ = std::fs::remove_dir_all(&dir);
        std::fs::create_dir_all(&dir).unwrap();
        let payload = b"payload of a regular file".to_vec();
        let symlink = FileHeader {
            symlink_target: "target".to_owned(),
            mode: 0o120777,
            ..regular_header()
        };
        block_on(async {
            for (mode, header) in [
                (RepoMode::Archive, regular_header()),
                (RepoMode::BareUser, regular_header()),
                (RepoMode::BareUser, symlink.clone()),
            ] {
                let root = dir.join(format!("{}-{}", mode.as_mode_str(), header.is_symlink()));
                let repo = Repo::create(&root, crate::CreateOptions::new(mode))
                    .await
                    .unwrap();
                let txn = repo.transaction().await.unwrap();
                let body = if header.is_symlink() {
                    Vec::new()
                } else {
                    payload.clone()
                };
                let mut hasher = ostrya_core::ContentHasher::new(&header).unwrap();
                hasher.update(&body);
                let checksum = hasher.finish();
                let mut deflated = Vec::new();
                if !header.is_symlink() {
                    DeflateEncoder::new(&body[..])
                        .read_to_end(&mut deflated)
                        .await
                        .unwrap();
                }
                let stored = framed(&header, body.len() as u64, &deflated);
                let (parsed, declared, framed_header, rest) =
                    read_archive_header(Cursor::new(stored)).await.unwrap();
                let FileHeader {
                    uid,
                    gid,
                    mode: file_mode,
                    xattrs,
                    ..
                } = parsed.clone();
                let meta = FileMeta {
                    uid,
                    gid,
                    mode: file_mode,
                    xattrs,
                };
                let mut stream = EndBeforeStore {
                    inner: rest,
                    txn: &txn,
                    checksum,
                    ended: false,
                };
                store_filez_payload(
                    &txn,
                    &checksum,
                    &parsed,
                    &meta,
                    declared,
                    &framed_header,
                    &mut stream,
                    &mut Vec::new(),
                )
                .await
                .unwrap();
                assert!(stream.ended, "{mode:?}: the stream was not read to its end");
                assert!(txn.is_staged(&checksum, ObjectType::File), "{mode:?}");
            }
        });
        let _ = std::fs::remove_dir_all(&dir);
    }

    /// Pops the next item, which must be the dirtree `byte`.
    fn pop_dirtree(plan: &mut Plan, byte: u8) {
        loop {
            match plan.next() {
                Some(Item::Object(name)) if name.ty == ObjectType::DirMeta => continue,
                Some(Item::Object(name)) => {
                    assert_eq!(name, object(byte, ObjectType::DirTree));
                    return;
                }
                _ => panic!("dirtree {byte} was not queued"),
            }
        }
    }

    /// A dirtree reached at two subpath positions gets a walk under both, also
    /// if the second position reaches it after its first walk. The plan queues
    /// it again, and the second walk fetches what the first walk left out.
    #[test]
    fn a_dirtree_reached_again_under_a_wider_scope_is_walked_again() {
        let values = ["/p/x/".to_owned(), "/q/x".to_owned()];
        let mut plan = Plan::new(Subpaths::parse(&values).unwrap());
        let mut marked = Vec::new();
        // The root (1) holds `p` (10) and `q` (11), and both hold `x`, the one
        // dirtree 20, which holds the file 30.
        let root = DirTree {
            files: Vec::new(),
            dirs: vec![
                ("p".into(), csum(10), csum(2)),
                ("q".into(), csum(11), csum(2)),
            ],
        };
        let parent = DirTree {
            files: Vec::new(),
            dirs: vec![("x".into(), csum(20), csum(2))],
        };
        let x = DirTree {
            files: vec![("f".into(), csum(30))],
            dirs: Vec::new(),
        };
        plan.apply(
            fetched(
                csum(1),
                vec![
                    object(2, ObjectType::DirMeta),
                    object(1, ObjectType::DirTree),
                ],
                None,
            ),
            &mut marked,
        );
        pop_dirtree(&mut plan, 1);
        plan.apply(Step::DirTree(csum(1), root), &mut marked);
        pop_dirtree(&mut plan, 10);
        pop_dirtree(&mut plan, 11);
        plan.apply(Step::DirTree(csum(10), parent.clone()), &mut marked);
        // The walk of `x` is under `/p/x/` alone, which fetches nothing in it.
        pop_dirtree(&mut plan, 20);
        plan.apply(Step::DirTree(csum(20), x.clone()), &mut marked);
        assert!(plan.content.is_empty());
        // `/q/x` reaches it again and names it whole.
        plan.apply(Step::DirTree(csum(11), parent), &mut marked);
        pop_dirtree(&mut plan, 20);
        plan.apply(Step::DirTree(csum(20), x.clone()), &mut marked);
        assert_eq!(
            plan.content.iter().copied().collect::<Vec<_>>(),
            [object(30, ObjectType::File)]
        );
        // The scope covers a third reach, so the plan queues nothing again.
        plan.push_object(object(20, ObjectType::DirTree), Scope::All);
        assert!(plan.scan.is_empty());
    }

    /// A delta whose objects all went to fallbacks has no part to wait for. So
    /// the plan queues its tree walk 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());
    }
}