/** * BatchWithFlusher implementation for IAVL. * * Wrapper around a batch that automatically flushes to disk when a configurable * size threshold is reached. This improves performance by batching writes while * preventing memory from growing unbounded. * * Based on Go IAVL batch.go */ import type { Batch, Database, } from "./types.js"; /** * Default flush threshold in bytes. * Based on Go IAVL options.go DefaultOptions().FlushThreshold */ export const DEFAULT_FLUSH_THRESHOLD = 100000; // 100KB /** * Overhead bytes to account for batch metadata. * Some batch implementations add extra metadata beyond key+value size. * Based on Go IAVL batch.go line 43 */ const BATCH_OVERHEAD = 100; /** * BatchWithFlusher wraps a regular batch and automatically flushes * when the batch size exceeds a threshold. * * Thread-safety: While the Go implementation uses mutexes, Node.js is single-threaded * so we don't need explicit locking. Async operations are naturally serialized. * * Based on Go IAVL batch.go BatchWithFlusher */ export class BatchWithFlusher implements Batch { private db: Database; private batch: Batch; private flushThreshold: number; private currentSize: number; private closed: boolean; /** * Creates a new BatchWithFlusher. * * @param db - Database to create batches from * @param flushThreshold - Size threshold in bytes to trigger flush (default 100KB) */ constructor(db: Database, flushThreshold = DEFAULT_FLUSH_THRESHOLD) { this.db = db; this.batch = db.batch(); this.flushThreshold = flushThreshold; this.currentSize = 0; this.closed = false; } /** * Estimates the batch size after adding a key-value pair. * * Based on Go IAVL batch.go estimateSizeAfterSetting * * @param key - Key bytes * @param value - Value bytes * @returns Estimated size after addition */ private estimateSizeAfterSetting(key: Uint8Array, value: Uint8Array): number { // Current size + key length + value length + overhead return this.currentSize + key.length + value.length + BATCH_OVERHEAD; } /** * Sets a key-value pair in the batch. * If this would exceed the flush threshold, flushes first. * * Based on Go IAVL batch.go Set * * @param key - Key to set * @param value - Value to set */ set(key: Uint8Array, value: Uint8Array): void { if (this.closed) { throw new Error("BatchWithFlusher is closed"); } const sizeAfter = this.estimateSizeAfterSetting(key, value); if (sizeAfter > this.flushThreshold) { // Need to flush before adding this entry // Note: In Go, they unlock/lock mutex here for async flush // In Node.js, we'll use async/await pattern this.flushSync(); } this.batch.set(key, value); this.currentSize += key.length + value.length; } /** * Deletes a key from the batch. * If this would exceed the flush threshold, flushes first. * * Based on Go IAVL batch.go Delete * * @param key - Key to delete */ delete(key: Uint8Array): void { if (this.closed) { throw new Error("BatchWithFlusher is closed"); } // Deletion entries also consume space (key + delete marker) const sizeAfter = this.estimateSizeAfterSetting(key, new Uint8Array(0)); if (sizeAfter > this.flushThreshold) { this.flushSync(); } this.batch.delete(key); this.currentSize += key.length; } /** * Synchronously flushes the current batch and creates a new one. * This is a private helper used during set/delete operations. * * Note: The Go implementation has async Write but we need sync here * to maintain operation ordering within set/delete. */ private flushSync(): void { // We'll need to make this operation async-safe // For now, we'll queue the flush operation throw new Error("Sync flush required - use writeAsync instead"); } /** * Writes the batch to the database and creates a new batch. * * Based on Go IAVL batch.go Write */ async write(): Promise { if (this.closed) { throw new Error("BatchWithFlusher is closed"); } await this.batch.write(); this.batch.close(); // Create new batch with pre-allocated size this.batch = this.db.batch(); this.currentSize = 0; } /** * Writes the batch to the database with sync flag and creates a new batch. * * Based on Go IAVL batch.go WriteSync * * Note: Our interface doesn't distinguish between Write and WriteSync, * but we provide this for API compatibility. */ async writeSync(): Promise { return this.write(); } /** * Closes the batch without writing. * * Based on Go IAVL batch.go Close */ close(): void { if (!this.closed) { this.batch.close(); this.closed = true; } } /** * Gets the current byte size of the batch. * * Based on Go IAVL batch.go GetByteSize * * @returns Current batch size in bytes */ getByteSize(): number { return this.currentSize; } } /** * Async version of BatchWithFlusher that properly handles async flushes. * * This version queues operations and processes them asynchronously, * allowing for proper async flush operations when threshold is exceeded. */ export class AsyncBatchWithFlusher { private db: Database; private batch: Batch; private flushThreshold: number; private currentSize: number; private closed: boolean; private operations: Array<{ type: "set" | "delete" key: Uint8Array value?: Uint8Array }> = []; private processing = false; private processPromise?: Promise; /** * Creates a new AsyncBatchWithFlusher. * * @param db - Database to create batches from * @param flushThreshold - Size threshold in bytes to trigger flush (default 100KB) */ constructor(db: Database, flushThreshold = DEFAULT_FLUSH_THRESHOLD) { this.db = db; this.batch = db.batch(); this.flushThreshold = flushThreshold; this.currentSize = 0; this.closed = false; } /** * Queues a set operation. * * @param key - Key to set * @param value - Value to set * @returns Promise that resolves when operation is processed */ async set(key: Uint8Array, value: Uint8Array): Promise { if (this.closed) { throw new Error("AsyncBatchWithFlusher is closed"); } this.operations.push({ type: "set", key, value, }); return this.processOperations(); } /** * Queues a delete operation. * * @param key - Key to delete * @returns Promise that resolves when operation is processed */ async delete(key: Uint8Array): Promise { if (this.closed) { throw new Error("AsyncBatchWithFlusher is closed"); } this.operations.push({ type: "delete", key, }); return this.processOperations(); } /** * Processes queued operations, flushing when necessary. */ private async processOperations(): Promise { if (this.processing) { // Wait for current processing to complete return this.processPromise; } this.processing = true; this.processPromise = this.doProcessOperations(); try { await this.processPromise; } finally { this.processing = false; } } /** * Actually processes the operations. */ private async doProcessOperations(): Promise { while (this.operations.length > 0) { const op = this.operations.shift()!; const sizeAfter = this.estimateSizeAfterOp(op); if (sizeAfter > this.flushThreshold) { // Flush current batch await this.flush(); } // Apply operation to batch if (op.type === "set" && op.value) { this.batch.set(op.key, op.value); this.currentSize += op.key.length + op.value.length; } else if (op.type === "delete") { this.batch.delete(op.key); this.currentSize += op.key.length; } } } /** * Estimates size after an operation. */ private estimateSizeAfterOp(op: { type: string key: Uint8Array value?: Uint8Array }): number { const valueSize = op.value ? op.value.length : 0; return this.currentSize + op.key.length + valueSize + BATCH_OVERHEAD; } /** * Flushes the current batch and creates a new one. */ private async flush(): Promise { await this.batch.write(); this.batch.close(); this.batch = this.db.batch(); this.currentSize = 0; } /** * Writes any pending operations and the final batch. */ async write(): Promise { if (this.closed) { throw new Error("AsyncBatchWithFlusher is closed"); } // Process any remaining operations await this.processOperations(); // Write final batch await this.batch.write(); this.batch.close(); // Create new batch this.batch = this.db.batch(); this.currentSize = 0; } /** * Writes any pending operations and the final batch with sync flag. * This ensures data is flushed to disk (fsync) before returning. * * Based on Go IAVL batch.go WriteSync */ async writeSync(): Promise { if (this.closed) { throw new Error("AsyncBatchWithFlusher is closed"); } // Process any remaining operations await this.processOperations(); // Write final batch with sync await this.batch.write(); this.batch.close(); // Create new batch this.batch = this.db.batch(); this.currentSize = 0; // For databases that support it, ensure data is flushed to disk // This is a placeholder - actual sync behavior depends on the database implementation } /** * Closes the batch. */ close(): void { if (!this.closed) { this.batch.close(); this.closed = true; this.operations = []; } } /** * Gets the current byte size. */ getByteSize(): number { return this.currentSize; } }