ostrya 0.12.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
3699
3700
3701
3702
3703
3704
3705
3706
3707
3708
3709
3710
3711
3712
3713
3714
3715
3716
3717
3718
3719
3720
3721
3722
3723
3724
3725
3726
3727
3728
3729
3730
3731
3732
3733
3734
3735
3736
3737
3738
3739
3740
3741
3742
3743
3744
3745
3746
3747
3748
3749
3750
3751
3752
3753
3754
3755
3756
3757
3758
3759
3760
3761
3762
3763
3764
3765
3766
3767
3768
3769
3770
3771
3772
3773
3774
3775
3776
3777
3778
3779
3780
3781
3782
3783
3784
3785
3786
3787
3788
3789
3790
3791
3792
3793
3794
3795
3796
3797
3798
3799
3800
3801
3802
3803
3804
3805
3806
3807
3808
3809
3810
3811
3812
3813
3814
3815
3816
3817
3818
3819
3820
3821
3822
3823
3824
3825
3826
3827
3828
3829
3830
3831
3832
3833
3834
3835
3836
3837
3838
3839
3840
3841
3842
3843
3844
3845
3846
3847
3848
3849
3850
3851
3852
3853
3854
3855
3856
3857
3858
3859
3860
3861
3862
3863
3864
3865
3866
3867
3868
3869
3870
3871
3872
3873
3874
3875
3876
3877
3878
3879
3880
3881
3882
3883
3884
3885
3886
3887
3888
3889
3890
3891
3892
3893
3894
3895
3896
3897
3898
3899
3900
3901
3902
3903
3904
3905
3906
3907
3908
3909
3910
3911
3912
3913
3914
3915
3916
3917
3918
3919
3920
3921
3922
3923
3924
3925
3926
3927
3928
3929
3930
3931
3932
3933
3934
3935
3936
3937
3938
3939
3940
3941
3942
3943
3944
3945
3946
3947
3948
3949
3950
3951
3952
3953
3954
3955
3956
3957
3958
3959
3960
3961
3962
3963
3964
3965
3966
3967
3968
3969
3970
3971
3972
3973
3974
3975
3976
3977
3978
3979
3980
3981
3982
3983
3984
3985
3986
3987
3988
3989
3990
3991
3992
3993
3994
3995
3996
3997
3998
3999
4000
4001
4002
4003
4004
4005
4006
4007
4008
4009
4010
4011
4012
4013
4014
4015
4016
4017
4018
4019
4020
4021
4022
4023
4024
4025
4026
4027
4028
4029
4030
4031
4032
4033
4034
4035
4036
4037
4038
4039
4040
4041
4042
4043
4044
4045
4046
4047
4048
4049
4050
4051
4052
4053
4054
4055
4056
4057
4058
4059
4060
4061
4062
4063
4064
4065
4066
4067
4068
4069
4070
4071
4072
4073
4074
4075
4076
4077
4078
4079
4080
4081
4082
4083
4084
4085
4086
4087
4088
4089
4090
4091
4092
4093
4094
4095
4096
4097
4098
4099
4100
4101
4102
4103
4104
4105
4106
4107
4108
4109
4110
4111
4112
4113
4114
4115
4116
4117
4118
4119
4120
4121
4122
4123
4124
4125
4126
4127
4128
4129
4130
4131
4132
4133
4134
4135
4136
4137
4138
4139
4140
4141
4142
4143
4144
4145
4146
4147
4148
4149
4150
4151
4152
4153
4154
4155
4156
4157
4158
4159
4160
4161
4162
4163
4164
4165
4166
4167
4168
4169
4170
4171
4172
4173
4174
4175
4176
4177
4178
4179
4180
4181
4182
4183
4184
4185
4186
4187
4188
4189
4190
4191
4192
4193
4194
4195
4196
4197
4198
4199
4200
4201
4202
4203
4204
4205
4206
4207
4208
4209
4210
4211
4212
4213
4214
4215
4216
4217
4218
4219
4220
4221
4222
4223
4224
4225
4226
4227
4228
4229
4230
4231
4232
4233
4234
4235
4236
4237
4238
4239
4240
4241
4242
4243
4244
4245
4246
4247
4248
4249
4250
4251
4252
4253
4254
4255
4256
4257
4258
4259
4260
4261
4262
4263
4264
4265
4266
4267
4268
4269
4270
4271
4272
4273
4274
4275
4276
4277
4278
4279
4280
4281
4282
4283
4284
4285
4286
4287
4288
4289
4290
4291
4292
4293
4294
4295
4296
4297
4298
4299
4300
4301
4302
4303
4304
4305
4306
4307
4308
4309
4310
4311
4312
4313
4314
4315
4316
4317
4318
4319
4320
4321
4322
4323
4324
4325
4326
4327
4328
4329
4330
4331
4332
4333
4334
4335
4336
4337
4338
4339
4340
4341
4342
4343
4344
4345
4346
4347
4348
4349
4350
4351
4352
4353
4354
4355
4356
4357
4358
4359
4360
4361
4362
4363
4364
4365
4366
4367
4368
4369
4370
4371
4372
4373
4374
4375
4376
4377
4378
4379
4380
4381
4382
4383
4384
4385
4386
4387
4388
4389
4390
4391
4392
4393
4394
4395
4396
4397
4398
4399
4400
4401
4402
4403
4404
4405
4406
4407
4408
4409
4410
4411
4412
4413
4414
4415
4416
4417
4418
4419
4420
4421
4422
4423
4424
4425
4426
4427
4428
4429
4430
4431
4432
4433
4434
4435
4436
4437
4438
4439
4440
4441
4442
4443
4444
4445
4446
4447
4448
4449
4450
4451
4452
4453
4454
4455
4456
4457
4458
4459
4460
4461
4462
4463
4464
4465
4466
4467
4468
4469
4470
4471
4472
4473
4474
4475
4476
4477
4478
4479
4480
4481
4482
4483
4484
4485
4486
4487
4488
4489
4490
4491
4492
4493
4494
4495
4496
4497
4498
4499
4500
4501
4502
4503
4504
4505
4506
4507
4508
4509
4510
4511
4512
4513
4514
4515
4516
4517
4518
4519
4520
4521
4522
4523
4524
4525
4526
4527
4528
4529
4530
4531
4532
4533
4534
4535
4536
4537
4538
4539
4540
4541
4542
4543
4544
4545
4546
4547
4548
4549
4550
4551
4552
4553
4554
4555
4556
4557
4558
4559
4560
4561
4562
4563
4564
4565
4566
4567
4568
4569
4570
4571
4572
4573
4574
4575
4576
4577
4578
4579
4580
4581
4582
4583
4584
4585
4586
4587
4588
4589
4590
4591
4592
4593
4594
4595
4596
4597
4598
4599
4600
4601
4602
4603
4604
4605
4606
4607
4608
4609
4610
4611
4612
4613
4614
4615
4616
4617
4618
4619
4620
4621
4622
4623
4624
4625
4626
4627
4628
4629
4630
4631
4632
4633
4634
4635
4636
4637
4638
4639
4640
4641
4642
4643
4644
4645
4646
4647
4648
4649
4650
4651
4652
4653
4654
4655
4656
4657
4658
4659
4660
4661
4662
4663
4664
4665
4666
4667
4668
4669
4670
4671
4672
4673
4674
4675
4676
4677
4678
4679
4680
4681
4682
4683
4684
4685
4686
4687
4688
4689
4690
4691
4692
4693
4694
4695
4696
4697
4698
4699
4700
4701
4702
4703
4704
4705
4706
4707
4708
4709
4710
4711
4712
4713
4714
4715
4716
4717
4718
4719
4720
4721
4722
4723
4724
4725
4726
4727
4728
4729
4730
4731
4732
4733
4734
4735
4736
4737
4738
4739
4740
4741
4742
4743
4744
4745
4746
4747
4748
4749
4750
4751
4752
4753
4754
4755
4756
4757
4758
4759
4760
4761
4762
4763
4764
4765
4766
4767
4768
4769
4770
4771
4772
4773
4774
4775
4776
4777
4778
4779
4780
4781
4782
4783
4784
4785
4786
4787
4788
4789
4790
4791
4792
4793
4794
4795
4796
4797
4798
4799
4800
4801
4802
4803
4804
4805
4806
4807
4808
4809
4810
4811
4812
4813
4814
4815
4816
4817
4818
4819
4820
4821
4822
4823
4824
4825
4826
4827
4828
4829
4830
4831
4832
4833
4834
4835
4836
4837
4838
4839
4840
4841
4842
4843
4844
4845
4846
4847
4848
4849
4850
4851
4852
4853
4854
4855
4856
4857
4858
4859
4860
4861
4862
4863
4864
4865
4866
4867
4868
4869
4870
4871
4872
4873
4874
4875
4876
4877
4878
4879
4880
4881
4882
4883
4884
4885
4886
4887
4888
4889
4890
4891
4892
4893
4894
4895
4896
4897
4898
4899
4900
4901
4902
4903
4904
4905
4906
4907
4908
4909
4910
4911
4912
4913
4914
4915
4916
4917
4918
4919
4920
4921
4922
4923
4924
4925
4926
4927
4928
4929
4930
4931
4932
4933
4934
4935
4936
4937
4938
4939
4940
4941
4942
4943
4944
4945
4946
4947
4948
4949
4950
4951
4952
4953
4954
4955
4956
4957
4958
4959
4960
4961
4962
4963
4964
4965
4966
4967
4968
4969
4970
4971
4972
4973
4974
4975
4976
4977
4978
4979
4980
4981
4982
4983
4984
4985
4986
4987
4988
4989
4990
4991
4992
4993
4994
4995
4996
4997
4998
4999
5000
5001
5002
5003
5004
5005
5006
5007
5008
5009
5010
5011
5012
5013
5014
5015
5016
5017
5018
5019
5020
5021
5022
5023
5024
5025
5026
5027
5028
5029
5030
5031
5032
5033
5034
5035
5036
5037
5038
5039
5040
5041
5042
5043
5044
5045
5046
5047
5048
5049
5050
5051
5052
5053
5054
5055
5056
5057
5058
5059
5060
5061
5062
5063
5064
5065
5066
5067
5068
5069
5070
5071
5072
5073
5074
5075
5076
5077
5078
5079
5080
5081
5082
5083
5084
5085
5086
5087
5088
5089
5090
5091
5092
5093
5094
5095
5096
5097
5098
5099
5100
5101
5102
5103
5104
5105
5106
5107
5108
5109
5110
5111
5112
5113
5114
5115
5116
5117
5118
5119
5120
5121
5122
5123
5124
5125
5126
5127
5128
5129
5130
5131
5132
5133
5134
5135
5136
5137
5138
5139
5140
5141
5142
5143
5144
5145
5146
5147
5148
5149
5150
5151
5152
5153
5154
5155
5156
5157
5158
5159
5160
5161
5162
5163
5164
5165
5166
5167
5168
5169
5170
5171
5172
5173
5174
5175
5176
5177
5178
5179
5180
5181
5182
5183
5184
5185
5186
5187
5188
5189
5190
5191
5192
5193
5194
5195
5196
5197
5198
5199
5200
5201
5202
5203
5204
5205
5206
5207
5208
5209
5210
5211
5212
5213
5214
5215
5216
5217
5218
5219
5220
5221
5222
5223
5224
5225
5226
5227
5228
5229
5230
5231
5232
5233
5234
5235
5236
5237
5238
5239
5240
5241
5242
5243
5244
5245
5246
5247
5248
5249
5250
5251
5252
5253
5254
5255
5256
5257
5258
5259
5260
5261
5262
5263
5264
5265
5266
5267
5268
5269
5270
5271
5272
5273
5274
5275
5276
5277
5278
5279
5280
5281
5282
5283
5284
5285
5286
5287
5288
5289
5290
5291
5292
5293
5294
5295
5296
5297
5298
5299
5300
5301
5302
5303
5304
5305
5306
5307
5308
5309
5310
5311
5312
5313
5314
5315
5316
5317
5318
5319
5320
5321
5322
5323
5324
5325
5326
5327
5328
5329
5330
5331
5332
5333
5334
5335
5336
5337
5338
5339
5340
5341
5342
5343
5344
5345
5346
5347
5348
5349
5350
5351
5352
5353
5354
5355
5356
5357
5358
5359
5360
5361
5362
5363
5364
5365
5366
5367
5368
5369
5370
5371
5372
5373
5374
5375
5376
5377
5378
5379
5380
5381
5382
5383
5384
5385
5386
5387
5388
5389
5390
5391
5392
5393
5394
5395
5396
5397
5398
5399
5400
5401
5402
5403
5404
5405
5406
5407
5408
5409
5410
5411
5412
5413
5414
5415
5416
5417
5418
5419
5420
5421
5422
5423
5424
5425
5426
5427
5428
5429
5430
5431
5432
5433
5434
5435
5436
5437
5438
5439
5440
5441
5442
5443
5444
//! Pulls of refs and their objects from another repository.
//!
//! - [`Repo::pull_local`] reads a local repository directly.
//! - [`Repo::pull`] fetches from an HTTP remote, or over ssh from a remote
//!   with an ssh address. With the `s3` feature, it also fetches from a
//!   bucket repository at an `s3://` address.
//! - [`Repo::pull_with_session`] reads through a
//!   [`PullSession`](crate::remote::PullSession) that the caller opened,
//!   under a [`PullTrust`](crate::verify::PullTrust) that the caller gives.
//!   It reads no remote section of the config.
//! - [`Repo::pull_collection`] pulls the refs of a collection from the
//!   remotes that serve it. For each ref, it selects the remote with the
//!   newest commit, and pulls from that remote as [`Repo::pull`] does.
//!
//! The pulls share [`PullOptions`], [`PullFlags`], [`PullStats`], the
//! ref-binding check, and the `.commitpartial` markers. [`PullVerify`] holds
//! the signature policy of each pull other than [`Repo::pull_with_session`].
//!
//! The sections from "Concurrency" to "Retries" apply to a pull from a
//! remote: [`Repo::pull`], [`Repo::pull_with_session`], and
//! [`Repo::pull_collection`].
//!
//! # Commit state
//!
//! The pull writes a zero-length `state/<commit>.commitpartial` marker for
//! each commit before it stores the commit object. It removes the marker
//! after the objects of the commit are published. So an interrupted pull
//! leaves the commit marked partial. A local pull writes no marker for a
//! commit that this repository holds complete.
//!
//! Two kinds of pull keep the marker in place, as the `ostree` command
//! does:
//!
//! - a [`COMMIT_ONLY`](PullFlags::COMMIT_ONLY) pull, which did not fetch
//!   the content of the commit.
//! - a pull from a remote with [`subpaths`](PullOptions::subpaths), which
//!   fetched part of the content.
//!
//! The pull does not write over an entry that is present at the name of a
//! marker. So the one-byte state that fsck writes stays after a pull over
//! the commit that it marked. The pull makes `state/` if it is absent. A
//! symlink or an entry that is not a directory at `state` fails the pull
//! with [`Error::InvalidFormat`] before it stages an object of the commit.
//!
//! If a pull returns an error, it removes the markers that it wrote for
//! commits that this repository does not hold. Its transaction published
//! no object, so such a marker guards nothing. A commit that this
//! repository holds keeps its marker, which the pull found in place over a
//! partial commit. A later [`prune`](Repo::prune) also removes each marker
//! whose commit is absent.
//!
//! # Marker durability
//!
//! The markers follow the `fsync` rule of the transaction of the pull:
//! `[core] fsync`, or `false` with
//! [`disable_fsync`](PullOptions::disable_fsync). With `fsync`, the pull
//! syncs `state/` after the create of each marker, and syncs `state/` one
//! time after the removal of its markers. It syncs no marker content,
//! because a marker of a pull has no content.
//!
//! The pull writes each marker before [`Transaction::commit`]. So the
//! `syncfs` at the start of publication makes the marker durable before the
//! first object rename, also with no `fsync`. A staged object enters
//! `objects/` in that rename, so no staged object is reachable before the
//! marker that guards it is durable.
//!
//! A local pull writes all its markers before the first import. A pull
//! from a remote writes the marker of each commit in the step that fetched
//! that commit.
//!
//! The removal of the markers is the last operation of the pull. The pull
//! removes all its markers in one pass, also when the removal of one marker
//! fails, and then returns the first error. The removal unlinks a symlink
//! or a FIFO at the name of a marker, and the target of a symlink stays. A
//! directory at the name of a marker gives [`Error::Io`] with `EISDIR`.
//! With no `fsync`, a crash right after a successful pull can leave a marker
//! on a complete commit. This costs availability, and the integrity of the
//! repository stays. Checkout refuses the commit until the next pull of it,
//! or a prune of it, clears the marker.
//!
//! # Concurrency
//!
//! A pull from a remote keeps as many steps in flight as its session admits:
//! [`PullSession::max_outstanding`](crate::remote::PullSession::max_outstanding).
//! [`Repo::pull`] gives the session the limit of
//! [`max_outstanding_fetches`](PullOptions::max_outstanding_fetches). If the
//! value is `None`, an HTTP pull keeps up to
//! [`max_outstanding`](crate::fetch::FetcherOptions::max_outstanding) of its
//! endpoint, and a pull over ssh keeps up to 8. Each step fetches one object
//! and stores it. The pull fills a free step from a plan of three classes, in
//! this order and with the matching fetch priority:
//!
//! - the commits: the requested tips, and their parents under
//!   [`depth`](PullOptions::depth)
//! - the scan: the dirtree and dirmeta objects that the walk waits for
//! - the content: the file objects, which nothing waits for
//!
//! The parts of a static delta drain after the commits and before the
//! scan. This drain order sets the order of the requests of a pull. The
//! fetcher admits as many requests at once as the pull has steps.
//!
//! A step has one fetch outstanding at a time, so the admission gate never
//! queues a request of one pull. If more callers share a [`Fetcher`] than
//! it admits, the priority of a class sets the order.
//!
//! With more than one step, the request order is not fixed: when a step
//! finishes, the free step takes the next queued object. The set of
//! requests and the class order are fixed.
//!
//! # Write permits
//!
//! A content step takes one of three write permits when the response head
//! arrives. It holds the permit for the whole body:
//!
//! - the read of the archive header.
//! - the payload stream into the object store.
//! - the read that finds the end of the stream.
//!
//! So a fast remote puts at most three concurrent writers on the
//! destination file system.
//!
//! The step takes the permit before it reads the body. So a wait for a
//! permit does not count against the progress clock of the fetcher. This
//! clock measures the silence since a read asked for bytes. The header
//! usually arrives in the first frame, so the permit spans that frame, the
//! payload, and the byte that ends the stream.
//!
//! A body that waits for a permit holds the bytes that it received,
//! unread. Over HTTP/2 these bytes are flow-control credit. The fetcher
//! gives a connection one stream window for each request that it admits.
//! So a waiting body holds its own credit, and the metadata stream that a
//! scan waits for receives over its own window.
//!
//! The stream source takes no write permit. Its session streams one body at a
//! time, and the depth of the pipeline bounds the stores that finish after
//! the end of their body.
//!
//! # Memory
//!
//! A content object streams into the object store through the 128 KiB
//! read buffer of its step. The step buffers the header alone, which
//! `MAX_FILE_HEADER_SIZE` caps at 1 MiB. All objects that a step stores
//! share its read buffer, from the remote or from a localcache repository.
//! Each object in flight also allocates the 16 KiB through which the
//! decoder reads its compressed input.
//!
//! The pull reads a metadata object (a commit, a dirtree, a dirmeta, or a
//! `.commitmeta`) whole, under the 128 MiB cap of the format,
//! [`MAX_METADATA_SIZE`](crate::MAX_METADATA_SIZE). The size of the buffer
//! comes from the length that the remote declares. A step holds one such
//! buffer, and the step of a commit holds two: the commit and its
//! `.commitmeta`.
//!
//! The metadata that a pull holds is at most two times that cap times the
//! step count.
//!
//! # Connections
//!
//! After the payload, a content step of an HTTP pull reads its response to
//! the end. One byte is enough, because nothing follows the final DEFLATE
//! block of an object. This read returns the connection to the pool.
//! HTTP/1.1 carries one request at a time, so a pull uses up to one
//! connection for each step.
//!
//! Bytes after the payload fail the pull. The stored form of a symlink has
//! the same rule.
//!
//! # Retries
//!
//! If a request of an HTTP pull fails with a retryable failure, the pull
//! sends it again, up to
//! [`max_retries`](crate::fetch::FetcherOptions::max_retries) times of the
//! endpoint. [`resolve_pull`](crate::endpoint::resolve_pull) sets 5. A body can
//! fail in transit: a cut connection, a silent peer, or a transfer slower
//! than the low-speed rule. Then the pull fetches it again from its first
//! byte. Each refetch spends one repeat of the same count.
//!
//! The bytes of the failed read stage nothing, and the pull removes their
//! temp file before the refetch. The pull does not fetch a body again if
//! it refused the body for its content. An object that spends the count
//! fails its step, and the first failed step ends the pull.
//!
//! # Bucket repository
//!
//! With the `s3` feature, [`Repo::pull`] reads a bucket repository at an
//! `s3://` address, and [`resolve_pull`](crate::endpoint::resolve_pull)
//! gives its endpoint. The pull is an HTTP pull through a fetcher that signs
//! each request with AWS Signature Version 4. The fetcher has one mirror,
//! the URL of the bucket repository, and follows no redirect.
//!
//! [`Repo::pull`] and [`Repo::remote_fetch_summary`] read `summary.sig`,
//! `summary`, and `config` through the bucket client of `ostrya-remote`,
//! which shares the fetcher of the pull. The bucket client asks for
//! `summary.sig` first. If the fetcher admits two requests at once, the
//! bucket client keeps the requests of `summary.sig` and `summary` in
//! flight together. The bucket client reads the S3
//! error document of a failed request. So a wrong secret key gives
//! [`Error::Remote`] with the S3 code `SignatureDoesNotMatch`, and an absent
//! bucket is an error, not a repository with no summary. A session that the caller opens for
//! [`Repo::pull_with_session`] reads these files through its fetcher.
//!
//! The credentials of the pull need the permissions `s3:GetObject` and
//! `s3:ListBucket` on the bucket. Without `s3:ListBucket`, AWS answers the
//! read of an absent key with 403 `AccessDenied` in place of 404. The pull
//! reads a 403 as an error, so an absent optional file, for example
//! `summary.sig` or a `.commitmeta` object, then fails the pull.
//!
//! The pull never asks a bucket repository for `_ostrya/refs/v1`.
//! [`Repo::pull_collection`] reads the refs of a remote at an `s3://`
//! address from its `summary` alone, through the bucket client, and skips a
//! bucket repository with no `summary`.
//!
//! [`Fetcher`]: crate::fetch::Fetcher

use std::collections::{HashMap, HashSet};
use std::io::Write;
use std::sync::atomic::{AtomicU32, AtomicU64, Ordering};
use std::sync::{Arc, Mutex};
use std::time::{Duration, Instant};

use futures_lite::AsyncReadExt;
use ostrya_core::{
    Checksum, Commit, ContentHasher, DirTree, ObjectName, ObjectType, Ref, RepoMode, Value,
};

use crate::error::{Error, Result};
use crate::file::FileKind;
use crate::refs::{ref_relpath, refspec_ref};
use crate::related::{self, RelatedRule};
use crate::repo::Repo;
use crate::repo_fs::{FsError, FsResultExt, RepoDir, RepoLayout, RootFile};
use crate::summary::AdvertisedDelta;
use crate::transaction::Transaction;
use crate::traverse::reaches_at_least;
use crate::verify::Payload;
use crate::write::FileMeta;

mod chain;
mod collection;
mod delta;
mod dependency;
pub(crate) mod drive;
#[doc(hidden)]
pub mod http;
mod source;
mod subpath;
mod verify;

pub(crate) use collection::collection_refs;
pub use collection::{
    CollectionPullEvent, CollectionPullOptions, CollectionPullRef, CollectionPullStats,
};

/// The chunk size of a streamed read of the payload of a content object.
const READ_CHUNK: usize = 128 * 1024;

/// The flags of a pull.
///
/// A bit set of the flag constants. Combine flags with `|`, and test a flag
/// with [`contains`](PullFlags::contains).
#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
pub struct PullFlags(u32);

impl PullFlags {
    /// The empty flag set.
    pub const NONE: PullFlags = PullFlags(0);
    /// The verification of the checksum of each imported object against its
    /// name.
    ///
    /// A mismatch fails a local pull with [`Error::ChecksumMismatch`]. The flag
    /// is off by default, as in the `ostree` command: a local source is
    /// trusted, and the pull links its objects without a read.
    /// [`Repo::pull_local`] states the reads that the flag adds.
    /// [`Repo::pull_collection`] turns the flag on for a local repository
    /// whose remote checks signatures.
    pub const UNTRUSTED: PullFlags = PullFlags(1 << 0);
    /// The import of the commit objects alone.
    ///
    /// The pull does not walk the trees, and it keeps the `.commitpartial`
    /// marker of each commit. A pull takes no dependency under this flag.
    pub const COMMIT_ONLY: PullFlags = PullFlags(1 << 1);
    /// The refusal of a regular file whose logical mode has bits outside
    /// `0775`.
    ///
    /// The flag refuses a world-writable, setuid, setgid, or sticky file with
    /// [`Error::Pull`]. A symlink is exempt. Each pull applies the check: to a
    /// local import, to a fetched loose object, and to the objects that a
    /// static delta part produces. A `bare-user-only` destination applies a
    /// stricter rule with or without this flag, as [`Repo::pull_local`] states.
    pub const BAREUSERONLY_FILES: PullFlags = PullFlags(1 << 2);
    /// The skip of the `ostree.ref-binding` check.
    ///
    /// Without this flag, the pull checks that the `ostree.ref-binding` list of
    /// each pulled commit names the ref that the pull reads. A commit with no
    /// binding key passes. A commit with a list that does not name the ref
    /// fails the pull with [`Error::Pull`]. The flag does not skip the
    /// collection-binding check of an `@ID:NAME` name in a pull without
    /// [`no_ref_writes`](PullOptions::no_ref_writes) ([`Repo::pull_local`],
    /// [`Repo::pull`]).
    /// [`Repo::pull_collection`] refuses this flag, because it always checks
    /// the bindings. To pull a tip with no
    /// collection binding, set
    /// [`CollectionPullOptions::allow_unbound`](crate::CollectionPullOptions::allow_unbound).
    pub const DISABLE_VERIFY_BINDINGS: PullFlags = PullFlags(1 << 3);
    /// A copy of each object, with no hardlink.
    ///
    /// An import from a source on another file system copies each object
    /// without this flag too. The pull copies a content object through its
    /// header, so the object gets the inode policy of this repository.
    pub const FORCE_COPY: PullFlags = PullFlags(1 << 4);
    /// A mirror of a remote: the refs of the remote in their collections,
    /// and a copy of the summary.
    ///
    /// [`Repo::pull`] writes a plain name as a ref of the collection that the
    /// summary of the remote states, and as a local ref under `refs/heads/`
    /// if the summary states no collection id. It writes an `@ID:NAME` name
    /// as without this flag. If [`refs`](PullOptions::refs) is empty, the
    /// pull takes each ref that the summary of the remote lists, in field 0
    /// and in its collection map. If the pull takes each such ref, it copies
    /// the `summary` and `summary.sig` bytes of the remote to this
    /// repository. [`Repo::pull`] states the rules in "Refs".
    ///
    /// [`Repo::pull_local`] ignores this flag. It writes the pulled refs under
    /// the prefix that [`remote`](PullOptions::remote) names, or as local refs
    /// if that is `None`. It writes the ref of an `@ID:NAME` name as the
    /// collection ref of `ID`, whatever `remote` is. An empty
    /// [`refs`](PullOptions::refs) list takes each ref of the source under
    /// `refs/heads`.
    pub const MIRROR: PullFlags = PullFlags(1 << 5);

    /// Returns the empty flag set.
    pub const fn empty() -> PullFlags {
        PullFlags(0)
    }

    /// Returns `true` if each bit of `other` is set in `self`.
    pub const fn contains(self, other: PullFlags) -> bool {
        self.0 & other.0 == other.0
    }

    /// Returns the raw bits.
    pub const fn bits(self) -> u32 {
        self.0
    }
}

impl std::ops::BitOr for PullFlags {
    type Output = PullFlags;

    fn bitor(self, rhs: PullFlags) -> PullFlags {
        PullFlags(self.0 | rhs.0)
    }
}

impl std::ops::BitOrAssign for PullFlags {
    fn bitor_assign(&mut self, rhs: PullFlags) {
        self.0 |= rhs.0;
    }
}

/// The commit that the timestamp of a fetched tip is compared against.
///
/// A pull refuses a tip that moves a ref back in time, so a downgrade cannot
/// arrive as an ordinary update. The pull refuses only a strictly older
/// timestamp: an equal timestamp passes.
#[derive(Debug, Clone, Default, PartialEq, Eq)]
pub enum TimestampCheck {
    /// No check.
    #[default]
    Off,
    /// The commit that the ref names in this repository now.
    ///
    /// The check reads the ref that the pull writes. Under the
    /// `[core] collection-id` of this repository, a collection pull reads
    /// `refs/heads/<name>`, the path that [`Repo::resolve_ref_tip`] reads.
    ///
    /// A ref that this repository does not hold passes.
    CurrentRef,
    /// A given commit.
    ///
    /// A pull from a remote that has at least one target reads the commit one
    /// time, so this repository must hold it. The pull reads it after the
    /// `summary`, the `config`, and the ref files of the remote, and before it
    /// fetches a delta index, a static delta superblock, a `.commitmeta`, or
    /// an object. If this repository does not hold the commit, the pull fails
    /// with [`Error::ObjectNotFound`] at that point. A pull with no target
    /// reads no commit. [`Repo::pull_local`] makes no timestamp check and
    /// reads no commit.
    Rev(Checksum),
}

/// The signature policy of a pull.
///
/// Each field overrides the remote config key of the same name. If a field is
/// `None`, the pull takes the value from the `[remote "NAME"]` section of the
/// remote:
///
/// - `gpg-verify`, default `true`.
/// - `gpg-verify-summary`, default `false`.
/// - `sign-verify` and `sign-verify-summary`, both default off.
///
/// [`Repo::pull`] applies these defaults also to a remote that the config
/// does not describe. [`Repo::pull_local`] reads the section of the remote
/// that [`PullOptions::remote`] names. If the local pull names no remote, or
/// the config has no section for the remote, a `None` field gives no check.
/// The `pull-local` command of `ostree` reads none of these keys.
///
/// A `Some` field sets the policy whatever the config says, so `Some(false)`
/// turns a configured check off. `Some(true)` on a sign-api field selects
/// each engine of this build, as `sign-verify=true` does.
///
/// The keys come from the config section of a remote. If a pull names no
/// remote and asks for a verification, it fails with [`Error::Pull`] before
/// it fetches anything. With [`PullOptions::trust_group`], a local pull that
/// names no remote takes its commit keys from the trust group, and refuses a
/// summary field `Some(true)` with [`Error::Pull`].
///
/// A remote with the key `trust=NAME` takes its commit policy from the trust
/// group `[ex-ostrya trust "NAME"]`, and each pull reads the key.
/// [`PullOptions::trust_group`] names a trust group for one pull, and wins
/// over the key. With a trust group, the pull refuses `Some(true)` in
/// [`gpg`](PullVerify::gpg) and in [`sign`](PullVerify::sign) with
/// [`Error::InvalidInput`]. `Some(false)` in one of the two fields turns that
/// commit axis of the group off. The two summary fields override the summary
/// keys of the remote, as they do without a trust group.
/// [`PullTrust::from_remote`](crate::verify::PullTrust::from_remote) states
/// the rules of the remote keys beside `trust`.
///
/// # Keys
///
/// - GPG: the trusted set of the remote. The set holds the keyring of the
///   remote and the keyrings that `gpgkeypath` names. The keyring of the
///   remote is the `<remote>.trustedkeys.gpg` of the repository, or, only
///   when that file is absent, the `<remote>.trustedkeys.gpg` of the remotes
///   directory of the handle ([`Repo::remotes_dir`]). The global trusted
///   directory takes part only when neither `<remote>.trustedkeys.gpg`
///   exists.
/// - The sign api: a value of `sign-verify` is a boolean or a list of engine
///   names. The keys of an engine are its `verification-<engine>-key` and
///   `verification-<engine>-file` entries and the system key store, less the
///   revoked set of the store.
/// - A trust group: the commit keys are the keys that the group names, and
///   nothing else. The repository keyring `<repo>/<remote>.trustedkeys.gpg`,
///   the keyring of the remotes directory, the global trusted directory, and
///   the system key store do not verify a commit of a remote with `trust`.
///   So the keys that a GPG import for the remote writes to the repository
///   keyring do not apply to its commits. The GPG check of the summary still
///   reads these sources.
///
/// The GPG axis and the sign-api axis are independent. If a policy asks for
/// both, the pull verifies both. In the sign-api axis, one engine that
/// reports a valid signature is sufficient, so `sign-verify=ed25519;spki`
/// accepts a commit signed by either engine. The `ostree` command does the
/// same.
///
/// # When the pull verifies
///
/// The pull verifies the summary when it has the summary and its signature.
/// The verification comes before the pull reads the refs or the deltas of
/// the summary. If the policy covers the summary and the source has no
/// `summary` or no `summary.sig`, the pull fails with [`Error::Signature`].
///
/// The policy belongs to the pull. The pull verifies each target, each
/// parent that a depth pull follows, and each commit of a chain of static
/// deltas, also a commit that this repository already holds. It verifies no
/// dependency, unless the dependency also has one of these roles. The section
/// `# Dependencies` of [`Repo::pull`] states the reason. A commit that fails
/// the policy fails the pull with [`Error::Signature`].
///
/// A pull from a remote verifies a commit outside a chain of static deltas in
/// the step that fetched it. The verification comes before the pull stages
/// the bytes and before it requests the tree.
///
/// With a [`static_deltas`](PullOptions::static_deltas) list, discovery
/// verifies each commit of a chain before the transaction opens. It reads the
/// commit from the superblock of its step, so it fetches no `.commit` object.
///
/// - An intermediate commit that no requested ref names gets the signature
///   checks alone. Discovery 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.
/// - A target commit gets the signature checks. Then it gets the ref-binding
///   check and the timestamp check of each requested ref that names it, in
///   the order of the refs.
/// - If a requested ref names an intermediate commit, discovery also makes
///   the ref-binding check and the timestamp check of that ref.
///
/// [`Repo::pull_local`] makes no timestamp check.
///
/// A commit that discovery refuses costs the superblocks and the
/// `.commitmeta` files that discovery fetched, and the pull fetches no part.
/// The pull does not verify a commit of a chain a second time. If the last
/// plan of discovery drops a commit, the commit gets its checks when the pull
/// fetches it.
///
/// The pull verifies the superblock of the static delta of a target before it
/// fetches a part of the delta. For a chain, discovery verifies the superblock
/// of each step before it verifies the commit of the step. Only the sign-api axis
/// applies to a superblock, because a static delta carries sign-api
/// signatures alone. A superblock with no signature of an engine of the
/// policy passes, and the commit that the delta gives still gets its checks.
/// The removal of a signature from a delta thus gives no gain: the delta map
/// of the summary or of the delta index names the superblock by its digest,
/// the superblock names each object that the delta gives, and the commit gets
/// the checks of its role.
/// If each such signature of a superblock is from a key that is not trusted,
/// the pull fails with [`Error::Signature`].
///
/// The pull verifies no superblock of the static delta of a dependency. The
/// superblock gives the dependency commit, and field 2 names that commit by
/// its checksum. The pull compares the checksum of the commit that the
/// superblock gives with that checksum. A dependency that is also a target,
/// or that a chain of static deltas makes, keeps the checks of that role.
///
/// A local pull verifies the commits and the summary before the transaction
/// opens, so a source that the policy refuses imports nothing.
#[derive(Debug, Clone, Copy, Default, PartialEq, Eq)]
pub struct PullVerify {
    /// A GPG signature on each commit that the pull verifies, from a trusted
    /// keyring of the remote.
    ///
    /// `# When the pull verifies` names these commits.
    pub gpg: Option<bool>,
    /// A GPG signature on the summary of the remote, from the same keyrings.
    pub gpg_summary: Option<bool>,
    /// A sign-api signature on each commit that the pull verifies, from a
    /// trusted key.
    ///
    /// `# When the pull verifies` names these commits. A trusted key comes
    /// from the config of the remote or from the system key store.
    pub sign: Option<bool>,
    /// A sign-api signature on the summary of the remote, from a trusted key.
    pub sign_summary: Option<bool>,
}

/// The options of a pull.
///
/// The defaults give the behavior of [`Repo::pull_local`]. Each field that
/// only a pull from a remote reads defaults to the behavior of a local pull.
///
/// # Fields for each kind of pull
///
/// - Each pull reads [`refs`](PullOptions::refs),
///   [`remote`](PullOptions::remote),
///   [`no_ref_writes`](PullOptions::no_ref_writes),
///   [`flags`](PullOptions::flags), [`depth`](PullOptions::depth),
///   [`localcache_repos`](PullOptions::localcache_repos),
///   [`disable_fsync`](PullOptions::disable_fsync),
///   [`per_object_fsync`](PullOptions::per_object_fsync),
///   [`disable_static_deltas`](PullOptions::disable_static_deltas),
///   [`require_static_deltas`](PullOptions::require_static_deltas),
///   [`static_deltas`](PullOptions::static_deltas),
///   [`verify`](PullOptions::verify), and
///   [`trust_group`](PullOptions::trust_group).
/// - [`Repo::pull_collection`] takes the collection id as an argument, and
///   states the fields that it refuses.
/// - A pull from a remote also reads [`subpaths`](PullOptions::subpaths),
///   [`overrides`](PullOptions::overrides),
///   [`max_outstanding_fetches`](PullOptions::max_outstanding_fetches),
///   [`timestamp_check`](PullOptions::timestamp_check), and
///   [`progress`](PullOptions::progress). A local pull refuses `subpaths`.
/// - [`Repo::pull_with_session`] refuses an empty `refs`, a `verify` other
///   than the default, a set `trust_group`, `overrides` other than the
///   default, and a set `max_outstanding_fetches`.
#[derive(Debug, Clone, Default)]
pub struct PullOptions {
    /// The ref names to pull.
    ///
    /// With an empty list, a local pull takes each ref of the source under
    /// `refs/heads`. [`Repo::pull`] takes each ref that the summary of the
    /// remote lists under [`MIRROR`](PullFlags::MIRROR). Otherwise it takes
    /// the configured `branches` of the remote and the refs of the summary
    /// that the `pull-branches` key of the remote selects, as
    /// [`Remote::pull_branches`](crate::config::Remote::pull_branches)
    /// states. [`Repo::pull_with_session`] reads neither key,
    /// and refuses an empty list with [`Error::InvalidInput`].
    ///
    /// A local pull reads each name as a revision of the source, `@ID:NAME`
    /// and a `^` suffix included, as [`Repo::pull_local`] states.
    /// [`Repo::pull`] and [`Repo::pull_with_session`] read each name as a ref
    /// `NAME` or a collection ref `@ID:NAME`, and refuse each other form, as
    /// [`Repo::pull`] states in "Refs". They take a name that occurs two
    /// times one time.
    pub refs: Vec<String>,
    /// The remote name under which the pull writes the refs
    /// (`refs/remotes/<remote>/<ref>`).
    ///
    /// For a local pull, the name also selects the `[remote "NAME"]` section
    /// whose verification keys apply (see [`PullVerify`]).
    ///
    /// If the value is `None`, a local pull and [`Repo::pull_with_session`]
    /// write local refs under `refs/heads/`. [`Repo::pull`] then writes the
    /// refs under the name of the remote. A pull from a remote does not read
    /// the value under [`MIRROR`](PullFlags::MIRROR), and writes each plain
    /// name as [`Repo::pull`] states in "Refs". Each
    /// pull writes the ref of an `@ID:NAME` name as the collection ref of
    /// `ID`, whatever the value. Under
    /// [`no_ref_writes`](PullOptions::no_ref_writes) the pull writes no ref,
    /// and the name still selects the ref that the pull reads.
    ///
    /// [`Repo::pull`] and [`Repo::pull_with_session`] refuse a name that
    /// [`valid_remote_name`](crate::config::valid_remote_name) refuses, with
    /// [`Error::InvalidInput`], before the first request. They refuse it also
    /// under `MIRROR`. [`Repo::pull_local`] refuses such a name with the same
    /// error, before it reads the source repository or a keyring. It refuses
    /// it also under `no_ref_writes`.
    pub remote: Option<String>,
    /// The option to write no ref.
    ///
    /// The pull stores the objects and the detached metadata, and clears the
    /// `.commitpartial` marker of each commit that it completes, as without
    /// the option. The caller writes the refs.
    ///
    /// [`PullStats`] does not report the commits of a pull. A local pull
    /// resolves each name in [`refs`](PullOptions::refs) on the source with
    /// revision syntax. So a caller pins the commit of a ref when it gives the
    /// checksum as the name.
    ///
    /// A pull from a remote resolves each name as a ref name, through the
    /// summary or the ref file of the remote. There, a checksum names no
    /// commit and fails with [`Error::RefNotFound`], unless the remote holds a
    /// ref of that name.
    ///
    /// A pull from a remote still reads the ref that it writes without the
    /// option. Delta discovery takes the commit of that ref as the source of a
    /// delta, and [`TimestampCheck::CurrentRef`] compares against it. A local
    /// pull reads that ref only for delta discovery, under
    /// [`require_static_deltas`](PullOptions::require_static_deltas) or with a
    /// list of [`static_deltas`](PullOptions::static_deltas). Under this
    /// option, a [`MIRROR`](PullFlags::MIRROR) pull of each ref copies no
    /// `summary` and no `summary.sig`.
    ///
    /// If a pulled commit has detached metadata, the pull takes the update
    /// lock to write it, as [`Transaction::commit`] does. If the caller holds
    /// an [`UpdateGuard`](crate::UpdateGuard) of the destination during the
    /// pull, the pull waits for that guard until the lock timeout.
    pub no_ref_writes: bool,
    /// The flag set.
    pub flags: PullFlags,
    /// The number of parents of each pulled commit that the pull follows.
    ///
    /// `0` takes the named commit alone, and `-1` takes the whole ancestry
    /// that the source holds. The pull follows the chain of each ref to this
    /// depth separately, so the order of the refs does not change the
    /// commits. A value below `-1` is [`Error::InvalidInput`], and the pull
    /// writes no object and no ref.
    ///
    /// A pull takes each dependency at depth 0, whatever this value is. It
    /// follows the dependencies of each commit that it takes, the parents
    /// included. [`Repo::pull`] and [`Repo::pull_local`] state the rules in
    /// "Dependencies".
    pub depth: i32,
    /// More local repositories that supply an object that the source does not
    /// hold, in order.
    ///
    /// A pull from a remote reads each object from these repositories before
    /// the network, through the import path of a local pull. It verifies the
    /// checksum of each such object.
    pub localcache_repos: Vec<Repo>,
    /// The option to turn off each sync of this pull.
    ///
    /// The option turns off these syncs:
    ///
    /// - the per-object syncs.
    /// - the `syncfs` and the directory syncs of publication.
    /// - the syncs of the detached metadata of each pulled commit, of the ref
    ///   writes, and of the summary that a mirror pull copies.
    ///
    /// `false` leaves `[core] fsync` in control. The option never turns a sync
    /// on, and it changes no byte that the pull writes.
    /// [`Transaction::commit`] states the sync sequence.
    pub disable_fsync: bool,
    /// The option to sync the file of each content object that this pull
    /// stages.
    ///
    /// The pull syncs each file when it stages it, whatever
    /// `[core] per-object-fsync` says, and `false` leaves the key in control.
    /// The pull does not sync a metadata object or a hardlinked object
    /// separately.
    /// If fsync is off, from `[core] fsync` or from
    /// [`disable_fsync`](PullOptions::disable_fsync), the pull syncs nothing.
    /// [`Transaction::commit`] states the sync sequence.
    pub per_object_fsync: bool,
    /// The parts of the tree of each commit that a pull from a remote fetches.
    ///
    /// Each value is an absolute path. An empty list fetches the whole tree.
    /// A path through a directory fetches the dirtree and the dirmeta of that
    /// directory and no sibling of it.
    ///
    /// The pull fetches the whole entry that the last component of the path
    /// names. Several paths fetch the union. The pull always fetches the root
    /// dirtree and dirmeta, and `/` fetches nothing more.
    ///
    /// A pull with subpaths leaves each commit that it marks partial, and a
    /// later pull without subpaths completes it. A pull with subpaths fetches
    /// no dependency. A value that does not start
    /// with `/`, the empty value included, fails the pull with
    /// [`Error::Pull`]. [`Repo::pull_local`] refuses the option with
    /// [`Error::Unsupported`].
    ///
    /// The pull splits each value on `/` after its leading `/`, and keeps each
    /// component, also an empty one. A component `.` or `..`, or an empty
    /// component from a doubled `/`, matches no entry, because no dirtree entry
    /// has such a name. `/sub/` fetches the `sub` dirtree and dirmeta and
    /// nothing in them. A file named by a component that is not the last, and
    /// a name that the dirtree does not hold, end the path there.
    ///
    /// Into an `archive` repository, a subpath pull takes no delta and fetches
    /// the subpaths loose, unless it requires static deltas. Into another
    /// mode, the pull applies a delta that it finds whole, and the walk after
    /// its last part finds the subpaths present.
    pub subpaths: Vec<String>,
    /// The overrides of the endpoint resolution of [`Repo::pull`]: the values
    /// of [`EndpointOverrides`](crate::endpoint::EndpointOverrides).
    ///
    /// [`Repo::pull`] gives them to
    /// [`resolve_pull`](crate::endpoint::resolve_pull) with this repository
    /// and the name of the remote. A value of the caller wins over its remote
    /// key. A relative path of the caller is relative to the working
    /// directory, and a relative path of a remote key is relative to the
    /// repository root or to the remotes directory, as
    /// [`Remote`](crate::config::Remote#paths) states. `resolve_pull` refuses the push fields `push_token_file`
    /// and `push_user` with [`Error::InvalidInput`]. The default value
    /// overrides nothing, and the pull defaults then apply: 5 retries, 8
    /// requests in flight, and a low speed limit of 1000 bytes per second for
    /// 30 seconds.
    ///
    /// [`Repo::pull_with_session`] refuses a value other than the default
    /// with [`Error::InvalidInput`], because its session selects the server.
    pub overrides: crate::endpoint::EndpointOverrides,
    /// The number of fetches that a pull from a remote keeps in flight.
    ///
    /// For an HTTP endpoint and an S3 endpoint, a value replaces
    /// [`max_outstanding`](crate::fetch::FetcherOptions::max_outstanding) of
    /// the endpoint, and `None` keeps the value of the endpoint.
    /// [`resolve_pull`](crate::endpoint::resolve_pull) sets 8. For an ssh
    /// endpoint, the value sets
    /// [`max_outstanding`](crate::remote::StreamSessionOptions::max_outstanding)
    /// of the stream session, and `None` is 8.
    ///
    /// [`Repo::pull_with_session`] refuses a value that is set with
    /// [`Error::InvalidInput`]. The limit of its session applies.
    pub max_outstanding_fetches: Option<usize>,
    /// The commit that the timestamp of a fetched tip is compared against.
    pub timestamp_check: TimestampCheck,
    /// The option to fetch each object loose and ignore static deltas.
    ///
    /// This option wins over
    /// [`require_static_deltas`](PullOptions::require_static_deltas): a pull
    /// that asks for no delta looks for none, so it finds nothing to require. A
    /// local pull reads a delta only if it requires one or applies a list of
    /// [`static_deltas`](PullOptions::static_deltas). So with this option, a
    /// local pull reads no delta. The option also applies to the delta of
    /// each dependency. [`Repo::pull`] states the static delta rules of a
    /// pull.
    ///
    /// A pull refuses this option together with
    /// [`static_deltas`](PullOptions::static_deltas).
    pub disable_static_deltas: bool,
    /// The option to require a static delta for each commit that the pull
    /// looks up.
    ///
    /// If the source serves no summary, the pull fails with [`Error::Pull`].
    /// With a summary, the pull refuses with [`Error::Pull`] a commit that this
    /// repository does not hold complete, in two cases:
    ///
    /// - the delta index and the summary name no delta that the pull can take.
    /// - the superblock of the chosen delta is absent.
    ///
    /// The pull leaves a from-scratch delta alone if the ref names a commit
    /// that this repository holds complete, or names the target commit. Such a
    /// delta satisfies the requirement, and that pull fetches its objects
    /// loose. The pull does not look up a commit that this repository holds
    /// complete, so a pull with nothing to fetch is not refused.
    ///
    /// With a list in [`static_deltas`](PullOptions::static_deltas), a pull
    /// needs no summary. It fails with [`Error::Pull`] for a target commit
    /// that no chain of the list reaches. A listed delta from scratch to the
    /// target that the rule above leaves alone counts as found: the pull does
    /// not fail, and fetches that target loose.
    ///
    /// The requirement also applies to each dependency that the pull fetches
    /// and that this repository does not hold complete. A dependency with no
    /// delta fails the pull with [`Error::Pull`], and the pull moves no ref.
    /// The message is `Static deltas required, but none found for <name> of
    /// <ref> to <checksum>`. `<ref>` is the first target whose chain names
    /// the dependency, as the pull names it, and `<name>` is the name of the
    /// entry nearest to the tip of that chain. If no chain of a target names
    /// the dependency, `<ref>` is the first target of the pull. `<name>` then
    /// comes from the commit of the pull with the lowest checksum that names
    /// the dependency, and is the lowest name if that commit has two entries
    /// for it. `<checksum>` is the dependency. A from-scratch delta that the
    /// rules of a dependency leave alone counts as found. With a list, the
    /// pull takes one entry of the list to the dependency, and plans no chain
    /// for it. [`Repo::pull`] states the search, under `# Static deltas`.
    ///
    /// A local pull reads a delta from the source directory only under this
    /// option or with a list. [`Repo::pull_local`] states the static delta
    /// rules of a local pull. The fetch counters of [`PullStats`] count the
    /// files that the local pull reads.
    ///
    /// A local pull reads the summary of the source and its signature under
    /// the size cap of a summary, 64 MiB. It refuses a file of the source that
    /// is not a regular file, so no read waits on a FIFO.
    pub require_static_deltas: bool,
    /// A list of static deltas that replaces the delta search of the pull.
    ///
    /// `None` keeps the search that [`Repo::pull`] and [`Repo::pull_local`]
    /// state. The list can come from [`Summary::static_deltas`] of a ref
    /// listing. Each entry names the source commit, the target commit, and the
    /// SHA-256 digest of the superblock of one delta. The pull ignores an
    /// entry that is equal to an earlier entry.
    ///
    /// The pull refuses these lists with [`Error::InvalidInput`], before its
    /// first request and before its transaction opens:
    ///
    /// - a list with two entries that have the same source and target and
    ///   different digests.
    /// - a list together with
    ///   [`disable_static_deltas`](PullOptions::disable_static_deltas).
    /// - a list together with a [`subpaths`](PullOptions::subpaths) list that
    ///   is not empty. [`Repo::pull_local`] refuses subpaths with
    ///   [`Error::Unsupported`] before this check.
    ///
    /// Each pull applies the chain with the fewest steps to each target
    /// commit, by the rules of [`Repo::pull`] under `# Static deltas`.
    /// [`Repo::pull_local`] states the rules of a local pull under the same
    /// heading. A [`COMMIT_ONLY`](PullFlags::COMMIT_ONLY) pull ignores the
    /// list.
    ///
    /// [`Summary::static_deltas`]: crate::Summary::static_deltas
    pub static_deltas: Option<Vec<AdvertisedDelta>>,
    /// The signature policy of this pull, over the configured policy of the
    /// remote.
    ///
    /// [`Repo::pull_with_session`] refuses a value other than the default
    /// with [`Error::InvalidInput`]. Its
    /// [`PullTrust`](crate::verify::PullTrust) holds the keys.
    pub verify: PullVerify,
    /// The name of the trust group `[ex-ostrya trust "NAME"]` that supplies
    /// the commit keys of this pull.
    ///
    /// The group sets the commit policy of the pull, as the remote key
    /// [`trust`](crate::config::Remote::trust) does. The field wins over that
    /// key, and the pull then does not read the key. [`Repo::pull`],
    /// [`Repo::pull_collection`], and [`Repo::pull_local`] read the field. A
    /// local pull with the field needs no [`remote`](PullOptions::remote).
    ///
    /// The rules of a trust group apply, as
    /// [`PullTrust::from_remote`](crate::verify::PullTrust::from_remote)
    /// states them for the key:
    ///
    /// - `Some(true)` in [`PullVerify::gpg`] or [`PullVerify::sign`] is
    ///   refused, and `Some(false)` turns that commit axis of the group off.
    /// - The section of the remote of the pull must not turn on a commit check,
    ///   and must not hold a key source that no summary check reads.
    /// - The summary keys of the section of the remote set the summary policy,
    ///   and the summary fields of [`verify`](PullOptions::verify) override
    ///   them.
    ///
    /// A local pull that names no remote checks no summary, because no
    /// section supplies the summary keys. It refuses `Some(true)` in
    /// [`PullVerify::gpg_summary`] and in [`PullVerify::sign_summary`] with
    /// [`Error::Pull`].
    ///
    /// [`Repo::pull_with_session`] refuses a value that is set with
    /// [`Error::InvalidInput`]. Its [`PullTrust`](crate::verify::PullTrust)
    /// holds the keys.
    ///
    /// # Errors
    ///
    /// Each pull that reads the field makes these checks before it reads a
    /// key source, sends a request, or reads the source of a local pull:
    ///
    /// - [`Error::InvalidInput`] if the name is empty or holds a `"` or a
    ///   control character, or if the config has no group of the name.
    /// - [`Error::InvalidFormat`] if the group fails the check of a trust
    ///   group.
    /// - [`Error::InvalidInput`] if [`PullVerify::gpg`] or [`PullVerify::sign`]
    ///   is `Some(true)`.
    /// - [`Error::Pull`] if the pull names no remote, and
    ///   [`PullVerify::gpg_summary`] or [`PullVerify::sign_summary`] is
    ///   `Some(true)`.
    /// - [`Error::InvalidFormat`] if the section of the remote turns on a
    ///   commit check or holds a key source that no summary check reads.
    pub trust_group: Option<String>,
    /// The handle to which a pull from a remote adds its live counters.
    ///
    /// A caller can show the progress of the pull while it runs. `None` keeps
    /// the counts in the counters of the pull alone. A local pull does not use
    /// the handle.
    pub progress: Option<PullProgress>,
}

/// Applies the durability options of a pull to its transaction.
fn apply_durability(txn: &mut Transaction, opts: &PullOptions) {
    if opts.disable_fsync {
        txn.set_fsync(false);
    }
    if opts.per_object_fsync {
        txn.set_per_object_fsync(true);
    }
}

/// The counts of what a pull imported and fetched.
///
/// The import counters and the written counters cover the objects that the
/// pull staged. An object that the destination already held does not count.
/// The plan of a [`COMMIT_ONLY`](PullFlags::COMMIT_ONLY) pull is the commit
/// objects alone, so the pull reports those and no content. The objects of
/// the dependencies that a pull takes count as the other objects of the
/// pull.
#[derive(Debug, Clone, Copy, Default, PartialEq, Eq)]
pub struct PullStats {
    /// The number of metadata objects that the pull imported.
    pub metadata_imported: u32,
    /// The number of content objects that the pull imported.
    pub content_imported: u32,
    /// The total on-disk size of the imported content objects.
    ///
    /// The total counts an object whether the pull wrote its bytes or shared
    /// them by reflink or by hardlink. It is the storage that those objects
    /// use, so it can be larger than the space that the pull used.
    pub content_bytes_written: u64,
    /// The total payload size of the regular files that the pull wrote.
    ///
    /// The size is before the compression that the destination mode applies.
    /// A symlink, an object shared by hardlink, and an object that a static
    /// delta produced add nothing. The `ostree` command reports this figure as
    /// the content written.
    pub content_bytes_unpacked: u64,
    /// The number of metadata requests of a pull from a remote.
    ///
    /// The count is the metadata fetched, as the `ostree` command counts it.
    /// The count includes each loose metadata object and `.commitmeta` that
    /// the remote served. It also includes each request for a delta index or a
    /// delta superblock, whatever the remote answered.
    ///
    /// A local pull that
    /// [requires static deltas](PullOptions::require_static_deltas), or that
    /// applies a list of [`static_deltas`](PullOptions::static_deltas), counts
    /// the same files when it reads them from the source. Each other local
    /// pull counts zero.
    pub metadata_fetched: u32,
    /// The number of content objects that a pull fetched loose from the
    /// remote.
    ///
    /// An object from a localcache repository does not count. A local pull
    /// counts as [`metadata_fetched`](PullStats::metadata_fetched) states.
    pub content_fetched: u32,
    /// The number of static delta parts that a pull fetched as files.
    ///
    /// A part that the superblock carries inline does not count. A local pull
    /// counts as [`metadata_fetched`](PullStats::metadata_fetched) states.
    pub delta_parts: u32,
    /// The bytes of the successful response bodies that a pull from a remote
    /// read.
    ///
    /// The count starts after the summary, the config, and the ref files of
    /// the remote, and it includes retried bodies. A local pull that requires
    /// static deltas, or that applies a list of static deltas, counts the
    /// stored size of each file that the other fetch counters count, and of
    /// each part file. Each other local pull counts zero.
    ///
    /// A pull over ssh counts the payload bytes of each body that it reads.
    /// So the HTTP count and the ssh count agree for the same files.
    pub bytes_transferred: u64,
    /// The run time of the pull.
    pub elapsed: Duration,
}

/// The live counters of pulls from a remote.
///
/// A caller reads the counters while the pulls run. The caller sets a clone of
/// the handle in [`PullOptions::progress`], and reads
/// [`snapshot`](PullProgress::snapshot) from another task or thread. A pull
/// adds to the counters of the handle and never sets them to zero. A local
/// pull does not use the handle.
///
/// If several pulls share a handle, or one pull after another uses it, the
/// handle shows the sum of their counters. Its `scanning` state is on while
/// any of the pulls scans. A caller that wants the progress of one pull gives
/// that pull a handle of its own.
///
/// The [`PullStats`] of a pull come from its own counters, whatever the handle
/// holds. Each count is one relaxed atomic add to those counters, and one more
/// to the handle if the pull has one. The pull counts the transferred bytes
/// once for each data frame of a response body.
#[derive(Debug, Clone, Default)]
pub struct PullProgress {
    inner: Arc<ProgressCounters>,
}

/// The counters behind a [`PullProgress`], and the counters of one pull.
#[derive(Debug, Default)]
pub(crate) struct ProgressCounters {
    /// The byte count, shared with the fetcher of the pull, which adds the
    /// bytes of each body.
    transferred: Arc<AtomicU64>,
    metadata_fetched: AtomicU32,
    content_fetched: AtomicU32,
    objects_done: AtomicU32,
    objects_total: AtomicU32,
    /// The number of pulls that scan: 0 or 1 in the counters of one pull.
    scanning: AtomicU32,
    delta_parts_fetched: AtomicU32,
    delta_parts_total: AtomicU32,
    delta_bytes_fetched: AtomicU64,
    delta_bytes_total: AtomicU64,
}

/// The counters of one pull: its own counters, which its [`PullStats`] read,
/// and the handle of the caller, which gets the same additions.
///
/// A local pull has no handle of the caller.
pub(crate) struct PullCounters {
    own: ProgressCounters,
    caller: Option<Arc<ProgressCounters>>,
}

impl PullCounters {
    /// Creates the counters of a pull that starts now in the scanning state.
    ///
    /// The counters also count into `caller` if it is present.
    pub(crate) fn new(caller: Option<&PullProgress>) -> PullCounters {
        let counters = PullCounters {
            own: ProgressCounters::default(),
            caller: caller.map(|progress| Arc::clone(&progress.inner)),
        };
        counters.each(|c| {
            c.scanning.fetch_add(1, Ordering::Relaxed);
        });
        counters
    }

    /// Runs `f` on the own counters of the pull, then on those of the caller.
    fn each(&self, f: impl Fn(&ProgressCounters)) {
        f(&self.own);
        if let Some(caller) = &self.caller {
            f(caller);
        }
    }

    /// Returns the byte counters to which the fetcher of the pull adds the
    /// bytes of each body.
    pub(crate) fn transferred_sinks(&self) -> Vec<Arc<AtomicU64>> {
        let mut sinks = vec![Arc::clone(&self.own.transferred)];
        if let Some(caller) = &self.caller {
            sinks.push(Arc::clone(&caller.transferred));
        }
        sinks
    }

    /// Takes back each byte counted so far from both counter sets, so the
    /// count starts again from zero.
    ///
    /// No request is in flight when a pull calls this function.
    pub(crate) fn restart_transferred(&self) {
        let counted = self.own.transferred.swap(0, Ordering::Relaxed);
        if let Some(caller) = &self.caller {
            caller.transferred.fetch_sub(counted, Ordering::Relaxed);
        }
    }

    /// Counts one metadata request that the `ostree` command counts as
    /// metadata fetched.
    pub(crate) fn metadata_fetched(&self) {
        self.each(|c| {
            c.metadata_fetched.fetch_add(1, Ordering::Relaxed);
        });
    }

    /// Counts one content object fetched loose.
    pub(crate) fn content_fetched(&self) {
        self.each(|c| {
            c.content_fetched.fetch_add(1, Ordering::Relaxed);
        });
    }

    /// Counts one finished unit of work.
    pub(crate) fn object_done(&self) {
        self.each(|c| {
            c.objects_done.fetch_add(1, Ordering::Relaxed);
        });
    }

    /// Adds `bytes` read from a local source to the transferred count.
    ///
    /// The fetcher of an HTTP pull adds to this count itself.
    pub(crate) fn add_transferred(&self, bytes: u64) {
        self.each(|c| {
            c.transferred.fetch_add(bytes, Ordering::Relaxed);
        });
    }

    /// Counts one delta part fetched as a file, of declared size `size`.
    pub(crate) fn part_fetched(&self, size: u64) {
        self.each(|c| {
            c.delta_parts_fetched.fetch_add(1, Ordering::Relaxed);
            c.delta_bytes_fetched.fetch_add(size, Ordering::Relaxed);
        });
    }

    /// Adds `parts` delta parts of declared sizes `bytes` to the totals.
    pub(crate) fn parts_planned(&self, parts: u32, bytes: u64) {
        self.each(|c| {
            c.delta_parts_total.fetch_add(parts, Ordering::Relaxed);
            c.delta_bytes_total.fetch_add(bytes, Ordering::Relaxed);
        });
    }

    /// Sets the total units of work of the pull to `total` and its scanning
    /// state to `scanning`.
    ///
    /// The sums of the caller move by the same change.
    pub(crate) fn report(&self, total: u32, scanning: bool) {
        let before = self.own.objects_total.swap(total, Ordering::Relaxed);
        let was = self
            .own
            .scanning
            .swap(u32::from(scanning), Ordering::Relaxed);
        if let Some(caller) = &self.caller {
            caller
                .objects_total
                .fetch_add(total.wrapping_sub(before), Ordering::Relaxed);
            match (was, scanning) {
                (0, true) => caller.scanning.fetch_add(1, Ordering::Relaxed),
                (1, false) => caller.scanning.fetch_sub(1, Ordering::Relaxed),
                _ => 0,
            };
        }
    }

    /// Returns the own count of metadata fetched of the pull.
    pub(crate) fn metadata(&self) -> u32 {
        self.own.metadata_fetched.load(Ordering::Relaxed)
    }

    /// Returns the own count of content objects fetched of the pull.
    pub(crate) fn content(&self) -> u32 {
        self.own.content_fetched.load(Ordering::Relaxed)
    }

    /// Returns the own count of delta parts fetched of the pull.
    pub(crate) fn parts(&self) -> u32 {
        self.own.delta_parts_fetched.load(Ordering::Relaxed)
    }

    /// Returns the own count of bytes transferred of the pull.
    pub(crate) fn bytes(&self) -> u64 {
        self.own.transferred.load(Ordering::Relaxed)
    }
}

impl Drop for PullCounters {
    /// Ends the scanning state in the handle of the caller if the pull ends
    /// on an error while it scans.
    fn drop(&mut self) {
        if let Some(caller) = &self.caller
            && self.own.scanning.load(Ordering::Relaxed) != 0
        {
            caller.scanning.fetch_sub(1, Ordering::Relaxed);
        }
    }
}

impl PullProgress {
    /// Creates a handle with all counters at zero.
    pub fn new() -> PullProgress {
        PullProgress::default()
    }

    /// Returns the counters as they are now.
    ///
    /// The method reads each counter separately, so two counters of one
    /// snapshot can differ by the work of one step.
    pub fn snapshot(&self) -> PullProgressSnapshot {
        let c = &self.inner;
        PullProgressSnapshot {
            bytes_transferred: c.transferred.load(Ordering::Relaxed),
            metadata_fetched: c.metadata_fetched.load(Ordering::Relaxed),
            content_fetched: c.content_fetched.load(Ordering::Relaxed),
            objects_done: c.objects_done.load(Ordering::Relaxed),
            objects_total: c.objects_total.load(Ordering::Relaxed),
            scanning: c.scanning.load(Ordering::Relaxed) != 0,
            delta_parts_fetched: c.delta_parts_fetched.load(Ordering::Relaxed),
            delta_parts_total: c.delta_parts_total.load(Ordering::Relaxed),
            delta_bytes_fetched: c.delta_bytes_fetched.load(Ordering::Relaxed),
            delta_bytes_total: c.delta_bytes_total.load(Ordering::Relaxed),
        }
    }
}

/// The counters of a [`PullProgress`] at one point in time.
#[derive(Debug, Clone, Copy, Default, PartialEq, Eq)]
pub struct PullProgressSnapshot {
    /// The value of [`PullStats::bytes_transferred`] so far.
    pub bytes_transferred: u64,
    /// The value of [`PullStats::metadata_fetched`] so far.
    pub metadata_fetched: u32,
    /// The value of [`PullStats::content_fetched`] so far.
    pub content_fetched: u32,
    /// The units of work that the pull finished.
    ///
    /// One unit is a commit, an object, or a delta part that the pull handled,
    /// fetched or found present.
    pub objects_done: u32,
    /// The units of work that the pull knows of.
    ///
    /// The count includes the finished units, the units in flight, and the
    /// queued units. It grows as the walk reads each dirtree.
    pub objects_total: u32,
    /// The scanning state: `true` while the total still grows.
    ///
    /// The value is `true` while a pull has not reached its objects yet, or
    /// has a commit or a dirtree in its queue.
    pub scanning: bool,
    /// The value of [`PullStats::delta_parts`] so far.
    pub delta_parts_fetched: u32,
    /// The delta parts that the pull fetches as files, over all deltas that it
    /// takes.
    pub delta_parts_total: u32,
    /// The sum of the declared sizes of the delta parts fetched so far.
    pub delta_bytes_fetched: u64,
    /// The sum of the declared sizes of all delta parts that the pull fetches
    /// as files.
    pub delta_bytes_total: u64,
}

/// Methods that pull from a local repository.
impl Repo {
    /// Pulls refs and their objects from another local repository.
    ///
    /// The pull resolves each requested ref in `src`, and follows its commit
    /// chain to [`depth`](PullOptions::depth) parents. It imports each object
    /// that those commits reach into this repository, in one transaction. If
    /// the pull fails, it publishes no object and writes no ref.
    ///
    /// A parent commit that the source does not hold ends its chain without an
    /// error. So a source with a truncated history pulls what it has. A parent
    /// that a commit of the pull names as a dependency is a dependency too, as
    /// "Dependencies" states.
    ///
    /// The pull writes the refs last, after the objects are published. So no
    /// ref of this repository names a commit with objects that are not durable.
    /// Under [`no_ref_writes`](PullOptions::no_ref_writes) the pull writes no
    /// ref.
    ///
    /// [`verify`](PullOptions::verify) selects the signature policy, as
    /// [`PullVerify`] states. The module [`pull`](self) states the rules of
    /// the `.commitpartial` markers.
    ///
    /// # Names
    ///
    /// The pull reads each name in [`refs`](PullOptions::refs) as a revision
    /// of `src`, as [`Repo::resolve_rev`] reads it. So a name can be a
    /// checksum, an abbreviated checksum, or a ref with a `^` suffix, and a
    /// ref is `NAME`, `REMOTE:NAME`, or `@ID:NAME`. The pull reads `@ID:NAME`
    /// in `src` at the path that [`Repo::resolve_ref_tip`] reads:
    /// `refs/mirrors/<ID>/<NAME>`, or `refs/heads/<NAME>` if the
    /// `[core] collection-id` of `src` is `ID`. One pull can take names of
    /// more than one collection, and plain names beside them.
    ///
    /// The pull writes the ref of each name in this repository:
    ///
    /// - An `@ID:NAME` name gives `refs/mirrors/<ID>/<NAME>`, or
    ///   `refs/heads/<NAME>` if the `[core] collection-id` of this repository
    ///   is `ID`, whatever [`remote`](PullOptions::remote) is.
    /// - Each other name gives `refs/remotes/<remote>/<name>` if `remote` is
    ///   set, and else the ref of the name as a refspec: `refs/heads/<name>`,
    ///   or `refs/remotes/<REMOTE>/<NAME>` for `REMOTE:NAME`.
    ///
    /// A name given two times counts one time. Two different names that write
    /// one ref, such as `main` and `@ID:main` with no `remote` into a
    /// repository whose `[core] collection-id` is `ID`, stop the pull before
    /// it reads `src`. Under [`no_ref_writes`](PullOptions::no_ref_writes) the
    /// pull makes no such check.
    ///
    /// Delta discovery reads the `from` commit of a delta at that ref, with
    /// and without [`no_ref_writes`](PullOptions::no_ref_writes).
    ///
    /// Without `no_ref_writes`, the pull checks the
    /// `ostree.collection-binding` of the tip commit of each `@ID:NAME` name.
    /// The pull fails with [`Error::Pull`] if the key is absent, if its value
    /// is not a string, or if it states an id other than `ID`. This is also
    /// true if `ID` is the `[core] collection-id` of this repository. The pull
    /// makes this check before it writes an object, a marker, or a ref.
    /// [`DISABLE_VERIFY_BINDINGS`](PullFlags::DISABLE_VERIFY_BINDINGS) skips
    /// the ref-binding check alone, and the collection-binding check stays
    /// on. With `no_ref_writes`, the pull reads no
    /// `ostree.collection-binding`. The ref-binding check reads the part
    /// after `@ID:` of an `@ID:NAME` name, and each other name whole.
    ///
    /// # Dependencies
    ///
    /// Field 2 of a commit names the dependencies of the commit.
    /// [`read_commit_related`](Repo::read_commit_related) reads them. The pull
    /// follows the dependencies of each commit that it walks: each target, and
    /// each parent that [`depth`](PullOptions::depth) takes. It also follows
    /// the dependencies of each intermediate commit of a chain of static
    /// deltas. Discovery reads field 2 of such a commit from the superblock of
    /// its step.
    ///
    /// - The pull takes each dependency at depth 0, so a dependency entry adds
    ///   no parent to the pull. The pull takes a dependency one time, also if
    ///   several commits name it.
    /// - The pull writes no ref for a dependency.
    /// - The pull checks no signature of a dependency commit. Field 2 holds
    ///   the checksum of the dependency, and the checksum and the signatures
    ///   of the commit that names it cover field 2. Under
    ///   [`UNTRUSTED`](PullFlags::UNTRUSTED), the import hashes the dependency
    ///   commit and compares the result with that checksum. Without the flag,
    ///   the pull trusts the source for a dependency as for each other
    ///   object. The pull makes no ref-binding check on a dependency.
    /// - A target, a parent that [`depth`](PullOptions::depth) takes, and a
    ///   commit of a chain of static deltas keep the checks of that role,
    ///   also if a field 2 names them.
    /// - The pull reads the commit object of a dependency from the source,
    ///   then from each localcache repository, then from this repository. It
    ///   reads no commit object of a dependency that a chain of static deltas
    ///   makes, so the source can hold that commit in the delta alone.
    /// - A dependency is a commit of the pull for each other rule: its
    ///   `.commitpartial` marker, the walk of its tree, and its detached
    ///   metadata. For a dependency that this repository holds complete, the
    ///   pull walks no tree and copies no `.commitmeta`. So the dependency
    ///   does not get the signatures that the source added after this
    ///   repository stored it. A pull that takes the dependency as a target
    ///   copies its `.commitmeta`. A dependency that this repository holds
    ///   partial gets the walk of its whole tree and its `.commitmeta`.
    /// - A pull that reads static deltas looks for a delta of each dependency
    ///   that it appends and that this repository does not hold complete, as
    ///   "Static deltas" states. The pull imports the objects of a dependency
    ///   with no delta loose, unless a chain of static deltas of the pull
    ///   makes that commit.
    /// - The pull does not follow a build source: a commit that the detached
    ///   metadata key `ostrya.related` names.
    ///
    /// A [`COMMIT_ONLY`](PullFlags::COMMIT_ONLY) pull takes no dependency. It
    /// also checks the format of the entries of field 2 of each commit that it
    /// walks.
    ///
    /// These cases fail the pull before the transaction opens, and the pull
    /// writes no object and no ref:
    ///
    /// - An entry of field 2 has an empty name or a checksum that is not 32
    ///   bytes.
    /// - A dependency names dependencies of its own: its own field 2 is not
    ///   empty.
    /// - Neither a source nor this repository holds a dependency. This is
    ///   also true for a parent that the source does not hold, if a commit of
    ///   the pull names that parent as a dependency.
    ///
    /// The pull reports these defects before a target or a parent that fails
    /// the signature policy, as for each other defect of the walk.
    ///
    /// # Remote config
    ///
    /// The pull reads the verification keys of the `[remote "NAME"]` section
    /// that [`remote`](PullOptions::remote) names, as [`Repo::pull`] does.
    /// Each field of [`verify`](PullOptions::verify) that is set wins over its
    /// key. If the pull names no remote, or the config has no section for the
    /// remote, the pull makes only the checks that the fields ask for. The
    /// `pull-local` command of `ostree` reads none of these keys.
    ///
    /// A section with no `gpg-verify` key turns on the GPG check of the
    /// commits. A build without the feature `verify-gpg`, which is the default
    /// feature set, then refuses the pull with [`Error::Unsupported`] before
    /// it reads `src`. To pull without the check, set `gpg-verify=false` in
    /// the section, or set [`PullVerify::gpg`] to `Some(false)`.
    ///
    /// # Sources
    ///
    /// The pull reads the source repository first, and then each of
    /// [`localcache_repos`](PullOptions::localcache_repos) in turn. It takes an
    /// object from the first source that holds it.
    ///
    /// The pull trusts the objects that this repository holds, and it does not
    /// import them. It takes an object as held if a `stat` of its path finds an
    /// entry. The `stat` does not follow a symlink.
    ///
    /// The walk reads a dirtree from this repository if this repository holds
    /// it, and from the first source that holds it otherwise. So a localcache
    /// repository supplies a subtree that the source lost.
    ///
    /// For each dirtree that it reads, the walk makes one blocking call. The
    /// call makes a `stat` of each name that the walk did not meet before. It
    /// plans the objects that this repository lacks, and no other objects.
    ///
    /// The walk descends into each dirtree that it reads, also into a dirtree
    /// that this repository holds and no source holds. It imports each object
    /// below that dirtree that this repository lacks from the first source that
    /// holds it. If neither this repository nor a source holds an object, the
    /// pull fails when the import gets to it, so a published commit is
    /// complete.
    ///
    /// The pull walks all its commits as one tree, and descends into each
    /// dirtree once. So a deep pull of a chain of near-identical trees reads
    /// each dirtree once. The plan of each commit holds the objects that the
    /// plans of the commits before it did not hold.
    ///
    /// # Damaged dirtrees
    ///
    /// If this repository holds a dirtree that the pull cannot read or parse,
    /// the pull fails, also if a source holds a good copy. The causes are:
    ///
    /// - a file that this process cannot read.
    /// - an entry that is not a regular file.
    /// - a symlink at the dirtree or at its fan-out directory.
    /// - a file larger than [`MAX_METADATA_SIZE`](crate::MAX_METADATA_SIZE).
    /// - bytes that do not parse as a dirtree.
    ///
    /// [`fsck`](Repo::fsck) with [`delete`](crate::FsckOptions::delete) does
    /// not remove such a dirtree. A pull after the removal of the entry from
    /// `objects/` imports that dirtree from the first source that holds it.
    ///
    /// # Complete commits
    ///
    /// A commit is complete in this repository if the commit object is present
    /// and no `.commitpartial` marker names it. The pull does not walk such a
    /// commit: it reads no object of its tree, and imports its detached
    /// metadata alone. For a dependency that is complete here, the pull also
    /// imports no detached metadata, as `# Dependencies` states.
    ///
    /// A gap in a complete commit stays until [`fsck`](Repo::fsck) marks the
    /// commit partial. Then a pull walks its tree and fills the gap. `fsck`
    /// marks a commit partial if a content object or a dirmeta object is
    /// missing. At a missing dirtree, `fsck` ends with
    /// [`FsckFailure::MissingDirTree`](crate::FsckFailure::MissingDirTree) and
    /// marks nothing, so no pull repairs that commit.
    ///
    /// # Import paths
    ///
    /// An imported object gets the file system metadata (unix mode, ownership,
    /// and xattrs) that a commit into this repository gives it. Within that
    /// rule, the object shares the bytes and the inode of the source. The path
    /// of an import depends on how much of the object the two repositories
    /// store in the same form.
    ///
    /// - Hardlink: the pull hardlinks an object with one shared form into the
    ///   staging directory of the transaction. Each metadata object has one
    ///   form in each mode. A content object has one form between repositories
    ///   of the same mode. A symlink object has one form between `bare-user`
    ///   and `bare-user-shared`.
    /// - Reflink or copy of a metadata object: if the pull cannot link a
    ///   metadata object, it makes a `FICLONE` reflink. If the reflink fails,
    ///   it makes a byte copy. The new inode is that of a metadata object written
    ///   into this repository: mode 0644, no xattrs, and the ownership of the
    ///   writing process.
    /// - Write of a metadata object: under
    ///   [`UNTRUSTED`](PullFlags::UNTRUSTED), a metadata object takes neither
    ///   the hardlink nor the reflink or copy. The pull reads it once and
    ///   writes the bytes that it hashes, as `# Trust` states.
    /// - Clone: the pull clones a regular file if the two modes share its
    ///   payload bytes and not its inode metadata, as two modes of the bare
    ///   family do. The clone is a `FICLONE`
    ///   reflink of the payload, or a copy if the reflink fails. The pull
    ///   applies the inode policy of this repository again from the logical
    ///   header of the object. It reads the header from the metadata of the
    ///   object, and does not read the payload for it.
    /// - Copy of a `.filez`: if the pull cannot link a regular file between
    ///   two `archive` repositories, it writes the stored `.filez` bytes of
    ///   the source unchanged. So the object keeps the DEFLATE level of the
    ///   source, and not the `[archive] zlib-level` of this repository. The
    ///   pull inflates the payload to hash it, and compares the result with
    ///   the name of the object.
    /// - Re-ingest: the pull reads the remaining content objects into their
    ///   logical form (uid, gid, mode, xattrs, and payload). It writes them
    ///   through the ordinary ingest path, in the form that the destination
    ///   mode needs. These objects are a content object across the `archive`
    ///   boundary and a symlink between modes that store it in different
    ///   forms. `archive` stores a framed, deflated form that no other mode
    ///   shares.
    ///
    /// If the pull cannot link a content object, it uses the clone, the
    /// `.filez` copy, or the re-ingest path. These paths give the object the
    /// inode metadata that a commit into this repository writes.
    ///
    /// # Hardlink rules
    ///
    /// A hardlink cannot separate the bytes from the ownership. So the pull
    /// links an object only if the ownership of the source inode is the
    /// ownership that a write into this repository gives.
    ///
    /// In a `bare` destination this is always true for a content object. Its
    /// uid, gid, permission bits, and xattrs come from the header that its
    /// checksum covers. Two `bare` repositories thus agree on such an inode
    /// byte for byte.
    ///
    /// In each other mode, the ownership comes from the writing process and
    /// the staging directory. So the pull compares the uid and the gid of the
    /// source inode with the pair that a new object in this repository gets.
    /// If the owners of the two repositories differ, for example two
    /// group-shared repositories of different groups, the pull does not link.
    /// It writes each object again, with a reflink of the bytes if the file
    /// system supports it, and a copy if not.
    ///
    /// To compare the owners, the pull links the source object into the
    /// staging directory and reads the status of the link. If the owners
    /// differ, the pull removes the link and then copies the object. The link
    /// and its removal change the ctime of the source object.
    ///
    /// The pull reads only the ownership of the source inode. It trusts that
    /// the permission bits and the xattrs match the header of the object, and
    /// does not check them. In `archive`, `bare-user`, and `bare-user-shared`
    /// the checksum of the object covers neither.
    ///
    /// Out-of-band changes to the inodes of a source thus go into this
    /// repository. Examples are a copy that dropped modes and a `chmod` over
    /// `objects/`. A pull of the `ostree` command does the same.
    ///
    /// The pull does not apply again the attributes from the environment of
    /// this repository. Examples are a default POSIX ACL on its directories
    /// and a security label. An object that the pull writes gets them from the
    /// environment, and a linked object keeps those of the source.
    ///
    /// A link fails in these cases:
    ///
    /// - the two repositories are on different file systems.
    /// - the source inode is at its link limit.
    /// - the protected-hardlink rules of the kernel refuse it.
    ///
    /// [`FORCE_COPY`](PullFlags::FORCE_COPY) turns off each link.
    ///
    /// A repository that seals its objects with fs-verity does not hardlink.
    /// Verity is a property of an inode, so a seal of a shared inode also
    /// seals the copy of the source. An unsealed link breaks the rule of the
    /// destination that each object stored as a regular file is sealed. Such a
    /// destination copies each object and seals each copy.
    ///
    /// A destination with `[ex-integrity] fsverity=maybe` seals its objects
    /// only if the probe of [`seals_objects`](Repo::seals_objects) gives
    /// `true`. On a file system that cannot seal a file, the probe gives
    /// `false`, and the pull hardlinks by the rules above. A linked object
    /// shares the inode of the source, so a later change of that inode in
    /// place is visible in this repository.
    ///
    /// This is a divergence from the `ostree` command, which hardlinks into a
    /// `fsverity=yes` repository and leaves the imported objects unsealed.
    ///
    /// # Bare-user-only destinations
    ///
    /// A `bare-user-only` destination refuses a content object whose logical
    /// header is not the header that it stores. That mode records no ownership
    /// and no xattrs, and it reduces the permission bits of a regular file to
    /// `perm & 0o755`. A commit into it names each object for that canonical
    /// header. An import keeps the name that the object arrives under.
    ///
    /// The pull refuses each of these with [`Error::Pull`]: a non-zero uid or
    /// gid, an xattr, and a regular-file mode with bits outside `0755`. The
    /// destination can hold such an object only under a name that its stored
    /// form does not hash to. This check applies to each pull, and also to
    /// the objects of a static delta part.
    ///
    /// This is a divergence from the `ostree` command, which hardlinks the
    /// object in and leaves a repository that its own fsck reports corrupt.
    /// [`BAREUSERONLY_FILES`](PullFlags::BAREUSERONLY_FILES) adds a rule of
    /// its own for each destination mode.
    ///
    /// # Free space
    ///
    /// The import charges the blocks that it allocates to the `min-free-space`
    /// budget of the transaction. A hardlinked object allocates no block, and
    /// a reflinked payload shares the extents of the source. So a pull of
    /// objects that the destination shares with the source can run on a file
    /// system with no space for a second copy. A byte-copied or re-ingested
    /// object is charged its full stored size. Under
    /// [`UNTRUSTED`](PullFlags::UNTRUSTED), the pull writes each metadata
    /// object, so each one is charged its full size.
    ///
    /// # Trust
    ///
    /// By default the pull does not verify the checksum of an imported object.
    /// This makes the link path and the clone path possible.
    /// [`UNTRUSTED`](PullFlags::UNTRUSTED) fails the pull if an imported
    /// object does not hash to its name.
    ///
    /// The `.filez` copy and the re-ingest path hash each object as they
    /// stream, and compare the result with the name, whatever the flags say.
    /// So these paths refuse a corrupt source with or without the flag. The
    /// other paths move bytes without a hash. On these paths, the flag reads a
    /// metadata object once, hashes the bytes, and writes the same bytes. The
    /// flag hashes a linked or cloned content object after the link or the
    /// clone. It reads the staged object as this repository stores it, and
    /// makes the hash and the mode checks of the pull on that one read. So a
    /// source that changes during the import cannot pass the hash. The import
    /// hashes each object once.
    ///
    /// The flag also hashes each commit and each dependency that the walk of
    /// the chains reads from a source, and each dirtree that the walk of the
    /// tree reads from a source. It compares each result with the name of the
    /// object before the pull uses the bytes. So the signature check, the
    /// ref-binding check, the timestamp check, and the walk read the objects
    /// that the pull imports.
    ///
    /// A hardlinked object shares its inode with the source. So a later change
    /// of the source file changes the object in this repository.
    ///
    /// A signature covers the commit or the summary alone. A signature check
    /// of this pull does not set the flag. A caller that checks the
    /// signatures of a source that it does not trust also sets
    /// [`UNTRUSTED`](PullFlags::UNTRUSTED).
    ///
    /// # Detached metadata
    ///
    /// The pull stages the detached metadata of a commit in the same
    /// transaction. The transaction writes it at its commit, after the objects
    /// publish and before the ref that names the commit. A verifier that reads
    /// the signatures with the commit needs this order.
    ///
    /// The pull copies the `.commitmeta` of the first source that holds one.
    /// It copies no `.commitmeta` of a dependency that this repository holds
    /// complete, as `# Dependencies` states. If
    /// `[ex-ostrya] keep-detached-related` of this repository is `false`
    /// ([`RepoConfig::keep_detached_related`](crate::RepoConfig::keep_detached_related)),
    /// the pull drops `ostrya.related` from it. A zero-length `.commitmeta` in
    /// a source is the "no metadata" marker, and it replaces the copy of this
    /// repository. If no source holds a `.commitmeta`, the signature
    /// verification reads the copy of this repository.
    ///
    /// If the policy checks the signatures of the commits, the check keeps the
    /// SHA-256 of the `.commitmeta` that it read from a source. If the sources
    /// do not hold the same `.commitmeta` at the import, the pull fails and
    /// stages no `.commitmeta` of the commit. The pull does not compare the
    /// copy of this repository.
    ///
    /// If the pull fails before the ref step of its commit, a
    /// [`LockTimeout`](Error::LockTimeout) at that step included, it leaves no
    /// `.commitmeta` of its own. A failure can occur in the ref step itself,
    /// at the install of a later `.commitmeta` or at a ref write. Then the
    /// `.commitmeta` files that the step installed before it stay.
    ///
    /// # Static deltas
    ///
    /// Under [`require_static_deltas`](PullOptions::require_static_deltas),
    /// the pull reads the summary of the source and the deltas that it
    /// advertises. It refuses a source with no summary, and a source outside
    /// `archive` mode. It finds each delta before it walks the commit chains
    /// and verifies their signatures.
    ///
    /// The pull applies each delta that it finds into the transaction one part
    /// at a time, and stages the commit from the superblock. The import then
    /// walks each commit and imports what no part produced.
    ///
    /// [`static_deltas`](PullOptions::static_deltas) replaces this search with
    /// a list. The pull then needs no summary for the deltas. For each target
    /// commit, it plans the chain with the fewest steps, by the rules of
    /// [`Repo::pull`] under `# Static deltas`. The pull reads the deltas of
    /// a list only from a source in `archive` mode. A
    /// [`COMMIT_ONLY`](PullFlags::COMMIT_ONLY) pull ignores the list.
    ///
    /// Before the transaction opens, the pull reads the superblock of each
    /// step and compares its SHA-256 with the digest in the list. It checks
    /// the signatures of the superblock, by the rules of [`PullVerify`], and
    /// its inline parts. For each commit of a chain, the target included, it
    /// also checks the signatures of the commit, and the ref binding of each
    /// requested ref that names the commit. It checks the collection binding
    /// of the commit too, if the pull makes that check. Then it checks the
    /// format of field 2 of the commit, as "Dependencies" states. The walk of
    /// the commit chains does not check the signatures or the bindings of that
    /// commit again. This pull makes no timestamp check. So a target that
    /// the policy or its bindings refuse costs the reads of the superblocks,
    /// and the pull applies no part. The pull reports this refusal before a
    /// defect that the walk of the commit chains finds. A target with no chain
    /// gets its checks in the walk of the commit chains, also before the
    /// transaction opens.
    ///
    /// The pull applies a chain one level at a time, in its one transaction.
    /// The parts, the loose objects, and the tree walk of one level end before
    /// the next level starts. The pull applies one step at a time, in each
    /// level and in the run of the targets. Before it applies a step, it reads
    /// the superblock of the step again from the source and compares it with
    /// the digest in the list again. 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.
    ///
    /// If the source does not hold a superblock of a chain when the pull reads
    /// it before the transaction, the pull plans again without that delta. If
    /// no chain reaches a target, the pull imports its objects loose, or fails
    /// under `require_static_deltas`.
    ///
    /// After the walk of the commit chains, and before the transaction opens,
    /// the pull looks for a delta of each dependency that the walk appends and
    /// that this repository does not hold complete. The search and its `from`
    /// are those of [`Repo::pull`] under `# Static deltas`: the summary and
    /// the delta index of the source, or one entry of the list. A target whose
    /// name is the full hex form of its commit is a pull by checksum, and
    /// gives no paired entry. Under `require_static_deltas`, a dependency with
    /// no delta fails the pull, and the pull writes nothing. The pull applies
    /// the deltas of the dependencies after the deltas of the targets, one
    /// part at a time, in the order of the walk. The search keeps no
    /// superblock of a dependency. Before the pull applies the delta of a
    /// dependency, it reads the superblock again from the source and compares
    /// it with the digest that the summary, the delta index, or the list
    /// states. The pull checks no signature of the superblock of a
    /// dependency, as [`Repo::pull`] states.
    ///
    /// # Errors
    ///
    /// - [`Error::Unsupported`] if [`subpaths`](PullOptions::subpaths) is not
    ///   empty, before the pull reads `src`. Also if the pull requires static
    ///   deltas or applies a [`static_deltas`](PullOptions::static_deltas)
    ///   list, and `src` is not an `archive` repository.
    /// - [`Error::InvalidInput`] if [`depth`](PullOptions::depth) is below
    ///   `-1`, before the pull reads `src`.
    /// - [`Error::InvalidInput`] if
    ///   [`valid_remote_name`](crate::config::valid_remote_name) refuses
    ///   [`remote`](PullOptions::remote), before the pull reads `src` or a
    ///   keyring of the remote.
    /// - [`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), before
    ///   the pull reads `src`.
    /// - [`Error::Core`] if `[ex-ostrya] keep-detached-related` of this
    ///   repository is not a boolean, before the pull reads `src`.
    /// - [`Error::InvalidRefspec`] if a name starts with `@` and is not an
    ///   `@ID:NAME` ref that [`Ref`] reads, less each `^` at its end, before
    ///   the pull reads `src`. The error holds the name.
    /// - [`Error::InvalidRefspec`] if, without
    ///   [`no_ref_writes`](PullOptions::no_ref_writes), a name gives no valid
    ///   ref to write, for example a name with a `^` suffix, before the pull
    ///   reads `src`.
    /// - [`Error::Pull`] if, without
    ///   [`no_ref_writes`](PullOptions::no_ref_writes), two different names
    ///   write one ref, before the pull reads `src`. The error names both
    ///   names and the path of the ref.
    /// - [`Error::Pull`] if the options ask for a signature verification and
    ///   name no [`remote`](PullOptions::remote). With
    ///   [`trust_group`](PullOptions::trust_group), only a summary check needs
    ///   a remote.
    /// - The errors of [`trust_group`](PullOptions::trust_group), before the
    ///   pull reads `src`.
    /// - [`Error::InvalidFormat`] if the remote section holds a `trust` value
    ///   that is malformed or names no trust group, if the group fails the
    ///   check of a trust group, or if the section turns on a commit check or
    ///   holds a key source that no summary check reads beside `trust`
    ///   ([`PullTrust::from_remote`](crate::verify::PullTrust::from_remote)).
    ///   The pull makes these checks before it reads `src`.
    /// - [`Error::InvalidInput`] if the remote section holds `trust` and
    ///   [`verify`](PullOptions::verify) sets `gpg` or `sign` to `Some(true)`,
    ///   before the pull reads `src`.
    /// - [`Error::Unsupported`] if the policy asks for GPG verification and
    ///   the build has no `verify-gpg` feature, or if `sign-verify` or
    ///   `sign-verify-summary` names an engine that this build does not
    ///   verify with. The pull makes these checks before it reads `src`.
    /// - [`Error::Core`] if a verification key of the remote section is
    ///   malformed: `gpg-verify` or `gpg-verify-summary` is not a boolean,
    ///   or a sign-api key is not valid base64.
    /// - [`Error::Signature`] if the policy selects a sign-api engine that has
    ///   no trusted key, or if a keyring or a key file of the remote cannot
    ///   be read.
    /// - [`Error::Pull`] if the pull requires static deltas and `src` has no
    ///   summary, or no delta for a commit or for a dependency that this
    ///   repository does not hold complete. With a `static_deltas` list, the
    ///   pull needs no summary, and fails if no chain of the list reaches a
    ///   target commit. A listed delta from scratch to the target that the
    ///   rule of [`require_static_deltas`](PullOptions::require_static_deltas)
    ///   leaves alone counts as found: the pull does not fail, and imports
    ///   that target loose. The walk reads the commit of each dependency
    ///   before the search for its delta. So a dependency that no source
    ///   holds gives [`Error::ObjectNotFound`], and a dependency that names
    ///   dependencies of its own gives [`Error::InvalidRelated`], before this
    ///   error.
    /// - [`Error::Pull`] if a superblock of the list produces another commit,
    ///   or from another commit, than its entry of the list.
    /// - [`Error::Pull`] if the policy checks the signatures of the commits and
    ///   the `.commitmeta` of a commit in the sources at the import is not the
    ///   `.commitmeta` that the signature check read. The error names the
    ///   commit.
    /// - [`Error::Pull`] if the ref binding of a commit does not name its ref.
    ///   Also, without [`no_ref_writes`](PullOptions::no_ref_writes), if the
    ///   `ostree.collection-binding` of the tip commit of an `@ID:NAME` name
    ///   is absent, is not a string, or states an id other than `ID`, before
    ///   the pull writes an object.
    /// - [`Error::Pull`] if an object fails the
    ///   [`BAREUSERONLY_FILES`](PullFlags::BAREUSERONLY_FILES) check or the
    ///   check of a `bare-user-only` destination.
    /// - [`Error::InvalidRelated`] if an entry of field 2 of a commit has an
    ///   empty name or a checksum that is not 32 bytes, or if a dependency
    ///   names dependencies of its own. The pull reports it before a failed
    ///   signature check of the walk, and before a `.commitmeta` of the walk
    ///   that does not parse.
    /// - [`Error::Signature`] if a commit or the summary fails the signature
    ///   policy, each commit of a chain included. Also if the signatures of the
    ///   superblock of a target or of a step fail the policy, or if the policy
    ///   covers the summary and `src` has no `summary` or no `summary.sig`.
    /// - [`Error::RefNotFound`] if `src` does not hold a requested ref. For a
    ///   collection ref, the error holds `@ID:NAME`.
    /// - [`Error::ObjectNotFound`] if neither this repository nor a source
    ///   holds a dependency or an object that a pulled commit reaches. Also if
    ///   a dirtree that this repository holds is a symlink that points to no
    ///   file.
    /// - [`Error::ChecksumMismatch`] if an imported object does not hash to its
    ///   name, under [`UNTRUSTED`](PullFlags::UNTRUSTED) or on the `.filez`
    ///   copy and the re-ingest path. Also under
    ///   [`UNTRUSTED`](PullFlags::UNTRUSTED), if a commit or a dependency that
    ///   the walk of the chains reads from a source, or a dirtree that the walk
    ///   of the tree reads from a source, does not hash to its name. Also if a
    ///   delta superblock does not match its advertised digest or its digest
    ///   in the list.
    /// - [`Error::InsufficientFreeSpace`] if an imported object needs more
    ///   space than the free-space budget of the transaction holds.
    /// - [`Error::LockTimeout`] if the wait for the repository lock or the
    ///   update lock passes `[core] lock-timeout-secs`.
    /// - [`Error::Core`] if a commit, a dirtree, or detached metadata does not
    ///   parse. If the signature policy verifies commits, the pull parses the
    ///   `.commitmeta` of each commit that it verifies: the copy that it reads
    ///   from `src` or a localcache repository, or the copy in this repository
    ///   if no source holds one. It verifies no dependency. If
    ///   `[ex-ostrya] keep-detached-related` of this repository is `false`, the
    ///   pull parses each `.commitmeta` that it stores.
    /// - [`Error::InvalidFormat`] if the `summary` or `summary.sig` of `src` is
    ///   larger than 64 MiB or is not a regular file. Also if a static delta of
    ///   `src` is malformed, or if `src` does not hold a superblock of a chain
    ///   or of a dependency when the pull applies its delta. Also if a
    ///   `.filez` that the pull copies has bytes after its payload, or a
    ///   payload that does not inflate to the size that its header declares.
    /// - [`Error::InvalidFormat`] for a held dirtree that is not a regular
    ///   file, that is larger than
    ///   [`MAX_METADATA_SIZE`](crate::MAX_METADATA_SIZE), or that has a
    ///   symlink on its path.
    /// - [`Error::InvalidFormat`] if `state` is a symlink or is not a
    ///   directory. The pull fails at the write of its first marker, before
    ///   it imports an object.
    /// - [`Error::Io`] with `EISDIR` if a directory is at the name of a
    ///   marker that the pull removes after its transaction commits.
    /// - [`Error::Io`] for an I/O failure of the file system. Also for a held
    ///   dirtree that the pull cannot read. Also if the read of a ref file of
    ///   `src` fails, for example with `EACCES`, or if the path of a requested
    ///   ref names a directory or goes through a file, before the pull writes
    ///   an object.
    pub async fn pull_local(&self, src: &Repo, mut opts: PullOptions) -> Result<PullStats> {
        let started = Instant::now();
        // A local pull copies whole trees. The `ostree pull-local` command
        // takes no subpath either.
        if !opts.subpaths.is_empty() {
            return Err(Error::Unsupported("a local pull takes no subpath".into()));
        }
        check_depth(opts.depth)?;
        check_remote_option(&opts)?;
        check_static_deltas(&opts)?;
        let related = RelatedRule::of(self.config())?;
        check_local_operands(&opts)?;
        check_local_places(self, &opts)?;
        let edges = take_static_deltas(&mut opts).await?;
        // The pull builds the signature policy before it reads the source. So
        // a check that the options ask for with no remote to take keys from
        // fails here, before the walk of a chain.
        let trust = crate::verify::PullTrust::resolve(
            self,
            opts.remote.as_deref(),
            &opts.verify,
            opts.trust_group
                .as_deref()
                .map(crate::verify::trust::FieldGroup::new)
                .as_mut(),
            crate::verify::Defaults::Section,
        )
        .await?;
        self.pull_local_from(
            src,
            trust,
            related,
            opts,
            LocalWanted::Named,
            edges,
            started,
        )
        .await
    }

    /// Pulls the refs `wanted` from the local repository `src` under `trust`,
    /// as [`Repo::pull_local`] does.
    ///
    /// The caller made each check of `opts` that applies to its entry, and
    /// took the list of static deltas out of `opts` as the index `edges`.
    /// With [`LocalWanted::Pinned`], the refs of the pull are at the place of
    /// the [`Pinned`]. With [`LocalWanted::Named`], they are at
    /// [`RefPlace::Operands`] of [`remote`](PullOptions::remote) and of the
    /// `[core] collection-id` of this repository. `started` is the start of
    /// [`PullStats::elapsed`].
    #[allow(clippy::too_many_arguments)]
    async fn pull_local_from(
        &self,
        src: &Repo,
        trust: crate::verify::PullTrust,
        related: RelatedRule,
        opts: PullOptions,
        wanted: LocalWanted<'_>,
        edges: Option<chain::Edges>,
        started: Instant,
    ) -> Result<PullStats> {
        let verification = verify::Verification::from_trust(trust);
        // A pull that requires static deltas reads the source as a fetch
        // reads a remote: the summary, then the deltas that it advertises. A
        // pull with a list of static deltas reads the deltas of the list and
        // needs no summary. The counts of both pulls are those of a fetch.
        // These steps come before the walk of the commit chains, in the order
        // of the refusals of the `ostree` command:
        //
        // - the summary verification.
        // - the refusal of a source with no summary or outside archive mode.
        // - the search for each delta.
        //
        // `read_checked_local_summary` states the read of the summary and its
        // signature.
        let fetching = opts.require_static_deltas && !opts.disable_static_deltas;
        // A commit-only pull ignores the list.
        let list_applies = edges.is_some() && !opts.flags.contains(PullFlags::COMMIT_ONLY);
        let reads_deltas = fetching || list_applies;
        let needs_summary = fetching && edges.is_none();
        let summary = read_checked_local_summary(src, &verification, needs_summary).await?;
        if needs_summary && summary.is_none() {
            return Err(delta::no_summary_error());
        }
        if reads_deltas && !src.mode().is_archive() {
            return Err(Error::Unsupported(format!(
                "can't pull from a repository in mode {}: a local pull that reads static \
                 deltas reads an archive repository",
                src.mode().as_mode_str()
            )));
        }
        // The pull drops the bytes here: discovery reads two values of the
        // parsed summary alone. A summary can be as large as
        // `SUMMARY_READ_CAP`, so the parse runs on the blocking pool, and the
        // bytes and the rest of the parse drop there.
        let advert = match summary.filter(|_| needs_summary) {
            Some(bytes) => Some(
                ostrya_rt::unblock(move || {
                    crate::summary::Summary::parse(&bytes).map(delta::DeltaAdvert::from_summary)
                })
                .await?,
            ),
            None => None,
        };

        let resolved;
        let (targets, pinned) = match wanted {
            LocalWanted::Named => {
                resolved = resolve_targets(src, &opts).await?;
                (resolved.as_slice(), None)
            }
            LocalWanted::Pinned(pinned) => (pinned.targets.as_slice(), Some(pinned)),
        };
        let flags = opts.flags;
        // A pull of collection refs from a local candidate reads and writes
        // the refs of its collection, and checks the collection binding of
        // each tip. `Repo::pull_local` reads and writes the ref that each name
        // gives, and checks the collection binding of each `@ID:NAME` name,
        // unless it writes no ref.
        let collection = pinned.map(|pinned| (pinned.collection, pinned.allow_unbound));
        let place = match pinned {
            Some(pinned) => pinned.place,
            None => RefPlace::Operands {
                remote: opts.remote.as_deref(),
                own: self.config().collection_id(),
            },
        };
        // `Repo::pull_local` makes no timestamp check. A pull of collection
        // refs from a local candidate makes the check of the options. The
        // check reads a commit that it names one time, before discovery.
        let timestamp = if pinned.is_some() {
            TimestampBase::resolve(self, &opts.timestamp_check).await?
        } else {
            TimestampBase::Off
        };
        let tip_checks = TipChecks {
            collection: collection.map(|(id, _)| id),
            allow_unbound: collection.is_some_and(|(_, allow_unbound)| allow_unbound),
            operand_collections: pinned.is_none() && !opts.no_ref_writes,
            listed: pinned.map(|pinned| &pinned.listed),
            ..TipChecks::new(flags, timestamp, place)
        };

        // The pull finds the deltas before the transaction opens, so a refusal
        // writes no object, no ref, and no marker. With a list, discovery also
        // checks each commit of a chain: the signatures, and the ref binding of
        // each requested ref that names it.
        let counters = PullCounters::new(None);
        let deltas = if advert.is_some() || edges.is_some() {
            delta::discover(
                self,
                &delta::DeltaSource::Local(src),
                advert.as_ref(),
                targets,
                &opts,
                tip_checks,
                edges,
                &verification,
                related,
                &counters,
            )
            .await?
        } else {
            delta::DeltaPlan::default()
        };
        let mut deltas = deltas;
        // The search for the deltas of the dependencies reads the summary
        // values or the list of static deltas, after the walk of the chains.
        let edges = deltas.take_edges();
        // The intermediate commits of the chains. The run of the levels
        // imports each of them, and the commit loop skips them.
        let done: HashSet<Checksum> = deltas.levels().iter().flatten().copied().collect();
        // Discovery read field 2 of each intermediate commit of the chains.
        let mut level_dependencies = deltas.take_dependencies();

        let sources: Vec<&Repo> = std::iter::once(src)
            .chain(opts.localcache_repos.iter())
            .collect();

        // The pull checks each commit of the chain before the transaction
        // opens, so a source with signatures that fail the policy imports
        // nothing. The walk of the chain checks each commit over the bytes that
        // it read to find the parent. Under `UNTRUSTED`, the walk hashes these
        // bytes and compares the result with the name of the commit before it
        // uses them. The import reads and hashes the commit again. The walk
        // also keeps the root dirtree and dirmeta of each commit, so the plan
        // of the tree reads no source commit again.
        //
        // The import loop reads the `.commitmeta` a second time, where it
        // copies the bytes. The check keeps the SHA-256 of the bytes that it
        // read, and the import fails on other bytes. A concurrent sign of the
        // source commit replaces its `.commitmeta` in place, and so fails the
        // pull. A carry of the verified metadata to the import needs one
        // entry for each commit of the chain. A `depth=-1` pull puts no bound
        // on that count, so the pull keeps one digest for each commit.
        //
        // Discovery checked each commit of a chain, so the walk does not check
        // it again.
        //
        // The dependencies of the commits are commits of the pull too. The
        // walk appends each one after the chains, at depth 0. It checks no
        // signature of an appended dependency: field 2 of the commit that
        // names it holds its checksum, and the signatures of that commit
        // cover field 2. A pull that reads static deltas then looks for the
        // delta of each dependency that it appended, before the transaction
        // opens. The search checks no signature of the superblock of such a
        // delta.
        let mut check = verification.checks_commits().then(|| ChainCheck {
            repo: self,
            sources: &sources,
            verification: &verification,
            plan: &deltas,
            failed: None,
        });

        // A commit-only pull follows no dependency. It also checks the format
        // of field 2 of each commit that it walks.
        // A pull that reads no static delta pairs no dependency with a target,
        // so it keeps no entry of field 2 and no parent.
        let mut deps = (!flags.contains(PullFlags::COMMIT_ONLY)).then(|| ChainDependencies {
            inner: dependency::Dependencies::new(!reads_deltas),
            parents: HashMap::new(),
        });
        let mut appended: Vec<Checksum> = Vec::new();
        // The commit chains, in the order of the refs, each commit once.
        let mut commits: Vec<ChainCommit> = Vec::new();
        let mut seen: HashMap<Checksum, i32> = HashMap::new();
        // The refs of each tip, in the order of the first ref that names the
        // tip. The loop reads each tip one time, and makes the checks of each
        // ref that names it.
        let mut tips: Vec<(Checksum, Vec<&str>)> = Vec::new();
        let mut slots: HashMap<Checksum, usize> = HashMap::new();
        for (ref_name, tip) in targets {
            let slot = *slots.entry(*tip).or_insert_with(|| {
                tips.push((*tip, Vec::new()));
                tips.len() - 1
            });
            tips[slot].1.push(ref_name.as_str());
        }
        let untrusted = flags.contains(PullFlags::UNTRUSTED);
        for (tip, refs) in &tips {
            let loaded = load_commit(src, tip, untrusted).await?;
            // Discovery made the binding checks of each ref that names a
            // commit of a chain.
            if !deltas.checked(tip) {
                check_tip_refs(self, tip_checks, tip, &loaded.commit, refs).await?;
            }
            collect_chain(
                src,
                *tip,
                loaded,
                opts.depth,
                untrusted,
                &mut commits,
                &mut seen,
                check.as_mut(),
                deps.as_mut(),
            )
            .await?;
        }
        if let Some(deps) = deps.as_mut() {
            // The run of the levels imports the intermediate commits of the
            // chains, so the walk reads none of them again.
            for commit in deltas.levels().iter().flatten() {
                if let Some(entries) = level_dependencies.remove(commit) {
                    deps.inner.record(*commit, entries);
                }
            }
            appended = collect_dependencies(
                self,
                &sources,
                deps,
                &done,
                untrusted,
                &mut commits,
                &mut seen,
            )
            .await?;
        }
        // The pull reports a defect that the walk finds before a failed check.
        if let Some(ChainCheck {
            failed: Some(err), ..
        }) = check
        {
            return Err(err);
        }
        // The search keeps the source commit and the digest of each delta of a
        // dependency alone. The pull reads each superblock again just before
        // it applies the delta. The maps of the walk drop here, before the
        // transaction opens.
        let mut dependency_deltas = match deps.take() {
            Some(deps) if reads_deltas && !appended.is_empty() => {
                let named = dependency::pair_targets(
                    targets,
                    opts.depth,
                    &deps.parents,
                    deps.inner.naming(),
                    appended,
                );
                drop(deps);
                let (lookups, known) = dependency::lookups(self, targets, place, named).await?;
                delta::discover_dependencies(
                    self,
                    &delta::DeltaSource::Local(src),
                    advert.as_ref(),
                    edges.as_ref(),
                    lookups,
                    &known,
                    &opts,
                    &counters,
                )
                .await?
            }
            _ => delta::DependencyDeltas::default(),
        };
        drop(advert);
        drop(edges);

        let mut txn = self.transaction().await?;
        apply_durability(&mut txn, &opts);
        // The markers follow the `fsync` rule of the transaction.
        let marker_fsync = txn.fsync_flags()?.0;

        // The markers that the pull writes. The list is outside the span that
        // writes them, so a failure in that span clears the markers that it
        // left.
        let mut marked: Vec<Checksum> = Vec::new();
        let published = async {
            // Mark each commit partial before the import of its objects. Skip a
            // commit that this repository already holds complete: an unrelated
            // failure must not demote a complete commit. The plan of the tree
            // reads the same answer and plans nothing for a complete commit.
            // The intermediate commits of the chains come first, with one
            // batched check and one batched write. `marked` takes each commit
            // before the write of its marker, so the cleanup also sees a
            // marker that a failed write created.
            let level_commits: Vec<Checksum> = deltas.levels().iter().flatten().copied().collect();
            let mut held_levels: HashSet<Checksum> = HashSet::new();
            let mut to_mark = Vec::new();
            for (commit, held) in chain::check_complete(self, &level_commits).await? {
                if held {
                    held_levels.insert(commit);
                } else {
                    to_mark.push(commit);
                }
            }
            marked.extend_from_slice(&to_mark);
            self.create_partial_markers(to_mark, &[], marker_fsync)
                .await?;
            // The other commits follow, with one batched check.
            let walked: Vec<Checksum> = commits
                .iter()
                .map(|commit| commit.checksum)
                .filter(|checksum| !done.contains(checksum))
                .collect();
            let states = chain::check_complete(self, &walked).await?;
            let walked = commits
                .iter_mut()
                .filter(|commit| !done.contains(&commit.checksum));
            let mut to_mark = Vec::new();
            for (commit, (_, held)) in walked.zip(states) {
                commit.held = held;
                if !held {
                    to_mark.push(commit.checksum);
                }
            }
            marked.extend_from_slice(&to_mark);
            self.create_partial_markers(to_mark, &[], marker_fsync)
                .await?;

            let checks = ModeChecks::new(flags, self.mode());
            let delta_source = delta::DeltaSource::Local(src);
            // A fetch counts each object that the pull reads from the source.
            let count = reads_deltas.then_some(&counters);
            let mut plan = PlanState::default();
            // The read buffer of an untrusted verification. The pull uses it
            // again for each object and sizes it on its first use, so a pull
            // that verifies nothing allocates nothing.
            let mut verify_buf: Vec<u8> = Vec::new();

            // A part of a later step of a chain can patch against an object
            // that an earlier step wrote. So the parts, the loose objects, and
            // the walk of each level of intermediate commits end before the
            // next level starts. The pull parses the job of one step at a
            // time, and drops it after its parts.
            for level in deltas.levels() {
                let mut made: Vec<ChainCommit> = Vec::with_capacity(level.len());
                for commit in level {
                    let job = deltas
                        .parse_record(self, &delta_source, commit)
                        .await?
                        .ok_or_else(|| {
                            Error::InvalidFormat(format!(
                                "static delta to {commit}: the plan holds no step for the commit"
                            ))
                        })?;
                    let held = held_levels.contains(commit);
                    if !held {
                        for index in 0..job.parts() {
                            delta::apply_job_part(
                                &txn,
                                &delta_source,
                                &job,
                                index,
                                checks,
                                &counters,
                            )
                            .await?;
                        }
                        txn.write_metadata(ObjectType::Commit, Some(commit), &job.commit_bytes)
                            .await?;
                    }
                    // A commit object can be as large as `MAX_METADATA_SIZE`,
                    // so the parse runs on the blocking pool.
                    let bytes = Arc::clone(&job.commit_bytes);
                    let parsed = ostrya_rt::unblock(move || Commit::parse(&bytes)).await?;
                    made.push(ChainCommit {
                        checksum: *commit,
                        root_dirtree: parsed.root_dirtree,
                        root_dirmeta: parsed.root_dirmeta,
                        held,
                        dependency: false,
                        detached: deltas.checked_detached(commit),
                    });
                }
                // Discovery counted the `.commitmeta` of each intermediate
                // commit.
                for chain_commit in &made {
                    self.import_planned(
                        &txn,
                        &sources,
                        chain_commit,
                        flags,
                        &mut plan,
                        &mut verify_buf,
                        count,
                    )
                    .await?;
                    self.import_detached_metadata(
                        &txn,
                        &sources,
                        &chain_commit.checksum,
                        chain_commit.detached,
                        related,
                        None,
                    )
                    .await?;
                }
            }

            // Apply each delta to a target whole, one part at a time, and then
            // stage its commit from the superblock. The import then walks each
            // commit and imports what no part produced. The pull takes or
            // parses the job of one target at a time, and drops it after its
            // parts. A target that a level made has its commit already.
            for (_, tip) in targets {
                if done.contains(tip) || txn.is_staged(tip, ObjectType::Commit) {
                    continue;
                }
                let job = match deltas.jobs.remove(tip) {
                    Some(job) => job,
                    None => match deltas.parse_record(self, &delta_source, tip).await? {
                        Some(job) => job,
                        None => continue,
                    },
                };
                for index in 0..job.parts() {
                    delta::apply_job_part(&txn, &delta_source, &job, index, checks, &counters)
                        .await?;
                }
                txn.write_metadata(ObjectType::Commit, Some(tip), &job.commit_bytes)
                    .await?;
            }
            // The deltas of the dependencies follow, in the order of the walk,
            // as the deltas of the targets. The pull parses the job of one
            // dependency at a time, and drops it after its parts.
            for chain_commit in &commits {
                if dependency_deltas.is_empty() {
                    break;
                }
                let dependency = &chain_commit.checksum;
                let Some(job) = dependency_deltas
                    .take_job(self, &delta_source, dependency)
                    .await?
                else {
                    continue;
                };
                for index in 0..job.parts() {
                    delta::apply_job_part(&txn, &delta_source, &job, index, checks, &counters)
                        .await?;
                }
                txn.write_metadata(ObjectType::Commit, Some(dependency), &job.commit_bytes)
                    .await?;
            }
            // The pull is done with the deltas, the inline part bodies of the
            // jobs that no target took included.
            drop(std::mem::take(&mut deltas));

            for chain_commit in &commits {
                let commit = &chain_commit.checksum;
                if done.contains(commit) {
                    continue;
                }
                self.import_planned(
                    &txn,
                    &sources,
                    chain_commit,
                    flags,
                    &mut plan,
                    &mut verify_buf,
                    count,
                )
                .await?;
                // A dependency that this repository holds complete keeps the
                // detached metadata of this repository.
                if !(chain_commit.dependency && chain_commit.held) {
                    self.import_detached_metadata(
                        &txn,
                        &sources,
                        commit,
                        chain_commit.detached,
                        related,
                        count,
                    )
                    .await?;
                }
            }
            if !opts.no_ref_writes {
                for (ref_name, tip) in targets {
                    place.queue(&txn, ref_name, tip);
                }
            }
            if completes_marked(&opts) {
                for commit in &marked {
                    txn.mark_complete(commit);
                }
            }
            txn.commit().await
        }
        .await;
        let stats = match published {
            Ok(stats) => stats,
            Err(e) => {
                self.clear_markers_for_absent_commits(&marked, marker_fsync)
                    .await;
                return Err(e);
            }
        };

        // The content that a marker guarded is published. A commit-only pull
        // keeps its markers, because it did not walk the trees.
        if completes_marked(&opts) {
            self.clear_markers(std::mem::take(&mut marked), marker_fsync)
                .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(),
        })
    }

    /// Plans the objects of `commit` with [`plan_commit`] and imports each
    /// one with [`import_object`](Repo::import_object).
    ///
    /// If `count` is set, the call counts each object that it read from the
    /// source, the first of `sources`, as a fetch counts it. An object from a
    /// localcache repository does not count. An object that a delta part
    /// staged is not planned, so it does not count either.
    #[allow(clippy::too_many_arguments)]
    async fn import_planned(
        &self,
        txn: &Transaction,
        sources: &[&Repo],
        commit: &ChainCommit,
        flags: PullFlags,
        plan: &mut PlanState,
        verify_buf: &mut Vec<u8>,
        count: Option<&PullCounters>,
    ) -> Result<()> {
        let names = plan_commit(txn, sources, commit, flags, plan).await?;
        #[cfg(test)]
        import_seam::run(self.repo_fd());
        for name in names {
            let imported = self
                .import_object(txn, sources, name, flags, verify_buf)
                .await?;
            if let Some(counters) = count
                && let Some((0, size)) = imported
            {
                count_fetched(counters, name.ty, size);
            }
        }
        Ok(())
    }

    /// Imports one object from the first source repository that holds it.
    ///
    /// Returns the position of that source in `sources` and the stored size of
    /// the object in that source. Returns `None` for an object that this
    /// repository already holds or has staged.
    ///
    /// `verify_buf` is the buffer of an untrusted verification for the payload
    /// of the object. The import loop keeps it, so the pull holds one buffer.
    async fn import_object(
        &self,
        txn: &Transaction,
        sources: &[&Repo],
        name: ObjectName,
        flags: PullFlags,
        verify_buf: &mut Vec<u8>,
    ) -> Result<Option<(usize, u64)>> {
        if txn.is_staged(&name.checksum, name.ty)
            || self.has_object(name.ty, &name.checksum).await?
        {
            return Ok(None);
        }
        for (position, src) in sources.iter().enumerate() {
            if let Some(size) = src.held_object_size(name.ty, &name.checksum).await? {
                self.import_from(txn, src, name, flags, verify_buf).await?;
                return Ok(Some((position, size)));
            }
        }
        Err(Error::ObjectNotFound {
            checksum: name.checksum,
            ty: name.ty,
        })
    }

    /// Imports one object that is present in `src`.
    async fn import_from(
        &self,
        txn: &Transaction,
        src: &Repo,
        name: ObjectName,
        flags: PullFlags,
        verify_buf: &mut Vec<u8>,
    ) -> Result<()> {
        if name.ty != ObjectType::File {
            // A metadata object is a plain file of its serialized bytes in each
            // mode, so the two repositories always store it in the same form.
            // An untrusted import reads the object once and writes the bytes
            // that it hashes, so a source that changes after the read cannot
            // pass the hash. The write charges each object in full.
            if flags.contains(PullFlags::UNTRUSTED) {
                let bytes = src.load_object_bytes(name.ty, &name.checksum).await?;
                #[cfg(test)]
                import_seam::run(self.repo_fd());
                txn.write_metadata_owned(name.ty, Some(&name.checksum), bytes)
                    .await?;
                return Ok(());
            }
            link_import(txn, src, name, flags).await?;
            return Ok(());
        }

        let same_mode = src.mode() == self.mode();
        let checks = ModeChecks::new(flags, self.mode());
        let untrusted = flags.contains(PullFlags::UNTRUSTED);

        // The mode checks read the logical form of the object, before each
        // import path. The link and the clone move bytes without a hash, so an
        // untrusted pull checks and hashes the staged object after them, as
        // `verify_staged_content` states. A `.filez` copy and a re-ingest hash
        // the object as they write it and compare the result with its name.
        // A second verification of them reads the payload twice, so the pull
        // makes none.
        let loaded = if checks.any() {
            let file = src.load_file(&name.checksum).await?;
            checks.check(&name.checksum, &file.meta())?;
            Some(file)
        } else {
            None
        };

        // Two repositories of one mode store a content object in the same form,
        // inode included, so the import shares the source inode.
        if same_mode && link_import(txn, src, name, flags).await? {
            if untrusted {
                verify_staged_content(txn, name, checks, verify_buf).await?;
            }
            return Ok(());
        }

        // The logical form of the object. The clone applies the inode policy
        // of the destination from its header, a `.filez` copy reads the
        // stored file of the source again, and a re-ingest streams its
        // payload. A refused link also gets here, at the cost of one
        // metadata read.
        let file = match loaded {
            Some(file) => file,
            None => src.load_file(&name.checksum).await?,
        };
        let meta = file.meta();
        match &file.kind {
            FileKind::Symlink { target } => {
                if symlink_shared(src.mode(), self.mode())
                    && link_import(txn, src, name, flags).await?
                {
                    if untrusted {
                        verify_staged_content(txn, name, checks, verify_buf).await?;
                    }
                    return Ok(());
                }
                // The identity of a symlink is its header alone. `write_symlink`
                // hashes it and compares the result with the name that it gets,
                // so this path verifies the object whatever the flags say.
                txn.write_symlink(target, &meta, Some(&name.checksum))
                    .await?;
            }
            FileKind::Regular { size } => {
                if payload_shared(src.mode(), self.mode()) {
                    txn.stage_clone_content(src, name.checksum, meta.regular_header(), *size)
                        .await?;
                    if untrusted {
                        verify_staged_content(txn, name, checks, verify_buf).await?;
                    }
                    return Ok(());
                }
                if src.mode().is_archive() && self.mode().is_archive() {
                    return import_filez(txn, src, name, &meta, verify_buf).await;
                }
                let reader = file.reader().await?;
                txn.write_content(Some(&name.checksum), &meta, reader)
                    .await?;
            }
        }
        Ok(())
    }

    /// Stages the detached metadata of a commit in `txn`, from the first
    /// source that holds it, through `rule`.
    ///
    /// If the rule keeps each property, the stored bytes are the bytes of the
    /// source unchanged. They get to `objects/` when `txn` commits. A source
    /// with no `.commitmeta`, and a dict of which the rule keeps no property,
    /// each leave the copy of the destination unchanged.
    ///
    /// If `count` is set, the call counts the `.commitmeta` as a fetch counts
    /// it when the bytes come from the source, the first of `sources`. The
    /// count is the length of the bytes that the call read, before the rule.
    /// A rule that fails counts the bytes first.
    ///
    /// `checked` is what the signature check of the commit read of the
    /// `.commitmeta`. If the sources do not hold the same `.commitmeta` now,
    /// the call stages nothing and fails.
    ///
    /// The read, the compare, and the rule run in one call on the blocking
    /// pool.
    ///
    /// # Errors
    ///
    /// [`Error::Pull`] if the `.commitmeta` that the sources hold is not the
    /// `.commitmeta` that `checked` gives.
    async fn import_detached_metadata(
        &self,
        txn: &Transaction,
        sources: &[&Repo],
        commit: &Checksum,
        checked: CheckedDetached,
        rule: RelatedRule,
        count: Option<&PullCounters>,
    ) -> Result<()> {
        let owned: Vec<Repo> = sources.iter().map(|src| (*src).clone()).collect();
        let key = *commit;
        let read = ostrya_rt::unblock(move || -> Result<_> {
            let held = detached_bytes_from_blocking(&owned, &key)?;
            if !checked.matches(held.as_ref().map(|(_, bytes)| bytes.as_slice())) {
                return Err(Error::Pull(format!(
                    "the .commitmeta of commit {key} changed after its signature check"
                )));
            }
            let Some((at, bytes)) = held else {
                return Ok(None);
            };
            let len = bytes.len() as u64;
            Ok(Some((at, len, rule.apply(&key, bytes))))
        })
        .await?;
        let Some((at, len, kept)) = read else {
            return Ok(());
        };
        if at == 0
            && let Some(counters) = count
        {
            count_fetched(counters, ObjectType::CommitMeta, len);
        }
        if let Some(bytes) = kept? {
            txn.stage_commit_detached_bytes(commit, bytes).await?;
        }
        Ok(())
    }

    /// Creates the `state/<commit>.commitpartial` marker of each of
    /// `commits` in one trip to the blocking pool, and writes `content` into
    /// each marker that the call creates.
    ///
    /// A pull writes zero-length markers, which it keeps while the objects of
    /// the commits are in flight. fsck writes the one state byte of the
    /// `ostree` command.
    ///
    /// An empty list does nothing. The call opens `state/` one time, and makes
    /// it if it is absent. It creates each marker with `O_EXCL`. With
    /// `fsync`, it syncs `state/` after the create of each marker. It does not
    /// sync the content of a marker.
    ///
    /// The call does not write over an entry that is present at the name of
    /// a marker, of any type, so the one-byte state that fsck writes stays.
    /// The `ostree` command does the same: its `pull-local` opens a marker
    /// that is present read-only, and creates a marker with `O_EXCL`.
    ///
    /// The module [`pull`](self) states the durability of the markers and the
    /// errors. The call stops at the first error.
    pub(crate) async fn create_partial_markers(
        &self,
        commits: Vec<Checksum>,
        content: &'static [u8],
        fsync: bool,
    ) -> Result<()> {
        if commits.is_empty() {
            return Ok(());
        }
        let repo = self.clone();
        ostrya_rt::unblock(move || {
            let state = repo.root_dir().ensure_layout(RepoLayout::State, fsync)?;
            for commit in &commits {
                create_partial_marker(&state, commit, content, fsync)?;
            }
            Ok(())
        })
        .await
    }

    /// Starts the create of the zero-length marker of `commit` on the
    /// blocking pool, as
    /// [`create_partial_markers`](Repo::create_partial_markers) creates one,
    /// and returns the handle of the job.
    ///
    /// The job continues if the handle drops. A pull from a remote gives the
    /// handle to its transaction, so that a failed run waits for the job
    /// before its cleanup.
    fn partial_marker_job(
        &self,
        commit: &Checksum,
        fsync: bool,
    ) -> ostrya_rt::JoinHandle<Result<()>> {
        let commit = *commit;
        let repo = self.clone();
        #[cfg(test)]
        let gate =
            crate::jobs::job_gate::key(self.repo_fd(), format!("marker {}", commit.to_hex()));
        ostrya_rt::unblock_task(move || {
            #[cfg(test)]
            let _gate = crate::jobs::job_gate::pass(&gate, repo.repo_fd())?;
            let state = repo.root_dir().ensure_layout(RepoLayout::State, fsync)?;
            create_partial_marker(&state, &commit, &[], fsync)
        })
    }

    /// Removes the `.commitpartial` marker of each of `commits` in one trip to
    /// the blocking pool.
    ///
    /// An empty list does nothing. An absent marker and an absent `state/` are
    /// a success. The call
    /// unlinks a symlink at the name of a marker, and its target stays. A
    /// directory at the name of a marker gives `EISDIR` for that commit. With
    /// `fsync`, the call syncs `state/` one time after the last unlink, if
    /// it unlinked an entry.
    ///
    /// The removal is the last operation of a pull, and no barrier follows it
    /// other than this sync. If a crash occurs before the unlink gets to the
    /// disk, the marker stays on a complete commit. The next pull of that
    /// commit, or a prune of it, clears it.
    ///
    /// Returns each commit whose marker stays, with the error, in the order of
    /// `commits`. The call tries each commit. The open of `state/` and its
    /// sync give the outer error.
    pub(crate) async fn remove_partial_markers(
        &self,
        commits: Vec<Checksum>,
        fsync: bool,
    ) -> Result<Vec<(Checksum, Error)>> {
        if commits.is_empty() {
            return Ok(Vec::new());
        }
        let repo = self.clone();
        ostrya_rt::unblock(move || {
            let Some(state) = repo.root_dir().open_layout(RepoLayout::State).optional()? else {
                return Ok(Vec::new());
            };
            let mut removed = false;
            let mut failed = Vec::new();
            for commit in commits {
                match state.remove_file(&partial_name(&commit), false) {
                    Ok(unlinked) => removed |= unlinked,
                    Err(e) => failed.push((commit, Error::from(e))),
                }
            }
            if removed && fsync {
                state.sync()?;
            }
            Ok(failed)
        })
        .await
    }

    /// Removes the markers of `marked` after the transaction of a pull
    /// published, and gives the outer error, or else the first error of a
    /// commit after the call tries each commit.
    async fn clear_markers(&self, marked: Vec<Checksum>, fsync: bool) -> Result<()> {
        let failed = self.remove_partial_markers(marked, fsync).await?;
        match failed.into_iter().next() {
            Some((_, e)) => Err(e),
            None => Ok(()),
        }
    }

    /// Removes the markers that a failed pull wrote for commits that this
    /// repository does not hold.
    ///
    /// `marked` is the list of markers that the pull wrote.
    /// The module [`pull`](self) states why such a marker guards nothing. A
    /// commit that this repository holds keeps its marker. The pull found that
    /// commit partial and kept the marker, so the state byte that fsck writes
    /// is in it.
    ///
    /// This function runs on the error path. It removes the markers in one
    /// call of [`remove_partial_markers`](Repo::remove_partial_markers) with
    /// `fsync`. It leaves a marker that it cannot remove, so the pull reports
    /// the error that ended it.
    async fn clear_markers_for_absent_commits(&self, marked: &[Checksum], fsync: bool) {
        let mut absent = Vec::new();
        for commit in marked {
            if matches!(self.has_object(ObjectType::Commit, commit).await, Ok(false)) {
                absent.push(*commit);
            }
        }
        let _ = self.remove_partial_markers(absent, fsync).await;
        #[cfg(test)]
        crate::jobs::job_gate::release(self.repo_fd());
    }
}

/// Returns `true` if a pull with `opts` completes each commit that it marks
/// partial.
///
/// A commit-only pull fetches no tree, and a pull with subpaths fetches part
/// of each tree, so both keep their markers. Each other pull removes its
/// markers after the commit of its transaction, and records each marked
/// commit as complete before it.
pub(crate) fn completes_marked(opts: &PullOptions) -> bool {
    !opts.flags.contains(PullFlags::COMMIT_ONLY) && opts.subpaths.is_empty()
}

/// Returns the `state/` path of the partial marker of a commit, relative to
/// the repository directory.
pub(crate) fn partial_path(commit: &Checksum) -> String {
    format!("state/{}.commitpartial", commit.to_hex())
}

/// Returns the name of the partial marker of a commit in `state/`.
pub(crate) fn partial_name(commit: &Checksum) -> String {
    format!("{}.commitpartial", commit.to_hex())
}

/// Creates the marker of `commit` in `state` with `O_EXCL`, and writes
/// `content` into the new file. An entry that is present at the name of the
/// marker stays as it is, and the call gives `Ok`. With `fsync`, the create
/// syncs `state/`.
fn create_partial_marker(
    state: &RepoDir,
    commit: &Checksum,
    content: &[u8],
    fsync: bool,
) -> Result<()> {
    match state.create_exclusive(&partial_name(commit), fsync) {
        Ok(mut file) => file.write_all(content).map_err(Error::Io),
        Err(FsError::Exists) => Ok(()),
        Err(e) => Err(e.into()),
    }
}

/// The place of the refs of a pull.
///
/// The pull writes each pulled ref at this place. Delta discovery, the
/// search for the delta of a dependency, and the timestamp check read the
/// current commit of a ref at the same place.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub(crate) enum RefPlace<'a> {
    /// The local refs, `refs/heads/<name>`.
    Heads,
    /// The refs of a collection, `refs/mirrors/<id>/<name>`.
    Collection(&'a str),
    /// The refs that the names of a pull give, as [`Repo::pull_local`] and
    /// [`Repo::pull`] state. An `@ID:NAME` name is the collection ref of
    /// `ID`, or the local ref `NAME` if `ID` is `own`, the
    /// `[core] collection-id` of the repository. Each other name is a ref
    /// of the remote `remote`, or a refspec if `remote` is `None`.
    Operands {
        /// The remote of a name that is not an `@ID:NAME` name.
        remote: Option<&'a str>,
        /// The `[core] collection-id` of the repository.
        own: Option<&'a str>,
    },
}

impl<'a> RefPlace<'a> {
    /// Returns the refs of the collection `id` in `repo`: the local refs if
    /// `id` is the `[core] collection-id` of `repo`, else the collection refs.
    pub(crate) fn of_collection(repo: &Repo, id: &'a str) -> RefPlace<'a> {
        if repo.config().collection_id() == Some(id) {
            RefPlace::Heads
        } else {
            RefPlace::Collection(id)
        }
    }

    /// Returns the path under the repository of the ref `name` at this place.
    ///
    /// # Errors
    ///
    /// [`Error::InvalidRefspec`] if the place and the name give no valid ref
    /// path.
    pub(crate) fn ref_path(self, name: &str) -> Result<String> {
        ref_relpath(None, &self.named(name))
    }

    /// Queues the write of the ref `name` at this place, to the commit `tip`,
    /// in `txn`.
    pub(crate) fn queue(self, txn: &Transaction, name: &str, tip: &Checksum) {
        txn.set_ref(&self.named(name), Some(tip));
    }

    /// Returns the ref `name` at this place. At [`RefPlace::Heads`], `name`
    /// is a refspec. The call does not check the ref.
    fn named(self, name: &str) -> Ref {
        match self {
            RefPlace::Heads => refspec_ref(name),
            RefPlace::Collection(id) => Ref::collection(id, name),
            RefPlace::Operands { remote, own } => match operand_collection(name) {
                Some((id, name)) => Ref::collection(id, name).canonical(own),
                None => match remote {
                    Some(remote) => Ref::remote(remote, name),
                    None => refspec_ref(name),
                },
            },
        }
    }
}

/// Resolves the refs to pull against the source: the requested names, or
/// each ref under `refs/heads` of the source if no name is given.
///
/// The function reads each name as a revision of `src`
/// ([`Repo::resolve_rev`]), and the target keeps the name as given.
async fn resolve_targets(src: &Repo, opts: &PullOptions) -> Result<Vec<(String, Checksum)>> {
    if opts.refs.is_empty() {
        return src.list_refs(None).await;
    }
    let mut out = Vec::with_capacity(opts.refs.len());
    for name in &opts.refs {
        let checksum = src
            .resolve_rev(name, false)
            .await?
            .ok_or_else(|| Error::RefNotFound(name.clone()))?;
        out.push((name.clone(), checksum));
    }
    Ok(out)
}

/// Returns the collection id and the rest of an `@ID:NAME` name of a pull,
/// or `None` if the name does not start with `@`. The rest of a name of a
/// local pull can hold a `^` suffix. [`check_local_operands`] and
/// [`check_remote_operands`] checked each name that starts with `@`, and a
/// mirror pull makes each other such name from a [`Ref`], so it holds a `:`.
fn operand_collection(name: &str) -> Option<(&str, &str)> {
    ostrya_core::split_collection(name)
}

/// Follows the parents of a commit in the source, and appends each commit
/// that is not collected yet.
///
/// `depth` is the number of parents to follow, `-1` for all of them. A parent
/// that the source does not hold ends the chain.
///
/// `seen` records, for each commit, the number of parents left to follow when
/// the walk got to it. If a chain gets to a commit with more parents left than
/// an earlier chain had, the walk continues from that commit. So the commits
/// of a pull do not depend on the order of the refs. The walk appends a commit
/// the first time that it gets to it, and not again.
///
/// `tip_commit` holds the bytes of the tip, the commit parsed from them, and
/// the format check of its field 2. The walk reads each parent from `src`.
/// If `untrusted` is set, the walk hashes each parent and compares the result
/// with the name of the parent before the parse. If `check` is present, it
/// runs on each commit when the walk appends it, over the bytes that the walk
/// read. The walk appends each commit with the root of its tree and with
/// what the check read of its `.commitmeta`, so the plan of the tree does not
/// read the commit object again.
///
/// The walk takes the format check of field 2 of each commit when it appends
/// the commit, also if `deps` is `None`. If `deps` is present, the walk
/// records the dependencies of each commit that it appends there. Unless
/// `deps` keeps the commits alone, the walk also records the parent of each
/// commit that it gets to.
///
/// # Errors
///
/// - [`Error::InvalidRelated`] if field 2 of a commit of the chain has an
///   entry with an empty name or with a checksum that is not 32 bytes.
/// - [`Error::ChecksumMismatch`] if `untrusted` is set and a parent does not
///   hash to its name.
#[allow(clippy::too_many_arguments)]
async fn collect_chain(
    src: &Repo,
    tip: Checksum,
    tip_commit: LoadedCommit,
    depth: i32,
    untrusted: bool,
    out: &mut Vec<ChainCommit>,
    seen: &mut HashMap<Checksum, i32>,
    mut check: Option<&mut ChainCheck<'_>>,
    mut deps: Option<&mut ChainDependencies>,
) -> Result<()> {
    let mut current = Some((tip, tip_commit));
    let mut remaining = depth;
    while let Some((
        checksum,
        LoadedCommit {
            bytes,
            commit,
            dependencies,
        },
    )) = current
    {
        if let Some(deps) = deps.as_deref_mut()
            && !deps.inner.keys_only()
        {
            deps.parents.insert(checksum, commit.parent);
        }
        if let Some(&prev) = seen.get(&checksum)
            && reaches_at_least(prev, remaining)
        {
            return Ok(());
        }
        if seen.insert(checksum, remaining).is_none() {
            let dependencies = dependencies?;
            let detached = match check.as_deref_mut() {
                Some(check) => check.check(&checksum, &bytes).await,
                None => CheckedDetached::Unchecked,
            };
            out.push(ChainCommit {
                checksum,
                root_dirtree: commit.root_dirtree,
                root_dirmeta: commit.root_dirmeta,
                held: false,
                dependency: false,
                detached,
            });
            if let Some(deps) = deps.as_deref_mut() {
                deps.inner.record(checksum, dependencies);
            }
        }
        drop(bytes);
        if remaining == 0 {
            return Ok(());
        }
        let Some(parent) = commit.parent else {
            return Ok(());
        };
        current = try_load_commit(src, &parent, untrusted)
            .await?
            .map(|parent_commit| (parent, parent_commit));
        if remaining > 0 {
            remaining -= 1;
        }
    }
    Ok(())
}

/// A commit that the walk of the chain collected, with the root of its tree
/// from the commit object that the walk read.
struct ChainCommit {
    checksum: Checksum,
    root_dirtree: Checksum,
    root_dirmeta: Checksum,
    /// The completeness state: `true` if this repository holds the commit
    /// object and no `.commitpartial` marker for it.
    ///
    /// The pull sets it when the transaction is open, where it writes the
    /// markers.
    held: bool,
    /// `true` for a dependency that the walk appended after the chains. Such
    /// a commit is a dependency alone: a target, a parent, and a commit of a
    /// chain are not appended.
    dependency: bool,
    /// What the signature check of the commit read of its `.commitmeta`.
    detached: CheckedDetached,
}

/// What the signature check of a commit of a local pull read of its
/// `.commitmeta` in the sources.
///
/// The check keeps the SHA-256 of the bytes alone, so the import can find
/// other bytes with no copy of the verified bytes.
#[derive(Clone, Copy)]
enum CheckedDetached {
    /// The pull checked no signature of the commit.
    Unchecked,
    /// No source held a `.commitmeta` of the commit.
    Absent,
    /// The source at position `at` held a `.commitmeta` of `len` bytes with
    /// the SHA-256 `digest`.
    Read {
        at: usize,
        len: u64,
        digest: Checksum,
    },
}

impl CheckedDetached {
    /// Returns `true` if `held`, the `.commitmeta` bytes that the sources
    /// hold now, are the bytes that the check read. A commit with no check
    /// matches each value.
    fn matches(&self, held: Option<&[u8]>) -> bool {
        match (self, held) {
            (CheckedDetached::Unchecked, _) => true,
            (CheckedDetached::Absent, held) => held.is_none(),
            (CheckedDetached::Read { digest, .. }, Some(bytes)) => {
                Checksum::sha256(bytes) == *digest
            }
            (CheckedDetached::Read { .. }, None) => false,
        }
    }
}

/// The dependencies that the walk of the chains of a local pull met, and the
/// commits that it checks them against.
struct ChainDependencies {
    /// The dependencies, in the order in which the pull first recorded them,
    /// and the commits that name them. The pull records the dependencies of
    /// the commits of the walk first, then the dependencies of the
    /// intermediate commits of the delta levels.
    inner: dependency::Dependencies,
    /// The parent that each commit of the chains named. Under
    /// [`keys_only`](dependency::Dependencies::keys_only), the map stays
    /// empty: a pull that reads no static delta pairs no dependency with a
    /// target, so it reads no parent.
    parents: HashMap<Checksum, Option<Checksum>>,
}

/// Appends each dependency of `deps` that the walk did not collect to `out`,
/// at depth 0, in the order of `deps`. Returns each appended dependency, in
/// the same order.
///
/// A dependency that `seen` holds, or that `made` holds, needs no read: the
/// walk collected it, or a chain of static deltas makes it. `made` holds the
/// intermediate commits of the chains, and `deps` holds their dependencies.
/// The call reads each other dependency from the first repository of
/// `sources` that holds it, else from `repo`. It follows no parent of a
/// dependency.
///
/// The function reads the dependencies that neither `seen` nor `made` holds in
/// one call on the blocking pool, in the order of `deps`. If `untrusted` is
/// set, it hashes each dependency that it reads from a source, as
/// [`load_dependencies_blocking`] states. The call stops at the first
/// failure. If no dependency needs a read, the function makes no call. The
/// call reads no dependency after the first dependency that `seen` or `made`
/// holds and that names dependencies of its own. If the caller drops the
/// future, the blocking call continues to the end of its list or to the first
/// failure.
///
/// The call checks no signature of a dependency. Field 2 of the commit that
/// names the dependency holds its checksum, and the checksum and the
/// signatures of that commit cover field 2. A dependency that the walk
/// collected, or that a chain makes, keeps the check of that role.
///
/// # Errors
///
/// - [`Error::InvalidRelated`] if a dependency names dependencies of its own.
///   The error names the commit that first named the dependency.
/// - [`Error::InvalidRelated`] if field 2 of a dependency that the call reads
///   has an entry with an empty name or with a checksum that is not 32 bytes.
///   The error names the dependency.
/// - [`Error::ObjectNotFound`] if neither a source nor `repo` holds a
///   dependency.
/// - [`Error::ChecksumMismatch`] if `untrusted` is set and a dependency that
///   the call reads from a source does not hash to its name.
/// - [`Error::Core`] if the commit object of a dependency does not parse.
/// - [`Error::InvalidFormat`] if the commit object of a dependency is larger
///   than [`MAX_METADATA_SIZE`](crate::MAX_METADATA_SIZE) or is not a regular
///   file, or if a symlink is on its path.
/// - [`Error::Io`] if a file system operation fails.
async fn collect_dependencies(
    repo: &Repo,
    sources: &[&Repo],
    deps: &ChainDependencies,
    made: &HashSet<Checksum>,
    untrusted: bool,
    out: &mut Vec<ChainCommit>,
    seen: &mut HashMap<Checksum, i32>,
) -> Result<Vec<Checksum>> {
    // The position in `deps.inner.order()` of each dependency to read, and
    // its checksum. A held dependency that names dependencies of its own
    // stops the list: the call reads no dependency after it.
    let order = deps.inner.order();
    let nested_error = |dependency: &Checksum| {
        deps.inner
            .nested_error(dependency)
            .expect("a commit names each dependency of the order")
    };
    let mut positions = Vec::new();
    let mut wanted = Vec::new();
    let mut stop = None;
    for (at, dependency) in order.iter().enumerate() {
        if seen.contains_key(dependency) || made.contains(dependency) {
            if deps.inner.naming().contains_key(dependency) {
                stop = Some(at);
                break;
            }
            continue;
        }
        positions.push(at);
        wanted.push(*dependency);
    }
    let mut loaded = Vec::new();
    if !wanted.is_empty() {
        let holders: Vec<Repo> = sources
            .iter()
            .map(|src| (*src).clone())
            .chain(std::iter::once(repo.clone()))
            .collect();
        // The closure gives the position in `wanted` of a nested dependency.
        // The names stay here.
        loaded = match ostrya_rt::unblock(move || {
            load_dependencies_blocking(&holders, &wanted, untrusted)
        })
        .await?
        {
            Ok(loaded) => loaded,
            Err(nested) => return Err(nested_error(&order[positions[nested]])),
        };
    }
    if let Some(at) = stop {
        return Err(nested_error(&order[at]));
    }
    let mut appended = Vec::with_capacity(loaded.len());
    for (at, dependency) in positions.into_iter().zip(loaded) {
        let checksum = order[at];
        seen.insert(checksum, 0);
        appended.push(checksum);
        out.push(ChainCommit {
            checksum,
            root_dirtree: dependency.root_dirtree,
            root_dirmeta: dependency.root_dirmeta,
            held: false,
            dependency: true,
            detached: CheckedDetached::Unchecked,
        });
    }
    Ok(appended)
}

/// The signature verification that a local pull runs on each commit of the
/// chain during the walk of the chain.
struct ChainCheck<'a> {
    /// The repository that the pull writes into. If no source holds a
    /// `.commitmeta`, the check reads the detached metadata of this repository.
    repo: &'a Repo,
    /// The source and the localcache repositories, in the order of the reads.
    sources: &'a [&'a Repo],
    verification: &'a verify::Verification,
    /// The deltas that discovery found. The check skips each commit whose
    /// signatures discovery checked.
    plan: &'a delta::DeltaPlan,
    /// The first check that failed.
    ///
    /// The commits after it get no check, and the walk continues, so the pull
    /// reports a defect that the walk finds before this failure.
    failed: Option<Error>,
}

impl ChainCheck<'_> {
    /// Checks `commit`, whose object holds `bytes`, unless a check failed
    /// before, and records a failure.
    ///
    /// Returns what the check read of the `.commitmeta`, or
    /// [`CheckedDetached::Unchecked`] after a failure.
    async fn check(&mut self, commit: &Checksum, bytes: &Arc<Vec<u8>>) -> CheckedDetached {
        if self.failed.is_some() {
            return CheckedDetached::Unchecked;
        }
        match self.check_one(commit, bytes).await {
            Ok(detached) => detached,
            Err(err) => {
                self.failed = Some(err);
                CheckedDetached::Unchecked
            }
        }
    }

    /// Checks `commit`, whose object holds `bytes`, against the commit policy.
    ///
    /// A commit that discovery checked passes with no read, with what
    /// discovery read of its `.commitmeta`.
    async fn check_one(&self, commit: &Checksum, bytes: &Arc<Vec<u8>>) -> Result<CheckedDetached> {
        if self.plan.checked(commit) {
            return Ok(self.plan.checked_detached(commit));
        }
        // The verification reads the detached metadata as the source holds
        // it. That is the `.commitmeta` of the first source that holds one,
        // else that of this repository. The rule of `[ex-ostrya]
        // keep-detached-related` can make the stored metadata smaller, so a
        // later verification of the stored commit reads what the rule kept.
        let sources: Vec<Repo> = self.sources.iter().map(|src| (*src).clone()).collect();
        check_local_commit_signatures(self.repo, self.verification, sources, commit, bytes.into())
            .await
    }
}

/// Checks the signatures of `commit`, whose object holds `bytes`, against the
/// commit policy of `verification`, and gives back `detached`.
///
/// `detached` is the `.commitmeta` that the pull puts in place. If it is
/// `None`, the check reads the detached metadata of `repo`. A policy that does
/// not apply to commits passes each commit and reads nothing.
///
/// The parse of the detached metadata runs on the blocking pool, because the
/// bytes can be as large as
/// [`MAX_METADATA_SIZE`](crate::MAX_METADATA_SIZE).
async fn check_commit_signatures(
    repo: &Repo,
    verification: &verify::Verification,
    commit: &Checksum,
    bytes: Payload<'_>,
    detached: Option<Vec<u8>>,
) -> Result<Option<Vec<u8>>> {
    if !verification.checks_commits() {
        return Ok(detached);
    }
    let (dict, detached) = match detached {
        Some(detached) => {
            let (dict, detached) = parse_detached(detached).await;
            (dict?, Some(detached))
        }
        None => match repo
            .held_object_bytes(ObjectType::CommitMeta, commit)
            .await?
        {
            Some(held) => (parse_detached(held).await.0?, None),
            None => (None, None),
        },
    };
    verification
        .check_commit(commit, bytes, dict.as_ref())
        .await?;
    Ok(detached)
}

/// Checks the signatures of `commit`, whose object holds `bytes`, against the
/// commit policy of `verification`, for a pull from local sources.
///
/// The check reads the `.commitmeta` of the first repository of `sources` that
/// holds one, as [`detached_bytes_from_blocking`] does. If no source holds
/// one, it reads the `.commitmeta` of `repo`, this repository. The reads and
/// the parse run in one call on the blocking pool, because the bytes can be as
/// large as [`MAX_METADATA_SIZE`](crate::MAX_METADATA_SIZE). The errors are
/// the errors of [`check_commit_signatures`] over the bytes of the sources, in
/// the same order.
///
/// Returns what the check read of the `.commitmeta` in the sources: the
/// position in `sources`, the length, and the SHA-256 of the bytes, or
/// [`CheckedDetached::Absent`] if no source holds one. The caller makes sure
/// that the policy checks commits.
async fn check_local_commit_signatures(
    repo: &Repo,
    verification: &verify::Verification,
    sources: Vec<Repo>,
    commit: &Checksum,
    bytes: Payload<'_>,
) -> Result<CheckedDetached> {
    let repo = repo.clone();
    let key = *commit;
    let (read, dict) = ostrya_rt::unblock(move || -> Result<_> {
        if let Some((at, held)) = detached_bytes_from_blocking(&sources, &key)? {
            let dict = crate::summary::parse_signature_dict(&held)?;
            let read = CheckedDetached::Read {
                at,
                len: held.len() as u64,
                digest: Checksum::sha256(&held),
            };
            return Ok((read, dict));
        }
        let dict = match repo.held_object_bytes_blocking(ObjectType::CommitMeta, &key)? {
            Some(held) => crate::summary::parse_signature_dict(&held)?,
            None => None,
        };
        Ok((CheckedDetached::Absent, dict))
    })
    .await?;
    verification
        .check_commit(commit, bytes, dict.as_ref())
        .await?;
    Ok(read)
}

/// The `.commitmeta` that the pull puts in place for a commit, after the
/// signature check of the commit.
enum CheckedMeta {
    /// The bytes as the source holds them. The rule did not run.
    Source(Vec<u8>),
    /// The result of the rule: the bytes to stage, or `None` if the pull
    /// stages nothing.
    Filtered(Option<Vec<u8>>),
}

impl CheckedMeta {
    /// Gives the bytes that the pull stages, or `None` if it stages nothing.
    ///
    /// [`CheckedMeta::Source`] goes through
    /// [`apply_on_pool`](RelatedRule::apply_on_pool).
    async fn filtered(self, rule: RelatedRule, commit: &Checksum) -> Result<Option<Vec<u8>>> {
        match self {
            CheckedMeta::Source(bytes) => rule.apply_on_pool(commit, bytes).await,
            CheckedMeta::Filtered(kept) => Ok(kept),
        }
    }
}

/// Checks the signatures of `commit` as [`check_commit_signatures`] does, and
/// runs `rule` over `detached` if the check parses it.
///
/// If the policy checks commits, `rule` drops `ostrya.related`, and `detached`
/// is `Some`, the rule reads the dict that the check parsed. The rule runs on
/// the blocking pool after the check, so the call parses `detached` one time
/// and gives [`CheckedMeta::Filtered`]. Else the call gives the bytes that
/// [`check_commit_signatures`] gives back, as [`CheckedMeta::Source`].
async fn check_commit_signatures_filtered(
    repo: &Repo,
    verification: &verify::Verification,
    rule: RelatedRule,
    commit: &Checksum,
    bytes: Payload<'_>,
    detached: Option<Vec<u8>>,
) -> Result<Option<CheckedMeta>> {
    match detached {
        Some(detached) if verification.checks_commits() && rule.drop_related => {
            let (dict, detached) = parse_detached(detached).await;
            let dict = dict?;
            verification
                .check_commit(commit, bytes, dict.as_ref())
                .await?;
            // The zero-length marker parses to `None`, and `apply` gives it
            // back unchanged.
            let Some(dict) = dict else {
                return Ok(Some(CheckedMeta::Filtered(Some(detached))));
            };
            let commit = *commit;
            let kept =
                ostrya_rt::unblock(move || rule.apply_parsed(&commit, detached, dict)).await?;
            Ok(Some(CheckedMeta::Filtered(kept)))
        }
        detached => Ok(
            check_commit_signatures(repo, verification, commit, bytes, detached)
                .await?
                .map(CheckedMeta::Source),
        ),
    }
}

/// Parses the `.commitmeta` bytes `bytes` on the blocking pool, and gives
/// back the bytes with the result.
///
/// A zero-length file reads as `None`, as
/// [`Repo::read_commit_detached_metadata`] states.
async fn parse_detached(bytes: Vec<u8>) -> (Result<Option<Value>>, Vec<u8>) {
    ostrya_rt::unblock(move || {
        let dict = crate::summary::parse_signature_dict(&bytes);
        (dict, bytes)
    })
    .await
}

/// The object names that the plans of a pull met so far, planned or found
/// present.
///
/// The commit loop keeps it, so the walk reads the trees of the chain as one
/// tree.
#[derive(Default)]
struct PlanState {
    seen: HashSet<ObjectName>,
}

impl PlanState {
    /// Adds a name to `out` unless a walk met it before.
    ///
    /// The held state of the name starts as `false`, and [`plan_absent`] sets
    /// it.
    fn meet(&mut self, name: ObjectName, out: &mut Vec<(ObjectName, bool)>) {
        if self.seen.insert(name) {
            out.push((name, false));
        }
    }
}

/// Returns the objects of one commit, in import order.
///
/// The metadata and the content of the tree come first, and the commit object
/// last. So a partly imported transaction never holds a commit before the
/// objects that it refers to. Under [`COMMIT_ONLY`](PullFlags::COMMIT_ONLY)
/// the walk skips the tree, and the commit object is the whole plan. A commit
/// that this repository holds complete gives no object: the objects that it
/// refers to are present, and the walk reads nothing.
///
/// The root of the tree comes from the commit object that the walk of the
/// chain read. Under [`UNTRUSTED`](PullFlags::UNTRUSTED), the walk hashes each
/// dirtree that it reads from a source before the parse, as
/// [`load_dirtree_from`] states. [`plan_absent`] finds the objects that this
/// repository lacks: first the root dirtree and dirmeta, then the children of
/// each dirtree. It makes one blocking call for each dirtree.
/// [`pull_local`](Repo::pull_local) states the rules of the walk. A dirtree
/// that `txn` staged from a delta part counts as held. A dirtree that neither
/// this repository nor a source holds gives its own name and nothing below it.
///
/// `state` holds what the commits before this one met. So the walk descends
/// into a dirtree that the chain shares once, and checks each object once.
async fn plan_commit(
    txn: &Transaction,
    sources: &[&Repo],
    commit: &ChainCommit,
    flags: PullFlags,
    state: &mut PlanState,
) -> Result<Vec<ObjectName>> {
    if commit.held {
        return Ok(Vec::new());
    }
    let commit_name = ObjectName::new(commit.checksum, ObjectType::Commit);
    if flags.contains(PullFlags::COMMIT_ONLY) {
        return Ok(vec![commit_name]);
    }
    // The own tree of this commit. The walk of the chain supplies the parents.
    let mut names: Vec<ObjectName> = Vec::new();
    // The dirtrees left to read, each with its held state in this repository.
    let mut stack: Vec<(Checksum, bool)> = Vec::new();
    let mut met: Vec<(ObjectName, bool)> = Vec::new();
    state.meet(
        ObjectName::new(commit.root_dirmeta, ObjectType::DirMeta),
        &mut met,
    );
    state.meet(
        ObjectName::new(commit.root_dirtree, ObjectType::DirTree),
        &mut met,
    );
    plan_absent(txn, met, &mut names, &mut stack).await?;
    while let Some((checksum, here)) = stack.pop() {
        let dirtree = if here {
            txn.load_dirtree_staged_first(&checksum).await?
        } else {
            match load_dirtree_from(sources, &checksum, flags.contains(PullFlags::UNTRUSTED))
                .await?
            {
                Some(dirtree) => dirtree,
                None => continue,
            }
        };
        let mut met: Vec<(ObjectName, bool)> = Vec::new();
        for (_, file) in dirtree.files {
            state.meet(ObjectName::new(file, ObjectType::File), &mut met);
        }
        for (_, subtree, submeta) in dirtree.dirs {
            state.meet(ObjectName::new(submeta, ObjectType::DirMeta), &mut met);
            state.meet(ObjectName::new(subtree, ObjectType::DirTree), &mut met);
        }
        plan_absent(txn, met, &mut names, &mut stack).await?;
    }
    // `Checksum` sorts by its raw bytes, which gives the ASCII order of the hex
    // names, so the key needs no formatting.
    names.sort_by_key(|name| (name.ty.as_u32(), name.checksum));
    names.push(commit_name);
    Ok(names)
}

/// Adds each name of `met` that this repository lacks to `names`, and pushes
/// each dirtree of `met` on `stack` with its held state.
///
/// A name that `txn` staged is held. Each other name is held if
/// [`Repo::has_object`] finds it: a `stat` that does not follow a symlink, the
/// same check as the import. One blocking call checks the names that `txn`
/// did not stage. If `met` holds no such name, the function makes no call.
async fn plan_absent(
    txn: &Transaction,
    mut met: Vec<(ObjectName, bool)>,
    names: &mut Vec<ObjectName>,
    stack: &mut Vec<(Checksum, bool)>,
) -> Result<()> {
    let mut unstaged = false;
    for (name, here) in &mut met {
        *here = txn.is_staged(&name.checksum, name.ty);
        unstaged |= !*here;
    }
    if unstaged {
        let repo = txn.repo().clone();
        met = ostrya_rt::unblock(move || -> Result<Vec<(ObjectName, bool)>> {
            for (name, here) in &mut met {
                if !*here {
                    *here = repo.has_object_blocking(name.ty, &name.checksum)?;
                }
            }
            Ok(met)
        })
        .await?;
    }
    for (name, here) in met {
        if name.ty == ObjectType::DirTree {
            stack.push((name.checksum, here));
        }
        if !here {
            names.push(name);
        }
    }
    Ok(())
}

/// Counts one object that a local pull read from its source, as a fetch counts
/// it.
///
/// The count is one metadata or content object fetched, and `size`, the stored
/// size in the source, transferred.
fn count_fetched(counters: &PullCounters, ty: ObjectType, size: u64) {
    match ty {
        ObjectType::File => counters.content_fetched(),
        _ => counters.metadata_fetched(),
    }
    counters.add_transferred(size);
}

/// A commit that a local pull read: its bytes, the commit parsed from them,
/// and the result of the format check of field 2.
struct LoadedCommit {
    /// The bytes of the commit. The signature check gives them to the
    /// blocking pool in this `Arc`, with no copy.
    bytes: Arc<Vec<u8>>,
    /// The parsed commit. Its field 2 is empty: the entries are in
    /// `dependencies`.
    commit: Commit,
    /// The entries of field 2 as names and checksums, in the stored order, or
    /// the [`Error::InvalidRelated`] of the first defective entry. The caller
    /// takes the result at its own point, so it sets the order of the errors.
    dependencies: Result<Vec<(String, Checksum)>>,
}

/// What a local pull keeps of a dependency that it read: the root of its
/// tree.
struct LoadedDependency {
    root_dirtree: Checksum,
    root_dirmeta: Checksum,
}

/// Parses the bytes of the commit `checksum` and checks the format of its
/// field 2. The entries of field 2 move out of the parse.
///
/// The call runs on the calling thread. A caller on the executor calls it on
/// the blocking pool.
fn parse_loaded(checksum: Checksum, bytes: Arc<Vec<u8>>) -> Result<LoadedCommit> {
    let mut commit = Commit::parse(&bytes)?;
    let related = std::mem::take(&mut commit.related);
    Ok(LoadedCommit {
        bytes,
        commit,
        dependencies: related::checked_dependencies(&checksum, related),
    })
}

/// Loads a commit from a repository: its bytes, the commit parsed from them,
/// and the format check of its field 2.
///
/// If `hash` is set, the call hashes the bytes and compares the result with
/// `checksum` before the parse.
///
/// A commit object can be as large as [`MAX_METADATA_SIZE`](crate::MAX_METADATA_SIZE),
/// so the read, the hash, the parse, and the check run in one call on the
/// blocking pool.
///
/// # Errors
///
/// [`Error::ChecksumMismatch`] if `hash` is set and the bytes do not hash to
/// `checksum`.
async fn load_commit(repo: &Repo, checksum: &Checksum, hash: bool) -> Result<LoadedCommit> {
    let repo = repo.clone();
    let checksum = *checksum;
    ostrya_rt::unblock(move || {
        let bytes = repo.load_object_bytes_blocking(ObjectType::Commit, &checksum)?;
        if hash {
            check_hash(&checksum, &bytes)?;
        }
        parse_loaded(checksum, Arc::new(bytes))
    })
    .await
}

/// Loads a commit as [`load_commit`] does, or returns `None` for an absent
/// object.
async fn try_load_commit(
    repo: &Repo,
    checksum: &Checksum,
    hash: bool,
) -> Result<Option<LoadedCommit>> {
    match load_commit(repo, checksum, hash).await {
        Ok(loaded) => Ok(Some(loaded)),
        Err(Error::ObjectNotFound { .. }) => Ok(None),
        Err(e) => Err(e),
    }
}

/// Loads the dependencies `wanted`, in order, each from the first repository
/// of `holders` that holds it.
///
/// For each dependency, the call parses the commit and checks the format of
/// its field 2. If `untrusted` is set, it first hashes a commit that it read
/// from a repository other than the last of `holders`, and compares the
/// result with the checksum of the dependency. It keeps the root of the tree
/// of the commit alone, and drops the bytes before it reads the next
/// dependency. It stops at the first failure. The inner `Err` holds the
/// position in `wanted` of a dependency that names dependencies of its own.
///
/// The function reads on the calling thread. A caller on the executor calls
/// it in one call on the blocking pool for all dependencies.
///
/// # Errors
///
/// - [`Error::ObjectNotFound`] if no repository of `holders` holds a
///   dependency.
/// - [`Error::ChecksumMismatch`] if `untrusted` is set and a commit that the
///   call hashes does not hash to the checksum of its dependency.
/// - [`Error::InvalidRelated`] if field 2 of a dependency has an entry with
///   an empty name or with a checksum that is not 32 bytes. The error names
///   the dependency.
/// - The errors of [`parse_loaded`], and the errors of the read of a commit
///   object other than an absent object.
fn load_dependencies_blocking(
    holders: &[Repo],
    wanted: &[Checksum],
    untrusted: bool,
) -> Result<std::result::Result<Vec<LoadedDependency>, usize>> {
    let mut loaded = Vec::with_capacity(wanted.len());
    for (at, checksum) in wanted.iter().enumerate() {
        let mut bytes = None;
        for (position, held) in holders.iter().enumerate() {
            if let Some(read) = held.held_object_bytes_blocking(ObjectType::Commit, checksum)? {
                if untrusted && position + 1 < holders.len() {
                    check_hash(checksum, &read)?;
                }
                bytes = Some(read);
                break;
            }
        }
        let Some(bytes) = bytes else {
            return Err(Error::ObjectNotFound {
                checksum: *checksum,
                ty: ObjectType::Commit,
            });
        };
        let LoadedCommit {
            commit,
            dependencies,
            ..
        } = parse_loaded(*checksum, Arc::new(bytes))?;
        if !dependencies?.is_empty() {
            return Ok(Err(at));
        }
        loaded.push(LoadedDependency {
            root_dirtree: commit.root_dirtree,
            root_dirmeta: commit.root_dirmeta,
        });
    }
    Ok(Ok(loaded))
}

/// Reads the `.commitmeta` bytes of a commit from the first source that holds
/// that object, or returns `None` if no source holds one.
///
/// The result holds the position of that source in `sources` and the bytes.
///
/// This function alone selects the detached metadata of a local pull. The
/// signature verification reads these bytes and keeps their SHA-256.
/// [`Repo::import_detached_metadata`] reads them again, compares their
/// SHA-256, and writes them, so the verified metadata and the stored metadata
/// agree. A
/// zero-length file counts as a source that holds one. It is the "no metadata"
/// marker, and it replaces the copy of the destination.
///
/// The function reads on the calling thread. A caller on the executor calls
/// it in one call on the blocking pool for all sources.
fn detached_bytes_from_blocking(
    sources: &[Repo],
    commit: &Checksum,
) -> Result<Option<(usize, Vec<u8>)>> {
    for (at, src) in sources.iter().enumerate() {
        if let Some(bytes) = src.held_object_bytes_blocking(ObjectType::CommitMeta, commit)? {
            return Ok(Some((at, bytes)));
        }
    }
    Ok(None)
}

/// Hashes `bytes` and compares the result with `expected`, the checksum of
/// the object that the bytes are read as.
///
/// # Errors
///
/// [`Error::ChecksumMismatch`] if the bytes do not hash to `expected`.
fn check_hash(expected: &Checksum, bytes: &[u8]) -> Result<()> {
    let actual = Checksum::sha256(bytes);
    if actual != *expected {
        return Err(Error::ChecksumMismatch {
            expected: *expected,
            actual,
        });
    }
    Ok(())
}

/// Loads a dirtree from the first source that holds it, or returns `None` if
/// no source holds it.
///
/// If `untrusted` is set, the call hashes the bytes and compares the result
/// with `checksum` before the parse. The read, the hash, and the parse then
/// run in one call on the blocking pool.
///
/// # Errors
///
/// [`Error::ChecksumMismatch`] if `untrusted` is set and the bytes do not
/// hash to `checksum`.
async fn load_dirtree_from(
    sources: &[&Repo],
    checksum: &Checksum,
    untrusted: bool,
) -> Result<Option<DirTree>> {
    for src in sources {
        let loaded = if untrusted {
            let src = (*src).clone();
            let checksum = *checksum;
            ostrya_rt::unblock(move || {
                let bytes = src.load_object_bytes_blocking(ObjectType::DirTree, &checksum)?;
                check_hash(&checksum, &bytes)?;
                Ok(DirTree::parse(&bytes)?)
            })
            .await
        } else {
            src.load_dirtree(checksum).await
        };
        match loaded {
            Ok(dirtree) => return Ok(Some(dirtree)),
            Err(Error::ObjectNotFound { .. }) => continue,
            Err(e) => return Err(e),
        }
    }
    Ok(None)
}

/// The refs of a collection pull from one candidate, and the checks of their
/// commits.
///
/// The pull from a remote and the pull from a local candidate read it.
struct Pinned<'a> {
    /// Each ref name, and the commit that the pull selected for it.
    targets: Vec<(String, Checksum)>,
    /// The timestamp that the candidate listed for each ref of `targets`,
    /// which the timestamp of its tip must equal.
    listed: HashMap<String, u64>,
    /// The collection id that the `ostree.collection-binding` of each tip
    /// must state.
    collection: &'a str,
    /// `true` if a tip with no `ostree.collection-binding` key passes the
    /// collection-binding check.
    allow_unbound: bool,
    /// The place of the written refs.
    place: RefPlace<'a>,
    /// The `summary` of a remote candidate, if the probe read the refs from
    /// it. The probe checked it under the trust of this pull, so the pull
    /// from the remote reads these bytes in place of the `summary` and the
    /// `summary.sig`, and does not check them again. The pull takes them out
    /// before the parse. `None` for a local candidate: its pull reads and
    /// checks the summary of the source again.
    summary: Mutex<Option<Arc<Vec<u8>>>>,
}

/// The refs of a local pull.
enum LocalWanted<'a> {
    /// The refs of [`refs`](PullOptions::refs), or each ref under
    /// `refs/heads` of the source if the list is empty. The pull reads the
    /// commit of each name from the source as a revision
    /// ([`resolve_targets`]).
    Named,
    /// The refs of a collection pull from a local candidate, each at the
    /// commit that the probe of the candidate selected.
    ///
    /// The pull reads no ref of the source, and does not read
    /// [`refs`](PullOptions::refs). It reads each tip commit from the source,
    /// and checks it against [`listed`](Pinned::listed), as the pull from a
    /// remote does. It does not read [`summary`](Pinned::summary).
    Pinned(&'a Pinned<'a>),
}

impl Repo {
    /// Pulls the refs `targets` of the collection `collection` from the local
    /// repository `src`, each at its commit, under the trust `trust` and the
    /// timestamp check `timestamp_check`.
    ///
    /// The pull is the pull of a local candidate of [`Repo::pull_collection`]
    /// at depth 0, with no static delta. It takes the `.commitmeta` and the
    /// dependencies of field 2 of each commit. It writes each ref at
    /// [`RefPlace::of_collection`]. The `ostree.collection-binding` of each
    /// tip must state `collection`, and the ref-binding check applies. If
    /// `listed` holds a timestamp for a ref, the timestamp of its tip must
    /// equal it. If `trust` checks signatures, the pull adds
    /// [`UNTRUSTED`](PullFlags::UNTRUSTED) to its flags.
    pub(crate) async fn pull_local_pinned(
        &self,
        src: &Repo,
        collection: &str,
        targets: Vec<(String, Checksum)>,
        listed: HashMap<String, u64>,
        trust: crate::verify::PullTrust,
        timestamp_check: TimestampCheck,
    ) -> Result<PullStats> {
        let pinned = Pinned {
            targets,
            listed,
            collection,
            allow_unbound: false,
            place: RefPlace::of_collection(self, collection),
            summary: Mutex::new(None),
        };
        let flags = if trust.checks_signatures() {
            PullFlags::UNTRUSTED
        } else {
            PullFlags::default()
        };
        let opts = PullOptions {
            disable_static_deltas: true,
            flags,
            timestamp_check,
            ..PullOptions::default()
        };
        self.pull_local_from(
            src,
            trust,
            RelatedRule::of(self.config())?,
            opts,
            LocalWanted::Pinned(&pinned),
            None,
            Instant::now(),
        )
        .await
    }
}

/// Checks each name of a local pull that starts with `@`.
///
/// Less each `^` at its end, the name must be an `@ID:NAME` ref that
/// [`Ref`] reads. The function refuses each other such name with
/// [`Error::InvalidRefspec`], which holds the name as given. The check reads
/// nothing.
fn check_local_operands(opts: &PullOptions) -> Result<()> {
    for name in opts.refs.iter().filter(|name| name.starts_with('@')) {
        if name.trim_end_matches('^').parse::<Ref>().is_err() {
            return Err(Error::InvalidRefspec(name.clone()));
        }
    }
    Ok(())
}

/// Refuses two different names of a local pull that write one ref.
///
/// Each name of [`refs`](PullOptions::refs) writes its ref at
/// [`RefPlace::Operands`] of [`remote`](PullOptions::remote) and of the
/// `[core] collection-id` of `repo`. A name given two times counts one time.
/// Under [`no_ref_writes`](PullOptions::no_ref_writes) the pull writes no ref,
/// and the function checks nothing. The check reads nothing.
///
/// # Errors
///
/// The errors of [`check_one_place`].
fn check_local_places(repo: &Repo, opts: &PullOptions) -> Result<()> {
    if opts.no_ref_writes {
        return Ok(());
    }
    let place = RefPlace::Operands {
        remote: opts.remote.as_deref(),
        own: repo.config().collection_id(),
    };
    let mut seen = HashSet::new();
    check_one_place(
        place,
        opts.refs
            .iter()
            .map(String::as_str)
            .filter(|name| seen.insert(*name))
            .map(|name| (name, name)),
    )
}

/// Refuses two refs of a pull that write one ref at `place`.
///
/// Each item is a name of the pull and its target. No two items have the
/// same name.
///
/// # Errors
///
/// - [`Error::InvalidRefspec`] if a target gives no valid ref path.
/// - [`Error::Pull`] if two targets write one ref. The error names both
///   names and the ref path.
fn check_one_place<'a>(
    place: RefPlace<'_>,
    refs: impl Iterator<Item = (&'a str, &'a str)>,
) -> Result<()> {
    let mut paths: HashMap<String, &str> = HashMap::new();
    for (name, target) in refs {
        let path = place.ref_path(target)?;
        if let Some(first) = paths.get(path.as_str()) {
            return Err(Error::Pull(format!(
                "the refs {first} and {name} write one ref {path}"
            )));
        }
        paths.insert(path, name);
    }
    Ok(())
}

/// Checks each name of a pull from a remote.
///
/// Each name must be a ref `NAME` or a collection ref `@ID:NAME` that
/// [`Ref`] reads. The function refuses each other name with
/// [`Error::InvalidRefspec`], which holds the name as given: a remote ref
/// `REMOTE:NAME`, a `^` suffix, and a part that fails its rule. The check
/// reads nothing.
fn check_remote_operands(opts: &PullOptions) -> Result<()> {
    for name in &opts.refs {
        match name.parse::<Ref>() {
            Ok(Ref::Local { .. } | Ref::Collection { .. }) => {}
            _ => return Err(Error::InvalidRefspec(name.clone())),
        }
    }
    Ok(())
}

/// Refuses a [`remote`](PullOptions::remote) that
/// [`valid_remote_name`](crate::config::valid_remote_name) refuses.
///
/// The name is the prefix of the written refs. A pull from a remote makes this
/// check before its first request, also under [`MIRROR`](PullFlags::MIRROR). A
/// local pull makes this check before it reads the source or a keyring.
fn check_remote_option(opts: &PullOptions) -> Result<()> {
    match opts.remote.as_deref() {
        Some(name) if !crate::config::valid_remote_name(name) => {
            Err(Error::InvalidInput(format!("invalid remote name: {name}")))
        }
        _ => Ok(()),
    }
}

/// Refuses a depth below -1.
fn check_depth(depth: i32) -> Result<()> {
    if depth < -1 {
        return Err(Error::InvalidInput(format!("depth {depth} is below -1")));
    }
    Ok(())
}

/// Refuses a list of static deltas that a pull cannot take with its other
/// options.
///
/// The check reads `opts` alone, so a refusal sends no request and opens no
/// transaction. A pull with no list passes.
fn check_static_deltas(opts: &PullOptions) -> Result<()> {
    if opts.static_deltas.is_none() {
        return Ok(());
    }
    if opts.disable_static_deltas {
        return Err(Error::InvalidInput(
            "a pull with static_deltas takes no disable_static_deltas option".into(),
        ));
    }
    if !opts.subpaths.is_empty() {
        return Err(Error::InvalidInput(
            "a pull with static_deltas takes no subpath".into(),
        ));
    }
    Ok(())
}

/// Takes the list of static deltas out of `opts` as the index of its deltas.
///
/// The index sorts the list on the blocking pool. The entry points call this
/// function after their other checks, because the sort of a long list costs
/// time. A pull with no list gets `None`. After the call,
/// `opts.static_deltas` is `None`, and the pull reads the list from the index
/// alone.
///
/// # Errors
///
/// [`Error::InvalidInput`] if two entries have the same source and target
/// and different digests.
async fn take_static_deltas(opts: &mut PullOptions) -> Result<Option<chain::Edges>> {
    let Some(list) = opts.static_deltas.take() else {
        return Ok(None);
    };
    ostrya_rt::unblock(move || chain::Edges::new(list))
        .await
        .map(Some)
}

/// Reads the `summary` of the local repository `src`, and checks it if
/// `verification` checks the summary.
///
/// The function reads `summary` if `verification` checks the summary or if
/// `needed` is `true`. It reads `summary.sig` only if `verification` checks
/// the summary and `summary` exists. It reads each file under
/// [`SUMMARY_READ_CAP`](crate::summary::SUMMARY_READ_CAP) with one `openat2`
/// that follows no symlink, and refuses a file that is not a regular file. A
/// FIFO does not block the open. If `verification` checks the summary, the
/// function gives the two files to
/// [`Verification::check_summary`](verify::Verification::check_summary).
///
/// Under the summary verification, with no `summary` the call does not read
/// `summary.sig`, and a missing file stops the call before the check. So
/// under the summary verification, a call that succeeds returns `Some`.
///
/// Without the summary verification, returns `None` if `src` has no
/// `summary`, or if the function does not read it.
///
/// # Errors
///
/// - [`Error::Signature`] if `verification` checks the summary and `src` has
///   no `summary` or no `summary.sig`, or if the summary fails the policy.
/// - [`Error::InvalidFormat`] if a file that the function reads is a symlink
///   or is not a regular file, or is longer than the cap.
/// - [`Error::Io`] if a file cannot be opened or read.
/// - The other errors of
///   [`Verification::check_summary`](verify::Verification::check_summary).
async fn read_checked_local_summary(
    src: &Repo,
    verification: &verify::Verification,
    needed: bool,
) -> Result<Option<Arc<Vec<u8>>>> {
    let checks_summary = verification.checks_summary();
    let root = src.root_dir().clone();
    let (summary, signature) = ostrya_rt::unblock(move || {
        let summary = if checks_summary || needed {
            crate::summary::read_root_file_blocking(&root, RootFile::Summary.name())?
        } else {
            None
        };
        let signature = if checks_summary && summary.is_some() {
            crate::summary::read_root_file_blocking(&root, RootFile::SummarySig.name())?
        } else {
            None
        };
        Ok::<_, Error>((summary, signature))
    })
    .await?;
    verification.check_summary_files(summary.is_some(), signature.is_some())?;
    let summary = summary.map(Arc::new);
    if checks_summary {
        verification
            .check_summary(summary.as_ref(), signature)
            .await?;
    }
    Ok(summary)
}

/// Checks that the `ostree.ref-binding` of a commit names the ref that the pull
/// reads.
///
/// A commit with no binding key is older than the convention and passes. A
/// commit with a binding list that does not name the ref fails.
pub(crate) fn check_ref_binding(
    checksum: &Checksum,
    commit: &Commit,
    ref_name: &str,
) -> Result<()> {
    if commit.metadata_value("ostree.ref-binding").is_none() {
        return Ok(());
    }
    let bindings = commit.ref_bindings();
    if bindings.contains(&ref_name) {
        return Ok(());
    }
    let listed = if bindings.is_empty() {
        "no refs".to_owned()
    } else {
        bindings.join(", ")
    };
    Err(Error::Pull(format!(
        "commit {checksum}: no requested ref '{ref_name}' in ref binding metadata ({listed})"
    )))
}

/// The commit that the timestamp check of a pull compares against, as the
/// pull resolves it before discovery.
#[derive(Debug, Clone, Copy)]
enum TimestampBase {
    /// No check.
    Off,
    /// The commit that the ref names in this repository, read for each ref.
    CurrentRef,
    /// The commit of [`TimestampCheck::Rev`] and its timestamp, read one time
    /// for each pull.
    Rev {
        /// The checksum of the commit.
        commit: Checksum,
        /// The timestamp of the commit.
        timestamp: u64,
    },
}

impl TimestampBase {
    /// Resolves `check` against this repository.
    ///
    /// For [`TimestampCheck::Rev`], the call reads the timestamp of the
    /// commit. If this repository does not hold the commit, the call fails
    /// with [`Error::ObjectNotFound`].
    async fn resolve(repo: &Repo, check: &TimestampCheck) -> Result<TimestampBase> {
        Ok(match check {
            TimestampCheck::Off => TimestampBase::Off,
            TimestampCheck::CurrentRef => TimestampBase::CurrentRef,
            TimestampCheck::Rev(commit) => TimestampBase::Rev {
                commit: *commit,
                timestamp: commit_timestamp(repo, commit).await?,
            },
        })
    }
}

/// Reads the timestamp of the commit `commit` of this repository.
///
/// The read and the decode run in one call on the blocking pool. The decode
/// reads the timestamp alone, with the checks of [`Commit::parse_timestamp`].
async fn commit_timestamp(repo: &Repo, commit: &Checksum) -> Result<u64> {
    let repo = repo.clone();
    let commit = *commit;
    ostrya_rt::unblock(move || {
        let bytes = repo.load_object_bytes_blocking(ObjectType::Commit, &commit)?;
        Ok(Commit::parse_timestamp(&bytes)?)
    })
    .await
}

/// Reads the commit that the ref at `relpath` of this repository names, and
/// the timestamp of that commit. Returns `None` if this repository holds no
/// such ref.
///
/// The ref, the read of the commit, and the decode run in one call on the
/// blocking pool. The errors come in this order: the read and the parse of
/// the ref, then the read and the decode of the commit, as
/// [`commit_timestamp`] states.
async fn current_ref_timestamp(repo: &Repo, relpath: String) -> Result<Option<(Checksum, u64)>> {
    let repo = repo.clone();
    ostrya_rt::unblock(move || {
        let Some(current) = repo.resolve_relpath_tip_blocking(&relpath)? else {
            return Ok(None);
        };
        let bytes = repo.load_object_bytes_blocking(ObjectType::Commit, &current)?;
        Ok(Some((current, Commit::parse_timestamp(&bytes)?)))
    })
    .await
}

/// The checks that a pull makes for each requested ref that names a tip
/// commit.
#[derive(Clone, Copy)]
struct TipChecks<'a> {
    /// `true` if the pull makes the ref-binding check.
    bindings: bool,
    /// The timestamp check of the pull.
    timestamp: TimestampBase,
    /// The place of the pulled refs. The timestamp check resolves the current
    /// tip of a ref there, by the rule of [`RefPlace::ref_path`].
    place: RefPlace<'a>,
    /// The collection id that the `ostree.collection-binding` of each tip
    /// must state, or `None` for no collection-binding check of each ref.
    collection: Option<&'a str>,
    /// `true` if the `ostree.collection-binding` of the tip of an `@ID:NAME`
    /// name must state `ID`, as [`Repo::pull_local`] and [`Repo::pull`]
    /// state.
    operand_collections: bool,
    /// `true` if a tip with no `ostree.collection-binding` key passes the
    /// collection-binding check.
    allow_unbound: bool,
    /// The timestamp that the remote listed for each requested ref, which the
    /// timestamp of its tip must equal. `None` for no such check.
    listed: Option<&'a HashMap<String, u64>>,
}

impl<'a> TipChecks<'a> {
    /// Returns the checks of a pull with the flags `flags`, the timestamp
    /// check `timestamp`, and its refs at `place`. The ref-binding check is on
    /// unless `flags` holds
    /// [`DISABLE_VERIFY_BINDINGS`](PullFlags::DISABLE_VERIFY_BINDINGS). The
    /// checks have no collection-binding check and no listed timestamps.
    fn new(flags: PullFlags, timestamp: TimestampBase, place: RefPlace<'a>) -> TipChecks<'a> {
        TipChecks {
            bindings: !flags.contains(PullFlags::DISABLE_VERIFY_BINDINGS),
            timestamp,
            place,
            collection: None,
            operand_collections: false,
            allow_unbound: false,
            listed: None,
        }
    }
}

/// Makes the checks of each ref of `refs`, in order, for the tip commit
/// `tip`, which parses to `commit`: the ref-binding check, the
/// collection-binding check, the check of the listed timestamp, and the
/// timestamp check.
///
/// The ref-binding check of an `@ID:NAME` name reads the part after `@ID:`.
/// The first check that fails stops the call.
async fn check_tip_refs(
    repo: &Repo,
    checks: TipChecks<'_>,
    tip: &Checksum,
    commit: &Commit,
    refs: &[&str],
) -> Result<()> {
    for ref_name in refs {
        let operand = operand_collection(ref_name);
        if checks.bindings {
            let bound = operand.map_or(*ref_name, |(_, name)| name);
            check_ref_binding(tip, commit, bound)?;
        }
        let operand_id = operand
            .filter(|_| checks.operand_collections)
            .map(|(id, _)| id);
        if let Some(id) = checks.collection.or(operand_id) {
            check_collection_binding(tip, commit, id, checks.allow_unbound)?;
        }
        if let Some(listed) = checks.listed.and_then(|listed| listed.get(*ref_name)) {
            check_listed_timestamp(tip, commit, ref_name, *listed)?;
        }
        check_timestamp(repo, checks.timestamp, checks.place, ref_name, tip, commit).await?;
    }
    Ok(())
}

/// Checks that the `ostree.collection-binding` of a commit states the
/// collection id `id`.
///
/// A commit with no binding key fails, unless `allow_unbound` is `true`. A
/// commit whose binding is not a string fails with either value.
pub(crate) fn check_collection_binding(
    checksum: &Checksum,
    commit: &Commit,
    id: &str,
    allow_unbound: bool,
) -> Result<()> {
    match commit.collection_binding() {
        Some(bound) if bound == id => Ok(()),
        Some(bound) => Err(Error::Pull(format!(
            "commit {checksum}: collection binding '{bound}' is not the requested collection \
             '{id}'"
        ))),
        None => match commit.metadata_value("ostree.collection-binding") {
            Some(_) => Err(Error::Pull(format!(
                "commit {checksum}: collection binding metadata is not a string"
            ))),
            None if allow_unbound => Ok(()),
            None => Err(Error::Pull(format!(
                "commit {checksum}: no collection binding metadata for the requested \
                 collection '{id}'"
            ))),
        },
    }
}

/// Checks that the timestamp of a commit equals the timestamp `listed` that
/// the remote listed for the ref `ref_name`.
fn check_listed_timestamp(
    checksum: &Checksum,
    commit: &Commit,
    ref_name: &str,
    listed: u64,
) -> Result<()> {
    if commit.timestamp == listed {
        return Ok(());
    }
    Err(Error::Pull(format!(
        "commit {checksum} (timestamp {}) of ref '{ref_name}' does not have the timestamp \
         that the remote listed ({listed})",
        commit.timestamp
    )))
}

/// Refuses a fetched tip that is older than the commit of the check.
///
/// Under [`TimestampBase::CurrentRef`], the call reads the ref at `place` and
/// the timestamp of its commit in one call on the blocking pool, through
/// [`current_ref_timestamp`].
async fn check_timestamp(
    repo: &Repo,
    check: TimestampBase,
    place: RefPlace<'_>,
    ref_name: &str,
    tip: &Checksum,
    fetched: &Commit,
) -> Result<()> {
    let (against, timestamp) = match check {
        TimestampBase::Off => return Ok(()),
        TimestampBase::CurrentRef => {
            // A ref that this repository does not hold has nothing to be
            // older than.
            let Some(current) = current_ref_timestamp(repo, place.ref_path(ref_name)?).await?
            else {
                return Ok(());
            };
            current
        }
        TimestampBase::Rev { commit, timestamp } => (commit, timestamp),
    };
    if fetched.timestamp >= timestamp {
        return Ok(());
    }
    Err(Error::Pull(format!(
        "commit {tip} (timestamp {}) is chronologically older than \
         {against} (timestamp {})",
        fetched.timestamp, timestamp
    )))
}

/// Imports an object that the two repositories store in the same form, inode
/// included, with a hardlink into the staging directory of the transaction.
///
/// Returns `true` if the object is staged. `false` is a content object with a
/// refused link, which the caller imports through the header of the object.
/// The link is refused in these cases:
///
/// - the destination seals its objects with fs-verity.
/// - the repositories are on different file systems.
/// - the source inode is at its link limit.
/// - the protected-hardlink rules of the kernel refuse it.
/// - [`FORCE_COPY`](PullFlags::FORCE_COPY) is set.
///
/// A metadata object has no header. The function copies it if its link is
/// refused, so it is always staged.
///
/// The link and the copy follow the rules of the source paths of
/// [`stage_import_blocking`](crate::write::stage_import_blocking), in each
/// open mode of `src`.
async fn link_import(
    txn: &Transaction,
    src: &Repo,
    name: ObjectName,
    flags: PullFlags,
) -> Result<bool> {
    txn.stage_import(
        src,
        name.checksum,
        name.ty,
        flags.contains(PullFlags::FORCE_COPY),
    )
    .await
}

/// Stores the regular-file content object `name` of the `archive` repository
/// `src` in the `archive` repository of `txn`, from the stored `.filez` file
/// of the source.
///
/// The staged file holds the bytes of the source unchanged, so the object
/// keeps the DEFLATE level of the source. The write inflates the payload in
/// bounded chunks to feed the digest. It refuses an object that does not hash
/// to its name, and a payload that does not inflate to the size that its
/// header declares. `meta` is the logical metadata of the object.
///
/// The open of the `.filez` file follows no symlink at any component of its
/// path below `objects/`, and refuses a file that is not a regular file.
async fn import_filez(
    txn: &Transaction,
    src: &Repo,
    name: ObjectName,
    meta: &FileMeta,
    buf: &mut Vec<u8>,
) -> Result<()> {
    let path = name.loose_path(src.mode());
    let repo = src.clone();
    let opened = ostrya_rt::unblock(move || {
        repo.objects()
            .open_regular(&path)
            .map_err(|e| e.into_object_error(&name.checksum, ObjectType::File))
    })
    .await?;
    let (header, declared, framed, body) = http::read_archive_header(
        ostrya_rt::FileReader::with_len_hint(opened.file, opened.stat.size),
    )
    .await?;
    http::store_filez_payload(
        txn,
        &name.checksum,
        &header,
        meta,
        declared,
        &framed,
        body,
        buf,
    )
    .await
}

/// Returns `true` if the two modes store the payload bytes of a regular file in
/// the same form.
///
/// The bare family stores the raw payload, so each pair of its modes
/// qualifies. `archive` stores a framed, deflated form that shares bytes with
/// no other mode.
fn payload_shared(src: RepoMode, dest: RepoMode) -> bool {
    !src.is_archive() && !dest.is_archive()
}

/// Returns `true` if the two modes store a symlink object in the same form,
/// inode included.
///
/// `bare-user` and `bare-user-shared` both store it as a 0644 regular file
/// that holds the target and a NUL, with the logical metadata in
/// `user.ostreemeta`. So the two modes can share the object.
fn symlink_shared(src: RepoMode, dest: RepoMode) -> bool {
    matches!(
        (src, dest),
        (RepoMode::BareUser, RepoMode::BareUserShared)
            | (RepoMode::BareUserShared, RepoMode::BareUser)
    )
}

/// The mode checks of a content object before the write.
///
/// Two rules apply to a content object from each source.
/// [`BAREUSERONLY_FILES`](PullFlags::BAREUSERONLY_FILES) limits the logical
/// mode of a regular file. A `bare-user-only` destination takes only an object
/// whose logical form is the form that it stores. Both rules read the logical
/// metadata alone, so one value holds them. Each path into the object store
/// makes the same checks: a local import, a fetched loose object, and the
/// objects of a static delta part.
#[derive(Clone, Copy)]
pub(crate) struct ModeChecks {
    /// The request of [`BAREUSERONLY_FILES`](PullFlags::BAREUSERONLY_FILES).
    bareuseronly_files: bool,
    /// The state of a `bare-user-only` destination.
    canonical: bool,
}

impl ModeChecks {
    /// Creates the checks of an import under `flags` into a repository of mode
    /// `dest`.
    ///
    /// A path with no pull flags of its own, the offline application of a
    /// static delta, passes [`PullFlags::empty()`]. The rule of the destination
    /// then stays alone.
    pub(crate) fn new(flags: PullFlags, dest: RepoMode) -> ModeChecks {
        ModeChecks {
            bareuseronly_files: flags.contains(PullFlags::BAREUSERONLY_FILES),
            canonical: dest == RepoMode::BareUserOnly,
        }
    }

    /// Returns `true` if a check applies.
    ///
    /// A path that does not read the logical metadata of an object for another
    /// purpose reads it only if this function returns `true`.
    pub(crate) fn any(&self) -> bool {
        self.bareuseronly_files || self.canonical
    }

    /// Refuses a content object whose logical metadata fails a check that
    /// applies.
    ///
    /// The caller calls it before the write of the bytes of the object, so a
    /// refused object leaves nothing. An untrusted local import also calls it
    /// on the object that a link or a clone staged, as
    /// [`verify_staged_content`] states. A refusal there fails the pull.
    pub(crate) fn check(&self, checksum: &Checksum, meta: &FileMeta) -> Result<()> {
        if self.bareuseronly_files {
            check_bareuseronly(checksum, meta)?;
        }
        if self.canonical {
            check_canonical(checksum, meta)?;
        }
        Ok(())
    }
}

/// Refuses a content object whose logical metadata is not the metadata that a
/// `bare-user-only` destination stores.
///
/// That mode records no ownership and no xattrs, and it reduces the permission
/// bits of a regular file to `perm & 0o755`. So a write into it makes the
/// header canonical and names the object for the result. An import keeps the
/// name that the object arrives under. This is possible only if that name
/// covers the canonical header. Another object gets a name that its stored
/// form does not hash to. The object model fixes the mode of a symlink, so a
/// symlink is exempt.
pub(crate) fn check_canonical(checksum: &Checksum, meta: &FileMeta) -> Result<()> {
    let extra = if meta.is_symlink() {
        0
    } else {
        // S_IFREG and the permission bits that the mode keeps.
        meta.mode & !0o100755
    };
    if extra == 0 && meta.uid == 0 && meta.gid == 0 && meta.xattrs.is_empty() {
        return Ok(());
    }
    Err(Error::Pull(format!(
        "content object {checksum}: a bare-user-only repository stores neither \
         ownership nor xattrs and reduces the mode to 0755, so this object -- uid \
         {}, gid {}, mode 0{:o}, {} xattr(s) -- cannot be imported under its own name",
        meta.uid,
        meta.gid,
        meta.mode,
        meta.xattrs.len()
    )))
}

/// Refuses a regular-file content object whose logical mode has bits outside
/// `0775`.
///
/// A symlink has a fixed mode and is exempt.
fn check_bareuseronly(checksum: &Checksum, meta: &FileMeta) -> Result<()> {
    if meta.is_symlink() {
        return Ok(());
    }
    let extra = meta.mode & !0o100775;
    if extra == 0 {
        return Ok(());
    }
    Err(Error::Pull(format!(
        "content object {checksum}: invalid mode 0{:o} with bits 0{:o}",
        meta.mode, extra
    )))
}

/// Verifies that the content object `name`, which a link or a clone staged in
/// `txn`, passes `checks` and hashes to its name.
///
/// The function loads the object as the destination stores it, and makes the
/// mode checks and the hash on that one load. So the checks and the hash
/// cover the object that the transaction publishes, and a source that changes
/// during the import cannot pass them. `buf` is the read buffer of
/// [`verify_content`].
async fn verify_staged_content(
    txn: &Transaction,
    name: ObjectName,
    checks: ModeChecks,
    buf: &mut Vec<u8>,
) -> Result<()> {
    #[cfg(test)]
    import_seam::run(txn.repo().repo_fd());
    let file = txn.load_file_staged_first(&name.checksum).await?;
    if checks.any() {
        checks.check(&name.checksum, &file.meta())?;
    }
    verify_content(&name.checksum, &file, buf).await
}

/// Verifies that the framed header and the streamed payload of a content
/// object hash to its name.
///
/// `buf` is the read buffer of the caller. The function grows it to
/// [`READ_CHUNK`] on its first use, and uses it again for each later object.
async fn verify_content(
    checksum: &Checksum,
    file: &crate::file::FileObject,
    buf: &mut Vec<u8>,
) -> Result<()> {
    let mut hasher = ContentHasher::new(&file.header())?;
    let mut reader = file.reader().await?;
    if buf.len() < READ_CHUNK {
        buf.resize(READ_CHUNK, 0);
    }
    loop {
        match reader.read(buf).await? {
            0 => break,
            n => hasher.update(&buf[..n]),
        }
    }
    let actual = hasher.finish();
    if actual != *checksum {
        return Err(Error::ChecksumMismatch {
            expected: *checksum,
            actual,
        });
    }
    Ok(())
}

/// A compile-time check that the pull options and the timestamp check are
/// `Send` and `Sync`.
const _: fn() = || {
    fn assert_send_sync<T: Send + Sync>() {}
    assert_send_sync::<PullOptions>();
    assert_send_sync::<TimestampCheck>();
};

/// A seam for the unit tests in the local import.
///
/// A test arms an action for one destination repository root. An untrusted
/// import runs the action once, where a change of the source object can come
/// between the bytes that the import stages and the bytes that it hashes:
/// after the read of a metadata object and before its write, and after the
/// link or the clone of a content object and before its hash. A local pull
/// also runs it after the plan of the tree of a commit and before the import
/// of its objects, and a pull from a remote after the read of a commit from a
/// localcache repository and before the checks of the commit. The action
/// runs at the first of these points that the pull gets to. The calls
/// compile out of a build that is not a test build.
#[cfg(test)]
pub(crate) mod import_seam {
    use std::os::fd::BorrowedFd;
    use std::sync::{Mutex, PoisonError};

    /// A repository root, by device and inode.
    type Root = (u64, u64);

    type Action = Box<dyn FnOnce() + Send>;

    static ACTIONS: Mutex<Vec<(Root, Action)>> = Mutex::new(Vec::new());

    /// Arms `f` for the next import into the repository at `root`.
    pub(crate) fn arm(root: &std::path::Path, f: impl FnOnce() + Send + 'static) {
        use std::os::unix::fs::MetadataExt;
        let meta = std::fs::metadata(root).unwrap();
        ACTIONS
            .lock()
            .unwrap_or_else(PoisonError::into_inner)
            .push(((meta.dev(), meta.ino()), Box::new(f)));
    }

    /// Runs the action armed for the repository whose root is open at
    /// `repo_fd`, if one is armed.
    pub(crate) fn run(repo_fd: BorrowedFd<'_>) {
        let stat = rustix::fs::fstat(repo_fd).unwrap();
        let root = (stat.st_dev, stat.st_ino);
        let action = {
            let mut actions = ACTIONS.lock().unwrap_or_else(PoisonError::into_inner);
            actions
                .iter()
                .position(|(at, _)| *at == root)
                .map(|at| actions.remove(at).1)
        };
        if let Some(action) = action {
            action();
        }
    }

    /// Removes the action armed for the repository at `root`, if one is
    /// armed. Returns `true` if one was armed.
    ///
    /// A test calls it after the pull, so that an action that did not run
    /// does not run in a later test whose repository root gets the same
    /// inode.
    pub(crate) fn disarm(root: &std::path::Path) -> bool {
        use std::os::unix::fs::MetadataExt;
        let meta = std::fs::metadata(root).unwrap();
        let root = (meta.dev(), meta.ino());
        let mut actions = ACTIONS.lock().unwrap_or_else(PoisonError::into_inner);
        let before = actions.len();
        actions.retain(|(at, _)| *at != root);
        actions.len() != before
    }
}

#[cfg(test)]
mod tests {
    use rustix::fs::{AtFlags, Mode, OFlags};

    use super::*;

    #[test]
    fn a_ref_place_gives_the_path_of_its_refs() {
        assert_eq!(
            RefPlace::Heads.ref_path("os/stable").unwrap(),
            "refs/heads/os/stable"
        );
        assert_eq!(
            RefPlace::Collection("org.example.Os")
                .ref_path("os/stable")
                .unwrap(),
            "refs/mirrors/org.example.Os/os/stable"
        );
        // The names of a pull from the remote `origin` into a repository
        // whose own id is `org.example.Own`.
        let operands = RefPlace::Operands {
            remote: Some("origin"),
            own: Some("org.example.Own"),
        };
        for (name, path) in [
            ("os/stable", "refs/remotes/origin/os/stable"),
            (
                "@org.example.Os:os/stable",
                "refs/mirrors/org.example.Os/os/stable",
            ),
            ("@org.example.Own:os/stable", "refs/heads/os/stable"),
        ] {
            assert_eq!(operands.ref_path(name).unwrap(), path, "{name}");
        }
        for name in ["../x", "origin:x"] {
            assert!(
                matches!(
                    RefPlace::Collection("org.example.Os").ref_path(name),
                    Err(Error::InvalidRefspec(_))
                ),
                "{name}"
            );
        }
    }

    /// A collection id is the place of the local refs in a repository whose
    /// `[core] collection-id` is that id, and the place of the collection
    /// refs in each other repository.
    #[test]
    fn a_collection_place_follows_the_collection_id_of_the_repository() {
        let dir = std::env::temp_dir().join(format!(
            "ostrya-pull-place-{}-{}",
            std::process::id(),
            crate::write::unique()
        ));
        std::fs::create_dir_all(&dir).unwrap();
        ostrya_rt::block_on(async {
            for (name, own, place) in [
                ("own", Some("org.example.Os"), RefPlace::Heads),
                (
                    "other",
                    Some("org.example.Other"),
                    RefPlace::Collection("org.example.Os"),
                ),
                ("none", None, RefPlace::Collection("org.example.Os")),
            ] {
                let mut opts = crate::CreateOptions::new(crate::RepoMode::Archive);
                if let Some(id) = own {
                    opts = opts.collection_id(id);
                }
                let repo = Repo::create(&dir.join(name), opts).await.unwrap();
                assert_eq!(
                    RefPlace::of_collection(&repo, "org.example.Os"),
                    place,
                    "{name}"
                );
            }
        });
        let _ = std::fs::remove_dir_all(&dir);
    }

    /// Returns a commit with the metadata `entries`, each a key and a value
    /// of type `ty`.
    fn commit_with(entries: &[(&str, &str, Value)]) -> Commit {
        let metadata = Value::Array(
            entries
                .iter()
                .map(|(key, ty, value)| {
                    Value::Tuple(vec![
                        Value::Str((*key).to_owned()),
                        Value::Variant(Box::new((
                            ostrya_core::Type::parse(ty).unwrap(),
                            value.clone(),
                        ))),
                    ])
                })
                .collect(),
        );
        Commit {
            metadata,
            parent: None,
            related: Vec::new(),
            subject: String::new(),
            body: String::new(),
            timestamp: 7,
            root_dirtree: Checksum::from_bytes([1; 32]),
            root_dirmeta: Checksum::from_bytes([2; 32]),
        }
    }

    #[test]
    fn the_collection_binding_must_state_the_collection() {
        let tip = Checksum::from_bytes([3; 32]);
        let id = "org.example.Os";
        let bound = commit_with(&[("ostree.collection-binding", "s", Value::Str(id.into()))]);
        check_collection_binding(&tip, &bound, id, false).unwrap();
        let other = commit_with(&[(
            "ostree.collection-binding",
            "s",
            Value::Str("org.example.Other".into()),
        )]);
        for allow_unbound in [false, true] {
            let err = check_collection_binding(&tip, &other, id, allow_unbound).unwrap_err();
            assert!(
                matches!(&err, Error::Pull(m) if m.contains("org.example.Other") && m.contains(id)),
                "{err:?}"
            );
        }
        let none = commit_with(&[]);
        assert!(matches!(
            check_collection_binding(&tip, &none, id, false),
            Err(Error::Pull(_))
        ));
        check_collection_binding(&tip, &none, id, true).unwrap();
        // A binding key whose value is not a string is a binding, and fails
        // with either value of the switch.
        let malformed = commit_with(&[(
            "ostree.collection-binding",
            "as",
            Value::Array(vec![Value::Str(id.into())]),
        )]);
        for allow_unbound in [false, true] {
            let err = check_collection_binding(&tip, &malformed, id, allow_unbound).unwrap_err();
            assert!(
                matches!(&err, Error::Pull(m) if m.contains("collection binding metadata is not a string")),
                "{allow_unbound}: {err:?}"
            );
        }
        assert!(check_listed_timestamp(&tip, &none, "os/stable", 7).is_ok());
        assert!(matches!(
            check_listed_timestamp(&tip, &none, "os/stable", 8),
            Err(Error::Pull(_))
        ));
    }

    #[test]
    fn flags_combine_and_test() {
        let flags = PullFlags::UNTRUSTED | PullFlags::COMMIT_ONLY;
        assert!(flags.contains(PullFlags::UNTRUSTED));
        assert!(flags.contains(PullFlags::COMMIT_ONLY));
        assert!(!flags.contains(PullFlags::FORCE_COPY));
        assert!(PullFlags::empty().contains(PullFlags::NONE));
    }

    /// Creates the repositories `src` of `src_mode` and `dst` of `dst_mode` in
    /// a new directory. Stores a regular file object, a dirmeta object, and a
    /// symlink object in `src`, and loads the regular file through a handle of
    /// `src` in the strict open mode. Returns the directory, the strict
    /// handle, the names of the three objects in this order, the metadata of
    /// the regular file, and `dst`.
    fn strict_fixture(
        tag: &str,
        src_mode: RepoMode,
        dst_mode: RepoMode,
    ) -> (std::path::PathBuf, Repo, [ObjectName; 3], FileMeta, Repo) {
        let dir = std::env::temp_dir().join(format!(
            "ostrya-pull-{tag}-{}-{}",
            std::process::id(),
            crate::write::unique()
        ));
        std::fs::create_dir_all(&dir).unwrap();
        ostrya_rt::block_on(async {
            let src = Repo::create(&dir.join("src"), crate::CreateOptions::new(src_mode))
                .await
                .unwrap();
            let txn = src.transaction().await.unwrap();
            let file = txn
                .write_regfile_inline(None, &FileMeta::regular(0, 0, 0o644), b"inside\n")
                .await
                .unwrap();
            let dirmeta = txn
                .write_dirmeta(&ostrya_core::DirMeta {
                    uid: 0,
                    gid: 0,
                    mode: 0o40755,
                    xattrs: Default::default(),
                })
                .await
                .unwrap();
            let symlink = txn
                .write_symlink("target", &FileMeta::regular(0, 0, 0o777), None)
                .await
                .unwrap();
            txn.commit().await.unwrap();
            let parent = std::fs::File::open(&dir).unwrap();
            let strict = Repo::open_at_strict(
                std::os::fd::AsFd::as_fd(&parent),
                std::path::Path::new("src"),
            )
            .await
            .unwrap();
            let meta = strict.load_file(&file).await.unwrap().meta();
            let dst = Repo::create(&dir.join("dst"), crate::CreateOptions::new(dst_mode))
                .await
                .unwrap();
            let names = [
                (file, ObjectType::File),
                (dirmeta, ObjectType::DirMeta),
                (symlink, ObjectType::File),
            ]
            .map(|(checksum, ty)| ObjectName { checksum, ty });
            (dir, strict, names, meta, dst)
        })
    }

    /// Moves `path` to `moved`, and puts a symlink to `moved` at `path`.
    fn swap_in_symlink(path: &std::path::Path, moved: &std::path::Path) {
        std::fs::rename(path, moved).unwrap();
        std::os::unix::fs::symlink(moved, path).unwrap();
    }

    /// Replaces the file at `path` with a FIFO.
    fn swap_in_fifo(path: &std::path::Path) {
        std::fs::remove_file(path).unwrap();
        rustix::fs::mknodat(
            rustix::fs::CWD,
            path,
            rustix::fs::FileType::Fifo,
            Mode::from_raw_mode(0o644),
            0,
        )
        .unwrap();
    }

    /// The `.filez` copy follows no symlink at the fan-out directory
    /// `objects/<xx>`, from a handle of each open mode. A symlink that
    /// replaces `objects/<xx>` after the load fails the copy.
    #[test]
    fn a_filez_copy_refuses_a_fanout_symlinked_after_the_load() {
        let (dir, strict, [name, ..], meta, dst) =
            strict_fixture("filez-fanout", RepoMode::Archive, RepoMode::Archive);
        let plain = ostrya_rt::block_on(Repo::open(&dir.join("src"))).unwrap();
        let hex = name.checksum.to_hex();
        let fanout = dir.join("src/objects").join(&hex[..2]);
        let moved = dir.join("moved");
        std::fs::rename(&fanout, &moved).unwrap();
        std::os::unix::fs::symlink(&moved, &fanout).unwrap();

        let results = ostrya_rt::block_on(async {
            let txn = dst.transaction().await.unwrap();
            [
                import_filez(&txn, &strict, name, &meta, &mut Vec::new()).await,
                import_filez(&txn, &plain, name, &meta, &mut Vec::new()).await,
            ]
        });
        let _ = std::fs::remove_dir_all(&dir);
        let expected = format!(
            "objects/{} passes through a symlink; ostrya refuses a symlink in the repository",
            name.loose_path(RepoMode::Archive)
        );
        for result in results {
            match result {
                Err(Error::InvalidFormat(m)) => assert_eq!(m, expected),
                other => panic!("{other:?}"),
            }
        }
    }

    /// The `.filez` copy refuses a FIFO that replaces the `.filez` file after
    /// the load, and does not wait for a writer.
    #[test]
    fn a_filez_copy_refuses_a_fifo_swapped_in_after_the_load() {
        let (dir, strict, [name, ..], meta, dst) =
            strict_fixture("filez-fifo", RepoMode::Archive, RepoMode::Archive);
        let filez = dir
            .join("src/objects")
            .join(name.loose_path(RepoMode::Archive));
        std::fs::remove_file(&filez).unwrap();
        rustix::fs::mknodat(
            rustix::fs::CWD,
            &filez,
            rustix::fs::FileType::Fifo,
            Mode::from_raw_mode(0o644),
            0,
        )
        .unwrap();

        let (tx, rx) = std::sync::mpsc::channel();
        std::thread::spawn(move || {
            let result = ostrya_rt::block_on(async {
                let txn = dst.transaction().await.unwrap();
                import_filez(&txn, &strict, name, &meta, &mut Vec::new()).await
            });
            let _ = tx.send(result);
        });
        let result = match rx.recv_timeout(Duration::from_secs(10)) {
            Ok(result) => result,
            Err(_) => {
                // A writer releases the blocked open, so the thread ends.
                let _ = rustix::fs::open(
                    &filez,
                    OFlags::WRONLY | OFlags::NONBLOCK | OFlags::CLOEXEC,
                    Mode::empty(),
                );
                let _ = rx.recv_timeout(Duration::from_secs(10));
                let _ = std::fs::remove_dir_all(&dir);
                panic!("the copy waits on the FIFO");
            }
        };
        let _ = std::fs::remove_dir_all(&dir);
        match result {
            Err(Error::InvalidFormat(m)) => {
                assert!(m.ends_with(".filez is not a regular file"), "{m}");
            }
            other => panic!("{other:?}"),
        }
    }

    /// Returns a handle of the source repository of `dir` in the default open
    /// mode, beside the handle `strict` of the strict open mode.
    fn both_modes(dir: &std::path::Path, strict: &Repo) -> [Repo; 2] {
        let plain = ostrya_rt::block_on(Repo::open(&dir.join("src"))).unwrap();
        [strict.clone(), plain]
    }

    /// Returns the text of the refusal of a symlink at the path of the
    /// source object `name` of a repository of mode `mode`.
    fn symlink_refusal(name: ObjectName, mode: RepoMode) -> String {
        format!(
            "objects/{} passes through a symlink; ostrya refuses a symlink in the repository",
            name.loose_path(mode)
        )
    }

    /// Returns the message of `result`, which must be
    /// [`Error::InvalidFormat`].
    fn invalid_format<T: std::fmt::Debug>(result: Result<T>) -> String {
        match result {
            Err(Error::InvalidFormat(m)) => m,
            other => panic!("{other:?}"),
        }
    }

    /// The link and the metadata copy follow no symlink at the fan-out
    /// directory `objects/<xx>`, from a handle of each open mode. A symlink
    /// that replaces `objects/<xx>` after the load fails the import.
    #[test]
    fn a_link_refuses_a_fanout_symlinked_after_the_load() {
        for (index, flags) in [
            (0, PullFlags::empty()),
            (1, PullFlags::empty()),
            (1, PullFlags::FORCE_COPY),
        ] {
            let (dir, strict, names, _, dst) =
                strict_fixture("link-fanout", RepoMode::Archive, RepoMode::Archive);
            let name = names[index];
            let object = dir
                .join("src/objects")
                .join(name.loose_path(RepoMode::Archive));
            swap_in_symlink(object.parent().unwrap(), &dir.join("moved"));

            let results = both_modes(&dir, &strict).map(|src| {
                ostrya_rt::block_on(async {
                    let txn = dst.transaction().await.unwrap();
                    link_import(&txn, &src, name, flags).await
                })
            });
            let _ = std::fs::remove_dir_all(&dir);
            for result in results {
                assert_eq!(
                    invalid_format(result),
                    symlink_refusal(name, RepoMode::Archive),
                    "{:?} {flags:?}",
                    name.ty
                );
            }
        }
    }

    /// The payload clone follows no symlink at `objects/<xx>`, from a handle
    /// of each open mode. A symlink that replaces `objects/<xx>` after the
    /// load fails the clone.
    #[test]
    fn a_payload_clone_refuses_a_fanout_symlinked_after_the_load() {
        let (dir, strict, [name, ..], meta, dst) =
            strict_fixture("clone-fanout", RepoMode::BareUser, RepoMode::BareUserOnly);
        let object = dir
            .join("src/objects")
            .join(name.loose_path(RepoMode::BareUser));
        swap_in_symlink(object.parent().unwrap(), &dir.join("moved"));

        let results = both_modes(&dir, &strict).map(|src| {
            ostrya_rt::block_on(async {
                let txn = dst.transaction().await.unwrap();
                txn.stage_clone_content(&src, name.checksum, meta.regular_header(), 0)
                    .await
            })
        });
        let _ = std::fs::remove_dir_all(&dir);
        for result in results {
            assert_eq!(
                invalid_format(result),
                symlink_refusal(name, RepoMode::BareUser)
            );
        }
    }

    /// The metadata copy and the payload clone refuse a FIFO that replaces
    /// the object after the load, from a handle of each open mode, and do not
    /// wait for a writer.
    #[test]
    fn a_copy_refuses_a_fifo_swapped_in_after_the_load() {
        for (clone, plain) in [(false, false), (false, true), (true, false), (true, true)] {
            let (dir, strict, [file, dirmeta, _], meta, dst) =
                strict_fixture("copy-fifo", RepoMode::BareUser, RepoMode::BareUserOnly);
            let [strict, plain_src] = both_modes(&dir, &strict);
            let src = if plain { plain_src } else { strict };
            let name = if clone { file } else { dirmeta };
            let object = dir
                .join("src/objects")
                .join(name.loose_path(RepoMode::BareUser));
            swap_in_fifo(&object);

            let (tx, rx) = std::sync::mpsc::channel();
            std::thread::spawn(move || {
                let result = ostrya_rt::block_on(async {
                    let txn = dst.transaction().await.unwrap();
                    if clone {
                        txn.stage_clone_content(&src, name.checksum, meta.regular_header(), 0)
                            .await
                    } else {
                        link_import(&txn, &src, name, PullFlags::FORCE_COPY)
                            .await
                            .map(drop)
                    }
                });
                let _ = tx.send(result);
            });
            let result = match rx.recv_timeout(Duration::from_secs(10)) {
                Ok(result) => result,
                Err(_) => {
                    // A writer releases the blocked open, so the thread ends.
                    let _ = rustix::fs::open(
                        &object,
                        OFlags::WRONLY | OFlags::NONBLOCK | OFlags::CLOEXEC,
                        Mode::empty(),
                    );
                    let _ = rx.recv_timeout(Duration::from_secs(10));
                    let _ = std::fs::remove_dir_all(&dir);
                    panic!("{:?}: the copy waits on the FIFO", name.ty);
                }
            };
            let _ = std::fs::remove_dir_all(&dir);
            let expected = format!(
                "objects/{} is not a regular file",
                name.loose_path(RepoMode::BareUser)
            );
            assert_eq!(invalid_format(result), expected, "{:?} {plain}", name.ty);
        }
    }

    /// Links `name` from `src` into a transaction of `dst`. Returns the
    /// result of the link, and `true` if the staging directory holds the
    /// object after it.
    fn link_and_probe(src: &Repo, dst: &Repo, name: ObjectName) -> (Result<bool>, bool) {
        ostrya_rt::block_on(async {
            let txn = dst.transaction().await.unwrap();
            let result = link_import(&txn, src, name, PullFlags::empty()).await;
            let staging = crate::write::flat_name(&name.checksum, name.ty, dst.mode());
            let staged = rustix::fs::statat(
                txn.staging_dir(),
                staging.as_str(),
                AtFlags::SYMLINK_NOFOLLOW,
            )
            .is_ok();
            (result, staged)
        })
    }

    /// The link from a handle of each open mode refuses a symlink that
    /// replaces the object after the load, and stages nothing.
    #[test]
    fn a_link_refuses_an_object_symlinked_after_the_load() {
        for index in [0, 1] {
            let (dir, strict, names, _, dst) =
                strict_fixture("link-object", RepoMode::Archive, RepoMode::Archive);
            let name = names[index];
            let object = dir
                .join("src/objects")
                .join(name.loose_path(RepoMode::Archive));
            swap_in_symlink(&object, &dir.join("moved"));

            let results = both_modes(&dir, &strict).map(|src| link_and_probe(&src, &dst, name));
            let _ = std::fs::remove_dir_all(&dir);
            for (result, staged) in results {
                assert_eq!(
                    invalid_format(result),
                    symlink_refusal(name, RepoMode::Archive),
                    "{:?}",
                    name.ty
                );
                assert!(!staged, "{:?}", name.ty);
            }
        }
    }

    /// The link from a handle of each open mode refuses a FIFO that replaces
    /// the object after the load, and stages nothing.
    #[test]
    fn a_link_refuses_a_fifo_swapped_in_after_the_load() {
        for index in [0, 1] {
            let (dir, strict, names, _, dst) =
                strict_fixture("link-fifo", RepoMode::Archive, RepoMode::Archive);
            let name = names[index];
            swap_in_fifo(
                &dir.join("src/objects")
                    .join(name.loose_path(RepoMode::Archive)),
            );

            let results = both_modes(&dir, &strict).map(|src| link_and_probe(&src, &dst, name));
            let _ = std::fs::remove_dir_all(&dir);
            let expected = format!(
                "objects/{} is not a regular file",
                name.loose_path(RepoMode::Archive)
            );
            for (result, staged) in results {
                assert_eq!(invalid_format(result), expected, "{:?}", name.ty);
                assert!(!staged, "{:?}", name.ty);
            }
        }
    }

    /// A `bare-user-only` repository stores a symlink content object as a
    /// symlink. The link from a handle of each open mode stages it.
    #[test]
    fn a_link_keeps_a_symlink_object_of_bare_user_only() {
        let (dir, strict, [_, _, symlink], _, dst) = strict_fixture(
            "link-symlink",
            RepoMode::BareUserOnly,
            RepoMode::BareUserOnly,
        );
        let results = both_modes(&dir, &strict).map(|src| link_and_probe(&src, &dst, symlink));
        let _ = std::fs::remove_dir_all(&dir);
        for (result, staged) in results {
            assert!(matches!(result, Ok(true)), "{result:?}");
            assert!(staged);
        }
    }

    /// An untrusted import stages the bytes that it hashes. The seam replaces
    /// the source object between the read that the import hashes and the read
    /// that it stages. A good object that goes bad there is staged from the
    /// good bytes. A bad object that comes good there is refused.
    #[test]
    fn an_untrusted_import_stages_only_the_bytes_that_it_hashes() {
        let (untrusted, copy) = (
            PullFlags::UNTRUSTED,
            PullFlags::UNTRUSTED | PullFlags::FORCE_COPY,
        );
        for (src_mode, dst_mode, flags, index) in [
            (RepoMode::Archive, RepoMode::Archive, untrusted, 0),
            (RepoMode::Archive, RepoMode::Archive, untrusted, 1),
            (RepoMode::BareUser, RepoMode::BareUserOnly, untrusted, 0),
            (RepoMode::BareUser, RepoMode::BareUser, copy, 0),
            (RepoMode::BareUser, RepoMode::BareUser, untrusted, 0),
            (RepoMode::BareUser, RepoMode::BareUserShared, untrusted, 2),
        ] {
            for goes_bad in [true, false] {
                let (dir, strict, names, _, dst) = strict_fixture("untrusted", src_mode, dst_mode);
                let name = names[index];
                // The bad object is another valid object of the same type.
                let other = ostrya_rt::block_on(async {
                    let src = Repo::open(&dir.join("src")).await.unwrap();
                    let txn = src.transaction().await.unwrap();
                    let other = match index {
                        0 => {
                            let meta = FileMeta::regular(0, 0, 0o644);
                            txn.write_regfile_inline(None, &meta, b"outside\n").await
                        }
                        1 => {
                            txn.write_dirmeta(&ostrya_core::DirMeta {
                                uid: 0,
                                gid: 0,
                                mode: 0o40700,
                                xattrs: Default::default(),
                            })
                            .await
                        }
                        _ => {
                            let meta = FileMeta::regular(0, 0, 0o777);
                            txn.write_symlink("outside", &meta, None).await
                        }
                    };
                    txn.commit().await.unwrap();
                    other.unwrap()
                });
                let objects = dir.join("src/objects");
                let object = objects.join(name.loose_path(src_mode));
                let other = ObjectName {
                    checksum: other,
                    ty: name.ty,
                };
                let other = objects.join(other.loose_path(src_mode));
                let good = std::fs::read(&object).unwrap();
                let (tmp, aside) = (dir.join("tmp"), dir.join("aside"));
                let at = object.clone();
                let put_bad = move || {
                    std::fs::hard_link(&other, &tmp).unwrap();
                    std::fs::rename(&tmp, &at).unwrap();
                };
                if goes_bad {
                    import_seam::arm(&dir.join("dst"), put_bad);
                } else {
                    std::fs::rename(&object, &aside).unwrap();
                    put_bad();
                    let at = object.clone();
                    import_seam::arm(&dir.join("dst"), move || {
                        std::fs::rename(&aside, &at).unwrap()
                    });
                }

                let (result, staged) = ostrya_rt::block_on(async {
                    let txn = dst.transaction().await.unwrap();
                    let result = dst
                        .import_from(&txn, &strict, name, flags, &mut Vec::new())
                        .await;
                    let staged = crate::write::flat_name(&name.checksum, name.ty, dst_mode);
                    let staged = rustix::fs::openat(
                        txn.staging_dir(),
                        staged.as_str(),
                        OFlags::RDONLY | OFlags::CLOEXEC,
                        Mode::empty(),
                    )
                    .ok()
                    .map(|fd| {
                        let mut bytes = Vec::new();
                        std::io::Read::read_to_end(&mut std::fs::File::from(fd), &mut bytes)
                            .unwrap();
                        bytes
                    });
                    (result, staged)
                });
                let ran = (std::fs::read(&object).unwrap() == good) != goes_bad;
                let _ = std::fs::remove_dir_all(&dir);
                let row = format!("{src_mode:?} -> {dst_mode:?} {flags:?} goes_bad={goes_bad}");
                assert!(ran, "{row}: the seam did not run");
                if goes_bad {
                    assert!(result.is_ok(), "{row}: {result:?}");
                    assert!(
                        staged.as_deref() == Some(&good[..]),
                        "{row}: bad bytes staged"
                    );
                } else {
                    match result {
                        Err(Error::ChecksumMismatch { expected, .. }) => {
                            assert_eq!(expected, name.checksum, "{row}")
                        }
                        other => panic!("{row}: {other:?}"),
                    }
                }
            }
        }
    }

    /// An untrusted import makes the mode checks on the object that it hashes.
    /// A `bare-user-only` destination refuses a setuid object. The source path
    /// holds a 0755 inode at the mode check of the source, and the seam sets
    /// the setuid bit on the linked inode before the hash.
    #[test]
    fn an_untrusted_link_checks_the_modes_of_the_staged_object() {
        use std::os::unix::fs::PermissionsExt;
        let (dir, strict, _, _, dst) = strict_fixture(
            "staged-modes",
            RepoMode::BareUserOnly,
            RepoMode::BareUserOnly,
        );
        let payload = b"setuid\n";
        let plain = ostrya_rt::block_on(async {
            let src = Repo::open(&dir.join("src")).await.unwrap();
            let txn = src.transaction().await.unwrap();
            let plain = txn
                .write_regfile_inline(None, &FileMeta::regular(0, 0, 0o755), payload)
                .await
                .unwrap();
            txn.commit().await.unwrap();
            ObjectName {
                checksum: plain,
                ty: ObjectType::File,
            }
        });
        let mut hasher =
            ContentHasher::new(&FileMeta::regular(0, 0, 0o4755).regular_header()).unwrap();
        hasher.update(payload);
        let name = ObjectName {
            checksum: hasher.finish(),
            ty: ObjectType::File,
        };
        let objects = dir.join("src/objects");
        let object = objects.join(name.loose_path(RepoMode::BareUserOnly));
        std::fs::create_dir_all(object.parent().unwrap()).unwrap();
        std::fs::hard_link(
            objects.join(plain.loose_path(RepoMode::BareUserOnly)),
            &object,
        )
        .unwrap();
        let at = object.clone();
        import_seam::arm(&dir.join("dst"), move || {
            std::fs::set_permissions(&at, std::fs::Permissions::from_mode(0o4755)).unwrap()
        });

        let result = ostrya_rt::block_on(async {
            let txn = dst.transaction().await.unwrap();
            dst.import_from(&txn, &strict, name, PullFlags::UNTRUSTED, &mut Vec::new())
                .await
        });
        let mode = std::fs::metadata(&object).unwrap().permissions().mode();
        let _ = std::fs::remove_dir_all(&dir);
        assert_eq!(mode & 0o7777, 0o4755, "the seam did not run");
        match result {
            Err(Error::Pull(message)) => {
                assert!(message.contains("cannot be imported"), "{message}")
            }
            other => panic!("{other:?}"),
        }
    }
}