import type { ExportNode, } from "../export/types.js"; import type { MutableTree, } from "../mutable-tree.js"; import { Node, } from "../node.js"; import { NodeKey, } from "../node-key.js"; /** * Maximum batch size before flushing to database * Based on Go IAVL import.go line 12 */ const MAX_BATCH_SIZE = 10000; /** * Error thrown when calling methods on a closed importer */ export class ErrNoImport extends Error { constructor() { super("no import in progress"); this.name = "ErrNoImport"; } } /** * Importer imports data into an empty MutableTree. * It is created by MutableTree.import(). Users must call close() when done. * * ExportNodes must be imported in the order returned by Exporter, * i.e. depth-first post-order (LRN). * * Importer is not concurrency-safe, it is the caller's responsibility to ensure * the tree is not modified while performing an import. * * Based on Go IAVL import.go lines 17-34. */ export class Importer { private tree: MutableTree | null; private version: bigint; private batchSize: number = 0; private stack: Node[] = []; private nonces: number[] = []; /** * Creates a new Importer for an empty MutableTree. * * @param tree - The MutableTree to import into (must be empty) * @param version - The version to import (must match exported version) * @throws Error if version is negative, tree is not empty, or database has existing versions * * Based on Go IAVL import.go lines 36-58. */ constructor(tree: MutableTree, version: bigint) { if (version < 0n) { throw new Error("imported version cannot be negative"); } const latestVersion = tree.getVersion(); if (latestVersion > 0n) { throw new Error(`found database at version ${latestVersion}, must be 0`); } if (tree.getSize() > 0n) { throw new Error("tree must be empty"); } this.tree = tree; this.version = version; this.stack = []; // Initialize nonces array with size version+1 this.nonces = new Array(Number(version) + 1).fill(0); } /** * Writes a node to the database. * Handles batching and flushing when batch size exceeds MAX_BATCH_SIZE. * * Based on Go IAVL import.go lines 60-104. */ private async writeNode(node: Node): Promise { if (!this.tree) { throw new ErrNoImport(); } // Hash the node node.computeHash(node.nodeKey!.version); // Validate node structure const validationError = node.validate(); if (validationError) { throw new Error(`Node validation failed: ${validationError}`); } // Serialize node const bytes = node.toBytes(); // Write to database const ndb = this.tree.getNodeDB(); const nodeKeyBytes = node.nodeKey!.toBytes(); const dbKey = ndb.nodeKey(nodeKeyBytes); await ndb.db.set(dbKey, bytes); this.batchSize++; // Flush if batch size exceeded (in a real implementation we'd batch these) if (this.batchSize >= MAX_BATCH_SIZE) { // In TypeScript we don't have async batch commits like Go // The database handles this internally this.batchSize = 0; } } /** * Adds an ExportNode to the import. * ExportNodes must be added in the order returned by Exporter (post-order LRN). * Nodes are periodically flushed to the database, but the imported version * is not visible until commit() is called. * * Based on Go IAVL import.go lines 120-186. * * @param exportNode - The exported node to add * @throws Error if importer is closed, node is nil, or version is invalid */ async add(exportNode: ExportNode): Promise { if (!this.tree) { throw new ErrNoImport(); } if (!exportNode) { throw new Error("node cannot be nil"); } if (exportNode.version > this.version) { throw new Error( `node version ${exportNode.version} can't be greater than import version ${this.version}`, ); } // Create node from export data const node = new Node(); node.key = exportNode.key; node.value = exportNode.value; node.subtreeHeight = exportNode.height; // Note: Branch nodes will have their value cleared below when children are attached // Build tree from bottom-left up using a stack. // The stack stores unresolved left children while constructing right children. // When all children are built, the parent can be constructed and resolved // children can be discarded from the stack. const stackSize = this.stack.length; if (node.subtreeHeight === 0) { // Leaf node node.size = 1n; } else if ( stackSize >= 2 && this.stack[stackSize - 1].subtreeHeight < node.subtreeHeight && this.stack[stackSize - 2].subtreeHeight < node.subtreeHeight ) { // Branch node: both children are on stack const leftNode = this.stack[stackSize - 2]; const rightNode = this.stack[stackSize - 1]; node.leftNode = leftNode; node.rightNode = rightNode; node.leftNodeKey = leftNode.nodeKey!.toBytes(); node.rightNodeKey = rightNode.nodeKey!.toBytes(); node.size = leftNode.size + rightNode.size; node.value = null; // Branch nodes have no value // Write children to database and remove from stack await this.writeNode(leftNode); await this.writeNode(rightNode); this.stack = this.stack.slice(0, stackSize - 2); // Remove recursive references to avoid memory leaks leftNode.leftNode = null; leftNode.rightNode = null; rightNode.leftNode = null; rightNode.rightNode = null; } // Assign node key with version and nonce const versionIdx = Number(exportNode.version); this.nonces[versionIdx]++; node.nodeKey = new NodeKey( exportNode.version, // Nonce is 1-indexed, but start at 2 since root has nonce of 1 this.nonces[versionIdx] + 1, ); // Push node onto stack this.stack.push(node); } /** * Finalizes the import by flushing outstanding nodes to the database, * making the version visible, and updating tree metadata. * Can only be called once, and calls close() internally. * * Based on Go IAVL import.go lines 188-229. * * @throws Error if importer is closed or stack has invalid state */ async commit(): Promise { if (!this.tree) { throw new ErrNoImport(); } const ndb = this.tree.getNodeDB(); const stackSize = this.stack.length; switch (stackSize) { case 0: { // Empty tree: save empty root const rootKey = ndb.rootKey(this.version); await ndb.db.set(rootKey, new Uint8Array(0)); break; } case 1: { // Single node (root) const root = this.stack[0]; // Root always has nonce 1 - create new NodeKey root.nodeKey = new NodeKey(root.nodeKey!.version, 1); await this.writeNode(root); // Save root reference only if root version < import version // When root.version == import.version with nonce=1, the root is implicit // (getRoot will automatically return getRootKey(version) as the nodeKey) if (root.nodeKey!.version < this.version) { const rootKey = ndb.rootKey(this.version); const nodeKeyBytes = root.nodeKey!.toBytes(); // IMPORTANT: Must save the PREFIXED nodeKey (13 bytes), not raw nodeKey (12 bytes) // This matches Go: i.batch.Set(nodeKey(GetRootKey(version)), nodeKey(stack[0].nodeKey.GetKey())) const prefixedNodeKey = ndb.nodeKey(nodeKeyBytes); await ndb.db.set(rootKey, prefixedNodeKey); } break; } default: throw new Error( `invalid node structure, found stack size ${stackSize} when committing`, ); } // Update tree metadata ndb.resetLatestVersion(this.version); // Load the imported version await this.tree.loadVersion(this.version); // Cleanup this.close(); } /** * Frees all resources. Safe to call multiple times. * Uncommitted nodes may already have been flushed to the database, * but will not be visible. * * Based on Go IAVL import.go lines 106-118. */ close(): void { this.tree = null; this.stack = []; this.batchSize = 0; } }