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
//! Transactions: the write path of a repository.
//!
//! [`Repo::transaction`] begins a [`Transaction`]. The transaction stages
//! objects in its own staging directory. [`commit`](Transaction::commit)
//! publishes them into `objects/` and writes the queued refs.
//! [`TransactionStats`] counts the work of a transaction.
//!
//! [`ContentWriter`] streams the payload of one regular file into a
//! transaction. [`FileMeta`] holds the uid, the gid, the mode, and the
//! extended attributes of a file object.
use std::collections::{BTreeSet, HashMap};
use std::os::fd::{AsFd, BorrowedFd};
use std::sync::atomic::{AtomicBool, Ordering};
use std::sync::{Mutex, OnceLock};
use ostrya_core::{Checksum, Commit, ObjectType, RepoMode, Value};
use crate::config::Tristate;
use crate::error::{Error, Result};
use crate::jobs::{Jobs, Tracked};
use crate::lock::{LockGuard, UpdateLockHeld};
use crate::repo::Repo;
use crate::staging::StagingDir;
use crate::write::{
Blocks, StageCtx, StageOutcome, TempKind, probe_fresh_owner, publish_blocking,
stage_clone_content_blocking, stage_content_blocking, stage_import_blocking,
stage_metadata_blocking, stage_symlink_blocking,
};
pub use crate::write::{ContentWriter, FileMeta};
/// The counts and sizes of the work of a transaction.
///
/// [`commit`](Transaction::commit) returns them. No field counts a composefs
/// image that the transaction stages, as no field counts detached commit
/// metadata.
#[derive(Debug, Clone, Copy, Default, PartialEq, Eq)]
pub struct TransactionStats {
/// The number of metadata objects offered for staging, dedup hits included.
///
/// A metadata object is a dirtree, a dirmeta, a commit, or another object
/// that is not a content object. Each directory counts its dirmeta once, so
/// a tree whose directories share one dirmeta counts it once for each
/// directory.
pub metadata_total: u32,
/// The number of metadata objects freshly staged.
///
/// A dedup hit does not count.
pub metadata_written: u32,
/// The number of content objects offered for staging, dedup hits included.
///
/// A content object that a [`DevInoCache`](crate::DevInoCache) hit
/// resolves is never offered, so it does not count.
pub content_total: u32,
/// The number of content objects freshly staged.
///
/// A dedup hit does not count.
pub content_written: u32,
/// The total on-disk size of the freshly staged content objects.
///
/// An object imported from another repository counts its full size. This
/// is true if its bytes were written, shared by reflink, or shared by
/// hardlink. So the value is the storage that the objects occupy. A shared
/// object uses no new space on the file system.
pub content_bytes_written: u64,
/// The total payload size of the freshly staged regular-file content objects.
///
/// The size is the size before the compression of the repository mode. An
/// object whose payload is cloned adds the length of its payload. These
/// objects add nothing:
///
/// - A symlink.
/// - An object hardlinked from another repository, because its payload is
/// never read.
/// - An object that a static delta produced. The `ostree` command also
/// counts nothing for such an object in a pull.
pub content_bytes_unpacked: u64,
/// The number of content objects that a [`DevInoCache`](crate::DevInoCache)
/// hit skipped in a file system ingest.
///
/// A hit is a file whose device and inode pair the cache knows already.
pub devino_cache_hits: u32,
/// The number of entries that a commit-modifier filter excluded in a file
/// system ingest.
pub filtered: u32,
}
/// One object staged in a transaction that waits for publication.
struct StagedObject {
/// The flat name of the object in the staging directory.
staging_name: String,
/// The loose path under `objects/` that the object publishes to. For a
/// composefs image, the path under `extensions/ostrya/composefs/`.
dest: String,
}
/// The archive size record of one staged object.
///
/// [`write_commit`](crate::Transaction::write_commit) reads the records to
/// write `ostree.sizes`. The `ostree.sizes` key of the `ostree` command covers
/// each object of the commit, content and metadata. So the transaction keeps a
/// record for each object type.
#[derive(Debug, Clone, Copy)]
pub(crate) struct SizeRecord {
/// The on-disk size: the `.filez` storage size for archive content, or the
/// serialized byte length for a metadata object.
pub(crate) compressed: u64,
/// The logical (unpacked) size: the payload length of a file, the target
/// length of a symlink, or the byte length of a metadata object.
pub(crate) unpacked: u64,
/// The object type, written as the last byte of the `ostree.sizes` entry.
pub(crate) objtype: ObjectType,
}
/// The mutable state that concurrent writers of one transaction share.
struct Staged {
/// The objects staged so far, by identity and type, for the dedup in the
/// transaction and for publication at commit.
objects: HashMap<(Checksum, ObjectType), StagedObject>,
/// The composefs images staged so far, by the checksum of their commit,
/// for publication into `extensions/ostrya/composefs/` at commit.
images: HashMap<Checksum, StagedObject>,
/// The commits that the writers recorded as complete, for the image build
/// of the commit.
complete: BTreeSet<Checksum>,
/// The size record of each object in archive mode, by checksum. The
/// records cover content and metadata objects, the input of `ostree.sizes`.
sizes: HashMap<Checksum, SizeRecord>,
/// The objects that `ostree.sizes` covers, if a caller limits the key by
/// tree source with [`begin_tree_source`](Transaction::begin_tree_source).
/// `None` makes the key cover each object that the commit reaches.
size_scope: Option<HashMap<Checksum, ObjectType>>,
/// The bytes that the transaction can write before the free space is less
/// than the configured reserve.
free_budget: u64,
/// The statistics so far.
stats: TransactionStats,
/// The number of staged objects that are durable before publication.
///
/// The count is the objects that the last `sync_staged` made durable, plus
/// each metadata object synced on its own after it. The publication step
/// skips its `syncfs` while this count equals the number of staged objects.
/// So an object staged after the sync gets the `syncfs` that it needs.
presynced: Option<usize>,
}
/// The queued detached-metadata edit of one commit.
///
/// The edit is a plan, so the read of the stored dict happens once, at the
/// write, under the guard that serializes the write. The parts are:
///
/// - `staged`: the file that a pull staged to replace the stored one.
/// - `replace`: the dict that
/// [`set_commit_detached_metadata`](Transaction::set_commit_detached_metadata)
/// queued to replace the stored one.
/// - `merge`: the dict that a receiving session merges in, with the keys whose
/// stored value stays.
/// - `related`: the build sources that
/// [`add_detached_related`](Transaction::add_detached_related) adds after
/// it, in call order.
/// - `appends`: the signatures that [`sign_commit`](Transaction::sign_commit)
/// made after it, in call order.
#[derive(Default)]
struct DetachedEdit {
/// The file in the staging directory whose bytes replace the stored
/// detached metadata, if a pull staged one. The write installs it first,
/// and the other parts of the edit apply to it next.
staged: Option<String>,
/// The dict that replaces the stored detached metadata, if a caller queued
/// one. `None` starts the edit from the stored dict.
replace: Option<Value>,
/// The serialized `a{sv}` dict that the edit merges in before the appends,
/// and the keys whose stored value stays.
///
/// Each signature list gets the union of the two lists. A listed key that
/// the starting dict holds keeps its value. Each other key takes the value
/// of this dict.
merge: Option<(Vec<u8>, Vec<String>)>,
/// The build sources to add after the merge, each a name and the checksum
/// of a commit.
related: Vec<(String, Checksum)>,
/// The signatures to append, each an engine metadata key and one signature.
appends: Vec<(String, Vec<u8>)>,
}
/// The queued detached-metadata edits of a transaction.
///
/// The queue holds one edit for each commit, in the order of the first edit of
/// each commit. An index maps each commit to the position of its edit.
#[derive(Default)]
struct DetachedQueue {
edits: Vec<(Checksum, DetachedEdit)>,
index: HashMap<Checksum, usize>,
}
/// A set of staged objects and queued writes to one repository.
///
/// [`Repo::transaction`] and [`Repo::transaction_with_lock`] begin a
/// transaction. The transaction holds the repository lock and its own staging
/// directory until it ends. [`commit`](Transaction::commit) publishes the
/// staged objects and writes the queued refs and detached metadata.
/// [`abort`](Transaction::abort) discards them.
///
/// If a transaction drops without `commit` or `abort`, it removes its staging
/// directory with each staged object and releases the lock. So an abandoned
/// transaction leaves nothing behind.
///
/// # Concurrency
///
/// One process can hold many transactions at once, each with its own staging
/// directory. The repository lock coordinates them. It also excludes other
/// processes and the `ostree` command, as [`LockKind`](crate::LockKind)
/// states.
///
/// `&Transaction` is `Send + Sync`, so concurrent writers can stage objects
/// through one shared reference. A mutex guards the state that the writers
/// share: the set of staged objects for the dedup, the free-space budget, and
/// the archive size records.
///
/// # Staging directory
///
/// A transaction stages its objects in `tmp/staging-<boot-id>-XXXXXX`. It
/// creates the directory when it begins and removes it when it ends. While the
/// transaction lives, it holds an exclusive record lock on the sibling file
/// `staging-<boot-id>-XXXXXX-lock`.
///
/// The boot id separates the directories of the current boot from the
/// directories of earlier boots. The owner of a directory of the current boot
/// can still be alive. The owner of a directory of an earlier boot is gone.
///
/// When a transaction begins, it removes these stale entries at the top level
/// of `tmp/`:
///
/// - A staging directory whose lock it can take, because no live holder has
/// the lock.
/// - A staging directory with no lock file, if the directory is older than
/// `tmp-expiry-secs`. The age test is necessary because another process can
/// be in the middle of the creation of the directory.
/// - Each other entry whose mtime is older than `tmp-expiry-secs`, as the
/// `ostree` command does. A directory goes as a whole tree, by its own
/// mtime. A symlink goes as the link itself.
///
/// It never touches `tmp/cache`, and it never removes a staging directory that
/// this process owns. A staging lock file has no age test, because a
/// transaction can live longer than `tmp-expiry-secs` and still hold the lock.
///
/// A ref write, a detached-metadata write, and a tombstone write create a temp
/// entry at the top level of `tmp/` and rename it over the target. The entry
/// of a ref write is named `.ostrya-ref-<pid>-<n>-XXXXXX`. The entry of the
/// other two writes is named `.ostrya-meta-<pid>-<n>-XXXXXX`. The age test
/// applies to such an entry.
///
/// If `tmp-expiry-secs` is very small or negative, a transaction that begins
/// can remove the entry before its rename. The write then fails with `ENOENT`,
/// and the ref or the object stays unchanged.
///
/// # Examples
///
/// Commit the directory `/srv/rootfs` and point a ref at the new commit:
///
/// ```no_run
/// # async fn run() -> ostrya::Result<()> {
/// use std::os::fd::AsFd;
/// use std::path::Path;
///
/// use ostrya::{CommitOptions, MutableTree, Ref, Repo};
///
/// let repo = Repo::open(Path::new("/srv/repo")).await?;
/// let txn = repo.transaction().await?;
///
/// let parent = std::fs::File::open("/srv")?;
/// let mut mtree = MutableTree::new();
/// txn.write_dfd_to_mtree(parent.as_fd(), Path::new("rootfs"), &mut mtree, None)
/// .await?;
/// let root = txn.write_mtree(&mut mtree).await?;
///
/// let opts = CommitOptions {
/// subject: Some("Build 1".into()),
/// ..CommitOptions::default()
/// };
/// let commit = txn.write_commit(opts, &root).await?;
/// txn.set_ref(&Ref::local("exampleos/stable"), Some(&commit));
/// let stats = txn.commit().await?;
/// println!("{} content objects written", stats.content_written);
/// # Ok(()) }
/// ```
pub struct Transaction {
repo: Repo,
/// The `[core] fsync` value of this transaction alone, from
/// [`set_fsync`](Transaction::set_fsync). `None` leaves the config value in
/// force.
fsync_override: Option<bool>,
/// The `[core] per-object-fsync` value of this transaction alone, from
/// [`set_per_object_fsync`](Transaction::set_per_object_fsync). `None`
/// leaves the config value in force.
per_object_fsync_override: Option<bool>,
/// The `ostree.sizes` request of a file system ingest under
/// [`GENERATE_SIZES`](crate::CommitModifierFlags::GENERATE_SIZES). The
/// commit assembly reads it to decide if it writes `ostree.sizes`.
generate_sizes: AtomicBool,
/// The answer of a caller for the whole transaction, from
/// [`set_generate_sizes`](Transaction::set_generate_sizes).
///
/// It overrides `generate_sizes` in both directions. `None` leaves the
/// ingest flag in force.
generate_sizes_override: Option<bool>,
// Fields drop in declaration order: the staged state and the staging
// directory go first, then the lock.
staged: Mutex<Staged>,
/// The refspec-to-checksum writes that [`set_ref`](Transaction::set_ref)
/// and [`set_ref_expecting`](Transaction::set_ref_expecting) queue.
/// [`commit`](Transaction::commit) applies them after object
/// publication, for durability.
pub(crate) refs: Mutex<Vec<crate::refs::RefWrite>>,
/// The detached-metadata edits that
/// [`set_commit_detached_metadata`](Transaction::set_commit_detached_metadata)
/// and [`sign_commit`](Transaction::sign_commit) queue.
///
/// [`commit`](Transaction::commit) applies them after object publication
/// and before the queued ref writes. So a commit that a ref names carries
/// its signatures.
detached: Mutex<DetachedQueue>,
/// The uid and gid of an object freshly staged in this transaction.
/// [`fresh_owner`](Transaction::fresh_owner) measures them once, on first
/// use.
fresh_owner: OnceLock<(u32, u32)>,
/// The blocking jobs of this transaction that a dropped future left
/// before they ended.
jobs: Jobs,
staging: Option<StagingDir>,
/// The repository lock hold, kept for the life of the transaction.
///
/// The drop of this field releases the lock. A commit that writes a ref
/// or detached metadata moves the hold into the blocking closure of that
/// write.
lock: LockGuard,
}
/// Methods that set the options of a transaction, read its staged trees, queue
/// detached metadata, and end it.
impl Transaction {
/// Assembles a transaction from a repository handle, an acquired lock, a
/// staging directory, and the initial free-space budget.
pub(crate) fn new(
repo: Repo,
lock: LockGuard,
staging: StagingDir,
free_budget: u64,
) -> Transaction {
Transaction {
repo,
fsync_override: None,
per_object_fsync_override: None,
generate_sizes: AtomicBool::new(false),
generate_sizes_override: None,
staged: Mutex::new(Staged {
objects: HashMap::new(),
images: HashMap::new(),
complete: BTreeSet::new(),
sizes: HashMap::new(),
size_scope: None,
free_budget,
stats: TransactionStats::default(),
presynced: None,
}),
refs: Mutex::new(Vec::new()),
detached: Mutex::new(DetachedQueue::default()),
fresh_owner: OnceLock::new(),
jobs: Jobs::default(),
staging: Some(staging),
lock,
}
}
/// Overrides the `[core] fsync` value for this transaction alone.
///
/// The value applies to the whole transaction: the per-object writes, the
/// publication step, the detached-metadata writes, and the ref writes. It
/// changes the durability of the writes and no byte that the repository
/// stores.
/// [`commit`](Transaction::commit) states the sync sequence.
pub fn set_fsync(&mut self, enabled: bool) {
self.fsync_override = Some(enabled);
}
/// Overrides the `[core] per-object-fsync` value for this transaction alone.
///
/// If the value is `true`, the transaction syncs the file of each content
/// object when it stages the object, before publication. It never syncs a
/// metadata object on its own. It does not sync an object imported by
/// hardlink.
///
/// The value has no effect while fsync is off, from the config or from
/// [`set_fsync`](Transaction::set_fsync). It changes the durability of the
/// writes and no byte that the repository stores.
/// [`commit`](Transaction::commit) states the sync sequence.
pub fn set_per_object_fsync(&mut self, enabled: bool) {
self.per_object_fsync_override = Some(enabled);
}
/// Sets if each commit of this transaction carries the `ostree.sizes` key.
///
/// A file system ingest under
/// [`GENERATE_SIZES`](crate::CommitModifierFlags::GENERATE_SIZES) turns the
/// key on. This call serves an ingest that runs no commit modifier, for
/// example the tar import. The value holds for the whole transaction and
/// overrides the flag of each ingest, so `false` turns the key off again.
///
/// Outside archive mode the call has no effect, because no other mode
/// writes the key.
pub fn set_generate_sizes(&mut self, enabled: bool) {
self.generate_sizes_override = Some(enabled);
}
/// Returns the repository that this transaction writes to.
pub(crate) fn repo(&self) -> &Repo {
&self.repo
}
/// Returns the descriptor of the staging directory, where the objects go.
pub(crate) fn staging_fd(&self) -> BorrowedFd<'_> {
self.staging
.as_ref()
.expect("staging directory present during the transaction")
.dir_fd()
}
/// Runs `f` on the blocking pool as a job of this transaction, and
/// returns a future of its result.
///
/// The jobs that stage an object, detached metadata, or a composefs
/// image, that open the temp file of an object to stage, or that probe
/// the owner of a fresh object run through this call. The marker write
/// of a step of a pull from a remote runs through
/// [`track`](Transaction::track). If the future drops before the job
/// ends, the job continues, and [`settle`](Transaction::settle) waits for
/// it. So a failed pull from a remote can wait for these jobs before its
/// cleanup. Other jobs run through `ostrya_rt::unblock`, and `settle`
/// does not wait for them. Some of them create a name, for example the
/// publish of [`commit`](Transaction::commit).
pub(crate) fn unblock<T, F>(&self, f: F) -> Tracked<'_, T>
where
F: FnOnce() -> T + Send + 'static,
T: Send + 'static,
{
self.jobs.track(ostrya_rt::unblock_task(f))
}
/// Makes `handle` a job of this transaction, as
/// [`unblock`](Transaction::unblock) does for the job that it starts.
pub(crate) fn track<T: Send + 'static>(
&self,
handle: ostrya_rt::JoinHandle<T>,
) -> Tracked<'_, T> {
self.jobs.track(handle)
}
/// Waits for each job of this transaction that a dropped future left
/// before the job ended.
pub(crate) async fn settle(&self) {
#[cfg(test)]
crate::jobs::job_gate::release(self.repo.repo_fd());
self.jobs.settle().await;
}
/// Returns the uid and gid of an object freshly staged in this transaction.
///
/// The call measures the pair on first use and keeps it for the life of the
/// transaction. The import path reads it. It accepts a hardlink only if the
/// source inode has this ownership already. If two callers race for the
/// first read, both measure the same directory, and one result stays.
pub(crate) async fn fresh_owner(&self) -> Result<(u32, u32)> {
if let Some(owner) = self.fresh_owner.get() {
return Ok(*owner);
}
let staging = self.staging_fd().try_clone_to_owned()?;
let owner = self
.unblock(move || probe_fresh_owner(staging.as_fd()))
.await?;
Ok(*self.fresh_owner.get_or_init(|| owner))
}
/// Records that this transaction writes `ostree.sizes` at commit.
///
/// A file system ingest under
/// [`GENERATE_SIZES`](crate::CommitModifierFlags::GENERATE_SIZES) calls it.
pub(crate) fn mark_generate_sizes(&self) {
self.generate_sizes.store(true, Ordering::Relaxed);
}
/// Returns `true` if the transaction writes `ostree.sizes`.
///
/// The answer of the caller from
/// [`set_generate_sizes`](Transaction::set_generate_sizes) applies if it
/// exists, else the ingest flag. [`write_commit`](Transaction::write_commit)
/// reads it.
pub(crate) fn generate_sizes(&self) -> bool {
self.generate_sizes_override
.unwrap_or_else(|| self.generate_sizes.load(Ordering::Relaxed))
}
/// Starts a new tree source for the `ostree.sizes` key.
///
/// The `ostree` command limits the key to the objects that the last tree
/// source added, plus the directory objects that the tree serialization
/// writes. So a content object from an earlier source leaves the key, and a
/// directory object stays.
///
/// A caller that builds a commit from several sources calls this method
/// before each source. Then the key that ostrya writes is the key that the
/// `ostree` command writes. If a caller never calls this method, the key
/// covers each object that the commit reaches.
///
/// The `--base` layer of a commit goes in before the first call, so it adds
/// nothing to the key. The `ostree` command records the same key.
pub fn begin_tree_source(&self) {
let mut staged = self.staged.lock().unwrap();
let scope = staged.size_scope.get_or_insert_with(HashMap::new);
scope.retain(|_, ty| *ty != ObjectType::File);
}
/// Records one object in the `ostree.sizes` scope, if a scope is in force.
///
/// Returns `true` if the object was not in the scope before.
pub(crate) fn note_size_scope(&self, checksum: Checksum, ty: ObjectType) -> bool {
let mut staged = self.staged.lock().unwrap();
match &mut staged.size_scope {
Some(scope) => scope.insert(checksum, ty).is_none(),
None => false,
}
}
/// Returns `true` if a size scope is in force.
pub(crate) fn size_scoped(&self) -> bool {
self.staged.lock().unwrap().size_scope.is_some()
}
/// Returns `true` if `checksum` is inside the `ostree.sizes` scope.
///
/// If no scope is in force, each object is inside it.
pub(crate) fn in_size_scope(&self, checksum: &Checksum) -> bool {
match &self.staged.lock().unwrap().size_scope {
Some(scope) => scope.contains_key(checksum),
None => true,
}
}
/// Returns a copy of the archive size records of the objects freshly staged
/// so far, as `ostree.sizes` entries.
///
/// [`write_commit`](Transaction::write_commit) reads the copy before it
/// stages the commit object, so the size of the commit itself is never in
/// it. `write_commit` looks up each reachable object in the copy. It reads
/// the sizes of an object that it does not find from disk: an object that
/// was a dedup hit against `objects/`. So in a transaction with many
/// commits, each commit gets its own key, limited to its reachable objects.
pub(crate) fn size_entries(&self) -> Vec<ostrya_core::sizes::SizeEntry> {
let staged = self.staged.lock().unwrap();
staged
.sizes
.iter()
.map(|(checksum, rec)| ostrya_core::sizes::SizeEntry {
checksum: *checksum,
compressed: rec.compressed,
unpacked: rec.unpacked,
objtype: Some(rec.objtype),
})
.collect()
}
/// Counts one content object that a devino-cache hit skipped.
pub(crate) fn note_devino_hit(&self) {
self.staged.lock().unwrap().stats.devino_cache_hits += 1;
}
/// Counts one entry that a commit-modifier filter excluded.
pub(crate) fn note_filtered(&self) {
self.staged.lock().unwrap().stats.filtered += 1;
}
/// Returns `true` if an object of this identity and type is staged in this
/// transaction.
///
/// A staged object is in the staging directory and is not yet published
/// into `objects/`.
pub(crate) fn is_staged(&self, checksum: &Checksum, ty: ObjectType) -> bool {
self.staged
.lock()
.unwrap()
.objects
.contains_key(&(*checksum, ty))
}
/// Returns `true` if the commit object `commit` is staged in this
/// transaction.
///
/// [`write_commit`](Transaction::write_commit) stages a new commit. A
/// commit that the repository holds before the write, complete or
/// partial, is not staged. A caller that attaches the image of a new
/// commit alone with
/// [`attach_composefs_image`](Transaction::attach_composefs_image) checks
/// the commit with this call. The call reads the staged set of this
/// transaction, so another writer under the shared lock does not change
/// its result. A [`Repo::has_object`] check after the write reads the
/// object store, and another transaction can publish the same commit
/// before that check.
pub fn is_commit_staged(&self, commit: &Checksum) -> bool {
self.is_staged(commit, ObjectType::Commit)
}
/// Returns `true` if a composefs image of `commit` is staged in this
/// transaction.
pub(crate) fn is_image_staged(&self, commit: &Checksum) -> bool {
self.staged.lock().unwrap().images.contains_key(commit)
}
/// Records `commit` as a complete commit of this transaction.
///
/// Each writer of a complete commit calls it. Under
/// `[ex-ostrya] generate-composefs`, the commit of the transaction builds
/// the composefs image of each recorded commit that this transaction
/// staged or that has a `.commitpartial` marker.
pub(crate) fn mark_complete(&self, commit: &Checksum) {
self.staged.lock().unwrap().complete.insert(*commit);
}
/// Takes the commits that [`mark_complete`](Transaction::mark_complete)
/// recorded.
pub(crate) fn take_complete(&self) -> BTreeSet<Checksum> {
std::mem::take(&mut self.staged.lock().unwrap().complete)
}
/// Returns, for each checksum of `checksums`, `true` if an object of that
/// identity and of type `ty` is staged in this transaction.
///
/// The call takes the lock of the staged set one time.
pub(crate) fn staged_flags(&self, ty: ObjectType, checksums: &[Checksum]) -> Vec<bool> {
let staged = self.staged.lock().unwrap();
checksums
.iter()
.map(|checksum| staged.objects.contains_key(&(*checksum, ty)))
.collect()
}
/// Returns the checksums of the objects of type `ty` staged in this
/// transaction.
#[cfg(feature = "receive")]
pub(crate) fn staged_of_type(&self, ty: ObjectType) -> Vec<Checksum> {
self.staged
.lock()
.unwrap()
.objects
.keys()
.filter(|(_, t)| *t == ty)
.map(|(checksum, _)| *checksum)
.collect()
}
/// Loads a file object from the staged set of this transaction, or else
/// from `objects/`.
///
/// The read and merge paths of a staging tree use it, so they see the
/// content staged in this transaction before it publishes.
pub(crate) async fn load_file_staged_first(
&self,
checksum: &Checksum,
) -> Result<crate::file::FileObject> {
self.load_file_staged_first_with(checksum, false).await
}
/// Loads a file object as [`load_file_staged_first`] does, with the
/// `measure` flag of [`Repo::load_file_with`].
///
/// [`load_file_staged_first`]: Transaction::load_file_staged_first
pub(crate) async fn load_file_staged_first_with(
&self,
checksum: &Checksum,
measure: bool,
) -> Result<crate::file::FileObject> {
if self.is_staged(checksum, ObjectType::File) {
crate::file::load_staged_file(&self.repo, self.staging_fd(), checksum, measure).await
} else {
self.repo.load_file_with(checksum, measure).await
}
}
/// Loads a dirtree object from the staged set of this transaction, or else
/// from `objects/`.
///
/// It does for the right side of the merge path what
/// [`load_file_staged_first`] does for files. So the merge sees a dirtree
/// staged in this transaction before it publishes.
///
/// [`load_file_staged_first`]: Transaction::load_file_staged_first
pub(crate) async fn load_dirtree_staged_first(
&self,
checksum: &Checksum,
) -> Result<ostrya_core::DirTree> {
if self.is_staged(checksum, ObjectType::DirTree) {
let name = crate::write::flat_name(checksum, ObjectType::DirTree, self.repo.mode());
let staging = self.staging_fd().try_clone_to_owned()?;
let bytes = ostrya_rt::unblock(move || {
crate::object::read_meta_object(
staging.as_fd(),
&name,
crate::object::MAX_METADATA_SIZE,
)
})
.await
.map_err(Error::Io)?;
Ok(ostrya_core::DirTree::parse(&bytes)?)
} else {
self.repo.load_dirtree(checksum).await
}
}
/// Loads a dirmeta object from the staged set of this transaction, or else
/// from `objects/`.
///
/// It does for the directory metadata of a staged tree what
/// [`load_dirtree_staged_first`](Self::load_dirtree_staged_first) does for
/// dirtrees.
pub(crate) async fn load_dirmeta_staged_first(
&self,
checksum: &Checksum,
) -> Result<ostrya_core::DirMeta> {
if self.is_staged(checksum, ObjectType::DirMeta) {
let name = crate::write::flat_name(checksum, ObjectType::DirMeta, self.repo.mode());
let staging = self.staging_fd().try_clone_to_owned()?;
let bytes = ostrya_rt::unblock(move || {
crate::object::read_meta_object(
staging.as_fd(),
&name,
crate::object::MAX_METADATA_SIZE,
)
})
.await
.map_err(Error::Io)?;
Ok(ostrya_core::DirMeta::parse(&bytes)?)
} else {
self.repo.load_dirmeta(checksum).await
}
}
/// Lists one directory of a tree that this transaction staged.
///
/// The call reads the objects that this transaction staged first, and then
/// `objects/`. A caller can use it to derive commit metadata from a tree
/// before the transaction commit.
///
/// [`RepoTree::read_dir`](crate::RepoTree::read_dir) reads `objects/`
/// alone, so it sees a tree only after the transaction commit. The order of
/// the entries is the same in both calls: files first, then subdirectories,
/// each group sorted by name.
///
/// Before the transaction commit, `RepoTree::read_dir` on a
/// [`TreeEntry::Dir`](crate::TreeEntry::Dir) of a staged tree fails with
/// [`Error::ObjectNotFound`]. This method reads such an entry.
///
/// # Errors
///
/// - [`Error::ObjectNotFound`] if the dirtree of `tree` is not staged and
/// not in `objects/`.
/// - [`Error::Io`] if the read of the dirtree fails, or if the dirtree is
/// larger than [`MAX_METADATA_SIZE`](crate::MAX_METADATA_SIZE).
/// - [`Error::Core`] if the dirtree does not parse.
pub async fn read_dir(&self, tree: &crate::RepoTree) -> Result<Vec<crate::TreeEntry>> {
let dirtree = self
.load_dirtree_staged_first(tree.dirtree_checksum())
.await?;
let mut entries = Vec::with_capacity(dirtree.files.len() + dirtree.dirs.len());
for (name, checksum) in dirtree.files {
entries.push(crate::TreeEntry::File { name, checksum });
}
for (name, subtree, submeta) in dirtree.dirs {
entries.push(crate::TreeEntry::Dir {
name,
tree: crate::RepoTree::from_parts(self.repo.clone(), subtree, submeta),
});
}
Ok(entries)
}
/// Queues the detached metadata of a commit that this transaction writes.
///
/// `meta` is an `a{sv}` dict. It replaces the detached metadata that the
/// repository stores for `checksum`. The write happens at
/// [`commit`](Transaction::commit), after the staged objects publish and
/// before the queued ref writes. So the commit and its detached metadata are
/// durable before a ref names them.
///
/// If the call runs twice for one checksum, the last dict stays. The call
/// also drops the signatures that [`sign_commit`](Transaction::sign_commit)
/// queued before it, and the build sources that
/// [`add_detached_related`](Transaction::add_detached_related) queued
/// before it.
///
/// The call does not check `meta`, and it cannot fail. [`commit`] checks
/// each `ostrya.related` entry of the queued dict, as
/// [`Repo::write_commit_detached_metadata`] does. If an entry is
/// defective, `commit` fails with [`Error::InvalidRelated`] and publishes
/// nothing.
///
/// [`commit`]: Transaction::commit
pub fn set_commit_detached_metadata(&self, checksum: &Checksum, meta: Value) {
let mut queue = self.detached.lock().unwrap();
let edit = Self::edit_for(&mut queue, checksum);
edit.staged = None;
edit.replace = Some(meta);
edit.merge = None;
edit.related.clear();
edit.appends.clear();
}
/// Queues the build source `name` with the checksum `source` for the
/// detached metadata of the commit `commit`.
///
/// The write at [`commit`](Transaction::commit) adds the entry to the
/// first `ostrya.related` entry of the detached metadata, as
/// [`Repo::add_detached_related`] does: it removes each element with the
/// name `name`, adds the new element, and keeps the elements sorted by
/// name in byte order. The write adds the entries of all calls for one
/// commit in one step. The result is the same as one add for each call,
/// in call order, after the dict that
/// [`set_commit_detached_metadata`](Transaction::set_commit_detached_metadata)
/// queued, or else after the stored dict. The signatures that
/// [`sign_commit`](Transaction::sign_commit) queues come after the adds.
///
/// The call does not check that the transaction or the repository holds
/// `commit` or `source`, and it writes nothing to the file system.
///
/// If the stored value of the first `ostrya.related` entry is defective,
/// the write at [`commit`](Transaction::commit) fails with
/// [`Error::InvalidRelated`]. The commit fails after it publishes the
/// staged objects. It then writes no ref, and the `.commitmeta` file of
/// `commit` stays as it was. The detached-metadata edits of other commits
/// that the queue holds before this one stay written.
///
/// # Errors
///
/// [`Error::InvalidRelated`] with `commit` and
/// [`RelatedField::BuildSources`](crate::RelatedField::BuildSources) if
/// `name` is empty. The call then queues nothing.
pub fn add_detached_related(
&self,
commit: &Checksum,
name: &str,
source: &Checksum,
) -> Result<()> {
if name.is_empty() {
return Err(crate::commit::empty_build_source_name(commit));
}
let mut queue = self.detached.lock().unwrap();
Self::edit_for(&mut queue, commit)
.related
.push((name.to_owned(), *source));
Ok(())
}
/// Stages `bytes`, the serialized detached metadata of `checksum`, to
/// replace the stored detached metadata.
///
/// A pull copies the `.commitmeta` of a source byte for byte through this
/// call. The bytes go to a file in the staging directory at once, so the
/// queue holds no copy of them.
///
/// At [`commit`](Transaction::commit) the write renames the file over the
/// `.commitmeta` of `checksum`. The rename comes after the staged objects
/// publish and before the queued ref writes. With fsync on, the file is
/// durable before the rename. The `syncfs` of the publication step covers
/// it, and if that step runs no `syncfs`, the write runs one of its own.
///
/// A transaction that does not commit leaves the stored file unchanged. A
/// second stage for one checksum replaces the file. As
/// [`set_commit_detached_metadata`](Transaction::set_commit_detached_metadata)
/// does, the call drops the edits queued for `checksum` before it.
pub(crate) async fn stage_commit_detached_bytes(
&self,
checksum: &Checksum,
bytes: Vec<u8>,
) -> Result<()> {
let name = crate::write::flat_name(checksum, ObjectType::CommitMeta, self.repo.mode());
let staging = self.staging_fd().try_clone_to_owned()?;
let staged = name.clone();
self.unblock(move || {
crate::commit::stage_detached_blocking(staging.as_fd(), &staged, &bytes)
})
.await?;
let mut queue = self.detached.lock().unwrap();
let edit = Self::edit_for(&mut queue, checksum);
edit.staged = Some(name);
edit.replace = None;
edit.merge = None;
edit.related.clear();
edit.appends.clear();
Ok(())
}
/// Queues a merge of `incoming`, the bytes of an `a{sv}` dict, into the
/// detached metadata of `checksum`.
///
/// At [`commit`](Transaction::commit) the write reads the stored dict and
/// parses `incoming`. It merges `incoming` into the stored dict under the
/// process-wide guard of detached-metadata edits:
///
/// - Each signature list gets the union of the stored and the incoming list.
/// - A key of `keep` that the stored dict holds keeps the stored value.
/// - Each other key takes the incoming value.
///
/// The signatures that [`append_signature`](Transaction::append_signature)
/// queues come after the merge. If the call runs twice for one checksum, the
/// last dict and its `keep` stay.
#[cfg(feature = "receive")]
pub(crate) fn merge_commit_detached(
&self,
checksum: &Checksum,
incoming: Vec<u8>,
keep: Vec<String>,
) {
let mut queue = self.detached.lock().unwrap();
Self::edit_for(&mut queue, checksum).merge = Some((incoming, keep));
}
/// Queues `signature`, made before this call, for the engine metadata key
/// `key` of the detached metadata of `checksum`.
///
/// The write at [`commit`](Transaction::commit) appends it as it appends a
/// signature from [`sign_commit`](Transaction::sign_commit).
#[cfg(feature = "receive")]
pub(crate) fn append_signature(&self, checksum: &Checksum, key: &str, signature: Vec<u8>) {
let mut queue = self.detached.lock().unwrap();
Self::edit_for(&mut queue, checksum)
.appends
.push((key.to_owned(), signature));
}
/// Signs a commit that this transaction wrote and queues the signature.
///
/// The signature goes into the detached metadata of the commit. The
/// payload is the canonical bytes of the commit object. The call reads them
/// from the staging directory if the object is staged, and from `objects/`
/// if the repository holds the object already.
///
/// The signature appends to the `aay` array of the engine, in the first of
/// these dicts that exists:
///
/// 1. The dict that
/// [`set_commit_detached_metadata`](Transaction::set_commit_detached_metadata)
/// queued.
/// 2. The dict that the repository stores at the time of the write.
/// 3. An empty dict.
///
/// The call writes nothing to the file system. The signing step comes
/// before the object publication and the ref writes. So a signer failure
/// fails the transaction before it publishes an object or moves a ref.
///
/// # Concurrent signers
///
/// The queue step takes one lock and holds no await. The call makes the
/// signature here, before it takes a lock of the commit.
///
/// The write at [`commit`](Transaction::commit) reads, merges, and replaces
/// the file under the update lock. So each signature that tasks or
/// processes make for one commit reaches the file: from one transaction,
/// from concurrent transactions, and from [`Repo::sign_commit`]. The
/// `ostree` command can lose a signature in that case.
///
/// # Errors
///
/// - [`Error::ObjectNotFound`] if the commit is not staged and not in
/// `objects/`.
/// - [`Error::Io`] if the read of the commit object fails, or if the object
/// is larger than [`MAX_METADATA_SIZE`](crate::MAX_METADATA_SIZE).
/// - [`Error::Signature`] if `signer` cannot make a signature. An error of
/// a signer can also convert to [`Error::InvalidFormat`] or
/// [`Error::Core`].
pub async fn sign_commit(&self, checksum: &Checksum, signer: &dyn crate::Signer) -> Result<()> {
let payload = self.load_commit_bytes_staged_first(checksum).await?;
let signature = signer.sign(&payload).await?;
let mut queue = self.detached.lock().unwrap();
Self::edit_for(&mut queue, checksum)
.appends
.push((signer.metadata_key().to_owned(), signature));
Ok(())
}
/// Returns the queued edit of `checksum`, and adds an empty edit if the
/// queue holds none.
fn edit_for<'a>(queue: &'a mut DetachedQueue, checksum: &Checksum) -> &'a mut DetachedEdit {
let edits = &mut queue.edits;
let index = *queue.index.entry(*checksum).or_insert_with(|| {
edits.push((*checksum, DetachedEdit::default()));
edits.len() - 1
});
&mut edits[index].1
}
/// Loads the canonical bytes of a commit object from the staged set of
/// this transaction, or else from `objects/`, as the other staged-first
/// readers do.
pub(crate) async fn load_commit_bytes_staged_first(
&self,
checksum: &Checksum,
) -> Result<Vec<u8>> {
if !self.is_staged(checksum, ObjectType::Commit) {
return self
.repo
.load_object_bytes(ObjectType::Commit, checksum)
.await;
}
let name = crate::write::flat_name(checksum, ObjectType::Commit, self.repo.mode());
let staging = self.staging_fd().try_clone_to_owned()?;
ostrya_rt::unblock(move || {
crate::object::read_meta_object(
staging.as_fd(),
&name,
crate::object::MAX_METADATA_SIZE,
)
})
.await
.map_err(Error::Io)
}
/// Loads a commit object as
/// [`load_commit_bytes_staged_first`](Transaction::load_commit_bytes_staged_first)
/// does, and parses it.
///
/// A commit object can be as large as
/// [`MAX_METADATA_SIZE`](crate::MAX_METADATA_SIZE), so the read and the
/// parse run in one call on the blocking pool. The errors are those of the
/// read, then [`Error::Core`] if the bytes do not parse as a commit.
pub(crate) async fn load_commit_staged_first(&self, checksum: &Checksum) -> Result<Commit> {
if !self.is_staged(checksum, ObjectType::Commit) {
let repo = self.repo.clone();
let checksum = *checksum;
return ostrya_rt::unblock(move || {
let bytes = repo.load_object_bytes_blocking(ObjectType::Commit, &checksum)?;
Ok(Commit::parse(&bytes)?)
})
.await;
}
let name = crate::write::flat_name(checksum, ObjectType::Commit, self.repo.mode());
let staging = self.staging_fd().try_clone_to_owned()?;
ostrya_rt::unblock(move || {
let bytes = crate::object::read_meta_object(
staging.as_fd(),
&name,
crate::object::MAX_METADATA_SIZE,
)
.map_err(Error::Io)?;
Ok(Commit::parse(&bytes)?)
})
.await
}
/// Takes the queued detached-metadata edits for [`DetachedJob::run`].
///
/// The job applies them between publication and the ref writes, under the
/// fsync policy of the transaction. `synced` is `true` if the publication
/// step ran its `syncfs`, which also makes the staged files durable.
fn detached_job(&self, synced: bool) -> Result<DetachedJob> {
let queued = std::mem::take(&mut self.detached.lock().unwrap().edits);
let (fsync, _) = self.fsync_flags()?;
Ok(DetachedJob {
queued,
fsync,
staged_durable: synced,
repo_mode: self.repo.mode(),
objects_fd: self.repo.objects_fd().try_clone_to_owned()?,
staging_fd: self.staging_fd().try_clone_to_owned()?,
})
}
/// Stages a regular-file content object whose payload is in `file`
/// already.
///
/// [`ContentWriter::finish`](crate::ContentWriter::finish) calls it. If
/// `counted` is `true`, the payload adds to
/// [`content_bytes_unpacked`](TransactionStats::content_bytes_unpacked).
pub(crate) async fn stage_regular(
&self,
checksum: Checksum,
header: ostrya_core::FileHeader,
file: std::fs::File,
temp: TempKind,
unpacked: u64,
counted: bool,
) -> Result<Checksum> {
let mode = self.repo.mode();
let (fsync, per_object_fsync) = self.fsync_flags()?;
let verity = self.verity()?;
let objects = self.repo.objects_fd().try_clone_to_owned()?;
let staging = self.staging_fd().try_clone_to_owned()?;
let key = checksum;
let outcome = self
.unblock(move || {
let ctx = StageCtx {
objects_fd: objects.as_fd(),
staging_fd: staging.as_fd(),
mode,
fsync,
per_object_fsync,
sync_metadata: false,
verity,
};
stage_content_blocking(&ctx, &key, &header, file, temp, unpacked)
})
.await?;
self.record(checksum, ObjectType::File, mode, outcome, counted)
}
/// Stages a symlink content object.
///
/// [`write_symlink`](Transaction::write_symlink) calls it.
pub(crate) async fn stage_symlink(
&self,
checksum: Checksum,
header: ostrya_core::FileHeader,
) -> Result<Checksum> {
let mode = self.repo.mode();
let (fsync, per_object_fsync) = self.fsync_flags()?;
let verity = self.verity()?;
let objects = self.repo.objects_fd().try_clone_to_owned()?;
let staging = self.staging_fd().try_clone_to_owned()?;
let key = checksum;
let outcome = self
.unblock(move || {
let ctx = StageCtx {
objects_fd: objects.as_fd(),
staging_fd: staging.as_fd(),
mode,
fsync,
per_object_fsync,
sync_metadata: false,
verity,
};
stage_symlink_blocking(&ctx, &key, &header)
})
.await?;
self.record(checksum, ObjectType::File, mode, outcome, false)
}
/// Stages a metadata object from its serialized bytes.
///
/// [`write_metadata`](Transaction::write_metadata) calls it.
pub(crate) async fn stage_metadata(
&self,
checksum: Checksum,
ty: ObjectType,
bytes: Vec<u8>,
) -> Result<Checksum> {
self.stage_metadata_outcome(checksum, ty, bytes)
.await
.map(|_| checksum)
}
/// Stages a metadata object as
/// [`stage_metadata`](Transaction::stage_metadata) does.
///
/// Returns `true` if the call wrote the object, and `false` if the
/// repository holds it already.
pub(crate) async fn stage_metadata_outcome(
&self,
checksum: Checksum,
ty: ObjectType,
bytes: Vec<u8>,
) -> Result<bool> {
let mode = self.repo.mode();
let (fsync, per_object_fsync) = self.fsync_flags()?;
let verity = self.verity()?;
// After `sync_staged` each metadata object is synced on its own, so the
// `syncfs` that already ran still covers every staged object.
let sync_metadata = fsync && self.staged.lock().unwrap().presynced.is_some();
let objects = self.repo.objects_fd().try_clone_to_owned()?;
let staging = self.staging_fd().try_clone_to_owned()?;
let key = checksum;
#[cfg(test)]
let gate =
crate::jobs::job_gate::key(self.repo.repo_fd(), format!("stage {}", checksum.to_hex()));
let outcome = self
.unblock(move || {
#[cfg(test)]
let _gate = crate::jobs::job_gate::pass(&gate, staging.as_fd())?;
let ctx = StageCtx {
objects_fd: objects.as_fd(),
staging_fd: staging.as_fd(),
mode,
fsync,
per_object_fsync,
sync_metadata,
verity,
};
stage_metadata_blocking(&ctx, &key, ty, &bytes)
})
.await?;
let written = !outcome.deduped;
self.record_object(checksum, ty, mode, outcome, true, false, sync_metadata)?;
Ok(written)
}
/// Imports one object from the `objects/` directory of the local
/// repository `src` with a hardlink, which shares the source inode.
///
/// The two repositories must store the object in the same form. The source
/// inode must have the ownership that a write here gives already.
/// [`stage_import_blocking`] states the rules. If `src` is a handle in the
/// strict open mode, the import follows the rules of a strict source of
/// that function. The local pull path calls this method.
///
/// Returns `true` if the object is staged. `false` is a content object
/// whose link the call refused. The caller then imports it through the
/// logical header of the object. A metadata object is always staged, by
/// link or by copy.
pub(crate) async fn stage_import(
&self,
src: &Repo,
checksum: Checksum,
ty: ObjectType,
force_copy: bool,
) -> Result<bool> {
let mode = self.repo.mode();
let (fsync, per_object_fsync) = self.fsync_flags()?;
let verity = self.verity()?;
let objects = self.repo.objects_fd().try_clone_to_owned()?;
let staging = self.staging_fd().try_clone_to_owned()?;
let source = src.objects_fd().try_clone_to_owned()?;
let (src_mode, strict) = (src.mode(), src.is_strict());
// The ownership that a link must match. The call measures it only if it
// tries a link. The measure creates and removes a staging temporary,
// and a forced copy or a sealing repository never reads the result.
let link_owner = if force_copy || verity != Tristate::No {
None
} else {
Some(self.fresh_owner().await?)
};
let outcome = self
.unblock(move || {
let ctx = StageCtx {
objects_fd: objects.as_fd(),
staging_fd: staging.as_fd(),
mode,
fsync,
per_object_fsync,
sync_metadata: false,
verity,
};
stage_import_blocking(
&ctx,
source.as_fd(),
&checksum,
ty,
src_mode,
strict,
link_owner,
)
})
.await?;
let Some(outcome) = outcome else {
return Ok(false);
};
// An imported object has no size record. A pull writes no commit, so
// this transaction never writes `ostree.sizes`. The call also never
// reads the payload, so the unpacked length is not known.
self.record_object(checksum, ty, mode, outcome, false, false, false)?;
Ok(true)
}
/// Imports one regular-file content object from the local repository
/// `src` with a clone of its payload.
///
/// The call applies the inode policy of this repository from the logical
/// header of the object. The two modes must store the payload in the same
/// form. [`stage_clone_content_blocking`] states the rules. If `src` is a
/// handle in the strict open mode, the clone follows the rules of a strict
/// source of that function. The local pull path calls this method.
pub(crate) async fn stage_clone_content(
&self,
src: &Repo,
checksum: Checksum,
header: ostrya_core::FileHeader,
unpacked: u64,
) -> Result<()> {
let mode = self.repo.mode();
let (fsync, per_object_fsync) = self.fsync_flags()?;
let verity = self.verity()?;
let objects = self.repo.objects_fd().try_clone_to_owned()?;
let staging = self.staging_fd().try_clone_to_owned()?;
let source = src.objects_fd().try_clone_to_owned()?;
let (src_mode, strict) = (src.mode(), src.is_strict());
let outcome = self
.unblock(move || {
let ctx = StageCtx {
objects_fd: objects.as_fd(),
staging_fd: staging.as_fd(),
mode,
fsync,
per_object_fsync,
sync_metadata: false,
verity,
};
stage_clone_content_blocking(
&ctx,
source.as_fd(),
&checksum,
src_mode,
strict,
&header,
unpacked,
)
})
.await?;
// An imported object has no size record. A pull writes no commit, so
// this transaction never writes `ostree.sizes`.
self.record_object(
checksum,
ObjectType::File,
mode,
outcome,
false,
true,
false,
)?;
Ok(())
}
/// Records the outcome of a staged object.
///
/// The call takes the blocks that the object allocated from the free-space
/// budget, adds the object to the staged set, and updates the statistics.
/// The call is idempotent by identity, so a second stage of an object that
/// is staged in this transaction does nothing.
fn record(
&self,
checksum: Checksum,
ty: ObjectType,
mode: RepoMode,
outcome: StageOutcome,
payload: bool,
) -> Result<Checksum> {
self.record_object(checksum, ty, mode, outcome, true, payload, false)
}
/// Records a composefs image that the caller linked into the staging
/// directory as the image of `commit`.
///
/// The image takes its size from the free-space budget. It adds no size
/// record and no statistic. A second record of an image of the same
/// commit does nothing.
pub(crate) fn record_image(&self, commit: Checksum, outcome: StageOutcome) -> Result<()> {
let mut staged = self.staged.lock().unwrap();
if staged.images.contains_key(&commit) {
return Ok(());
}
if outcome.on_disk_size > staged.free_budget {
return Err(Error::InsufficientFreeSpace {
shortfall: outcome.on_disk_size - staged.free_budget,
});
}
staged.free_budget -= outcome.on_disk_size;
staged.images.insert(
commit,
StagedObject {
staging_name: outcome.staging_name,
dest: outcome.dest,
},
);
Ok(())
}
/// Records the outcome of a staged object, as [`record`](Transaction::record)
/// does, with all flags.
///
/// - `with_size`: the object adds an archive size record. An import adds
/// none, because the pull that imports it writes no commit to carry one.
/// - `payload`: the object is a regular-file content object. Its unpacked
/// length adds to
/// [`content_bytes_unpacked`](TransactionStats::content_bytes_unpacked).
/// A symlink and a metadata object add none.
/// - `synced`: the file of the object was synced on its own after
/// `sync_staged`. The count of durable objects then includes it.
#[allow(clippy::too_many_arguments)]
fn record_object(
&self,
checksum: Checksum,
ty: ObjectType,
mode: RepoMode,
outcome: StageOutcome,
with_size: bool,
payload: bool,
synced: bool,
) -> Result<Checksum> {
let mut staged = self.staged.lock().unwrap();
// The totals count each object offered, dedup hits included. They are
// the work that the caller asked for.
match ty {
ObjectType::File => staged.stats.content_total += 1,
_ => staged.stats.metadata_total += 1,
}
// An object that the object store holds already is inside the
// `ostree.sizes` scope, as a freshly staged one is. `write_commit` reads
// its sizes from disk.
if with_size
&& mode.is_archive()
&& let Some(scope) = &mut staged.size_scope
{
scope.insert(checksum, ty);
}
if outcome.deduped {
return Ok(checksum);
}
if staged.objects.contains_key(&(checksum, ty)) {
// Already staged in this transaction: idempotent no-op.
return Ok(checksum);
}
// Only freshly written blocks come off the budget. An imported object
// that shares the source inode by hardlink allocates nothing. An object
// whose payload came from a `FICLONE` reflink shares the source extents.
// So neither reduces the bytes free on the file system.
let allocated = match outcome.blocks {
Blocks::Written => outcome.on_disk_size,
Blocks::Linked | Blocks::Reflinked => 0,
};
if allocated > staged.free_budget {
return Err(Error::InsufficientFreeSpace {
shortfall: allocated - staged.free_budget,
});
}
staged.free_budget -= allocated;
staged.objects.insert(
(checksum, ty),
StagedObject {
staging_name: outcome.staging_name,
dest: outcome.dest,
},
);
if synced && let Some(durable) = &mut staged.presynced {
*durable += 1;
}
// In archive mode every staged object -- content and metadata alike --
// contributes an `ostree.sizes` record. A metadata object is stored
// raw, so its unpacked size equals its on-disk size.
if with_size && mode.is_archive() {
let unpacked = if ty == ObjectType::File {
outcome.unpacked
} else {
outcome.on_disk_size
};
staged.sizes.insert(
checksum,
SizeRecord {
compressed: outcome.on_disk_size,
unpacked,
objtype: ty,
},
);
}
match ty {
ObjectType::File => {
staged.stats.content_written += 1;
staged.stats.content_bytes_written += outcome.on_disk_size;
if payload {
staged.stats.content_bytes_unpacked += outcome.unpacked;
}
}
_ => staged.stats.metadata_written += 1,
}
Ok(checksum)
}
/// Returns the `fsync` and `per-object-fsync` values of the transaction.
///
/// Each value comes from its override, from
/// [`set_fsync`](Transaction::set_fsync) or
/// [`set_per_object_fsync`](Transaction::set_per_object_fsync), if the
/// transaction has one. Else it comes from the repository config. Each write
/// path of the transaction reads this pair: the per-object writes, the
/// publication step, the detached-metadata writes, and the ref writes.
///
/// The call reads `[core] fsync` and `[core] per-object-fsync` in all
/// cases, also when an override is set. So each transaction reports a value
/// that the reader refuses, and an override never hides it.
pub(crate) fn fsync_flags(&self) -> Result<(bool, bool)> {
let config = self.repo.config();
let configured = config.fsync()?;
let configured_per_object = config.per_object_fsync()?;
let fsync = self.fsync_override.unwrap_or(configured);
let per_object = self
.per_object_fsync_override
.unwrap_or(configured_per_object);
Ok((fsync, per_object))
}
/// Returns the `[ex-integrity] fsverity` value of the repository config.
///
/// The stage of each regular-file object applies it.
fn verity(&self) -> Result<Tristate> {
self.repo.config().fsverity()
}
/// Publishes the staged objects into `objects/` and writes the queued refs.
///
/// # Sequence
///
/// 1. The call checks each queued refspec. If a refspec is malformed, the
/// call fails before it publishes an object, and it writes nothing.
/// The call then checks each `ostrya.related` entry of each dict that
/// [`set_commit_detached_metadata`](Transaction::set_commit_detached_metadata)
/// queued, as [`Repo::write_commit_detached_metadata`] does. On a
/// refusal the call publishes no object and writes nothing.
/// 2. If `[ex-ostrya] generate-composefs` is `true`, the call builds the
/// composefs image of each commit that the writer recorded as complete,
/// as `# Composefs images` states. If a build fails, the call publishes
/// no object and writes nothing.
/// 3. The call renames each staged object into `objects/<xx>/`, and then
/// each staged composefs image into
/// `extensions/ostrya/composefs/<xx>/`. So an image is in place only
/// after each object of the transaction. The rename of an image
/// replaces a stored image of the same commit.
/// 4. The call checks the queued refs against the ref store, as
/// [`set_ref`](Transaction::set_ref) states. It also compares each
/// entry of [`set_ref_expecting`](Transaction::set_ref_expecting) with
/// the ref store. On a refusal the call writes no detached metadata
/// and no ref.
/// 5. The call writes the queued detached-metadata edits.
/// 6. The call writes the queued refs. Each ref write is atomic: a temp
/// file, then a rename. The set of ref writes is not atomic as a whole.
/// If a ref write fails after the check, for example on a full disk or
/// below an alias as [`set_ref`](Transaction::set_ref) states, the refs
/// written before it stay. The call does not roll them back.
/// 7. The call removes the staging directory and releases the repository
/// lock.
///
/// Steps 4, 5, and 6 run in one trip to the blocking pool.
///
/// # Composefs images
///
/// Each writer of a complete commit records the commit for the build of
/// step 2: [`write_commit`](Transaction::write_commit),
/// [`write_commit_checked`](Transaction::write_commit_checked), a pull
/// from a remote, a local pull, a receive with ref updates, and
/// [`Repo::apply_static_delta`]. The commit writes and
/// [`Repo::apply_static_delta`] record a commit only if they stage its
/// object, so a commit that the repository holds already, complete or
/// partial, gets no image from them. A pull records each commit that it
/// completes: the targets, the parents within the depth, the
/// dependencies, and each held partial commit. A partial commit is not
/// recorded. [`write_metadata`](Transaction::write_metadata) records no
/// commit. [`Repo::commit_add_composefs_metadata`] and the server commit
/// of a receive build the image of their commit themselves, and stage it
/// if the transaction stages the commit. So step 2 does not build it
/// again.
///
/// The build reads each recorded commit, staged first. It skips a commit
/// that the transaction did not stage and that has no `.commitpartial`
/// marker, so a commit that the repository holds complete before the
/// transaction gets no image. It also skips a commit with no
/// `ostree.composefs.digest.v0` key and a commit whose image is staged.
/// For each other commit, it makes the steps of
/// [`write_composefs_image`](Transaction::write_composefs_image). The
/// build reads the fs-verity digest of a sealed object from the kernel.
/// It reads and hashes each other object one time, and uses that digest
/// for each commit and each path that names the object.
///
/// # Durability
///
/// One fsync policy applies to all steps: the value from
/// [`set_fsync`](Transaction::set_fsync), or else `[core] fsync` of the
/// repository config. With fsync on, the call syncs as follows:
///
/// - Before the renames of step 3, it runs `syncfs` on the repository.
/// - After the renames of the objects, it runs `fsync` on each fanout
/// directory that got an object, and on `objects/`.
/// - After the renames of the images, it runs `fsync` on each
/// `extensions/ostrya/composefs/<xx>/` directory that got an image, and
/// on `extensions/ostrya/composefs/`. It syncs each directory that the
/// call creates into its parent.
/// - Before the rename of each ref, it runs `fdatasync` on the temp file.
/// - After the last ref rename, it runs `fsync` once on each directory that
/// gained or lost a ref name, deepest first.
///
/// With this sequence, a commit and its `.commitmeta` are durable before a
/// ref names them. Each ref is durable when the call returns. With fsync
/// off, no step syncs.
///
/// # Locks
///
/// The transaction holds the repository lock from its begin to the end of
/// this call, in the [`LockKind`](crate::LockKind) of its begin. Steps 2
/// and 3 run with no update lock.
///
/// If the transaction writes a ref, a ref removal included, or detached
/// metadata, the call takes the update lock for steps 4 to 6. The update
/// lock excludes the other writers of refs and detached metadata, as
/// [`UpdateGuard`](crate::UpdateGuard) states. The wait is for the update
/// lock alone, because the transaction holds the repository lock already. A
/// transaction that writes neither does not take the update lock.
///
/// # Cancellation
///
/// The update lock, the repository lock, and the staging directory move
/// into the blocking closure of steps 4 to 6. The closure releases them
/// when its writes end. If a caller drops the returned future, the writes
/// complete, and the locks and the staged files stay until the writes end.
///
/// # Errors
///
/// - [`Error::InvalidRefspec`] if a queued refspec is malformed, or if
/// the collection id of a queued collection ref does not pass
/// [`is_collection_id`](crate::is_collection_id) or is longer than 255
/// bytes. The call publishes no object and writes no ref.
/// - [`Error::InvalidRelated`] if an `ostrya.related` entry of a queued
/// detached-metadata dict is not a variant of type `a(say)`, or if one
/// of its elements has an empty name or a checksum that is not 32
/// bytes. The call publishes no object and writes nothing.
/// - [`Error::InvalidRelated`] if a build source that
/// [`add_detached_related`](Transaction::add_detached_related) queued
/// meets a defective stored `ostrya.related` value. The published
/// objects stay, and the call writes no ref.
/// - Under `[ex-ostrya] generate-composefs`, the errors of
/// [`write_composefs_image`](Transaction::write_composefs_image) for a
/// recorded commit. Among them, [`Error::InvalidFormat`] if the value of
/// the digest key of the commit is malformed, and
/// [`Error::ComposefsDigestMismatch`] if the image of its tree does not
/// have the digest that the key records. The call publishes no object
/// and writes nothing.
/// - The errors of [`RepoConfig::generate_composefs`](crate::RepoConfig::generate_composefs)
/// if a writer recorded a commit.
/// - [`Error::InvalidFormat`] if a staged composefs image meets a
/// component of `extensions/ostrya/composefs/<xx>/` that is a symlink or
/// no directory. The objects and the images that the call renamed
/// before stay, and the call writes no detached metadata and no ref.
/// - [`Error::LockTimeout`] if the wait for the update lock passes
/// `[core] lock-timeout-secs`. The published objects stay, and the call
/// writes no detached metadata and no ref.
/// - [`Error::RefNotWritable`] if the check of step 4 refuses a queued
/// ref. The published objects stay, and the call writes no detached
/// metadata and no ref.
/// - [`Error::RefMismatch`] if the ref of an entry of
/// [`set_ref_expecting`](Transaction::set_ref_expecting) does not have
/// the expected state. The published objects stay, and the call writes
/// no detached metadata and no ref.
/// - [`Error::InvalidFormat`] or [`Error::Core`] if the ref file of an
/// entry of [`set_ref_expecting`](Transaction::set_ref_expecting) does
/// not parse. The published objects stay, and the call writes no
/// detached metadata and no ref.
/// - [`Error::Core`] if `[core] fsync`, `[core] per-object-fsync`, or
/// `[core] lock-timeout-secs` has a value that does not parse.
/// - [`Error::Core`] if the stored detached metadata of a commit does not
/// parse.
/// - [`Error::InvalidFormat`] if `[core] lock-timeout-secs` is less than
/// `-1`, or if a signature entry of the stored detached metadata is not
/// an array.
/// - [`Error::Io`] if the check of step 4 cannot read a queued ref path,
/// or cannot open or read the ref file of an entry of
/// [`set_ref_expecting`](Transaction::set_ref_expecting), for example
/// with `EACCES` or `ELOOP`. The call then writes no detached metadata
/// and no ref.
/// - [`Error::Io`] if a rename, a sync, or a write of a ref or of the
/// detached metadata fails.
pub async fn commit(mut self) -> Result<TransactionStats> {
let refs = self.resolve_ref_queue()?;
self.check_queued_related()?;
Box::pin(self.build_recorded_images()).await?;
let synced = self.publish().await?;
if refs.is_empty() && self.detached.lock().unwrap().edits.is_empty() {
let stats = self.staged.lock().unwrap().stats;
self.reap_staging().await;
return Ok(stats);
}
let held = self.repo.lock_update().await?;
self.write_tail(refs, synced, Some(held)).await
}
/// Commits the transaction as [`commit`](Transaction::commit) does, under
/// the update lock that the caller holds.
///
/// The reference to the hold makes a call without the lock a type error.
/// The call does not take the lock again.
pub(crate) async fn commit_under(self, held: &UpdateLockHeld) -> Result<TransactionStats> {
debug_assert!(
self.repo.holds_update_lock(held),
"the hold is not the update lock of this repository"
);
let refs = self.resolve_ref_queue()?;
self.check_queued_related()?;
Box::pin(self.build_recorded_images()).await?;
let synced = self.publish().await?;
self.write_tail(refs, synced, None).await
}
/// Checks each `ostrya.related` entry in each dict that
/// [`set_commit_detached_metadata`](Transaction::set_commit_detached_metadata)
/// queued, as
/// [`Repo::write_commit_detached_metadata`] checks the dict that it
/// writes.
///
/// The check reads no file, so it holds the lock of the queue and no
/// await. The first defect in queue order gives the error.
fn check_queued_related(&self) -> Result<()> {
let queue = self.detached.lock().unwrap();
for (checksum, edit) in &queue.edits {
if let Some(dict) = &edit.replace {
crate::related::check_detached(checksum, dict)?;
}
}
Ok(())
}
/// Checks `refs`, writes the queued detached metadata and then `refs`,
/// removes the staging directory, and releases the locks, in one trip to
/// the blocking pool.
///
/// `synced` is `true` if the publication step ran its `syncfs`. The staging
/// directory, the repository lock, and `held`, if given, move into the
/// blocking closure. The closure releases the update lock after the last
/// ref write, then removes the staging directory, then releases the
/// repository lock.
///
/// The move makes sure that a caller that drops the returned future cannot
/// release a lock or remove a staged file while the writes run.
async fn write_tail(
mut self,
refs: Vec<crate::refs::ResolvedRef>,
synced: bool,
held: Option<UpdateLockHeld>,
) -> Result<TransactionStats> {
let detached = self.detached_job(synced)?;
let (fsync, _) = self.fsync_flags()?;
let repo_mode = self.repo.mode();
let repo_fd = self.repo.repo_fd().try_clone_to_owned()?;
let stats = self.staged.lock().unwrap().stats;
let staging = self
.staging
.take()
.expect("staging directory present during the transaction");
let lock = self.lock;
ostrya_rt::unblock(move || {
#[cfg(test)]
test_tail::pass(repo_fd.as_fd());
let tmp_fd = staging.tmp_fd();
let written = crate::refs::check_resolved_refs_blocking(repo_fd.as_fd(), &refs)
.and_then(|()| detached.run(tmp_fd))
.and_then(|()| {
crate::refs::write_resolved_refs_blocking(
repo_fd.as_fd(),
tmp_fd,
&refs,
fsync,
repo_mode,
)
});
drop(held);
drop(staging);
drop(lock);
written
})
.await?;
Ok(stats)
}
/// Makes the objects staged so far durable before
/// [`commit`](Transaction::commit).
///
/// With fsync on, the call runs one `syncfs` of the repository. The
/// publication step of `commit` then runs no `syncfs` of its own, unless an
/// object was staged after this call. With fsync off, the call does
/// nothing.
#[cfg(feature = "receive")]
pub(crate) async fn sync_staged(&self) -> Result<()> {
let (fsync, _) = self.fsync_flags()?;
if !fsync {
return Ok(());
}
// Each object in the count is in the staging directory before the
// `syncfs` starts, because an object is recorded after its write. A
// composefs image is in the staging directory too.
let count = {
let staged = self.staged.lock().unwrap();
staged.objects.len() + staged.images.len()
};
let repo_fd = self.repo.repo_fd().try_clone_to_owned()?;
ostrya_rt::unblock(move || rustix::fs::syncfs(repo_fd.as_fd())).await?;
self.staged.lock().unwrap().presynced = Some(count);
Ok(())
}
/// Returns `true` if the publication step runs its `syncfs`.
///
/// The step runs it with fsync on, unless `sync_staged` made each staged
/// object durable already.
fn syncfs_at_publish(&self, fsync: bool) -> bool {
let staged = self.staged.lock().unwrap();
fsync && staged.presynced != Some(staged.objects.len() + staged.images.len())
}
/// Discards the transaction and its staged objects, and releases the lock.
///
/// The call first waits for each blocking job of the transaction that a
/// dropped future left before the job ended.
///
/// # Errors
///
/// The call does not fail. It always returns `Ok(())`.
pub async fn abort(mut self) -> Result<()> {
self.settle().await;
self.reap_staging().await;
Ok(())
}
/// Renames each staged object into `objects/`, and then each staged
/// composefs image into `extensions/ostrya/composefs/`, on the blocking
/// pool.
///
/// Returns `true` if the step ran its `syncfs`.
async fn publish(&self) -> Result<bool> {
let (objects, images) = {
let staged = self.staged.lock().unwrap();
(
rename_pairs(staged.objects.values()),
rename_pairs(staged.images.values()),
)
};
if objects.is_empty() && images.is_empty() {
return Ok(false);
}
let (fsync, _) = self.fsync_flags()?;
let syncfs = self.syncfs_at_publish(fsync);
let repo_mode = self.repo.mode();
let repo_fd = self.repo.repo_fd().try_clone_to_owned()?;
let objects_fd = self.repo.objects_fd().try_clone_to_owned()?;
let staging_fd = self.staging_fd().try_clone_to_owned()?;
ostrya_rt::unblock(move || {
publish_blocking(
repo_fd.as_fd(),
objects_fd.as_fd(),
staging_fd.as_fd(),
&objects,
&images,
syncfs,
fsync,
repo_mode,
)
})
.await?;
Ok(syncfs)
}
/// Removes the staging directory on the blocking pool, if it is still
/// present.
async fn reap_staging(&mut self) {
if let Some(staging) = self.staging.take() {
ostrya_rt::unblock(move || drop(staging)).await;
}
}
}
/// Returns the staging name and the destination of each staged entry.
fn rename_pairs<'a>(staged: impl Iterator<Item = &'a StagedObject>) -> Vec<(String, String)> {
staged
.map(|o| (o.staging_name.clone(), o.dest.clone()))
.collect()
}
/// The queued detached-metadata edits of a commit, taken from the
/// transaction for one trip to the blocking pool.
struct DetachedJob {
queued: Vec<(Checksum, DetachedEdit)>,
fsync: bool,
/// `true` if the staged files are durable already, from the `syncfs` of
/// the publication step.
staged_durable: bool,
repo_mode: RepoMode,
objects_fd: std::os::fd::OwnedFd,
staging_fd: std::os::fd::OwnedFd,
}
impl DetachedJob {
/// Applies the edits.
///
/// The call installs the staged files first, in one step. The rest of the
/// edit of each commit then applies to its installed file. With fsync on,
/// if the publication step ran no `syncfs`, a `syncfs` makes the staged
/// files durable before the install.
///
/// The call writes each other edit before the next one starts, and with
/// fsync on it makes the edit durable first. Each edit takes the
/// process-wide guard of detached-metadata edits for itself alone.
///
/// `tmp_fd` is the open `tmp/` of the repository, where each edit creates
/// its temp file. The caller holds the update lock.
fn run(self, tmp_fd: BorrowedFd<'_>) -> Result<()> {
let staged: Vec<(&Checksum, &str)> = self
.queued
.iter()
.filter_map(|(checksum, edit)| Some((checksum, edit.staged.as_deref()?)))
.collect();
if !staged.is_empty() {
if self.fsync && !self.staged_durable {
rustix::fs::syncfs(self.staging_fd.as_fd())?;
}
crate::commit::install_detached_blocking(
self.staging_fd.as_fd(),
&staged,
self.objects_fd.as_fd(),
self.fsync,
self.repo_mode,
)?;
}
for (checksum, edit) in self.queued {
if edit.staged.is_some()
&& edit.replace.is_none()
&& edit.merge.is_none()
&& edit.related.is_empty()
&& edit.appends.is_empty()
{
continue;
}
crate::commit::merge_detached_blocking(
tmp_fd,
self.objects_fd.as_fd(),
&checksum,
edit.replace,
edit.merge,
edit.related,
edit.appends,
self.fsync,
self.repo_mode,
)?;
}
Ok(())
}
}
/// A transaction moves freely across tasks and threads.
const _: fn() = || {
fn is_send_sync<T: Send + Sync>() {}
is_send_sync::<Transaction>();
is_send_sync::<crate::StagedComposefsImage<'static>>();
is_send_sync::<crate::ComposefsImageAdd>();
is_send_sync::<crate::ComposefsImageState>();
};
/// A gate for the unit tests, at the commit step that writes detached metadata
/// and refs.
///
/// A test arms the gate for one repository root. The next such step of a
/// commit of that repository then reports that it started, and waits until the
/// test opens the gate.
#[cfg(test)]
mod test_tail {
use std::os::fd::BorrowedFd;
use std::sync::Mutex;
use std::sync::mpsc::{Receiver, Sender, channel};
type Gate = ((u64, u64), Sender<()>, Receiver<()>);
static GATES: Mutex<Vec<Gate>> = Mutex::new(Vec::new());
/// Arms the gate for the repository root `root`, and returns the receiver
/// of the start report and the sender that opens the gate.
pub(super) fn arm(root: &std::path::Path) -> (Receiver<()>, Sender<()>) {
use std::os::unix::fs::MetadataExt;
let meta = std::fs::metadata(root).unwrap();
let (started_tx, started_rx) = channel();
let (go_tx, go_rx) = channel();
GATES
.lock()
.unwrap()
.push(((meta.dev(), meta.ino()), started_tx, go_rx));
(started_rx, go_tx)
}
/// Reports the start and waits for the gate, if a gate is armed for the
/// repository root `repo_fd`.
pub(super) fn pass(repo_fd: BorrowedFd<'_>) {
let Ok(stat) = rustix::fs::fstat(repo_fd) else {
return;
};
let key = (stat.st_dev, stat.st_ino);
let gate = {
let mut gates = GATES.lock().unwrap();
let index = gates.iter().position(|gate| gate.0 == key);
index.map(|index| gates.remove(index))
};
if let Some((_, started, go)) = gate {
let _ = started.send(());
let _ = go.recv();
}
}
}
#[cfg(test)]
mod tests {
use super::*;
use crate::CreateOptions;
use crate::Ref;
use crate::write::FileMeta;
use ostrya_rt::block_on;
/// A throwaway directory removed on drop.
struct Scratch(std::path::PathBuf);
impl Scratch {
fn new(tag: &str) -> Scratch {
use std::sync::atomic::{AtomicU64, Ordering};
static COUNTER: AtomicU64 = AtomicU64::new(0);
let n = COUNTER.fetch_add(1, Ordering::Relaxed);
let dir =
std::env::temp_dir().join(format!("ostrya-txn-{}-{tag}-{n}", std::process::id()));
let _ = std::fs::remove_dir_all(&dir);
std::fs::create_dir_all(&dir).unwrap();
Scratch(dir)
}
}
impl Drop for Scratch {
fn drop(&mut self) {
let _ = std::fs::remove_dir_all(&self.0);
}
}
/// The archive size record separates the compressed `.filez` size from the
/// uncompressed payload size. A highly compressible payload makes the two
/// diverge, so recording the payload size in the `unpacked` field is the
/// only value that satisfies the assertions.
#[test]
fn archive_size_record_separates_compressed_and_unpacked() {
let scratch = Scratch::new("sizes");
let root = scratch.0.join("repo");
block_on(async {
let repo = crate::Repo::create(&root, CreateOptions::new(RepoMode::Archive))
.await
.unwrap();
let txn = repo.transaction().await.unwrap();
let payload = vec![b'a'; 8192];
let checksum = txn
.write_regfile_inline(None, &FileMeta::regular(0, 0, 0o644), &payload)
.await
.unwrap();
// Read the record out from under the lock so the guard is released
// before the abort await.
let (record, content_bytes) = {
let staged = txn.staged.lock().unwrap();
let record = staged.sizes.get(&checksum).copied().expect("size record");
(record, staged.stats.content_bytes_written)
};
assert_eq!(
record.unpacked,
payload.len() as u64,
"unpacked is the pre-compression payload size"
);
assert_eq!(
record.compressed, content_bytes,
"compressed is the on-disk .filez size"
);
assert!(
record.compressed < record.unpacked,
"a compressible payload stores smaller than it unpacks: \
compressed={} unpacked={}",
record.compressed,
record.unpacked,
);
txn.abort().await.unwrap();
});
}
/// `sync_staged` makes the objects staged so far durable, so the
/// publication step runs no `syncfs` of its own. An object staged after the
/// call brings the `syncfs` back, an object staged a second time does not,
/// and the commit publishes every object.
#[cfg(feature = "receive")]
#[test]
fn sync_staged_skips_the_publication_syncfs_until_a_later_stage() {
let scratch = Scratch::new("presynced");
block_on(async {
let repo = crate::Repo::create(
&scratch.0.join("repo"),
CreateOptions::new(RepoMode::Archive),
)
.await
.unwrap();
let mut txn = repo.transaction().await.unwrap();
txn.set_fsync(true);
let meta = FileMeta::regular(0, 0, 0o644);
let first = txn.write_regfile_inline(None, &meta, b"one").await.unwrap();
assert!(txn.syncfs_at_publish(true));
txn.sync_staged().await.unwrap();
assert!(!txn.syncfs_at_publish(true));
txn.write_regfile_inline(None, &meta, b"one").await.unwrap();
assert!(
!txn.syncfs_at_publish(true),
"a second stage adds no object"
);
let second = txn.write_regfile_inline(None, &meta, b"two").await.unwrap();
assert!(
txn.syncfs_at_publish(true),
"a later object needs the syncfs"
);
txn.sync_staged().await.unwrap();
assert!(!txn.syncfs_at_publish(true));
txn.commit().await.unwrap();
for checksum in [first, second] {
assert!(repo.has_object(ObjectType::File, &checksum).await.unwrap());
}
});
}
/// Metadata objects staged after `sync_staged` are synced one by one and
/// counted as durable. So the anchor commit that a receiving session stages
/// under its lock brings no `syncfs` back at publication.
#[cfg(feature = "receive")]
#[test]
fn metadata_staged_after_sync_staged_needs_no_second_syncfs() {
let scratch = Scratch::new("presynced-anchor");
block_on(async {
let repo = crate::Repo::create(
&scratch.0.join("repo"),
CreateOptions::new(RepoMode::Archive),
)
.await
.unwrap();
let mut txn = repo.transaction().await.unwrap();
txn.set_fsync(true);
let meta = FileMeta::regular(0, 0, 0o644);
txn.write_regfile_inline(None, &meta, b"one").await.unwrap();
txn.sync_staged().await.unwrap();
let anchor = repo
.stage_anchor_commit(&txn, "org.example.C", None, Some(1_700_000_000))
.await
.unwrap();
{
let staged = txn.staged.lock().unwrap();
assert_eq!(
staged.objects.len(),
4,
"the file, dirmeta, dirtree, commit"
);
assert_eq!(staged.presynced, Some(staged.objects.len()));
}
assert!(!txn.syncfs_at_publish(true));
txn.commit().await.unwrap();
assert_eq!(
repo.resolve_ref_tip(&Ref::local(crate::summary::OSTREE_METADATA_REF))
.await
.unwrap(),
Some(anchor)
);
});
}
/// A queued merge runs on the stored dict before the queued signatures.
/// The signature lists get the union, another key takes the incoming
/// value, and a stored key that the incoming dict does not hold stays.
#[cfg(feature = "receive")]
#[test]
fn a_queued_merge_applies_before_the_appended_signatures() {
use crate::sign::append_signature;
const KEY: &str = "ostree.sign.ed25519";
let scratch = Scratch::new("merge-edit");
block_on(async {
let repo = crate::Repo::create(
&scratch.0.join("repo"),
CreateOptions::new(RepoMode::Archive),
)
.await
.unwrap();
let commit = Checksum::from_bytes([0x22; 32]);
let str_variant = |text: &str| {
Value::variant(
ostrya_core::Type::parse("s").unwrap(),
Value::Str(text.into()),
)
};
let mut stored = Value::Array(Vec::new());
append_signature(&mut stored, KEY, b"A".to_vec()).unwrap();
crate::commit::append_dict_entry(&mut stored, "kept", str_variant("stored")).unwrap();
crate::commit::append_dict_entry(&mut stored, "other", str_variant("stored")).unwrap();
repo.write_commit_detached_metadata(&commit, Some(&stored))
.await
.unwrap();
let mut incoming = Value::Array(Vec::new());
append_signature(&mut incoming, KEY, b"A".to_vec()).unwrap();
append_signature(&mut incoming, KEY, b"B".to_vec()).unwrap();
crate::commit::append_dict_entry(&mut incoming, "other", str_variant("incoming"))
.unwrap();
let txn = repo.transaction().await.unwrap();
txn.append_signature(&commit, KEY, b"C".to_vec());
txn.merge_commit_detached(
&commit,
crate::summary::serialize_signature_dict(&incoming).unwrap(),
Vec::new(),
);
txn.commit().await.unwrap();
let dict = repo
.read_commit_detached_metadata(&commit)
.await
.unwrap()
.unwrap();
assert_eq!(
crate::sign::signatures_for(&dict, KEY),
vec![b"A".to_vec(), b"B".to_vec(), b"C".to_vec()]
);
let text = |key: &str| {
dict.dict_get(key)
.and_then(Value::as_variant)
.and_then(|(_, value)| value.as_str().map(str::to_owned))
};
assert_eq!(text("kept").as_deref(), Some("stored"));
assert_eq!(text("other").as_deref(), Some("incoming"));
});
}
/// With fsync off `sync_staged` does nothing, and the publication step runs
/// no `syncfs` either way.
#[cfg(feature = "receive")]
#[test]
fn sync_staged_with_fsync_off_does_nothing() {
let scratch = Scratch::new("presynced-off");
block_on(async {
let repo = crate::Repo::create(
&scratch.0.join("repo"),
CreateOptions::new(RepoMode::Archive),
)
.await
.unwrap();
let mut txn = repo.transaction().await.unwrap();
txn.set_fsync(false);
txn.write_regfile_inline(None, &FileMeta::regular(0, 0, 0o644), b"one")
.await
.unwrap();
txn.sync_staged().await.unwrap();
assert_eq!(txn.staged.lock().unwrap().presynced, None);
assert!(!txn.syncfs_at_publish(false));
txn.abort().await.unwrap();
});
}
/// If the clone path cannot open a source object because it is gone, the
/// error reports the object as missing. The link path gives the same
/// answer for the same condition.
#[test]
fn a_clone_of_an_absent_source_object_reports_it_missing() {
let scratch = Scratch::new("clone-missing");
block_on(async {
let src = crate::Repo::create(
&scratch.0.join("src"),
CreateOptions::new(RepoMode::BareUserShared),
)
.await
.unwrap();
let dst = crate::Repo::create(
&scratch.0.join("dst"),
CreateOptions::new(RepoMode::BareUser),
)
.await
.unwrap();
let txn = dst.transaction().await.unwrap();
let checksum = Checksum::from_bytes([0x11; 32]);
let err = txn
.stage_clone_content(
&src,
checksum,
FileMeta::regular(0, 0, 0o644).regular_header(),
0,
)
.await
.unwrap_err();
assert!(
matches!(
err,
Error::ObjectNotFound { checksum: c, ty }
if c == checksum && ty == ObjectType::File
),
"unexpected error: {err}"
);
txn.abort().await.unwrap();
});
}
/// Create an archive repository under `scratch`, with `lock-timeout-secs=0`
/// in its `[core]` group, and open it again so the handle reads the value.
async fn no_wait_repo(scratch: &Scratch) -> crate::Repo {
let root = scratch.0.join("repo");
drop(
crate::Repo::create(&root, CreateOptions::new(RepoMode::Archive))
.await
.unwrap(),
);
let config = root.join("config");
let mut text = std::fs::read_to_string(&config).unwrap();
text.push_str("lock-timeout-secs=0\n");
std::fs::write(&config, text).unwrap();
crate::Repo::open(&root).await.unwrap()
}
/// The `.commitmeta` path of `commit` under the archive repository at
/// `root`.
fn commitmeta(root: &std::path::Path, commit: &Checksum) -> std::path::PathBuf {
root.join("objects").join(ostrya_core::loose_path(
commit,
ObjectType::CommitMeta,
RepoMode::Archive,
))
}
/// An `a{sv}` dict of one string entry.
fn string_dict(key: &str, text: &str) -> Value {
Value::Array(vec![Value::Tuple(vec![
Value::Str(key.into()),
Value::variant(
ostrya_core::Type::parse("s").unwrap(),
Value::Str(text.into()),
),
])])
}
/// Staged bytes reach `objects/` verbatim at the commit, at mode 0644, and
/// the signatures queued after the stage append to them.
#[test]
fn a_staged_file_is_installed_at_the_commit_and_takes_later_appends() {
use std::os::unix::fs::PermissionsExt;
const KEY: &str = "ostree.sign.ed25519";
let scratch = Scratch::new("staged-detached");
block_on(async {
let repo = no_wait_repo(&scratch).await;
let root = scratch.0.join("repo");
let commit = Checksum::from_bytes([0x31; 32]);
let staged = crate::summary::serialize_signature_dict(&string_dict("a", "x")).unwrap();
let txn = repo.transaction().await.unwrap();
txn.stage_commit_detached_bytes(&commit, b"first".to_vec())
.await
.unwrap();
txn.stage_commit_detached_bytes(&commit, staged.clone())
.await
.unwrap();
assert!(
!commitmeta(&root, &commit).exists(),
"nothing before commit"
);
txn.commit().await.unwrap();
assert_eq!(std::fs::read(commitmeta(&root, &commit)).unwrap(), staged);
let mode = std::fs::metadata(commitmeta(&root, &commit))
.unwrap()
.permissions()
.mode();
assert_eq!(mode & 0o7777, 0o644);
let txn = repo.transaction().await.unwrap();
txn.stage_commit_detached_bytes(&commit, staged.clone())
.await
.unwrap();
Transaction::edit_for(&mut txn.detached.lock().unwrap(), &commit)
.appends
.push((KEY.to_owned(), vec![9; 64]));
txn.commit().await.unwrap();
let stored = repo
.read_commit_detached_metadata(&commit)
.await
.unwrap()
.unwrap();
assert!(stored.dict_get("a").is_some(), "the staged key stays");
assert_eq!(crate::sign::signatures_for(&stored, KEY), vec![vec![9; 64]]);
});
}
/// A dict queued after a stage replaces it, and a stage after a queued
/// dict replaces the dict.
#[test]
fn the_last_of_a_stage_and_a_queued_dict_wins() {
let scratch = Scratch::new("staged-replace");
block_on(async {
let repo = no_wait_repo(&scratch).await;
let commit = Checksum::from_bytes([0x32; 32]);
let staged = crate::summary::serialize_signature_dict(&string_dict("a", "x")).unwrap();
let txn = repo.transaction().await.unwrap();
txn.stage_commit_detached_bytes(&commit, staged.clone())
.await
.unwrap();
txn.set_commit_detached_metadata(&commit, string_dict("b", "y"));
txn.commit().await.unwrap();
assert_eq!(
repo.read_commit_detached_metadata(&commit).await.unwrap(),
Some(string_dict("b", "y"))
);
let txn = repo.transaction().await.unwrap();
txn.set_commit_detached_metadata(&commit, string_dict("b", "z"));
txn.stage_commit_detached_bytes(&commit, staged)
.await
.unwrap();
txn.commit().await.unwrap();
assert_eq!(
repo.read_commit_detached_metadata(&commit).await.unwrap(),
Some(string_dict("a", "x"))
);
});
}
/// A transaction that does not commit leaves the stored file as it
/// stands.
#[test]
fn an_aborted_transaction_installs_no_staged_file() {
let scratch = Scratch::new("staged-abort");
block_on(async {
let repo = no_wait_repo(&scratch).await;
let root = scratch.0.join("repo");
let commit = Checksum::from_bytes([0x33; 32]);
let txn = repo.transaction().await.unwrap();
txn.stage_commit_detached_bytes(&commit, b"staged".to_vec())
.await
.unwrap();
txn.abort().await.unwrap();
assert!(!commitmeta(&root, &commit).exists());
repo.write_commit_detached_metadata(&commit, Some(&string_dict("a", "x")))
.await
.unwrap();
let before = std::fs::read(commitmeta(&root, &commit)).unwrap();
let txn = repo.transaction().await.unwrap();
txn.stage_commit_detached_bytes(&commit, b"staged".to_vec())
.await
.unwrap();
drop(txn);
assert_eq!(std::fs::read(commitmeta(&root, &commit)).unwrap(), before);
});
}
/// The update lock is taken only by a commit that writes a ref, a ref
/// removal included, or detached metadata. A commit that waits in vain
/// leaves its published objects, no ref, and no detached metadata.
#[test]
fn only_a_commit_that_writes_a_ref_or_detached_metadata_takes_the_update_lock() {
let scratch = Scratch::new("lock-condition");
block_on(async {
let repo = no_wait_repo(&scratch).await;
let root = scratch.0.join("repo");
let meta = FileMeta::regular(0, 0, 0o644);
let held = repo.lock_update().await.unwrap();
let txn = repo.transaction().await.unwrap();
let object = txn.write_regfile_inline(None, &meta, b"one").await.unwrap();
txn.commit().await.unwrap();
assert!(repo.has_object(ObjectType::File, &object).await.unwrap());
let commit = Checksum::from_bytes([0x34; 32]);
let refused: [&dyn Fn(&Transaction); 3] = [
&|txn| txn.set_ref(&Ref::local("main"), Some(&commit)),
&|txn| txn.set_ref(&Ref::local("main"), None),
&|txn| txn.set_commit_detached_metadata(&commit, string_dict("a", "x")),
];
for queue in refused {
let txn = repo.transaction().await.unwrap();
let object = txn.write_regfile_inline(None, &meta, b"two").await.unwrap();
queue(&txn);
let err = txn.commit().await.unwrap_err();
assert!(matches!(err, Error::LockTimeout { secs: 0 }), "{err:?}");
assert!(repo.has_object(ObjectType::File, &object).await.unwrap());
assert_eq!(
repo.resolve_ref_tip(&Ref::local("main")).await.unwrap(),
None
);
assert!(!commitmeta(&root, &commit).exists());
}
drop(held);
});
}
/// Assert that `err` refuses the ref `name` with a reason that holds
/// `reason`.
fn assert_not_writable(err: Error, name: &str, reason: &str) {
match err {
Error::RefNotWritable { name: n, reason: r } => {
assert_eq!(n, name);
assert!(r.contains(reason), "{r}");
}
other => panic!("{other:?}"),
}
}
/// The commit of the local ref `name`, or `None`.
async fn tip(repo: &crate::Repo, name: &str) -> Option<Checksum> {
repo.resolve_ref_tip(&Ref::local(name)).await.unwrap()
}
/// A ref that names a directory refuses the commit before the detached
/// metadata and before the first ref write. The update lock is free
/// after the refusal.
#[test]
fn a_ref_that_names_a_directory_refuses_the_whole_commit() {
let scratch = Scratch::new("ref-check-dir");
block_on(async {
let repo = no_wait_repo(&scratch).await;
let root = scratch.0.join("repo");
let a = Checksum::from_bytes([0x41; 32]);
let c = Checksum::from_bytes([0x43; 32]);
repo.set_ref_immediate(&Ref::local("main"), Some(&a))
.await
.unwrap();
repo.set_ref_immediate(&Ref::local("host/main"), Some(&a))
.await
.unwrap();
let txn = repo.transaction().await.unwrap();
txn.set_commit_detached_metadata(&c, string_dict("a", "x"));
txn.set_ref(&Ref::local("main"), Some(&c));
txn.set_ref(&Ref::local("host"), Some(&c));
let err = txn.commit().await.unwrap_err();
assert_not_writable(err, "host", "names a directory");
assert_eq!(tip(&repo, "main").await, Some(a));
assert_eq!(tip(&repo, "host/main").await, Some(a));
assert!(!commitmeta(&root, &c).exists());
drop(repo.lock_update().await.unwrap());
});
}
/// A ref path through a ref file refuses the commit, and a ref queued
/// before it keeps its commit.
#[test]
fn a_ref_that_passes_through_a_file_refuses_the_commit() {
let scratch = Scratch::new("ref-check-file");
block_on(async {
let repo = no_wait_repo(&scratch).await;
let a = Checksum::from_bytes([0x41; 32]);
let c = Checksum::from_bytes([0x43; 32]);
for name in ["rel/main", "app"] {
repo.set_ref_immediate(&Ref::local(name), Some(&a))
.await
.unwrap();
}
let txn = repo.transaction().await.unwrap();
txn.set_ref(&Ref::local("rel/main"), Some(&c));
txn.set_ref(&Ref::local("app/x"), Some(&c));
let err = txn.commit().await.unwrap_err();
assert_not_writable(err, "app/x", "passes through a file");
assert_eq!(tip(&repo, "rel/main").await, Some(a));
assert_eq!(tip(&repo, "app").await, Some(a));
});
}
/// A removal of a path that names a directory refuses the commit.
#[test]
fn a_removal_of_a_directory_refuses_the_commit() {
let scratch = Scratch::new("ref-check-remove-dir");
block_on(async {
let repo = no_wait_repo(&scratch).await;
let a = Checksum::from_bytes([0x41; 32]);
repo.set_ref_immediate(&Ref::local("d/e"), Some(&a))
.await
.unwrap();
let txn = repo.transaction().await.unwrap();
txn.set_ref(&Ref::local("d"), None);
let err = txn.commit().await.unwrap_err();
assert_not_writable(err, "d", "names a directory");
assert_eq!(tip(&repo, "d/e").await, Some(a));
});
}
/// Two queued refs where the path of one names a directory of the other
/// refuse the commit: two writes in each order, and a write with a
/// removal. The commit writes nothing.
#[test]
fn nested_queued_refs_refuse_the_commit() {
let scratch = Scratch::new("ref-check-nested");
block_on(async {
let repo = no_wait_repo(&scratch).await;
let root = scratch.0.join("repo");
let c = Checksum::from_bytes([0x43; 32]);
let queues: [[(&str, Option<&Checksum>); 2]; 3] = [
[("a", Some(&c)), ("a/b", Some(&c))],
[("a/b", Some(&c)), ("a", Some(&c))],
[("a/b", Some(&c)), ("a", None)],
];
for queue in queues {
let txn = repo.transaction().await.unwrap();
for (name, checksum) in queue {
txn.set_ref(&Ref::local(name), checksum);
}
let err = txn.commit().await.unwrap_err();
assert_not_writable(
err,
"a",
"names a directory of ref a/b of the same transaction",
);
assert!(!root.join("refs/heads/a").exists());
}
});
}
/// A removal of the ref file `a` and a write of `a/b` refuse the commit,
/// and `a` keeps its commit.
#[test]
fn a_removal_of_a_ref_file_and_a_write_below_it_refuse_the_commit() {
let scratch = Scratch::new("ref-check-before");
block_on(async {
let repo = no_wait_repo(&scratch).await;
let a = Checksum::from_bytes([0x41; 32]);
let c = Checksum::from_bytes([0x43; 32]);
repo.set_ref_immediate(&Ref::local("a"), Some(&a))
.await
.unwrap();
let txn = repo.transaction().await.unwrap();
txn.set_ref(&Ref::local("a"), None);
txn.set_ref(&Ref::local("a/b"), Some(&c));
let err = txn.commit().await.unwrap_err();
assert_not_writable(err, "a/b", "passes through a file");
assert_eq!(tip(&repo, "a").await, Some(a));
});
}
/// Two removals on nested paths pass the check, and so do two writes where
/// the name of one starts with the name of the other but is not below it.
#[test]
fn nested_removals_and_prefix_names_pass_the_check() {
let scratch = Scratch::new("ref-check-pass");
block_on(async {
let repo = no_wait_repo(&scratch).await;
let c = Checksum::from_bytes([0x43; 32]);
let txn = repo.transaction().await.unwrap();
txn.set_ref(&Ref::local("a"), None);
txn.set_ref(&Ref::local("a/b"), None);
txn.commit().await.unwrap();
let txn = repo.transaction().await.unwrap();
txn.set_ref(&Ref::local("a"), Some(&c));
txn.set_ref(&Ref::local("ab"), Some(&c));
txn.commit().await.unwrap();
assert_eq!(tip(&repo, "a").await, Some(c));
assert_eq!(tip(&repo, "ab").await, Some(c));
});
}
/// A removal of the ref file `a`, then removals of `a/b` and `a/b/c`,
/// pass the check, and the commit removes `a`. A conditional removal of
/// `a`, then a removal of `a/b`, also pass.
#[test]
fn removals_below_a_removed_ref_file_pass_the_check() {
let scratch = Scratch::new("ref-check-remove-below");
block_on(async {
let repo = no_wait_repo(&scratch).await;
let root = scratch.0.join("repo");
let a = Checksum::from_bytes([0x41; 32]);
repo.set_ref_immediate(&Ref::local("a"), Some(&a))
.await
.unwrap();
let txn = repo.transaction().await.unwrap();
txn.set_ref(&Ref::local("a"), None);
txn.set_ref(&Ref::local("a/b"), None);
txn.set_ref(&Ref::local("a/b/c"), None);
txn.commit().await.unwrap();
assert!(!root.join("refs/heads/a").exists());
repo.set_ref_immediate(&Ref::local("a"), Some(&a))
.await
.unwrap();
let txn = repo.transaction().await.unwrap();
txn.set_ref_expecting(&Ref::local("a"), Some(&a), None);
txn.set_ref(&Ref::local("a/b"), None);
txn.commit().await.unwrap();
assert!(!root.join("refs/heads/a").exists());
});
}
/// A removal below the ref file `a` before the removal of `a` refuses
/// the commit, and so does a conditional removal below `a` after the
/// removal of `a`. Each ref keeps its commit.
#[test]
fn a_removal_below_a_ref_file_without_an_earlier_removal_of_it_fails() {
let scratch = Scratch::new("ref-check-remove-below-order");
block_on(async {
let repo = no_wait_repo(&scratch).await;
let a = Checksum::from_bytes([0x41; 32]);
let c = Checksum::from_bytes([0x43; 32]);
for name in ["main", "a"] {
repo.set_ref_immediate(&Ref::local(name), Some(&a))
.await
.unwrap();
}
let txn = repo.transaction().await.unwrap();
txn.set_ref(&Ref::local("main"), Some(&c));
txn.set_ref(&Ref::local("a/b"), None);
txn.set_ref(&Ref::local("a"), None);
let err = txn.commit().await.unwrap_err();
assert_not_writable(err, "a/b", "passes through a file");
assert_eq!(tip(&repo, "main").await, Some(a));
assert_eq!(tip(&repo, "a").await, Some(a));
let txn = repo.transaction().await.unwrap();
txn.set_ref(&Ref::local("a"), None);
txn.set_ref_expecting(&Ref::local("a/b"), None, None);
let err = txn.commit().await.unwrap_err();
assert_not_writable(err, "a/b", "passes through a file");
assert_eq!(tip(&repo, "a").await, Some(a));
});
}
/// A removal of the ref file `x`, then a removal of `al/b`, where `al`
/// is an alias of `x`, refuses the commit before the first write. Each
/// ref keeps its commit.
#[test]
fn a_removal_below_an_alias_of_a_removed_ref_file_fails() {
let scratch = Scratch::new("ref-check-remove-below-alias");
block_on(async {
let repo = no_wait_repo(&scratch).await;
let a = Checksum::from_bytes([0x41; 32]);
let c = Checksum::from_bytes([0x43; 32]);
for name in ["main", "x"] {
repo.set_ref_immediate(&Ref::local(name), Some(&a))
.await
.unwrap();
}
repo.set_ref_alias_immediate("al", "x").await.unwrap();
let txn = repo.transaction().await.unwrap();
txn.set_ref(&Ref::local("main"), Some(&c));
txn.set_ref(&Ref::local("x"), None);
txn.set_ref(&Ref::local("al/b"), None);
let err = txn.commit().await.unwrap_err();
assert_not_writable(err, "al/b", "passes through an alias");
assert_eq!(tip(&repo, "main").await, Some(a));
assert_eq!(tip(&repo, "x").await, Some(a));
});
}
/// A queued write, conditional write, or removal below an alias refuses
/// the commit before the first ref write: below a dangling alias and
/// below an alias to a directory of refs. A ref queued before it keeps
/// its commit, and the commit writes nothing through the alias.
#[test]
fn a_ref_below_an_alias_refuses_the_commit() {
let scratch = Scratch::new("ref-check-below-alias");
block_on(async {
let repo = no_wait_repo(&scratch).await;
let heads = scratch.0.join("repo/refs/heads");
let a = Checksum::from_bytes([0x41; 32]);
let c = Checksum::from_bytes([0x43; 32]);
for name in ["main", "d0/y"] {
repo.set_ref_immediate(&Ref::local(name), Some(&a))
.await
.unwrap();
}
std::os::unix::fs::symlink("nosuch", heads.join("up")).unwrap();
std::os::unix::fs::symlink("d0", heads.join("up2")).unwrap();
for name in ["up/x", "up2/x", "up2/y"] {
for entry in 0..3 {
let txn = repo.transaction().await.unwrap();
txn.set_ref(&Ref::local("main"), Some(&c));
let r = Ref::local(name);
match entry {
0 => txn.set_ref_expecting(&r, None, Some(&c)),
1 => txn.set_ref(&r, Some(&c)),
_ => txn.set_ref(&r, None),
}
let err = txn.commit().await.unwrap_err();
assert_not_writable(err, name, "passes through an alias");
assert_eq!(tip(&repo, "main").await, Some(a), "{name}");
assert!(!heads.join("d0/x").exists(), "{name}");
assert_eq!(tip(&repo, "d0/y").await, Some(a), "{name}");
assert!(!heads.join("nosuch").exists(), "{name}");
}
}
});
}
/// A queued write or removal over an alias refuses the commit before the
/// first ref write. The link and its target stay.
#[test]
fn a_write_or_a_removal_over_an_alias_refuses_the_commit() {
let scratch = Scratch::new("ref-check-alias");
block_on(async {
let repo = no_wait_repo(&scratch).await;
let root = scratch.0.join("repo");
let a = Checksum::from_bytes([0x41; 32]);
let c = Checksum::from_bytes([0x43; 32]);
repo.set_ref_immediate(&Ref::local("target"), Some(&a))
.await
.unwrap();
repo.set_ref_alias_immediate("alias", "target")
.await
.unwrap();
for checksum in [Some(&c), None] {
let txn = repo.transaction().await.unwrap();
txn.set_ref(&Ref::local("main"), Some(&c));
txn.set_ref(&Ref::local("alias"), checksum);
let err = txn.commit().await.unwrap_err();
assert_not_writable(err, "alias", "names an alias");
let link = std::fs::symlink_metadata(root.join("refs/heads/alias")).unwrap();
assert!(link.file_type().is_symlink());
assert_eq!(tip(&repo, "alias").await, Some(a));
assert_eq!(tip(&repo, "target").await, Some(a));
assert_eq!(tip(&repo, "main").await, None);
}
});
}
/// A FIFO at a ref path refuses the commit.
#[test]
fn a_ref_that_names_a_special_file_refuses_the_commit() {
let scratch = Scratch::new("ref-check-fifo");
block_on(async {
let repo = no_wait_repo(&scratch).await;
let root = scratch.0.join("repo");
let fifo = root.join("refs/heads/fifo");
rustix::fs::mknodat(
rustix::fs::CWD,
&fifo,
rustix::fs::FileType::Fifo,
rustix::fs::Mode::from_raw_mode(0o600),
0,
)
.unwrap();
let txn = repo.transaction().await.unwrap();
txn.set_ref(&Ref::local("fifo"), Some(&Checksum::from_bytes([0x43; 32])));
let err = txn.commit().await.unwrap_err();
assert_not_writable(err, "fifo", "names a special file");
let kind = std::fs::symlink_metadata(&fifo).unwrap().file_type();
assert!(std::os::unix::fs::FileTypeExt::is_fifo(&kind));
});
}
/// A commit under a lock that the caller holds checks the refs too.
#[test]
fn a_commit_under_a_held_lock_checks_the_refs() {
let scratch = Scratch::new("ref-check-under");
block_on(async {
let repo = no_wait_repo(&scratch).await;
let a = Checksum::from_bytes([0x41; 32]);
let c = Checksum::from_bytes([0x43; 32]);
repo.set_ref_immediate(&Ref::local("host/main"), Some(&a))
.await
.unwrap();
let held = repo.lock_update().await.unwrap();
let txn = repo.transaction().await.unwrap();
txn.set_ref(&Ref::local("host"), Some(&c));
let err = txn.commit_under(&held).await.unwrap_err();
assert_not_writable(err, "host", "names a directory");
assert_eq!(tip(&repo, "host/main").await, Some(a));
drop(held);
});
}
/// Assert that `err` is a mismatch of the ref `name` with the states
/// `expected` and `current`.
fn assert_mismatch(
err: Error,
name: &str,
expected: Option<Checksum>,
current: Option<Checksum>,
) {
match err {
Error::RefMismatch {
name: n,
expected: e,
current: c,
} => assert_eq!((n.as_str(), e, c), (name, expected, current)),
other => panic!("{other:?}"),
}
}
/// A conditional write that expects an absent ref writes the ref.
#[test]
fn a_conditional_write_on_an_absent_ref_passes() {
let scratch = Scratch::new("ref-cas-absent");
block_on(async {
let repo = no_wait_repo(&scratch).await;
let c = Checksum::from_bytes([0x43; 32]);
let txn = repo.transaction().await.unwrap();
txn.set_ref_expecting(&Ref::local("main"), None, Some(&c));
txn.commit().await.unwrap();
assert_eq!(tip(&repo, "main").await, Some(c));
});
}
/// A conditional write that expects an absent ref refuses a present ref,
/// and the ref keeps its commit.
#[test]
fn a_conditional_write_on_a_present_ref_against_absent_fails() {
let scratch = Scratch::new("ref-cas-present");
block_on(async {
let repo = no_wait_repo(&scratch).await;
let a = Checksum::from_bytes([0x41; 32]);
let c = Checksum::from_bytes([0x43; 32]);
repo.set_ref_immediate(&Ref::local("main"), Some(&a))
.await
.unwrap();
let txn = repo.transaction().await.unwrap();
txn.set_ref_expecting(&Ref::local("main"), None, Some(&c));
let err = txn.commit().await.unwrap_err();
assert_eq!(
err.to_string(),
format!("ref mismatch: main: expected absent, found {a}")
);
assert_mismatch(err, "main", None, Some(a));
assert_eq!(tip(&repo, "main").await, Some(a));
});
}
/// A conditional write whose expected commit matches moves the ref.
#[test]
fn a_conditional_write_that_matches_moves_the_ref() {
let scratch = Scratch::new("ref-cas-match");
block_on(async {
let repo = no_wait_repo(&scratch).await;
let a = Checksum::from_bytes([0x41; 32]);
let c = Checksum::from_bytes([0x43; 32]);
repo.set_ref_immediate(&Ref::local("main"), Some(&a))
.await
.unwrap();
let txn = repo.transaction().await.unwrap();
txn.set_ref_expecting(&Ref::local("main"), Some(&a), Some(&c));
txn.commit().await.unwrap();
assert_eq!(tip(&repo, "main").await, Some(c));
});
}
/// A conditional write whose expected commit does not match fails, on a
/// present ref and on an absent ref.
#[test]
fn a_conditional_write_that_does_not_match_fails() {
let scratch = Scratch::new("ref-cas-mismatch");
block_on(async {
let repo = no_wait_repo(&scratch).await;
let a = Checksum::from_bytes([0x41; 32]);
let b = Checksum::from_bytes([0x42; 32]);
let c = Checksum::from_bytes([0x43; 32]);
repo.set_ref_immediate(&Ref::local("main"), Some(&a))
.await
.unwrap();
let txn = repo.transaction().await.unwrap();
txn.set_ref_expecting(&Ref::local("main"), Some(&b), Some(&c));
let err = txn.commit().await.unwrap_err();
assert_mismatch(err, "main", Some(b), Some(a));
assert_eq!(tip(&repo, "main").await, Some(a));
let txn = repo.transaction().await.unwrap();
txn.set_ref_expecting(&Ref::local("other"), Some(&b), Some(&c));
let err = txn.commit().await.unwrap_err();
assert_mismatch(err, "other", Some(b), None);
assert_eq!(tip(&repo, "other").await, None);
});
}
/// A conditional write on an alias fails. The link and its target stay.
#[test]
fn a_conditional_write_on_an_alias_fails() {
let scratch = Scratch::new("ref-cas-alias");
block_on(async {
let repo = no_wait_repo(&scratch).await;
let root = scratch.0.join("repo");
let a = Checksum::from_bytes([0x41; 32]);
let c = Checksum::from_bytes([0x43; 32]);
repo.set_ref_immediate(&Ref::local("target"), Some(&a))
.await
.unwrap();
repo.set_ref_alias_immediate("alias", "target")
.await
.unwrap();
let txn = repo.transaction().await.unwrap();
txn.set_ref_expecting(&Ref::local("alias"), Some(&a), Some(&c));
let err = txn.commit().await.unwrap_err();
assert_not_writable(err, "alias", "names an alias");
let link = std::fs::symlink_metadata(root.join("refs/heads/alias")).unwrap();
assert!(link.file_type().is_symlink());
assert_eq!(tip(&repo, "target").await, Some(a));
});
}
/// A conditional removal removes the ref on a match and keeps it on a
/// mismatch.
#[test]
fn a_conditional_removal_obeys_the_expectation() {
let scratch = Scratch::new("ref-cas-remove");
block_on(async {
let repo = no_wait_repo(&scratch).await;
let a = Checksum::from_bytes([0x41; 32]);
let b = Checksum::from_bytes([0x42; 32]);
repo.set_ref_immediate(&Ref::local("main"), Some(&a))
.await
.unwrap();
let txn = repo.transaction().await.unwrap();
txn.set_ref_expecting(&Ref::local("main"), Some(&b), None);
let err = txn.commit().await.unwrap_err();
assert_mismatch(err, "main", Some(b), Some(a));
assert_eq!(tip(&repo, "main").await, Some(a));
let txn = repo.transaction().await.unwrap();
txn.set_ref_expecting(&Ref::local("main"), Some(&a), None);
txn.commit().await.unwrap();
assert_eq!(tip(&repo, "main").await, None);
});
}
/// A mismatch on the second entry refuses the whole commit: the first
/// ref keeps its commit, and the detached metadata is not written.
#[test]
fn a_mismatch_on_the_second_entry_refuses_the_whole_commit() {
let scratch = Scratch::new("ref-cas-second");
block_on(async {
let repo = no_wait_repo(&scratch).await;
let root = scratch.0.join("repo");
let a = Checksum::from_bytes([0x41; 32]);
let b = Checksum::from_bytes([0x42; 32]);
let c = Checksum::from_bytes([0x43; 32]);
repo.set_ref_immediate(&Ref::local("main"), Some(&a))
.await
.unwrap();
repo.set_ref_immediate(&Ref::local("tag"), Some(&b))
.await
.unwrap();
let txn = repo.transaction().await.unwrap();
txn.set_commit_detached_metadata(&c, string_dict("a", "x"));
txn.set_ref_expecting(&Ref::local("main"), Some(&a), Some(&c));
txn.set_ref_expecting(&Ref::local("tag"), None, Some(&c));
let err = txn.commit().await.unwrap_err();
assert_mismatch(err, "tag", None, Some(b));
assert_eq!(tip(&repo, "main").await, Some(a));
assert_eq!(tip(&repo, "tag").await, Some(b));
assert!(!commitmeta(&root, &c).exists());
});
}
/// A conditional entry compares with the store before the first write,
/// also when an earlier entry writes the same ref.
#[test]
fn a_conditional_entry_reads_the_store_before_the_first_write() {
let scratch = Scratch::new("ref-cas-twice");
block_on(async {
let repo = no_wait_repo(&scratch).await;
let c = Checksum::from_bytes([0x43; 32]);
let d = Checksum::from_bytes([0x44; 32]);
let txn = repo.transaction().await.unwrap();
txn.set_ref(&Ref::local("x"), Some(&c));
txn.set_ref_expecting(&Ref::local("x"), None, Some(&d));
txn.commit().await.unwrap();
assert_eq!(tip(&repo, "x").await, Some(d));
});
}
/// A mismatch on a collection ref of the own collection id names the
/// local ref.
#[test]
fn a_conditional_mismatch_on_the_own_collection_id_names_the_local_ref() {
let scratch = Scratch::new("ref-cas-own");
block_on(async {
let repo = crate::Repo::create(
&scratch.0.join("repo"),
CreateOptions::new(RepoMode::Archive).collection_id("org.example.Os"),
)
.await
.unwrap();
let a = Checksum::from_bytes([0x41; 32]);
let b = Checksum::from_bytes([0x42; 32]);
let c = Checksum::from_bytes([0x43; 32]);
repo.set_ref_immediate(&Ref::local("x"), Some(&a))
.await
.unwrap();
let own = Ref::Collection {
id: "org.example.Os".into(),
name: "x".into(),
};
let txn = repo.transaction().await.unwrap();
txn.set_ref_expecting(&own, Some(&b), Some(&c));
let err = txn.commit().await.unwrap_err();
assert_mismatch(err, "x", Some(b), Some(a));
assert_eq!(tip(&repo, "x").await, Some(a));
});
}
/// A conditional entry whose ref file does not parse fails with the
/// error of the parse. The commit writes no detached metadata and no
/// ref.
#[test]
fn a_conditional_entry_on_a_ref_file_that_does_not_parse_fails() {
let scratch = Scratch::new("ref-cas-junk");
block_on(async {
let repo = no_wait_repo(&scratch).await;
let root = scratch.0.join("repo");
let c = Checksum::from_bytes([0x43; 32]);
let path = root.join("refs/heads/x");
std::fs::write(&path, "not a checksum\n").unwrap();
let txn = repo.transaction().await.unwrap();
txn.set_commit_detached_metadata(&c, string_dict("a", "x"));
txn.set_ref_expecting(&Ref::local("x"), None, Some(&c));
let err = txn.commit().await.unwrap_err();
assert!(matches!(err, Error::Core(_)), "{err:?}");
assert_eq!(std::fs::read(&path).unwrap(), b"not a checksum\n");
assert!(!commitmeta(&root, &c).exists());
});
}
/// A path that names a directory, or that passes through a file, reads
/// as an absent ref. A conditional entry that gives back this absent tip
/// fails, and the refs in the store keep their commits.
#[test]
fn a_conditional_entry_on_the_absent_tip_of_a_path_that_is_not_a_ref_fails() {
let scratch = Scratch::new("ref-cas-absent-tip");
block_on(async {
let repo = no_wait_repo(&scratch).await;
let a = Checksum::from_bytes([0x41; 32]);
let c = Checksum::from_bytes([0x43; 32]);
for name in ["app", "host/main"] {
repo.set_ref_immediate(&Ref::local(name), Some(&a))
.await
.unwrap();
}
for (name, reason) in [
("app/x", "passes through a file"),
("host", "names a directory"),
] {
let expected = tip(&repo, name).await;
assert_eq!(expected, None);
let txn = repo.transaction().await.unwrap();
txn.set_ref_expecting(&Ref::local(name), expected.as_ref(), Some(&c));
let err = txn.commit().await.unwrap_err();
assert_not_writable(err, name, reason);
}
assert_eq!(tip(&repo, "app").await, Some(a));
assert_eq!(tip(&repo, "host/main").await, Some(a));
});
}
/// Poll the commit of `txn` until its ref step reports the start through
/// `started`, and then drop the commit future.
async fn drop_commit_at_the_tail(txn: Transaction, started: &std::sync::mpsc::Receiver<()>) {
use futures_lite::future::poll_once;
use std::time::{Duration, Instant};
let mut committing = Box::pin(txn.commit());
let deadline = Instant::now() + Duration::from_secs(10);
while started.try_recv().is_err() {
assert!(Instant::now() < deadline, "the ref step never started");
assert!(poll_once(&mut committing).await.is_none());
ostrya_rt::Timer::after(Duration::from_millis(10)).await;
}
drop(committing);
}
/// Retry `attempt` every 10 ms until it no longer fails with
/// [`Error::LockTimeout`], for at most 10 s.
async fn retry_lock<T, F: std::future::Future<Output = Result<T>>>(
mut attempt: impl FnMut() -> F,
) -> T {
use std::time::{Duration, Instant};
let deadline = Instant::now() + Duration::from_secs(10);
loop {
match attempt().await {
Ok(held) => return held,
Err(Error::LockTimeout { .. }) => {
assert!(Instant::now() < deadline, "the lock was never released");
ostrya_rt::Timer::after(Duration::from_millis(10)).await;
}
Err(err) => panic!("{err:?}"),
}
}
}
/// A commit future dropped while its ref step runs on the blocking pool
/// keeps the update lock until that step ends, and the step completes.
#[test]
fn a_dropped_commit_holds_the_update_lock_until_its_ref_step_ends() {
let scratch = Scratch::new("dropped-commit");
block_on(async {
let repo = no_wait_repo(&scratch).await;
let root = scratch.0.join("repo");
let commit = Checksum::from_bytes([0x35; 32]);
let txn = repo.transaction().await.unwrap();
txn.set_ref(&Ref::local("main"), Some(&commit));
let (started, go) = test_tail::arm(&root);
drop_commit_at_the_tail(txn, &started).await;
assert!(crate::lock::update_lock_held_in_process(repo.repo_fd()));
let err = repo.lock_update().await.unwrap_err();
assert!(matches!(err, Error::LockTimeout { secs: 0 }), "{err:?}");
go.send(()).unwrap();
drop(retry_lock(|| repo.lock_update()).await);
assert_eq!(
repo.resolve_ref_tip(&Ref::local("main")).await.unwrap(),
Some(commit)
);
});
}
/// A commit future dropped while its ref step runs on the blocking pool
/// keeps the repository lock until that step ends. So an exclusive holder,
/// for example a prune, cannot start before the ref is written.
#[test]
fn a_dropped_commit_holds_the_repository_lock_until_its_ref_step_ends() {
use crate::LockKind;
let scratch = Scratch::new("dropped-commit-repo-lock");
block_on(async {
let repo = no_wait_repo(&scratch).await;
let root = scratch.0.join("repo");
let commit = Checksum::from_bytes([0x36; 32]);
let txn = repo.transaction().await.unwrap();
txn.set_ref(&Ref::local("main"), Some(&commit));
let (started, go) = test_tail::arm(&root);
drop_commit_at_the_tail(txn, &started).await;
let err = repo.lock_repo(LockKind::Exclusive).await.unwrap_err();
assert!(matches!(err, Error::LockTimeout { secs: 0 }), "{err:?}");
go.send(()).unwrap();
drop(retry_lock(|| repo.lock_repo(LockKind::Exclusive)).await);
assert_eq!(
repo.resolve_ref_tip(&Ref::local("main")).await.unwrap(),
Some(commit)
);
});
}
/// A commit future dropped while its ref step runs on the blocking pool
/// still installs the staged detached metadata and writes the ref.
#[test]
fn a_dropped_commit_installs_its_staged_file_and_writes_its_ref() {
let scratch = Scratch::new("dropped-commit-staged");
block_on(async {
let repo = no_wait_repo(&scratch).await;
let root = scratch.0.join("repo");
let commit = Checksum::from_bytes([0x37; 32]);
let staged = crate::summary::serialize_signature_dict(&string_dict("a", "x")).unwrap();
let txn = repo.transaction().await.unwrap();
txn.stage_commit_detached_bytes(&commit, staged.clone())
.await
.unwrap();
txn.set_ref(&Ref::local("main"), Some(&commit));
let (started, go) = test_tail::arm(&root);
drop_commit_at_the_tail(txn, &started).await;
go.send(()).unwrap();
drop(retry_lock(|| repo.lock_update()).await);
assert_eq!(
repo.resolve_ref_tip(&Ref::local("main")).await.unwrap(),
Some(commit)
);
assert_eq!(std::fs::read(commitmeta(&root, &commit)).unwrap(), staged);
});
}
}