ostrya 0.19.1

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
5445
5446
5447
5448
5449
5450
5451
5452
5453
5454
5455
5456
5457
5458
5459
5460
5461
5462
5463
5464
5465
5466
5467
5468
5469
5470
5471
5472
5473
5474
5475
5476
5477
5478
5479
5480
5481
5482
5483
5484
5485
5486
5487
5488
5489
5490
5491
5492
5493
5494
5495
5496
5497
5498
5499
5500
5501
5502
5503
5504
5505
5506
5507
5508
5509
5510
5511
5512
5513
5514
5515
5516
5517
5518
5519
5520
5521
5522
5523
5524
5525
5526
5527
5528
5529
5530
5531
5532
5533
5534
5535
5536
5537
5538
5539
5540
5541
5542
5543
5544
5545
5546
5547
5548
5549
5550
5551
5552
5553
5554
5555
5556
5557
5558
5559
5560
5561
5562
5563
5564
5565
5566
5567
5568
5569
5570
5571
5572
5573
5574
5575
5576
5577
5578
5579
5580
5581
5582
5583
5584
5585
5586
5587
5588
//! The pull of the refs of a collection from the remotes that serve it.
//!
//! Each test serves remote repositories from in-process static file servers.
//! A server answers the ref listing with fixed bytes that the test builds
//! with `Repo::build_ref_listing`, whatever the query. A server with no such
//! bytes answers 404, as a static server does, and the pull reads its
//! summary.
//!
//! ostrya builds the remote repositories. A remote with the collection id
//! `org.example.Os` lists its refs in field 0, and a remote with another id
//! lists them in its collection map.

mod common;
#[path = "common/pull.rs"]
mod pull;

use std::os::fd::AsFd;
use std::path::Path;
use std::sync::{Arc, Mutex};

use common::{TmpDir, anyone, store_with_field2};
use ostrya::config::{ex_ostrya, remote};
use ostrya::endpoint::EndpointOverrides;
use ostrya::{
    Checksum, CollectionPullEvent, CollectionPullOptions, CollectionPullStats, CommitModifier,
    CommitModifierFlags, CommitOptions, CreateOptions, DeltaOptions, Ed25519Signer, Error,
    FileKind, FsckOptions, MAX_REF_PATTERNS, MutableTree, ObjectName, ObjectType, PullFlags,
    PullOptions, PullStats, Ref, RefSelector, Repo, RepoMode, SummaryOptions, TimestampCheck, Type,
    Value, commit_operand,
};
use ostrya_rt::block_on;
use pull::*;

/// The collection that the tests pull.
const ID: &str = "org.example.Os";
/// Another collection.
const OTHER: &str = "org.example.Other";
/// The ref that the tests pull.
const REF: &str = "os/stable";
/// A fixed ed25519 keypair. A destination trusts its public key.
const SECRET_B64: &str =
    "o74ME/dmhvDeYf64dDJQY8kX2piK0M/nyIRWVi30i6DCOzRsHVcvgYToz6zOb5OvK/v8nH6KfLR3dfdsn6ZSyQ==";
const PUBLIC_B64: &str = "wjs0bB1XL4GE6M+szm+Tryv7/Jx+iny0d3X3bJ+mUsk=";
/// A second keypair. It stands for a key that a destination does not trust.
const OTHER_SECRET_B64: &str =
    "5ILWxT+l9G/u3h0BptRpmSi35C9uog7YDdD+Fp1Xk+Hz52p0NlYh6xBA73kJEJKhKbbnjcE0rsWA5XA/K5Sq5Q==";
/// The path of the ref listing on a server.
const LISTING: &str = "_ostrya/refs/v1";

/// The bindings of a test commit.
#[derive(Clone, Copy)]
struct Bind<'a> {
    /// The `ostree.collection-binding`, or `None` for no key.
    collection: Option<&'a str>,
    /// The `ostree.ref-binding`, or `None` for no key.
    refs: Option<&'a [&'a str]>,
}

/// The bindings of a commit of `REF` in `ID`.
const BOUND: Bind<'static> = Bind {
    collection: Some(ID),
    refs: Some(&[REF]),
};

/// Returns a metadata entry `key` with the value `value` of type `ty`.
fn entry(key: &str, ty: &str, value: Value) -> Value {
    Value::Tuple(vec![
        Value::Str(key.to_owned()),
        Value::Variant(Box::new((Type::parse(ty).unwrap(), value))),
    ])
}

/// Creates an archive repository at `dir/name` with the collection id `own`.
async fn create(dir: &Path, name: &str, own: Option<&str>) -> Repo {
    let mut opts = CreateOptions::new(RepoMode::Archive);
    if let Some(id) = own {
        opts = opts.collection_id(id);
    }
    Repo::create(&dir.join(name), opts).await.unwrap()
}

/// Commits a small tree with the marker `marker` into `repo`, with the
/// timestamp `timestamp` and the bindings `bind`. Writes the commit to the
/// ref `name` of the collection `collection`, or to the local ref `name` if
/// `collection` is `None`.
async fn commit(
    repo: &Repo,
    dir: &Path,
    marker: &str,
    collection: Option<&str>,
    name: &str,
    timestamp: u64,
    bind: Bind<'_>,
) -> Checksum {
    let sub = format!("src-{marker}");
    build_tree(&dir.join(&sub), marker.as_bytes());
    let txn = repo.transaction().await.unwrap();
    let mut mtree = MutableTree::new();
    let mut modifier = CommitModifier::new(
        CommitModifierFlags::SKIP_XATTRS | CommitModifierFlags::CANONICAL_PERMISSIONS,
    );
    let dfd = std::fs::File::open(dir).unwrap();
    txn.write_dfd_to_mtree(
        dfd.as_fd(),
        Path::new(&sub),
        &mut mtree,
        Some(&mut modifier),
    )
    .await
    .unwrap();
    let root = txn.write_mtree(&mut mtree).await.unwrap();
    let mut metadata = Vec::new();
    if let Some(id) = bind.collection {
        metadata.push(entry(
            "ostree.collection-binding",
            "s",
            Value::Str(id.to_owned()),
        ));
    }
    if let Some(refs) = bind.refs {
        let refs = refs.iter().map(|r| Value::Str((*r).to_owned())).collect();
        metadata.push(entry("ostree.ref-binding", "as", Value::Array(refs)));
    }
    let checksum = txn
        .write_commit(
            CommitOptions {
                subject: Some(marker.to_owned()),
                timestamp: Some(timestamp),
                metadata: Some(Value::Array(metadata)),
                ..CommitOptions::default()
            },
            &root,
        )
        .await
        .unwrap();
    match collection {
        Some(id) => txn.set_ref(&Ref::collection(id, name), Some(&checksum)),
        None => txn.set_ref(&Ref::local(name), Some(&checksum)),
    }
    txn.commit().await.unwrap();
    checksum
}

/// Writes the summary of `repo`.
async fn summarize(repo: &Repo) {
    repo.regenerate_summary(&SummaryOptions {
        last_modified: Some(FIXED_TS),
        ..SummaryOptions::default()
    })
    .await
    .unwrap();
}

/// Makes `server` answer each ref listing request with the listing of `repo`
/// for the names `names` in `ID`, or for each ref of `ID` if `names` is
/// empty.
async fn serve_listing(server: &RepoServer, repo: &Repo, names: &[&str]) {
    server.tamper("_ostrya/refs/v1", listing(repo, names).await);
}

/// Returns the ref listing of `repo` for the names `names` in `ID`, or for
/// each ref of `ID` and no local ref if `names` is empty.
async fn listing(repo: &Repo, names: &[&str]) -> Vec<u8> {
    let refs = if names.is_empty() {
        RefSelector::parse(["!**"]).unwrap()
    } else {
        RefSelector::parse(names.iter().copied()).unwrap()
    };
    let entries: Vec<String> = if names.is_empty() {
        vec![format!("{ID}/**")]
    } else {
        names.iter().map(|name| format!("{ID}/{name}")).collect()
    };
    let collections = RefSelector::parse(entries.iter().map(String::as_str)).unwrap();
    repo_listing(repo, &refs, Some(&collections)).await
}

/// Returns the ref listing of `repo` for the selectors `refs` and
/// `collections`.
async fn repo_listing(
    repo: &Repo,
    refs: &RefSelector,
    collections: Option<&RefSelector>,
) -> Vec<u8> {
    repo.build_ref_listing(refs, collections, &anyone())
        .await
        .unwrap()
        .bytes
}

/// Creates the destination repository at `dir/dest`, with the collection id
/// `own` and the remotes `remotes`: each a name, a URL, and extra keys.
async fn dest(dir: &Path, own: Option<&str>, remotes: &[(&str, &str, &str)]) -> Repo {
    let path = dir.join("dest");
    drop(create(dir, "dest", own).await);
    let config = path.join("config");
    let mut text = std::fs::read_to_string(&config).unwrap();
    for (name, url, extra) in remotes {
        text.push_str(&format!(
            "\n[remote \"{name}\"]\nurl={url}\ngpg-verify=false\ncollection-id={ID}\n{extra}"
        ));
    }
    std::fs::write(&config, text).unwrap();
    Repo::open(&path).await.unwrap()
}

/// Returns the options of a pull of `refs`, with no retry, and a sink for
/// its events.
fn options(refs: &[&str]) -> (CollectionPullOptions, Arc<Mutex<Vec<CollectionPullEvent>>>) {
    let events = Arc::new(Mutex::new(Vec::new()));
    let sink = Arc::clone(&events);
    let mut opts = CollectionPullOptions::default();
    opts.pull = PullOptions {
        refs: refs.iter().map(|r| (*r).to_owned()).collect(),
        overrides: EndpointOverrides {
            max_retries: Some(0),
            ..EndpointOverrides::default()
        },
        ..PullOptions::default()
    };
    opts.on_event = Some(Box::new(move |event| sink.lock().unwrap().push(event)));
    (opts, events)
}

/// Returns the commit of the collection ref `name` of `ID` in `repo`.
async fn mirror(repo: &Repo, name: &str) -> Option<Checksum> {
    repo.list_mirror_refs()
        .await
        .unwrap()
        .into_iter()
        .find(|(id, n, _)| id == ID && n == name)
        .map(|(_, _, commit)| commit)
}

/// Starts a server over `root` that answers each ref listing request with
/// `status`.
async fn listing_status(root: &Path, status: u16) -> RepoServer {
    let server = RepoServer::start(root, false).await;
    server.answer_status(LISTING, status);
    server
}

/// Appends `text` to the config of the repository `repo` at `dir/dest`, and
/// opens the repository again.
async fn reconfigure(dir: &Path, text: &str) -> Repo {
    let path = dir.join("dest/config");
    let mut config = std::fs::read_to_string(&path).unwrap();
    config.push_str(text);
    std::fs::write(&path, config).unwrap();
    Repo::open(&dir.join("dest")).await.unwrap()
}

/// Asserts that `repo` holds no ref and no object.
async fn assert_nothing_written(repo: &Repo) {
    assert!(repo.list_refs(None).await.unwrap().is_empty());
    assert!(repo.list_mirror_refs().await.unwrap().is_empty());
    assert!(repo.list_remote_refs().await.unwrap().is_empty());
    let objects = repo.list_objects().await.unwrap();
    assert!(objects.is_empty(), "{objects:?}");
}

/// Returns `true` if `server` received a request for an object.
fn objects_requested(server: &RepoServer) -> bool {
    server
        .seen()
        .iter()
        .any(|path| path.starts_with("objects/"))
}

// --- selection ---------------------------------------------------------------

/// The newest commit wins. The first remote serves no listing and lists the
/// ref in field 0 of its summary. The second remote serves a listing with
/// the ref in its collection map. The pull takes the objects from the second
/// remote alone, and writes the collection ref and no remote ref.
#[test]
fn the_newest_commit_wins_from_a_listing_or_a_summary() {
    block_on(async {
        let dir = TmpDir::new("pull-collection-newest");
        let a = create(dir.path(), "a", Some(ID)).await;
        commit(&a, dir.path(), "a", None, REF, FIXED_TS, BOUND).await;
        summarize(&a).await;
        let b = create(dir.path(), "b", Some(OTHER)).await;
        let newer = commit(&b, dir.path(), "b", Some(ID), REF, FIXED_TS + 10, BOUND).await;
        let server_a = RepoServer::start(&dir.path().join("a"), false).await;
        let server_b = RepoServer::start(&dir.path().join("b"), false).await;
        serve_listing(&server_b, &b, &[REF]).await;
        let dest = dest(
            dir.path(),
            None,
            &[("a", &server_a.url(), ""), ("b", &server_b.url(), "")],
        )
        .await;

        let (opts, events) = options(&[REF]);
        let pulled: CollectionPullStats =
            dest.pull_collection(ID, &["a", "b"], opts).await.unwrap();

        assert!(events.lock().unwrap().is_empty());
        assert_eq!(pulled.refs.len(), 1);
        assert_eq!(pulled.refs[0].name, REF);
        assert_eq!(pulled.refs[0].remote, "b");
        assert_eq!(pulled.refs[0].commit, newer);
        assert_eq!(pulled.refs[0].timestamp, FIXED_TS + 10);
        assert_eq!(mirror(&dest, REF).await, Some(newer));
        assert!(dest.list_refs(None).await.unwrap().is_empty());
        assert!(dest.list_remote_refs().await.unwrap().is_empty());
        assert!(dest.fsck(&FsckOptions::default()).await.unwrap().is_ok());
        assert_eq!(pulled.stats.content_fetched, 4);
        assert_eq!(pulled.local, PullStats::default());

        // The remote with no listing answered the probe from its summary,
        // and the pull asked it for no object.
        // With no summary policy, the probe reads no `summary.sig`.
        assert_eq!(server_a.seen(), [LISTING, "summary"]);
        assert!(objects_requested(&server_b));
    });
}

/// A tie of timestamps goes to the earlier remote of the list.
#[test]
fn a_tie_goes_to_the_earlier_remote() {
    block_on(async {
        let dir = TmpDir::new("pull-collection-tie");
        let a = create(dir.path(), "a", Some(ID)).await;
        let first = commit(&a, dir.path(), "a", None, REF, FIXED_TS, BOUND).await;
        summarize(&a).await;
        let b = create(dir.path(), "b", Some(ID)).await;
        commit(&b, dir.path(), "b", None, REF, FIXED_TS, BOUND).await;
        summarize(&b).await;
        let server_a = RepoServer::start(&dir.path().join("a"), false).await;
        let server_b = RepoServer::start(&dir.path().join("b"), false).await;
        let dest = dest(
            dir.path(),
            None,
            &[("a", &server_a.url(), ""), ("b", &server_b.url(), "")],
        )
        .await;

        let (opts, _) = options(&[REF]);
        let pulled = dest.pull_collection(ID, &["a", "b"], opts).await.unwrap();
        assert_eq!(pulled.refs[0].remote, "a");
        assert_eq!(mirror(&dest, REF).await, Some(first));
        assert!(!objects_requested(&server_b));
        // The pull from the selected remote uses the summary that the probe
        // read, and does not fetch it again.
        assert_eq!(server_a.requests_for("summary"), 1);
        assert_eq!(server_a.requests_for("summary.sig"), 0);
        assert_eq!(server_a.requests_for("config"), 1);
    });
}

/// A remote that answers the listing with a server error is skipped with an
/// event, and the pull takes the ref from the next remote. The skipped
/// remote holds a newer commit, and the pull reads no summary from it.
#[test]
fn a_failing_remote_is_skipped() {
    block_on(async {
        let dir = TmpDir::new("pull-collection-skip");
        let a = create(dir.path(), "a", Some(ID)).await;
        commit(&a, dir.path(), "a", None, REF, FIXED_TS + 10, BOUND).await;
        summarize(&a).await;
        let b = create(dir.path(), "b", Some(ID)).await;
        let tip = commit(&b, dir.path(), "b", None, REF, FIXED_TS, BOUND).await;
        summarize(&b).await;
        let server_a = listing_status(&dir.path().join("a"), 500).await;
        let server_b = RepoServer::start(&dir.path().join("b"), false).await;
        let dest = dest(
            dir.path(),
            None,
            &[("a", &server_a.url(), ""), ("b", &server_b.url(), "")],
        )
        .await;

        let (opts, events) = options(&[REF]);
        let pulled = dest.pull_collection(ID, &["a", "b"], opts).await.unwrap();
        assert_eq!(pulled.refs[0].remote, "b");
        assert_eq!(mirror(&dest, REF).await, Some(tip));
        let events = events.lock().unwrap();
        assert_eq!(events.len(), 1, "{events:?}");
        let CollectionPullEvent::RemoteSkipped {
            remote, message, ..
        } = &events[0]
        else {
            panic!("{events:?}");
        };
        assert_eq!(remote, "a");
        assert!(message.contains("500"), "{message}");
        assert!(events[0].to_string().starts_with("remote a skipped: "));
        assert_eq!(server_a.seen(), [LISTING]);
    });
}

/// A remote that refuses the listing request with a status from 400 to 499
/// serves no listing, and the pull reads its summary.
#[test]
fn a_client_error_on_the_listing_reads_the_summary() {
    block_on(async {
        for status in [400, 403] {
            let dir = TmpDir::new("pull-collection-client-error");
            let a = create(dir.path(), "a", Some(ID)).await;
            let tip = commit(&a, dir.path(), "a", None, REF, FIXED_TS, BOUND).await;
            summarize(&a).await;
            let server_a = listing_status(&dir.path().join("a"), status).await;
            let dest = dest(dir.path(), None, &[("a", &server_a.url(), "")]).await;

            let (opts, events) = options(&[REF]);
            let pulled = dest.pull_collection(ID, &["a"], opts).await.unwrap();
            assert_eq!(pulled.refs[0].remote, "a", "{status}");
            assert_eq!(mirror(&dest, REF).await, Some(tip), "{status}");
            assert!(events.lock().unwrap().is_empty(), "{status}");
            assert_eq!(server_a.statuses_for(LISTING), [status]);
            assert_eq!(server_a.requests_for("summary"), 1, "{status}");
        }
    });
}

/// A remote whose summary fails the summary policy of the remote is
/// skipped: a summary with no `summary.sig`, and a summary that an untrusted
/// key signed. The remote serves a listing, and the pull does not read it,
/// because no signature covers it.
#[test]
fn a_summary_that_fails_the_policy_skips_the_remote() {
    block_on(async {
        for signer in [None, Some(OTHER_SECRET_B64)] {
            let dir = TmpDir::new("pull-collection-summary-policy");
            let a = create(dir.path(), "a", Some(ID)).await;
            commit(&a, dir.path(), "a", None, REF, FIXED_TS + 10, BOUND).await;
            summarize(&a).await;
            if let Some(secret) = signer {
                let signer = Ed25519Signer::from_base64(secret).unwrap();
                a.sign_summary(&signer).await.unwrap();
            }
            let b = create(dir.path(), "b", Some(ID)).await;
            let tip = commit(&b, dir.path(), "b", None, REF, FIXED_TS, BOUND).await;
            summarize(&b).await;
            let server_a = RepoServer::start(&dir.path().join("a"), false).await;
            serve_listing(&server_a, &a, &[REF]).await;
            let server_b = RepoServer::start(&dir.path().join("b"), false).await;
            let policy =
                format!("sign-verify-summary=ed25519\nverification-ed25519-key={PUBLIC_B64}\n");
            let dest = dest(
                dir.path(),
                None,
                &[("a", &server_a.url(), &policy), ("b", &server_b.url(), "")],
            )
            .await;

            let (opts, events) = options(&[REF]);
            let pulled = dest.pull_collection(ID, &["a", "b"], opts).await.unwrap();
            assert_eq!(pulled.refs[0].remote, "b");
            assert_eq!(mirror(&dest, REF).await, Some(tip));
            let events = events.lock().unwrap();
            assert!(
                matches!(&events[..], [CollectionPullEvent::RemoteSkipped { remote, .. }] if remote == "a"),
                "{events:?}"
            );
            assert!(!objects_requested(&server_a));
            assert_eq!(server_a.requests_for(LISTING), 0);
        }
    });
}

/// Under a summary policy, the pull reads the refs from the verified
/// summary, also when the remote serves a listing. The listing names a newer
/// commit of another repository, and the pull takes the commit of the
/// summary. The pull from the selected remote reads the summary and its
/// signature one time, in the probe.
#[test]
fn a_summary_policy_takes_the_refs_from_the_verified_summary() {
    block_on(async {
        for with_listing in [false, true] {
            let dir = TmpDir::new("pull-collection-signed-summary");
            let a = create(dir.path(), "a", Some(ID)).await;
            let tip = commit(&a, dir.path(), "a", None, REF, FIXED_TS, BOUND).await;
            summarize(&a).await;
            let signer = Ed25519Signer::from_base64(SECRET_B64).unwrap();
            a.sign_summary(&signer).await.unwrap();
            let decoy = create(dir.path(), "decoy", Some(ID)).await;
            commit(&decoy, dir.path(), "d", None, REF, FIXED_TS + 10, BOUND).await;
            let server_a = RepoServer::start(&dir.path().join("a"), false).await;
            if with_listing {
                serve_listing(&server_a, &decoy, &[REF]).await;
            }
            let policy =
                format!("sign-verify-summary=ed25519\nverification-ed25519-key={PUBLIC_B64}\n");
            let dest = dest(dir.path(), None, &[("a", &server_a.url(), &policy)]).await;

            let (opts, events) = options(&[REF]);
            let pulled = dest.pull_collection(ID, &["a"], opts).await.unwrap();
            assert!(events.lock().unwrap().is_empty());
            assert_eq!(pulled.refs[0].commit, tip, "{with_listing}");
            assert_eq!(pulled.refs[0].timestamp, FIXED_TS);
            assert_eq!(mirror(&dest, REF).await, Some(tip));
            assert_eq!(server_a.requests_for(LISTING), 0);
            assert_eq!(server_a.requests_for("summary"), 1);
            assert_eq!(server_a.requests_for("summary.sig"), 1);
        }
    });
}

/// A ref that no remote lists fails the pull before an object request. A
/// pull in which each remote fails fails too.
#[test]
fn a_ref_that_no_remote_lists_fails_the_pull() {
    block_on(async {
        let dir = TmpDir::new("pull-collection-missing");
        let a = create(dir.path(), "a", Some(ID)).await;
        commit(&a, dir.path(), "a", None, REF, FIXED_TS, BOUND).await;
        summarize(&a).await;
        let server_a = RepoServer::start(&dir.path().join("a"), false).await;
        let server_dead = listing_status(dir.path(), 500).await;
        let dest = dest(
            dir.path(),
            None,
            &[("a", &server_a.url(), ""), ("dead", &server_dead.url(), "")],
        )
        .await;

        let (opts, _) = options(&[REF, "os/absent"]);
        let err = dest
            .pull_collection(ID, &["a", "dead"], opts)
            .await
            .unwrap_err();
        assert!(
            matches!(&err, Error::Pull(m) if m.contains("os/absent") && m.contains(ID)),
            "{err:?}"
        );
        assert!(!objects_requested(&server_a));
        assert_nothing_written(&dest).await;

        let (opts, events) = options(&[REF]);
        let err = dest.pull_collection(ID, &["dead"], opts).await.unwrap_err();
        assert!(matches!(err, Error::Pull(_)), "{err:?}");
        assert_eq!(events.lock().unwrap().len(), 1);
    });
}

/// With no ref name, the pull takes each ref of the collection that a remote
/// lists, and no ref of another collection. The listing request selects no
/// local ref, so a remote of another collection sends none.
#[test]
fn no_ref_name_pulls_each_ref_of_the_collection() {
    block_on(async {
        let dir = TmpDir::new("pull-collection-all");
        let b = create(dir.path(), "b", Some(OTHER)).await;
        let stable = commit(&b, dir.path(), "s", Some(ID), REF, FIXED_TS, BOUND).await;
        let next_bind = Bind {
            collection: Some(ID),
            refs: Some(&["os/next"]),
        };
        let next = commit(
            &b,
            dir.path(),
            "n",
            Some(ID),
            "os/next",
            FIXED_TS,
            next_bind,
        )
        .await;
        let other_bind = Bind {
            collection: Some(OTHER),
            refs: Some(&["other"]),
        };
        commit(&b, dir.path(), "o", None, "other", FIXED_TS, other_bind).await;
        let server_b = RepoServer::start(&dir.path().join("b"), false).await;
        serve_listing(&server_b, &b, &[]).await;
        let dest = dest(dir.path(), None, &[("b", &server_b.url(), "")]).await;

        let (opts, _) = options(&[]);
        let pulled = dest.pull_collection(ID, &["b"], opts).await.unwrap();
        let names: Vec<&str> = pulled.refs.iter().map(|r| r.name.as_str()).collect();
        assert_eq!(names, ["os/next", REF]);
        assert_eq!(mirror(&dest, REF).await, Some(stable));
        assert_eq!(mirror(&dest, "os/next").await, Some(next));
        assert_eq!(dest.list_mirror_refs().await.unwrap().len(), 2);
        assert!(dest.list_refs(None).await.unwrap().is_empty());
        assert_eq!(
            server_b.queries_for(LISTING),
            ["pattern=%21%2A%2A&collection=org.example.Os%2F%2A%2A"]
        );
    });
}

/// With no ref name, a remote whose own collection id is the pulled id
/// lists the refs in field 0. The pull asks it a second time, for each local
/// ref and no collection ref.
#[test]
fn no_ref_name_asks_a_remote_of_the_collection_for_its_local_refs() {
    block_on(async {
        let dir = TmpDir::new("pull-collection-all-own");
        let a = create(dir.path(), "a", Some(ID)).await;
        let stable = commit(&a, dir.path(), "a", None, REF, FIXED_TS, BOUND).await;
        let server_a = RepoServer::start(&dir.path().join("a"), false).await;
        let refs = RefSelector::parse(std::iter::empty()).unwrap();
        let every = repo_listing(&a, &refs, None).await;
        server_a.tamper(LISTING, every);
        let dest = dest(dir.path(), None, &[("a", &server_a.url(), "")]).await;

        let (opts, _) = options(&[]);
        let pulled = dest.pull_collection(ID, &["a"], opts).await.unwrap();
        assert_eq!(pulled.refs.len(), 1);
        assert_eq!(mirror(&dest, REF).await, Some(stable));
        assert_eq!(
            server_a.queries_for(LISTING),
            ["pattern=%21%2A%2A&collection=org.example.Os%2F%2A%2A", ""]
        );
    });
}

/// With no ref name, a pull in which no remote lists a ref of the collection
/// fails before an object request, and writes nothing.
#[test]
fn no_ref_name_and_no_listed_ref_fails_the_pull() {
    block_on(async {
        let dir = TmpDir::new("pull-collection-none");
        let b = create(dir.path(), "b", Some(OTHER)).await;
        let other_bind = Bind {
            collection: Some(OTHER),
            refs: Some(&["other"]),
        };
        commit(&b, dir.path(), "o", None, "other", FIXED_TS, other_bind).await;
        summarize(&b).await;
        let server_b = RepoServer::start(&dir.path().join("b"), false).await;
        let dest = dest(dir.path(), None, &[("b", &server_b.url(), "")]).await;

        let (opts, events) = options(&[]);
        let err = dest.pull_collection(ID, &["b"], opts).await.unwrap_err();
        assert!(
            matches!(&err, Error::Pull(m) if m == &format!("no remote lists a ref of collection '{ID}'")),
            "{err:?}"
        );
        assert!(events.lock().unwrap().is_empty());
        assert!(!objects_requested(&server_b));
        assert_nothing_written(&dest).await;
    });
}

// --- checks of the commit ----------------------------------------------------

/// The pull refuses a commit bound to another collection, a commit with no
/// collection binding, and a commit whose ref binding does not hold the ref.
/// A commit with no ref binding passes. With `allow_unbound`, a commit bound
/// to another collection and a commit whose ref binding does not hold the ref
/// also fail.
#[test]
fn the_bindings_of_each_commit_are_checked() {
    block_on(async {
        let cases: [(&str, Bind<'static>, bool, Option<&str>); 6] = [
            (
                "other collection",
                Bind {
                    collection: Some(OTHER),
                    refs: Some(&[REF]),
                },
                false,
                Some(OTHER),
            ),
            (
                "other collection",
                Bind {
                    collection: Some(OTHER),
                    refs: Some(&[REF]),
                },
                true,
                Some(OTHER),
            ),
            (
                "no collection binding",
                Bind {
                    collection: None,
                    refs: Some(&[REF]),
                },
                false,
                Some("no collection binding"),
            ),
            (
                "other ref",
                Bind {
                    collection: Some(ID),
                    refs: Some(&["os/next"]),
                },
                false,
                Some("in ref binding metadata"),
            ),
            (
                "other ref",
                Bind {
                    collection: None,
                    refs: Some(&["os/next"]),
                },
                true,
                Some("in ref binding metadata"),
            ),
            (
                "no ref binding",
                Bind {
                    collection: Some(ID),
                    refs: None,
                },
                false,
                None,
            ),
        ];
        for (tag, bind, allow_unbound, fragment) in cases {
            let dir = TmpDir::new("pull-collection-bindings");
            let a = create(dir.path(), "a", Some(ID)).await;
            let tip = commit(&a, dir.path(), "a", None, REF, FIXED_TS, bind).await;
            summarize(&a).await;
            let server_a = RepoServer::start(&dir.path().join("a"), false).await;
            let dest = dest(dir.path(), None, &[("a", &server_a.url(), "")]).await;

            let (mut opts, _) = options(&[REF]);
            opts.allow_unbound = allow_unbound;
            let pulled = dest.pull_collection(ID, &["a"], opts).await;
            let Some(fragment) = fragment else {
                pulled.unwrap();
                assert_eq!(
                    mirror(&dest, REF).await,
                    Some(tip),
                    "{tag}, allow_unbound={allow_unbound}"
                );
                continue;
            };
            let err = pulled.unwrap_err();
            assert!(
                matches!(&err, Error::Pull(m) if m.contains(fragment)),
                "{tag}, allow_unbound={allow_unbound}: {err:?}"
            );
            assert_nothing_written(&dest).await;
        }
    });
}

/// With `allow_unbound`, a tip with no collection binding passes, with or
/// without a ref binding that holds the ref. The pull writes the collection
/// ref.
#[test]
fn allow_unbound_pulls_a_tip_with_no_collection_binding() {
    block_on(async {
        let cases: [(&str, Bind<'static>); 2] = [
            (
                "ref binding",
                Bind {
                    collection: None,
                    refs: Some(&[REF]),
                },
            ),
            (
                "no binding",
                Bind {
                    collection: None,
                    refs: None,
                },
            ),
        ];
        for (tag, bind) in cases {
            let dir = TmpDir::new("pull-collection-unbound");
            let a = create(dir.path(), "a", Some(ID)).await;
            let tip = commit(&a, dir.path(), "a", None, REF, FIXED_TS, bind).await;
            summarize(&a).await;
            let server_a = RepoServer::start(&dir.path().join("a"), false).await;
            let dest = dest(dir.path(), None, &[("a", &server_a.url(), "")]).await;

            let (mut opts, _) = options(&[REF]);
            opts.allow_unbound = true;
            let pulled = dest.pull_collection(ID, &["a"], opts).await.unwrap();

            assert_eq!(pulled.refs.len(), 1, "{tag}");
            assert_eq!(pulled.refs[0].commit, tip, "{tag}");
            assert_eq!(mirror(&dest, REF).await, Some(tip), "{tag}");
            assert!(
                dest.fsck(&FsckOptions::default()).await.unwrap().is_ok(),
                "{tag}"
            );
        }
    });
}

/// With `allow_unbound`, the pull takes a tip with no collection binding from
/// a static delta. Without it, the same pull fails and writes nothing.
#[test]
fn allow_unbound_reaches_a_tip_from_a_static_delta() {
    block_on(async {
        let dir = TmpDir::new("pull-collection-unbound-delta");
        let a = create(dir.path(), "a", Some(ID)).await;
        let bind = Bind {
            collection: None,
            refs: Some(&[REF]),
        };
        let tip = commit(&a, dir.path(), "a", None, REF, FIXED_TS, bind).await;
        a.generate_static_delta(None, &tip, &DeltaOptions::default())
            .await
            .unwrap();
        summarize(&a).await;
        let server_a = RepoServer::start(&dir.path().join("a"), false).await;
        let dest = dest(dir.path(), None, &[("a", &server_a.url(), "")]).await;

        let (mut opts, _) = options(&[REF]);
        opts.pull.require_static_deltas = true;
        let err = dest.pull_collection(ID, &["a"], opts).await.unwrap_err();
        assert!(
            matches!(&err, Error::Pull(m) if m.contains("no collection binding")),
            "{err:?}"
        );
        let seen = server_a.seen();
        assert!(seen.iter().any(|p| p.starts_with("deltas/")), "{seen:?}");
        assert_nothing_written(&dest).await;

        let (mut opts, _) = options(&[REF]);
        opts.pull.require_static_deltas = true;
        opts.allow_unbound = true;
        let pulled = dest.pull_collection(ID, &["a"], opts).await.unwrap();
        assert!(pulled.stats.delta_parts > 0, "{:?}", pulled.stats);
        assert_eq!(mirror(&dest, REF).await, Some(tip));
    });
}

/// A commit whose timestamp differs from the timestamp that the remote
/// listed fails the pull.
#[test]
fn a_commit_with_another_timestamp_than_listed_fails() {
    block_on(async {
        let dir = TmpDir::new("pull-collection-listed-timestamp");
        let b = create(dir.path(), "b", Some(OTHER)).await;
        commit(&b, dir.path(), "b", Some(ID), REF, FIXED_TS, BOUND).await;
        let server_b = RepoServer::start(&dir.path().join("b"), false).await;
        // The listing states one second more than the commit holds.
        let mut bytes = listing(&b, &[REF]).await;
        let real = FIXED_TS.to_be_bytes();
        let at = bytes
            .windows(8)
            .position(|w| w == real)
            .expect("the listing holds the timestamp");
        bytes[at..at + 8].copy_from_slice(&(FIXED_TS + 1).to_be_bytes());
        server_b.tamper("_ostrya/refs/v1", bytes);
        let dest = dest(dir.path(), None, &[("b", &server_b.url(), "")]).await;

        let (opts, _) = options(&[REF]);
        let err = dest.pull_collection(ID, &["b"], opts).await.unwrap_err();
        assert!(
            matches!(&err, Error::Pull(m) if m.contains("timestamp")),
            "{err:?}"
        );
        assert_nothing_written(&dest).await;
    });
}

/// The keys of the selected remote apply. The newer remote requires a
/// signature, and its unsigned commit fails the pull. With an older commit
/// there, the other remote is selected, and its policy passes the commit.
#[test]
fn the_keys_of_the_selected_remote_apply() {
    block_on(async {
        for newer_signed_remote in [true, false] {
            let dir = TmpDir::new("pull-collection-keys");
            let a = create(dir.path(), "a", Some(ID)).await;
            let a_ts = if newer_signed_remote {
                FIXED_TS
            } else {
                FIXED_TS + 10
            };
            let a_tip = commit(&a, dir.path(), "a", None, REF, a_ts, BOUND).await;
            summarize(&a).await;
            let b = create(dir.path(), "b", Some(ID)).await;
            commit(&b, dir.path(), "b", None, REF, FIXED_TS + 5, BOUND).await;
            summarize(&b).await;
            let server_a = RepoServer::start(&dir.path().join("a"), false).await;
            let server_b = RepoServer::start(&dir.path().join("b"), false).await;
            let policy = format!("sign-verify=ed25519\nverification-ed25519-key={PUBLIC_B64}\n");
            let dest = dest(
                dir.path(),
                None,
                &[("a", &server_a.url(), ""), ("b", &server_b.url(), &policy)],
            )
            .await;

            let (opts, _) = options(&[REF]);
            let pulled = dest.pull_collection(ID, &["a", "b"], opts).await;
            if newer_signed_remote {
                let err = pulled.unwrap_err();
                assert!(matches!(err, Error::Signature(_)), "{err:?}");
                assert_nothing_written(&dest).await;
            } else {
                assert_eq!(pulled.unwrap().refs[0].remote, "a");
                assert_eq!(mirror(&dest, REF).await, Some(a_tip));
            }
        }
    });
}

/// The trust group option applies to the pull from each remote. The group
/// trusts one key, and the remote section names no key. An unsigned commit
/// fails the pull, and a commit of the key of the group passes.
#[test]
fn a_collection_pull_takes_the_trust_group_option() {
    block_on(async {
        let dir = TmpDir::new("pull-collection-trust-group");
        let a = create(dir.path(), "a", Some(ID)).await;
        let tip = commit(&a, dir.path(), "a", None, REF, FIXED_TS, BOUND).await;
        summarize(&a).await;
        let server = RepoServer::start(&dir.path().join("a"), false).await;
        let group = format!(
            "[ex-ostrya trust \"t\"]\nsign-verify=ed25519\nverification-ed25519-key={PUBLIC_B64}\n"
        );
        let dest = dest(dir.path(), None, &[("a", &server.url(), &group)]).await;
        let pull = || {
            let (mut opts, _) = options(&[REF]);
            opts.pull.trust_group = Some("t".to_owned());
            dest.pull_collection(ID, &["a"], opts)
        };

        let err = pull().await.unwrap_err();
        assert!(
            matches!(&err, Error::Signature(m) if m.contains("carries no signature")),
            "{err:?}"
        );
        assert_nothing_written(&dest).await;

        a.sign_commit(&tip, &Ed25519Signer::from_base64(SECRET_B64).unwrap())
            .await
            .unwrap();
        let pulled = pull().await.unwrap();
        assert_eq!(pulled.refs[0].remote, "a");
        assert_eq!(mirror(&dest, REF).await, Some(tip));
    });
}

// --- the place of the refs ---------------------------------------------------

/// Into a repository whose own collection id is the pulled id, and that holds
/// no collection ref of the name, the pull writes the local ref, and the
/// timestamp check reads that ref.
#[test]
fn the_own_collection_writes_the_local_ref() {
    block_on(async {
        let dir = TmpDir::new("pull-collection-local");
        let a = create(dir.path(), "a", Some(ID)).await;
        let tip = commit(&a, dir.path(), "a", None, REF, FIXED_TS, BOUND).await;
        summarize(&a).await;
        let server_a = RepoServer::start(&dir.path().join("a"), false).await;
        let dest = dest(dir.path(), Some(ID), &[("a", &server_a.url(), "")]).await;

        let (mut opts, _) = options(&[REF]);
        opts.pull.timestamp_check = TimestampCheck::CurrentRef;
        dest.pull_collection(ID, &["a"], opts).await.unwrap();
        assert_eq!(
            dest.resolve_ref_tip(&Ref::local(REF)).await.unwrap(),
            Some(tip)
        );
        assert!(dest.list_mirror_refs().await.unwrap().is_empty());

        // An older commit on the remote now fails the timestamp check against
        // the local ref.
        let older = create(dir.path(), "older", Some(ID)).await;
        commit(&older, dir.path(), "older", None, REF, FIXED_TS - 10, BOUND).await;
        summarize(&older).await;
        let server_older = RepoServer::start(&dir.path().join("older"), false).await;
        let path = dir.path().join("dest/config");
        let mut text = std::fs::read_to_string(&path).unwrap();
        text.push_str(&format!(
            "\n[remote \"older\"]\nurl={}\ngpg-verify=false\n",
            server_older.url()
        ));
        std::fs::write(&path, text).unwrap();
        let dest = Repo::open(&dir.path().join("dest")).await.unwrap();
        let (mut opts, _) = options(&[REF]);
        opts.pull.timestamp_check = TimestampCheck::CurrentRef;
        let err = dest
            .pull_collection(ID, &["older"], opts)
            .await
            .unwrap_err();
        assert!(
            matches!(&err, Error::Pull(m) if m.contains("chronologically older")),
            "{err:?}"
        );
        assert_eq!(
            dest.resolve_ref_tip(&Ref::local(REF)).await.unwrap(),
            Some(tip)
        );
    });
}

/// Creates the destination at `dir/dest` with the collection id `ID` and the
/// remote `a` at `url`. The destination holds `refs/mirrors/ID/REF`, written
/// by hand, at a commit with the timestamp `mirror_ts`, and the local ref
/// `REF` at a commit with the timestamp `local_ts`. Returns the destination
/// and the two commits.
async fn dest_with_own_mirror(
    dir: &Path,
    url: &str,
    mirror_ts: u64,
    local_ts: u64,
) -> (Repo, Checksum, Checksum) {
    let dest = dest(dir, Some(ID), &[("a", url, "")]).await;
    let held = commit(&dest, dir, "held", None, REF, mirror_ts, BOUND).await;
    let mirror = dir.join(format!("dest/refs/mirrors/{ID}/{REF}"));
    std::fs::create_dir_all(mirror.parent().unwrap()).unwrap();
    std::fs::write(&mirror, format!("{}\n", held.to_hex())).unwrap();
    let local = commit(&dest, dir, "local", None, REF, local_ts, BOUND).await;
    (dest, held, local)
}

/// Asserts that the destination `dest` at `dir/dest` holds
/// `refs/mirrors/ID/REF` at `held` and the local ref `REF` at `local`, and
/// that the resolve and the listing of the collection ref give `local`.
async fn assert_own_refs(dir: &Path, dest: &Repo, held: Checksum, local: Checksum) {
    let path = dir.join(format!("dest/refs/mirrors/{ID}/{REF}"));
    let file = std::fs::read_to_string(path).unwrap();
    assert_eq!(file.trim(), held.to_hex());
    assert_eq!(
        dest.resolve_ref_tip(&Ref::local(REF)).await.unwrap(),
        Some(local)
    );
    let cref = Ref::collection(ID, REF);
    assert_eq!(dest.resolve_ref_tip(&cref).await.unwrap(), Some(local));
    let all = RefSelector::parse([]).unwrap();
    assert_eq!(
        dest.list_collection_refs_in(ID, &all).await.unwrap(),
        vec![(REF.to_owned(), local)]
    );
}

/// Into a repository whose own collection id is the pulled id, and that holds
/// `refs/mirrors/ID/REF`, the pull writes the local ref of the name. The
/// mirror ref keeps its commit, and the resolve and the listing of the
/// collection ref read the local ref.
#[test]
fn the_own_collection_writes_the_local_ref_beside_a_mirror_ref() {
    block_on(async {
        let dir = TmpDir::new("pull-collection-own-mirror");
        let a = create(dir.path(), "a", Some(ID)).await;
        let tip = commit(&a, dir.path(), "a", None, REF, FIXED_TS, BOUND).await;
        summarize(&a).await;
        let server_a = RepoServer::start(&dir.path().join("a"), false).await;
        let (dest, held, _) =
            dest_with_own_mirror(dir.path(), &server_a.url(), FIXED_TS - 10, FIXED_TS - 10).await;

        let (opts, _) = options(&[REF]);
        dest.pull_collection(ID, &["a"], opts).await.unwrap();

        assert_own_refs(dir.path(), &dest, held, tip).await;
    });
}

/// Into a repository whose own collection id is the pulled id, and that holds
/// `refs/mirrors/ID/REF`, the timestamp check reads the local ref and not the
/// mirror ref. A local ref newer than the tip fails the pull, and the pull
/// writes no ref. A local ref older than the tip passes, and the pull writes
/// the local ref. The mirror ref has the other timestamp in each case.
#[test]
fn the_timestamp_check_of_the_own_collection_reads_the_local_ref() {
    block_on(async {
        let dir = TmpDir::new("pull-collection-own-mirror-timestamp");
        let a = create(dir.path(), "a", Some(ID)).await;
        let tip = commit(&a, dir.path(), "a", None, REF, FIXED_TS, BOUND).await;
        summarize(&a).await;
        let server_a = RepoServer::start(&dir.path().join("a"), false).await;
        for (case, mirror_ts, local_ts) in [
            ("newer", FIXED_TS - 10, FIXED_TS + 10),
            ("older", FIXED_TS + 10, FIXED_TS - 10),
        ] {
            let path = dir.path().join(case);
            std::fs::create_dir(&path).unwrap();
            let (dest, held, local) =
                dest_with_own_mirror(&path, &server_a.url(), mirror_ts, local_ts).await;

            let (mut opts, _) = options(&[REF]);
            opts.pull.timestamp_check = TimestampCheck::CurrentRef;
            let pulled = dest.pull_collection(ID, &["a"], opts).await;

            if local_ts > FIXED_TS {
                let err = pulled.unwrap_err();
                assert!(
                    matches!(&err, Error::Pull(m) if m.contains("chronologically older")),
                    "{case}: {err:?}"
                );
                assert_own_refs(&path, &dest, held, local).await;
            } else {
                pulled.unwrap();
                assert_own_refs(&path, &dest, held, tip).await;
            }
        }
    });
}

/// Into a repository of another collection, the timestamp check reads the
/// collection ref that the pull writes.
#[test]
fn the_timestamp_check_reads_the_collection_ref() {
    block_on(async {
        let dir = TmpDir::new("pull-collection-mirror-timestamp");
        let a = create(dir.path(), "a", Some(ID)).await;
        let tip = commit(&a, dir.path(), "a", None, REF, FIXED_TS, BOUND).await;
        summarize(&a).await;
        let older = create(dir.path(), "older", Some(ID)).await;
        commit(&older, dir.path(), "older", None, REF, FIXED_TS - 10, BOUND).await;
        summarize(&older).await;
        let server_a = RepoServer::start(&dir.path().join("a"), false).await;
        let server_older = RepoServer::start(&dir.path().join("older"), false).await;
        let dest = dest(
            dir.path(),
            Some(OTHER),
            &[
                ("a", &server_a.url(), ""),
                ("older", &server_older.url(), ""),
            ],
        )
        .await;

        let (mut opts, _) = options(&[REF]);
        opts.pull.timestamp_check = TimestampCheck::CurrentRef;
        dest.pull_collection(ID, &["a"], opts).await.unwrap();
        assert_eq!(mirror(&dest, REF).await, Some(tip));

        let (mut opts, _) = options(&[REF]);
        opts.pull.timestamp_check = TimestampCheck::CurrentRef;
        let err = dest
            .pull_collection(ID, &["older"], opts)
            .await
            .unwrap_err();
        assert!(
            matches!(&err, Error::Pull(m) if m.contains("chronologically older")),
            "{err:?}"
        );
        assert_eq!(mirror(&dest, REF).await, Some(tip));
        assert!(dest.list_refs(None).await.unwrap().is_empty());
    });
}

// --- detached metadata -------------------------------------------------------

/// With `keep-detached-related=false` in the destination, the pull drops
/// `ostrya.related` from the detached metadata that it stores, and stores
/// each other property.
#[test]
fn the_switch_drops_the_related_key_of_a_collection_pull() {
    block_on(async {
        let dir = TmpDir::new("pull-collection-keep-related");
        let a = create(dir.path(), "a", Some(ID)).await;
        let base = commit(&a, dir.path(), "base", None, "os/base", FIXED_TS, BOUND).await;
        let tip = commit(&a, dir.path(), "a", None, REF, FIXED_TS, BOUND).await;
        let kept = Value::Array(vec![entry("test.kept", "s", Value::Str("a".to_owned()))]);
        a.write_commit_detached_metadata(&tip, Some(&kept))
            .await
            .unwrap();
        a.add_supplement(&tip, "layer/base", &base).await.unwrap();
        summarize(&a).await;
        let server_a = RepoServer::start(&dir.path().join("a"), false).await;
        drop(dest(dir.path(), None, &[("a", &server_a.url(), "")]).await);
        let dest = reconfigure(dir.path(), "\n[ex-ostrya]\nkeep-detached-related=false\n").await;
        assert!(
            !dest
                .config()
                .get::<ex_ostrya::KeepDetachedRelated>()
                .unwrap()
        );

        let (opts, _) = options(&[REF]);
        dest.pull_collection(ID, &["a"], opts).await.unwrap();

        assert_eq!(mirror(&dest, REF).await, Some(tip));
        let stored = dest
            .read_commit_detached_metadata(&tip)
            .await
            .unwrap()
            .unwrap();
        assert!(stored.dict_get("test.kept").is_some(), "{stored:?}");
        assert!(stored.dict_get("ostrya.related").is_none(), "{stored:?}");
    });
}

// --- config values -----------------------------------------------------------

/// A value of `[core] fsync` or `[core] per-object-fsync` that is not a
/// boolean stops a collection pull before its first request.
#[test]
fn a_bad_fsync_value_refuses_a_collection_pull() {
    for key in ["fsync", "per-object-fsync"] {
        block_on(async {
            let dir = TmpDir::new("pull-collection-fsync-bad-value");
            let a = create(dir.path(), "a", Some(ID)).await;
            commit(&a, dir.path(), "a", None, REF, FIXED_TS, BOUND).await;
            summarize(&a).await;
            let server_a = RepoServer::start(&dir.path().join("a"), false).await;
            drop(dest(dir.path(), None, &[("a", &server_a.url(), "")]).await);
            let config = dir.path().join("dest/config");
            let text = std::fs::read_to_string(&config).unwrap();
            std::fs::write(
                &config,
                text.replacen("[core]\n", &format!("[core]\n{key}=maybe\n"), 1),
            )
            .unwrap();
            let dest = Repo::open(&dir.path().join("dest")).await.unwrap();

            let (opts, _) = options(&[REF]);
            let err = dest.pull_collection(ID, &["a"], opts).await.unwrap_err();
            assert!(matches!(err, Error::Core(_)), "{key}: {err}");
            assert!(server_a.seen().is_empty(), "{:?}", server_a.seen());
            assert_nothing_written(&dest).await;
        });
    }
}

// --- attachments ------------------------------------------------------------

/// A collection pull fetches the attachment that field 2 of the pulled commit
/// names, complete, and writes no ref for it. The attachment gets no binding
/// check.
#[test]
fn a_collection_pull_fetches_the_attachment() {
    block_on(async {
        let dir = TmpDir::new("pull-collection-dependency");
        let a = create(dir.path(), "a", Some(ID)).await;
        let unbound = Bind {
            collection: None,
            refs: None,
        };
        let att = commit(&a, dir.path(), "dep", None, "os/dep", FIXED_TS, unbound).await;
        let plain = commit(&a, dir.path(), "a", None, REF, FIXED_TS, BOUND).await;
        let tip = store_with_field2(&a, &plain, &[("boot/uki", att.as_bytes())]).await;
        let txn = a.transaction().await.unwrap();
        txn.set_ref(&Ref::local(REF), Some(&tip));
        txn.commit().await.unwrap();
        summarize(&a).await;
        let server_a = RepoServer::start(&dir.path().join("a"), false).await;
        let dest = dest(dir.path(), None, &[("a", &server_a.url(), "")]).await;

        let (opts, _) = options(&[REF]);
        dest.pull_collection(ID, &["a"], opts).await.unwrap();

        assert_eq!(mirror(&dest, REF).await, Some(tip));
        assert_eq!(dest.list_mirror_refs().await.unwrap().len(), 1);
        assert!(dest.list_refs(None).await.unwrap().is_empty());
        assert!(dest.list_remote_refs().await.unwrap().is_empty());
        assert!(dest.has_object(ObjectType::Commit, &att).await.unwrap());
        assert_eq!(
            dest.commit_state(&att).await.unwrap(),
            ostrya::CommitState::Normal
        );
        for name in &a.traverse_commit(&att, 0).await.unwrap() {
            assert!(
                dest.has_object(name.ty, &name.checksum).await.unwrap(),
                "{name} missing from the destination"
            );
        }
        assert!(dest.fsck(&FsckOptions::default()).await.unwrap().is_ok());
    });
}

/// A collection pull takes the full set of attachments of the pulled
/// commit: the tip names C of the chain R -> C -> D, and the pull takes C
/// and D, complete, with no marker and no ref for either.
#[test]
fn a_collection_pull_takes_the_full_set_of_attachments() {
    block_on(async {
        let dir = TmpDir::new("pull-collection-attachment-chain");
        let a = create(dir.path(), "a", Some(ID)).await;
        let chain = common::write_chain(&a, &dir.path().join("trees"), "os/chain").await;
        let plain = commit(&a, dir.path(), "a", None, REF, FIXED_TS, BOUND).await;
        let tip = store_with_field2(&a, &plain, &[(common::CHAIN_C, chain.c.as_bytes())]).await;
        let txn = a.transaction().await.unwrap();
        txn.set_ref(&Ref::local(REF), Some(&tip));
        txn.commit().await.unwrap();
        summarize(&a).await;
        let server_a = RepoServer::start(&dir.path().join("a"), false).await;
        let dest = dest(dir.path(), None, &[("a", &server_a.url(), "")]).await;

        let (opts, _) = options(&[REF]);
        dest.pull_collection(ID, &["a"], opts).await.unwrap();

        assert_eq!(mirror(&dest, REF).await, Some(tip));
        assert_eq!(dest.list_mirror_refs().await.unwrap().len(), 1);
        assert!(dest.list_refs(None).await.unwrap().is_empty());
        for commit in [tip, chain.c, chain.d] {
            assert_eq!(
                dest.commit_state(&commit).await.unwrap(),
                ostrya::CommitState::Normal
            );
            for name in &a.traverse_commit(&commit, 0).await.unwrap() {
                assert!(
                    dest.has_object(name.ty, &name.checksum).await.unwrap(),
                    "{name} missing from the destination"
                );
            }
        }
        assert_eq!(
            common::file_inventory(&dir.path().join("dest"), "state"),
            Vec::new()
        );
        let report = dest.fsck(&FsckOptions::default()).await.unwrap();
        assert!(
            report.errors.is_empty() && report.failure.is_none(),
            "{report:?}"
        );
    });
}

// --- local repositories ------------------------------------------------------

/// The bindings of a commit bound to `ID` with no ref binding.
const COLLECTION_ONLY: Bind<'static> = Bind {
    collection: Some(ID),
    refs: None,
};

/// Returns the `file://` address of the repository at `dir/name`.
fn file_url(dir: &Path, name: &str) -> String {
    format!("file://{}", dir.join(name).display())
}

/// Returns the names of the remotes of the skip events of `events`, and
/// checks that each message holds the path of the remote at `dir/NAME`.
fn skipped(dir: &Path, events: &Mutex<Vec<CollectionPullEvent>>) -> Vec<String> {
    events
        .lock()
        .unwrap()
        .iter()
        .map(|event| match event {
            CollectionPullEvent::RemoteSkipped {
                remote, message, ..
            } => {
                let path = dir.join(remote).display().to_string();
                assert!(message.contains(&path), "{remote}: {message}");
                remote.clone()
            }
            other => panic!("{other:?}"),
        })
        .collect()
}

/// Sets `mode` on `path`. Returns `false`, with mode `restore` set again
/// and a skip message on standard error, when the process still reads the
/// path: a user that ignores the mode cannot run the test.
fn lock(path: &Path, mode: u32, restore: u32) -> bool {
    use std::os::unix::fs::PermissionsExt;
    std::fs::set_permissions(path, std::fs::Permissions::from_mode(mode)).unwrap();
    let readable = if path.is_dir() {
        std::fs::read_dir(path).is_ok()
    } else {
        std::fs::read(path).is_ok()
    };
    if readable {
        unlock(path, restore);
        eprintln!(
            "skipping: the process reads {} with mode {mode:o}, so it ignores the mode",
            path.display()
        );
        return false;
    }
    true
}

/// Sets `mode` on `path`.
fn unlock(path: &Path, mode: u32) {
    use std::os::unix::fs::PermissionsExt;
    std::fs::set_permissions(path, std::fs::Permissions::from_mode(mode)).unwrap();
}

/// A remote at a `file://` address is a local repository, and the pull reads
/// its refs and objects through the file system. Without `allow_unbound`, a
/// tip with no collection binding fails the pull, and the pull writes
/// nothing. With it, the pull writes each ref with the commit and the
/// timestamp of the ref file of the source, and copies the `.commitmeta` of
/// a commit. The pull fetches nothing. With no ref name, the pull takes each
/// ref of the collection.
#[test]
fn a_file_remote_pulls_from_a_local_repository() {
    block_on(async {
        let dir = TmpDir::new("pull-collection-file");
        let a = create(dir.path(), "a", Some(OTHER)).await;
        let unbound = Bind {
            collection: None,
            refs: None,
        };
        let stable = commit(&a, dir.path(), "a1", Some(ID), REF, FIXED_TS, unbound).await;
        let next = commit(
            &a,
            dir.path(),
            "a2",
            Some(ID),
            "os/next",
            FIXED_TS + 5,
            unbound,
        )
        .await;
        let signer = Ed25519Signer::from_base64(SECRET_B64).unwrap();
        a.sign_commit(&stable, &signer).await.unwrap();
        let dest = dest(dir.path(), None, &[("a", &file_url(dir.path(), "a"), "")]).await;

        let (opts, events) = options(&[REF, "os/next"]);
        let err = dest.pull_collection(ID, &["a"], opts).await.unwrap_err();
        assert!(
            matches!(&err, Error::Pull(m) if m.contains("no collection binding")),
            "{err:?}"
        );
        assert!(events.lock().unwrap().is_empty());
        assert_nothing_written(&dest).await;

        let (mut opts, events) = options(&[REF, "os/next"]);
        opts.allow_unbound = true;
        let pulled = dest.pull_collection(ID, &["a"], opts).await.unwrap();
        assert!(events.lock().unwrap().is_empty());
        let got: Vec<(&str, &str, Checksum, u64)> = pulled
            .refs
            .iter()
            .map(|r| (r.name.as_str(), r.remote.as_str(), r.commit, r.timestamp))
            .collect();
        assert_eq!(
            got,
            [
                (REF, "a", stable, FIXED_TS),
                ("os/next", "a", next, FIXED_TS + 5)
            ]
        );
        assert_eq!(mirror(&dest, REF).await, Some(stable));
        assert_eq!(mirror(&dest, "os/next").await, Some(next));
        assert!(dest.list_refs(None).await.unwrap().is_empty());
        assert!(dest.list_remote_refs().await.unwrap().is_empty());
        assert!(dest.fsck(&FsckOptions::default()).await.unwrap().is_ok());
        let detached = dest.read_commit_detached_metadata(&stable).await.unwrap();
        assert!(detached.is_some());
        assert_eq!(
            detached,
            a.read_commit_detached_metadata(&stable).await.unwrap()
        );
        assert!(pulled.stats.metadata_imported > 0, "{:?}", pulled.stats);
        assert!(pulled.stats.content_imported > 0, "{:?}", pulled.stats);
        assert_eq!(pulled.stats.metadata_fetched, 0);
        assert_eq!(pulled.stats.content_fetched, 0);
        assert_eq!(pulled.stats.bytes_transferred, 0);
        assert_eq!(
            PullStats {
                elapsed: pulled.stats.elapsed,
                ..pulled.local
            },
            pulled.stats
        );

        let (mut opts, _) = options(&[]);
        opts.allow_unbound = true;
        let pulled = dest.pull_collection(ID, &["a"], opts).await.unwrap();
        let names: Vec<&str> = pulled.refs.iter().map(|r| r.name.as_str()).collect();
        assert_eq!(names, ["os/next", REF]);
    });
}

/// An HTTP remote and a `file://` remote each give the ref for which they
/// list the newer commit.
#[test]
fn an_http_remote_and_a_file_remote_each_give_the_newer_commit() {
    block_on(async {
        let dir = TmpDir::new("pull-collection-file-mixed");
        let next_bound = Bind {
            collection: Some(ID),
            refs: Some(&["os/next"]),
        };
        let a = create(dir.path(), "a", Some(ID)).await;
        let a_stable = commit(&a, dir.path(), "a1", None, REF, FIXED_TS + 10, BOUND).await;
        commit(&a, dir.path(), "a2", None, "os/next", FIXED_TS, next_bound).await;
        summarize(&a).await;
        let b = create(dir.path(), "b", Some(OTHER)).await;
        commit(&b, dir.path(), "b1", Some(ID), REF, FIXED_TS, BOUND).await;
        let b_next = commit(
            &b,
            dir.path(),
            "b2",
            Some(ID),
            "os/next",
            FIXED_TS + 10,
            next_bound,
        )
        .await;
        let server_a = RepoServer::start(&dir.path().join("a"), false).await;
        let dest = dest(
            dir.path(),
            None,
            &[
                ("a", &server_a.url(), ""),
                ("b", &file_url(dir.path(), "b"), ""),
            ],
        )
        .await;

        let (opts, events) = options(&[REF, "os/next"]);
        let pulled = dest.pull_collection(ID, &["a", "b"], opts).await.unwrap();
        assert!(events.lock().unwrap().is_empty());
        let got: Vec<(&str, &str)> = pulled
            .refs
            .iter()
            .map(|r| (r.name.as_str(), r.remote.as_str()))
            .collect();
        assert_eq!(got, [(REF, "a"), ("os/next", "b")]);
        assert_eq!(mirror(&dest, REF).await, Some(a_stable));
        assert_eq!(mirror(&dest, "os/next").await, Some(b_next));
        assert!(objects_requested(&server_a));
        assert!(pulled.stats.content_fetched > 0, "{:?}", pulled.stats);
        assert!(pulled.local.metadata_imported > 0, "{:?}", pulled.local);
        assert!(pulled.local.content_imported > 0, "{:?}", pulled.local);
        assert_eq!(pulled.local.metadata_fetched, 0);
        assert_eq!(pulled.local.content_fetched, 0);
        assert_eq!(pulled.local.bytes_transferred, 0);
        assert!(
            pulled.stats.metadata_imported > pulled.local.metadata_imported,
            "{:?} {:?}",
            pulled.stats,
            pulled.local
        );
        assert!(dest.fsck(&FsckOptions::default()).await.unwrap().is_ok());
    });
}

/// The pull lists the refs that it changed, in the order of the remotes
/// that it pulled from: the ref from an HTTP remote, then the ref from a
/// `file://` remote. A second pull at the same commits lists nothing. After
/// each remote moves its ref, a third pull lists each ref with its old
/// commit. Into a repository whose own collection id is the pulled id, the
/// entry is a local ref.
#[test]
fn a_collection_pull_lists_the_refs_that_it_changed() {
    block_on(async {
        let dir = TmpDir::new("pull-collection-changed");
        let next_bound = Bind {
            collection: Some(ID),
            refs: Some(&["os/next"]),
        };
        let a = create(dir.path(), "a", Some(ID)).await;
        let a_stable = commit(&a, dir.path(), "a1", None, REF, FIXED_TS + 10, BOUND).await;
        summarize(&a).await;
        let b = create(dir.path(), "b", Some(OTHER)).await;
        let b_next = commit(
            &b,
            dir.path(),
            "b2",
            Some(ID),
            "os/next",
            FIXED_TS + 10,
            next_bound,
        )
        .await;
        let server_a = RepoServer::start(&dir.path().join("a"), false).await;
        let remotes = [("a", server_a.url()), ("b", file_url(dir.path(), "b"))];
        let remotes: Vec<(&str, &str, &str)> = remotes
            .iter()
            .map(|(name, url)| (*name, url.as_str(), ""))
            .collect();
        let dest = dest(dir.path(), None, &remotes).await;

        let (opts, _) = options(&["os/next", REF]);
        let pulled = dest.pull_collection(ID, &["a", "b"], opts).await.unwrap();
        let got: Vec<(Ref, Option<Checksum>, Checksum)> = pulled
            .changed_refs
            .iter()
            .map(|c| (c.name.clone(), c.old, c.new))
            .collect();
        assert_eq!(
            got,
            [
                (Ref::collection(ID, REF), None, a_stable),
                (Ref::collection(ID, "os/next"), None, b_next),
            ]
        );

        let (opts, _) = options(&["os/next", REF]);
        let pulled = dest.pull_collection(ID, &["a", "b"], opts).await.unwrap();
        assert!(pulled.changed_refs.is_empty(), "{pulled:?}");

        let a_moved = commit(&a, dir.path(), "a3", None, REF, FIXED_TS + 20, BOUND).await;
        summarize(&a).await;
        let b_moved = commit(
            &b,
            dir.path(),
            "b3",
            Some(ID),
            "os/next",
            FIXED_TS + 20,
            next_bound,
        )
        .await;
        let (opts, _) = options(&["os/next", REF]);
        let pulled = dest.pull_collection(ID, &["a", "b"], opts).await.unwrap();
        let got: Vec<(Ref, Option<Checksum>, Checksum)> = pulled
            .changed_refs
            .iter()
            .map(|c| (c.name.clone(), c.old, c.new))
            .collect();
        assert_eq!(
            got,
            [
                (Ref::collection(ID, REF), Some(a_stable), a_moved),
                (Ref::collection(ID, "os/next"), Some(b_next), b_moved),
            ]
        );

        let own = Repo::create(
            &dir.path().join("own"),
            CreateOptions::new(RepoMode::Archive).collection_id(ID),
        )
        .await
        .unwrap();
        drop(own);
        let config = dir.path().join("own/config");
        let mut text = std::fs::read_to_string(&config).unwrap();
        text.push_str(&format!(
            "\n[remote \"a\"]\nurl={}\ngpg-verify=false\ncollection-id={ID}\n",
            server_a.url()
        ));
        std::fs::write(&config, text).unwrap();
        let own = Repo::open(&dir.path().join("own")).await.unwrap();
        let (opts, _) = options(&[REF]);
        let pulled = own.pull_collection(ID, &["a"], opts).await.unwrap();
        let got: Vec<(Ref, Option<Checksum>, Checksum)> = pulled
            .changed_refs
            .iter()
            .map(|c| (c.name.clone(), c.old, c.new))
            .collect();
        assert_eq!(got, [(Ref::local(REF), None, a_moved)]);
    });
}

/// A pull whose second remote fails after the pull from the first remote
/// wrote its ref returns the error and no list. The tip of the `file://`
/// remote has no collection binding, so its pull fails.
#[test]
fn a_collection_pull_that_fails_after_a_ref_write_returns_the_error() {
    block_on(async {
        let dir = TmpDir::new("pull-collection-changed-fails");
        let a = create(dir.path(), "a", Some(ID)).await;
        let a_stable = commit(&a, dir.path(), "a1", None, REF, FIXED_TS, BOUND).await;
        summarize(&a).await;
        let b = create(dir.path(), "b", Some(OTHER)).await;
        let unbound = Bind {
            collection: None,
            refs: None,
        };
        commit(&b, dir.path(), "b1", Some(ID), "os/next", FIXED_TS, unbound).await;
        let server_a = RepoServer::start(&dir.path().join("a"), false).await;
        let dest = dest(
            dir.path(),
            None,
            &[
                ("a", &server_a.url(), ""),
                ("b", &file_url(dir.path(), "b"), ""),
            ],
        )
        .await;

        let (opts, _) = options(&[REF, "os/next"]);
        let err = dest
            .pull_collection(ID, &["a", "b"], opts)
            .await
            .unwrap_err();
        assert!(
            matches!(&err, Error::Pull(m) if m.contains("no collection binding")),
            "{err:?}"
        );
        assert_eq!(mirror(&dest, REF).await, Some(a_stable));
        assert_eq!(mirror(&dest, "os/next").await, None);
    });
}

/// A `file://` address with a host part, `localhost` included, with no
/// path, or with `%`, `?`, or `#` stops the pull before the request to the
/// first remote. The pull writes nothing.
#[test]
fn a_malformed_file_address_stops_the_pull_before_the_first_request() {
    block_on(async {
        for (tag, reason) in [
            ("localhost", "names a host"),
            ("host", "names a host"),
            ("empty", "has no path"),
            ("percent", "holds '%'"),
            ("query", "holds '%'"),
            ("fragment", "holds '%'"),
        ] {
            let dir = TmpDir::new("pull-collection-file-address");
            let a = create(dir.path(), "a", Some(ID)).await;
            commit(&a, dir.path(), "a", None, REF, FIXED_TS, BOUND).await;
            summarize(&a).await;
            let path = dir.path().join("a").display().to_string();
            let address = match tag {
                "localhost" => format!("file://localhost{path}"),
                "host" => format!("file://host{path}"),
                "empty" => "file://".to_owned(),
                "percent" => format!("file://{path}%41"),
                "query" => format!("file://{path}?x"),
                _ => format!("file://{path}#x"),
            };
            let server_a = RepoServer::start(&dir.path().join("a"), false).await;
            let dest = dest(
                dir.path(),
                None,
                &[("a", &server_a.url(), ""), ("b", &address, "")],
            )
            .await;

            let (opts, events) = options(&[REF]);
            let err = dest
                .pull_collection(ID, &["a", "b"], opts)
                .await
                .unwrap_err();
            assert!(
                matches!(&err, Error::Pull(m)
                    if m.starts_with("remote 'b': the file address") && m.contains(reason)),
                "{tag}: {err:?}"
            );
            assert!(events.lock().unwrap().is_empty(), "{tag}");
            assert!(server_a.seen().is_empty(), "{tag}: {:?}", server_a.seen());
            assert_nothing_written(&dest).await;
        }
    });
}

/// A `file://` path with no repository, absent or an empty directory, skips
/// the remote. The message holds the path. The pull takes the ref from the
/// next remote.
#[test]
fn a_file_path_with_no_repository_skips_the_remote() {
    block_on(async {
        let dir = TmpDir::new("pull-collection-file-none");
        let a = create(dir.path(), "a", Some(ID)).await;
        let tip = commit(&a, dir.path(), "a", None, REF, FIXED_TS, BOUND).await;
        std::fs::create_dir(dir.path().join("empty")).unwrap();
        let dest = dest(
            dir.path(),
            None,
            &[
                ("missing", &file_url(dir.path(), "missing"), ""),
                ("empty", &file_url(dir.path(), "empty"), ""),
                ("a", &file_url(dir.path(), "a"), ""),
            ],
        )
        .await;

        let (opts, events) = options(&[REF]);
        let pulled = dest
            .pull_collection(ID, &["missing", "empty", "a"], opts)
            .await
            .unwrap();
        assert_eq!(skipped(dir.path(), &events), ["missing", "empty"]);
        assert_eq!(pulled.refs[0].remote, "a");
        assert_eq!(mirror(&dest, REF).await, Some(tip));
    });
}

/// The probe of a local candidate reads no remotes directory of the source.
/// A malformed `.conf` file in the remotes directory that the config of the
/// source names fails nothing, and the pull takes the ref from the source.
#[test]
fn a_file_remote_reads_no_remotes_directory_of_the_source() {
    block_on(async {
        let dir = TmpDir::new("pull-collection-file-remotes-dir");
        let a = create(dir.path(), "a", Some(ID)).await;
        let tip = commit(&a, dir.path(), "a", None, REF, FIXED_TS, BOUND).await;
        name_malformed_remotes_dir(dir.path(), "a");
        let err = Repo::open(&dir.path().join("a")).await.unwrap_err();
        assert!(
            matches!(&err, Error::InvalidFormat(m) if m.contains("x.conf")),
            "{err:?}"
        );
        let dest = dest(dir.path(), None, &[("a", &file_url(dir.path(), "a"), "")]).await;

        let (opts, events) = options(&[REF]);
        let pulled = dest.pull_collection(ID, &["a"], opts).await.unwrap();
        assert!(events.lock().unwrap().is_empty());
        assert_eq!(pulled.refs[0].remote, "a");
        assert_eq!(mirror(&dest, REF).await, Some(tip));
    });
}

/// The client groups of a local source do not apply: a `file://` pull reads
/// a ref that no group of the source lets a client read.
#[test]
fn the_client_groups_of_a_local_source_do_not_apply() {
    block_on(async {
        let dir = TmpDir::new("pull-collection-file-groups");
        let a = create(dir.path(), "a", Some(OTHER)).await;
        let tip = commit(&a, dir.path(), "a", Some(ID), REF, FIXED_TS, BOUND).await;
        let config = dir.path().join("a/config");
        let mut text = std::fs::read_to_string(&config).unwrap();
        text.push_str(&format!(
            "[ex-ostrya client \"c\"]\nauth=anonymous\nallow=r:pub/**;r:@{ID}:pub/**\n"
        ));
        std::fs::write(&config, text).unwrap();
        // Over HTTP, the groups hide the ref from an anonymous client.
        let source = Repo::open(&dir.path().join("a")).await.unwrap();
        let holds_ref = |bytes: &[u8]| bytes.windows(REF.len()).any(|w| w == REF.as_bytes());
        let refs = RefSelector::parse(["!**"]).unwrap();
        let collections = RefSelector::parse([format!("{ID}/**").as_str()]).unwrap();
        let hidden = source
            .build_ref_listing(
                &refs,
                Some(&collections),
                &common::repo_access(&source, "anonymous"),
            )
            .await
            .unwrap();
        assert!(!holds_ref(&hidden.bytes));
        assert!(holds_ref(
            &repo_listing(&source, &refs, Some(&collections)).await
        ));
        let dest = dest(dir.path(), None, &[("a", &file_url(dir.path(), "a"), "")]).await;

        let (opts, events) = options(&[REF]);
        let pulled = dest.pull_collection(ID, &["a"], opts).await.unwrap();
        assert!(events.lock().unwrap().is_empty());
        assert_eq!(pulled.refs[0].commit, tip);
        assert_eq!(mirror(&dest, REF).await, Some(tip));
    });
}

/// A directory or a ref file inside the selection that the probe cannot read
/// skips the remote, and the pull takes the ref from the next remote. A
/// directory outside the selection that the probe cannot read fails nothing.
/// The test returns at once for a user that ignores the mode.
#[test]
fn an_unreadable_path_skips_the_remote_only_inside_the_selection() {
    block_on(async {
        let dir = TmpDir::new("pull-collection-file-perm");
        let a = create(dir.path(), "a", Some(OTHER)).await;
        let a_pool = commit(
            &a,
            dir.path(),
            "a1",
            Some(ID),
            "pool/x",
            FIXED_TS + 10,
            COLLECTION_ONLY,
        )
        .await;
        commit(
            &a,
            dir.path(),
            "a2",
            Some(ID),
            "builds/locked/y",
            FIXED_TS,
            COLLECTION_ONLY,
        )
        .await;
        let b = create(dir.path(), "b", Some(OTHER)).await;
        let b_pool = commit(
            &b,
            dir.path(),
            "b1",
            Some(ID),
            "pool/x",
            FIXED_TS,
            COLLECTION_ONLY,
        )
        .await;
        let b_build = commit(
            &b,
            dir.path(),
            "b2",
            Some(ID),
            "builds/locked/y",
            FIXED_TS,
            COLLECTION_ONLY,
        )
        .await;
        let dest = dest(
            dir.path(),
            None,
            &[
                ("a", &file_url(dir.path(), "a"), ""),
                ("b", &file_url(dir.path(), "b"), ""),
            ],
        )
        .await;
        let mirrors = dir.path().join("a/refs/mirrors").join(ID);
        let locked = mirrors.join("builds/locked");
        if !lock(&locked, 0o000, 0o755) {
            return;
        }

        let (opts, events) = options(&["pool/x"]);
        let pulled = dest.pull_collection(ID, &["a", "b"], opts).await;
        let (opts, all_events) = options(&[]);
        let all = dest.pull_collection(ID, &["a", "b"], opts).await;
        unlock(&locked, 0o755);

        let pulled = pulled.unwrap();
        assert!(events.lock().unwrap().is_empty());
        assert_eq!(pulled.refs[0].remote, "a");
        assert_eq!(pulled.refs[0].commit, a_pool);
        let all = all.unwrap();
        assert_eq!(skipped(dir.path(), &all_events), ["a"]);
        let got: Vec<(&str, &str, Checksum)> = all
            .refs
            .iter()
            .map(|r| (r.name.as_str(), r.remote.as_str(), r.commit))
            .collect();
        assert_eq!(
            got,
            [("builds/locked/y", "b", b_build), ("pool/x", "b", b_pool)]
        );

        let file = mirrors.join("pool/x");
        if !lock(&file, 0o000, 0o644) {
            return;
        }
        let (opts, events) = options(&["pool/x"]);
        let pulled = dest.pull_collection(ID, &["a", "b"], opts).await;
        unlock(&file, 0o644);
        let pulled = pulled.unwrap();
        assert_eq!(skipped(dir.path(), &events), ["a"]);
        assert_eq!(pulled.refs[0].remote, "b");
    });
}

/// A source whose collection id is `ID` holds the refs of the collection
/// under `refs/heads`. The pull reads them there, with a ref name and with
/// no ref name.
#[test]
fn a_file_remote_of_the_collection_gives_its_local_refs() {
    block_on(async {
        let dir = TmpDir::new("pull-collection-file-own");
        let a = create(dir.path(), "a", Some(ID)).await;
        let tip = commit(&a, dir.path(), "a", None, REF, FIXED_TS, BOUND).await;
        let dest = dest(dir.path(), None, &[("a", &file_url(dir.path(), "a"), "")]).await;
        for names in [&[REF][..], &[][..]] {
            let (opts, events) = options(names);
            let pulled = dest.pull_collection(ID, &["a"], opts).await.unwrap();
            assert!(events.lock().unwrap().is_empty());
            assert_eq!(pulled.refs.len(), 1);
            assert_eq!(pulled.refs[0].name, REF);
            assert_eq!(pulled.refs[0].commit, tip);
            assert_eq!(mirror(&dest, REF).await, Some(tip));
        }
    });
}

/// Returns the remote and the ref of each ref skip event of `events`, and
/// fails on each other event.
fn skipped_refs(events: &Mutex<Vec<CollectionPullEvent>>) -> Vec<(String, String)> {
    events
        .lock()
        .unwrap()
        .iter()
        .map(|event| match event {
            CollectionPullEvent::RefSkipped { remote, name, .. } => (remote.clone(), name.clone()),
            other => panic!("{other:?}"),
        })
        .collect()
}

/// Returns the remote and the ref of each ref skip event of a query of each
/// ref of `ID` on the remote `remote` of `repo`, and the result of the query.
async fn query_skipped(
    repo: &Repo,
    remote: &str,
) -> (Vec<(String, Checksum)>, Vec<(String, String)>) {
    let events = Arc::new(Mutex::new(Vec::new()));
    let sink = Arc::clone(&events);
    let listed = repo
        .remote_list_collection_refs_with(
            remote,
            ID,
            &[],
            EndpointOverrides::default(),
            Some(Box::new(move |event| sink.lock().unwrap().push(event))),
        )
        .await
        .unwrap();
    (listed, skipped_refs(&events))
}

/// A listed ref whose name fails the ref-name rule is skipped with an event,
/// and the other refs of the remote stay in the selection. The skipped ref
/// file names a commit that the repository does not hold, so the probe reads
/// no commit of a skipped ref. This is true for a repository of the
/// collection, which lists `refs/heads/origin:main`, and for a repository of
/// another collection, which lists `refs/mirrors/ID/origin:main`. A query of
/// the refs skips the same ref, with and without a callback.
#[test]
fn a_file_remote_skips_a_listed_name_that_fails_the_ref_name_rule() {
    block_on(async {
        let dir = TmpDir::new("pull-collection-file-bad-name");
        let a = create(dir.path(), "a", Some(ID)).await;
        let stable = commit(&a, dir.path(), "a", None, REF, FIXED_TS, BOUND).await;
        let b = create(dir.path(), "b", Some(OTHER)).await;
        let next = commit(
            &b,
            dir.path(),
            "b",
            Some(ID),
            "os/next",
            FIXED_TS,
            COLLECTION_ONLY,
        )
        .await;
        let ghost = format!("{}\n", "ab".repeat(32));
        std::fs::write(dir.path().join("a/refs/heads/origin:main"), &ghost).unwrap();
        let mirrors = dir.path().join("b/refs/mirrors").join(ID);
        std::fs::write(mirrors.join("origin:main"), &ghost).unwrap();
        let dest = dest(
            dir.path(),
            None,
            &[
                ("a", &file_url(dir.path(), "a"), ""),
                ("b", &file_url(dir.path(), "b"), ""),
            ],
        )
        .await;

        let (opts, events) = options(&[]);
        let pulled = dest.pull_collection(ID, &["a", "b"], opts).await.unwrap();
        let bad = "origin:main".to_owned();
        assert_eq!(
            skipped_refs(&events),
            [("a".to_owned(), bad.clone()), ("b".to_owned(), bad.clone())]
        );
        let mut got: Vec<(&str, &str, Checksum)> = pulled
            .refs
            .iter()
            .map(|r| (r.name.as_str(), r.remote.as_str(), r.commit))
            .collect();
        got.sort_unstable();
        assert_eq!(got, [("os/next", "b", next), (REF, "a", stable)]);
        assert_eq!(mirror(&dest, REF).await, Some(stable));
        assert_eq!(mirror(&dest, "os/next").await, Some(next));
        assert_eq!(dest.list_mirror_refs().await.unwrap().len(), 2);

        for (remote, name, tip) in [("a", REF, stable), ("b", "os/next", next)] {
            let expected = [(name.to_owned(), tip)];
            let (listed, skipped) = query_skipped(&dest, remote).await;
            assert_eq!(listed, expected, "{remote}");
            assert_eq!(skipped, [(remote.to_owned(), bad.clone())]);
            let listed = dest
                .remote_list_collection_refs(remote, ID, &[])
                .await
                .unwrap();
            assert_eq!(listed, expected, "{remote}");
        }
    });
}

/// A served listing that lists a name that fails the ref-name rule gives the
/// same skip, in a pull and in a query. The server answers each listing
/// request with the local refs of a remote of the collection. So the probe
/// sends the second request, and the event comes from the answer to that
/// request alone.
#[test]
fn an_http_remote_skips_a_listed_name_that_fails_the_ref_name_rule() {
    block_on(async {
        let dir = TmpDir::new("pull-collection-http-bad-name");
        let a = create(dir.path(), "a", Some(ID)).await;
        let stable = commit(&a, dir.path(), "a", None, REF, FIXED_TS, BOUND).await;
        std::fs::write(
            dir.path().join("a/refs/heads/origin:main"),
            format!("{stable}\n"),
        )
        .unwrap();
        let server_a = RepoServer::start(&dir.path().join("a"), false).await;
        let refs = RefSelector::parse(std::iter::empty()).unwrap();
        let listing = repo_listing(&a, &refs, None).await;
        server_a.tamper(LISTING, listing);
        let dest = dest(dir.path(), None, &[("a", &server_a.url(), "")]).await;
        let skip = [("a".to_owned(), "origin:main".to_owned())];

        let (listed, skipped) = query_skipped(&dest, "a").await;
        assert_eq!(listed, [(REF.to_owned(), stable)]);
        assert_eq!(skipped, skip);
        assert_eq!(server_a.queries_for(LISTING).len(), 2);

        let (opts, events) = options(&[]);
        let pulled = dest.pull_collection(ID, &["a"], opts).await.unwrap();
        assert_eq!(skipped_refs(&events), skip);
        assert_eq!(pulled.refs.len(), 1);
        assert_eq!(pulled.refs[0].name, REF);
        assert_eq!(mirror(&dest, REF).await, Some(stable));
        assert_eq!(dest.list_mirror_refs().await.unwrap().len(), 1);
    });
}

/// The timestamp check applies to a pull from a `file://` remote.
#[test]
fn the_timestamp_check_applies_to_a_file_remote() {
    block_on(async {
        let dir = TmpDir::new("pull-collection-file-timestamp");
        let a = create(dir.path(), "a", Some(ID)).await;
        let tip = commit(&a, dir.path(), "a", None, REF, FIXED_TS, BOUND).await;
        let older = create(dir.path(), "older", Some(ID)).await;
        commit(&older, dir.path(), "older", None, REF, FIXED_TS - 10, BOUND).await;
        let dest = dest(
            dir.path(),
            None,
            &[
                ("a", &file_url(dir.path(), "a"), ""),
                ("older", &file_url(dir.path(), "older"), ""),
            ],
        )
        .await;

        let (mut opts, _) = options(&[REF]);
        opts.pull.timestamp_check = TimestampCheck::CurrentRef;
        dest.pull_collection(ID, &["a"], opts).await.unwrap();
        assert_eq!(mirror(&dest, REF).await, Some(tip));

        let (mut opts, _) = options(&[REF]);
        opts.pull.timestamp_check = TimestampCheck::CurrentRef;
        let err = dest
            .pull_collection(ID, &["older"], opts)
            .await
            .unwrap_err();
        assert!(
            matches!(&err, Error::Pull(m) if m.contains("chronologically older")),
            "{err:?}"
        );
        assert_eq!(mirror(&dest, REF).await, Some(tip));
    });
}

/// From a `file://` remote into a repository whose own collection id is the
/// pulled id, and that holds `refs/mirrors/ID/REF`, the timestamp check reads
/// the local ref, and the pull writes it. The local ref is older than the
/// tip, and the mirror ref is newer.
#[test]
fn a_file_remote_into_the_own_collection_writes_the_local_ref() {
    block_on(async {
        let dir = TmpDir::new("pull-collection-file-own-mirror");
        let a = create(dir.path(), "a", Some(ID)).await;
        let tip = commit(&a, dir.path(), "a", None, REF, FIXED_TS, BOUND).await;
        let (dest, held, _) = dest_with_own_mirror(
            dir.path(),
            &file_url(dir.path(), "a"),
            FIXED_TS + 10,
            FIXED_TS - 10,
        )
        .await;

        let (mut opts, events) = options(&[REF]);
        opts.pull.timestamp_check = TimestampCheck::CurrentRef;
        dest.pull_collection(ID, &["a"], opts).await.unwrap();

        assert!(events.lock().unwrap().is_empty());
        assert_own_refs(dir.path(), &dest, held, tip).await;
    });
}

/// With a `file://` remote, the pull refuses a field of another transport
/// with `InvalidInput` that names it, before the request to the first
/// remote. The pull writes nothing.
#[test]
fn a_file_remote_refuses_the_fields_of_other_transports() {
    block_on(async {
        let dir = TmpDir::new("pull-collection-file-refusals");
        let a = create(dir.path(), "a", Some(ID)).await;
        commit(&a, dir.path(), "a", None, REF, FIXED_TS, BOUND).await;
        summarize(&a).await;
        let server_a = RepoServer::start(&dir.path().join("a"), false).await;
        let dest = dest(
            dir.path(),
            None,
            &[
                ("a", &server_a.url(), ""),
                ("b", &file_url(dir.path(), "a"), ""),
            ],
        )
        .await;

        let (mut opts, _) = options(&[REF]);
        opts.pull.overrides.http_headers = vec![("X-A".to_owned(), "b".to_owned())];
        let err = dest
            .pull_collection(ID, &["a", "b"], opts)
            .await
            .unwrap_err();
        assert!(
            matches!(&err, Error::InvalidInput(m) if m.starts_with("http-header applies to")),
            "{err:?}"
        );
        assert!(server_a.seen().is_empty(), "{:?}", server_a.seen());
        assert_nothing_written(&dest).await;
    });
}

/// A local candidate imports the objects of the subpaths alone: the
/// commit, the root dirtree and dirmeta, and each object under the entry
/// that a subpath names. The pull writes the collection ref and leaves the
/// commit partial with a zero-length marker. A later pull with no subpath
/// completes the commit. When an HTTP remote and a `file://` remote serve
/// the ref, and the `file://` remote lists the newer commit, the pull takes
/// the subpath from the `file://` remote.
#[test]
fn a_local_candidate_takes_subpaths() {
    block_on(async {
        let dir = TmpDir::new("pull-collection-file-subpath");
        let a = create(dir.path(), "a", Some(ID)).await;
        let tip = commit(&a, dir.path(), "a1", None, REF, FIXED_TS, BOUND).await;
        summarize(&a).await;
        let dest = dest(dir.path(), None, &[("a", &file_url(dir.path(), "a"), "")]).await;
        let (mut opts, events) = options(&[REF]);
        opts.pull.subpaths = vec!["/subdir".to_owned()];
        let pulled = dest.pull_collection(ID, &["a"], opts).await.unwrap();
        assert!(events.lock().unwrap().is_empty());
        let mut expected = subpath_base(&a, &tip).await;
        expected.extend(whole_objects(&a, &tip, "/subdir").await);
        assert_eq!(dest.list_objects().await.unwrap(), expected);
        assert_eq!(mirror(&dest, REF).await, Some(tip));
        assert_eq!(
            dest.commit_state(&tip).await.unwrap(),
            ostrya::CommitState::Partial
        );
        let marker = dir
            .path()
            .join("dest/state")
            .join(format!("{}.commitpartial", tip.to_hex()));
        assert_eq!(std::fs::metadata(&marker).unwrap().len(), 0);
        assert_eq!(pulled.local.content_fetched, 0);
        assert_eq!(pulled.local.content_imported, 1, "{:?}", pulled.local);

        let (opts, _) = options(&[REF]);
        dest.pull_collection(ID, &["a"], opts).await.unwrap();
        assert_eq!(
            dest.commit_state(&tip).await.unwrap(),
            ostrya::CommitState::Normal
        );
        assert!(!marker.exists());
        assert!(dest.fsck(&FsckOptions::default()).await.unwrap().is_ok());

        // An HTTP remote with an older commit, and a `file://` remote with
        // the newer one.
        let older = create(dir.path(), "older", Some(ID)).await;
        commit(&older, dir.path(), "o1", None, REF, FIXED_TS - 10, BOUND).await;
        summarize(&older).await;
        let server = RepoServer::start(&dir.path().join("older"), false).await;
        std::fs::remove_dir_all(dir.path().join("dest")).unwrap();
        let dest = self::dest(
            dir.path(),
            None,
            &[
                ("older", &server.url(), ""),
                ("a", &file_url(dir.path(), "a"), ""),
            ],
        )
        .await;
        let (mut opts, _) = options(&[REF]);
        opts.pull.subpaths = vec!["/subdir".to_owned()];
        let pulled = dest
            .pull_collection(ID, &["older", "a"], opts)
            .await
            .unwrap();
        let got: Vec<(&str, &str)> = pulled
            .refs
            .iter()
            .map(|r| (r.name.as_str(), r.remote.as_str()))
            .collect();
        assert_eq!(got, [(REF, "a")]);
        assert!(!objects_requested(&server));
        assert_eq!(dest.list_objects().await.unwrap(), expected);
        assert_eq!(mirror(&dest, REF).await, Some(tip));
        assert_eq!(
            dest.commit_state(&tip).await.unwrap(),
            ostrya::CommitState::Partial
        );
    });
}

/// Under a summary policy, the probe of a `file://` remote reads the refs
/// from the verified summary of the source, and the pull takes the commit
/// that the summary lists, also when the ref file names a newer commit. A
/// summary signed with a key that is not trusted, and a summary with no
/// `summary.sig`, skip the remote.
#[test]
fn a_summary_policy_reads_the_verified_summary_of_a_file_remote() {
    block_on(async {
        for case in ["trusted", "other key", "no signature"] {
            let dir = TmpDir::new("pull-collection-file-summary");
            let a = create(dir.path(), "a", Some(ID)).await;
            let tip = commit(&a, dir.path(), "a1", None, REF, FIXED_TS, BOUND).await;
            summarize(&a).await;
            let secret = match case {
                "trusted" => Some(SECRET_B64),
                "other key" => Some(OTHER_SECRET_B64),
                _ => None,
            };
            if let Some(secret) = secret {
                let signer = Ed25519Signer::from_base64(secret).unwrap();
                a.sign_summary(&signer).await.unwrap();
            }
            commit(&a, dir.path(), "a2", None, REF, FIXED_TS + 10, BOUND).await;
            let b = create(dir.path(), "b", Some(ID)).await;
            let fallback = commit(&b, dir.path(), "b", None, REF, FIXED_TS - 10, BOUND).await;
            let policy =
                format!("sign-verify-summary=ed25519\nverification-ed25519-key={PUBLIC_B64}\n");
            let dest = dest(
                dir.path(),
                None,
                &[
                    ("a", &file_url(dir.path(), "a"), &policy),
                    ("b", &file_url(dir.path(), "b"), ""),
                ],
            )
            .await;

            let (opts, events) = options(&[REF]);
            let pulled = dest.pull_collection(ID, &["a", "b"], opts).await.unwrap();
            if case == "trusted" {
                assert!(events.lock().unwrap().is_empty());
                assert_eq!(pulled.refs[0].remote, "a");
                assert_eq!(pulled.refs[0].commit, tip);
                assert_eq!(mirror(&dest, REF).await, Some(tip));
            } else {
                assert_eq!(skipped(dir.path(), &events), ["a"], "{case}");
                assert_eq!(pulled.refs[0].remote, "b", "{case}");
                assert_eq!(mirror(&dest, REF).await, Some(fallback), "{case}");
            }
        }
    });
}

/// Under a summary policy, a commit of a `file://` remote whose timestamp
/// differs from the timestamp that the verified summary lists fails the
/// pull, as over HTTP. The summary lists one ref, with a timestamp that the
/// commit does not hold, and a trusted key signs that summary.
#[test]
fn a_file_remote_commit_with_another_timestamp_than_listed_fails() {
    block_on(async {
        let dir = TmpDir::new("pull-collection-file-listed-timestamp");
        let a = create(dir.path(), "a", Some(ID)).await;
        commit(&a, dir.path(), "a", None, REF, FIXED_TS + 1, BOUND).await;
        summarize(&a).await;
        // The summary states 99 seconds more than the commit holds.
        let path = dir.path().join("a/summary");
        let mut bytes = std::fs::read(&path).unwrap();
        let real = (FIXED_TS + 1).to_be_bytes();
        let at = bytes
            .windows(8)
            .position(|w| w == real)
            .expect("the summary holds the timestamp");
        bytes[at..at + 8].copy_from_slice(&(FIXED_TS + 100).to_be_bytes());
        std::fs::write(&path, bytes).unwrap();
        let signer = Ed25519Signer::from_base64(SECRET_B64).unwrap();
        a.sign_summary(&signer).await.unwrap();
        let policy =
            format!("sign-verify-summary=ed25519\nverification-ed25519-key={PUBLIC_B64}\n");
        let dest = dest(
            dir.path(),
            None,
            &[("a", &file_url(dir.path(), "a"), &policy)],
        )
        .await;

        let (opts, events) = options(&[REF]);
        let err = dest.pull_collection(ID, &["a"], opts).await.unwrap_err();
        assert!(events.lock().unwrap().is_empty());
        assert!(
            matches!(&err, Error::Pull(m) if m.contains("timestamp")),
            "{err:?}"
        );
        assert_nothing_written(&dest).await;
    });
}

/// The commit keys of a `file://` remote apply to the pull from it. The
/// remote trusts one key. A commit signed with another key fails the pull,
/// and the pull writes nothing. A commit signed with the trusted key passes.
#[test]
fn the_keys_of_a_file_remote_apply() {
    block_on(async {
        for secret in [OTHER_SECRET_B64, SECRET_B64] {
            let dir = TmpDir::new("pull-collection-file-keys");
            let a = create(dir.path(), "a", Some(ID)).await;
            let tip = commit(&a, dir.path(), "a", None, REF, FIXED_TS, BOUND).await;
            let signer = Ed25519Signer::from_base64(secret).unwrap();
            a.sign_commit(&tip, &signer).await.unwrap();
            let policy = format!("sign-verify=true\nverification-ed25519-key={PUBLIC_B64}\n");
            let dest = dest(
                dir.path(),
                None,
                &[("a", &file_url(dir.path(), "a"), &policy)],
            )
            .await;

            let (opts, events) = options(&[REF]);
            let pulled = dest.pull_collection(ID, &["a"], opts).await;
            assert!(events.lock().unwrap().is_empty());
            if secret == SECRET_B64 {
                assert_eq!(pulled.unwrap().refs[0].remote, "a");
                assert_eq!(mirror(&dest, REF).await, Some(tip));
            } else {
                let err = pulled.unwrap_err();
                assert!(matches!(err, Error::Signature(_)), "{err:?}");
                assert_nothing_written(&dest).await;
            }
        }
    });
}

/// With `require_static_deltas`, the pull from a `file://` remote applies
/// the static delta that the summary of the source advertises. Under a
/// summary policy, the probe reads the refs from the verified summary, and
/// the pull takes the commit that the summary lists, also when the ref file
/// names a newer commit. Without the policy, the probe reads the ref file,
/// and the pull reads the summary for the delta.
#[test]
fn a_file_remote_with_require_static_deltas_applies_the_delta() {
    block_on(async {
        for case in ["summary policy", "ref files"] {
            let dir = TmpDir::new("pull-collection-file-delta");
            let a = create(dir.path(), "a", Some(ID)).await;
            let tip = commit(&a, dir.path(), "a1", None, REF, FIXED_TS, BOUND).await;
            a.generate_static_delta(None, &tip, &DeltaOptions::default())
                .await
                .unwrap();
            summarize(&a).await;
            let policy = if case == "summary policy" {
                let signer = Ed25519Signer::from_base64(SECRET_B64).unwrap();
                a.sign_summary(&signer).await.unwrap();
                commit(&a, dir.path(), "a2", None, REF, FIXED_TS + 10, BOUND).await;
                format!("sign-verify-summary=ed25519\nverification-ed25519-key={PUBLIC_B64}\n")
            } else {
                String::new()
            };
            let dest = dest(
                dir.path(),
                None,
                &[("a", &file_url(dir.path(), "a"), &policy)],
            )
            .await;

            let (mut opts, events) = options(&[REF]);
            opts.pull.require_static_deltas = true;
            let pulled = dest.pull_collection(ID, &["a"], opts).await.unwrap();

            assert!(events.lock().unwrap().is_empty(), "{case}");
            assert_eq!(pulled.refs[0].commit, tip, "{case}");
            assert!(pulled.stats.delta_parts > 0, "{case}: {:?}", pulled.stats);
            assert_eq!(mirror(&dest, REF).await, Some(tip), "{case}");
            assert!(
                dest.has_object(ObjectType::Commit, &tip).await.unwrap(),
                "{case}"
            );
            assert!(
                dest.fsck(&FsckOptions::default()).await.unwrap().is_ok(),
                "{case}"
            );
        }
    });
}

/// Writes the bytes of the second regular content object of `commit` in
/// `repo` at `dir/a` under the name of the first, in the order of the
/// checksums. Returns the checksum of the first.
async fn swap_content(dir: &Path, repo: &Repo, commit: &Checksum) -> Checksum {
    let mut names: Vec<Checksum> = repo
        .traverse_commit(commit, 0)
        .await
        .unwrap()
        .into_iter()
        .filter(|name| name.ty == ObjectType::File)
        .map(|name| name.checksum)
        .collect();
    names.sort_by_key(Checksum::to_hex);
    let mut regular = Vec::new();
    for checksum in names {
        let file = repo.load_file(&checksum).await.unwrap();
        if matches!(file.kind, FileKind::Regular { .. }) {
            regular.push(checksum);
        }
    }
    let path = |checksum: Checksum| {
        dir.join("a/objects")
            .join(ObjectName::new(checksum, ObjectType::File).loose_path(RepoMode::Archive))
    };
    std::fs::remove_file(path(regular[0])).unwrap();
    std::fs::copy(path(regular[1]), path(regular[0])).unwrap();
    regular[0]
}

/// Writes the bytes of the dirtree of the one subdirectory of the root of
/// `commit` in `repo` at `dir/a` under the name of the root dirtree. Returns
/// the checksum of the root dirtree.
///
/// The bytes parse as a dirtree, and each object that they name is an object
/// of the commit. So the walk of the pull reads them, and each content object
/// that the pull imports hashes to its name.
async fn swap_dirtree(dir: &Path, repo: &Repo, commit: &Checksum) -> Checksum {
    let (commit, _) = repo.load_commit(commit).await.unwrap();
    let root = commit.root_dirtree;
    let dirs = repo.load_dirtree(&root).await.unwrap().dirs;
    assert_eq!(dirs.len(), 1);
    let path = |checksum: Checksum| {
        dir.join("a/objects")
            .join(ObjectName::new(checksum, ObjectType::DirTree).loose_path(RepoMode::Archive))
    };
    std::fs::remove_file(path(root)).unwrap();
    std::fs::copy(path(dirs[0].1), path(root)).unwrap();
    root
}

/// A signature covers the commit, or the summary its checksum, and not the
/// objects of the tree. So the pull from a `file://` remote whose keys check
/// the signatures of the commits or of the summary hashes each object that
/// it imports. The source holds a signed commit and a signed summary, and
/// the bytes of one content object under the name of another. With commit
/// keys, with the commit keys of a trust group, and with summary keys alone,
/// the pull fails and writes nothing. With no keys, the pull does not read
/// the objects, and the bad object goes to the destination. `UNTRUSTED` from
/// the caller makes that pull fail. A dirtree under the name of another
/// dirtree fails the pull with commit keys in the same way.
#[test]
fn a_file_remote_with_signature_keys_hashes_each_imported_object() {
    block_on(async {
        let keys = format!("verification-ed25519-key={PUBLIC_B64}\n");
        for case in [
            "commit keys",
            "trust group",
            "summary keys",
            "no keys",
            "untrusted",
            "dirtree",
        ] {
            let dir = TmpDir::new("pull-collection-file-hash");
            let a = create(dir.path(), "a", Some(ID)).await;
            let tip = commit(&a, dir.path(), "a", None, REF, FIXED_TS, BOUND).await;
            let signer = Ed25519Signer::from_base64(SECRET_B64).unwrap();
            a.sign_commit(&tip, &signer).await.unwrap();
            summarize(&a).await;
            a.sign_summary(&signer).await.unwrap();
            let target = if case == "dirtree" {
                swap_dirtree(dir.path(), &a, &tip).await
            } else {
                swap_content(dir.path(), &a, &tip).await
            };
            let extra = match case {
                "commit keys" | "dirtree" => format!("sign-verify=true\n{keys}"),
                "trust group" => format!("[ex-ostrya trust \"t\"]\nsign-verify=ed25519\n{keys}"),
                "summary keys" => format!("sign-verify-summary=ed25519\n{keys}"),
                _ => String::new(),
            };
            let dest = dest(
                dir.path(),
                None,
                &[("a", &file_url(dir.path(), "a"), &extra)],
            )
            .await;

            let (mut opts, events) = options(&[REF]);
            if case == "trust group" {
                opts.pull.trust_group = Some("t".to_owned());
            }
            if case == "untrusted" {
                opts.pull.flags = PullFlags::UNTRUSTED;
            }
            let pulled = dest.pull_collection(ID, &["a"], opts).await;
            assert!(events.lock().unwrap().is_empty(), "{case}");
            if case == "no keys" {
                assert_eq!(pulled.unwrap().refs[0].commit, tip);
                assert_eq!(mirror(&dest, REF).await, Some(tip));
                let report = dest.fsck(&FsckOptions::default()).await.unwrap();
                let bad: Vec<Checksum> = report.errors.iter().map(|e| e.object.checksum).collect();
                assert_eq!(bad, [target]);
            } else {
                let err = pulled.unwrap_err();
                assert!(
                    matches!(err, Error::ChecksumMismatch { expected, .. } if expected == target),
                    "{case}: {err:?}"
                );
                assert_nothing_written(&dest).await;
            }
        }
    });
}

/// A pull of one remote reads a `file://` address as a local repository,
/// and writes the remote ref `REMOTE:REF`, as a pull over HTTP does.
#[test]
fn a_pull_from_one_remote_reads_a_file_address() {
    block_on(async {
        let dir = TmpDir::new("pull-collection-file-plain");
        let a = create(dir.path(), "a", Some(ID)).await;
        let tip = commit(&a, dir.path(), "a", None, REF, FIXED_TS, BOUND).await;
        summarize(&a).await;
        let dest = dest(dir.path(), None, &[("a", &file_url(dir.path(), "a"), "")]).await;

        let opts = PullOptions {
            refs: vec![REF.to_owned()],
            ..PullOptions::default()
        };
        let stats = dest.pull("a", opts).await.unwrap();
        assert!(stats.metadata_imported > 0 && stats.content_imported > 0);
        assert_eq!(stats.metadata_fetched + stats.content_fetched, 0);
        assert_eq!(
            dest.resolve_rev(&format!("a:{REF}"), false).await.unwrap(),
            Some(tip)
        );
        assert_eq!(dest.resolve_rev(REF, true).await.unwrap(), None);
    });
}

/// The fetch of the summary of a `file://` remote reads `summary` and
/// `summary.sig` of the local repository through the file system. An absent
/// file is `None`. A path with no repository gives the error of the open.
#[test]
fn remote_fetch_summary_reads_a_file_remote() {
    block_on(async {
        let dir = TmpDir::new("pull-collection-file-summary-fetch");
        let a = create(dir.path(), "a", Some(ID)).await;
        commit(&a, dir.path(), "a", None, REF, FIXED_TS, BOUND).await;
        summarize(&a).await;
        create(dir.path(), "b", Some(ID)).await;
        let dest = dest(
            dir.path(),
            None,
            &[
                ("a", &file_url(dir.path(), "a"), ""),
                ("b", &file_url(dir.path(), "b"), ""),
                ("none", &file_url(dir.path(), "none"), ""),
            ],
        )
        .await;

        let summary = std::fs::read(dir.path().join("a/summary")).unwrap();
        assert_eq!(
            dest.remote_fetch_summary("a").await.unwrap(),
            (Some(summary.clone()), None)
        );
        let signer = Ed25519Signer::from_base64(SECRET_B64).unwrap();
        a.sign_summary(&signer).await.unwrap();
        let signature = std::fs::read(dir.path().join("a/summary.sig")).unwrap();
        assert_eq!(
            dest.remote_fetch_summary("a").await.unwrap(),
            (Some(summary), Some(signature))
        );
        assert_eq!(dest.remote_fetch_summary("b").await.unwrap(), (None, None));
        let err = dest.remote_fetch_summary("none").await.unwrap_err();
        let open = Repo::open(&dir.path().join("none")).await.unwrap_err();
        assert_eq!(err.to_string(), open.to_string());
        assert_nothing_written(&dest).await;
    });
}

/// Makes the config of the repository at `dir/name` name the remotes
/// directory `dir/name-remotes`, which holds a malformed `.conf` file. An
/// open that reads the remotes directory then fails.
fn name_malformed_remotes_dir(dir: &Path, name: &str) {
    let remotes = dir.join(format!("{name}-remotes"));
    std::fs::create_dir(&remotes).unwrap();
    std::fs::write(remotes.join("x.conf"), "[remote \"x\"\n").unwrap();
    let config = dir.join(name).join("config");
    let mut text = std::fs::read_to_string(&config).unwrap();
    text.push_str(&format!(
        "\n[ex-ostrya]\nremotes-config-dir={}\n",
        remotes.display()
    ));
    std::fs::write(&config, text).unwrap();
}

/// The fetch of the summary of a `file://` remote reads no remotes
/// directory of the source. A malformed `.conf` file in the remotes
/// directory that the config of the source names fails nothing.
#[test]
fn remote_fetch_summary_reads_no_remotes_directory_of_the_source() {
    block_on(async {
        let dir = TmpDir::new("pull-collection-file-summary-remotes-dir");
        let a = create(dir.path(), "a", Some(ID)).await;
        commit(&a, dir.path(), "a", None, REF, FIXED_TS, BOUND).await;
        summarize(&a).await;
        name_malformed_remotes_dir(dir.path(), "a");
        let err = Repo::open(&dir.path().join("a")).await.unwrap_err();
        assert!(
            matches!(&err, Error::InvalidFormat(m) if m.contains("x.conf")),
            "{err:?}"
        );
        let dest = dest(dir.path(), None, &[("a", &file_url(dir.path(), "a"), "")]).await;

        let summary = std::fs::read(dir.path().join("a/summary")).unwrap();
        assert_eq!(
            dest.remote_fetch_summary("a").await.unwrap(),
            (Some(summary), None)
        );
    });
}

/// The fetch of the summary of a `file://` remote refuses a `summary` or a
/// `summary.sig` that is a symlink, a FIFO, a directory, or a file larger
/// than 64 MiB. The read of a FIFO does not block.
#[test]
fn remote_fetch_summary_of_a_file_remote_refuses_a_file_that_is_not_a_summary() {
    block_on(async {
        let dir = TmpDir::new("pull-collection-file-summary-refused");
        let a = create(dir.path(), "a", Some(ID)).await;
        commit(&a, dir.path(), "a", None, REF, FIXED_TS, BOUND).await;
        summarize(&a).await;
        let target = dir.path().join("summary-copy");
        std::fs::copy(dir.path().join("a/summary"), &target).unwrap();
        let dest = dest(dir.path(), None, &[("a", &file_url(dir.path(), "a"), "")]).await;
        let cap = 64 * 1024 * 1024;

        for name in ["summary", "summary.sig"] {
            let path = dir.path().join("a").join(name);
            for kind in ["symlink", "fifo", "directory", "large"] {
                let _ = std::fs::remove_file(&path);
                let reason = match kind {
                    "symlink" => {
                        std::os::unix::fs::symlink(&target, &path).unwrap();
                        "passes through a symlink; ostrya refuses a symlink in the repository"
                            .to_owned()
                    }
                    "fifo" => {
                        rustix::fs::mknodat(
                            rustix::fs::CWD,
                            &path,
                            rustix::fs::FileType::Fifo,
                            rustix::fs::Mode::from_raw_mode(0o644),
                            0,
                        )
                        .unwrap();
                        "is not a regular file".to_owned()
                    }
                    "directory" => {
                        std::fs::create_dir(&path).unwrap();
                        "is not a regular file".to_owned()
                    }
                    _ => {
                        let file = std::fs::File::create(&path).unwrap();
                        file.set_len(cap + 1).unwrap();
                        format!("is larger than its cap of {cap} bytes")
                    }
                };
                let err = dest.remote_fetch_summary("a").await.unwrap_err();
                assert!(
                    matches!(&err, Error::InvalidFormat(m) if *m == format!("{name} {reason}")),
                    "{name} {kind}: {err:?}"
                );
                if kind == "directory" {
                    std::fs::remove_dir(&path).unwrap();
                }
            }
            std::fs::remove_file(&path).unwrap();
            if name == "summary" {
                std::fs::copy(&target, &path).unwrap();
            }
        }
        assert_nothing_written(&dest).await;
    });
}

/// The fetch of the summary of a `file://` remote refuses each field of the
/// caller that applies to another transport or to a push, before it opens
/// the path.
#[test]
fn remote_fetch_summary_of_a_file_remote_refuses_the_fields_of_another_transport() {
    block_on(async {
        let dir = TmpDir::new("pull-collection-file-summary-fields");
        let dest = dest(dir.path(), None, &[("a", &file_url(dir.path(), "a"), "")]).await;
        let d = EndpointOverrides::default;
        for (name, o) in [
            (
                "push-token-file",
                EndpointOverrides {
                    push_token_file: Some("/nowhere/token".into()),
                    ..d()
                },
            ),
            (
                "http-header",
                EndpointOverrides {
                    http_headers: vec![("X-A".to_owned(), "b".to_owned())],
                    ..d()
                },
            ),
            (
                "tls-ca-path",
                EndpointOverrides {
                    tls_ca_path: Some("/nowhere/ca.pem".into()),
                    ..d()
                },
            ),
            (
                "s3-region",
                EndpointOverrides {
                    s3_region: Some("eu-west-1".to_owned()),
                    ..d()
                },
            ),
            (
                "ssh-command",
                EndpointOverrides {
                    ssh_command: Some(vec!["ssh".to_owned()]),
                    ..d()
                },
            ),
        ] {
            let err = dest.remote_fetch_summary_with("a", o).await.unwrap_err();
            assert!(
                matches!(&err, Error::InvalidInput(m) if m.starts_with(&format!("{name} applies to "))),
                "{name}: {err:?}"
            );
        }
    });
}

// --- refusals ----------------------------------------------------------------

/// The pull refuses each option that it cannot carry before its first
/// request, and writes nothing.
#[test]
fn refused_options_send_no_request() {
    block_on(async {
        let dir = TmpDir::new("pull-collection-refusals");
        let a = create(dir.path(), "a", Some(ID)).await;
        commit(&a, dir.path(), "a", None, REF, FIXED_TS, BOUND).await;
        summarize(&a).await;
        let server_a = RepoServer::start(&dir.path().join("a"), false).await;
        let dest = dest(dir.path(), None, &[("a", &server_a.url(), "")]).await;

        let long = "a.b".repeat(100);
        let base = || PullOptions {
            refs: vec![REF.to_owned()],
            ..PullOptions::default()
        };
        let cases: Vec<(&str, &str, Vec<&str>, PullOptions)> = vec![
            ("invalid id", "fresh", vec!["a"], base()),
            ("long id", &long, vec!["a"], base()),
            ("no remote", ID, vec![], base()),
            (
                "remote",
                ID,
                vec!["a"],
                PullOptions {
                    remote: Some("a".to_owned()),
                    ..base()
                },
            ),
            (
                "mirror",
                ID,
                vec!["a"],
                PullOptions {
                    flags: PullFlags::MIRROR,
                    ..base()
                },
            ),
            (
                "static deltas",
                ID,
                vec!["a"],
                PullOptions {
                    static_deltas: Some(Vec::new()),
                    ..base()
                },
            ),
            (
                "url",
                ID,
                vec!["a"],
                PullOptions {
                    overrides: EndpointOverrides {
                        url: Some(server_a.url()),
                        ..EndpointOverrides::default()
                    },
                    ..base()
                },
            ),
            (
                "disable bindings",
                ID,
                vec!["a"],
                PullOptions {
                    flags: PullFlags::DISABLE_VERIFY_BINDINGS,
                    ..base()
                },
            ),
            (
                "ref name",
                ID,
                vec!["a"],
                PullOptions {
                    refs: vec!["a:b".to_owned()],
                    ..base()
                },
            ),
            (
                "long ref name",
                ID,
                vec!["a"],
                PullOptions {
                    refs: vec![REF.to_owned(), "x".repeat(4090)],
                    ..base()
                },
            ),
            ("unknown remote", ID, vec!["a", "nowhere"], base()),
        ];
        for (tag, id, remotes, pull) in cases {
            let mut opts = CollectionPullOptions::default();
            opts.pull = pull;
            let err = dest.pull_collection(id, &remotes, opts).await.unwrap_err();
            let expected = match tag {
                "ref name" => matches!(err, Error::InvalidRefspec(_)),
                "unknown remote" => true,
                _ => matches!(err, Error::InvalidInput(_)),
            };
            assert!(expected, "{tag}: {err:?}");
            assert!(server_a.seen().is_empty(), "{tag}: {:?}", server_a.seen());
            assert_nothing_written(&dest).await;
        }
    });
}

/// A name of the pull is `NAME` or `@ID:NAME` of the pulled collection, and
/// both forms name one ref. The pull writes `refs/mirrors/ID/NAME`, or
/// `refs/heads/NAME` into a repository whose own id is the pulled id.
#[test]
fn a_collection_pull_takes_plain_and_id_operands() {
    block_on(async {
        let dir = TmpDir::new("pull-collection-operands");
        let b = create(dir.path(), "b", Some(OTHER)).await;
        let bind_a = Bind {
            collection: Some(ID),
            refs: Some(&["A"]),
        };
        let bind_b = Bind {
            collection: Some(ID),
            refs: Some(&["B"]),
        };
        let a_tip = commit(&b, dir.path(), "a", Some(ID), "A", FIXED_TS, bind_a).await;
        let b_tip = commit(&b, dir.path(), "b", Some(ID), "B", FIXED_TS, bind_b).await;
        summarize(&b).await;
        let server = RepoServer::start(&dir.path().join("b"), false).await;
        let at_a = format!("@{ID}:A");
        let at_b = format!("@{ID}:B");

        let plain = dest(dir.path(), None, &[("b", &server.url(), "")]).await;
        let (opts, _) = options(&["A", &at_b, &at_a]);
        let pulled = plain.pull_collection(ID, &["b"], opts).await.unwrap();
        let names: Vec<&str> = pulled.refs.iter().map(|r| r.name.as_str()).collect();
        assert_eq!(names, ["A", "B"]);
        assert_eq!(mirror(&plain, "A").await, Some(a_tip));
        assert_eq!(mirror(&plain, "B").await, Some(b_tip));
        assert!(plain.list_refs(None).await.unwrap().is_empty());
        drop(plain);

        std::fs::remove_dir_all(dir.path().join("dest")).unwrap();
        let own = dest(dir.path(), Some(ID), &[("b", &server.url(), "")]).await;
        let (opts, _) = options(&["A", &at_b]);
        own.pull_collection(ID, &["b"], opts).await.unwrap();
        assert_eq!(
            own.list_refs(None).await.unwrap(),
            [("A".to_owned(), a_tip), ("B".to_owned(), b_tip)]
        );
        assert!(own.list_mirror_refs().await.unwrap().is_empty());
    });
}

/// The pull refuses an `@ID:NAME` name of another collection, and a name
/// that starts with `@` and is no `@ID:NAME` ref, before its first request.
#[test]
fn a_collection_pull_refuses_an_operand_of_another_collection() {
    block_on(async {
        let dir = TmpDir::new("pull-collection-other-operand");
        let a = create(dir.path(), "a", Some(ID)).await;
        commit(&a, dir.path(), "a", None, REF, FIXED_TS, BOUND).await;
        summarize(&a).await;
        let server_a = RepoServer::start(&dir.path().join("a"), false).await;
        let dest = dest(dir.path(), None, &[("a", &server_a.url(), "")]).await;

        let other = format!("@{OTHER}:{REF}");
        let (opts, _) = options(&[REF, &other]);
        let err = dest.pull_collection(ID, &["a"], opts).await.unwrap_err();
        assert!(matches!(err, Error::InvalidInput(_)), "{err:?}");
        for name in [format!("@{ID}:{REF}^"), format!("@{ID}"), format!("@{ID}:")] {
            let (opts, _) = options(&[&name]);
            let err = dest.pull_collection(ID, &["a"], opts).await.unwrap_err();
            assert!(
                matches!(&err, Error::InvalidRefspec(got) if *got == name),
                "{name}: {err:?}"
            );
        }
        assert!(server_a.seen().is_empty(), "{:?}", server_a.seen());
        assert_nothing_written(&dest).await;
    });
}

/// An empty ssh command or send command of a later remote fails the pull
/// before the request to the first remote, and the pull starts no ssh
/// client.
#[test]
fn an_empty_ssh_command_fails_before_the_first_request() {
    block_on(async {
        for key in ["ssh-command", "send-command"] {
            let dir = TmpDir::new("pull-collection-empty-ssh");
            let a = create(dir.path(), "a", Some(ID)).await;
            commit(&a, dir.path(), "a", None, REF, FIXED_TS, BOUND).await;
            summarize(&a).await;
            let server_a = RepoServer::start(&dir.path().join("a"), false).await;
            drop(dest(dir.path(), None, &[("a", &server_a.url(), "")]).await);
            let dest = reconfigure(
                dir.path(),
                &format!(
                    "\n[remote \"b\"]\npull-url=ssh://localhost/nowhere\ngpg-verify=false\n\
                     collection-id={ID}\n{key}=\n"
                ),
            )
            .await;

            let (opts, events) = options(&[REF]);
            let err = dest
                .pull_collection(ID, &["a", "b"], opts)
                .await
                .unwrap_err();
            assert!(
                matches!(&err, Error::Remote(_)) && err.to_string().contains("is empty"),
                "{key}: {err:?}"
            );
            assert!(events.lock().unwrap().is_empty());
            assert!(server_a.seen().is_empty(), "{key}: {:?}", server_a.seen());
            assert_nothing_written(&dest).await;
        }
    });
}

// --- commit operands ---------------------------------------------------------

/// Returns the operand `NAME@CHECKSUM` of the ref `name` and `commit`.
fn at(name: &str, commit: &Checksum) -> String {
    commit_operand(&Ref::local(name), commit)
}

/// Copies the repository at `dir/from` to `dir/to`, so both hold the same
/// commits.
fn copy_repo(dir: &Path, from: &str, to: &str) {
    let status = std::process::Command::new("cp")
        .arg("-a")
        .arg(dir.join(from))
        .arg(dir.join(to))
        .status()
        .unwrap();
    assert!(status.success());
}

/// Returns `true` if `server` received a request that reads refs: for the
/// ref listing, the `summary`, or the `summary.sig`.
fn refs_requested(server: &RepoServer) -> bool {
    server
        .seen()
        .iter()
        .any(|path| path == LISTING || path == "summary" || path == "summary.sig")
}

/// Two remotes serve the commit of a `REF@CHECKSUM` operand. The pull takes
/// the commit from the first remote, and asks the second remote for nothing.
/// The entry of the ref in the result holds the timestamp of the commit.
#[test]
fn the_first_remote_that_serves_the_commit_wins() {
    block_on(async {
        let dir = TmpDir::new("pull-collection-commit-first");
        let a = create(dir.path(), "a", Some(ID)).await;
        let tip = commit(&a, dir.path(), "c", None, REF, FIXED_TS, BOUND).await;
        copy_repo(dir.path(), "a", "b");
        let server_a = RepoServer::start(&dir.path().join("a"), false).await;
        let server_b = RepoServer::start(&dir.path().join("b"), false).await;
        let dest = dest(
            dir.path(),
            None,
            &[("a", &server_a.url(), ""), ("b", &server_b.url(), "")],
        )
        .await;

        let (opts, events) = options(&[&at(REF, &tip)]);
        let pulled = dest.pull_collection(ID, &["a", "b"], opts).await.unwrap();
        assert!(events.lock().unwrap().is_empty());
        let got: Vec<(&str, &str, Checksum, u64)> = pulled
            .refs
            .iter()
            .map(|r| (r.name.as_str(), r.remote.as_str(), r.commit, r.timestamp))
            .collect();
        assert_eq!(got, [(REF, "a", tip, FIXED_TS)]);
        assert_eq!(mirror(&dest, REF).await, Some(tip));
        assert!(dest.fsck(&FsckOptions::default()).await.unwrap().is_ok());
        assert!(objects_requested(&server_a));
        assert!(server_b.seen().is_empty(), "{:?}", server_b.seen());
    });
}

/// A remote that does not serve the commit gives way to the next remote,
/// with no event. The pull asks it for the commit object alone.
#[test]
fn a_remote_without_the_commit_gives_way_to_the_next_remote() {
    block_on(async {
        let dir = TmpDir::new("pull-collection-commit-next");
        let a = create(dir.path(), "a", Some(ID)).await;
        let tip = commit(&a, dir.path(), "c", None, REF, FIXED_TS, BOUND).await;
        copy_repo(dir.path(), "a", "b");
        let server_a = RepoServer::start(&dir.path().join("a"), false).await;
        server_a.hide(&meta_path(&tip, "commit"));
        let server_b = RepoServer::start(&dir.path().join("b"), false).await;
        let dest = dest(
            dir.path(),
            None,
            &[("a", &server_a.url(), ""), ("b", &server_b.url(), "")],
        )
        .await;

        let (opts, events) = options(&[&at(REF, &tip)]);
        let pulled = dest.pull_collection(ID, &["a", "b"], opts).await.unwrap();
        assert!(events.lock().unwrap().is_empty());
        assert_eq!(pulled.refs[0].remote, "b");
        assert_eq!(mirror(&dest, REF).await, Some(tip));
        assert_eq!(server_a.seen(), [meta_path(&tip, "commit")]);
    });
}

/// A remote that answers 403 or 410 for the commit object of an operand
/// does not serve it. The operand goes to the next remote, with no event.
#[test]
fn a_commit_operand_answered_403_goes_to_the_next_remote() {
    block_on(async {
        for status in [403u16, 410] {
            let dir = TmpDir::new("pull-collection-commit-403");
            let a = create(dir.path(), "a", Some(ID)).await;
            let tip = commit(&a, dir.path(), "c", None, REF, FIXED_TS, BOUND).await;
            copy_repo(dir.path(), "a", "b");
            let server_a = RepoServer::start(&dir.path().join("a"), false).await;
            server_a.answer_status(&meta_path(&tip, "commit"), status);
            let server_b = RepoServer::start(&dir.path().join("b"), false).await;
            let dest = dest(
                dir.path(),
                None,
                &[("a", &server_a.url(), ""), ("b", &server_b.url(), "")],
            )
            .await;

            let (opts, events) = options(&[&at(REF, &tip)]);
            let pulled = dest.pull_collection(ID, &["a", "b"], opts).await.unwrap();
            assert!(events.lock().unwrap().is_empty(), "{status}");
            assert_eq!(pulled.refs[0].remote, "b", "{status}");
            assert_eq!(mirror(&dest, REF).await, Some(tip), "{status}");
            assert_eq!(server_a.statuses_for(&meta_path(&tip, "commit")), [status]);
        }
    });
}

/// A remote that answers 403 for the listing and for the summary is a
/// candidate that lists no ref: the query returns no ref, and a pull takes
/// the ref from the next remote with no event. A remote that answers 401 is
/// skipped with an event that names the status.
#[test]
fn a_remote_that_answers_403_is_a_candidate_with_no_ref() {
    block_on(async {
        let dir = TmpDir::new("pull-collection-403-candidate");
        let a = create(dir.path(), "a", Some(ID)).await;
        commit(&a, dir.path(), "a", None, REF, FIXED_TS + 10, BOUND).await;
        summarize(&a).await;
        let b = create(dir.path(), "b", Some(ID)).await;
        let tip = commit(&b, dir.path(), "b", None, REF, FIXED_TS, BOUND).await;
        summarize(&b).await;
        let server_a = RepoServer::start(&dir.path().join("a"), false).await;
        for path in [LISTING, "summary.sig", "summary"] {
            server_a.answer_status(path, 403);
        }
        let server_b = RepoServer::start(&dir.path().join("b"), false).await;
        let repo = dest(
            dir.path(),
            None,
            &[("a", &server_a.url(), ""), ("b", &server_b.url(), "")],
        )
        .await;

        assert_eq!(query(&repo, "a", &[REF]).await.unwrap(), []);
        assert_eq!(server_a.statuses_for(LISTING), [403]);
        assert_eq!(server_a.statuses_for("summary"), [403]);

        let (opts, events) = options(&[REF]);
        let pulled = repo.pull_collection(ID, &["a", "b"], opts).await.unwrap();
        assert!(events.lock().unwrap().is_empty());
        assert_eq!(pulled.refs[0].remote, "b");
        assert_eq!(mirror(&repo, REF).await, Some(tip));
        assert!(!objects_requested(&server_a));

        let dir = TmpDir::new("pull-collection-401-skipped");
        let a = create(dir.path(), "a", Some(ID)).await;
        commit(&a, dir.path(), "a", None, REF, FIXED_TS + 10, BOUND).await;
        summarize(&a).await;
        let b = create(dir.path(), "b", Some(ID)).await;
        let tip = commit(&b, dir.path(), "b", None, REF, FIXED_TS, BOUND).await;
        summarize(&b).await;
        let server_a = RepoServer::start(&dir.path().join("a"), false).await;
        for path in [LISTING, "summary.sig", "summary"] {
            server_a.answer_status(path, 401);
        }
        let server_b = RepoServer::start(&dir.path().join("b"), false).await;
        let dest = dest(
            dir.path(),
            None,
            &[("a", &server_a.url(), ""), ("b", &server_b.url(), "")],
        )
        .await;
        let (opts, events) = options(&[REF]);
        let pulled = dest.pull_collection(ID, &["a", "b"], opts).await.unwrap();
        assert_eq!(pulled.refs[0].remote, "b");
        assert_eq!(mirror(&dest, REF).await, Some(tip));
        let events = events.lock().unwrap();
        assert!(
            matches!(&events[..], [CollectionPullEvent::RemoteSkipped { remote, message, .. }]
                if remote == "a" && message.contains("401")),
            "{events:?}"
        );
    });
}

/// A remote whose answer to the commit request is a failure is skipped with
/// an event, and the pull takes the commit from the next remote. A commit
/// that no remote serves fails the pull, and a pull in which each remote
/// fails fails too. Both failures write nothing.
#[test]
fn a_remote_that_fails_the_commit_request_is_skipped_with_an_event() {
    block_on(async {
        let dir = TmpDir::new("pull-collection-commit-failure");
        let a = create(dir.path(), "a", Some(ID)).await;
        let tip = commit(&a, dir.path(), "c", None, REF, FIXED_TS, BOUND).await;
        copy_repo(dir.path(), "a", "b");
        let server_a = RepoServer::start(&dir.path().join("a"), false).await;
        server_a.answer_status(&meta_path(&tip, "commit"), 500);
        let server_b = RepoServer::start(&dir.path().join("b"), false).await;
        let dest = dest(
            dir.path(),
            None,
            &[("a", &server_a.url(), ""), ("b", &server_b.url(), "")],
        )
        .await;

        let absent = Checksum::from_bytes([7; 32]);
        let (opts, events) = options(&[&at(REF, &absent)]);
        let err = dest
            .pull_collection(ID, &["a", "b"], opts)
            .await
            .unwrap_err();
        let expected = format!("no remote of collection '{ID}' serves the commit {absent}");
        assert!(matches!(&err, Error::Pull(m) if *m == expected), "{err:?}");
        assert!(events.lock().unwrap().is_empty());
        assert!(!server_a.seen().iter().any(|path| path == "config"));
        assert_nothing_written(&dest).await;

        let (opts, events) = options(&[&at(REF, &tip)]);
        let err = dest.pull_collection(ID, &["a"], opts).await.unwrap_err();
        let expected = format!("no remote of collection '{ID}' answered");
        assert!(matches!(&err, Error::Pull(m) if *m == expected), "{err:?}");
        assert_eq!(events.lock().unwrap().len(), 1);
        assert_nothing_written(&dest).await;

        let (opts, events) = options(&[&at(REF, &tip)]);
        let pulled = dest.pull_collection(ID, &["a", "b"], opts).await.unwrap();
        assert_eq!(pulled.refs[0].remote, "b");
        assert_eq!(mirror(&dest, REF).await, Some(tip));
        let events = events.lock().unwrap();
        assert!(
            matches!(
                &events[..],
                [CollectionPullEvent::RemoteSkipped { remote, message, .. }]
                    if remote == "a" && message.contains("500")
            ),
            "{events:?}"
        );
    });
}

/// A pull whose operands each name a commit reads no ref listing, no
/// `summary`, and no `summary.sig` of a remote, so a summary that fails the
/// policy of the remote does not stop it. A pull that also names a ref with
/// no commit reads the summary, and the policy applies.
#[test]
fn commit_operands_alone_read_no_summary_of_a_remote() {
    block_on(async {
        let dir = TmpDir::new("pull-collection-commit-no-summary");
        let a = create(dir.path(), "a", Some(ID)).await;
        let old = commit(&a, dir.path(), "old", None, REF, FIXED_TS, BOUND).await;
        let tip = commit(&a, dir.path(), "new", None, REF, FIXED_TS + 10, BOUND).await;
        // The policy refuses a summary with no signature.
        summarize(&a).await;
        let server_a = RepoServer::start(&dir.path().join("a"), false).await;
        let policy =
            format!("sign-verify-summary=ed25519\nverification-ed25519-key={PUBLIC_B64}\n");
        let dest = dest(dir.path(), None, &[("a", &server_a.url(), &policy)]).await;

        let (opts, events) = options(&["os/next", &at(REF, &old)]);
        let err = dest.pull_collection(ID, &["a"], opts).await.unwrap_err();
        assert!(
            matches!(&err, Error::Pull(m) if m.contains("answered")),
            "{err:?}"
        );
        assert_eq!(events.lock().unwrap().len(), 1);
        assert!(refs_requested(&server_a));
        assert!(!objects_requested(&server_a));
        assert_nothing_written(&dest).await;

        let server_a = RepoServer::start(&dir.path().join("a"), false).await;
        let dest = reconfigure(
            dir.path(),
            &format!(
                "\n[remote \"again\"]\nurl={}\ngpg-verify=false\n{policy}",
                server_a.url()
            ),
        )
        .await;
        let (opts, events) = options(&[&at(REF, &old), &tip.to_hex()]);
        let pulled = dest.pull_collection(ID, &["again"], opts).await.unwrap();
        assert!(events.lock().unwrap().is_empty());
        assert_eq!(pulled.refs.len(), 1);
        assert_eq!(mirror(&dest, REF).await, Some(old));
        assert!(dest.has_object(ObjectType::Commit, &tip).await.unwrap());
        assert!(dest.fsck(&FsckOptions::default()).await.unwrap().is_ok());
        assert!(!refs_requested(&server_a), "{:?}", server_a.seen());
    });
}

/// Two operands that write one ref with two commits stop the pull before its
/// first request: two `REF@CHECKSUM` operands, in either form of the ref, and
/// a ref with no commit beside a `REF@CHECKSUM` operand. The error names the
/// path of the ref. `REF@CHECKSUM` and `@ID:REF@CHECKSUM` of one commit are
/// one operand. A pull that writes no ref takes two commits for one ref name.
#[test]
fn two_commit_operands_for_one_ref_are_refused() {
    block_on(async {
        let dir = TmpDir::new("pull-collection-commit-one-ref");
        let a = create(dir.path(), "a", Some(ID)).await;
        let old = commit(&a, dir.path(), "old", None, REF, FIXED_TS, BOUND).await;
        let tip = commit(&a, dir.path(), "new", None, REF, FIXED_TS + 10, BOUND).await;
        summarize(&a).await;
        let server_a = RepoServer::start(&dir.path().join("a"), false).await;
        let with_id = |commit: &Checksum| commit_operand(&Ref::collection(ID, REF), commit);

        for (own, path) in [
            (None, format!("refs/mirrors/{ID}/{REF}")),
            (Some(ID), format!("refs/heads/{REF}")),
        ] {
            let dest = dest(dir.path(), own, &[("a", &server_a.url(), "")]).await;
            let cases = [
                [at(REF, &old), at(REF, &tip)],
                [REF.to_owned(), at(REF, &old)],
                [at(REF, &old), with_id(&tip)],
            ];
            for [first, second] in cases {
                let (opts, _) = options(&[&first, &second]);
                let err = dest.pull_collection(ID, &["a"], opts).await.unwrap_err();
                let expected = format!("the refs {first} and {second} write one ref {path}");
                assert!(matches!(&err, Error::Pull(m) if *m == expected), "{err:?}");
            }
            assert!(server_a.seen().is_empty(), "{:?}", server_a.seen());
            assert_nothing_written(&dest).await;
            drop(dest);
            std::fs::remove_dir_all(dir.path().join("dest")).unwrap();
        }

        let once = dest(dir.path(), None, &[("a", &server_a.url(), "")]).await;
        let (opts, _) = options(&[&at(REF, &old), &with_id(&old)]);
        let pulled = once.pull_collection(ID, &["a"], opts).await.unwrap();
        assert_eq!(pulled.refs.len(), 1);
        assert_eq!(mirror(&once, REF).await, Some(old));
        drop(once);
        std::fs::remove_dir_all(dir.path().join("dest")).unwrap();

        // The remote lists the ref at the newer commit. The check of the
        // listed timestamp applies to that commit alone.
        let unwritten = dest(dir.path(), None, &[("a", &server_a.url(), "")]).await;
        let (mut opts, events) = options(&[REF, &at(REF, &old)]);
        opts.pull.no_ref_writes = true;
        let pulled = unwritten.pull_collection(ID, &["a"], opts).await.unwrap();
        assert!(events.lock().unwrap().is_empty());
        let got: Vec<(&str, Checksum, u64)> = pulled
            .refs
            .iter()
            .map(|r| (r.name.as_str(), r.commit, r.timestamp))
            .collect();
        assert_eq!(got, [(REF, tip, FIXED_TS + 10), (REF, old, FIXED_TS)]);
        assert!(
            unwritten
                .has_object(ObjectType::Commit, &old)
                .await
                .unwrap()
        );
        assert!(
            unwritten
                .has_object(ObjectType::Commit, &tip)
                .await
                .unwrap()
        );
        assert!(unwritten.list_mirror_refs().await.unwrap().is_empty());
        assert!(unwritten.list_refs(None).await.unwrap().is_empty());
    });
}

/// The `ostree.collection-binding` of the commit of a `CHECKSUM` operand
/// must state the collection of the pull. A commit with no binding key
/// passes with `allow_unbound` alone. The pull writes no ref for the
/// operand, makes no ref-binding check of its commit, and gives it no entry
/// in the result.
#[test]
fn a_checksum_operand_must_be_bound_to_the_collection() {
    block_on(async {
        let other_ref: &[&str] = &["os/next"];
        let cases: [(&str, Option<&str>, bool, Option<&str>); 4] = [
            ("other collection", Some(OTHER), true, Some(OTHER)),
            ("no binding", None, false, Some("no collection binding")),
            ("no binding, allowed", None, true, None),
            ("bound", Some(ID), false, None),
        ];
        for (tag, collection, allow_unbound, fragment) in cases {
            let dir = TmpDir::new("pull-collection-commit-binding");
            let a = create(dir.path(), "a", Some(ID)).await;
            let bind = Bind {
                collection,
                refs: Some(other_ref),
            };
            let tip = commit(&a, dir.path(), "a", None, REF, FIXED_TS, bind).await;
            let server_a = RepoServer::start(&dir.path().join("a"), false).await;
            let dest = dest(dir.path(), None, &[("a", &server_a.url(), "")]).await;

            let (mut opts, _) = options(&[&tip.to_hex()]);
            opts.allow_unbound = allow_unbound;
            let pulled = dest.pull_collection(ID, &["a"], opts).await;
            let Some(fragment) = fragment else {
                let pulled = pulled.unwrap();
                assert!(pulled.refs.is_empty(), "{tag}: {:?}", pulled.refs);
                assert!(
                    dest.has_object(ObjectType::Commit, &tip).await.unwrap(),
                    "{tag}"
                );
                assert!(dest.list_refs(None).await.unwrap().is_empty(), "{tag}");
                assert!(dest.list_mirror_refs().await.unwrap().is_empty(), "{tag}");
                assert!(dest.fsck(&FsckOptions::default()).await.unwrap().is_ok());
                continue;
            };
            let err = pulled.unwrap_err();
            assert!(
                matches!(&err, Error::Pull(m) if m.contains(fragment)),
                "{tag}: {err:?}"
            );
            assert_nothing_written(&dest).await;
        }
    });
}

/// The pull refuses a malformed commit operand, a commit operand of another
/// collection, and a `CHECKSUM` operand that its options cannot take, before
/// its first request.
#[test]
fn a_collection_pull_refuses_a_malformed_commit_operand() {
    block_on(async {
        let dir = TmpDir::new("pull-collection-commit-malformed");
        let a = create(dir.path(), "a", Some(ID)).await;
        let tip = commit(&a, dir.path(), "a", None, REF, FIXED_TS, BOUND).await;
        let server_a = RepoServer::start(&dir.path().join("a"), false).await;
        let dest = dest(dir.path(), None, &[("a", &server_a.url(), "")]).await;
        let hex = tip.to_hex();

        let malformed = [
            format!("{REF}@"),
            format!("{REF}@{}", &hex[..10]),
            format!("{REF}@{}", hex.to_uppercase()),
            format!("{REF}@{hex}^"),
            format!("origin:{REF}@{hex}"),
            format!("a@b@{hex}"),
            format!("@{hex}"),
        ];
        for name in malformed {
            let (opts, _) = options(&[&name]);
            let err = dest.pull_collection(ID, &["a"], opts).await.unwrap_err();
            assert!(
                matches!(&err, Error::InvalidRefspec(got) if *got == name),
                "{name}: {err:?}"
            );
        }

        let other = commit_operand(&Ref::collection(OTHER, REF), &tip);
        let (opts, _) = options(&[&other]);
        let err = dest.pull_collection(ID, &["a"], opts).await.unwrap_err();
        assert!(matches!(err, Error::InvalidInput(_)), "{err:?}");

        let (mut opts, _) = options(&[&hex]);
        opts.pull.timestamp_check = TimestampCheck::CurrentRef;
        let err = dest.pull_collection(ID, &["a"], opts).await.unwrap_err();
        assert!(matches!(err, Error::InvalidInput(_)), "{err:?}");

        let (mut opts, _) = options(&[&hex]);
        opts.pull.require_static_deltas = true;
        let err = dest.pull_collection(ID, &["a"], opts).await.unwrap_err();
        assert!(
            matches!(&err, Error::Pull(m) if m.contains("Static deltas required")),
            "{err:?}"
        );

        assert!(server_a.seen().is_empty(), "{:?}", server_a.seen());
        assert_nothing_written(&dest).await;
    });
}

/// A `REF@CHECKSUM` operand writes the ref of the collection to its commit,
/// also for a commit that is older than the commit that the remote lists for
/// the ref. Into a repository whose own id is the pulled id, the pull writes
/// the local ref. The pull refuses a commit whose ref binding does not hold
/// the ref.
#[test]
fn a_ref_at_checksum_operand_writes_the_collection_ref() {
    block_on(async {
        let dir = TmpDir::new("pull-collection-commit-ref");
        let a = create(dir.path(), "a", Some(ID)).await;
        let old = commit(&a, dir.path(), "old", None, REF, FIXED_TS, BOUND).await;
        commit(&a, dir.path(), "new", None, REF, FIXED_TS + 10, BOUND).await;
        let bind = Bind {
            collection: Some(ID),
            refs: Some(&["os/next"]),
        };
        let next = commit(&a, dir.path(), "next", None, "os/next", FIXED_TS, bind).await;
        summarize(&a).await;
        let server_a = RepoServer::start(&dir.path().join("a"), false).await;

        let plain = dest(dir.path(), None, &[("a", &server_a.url(), "")]).await;
        let (opts, _) = options(&[&at(REF, &next)]);
        let err = plain.pull_collection(ID, &["a"], opts).await.unwrap_err();
        assert!(
            matches!(&err, Error::Pull(m) if m.contains("in ref binding metadata")),
            "{err:?}"
        );
        assert_nothing_written(&plain).await;

        let operand = commit_operand(&Ref::collection(ID, REF), &old);
        let (opts, events) = options(&[&operand]);
        let pulled = plain.pull_collection(ID, &["a"], opts).await.unwrap();
        assert!(events.lock().unwrap().is_empty());
        let got: Vec<(&str, &str, Checksum, u64)> = pulled
            .refs
            .iter()
            .map(|r| (r.name.as_str(), r.remote.as_str(), r.commit, r.timestamp))
            .collect();
        assert_eq!(got, [(REF, "a", old, FIXED_TS)]);
        assert_eq!(mirror(&plain, REF).await, Some(old));
        assert!(plain.list_refs(None).await.unwrap().is_empty());
        assert!(plain.list_remote_refs().await.unwrap().is_empty());
        assert!(plain.fsck(&FsckOptions::default()).await.unwrap().is_ok());
        drop(plain);

        std::fs::remove_dir_all(dir.path().join("dest")).unwrap();
        let own = dest(dir.path(), Some(ID), &[("a", &server_a.url(), "")]).await;
        let (opts, _) = options(&[&at(REF, &old)]);
        own.pull_collection(ID, &["a"], opts).await.unwrap();
        assert_eq!(own.list_refs(None).await.unwrap(), [(REF.to_owned(), old)]);
        assert!(own.list_mirror_refs().await.unwrap().is_empty());
    });
}

/// A remote at a `file://` address serves commit operands from the local
/// repository. The pull writes the ref of a `REF@CHECKSUM` operand and no
/// ref for a `CHECKSUM` operand. With commit operands alone, the pull reads
/// no summary of the repository, so a summary policy that the repository
/// cannot meet does not stop it. With a ref that names no commit beside
/// them, the policy skips the remote.
#[test]
fn a_file_remote_serves_commit_operands() {
    block_on(async {
        let dir = TmpDir::new("pull-collection-commit-file");
        let a = create(dir.path(), "a", Some(OTHER)).await;
        let old = commit(&a, dir.path(), "old", Some(ID), REF, FIXED_TS, BOUND).await;
        let tip = commit(&a, dir.path(), "new", Some(ID), REF, FIXED_TS + 10, BOUND).await;
        let policy =
            format!("sign-verify-summary=ed25519\nverification-ed25519-key={PUBLIC_B64}\n");
        let dest = dest(
            dir.path(),
            None,
            &[("a", &file_url(dir.path(), "a"), &policy)],
        )
        .await;

        let (opts, events) = options(&["os/next", &at(REF, &old)]);
        let err = dest.pull_collection(ID, &["a"], opts).await.unwrap_err();
        assert!(
            matches!(&err, Error::Pull(m) if m.contains("answered")),
            "{err:?}"
        );
        assert_eq!(skipped(dir.path(), &events), ["a"]);
        assert_nothing_written(&dest).await;

        let absent = Checksum::from_bytes([7; 32]);
        let (opts, events) = options(&[&absent.to_hex()]);
        let err = dest.pull_collection(ID, &["a"], opts).await.unwrap_err();
        assert!(
            matches!(&err, Error::Pull(m) if m.contains("serves the commit")),
            "{err:?}"
        );
        assert!(events.lock().unwrap().is_empty());
        assert_nothing_written(&dest).await;

        let (opts, events) = options(&[&at(REF, &old), &tip.to_hex()]);
        let pulled = dest.pull_collection(ID, &["a"], opts).await.unwrap();
        assert!(events.lock().unwrap().is_empty());
        let got: Vec<(&str, &str, Checksum, u64)> = pulled
            .refs
            .iter()
            .map(|r| (r.name.as_str(), r.remote.as_str(), r.commit, r.timestamp))
            .collect();
        assert_eq!(got, [(REF, "a", old, FIXED_TS)]);
        assert_eq!(mirror(&dest, REF).await, Some(old));
        assert_eq!(dest.list_mirror_refs().await.unwrap().len(), 1);
        assert!(dest.list_refs(None).await.unwrap().is_empty());
        assert!(dest.has_object(ObjectType::Commit, &tip).await.unwrap());
        assert!(dest.fsck(&FsckOptions::default()).await.unwrap().is_ok());
        assert!(pulled.local.content_imported > 0, "{:?}", pulled.local);
    });
}

/// A remote at a `file://` address under `require_static_deltas`, with
/// commit operands alone and no summary: the pull reads no summary, and
/// reads the from-scratch delta of the commit by name.
#[test]
fn a_file_remote_takes_a_required_delta_of_a_commit_operand_by_name() {
    block_on(async {
        let dir = TmpDir::new("pull-collection-commit-file-delta");
        let a = create(dir.path(), "a", Some(ID)).await;
        let tip = commit(&a, dir.path(), "a", None, REF, FIXED_TS, BOUND).await;
        a.generate_static_delta(None, &tip, &DeltaOptions::default())
            .await
            .unwrap();
        assert!(!dir.path().join("a/summary").exists());
        let dest = dest(dir.path(), None, &[("a", &file_url(dir.path(), "a"), "")]).await;

        let (mut opts, events) = options(&[&at(REF, &tip)]);
        opts.pull.require_static_deltas = true;
        let pulled = dest.pull_collection(ID, &["a"], opts).await.unwrap();

        assert!(events.lock().unwrap().is_empty());
        assert!(pulled.stats.delta_parts > 0, "{:?}", pulled.stats);
        assert_eq!(mirror(&dest, REF).await, Some(tip));
        assert!(dest.fsck(&FsckOptions::default()).await.unwrap().is_ok());
    });
}

/// The destination holds C of the chain R -> C -> D complete, and not the
/// commit object of D. A pull from a remote at a `file://` address of a
/// commit that names C reads field 2 of C from the destination, and takes D
/// complete. Each operand form runs into a new destination: the ref, and the
/// commit operand `REF@CHECKSUM`.
#[test]
fn a_file_remote_takes_an_attachment_below_an_attachment_held_complete() {
    block_on(async {
        let dir = TmpDir::new("pull-collection-file-attachment-held");
        let a = create(dir.path(), "a", Some(ID)).await;
        let chain = common::write_chain(&a, &dir.path().join("trees"), "os/chain").await;
        let plain = commit(&a, dir.path(), "a", None, REF, FIXED_TS, BOUND).await;
        let tip = store_with_field2(&a, &plain, &[(common::CHAIN_C, chain.c.as_bytes())]).await;
        let txn = a.transaction().await.unwrap();
        txn.set_ref(&Ref::local(REF), Some(&tip));
        txn.commit().await.unwrap();
        let hex = chain.d.to_hex();

        for (case, operand) in [("ref", REF.to_owned()), ("commit", at(REF, &tip))] {
            let base = dir.path().join(case);
            std::fs::create_dir(&base).unwrap();
            let dest = dest(&base, None, &[("a", &file_url(dir.path(), "a"), "")]).await;
            dest.pull_local(
                &a,
                PullOptions {
                    refs: vec![chain.c.to_hex()],
                    ..PullOptions::default()
                },
            )
            .await
            .unwrap();
            std::fs::remove_file(
                base.join("dest/objects")
                    .join(&hex[..2])
                    .join(format!("{}.commit", &hex[2..])),
            )
            .unwrap();
            assert!(!dest.has_object(ObjectType::Commit, &chain.d).await.unwrap());

            let (opts, events) = options(&[&operand]);
            dest.pull_collection(ID, &["a"], opts).await.unwrap();
            assert!(events.lock().unwrap().is_empty(), "{case}");

            assert_eq!(mirror(&dest, REF).await, Some(tip), "{case}");
            for commit in [tip, chain.c, chain.d] {
                assert_eq!(
                    dest.commit_state(&commit).await.unwrap(),
                    ostrya::CommitState::Normal,
                    "{case}"
                );
                for name in &a.traverse_commit(&commit, 0).await.unwrap() {
                    assert!(
                        dest.has_object(name.ty, &name.checksum).await.unwrap(),
                        "{case}: {name} missing from the destination"
                    );
                }
            }
            assert_eq!(
                common::file_inventory(&base.join("dest"), "state"),
                Vec::new(),
                "{case}"
            );
        }
    });
}

/// With commit operands alone, the pull stops the probe at the remote that
/// serves the last commit, and opens no session to a later remote. So a
/// later remote at a `file://` path with no repository gives no event. With
/// a ref that names no commit, the pull probes each remote, and that remote
/// gives an event.
#[test]
fn commit_operands_alone_open_no_session_to_a_later_remote() {
    block_on(async {
        let dir = TmpDir::new("pull-collection-commit-no-session");
        let a = create(dir.path(), "a", Some(ID)).await;
        let tip = commit(&a, dir.path(), "a", None, REF, FIXED_TS, BOUND).await;
        summarize(&a).await;
        let server_a = RepoServer::start(&dir.path().join("a"), false).await;
        let dest = dest(
            dir.path(),
            None,
            &[
                ("a", &server_a.url(), ""),
                ("missing", &file_url(dir.path(), "missing"), ""),
            ],
        )
        .await;

        let (opts, events) = options(&[&at(REF, &tip)]);
        let pulled = dest
            .pull_collection(ID, &["a", "missing"], opts)
            .await
            .unwrap();
        assert!(events.lock().unwrap().is_empty());
        assert_eq!(pulled.refs[0].remote, "a");
        assert_eq!(mirror(&dest, REF).await, Some(tip));

        let (opts, events) = options(&[REF]);
        dest.pull_collection(ID, &["a", "missing"], opts)
            .await
            .unwrap();
        assert_eq!(skipped(dir.path(), &events), ["missing"]);
    });
}

/// A remote lists a ref whose name is the hex form of its commit. The pull
/// writes that ref when the `CHECKSUM` operand of the same commit stands
/// beside the ref: when one remote gives both, and when an earlier remote
/// serves the commit of the `CHECKSUM` operand.
#[test]
fn a_listed_ref_named_as_its_commit_is_written_beside_the_checksum_operand() {
    block_on(async {
        let dir = TmpDir::new("pull-collection-commit-hex-ref");
        let a = create(dir.path(), "a", Some(ID)).await;
        let bind = Bind {
            collection: Some(ID),
            refs: None,
        };
        let tip = commit(&a, dir.path(), "c", None, REF, FIXED_TS, bind).await;
        summarize(&a).await;
        // The second remote holds the commit and lists no ref of its name.
        copy_repo(dir.path(), "a", "b");
        let hex = tip.to_hex();
        let txn = a.transaction().await.unwrap();
        txn.set_ref(&Ref::local(&hex), Some(&tip));
        txn.commit().await.unwrap();
        summarize(&a).await;
        let server_a = RepoServer::start(&dir.path().join("a"), false).await;
        let server_b = RepoServer::start(&dir.path().join("b"), false).await;
        let named = format!("@{ID}:{hex}");

        for remotes in [&["b", "a"][..], &["a"]] {
            let dest = dest(
                dir.path(),
                None,
                &[("a", &server_a.url(), ""), ("b", &server_b.url(), "")],
            )
            .await;
            let (opts, events) = options(&[&named, &hex]);
            let pulled = dest.pull_collection(ID, remotes, opts).await.unwrap();
            assert!(events.lock().unwrap().is_empty());
            let got: Vec<(&str, &str, Checksum, u64)> = pulled
                .refs
                .iter()
                .map(|r| (r.name.as_str(), r.remote.as_str(), r.commit, r.timestamp))
                .collect();
            assert_eq!(got, [(hex.as_str(), "a", tip, FIXED_TS)], "{remotes:?}");
            assert_eq!(mirror(&dest, &hex).await, Some(tip), "{remotes:?}");
            assert_eq!(dest.list_mirror_refs().await.unwrap().len(), 1);
            assert!(dest.fsck(&FsckOptions::default()).await.unwrap().is_ok());
            drop(dest);
            std::fs::remove_dir_all(dir.path().join("dest")).unwrap();
        }
        // The earlier remote served the commit of the `CHECKSUM` operand.
        assert!(objects_requested(&server_b));
    });
}

/// A remote whose commit object does not hash to its name is skipped with
/// an event, and the pull takes the commit from the next remote.
#[test]
fn a_remote_with_a_damaged_commit_object_is_skipped_with_an_event() {
    block_on(async {
        let dir = TmpDir::new("pull-collection-commit-damaged");
        let a = create(dir.path(), "a", Some(ID)).await;
        let tip = commit(&a, dir.path(), "c", None, REF, FIXED_TS, BOUND).await;
        copy_repo(dir.path(), "a", "b");
        let server_a = RepoServer::start(&dir.path().join("a"), false).await;
        server_a.tamper(&meta_path(&tip, "commit"), b"not the commit".to_vec());
        let server_b = RepoServer::start(&dir.path().join("b"), false).await;
        let dest = dest(
            dir.path(),
            None,
            &[("a", &server_a.url(), ""), ("b", &server_b.url(), "")],
        )
        .await;

        let (opts, events) = options(&[&at(REF, &tip)]);
        let pulled = dest.pull_collection(ID, &["a", "b"], opts).await.unwrap();
        assert_eq!(pulled.refs[0].remote, "b");
        assert_eq!(mirror(&dest, REF).await, Some(tip));
        assert!(dest.fsck(&FsckOptions::default()).await.unwrap().is_ok());
        assert_eq!(server_a.seen(), [meta_path(&tip, "commit")]);
        let events = events.lock().unwrap();
        assert!(
            matches!(
                &events[..],
                [CollectionPullEvent::RemoteSkipped { remote, .. }] if remote == "a"
            ),
            "{events:?}"
        );
    });
}

/// A pull names a ref with no commit and a `CHECKSUM` operand. A remote
/// whose answer to the commit request is a failure is skipped together with
/// the refs that it lists. The pull takes the ref and the commit from the
/// next remote.
#[test]
fn a_failed_commit_request_skips_the_listed_refs_of_the_remote() {
    block_on(async {
        let dir = TmpDir::new("pull-collection-commit-failure-mixed");
        let a = create(dir.path(), "a", Some(ID)).await;
        let old = commit(&a, dir.path(), "old", None, REF, FIXED_TS, BOUND).await;
        let tip = commit(&a, dir.path(), "new", None, REF, FIXED_TS + 10, BOUND).await;
        summarize(&a).await;
        copy_repo(dir.path(), "a", "b");
        let server_a = RepoServer::start(&dir.path().join("a"), false).await;
        server_a.answer_status(&meta_path(&old, "commit"), 500);
        let server_b = RepoServer::start(&dir.path().join("b"), false).await;
        let dest = dest(
            dir.path(),
            None,
            &[("a", &server_a.url(), ""), ("b", &server_b.url(), "")],
        )
        .await;

        let (opts, events) = options(&[REF, &old.to_hex()]);
        let pulled = dest.pull_collection(ID, &["a", "b"], opts).await.unwrap();
        let got: Vec<(&str, &str, Checksum)> = pulled
            .refs
            .iter()
            .map(|r| (r.name.as_str(), r.remote.as_str(), r.commit))
            .collect();
        assert_eq!(got, [(REF, "b", tip)]);
        assert_eq!(mirror(&dest, REF).await, Some(tip));
        assert!(dest.has_object(ObjectType::Commit, &old).await.unwrap());
        assert!(dest.fsck(&FsckOptions::default()).await.unwrap().is_ok());
        // The pull read the refs of the skipped remote, and then asked it
        // for nothing more.
        assert!(refs_requested(&server_a));
        assert!(!server_a.seen().iter().any(|path| path == "config"));
        let events = events.lock().unwrap();
        assert!(
            matches!(
                &events[..],
                [CollectionPullEvent::RemoteSkipped { remote, message, .. }]
                    if remote == "a" && message.contains("500")
            ),
            "{events:?}"
        );
    });
}

/// A pull that writes no ref makes the collection-binding check of the
/// commit of each form of a commit operand.
#[test]
fn a_pull_with_no_ref_writes_checks_the_binding_of_each_commit_operand() {
    block_on(async {
        let dir = TmpDir::new("pull-collection-commit-binding-unwritten");
        let a = create(dir.path(), "a", Some(ID)).await;
        let bind = Bind {
            collection: Some(OTHER),
            refs: Some(&[REF]),
        };
        let tip = commit(&a, dir.path(), "a", None, REF, FIXED_TS, bind).await;
        let server_a = RepoServer::start(&dir.path().join("a"), false).await;
        let dest = dest(dir.path(), None, &[("a", &server_a.url(), "")]).await;

        let operands = [
            tip.to_hex(),
            at(REF, &tip),
            commit_operand(&Ref::collection(ID, REF), &tip),
        ];
        for operand in operands {
            let (mut opts, _) = options(&[&operand]);
            opts.pull.no_ref_writes = true;
            let err = dest.pull_collection(ID, &["a"], opts).await.unwrap_err();
            assert!(
                matches!(&err, Error::Pull(m) if m.contains(OTHER)),
                "{operand}: {err:?}"
            );
            assert_nothing_written(&dest).await;
        }
    });
}

/// The operand `CHECKSUM@CHECKSUM` writes the ref whose name is the hex form
/// of the commit. The `CHECKSUM` operand of the same commit beside it adds
/// no entry to the result.
#[test]
fn a_checksum_operand_beside_its_ref_form_gives_one_entry() {
    block_on(async {
        let dir = TmpDir::new("pull-collection-commit-own-name");
        let a = create(dir.path(), "a", Some(ID)).await;
        let bind = Bind {
            collection: Some(ID),
            refs: None,
        };
        let tip = commit(&a, dir.path(), "a", None, REF, FIXED_TS, bind).await;
        let server_a = RepoServer::start(&dir.path().join("a"), false).await;
        let dest = dest(dir.path(), None, &[("a", &server_a.url(), "")]).await;
        let hex = tip.to_hex();

        let (opts, events) = options(&[&at(&hex, &tip), &hex]);
        let pulled = dest.pull_collection(ID, &["a"], opts).await.unwrap();
        assert!(events.lock().unwrap().is_empty());
        let got: Vec<(&str, &str, Checksum, u64)> = pulled
            .refs
            .iter()
            .map(|r| (r.name.as_str(), r.remote.as_str(), r.commit, r.timestamp))
            .collect();
        assert_eq!(got, [(hex.as_str(), "a", tip, FIXED_TS)]);
        assert_eq!(mirror(&dest, &hex).await, Some(tip));
        assert_eq!(dest.list_mirror_refs().await.unwrap().len(), 1);
        assert!(dest.fsck(&FsckOptions::default()).await.unwrap().is_ok());
    });
}

/// Two remotes serve one commit each. The pull asks the second remote only
/// for the commit that the first remote does not serve, and sends no request
/// to a third remote. The result follows the order of the operands.
#[test]
fn each_commit_comes_from_the_first_remote_that_serves_it() {
    block_on(async {
        let dir = TmpDir::new("pull-collection-commit-two-remotes");
        let a = create(dir.path(), "a", Some(ID)).await;
        let first = commit(&a, dir.path(), "first", None, REF, FIXED_TS, BOUND).await;
        copy_repo(dir.path(), "a", "b");
        let b = Repo::open(&dir.path().join("b")).await.unwrap();
        let next = "os/next";
        let bind = Bind {
            collection: Some(ID),
            refs: Some(&[next]),
        };
        let second = commit(&b, dir.path(), "second", None, next, FIXED_TS + 10, bind).await;
        copy_repo(dir.path(), "b", "c");
        let server_a = RepoServer::start(&dir.path().join("a"), false).await;
        let server_b = RepoServer::start(&dir.path().join("b"), false).await;
        let server_c = RepoServer::start(&dir.path().join("c"), false).await;
        let dest = dest(
            dir.path(),
            None,
            &[
                ("a", &server_a.url(), ""),
                ("b", &server_b.url(), ""),
                ("c", &server_c.url(), ""),
            ],
        )
        .await;

        let (opts, events) = options(&[&at(next, &second), &at(REF, &first)]);
        let pulled = dest
            .pull_collection(ID, &["a", "b", "c"], opts)
            .await
            .unwrap();
        assert!(events.lock().unwrap().is_empty());
        let got: Vec<(&str, &str, Checksum, u64)> = pulled
            .refs
            .iter()
            .map(|r| (r.name.as_str(), r.remote.as_str(), r.commit, r.timestamp))
            .collect();
        assert_eq!(
            got,
            [
                (next, "b", second, FIXED_TS + 10),
                (REF, "a", first, FIXED_TS)
            ]
        );
        assert_eq!(mirror(&dest, REF).await, Some(first));
        assert_eq!(mirror(&dest, next).await, Some(second));
        assert!(dest.fsck(&FsckOptions::default()).await.unwrap().is_ok());
        assert_eq!(server_a.requests_for(&meta_path(&second, "commit")), 1);
        assert_eq!(server_b.requests_for(&meta_path(&first, "commit")), 0);
        assert!(server_c.seen().is_empty(), "{:?}", server_c.seen());
    });
}

/// Under `TimestampCheck::CurrentRef`, the pull refuses a `REF@CHECKSUM`
/// operand whose commit is older than the current commit of the ref.
#[test]
fn the_current_ref_check_refuses_an_older_commit_operand() {
    block_on(async {
        let dir = TmpDir::new("pull-collection-commit-downgrade");
        let a = create(dir.path(), "a", Some(ID)).await;
        let old = commit(&a, dir.path(), "old", None, REF, FIXED_TS, BOUND).await;
        let tip = commit(&a, dir.path(), "new", None, REF, FIXED_TS + 10, BOUND).await;
        let server_a = RepoServer::start(&dir.path().join("a"), false).await;
        let dest = dest(dir.path(), None, &[("a", &server_a.url(), "")]).await;

        let (mut opts, _) = options(&[&at(REF, &tip)]);
        opts.pull.timestamp_check = TimestampCheck::CurrentRef;
        dest.pull_collection(ID, &["a"], opts).await.unwrap();
        assert_eq!(mirror(&dest, REF).await, Some(tip));

        let (mut opts, _) = options(&[&at(REF, &old)]);
        opts.pull.timestamp_check = TimestampCheck::CurrentRef;
        let err = dest.pull_collection(ID, &["a"], opts).await.unwrap_err();
        assert!(
            matches!(&err, Error::Pull(m) if m.contains("chronologically older")),
            "{err:?}"
        );
        assert_eq!(mirror(&dest, REF).await, Some(tip));
    });
}

/// A pull names a ref with no commit and a `CHECKSUM` operand. The remote
/// that gives the commit of the `CHECKSUM` operand and no ref still reads
/// its summary in the pull.
#[test]
fn a_remote_with_commit_targets_alone_reads_its_summary_in_a_mixed_pull() {
    block_on(async {
        let dir = TmpDir::new("pull-collection-commit-mixed-summary");
        let a = create(dir.path(), "a", Some(ID)).await;
        let old = commit(&a, dir.path(), "old", None, REF, FIXED_TS, BOUND).await;
        summarize(&a).await;
        copy_repo(dir.path(), "a", "b");
        let b = Repo::open(&dir.path().join("b")).await.unwrap();
        let tip = commit(&b, dir.path(), "new", None, REF, FIXED_TS + 10, BOUND).await;
        summarize(&b).await;
        // The first remote answers the probe from its listing, so its probe
        // reads no summary.
        let server_a = RepoServer::start(&dir.path().join("a"), false).await;
        serve_listing(&server_a, &a, &[REF]).await;
        let server_b = RepoServer::start(&dir.path().join("b"), false).await;
        let dest = dest(
            dir.path(),
            None,
            &[("a", &server_a.url(), ""), ("b", &server_b.url(), "")],
        )
        .await;

        let (opts, events) = options(&[REF, &old.to_hex()]);
        let pulled = dest.pull_collection(ID, &["a", "b"], opts).await.unwrap();
        assert!(events.lock().unwrap().is_empty());
        let got: Vec<(&str, &str, Checksum)> = pulled
            .refs
            .iter()
            .map(|r| (r.name.as_str(), r.remote.as_str(), r.commit))
            .collect();
        assert_eq!(got, [(REF, "b", tip)]);
        assert_eq!(mirror(&dest, REF).await, Some(tip));
        assert!(dest.has_object(ObjectType::Commit, &old).await.unwrap());
        assert_eq!(server_a.requests_for("summary"), 1, "{:?}", server_a.seen());
        assert_eq!(server_b.requests_for(&meta_path(&old, "commit")), 0);
    });
}

// --- the listing of collection refs ------------------------------------------

/// Returns the overrides of a query with no retry.
fn no_retry() -> EndpointOverrides {
    EndpointOverrides {
        max_retries: Some(0),
        ..EndpointOverrides::default()
    }
}

/// Lists the refs `names` of `ID` on the remote `remote` of `repo`, with no
/// retry.
async fn query(
    repo: &Repo,
    remote: &str,
    names: &[&str],
) -> ostrya::Result<Vec<(String, Checksum)>> {
    repo.remote_list_collection_refs_with(remote, ID, names, no_retry(), None)
        .await
}

/// A list of 300 names takes more than one listing request. The result holds
/// each listed ref once, sorted by name, whatever the order of the names. A
/// name that the remote does not hold, and a name that occurs again, add
/// nothing.
#[test]
fn a_query_of_300_names_takes_more_than_one_request() {
    block_on(async {
        let dir = TmpDir::new("pull-collection-query-many");
        let b = create(dir.path(), "b", Some(OTHER)).await;
        let tip = commit(
            &b,
            dir.path(),
            "b",
            Some(ID),
            "pool/n000",
            FIXED_TS,
            COLLECTION_ONLY,
        )
        .await;
        let names: Vec<String> = (0..300).map(|n| format!("pool/n{n:03}")).collect();
        let txn = b.transaction().await.unwrap();
        for name in &names[1..] {
            txn.set_ref(&Ref::collection(ID, name), Some(&tip));
        }
        txn.commit().await.unwrap();
        let server_b = RepoServer::start(&dir.path().join("b"), false).await;
        serve_listing(&server_b, &b, &[]).await;
        let dest = dest(dir.path(), None, &[("b", &server_b.url(), "")]).await;

        let mut asked: Vec<&str> = names.iter().rev().map(String::as_str).collect();
        asked.push("pool/absent");
        asked.push("pool/n007");
        let listed = query(&dest, "b", &asked).await.unwrap();
        let expected: Vec<(String, Checksum)> =
            names.iter().map(|name| (name.clone(), tip)).collect();
        assert_eq!(listed, expected);
        let requests = (asked.len() - 1).div_ceil(MAX_REF_PATTERNS / 2);
        assert!(requests > 1);
        assert_eq!(server_b.requests_for(LISTING), requests);
        assert_eq!(server_b.requests_for("summary"), 0);
        assert_nothing_written(&dest).await;
    });
}

/// A remote whose own collection id is the queried id lists the refs in
/// field 0. With no name, the query asks it a second time, for each local
/// ref. With names, one request names each ref and each ref under the id.
#[test]
fn a_query_reads_the_local_refs_of_a_remote_of_the_collection() {
    block_on(async {
        let dir = TmpDir::new("pull-collection-query-own");
        let a = create(dir.path(), "a", Some(ID)).await;
        let stable = commit(&a, dir.path(), "a1", None, REF, FIXED_TS, BOUND).await;
        let next_bind = Bind {
            collection: Some(ID),
            refs: Some(&["os/next"]),
        };
        let next = commit(&a, dir.path(), "a2", None, "os/next", FIXED_TS, next_bind).await;
        let server_a = RepoServer::start(&dir.path().join("a"), false).await;
        let refs = RefSelector::parse(std::iter::empty()).unwrap();
        server_a.tamper(LISTING, repo_listing(&a, &refs, None).await);
        let dest = dest(dir.path(), None, &[("a", &server_a.url(), "")]).await;

        let listed = dest
            .remote_list_collection_refs("a", ID, &[])
            .await
            .unwrap();
        assert_eq!(
            listed,
            [("os/next".to_owned(), next), (REF.to_owned(), stable)]
        );
        assert_eq!(
            server_a.queries_for(LISTING),
            ["pattern=%21%2A%2A&collection=org.example.Os%2F%2A%2A", ""]
        );

        server_a.forget();
        let listed = query(&dest, "a", &[REF, REF]).await.unwrap();
        assert_eq!(listed, [(REF.to_owned(), stable)]);
        assert_eq!(
            server_a.queries_for(LISTING),
            ["pattern=os%2Fstable&collection=org.example.Os%2Fos%2Fstable"]
        );
        assert_nothing_written(&dest).await;
    });
}

/// A remote that answers the listing request with a status from 400 to 499
/// serves no listing, and the query reads the refs from its summary: a
/// static server that answers 404, and a server that answers 400 or 403.
#[test]
fn a_query_with_no_listing_reads_the_summary() {
    block_on(async {
        for status in [404, 400, 403] {
            let dir = TmpDir::new("pull-collection-query-summary");
            let a = create(dir.path(), "a", Some(ID)).await;
            let tip = commit(&a, dir.path(), "a", None, REF, FIXED_TS, BOUND).await;
            summarize(&a).await;
            let server_a = match status {
                404 => RepoServer::start(&dir.path().join("a"), false).await,
                _ => listing_status(&dir.path().join("a"), status).await,
            };
            let dest = dest(dir.path(), None, &[("a", &server_a.url(), "")]).await;

            let listed = query(&dest, "a", &[REF, "os/absent"]).await.unwrap();
            assert_eq!(listed, [(REF.to_owned(), tip)], "{status}");
            assert_eq!(server_a.statuses_for(LISTING), [status]);
            assert_eq!(server_a.seen(), [LISTING, "summary"], "{status}");
        }
    });
}

/// Under a summary policy, the query reads the refs from the verified
/// summary, and sends no listing request. The listing names a newer commit
/// of another repository, and the query gives the commit of the summary. A
/// summary that a key that is not trusted signed, a summary with no
/// `summary.sig`, and a remote with no summary give `Error::Signature`.
#[test]
fn a_query_under_a_summary_policy_reads_the_verified_summary() {
    block_on(async {
        for case in ["trusted", "other key", "no signature", "no summary"] {
            let dir = TmpDir::new("pull-collection-query-policy");
            let a = create(dir.path(), "a", Some(ID)).await;
            let tip = commit(&a, dir.path(), "a", None, REF, FIXED_TS, BOUND).await;
            if case != "no summary" {
                summarize(&a).await;
            }
            let secret = match case {
                "trusted" => Some(SECRET_B64),
                "other key" => Some(OTHER_SECRET_B64),
                _ => None,
            };
            if let Some(secret) = secret {
                let signer = Ed25519Signer::from_base64(secret).unwrap();
                a.sign_summary(&signer).await.unwrap();
            }
            let decoy = create(dir.path(), "decoy", Some(ID)).await;
            commit(&decoy, dir.path(), "d", None, REF, FIXED_TS + 10, BOUND).await;
            let server_a = RepoServer::start(&dir.path().join("a"), false).await;
            serve_listing(&server_a, &decoy, &[REF]).await;
            let policy =
                format!("sign-verify-summary=ed25519\nverification-ed25519-key={PUBLIC_B64}\n");
            let dest = dest(dir.path(), None, &[("a", &server_a.url(), &policy)]).await;

            let listed = query(&dest, "a", &[REF]).await;
            if case == "trusted" {
                assert_eq!(listed.unwrap(), [(REF.to_owned(), tip)]);
                assert_eq!(server_a.requests_for("summary.sig"), 1);
            } else {
                assert!(
                    matches!(listed, Err(Error::Signature(_))),
                    "{case}: {listed:?}"
                );
            }
            assert_eq!(server_a.requests_for(LISTING), 0, "{case}");
            assert_eq!(server_a.requests_for("summary"), 1, "{case}");
        }
    });
}

/// A remote with no listing and no summary gives an empty vector, with a
/// name and with no name. After a write of its summary, the same query
/// gives the ref.
#[test]
fn a_remote_with_no_listing_and_no_summary_gives_no_ref() {
    block_on(async {
        let dir = TmpDir::new("pull-collection-query-none");
        let a = create(dir.path(), "a", Some(ID)).await;
        let tip = commit(&a, dir.path(), "a", None, REF, FIXED_TS, BOUND).await;
        let server_a = RepoServer::start(&dir.path().join("a"), false).await;
        let dest = dest(dir.path(), None, &[("a", &server_a.url(), "")]).await;

        for names in [&[REF][..], &[][..]] {
            server_a.forget();
            assert_eq!(query(&dest, "a", names).await.unwrap(), []);
            assert_eq!(server_a.seen(), [LISTING, "summary"]);
        }
        summarize(&a).await;
        assert_eq!(
            query(&dest, "a", &[REF]).await.unwrap(),
            [(REF.to_owned(), tip)]
        );
    });
}

/// A status from 500 to 599 on the listing, or on the summary of a remote
/// with no listing, is the error of the query.
#[test]
fn a_server_error_fails_the_query() {
    block_on(async {
        for path in [LISTING, "summary"] {
            let dir = TmpDir::new("pull-collection-query-5xx");
            let a = create(dir.path(), "a", Some(ID)).await;
            commit(&a, dir.path(), "a", None, REF, FIXED_TS, BOUND).await;
            summarize(&a).await;
            let server_a = RepoServer::start(&dir.path().join("a"), false).await;
            server_a.answer_status(path, 503);
            let dest = dest(dir.path(), None, &[("a", &server_a.url(), "")]).await;

            let err = query(&dest, "a", &[REF]).await.unwrap_err();
            assert!(
                matches!(err, Error::HttpStatus { status: 503, .. }),
                "{path}: {err:?}"
            );
            assert_eq!(server_a.statuses_for(path), [503]);
        }
    });
}

/// The query reads the summary policy of the remote alone, and no commit
/// policy. A remote with no `gpg-verify` key, whose GPG check of the commits
/// is on, and a remote with `sign-verify=true` and no trusted key list the
/// refs. A remote with a malformed `gpg-verify` value and a remote with a
/// malformed `sign-verify` value also list the refs, in each feature set. A
/// collection pull from the first remote reads its commit policy and fails.
/// A remote whose `trust` names a trust group with the GPG check of the
/// commits keeps its summary policy: the query reads the verified summary,
/// and sends no listing request.
#[test]
fn a_query_reads_no_commit_policy() {
    block_on(async {
        let dir = TmpDir::new("pull-collection-query-commit-policy");
        let a = create(dir.path(), "a", Some(ID)).await;
        let tip = commit(&a, dir.path(), "a", None, REF, FIXED_TS, BOUND).await;
        summarize(&a).await;
        a.sign_summary(&Ed25519Signer::from_base64(SECRET_B64).unwrap())
            .await
            .unwrap();
        let server_a = RepoServer::start(&dir.path().join("a"), false).await;
        drop(create(dir.path(), "dest", None).await);
        let url = server_a.url();
        let dest = reconfigure(
            dir.path(),
            &format!(
                "\n[remote \"gpg\"]\nurl={url}\n\
                 [remote \"sign\"]\nurl={url}\ngpg-verify=false\nsign-verify=true\n\
                 [remote \"bad-gpg\"]\nurl={url}\ngpg-verify=maybe\n\
                 [remote \"bad-sign\"]\nurl={url}\ngpg-verify=false\nsign-verify=\\q\n\
                 [remote \"trust\"]\nurl={url}\ntrust=t\nsign-verify-summary=ed25519\n\
                 verification-ed25519-key={PUBLIC_B64}\n\
                 [ex-ostrya trust \"t\"]\ngpg-verify=true\n"
            ),
        )
        .await;
        let config = dest.config();
        let section = |name| config.section::<remote::Group>(name).unwrap();
        assert!(section("bad-gpg").get::<remote::GpgVerify>().is_err());
        assert!(section("bad-sign").get::<remote::SignVerify>().is_err());

        for remote in ["gpg", "sign", "bad-gpg", "bad-sign"] {
            server_a.forget();
            let listed = query(&dest, remote, &[REF]).await.unwrap();
            assert_eq!(listed, [(REF.to_owned(), tip)], "{remote}");
            assert_eq!(server_a.requests_for(LISTING), 1, "{remote}");
        }
        server_a.forget();
        let listed = query(&dest, "trust", &[REF]).await.unwrap();
        assert_eq!(listed, [(REF.to_owned(), tip)]);
        assert_eq!(server_a.requests_for(LISTING), 0);
        assert_eq!(server_a.requests_for("summary.sig"), 1);

        let (opts, _) = options(&[REF]);
        assert!(dest.pull_collection(ID, &["gpg"], opts).await.is_err());
        assert_nothing_written(&dest).await;
    });
}

/// A remote at a closed port gives the transport error of the request. The
/// query makes no retry.
#[test]
fn a_closed_port_fails_the_query() {
    block_on(async {
        let dir = TmpDir::new("pull-collection-query-closed");
        let port = std::net::TcpListener::bind("127.0.0.1:0")
            .unwrap()
            .local_addr()
            .unwrap()
            .port();
        let url = format!("http://127.0.0.1:{port}/");
        let dest = dest(dir.path(), None, &[("a", &url, "")]).await;

        let err = query(&dest, "a", &[REF]).await.unwrap_err();
        assert!(matches!(err, Error::Fetch(_)), "{err:?}");
    });
}

/// A remote at a `file://` address is a local repository, and the query
/// reads its ref files. The query returns each error of the local
/// repository unchanged: a path with no repository, a ref whose commit the
/// repository does not hold, and a summary policy with no summary. A host
/// part in the address stops the query before it opens the path.
#[test]
fn a_query_reads_a_file_remote() {
    block_on(async {
        let dir = TmpDir::new("pull-collection-query-file");
        let a = create(dir.path(), "a", Some(OTHER)).await;
        let stable = commit(
            &a,
            dir.path(),
            "a1",
            Some(ID),
            REF,
            FIXED_TS,
            COLLECTION_ONLY,
        )
        .await;
        let next = commit(
            &a,
            dir.path(),
            "a2",
            Some(ID),
            "os/next",
            FIXED_TS,
            COLLECTION_ONLY,
        )
        .await;
        commit(
            &a,
            dir.path(),
            "a3",
            None,
            "local",
            FIXED_TS,
            COLLECTION_ONLY,
        )
        .await;
        let missing = dir.path().join("missing");
        let policy =
            format!("sign-verify-summary=ed25519\nverification-ed25519-key={PUBLIC_B64}\n");
        let host = format!("file://host{}", dir.path().join("a").display());
        let dest = dest(
            dir.path(),
            None,
            &[
                ("a", &file_url(dir.path(), "a"), ""),
                ("missing", &file_url(dir.path(), "missing"), ""),
                ("signed", &file_url(dir.path(), "a"), &policy),
                ("host", &host, ""),
            ],
        )
        .await;

        let listed = dest
            .remote_list_collection_refs("a", ID, &[])
            .await
            .unwrap();
        assert_eq!(
            listed,
            [("os/next".to_owned(), next), (REF.to_owned(), stable)]
        );
        let listed = query(&dest, "a", &[REF, "os/absent"]).await.unwrap();
        assert_eq!(listed, [(REF.to_owned(), stable)]);

        let err = query(&dest, "missing", &[REF]).await.unwrap_err();
        let opened = Repo::open(&missing).await.unwrap_err();
        assert_eq!(err.to_string(), opened.to_string());
        let err = query(&dest, "signed", &[REF]).await.unwrap_err();
        assert!(matches!(err, Error::Signature(_)), "{err:?}");
        let err = query(&dest, "host", &[REF]).await.unwrap_err();
        assert!(
            matches!(&err, Error::Pull(m) if m.contains("names a host")),
            "{err:?}"
        );

        let ghost = dir.path().join("a/refs/mirrors").join(ID).join("os/ghost");
        std::fs::write(&ghost, format!("{}\n", "ab".repeat(32))).unwrap();
        let err = query(&dest, "a", &["os/ghost"]).await.unwrap_err();
        assert!(matches!(err, Error::ObjectNotFound { .. }), "{err:?}");
        std::fs::remove_file(&ghost).unwrap();
        assert_nothing_written(&dest).await;
    });
}

/// The query of 300 names of a local repository reads the ref of each name,
/// under the collection id of the repository and under another id.
#[test]
fn a_file_query_of_300_names_reads_each_ref() {
    block_on(async {
        let dir = TmpDir::new("pull-collection-query-file-many");
        let a = create(dir.path(), "a", Some(OTHER)).await;
        let tip = commit(
            &a,
            dir.path(),
            "a",
            Some(ID),
            "pool/n000",
            FIXED_TS,
            COLLECTION_ONLY,
        )
        .await;
        let names: Vec<String> = (0..300).map(|n| format!("pool/n{n:03}")).collect();
        let txn = a.transaction().await.unwrap();
        for name in &names {
            txn.set_ref(&Ref::collection(ID, name), Some(&tip));
            txn.set_ref(&Ref::local(name), Some(&tip));
        }
        txn.commit().await.unwrap();
        let dest = dest(dir.path(), None, &[("a", &file_url(dir.path(), "a"), "")]).await;

        let mut asked: Vec<&str> = names.iter().rev().map(String::as_str).collect();
        asked.push("pool/absent");
        let expected: Vec<(String, Checksum)> =
            names.iter().map(|name| (name.clone(), tip)).collect();
        for id in [ID, OTHER] {
            let listed = dest
                .remote_list_collection_refs_with("a", id, &asked, no_retry(), None)
                .await
                .unwrap();
            assert_eq!(listed, expected, "{id}");
        }
    });
}

/// A directory inside the selection that the query cannot read gives
/// `Error::Io`. A directory outside the selection that it cannot read fails
/// nothing. The test skips, with a message, for a user that ignores the
/// mode.
#[test]
fn an_unreadable_directory_fails_a_file_query_only_inside_the_selection() {
    block_on(async {
        let dir = TmpDir::new("pull-collection-query-file-perm");
        let a = create(dir.path(), "a", Some(OTHER)).await;
        let pool = commit(
            &a,
            dir.path(),
            "a1",
            Some(ID),
            "pool/x",
            FIXED_TS,
            COLLECTION_ONLY,
        )
        .await;
        commit(
            &a,
            dir.path(),
            "a2",
            Some(ID),
            "builds/locked/y",
            FIXED_TS,
            COLLECTION_ONLY,
        )
        .await;
        let dest = dest(dir.path(), None, &[("a", &file_url(dir.path(), "a"), "")]).await;
        let locked = dir
            .path()
            .join("a/refs/mirrors")
            .join(ID)
            .join("builds/locked");
        if !lock(&locked, 0o000, 0o755) {
            return;
        }
        let named = query(&dest, "a", &["pool/x"]).await;
        let all = query(&dest, "a", &[]).await;
        unlock(&locked, 0o755);

        assert_eq!(named.unwrap(), [("pool/x".to_owned(), pool)]);
        assert!(matches!(all, Err(Error::Io(_))), "{all:?}");
    });
}

/// The query refuses a bad collection id, a bad ref name, a name that no
/// listing request can hold, and a `url` override before its first request.
/// With a `file://` remote, it refuses a field of another transport.
#[test]
fn a_query_refuses_bad_arguments_before_the_first_request() {
    block_on(async {
        let dir = TmpDir::new("pull-collection-query-refusals");
        let a = create(dir.path(), "a", Some(ID)).await;
        commit(&a, dir.path(), "a", None, REF, FIXED_TS, BOUND).await;
        summarize(&a).await;
        let server_a = RepoServer::start(&dir.path().join("a"), false).await;
        let dest = dest(
            dir.path(),
            None,
            &[
                ("a", &server_a.url(), ""),
                ("b", &file_url(dir.path(), "a"), ""),
            ],
        )
        .await;

        let long_id = "a.b".repeat(100);
        let long_name = "x".repeat(4090);
        let url = EndpointOverrides {
            url: Some(server_a.url()),
            ..EndpointOverrides::default()
        };
        let header = EndpointOverrides {
            http_headers: vec![("X-A".to_owned(), "b".to_owned())],
            ..EndpointOverrides::default()
        };
        let cases: Vec<(&str, &str, &str, Vec<&str>, EndpointOverrides)> = vec![
            ("invalid id", "a", "fresh", vec![REF], no_retry()),
            ("long id", "a", &long_id, vec![REF], no_retry()),
            ("ref name", "a", ID, vec![REF, "a:b"], no_retry()),
            ("long ref name", "a", ID, vec![REF, &long_name], no_retry()),
            ("url", "a", ID, vec![REF], url),
            ("header", "b", ID, vec![REF], header),
        ];
        for (tag, remote, id, names, overrides) in cases {
            let err = dest
                .remote_list_collection_refs_with(remote, id, &names, overrides, None)
                .await
                .unwrap_err();
            let expected = match tag {
                "ref name" => matches!(err, Error::InvalidRefspec(_)),
                "header" => matches!(&err, Error::InvalidInput(m) if m.starts_with("http-header")),
                _ => matches!(err, Error::InvalidInput(_)),
            };
            assert!(expected, "{tag}: {err:?}");
            assert!(server_a.seen().is_empty(), "{tag}: {:?}", server_a.seen());
        }
    });
}

// --- interoperability with the `ostree` command ------------------------------

/// The pull reads the summaries that the `ostree` command writes: field 0 of
/// a repository whose collection id is the pulled id, and the collection map
/// of a repository with another id. The tool then lists the pulled
/// collection refs and passes fsck on the destination.
#[test]
fn the_pull_reads_the_summaries_of_the_tool() {
    if !common::ostree_available() {
        eprintln!("skipped: `ostree` is not installed");
        return;
    }
    block_on(async {
        let dir = TmpDir::new("pull-collection-tool");
        let root = dir.path();
        let repo = |name: &str| format!("--repo={}", root.join(name).display());
        let tree = |name: &str, text: &str| {
            let path = root.join(name);
            std::fs::create_dir_all(path.join("dir")).unwrap();
            std::fs::write(path.join("a"), text).unwrap();
            std::fs::write(path.join("dir/b"), b"beta\n").unwrap();
            path.display().to_string()
        };
        let checksum = |out: Vec<u8>| String::from_utf8(out).unwrap().trim().to_owned();
        let collection = format!("--collection-id={ID}");
        let other = format!("--collection-id={OTHER}");

        // `a` has the collection id, and lists the refs in field 0.
        ostree(&[&repo("a"), "init", "--mode=archive", &collection]);
        let older = checksum(ostree(&[
            &repo("a"),
            "commit",
            &format!("--branch={REF}"),
            "--timestamp=@1700000000",
            "-s",
            "older",
            &tree("t1", "one\n"),
        ]));
        let next = checksum(ostree(&[
            &repo("a"),
            "commit",
            "--branch=os/next",
            "--timestamp=@1700000000",
            "-s",
            "next",
            &tree("t2", "two\n"),
        ]));
        ostree(&[&repo("a"), "summary", "-u"]);

        // `b` has another id, and lists the newer commit in its collection
        // map. The commit comes from a scratch repository of the collection,
        // so it is bound to the collection.
        ostree(&[&repo("scratch"), "init", "--mode=archive", &collection]);
        let newer = checksum(ostree(&[
            &repo("scratch"),
            "commit",
            &format!("--branch={REF}"),
            "--timestamp=@1700000100",
            "-s",
            "newer",
            &tree("t3", "three\n"),
        ]));
        ostree(&[&repo("b"), "init", "--mode=archive", &other]);
        let scratch = root.join("scratch").display().to_string();
        ostree(&[&repo("b"), "pull-local", &scratch, REF]);
        ostree(&[
            &repo("b"),
            "refs",
            "--collections",
            &format!("--create={ID}:{REF}"),
            &newer,
        ]);
        ostree(&[&repo("b"), "refs", "--delete", REF]);
        ostree(&[&repo("b"), "summary", "-u"]);

        let server_a = RepoServer::start(&root.join("a"), false).await;
        let server_b = RepoServer::start(&root.join("b"), false).await;
        let dest = dest(
            root,
            None,
            &[("a", &server_a.url(), ""), ("b", &server_b.url(), "")],
        )
        .await;
        let (opts, events) = options(&[REF, "os/next"]);
        let pulled = dest.pull_collection(ID, &["a", "b"], opts).await.unwrap();
        assert!(events.lock().unwrap().is_empty());
        let selected: Vec<(&str, &str)> = pulled
            .refs
            .iter()
            .map(|r| (r.name.as_str(), r.remote.as_str()))
            .collect();
        assert_eq!(selected, [(REF, "b"), ("os/next", "a")]);
        assert_eq!(mirror(&dest, REF).await.unwrap().to_hex(), newer);
        assert_eq!(mirror(&dest, "os/next").await.unwrap().to_hex(), next);
        assert_ne!(older, newer);

        let listed = String::from_utf8(ostree(&[&repo("dest"), "refs", "--collections"])).unwrap();
        let mut lines: Vec<&str> = listed.lines().collect();
        lines.sort_unstable();
        assert_eq!(
            lines,
            [
                format!("({ID}, os/next)").as_str(),
                format!("({ID}, {REF})").as_str()
            ]
        );
        common::tool_fsck(&root.join("dest"));
    });
}

// --- bucket repositories -----------------------------------------------------

/// The pull of collection refs from bucket repositories at `s3://`
/// addresses.
///
/// Most cases serve the bucket `bkt` from the S3 stand-in of
/// `common/s3.rs`, which accepts each signature and keeps each request. Two
/// cases serve it from `rclone serve s3`, which checks each signature. A
/// case copies the files of a local `archive` repository, its summary
/// included, into the bucket.
///
/// `Repo::pull_collection` reads the key pair from the environment of the
/// process. So each test runs its case in a child process of this test
/// binary, which gets the key pair, the two shared AWS files at absent
/// paths, no other AWS variable, and no proxy variable. The rclone cases
/// skip when `rclone` is absent, and `OSTRYA_REQUIRE_S3` turns the skip into
/// a failure.
#[cfg(feature = "s3")]
mod s3_remote {
    use std::path::Path;
    use std::process::Command;
    use std::sync::atomic::{AtomicU64, Ordering};
    use std::time::Duration;

    use ostrya::PullProgress;

    use super::*;
    use crate::common::s3::{ACCESS_KEY, Rclone, SECRET_KEY, StandIn, rclone_available};

    /// The variable that names the case of the child process.
    const CASE: &str = "OSTRYA_TEST_S3_CASE";

    /// The proxy variables that the fetcher reads. The child process gets
    /// none of them, so it connects to the server directly.
    const PROXY_VARIABLES: [&str; 7] = [
        "http_proxy",
        "HTTP_PROXY",
        "https_proxy",
        "HTTPS_PROXY",
        "all_proxy",
        "ALL_PROXY",
        "no_proxy",
    ];

    /// The request target of a key of the bucket repository `s3://bkt/repo`
    /// on the stand-in.
    fn target(key: &str) -> String {
        format!("/bkt/repo/{key}")
    }

    /// Runs the case `case` in a child process with the secret key `secret`.
    fn run_case(case: &str, secret: &str) {
        let scratch = TmpDir::new("pull-collection-s3-env");
        let mut child = Command::new(std::env::current_exe().unwrap());
        child
            .args([
                "s3_remote::subprocess",
                "--exact",
                "--ignored",
                "--nocapture",
            ])
            .env(CASE, case)
            .env("AWS_ACCESS_KEY_ID", ACCESS_KEY)
            .env("AWS_SECRET_ACCESS_KEY", secret)
            .env("AWS_CONFIG_FILE", scratch.path().join("absent-aws-config"))
            .env(
                "AWS_SHARED_CREDENTIALS_FILE",
                scratch.path().join("absent-aws-credentials"),
            );
        for (name, _) in std::env::vars_os() {
            let text = name.to_string_lossy();
            if text.starts_with("AWS_") && !child.get_envs().any(|(set, _)| set == name) {
                child.env_remove(&name);
            }
        }
        for name in PROXY_VARIABLES {
            child.env_remove(name);
        }
        let output = child.output().expect("re-execute this test binary");
        let stdout = String::from_utf8_lossy(&output.stdout);
        assert!(
            output.status.success() && stdout.contains("1 passed"),
            "the child of the case {case} reported {}:\n{stdout}{}",
            output.status,
            String::from_utf8_lossy(&output.stderr),
        );
    }

    /// Runs a case of a test of this module.
    ///
    /// This test does its work only when a test of this module runs this
    /// binary again with the variables set.
    #[test]
    #[ignore = "helper process for the tests of bucket repositories"]
    fn subprocess() {
        let Some(case) = std::env::var_os(CASE) else {
            return;
        };
        block_on(async {
            match case.to_str().unwrap() {
                "collection-map" => collection_map().await,
                "field-0" => field_0().await,
                "live-count" => live_count().await,
                "across-transports" => across_transports().await,
                "no-summary" => no_summary().await,
                "summary-policy" => summary_policy().await,
                "stale-summary" => stale_summary().await,
                "absent-bucket" => absent_bucket().await,
                "rclone" => rclone(false).await,
                "rclone-wrong-secret" => rclone(true).await,
                "query" => query_bucket().await,
                "rclone-query" => rclone_query().await,
                other => panic!("unknown case {other}"),
            }
        });
    }

    /// Stores each file under the directory `dir` in `server`, at its path
    /// under `dir` with the prefix `repo/`.
    fn store_tree(server: &StandIn, dir: &Path) {
        let mut pending = vec![dir.to_path_buf()];
        while let Some(at) = pending.pop() {
            for entry in std::fs::read_dir(&at).unwrap() {
                let path = entry.unwrap().path();
                if path.is_dir() {
                    pending.push(path);
                } else {
                    let key = path.strip_prefix(dir).unwrap().to_str().unwrap();
                    let bytes = std::fs::read(&path).unwrap();
                    server.state().store(&format!("repo/{key}"), &bytes);
                }
            }
        }
    }

    /// Returns the keys of a remote at the address `address` on the server
    /// at `url`.
    fn bucket(url: &str, address: &str) -> String {
        format!("pull-url={address}\ns3-endpoint={url}\n")
    }

    /// Creates the destination repository at `dir/name`, with the collection
    /// id `own` and the remotes `remotes`: each a name and its keys.
    async fn bucket_dest(
        dir: &Path,
        name: &str,
        own: Option<&str>,
        remotes: &[(&str, &str)],
    ) -> Repo {
        drop(create(dir, name, own).await);
        let config = dir.join(name).join("config");
        let mut text = std::fs::read_to_string(&config).unwrap();
        for (remote, keys) in remotes {
            text.push_str(&format!(
                "\n[remote \"{remote}\"]\ngpg-verify=false\ncollection-id={ID}\n{keys}"
            ));
        }
        std::fs::write(&config, text).unwrap();
        Repo::open(&dir.join(name)).await.unwrap()
    }

    /// Returns the options of [`options`] that allow the `http://`
    /// endpoint of the server.
    fn bucket_options(
        refs: &[&str],
    ) -> (CollectionPullOptions, Arc<Mutex<Vec<CollectionPullEvent>>>) {
        let (mut opts, events) = options(refs);
        opts.pull.overrides.allow_cleartext_credentials = true;
        (opts, events)
    }

    /// Asserts that each request to `server` is signed, and that no request
    /// asks for the ref listing.
    fn assert_signed_with_no_listing(server: &StandIn) {
        let state = server.state();
        assert!(state.authorizations.iter().all(Option::is_some));
        assert!(
            !state
                .requests
                .iter()
                .any(|(_, target)| target.contains(LISTING)),
            "{:?}",
            state.requests
        );
    }

    /// Returns the number of requests to `server` for the key `key` of the
    /// bucket repository.
    fn requests_for(server: &StandIn, key: &str) -> usize {
        let wanted = target(key);
        server
            .state()
            .requests
            .iter()
            .filter(|(_, target)| *target == wanted)
            .count()
    }

    /// Returns `true` if `server` received a request for an object of the
    /// bucket repository.
    fn bucket_objects_requested(server: &StandIn) -> bool {
        let objects = target("objects/");
        server
            .state()
            .requests
            .iter()
            .any(|(_, target)| target.starts_with(&objects))
    }

    /// Returns the single skip event of `events`, as the remote and the
    /// message.
    fn skipped(events: &Mutex<Vec<CollectionPullEvent>>) -> (String, String) {
        let events = events.lock().unwrap();
        match &events[..] {
            [
                CollectionPullEvent::RemoteSkipped {
                    remote, message, ..
                },
            ] => (remote.clone(), message.clone()),
            other => panic!("{other:?}"),
        }
    }

    /// A bucket repository with no collection id holds the ref of the
    /// collection under `refs/mirrors/ID/`, and its summary lists it in the
    /// collection map. A pull of the named ref and a pull of each ref read
    /// the summary alone, then the `config`, and write the collection ref.
    #[test]
    fn a_bucket_serves_the_refs_of_its_collection_map() {
        run_case("collection-map", SECRET_KEY);
    }

    async fn collection_map() {
        let dir = TmpDir::new("pull-collection-s3-map");
        let source = create(dir.path(), "source", None).await;
        let tip = commit(&source, dir.path(), "a", Some(ID), REF, FIXED_TS, BOUND).await;
        summarize(&source).await;
        for refs in [&[REF][..], &[]] {
            let server = StandIn::start();
            store_tree(&server, &dir.path().join("source"));
            let keys = bucket(&server.endpoint(), "s3://bkt/repo");
            let name = format!("dest-{}", refs.len());
            let dest = bucket_dest(dir.path(), &name, None, &[("bkt", &keys)]).await;
            let (opts, events) = bucket_options(refs);
            let pulled = dest.pull_collection(ID, &["bkt"], opts).await.unwrap();
            assert!(events.lock().unwrap().is_empty());
            assert_eq!(pulled.refs.len(), 1);
            assert_eq!(pulled.refs[0].remote, "bkt");
            assert_eq!(pulled.refs[0].commit, tip);
            assert_eq!(pulled.refs[0].timestamp, FIXED_TS);
            assert_eq!(mirror(&dest, REF).await, Some(tip));
            assert!(dest.list_refs(None).await.unwrap().is_empty());
            assert!(dest.fsck(&FsckOptions::default()).await.unwrap().is_ok());
            let requests = server.state().requests.clone();
            assert_eq!(
                requests[..2],
                [
                    ("GET".to_owned(), target("summary")),
                    ("GET".to_owned(), target("config")),
                ]
            );
            assert_eq!(requests_for(&server, "summary.sig"), 0);
            assert_eq!(requests_for(&server, "summary"), 1);
            assert_signed_with_no_listing(&server);
        }
    }

    /// A bucket repository whose summary states the collection id lists the
    /// refs of the collection in field 0. A destination of the same
    /// collection writes the local ref.
    #[test]
    fn a_bucket_of_the_collection_serves_field_0() {
        run_case("field-0", SECRET_KEY);
    }

    async fn field_0() {
        let dir = TmpDir::new("pull-collection-s3-field-0");
        let source = create(dir.path(), "source", Some(ID)).await;
        let tip = commit(&source, dir.path(), "a", None, REF, FIXED_TS, BOUND).await;
        summarize(&source).await;
        let server = StandIn::start();
        store_tree(&server, &dir.path().join("source"));
        let keys = bucket(&server.endpoint(), "s3://bkt/repo");
        let dest = bucket_dest(dir.path(), "dest", Some(ID), &[("bkt", &keys)]).await;
        let (opts, events) = bucket_options(&[REF]);
        let pulled = dest.pull_collection(ID, &["bkt"], opts).await.unwrap();
        assert!(events.lock().unwrap().is_empty());
        assert_eq!(pulled.refs[0].commit, tip);
        assert_eq!(dest.resolve_rev(REF, false).await.unwrap(), Some(tip));
        assert!(dest.list_mirror_refs().await.unwrap().is_empty());
        assert_signed_with_no_listing(&server);
    }

    /// The live count of a pull from a bucket repository includes the bytes
    /// of `summary` and `summary.sig` until the pull reads the `config`, as
    /// over HTTP. The count of the stats starts after the root files.
    #[test]
    fn the_live_count_of_a_bucket_pull_includes_the_summary() {
        run_case("live-count", SECRET_KEY);
    }

    async fn live_count() {
        let dir = TmpDir::new("pull-collection-s3-live-count");
        let source = create(dir.path(), "source", Some(ID)).await;
        let tip = commit(&source, dir.path(), "a", None, REF, FIXED_TS, BOUND).await;
        summarize(&source).await;
        let signer = Ed25519Signer::from_base64(SECRET_B64).unwrap();
        source.sign_summary(&signer).await.unwrap();
        let server = StandIn::start();
        store_tree(&server, &dir.path().join("source"));
        let keys = bucket(&server.endpoint(), "s3://bkt/repo");
        let dest = bucket_dest(dir.path(), "dest", Some(ID), &[("bkt", &keys)]).await;
        let progress = PullProgress::new();
        let at_config = Arc::new(AtomicU64::new(u64::MAX));
        let root = {
            let mut state = server.state();
            let (seen, stored) = (progress.clone(), Arc::clone(&at_config));
            state.before_key = Some((
                "GET",
                "repo/config".to_owned(),
                Box::new(move |_| {
                    stored.store(seen.snapshot().bytes_transferred, Ordering::Relaxed);
                }),
            ));
            state.objects["repo/summary"].bytes.len()
                + state.objects["repo/summary.sig"].bytes.len()
        };
        let stats = dest
            .pull(
                "bkt",
                PullOptions {
                    refs: vec![REF.to_owned()],
                    progress: Some(progress.clone()),
                    overrides: EndpointOverrides {
                        allow_cleartext_credentials: true,
                        ..EndpointOverrides::default()
                    },
                    ..PullOptions::default()
                },
            )
            .await
            .unwrap();
        assert_eq!(
            dest.resolve_rev(&format!("bkt:{REF}"), false)
                .await
                .unwrap(),
            Some(tip)
        );
        assert_eq!(at_config.load(Ordering::Relaxed), root as u64);
        assert_eq!(
            progress.snapshot().bytes_transferred,
            stats.bytes_transferred
        );
        assert_signed_with_no_listing(&server);
    }

    /// An HTTP remote and a bucket repository serve the collection. The
    /// newest commit wins across the two transports, and the pull takes the
    /// objects from the selected remote alone.
    #[test]
    fn the_newest_commit_wins_across_http_and_s3() {
        run_case("across-transports", SECRET_KEY);
    }

    async fn across_transports() {
        for bucket_newer in [true, false] {
            let dir = TmpDir::new("pull-collection-s3-across");
            let (http_ts, bucket_ts) = if bucket_newer {
                (FIXED_TS, FIXED_TS + 10)
            } else {
                (FIXED_TS + 10, FIXED_TS)
            };
            let a = create(dir.path(), "a", Some(ID)).await;
            let http_tip = commit(&a, dir.path(), "a", None, REF, http_ts, BOUND).await;
            summarize(&a).await;
            let source = create(dir.path(), "source", None).await;
            let bucket_tip =
                commit(&source, dir.path(), "b", Some(ID), REF, bucket_ts, BOUND).await;
            summarize(&source).await;
            let server_a = RepoServer::start(&dir.path().join("a"), false).await;
            let server = StandIn::start();
            store_tree(&server, &dir.path().join("source"));
            let http = format!("url={}\n", server_a.url());
            let keys = bucket(&server.endpoint(), "s3://bkt/repo");
            let dest = bucket_dest(dir.path(), "dest", None, &[("a", &http), ("bkt", &keys)]).await;
            let (opts, events) = bucket_options(&[REF]);
            let pulled = dest.pull_collection(ID, &["a", "bkt"], opts).await.unwrap();
            assert!(events.lock().unwrap().is_empty());
            let (winner, tip) = if bucket_newer {
                ("bkt", bucket_tip)
            } else {
                ("a", http_tip)
            };
            assert_eq!(pulled.refs[0].remote, winner);
            assert_eq!(mirror(&dest, REF).await, Some(tip));
            assert_eq!(objects_requested(&server_a), !bucket_newer);
            assert_eq!(bucket_objects_requested(&server), bucket_newer);
            assert_signed_with_no_listing(&server);
        }
    }

    /// A bucket repository with no `summary` fails the probe, and the next
    /// remote serves the ref. A bucket repository alone with no `summary`
    /// fails the pull before an object request, and the pull writes nothing.
    #[test]
    fn a_bucket_with_no_summary_is_skipped() {
        run_case("no-summary", SECRET_KEY);
    }

    async fn no_summary() {
        let dir = TmpDir::new("pull-collection-s3-no-summary");
        let source = create(dir.path(), "source", None).await;
        commit(
            &source,
            dir.path(),
            "b",
            Some(ID),
            REF,
            FIXED_TS + 10,
            BOUND,
        )
        .await;
        let a = create(dir.path(), "a", Some(ID)).await;
        let tip = commit(&a, dir.path(), "a", None, REF, FIXED_TS, BOUND).await;
        summarize(&a).await;
        let server_a = RepoServer::start(&dir.path().join("a"), false).await;
        let server = StandIn::start();
        store_tree(&server, &dir.path().join("source"));
        let http = format!("url={}\n", server_a.url());
        let keys = bucket(&server.endpoint(), "s3://bkt/repo");

        let dest = bucket_dest(dir.path(), "dest", None, &[("bkt", &keys), ("a", &http)]).await;
        let (opts, events) = bucket_options(&[REF]);
        let pulled = dest.pull_collection(ID, &["bkt", "a"], opts).await.unwrap();
        assert_eq!(pulled.refs[0].remote, "a");
        assert_eq!(mirror(&dest, REF).await, Some(tip));
        let (remote, message) = skipped(&events);
        assert_eq!(remote, "bkt");
        assert!(
            message.contains("the bucket repository has no summary"),
            "{message}"
        );

        let alone = bucket_dest(dir.path(), "alone", None, &[("bkt", &keys)]).await;
        let (opts, events) = bucket_options(&[REF]);
        let err = alone.pull_collection(ID, &["bkt"], opts).await.unwrap_err();
        assert!(matches!(err, Error::Pull(_)), "{err:?}");
        assert_eq!(skipped(&events).0, "bkt");
        assert_nothing_written(&alone).await;
        assert!(!bucket_objects_requested(&server));
        assert_signed_with_no_listing(&server);
    }

    /// Under a summary policy, the pull reads `summary.sig` and `summary`
    /// through the bucket client, and verifies the summary. The two requests
    /// are in flight together: in the first pull, the server waits before it
    /// answers `summary.sig`, and logs `summary` first. The pull asks for
    /// `summary.sig` first: in the second pull, with a fetch limit of one,
    /// the server logs `summary.sig` first. A summary that an untrusted key
    /// signed, and a summary with no `summary.sig`, skip the bucket
    /// repository.
    #[test]
    fn a_summary_policy_verifies_the_summary_of_a_bucket() {
        run_case("summary-policy", SECRET_KEY);
    }

    async fn summary_policy() {
        for signer in [Some(SECRET_B64), Some(OTHER_SECRET_B64), None] {
            let dir = TmpDir::new("pull-collection-s3-policy");
            let source = create(dir.path(), "source", None).await;
            let tip = commit(&source, dir.path(), "a", Some(ID), REF, FIXED_TS, BOUND).await;
            summarize(&source).await;
            if let Some(secret) = signer {
                let signer = Ed25519Signer::from_base64(secret).unwrap();
                source.sign_summary(&signer).await.unwrap();
            }
            let server = StandIn::start();
            store_tree(&server, &dir.path().join("source"));
            if signer == Some(SECRET_B64) {
                server.state().delay = Some((
                    "GET",
                    "repo/summary.sig".to_owned(),
                    Duration::from_millis(500),
                ));
            }
            let keys = format!(
                "{}sign-verify-summary=ed25519\nverification-ed25519-key={PUBLIC_B64}\n",
                bucket(&server.endpoint(), "s3://bkt/repo")
            );
            let dest = bucket_dest(dir.path(), "dest", None, &[("bkt", &keys)]).await;
            let (mut opts, events) = bucket_options(&[REF]);
            if signer == Some(OTHER_SECRET_B64) {
                opts.pull.max_outstanding_fetches = Some(1);
            }
            let pulled = dest.pull_collection(ID, &["bkt"], opts).await;
            let requests = server.state().requests.clone();
            let summary = ("GET".to_owned(), target("summary"));
            let signature = ("GET".to_owned(), target("summary.sig"));
            let mut first = requests[..2].to_vec();
            if signer == Some(SECRET_B64) {
                assert_eq!(first, [summary, signature]);
            } else if signer == Some(OTHER_SECRET_B64) {
                assert_eq!(first, [signature, summary]);
            } else {
                first.sort();
                assert_eq!(first, [summary, signature]);
            }
            if signer == Some(SECRET_B64) {
                let pulled = pulled.unwrap();
                assert!(events.lock().unwrap().is_empty());
                assert_eq!(pulled.refs[0].commit, tip);
                assert_eq!(mirror(&dest, REF).await, Some(tip));
                assert_eq!(requests_for(&server, "summary.sig"), 1);
                assert_eq!(requests_for(&server, "summary"), 1);
            } else {
                assert!(matches!(pulled, Err(Error::Pull(_))), "{pulled:?}");
                assert_eq!(skipped(&events).0, "bkt");
                assert_nothing_written(&dest).await;
                assert!(!bucket_objects_requested(&server));
            }
            assert_signed_with_no_listing(&server);
        }
    }

    /// A ref file of the bucket repository that names a newer commit than
    /// its summary: the pull takes the commit of the summary, and reads no
    /// ref file.
    #[test]
    fn a_stale_summary_gives_the_commit_of_the_summary() {
        run_case("stale-summary", SECRET_KEY);
    }

    async fn stale_summary() {
        let dir = TmpDir::new("pull-collection-s3-stale");
        let source = create(dir.path(), "source", None).await;
        let old = commit(&source, dir.path(), "a", Some(ID), REF, FIXED_TS, BOUND).await;
        summarize(&source).await;
        let new = commit(
            &source,
            dir.path(),
            "b",
            Some(ID),
            REF,
            FIXED_TS + 10,
            BOUND,
        )
        .await;
        let server = StandIn::start();
        store_tree(&server, &dir.path().join("source"));
        assert_eq!(
            server.state().objects[&format!("repo/refs/mirrors/{ID}/{REF}")].bytes,
            format!("{new}\n").into_bytes()
        );
        let keys = bucket(&server.endpoint(), "s3://bkt/repo");
        let dest = bucket_dest(dir.path(), "dest", None, &[("bkt", &keys)]).await;
        let (opts, _) = bucket_options(&[REF]);
        let pulled = dest.pull_collection(ID, &["bkt"], opts).await.unwrap();
        assert_eq!(pulled.refs[0].commit, old);
        assert_eq!(mirror(&dest, REF).await, Some(old));
        let refs = target("refs/");
        assert!(
            !server
                .state()
                .requests
                .iter()
                .any(|(_, target)| target.starts_with(&refs))
        );
    }

    /// A remote whose bucket the server does not hold is skipped with the S3
    /// code `NoSuchBucket`, which the bucket client reads, and the next
    /// remote serves the ref.
    #[test]
    fn an_absent_bucket_is_skipped_with_the_s3_error() {
        run_case("absent-bucket", SECRET_KEY);
    }

    async fn absent_bucket() {
        let dir = TmpDir::new("pull-collection-s3-absent");
        let source = create(dir.path(), "source", None).await;
        let tip = commit(&source, dir.path(), "a", Some(ID), REF, FIXED_TS, BOUND).await;
        summarize(&source).await;
        let server = StandIn::start();
        store_tree(&server, &dir.path().join("source"));
        let gone = bucket(&server.endpoint(), "s3://other/repo");
        let keys = bucket(&server.endpoint(), "s3://bkt/repo");
        let dest = bucket_dest(dir.path(), "dest", None, &[("gone", &gone), ("bkt", &keys)]).await;
        let (opts, events) = bucket_options(&[REF]);
        let pulled = dest
            .pull_collection(ID, &["gone", "bkt"], opts)
            .await
            .unwrap();
        assert_eq!(pulled.refs[0].remote, "bkt");
        assert_eq!(mirror(&dest, REF).await, Some(tip));
        let (remote, message) = skipped(&events);
        assert_eq!(remote, "gone");
        assert!(message.contains("NoSuchBucket"), "{message}");
        assert_signed_with_no_listing(&server);
    }

    /// `rclone serve s3` checks the signature of each request. The pull
    /// reads the collection map of the summary of a bucket directory, and
    /// writes the collection ref. A wrong secret key skips the remote with
    /// the S3 code `SignatureDoesNotMatch`, and the pull writes nothing.
    #[test]
    fn a_bucket_on_rclone_serves_the_refs_of_a_collection() {
        if !rclone_available("a_bucket_on_rclone_serves_the_refs_of_a_collection") {
            return;
        }
        run_case("rclone", SECRET_KEY);
        run_case("rclone-wrong-secret", "wrong-secret-key");
    }

    async fn rclone(wrong_secret: bool) {
        let dir = TmpDir::new("pull-collection-s3-rclone");
        let source = create(dir.path(), "source", None).await;
        let tip = commit(&source, dir.path(), "a", Some(ID), REF, FIXED_TS, BOUND).await;
        summarize(&source).await;
        drop(source);
        // rclone keeps the listing of each directory, so the files of the
        // bucket directory are in place before the server starts.
        let root = dir.path().join("root");
        std::fs::create_dir_all(root.join("bkt")).unwrap();
        let status = Command::new("cp")
            .arg("-r")
            .arg(dir.path().join("source"))
            .arg(root.join("bkt").join("repo"))
            .status()
            .unwrap();
        assert!(status.success(), "cp -r");
        let server = Rclone::start(dir.path(), &root);
        let keys = bucket(&server.endpoint(), "s3://bkt/repo");
        let dest = bucket_dest(dir.path(), "dest", None, &[("bkt", &keys)]).await;
        let (opts, events) = bucket_options(&[REF]);
        let pulled = dest.pull_collection(ID, &["bkt"], opts).await;
        if wrong_secret {
            assert!(matches!(pulled, Err(Error::Pull(_))), "{pulled:?}");
            let (remote, message) = skipped(&events);
            assert_eq!(remote, "bkt");
            assert!(message.contains("SignatureDoesNotMatch"), "{message}");
            assert_nothing_written(&dest).await;
        } else {
            let pulled = pulled.unwrap();
            assert!(events.lock().unwrap().is_empty());
            assert_eq!(pulled.refs[0].commit, tip);
            assert_eq!(mirror(&dest, REF).await, Some(tip));
            assert!(dest.fsck(&FsckOptions::default()).await.unwrap().is_ok());
        }
    }

    /// Returns the overrides that allow the `http://` endpoint of the
    /// server.
    fn cleartext() -> EndpointOverrides {
        EndpointOverrides {
            allow_cleartext_credentials: true,
            ..EndpointOverrides::default()
        }
    }

    /// The listing of collection refs reads the refs of a bucket repository
    /// from its summary alone, with a name and with no name, and sends no
    /// listing request. A bucket repository with no `summary` gives
    /// `Error::Pull`. The call with the default overrides refuses the
    /// `http://` endpoint of the server before its first request.
    #[test]
    fn a_query_reads_the_summary_of_a_bucket() {
        run_case("query", SECRET_KEY);
    }

    async fn query_bucket() {
        let dir = TmpDir::new("pull-collection-s3-query");
        let source = create(dir.path(), "source", None).await;
        let tip = commit(&source, dir.path(), "a", Some(ID), REF, FIXED_TS, BOUND).await;
        let bare = StandIn::start();
        store_tree(&bare, &dir.path().join("source"));
        summarize(&source).await;
        let server = StandIn::start();
        store_tree(&server, &dir.path().join("source"));
        let keys = bucket(&server.endpoint(), "s3://bkt/repo");
        let bare_keys = bucket(&bare.endpoint(), "s3://bkt/repo");
        let dest = bucket_dest(
            dir.path(),
            "dest",
            None,
            &[("bkt", &keys), ("bare", &bare_keys)],
        )
        .await;

        for names in [&[REF, "os/absent"][..], &[]] {
            let listed = dest
                .remote_list_collection_refs_with("bkt", ID, names, cleartext(), None)
                .await
                .unwrap();
            assert_eq!(listed, [(REF.to_owned(), tip)]);
        }
        assert_eq!(requests_for(&server, "summary"), 2);
        assert_eq!(requests_for(&server, "summary.sig"), 0);
        assert_signed_with_no_listing(&server);

        let err = dest
            .remote_list_collection_refs_with("bare", ID, &[REF], cleartext(), None)
            .await
            .unwrap_err();
        assert!(
            matches!(&err, Error::Pull(m) if m.contains("the bucket repository has no summary")),
            "{err:?}"
        );
        assert_eq!(requests_for(&bare, "summary"), 1);
        assert_signed_with_no_listing(&bare);

        let err = dest
            .remote_list_collection_refs("bkt", ID, &[REF])
            .await
            .unwrap_err();
        assert!(matches!(err, Error::InvalidInput(_)), "{err:?}");
        assert_eq!(requests_for(&server, "summary"), 2);
        assert_nothing_written(&dest).await;
    }

    /// `rclone serve s3` checks the signature of each request. The listing
    /// of collection refs reads the collection map of the summary of a
    /// bucket directory.
    #[test]
    fn a_query_on_rclone_reads_the_summary_of_a_bucket() {
        if !rclone_available("a_query_on_rclone_reads_the_summary_of_a_bucket") {
            return;
        }
        run_case("rclone-query", SECRET_KEY);
    }

    async fn rclone_query() {
        let dir = TmpDir::new("pull-collection-s3-rclone-query");
        let source = create(dir.path(), "source", None).await;
        let tip = commit(&source, dir.path(), "a", Some(ID), REF, FIXED_TS, BOUND).await;
        summarize(&source).await;
        drop(source);
        // rclone keeps the listing of each directory, so the files of the
        // bucket directory are in place before the server starts.
        let root = dir.path().join("root");
        std::fs::create_dir_all(root.join("bkt")).unwrap();
        let status = Command::new("cp")
            .arg("-r")
            .arg(dir.path().join("source"))
            .arg(root.join("bkt").join("repo"))
            .status()
            .unwrap();
        assert!(status.success(), "cp -r");
        let server = Rclone::start(dir.path(), &root);
        let keys = bucket(&server.endpoint(), "s3://bkt/repo");
        let dest = bucket_dest(dir.path(), "dest", None, &[("bkt", &keys)]).await;
        let listed = dest
            .remote_list_collection_refs_with("bkt", ID, &[], cleartext(), None)
            .await
            .unwrap();
        assert_eq!(listed, [(REF.to_owned(), tip)]);
        assert_nothing_written(&dest).await;
    }
}

/// The X.509 CRLs of the spki engine in a pull of collection refs.
#[cfg(all(feature = "sign-spki", feature = "sign-x509"))]
mod x509 {
    use std::path::PathBuf;

    use ostrya::sign::{SignFuture, X509Attachments};
    use ostrya::spki::{X509Chain, spki_secret_keys};

    use super::*;

    /// Returns the path of the X.509 fixture file `name`.
    fn x509_path(name: &str) -> PathBuf {
        common::fixture_root().join("../x509").join(name)
    }

    /// Returns the DER of each CRL of the fixture files `names`, in order.
    fn crls(names: &[&str]) -> Vec<Vec<u8>> {
        names
            .iter()
            .flat_map(|name| {
                ostrya::spki::x509_crls(&std::fs::read(x509_path(name)).unwrap(), name).unwrap()
            })
            .collect()
    }

    /// The ed25519 signer of the remotes, whose signatures carry X.509 CRLs
    /// and no chain.
    struct RawWithCrls {
        key: Ed25519Signer,
        crls: X509Attachments,
    }

    impl ostrya::Signer for RawWithCrls {
        fn name(&self) -> &str {
            self.key.name()
        }

        fn metadata_key(&self) -> &str {
            self.key.metadata_key()
        }

        fn sign<'a>(&'a self, data: &'a [u8]) -> SignFuture<'a> {
            self.key.sign(data)
        }

        fn x509_attachments(&self) -> Option<&X509Attachments> {
            Some(&self.crls)
        }
    }

    /// A pull of collection refs checks the commit of the selected remote
    /// with the CRLs of the `summary.sig` that the probe checked, from an
    /// HTTP remote and from a local repository. A raw key signs the summary,
    /// and the fresh CRL is in `summary.sig` alone. It revokes the leaf of
    /// the commit, so the pull is refused, and the pull caches the CRL.
    #[test]
    fn a_collection_pull_checks_the_commit_with_the_crl_of_the_summary() {
        block_on(async {
            for local in [false, true] {
                let dir = TmpDir::new("pull-collection-x509-summary-crl");
                let a = create(dir.path(), "a", Some(ID)).await;
                let tip = commit(&a, dir.path(), "a", None, REF, FIXED_TS, BOUND).await;
                let key = std::fs::read(x509_path("leaf-revoked.key.pem")).unwrap();
                let chain = std::fs::read(x509_path("chain-revoked.pem")).unwrap();
                let chain_signer = spki_secret_keys(key, "k")
                    .unwrap()
                    .remove(0)
                    .with_x509(vec![X509Chain::from_pem(&chain, "c").unwrap()], Vec::new())
                    .unwrap();
                a.sign_commit(&tip, &chain_signer).await.unwrap();
                summarize(&a).await;
                let summary_signer = RawWithCrls {
                    key: Ed25519Signer::from_base64(SECRET_B64).unwrap(),
                    crls: X509Attachments::new(Vec::new(), crls(&["intermediate-2.crl.pem"]))
                        .unwrap(),
                };
                a.sign_summary(&summary_signer).await.unwrap();
                let server = RepoServer::start(&dir.path().join("a"), false).await;
                let url = if local {
                    format!("file://{}", dir.path().join("a").display())
                } else {
                    server.url()
                };
                let policy = format!(
                    "sign-verify-summary=ed25519\nverification-ed25519-key={PUBLIC_B64}\n\
                     sign-verify=spki\nverification-spki-ca-file={}\n\
                     verification-spki-identity=*\n",
                    x509_path("root.pem").display()
                );
                let dest = dest(dir.path(), None, &[("a", &url, &policy)]).await;

                let (opts, _) = options(&[REF]);
                let err = dest.pull_collection(ID, &["a"], opts).await.unwrap_err();
                let Error::Signature(message) = &err else {
                    panic!("{err}");
                };
                assert!(
                    message.ends_with(&format!(
                        "commit {tip}: no sign-api signature is from a trusted key: \
                         certificate \"CN=ostrya test leaf revoked\" is revoked by the CRL of \
                         \"CN=ostrya test intermediate\""
                    )),
                    "local {local}: {message}"
                );
                assert_eq!(mirror(&dest, REF).await, None);
                let cached: Vec<Vec<u8>> =
                    common::file_inventory(&dir.path().join("dest"), "extensions/ostrya/x509-crl")
                        .into_iter()
                        .map(|(_, bytes)| bytes)
                        .collect();
                assert_eq!(cached, crls(&["intermediate-2.crl.pem"]), "local {local}");
            }
        });
    }
}