import { ChangeSet } from "../generated/changeset.cjs"; import { Options, Statistics } from "../types/options.cjs"; import { Node, NodeGetter } from "../node.cjs"; import { ImmutableTree } from "../immutable-tree.cjs"; import { Database, Iterator } from "../db/types.cjs"; import { FastNode } from "./fast-node.cjs"; import { Logger } from "winston"; //#region src/storage/node-db.d.ts /** * NodeDB manages persistent storage of IAVL nodes. * Implements the NodeGetter interface for node retrieval. */ declare 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; /** Cache for regular tree nodes */ private readonly nodeCache; /** Cache for fast storage nodes */ private readonly fastNodeCache; /** Configuration options */ private readonly opts; /** Storage version string */ private storageVersion; /** First version stored in this DB */ private firstVersion; /** Latest version stored in this DB */ private latestVersion; /** Latest version in legacy format (hash-based keys), 0 if none */ private legacyLatestVersion; /** Optional logger for diagnostics */ private readonly logger; /** Version to prune up to (for async pruning) */ private pruneVersion; /** Flag indicating if NodeDB is in the middle of committing */ private _isCommitting; /** Resolve function for commit completion promise */ private commitCompleteResolve; /** Promise that resolves when commit is complete */ private commitCompletePromise; /** Abort controller for async pruning worker */ private pruningAbortController; /** Map tracking number of active readers per version */ private readonly versionReaders; /** * 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); /** * Asynchronously initializes the NodeDB by loading storage version from database. * Should be called after construction. * * @returns Promise that resolves when initialization is complete */ initialize(): Promise; /** * 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 */ getNode(nodeKey: Uint8Array): Promise; /** * Saves a node to the database. * * @param node - The node to save */ saveNode(node: Node): Promise; /** * Saves a fast node to the database. * * @param fastNode - The fast node to save */ saveFastNode(fastNode: FastNode): Promise; /** * Gets a fast node from cache or database. * * @param key - The key to look up * @returns The fast node, or null if not found */ getFastNode(key: Uint8Array): Promise; /** * 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; /** * Returns whether fast storage has been enabled. * * @returns true if storage version >= 1.1.0 (fast storage) */ hasUpgradedToFastStorage(): boolean; /** * Gets the storage version string. * * @returns Storage version */ getStorageVersion(): string; /** * Gets the first version stored in this database. * * @returns First version number */ getFirstVersion(): bigint; /** * Gets the latest version stored in this database. * * @returns Latest version number */ getLatestVersion(): bigint; /** * 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 */ getVersions(): Promise; /** * 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 */ getLegacyLatestVersion(): Promise; /** * Sets the cached legacy latest version. * * @param version - Version to set */ private resetLegacyLatestVersion; /** * Gets the configuration options for this NodeDB. * * @returns Options object */ getOptions(): Options; /** * Checks if a version exists in the database. * * @param version - Version number to check * @returns True if version exists */ versionExists(version: bigint): Promise; /** * 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 */ getRoot(version: bigint): Promise; /** * Saves an empty root for a version. * * @param version - Version number */ saveEmptyRoot(version: bigint): Promise; /** * 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) */ saveRoot(version: bigint, nodeKey: Uint8Array): Promise; /** * 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). */ commit(): Promise; /** * 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; /** * Sets the fast storage version in the batch. * Updates storage version metadata with fast storage version. * * @param version - Latest version for fast storage */ setFastStorageVersionToBatch(version: bigint): Promise; /** * Deletes a fast node from storage. * * @param key - Key to delete */ deleteFastNode(key: Uint8Array): Promise; /** * Closes the database connection. */ close(): Promise; /** * 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; /** * Formats a fast node key for storage. * Format: 'f' + key bytes * * @param _key - The key bytes * @returns Database key */ private fastNodeKey; /** * Formats a metadata key for storage. * Format: 'm' + key bytes * * @param key - The metadata key bytes * @returns Database key */ private metadataKey; /** * 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; /** * 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 */ deleteVersion(version: bigint): Promise; /** * 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 */ deleteVersionsTo(toVersion: bigint): Promise; /** * 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 deleteVersionsToSync; /** * 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 */ deleteVersionsFrom(fromVersion: bigint): Promise; /** * Resets the first version number. * Used internally after version deletion. * * @param version - New first version */ private resetFirstVersion; /** * 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; /** * Creates a legacy node key (hash-based format). * Format: 'n' * * @param hash - Node hash (32 bytes) * @returns Legacy node key bytes */ private legacyNodeKey; /** * Creates a legacy root key. * Format: 'r' * * @param version - Tree version * @returns Legacy root key bytes */ private legacyRootKey; /** * 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 */ saveNodeFromPruning(node: Node): Promise; /** * 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 */ deleteFromPruning(key: Uint8Array): Promise; /** * 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 */ traverseOrphans(prevVersion: bigint, curVersion: bigint, fn: (node: Node) => Promise): Promise; /** * Helper to compare two hash arrays for equality. * * @param a - First hash * @param b - Second hash * @returns true if hashes are equal */ private hashesEqual; /** * 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 */ getImmutableTree(version: bigint): Promise; /** * 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; /** * 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; /** * Returns true if a commit is currently in progress. * * Based on Go IAVL v1.3.5 nodedb.go IsCommitting (lines 295-299) */ isCommitting(): boolean; /** * 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; /** * Waits for the current commit to complete. * * @param signal - Abort signal to cancel the wait */ private waitForCommitComplete; /** * Stops the async pruning worker. * Should be called when closing the database. */ stopPruningWorker(): void; /** * 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; /** * Gets all legacy nodes (hash-based format) from the database. * Used for migration and verification purposes. * * @returns Array of legacy nodes */ legacyNodes(): Promise; /** * 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 */ traverseStateChanges(startVersion: bigint, endVersion: bigint, fn: (version: bigint, changeSet: ChangeSet) => Promise): Promise; /** * 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 extractStateChanges; /** * 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 */ traversePrefix(prefix: Uint8Array, fn: (key: Uint8Array, value: Uint8Array) => Promise): Promise; /** * 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; /** * 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; /** * 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; /** * 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; /** * 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; } //#endregion export { NodeDB }; //# sourceMappingURL=node-db.d.cts.map