aboutsummaryrefslogtreecommitdiff
path: root/zenstore/compactcas.cpp
blob: 920ed965ff2c0878560770730c7830e483adc38c (plain) (blame)
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
// Copyright Epic Games, Inc. All Rights Reserved.

#include "compactcas.h"

#include <zenstore/cas.h>

#include <zencore/except.h>
#include <zencore/filesystem.h>
#include <zencore/fmtutils.h>
#include <zencore/logging.h>
#include <zencore/scopeguard.h>
#include <gsl/gsl-lite.hpp>

#include <xxhash.h>

#if ZEN_WITH_TESTS
#	include <zencore/compactbinarybuilder.h>
#	include <zencore/testing.h>
#	include <zencore/testutils.h>
#	include <zencore/workthreadpool.h>
#	include <zenstore/cidstore.h>
#	include <algorithm>
#	include <random>
#endif

//////////////////////////////////////////////////////////////////////////

namespace zen {

struct CasDiskIndexHeader
{
	static constexpr uint32_t ExpectedMagic	 = 0x75696478;	// 'uidx';
	static constexpr uint32_t CurrentVersion = 1;

	uint32_t Magic			  = ExpectedMagic;
	uint32_t Version		  = CurrentVersion;
	uint64_t EntryCount		  = 0;
	uint64_t LogPosition	  = 0;
	uint32_t PayloadAlignment = 0;
	uint32_t Checksum		  = 0;

	static uint32_t ComputeChecksum(const CasDiskIndexHeader& Header)
	{
		return XXH32(&Header.Magic, sizeof(CasDiskIndexHeader) - sizeof(uint32_t), 0xC0C0'BABA);
	}
};

static_assert(sizeof(CasDiskIndexHeader) == 32);

namespace {
	std::vector<CasDiskIndexEntry> MakeCasDiskEntries(const std::unordered_map<IoHash, BlockStoreDiskLocation>& MovedChunks,
													  const std::vector<IoHash>&								DeletedChunks)
	{
		std::vector<CasDiskIndexEntry> result;
		result.reserve(MovedChunks.size());
		for (const auto& MovedEntry : MovedChunks)
		{
			result.push_back({.Key = MovedEntry.first, .Location = MovedEntry.second});
		}
		for (const IoHash& ChunkHash : DeletedChunks)
		{
			result.push_back({.Key = ChunkHash, .Flags = CasDiskIndexEntry::kTombstone});
		}
		return result;
	}

	const char* IndexExtension = ".uidx";
	const char* LogExtension   = ".ulog";
	const char* DataExtension  = ".ucas";

	std::filesystem::path GetBasePath(const std::filesystem::path& RootPath, const std::string& ContainerBaseName)
	{
		return RootPath / ContainerBaseName;
	}

	std::filesystem::path GetIndexPath(const std::filesystem::path& RootPath, const std::string& ContainerBaseName)
	{
		return GetBasePath(RootPath, ContainerBaseName) / (ContainerBaseName + IndexExtension);
	}

	std::filesystem::path GetTempIndexPath(const std::filesystem::path& RootPath, const std::string& ContainerBaseName)
	{
		return GetBasePath(RootPath, ContainerBaseName) / (ContainerBaseName + ".tmp" + LogExtension);
	}

	std::filesystem::path GetLogPath(const std::filesystem::path& RootPath, const std::string& ContainerBaseName)
	{
		return GetBasePath(RootPath, ContainerBaseName) / (ContainerBaseName + LogExtension);
	}

	std::filesystem::path GetBlocksBasePath(const std::filesystem::path& RootPath, const std::string& ContainerBaseName)
	{
		return GetBasePath(RootPath, ContainerBaseName) / "blocks";
	}

	std::filesystem::path GetBlockPath(const std::filesystem::path& BlocksBasePath, const uint32_t BlockIndex)
	{
		ExtendablePathBuilder<256> Path;

		char BlockHexString[9];
		ToHexNumber(BlockIndex, BlockHexString);

		Path.Append(BlocksBasePath);
		Path.AppendSeparator();
		Path.AppendAsciiRange(BlockHexString, BlockHexString + 4);
		Path.AppendSeparator();
		Path.Append(BlockHexString);
		Path.Append(DataExtension);
		return Path.ToPath();
	}

	std::filesystem::path GetLegacyLogPath(const std::filesystem::path& RootPath, const std::string& ContainerBaseName)
	{
		return RootPath / (ContainerBaseName + LogExtension);
	}

	std::filesystem::path GetLegacyDataPath(const std::filesystem::path& RootPath, const std::string& ContainerBaseName)
	{
		return RootPath / (ContainerBaseName + DataExtension);
	}

	std::filesystem::path GetLegacyIndexPath(const std::filesystem::path& RootPath, const std::string& ContainerBaseName)
	{
		return RootPath / (ContainerBaseName + IndexExtension);
	}

	struct LegacyCasDiskLocation
	{
		LegacyCasDiskLocation(uint64_t InOffset, uint64_t InSize)
		{
			ZEN_ASSERT(InOffset <= 0xff'ffff'ffff);
			ZEN_ASSERT(InSize <= 0xff'ffff'ffff);

			memcpy(&m_Offset[0], &InOffset, sizeof m_Offset);
			memcpy(&m_Size[0], &InSize, sizeof m_Size);
		}

		LegacyCasDiskLocation() = default;

		inline uint64_t GetOffset() const
		{
			uint64_t Offset = 0;
			memcpy(&Offset, &m_Offset, sizeof m_Offset);
			return Offset;
		}

		inline uint64_t GetSize() const
		{
			uint64_t Size = 0;
			memcpy(&Size, &m_Size, sizeof m_Size);
			return Size;
		}

	private:
		uint8_t m_Offset[5];
		uint8_t m_Size[5];
	};

	struct LegacyCasDiskIndexEntry
	{
		static const uint8_t kTombstone = 0x01;

		IoHash				  Key;
		LegacyCasDiskLocation Location;
		ZenContentType		  ContentType = ZenContentType::kUnknownContentType;
		uint8_t				  Flags		  = 0;
	};

	bool ValidateLegacyEntry(const LegacyCasDiskIndexEntry& Entry, std::string& OutReason)
	{
		if (Entry.Key == IoHash::Zero)
		{
			OutReason = fmt::format("Invalid hash key {}", Entry.Key.ToHexString());
			return false;
		}
		if ((Entry.Flags & ~LegacyCasDiskIndexEntry::kTombstone) != 0)
		{
			OutReason = fmt::format("Invalid flags {} for entry {}", Entry.Flags, Entry.Key.ToHexString());
			return false;
		}
		if (Entry.Flags & LegacyCasDiskIndexEntry::kTombstone)
		{
			return true;
		}
		if (Entry.ContentType != ZenContentType::kUnknownContentType)
		{
			OutReason =
				fmt::format("Invalid content type {} for entry {}", static_cast<uint8_t>(Entry.ContentType), Entry.Key.ToHexString());
			return false;
		}
		uint64_t Size = Entry.Location.GetSize();
		if (Size == 0)
		{
			OutReason = fmt::format("Invalid size {} for entry {}", Size, Entry.Key.ToHexString());
			return false;
		}
		return true;
	}

	bool ValidateEntry(const CasDiskIndexEntry& Entry, std::string& OutReason)
	{
		if (Entry.Key == IoHash::Zero)
		{
			OutReason = fmt::format("Invalid hash key {}", Entry.Key.ToHexString());
			return false;
		}
		if ((Entry.Flags & ~CasDiskIndexEntry::kTombstone) != 0)
		{
			OutReason = fmt::format("Invalid flags {} for entry {}", Entry.Flags, Entry.Key.ToHexString());
			return false;
		}
		if (Entry.Flags & CasDiskIndexEntry::kTombstone)
		{
			return true;
		}
		if (Entry.ContentType != ZenContentType::kUnknownContentType)
		{
			OutReason =
				fmt::format("Invalid content type {} for entry {}", static_cast<uint8_t>(Entry.ContentType), Entry.Key.ToHexString());
			return false;
		}
		uint64_t Size = Entry.Location.GetSize();
		if (Size == 0)
		{
			OutReason = fmt::format("Invalid size {} for entry {}", Size, Entry.Key.ToHexString());
			return false;
		}
		return true;
	}

}  // namespace

//////////////////////////////////////////////////////////////////////////

CasContainerStrategy::CasContainerStrategy(const CasStoreConfiguration& Config, CasGc& Gc)
: GcStorage(Gc)
, m_Config(Config)
, m_Log(logging::Get("containercas"))
{
}

CasContainerStrategy::~CasContainerStrategy()
{
}

void
CasContainerStrategy::Initialize(const std::string_view ContainerBaseName, uint32_t MaxBlockSize, uint64_t Alignment, bool IsNewStore)
{
	ZEN_ASSERT(IsPow2(Alignment));
	ZEN_ASSERT(!m_IsInitialized);
	ZEN_ASSERT(MaxBlockSize > 0);

	m_ContainerBaseName = ContainerBaseName;
	m_PayloadAlignment	= Alignment;
	m_MaxBlockSize		= MaxBlockSize;
	m_BlocksBasePath	= GetBlocksBasePath(m_Config.RootDirectory, m_ContainerBaseName);

	OpenContainer(IsNewStore);

	m_IsInitialized = true;
}

CasStore::InsertResult
CasContainerStrategy::InsertChunk(const void* ChunkData, size_t ChunkSize, const IoHash& ChunkHash)
{
	uint32_t			WriteBlockIndex;
	Ref<BlockStoreFile> WriteBlock;
	uint64_t			InsertOffset;
	{
		RwLock::ExclusiveLockScope _(m_InsertLock);

		{
			RwLock::SharedLockScope __(m_LocationMapLock);
			if (m_LocationMap.contains(ChunkHash))
			{
				return CasStore::InsertResult{.New = false};
			}
		}

		// New entry

		WriteBlockIndex = m_WriteBlockIndex.load(std::memory_order_acquire);
		bool IsWriting	= m_WriteBlock != nullptr;
		if (!IsWriting || (m_CurrentInsertOffset + ChunkSize) > m_MaxBlockSize)
		{
			if (m_WriteBlock)
			{
				m_WriteBlock = nullptr;
			}
			{
				RwLock::ExclusiveLockScope __(m_LocationMapLock);
				if (m_ChunkBlocks.size() == BlockStoreDiskLocation::MaxBlockIndex)
				{
					throw std::runtime_error(
						fmt::format("unable to allocate a new block in '{}'", m_Config.RootDirectory / m_ContainerBaseName));
				}
				WriteBlockIndex += IsWriting ? 1 : 0;
				while (m_ChunkBlocks.contains(WriteBlockIndex))
				{
					WriteBlockIndex = (WriteBlockIndex + 1) & BlockStoreDiskLocation::MaxBlockIndex;
				}
				std::filesystem::path BlockPath = GetBlockPath(m_BlocksBasePath, WriteBlockIndex);
				m_WriteBlock					= new BlockStoreFile(BlockPath);
				m_ChunkBlocks[WriteBlockIndex]	= m_WriteBlock;
				m_WriteBlockIndex.store(WriteBlockIndex, std::memory_order_release);
			}
			m_CurrentInsertOffset = 0;
			m_WriteBlock->Create(m_MaxBlockSize);
		}
		InsertOffset		  = m_CurrentInsertOffset;
		m_CurrentInsertOffset = RoundUp(InsertOffset + ChunkSize, m_PayloadAlignment);
		WriteBlock			  = m_WriteBlock;
	}

	// We can end up in a situation that InsertChunk writes the same chunk data in
	// different locations.
	// We release the insert lock once we have the correct WriteBlock ready and we know
	// where to write the data. If a new InsertChunk request for the same chunk hash/data
	// comes in before we update m_LocationMap below we will have a race.
	// The outcome of that is that we will write the chunk data in more than one location
	// but the chunk hash will only point to one of the chunks.
	// We will in that case waste space until the next GC operation.
	//
	// This should be a rare occasion and the current flow reduces the time we block for
	// reads, insert and GC.

	BlockStoreDiskLocation	Location({.BlockIndex = WriteBlockIndex, .Offset = InsertOffset, .Size = ChunkSize}, m_PayloadAlignment);
	const CasDiskIndexEntry IndexEntry{.Key = ChunkHash, .Location = Location};

	WriteBlock->Write(ChunkData, ChunkSize, InsertOffset);
	m_CasLog.Append(IndexEntry);

	m_TotalSize.fetch_add(static_cast<uint64_t>(ChunkSize), std::memory_order_seq_cst);
	{
		RwLock::ExclusiveLockScope __(m_LocationMapLock);
		m_LocationMap.emplace(ChunkHash, Location);
	}

	return CasStore::InsertResult{.New = true};
}

CasStore::InsertResult
CasContainerStrategy::InsertChunk(IoBuffer Chunk, const IoHash& ChunkHash)
{
	return InsertChunk(Chunk.Data(), Chunk.Size(), ChunkHash);
}

IoBuffer
CasContainerStrategy::FindChunk(const IoHash& ChunkHash)
{
	Ref<BlockStoreFile> ChunkBlock;
	BlockStoreLocation	Location;
	{
		RwLock::SharedLockScope _(m_LocationMapLock);
		if (auto KeyIt = m_LocationMap.find(ChunkHash); KeyIt != m_LocationMap.end())
		{
			Location   = KeyIt->second.Get(m_PayloadAlignment);
			ChunkBlock = m_ChunkBlocks[Location.BlockIndex];
		}
		else
		{
			return IoBuffer();
		}
	}
	return ChunkBlock->GetChunk(Location.Offset, Location.Size);
}

bool
CasContainerStrategy::HaveChunk(const IoHash& ChunkHash)
{
	RwLock::SharedLockScope _(m_LocationMapLock);
	return m_LocationMap.contains(ChunkHash);
}

void
CasContainerStrategy::FilterChunks(CasChunkSet& InOutChunks)
{
	// This implementation is good enough for relatively small
	// chunk sets (in terms of chunk identifiers), but would
	// benefit from a better implementation which removes
	// items incrementally for large sets, especially when
	// we're likely to already have a large proportion of the
	// chunks in the set

	InOutChunks.RemoveChunksIf([&](const IoHash& Hash) { return HaveChunk(Hash); });
}

void
CasContainerStrategy::Flush()
{
	{
		RwLock::ExclusiveLockScope _(m_InsertLock);
		if (m_CurrentInsertOffset > 0)
		{
			uint32_t WriteBlockIndex = m_WriteBlockIndex.load(std::memory_order_acquire);
			WriteBlockIndex			 = (WriteBlockIndex + 1) & BlockStoreDiskLocation::MaxBlockIndex;
			m_WriteBlock			 = nullptr;
			m_WriteBlockIndex.store(WriteBlockIndex, std::memory_order_release);
			m_CurrentInsertOffset = 0;
		}
	}
	MakeIndexSnapshot();
}

void
CasContainerStrategy::Scrub(ScrubContext& Ctx)
{
	std::vector<CasDiskIndexEntry> BadChunks;

	// We do a read sweep through the payloads file and validate
	// any entries that are contained within each segment, with
	// the assumption that most entries will be checked in this
	// pass. An alternative strategy would be to use memory mapping.

	{
		std::vector<CasDiskIndexEntry> BigChunks;
		const uint64_t				   WindowSize = 4 * 1024 * 1024;
		IoBuffer					   ReadBuffer{WindowSize};
		void*						   BufferBase = ReadBuffer.MutableData();

		RwLock::SharedLockScope _(m_InsertLock);  // TODO: Refactor so we don't have to keep m_InsertLock all the time?
		RwLock::SharedLockScope __(m_LocationMapLock);

		for (const auto& Block : m_ChunkBlocks)
		{
			uint64_t				   WindowStart = 0;
			uint64_t				   WindowEnd   = WindowSize;
			const Ref<BlockStoreFile>& BlockFile   = Block.second;
			BlockFile->Open();
			const uint64_t FileSize = BlockFile->FileSize();

			do
			{
				const uint64_t ChunkSize = Min(WindowSize, FileSize - WindowStart);
				BlockFile->Read(BufferBase, ChunkSize, WindowStart);

				for (auto& Entry : m_LocationMap)
				{
					const BlockStoreLocation Location	 = Entry.second.Get(m_PayloadAlignment);
					const uint64_t			 EntryOffset = Location.Offset;

					if ((EntryOffset >= WindowStart) && (EntryOffset < WindowEnd))
					{
						const uint64_t EntryEnd = EntryOffset + Location.Size;

						if (EntryEnd >= WindowEnd)
						{
							BigChunks.push_back({.Key = Entry.first, .Location = Entry.second});

							continue;
						}

						const IoHash ComputedHash =
							IoHash::HashBuffer(reinterpret_cast<uint8_t*>(BufferBase) + Location.Offset - WindowStart, Location.Size);

						if (Entry.first != ComputedHash)
						{
							// Hash mismatch
							BadChunks.push_back({.Key = Entry.first, .Location = Entry.second, .Flags = CasDiskIndexEntry::kTombstone});
						}
					}
				}

				WindowStart += WindowSize;
				WindowEnd += WindowSize;
			} while (WindowStart < FileSize);
		}

		// Deal with large chunks

		for (const CasDiskIndexEntry& Entry : BigChunks)
		{
			IoHashStream			   Hasher;
			const BlockStoreLocation   Location	 = Entry.Location.Get(m_PayloadAlignment);
			const Ref<BlockStoreFile>& BlockFile = m_ChunkBlocks[Location.BlockIndex];
			BlockFile->StreamByteRange(Location.Offset, Location.Size, [&](const void* Data, uint64_t Size) { Hasher.Append(Data, Size); });
			IoHash ComputedHash = Hasher.GetHash();

			if (Entry.Key != ComputedHash)
			{
				BadChunks.push_back({.Key = Entry.Key, .Location = Entry.Location, .Flags = CasDiskIndexEntry::kTombstone});
			}
		}
	}

	if (BadChunks.empty())
	{
		return;
	}

	ZEN_ERROR("Scrubbing found {} bad chunks in '{}'", BadChunks.size(), m_Config.RootDirectory / m_ContainerBaseName);

	// Deal with bad chunks by removing them from our lookup map

	std::vector<IoHash> BadChunkHashes;
	BadChunkHashes.reserve(BadChunks.size());

	m_CasLog.Append(BadChunks);
	{
		RwLock::ExclusiveLockScope _(m_LocationMapLock);
		for (const CasDiskIndexEntry& Entry : BadChunks)
		{
			BadChunkHashes.push_back(Entry.Key);
			m_LocationMap.erase(Entry.Key);
		}
	}

	// Let whomever it concerns know about the bad chunks. This could
	// be used to invalidate higher level data structures more efficiently
	// than a full validation pass might be able to do

	Ctx.ReportBadCasChunks(BadChunkHashes);
}

void
CasContainerStrategy::CollectGarbage(GcContext& GcCtx)
{
	// It collects all the blocks that we want to delete chunks from. For each such
	// block we keep a list of chunks to retain and a list of chunks to delete.
	//
	// If there is a block that we are currently writing to, that block is omitted
	// from the garbage collection.
	//
	// Next it will iterate over all blocks that we want to remove chunks from.
	// If the block is empty after removal of chunks we mark the block as pending
	// delete - we want to delete it as soon as there are no IoBuffers using the
	// block file.
	// Once complete we update the m_LocationMap by removing the chunks.
	//
	// If the block is non-empty we write out the chunks we want to keep to a new
	// block file (creating new block files as needed).
	//
	// We update the index as we complete each new block file. This makes it possible
	// to break the GC if we want to limit time for execution.
	//
	// GC can fairly parallell to regular operation - it will block while taking
	// a snapshot of the current m_LocationMap state.
	//
	// While moving blocks it will do a blocking operation and update the m_LocationMap
	// after each new block is written and figuring out the path to the next new block.

	ZEN_INFO("collecting garbage from '{}'", m_Config.RootDirectory / m_ContainerBaseName);
	uint64_t WriteBlockTimeUs		 = 0;
	uint64_t WriteBlockLongestTimeUs = 0;
	uint64_t ReadBlockTimeUs		 = 0;
	uint64_t ReadBlockLongestTimeUs	 = 0;
	uint64_t TotalChunkCount		 = 0;
	uint64_t DeletedSize			 = 0;
	uint64_t OldTotalSize			 = m_TotalSize.load(std::memory_order::relaxed);

	std::vector<IoHash> DeletedChunks;
	uint64_t			MovedCount = 0;

	Stopwatch  TotalTimer;
	const auto _ = MakeGuard([this,
							  &TotalTimer,
							  &WriteBlockTimeUs,
							  &WriteBlockLongestTimeUs,
							  &ReadBlockTimeUs,
							  &ReadBlockLongestTimeUs,
							  &TotalChunkCount,
							  &DeletedChunks,
							  &MovedCount,
							  &DeletedSize,
							  OldTotalSize] {
		ZEN_INFO(
			"garbage collect for '{}' DONE after {}, write lock: {} ({}), read lock: {} ({}), collected {} bytes, deleted #{} and moved "
			"#{} "
			"of #{} "
			"chunks ({}).",
			m_Config.RootDirectory / m_ContainerBaseName,
			NiceTimeSpanMs(TotalTimer.GetElapsedTimeMs()),
			NiceLatencyNs(WriteBlockTimeUs),
			NiceLatencyNs(WriteBlockLongestTimeUs),
			NiceLatencyNs(ReadBlockTimeUs),
			NiceLatencyNs(ReadBlockLongestTimeUs),
			NiceBytes(DeletedSize),
			DeletedChunks.size(),
			MovedCount,
			TotalChunkCount,
			NiceBytes(OldTotalSize));
	});

	LocationMap_t LocationMap;
	size_t		  BlockCount;
	uint64_t	  ExcludeBlockIndex = 0x800000000ull;
	{
		RwLock::SharedLockScope __(m_InsertLock);
		RwLock::SharedLockScope ___(m_LocationMapLock);
		{
			Stopwatch  Timer;
			const auto ____ = MakeGuard([&Timer, &WriteBlockTimeUs, &WriteBlockLongestTimeUs] {
				uint64_t ElapsedUs = Timer.GetElapsedTimeUs();
				WriteBlockTimeUs += ElapsedUs;
				WriteBlockLongestTimeUs = std::max(ElapsedUs, WriteBlockLongestTimeUs);
			});
			if (m_WriteBlock)
			{
				ExcludeBlockIndex = m_WriteBlockIndex.load(std::memory_order_acquire);
			}
			__.ReleaseNow();
		}
		LocationMap = m_LocationMap;
		BlockCount	= m_ChunkBlocks.size();
	}

	if (LocationMap.empty())
	{
		ZEN_INFO("garbage collect SKIPPED, for '{}', container is empty", m_Config.RootDirectory / m_ContainerBaseName);
		return;
	}

	TotalChunkCount = LocationMap.size();

	std::unordered_map<uint32_t, size_t> BlockIndexToChunkMapIndex;
	std::vector<std::vector<IoHash>>	 KeepChunks;
	std::vector<std::vector<IoHash>>	 DeleteChunks;

	BlockIndexToChunkMapIndex.reserve(BlockCount);
	KeepChunks.reserve(BlockCount);
	DeleteChunks.reserve(BlockCount);
	size_t GuesstimateCountPerBlock = TotalChunkCount / BlockCount / 2;

	std::vector<IoHash> TotalChunkHashes;
	TotalChunkHashes.reserve(TotalChunkCount);
	for (const auto& Entry : LocationMap)
	{
		TotalChunkHashes.push_back(Entry.first);
	}

	uint64_t DeleteCount = 0;

	uint64_t NewTotalSize = 0;
	GcCtx.FilterCas(TotalChunkHashes, [&](const IoHash& ChunkHash, bool Keep) {
		auto						  KeyIt		 = LocationMap.find(ChunkHash);
		const BlockStoreDiskLocation& Location	 = KeyIt->second;
		uint32_t					  BlockIndex = Location.GetBlockIndex();

		if (static_cast<uint64_t>(BlockIndex) == ExcludeBlockIndex)
		{
			return;
		}

		auto   BlockIndexPtr = BlockIndexToChunkMapIndex.find(BlockIndex);
		size_t ChunkMapIndex = 0;
		if (BlockIndexPtr == BlockIndexToChunkMapIndex.end())
		{
			ChunkMapIndex						  = KeepChunks.size();
			BlockIndexToChunkMapIndex[BlockIndex] = ChunkMapIndex;
			KeepChunks.resize(ChunkMapIndex + 1);
			KeepChunks.back().reserve(GuesstimateCountPerBlock);
			DeleteChunks.resize(ChunkMapIndex + 1);
			DeleteChunks.back().reserve(GuesstimateCountPerBlock);
		}
		else
		{
			ChunkMapIndex = BlockIndexPtr->second;
		}
		if (Keep)
		{
			std::vector<IoHash>& ChunkMap = KeepChunks[ChunkMapIndex];
			ChunkMap.push_back(ChunkHash);
			NewTotalSize += Location.GetSize();
		}
		else
		{
			std::vector<IoHash>& ChunkMap = DeleteChunks[ChunkMapIndex];
			ChunkMap.push_back(ChunkHash);
			DeleteCount++;
		}
	});

	std::unordered_set<uint32_t> BlocksToReWrite;
	BlocksToReWrite.reserve(BlockIndexToChunkMapIndex.size());
	for (const auto& Entry : BlockIndexToChunkMapIndex)
	{
		uint32_t				   BlockIndex	 = Entry.first;
		size_t					   ChunkMapIndex = Entry.second;
		const std::vector<IoHash>& ChunkMap		 = DeleteChunks[ChunkMapIndex];
		if (ChunkMap.empty())
		{
			continue;
		}
		BlocksToReWrite.insert(BlockIndex);
	}

	const bool PerformDelete = GcCtx.IsDeletionMode() && GcCtx.CollectSmallObjects();
	if (!PerformDelete)
	{
		uint64_t TotalSize = m_TotalSize.load(std::memory_order_relaxed);
		ZEN_INFO("garbage collect for '{}' DISABLED, found #{} {} chunks of total #{} {}",
				 m_Config.RootDirectory / m_ContainerBaseName,
				 DeleteCount,
				 NiceBytes(TotalSize - NewTotalSize),
				 TotalChunkCount,
				 NiceBytes(TotalSize));
		return;
	}

	// Move all chunks in blocks that have chunks removed to new blocks

	Ref<BlockStoreFile> NewBlockFile;
	uint64_t			WriteOffset	  = 0;
	uint32_t			NewBlockIndex = 0;
	DeletedChunks.reserve(DeleteCount);

	auto UpdateLocations = [this](const std::span<CasDiskIndexEntry>& Entries) {
		for (const CasDiskIndexEntry& Entry : Entries)
		{
			if (Entry.Flags & CasDiskIndexEntry::kTombstone)
			{
				auto	 KeyIt	   = m_LocationMap.find(Entry.Key);
				uint64_t ChunkSize = KeyIt->second.GetSize();
				m_TotalSize.fetch_sub(ChunkSize);
				m_LocationMap.erase(KeyIt);
				continue;
			}
			m_LocationMap[Entry.Key] = Entry.Location;
		}
	};

	std::unordered_map<IoHash, BlockStoreDiskLocation> MovedBlockChunks;
	for (uint32_t BlockIndex : BlocksToReWrite)
	{
		const size_t ChunkMapIndex = BlockIndexToChunkMapIndex[BlockIndex];

		Ref<BlockStoreFile> OldBlockFile;
		{
			RwLock::SharedLockScope _i(m_LocationMapLock);
			OldBlockFile = m_ChunkBlocks[BlockIndex];
		}

		const std::vector<IoHash>& KeepMap = KeepChunks[ChunkMapIndex];
		if (KeepMap.empty())
		{
			const std::vector<IoHash>&	   DeleteMap  = DeleteChunks[ChunkMapIndex];
			std::vector<CasDiskIndexEntry> LogEntries = MakeCasDiskEntries({}, DeleteMap);
			m_CasLog.Append(LogEntries);
			m_CasLog.Flush();
			{
				RwLock::ExclusiveLockScope _i(m_LocationMapLock);
				Stopwatch				   Timer;
				const auto				   __ = MakeGuard([&Timer, &ReadBlockTimeUs, &ReadBlockLongestTimeUs] {
					uint64_t ElapsedUs = Timer.GetElapsedTimeUs();
					ReadBlockTimeUs += ElapsedUs;
					ReadBlockLongestTimeUs = std::max(ElapsedUs, ReadBlockLongestTimeUs);
				});
				UpdateLocations(LogEntries);
				m_ChunkBlocks[BlockIndex] = nullptr;
			}
			DeletedChunks.insert(DeletedChunks.end(), DeleteMap.begin(), DeleteMap.end());
			ZEN_DEBUG("marking cas store file in '{}' for delete , block #{}, '{}'",
					  m_ContainerBaseName,
					  BlockIndex,
					  OldBlockFile->GetPath());
			std::error_code Ec;
			OldBlockFile->MarkAsDeleteOnClose(Ec);
			if (Ec)
			{
				ZEN_WARN("Failed to flag file '{}' for deletion: '{}'", OldBlockFile->GetPath(), Ec.message());
			}
			continue;
		}

		std::vector<uint8_t> Chunk;
		for (const IoHash& ChunkHash : KeepMap)
		{
			auto					 KeyIt		   = LocationMap.find(ChunkHash);
			const BlockStoreLocation ChunkLocation = KeyIt->second.Get(m_PayloadAlignment);
			Chunk.resize(ChunkLocation.Size);
			OldBlockFile->Read(Chunk.data(), Chunk.size(), ChunkLocation.Offset);

			if (!NewBlockFile || (WriteOffset + Chunk.size() > m_MaxBlockSize))
			{
				uint32_t					   NextBlockIndex = m_WriteBlockIndex.load(std::memory_order_relaxed);
				std::vector<CasDiskIndexEntry> LogEntries	  = MakeCasDiskEntries(MovedBlockChunks, {});
				m_CasLog.Append(LogEntries);
				m_CasLog.Flush();

				if (NewBlockFile)
				{
					NewBlockFile->Truncate(WriteOffset);
					NewBlockFile->Flush();
				}
				{
					RwLock::ExclusiveLockScope __(m_LocationMapLock);
					Stopwatch				   Timer;
					const auto				   ___ = MakeGuard([&Timer, &ReadBlockTimeUs, &ReadBlockLongestTimeUs] {
						uint64_t ElapsedUs = Timer.GetElapsedTimeUs();
						ReadBlockTimeUs += ElapsedUs;
						ReadBlockLongestTimeUs = std::max(ElapsedUs, ReadBlockLongestTimeUs);
					});
					UpdateLocations(LogEntries);
					if (m_ChunkBlocks.size() == BlockStoreDiskLocation::MaxBlockIndex)
					{
						ZEN_ERROR("unable to allocate a new block in '{}', count limit {} exeeded",
								  m_Config.RootDirectory / m_ContainerBaseName,
								  static_cast<uint64_t>(std::numeric_limits<uint32_t>::max()) + 1);
						return;
					}
					while (m_ChunkBlocks.contains(NextBlockIndex))
					{
						NextBlockIndex = (NextBlockIndex + 1) & BlockStoreDiskLocation::MaxBlockIndex;
					}
					std::filesystem::path NewBlockPath = GetBlockPath(m_BlocksBasePath, NextBlockIndex);
					NewBlockFile					   = new BlockStoreFile(NewBlockPath);
					m_ChunkBlocks[NextBlockIndex]	   = NewBlockFile;
				}

				MovedCount += MovedBlockChunks.size();
				MovedBlockChunks.clear();

				std::error_code Error;
				DiskSpace		Space = DiskSpaceInfo(m_Config.RootDirectory, Error);
				if (Error)
				{
					ZEN_ERROR("get disk space in '{}' FAILED, reason: '{}'", m_Config.RootDirectory, Error.message());
					return;
				}
				if (Space.Free < m_MaxBlockSize)
				{
					uint64_t ReclaimedSpace = GcCtx.ClaimGCReserve();
					if (Space.Free + ReclaimedSpace < m_MaxBlockSize)
					{
						ZEN_WARN("garbage collect for '{}' FAILED, required disk space {}, free {}",
								 m_Config.RootDirectory / m_ContainerBaseName,
								 m_MaxBlockSize,
								 NiceBytes(Space.Free + ReclaimedSpace));
						RwLock::ExclusiveLockScope _l(m_LocationMapLock);
						Stopwatch				   Timer;
						const auto				   __ = MakeGuard([&Timer, &ReadBlockTimeUs, &ReadBlockLongestTimeUs] {
							uint64_t ElapsedUs = Timer.GetElapsedTimeUs();
							ReadBlockTimeUs += ElapsedUs;
							ReadBlockLongestTimeUs = std::max(ElapsedUs, ReadBlockLongestTimeUs);
						});
						m_ChunkBlocks.erase(NextBlockIndex);
						return;
					}

					ZEN_INFO("using gc reserve for '{}', reclaimed {}, disk free {}",
							 m_Config.RootDirectory / m_ContainerBaseName,
							 ReclaimedSpace,
							 NiceBytes(Space.Free + ReclaimedSpace));
				}
				NewBlockFile->Create(m_MaxBlockSize);
				NewBlockIndex = NextBlockIndex;
				WriteOffset	  = 0;
			}

			NewBlockFile->Write(Chunk.data(), Chunk.size(), WriteOffset);
			MovedBlockChunks.emplace(
				ChunkHash,
				BlockStoreDiskLocation({.BlockIndex = NewBlockIndex, .Offset = WriteOffset, .Size = Chunk.size()}, m_PayloadAlignment));
			WriteOffset = RoundUp(WriteOffset + Chunk.size(), m_PayloadAlignment);
		}
		Chunk.clear();
		if (NewBlockFile)
		{
			NewBlockFile->Truncate(WriteOffset);
			NewBlockFile->Flush();
			NewBlockFile = {};
		}

		const std::vector<IoHash>&	   DeleteMap  = DeleteChunks[ChunkMapIndex];
		std::vector<CasDiskIndexEntry> LogEntries = MakeCasDiskEntries(MovedBlockChunks, DeleteMap);
		m_CasLog.Append(LogEntries);
		m_CasLog.Flush();
		{
			RwLock::ExclusiveLockScope __(m_LocationMapLock);
			Stopwatch				   Timer;
			const auto				   ___ = MakeGuard([&Timer, &ReadBlockTimeUs, &ReadBlockLongestTimeUs] {
				uint64_t ElapsedUs = Timer.GetElapsedTimeUs();
				ReadBlockTimeUs += ElapsedUs;
				ReadBlockLongestTimeUs = std::max(ElapsedUs, ReadBlockLongestTimeUs);
			});
			UpdateLocations(LogEntries);
			m_ChunkBlocks[BlockIndex] = nullptr;
		}
		MovedCount += MovedBlockChunks.size();
		DeletedChunks.insert(DeletedChunks.end(), DeleteMap.begin(), DeleteMap.end());
		MovedBlockChunks.clear();

		ZEN_DEBUG("marking cas store file in '{}' for delete , block #{}, '{}'", m_ContainerBaseName, BlockIndex, OldBlockFile->GetPath());
		std::error_code Ec;
		OldBlockFile->MarkAsDeleteOnClose(Ec);
		if (Ec)
		{
			ZEN_WARN("Failed to flag file '{}' for deletion: '{}'", OldBlockFile->GetPath(), Ec.message());
		}
		OldBlockFile = nullptr;
	}

	for (const IoHash& ChunkHash : DeletedChunks)
	{
		DeletedSize += LocationMap[ChunkHash].GetSize();
	}

	GcCtx.DeletedCas(DeletedChunks);
}

void
CasContainerStrategy::MakeIndexSnapshot()
{
	ZEN_INFO("write store snapshot for '{}'", m_Config.RootDirectory / m_ContainerBaseName);
	uint64_t   EntryCount = 0;
	Stopwatch  Timer;
	const auto _ = MakeGuard([this, &EntryCount, &Timer] {
		ZEN_INFO("wrote store snapshot for '{}' containing #{} entries in {}",
				 m_Config.RootDirectory / m_ContainerBaseName,
				 EntryCount,
				 NiceTimeSpanMs(Timer.GetElapsedTimeMs()));
	});

	namespace fs = std::filesystem;

	fs::path IndexPath	   = GetIndexPath(m_Config.RootDirectory, m_ContainerBaseName);
	fs::path TempIndexPath = GetTempIndexPath(m_Config.RootDirectory, m_ContainerBaseName);

	// Move index away, we keep it if something goes wrong
	if (fs::is_regular_file(TempIndexPath))
	{
		fs::remove(TempIndexPath);
	}
	if (fs::is_regular_file(IndexPath))
	{
		fs::rename(IndexPath, TempIndexPath);
	}

	try
	{
		m_CasLog.Flush();

		// Write the current state of the location map to a new index state
		uint64_t					   LogCount = 0;
		std::vector<CasDiskIndexEntry> Entries;

		{
			RwLock::SharedLockScope __(m_InsertLock);
			RwLock::SharedLockScope ___(m_LocationMapLock);
			Entries.resize(m_LocationMap.size());

			uint64_t EntryIndex = 0;
			for (auto& Entry : m_LocationMap)
			{
				CasDiskIndexEntry& IndexEntry = Entries[EntryIndex++];
				IndexEntry.Key				  = Entry.first;
				IndexEntry.Location			  = Entry.second;
			}

			LogCount = m_CasLog.GetLogCount();
		}

		BasicFile ObjectIndexFile;
		ObjectIndexFile.Open(IndexPath, BasicFile::Mode::kTruncate);
		CasDiskIndexHeader Header = {.EntryCount	   = Entries.size(),
									 .LogPosition	   = LogCount,
									 .PayloadAlignment = gsl::narrow<uint32_t>(m_PayloadAlignment)};

		Header.Checksum = CasDiskIndexHeader::ComputeChecksum(Header);

		ObjectIndexFile.Write(&Header, sizeof(CasDiskIndexEntry), 0);
		ObjectIndexFile.Write(Entries.data(), Entries.size() * sizeof(CasDiskIndexEntry), sizeof(CasDiskIndexEntry));
		ObjectIndexFile.Flush();
		ObjectIndexFile.Close();
		EntryCount = Entries.size();
	}
	catch (std::exception& Err)
	{
		ZEN_ERROR("snapshot FAILED, reason: '{}'", Err.what());

		// Restore any previous snapshot

		if (fs::is_regular_file(TempIndexPath))
		{
			fs::remove(IndexPath);
			fs::rename(TempIndexPath, IndexPath);
		}
	}
	if (fs::is_regular_file(TempIndexPath))
	{
		fs::remove(TempIndexPath);
	}
}

uint64_t
CasContainerStrategy::ReadIndexFile()
{
	std::vector<CasDiskIndexEntry> Entries;
	std::filesystem::path		   IndexPath = GetIndexPath(m_Config.RootDirectory, m_ContainerBaseName);
	if (std::filesystem::is_regular_file(IndexPath))
	{
		Stopwatch  Timer;
		const auto _ = MakeGuard([this, &Entries, &Timer] {
			ZEN_INFO("read store '{}' index containing #{} entries in {}",
					 m_Config.RootDirectory / m_ContainerBaseName,
					 Entries.size(),
					 NiceTimeSpanMs(Timer.GetElapsedTimeMs()));
		});

		BasicFile ObjectIndexFile;
		ObjectIndexFile.Open(IndexPath, BasicFile::Mode::kRead);
		uint64_t Size = ObjectIndexFile.FileSize();
		if (Size >= sizeof(CasDiskIndexHeader))
		{
			uint64_t		   ExpectedEntryCount = (Size - sizeof(sizeof(CasDiskIndexHeader))) / sizeof(CasDiskIndexEntry);
			CasDiskIndexHeader Header;
			ObjectIndexFile.Read(&Header, sizeof(Header), 0);
			if ((Header.Magic == CasDiskIndexHeader::ExpectedMagic) && (Header.Version == CasDiskIndexHeader::CurrentVersion) &&
				(Header.Checksum == CasDiskIndexHeader::ComputeChecksum(Header)) && (Header.PayloadAlignment > 0) &&
				(Header.EntryCount <= ExpectedEntryCount))
			{
				Entries.resize(Header.EntryCount);
				ObjectIndexFile.Read(Entries.data(), Header.EntryCount * sizeof(CasDiskIndexEntry), sizeof(CasDiskIndexHeader));
				m_PayloadAlignment = Header.PayloadAlignment;

				std::string InvalidEntryReason;
				for (const CasDiskIndexEntry& Entry : Entries)
				{
					if (!ValidateEntry(Entry, InvalidEntryReason))
					{
						ZEN_WARN("skipping invalid entry in '{}', reason: '{}'", IndexPath, InvalidEntryReason);
						continue;
					}
					m_LocationMap[Entry.Key] = Entry.Location;
				}

				return Header.LogPosition;
			}
			else
			{
				ZEN_WARN("skipping invalid index file '{}'", IndexPath);
			}
		}
	}
	return 0;
}

uint64_t
CasContainerStrategy::ReadLog(uint64_t SkipEntryCount)
{
	std::vector<CasDiskIndexEntry> Entries;
	std::filesystem::path		   LogPath = GetLogPath(m_Config.RootDirectory, m_ContainerBaseName);
	if (std::filesystem::is_regular_file(LogPath))
	{
		Stopwatch  Timer;
		const auto _ = MakeGuard([this, &Entries, &Timer] {
			ZEN_INFO("read store '{}' log containing #{} entries in {}",
					 m_Config.RootDirectory / m_ContainerBaseName,
					 Entries.size(),
					 NiceTimeSpanMs(Timer.GetElapsedTimeMs()));
		});

		TCasLogFile<CasDiskIndexEntry> CasLog;
		CasLog.Open(LogPath, CasLogFile::Mode::kRead);
		if (CasLog.Initialize())
		{
			uint64_t EntryCount = CasLog.GetLogCount();
			if (EntryCount < SkipEntryCount)
			{
				ZEN_WARN("reading full log at '{}', reason: Log position from index snapshot is out of range", LogPath);
				SkipEntryCount = 0;
			}
			uint64_t ReadCount = EntryCount - SkipEntryCount;
			Entries.reserve(ReadCount);
			CasLog.Replay(
				[&](const CasDiskIndexEntry& Record) {
					std::string InvalidEntryReason;
					if (Record.Flags & CasDiskIndexEntry::kTombstone)
					{
						m_LocationMap.erase(Record.Key);
						return;
					}
					if (!ValidateEntry(Record, InvalidEntryReason))
					{
						ZEN_WARN("skipping invalid entry in '{}', reason: '{}'", LogPath, InvalidEntryReason);
						return;
					}
					m_LocationMap[Record.Key] = Record.Location;
				},
				SkipEntryCount);
			return ReadCount;
		}
	}
	return 0;
}

uint64_t
CasContainerStrategy::MigrateLegacyData(bool CleanSource)
{
	std::filesystem::path LegacyLogPath = GetLegacyLogPath(m_Config.RootDirectory, m_ContainerBaseName);

	if (!std::filesystem::is_regular_file(LegacyLogPath) || std::filesystem::file_size(LegacyLogPath) == 0)
	{
		return 0;
	}

	ZEN_INFO("migrating store '{}'", m_Config.RootDirectory / m_ContainerBaseName);

	std::filesystem::path LegacyDataPath  = GetLegacyDataPath(m_Config.RootDirectory, m_ContainerBaseName);
	std::filesystem::path LegacyIndexPath = GetLegacyIndexPath(m_Config.RootDirectory, m_ContainerBaseName);

	uint64_t   MigratedChunkCount = 0;
	uint32_t   MigratedBlockCount = 0;
	Stopwatch  MigrationTimer;
	uint64_t   TotalSize = 0;
	const auto _		 = MakeGuard([this, &MigrationTimer, &MigratedChunkCount, &MigratedBlockCount, &TotalSize] {
		ZEN_INFO("migrated store '{}' to #{} chunks in #{} blocks in {} ({})",
				 m_Config.RootDirectory / m_ContainerBaseName,
				 MigratedChunkCount,
				 MigratedBlockCount,
				 NiceTimeSpanMs(MigrationTimer.GetElapsedTimeMs()),
				 NiceBytes(TotalSize));
	});

	uint32_t WriteBlockIndex = 0;
	while (std::filesystem::exists(GetBlockPath(m_BlocksBasePath, WriteBlockIndex)))
	{
		++WriteBlockIndex;
	}

	std::error_code Error;
	DiskSpace		Space = DiskSpaceInfo(m_Config.RootDirectory, Error);
	if (Error)
	{
		ZEN_ERROR("get disk space in {} FAILED, reason: '{}'", m_Config.RootDirectory, Error.message());
		return 0;
	}

	if (Space.Free < m_MaxBlockSize)
	{
		ZEN_ERROR("legacy store migration from '{}' FAILED, required disk space {}, free {}",
				  m_Config.RootDirectory / m_ContainerBaseName,
				  m_MaxBlockSize,
				  NiceBytes(Space.Free));
		return 0;
	}

	BasicFile BlockFile;
	BlockFile.Open(LegacyDataPath, CleanSource ? BasicFile::Mode::kWrite : BasicFile::Mode::kRead);

	std::unordered_map<IoHash, LegacyCasDiskIndexEntry, IoHash::Hasher> LegacyDiskIndex;
	uint64_t															InvalidEntryCount = 0;

	TCasLogFile<LegacyCasDiskIndexEntry> LegacyCasLog;
	LegacyCasLog.Open(LegacyLogPath, CleanSource ? CasLogFile::Mode::kWrite : CasLogFile::Mode::kRead);
	{
		Stopwatch  Timer;
		const auto __ = MakeGuard([this, &LegacyDiskIndex, &Timer] {
			ZEN_INFO("read store '{}' legacy log containing #{} entries in {}",
					 m_Config.RootDirectory / m_ContainerBaseName,
					 LegacyDiskIndex.size(),
					 NiceTimeSpanMs(Timer.GetElapsedTimeMs()));
		});
		if (LegacyCasLog.Initialize())
		{
			LegacyDiskIndex.reserve(LegacyCasLog.GetLogCount());
			LegacyCasLog.Replay(
				[&](const LegacyCasDiskIndexEntry& Record) {
					std::string InvalidEntryReason;
					if (Record.Flags & LegacyCasDiskIndexEntry::kTombstone)
					{
						LegacyDiskIndex.erase(Record.Key);
						return;
					}
					if (!ValidateLegacyEntry(Record, InvalidEntryReason))
					{
						ZEN_WARN("skipping invalid entry in '{}', reason: '{}'", LegacyLogPath, InvalidEntryReason);
						InvalidEntryCount++;
						return;
					}
					LegacyDiskIndex.insert_or_assign(Record.Key, Record);
				},
				0);

			std::vector<IoHash> BadEntries;
			uint64_t			BlockFileSize = BlockFile.FileSize();
			for (const auto& Entry : LegacyDiskIndex)
			{
				const LegacyCasDiskIndexEntry& Record(Entry.second);
				if (Record.Location.GetOffset() + Record.Location.GetSize() <= BlockFileSize)
				{
					continue;
				}
				ZEN_WARN("skipping invalid entry in '{}', reason: location is outside of file", LegacyLogPath);
				BadEntries.push_back(Entry.first);
			}
			for (const IoHash& BadHash : BadEntries)
			{
				LegacyDiskIndex.erase(BadHash);
			}
			InvalidEntryCount += BadEntries.size();
		}
	}

	if (InvalidEntryCount)
	{
		ZEN_WARN("found #{} invalid entries in '{}'", InvalidEntryCount, m_Config.RootDirectory / m_ContainerBaseName);
	}

	if (LegacyDiskIndex.empty())
	{
		BlockFile.Close();
		LegacyCasLog.Close();
		if (CleanSource)
		{
			// Older versions of CasContainerStrategy expects the legacy files to exist if it can find
			// a CAS manifest and crashes on startup if they don't.
			// In order to not break startup when switching back an older version, lets just reset
			// the legacy data files to zero length.

			BasicFile LegacyLog;
			LegacyLog.Open(LegacyLogPath, BasicFile::Mode::kTruncate);
			BasicFile LegacySobs;
			LegacySobs.Open(LegacyDataPath, BasicFile::Mode::kTruncate);
			BasicFile LegacySidx;
			LegacySidx.Open(LegacyIndexPath, BasicFile::Mode::kTruncate);
		}
		return 0;
	}

	for (const auto& Entry : LegacyDiskIndex)
	{
		const LegacyCasDiskIndexEntry& Record(Entry.second);
		TotalSize += Record.Location.GetSize();
	}

	uint64_t RequiredDiskSpace	   = TotalSize + ((m_PayloadAlignment - 1) * LegacyDiskIndex.size());
	uint64_t MaxRequiredBlockCount = RoundUp(RequiredDiskSpace, m_MaxBlockSize) / m_MaxBlockSize;
	if (MaxRequiredBlockCount > BlockStoreDiskLocation::MaxBlockIndex)
	{
		ZEN_ERROR("legacy store migration from '{}' FAILED, required block count {}, possible {}",
				  m_Config.RootDirectory / m_ContainerBaseName,
				  MaxRequiredBlockCount,
				  BlockStoreDiskLocation::MaxBlockIndex);
		return 0;
	}

	constexpr const uint64_t DiskReserve = 1ul << 28;

	if (CleanSource)
	{
		if (Space.Free < (m_MaxBlockSize + DiskReserve))
		{
			ZEN_INFO("legacy store migration from '{}' aborted, not enough disk space available {} ({})",
					 m_Config.RootDirectory / m_ContainerBaseName,
					 NiceBytes(m_MaxBlockSize + DiskReserve),
					 NiceBytes(Space.Free));
			return 0;
		}
	}
	else
	{
		if (Space.Free < (RequiredDiskSpace + DiskReserve))
		{
			ZEN_INFO("legacy store migration from '{}' aborted, not enough disk space available {} ({})",
					 m_Config.RootDirectory / m_ContainerBaseName,
					 NiceBytes(RequiredDiskSpace + DiskReserve),
					 NiceBytes(Space.Free));
			return 0;
		}
	}

	std::filesystem::path LogPath = GetLogPath(m_Config.RootDirectory, m_ContainerBaseName);
	CreateDirectories(LogPath.parent_path());
	TCasLogFile<CasDiskIndexEntry> CasLog;
	CasLog.Open(LogPath, CasLogFile::Mode::kWrite);

	if (CleanSource && (MaxRequiredBlockCount < 2))
	{
		std::vector<CasDiskIndexEntry> LogEntries;
		LogEntries.reserve(LegacyDiskIndex.size());

		// We can use the block as is, just move it and add the blocks to our new log
		for (auto& Entry : LegacyDiskIndex)
		{
			const LegacyCasDiskIndexEntry& Record(Entry.second);

			BlockStoreLocation	   NewChunkLocation{WriteBlockIndex, Record.Location.GetOffset(), Record.Location.GetSize()};
			BlockStoreDiskLocation NewLocation(NewChunkLocation, m_PayloadAlignment);
			LogEntries.push_back(
				{.Key = Entry.second.Key, .Location = NewLocation, .ContentType = Record.ContentType, .Flags = Record.Flags});
		}
		std::filesystem::path BlockPath = GetBlockPath(m_BlocksBasePath, WriteBlockIndex);
		CreateDirectories(BlockPath.parent_path());
		BlockFile.Close();
		std::filesystem::rename(LegacyDataPath, BlockPath);
		CasLog.Append(LogEntries);
		for (const CasDiskIndexEntry& Entry : LogEntries)
		{
			m_LocationMap.insert_or_assign(Entry.Key, Entry.Location);
		}

		MigratedChunkCount += LogEntries.size();
		MigratedBlockCount++;
	}
	else
	{
		std::vector<IoHash> ChunkHashes;
		ChunkHashes.reserve(LegacyDiskIndex.size());
		for (const auto& Entry : LegacyDiskIndex)
		{
			ChunkHashes.push_back(Entry.first);
		}

		std::sort(begin(ChunkHashes), end(ChunkHashes), [&](IoHash Lhs, IoHash Rhs) {
			auto LhsKeyIt = LegacyDiskIndex.find(Lhs);
			auto RhsKeyIt = LegacyDiskIndex.find(Rhs);
			return LhsKeyIt->second.Location.GetOffset() < RhsKeyIt->second.Location.GetOffset();
		});

		uint64_t						BlockSize	= 0;
		uint64_t						BlockOffset = 0;
		std::vector<BlockStoreLocation> NewLocations;
		struct BlockData
		{
			std::vector<std::pair<IoHash, BlockStoreLocation>> Chunks;
			uint64_t										   BlockOffset;
			uint64_t										   BlockSize;
			uint32_t										   BlockIndex;
		};

		std::vector<BlockData>							   BlockRanges;
		std::vector<std::pair<IoHash, BlockStoreLocation>> Chunks;
		BlockRanges.reserve(MaxRequiredBlockCount);
		for (const IoHash& ChunkHash : ChunkHashes)
		{
			const LegacyCasDiskIndexEntry& LegacyEntry		   = LegacyDiskIndex[ChunkHash];
			const LegacyCasDiskLocation&   LegacyChunkLocation = LegacyEntry.Location;

			uint64_t ChunkOffset = LegacyChunkLocation.GetOffset();
			uint64_t ChunkSize	 = LegacyChunkLocation.GetSize();
			uint64_t ChunkEnd	 = ChunkOffset + ChunkSize;

			if (BlockSize == 0)
			{
				BlockOffset = ChunkOffset;
			}
			if ((ChunkEnd - BlockOffset) > m_MaxBlockSize)
			{
				BlockData BlockRange{.BlockOffset = BlockOffset, .BlockSize = BlockSize, .BlockIndex = WriteBlockIndex};
				BlockRange.Chunks.swap(Chunks);
				BlockRanges.push_back(BlockRange);

				WriteBlockIndex++;
				while (std::filesystem::exists(GetBlockPath(m_BlocksBasePath, WriteBlockIndex)))
				{
					++WriteBlockIndex;
				}
				BlockOffset = ChunkOffset;
				BlockSize	= 0;
			}
			BlockSize						 = RoundUp(BlockSize, m_PayloadAlignment);
			BlockStoreLocation ChunkLocation = {.BlockIndex = WriteBlockIndex, .Offset = ChunkOffset - BlockOffset, .Size = ChunkSize};
			Chunks.push_back({ChunkHash, ChunkLocation});
			BlockSize = ChunkEnd - BlockOffset;
		}
		if (BlockSize > 0)
		{
			BlockRanges.push_back(
				{.Chunks = std::move(Chunks), .BlockOffset = BlockOffset, .BlockSize = BlockSize, .BlockIndex = WriteBlockIndex});
		}
		Stopwatch WriteBlockTimer;

		std::reverse(BlockRanges.begin(), BlockRanges.end());
		std::vector<std::uint8_t> Buffer(1 << 28);
		for (size_t Idx = 0; Idx < BlockRanges.size(); ++Idx)
		{
			const BlockData& BlockRange = BlockRanges[Idx];
			if (Idx > 0)
			{
				uint64_t Remaining = BlockRange.BlockOffset + BlockRange.BlockSize;
				uint64_t Completed = BlockOffset + BlockSize - Remaining;
				uint64_t ETA	   = (WriteBlockTimer.GetElapsedTimeMs() * Remaining) / Completed;

				ZEN_INFO("migrating store '{}' {}/{} blocks, remaining {} ({}) ETA: {}",
						 m_Config.RootDirectory / m_ContainerBaseName,
						 Idx,
						 BlockRanges.size(),
						 NiceBytes(BlockRange.BlockOffset + BlockRange.BlockSize),
						 NiceBytes(BlockOffset + BlockSize),
						 NiceTimeSpanMs(ETA));
			}

			std::filesystem::path BlockPath = GetBlockPath(m_BlocksBasePath, BlockRange.BlockIndex);
			BlockStoreFile		  ChunkBlock(BlockPath);
			ChunkBlock.Create(BlockRange.BlockSize);
			uint64_t Offset = 0;
			while (Offset < BlockRange.BlockSize)
			{
				uint64_t Size = BlockRange.BlockSize - Offset;
				if (Size > Buffer.size())
				{
					Size = Buffer.size();
				}
				BlockFile.Read(Buffer.data(), Size, BlockRange.BlockOffset + Offset);
				ChunkBlock.Write(Buffer.data(), Size, Offset);
				Offset += Size;
			}
			ChunkBlock.Truncate(Offset);
			ChunkBlock.Flush();

			std::vector<CasDiskIndexEntry> LogEntries;
			LogEntries.reserve(BlockRange.Chunks.size());
			for (const auto& Entry : BlockRange.Chunks)
			{
				const LegacyCasDiskIndexEntry& LegacyEntry = LegacyDiskIndex[Entry.first];
				BlockStoreDiskLocation		   Location(Entry.second, m_PayloadAlignment);
				LogEntries.push_back(
					{.Key = Entry.first, .Location = Location, .ContentType = LegacyEntry.ContentType, .Flags = LegacyEntry.Flags});
			}
			CasLog.Append(LogEntries);
			for (const CasDiskIndexEntry& Entry : LogEntries)
			{
				m_LocationMap.insert_or_assign(Entry.Key, Entry.Location);
			}
			MigratedChunkCount += LogEntries.size();
			MigratedBlockCount++;

			if (CleanSource)
			{
				std::vector<LegacyCasDiskIndexEntry> LegacyLogEntries;
				LegacyLogEntries.reserve(BlockRange.Chunks.size());
				for (const auto& Entry : BlockRange.Chunks)
				{
					LegacyLogEntries.push_back({.Key = Entry.first, .Flags = LegacyCasDiskIndexEntry::kTombstone});
				}
				LegacyCasLog.Append(LegacyLogEntries);
				BlockFile.SetFileSize(BlockRange.BlockOffset);
			}
		}
	}

	BlockFile.Close();
	LegacyCasLog.Close();
	CasLog.Close();

	if (CleanSource)
	{
		// Older versions of CasContainerStrategy expects the legacy files to exist if it can find
		// a CAS manifest and crashes on startup if they don't.
		// In order to not break startup when switching back an older version, lets just reset
		// the legacy data files to zero length.

		BasicFile LegacyLog;
		LegacyLog.Open(LegacyLogPath, BasicFile::Mode::kTruncate);
		BasicFile LegacySobs;
		LegacySobs.Open(LegacyDataPath, BasicFile::Mode::kTruncate);
		BasicFile LegacySidx;
		LegacySidx.Open(LegacyIndexPath, BasicFile::Mode::kTruncate);
	}
	return MigratedChunkCount;
}

void
CasContainerStrategy::OpenContainer(bool IsNewStore)
{
	// Add .running file and delete on clean on close to detect bad termination
	m_TotalSize = 0;

	m_LocationMap.clear();

	std::filesystem::path BasePath = GetBasePath(m_Config.RootDirectory, m_ContainerBaseName);

	if (IsNewStore)
	{
		std::filesystem::path LegacyDataPath = GetLegacyDataPath(m_Config.RootDirectory, m_ContainerBaseName);
		std::filesystem::path LegacyLogPath	 = GetLegacyLogPath(m_Config.RootDirectory, m_ContainerBaseName);

		std::filesystem::remove(LegacyLogPath);
		std::filesystem::remove(LegacyDataPath);
		std::filesystem::remove_all(BasePath);
	}

	uint64_t LogPosition		 = ReadIndexFile();
	uint64_t LogEntryCount		 = ReadLog(LogPosition);
	uint64_t LegacyLogEntryCount = MigrateLegacyData(true);

	CreateDirectories(BasePath);

	std::filesystem::path LogPath = GetLogPath(m_Config.RootDirectory, m_ContainerBaseName);
	m_CasLog.Open(LogPath, CasLogFile::Mode::kWrite);

	std::unordered_set<uint32_t> KnownBlocks;
	for (const auto& Entry : m_LocationMap)
	{
		const BlockStoreDiskLocation& Location = Entry.second;
		m_TotalSize.fetch_add(Location.GetSize(), std::memory_order_seq_cst);
		KnownBlocks.insert(Location.GetBlockIndex());
	}

	if (std::filesystem::is_directory(m_BlocksBasePath))
	{
		std::vector<std::filesystem::path> FoldersToScan;
		FoldersToScan.push_back(m_BlocksBasePath);
		size_t FolderOffset = 0;
		while (FolderOffset < FoldersToScan.size())
		{
			for (const std::filesystem::directory_entry& Entry : std::filesystem::directory_iterator(FoldersToScan[FolderOffset]))
			{
				if (Entry.is_directory())
				{
					FoldersToScan.push_back(Entry.path());
					continue;
				}
				if (Entry.is_regular_file())
				{
					const std::filesystem::path Path = Entry.path();
					if (Path.extension() != DataExtension)
					{
						continue;
					}
					std::string FileName = Path.stem().string();
					uint32_t	BlockIndex;
					bool		OK = ParseHexNumber(FileName, BlockIndex);
					if (!OK)
					{
						continue;
					}
					if (!KnownBlocks.contains(BlockIndex))
					{
						// Log removing unreferenced block
						// Clear out unused blocks
						ZEN_INFO("removing unused block for '{}' at '{}'", m_ContainerBaseName, Path);
						std::error_code Ec;
						std::filesystem::remove(Path, Ec);
						if (Ec)
						{
							ZEN_WARN("Failed to delete file '{}' reason: '{}'", Path, Ec.message());
						}
						continue;
					}
					Ref<BlockStoreFile> BlockFile = new BlockStoreFile(Path);
					BlockFile->Open();
					m_ChunkBlocks[BlockIndex] = BlockFile;
				}
			}
			++FolderOffset;
		}
	}
	else
	{
		CreateDirectories(m_BlocksBasePath);
	}

	if (IsNewStore || ((LogEntryCount + LegacyLogEntryCount) > 0))
	{
		MakeIndexSnapshot();
	}

	// TODO: should validate integrity of container files here
}

//////////////////////////////////////////////////////////////////////////

#if ZEN_WITH_TESTS

namespace {
	static IoBuffer CreateChunk(uint64_t Size)
	{
		static std::random_device rd;
		static std::mt19937		  g(rd());

		std::vector<uint8_t> Values;
		Values.resize(Size);
		for (size_t Idx = 0; Idx < Size; ++Idx)
		{
			Values[Idx] = static_cast<uint8_t>(Idx);
		}
		std::shuffle(Values.begin(), Values.end(), g);

		return IoBufferBuilder::MakeCloneFromMemory(Values.data(), Values.size());
	}
}  // namespace

TEST_CASE("compactcas.hex")
{
	uint32_t	Value;
	std::string HexString;
	CHECK(!ParseHexNumber("", Value));
	char Hex[9];

	ToHexNumber(0u, Hex);
	HexString = std::string(Hex);
	CHECK(ParseHexNumber(HexString, Value));
	CHECK(Value == 0u);

	ToHexNumber(std::numeric_limits<std::uint32_t>::max(), Hex);
	HexString = std::string(Hex);
	CHECK(HexString == "ffffffff");
	CHECK(ParseHexNumber(HexString, Value));
	CHECK(Value == std::numeric_limits<std::uint32_t>::max());

	ToHexNumber(0xadf14711u, Hex);
	HexString = std::string(Hex);
	CHECK(HexString == "adf14711");
	CHECK(ParseHexNumber(HexString, Value));
	CHECK(Value == 0xadf14711u);

	ToHexNumber(0x80000000u, Hex);
	HexString = std::string(Hex);
	CHECK(HexString == "80000000");
	CHECK(ParseHexNumber(HexString, Value));
	CHECK(Value == 0x80000000u);

	ToHexNumber(0x718293a4u, Hex);
	HexString = std::string(Hex);
	CHECK(HexString == "718293a4");
	CHECK(ParseHexNumber(HexString, Value));
	CHECK(Value == 0x718293a4u);
}

TEST_CASE("compactcas.compact.gc")
{
	ScopedTemporaryDirectory TempDir;

	CasStoreConfiguration CasConfig;
	CasConfig.RootDirectory = TempDir.Path();
	CreateDirectories(CasConfig.RootDirectory);

	const int kIterationCount = 1000;

	std::vector<IoHash> Keys(kIterationCount);

	{
		CasGc				 Gc;
		CasContainerStrategy Cas(CasConfig, Gc);
		Cas.Initialize("test", 65536, 16, true);

		for (int i = 0; i < kIterationCount; ++i)
		{
			CbObjectWriter Cbo;
			Cbo << "id" << i;
			CbObject Obj = Cbo.Save();

			IoBuffer	 ObjBuffer = Obj.GetBuffer().AsIoBuffer();
			const IoHash Hash	   = HashBuffer(ObjBuffer);

			Cas.InsertChunk(ObjBuffer, Hash);

			Keys[i] = Hash;
		}

		for (int i = 0; i < kIterationCount; ++i)
		{
			IoBuffer Chunk = Cas.FindChunk(Keys[i]);

			CHECK(!!Chunk);

			CbObject Value = LoadCompactBinaryObject(Chunk);

			CHECK_EQ(Value["id"].AsInt32(), i);
		}
	}

	// Validate that we can still read the inserted data after closing
	// the original cas store

	{
		CasGc				 Gc;
		CasContainerStrategy Cas(CasConfig, Gc);
		Cas.Initialize("test", 65536, 16, false);

		for (int i = 0; i < kIterationCount; ++i)
		{
			IoBuffer Chunk = Cas.FindChunk(Keys[i]);

			CHECK(!!Chunk);

			CbObject Value = LoadCompactBinaryObject(Chunk);

			CHECK_EQ(Value["id"].AsInt32(), i);
		}
	}
}

TEST_CASE("compactcas.compact.totalsize")
{
	std::random_device rd;
	std::mt19937	   g(rd());

	//	for (uint32_t i = 0; i < 100; ++i)
	{
		ScopedTemporaryDirectory TempDir;

		CasStoreConfiguration CasConfig;
		CasConfig.RootDirectory = TempDir.Path();

		CreateDirectories(CasConfig.RootDirectory);

		const uint64_t kChunkSize  = 1024;
		const int32_t  kChunkCount = 16;

		{
			CasGc				 Gc;
			CasContainerStrategy Cas(CasConfig, Gc);
			Cas.Initialize("test", 65536, 16, true);

			for (int32_t Idx = 0; Idx < kChunkCount; ++Idx)
			{
				IoBuffer			   Chunk		= CreateChunk(kChunkSize);
				const IoHash		   Hash			= HashBuffer(Chunk);
				CasStore::InsertResult InsertResult = Cas.InsertChunk(Chunk, Hash);
				ZEN_ASSERT(InsertResult.New);
			}

			const uint64_t TotalSize = Cas.StorageSize().DiskSize;
			CHECK_EQ(kChunkSize * kChunkCount, TotalSize);
		}

		{
			CasGc				 Gc;
			CasContainerStrategy Cas(CasConfig, Gc);
			Cas.Initialize("test", 65536, 16, false);

			const uint64_t TotalSize = Cas.StorageSize().DiskSize;
			CHECK_EQ(kChunkSize * kChunkCount, TotalSize);
		}

		// Re-open again, this time we should have a snapshot
		{
			CasGc				 Gc;
			CasContainerStrategy Cas(CasConfig, Gc);
			Cas.Initialize("test", 65536, 16, false);

			const uint64_t TotalSize = Cas.StorageSize().DiskSize;
			CHECK_EQ(kChunkSize * kChunkCount, TotalSize);
		}
	}
}

TEST_CASE("compactcas.gc.basic")
{
	ScopedTemporaryDirectory TempDir;

	CasStoreConfiguration CasConfig;
	CasConfig.RootDirectory = TempDir.Path();
	CreateDirectories(CasConfig.RootDirectory);

	CasGc				 Gc;
	CasContainerStrategy Cas(CasConfig, Gc);
	Cas.Initialize("cb", 65536, 1 << 4, true);

	IoBuffer Chunk	   = CreateChunk(128);
	IoHash	 ChunkHash = IoHash::HashBuffer(Chunk);

	const CasStore::InsertResult InsertResult = Cas.InsertChunk(Chunk, ChunkHash);
	CHECK(InsertResult.New);
	Cas.Flush();

	GcContext GcCtx;
	GcCtx.CollectSmallObjects(true);

	Cas.CollectGarbage(GcCtx);

	CHECK(!Cas.HaveChunk(ChunkHash));
}

TEST_CASE("compactcas.gc.removefile")
{
	ScopedTemporaryDirectory TempDir;

	CasStoreConfiguration CasConfig;
	CasConfig.RootDirectory = TempDir.Path();
	CreateDirectories(CasConfig.RootDirectory);

	IoBuffer Chunk	   = CreateChunk(128);
	IoHash	 ChunkHash = IoHash::HashBuffer(Chunk);
	{
		CasGc				 Gc;
		CasContainerStrategy Cas(CasConfig, Gc);
		Cas.Initialize("cb", 65536, 1 << 4, true);

		const CasStore::InsertResult InsertResult = Cas.InsertChunk(Chunk, ChunkHash);
		CHECK(InsertResult.New);
		const CasStore::InsertResult InsertResultDup = Cas.InsertChunk(Chunk, ChunkHash);
		CHECK(!InsertResultDup.New);
		Cas.Flush();
	}

	CasGc				 Gc;
	CasContainerStrategy Cas(CasConfig, Gc);
	Cas.Initialize("cb", 65536, 1 << 4, false);

	GcContext GcCtx;
	GcCtx.CollectSmallObjects(true);

	Cas.CollectGarbage(GcCtx);

	CHECK(!Cas.HaveChunk(ChunkHash));
}

TEST_CASE("compactcas.gc.compact")
{
	//	for (uint32_t i = 0; i < 100; ++i)
	{
		ScopedTemporaryDirectory TempDir;

		CasStoreConfiguration CasConfig;
		CasConfig.RootDirectory = TempDir.Path();
		CreateDirectories(CasConfig.RootDirectory);

		CasGc				 Gc;
		CasContainerStrategy Cas(CasConfig, Gc);
		Cas.Initialize("cb", 2048, 1 << 4, true);

		uint64_t			  ChunkSizes[9] = {128, 541, 1023, 781, 218, 37, 4, 997, 5};
		std::vector<IoBuffer> Chunks;
		Chunks.reserve(9);
		for (uint64_t Size : ChunkSizes)
		{
			Chunks.push_back(CreateChunk(Size));
		}

		std::vector<IoHash> ChunkHashes;
		ChunkHashes.reserve(9);
		for (const IoBuffer& Chunk : Chunks)
		{
			ChunkHashes.push_back(IoHash::HashBuffer(Chunk.Data(), Chunk.Size()));
		}

		CHECK(Cas.InsertChunk(Chunks[0], ChunkHashes[0]).New);
		CHECK(Cas.InsertChunk(Chunks[1], ChunkHashes[1]).New);
		CHECK(Cas.InsertChunk(Chunks[2], ChunkHashes[2]).New);
		CHECK(Cas.InsertChunk(Chunks[3], ChunkHashes[3]).New);
		CHECK(Cas.InsertChunk(Chunks[4], ChunkHashes[4]).New);
		CHECK(Cas.InsertChunk(Chunks[5], ChunkHashes[5]).New);
		CHECK(Cas.InsertChunk(Chunks[6], ChunkHashes[6]).New);
		CHECK(Cas.InsertChunk(Chunks[7], ChunkHashes[7]).New);
		CHECK(Cas.InsertChunk(Chunks[8], ChunkHashes[8]).New);

		CHECK(Cas.HaveChunk(ChunkHashes[0]));
		CHECK(Cas.HaveChunk(ChunkHashes[1]));
		CHECK(Cas.HaveChunk(ChunkHashes[2]));
		CHECK(Cas.HaveChunk(ChunkHashes[3]));
		CHECK(Cas.HaveChunk(ChunkHashes[4]));
		CHECK(Cas.HaveChunk(ChunkHashes[5]));
		CHECK(Cas.HaveChunk(ChunkHashes[6]));
		CHECK(Cas.HaveChunk(ChunkHashes[7]));
		CHECK(Cas.HaveChunk(ChunkHashes[8]));

		uint64_t InitialSize = Cas.StorageSize().DiskSize;

		// Keep first and last
		{
			GcContext GcCtx;
			GcCtx.CollectSmallObjects(true);

			std::vector<IoHash> KeepChunks;
			KeepChunks.push_back(ChunkHashes[0]);
			KeepChunks.push_back(ChunkHashes[8]);
			GcCtx.ContributeCas(KeepChunks);

			Cas.Flush();
			Cas.CollectGarbage(GcCtx);

			CHECK(Cas.HaveChunk(ChunkHashes[0]));
			CHECK(!Cas.HaveChunk(ChunkHashes[1]));
			CHECK(!Cas.HaveChunk(ChunkHashes[2]));
			CHECK(!Cas.HaveChunk(ChunkHashes[3]));
			CHECK(!Cas.HaveChunk(ChunkHashes[4]));
			CHECK(!Cas.HaveChunk(ChunkHashes[5]));
			CHECK(!Cas.HaveChunk(ChunkHashes[6]));
			CHECK(!Cas.HaveChunk(ChunkHashes[7]));
			CHECK(Cas.HaveChunk(ChunkHashes[8]));

			CHECK(ChunkHashes[0] == IoHash::HashBuffer(Cas.FindChunk(ChunkHashes[0])));
			CHECK(ChunkHashes[8] == IoHash::HashBuffer(Cas.FindChunk(ChunkHashes[8])));
		}

		Cas.InsertChunk(Chunks[1], ChunkHashes[1]);
		Cas.InsertChunk(Chunks[2], ChunkHashes[2]);
		Cas.InsertChunk(Chunks[3], ChunkHashes[3]);
		Cas.InsertChunk(Chunks[4], ChunkHashes[4]);
		Cas.InsertChunk(Chunks[5], ChunkHashes[5]);
		Cas.InsertChunk(Chunks[6], ChunkHashes[6]);
		Cas.InsertChunk(Chunks[7], ChunkHashes[7]);

		// Keep last
		{
			GcContext GcCtx;
			GcCtx.CollectSmallObjects(true);
			std::vector<IoHash> KeepChunks;
			KeepChunks.push_back(ChunkHashes[8]);
			GcCtx.ContributeCas(KeepChunks);

			Cas.Flush();
			Cas.CollectGarbage(GcCtx);

			CHECK(!Cas.HaveChunk(ChunkHashes[0]));
			CHECK(!Cas.HaveChunk(ChunkHashes[1]));
			CHECK(!Cas.HaveChunk(ChunkHashes[2]));
			CHECK(!Cas.HaveChunk(ChunkHashes[3]));
			CHECK(!Cas.HaveChunk(ChunkHashes[4]));
			CHECK(!Cas.HaveChunk(ChunkHashes[5]));
			CHECK(!Cas.HaveChunk(ChunkHashes[6]));
			CHECK(!Cas.HaveChunk(ChunkHashes[7]));
			CHECK(Cas.HaveChunk(ChunkHashes[8]));

			CHECK(ChunkHashes[8] == IoHash::HashBuffer(Cas.FindChunk(ChunkHashes[8])));

			Cas.InsertChunk(Chunks[1], ChunkHashes[1]);
			Cas.InsertChunk(Chunks[2], ChunkHashes[2]);
			Cas.InsertChunk(Chunks[3], ChunkHashes[3]);
			Cas.InsertChunk(Chunks[4], ChunkHashes[4]);
			Cas.InsertChunk(Chunks[5], ChunkHashes[5]);
			Cas.InsertChunk(Chunks[6], ChunkHashes[6]);
			Cas.InsertChunk(Chunks[7], ChunkHashes[7]);
		}

		// Keep mixed
		{
			GcContext GcCtx;
			GcCtx.CollectSmallObjects(true);
			std::vector<IoHash> KeepChunks;
			KeepChunks.push_back(ChunkHashes[1]);
			KeepChunks.push_back(ChunkHashes[4]);
			KeepChunks.push_back(ChunkHashes[7]);
			GcCtx.ContributeCas(KeepChunks);

			Cas.Flush();
			Cas.CollectGarbage(GcCtx);

			CHECK(!Cas.HaveChunk(ChunkHashes[0]));
			CHECK(Cas.HaveChunk(ChunkHashes[1]));
			CHECK(!Cas.HaveChunk(ChunkHashes[2]));
			CHECK(!Cas.HaveChunk(ChunkHashes[3]));
			CHECK(Cas.HaveChunk(ChunkHashes[4]));
			CHECK(!Cas.HaveChunk(ChunkHashes[5]));
			CHECK(!Cas.HaveChunk(ChunkHashes[6]));
			CHECK(Cas.HaveChunk(ChunkHashes[7]));
			CHECK(!Cas.HaveChunk(ChunkHashes[8]));

			CHECK(ChunkHashes[1] == IoHash::HashBuffer(Cas.FindChunk(ChunkHashes[1])));
			CHECK(ChunkHashes[4] == IoHash::HashBuffer(Cas.FindChunk(ChunkHashes[4])));
			CHECK(ChunkHashes[7] == IoHash::HashBuffer(Cas.FindChunk(ChunkHashes[7])));

			Cas.InsertChunk(Chunks[0], ChunkHashes[0]);
			Cas.InsertChunk(Chunks[2], ChunkHashes[2]);
			Cas.InsertChunk(Chunks[3], ChunkHashes[3]);
			Cas.InsertChunk(Chunks[5], ChunkHashes[5]);
			Cas.InsertChunk(Chunks[6], ChunkHashes[6]);
			Cas.InsertChunk(Chunks[8], ChunkHashes[8]);
		}

		// Keep multiple at end
		{
			GcContext GcCtx;
			GcCtx.CollectSmallObjects(true);
			std::vector<IoHash> KeepChunks;
			KeepChunks.push_back(ChunkHashes[6]);
			KeepChunks.push_back(ChunkHashes[7]);
			KeepChunks.push_back(ChunkHashes[8]);
			GcCtx.ContributeCas(KeepChunks);

			Cas.Flush();
			Cas.CollectGarbage(GcCtx);

			CHECK(!Cas.HaveChunk(ChunkHashes[0]));
			CHECK(!Cas.HaveChunk(ChunkHashes[1]));
			CHECK(!Cas.HaveChunk(ChunkHashes[2]));
			CHECK(!Cas.HaveChunk(ChunkHashes[3]));
			CHECK(!Cas.HaveChunk(ChunkHashes[4]));
			CHECK(!Cas.HaveChunk(ChunkHashes[5]));
			CHECK(Cas.HaveChunk(ChunkHashes[6]));
			CHECK(Cas.HaveChunk(ChunkHashes[7]));
			CHECK(Cas.HaveChunk(ChunkHashes[8]));

			CHECK(ChunkHashes[6] == IoHash::HashBuffer(Cas.FindChunk(ChunkHashes[6])));
			CHECK(ChunkHashes[7] == IoHash::HashBuffer(Cas.FindChunk(ChunkHashes[7])));
			CHECK(ChunkHashes[8] == IoHash::HashBuffer(Cas.FindChunk(ChunkHashes[8])));

			Cas.InsertChunk(Chunks[0], ChunkHashes[0]);
			Cas.InsertChunk(Chunks[1], ChunkHashes[1]);
			Cas.InsertChunk(Chunks[2], ChunkHashes[2]);
			Cas.InsertChunk(Chunks[3], ChunkHashes[3]);
			Cas.InsertChunk(Chunks[4], ChunkHashes[4]);
			Cas.InsertChunk(Chunks[5], ChunkHashes[5]);
		}

		// Keep every other
		{
			GcContext GcCtx;
			GcCtx.CollectSmallObjects(true);
			std::vector<IoHash> KeepChunks;
			KeepChunks.push_back(ChunkHashes[0]);
			KeepChunks.push_back(ChunkHashes[2]);
			KeepChunks.push_back(ChunkHashes[4]);
			KeepChunks.push_back(ChunkHashes[6]);
			KeepChunks.push_back(ChunkHashes[8]);
			GcCtx.ContributeCas(KeepChunks);

			Cas.Flush();
			Cas.CollectGarbage(GcCtx);

			CHECK(Cas.HaveChunk(ChunkHashes[0]));
			CHECK(!Cas.HaveChunk(ChunkHashes[1]));
			CHECK(Cas.HaveChunk(ChunkHashes[2]));
			CHECK(!Cas.HaveChunk(ChunkHashes[3]));
			CHECK(Cas.HaveChunk(ChunkHashes[4]));
			CHECK(!Cas.HaveChunk(ChunkHashes[5]));
			CHECK(Cas.HaveChunk(ChunkHashes[6]));
			CHECK(!Cas.HaveChunk(ChunkHashes[7]));
			CHECK(Cas.HaveChunk(ChunkHashes[8]));

			CHECK(ChunkHashes[0] == IoHash::HashBuffer(Cas.FindChunk(ChunkHashes[0])));
			CHECK(ChunkHashes[2] == IoHash::HashBuffer(Cas.FindChunk(ChunkHashes[2])));
			CHECK(ChunkHashes[4] == IoHash::HashBuffer(Cas.FindChunk(ChunkHashes[4])));
			CHECK(ChunkHashes[6] == IoHash::HashBuffer(Cas.FindChunk(ChunkHashes[6])));
			CHECK(ChunkHashes[8] == IoHash::HashBuffer(Cas.FindChunk(ChunkHashes[8])));

			Cas.InsertChunk(Chunks[1], ChunkHashes[1]);
			Cas.InsertChunk(Chunks[3], ChunkHashes[3]);
			Cas.InsertChunk(Chunks[5], ChunkHashes[5]);
			Cas.InsertChunk(Chunks[7], ChunkHashes[7]);
		}

		// Verify that we nicely appended blocks even after all GC operations
		CHECK(ChunkHashes[0] == IoHash::HashBuffer(Cas.FindChunk(ChunkHashes[0])));
		CHECK(ChunkHashes[1] == IoHash::HashBuffer(Cas.FindChunk(ChunkHashes[1])));
		CHECK(ChunkHashes[2] == IoHash::HashBuffer(Cas.FindChunk(ChunkHashes[2])));
		CHECK(ChunkHashes[3] == IoHash::HashBuffer(Cas.FindChunk(ChunkHashes[3])));
		CHECK(ChunkHashes[4] == IoHash::HashBuffer(Cas.FindChunk(ChunkHashes[4])));
		CHECK(ChunkHashes[5] == IoHash::HashBuffer(Cas.FindChunk(ChunkHashes[5])));
		CHECK(ChunkHashes[6] == IoHash::HashBuffer(Cas.FindChunk(ChunkHashes[6])));
		CHECK(ChunkHashes[7] == IoHash::HashBuffer(Cas.FindChunk(ChunkHashes[7])));
		CHECK(ChunkHashes[8] == IoHash::HashBuffer(Cas.FindChunk(ChunkHashes[8])));

		uint64_t FinalSize = Cas.StorageSize().DiskSize;
		CHECK(InitialSize == FinalSize);
	}
}

TEST_CASE("compactcas.gc.deleteblockonopen")
{
	ScopedTemporaryDirectory TempDir;

	uint64_t			  ChunkSizes[20] = {128, 541, 311, 181, 218, 37, 4, 397, 5, 92, 551, 721, 31, 92, 16, 99, 131, 41, 541, 84};
	std::vector<IoBuffer> Chunks;
	Chunks.reserve(20);
	for (uint64_t Size : ChunkSizes)
	{
		Chunks.push_back(CreateChunk(Size));
	}

	std::vector<IoHash> ChunkHashes;
	ChunkHashes.reserve(20);
	for (const IoBuffer& Chunk : Chunks)
	{
		ChunkHashes.push_back(IoHash::HashBuffer(Chunk.Data(), Chunk.Size()));
	}

	CasStoreConfiguration CasConfig;
	CasConfig.RootDirectory = TempDir.Path();
	CreateDirectories(CasConfig.RootDirectory);
	{
		CasGc				 Gc;
		CasContainerStrategy Cas(CasConfig, Gc);
		Cas.Initialize("test", 1024, 16, true);

		for (size_t i = 0; i < 20; i++)
		{
			CHECK(Cas.InsertChunk(Chunks[i], ChunkHashes[i]).New);
		}

		// GC every other block
		{
			GcContext GcCtx;
			GcCtx.CollectSmallObjects(true);
			std::vector<IoHash> KeepChunks;
			for (size_t i = 0; i < 20; i += 2)
			{
				KeepChunks.push_back(ChunkHashes[i]);
			}
			GcCtx.ContributeCas(KeepChunks);

			Cas.Flush();
			Cas.CollectGarbage(GcCtx);

			for (size_t i = 0; i < 20; i += 2)
			{
				CHECK(Cas.HaveChunk(ChunkHashes[i]));
				CHECK(!Cas.HaveChunk(ChunkHashes[i + 1]));
				CHECK(ChunkHashes[i] == IoHash::HashBuffer(Cas.FindChunk(ChunkHashes[i])));
			}
		}
	}
	{
		// Re-open
		CasGc				 Gc;
		CasContainerStrategy Cas(CasConfig, Gc);
		Cas.Initialize("test", 1024, 16, false);

		for (size_t i = 0; i < 20; i += 2)
		{
			CHECK(Cas.HaveChunk(ChunkHashes[i]));
			CHECK(!Cas.HaveChunk(ChunkHashes[i + 1]));
			CHECK(ChunkHashes[i] == IoHash::HashBuffer(Cas.FindChunk(ChunkHashes[i])));
		}
	}
}

TEST_CASE("compactcas.gc.handleopeniobuffer")
{
	ScopedTemporaryDirectory TempDir;

	uint64_t			  ChunkSizes[20] = {128, 541, 311, 181, 218, 37, 4, 397, 5, 92, 551, 721, 31, 92, 16, 99, 131, 41, 541, 84};
	std::vector<IoBuffer> Chunks;
	Chunks.reserve(20);
	for (const uint64_t& Size : ChunkSizes)
	{
		Chunks.push_back(CreateChunk(Size));
	}

	std::vector<IoHash> ChunkHashes;
	ChunkHashes.reserve(20);
	for (const IoBuffer& Chunk : Chunks)
	{
		ChunkHashes.push_back(IoHash::HashBuffer(Chunk.Data(), Chunk.Size()));
	}

	CasStoreConfiguration CasConfig;
	CasConfig.RootDirectory = TempDir.Path();
	CreateDirectories(CasConfig.RootDirectory);

	CasGc				 Gc;
	CasContainerStrategy Cas(CasConfig, Gc);
	Cas.Initialize("test", 1024, 16, true);

	for (size_t i = 0; i < 20; i++)
	{
		CHECK(Cas.InsertChunk(Chunks[i], ChunkHashes[i]).New);
	}

	IoBuffer RetainChunk = Cas.FindChunk(ChunkHashes[5]);
	Cas.Flush();

	// GC everything
	GcContext GcCtx;
	GcCtx.CollectSmallObjects(true);
	Cas.CollectGarbage(GcCtx);

	for (size_t i = 0; i < 20; i++)
	{
		CHECK(!Cas.HaveChunk(ChunkHashes[i]));
	}

	CHECK(ChunkHashes[5] == IoHash::HashBuffer(RetainChunk));
}

TEST_CASE("compactcas.legacyconversion")
{
	ScopedTemporaryDirectory TempDir;

	uint64_t ChunkSizes[]	 = {2041, 1123, 1223, 1239, 341, 1412, 912, 774, 341, 431, 554, 1098, 2048, 339, 561, 16, 16, 2048, 2048};
	size_t	 ChunkCount		 = sizeof(ChunkSizes) / sizeof(uint64_t);
	size_t	 SingleBlockSize = 0;
	std::vector<IoBuffer> Chunks;
	Chunks.reserve(ChunkCount);
	for (uint64_t Size : ChunkSizes)
	{
		Chunks.push_back(CreateChunk(Size));
		SingleBlockSize += Size;
	}

	std::vector<IoHash> ChunkHashes;
	ChunkHashes.reserve(ChunkCount);
	for (const IoBuffer& Chunk : Chunks)
	{
		ChunkHashes.push_back(IoHash::HashBuffer(Chunk.Data(), Chunk.Size()));
	}

	CasStoreConfiguration CasConfig;
	CasConfig.RootDirectory = TempDir.Path();
	CreateDirectories(CasConfig.RootDirectory);

	{
		CasGc				 Gc;
		CasContainerStrategy Cas(CasConfig, Gc);
		Cas.Initialize("test", gsl::narrow<uint32_t>(SingleBlockSize * 2), 16, true);

		for (size_t i = 0; i < ChunkCount; i++)
		{
			CHECK(Cas.InsertChunk(Chunks[i], ChunkHashes[i]).New);
		}

		std::vector<IoHash> KeepChunks;
		for (size_t i = 0; i < ChunkCount; i += 2)
		{
			KeepChunks.push_back(ChunkHashes[i]);
		}
		GcContext GcCtx;
		GcCtx.CollectSmallObjects(true);
		GcCtx.ContributeCas(KeepChunks);
		Cas.Flush();
		Gc.CollectGarbage(GcCtx);
	}

	std::filesystem::path BlockPath		 = GetBlockPath(GetBlocksBasePath(CasConfig.RootDirectory, "test"), 1);
	std::filesystem::path LegacyDataPath = GetLegacyDataPath(CasConfig.RootDirectory, "test");
	std::filesystem::rename(BlockPath, LegacyDataPath);

	std::vector<CasDiskIndexEntry> LogEntries;
	std::filesystem::path		   IndexPath = GetIndexPath(CasConfig.RootDirectory, "test");
	if (std::filesystem::is_regular_file(IndexPath))
	{
		BasicFile ObjectIndexFile;
		ObjectIndexFile.Open(IndexPath, BasicFile::Mode::kRead);
		uint64_t Size = ObjectIndexFile.FileSize();
		if (Size >= sizeof(CasDiskIndexHeader))
		{
			uint64_t		   ExpectedEntryCount = (Size - sizeof(sizeof(CasDiskIndexHeader))) / sizeof(CasDiskIndexEntry);
			CasDiskIndexHeader Header;
			ObjectIndexFile.Read(&Header, sizeof(Header), 0);
			if (Header.Magic == CasDiskIndexHeader::ExpectedMagic && Header.Version == CasDiskIndexHeader::CurrentVersion &&
				Header.PayloadAlignment > 0 && Header.EntryCount == ExpectedEntryCount)
			{
				LogEntries.resize(Header.EntryCount);
				ObjectIndexFile.Read(LogEntries.data(), Header.EntryCount * sizeof(CasDiskIndexEntry), sizeof(CasDiskIndexHeader));
			}
		}
		ObjectIndexFile.Close();
		std::filesystem::remove(IndexPath);
	}

	std::filesystem::path LogPath = GetLogPath(CasConfig.RootDirectory, "test");
	{
		TCasLogFile<CasDiskIndexEntry> CasLog;
		CasLog.Open(LogPath, CasLogFile::Mode::kRead);
		LogEntries.reserve(CasLog.GetLogCount());
		CasLog.Replay([&](const CasDiskIndexEntry& Record) { LogEntries.push_back(Record); }, 0);
	}
	TCasLogFile<LegacyCasDiskIndexEntry> LegacyCasLog;
	std::filesystem::path				 LegacylogPath = GetLegacyLogPath(CasConfig.RootDirectory, "test");
	LegacyCasLog.Open(LegacylogPath, CasLogFile::Mode::kTruncate);

	for (const CasDiskIndexEntry& Entry : LogEntries)
	{
		BlockStoreLocation		Location = Entry.Location.Get(16);
		LegacyCasDiskLocation	LegacyLocation(Location.Offset, Location.Size);
		LegacyCasDiskIndexEntry LegacyEntry = {.Key			= Entry.Key,
											   .Location	= LegacyLocation,
											   .ContentType = Entry.ContentType,
											   .Flags		= Entry.Flags};
		LegacyCasLog.Append(LegacyEntry);
	}
	LegacyCasLog.Close();

	std::filesystem::remove_all(CasConfig.RootDirectory / "test");

	{
		CasGc				 Gc;
		CasContainerStrategy Cas(CasConfig, Gc);
		Cas.Initialize("test", 2048, 16, false);

		for (size_t i = 0; i < ChunkCount; i += 2)
		{
			CHECK(Cas.HaveChunk(ChunkHashes[i]));
			CHECK(!Cas.HaveChunk(ChunkHashes[i + 1]));
			CHECK(ChunkHashes[i] == IoHash::HashBuffer(Cas.FindChunk(ChunkHashes[i])));
		}
	}
}

TEST_CASE("compactcas.threadedinsert")	// * doctest::skip(true))
{
	//	for (uint32_t i = 0; i < 100; ++i)
	{
		ScopedTemporaryDirectory TempDir;

		CasStoreConfiguration CasConfig;
		CasConfig.RootDirectory = TempDir.Path();

		CreateDirectories(CasConfig.RootDirectory);

		const uint64_t kChunkSize	= 1048;
		const int32_t  kChunkCount	= 4096;
		uint64_t	   ExpectedSize = 0;

		std::unordered_map<IoHash, IoBuffer, IoHash::Hasher> Chunks;
		Chunks.reserve(kChunkCount);

		for (int32_t Idx = 0; Idx < kChunkCount; ++Idx)
		{
			while (true)
			{
				IoBuffer Chunk = CreateChunk(kChunkSize);
				IoHash	 Hash  = HashBuffer(Chunk);
				if (Chunks.contains(Hash))
				{
					continue;
				}
				Chunks[Hash] = Chunk;
				ExpectedSize += Chunk.Size();
				break;
			}
		}

		std::atomic<size_t>	 WorkCompleted = 0;
		WorkerThreadPool	 ThreadPool(4);
		CasGc				 Gc;
		CasContainerStrategy Cas(CasConfig, Gc);
		Cas.Initialize("test", 32768, 16, true);
		{
			for (const auto& Chunk : Chunks)
			{
				const IoHash&	Hash   = Chunk.first;
				const IoBuffer& Buffer = Chunk.second;
				ThreadPool.ScheduleWork([&Cas, &WorkCompleted, Buffer, Hash]() {
					CasStore::InsertResult InsertResult = Cas.InsertChunk(Buffer, Hash);
					ZEN_ASSERT(InsertResult.New);
					WorkCompleted.fetch_add(1);
				});
			}
			while (WorkCompleted < Chunks.size())
			{
				Sleep(1);
			}
		}

		WorkCompleted			 = 0;
		const uint64_t TotalSize = Cas.StorageSize().DiskSize;
		CHECK_EQ(ExpectedSize, TotalSize);

		{
			for (const auto& Chunk : Chunks)
			{
				ThreadPool.ScheduleWork([&Cas, &WorkCompleted, &Chunk]() {
					IoHash	 ChunkHash = Chunk.first;
					IoBuffer Buffer	   = Cas.FindChunk(ChunkHash);
					IoHash	 Hash	   = IoHash::HashBuffer(Buffer);
					CHECK(ChunkHash == Hash);
					WorkCompleted.fetch_add(1);
				});
			}
			while (WorkCompleted < Chunks.size())
			{
				Sleep(1);
			}
		}

		std::unordered_set<IoHash, IoHash::Hasher> GcChunkHashes;
		GcChunkHashes.reserve(Chunks.size());
		for (const auto& Chunk : Chunks)
		{
			GcChunkHashes.insert(Chunk.first);
		}
		{
			WorkCompleted = 0;
			std::unordered_map<IoHash, IoBuffer, IoHash::Hasher> NewChunks;
			NewChunks.reserve(kChunkCount);

			for (int32_t Idx = 0; Idx < kChunkCount; ++Idx)
			{
				IoBuffer Chunk	= CreateChunk(kChunkSize);
				IoHash	 Hash	= HashBuffer(Chunk);
				NewChunks[Hash] = Chunk;
			}

			std::atomic_uint32_t AddedChunkCount;

			for (const auto& Chunk : NewChunks)
			{
				ThreadPool.ScheduleWork([&Cas, &WorkCompleted, Chunk, &AddedChunkCount]() {
					Cas.InsertChunk(Chunk.second, Chunk.first);
					AddedChunkCount.fetch_add(1);
					WorkCompleted.fetch_add(1);
				});
			}
			for (const auto& Chunk : Chunks)
			{
				ThreadPool.ScheduleWork([&Cas, &WorkCompleted, Chunk]() {
					IoHash	 ChunkHash = Chunk.first;
					IoBuffer Buffer	   = Cas.FindChunk(ChunkHash);
					if (Buffer)
					{
						CHECK(ChunkHash == IoHash::HashBuffer(Buffer));
					}
					WorkCompleted.fetch_add(1);
				});
			}

			while (AddedChunkCount.load() < NewChunks.size())
			{
				// Need to be careful since we might GC blocks we don't know outside of RwLock::ExclusiveLockScope
				for (const auto& Chunk : NewChunks)
				{
					if (Cas.HaveChunk(Chunk.first))
					{
						GcChunkHashes.emplace(Chunk.first);
					}
				}
				std::vector<IoHash> KeepHashes(GcChunkHashes.begin(), GcChunkHashes.end());
				size_t				C = 0;
				while (C < KeepHashes.size())
				{
					if (C % 155 == 0)
					{
						if (C < KeepHashes.size() - 1)
						{
							KeepHashes[C] = KeepHashes[KeepHashes.size() - 1];
							KeepHashes.pop_back();
						}
						if (C + 3 < KeepHashes.size() - 1)
						{
							KeepHashes[C + 3] = KeepHashes[KeepHashes.size() - 1];
							KeepHashes.pop_back();
						}
					}
					C++;
				}

				GcContext GcCtx;
				GcCtx.CollectSmallObjects(true);
				GcCtx.ContributeCas(KeepHashes);
				Cas.CollectGarbage(GcCtx);
				CasChunkSet& Deleted = GcCtx.DeletedCas();
				Deleted.IterateChunks([&GcChunkHashes](const IoHash& ChunkHash) { GcChunkHashes.erase(ChunkHash); });
			}

			while (WorkCompleted < NewChunks.size() + Chunks.size())
			{
				Sleep(1);
			}

			// Need to be careful since we might GC blocks we don't know outside of RwLock::ExclusiveLockScope
			for (const auto& Chunk : NewChunks)
			{
				if (Cas.HaveChunk(Chunk.first))
				{
					GcChunkHashes.emplace(Chunk.first);
				}
			}
			std::vector<IoHash> KeepHashes(GcChunkHashes.begin(), GcChunkHashes.end());
			size_t				C = 0;
			while (C < KeepHashes.size())
			{
				if (C % 155 == 0)
				{
					if (C < KeepHashes.size() - 1)
					{
						KeepHashes[C] = KeepHashes[KeepHashes.size() - 1];
						KeepHashes.pop_back();
					}
					if (C + 3 < KeepHashes.size() - 1)
					{
						KeepHashes[C + 3] = KeepHashes[KeepHashes.size() - 1];
						KeepHashes.pop_back();
					}
				}
				C++;
			}

			GcContext GcCtx;
			GcCtx.CollectSmallObjects(true);
			GcCtx.ContributeCas(KeepHashes);
			Cas.CollectGarbage(GcCtx);
			CasChunkSet& Deleted = GcCtx.DeletedCas();
			Deleted.IterateChunks([&GcChunkHashes](const IoHash& ChunkHash) { GcChunkHashes.erase(ChunkHash); });
		}
		{
			WorkCompleted = 0;
			for (const IoHash& ChunkHash : GcChunkHashes)
			{
				ThreadPool.ScheduleWork([&Cas, &WorkCompleted, ChunkHash]() {
					CHECK(Cas.HaveChunk(ChunkHash));
					CHECK(ChunkHash == IoHash::HashBuffer(Cas.FindChunk(ChunkHash)));
					WorkCompleted.fetch_add(1);
				});
			}
			while (WorkCompleted < GcChunkHashes.size())
			{
				Sleep(1);
			}
		}
	}
}

TEST_CASE("compactcas.migrate.large.data" * doctest::skip(true))
{
	const char*			  BigDataPath  = "D:\\zen-data\\dc4-zen-cache-t\\cas";
	std::filesystem::path TobsBasePath = GetBasePath(BigDataPath, "tobs");
	std::filesystem::path SobsBasePath = GetBasePath(BigDataPath, "sobs");
	std::filesystem::remove_all(TobsBasePath);
	std::filesystem::remove_all(SobsBasePath);

	CasStoreConfiguration CasConfig;
	CasConfig.RootDirectory = BigDataPath;
	uint64_t TObsSize		= 0;
	{
		CasGc				 TobsCasGc;
		CasContainerStrategy TobsCas(CasConfig, TobsCasGc);
		TobsCas.Initialize("tobs", 1u << 28, 16, false);
		TObsSize = TobsCas.StorageSize().DiskSize;
		CHECK(TObsSize > 0);
	}

	uint64_t SObsSize = 0;
	{
		CasGc				 SobsCasGc;
		CasContainerStrategy SobsCas(CasConfig, SobsCasGc);
		SobsCas.Initialize("sobs", 1u << 30, 4096, false);
		SObsSize = SobsCas.StorageSize().DiskSize;
		CHECK(SObsSize > 0);
	}

	CasGc				 TobsCasGc;
	CasContainerStrategy TobsCas(CasConfig, TobsCasGc);
	TobsCas.Initialize("tobs", 1u << 28, 16, false);
	GcContext TobsGcCtx;
	TobsCas.CollectGarbage(TobsGcCtx);
	CHECK(TobsCas.StorageSize().DiskSize == TObsSize);

	CasGc				 SobsCasGc;
	CasContainerStrategy SobsCas(CasConfig, SobsCasGc);
	SobsCas.Initialize("sobs", 1u << 30, 4096, false);
	GcContext SobsGcCtx;
	SobsCas.CollectGarbage(SobsGcCtx);
	CHECK(SobsCas.StorageSize().DiskSize == SObsSize);
}

#endif

void
compactcas_forcelink()
{
}

}  // namespace zen