/** * CrossKvDB persistence test without using test factory pattern. * Tests that data persists across database close/reopen cycles. * * This test: * 1. Creates a CrossKvDB with a specific filename * 2. Creates a tree and adds data * 3. Saves a version * 4. Closes the database * 5. Reopens the same database file * 6. Loads the saved version * 7. Verifies the data is correct */ import { existsSync, rmSync, } from "node:fs"; import { tmpdir, } from "node:os"; import { join, } from "node:path"; import { afterEach, beforeEach, describe, expect, it, } from "vitest"; import { ImmutableTree, } from "../immutable-tree.js"; import { MutableTree, } from "../mutable-tree.js"; import { NodeDB, } from "../storage/node-db.js"; import { DEFAULT_OPTIONS, } from "../types/options.js"; import { CrossKvDB, } from "./cross-kv.js"; // Text encoder for creating keys/values const encoder = new TextEncoder(); describe("CrossKvDB Persistence - Direct Instantiation", () => { let dbPath: string; beforeEach(() => { // Generate unique filename for each test const timestamp = Date.now(); const random = Math.floor(Math.random() * 1000000); dbPath = join(tmpdir(), `iavl-test-crosskv-${timestamp}-${random}.db`); }); afterEach(() => { // Clean up test database file try { if (existsSync(dbPath)) { rmSync(dbPath, { recursive: true, force: true, }); } } catch (err) { console.error(`Failed to cleanup test db at ${dbPath}:`, err); } }); it("should persist data across database close and reopen", async () => { const key1 = encoder.encode("key1"); const value1 = encoder.encode("value1"); const key2 = encoder.encode("key2"); const value2 = encoder.encode("value2"); const key3 = encoder.encode("key3"); const value3 = encoder.encode("value3"); let savedHash: Uint8Array; let savedVersion: bigint; // ===== PHASE 1: Create DB, add data, save version, close ===== { // Create CrossKvDB with specific filename const db = new CrossKvDB(); await db.open(dbPath, true); // Create NodeDB with sync enabled to ensure data is flushed to disk const ndb = new NodeDB(db, 100, { ...DEFAULT_OPTIONS, sync: true, }); await ndb.initialize(); const workingTree = new ImmutableTree(null, ndb, 0n); const tree = new MutableTree(ndb, workingTree, true); // skipFastStorageUpgrade=true // Add data to tree await tree.set(key1, value1); await tree.set(key2, value2); await tree.set(key3, value3); // Verify data is accessible before saving expect(await tree.get(key1)).toEqual(value1); expect(await tree.get(key2)).toEqual(value2); expect(await tree.get(key3)).toEqual(value3); // Save version 1 const result = await tree.saveVersion(); savedHash = result.hash; savedVersion = tree.getVersion(); expect(savedHash).toBeTruthy(); expect(savedHash.length).toBe(32); // SHA-256 hash expect(savedVersion).toBe(1n); // Close the database (sync option ensures data is already flushed) await db.close(); // Check if database file exists and has data const stats = await import("node:fs/promises").then(fs => fs.stat(dbPath)); expect(stats.size).toBeGreaterThan(0); } // ===== PHASE 2: Reopen DB, load version, verify data ===== { // Reopen the same database file const db = new CrossKvDB(); await db.open(dbPath, false); // Do not create, must exist // Create NodeDB with sync enabled to ensure data is flushed to disk const ndb = new NodeDB(db, 100, { ...DEFAULT_OPTIONS, sync: true, }); await ndb.initialize(); // Scan for versions and update NodeDB internal state const versions = await ndb.getVersions(); expect(versions).toEqual([1n]); // Update NodeDB with the latest version from the scan if (versions.length > 0) { ndb.resetLatestVersion(versions[versions.length - 1]); } expect(ndb.getLatestVersion()).toBe(1n); // Load the saved version const rootNodeKey = await ndb.getRoot(savedVersion); expect(rootNodeKey).toBeTruthy(); // Load the actual root node from the node key const rootNode = await ndb.getNode(rootNodeKey!); expect(rootNode).toBeTruthy(); const loadedTree = new ImmutableTree(rootNode!, ndb, savedVersion); // Verify all data is correct const retrievedValue1 = await loadedTree.get(key1); const retrievedValue2 = await loadedTree.get(key2); const retrievedValue3 = await loadedTree.get(key3); expect(retrievedValue1).toEqual(value1); expect(retrievedValue2).toEqual(value2); expect(retrievedValue3).toEqual(value3); // Verify non-existent key returns null const nonExistentKey = encoder.encode("nonexistent"); expect(await loadedTree.get(nonExistentKey)).toBeNull(); // Verify the hash matches const loadedHash = loadedTree.hash(); expect(loadedHash).toBeTruthy(); expect(loadedHash!.length).toBe(32); expect(Buffer.from(loadedHash!).equals(Buffer.from(savedHash))).toBe(true); // Close the database await db.close(); } }); it("should persist multiple versions across database close and reopen", async () => { const savedData: Array<{ version: bigint hash: Uint8Array keys: Uint8Array[] values: Uint8Array[] }> = []; // ===== PHASE 1: Create DB, add multiple versions, close ===== { const db = new CrossKvDB(); await db.open(dbPath, true); // Create NodeDB with sync enabled to ensure data is flushed to disk const ndb = new NodeDB(db, 100, { ...DEFAULT_OPTIONS, sync: true, }); await ndb.initialize(); const workingTree = new ImmutableTree(null, ndb, 0n); const tree = new MutableTree(ndb, workingTree, true); // Create 5 versions, each adding one more key for (let i = 1; i <= 5; i++) { const key = encoder.encode(`version-${i}-key`); const value = encoder.encode(`version-${i}-value`); await tree.set(key, value); const result = await tree.saveVersion(); savedData.push({ version: tree.getVersion(), hash: result.hash, keys: [key], values: [value], }); expect(tree.getVersion()).toBe(BigInt(i)); } // Close the database await db.close(); } // ===== PHASE 2: Reopen DB, load each version, verify data ===== { const db = new CrossKvDB(); await db.open(dbPath, false); // Create NodeDB with sync enabled (not required for reading, but for consistency) const ndb = new NodeDB(db, 100, { ...DEFAULT_OPTIONS, sync: true, }); await ndb.initialize(); // Scan for versions and update NodeDB internal state const versions = await ndb.getVersions(); expect(versions).toEqual([ 1n, 2n, 3n, 4n, 5n, ]); // Update NodeDB with the latest version from the scan if (versions.length > 0) { ndb.resetLatestVersion(versions[versions.length - 1]); } expect(ndb.getLatestVersion()).toBe(5n); // Load and verify each version for (let i = 0; i < savedData.length; i++) { const versionData = savedData[i]; const rootNodeKey = await ndb.getRoot(versionData.version); expect(rootNodeKey).toBeTruthy(); // Load the actual root node from the node key const rootNode = await ndb.getNode(rootNodeKey!); expect(rootNode).toBeTruthy(); const loadedTree = new ImmutableTree(rootNode!, ndb, versionData.version); // Verify hash matches expect(loadedTree.hash()).toEqual(versionData.hash); // Verify cumulative data: each version should have all keys from version 1 to i+1 for (let j = 0; j <= i; j++) { const key = encoder.encode(`version-${j + 1}-key`); const expectedValue = encoder.encode(`version-${j + 1}-value`); const actualValue = await loadedTree.get(key); expect(actualValue).toEqual(expectedValue); } } await db.close(); } }); it("should handle updates and persist correctly", async () => { const key1 = encoder.encode("updateKey"); const value1 = encoder.encode("originalValue"); const value2 = encoder.encode("updatedValue"); let hash1: Uint8Array; let hash2: Uint8Array; // ===== PHASE 1: Create, set original value, save, update, save, close ===== { const db = new CrossKvDB(); await db.open(dbPath, true); // Create NodeDB with sync enabled to ensure data is flushed to disk const ndb = new NodeDB(db, 100, { ...DEFAULT_OPTIONS, sync: true, }); await ndb.initialize(); const workingTree = new ImmutableTree(null, ndb, 0n); const tree = new MutableTree(ndb, workingTree, true); // Set original value and save version 1 await tree.set(key1, value1); const result1 = await tree.saveVersion(); hash1 = result1.hash; expect(tree.getVersion()).toBe(1n); // Update value and save version 2 await tree.set(key1, value2); const result2 = await tree.saveVersion(); hash2 = result2.hash; expect(tree.getVersion()).toBe(2n); // Hashes should be different expect(Buffer.from(hash1).equals(Buffer.from(hash2))).toBe(false); await db.close(); } // ===== PHASE 2: Reopen and verify both versions ===== { const db = new CrossKvDB(); await db.open(dbPath, false); // Create NodeDB with sync enabled (not required for reading, but for consistency) const ndb = new NodeDB(db, 100, { ...DEFAULT_OPTIONS, sync: true, }); await ndb.initialize(); // Scan for versions and update NodeDB internal state const versions = await ndb.getVersions(); expect(versions).toEqual([1n, 2n]); // Update NodeDB with the latest version from the scan if (versions.length > 0) { ndb.resetLatestVersion(versions[versions.length - 1]); } // Load version 1 and verify original value const rootNodeKey1 = await ndb.getRoot(1n); expect(rootNodeKey1).toBeTruthy(); const rootNode1 = await ndb.getNode(rootNodeKey1!); expect(rootNode1).toBeTruthy(); const tree1 = new ImmutableTree(rootNode1!, ndb, 1n); expect(tree1.hash()).toEqual(hash1); expect(await tree1.get(key1)).toEqual(value1); // Load version 2 and verify updated value const rootNodeKey2 = await ndb.getRoot(2n); expect(rootNodeKey2).toBeTruthy(); const rootNode2 = await ndb.getNode(rootNodeKey2!); expect(rootNode2).toBeTruthy(); const tree2 = new ImmutableTree(rootNode2!, ndb, 2n); expect(tree2.hash()).toEqual(hash2); expect(await tree2.get(key1)).toEqual(value2); await db.close(); } }); });