Source file store.ml
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
1708
1709
1710
1711
1712
1713
1714
1715
1716
1717
1718
1719
1720
1721
1722
1723
1724
1725
1726
1727
1728
1729
1730
1731
1732
1733
1734
1735
1736
1737
1738
1739
1740
1741
1742
1743
1744
1745
1746
1747
1748
1749
1750
1751
1752
1753
1754
1755
1756
1757
1758
1759
1760
1761
1762
1763
1764
1765
1766
1767
1768
1769
1770
1771
1772
1773
1774
1775
1776
1777
1778
1779
1780
1781
1782
1783
1784
1785
1786
1787
1788
1789
1790
1791
1792
1793
1794
1795
1796
1797
1798
1799
1800
1801
1802
1803
1804
1805
1806
1807
1808
1809
1810
1811
1812
1813
1814
1815
1816
1817
1818
1819
1820
1821
1822
1823
1824
1825
1826
1827
1828
1829
1830
1831
1832
1833
1834
1835
1836
1837
1838
1839
1840
1841
1842
1843
1844
1845
1846
1847
1848
1849
1850
1851
1852
1853
1854
1855
1856
1857
1858
1859
1860
1861
1862
1863
1864
1865
1866
1867
1868
1869
1870
1871
1872
1873
1874
1875
1876
1877
1878
1879
1880
1881
1882
1883
1884
1885
1886
1887
1888
1889
1890
1891
1892
1893
1894
1895
1896
1897
1898
1899
1900
1901
1902
1903
1904
1905
1906
1907
1908
1909
1910
1911
1912
1913
1914
1915
1916
1917
1918
1919
1920
1921
1922
1923
1924
1925
1926
1927
1928
1929
1930
1931
1932
1933
1934
1935
1936
1937
1938
1939
1940
1941
1942
1943
1944
1945
1946
1947
1948
1949
1950
1951
1952
1953
1954
1955
1956
1957
1958
1959
1960
1961
1962
1963
1964
1965
1966
1967
1968
1969
1970
1971
1972
1973
1974
1975
1976
1977
1978
1979
1980
1981
1982
1983
1984
1985
1986
1987
1988
1989
1990
1991
1992
1993
1994
1995
1996
1997
1998
1999
2000
2001
2002
2003
2004
2005
2006
2007
2008
2009
2010
2011
2012
2013
2014
2015
2016
2017
2018
2019
2020
2021
2022
2023
2024
2025
2026
2027
2028
2029
2030
2031
2032
2033
2034
2035
2036
2037
2038
2039
2040
2041
2042
2043
2044
2045
2046
2047
2048
2049
2050
2051
2052
2053
2054
2055
2056
2057
2058
2059
2060
2061
2062
2063
2064
2065
2066
2067
2068
2069
2070
2071
2072
2073
2074
2075
2076
2077
2078
2079
2080
2081
2082
2083
2084
2085
2086
2087
2088
2089
2090
2091
2092
2093
2094
2095
2096
2097
2098
2099
2100
2101
2102
2103
2104
2105
2106
2107
2108
2109
2110
2111
2112
2113
2114
2115
2116
2117
2118
2119
2120
2121
2122
2123
2124
2125
2126
2127
2128
2129
2130
2131
2132
2133
2134
2135
2136
2137
2138
2139
2140
2141
2142
2143
2144
2145
2146
2147
2148
2149
2150
2151
2152
2153
2154
2155
2156
2157
2158
2159
2160
2161
2162
2163
2164
2165
2166
2167
2168
2169
2170
2171
2172
2173
2174
2175
2176
2177
2178
2179
2180
2181
2182
2183
2184
2185
2186
2187
2188
2189
2190
2191
2192
2193
2194
2195
2196
2197
2198
2199
2200
2201
2202
2203
2204
2205
2206
2207
2208
2209
2210
2211
2212
2213
2214
2215
2216
2217
2218
2219
2220
2221
2222
2223
2224
2225
2226
2227
2228
2229
2230
2231
2232
2233
2234
2235
2236
2237
2238
2239
2240
2241
2242
2243
2244
2245
2246
2247
2248
2249
2250
2251
2252
2253
2254
2255
2256
2257
2258
2259
2260
2261
2262
2263
2264
2265
2266
2267
2268
2269
2270
2271
2272
2273
2274
2275
2276
2277
2278
2279
2280
2281
2282
2283
2284
2285
2286
2287
2288
2289
2290
2291
2292
2293
2294
2295
2296
2297
2298
2299
2300
2301
2302
2303
2304
2305
2306
2307
2308
2309
2310
2311
2312
2313
2314
2315
2316
2317
2318
2319
2320
2321
2322
2323
2324
2325
2326
2327
2328
2329
2330
2331
2332
2333
2334
2335
2336
2337
2338
2339
2340
2341
2342
2343
2344
2345
2346
2347
2348
2349
2350
2351
2352
2353
2354
2355
2356
2357
2358
2359
2360
2361
2362
2363
2364
2365
2366
2367
2368
2369
2370
2371
2372
2373
2374
2375
2376
2377
2378
2379
2380
2381
2382
2383
2384
2385
2386
2387
2388
2389
2390
2391
2392
2393
2394
2395
2396
2397
2398
2399
2400
2401
2402
2403
2404
2405
2406
2407
2408
2409
2410
2411
2412
2413
2414
2415
2416
2417
2418
2419
2420
2421
2422
2423
2424
2425
2426
2427
2428
2429
2430
2431
2432
2433
2434
2435
2436
2437
2438
2439
2440
2441
2442
2443
2444
2445
2446
2447
2448
2449
2450
2451
2452
2453
2454
2455
2456
2457
2458
2459
2460
2461
2462
2463
2464
2465
2466
2467
2468
2469
2470
2471
2472
2473
2474
2475
2476
2477
2478
2479
2480
2481
2482
2483
2484
2485
2486
2487
2488
2489
2490
2491
2492
2493
2494
2495
2496
2497
2498
2499
2500
2501
2502
2503
2504
2505
2506
2507
2508
2509
2510
2511
2512
2513
2514
2515
2516
2517
2518
2519
2520
2521
2522
2523
2524
2525
2526
2527
2528
2529
2530
2531
2532
2533
2534
2535
2536
2537
2538
2539
2540
2541
2542
2543
2544
2545
2546
2547
2548
2549
2550
2551
2552
2553
2554
2555
2556
2557
2558
2559
2560
2561
2562
2563
2564
2565
2566
2567
2568
2569
2570
2571
2572
2573
2574
2575
2576
2577
2578
2579
2580
2581
2582
2583
2584
2585
2586
2587
2588
2589
2590
2591
2592
2593
2594
2595
2596
2597
2598
2599
2600
2601
2602
2603
2604
2605
2606
2607
2608
2609
2610
2611
2612
2613
2614
2615
2616
2617
2618
2619
2620
2621
2622
2623
2624
2625
2626
2627
2628
2629
2630
2631
2632
2633
2634
2635
2636
2637
2638
2639
2640
2641
2642
2643
2644
2645
2646
2647
2648
2649
2650
2651
2652
2653
2654
2655
2656
2657
2658
2659
2660
2661
2662
2663
2664
2665
2666
2667
2668
2669
2670
2671
2672
2673
2674
2675
2676
2677
2678
2679
2680
2681
2682
2683
2684
2685
2686
2687
2688
2689
2690
2691
2692
2693
2694
2695
2696
2697
2698
2699
2700
2701
2702
2703
2704
2705
2706
2707
2708
2709
2710
2711
2712
2713
2714
2715
2716
2717
2718
2719
2720
2721
2722
2723
2724
2725
2726
2727
2728
2729
2730
2731
2732
2733
2734
2735
2736
2737
2738
2739
2740
2741
2742
2743
2744
2745
2746
2747
2748
2749
2750
2751
2752
2753
2754
2755
2756
2757
2758
2759
2760
2761
2762
2763
2764
2765
2766
2767
2768
2769
2770
2771
2772
2773
2774
2775
2776
2777
2778
2779
2780
2781
2782
2783
2784
2785
2786
2787
2788
2789
2790
2791
2792
2793
2794
2795
2796
2797
2798
2799
2800
2801
2802
2803
2804
2805
2806
2807
2808
2809
2810
2811
2812
2813
2814
2815
2816
2817
2818
2819
2820
2821
2822
2823
2824
2825
2826
2827
2828
2829
2830
2831
2832
2833
2834
2835
2836
2837
2838
2839
2840
2841
2842
2843
2844
2845
2846
2847
2848
2849
2850
2851
2852
2853
2854
2855
2856
2857
2858
2859
2860
2861
2862
2863
2864
2865
2866
2867
2868
2869
2870
2871
2872
2873
2874
2875
2876
2877
2878
2879
2880
2881
2882
2883
2884
2885
2886
2887
2888
2889
2890
2891
2892
2893
2894
2895
2896
2897
2898
2899
2900
2901
2902
2903
2904
2905
2906
2907
2908
2909
2910
2911
2912
2913
2914
2915
2916
2917
2918
2919
2920
2921
2922
2923
2924
2925
2926
2927
2928
2929
2930
2931
2932
2933
2934
2935
2936
2937
2938
2939
2940
2941
2942
2943
2944
2945
2946
2947
2948
2949
2950
2951
2952
2953
2954
2955
2956
2957
2958
2959
2960
2961
2962
2963
2964
2965
2966
2967
2968
2969
2970
2971
2972
2973
2974
2975
2976
2977
2978
2979
2980
2981
2982
2983
2984
2985
2986
2987
2988
2989
2990
2991
2992
2993
2994
2995
2996
2997
2998
2999
3000
3001
3002
3003
3004
3005
3006
3007
3008
3009
3010
3011
3012
3013
3014
3015
3016
3017
3018
3019
3020
3021
3022
3023
3024
3025
3026
3027
3028
3029
3030
3031
3032
3033
3034
3035
3036
3037
3038
3039
3040
3041
3042
3043
3044
3045
3046
3047
3048
3049
3050
3051
3052
3053
3054
3055
3056
3057
3058
3059
3060
3061
3062
3063
3064
3065
3066
3067
3068
3069
3070
3071
3072
3073
3074
3075
3076
3077
3078
3079
3080
3081
3082
3083
3084
3085
3086
3087
3088
3089
3090
3091
3092
3093
3094
3095
3096
3097
3098
3099
3100
3101
3102
3103
3104
3105
3106
3107
3108
3109
3110
3111
3112
3113
3114
3115
3116
3117
3118
3119
3120
3121
3122
3123
3124
3125
3126
3127
3128
3129
3130
3131
3132
3133
3134
3135
3136
3137
3138
3139
3140
3141
3142
3143
3144
3145
3146
3147
3148
3149
3150
3151
3152
3153
3154
3155
3156
3157
3158
3159
3160
3161
3162
3163
3164
3165
3166
3167
3168
3169
3170
3171
3172
3173
3174
3175
3176
3177
3178
3179
3180
3181
3182
3183
3184
3185
3186
3187
3188
3189
3190
3191
3192
3193
3194
3195
3196
3197
3198
3199
3200
3201
3202
3203
3204
3205
3206
3207
3208
3209
3210
3211
3212
3213
3214
3215
3216
3217
3218
3219
3220
3221
3222
3223
3224
3225
3226
3227
3228
3229
3230
3231
3232
3233
3234
3235
3236
3237
3238
3239
3240
3241
3242
3243
3244
3245
3246
3247
3248
3249
3250
3251
3252
3253
3254
3255
3256
3257
3258
3259
3260
3261
3262
3263
3264
3265
3266
3267
3268
3269
3270
3271
3272
3273
3274
3275
3276
3277
3278
3279
3280
3281
3282
3283
3284
3285
3286
3287
3288
3289
3290
3291
3292
3293
3294
3295
3296
3297
3298
3299
3300
3301
3302
3303
3304
3305
3306
3307
3308
3309
3310
3311
3312
3313
3314
3315
3316
3317
3318
3319
3320
3321
3322
3323
3324
3325
3326
3327
3328
3329
3330
3331
3332
3333
3334
3335
3336
3337
3338
3339
3340
3341
3342
3343
3344
3345
3346
3347
3348
3349
3350
3351
3352
3353
3354
3355
3356
3357
3358
3359
3360
3361
3362
3363
3364
3365
3366
3367
3368
3369
3370
3371
3372
3373
3374
3375
3376
3377
3378
3379
3380
3381
3382
3383
3384
3385
3386
3387
3388
3389
3390
3391
3392
3393
3394
3395
3396
3397
3398
3399
3400
3401
3402
3403
3404
3405
3406
3407
3408
3409
3410
3411
3412
3413
3414
3415
3416
3417
3418
3419
3420
3421
3422
3423
3424
3425
3426
3427
3428
3429
3430
3431
3432
3433
3434
3435
3436
3437
3438
3439
3440
3441
3442
3443
3444
3445
3446
3447
3448
3449
3450
3451
3452
3453
3454
3455
3456
3457
3458
3459
3460
3461
3462
3463
3464
3465
3466
3467
3468
3469
3470
3471
3472
3473
3474
3475
3476
3477
3478
3479
3480
3481
3482
3483
3484
3485
3486
3487
3488
3489
3490
3491
3492
3493
3494
3495
3496
3497
3498
3499
3500
3501
3502
3503
3504
3505
3506
3507
3508
3509
3510
3511
3512
3513
3514
3515
3516
3517
3518
3519
3520
3521
3522
3523
3524
3525
3526
3527
3528
3529
3530
3531
3532
3533
3534
3535
3536
3537
3538
3539
3540
3541
3542
3543
3544
3545
3546
3547
3548
3549
3550
3551
3552
3553
3554
3555
3556
3557
3558
3559
3560
3561
3562
3563
3564
3565
3566
3567
3568
3569
3570
3571
3572
3573
3574
3575
3576
3577
3578
3579
3580
open Lwt.Syntax
module Btree = Granary_storage.Btree
module Freelist = Granary_storage.Freelist
module Page = Granary_storage.Page
module Geometry = Granary_storage.Geometry
module Crypto = Granary_storage.Crypto
module Varint = Granary_encoding.Varint
module Bytes_map = Map.Make (Bytes)
type ro
type rw
type tree_id = int
type error =
| Block_error of string
| Corruption of string
| Key_too_large of int
| Value_too_large of int
| Encryption_key_required (** DB is encrypted but no key was supplied *)
| Encryption_key_mismatch (** supplied key fails the header canary *)
| Not_encrypted (** a key was supplied for a plaintext DB *)
| Encryption_rng_unseeded
(** a key was supplied but {!Mirage_crypto_rng} is not seeded, so no per-page
nonce can be generated — the application must seed the RNG at boot *)
| History_unavailable (** as-of API used on a store opened without the feature *)
| History_pruned (** as-of target is older than the retained floor *)
| History_misconfigured (** [as_of_history:true] but no history sink supplied *)
let pp_error fmt = function
| Block_error s -> Format.fprintf fmt "Block_error(%s)" s
| Corruption s -> Format.fprintf fmt "Corruption(%s)" s
| Key_too_large n -> Format.fprintf fmt "Key_too_large(%d)" n
| Value_too_large n -> Format.fprintf fmt "Value_too_large(%d)" n
| Header_error s -> Format.fprintf fmt "Header_error(%s)" s
| Encryption_key_required -> Format.pp_print_string fmt "Encryption_key_required"
| Encryption_key_mismatch -> Format.pp_print_string fmt "Encryption_key_mismatch"
| Not_encrypted -> Format.pp_print_string fmt "Not_encrypted"
| Encryption_rng_unseeded -> Format.pp_print_string fmt "Encryption_rng_unseeded"
| History_unavailable ->
Format.fprintf fmt "as-of time travel is not enabled on this database"
| History_pruned ->
Format.fprintf fmt "as-of target is older than the retained history horizon"
| History_misconfigured ->
Format.fprintf fmt "as_of_history was requested but no history log was supplied"
;;
type bt_savepoint =
{ sp_name : string
; sp_meta_root : int64
; sp_tree_roots : (tree_id * int64) list
; sp_freelist : Freelist.t
; sp_n_pages : int64
; sp_dirty : Pager.dirty_snapshot
; sp_txn_pool : int64 list
(** #297: txn-owned page pool snapshot, restored on savepoint rollback. *)
}
type commit_queue =
{ mutable drainer : bool
; mutable pending : int
; mutable waiters : (unit, exn) result Lwt.u list
}
let create_commit_queue () = { drainer = false; pending = 0; waiters = [] }
type bt_state =
{ close_fn : unit -> unit Lwt.t
; pager : Pager.t
; cipher : Crypto.t option
(** #84: the page cipher when the DB is encrypted, else [None]. Mirrors
the cipher captured by the read/write callback closures; retained here
so [copy_to]/[rekey_to] can re-encrypt the snapshot page image. *)
; mutable meta : Btree.t
; trees : (tree_id, Btree.t) Hashtbl.t
; tree_tags : (tree_id, int32) Hashtbl.t
(** #174: per-tree page-header stamp (low 32 bits of the schema
fingerprint), set by the catalog via {!set_tree_tag}. Pages written
for a tree carry its tag in the reserved header bytes; untagged trees
(default) carry 0. *)
; mutable current_header : Header.t
; schema_version : int64
; mutable txn_freelist_snapshot : Freelist.t option
;
active_readers : (int64, int) Hashtbl.t
;
mutable bt_savepoints : bt_savepoint list
;
bt_append : (tree_id, Btree.append_cursor) Hashtbl.t
;
wal : Granary_storage.Wal.t option
;
wal_close : (unit -> unit Lwt.t) option
; mutable wal_autocheckpoint_threshold : int
;
commit_queue : commit_queue
;
active_reader_frames : (int, int) Hashtbl.t
;
reader_done_cond : unit Lwt_condition.t
;
mutable autockpt_in_flight : bool
; mutable replication_shipped_frames : int
; mutable replication_gate_max_yields : int
; mutable backup_shipped_frames : int
; mutable backup_gate_max_yields : int
; mutable on_committed_frames :
(epoch:int64 -> base_idx:int -> count:int -> unit Lwt.t) option
; mutable on_event : (Store_event.t -> unit) option
; history : History.sink option
; history_now : unit -> int64
; mutable history_floor : int64 option
; mutable current_tree : tree_id option
; mutable follower : bool
; mutable follower_ack_position : int option
; mutable sync_mode : [ `Full | `Batched | `Off ]
; mutable batch_commits : int
; mutable batch_interval_ms : int
; mutable unsynced_commits : int
; mutable last_sync_time : float
; mutable clock : unit -> float
; mutable sink_shipped_frames : int
; mutable closing : bool
; mutable ckpt_io_in_flight : int
; mutable sink_ships_in_flight : int
}
let default_wal_autocheckpoint_threshold = 1000
let default_batch_commits = 256
let default_batch_interval_ms = 100
(** #298: per-deployment durability mode. *)
type durability =
| Full
| Batched of
{ commits : int
; interval_ms : int
}
| Off
type backend =
| Mem of (tree_id, Bytes.t Bytes_map.t ref) Hashtbl.t
| Btree of bt_state
type t =
{ backend : backend
; lock : Rwlock.t
;
mutable mem_rw_shadow : (tree_id * Bytes.t Bytes_map.t) list option
;
mutable mem_savepoints : (string * (tree_id * Bytes.t Bytes_map.t) list) list
}
let pp fmt t =
Format.fprintf
fmt
"Store.t { backend = %s }"
(match t.backend with
| Mem _ -> "Mem"
| Btree _ -> "Btree")
;;
let geometry t =
match t.backend with
| Mem _ -> Geometry.default
| Btree st -> Pager.geom st.pager
;;
type ro_snapshot =
{ rs_store : t
; rs_snap_txn_id : int64
; rs_snap_meta_root : int64
; rs_snap_trees : (tree_id, Btree.t) Hashtbl.t
; rs_snap_frames : int
;
rs_pinned : (int64, unit) Hashtbl.t
; rs_mem_snap : (tree_id * Bytes.t Bytes_map.t) list option
(** #178: for the in-memory backend, a deep copy of every tree's
contents taken at [ro_begin] so RO reads never see uncommitted
writes from a concurrent (but rollback-destined) writer.
[None] for Btree backend. *)
}
type 'a txn =
| Ro : ro_snapshot -> ro txn
| Rw : t -> rw txn
type seek_result =
| Found of bytes
| Not_found of [ `Greater of bytes | `End ]
type cursor =
{ all : (bytes * bytes) list
; mutable remaining : (bytes * bytes) list
; mutable ready : bool
}
let mem_tree trees tid =
match Hashtbl.find_opt trees tid with
| Some r -> r
| None ->
let r = ref Bytes_map.empty in
Hashtbl.add trees tid r;
r
;;
let mem_tree_snap (snap : (tree_id * Bytes.t Bytes_map.t) list) (tid : tree_id) =
match List.assoc_opt tid snap with
| Some map -> map
| None -> Bytes_map.empty
;;
let shadow_get
(shadow : (tree_id * Bytes.t Bytes_map.t) list)
(trees : (tree_id, Bytes.t Bytes_map.t ref) Hashtbl.t)
(tid : tree_id)
=
match List.assoc_opt tid shadow with
| Some map -> map
| None -> !(mem_tree trees tid)
;;
let shadow_update
(shadow : (tree_id * Bytes.t Bytes_map.t) list)
(trees : (tree_id, Bytes.t Bytes_map.t ref) Hashtbl.t)
(tid : tree_id)
(f : Bytes.t Bytes_map.t -> Bytes.t Bytes_map.t)
=
let map = shadow_get shadow trees tid in
(tid, f map) :: List.remove_assoc tid shadow
;;
let encode_tree_id (tid : tree_id) : bytes =
let buf = Buffer.create 8 in
Varint.encode_int64 buf (Int64.of_int tid);
Buffer.to_bytes buf
;;
let encode_root_page (pid : int64) : bytes =
let buf = Buffer.create 8 in
Varint.encode_uint64 buf pid;
Buffer.to_bytes buf
;;
let decode_root_page (b : bytes) : int64 =
let v, _ = Varint.decode_uint64 b 0 in
v
;;
let map_btree_err : Btree.error -> error = function
| Btree.Pager_error (Pager.Block_error s) -> Block_error s
| Btree.Pager_error (Pager.Corruption s) -> Corruption s
| Btree.Key_too_large n -> Key_too_large n
| Btree.Value_too_large n -> Value_too_large n
| Btree.Tree_corrupt s -> Corruption s
;;
let bt_get_tree st (tid : tree_id) : (Btree.t, error) result Lwt.t =
st.current_tree <- None;
let* r =
match Hashtbl.find_opt st.trees tid with
| Some bt -> Lwt.return_ok bt
| None ->
let key = encode_tree_id tid in
let* r = Btree.get st.meta key in
(match r with
| Error e -> Lwt.return_error (map_btree_err e)
| Ok None ->
let bt = Btree.create st.pager ~root_page:0L in
Hashtbl.replace st.trees tid bt;
Lwt.return_ok bt
| Ok (Some v) ->
let root_page = decode_root_page v in
let bt = Btree.create st.pager ~root_page in
Hashtbl.replace st.trees tid bt;
Lwt.return_ok bt)
in
st.current_tree <- Some tid;
Lwt.return r
;;
let tree_tag st (tid : tree_id) : int32 =
Option.value ~default:0l (Hashtbl.find_opt st.tree_tags tid)
;;
let unwrap_error r =
match r with
| Ok v -> Lwt.return v
| Error e -> Lwt.fail_with (Format.asprintf "Store: %a" pp_error e)
;;
let min_active_reader_txn st =
Hashtbl.fold
(fun txn_id _ acc ->
match acc with
| None -> Some txn_id
| Some m -> Some (Int64.min m txn_id))
st.active_readers
None
;;
let min_active_ro_reader_frames (st : bt_state) : int option =
Hashtbl.fold
(fun k _ acc ->
match acc with
| None -> Some k
| Some m -> Some (min m k))
st.active_reader_frames
None
;;
let ro_readers_below (st : bt_state) ~target =
match min_active_ro_reader_frames st with
| Some m -> m < target
| None -> false
;;
let replication_floor_below (st : bt_state) ~target =
st.replication_shipped_frames <> max_int && st.replication_shipped_frames < target
;;
let backup_floor_below (st : bt_state) ~target =
st.backup_shipped_frames <> max_int && st.backup_shipped_frames < target
;;
let bt_get_tree_ro (snap : ro_snapshot) (st : bt_state) (tid : tree_id)
: (Btree.t, error) result Lwt.t
=
st.current_tree <- None;
let* r =
match Hashtbl.find_opt snap.rs_snap_trees tid with
| Some bt -> Lwt.return_ok bt
| None ->
let snap_frames =
if snap.rs_snap_frames = 0 then None else Some snap.rs_snap_frames
in
let snap_meta =
Btree.create
?snapshot_frames:snap_frames
~pin_set:snap.rs_pinned
st.pager
~root_page:snap.rs_snap_meta_root
in
let key = encode_tree_id tid in
let* r = Btree.get snap_meta key in
(match r with
| Error e -> Lwt.return_error (map_btree_err e)
| Ok None ->
let bt =
Btree.create
?snapshot_frames:snap_frames
~pin_set:snap.rs_pinned
st.pager
~root_page:0L
in
Hashtbl.replace snap.rs_snap_trees tid bt;
Lwt.return_ok bt
| Ok (Some v) ->
let root_page = decode_root_page v in
let bt =
Btree.create
?snapshot_frames:snap_frames
~pin_set:snap.rs_pinned
st.pager
~root_page
in
Hashtbl.replace snap.rs_snap_trees tid bt;
Lwt.return_ok bt)
in
st.current_tree <- Some tid;
Lwt.return r
;;
let read_freelist_pages ~first_page : Freelist.t Lwt.t =
if Int64.equal first_page 0L
then Lwt.return Freelist.empty
else (
let rec loop pid acc =
if Int64.equal pid 0L
then Lwt.return (Freelist.of_list (List.rev acc))
else
let* r = Pager.read pager pid in
match r with
| Error _ -> Lwt.return (Freelist.of_list (List.rev acc))
| Ok buf ->
let common = Page.read_common buf in
let n = min common.Page.n_keys (Pager.max_freelist_entries_per_page pager) in
let next_pid =
Int64.logand 0xFFFFFFFFL (Int64.of_int32 common.Page.right_page)
in
let entries =
List.init n (fun i ->
let e = Page.freelist_entry_at buf ~index:i in
e.Page.page_id, e.Page.freed_at_txn_id)
in
loop next_pid (List.rev_append entries acc)
in
loop first_page [])
;;
let create () : t =
{ backend = Mem (Hashtbl.create 16)
; lock = Rwlock.create ()
; mem_rw_shadow = None
; mem_savepoints = []
}
;;
let (e : Header.error) : error =
match e with
| Header.Io s -> Header_error s
| Header.Both_headers_corrupt -> Header_error "both header pages corrupt"
| Header.Unsupported_format v ->
Header_error (Printf.sprintf "unsupported on-disk format_version %ld" v)
;;
let make_btree_store
?(wal = None)
?(wal_close = None)
?(cipher = None)
?(history = None)
?(history_now = fun () -> 0L)
~close_fn
~
~meta
~(h : Header.t)
()
=
let st =
{ close_fn
; pager
; cipher
; meta
; trees = Hashtbl.create 16
; current_tree = None
; tree_tags = Hashtbl.create 16
; current_header = h
; schema_version = h.schema_version
; txn_freelist_snapshot = None
; active_readers = Hashtbl.create 4
; bt_savepoints = []
; bt_append = Hashtbl.create 8
; wal
; wal_close
; wal_autocheckpoint_threshold = default_wal_autocheckpoint_threshold
; commit_queue = create_commit_queue ()
; active_reader_frames = Hashtbl.create 4
; reader_done_cond = Lwt_condition.create ()
; autockpt_in_flight = false
; replication_shipped_frames = max_int
; replication_gate_max_yields = max_int
; backup_shipped_frames = max_int
; backup_gate_max_yields = max_int
; on_committed_frames = None
; on_event = None
; history
; history_now
; history_floor = None
; follower = false
; follower_ack_position = None
; sync_mode = `Full
; batch_commits = default_batch_commits
; batch_interval_ms = default_batch_interval_ms
; unsynced_commits = 0
; last_sync_time = 0.
; clock = (fun () -> 0.)
; sink_shipped_frames = 0
; sink_ships_in_flight = 0
; closing = false
; ckpt_io_in_flight = 0
}
in
{ backend = Btree st
; lock = Rwlock.create ()
; mem_rw_shadow = None
; mem_savepoints = []
}
;;
let rec wait_until (st : bt_state) (pred : unit -> bool) : unit Lwt.t =
if pred ()
then Lwt.return_unit
else
let* () = Lwt_condition.wait st.reader_done_cond in
wait_until st pred
;;
let close (t : t) : unit Lwt.t =
match t.backend with
| Mem _ -> Lwt.return_unit
| Btree st ->
st.closing <- true;
Lwt_condition.broadcast st.reader_done_cond ();
let* () =
wait_until st (fun () -> st.ckpt_io_in_flight = 0 && st.sink_ships_in_flight = 0)
in
let needs_final_sync =
st.sync_mode <> `Full
&&
match st.wal with
| Some w -> Granary_storage.Wal.committed_frames w > 0
| None -> false
in
let* sync_err =
if needs_final_sync
then
let* r = Pager.wal_sync st.pager in
match r with
| Ok () ->
st.unsynced_commits <- 0;
Lwt.return_none
| Error e -> Lwt.return_some e
else Lwt.return_none
in
let* () =
match st.wal_close with
| None -> Lwt.return_unit
| Some f -> f ()
in
let* () = st.close_fn () in
(match sync_err with
| None -> Lwt.return_unit
| Some e ->
Lwt.fail_with (Format.asprintf "Store.close: final wal_sync: %a" Pager.pp_error e))
;;
let peek_geometry ~read_page ~fallback =
let buf = Cstruct.create Geometry.default.page_size in
let%lwt r = read_page ~page_id:0L buf in
match r with
| Ok () -> Lwt.return (Option.value (Header.peek_geometry buf) ~default:fallback)
| Error _ -> Lwt.return fallback
;;
let build_cipher = function
| None -> Ok None
| Some k ->
(match Crypto.create ~key:k with
| Ok c -> Ok (Some c)
| Error `Bad_key_length -> Error (Block_error "encryption key must be 32 bytes"))
;;
let ensure_rng_seeded = function
| None -> Ok ()
| Some _ ->
(try
ignore (Mirage_crypto_rng.generate 1 : string);
Ok ()
with
| Mirage_crypto_rng.Unseeded_generator | Mirage_crypto_rng.No_default_generator ->
Error Encryption_rng_unseeded)
;;
let geom_for_cipher cipher (g : Geometry.t) =
match cipher with
| None -> Ok g
| Some _ ->
if g.reserved_bytes_per_page >= Crypto.overhead
then Ok g
else (
match
Geometry.create
~page_size:g.page_size
~reserved_bytes_per_page:(max g.reserved_bytes_per_page Crypto.overhead)
with
| Ok g' -> Ok g'
| Error e ->
Error
(Block_error
(Format.asprintf
"encryption needs %d reserved bytes/page, but the geometry rejects it: %a"
Crypto.overhead
Geometry.pp_error
e)))
;;
let wrap_callbacks cipher ~read_page ~write_page =
match cipher with
| None -> read_page, write_page
| Some c ->
let rd ~page_id buf =
let* r = read_page ~page_id buf in
match r with
| Error _ as e -> Lwt.return e
| Ok () ->
if Int64.compare page_id 2L < 0
then Lwt.return_ok ()
else (
match Crypto.decrypt_page c ~page_id buf with
| Ok () -> Lwt.return_ok ()
| Error `Tag_mismatch -> Lwt.return_error "decrypt: tag mismatch")
in
let wr ~page_id buf =
if Int64.compare page_id 2L < 0
then write_page ~page_id buf
else (
let tmp = Cstruct.create (Cstruct.length buf) in
Cstruct.blit buf 0 tmp 0 (Cstruct.length buf);
Crypto.encrypt_page c ~page_id tmp;
write_page ~page_id tmp)
in
rd, wr
;;
let make_enc_info = function
| None -> None
| Some c ->
let nonce = Mirage_crypto_rng.generate Crypto.nonce_len in
let tag = Crypto.make_canary c ~nonce in
Some { Header.canary_nonce = nonce; canary_tag = tag }
;;
let check_key (h : Header.t) cipher =
match h.Header.enc, cipher with
| None, None -> Ok ()
| Some _, None -> Error Encryption_key_required
| None, Some _ -> Error Not_encrypted
| Some e, Some c ->
if Crypto.check_canary c ~nonce:e.Header.canary_nonce ~tag:e.Header.canary_tag
then Ok ()
else Error Encryption_key_mismatch
;;
let open_block
?(as_of_history = false)
?(history : History.sink option)
?(now : (unit -> int64) option)
?(key : string option)
?(geom = Geometry.default)
~(init_if_corrupt : bool)
~(read_page : page_id:int64 -> Cstruct.t -> (unit, string) result Lwt.t)
~(write_page : page_id:int64 -> Cstruct.t -> (unit, string) result Lwt.t)
~(sync : unit -> (unit, string) result Lwt.t)
~(resize : n_pages:int64 -> (unit, string) result Lwt.t)
~(n_pages : int64)
~(close : unit -> unit Lwt.t)
()
: (t, error) result Lwt.t
=
if as_of_history && Option.is_none history
then Lwt.return_error History_misconfigured
else (
let history = if as_of_history then history else None in
let history_now =
match now with
| Some f -> f
| None -> fun () -> 0L
in
match
let ( let* ) = Result.bind in
let* cipher = build_cipher key in
let* () = ensure_rng_seeded cipher in
let* geom = geom_for_cipher cipher geom in
Ok (cipher, geom)
with
| Error e -> Lwt.return_error e
| Ok (cipher, geom) ->
let read_page, write_page = wrap_callbacks cipher ~read_page ~write_page in
let =
Pager.create
~read_page
~write_page
~sync
~resize
~n_pages
~freelist:Freelist.empty
in
let%lwt eff_geom = peek_geometry ~read_page ~fallback:geom in
Pager.set_geom pager eff_geom;
let%lwt hr = Header.read_live pager in
(match hr with
| Error Header.Both_headers_corrupt when init_if_corrupt ->
let%lwt ir = Header.init ~enc:(make_enc_info cipher) pager in
(match ir with
| Error e -> Lwt.return_error (map_header_err e)
| Ok () ->
Pager.set_n_pages pager 2L;
let%lwt hr2 = Header.read_live pager in
(match hr2 with
| Error e -> Lwt.return_error (map_header_err e)
| Ok h ->
let meta = Btree.create pager ~root_page:0L in
Lwt.return_ok
(make_btree_store
~cipher
~history
~history_now
~close_fn:close
~pager
~meta
~h
())))
| Error e -> Lwt.return_error (map_header_err e)
| Ok h ->
(match check_key h cipher with
| Error e -> Lwt.return_error e
| Ok () ->
Pager.set_n_pages pager h.n_pages_total;
let%lwt fl = read_freelist_pages pager ~first_page:h.freelist_page in
Pager.set_freelist pager fl;
let meta = Btree.create pager ~root_page:h.root_page in
Lwt.return_ok
(make_btree_store
~cipher
~history
~history_now
~close_fn:close
~pager
~meta
~h
()))))
;;
module Wal = Granary_storage.Wal
let install_wal_hook ( : Pager.t) (wal : Wal.t) =
let cb : Pager.wal_callbacks =
{ wal_find_page = (fun pid -> Wal.find_page wal pid)
; wal_find_page_at = (fun pid ~max_frame -> Wal.find_page_at wal pid ~max_frame)
; wal_read_frame =
(fun idx ->
let* r = Wal.read_frame wal idx in
match r with
| Ok page -> Lwt.return_ok page
| Error e -> Lwt.return_error (Format.asprintf "%a" Wal.pp_error e))
; wal_append_commit =
(fun pages ->
let* r = Wal.append_commit wal pages in
match r with
| Ok () -> Lwt.return_ok ()
| Error e -> Lwt.return_error (Format.asprintf "%a" Wal.pp_error e))
; wal_append_commit_no_sync =
(fun pages ->
let* r = Wal.append_commit_no_sync wal pages in
match r with
| Ok () -> Lwt.return_ok ()
| Error e -> Lwt.return_error (Format.asprintf "%a" Wal.pp_error e))
; wal_sync =
(fun () ->
let* r = Wal.flush_sync wal in
match r with
| Ok () -> Lwt.return_ok ()
| Error e -> Lwt.return_error (Format.asprintf "%a" Wal.pp_error e))
}
in
Pager.set_wal pager (Some cb)
;;
let finish_wal_open ~cipher ~history ~history_now ~close ~wal_close ~ ~wal ~was_fresh
=
let%lwt hr2 = Header.read_live pager in
match hr2 with
| Error e -> Lwt.return_error (map_header_err e)
| Ok h ->
(match check_key h cipher with
| Error e -> Lwt.return_error e
| Ok () ->
let chosen_n_pages =
if was_fresh
then Int64.max h.n_pages_total (Pager.n_pages pager)
else h.n_pages_total
in
Pager.set_n_pages pager chosen_n_pages;
let%lwt fl = read_freelist_pages pager ~first_page:h.freelist_page in
Pager.set_freelist pager fl;
let meta = Btree.create pager ~root_page:h.root_page in
Lwt.return_ok
(make_btree_store
~cipher
~history
~history_now
~wal:(Some wal)
~wal_close:(Some wal_close)
~close_fn:close
~pager
~meta
~h
()))
;;
let open_block_wal
?(as_of_history = false)
?(history : History.sink option)
?(now : (unit -> int64) option)
?(key : string option)
?(geom = Geometry.default)
~(read_page : page_id:int64 -> Cstruct.t -> (unit, string) result Lwt.t)
~(write_page : page_id:int64 -> Cstruct.t -> (unit, string) result Lwt.t)
~(sync : unit -> (unit, string) result Lwt.t)
~(resize : n_pages:int64 -> (unit, string) result Lwt.t)
~(n_pages : int64)
~(wal_read_at : offset:int64 -> Cstruct.t -> (unit, string) result Lwt.t)
~(wal_write_at : offset:int64 -> Cstruct.t -> (unit, string) result Lwt.t)
~(wal_sync : unit -> (unit, string) result Lwt.t)
~(wal_size_bytes : int64)
~(close : unit -> unit Lwt.t)
~(wal_close : unit -> unit Lwt.t)
()
: (t, error) result Lwt.t
=
if as_of_history && Option.is_none history
then Lwt.return_error History_misconfigured
else (
let history = if as_of_history then history else None in
let history_now =
match now with
| Some f -> f
| None -> fun () -> 0L
in
match
let ( let* ) = Result.bind in
let* cipher = build_cipher key in
let* () = ensure_rng_seeded cipher in
let* geom = geom_for_cipher cipher geom in
Ok (cipher, geom)
with
| Error e -> Lwt.return_error e
| Ok (cipher, geom) ->
let read_page, write_page = wrap_callbacks cipher ~read_page ~write_page in
let =
Pager.create
~read_page
~write_page
~sync
~resize
~n_pages
~freelist:Freelist.empty
in
let%lwt eff_geom = peek_geometry ~read_page ~fallback:geom in
Pager.set_geom pager eff_geom;
let%lwt hr = Header.read_live pager in
let%lwt init_result =
match hr with
| Error Header.Both_headers_corrupt ->
let%lwt ir = Header.init ~enc:(make_enc_info cipher) pager in
(match ir with
| Error e -> Lwt.return_error (map_header_err e)
| Ok () ->
Pager.set_n_pages pager 2L;
Lwt.return_ok true)
| Error e -> Lwt.return_error (map_header_err e)
| Ok _ -> Lwt.return_ok false
in
(match init_result with
| Error e -> Lwt.return_error e
| Ok was_fresh ->
let%lwt wr =
Wal.open_
~cipher
~page_size:(Pager.page_size pager)
~read_at:wal_read_at
~write_at:wal_write_at
~sync:wal_sync
~size_bytes:wal_size_bytes
()
in
(match wr with
| Error e ->
Lwt.return_error (Block_error (Format.asprintf "wal open: %a" Wal.pp_error e))
| Ok wal ->
install_wal_hook pager wal;
finish_wal_open
~cipher
~history
~history_now
~close
~wal_close
~pager
~wal
~was_fresh)))
;;
let ro_begin_at t st ~snap_txn_id ~snap_meta_root =
let committed_frames =
match st.wal with
| None -> 0
| Some w -> Wal.committed_frames w
in
let snap_frames =
if st.follower
then (
match st.follower_ack_position with
| Some n -> min committed_frames n
| None -> committed_frames)
else committed_frames
in
let count = Option.value ~default:0 (Hashtbl.find_opt st.active_readers snap_txn_id) in
Hashtbl.replace st.active_readers snap_txn_id (count + 1);
let frame_count =
Option.value ~default:0 (Hashtbl.find_opt st.active_reader_frames snap_frames)
in
Hashtbl.replace st.active_reader_frames snap_frames (frame_count + 1);
Ro
{ rs_store = t
; rs_snap_txn_id = snap_txn_id
; rs_snap_meta_root = snap_meta_root
; rs_snap_trees = Hashtbl.create 4
; rs_snap_frames = snap_frames
; rs_pinned = Hashtbl.create 64
; rs_mem_snap = None
}
;;
let ro_begin t =
let* () = Rwlock.acquire_read t.lock in
let is_closing =
match t.backend with
| Btree st -> st.closing
| Mem _ -> false
in
if is_closing
then (
Rwlock.release_read t.lock;
Lwt.fail_with "Store.ro_begin: store is closing — read transactions are rejected")
else (
match t.backend with
| Mem trees ->
let snap = Hashtbl.fold (fun tid r acc -> (tid, !r) :: acc) trees [] in
Lwt.return
(Ro
{ rs_store = t
; rs_snap_txn_id = 0L
; rs_snap_meta_root = 0L
; rs_snap_trees = Hashtbl.create 1
; rs_snap_frames = 0
; rs_pinned = Hashtbl.create 1
; rs_mem_snap = Some snap
})
| Btree st ->
Lwt.return
(ro_begin_at
t
st
~snap_txn_id:st.current_header.txn_id
~snap_meta_root:st.current_header.root_page))
;;
exception History_error of error
let bt_of t =
match t.backend with
| Btree s -> Some s
| Mem _ -> None
;;
let history_pin t ~txn_id =
match bt_of t with
| Some st -> st.history_floor <- Some txn_id
| None -> ()
;;
let history_floor t =
match bt_of t with
| Some st -> st.history_floor
| None -> None
;;
let history_release t =
match bt_of t with
| Some st -> st.history_floor <- None
| None -> ()
;;
let history_log t =
match bt_of t with
| Some { history = Some sink; _ } -> sink.History.load ()
| _ -> Lwt.return []
;;
let history_enabled t =
match bt_of t with
| Some { history = Some _; _ } -> true
| _ -> false
;;
let ro_begin_as_of t (target : History.target) =
match bt_of t with
| None -> Lwt.fail (History_error History_unavailable)
| Some { history = None; _ } -> Lwt.fail (History_error History_unavailable)
| Some ({ history = Some sink; _ } as st) ->
let* records = sink.History.load () in
(match History.resolve records target with
| None -> Lwt.fail (History_error History_pruned)
| Some r ->
let pruned =
match st.history_floor with
| Some f -> Int64.compare r.History.txn_id f < 0
| None ->
true
in
if pruned
then Lwt.fail (History_error History_pruned)
else
let* () = Rwlock.acquire_read t.lock in
if st.closing
then (
Rwlock.release_read t.lock;
Lwt.fail_with "Store.ro_begin_as_of: store is closing")
else
Lwt.return
(ro_begin_at
t
st
~snap_txn_id:r.History.txn_id
~snap_meta_root:r.History.root_page))
;;
let emit_event (st : bt_state) (ev : Store_event.t) =
match st.on_event with
| None -> ()
| Some f ->
(try f ev with
| _ -> ())
;;
let active_txn_id (st : bt_state) = Int64.add st.current_header.txn_id 1L
let rw_begin t =
let* () = Rwlock.acquire_write t.lock in
let is_follower =
match t.backend with
| Btree st -> st.follower
| Mem _ -> false
in
let is_closing =
match t.backend with
| Btree st -> st.closing
| Mem _ -> false
in
if is_closing
then (
Rwlock.release_write t.lock;
Lwt.fail_with "Store.rw_begin: store is closing — write transactions are rejected")
else if is_follower
then (
Rwlock.release_write t.lock;
Lwt.fail_with
"Store.rw_begin: store is in follower mode — write transactions are rejected while \
following")
else (
(match t.backend with
| Mem trees ->
let snap = Hashtbl.fold (fun tid r acc -> (tid, !r) :: acc) trees [] in
t.mem_rw_shadow <- Some snap;
t.mem_savepoints <- []
| Btree st ->
let current_rw_txn_id = Int64.add st.current_header.txn_id 1L in
emit_event st (Store_event.Txn_begin { txn_id = current_rw_txn_id });
Pager.set_txn_id st.pager current_rw_txn_id;
let min_safe =
match min_active_reader_txn st with
| None -> current_rw_txn_id
| Some m -> Int64.min current_rw_txn_id m
in
let min_safe =
match st.history_floor with
| None -> min_safe
| Some f -> Int64.min min_safe (Int64.add f 1L)
in
Pager.set_alloc_min_safe st.pager min_safe;
Pager.set_n_pages_at_rw_begin st.pager (Pager.n_pages st.pager);
Pager.txn_owned_pool_set st.pager [];
st.txn_freelist_snapshot <- Some (Pager.freelist st.pager));
Lwt.return (Rw t))
;;
let ro_end (Ro snap : ro txn) =
(match snap.rs_store.backend with
| Mem _ -> ()
| Btree st ->
let tid = snap.rs_snap_txn_id in
(match Hashtbl.find_opt st.active_readers tid with
| None | Some 1 -> Hashtbl.remove st.active_readers tid
| Some n -> Hashtbl.replace st.active_readers tid (n - 1));
(match Hashtbl.find_opt st.active_reader_frames snap.rs_snap_frames with
| None | Some 1 -> Hashtbl.remove st.active_reader_frames snap.rs_snap_frames
| Some n -> Hashtbl.replace st.active_reader_frames snap.rs_snap_frames (n - 1));
Pager.unpin_all st.pager snap.rs_pinned;
Lwt_condition.broadcast st.reader_done_cond ());
Rwlock.release_read snap.rs_store.lock;
Lwt.return_unit
;;
let with_ro t f =
let* tx = ro_begin t in
Lwt.finalize (fun () -> f tx) (fun () -> ro_end tx)
;;
let free_old_freelist_pages ~first_page =
let rec loop pid =
if Int64.equal pid 0L
then Lwt.return_unit
else
let* r = Pager.read pager pid in
let next_pid =
match r with
| Error _ -> 0L
| Ok buf ->
let c = Page.read_common buf in
Int64.logand 0xFFFFFFFFL (Int64.of_int32 c.Page.right_page)
in
Pager.free pager ~page_id:pid ~freed_at_txn_id:(Pager.get_txn_id pager);
loop next_pid
in
loop first_page
;;
let write_one_freelist_page ~pid ~next ~chunk =
let buf = Cstruct.create (Pager.page_size pager) in
Cstruct.memset buf 0;
Page.write_common
buf
{ Page.kind = Page.Freelist
; flags = 0
; n_keys = List.length chunk
; right_page = Int64.to_int32 next
; crc32 = 0l
};
List.iteri
(fun j (page_id, freed_at_txn_id) ->
Page.freelist_set_entry buf ~index:j ~page_id ~freed_at_txn_id)
chunk;
Pager.write pager pid buf
;;
let write_freelist_pages : int64 Lwt.t =
let entries_before = Freelist.to_list (Pager.freelist pager) in
let n_entries = List.length entries_before in
let max_per = Pager.max_freelist_entries_per_page pager in
let n_fl_pages = (n_entries + max_per - 1) / max_per in
if n_fl_pages = 0
then Lwt.return 0L
else
let* page_ids =
Lwt_list.map_s
(fun () ->
let* r = Pager.alloc pager in
match r with
| Ok pid -> Lwt.return pid
| Error e ->
Lwt.fail_with (Format.asprintf "write_freelist_pages: %a" Pager.pp_error e))
(List.init n_fl_pages (fun _ -> ()))
in
let final_entries = Freelist.to_list (Pager.freelist pager) in
let rec chunkify = function
| [] -> []
| lst ->
let chunk = List.filteri (fun i _ -> i < max_per) lst in
let rest = List.filteri (fun i _ -> i >= max_per) lst in
chunk :: chunkify rest
in
let chunks = chunkify final_entries in
let n_chunks = List.length chunks in
let pid_arr = Array.of_list page_ids in
let next_of i = if i + 1 < Array.length pid_arr then pid_arr.(i + 1) else 0L in
List.iteri
(fun i chunk ->
write_one_freelist_page pager ~pid:pid_arr.(i) ~next:(next_of i) ~chunk)
chunks;
for i = n_chunks to n_fl_pages - 1 do
write_one_freelist_page pager ~pid:pid_arr.(i) ~next:(next_of i) ~chunk:[]
done;
Lwt.return pid_arr.(0)
;;
(** Body of [checkpoint] without mutex management. Caller MUST already
hold [t.lock] (e.g. during [commit]). Defined here so [commit]
can invoke it via [maybe_autocheckpoint] below. *)
let rec wait_for_readers_past
(st : bt_state)
~target
~replication_max_yields
~backup_max_yields
=
if st.closing
then
Lwt.return_unit
else if ro_readers_below st ~target
then
let* () = Lwt_condition.wait st.reader_done_cond in
wait_for_readers_past st ~target ~replication_max_yields ~backup_max_yields
else if replication_floor_below st ~target && replication_max_yields > 0
then
if replication_max_yields = max_int
then
let* () = Lwt_condition.wait st.reader_done_cond in
wait_for_readers_past st ~target ~replication_max_yields ~backup_max_yields
else
let* () = Lwt.pause () in
wait_for_readers_past
st
~target
~replication_max_yields:(replication_max_yields - 1)
~backup_max_yields
else if backup_floor_below st ~target
then
if backup_max_yields = max_int
then
let* () = Lwt_condition.wait st.reader_done_cond in
wait_for_readers_past st ~target ~replication_max_yields ~backup_max_yields
else if backup_max_yields <= 0
then Lwt.return_unit
else
let* () = Lwt.pause () in
wait_for_readers_past
st
~target
~replication_max_yields
~backup_max_yields:(backup_max_yields - 1)
else Lwt.return_unit
;;
let checkpoint_unlocked (st : bt_state) (wal : Wal.t) : unit Lwt.t =
let target = Wal.committed_frames wal in
emit_event st (Store_event.Checkpoint_begin { target_frames = target });
let* () =
wait_for_readers_past
st
~target
~replication_max_yields:st.replication_gate_max_yields
~backup_max_yields:st.backup_gate_max_yields
in
if st.closing
then
Lwt.return_unit
else (
st.ckpt_io_in_flight <- st.ckpt_io_in_flight + 1;
Lwt.finalize
(fun () ->
let pairs = ref [] in
Wal.iter_index wal (fun pid idx -> pairs := (pid, idx) :: !pairs);
let migrated = ref 0 in
let rec write_each = function
| [] -> Lwt.return_unit
| (pid, idx) :: rest ->
let* r = Wal.read_frame wal idx in
(match r with
| Error e ->
Lwt.fail_with (Format.asprintf "checkpoint read: %a" Wal.pp_error e)
| Ok page ->
let* wr = Pager.flush_one_to_main st.pager ~page_id:pid ~buf:page in
(match wr with
| Error e ->
Lwt.fail_with (Format.asprintf "checkpoint write: %a" Pager.pp_error e)
| Ok () ->
incr migrated;
write_each rest))
in
let* () = write_each !pairs in
let* sr = Pager.flush_sync_main st.pager in
match sr with
| Error e ->
Lwt.fail_with (Format.asprintf "checkpoint sync: %a" Pager.pp_error e)
| Ok () ->
let* () = wait_until st (fun () -> st.sink_ships_in_flight = 0) in
Wal.reset wal;
emit_event st (Store_event.Wal_reset { epoch = Wal.epoch wal });
emit_event st (Store_event.Checkpoint_end { pages_migrated = !migrated });
st.sink_shipped_frames <- 0;
st.unsynced_commits <- 0;
st.last_sync_time <- st.clock ();
if st.on_committed_frames <> None
then st.replication_shipped_frames <- Wal.committed_frames wal;
if st.backup_shipped_frames <> max_int
then st.backup_shipped_frames <- Wal.committed_frames wal;
Lwt.return_unit)
(fun () ->
st.ckpt_io_in_flight <- st.ckpt_io_in_flight - 1;
Lwt_condition.broadcast st.reader_done_cond ();
Lwt.return_unit))
;;
(** Called from [commit] while [lock] is still held (exclusive). If the WAL has
grown past the per-connection threshold, migrate it inline so
subsequent commits start fresh. Best-effort: a checkpoint failure
is swallowed (the commit itself already succeeded). *)
let maybe_autocheckpoint (st : bt_state) : unit Lwt.t =
match st.wal with
| None -> Lwt.return_unit
| Some wal ->
let thr = st.wal_autocheckpoint_threshold in
if thr <= 0
then Lwt.return_unit
else if Wal.committed_frames wal < thr
then Lwt.return_unit
else Lwt.catch (fun () -> checkpoint_unlocked st wal) (fun _ -> Lwt.return_unit)
;;
let group_commit_sync (q : commit_queue) (sync_fn : unit -> unit Lwt.t)
: [ `Drainer | `Joiner ] Lwt.t
=
if q.drainer
then (
let p, u = Lwt.wait () in
q.waiters <- u :: q.waiters;
q.pending <- q.pending + 1;
let* r = p in
match r with
| Ok () -> Lwt.return `Joiner
| Error exn -> Lwt.fail exn)
else (
q.drainer <- true;
let* () = Lwt.pause () in
let rec gather last_seen =
let now_seen = q.pending in
if now_seen > last_seen
then
let* () = Lwt.pause () in
gather now_seen
else Lwt.return_unit
in
let* () = gather 0 in
Lwt.try_bind
sync_fn
(fun () ->
let waiters = q.waiters in
q.waiters <- [];
q.pending <- 0;
q.drainer <- false;
List.iter (fun u -> Lwt.wakeup_later u (Ok ())) waiters;
Lwt.return `Drainer)
(fun exn ->
let waiters = q.waiters in
q.waiters <- [];
q.pending <- 0;
q.drainer <- false;
List.iter (fun u -> Lwt.wakeup_later u (Error exn)) waiters;
Lwt.fail exn))
;;
let commit_prepare_btree
~( :
Pager.t
-> prev_header:Header.t
-> new_state:Header.t
-> (unit, Header.error) result Lwt.t)
(st : bt_state)
: unit Lwt.t
=
let* () =
free_old_freelist_pages st.pager ~first_page:st.current_header.freelist_page
in
let bindings = Hashtbl.fold (fun tid bt acc -> (tid, bt) :: acc) st.trees [] in
Pager.set_write_tag st.pager 0l;
let* () =
Lwt_list.iter_s
(fun (tid, bt) ->
let key = encode_tree_id tid in
let v = encode_root_page (Btree.root_page bt) in
let* r = Btree.put st.meta key v in
match r with
| Ok meta' ->
st.meta <- meta';
Lwt.return_unit
| Error e ->
Lwt.fail_with (Format.asprintf "Store.commit: %a" pp_error (map_btree_err e)))
bindings
in
let* freelist_first_page = write_freelist_pages st.pager in
let new_state : Header.t =
{ txn_id = 0L
;
root_page = Btree.root_page st.meta
; freelist_page = freelist_first_page
; n_pages_total = Pager.n_pages st.pager
; schema_version = st.schema_version
;
format_version = st.current_header.format_version
;
geom = st.current_header.geom
;
enc = st.current_header.enc
}
in
let* r = header_commit st.pager ~prev_header:st.current_header ~new_state in
match r with
| Error e ->
Lwt.fail_with (Format.asprintf "Store.commit: %a" pp_error (map_header_err e))
| Ok () ->
st.current_header <- { new_state with txn_id = Int64.add st.current_header.txn_id 1L };
st.txn_freelist_snapshot <- None;
st.bt_savepoints <- [];
Pager.txn_owned_pool_set st.pager [];
(match st.history with
| None -> Lwt.return_unit
| Some sink ->
let r =
{ History.txn_id = st.current_header.txn_id
; timestamp = st.history_now ()
; root_page = st.current_header.root_page
}
in
Lwt.catch (fun () -> sink.History.append r) (fun _ -> Lwt.return_unit))
;;
let maybe_autockpt_after_commit t st =
if
st.closing
|| st.wal_autocheckpoint_threshold <= 0
|| Wal.committed_frames
(match st.wal with
| Some w -> w
| None -> assert false)
< st.wal_autocheckpoint_threshold
|| st.autockpt_in_flight
then Lwt.return_unit
else (
st.autockpt_in_flight <- true;
Lwt.async (fun () ->
Lwt.finalize
(fun () ->
Lwt.catch
(fun () ->
let* () = Rwlock.acquire_write t.lock in
Lwt.finalize
(fun () ->
match st.wal with
| None -> Lwt.return_unit
| Some wal -> checkpoint_unlocked st wal)
(fun () ->
Rwlock.release_write t.lock;
Lwt.return_unit))
(fun _ -> Lwt.return_unit))
(fun () ->
st.autockpt_in_flight <- false;
Lwt_condition.broadcast st.reader_done_cond ();
Lwt.return_unit));
Lwt.return_unit)
;;
let commit_wal t st =
let unlocked = ref false in
let unlock_once () =
if not !unlocked
then (
unlocked := true;
Rwlock.release_write t.lock)
in
let wal =
match st.wal with
| Some w -> w
| None -> assert false
in
let frames_before = Wal.committed_frames wal in
let append_txn_id = active_txn_id st in
Lwt.catch
(fun () ->
let* () = commit_prepare_btree ~header_commit:Header.commit_no_sync st in
let frames_after = Wal.committed_frames wal in
let do_sync =
match st.sync_mode with
| `Full -> true
| `Off ->
st.unsynced_commits <- st.unsynced_commits + 1;
false
| `Batched ->
st.unsynced_commits <- st.unsynced_commits + 1;
let n_trig = st.batch_commits > 0 && st.unsynced_commits >= st.batch_commits in
let t_trig =
st.batch_interval_ms > 0
&& (st.clock () -. st.last_sync_time) *. 1000.
>= float_of_int st.batch_interval_ms
in
n_trig || t_trig
in
if do_sync
then (
st.unsynced_commits <- 0;
st.last_sync_time <- st.clock ());
unlock_once ();
let* () =
if do_sync
then (
let* role =
group_commit_sync st.commit_queue (fun () ->
let* r = Pager.wal_sync st.pager in
match r with
| Ok () -> Lwt.return_unit
| Error e ->
Lwt.fail_with
(Format.asprintf "Store.commit: wal_sync: %a" Pager.pp_error e))
in
(match st.on_committed_frames with
| None -> ()
| Some cb ->
let synced = Wal.committed_frames wal in
if (not st.closing) && synced > st.sink_shipped_frames
then (
let base = st.sink_shipped_frames in
let count = synced - base in
st.sink_shipped_frames <- synced;
let epoch = Wal.epoch wal in
st.sink_ships_in_flight <- st.sink_ships_in_flight + 1;
Lwt.async (fun () ->
Lwt.finalize
(fun () -> cb ~epoch ~base_idx:base ~count)
(fun () ->
st.sink_ships_in_flight <- st.sink_ships_in_flight - 1;
Lwt_condition.broadcast st.reader_done_cond ();
Lwt.return_unit))));
match role with
| `Joiner -> Lwt.return_unit
| `Drainer -> maybe_autockpt_after_commit t st)
else
maybe_autockpt_after_commit t st
in
let appended = frames_after - frames_before in
emit_event
st
(Store_event.Wal_append
{ txn_id = append_txn_id; base_idx = frames_before; count = appended });
Lwt.return appended)
(fun exn ->
unlock_once ();
Lwt.fail exn)
;;
let commit (Rw t : rw txn) : unit Lwt.t =
match t.backend with
| Mem trees ->
(match t.mem_rw_shadow with
| None -> ()
| Some shadow ->
List.iter
(fun (tid, map) ->
let r = mem_tree trees tid in
r := map)
shadow);
t.mem_rw_shadow <- None;
t.mem_savepoints <- [];
Rwlock.release_write t.lock;
Lwt.return_unit
| Btree st ->
Hashtbl.clear st.bt_append;
let committed_id = active_txn_id st in
let* frames =
match st.wal with
| None ->
let* () =
Lwt.finalize
(fun () ->
let* () = commit_prepare_btree ~header_commit:Header.commit st in
maybe_autocheckpoint st)
(fun () ->
Rwlock.release_write t.lock;
Lwt.return_unit)
in
Lwt.return 0
| Some _ -> commit_wal t st
in
emit_event st (Store_event.Txn_commit { txn_id = committed_id; frames });
Lwt.return_unit
;;
let rollback (Rw t : rw txn) : unit Lwt.t =
let to_emit = ref None in
(match t.backend with
| Mem _ ->
t.mem_rw_shadow <- None;
t.mem_savepoints <- []
| Btree st ->
Hashtbl.clear st.trees;
Hashtbl.clear st.bt_append ;
st.meta <- Btree.create st.pager ~root_page:st.current_header.root_page;
(match st.txn_freelist_snapshot with
| Some fl ->
Pager.set_freelist st.pager fl;
Pager.clear_dirty st.pager;
st.txn_freelist_snapshot <- None
| None -> ());
st.bt_savepoints <- [];
to_emit := Some (st, Store_event.Txn_rollback { txn_id = active_txn_id st }));
Rwlock.release_write t.lock;
(match !to_emit with
| Some (st, ev) -> emit_event st ev
| None -> ());
Lwt.return_unit
;;
(** Migrate every page currently in the WAL index to the main DB, sync
the main DB, then reset the WAL. Holds the RW mutex so no
concurrent commit can append fresh frames while we read the index.
On Mem stores or non-WAL Btree stores this is a no-op. *)
let checkpoint (t : t) : unit Lwt.t =
match t.backend with
| Mem _ -> Lwt.return_unit
| Btree st ->
(match st.wal with
| None -> Lwt.return_unit
| Some wal ->
let* () = Rwlock.acquire_write t.lock in
Lwt.finalize
(fun () -> checkpoint_unlocked st wal)
(fun () ->
Rwlock.release_write t.lock;
Lwt.return_unit))
;;
let wal_autocheckpoint (t : t) : int =
match t.backend with
| Mem _ -> 0
| Btree st -> st.wal_autocheckpoint_threshold
;;
let set_wal_autocheckpoint (t : t) (n : int) : unit =
match t.backend with
| Mem _ -> ()
| Btree st -> st.wal_autocheckpoint_threshold <- max 0 n
;;
let durability (t : t) : durability =
match t.backend with
| Mem _ -> Full
| Btree st ->
(match st.sync_mode with
| `Full -> Full
| `Off -> Off
| `Batched ->
Batched { commits = st.batch_commits; interval_ms = st.batch_interval_ms })
;;
let durability_of_string (s : string) : durability option =
match String.lowercase_ascii s with
| "full" -> Some Full
| "off" -> Some Off
| "batched" ->
Some
(Batched
{ commits = default_batch_commits; interval_ms = default_batch_interval_ms })
| _ -> None
;;
let string_of_durability (d : durability) : string =
match d with
| Full -> "full"
| Batched _ -> "batched"
| Off -> "off"
;;
let set_durability (t : t) (d : durability) : unit =
match t.backend with
| Mem _ -> ()
| Btree st ->
let requested_non_full =
match d with
| Full -> false
| _ -> true
in
if requested_non_full && st.on_committed_frames <> None
then (
match d with
| Batched { commits; interval_ms } ->
st.batch_commits <- max 0 commits;
st.batch_interval_ms <- max 0 interval_ms
| _ -> ())
else (
let new_mode =
match d with
| Full -> `Full
| Off -> `Off
| Batched _ -> `Batched
in
if st.sync_mode <> new_mode
then (
st.unsynced_commits <- 0;
st.last_sync_time <- st.clock ());
match d with
| Full -> st.sync_mode <- `Full
| Off -> st.sync_mode <- `Off
| Batched { commits; interval_ms } ->
st.sync_mode <- `Batched;
st.batch_commits <- max 0 commits;
st.batch_interval_ms <- max 0 interval_ms)
;;
let commit_callback_active (t : t) : bool =
match t.backend with
| Mem _ -> false
| Btree st -> st.on_committed_frames <> None
;;
let flush_unsynced (t : t) : unit Lwt.t =
match t.backend with
| Mem _ -> Lwt.return_unit
| Btree st ->
let pending =
st.sync_mode <> `Full
&&
match st.wal with
| Some w -> Wal.committed_frames w > 0
| None -> false
in
if not pending
then Lwt.return_unit
else
let* (_ : [ `Drainer | `Joiner ]) =
group_commit_sync st.commit_queue (fun () ->
let* r = Pager.wal_sync st.pager in
match r with
| Ok () -> Lwt.return_unit
| Error e ->
Lwt.fail_with
(Format.asprintf "Store.flush_unsynced: wal_sync: %a" Pager.pp_error e))
in
st.unsynced_commits <- 0;
st.last_sync_time <- st.clock ();
Lwt.return_unit
;;
let sync_batch_commits (t : t) : int =
match t.backend with
| Mem _ -> default_batch_commits
| Btree st -> st.batch_commits
;;
let set_sync_batch_commits (t : t) (n : int) : unit =
match t.backend with
| Mem _ -> ()
| Btree st -> st.batch_commits <- max 0 n
;;
let sync_batch_interval_ms (t : t) : int =
match t.backend with
| Mem _ -> default_batch_interval_ms
| Btree st -> st.batch_interval_ms
;;
let set_sync_batch_interval_ms (t : t) (n : int) : unit =
match t.backend with
| Mem _ -> ()
| Btree st -> st.batch_interval_ms <- max 0 n
;;
let set_clock (t : t) (c : unit -> float) : unit =
match t.backend with
| Mem _ -> ()
| Btree st ->
st.clock <- c;
st.last_sync_time <- c ()
;;
let wal_sync_count (t : t) : int =
match t.backend with
| Mem _ -> 0
| Btree st ->
(match st.wal with
| None -> 0
| Some w -> Granary_storage.Wal.sync_count w)
;;
let active_reader_count (t : t) : int =
match t.backend with
| Mem _ -> 0
| Btree st -> Hashtbl.fold (fun _ c acc -> acc + c) st.active_readers 0
;;
let pinned_page_count (t : t) : int =
match t.backend with
| Mem _ -> 0
| Btree st -> Pager.pinned_count st.pager
;;
let live_read_locks (t : t) : int = Rwlock.readers t.lock
(** Push a named savepoint: snapshot the current shadow state (#178). *)
let savepoint_begin (Rw t : rw txn) name =
match t.backend with
| Mem trees ->
let snap =
match t.mem_rw_shadow with
| None -> Hashtbl.fold (fun tid r acc -> (tid, !r) :: acc) trees []
| Some shadow -> shadow
in
t.mem_savepoints <- (name, snap) :: t.mem_savepoints;
Lwt.return_unit
| Btree st ->
let tree_roots =
Hashtbl.fold (fun tid bt acc -> (tid, Btree.root_page bt) :: acc) st.trees []
in
let sp =
{ sp_name = name
; sp_meta_root = Btree.root_page st.meta
; sp_tree_roots = tree_roots
; sp_freelist = Pager.freelist st.pager
; sp_n_pages = Pager.n_pages st.pager
; sp_dirty = Pager.dirty_clone st.pager
; sp_txn_pool = Pager.txn_owned_pool_get st.pager
}
in
st.bt_savepoints <- sp :: st.bt_savepoints;
emit_event st (Store_event.Savepoint_begin { txn_id = active_txn_id st; name });
Lwt.return_unit
;;
(** Release the named savepoint and all newer ones (writes are kept). *)
let savepoint_release (Rw t : rw txn) name =
match t.backend with
| Mem _ ->
let rec drop = function
| [] -> []
| (n, _) :: rest when String.equal n name -> rest
| _ :: rest -> drop rest
in
t.mem_savepoints <- drop t.mem_savepoints;
Lwt.return_unit
| Btree st ->
let rec drop = function
| [] -> []
| sp :: rest when String.equal sp.sp_name name -> rest
| _ :: rest -> drop rest
in
st.bt_savepoints <- drop st.bt_savepoints;
emit_event st (Store_event.Savepoint_release { txn_id = active_txn_id st; name });
Lwt.return_unit
;;
(** Rollback to the named savepoint: restore snapshot, drop newer savepoints,
keep the named savepoint so it can be rolled back to again. *)
let savepoint_rollback (Rw t : rw txn) name =
match t.backend with
| Mem _ ->
let rec find = function
| [] -> ()
| (n, snap) :: rest when String.equal n name ->
t.mem_rw_shadow <- Some snap;
t.mem_savepoints <- (name, snap) :: rest
| _ :: rest -> find rest
in
find t.mem_savepoints;
Lwt.return_unit
| Btree st ->
let rec find = function
| [] -> ()
| sp :: rest when String.equal sp.sp_name name ->
st.meta <- Btree.create st.pager ~root_page:sp.sp_meta_root;
Hashtbl.clear st.trees;
List.iter
(fun (tid, root) ->
let bt = Btree.create st.pager ~root_page:root in
Hashtbl.replace st.trees tid bt)
sp.sp_tree_roots;
Pager.set_freelist st.pager sp.sp_freelist;
Pager.set_n_pages st.pager sp.sp_n_pages;
Pager.dirty_restore st.pager sp.sp_dirty;
Pager.txn_owned_pool_set st.pager sp.sp_txn_pool;
Hashtbl.clear st.bt_append;
st.bt_savepoints <- sp :: rest
| _ :: rest -> find rest
in
find st.bt_savepoints;
emit_event st (Store_event.Savepoint_rollback { txn_id = active_txn_id st; name });
Lwt.return_unit
;;
let txn_store : type a. a txn -> t = function
| Ro snap -> snap.rs_store
| Rw s -> s
;;
let get : type a. a txn -> tree_id -> bytes -> bytes option Lwt.t =
fun tx tid key ->
match tx with
| Ro snap ->
(match snap.rs_store.backend with
| Mem _ ->
let map =
match snap.rs_mem_snap with
| Some snap -> mem_tree_snap snap tid
| None -> Bytes_map.empty
in
Lwt.return (Bytes_map.find_opt key map)
| Btree st ->
let* r = bt_get_tree_ro snap st tid in
let* bt = unwrap_error r in
let* g = Btree.get bt key in
(match g with
| Ok v -> Lwt.return v
| Error e ->
Lwt.fail_with (Format.asprintf "Store.get(ro): %a" pp_error (map_btree_err e))))
| Rw t ->
(match t.backend with
| Mem trees ->
let map =
match t.mem_rw_shadow with
| None -> !(mem_tree trees tid)
| Some shadow -> shadow_get shadow trees tid
in
Lwt.return (Bytes_map.find_opt key map)
| Btree st ->
let* r = bt_get_tree st tid in
let* bt = unwrap_error r in
let* g = Btree.get bt key in
(match g with
| Ok v -> Lwt.return v
| Error e ->
Lwt.fail_with (Format.asprintf "Store.get(rw): %a" pp_error (map_btree_err e))))
;;
let put (Rw t : rw txn) tid key value : unit Lwt.t =
match t.backend with
| Mem trees ->
(match t.mem_rw_shadow with
| None ->
let r = mem_tree trees tid in
r := Bytes_map.add key value !r
| Some shadow ->
t.mem_rw_shadow <- Some (shadow_update shadow trees tid (Bytes_map.add key value)));
Lwt.return_unit
| Btree st ->
let* r = bt_get_tree st tid in
let* bt = unwrap_error r in
Pager.set_write_tag st.pager (tree_tag st tid);
Hashtbl.remove st.bt_append tid;
let* p = Btree.put bt key value in
(match p with
| Ok bt' ->
Hashtbl.replace st.trees tid bt';
Lwt.return_unit
| Error e ->
Lwt.fail_with (Format.asprintf "Store.put: %a" pp_error (map_btree_err e)))
;;
let put_x (Rw t : rw txn) tid key value : bytes option Lwt.t =
match t.backend with
| Mem trees ->
let map =
match t.mem_rw_shadow with
| None -> !(mem_tree trees tid)
| Some shadow -> shadow_get shadow trees tid
in
(match Bytes_map.find_opt key map with
| Some _ -> Lwt.return (Some Bytes.empty)
| None ->
(match t.mem_rw_shadow with
| None ->
let r = mem_tree trees tid in
r := Bytes_map.add key value !r
| Some shadow ->
t.mem_rw_shadow
<- Some (shadow_update shadow trees tid (Bytes_map.add key value)));
Lwt.return None)
| Btree st ->
let* r = bt_get_tree st tid in
let* bt = unwrap_error r in
Pager.set_write_tag st.pager (tree_tag st tid);
let* fast =
match Hashtbl.find_opt st.bt_append tid with
| Some ac when Bytes.compare key (Btree.append_cursor_max_key ac) > 0 ->
let* outcome = Btree.try_inplace_append bt ac ~key ~value in
(match outcome with
| Btree.Appended ac' ->
Hashtbl.replace st.bt_append tid ac';
Lwt.return (Some None)
| Btree.Not_applicable -> Lwt.return None
| Btree.Append_failed e ->
Lwt.fail_with (Format.asprintf "Store.put_x: %a" pp_error (map_btree_err e)))
| _ -> Lwt.return None
in
(match fast with
| Some old_opt -> Lwt.return old_opt
| None ->
let prev_max =
Option.map Btree.append_cursor_max_key (Hashtbl.find_opt st.bt_append tid)
in
let* p = Btree.put_x bt key value in
(match p with
| Error e ->
Lwt.fail_with (Format.asprintf "Store.put_x: %a" pp_error (map_btree_err e))
| Ok (bt', old_opt) ->
Hashtbl.replace st.trees tid bt';
(match old_opt with
| Some _ ->
Lwt.return old_opt
| None ->
let append_like =
match prev_max with
| None -> true
| Some m -> Bytes.compare key m > 0
in
if not append_like
then (
Hashtbl.remove st.bt_append tid;
Lwt.return None)
else
let* rc = Btree.rightmost_append_cursor bt' in
(match rc with
| Ok (Some ac) when Bytes.equal (Btree.append_cursor_max_key ac) key ->
Hashtbl.replace st.bt_append tid ac;
Lwt.return None
| Ok _ ->
Hashtbl.remove st.bt_append tid;
Lwt.return None
| Error e ->
Lwt.fail_with
(Format.asprintf "Store.put_x: %a" pp_error (map_btree_err e))))))
;;
let del (Rw t : rw txn) tid key : unit Lwt.t =
match t.backend with
| Mem trees ->
(match t.mem_rw_shadow with
| None ->
let r = mem_tree trees tid in
r := Bytes_map.remove key !r
| Some shadow ->
t.mem_rw_shadow <- Some (shadow_update shadow trees tid (Bytes_map.remove key)));
Lwt.return_unit
| Btree st ->
let* r = bt_get_tree st tid in
let* bt = unwrap_error r in
Pager.set_write_tag st.pager (tree_tag st tid);
Hashtbl.remove st.bt_append tid;
let* d = Btree.del bt key in
(match d with
| Ok bt' ->
Hashtbl.replace st.trees tid bt';
Lwt.return_unit
| Error e ->
Lwt.fail_with (Format.asprintf "Store.del: %a" pp_error (map_btree_err e)))
;;
let set_tree_tag (t : t) (tid : tree_id) (tag : int32) : unit =
match t.backend with
| Mem _ -> ()
| Btree st -> Hashtbl.replace st.tree_tags tid tag
;;
let drain_btree_cursor (c : Btree.cursor) : (bytes * bytes) list Lwt.t =
let rec loop acc =
let* r = Btree.cursor_next c in
match r with
| Error e ->
Lwt.fail_with (Format.asprintf "Store.cursor: %a" pp_error (map_btree_err e))
| Ok None -> Lwt.return (List.rev acc)
| Ok (Some kv) -> loop (kv :: acc)
in
loop []
;;
let cursor_open : type a. a txn -> tree_id -> cursor Lwt.t =
fun tx tid ->
match tx with
| Ro snap ->
(match snap.rs_store.backend with
| Mem _ ->
let map =
match snap.rs_mem_snap with
| Some snap -> mem_tree_snap snap tid
| None -> Bytes_map.empty
in
let entries = Bytes_map.bindings map in
Lwt.return { all = entries; remaining = []; ready = false }
| Btree st ->
let* r = bt_get_tree_ro snap st tid in
let* bt = unwrap_error r in
let* co = Btree.cursor_open bt in
(match co with
| Error e ->
Lwt.fail_with
(Format.asprintf "Store.cursor_open(ro): %a" pp_error (map_btree_err e))
| Ok c ->
let* entries = drain_btree_cursor c in
Btree.cursor_close c;
Lwt.return { all = entries; remaining = []; ready = false }))
| Rw _ ->
let t = txn_store tx in
(match t.backend with
| Mem trees ->
let map =
match t.mem_rw_shadow with
| None -> !(mem_tree trees tid)
| Some shadow -> shadow_get shadow trees tid
in
let entries = Bytes_map.bindings map in
Lwt.return { all = entries; remaining = []; ready = false }
| Btree st ->
let* r = bt_get_tree st tid in
let* bt = unwrap_error r in
let* co = Btree.cursor_open bt in
(match co with
| Error e ->
Lwt.fail_with
(Format.asprintf "Store.cursor_open: %a" pp_error (map_btree_err e))
| Ok c ->
let* entries = drain_btree_cursor c in
Btree.cursor_close c;
Lwt.return { all = entries; remaining = []; ready = false }))
;;
let cursor_close _ = ()
let cursor_first c =
c.remaining <- c.all;
match c.all with
| [] ->
c.ready <- false;
Not_found `End
| (k, _) :: _ ->
c.ready <- true;
Found k
;;
let cursor_seek c key =
let rec find = function
| [] ->
c.remaining <- [];
c.ready <- false;
Not_found `End
| (k, _) :: _ as cur ->
let cmp = Bytes.compare k key in
if cmp >= 0
then (
c.remaining <- cur;
c.ready <- true;
if cmp = 0 then Found k else Not_found (`Greater k))
else find (List.tl cur)
in
find c.all
;;
let cursor_next c =
match c.remaining with
| [] -> None
| entry :: rest ->
if c.ready
then (
c.ready <- false;
Some entry)
else (
c.remaining <- rest;
match rest with
| [] -> None
| next :: _ -> Some next)
;;
let cursor_value c =
match c.remaining with
| (_, v) :: _ when c.ready -> Some v
| _ -> None
;;
type seek_impl =
| SC_mem of (bytes * bytes) Seq.t ref
| SC_bt of Btree.cursor
type seek_cursor =
{ mutable sc_calls : int
; sc_impl : seek_impl
}
let seek_pause_interval = 256
let mk_seek_cursor sc_impl = { sc_calls = 0; sc_impl }
let seek_ge : type a. a txn -> tree_id -> bytes -> seek_cursor Lwt.t =
fun tx tid key ->
match tx with
| Ro snap ->
(match snap.rs_store.backend with
| Mem _ ->
let map =
match snap.rs_mem_snap with
| Some snap -> mem_tree_snap snap tid
| None -> Bytes_map.empty
in
Lwt.return (mk_seek_cursor (SC_mem (ref (Bytes_map.to_seq_from key map))))
| Btree st ->
let* r = bt_get_tree_ro snap st tid in
let* bt = unwrap_error r in
let* co = Btree.cursor_open bt in
(match co with
| Error e ->
Lwt.fail_with
(Format.asprintf "Store.seek_ge(ro): %a" pp_error (map_btree_err e))
| Ok c ->
let* sr = Btree.cursor_seek c key in
(match sr with
| Error e ->
Lwt.fail_with
(Format.asprintf "Store.seek_ge(ro): %a" pp_error (map_btree_err e))
| Ok _ -> Lwt.return (mk_seek_cursor (SC_bt c)))))
| Rw _ ->
let t = txn_store tx in
(match t.backend with
| Mem trees ->
let map =
match t.mem_rw_shadow with
| None -> !(mem_tree trees tid)
| Some shadow -> shadow_get shadow trees tid
in
Lwt.return (mk_seek_cursor (SC_mem (ref (Bytes_map.to_seq_from key map))))
| Btree st ->
let* r = bt_get_tree st tid in
let* bt = unwrap_error r in
let* co = Btree.cursor_open bt in
(match co with
| Error e ->
Lwt.fail_with (Format.asprintf "Store.seek_ge: %a" pp_error (map_btree_err e))
| Ok c ->
let* sr = Btree.cursor_seek c key in
(match sr with
| Error e ->
Lwt.fail_with
(Format.asprintf "Store.seek_ge: %a" pp_error (map_btree_err e))
| Ok _ -> Lwt.return (mk_seek_cursor (SC_bt c)))))
;;
let seek_next : seek_cursor -> (bytes * bytes) option Lwt.t =
fun sc ->
let result =
match sc.sc_impl with
| SC_mem r ->
(match !r () with
| Seq.Nil -> Lwt.return_none
| Seq.Cons (kv, rest) ->
r := rest;
Lwt.return_some kv)
| SC_bt c ->
let* r = Btree.cursor_next c in
(match r with
| Ok kv -> Lwt.return kv
| Error e ->
Lwt.fail_with (Format.asprintf "Store.seek_next: %a" pp_error (map_btree_err e)))
in
sc.sc_calls <- sc.sc_calls + 1;
if sc.sc_calls mod seek_pause_interval = 0
then Lwt.bind (Lwt.pause ()) (fun () -> result)
else result
;;
let seek_close : seek_cursor -> unit =
fun sc ->
match sc.sc_impl with
| SC_mem _ -> ()
| SC_bt c -> Btree.cursor_close c
;;
let wal_mode t =
match t.backend with
| Mem _ -> false
| Btree st -> st.wal <> None
;;
let freelist_size t =
match t.backend with
| Mem _ -> 0
| Btree st -> Freelist.size (Pager.freelist st.pager)
;;
let freelist_entries t =
match t.backend with
| Mem _ -> []
| Btree st -> Freelist.to_list (Pager.freelist st.pager)
;;
let n_pages t =
match t.backend with
| Mem _ -> 0L
| Btree st -> Pager.n_pages st.pager
;;
let list_tree_ids t : tree_id list Lwt.t =
match t.backend with
| Mem trees -> Lwt.return (Hashtbl.fold (fun tid _ acc -> tid :: acc) trees [])
| Btree st ->
let* r = Btree.cursor_open st.meta in
(match r with
| Error e ->
Lwt.fail_with
(Format.asprintf "Store.list_tree_ids: %a" pp_error (map_btree_err e))
| Ok cur ->
let rec loop acc =
let* r = Btree.cursor_next cur in
match r with
| Error e ->
Lwt.fail_with
(Format.asprintf "Store.list_tree_ids: %a" pp_error (map_btree_err e))
| Ok None -> Lwt.return (List.rev acc)
| Ok (Some (k, _v)) ->
let tid, _ = Varint.decode_int64 k 0 in
loop (Int64.to_int tid :: acc)
in
let* result = loop [] in
Btree.cursor_close cur;
Lwt.return result)
;;
type page_sink = page_id:int64 -> page:Cstruct.t -> unit Lwt.t
let iter_snapshot_pages st (Ro snap) ~(f : page_id:int64 -> page:Cstruct.t -> unit Lwt.t)
: unit Lwt.t
=
let n = Pager.n_pages st.pager in
let horizon = snap.rs_snap_frames in
let rec loop (page_id : int64) =
if Int64.compare page_id n >= 0
then Lwt.return_unit
else
let* page_buf =
match st.wal with
| None ->
let* r =
Pager.read ~snapshot_frames:0 ~pin_set:snap.rs_pinned st.pager page_id
in
(match r with
| Ok buf -> Lwt.return buf
| Error e ->
Lwt.fail_with
(Format.asprintf
"Store.iter_snapshot_pages(pg=%Ld): %a"
page_id
Pager.pp_error
e))
| Some wal ->
(match Wal.find_page_at wal page_id ~max_frame:horizon with
| Some idx ->
let* r = Wal.read_frame wal idx in
(match r with
| Ok buf -> Lwt.return buf
| Error e ->
Lwt.fail_with
(Format.asprintf
"Store.iter_snapshot_pages(pg=%Ld,frame=%d): %a"
page_id
idx
Wal.pp_error
e))
| None ->
let* r =
Pager.read
~snapshot_frames:horizon
~pin_set:snap.rs_pinned
st.pager
page_id
in
(match r with
| Ok buf -> Lwt.return buf
| Error e ->
Lwt.fail_with
(Format.asprintf
"Store.iter_snapshot_pages(pg=%Ld): %a"
page_id
Pager.pp_error
e)))
in
let* () = f ~page_id ~page:page_buf in
loop (Int64.add page_id 1L)
in
loop 0L
;;
let copy_to (t : t) (sink : page_sink) : unit Lwt.t =
match t.backend with
| Mem _ -> Lwt.return_unit
| Btree st ->
with_ro t (fun ro ->
iter_snapshot_pages st ro ~f:(fun ~page_id ~page ->
match st.cipher with
| Some c when Int64.compare page_id 2L >= 0 ->
let tmp = Cstruct.create (Cstruct.length page) in
Cstruct.blit page 0 tmp 0 (Cstruct.length page);
Crypto.encrypt_page c ~page_id tmp;
sink ~page_id ~page:tmp
| _ -> sink ~page_id ~page))
;;
let rekey_to (t : t) ~(new_key : string) (sink : page_sink) : (unit, error) result Lwt.t =
match t.backend with
| Mem _ -> Lwt.return_ok ()
| Btree st ->
(match st.cipher with
| None -> Lwt.return_error Not_encrypted
| Some _old ->
(match Crypto.create ~key:new_key with
| Error `Bad_key_length ->
Lwt.return_error (Block_error "encryption key must be 32 bytes")
| Ok c' ->
let nonce = Mirage_crypto_rng.generate Crypto.nonce_len in
let canary_tag = Crypto.make_canary c' ~nonce in
let* () =
with_ro t (fun ro ->
iter_snapshot_pages st ro ~f:(fun ~page_id ~page ->
let len = Cstruct.length page in
let tmp = Cstruct.create len in
Cstruct.blit page 0 tmp 0 len;
if Int64.compare page_id 2L < 0
then (
let f = Page.read_header_fields tmp in
Page.write_header_fields
tmp
{ f with Page.canary_nonce = nonce; canary_tag };
Page.seal tmp;
sink ~page_id ~page:tmp)
else (
Crypto.encrypt_page c' ~page_id tmp;
sink ~page_id ~page:tmp)))
in
Lwt.return_ok ()))
;;
(** Register the replication consumer's shipped position so checkpoint
truncation waits for frames to be shipped before recycling them. *)
let update_replication_position (t : t) ~shipped =
match t.backend with
| Mem _ -> ()
| Btree st ->
st.replication_shipped_frames <- shipped;
Lwt_condition.broadcast st.reader_done_cond ()
;;
(** Bounded-yield "timeout" for the checkpoint gate's wait on the
replication floor (#207). Returns [max_int] (unbounded) by default.
[0] on the in-memory backend (no checkpoint gating). *)
let replication_gate_max_yields (t : t) : int =
match t.backend with
| Mem _ -> 0
| Btree st -> st.replication_gate_max_yields
;;
(** Set the bounded-yield budget the checkpoint gate will spend waiting for
the replication floor (a standby's acked position) to reach the
checkpoint target before proceeding anyway. See {!update_replication_position}.
Pure-Mirage has no ambient clock, so this "timeout" is a count of
cooperative [Lwt.pause] yields rather than wall-clock time. [max_int]
(the default) means wait indefinitely — a dead standby wedges the WAL,
matching the behavior before this knob existed. A finite value bounds
the wait: once spent, the checkpoint proceeds and the now-stranded
standby must re-base (#208). Negative inputs clamp to [0] (proceed
immediately if the floor is behind).
Local RO readers are never abandoned by this budget — only the
replication floor. No-op on the in-memory backend. *)
let set_replication_gate_max_yields (t : t) (n : int) : unit =
match t.backend with
| Mem _ -> ()
| Btree st -> st.replication_gate_max_yields <- max 0 n
;;
(** Get (epoch, committed_frames) for the active WAL; [None] if no WAL. *)
let replication_state (t : t) =
match t.backend with
| Mem _ -> None
| Btree st ->
(match st.wal with
| None -> None
| Some wal -> Some (Wal.epoch wal, Wal.committed_frames wal))
;;
(** Register the backup consumer's captured position so checkpoint
truncation waits for frames to be backed up before recycling them.
Analogous to {!update_replication_position} but for the incremental
backup watermark. *)
let update_backup_position (t : t) ~shipped =
match t.backend with
| Mem _ -> ()
| Btree st ->
st.backup_shipped_frames <- shipped;
Lwt_condition.broadcast st.reader_done_cond ()
;;
(** Get (epoch, committed_frames) for the active WAL; [None] if no WAL.
Review #8: delegates to {!replication_state} — the two functions share
the same body because both track the same WAL position. *)
let backup_state (t : t) = replication_state t
(** Return the backup floor's bounded-yield budget for the checkpoint
gate. Defaults to [max_int] (unbounded) on the B+-tree backend,
[0] on the in-memory backend (no checkpoint gating). *)
let backup_gate_max_yields (t : t) : int =
match t.backend with
| Mem _ -> 0
| Btree st -> st.backup_gate_max_yields
;;
(** Set the bounded-yield budget the checkpoint gate will spend waiting
for the backup floor to reach the checkpoint target before proceeding
anyway (#265). Same semantics as {!set_replication_gate_max_yields}.
Negative inputs clamp to [0]. No-op on the in-memory backend. *)
let set_backup_gate_max_yields (t : t) (n : int) : unit =
match t.backend with
| Mem _ -> ()
| Btree st -> st.backup_gate_max_yields <- max 0 n
;;
(** A captured WAL frame for incremental backup (#265). Contains the
full frame metadata and page payload needed to reconstruct the
database at a later point.
The {!checksum} field covers the decrypted page payload (transport
integrity for the backup frame), matching the same scheme used by
{!Granary_replication.replicated_frame}. For unencrypted WALs the
plaintext equals the on-disk page; for encrypted WALs the checksum
guards against corruption of the decrypted content during transport
or storage, not the on-disk ciphertext. *)
type backup_frame =
{ epoch : int64
; frame_idx : int
; page_id : int64
; is_commit : bool
; page : Cstruct.t
; checksum : int64
; source_salt : int64
; source_seed : int64
}
(** Capture the committed WAL frames since a given watermark position,
returning them as a list of {!backup_frame}.
[~since_epoch] and [~since_idx] identify the watermark: frames with
indices strictly greater than [since_idx] in the current epoch are
returned. If the WAL's epoch has advanced past [since_epoch], no
frames can be captured (the caller must take a fresh base snapshot).
Returns [None] when the WAL's epoch has changed (meaning the caller's
watermark is stale and a re-base is needed). Returns [Some []] when
the watermark is current but no new frames have been committed. *)
let capture_frames_since (t : t) ~since_epoch ~since_idx
: (backup_frame list, [> `Capture_error of string ]) result option Lwt.t
=
match t.backend with
| Mem _ -> Some (Ok []) |> Lwt.return
| Btree st ->
(match st.wal with
| None -> Lwt.return (Some (Error (`Capture_error "no WAL active")))
| Some wal ->
let current_epoch = Wal.epoch wal in
if not (Int64.equal current_epoch since_epoch)
then
Lwt.return None
else (
let committed = Wal.committed_frames wal in
let start = if since_idx = max_int then max_int else since_idx + 1 in
if start >= committed
then Lwt.return (Some (Ok []))
else (
let salt = Wal.salt wal in
let seed = Wal.seed wal in
let rec loop idx acc =
if idx >= committed
then Lwt.return (Some (Ok (List.rev acc)))
else (
let current_epoch = Wal.epoch wal in
if not (Int64.equal current_epoch since_epoch)
then Lwt.return None
else
let* r = Wal.read_committed_frame wal idx in
match r with
| Error _ when not (Int64.equal (Wal.epoch wal) since_epoch) ->
Lwt.return None
| Error e ->
Lwt.return
(Some
(Error
(`Capture_error
(Format.asprintf "read frame %d: %a" idx Wal.pp_error e))))
| Ok f ->
if not (Int64.equal (Wal.epoch wal) since_epoch)
then Lwt.return None
else (
let flags = if f.is_commit then 1L else 0L in
let checksum =
Wal.frame_checksum
~salt
~seed
~page_id:f.page_id
~flags
~page:f.page
in
let bf : backup_frame =
{ epoch = current_epoch
; frame_idx = idx
; page_id = f.page_id
; is_commit = f.is_commit
; page = f.page
; checksum
; source_salt = salt
; source_seed = seed
}
in
loop (idx + 1) (bf :: acc)))
in
loop start [])))
;;
(** Install an asynchronous callback invoked after each WAL commit batch.
The callback receives ~epoch, ~base_idx (starting WAL frame index),
and ~count (number of committed frames). Fired via [Lwt.async] so
the commit path is never blocked by replication I/O.
When a callback is registered, the replication shipped-position
floor is initialised to the WAL's current [committed_frames] so
that checkpoint cannot recycle already-acknowledged frames before
the async sink ships its first batch. The consumer must still
call {!update_replication_position} to advance the floor as
frames are shipped.
Pass [None] to unregister (resets the floor to [max_int]). *)
let set_commit_callback
(t : t)
(cb : (epoch:int64 -> base_idx:int -> count:int -> unit Lwt.t) option)
=
match t.backend with
| Mem _ -> Lwt.return_unit
| Btree st ->
(match cb with
| None ->
st.on_committed_frames <- None;
st.replication_shipped_frames <- max_int;
Lwt.return_unit
| Some _ ->
let* () = Rwlock.acquire_write t.lock in
Lwt.finalize
(fun () ->
let* () = flush_unsynced t in
st.on_committed_frames <- cb;
st.sync_mode <- `Full;
(match st.wal with
| None -> ()
| Some wal ->
st.replication_shipped_frames <- Wal.committed_frames wal;
st.sink_shipped_frames <- Wal.committed_frames wal);
Lwt.return_unit)
(fun () ->
Rwlock.release_write t.lock;
Lwt.return_unit))
;;
let (st : bt_state) (pev : Pager_event.t) : Store_event.t =
let txn_id = Pager.get_txn_id st.pager in
let tree = Option.value st.current_tree ~default:(-1) in
match pev with
| Pager_event.Page_read { page_id } ->
Store_event.Page_read { txn_id; tree; page = page_id }
| Pager_event.Wal_read { page_id } ->
Store_event.Wal_read { txn_id; tree; page = page_id }
| Pager_event.Page_write { page_id } ->
Store_event.Page_write { txn_id; tree; page = page_id }
| Pager_event.Page_alloc { page_id; reused } ->
Store_event.Page_alloc { txn_id; tree; page = page_id; reused }
| Pager_event.Page_free { page_id } ->
Store_event.Page_free { txn_id; tree; page = page_id }
;;
let set_event_callback (t : t) (cb : (Store_event.t -> unit) option) =
match t.backend with
| Mem _ -> ()
| Btree st ->
st.on_event <- cb;
(match cb with
| None -> Pager.set_page_event_callback st.pager None
| Some f ->
Pager.set_page_event_callback
st.pager
(Some
(fun pev ->
try f (translate_pager_event st pev) with
| _ -> ())))
;;
module Event = Store_event
(** Enable or disable follower mode on the store. When [true],
[rw_begin] rejects write transactions so the standby's WAL does not
diverge from the master's stream. No-op on the in-memory backend. *)
let set_follower (t : t) (on : bool) =
match t.backend with
| Mem _ -> ()
| Btree st ->
st.follower <- on;
if not on then st.follower_ack_position <- None
;;
(** True iff follower mode is active (writes are rejected). *)
let is_follower (t : t) =
match t.backend with
| Mem _ -> false
| Btree st -> st.follower
;;
(** Record a local [Wal.committed_frames] count as the follower's last-applied
commit boundary. [ro_begin] will cap RO snapshots to this position so
readers never observe WAL frames past what has been applied on this node
(#263). The caller should supply the count from the WAL handle it applied
into, so the value lives in local committed-frame count space (no coordinate
mismatch vs. master epoch indices) without depending on WAL instance identity
between the caller and the store. No-op on the in-memory backend. *)
let set_follower_ack_position (t : t) ~(frames : int) =
match t.backend with
| Mem _ -> ()
| Btree st -> st.follower_ack_position <- Some frames
;;
(** Get the recorded follower ack position (a local [Wal.committed_frames]
count), or [None] if not following or no position has been recorded yet. *)
let follower_ack_position (t : t) =
match t.backend with
| Mem _ -> None
| Btree st -> st.follower_ack_position
;;
let wait_for_readers_past (t : t) ~target =
match t.backend with
| Mem _ -> Lwt.return_unit
| Btree st ->
wait_for_readers_past
st
~target
~replication_max_yields:st.replication_gate_max_yields
~backup_max_yields:st.backup_gate_max_yields
;;
[@@@ai_disclosure "ai-generated"]
[@@@ai_model "claude-opus-4-7"]
[@@@ai_provider "Anthropic"]