/** * @cross/kv database adapter implementation. * Based on the reference implementation patterns from Go iavl db/ directory. */ import { KV, } from "@cross/kv"; import { bytesToHex, hexToBytes, } from "../utils/bytes.js"; import type { Batch, Database, Iterator, } from "./types.js"; /** * Iterator implementation for @cross/kv. * Pre-fetches all keys/values asynchronously. */ class CrossKvIterator implements Iterator { private index = 0; private keys: Uint8Array[] = []; private values: Uint8Array[] = []; private ready = false; private readyPromise: Promise; constructor( dataPromise: Promise<{ keys: Uint8Array[] values: Uint8Array[] }>, ) { this.readyPromise = dataPromise.then((data) => { this.keys = data.keys; this.values = data.values; this.ready = true; }); } /** * Wait for the iterator to load data. * Tests should call this before using the iterator. */ async waitReady(): Promise { await this.readyPromise; } key(): Uint8Array { if (!this.valid()) { throw new Error("Iterator is not valid"); } return this.keys[this.index]; } value(): Uint8Array { if (!this.valid()) { throw new Error("Iterator is not valid"); } return this.values[this.index]; } valid(): boolean { return this.ready && this.index >= 0 && this.index < this.keys.length; } next(): void { this.index++; } close(): void { // No resources to clean up } } /** * Batch implementation for @cross/kv using transactions. */ class CrossKvBatch implements Batch { private operations: Array<{ type: "set" | "delete" key: Uint8Array value?: Uint8Array }> = []; private closed = false; constructor(private readonly db: CrossKvDB) {} set(key: Uint8Array, value: Uint8Array): void { if (this.closed) { throw new Error("Batch is closed"); } this.operations.push({ type: "set", key, value, }); } delete(key: Uint8Array): void { if (this.closed) { throw new Error("Batch is closed"); } this.operations.push({ type: "delete", key, }); } async write(): Promise { if (this.closed) { throw new Error("Batch is closed"); } // Use transaction for atomic batch operations this.db.kv.beginTransaction(); try { for (const op of this.operations) { if (op.type === "set" && op.value) { await this.db.set(op.key, op.value); } else if (op.type === "delete") { await this.db.delete(op.key); } } // End transaction and wait for it to complete await this.db.kv.endTransaction(); // Give @cross/kv time to flush writes to disk // This is a workaround for @cross/kv's async write behavior await new Promise(resolve => setTimeout(resolve, 10)); } finally { this.close(); } } close(): void { this.closed = true; this.operations = []; } } /** * Database implementation using @cross/kv. * Maps our Database interface to @cross/kv operations. */ export class CrossKvDB implements Database { public readonly kv: KV; private closed = false; constructor(filepath?: string) { this.kv = new KV(); if (filepath) { // Note: open() is async, so we'll need to call it separately void this.open(filepath); } } /** * Opens the database at the specified filepath. * Must be called before using the database if filepath is not provided in constructor. */ async open(filepath: string, createIfMissing = true): Promise { await this.kv.open(filepath, createIfMissing); } /** * Converts a Uint8Array key to @cross/kv key format. * Uses ["kv", hexKey] format to ensure valid @cross/kv keys. */ private keyToKvKey(key: Uint8Array): string[] { return ["kv", bytesToHex(key)]; } async get(key: Uint8Array): Promise { if (this.closed) { throw new Error("Database is closed"); } const kvKey = this.keyToKvKey(key); const result = await this.kv.get(kvKey); // @cross/kv returns KVTransactionResult which contains the data return result ? result.data : null; } async has(key: Uint8Array): Promise { if (this.closed) { throw new Error("Database is closed"); } const value = await this.get(key); return value !== null; } async set(key: Uint8Array, value: Uint8Array): Promise { if (this.closed) { throw new Error("Database is closed"); } const kvKey = this.keyToKvKey(key); await this.kv.set(kvKey, value); } async delete(key: Uint8Array): Promise { if (this.closed) { throw new Error("Database is closed"); } const kvKey = this.keyToKvKey(key); await this.kv.delete(kvKey); } async iterator(start?: Uint8Array, end?: Uint8Array): Promise { if (this.closed) { throw new Error("Database is closed"); } const iter = this.createIterator(start, end, false); await (iter as CrossKvIterator).waitReady(); return iter; } async reverseIterator(start?: Uint8Array, end?: Uint8Array): Promise { if (this.closed) { throw new Error("Database is closed"); } const iter = this.createIterator(start, end, true); await (iter as CrossKvIterator).waitReady(); return iter; } batch(): Batch { if (this.closed) { throw new Error("Database is closed"); } return new CrossKvBatch(this); } async close(): Promise { this.closed = true; // Give @cross/kv time to flush any pending writes before closing // This ensures data persistence across close/reopen cycles await new Promise(resolve => setTimeout(resolve, 50)); await this.kv.close(); } private createIterator(start: Uint8Array | undefined, end: Uint8Array | undefined, reverse: boolean): Iterator { // Build query for @cross/kv // We need to iterate over keys in the ["kv", hexKey] format const query: unknown[] = ["kv"]; if (start || end) { // Build range query const range: Record = { }; if (start) { range.from = bytesToHex(start); } if (end) { range.to = bytesToHex(end); } query.push(range); } else { // Match all keys under "kv" query.push({ }); } // Create a promise that collects all keys and values const dataPromise = (async () => { const keys: Uint8Array[] = []; const values: Uint8Array[] = []; for await (const entry of this.kv.iterate(query as string[], undefined, reverse)) { // Extract hex key from ["kv", hexKey] format const hexKey = entry.key[1] as string; const key = hexToBytes(hexKey); // @cross/kv uses inclusive end bounds, but our interface expects exclusive // Filter out the end key if it matches if (end) { const endHex = bytesToHex(end); if (hexKey >= endHex) { continue; } } keys.push(key); // @cross/kv returns KVTransactionResult which contains the data values.push(entry.data); } return { keys, values, }; })(); return new CrossKvIterator(dataPromise); } }