/** * NodeDB handles persistent storage of IAVL tree nodes. * It manages both regular nodes (tree structure) and fast nodes (flat key-value index). * * Key Prefixes: * - 's': Regular node keys (format: s) * - 'f': Fast node keys (format: f) * - 'm': Metadata keys (format: m) * - 'o': Legacy orphan keys (format: o) * - 'n': Legacy node keys (format: n) * - 'r': Legacy root keys (format: r) * * Corresponds to Go's nodeDB in nodedb.go */ import type { Logger, } from "winston"; import { AsyncBatchWithFlusher, } from "../db/batch-with-flusher.js"; import type { Database, Iterator, } from "../db/types.js"; import { ImmutableTree, } from "../immutable-tree.js"; import { fastKeyFormat, metadataKeyFormat, } from "../keyformat/index.js"; import type { Node, NodeGetter, } from "../node.js"; import { getRootKey, } from "../node-key.js"; import type { ChangeSet, KVPair, } from "../types/index.js"; import type { Options, Statistics, } from "../types/options.js"; import { incCacheHitCnt, incCacheMissCnt, incFastCacheHitCnt, incFastCacheMissCnt, } from "../types/options.js"; import type { Cache, } from "./cache.js"; import { LRUCache, } from "./cache.js"; import type { FastNode, } from "./fast-node.js"; // Storage version constants const STORAGE_VERSION_KEY = "storage_version"; const DEFAULT_STORAGE_VERSION = "1.0.0"; const FAST_STORAGE_VERSION = "1.1.0"; const _FAST_STORAGE_VERSION_DELIMITER = "-"; // Will be used for fast storage upgrades // Key prefixes for different data types const NODE_KEY_PREFIX = 0x73; // 's' - regular nodes const _FAST_NODE_KEY_PREFIX = 0x66; // 'f' - fast nodes (unused, using fastKeyFormat) const _METADATA_KEY_PREFIX = 0x6D; // 'm' - metadata (unused, using metadataKeyFormat) const LEGACY_ORPHAN_KEY_PREFIX = 0x6F; // 'o' - legacy orphans const LEGACY_NODE_KEY_PREFIX = 0x6E; // 'n' - legacy nodes (hash-based) const LEGACY_ROOT_KEY_PREFIX = 0x72; // 'r' - legacy roots // Default cache size for fast nodes const FAST_NODE_CACHE_SIZE = 100000; /** * NodeDB manages persistent storage of IAVL nodes. * Implements the NodeGetter interface for node retrieval. */ export class NodeDB implements NodeGetter { /** Underlying database for persistent storage */ /** * The underlying database * @internal - exposed for Importer use */ readonly db: Database; /** Batch for buffering writes with auto-flush */ private batch: AsyncBatchWithFlusher; /** Cache for regular tree nodes */ private readonly nodeCache: Cache; /** Cache for fast storage nodes */ private readonly fastNodeCache: Cache; /** Configuration options */ private readonly opts: Options; /** Storage version string */ private storageVersion: string; /** First version stored in this DB */ private firstVersion: bigint; /** Latest version stored in this DB */ private latestVersion: bigint; /** Latest version in legacy format (hash-based keys), 0 if none */ private legacyLatestVersion: bigint; /** Optional logger for diagnostics */ private readonly logger: Logger | null; /** Version to prune up to (for async pruning) */ private pruneVersion: bigint; /** Flag indicating if NodeDB is in the middle of committing */ private _isCommitting: boolean; /** Resolve function for commit completion promise */ private commitCompleteResolve: (() => void) | null; /** Promise that resolves when commit is complete */ private commitCompletePromise: Promise | null; /** Abort controller for async pruning worker */ private pruningAbortController: AbortController | null; /** Map tracking number of active readers per version */ private readonly versionReaders: Map; /** * Creates a new NodeDB instance. * * @param db - Underlying database for persistent storage * @param cacheSize - Size of the regular node cache (default: from options) * @param opts - Configuration options * @param logger - Optional logger instance */ constructor( db: Database, cacheSize: number, opts: Options, logger: Logger | null = null, ) { this.db = db; this.opts = opts; this.logger = logger; // Initialize batch with auto-flush capability this.batch = new AsyncBatchWithFlusher(db, opts.flushThreshold); // Initialize caches this.nodeCache = new LRUCache(cacheSize); this.fastNodeCache = new LRUCache(FAST_NODE_CACHE_SIZE); // Initialize versions this.firstVersion = 0n; this.latestVersion = 0n; this.legacyLatestVersion = 0n; // Initialize storage version (will be loaded from DB in async init) this.storageVersion = DEFAULT_STORAGE_VERSION; // Initialize async pruning state this.pruneVersion = 0n; this._isCommitting = false; this.commitCompleteResolve = null; this.commitCompletePromise = null; this.pruningAbortController = null; // Initialize version readers tracking this.versionReaders = new Map(); } /** * Asynchronously initializes the NodeDB by loading storage version from database. * Should be called after construction. * * @returns Promise that resolves when initialization is complete */ async initialize(): Promise { // Load storage version from database const versionKey = this.metadataKey(stringToBytes(STORAGE_VERSION_KEY)); const storedVersion = await this.db.get(versionKey); if (storedVersion) { this.storageVersion = bytesToString(storedVersion); this.logger?.debug("Loaded storage version", { version: this.storageVersion, }); } else { this.storageVersion = DEFAULT_STORAGE_VERSION; this.logger?.debug("Using default storage version", { version: this.storageVersion, }); } // Start async pruning worker if enabled if (this.opts.asyncPruning) { this.startPruningWorker(); } } /** * Gets a node from cache or database. * Implements the NodeGetter interface. * * @param nodeKey - The node key (version + nonce encoded) * @returns The node, or null if not found */ async getNode(nodeKey: Uint8Array): Promise { if (!nodeKey || nodeKey.length === 0) { throw new Error("NodeDB.getNode() requires nodeKey"); } // Check cache first const cacheKey = Buffer.from(nodeKey).toString("hex"); const cachedNode = this.nodeCache.get(cacheKey); if (cachedNode) { this.logger?.debug("Node cache hit", { nodeKey: cacheKey, }); incCacheHitCnt(this.opts.statistics); return cachedNode; } this.logger?.debug("Node cache miss", { nodeKey: cacheKey, }); incCacheMissCnt(this.opts.statistics); // Load from database const dbKey = this.nodeKey(nodeKey); let bytes = await this.db.get(dbKey); // If not found and nodeKey is a hash (32 bytes), try legacy format if (!bytes && nodeKey.length === 32) { const legacyKey = this.legacyNodeKey(nodeKey); bytes = await this.db.get(legacyKey); } if (!bytes) { return null; } // Deserialize node const { Node: NodeClass, } = await import("../node.js"); const node = NodeClass.fromBytes(nodeKey, bytes); // Add to cache this.nodeCache.add(cacheKey, node); return node; } /** * Saves a node to the database. * * @param node - The node to save */ async saveNode(node: Node): Promise { const nodeKeyBytes = node.getNodeKey(); if (!nodeKeyBytes || nodeKeyBytes.length === 0) { throw new Error("NodeDB.saveNode() requires node to have nodeKey"); } // Serialize node const bytes = node.toBytes(); // Save to database via batch const dbKey = this.nodeKey(nodeKeyBytes); await this.batch.set(dbKey, bytes); // Add to cache const cacheKey = Buffer.from(nodeKeyBytes).toString("hex"); this.nodeCache.add(cacheKey, node); this.logger?.debug("Saved node", { nodeKey: cacheKey, size: bytes.length, }); } /** * Saves a fast node to the database. * * @param fastNode - The fast node to save */ async saveFastNode(fastNode: FastNode): Promise { if (!fastNode.key || fastNode.key.length === 0) { throw new Error("NodeDB.saveFastNode() requires fastNode to have key"); } if (!this.hasUpgradedToFastStorage()) { throw new Error("Fast storage not enabled - storage version < 1.1.0"); } // Serialize fast node const bytes = fastNode.toBytes(); // Save to database via batch const dbKey = this.fastNodeKey(fastNode.key); await this.batch.set(dbKey, bytes); // Add to cache const cacheKey = Buffer.from(fastNode.key).toString("hex"); this.fastNodeCache.add(cacheKey, fastNode); this.logger?.debug("Saved fast node", { key: cacheKey, version: fastNode.versionLastUpdatedAt, size: bytes.length, }); } /** * Gets a fast node from cache or database. * * @param key - The key to look up * @returns The fast node, or null if not found */ async getFastNode(key: Uint8Array): Promise { if (!key || key.length === 0) { throw new Error("NodeDB.getFastNode() requires key"); } if (!this.hasUpgradedToFastStorage()) { throw new Error("Fast storage not enabled - storage version < 1.1.0"); } // Check cache first const cacheKey = Buffer.from(key).toString("hex"); const cachedFastNode = this.fastNodeCache.get(cacheKey); if (cachedFastNode) { this.logger?.debug("Fast node cache hit", { key: cacheKey, }); incFastCacheHitCnt(this.opts.statistics); return cachedFastNode; } this.logger?.debug("Fast node cache miss", { key: cacheKey, }); incFastCacheMissCnt(this.opts.statistics); // Load from database const dbKey = this.fastNodeKey(key); const bytes = await this.db.get(dbKey); if (!bytes) { return null; } // Deserialize fast node const { FastNode: FastNodeClass, } = await import("./fast-node.js"); const fastNode = FastNodeClass.fromBytes(key, bytes); // Add to cache this.fastNodeCache.add(cacheKey, fastNode); return fastNode; } /** * Get iterator for fast prefix and error, if any. * Creates a database iterator over the fast node key range. * * Based on Go IAVL v1.3.5 nodedb.go getFastIterator (lines 1031-1052) * * @param start - Start key (inclusive), null for beginning * @param end - End key (exclusive), null for end * @param ascending - True for forward iteration, false for reverse * @returns Database iterator * @internal */ getFastIterator( start: Uint8Array | null, end: Uint8Array | null, ascending: boolean, ): Promise { let startFormatted: Uint8Array; let endFormatted: Uint8Array; if (start !== null) { startFormatted = this.fastNodeKey(start); } else { // Start from beginning of fast node prefix startFormatted = fastKeyFormat.key(new Uint8Array(0)); } if (end !== null) { endFormatted = this.fastNodeKey(end); } else { // End at next prefix ('f' = 0x66, next is 'g' = 0x67) endFormatted = new Uint8Array(["g".charCodeAt(0)]); } if (ascending) { return this.db.iterator(startFormatted, endFormatted); } return this.db.reverseIterator(startFormatted, endFormatted); } /** * Returns whether fast storage has been enabled. * * @returns true if storage version >= 1.1.0 (fast storage) */ hasUpgradedToFastStorage(): boolean { return this.storageVersion >= FAST_STORAGE_VERSION; } /** * Gets the storage version string. * * @returns Storage version */ getStorageVersion(): string { return this.storageVersion; } /** * Gets the first version stored in this database. * * @returns First version number */ getFirstVersion(): bigint { return this.firstVersion; } /** * Gets the latest version stored in this database. * * @returns Latest version number */ getLatestVersion(): bigint { return this.latestVersion; } /** * Returns all available version numbers in the tree. * Scans the database for all saved root keys. * Returns empty array if no versions have been saved. * * Corresponds to Go's NodeDB getVersions() (used by MutableTree.AvailableVersions()) * * @returns Sorted array of all saved version numbers */ async getVersions(): Promise { const versions: bigint[] = []; // Root keys are stored as node keys with format: 's' + version (8 bytes) + nonce (4 bytes = 1) // For roots, nonce is always 1 const prefix = Buffer.from([NODE_KEY_PREFIX]); // 's' prefix // Create an iterator starting from the node key prefix const iter = await this.db.iterator(prefix, undefined); try { while (iter.valid()) { const key = iter.key(); // Check if this is a node key (starts with NODE_KEY_PREFIX='s') if (key.length > 0 && key[0] === NODE_KEY_PREFIX) { // Node keys are: 's' + version (8 bytes) + nonce (4 bytes) // Root keys have nonce = 1 if (key.length === 13) { // Check if nonce is 1 (root key) const nonceView = new DataView(key.buffer, key.byteOffset + 9, 4); const nonce = nonceView.getUint32(0, false); // big-endian if (nonce === 1) { // This is a root key, extract version const versionBytes = key.slice(1, 9); const versionView = new DataView(versionBytes.buffer, versionBytes.byteOffset, 8); const version = versionView.getBigUint64(0, false); // big-endian versions.push(version); } } } else { // No longer in node key range break; } iter.next(); } } finally { iter.close(); } // Sort versions in ascending order versions.sort((a, b) => Number(a - b)); return versions; } /** * Gets the latest version in legacy (hash-based) format. * Returns 0n if not yet loaded, -1n if no legacy versions exist. * * @returns Latest legacy version number */ async getLegacyLatestVersion(): Promise { // Return cached value if already loaded if (this.legacyLatestVersion !== 0n) { return this.legacyLatestVersion; } // Scan for the highest legacy root version // Legacy roots use prefix 'r' + version (8 bytes big-endian) const startKey = this.legacyRootKey(1n); const endKey = this.legacyRootKey(BigInt(Number.MAX_SAFE_INTEGER)); const iter = await this.db.reverseIterator(startKey, endKey); try { if (iter.valid()) { const key = iter.key(); const view = new DataView(key.buffer, key.byteOffset, key.byteLength); const version = view.getBigInt64(1, false); // Read big-endian int64 this.resetLegacyLatestVersion(version); return version; } // No legacy versions found this.resetLegacyLatestVersion(-1n); return -1n; } finally { iter.close(); } } /** * Sets the cached legacy latest version. * * @param version - Version to set */ private resetLegacyLatestVersion(version: bigint): void { this.legacyLatestVersion = version; } /** * Gets the configuration options for this NodeDB. * * @returns Options object */ getOptions(): Options { return this.opts; } /** * Checks if a version exists in the database. * * @param version - Version number to check * @returns True if version exists */ async versionExists(version: bigint): Promise { const rootKey = this.rootKey(version); return await this.db.has(rootKey); } /** * Gets the root node key for a specific version. * Returns null if version doesn't exist or has empty root. * * Based on Go IAVL nodedb.go GetRoot() - handles both stored references * and implicit root keys (when root version == stored version with nonce=1). * * @param version - Version number * @returns Root node key or null */ async getRoot(version: bigint): Promise { const rootKey = this.rootKey(version); let value = await this.db.get(rootKey); let isLegacy = false; // If not found in new format, check legacy format if (!value) { const legacyKey = this.legacyRootKey(version); value = await this.db.get(legacyKey); isLegacy = true; } if (!value) { // No value stored - check if implicit root exists // If root node has version==version and nonce==1, it's implicitly the root const implicitRootKey = getRootKey(version); const nodeKey = this.nodeKey(implicitRootKey); const nodeExists = await this.db.has(nodeKey); if (nodeExists) { return implicitRootKey; } return null; } // Empty root is stored as empty bytes if (value.length === 0) { return null; } // If value came from legacy location, return it as-is (legacy hash) // Matches Go IAVL nodedb.go GetRoot() legacy handling if (isLegacy) { return value; } // Value from new format location could be: // 1. A reference to another node (starts with 's' prefix = 0x73) // 2. Anything else (should not happen in normal operation) // // References are detected by checking if first byte is NODE_KEY_PREFIX ('s' = 0x73). // If it's a reference, strip the prefix and return the nodeKey. // If it's NOT a reference, the root IS at the implicit location GetRootKey(version). // // Matches Go IAVL nodedb.go GetRoot() and isReferenceRoot() logic. const NODE_KEY_PREFIX_LENGTH = 1; // Check if value is a reference (starts with node key prefix 's') if (value[0] === NODE_KEY_PREFIX) { // It's a prefixed reference - strip the prefix to get nodeKey return value.slice(NODE_KEY_PREFIX_LENGTH); } // Not a reference - root node IS stored at the implicit root key // This handles edge cases and malformed data return getRootKey(version); } /** * Saves an empty root for a version. * * @param version - Version number */ async saveEmptyRoot(version: bigint): Promise { const rootKey = this.rootKey(version); await this.batch.set(rootKey, new Uint8Array(0)); } /** * Saves a root reference for a version. * Stores the prefixed nodeKey as the value, matching Go IAVL's SaveRoot. * * @param version - Version number * @param nodeKey - Node key of the root node (unprefixed) */ async saveRoot(version: bigint, nodeKey: Uint8Array): Promise { const rootKey = this.rootKey(version); // Store prefixed nodeKey, matching Go: nodeKeyFormat.Key(nk.GetKey()) const prefixedNodeKey = this.nodeKey(nodeKey); await this.batch.set(rootKey, prefixedNodeKey); } /** * Commits any pending batch operations to the database. * Writes all buffered operations and starts a new batch. * * If sync option is enabled, performs a synchronous write with fsync * to ensure data is flushed to disk (matching Go implementation). */ async commit(): Promise { // Write the current batch to database // Use sync write if enabled (ensures data is flushed to disk) if (this.opts.sync) { await this.batch.writeSync(); } else { await this.batch.write(); } // Create a new batch for subsequent operations this.batch = new AsyncBatchWithFlusher(this.db, this.opts.flushThreshold); } /** * Resets the latest version tracker. * Called after successfully saving a version. * If this is the first version (firstVersion is 0), also sets firstVersion. * * @param version - New latest version */ resetLatestVersion(version: bigint): void { this.latestVersion = version; // If this is the first version being saved, set firstVersion if (this.firstVersion === 0n) { this.firstVersion = version; } } /** * Sets the fast storage version in the batch. * Updates storage version metadata with fast storage version. * * @param version - Latest version for fast storage */ async setFastStorageVersionToBatch(version: bigint): Promise { // Get current storage version const parts = this.storageVersion.split("-"); const baseVersion = parts[0]; // Format: "1.1.0-{version}" const newVersion = `${baseVersion}-${version}`; // Save to metadata const versionKey = this.metadataKey(stringToBytes("version")); await this.batch.set(versionKey, stringToBytes(newVersion)); this.storageVersion = newVersion; } /** * Deletes a fast node from storage. * * @param key - Key to delete */ async deleteFastNode(key: Uint8Array): Promise { const dbKey = this.fastNodeKey(key); await this.batch.delete(dbKey); // Remove from cache if present const keyStr = Buffer.from(key).toString("hex"); this.fastNodeCache.remove(keyStr); } /** * Closes the database connection. */ async close(): Promise { await this.db.close(); } // ==================== Key Formatting Methods ==================== /** * Formats a node key for storage. * Format: 's' + nodeKey bytes (version + nonce) * * @param _nodeKey - The node key bytes * @returns Database key */ /** * Constructs a database key for a node * @internal */ nodeKey(_nodeKey: Uint8Array): Uint8Array { // For regular node keys, just add 's' prefix // Node keys are already formatted as const key = new Uint8Array(1 + _nodeKey.length); key[0] = NODE_KEY_PREFIX; key.set(_nodeKey, 1); return key; } /** * Formats a fast node key for storage. * Format: 'f' + key bytes * * @param _key - The key bytes * @returns Database key */ private fastNodeKey(_key: Uint8Array): Uint8Array { return fastKeyFormat.key(_key); } /** * Formats a metadata key for storage. * Format: 'm' + key bytes * * @param key - The metadata key bytes * @returns Database key */ private metadataKey(key: Uint8Array): Uint8Array { return metadataKeyFormat.key(key); } /** * Creates a root key for a given version. * Root keys are node keys with nonce = 1. * * @param version - Version number * @returns Database key for the root */ /** * Constructs a database key for a root at a given version * @internal */ rootKey(version: bigint): Uint8Array { return this.nodeKey(getRootKey(version)); } /** * Deletes a specific version from the database. * This removes the root reference and all nodes unique to this version. * * Uses traverseOrphans to identify and delete all nodes that existed in the * deleted version but don't exist in the next version (orphaned nodes). * * @param version - Version to delete * @throws Error if version doesn't exist or is the latest version */ async deleteVersion(version: bigint): Promise { // Check version exists const exists = await this.versionExists(version); if (!exists) { throw new Error(`version ${version} does not exist`); } // Cannot delete the latest version if (version === this.latestVersion) { throw new Error(`cannot delete latest version ${version}`); } // Traverse and delete all orphaned nodes // Orphans are nodes that exist in version but not in version+1 await this.traverseOrphans(version, version + 1n, async (orphan) => { try { const nodeKey = orphan.getNodeKey(); // Delete the node from storage await this.deleteFromPruning(this.nodeKey(nodeKey)); } catch (err) { // Skip nodes without valid keys if (err instanceof Error && err.message.includes("must have")) { return; } throw err; } }); // Delete the root reference for this version const rootKey = this.rootKey(version); await this.batch.delete(rootKey); } /** * Deletes all versions from firstVersion up to and including toVersion. * Updates firstVersion to toVersion + 1 after deletion. * * If asyncPruning is enabled, this queues the deletion for background processing. * Otherwise, performs synchronous deletion. * * Based on Go IAVL v1.3.5 nodedb.go DeleteVersionsTo (lines 653-663) * * @param toVersion - Delete all versions up to and including this (inclusive) * @throws Error if toVersion >= latestVersion or if versions have active readers */ async deleteVersionsTo(toVersion: bigint): Promise { // If async pruning is enabled, queue the request if (this.opts.asyncPruning) { this.pruneVersion = toVersion; return; } // Otherwise, perform synchronous deletion await this.deleteVersionsToSync(toVersion); } /** * Performs synchronous deletion of versions. * This is the actual deletion logic, used by both sync and async modes. * * @param toVersion - Delete all versions up to and including this (inclusive) * @throws Error if toVersion >= latestVersion or if versions have active readers */ private async deleteVersionsToSync(toVersion: bigint): Promise { const first = this.firstVersion; const latest = this.latestVersion; // Validate bounds if (toVersion >= latest) { throw new Error( `toVersion ${toVersion} must be less than latest version ${latest}`, ); } if (toVersion < first) { // Nothing to delete return; } // Delete each version from first to toVersion (inclusive) for (let v = first; v <= toVersion; v++) { try { await this.deleteVersion(v); } catch (err) { // If version doesn't exist, skip it (may have been deleted already) if (err instanceof Error && err.message.includes("does not exist")) { continue; } throw err; } } // Update first version to the next version after deleted ones this.firstVersion = toVersion + 1n; } /** * Deletes all versions from fromVersion upwards (including fromVersion). * Updates latestVersion to fromVersion-1 after deletion. * * @param fromVersion - Delete all versions from this onwards (inclusive) * @throws Error if versions have active readers */ async deleteVersionsFrom(fromVersion: bigint): Promise { const latest = this.latestVersion; // Validate bounds if (fromVersion > latest) { // Nothing to delete return; } // Delete all nodes in the version range [fromVersion, latest+1) // Node keys have format: 's' + version (8 bytes) + nonce (4 bytes) // We can safely delete all nodes in this range because: // 1. We're deleting future history // 2. Nodes can only reference nodes from same or earlier versions // 3. Earlier versions cannot reference nodes created in later versions // Create start key: 's' + fromVersion (8 bytes) const startKey = new Uint8Array(1 + 8); const startView = new DataView(startKey.buffer); startKey[0] = NODE_KEY_PREFIX; startView.setBigUint64(1, fromVersion, false); // big-endian // Create end key: 's' + (latest+1) (8 bytes) const endKey = new Uint8Array(1 + 8); const endView = new DataView(endKey.buffer); endKey[0] = NODE_KEY_PREFIX; endView.setBigUint64(1, latest + 1n, false); // big-endian // Delete all node keys in range const iter = await this.db.iterator(startKey, endKey); try { while (iter.valid()) { const key = iter.key(); await this.batch.delete(key); iter.next(); } } finally { iter.close(); } // Delete root keys for all versions in range for (let v = fromVersion; v <= latest; v++) { const rootKey = this.rootKey(v); try { await this.batch.delete(rootKey); } catch { // Ignore if root doesn't exist } } // Update latest version this.latestVersion = fromVersion - 1n; } /** * Resets the first version number. * Used internally after version deletion. * * @param version - New first version */ private resetFirstVersion(version: bigint): void { this.firstVersion = version; } /** * Creates a legacy orphan key. * Format: 'o' * * @param lastVersion - Last version this node existed in * @param firstVersion - First version this node existed in * @param hash - Node hash * @returns Orphan key bytes */ private legacyOrphanKey( lastVersion: bigint, firstVersion: bigint, hash: Uint8Array, ): Uint8Array { // Calculate total size: prefix (1) + lastVersion (8) + firstVersion (8) + hash const key = new Uint8Array(1 + 8 + 8 + hash.length); const view = new DataView(key.buffer); // Set prefix key[0] = LEGACY_ORPHAN_KEY_PREFIX; // Set lastVersion (big-endian) view.setBigUint64(1, lastVersion, false); // Set firstVersion (big-endian) view.setBigUint64(9, firstVersion, false); // Set hash key.set(hash, 17); return key; } /** * Creates a legacy node key (hash-based format). * Format: 'n' * * @param hash - Node hash (32 bytes) * @returns Legacy node key bytes */ private legacyNodeKey(hash: Uint8Array): Uint8Array { const key = new Uint8Array(1 + hash.length); key[0] = LEGACY_NODE_KEY_PREFIX; key.set(hash, 1); return key; } /** * Creates a legacy root key. * Format: 'r' * * @param version - Tree version * @returns Legacy root key bytes */ private legacyRootKey(version: bigint): Uint8Array { const key = new Uint8Array(1 + 8); const view = new DataView(key.buffer); key[0] = LEGACY_ROOT_KEY_PREFIX; view.setBigInt64(1, BigInt.asIntN(64, version), false); return key; } /** * Saves a node during pruning/cleanup operations. * This is used to track nodes that need to be deleted when cleaning up old versions. * * Note: In Go, this method handles commit synchronization. In our single-threaded * JS environment, we don't need that complexity. * * @param node - Node to save for pruning */ async saveNodeFromPruning(node: Node): Promise { // Encode and save the node const nodeKey = node.getNodeKey(); const nodeBytes = node.toBytes(); await this.batch.set(this.nodeKey(nodeKey), nodeBytes); } /** * Deletes a key during pruning/cleanup operations. * * Note: In Go, this method handles commit synchronization. In our single-threaded * JS environment, we don't need that complexity. * * @param key - Key to delete */ async deleteFromPruning(key: Uint8Array): Promise { await this.batch.delete(key); } /** * Traverses orphaned nodes between two versions. * * An orphaned node is one that exists in prevVersion but not in curVersion. * This is determined by comparing the tree structures using parallel iterators. * * The algorithm: * 1. Create iterators for both prevVersion and curVersion trees * 2. For each node in prevVersion tree: * a. Find matching "original" node in curVersion (node.version <= prevVersion) * b. If hashes match, both trees share this node - skip it * c. If no match or different hash, node is orphaned - call callback * * This is used during DeleteVersion to identify nodes that need cleanup. * * @param prevVersion - Previous version to compare from * @param curVersion - Current version to compare to * @param fn - Callback function for each orphaned node */ async traverseOrphans( prevVersion: bigint, curVersion: bigint, fn: (node: Node) => Promise, ): Promise { // Import NodeIterator here to avoid circular dependency const { NodeIterator, } = await import("./node-iterator.js"); // Get root keys for both versions const curKey = await this.getRoot(curVersion); const prevKey = await this.getRoot(prevVersion); // Create iterators const curIter = await NodeIterator.create(curKey, this); const prevIter = await NodeIterator.create(prevKey, this); // Track the current "original" node from curVersion tree // (original = node with version <= prevVersion) let orgNode: Node | null = null; // Iterate through all nodes in prevVersion tree while (prevIter.valid()) { // Find the next original node in curVersion tree // Original nodes are those that existed at or before prevVersion while (orgNode === null && curIter.valid()) { const node = curIter.getNode(); const nodeVersion = node.nodeKey?.version; if (nodeVersion !== undefined && nodeVersion <= prevVersion) { // This is an original node (existed in prevVersion) await curIter.next(true); // Skip its children (we found it) orgNode = node; } else { // This is a new node (created after prevVersion) await curIter.next(false); // Continue traversing } } const pNode = prevIter.getNode(); // Compare hashes to see if this node is orphaned if ( orgNode !== null && pNode.hash && orgNode.hash && this.hashesEqual(pNode.hash, orgNode.hash) ) { // Hashes match - this node exists in both versions // Skip the subtree (it's shared between versions) await prevIter.next(true); orgNode = null; } else { // Node is orphaned (doesn't exist in curVersion or has different hash) await fn(pNode); await prevIter.next(false); } } // Check for errors if (curIter.error()) { throw curIter.error()!; } if (prevIter.error()) { throw prevIter.error()!; } } /** * Helper to compare two hash arrays for equality. * * @param a - First hash * @param b - Second hash * @returns true if hashes are equal */ private hashesEqual(a: Uint8Array, b: Uint8Array): boolean { if (a.length !== b.length) { return false; } for (let i = 0; i < a.length; i++) { if (a[i] !== b[i]) { return false; } } return true; } /** * Helper method to get an empty ImmutableTree at a given version. * Used primarily for testing to create initial tree instances. * * @param version - Version number for the tree * @returns Promise resolving to empty ImmutableTree instance */ async getImmutableTree(version: bigint): Promise { return new ImmutableTree( null, this, version, this.opts.skipFastStorageUpgrade ?? false, ); } // ==================== Async Pruning Methods ==================== /** * Sets the committing flag to indicate that a commit is in progress. * This prevents the async pruning worker from interfering with the commit. * * Based on Go IAVL v1.3.5 nodedb.go SetCommitting (lines 275-284) */ setCommitting(): void { // Wait for any pending commit to complete if (this.commitCompletePromise) { // Drain the promise by resetting it this.commitCompletePromise = null; this.commitCompleteResolve = null; } // Set committing flag this._isCommitting = true; } /** * Unsets the committing flag to indicate that the commit is complete. * This signals the async pruning worker that it can continue. * * Based on Go IAVL v1.3.5 nodedb.go UnsetCommitting (lines 286-293) */ unsetCommitting(): void { // Clear committing flag this._isCommitting = false; // Signal commit complete if (this.commitCompleteResolve) { this.commitCompleteResolve(); } } /** * Returns true if a commit is currently in progress. * * Based on Go IAVL v1.3.5 nodedb.go IsCommitting (lines 295-299) */ isCommitting(): boolean { return this._isCommitting; } /** * Starts the async pruning worker. * The worker runs in the background and processes pruning requests. * * Based on Go IAVL v1.3.5 nodedb.go startPruning (lines 621-651) */ private startPruningWorker(): void { this.pruningAbortController = new AbortController(); const signal = this.pruningAbortController.signal; // Run the pruning loop asynchronously (async () => { while (!signal.aborted) { try { // Check if there's a version to prune const toVersion = this.pruneVersion; if (toVersion === 0n) { // No pruning needed, wait a bit await sleep(100, signal); continue; } // Wait for commit to complete if in progress if (this.isCommitting()) { await this.waitForCommitComplete(signal); } // Perform the pruning (bypassing async mode) await this.deleteVersionsToSync(toVersion); // Commit the batch after pruning await this.commit(); // Clear the prune version if it hasn't been updated if (this.pruneVersion <= toVersion) { this.pruneVersion = 0n; } } catch (err) { // Check if error is due to abort if (signal.aborted) { break; } // Log error and wait before retrying this.logger?.error("Error during async pruning", { error: err, }); await sleep(1000, signal); } } })().catch((err) => { // Only log if not aborted if (!signal.aborted) { this.logger?.error("Pruning worker crashed", { error: err, }); } }); } /** * Waits for the current commit to complete. * * @param signal - Abort signal to cancel the wait */ private async waitForCommitComplete(signal: AbortSignal): Promise { if (!this.commitCompletePromise) { this.commitCompletePromise = new Promise((resolve) => { this.commitCompleteResolve = resolve; }); } // Race between commit complete and abort signal await Promise.race([ this.commitCompletePromise, new Promise((_, reject) => { signal.addEventListener("abort", () => reject(new Error("Aborted"))); }), ]); } /** * Stops the async pruning worker. * Should be called when closing the database. */ stopPruningWorker(): void { if (this.pruningAbortController) { this.pruningAbortController.abort(); this.pruningAbortController = null; } } // ==================== Statistics Methods ==================== /** * Gets the current statistics for this NodeDB. * Returns undefined if statistics tracking is not enabled. * * Based on Go IAVL v1.3.5 options.go Statistics getters * * @returns Statistics object or undefined */ getStatistics(): Statistics | undefined { return this.opts.statistics; } // ==================== Legacy Migration Methods ==================== /** * Gets all legacy nodes (hash-based format) from the database. * Used for migration and verification purposes. * * @returns Array of legacy nodes */ async legacyNodes(): Promise { const nodes: Node[] = []; const prefix = new Uint8Array([LEGACY_NODE_KEY_PREFIX]); const iter = await this.db.iterator(prefix, new Uint8Array([LEGACY_NODE_KEY_PREFIX + 1])); try { while (iter.valid()) { const key = iter.key(); const value = iter.value(); // Skip the prefix byte to get the hash const hash = key.slice(1); // Import Node.fromBytes to parse legacy nodes const { Node: NodeClass, } = await import("../node.js"); const node = NodeClass.fromBytes(hash, value); nodes.push(node); iter.next(); } } finally { iter.close(); } return nodes; } /** * Traverses state changes between a range of versions. * For each version in the range, it extracts the changes from the previous version * and calls the callback function with the version number and the ChangeSet. * * Based on Go IAVL v1.3.5 nodedb.go traverseStateChanges * * @param startVersion - First version to extract changes for * @param endVersion - Last version to extract changes for * @param fn - Callback function to receive changes * @returns Promise that resolves when traversal is complete */ async traverseStateChanges( startVersion: bigint, endVersion: bigint, fn: (version: bigint, changeSet: ChangeSet) => Promise, ): Promise { // Get first version const firstVersion = this.getFirstVersion(); if (startVersion < firstVersion) { startVersion = firstVersion; } // Get latest version const latestVersion = this.latestVersion; if (endVersion > latestVersion) { endVersion = latestVersion; } // Get previous version root (may not exist) let prevVersion = startVersion - 1n; let prevRoot: Uint8Array | null = null; if (prevVersion >= 0n) { try { prevRoot = await this.getRoot(prevVersion); } catch { // Previous version doesn't exist, that's ok prevRoot = null; } } // Iterate through each version for (let version = startVersion; version <= endVersion; version++) { const root = await this.getRoot(version); // Collect changes for this version const pairs: KVPair[] = []; const receiveKVPair = async (pair: KVPair): Promise => { pairs.push(pair); }; // Extract state changes between prevRoot and current root if (root) { await this.extractStateChanges(prevVersion, prevRoot, root, receiveKVPair); } // Call callback with the changeset const changeSet: ChangeSet = { pairs, }; const stop = await fn(version, changeSet); if (stop === true) { return; } // Move to next version prevVersion = version; prevRoot = root; } } /** * Extracts state changes between two tree versions. * This implements the diff algorithm from Go IAVL v1.3.5 diff.go * * The algorithm traverses both trees simultaneously: * 1. Advances through the current tree until reaching a shared node * 2. Records new leaf nodes during traversal * 3. Traverses the previous tree to find orphaned nodes * 4. Compares orphaned and new nodes to generate KVPair stream * * @param prevVersion - Previous version number * @param prevRoot - Root node key of previous version (null if no previous version) * @param root - Root node key of current version * @param receiver - Callback to receive KVPair changes * @returns Promise that resolves when extraction is complete */ private async extractStateChanges( prevVersion: bigint, prevRoot: Uint8Array | null, root: Uint8Array, receiver: (pair: KVPair) => Promise, ): Promise { const { NodeIterator, } = await import("./node-iterator.js"); // Create iterators for both trees const curIter = await NodeIterator.create(root, this); const prevIter = await NodeIterator.create(prevRoot, this); // Current shared node between two versions let sharedNode: Node | null = null; // New leaf nodes found during traversal to shared node const newLeaves: Node[] = []; /** * Consumes remaining newLeaves nodes and produces insertion KVPairs */ const consumeNewLeaves = async (): Promise => { for (const node of newLeaves) { if (!node.key || !node.value) { throw new Error("Leaf node must have key and value"); } await receiver({ delete: false, key: node.key, value: node.value, }); } newLeaves.length = 0; }; /** * Advances curIter until the next shared node. * Records new leaf nodes during traversal. * Sets sharedNode to null if current version is exhausted. */ const advanceSharedNode = async (): Promise => { await consumeNewLeaves(); sharedNode = null; while (curIter.valid()) { const node = curIter.getNode(); const shared = (node.nodeKey?.version ?? 0n) <= prevVersion; await curIter.next(shared); if (shared) { sharedNode = node; break; } else if (node.isLeaf()) { newLeaves.push(node); } } }; // Initialize by finding first shared node await advanceSharedNode(); /** * Processes an orphaned leaf node from the previous version. * Compares with newLeaves to produce KVPair changes. */ const addOrphanedLeaf = async (orphaned: Node): Promise => { if (!orphaned.key) { throw new Error("Orphaned leaf node must have key"); } while (newLeaves.length > 0) { const newLeaf = newLeaves[0]; if (!newLeaf.key || !newLeaf.value) { throw new Error("New leaf node must have key and value"); } // Compare keys const cmp = Buffer.compare( Buffer.from(orphaned.key), Buffer.from(newLeaf.key), ); if (cmp > 0) { // New key is smaller - it's an insertion newLeaves.shift(); await receiver({ delete: false, key: newLeaf.key, value: newLeaf.value, }); continue; } else if (cmp < 0) { // Orphaned key is smaller - it's a deletion await receiver({ delete: true, key: orphaned.key, value: new Uint8Array(0), }); return; } else { // Keys are equal - it's an update newLeaves.shift(); await receiver({ delete: false, key: newLeaf.key, value: newLeaf.value, }); return; } } // No more new leaves - this is a deletion await receiver({ delete: true, key: orphaned.key, value: new Uint8Array(0), }); }; /** * Traverse previous tree to find orphaned nodes */ while (prevIter.valid()) { const node = prevIter.getNode(); // Check if this node is shared let shared = false; if (sharedNode) { // TypeScript has control-flow narrowing issues here, so we explicitly type the variable const currentShared: Node = sharedNode; // Check for reference equality shared = (node === currentShared); // If not the same reference, check hash equality if (!shared && node.hash !== null && currentShared.hash !== null) { shared = Buffer.compare(Buffer.from(node.hash), Buffer.from(currentShared.hash)) === 0; } } // Skip subtree of shared nodes await prevIter.next(shared); if (shared) { // Advance to next shared node in current tree await advanceSharedNode(); } else if (node.isLeaf()) { // Process orphaned leaf await addOrphanedLeaf(node); } } // Consume any remaining new leaves await consumeNewLeaves(); // Check for errors if (curIter.error()) { throw curIter.error(); } if (prevIter.error()) { throw prevIter.error(); } } /** * Traverse all keys with a certain prefix. * Calls the provided function for each key-value pair matching the prefix. * * Based on Go IAVL v1.3.5 nodedb.go traversePrefix (lines 1000-1014) * * @param prefix - The key prefix to search for * @param fn - Callback function receiving key and value for each match * @throws Error if callback returns error or iterator fails */ async traversePrefix( prefix: Uint8Array, fn: (key: Uint8Array, value: Uint8Array) => Promise, ): Promise { const itr = await this.getPrefixIterator(prefix); try { while (itr.valid()) { await fn(itr.key(), itr.value()); itr.next(); } } finally { itr.close(); } } /** * Get the iterator for a given prefix. * Creates a database iterator that yields all keys starting with the prefix. * * Based on Go IAVL v1.3.5 nodedb.go getPrefixIterator (lines 1017-1028) * * @param prefix - The key prefix to iterate over * @returns Promise resolving to database iterator over keys with the prefix * @internal */ getPrefixIterator(prefix: Uint8Array): Promise { let start: Uint8Array | undefined; let end: Uint8Array | undefined; if (prefix.length === 0) { // Empty prefix means iterate everything start = undefined; end = undefined; } else { // Copy the prefix for start start = new Uint8Array(prefix); // Increment the prefix for end (exclusive upper bound) end = incrementBytes(prefix); } return this.db.iterator(start, end); } /** * Increments the number of active readers for a version. * This prevents the version from being deleted while readers are active. * * Based on Go IAVL v1.3.5 nodedb.go incrVersionReaders (lines 1072-1076) * * Note: JavaScript is single-threaded, so no mutex is needed for this operation. * The Go implementation uses a mutex because Go is multi-threaded. * * @param version - The version to increment readers for */ incrVersionReaders(version: bigint): void { const count = this.versionReaders.get(version) ?? 0; this.versionReaders.set(version, count + 1); } /** * Decrements the number of active readers for a version. * When the count reaches zero, the version can be safely deleted. * * Based on Go IAVL v1.3.5 nodedb.go decrVersionReaders (lines 1078-1087) * * Note: JavaScript is single-threaded, so no mutex is needed for this operation. * The Go implementation uses a mutex because Go is multi-threaded. * * @param version - The version to decrement readers for */ decrVersionReaders(version: bigint): void { const count = this.versionReaders.get(version) ?? 0; if (count > 0) { const newCount = count - 1; if (newCount === 0) { // Remove from map when count reaches zero (same as Go's delete) this.versionReaders.delete(version); } else { this.versionReaders.set(version, newCount); } } } /** * Checks if a version has any active readers. * Versions with active readers should not be deleted. * * @param version - The version to check * @returns True if the version has active readers */ hasVersionReaders(version: bigint): boolean { return (this.versionReaders.get(version) ?? 0) > 0; } /** * Returns a string representation of the NodeDB for debugging purposes. * Shows metadata about the database including version range, storage version, * and cache statistics. * * Corresponds to Go's nodeDB.String() but simplified version. * The full Go implementation dumps all nodes which requires traverseNodes(). * This simplified version provides useful debug information without the full dump. * * @returns String representation of the database state */ toString(): string { const lines: string[] = []; lines.push("----- NodeDB State -----"); lines.push(`Storage Version: ${this.storageVersion}`); lines.push(`Latest Version: ${this.latestVersion}`); lines.push(`First Version: ${this.firstVersion}`); lines.push(`Version Range: [${this.firstVersion}, ${this.latestVersion}]`); lines.push(`Has Fast Storage: ${this.hasUpgradedToFastStorage()}`); // Cache stats const stats = this.opts.statistics; if (stats) { lines.push(""); lines.push("Cache Statistics:"); lines.push(` Node Cache Hits: ${stats.cacheHitCnt}`); lines.push(` Node Cache Misses: ${stats.cacheMissCnt}`); lines.push(` Fast Cache Hits: ${stats.fastCacheHitCnt}`); lines.push(` Fast Cache Misses: ${stats.fastCacheMissCnt}`); const totalNodeAccess = stats.cacheHitCnt + stats.cacheMissCnt; const totalFastAccess = stats.fastCacheHitCnt + stats.fastCacheMissCnt; if (totalNodeAccess > 0) { const nodeHitRate = ((stats.cacheHitCnt / totalNodeAccess) * 100).toFixed(2); lines.push(` Node Cache Hit Rate: ${nodeHitRate}%`); } if (totalFastAccess > 0) { const fastHitRate = ((stats.fastCacheHitCnt / totalFastAccess) * 100).toFixed(2); lines.push(` Fast Cache Hit Rate: ${fastHitRate}%`); } } lines.push("-----------------------"); return lines.join("\n"); } } // ==================== Helper Functions ==================== /** * Increments a byte array by one, treating it as a big-endian number. * Returns undefined if the increment would overflow (all bytes are 0xFF). * This is used to create an exclusive upper bound for prefix iteration. * * Based on Go IAVL v1.3.5 internal/bytes/bytes.go CpIncr * * @param bz - The byte array to increment * @returns Incremented copy, or undefined on overflow */ function incrementBytes(bz: Uint8Array): Uint8Array | undefined { if (bz.length === 0) { throw new Error("incrementBytes expects non-zero length"); } // Create a copy const ret = new Uint8Array(bz); // Increment from right to left (big-endian) for (let i = ret.length - 1; i >= 0; i--) { if (ret[i] < 0xFF) { ret[i]++; return ret; } // Set to 0 and continue carry ret[i] = 0x00; if (i === 0) { // Overflow - all bytes were 0xFF return undefined; } } return ret; } /** * Converts a string to Uint8Array. * * @param str - The string to convert * @returns Uint8Array representation */ function stringToBytes(str: string): Uint8Array { return new TextEncoder().encode(str); } /** * Converts a Uint8Array to string. * * @param bytes - The bytes to convert * @returns String representation */ function bytesToString(bytes: Uint8Array): string { return new TextDecoder().decode(bytes); } /** * Sleeps for the specified duration or until the signal is aborted. * * @param ms - Duration in milliseconds * @param signal - Abort signal to cancel the sleep */ function sleep(ms: number, signal: AbortSignal): Promise { return new Promise((resolve, reject) => { if (signal.aborted) { reject(new Error("Aborted")); return; } const timeout = setTimeout(() => { signal.removeEventListener("abort", onAbort); resolve(); }, ms); const onAbort = () => { clearTimeout(timeout); reject(new Error("Aborted")); }; signal.addEventListener("abort", onAbort); }); }