/** * FastIterator is an iterator for ImmutableTree that iterates over the latest state * via fast nodes, taking advantage of keys being located in sequence in the underlying database. * * Corresponds to Go's FastIterator in fast_iterator.go (lines 1-136) */ import type { Iterator, } from "../db/types.js"; import { FastNode, } from "../storage/fast-node.js"; import type { NodeDB, } from "../storage/node-db.js"; /** * Error thrown when FastIterator is created with null NodeDB */ export class ErrFastIteratorNilNdbGiven extends Error { constructor() { super("fast iterator must be created with a nodedb but it was nil"); this.name = "ErrFastIteratorNilNdbGiven"; } } /** * FastIterator implements iteration over fast nodes in a database. * It provides O(1) sequential access to keys in the latest tree version. * * Based on Go IAVL v1.3.5 fast_iterator.go (lines 13-136) */ export class FastIterator { private start: Uint8Array | null; private end: Uint8Array | null; private valid: boolean; private ascending: boolean; private err: Error | null; private ndb: NodeDB | null; private nextFastNode: FastNode | null; private fastIterator: Iterator | null; private fastIteratorPromise: Promise | null; /** * Creates a new FastIterator. * * Note: The constructor does NOT initialize the iterator. Use the static create() method * for proper async initialization, or manually call nextAsync() after construction. * * @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 * @param ndb - NodeDB to iterate over * @private Use FastIterator.create() instead */ private constructor( start: Uint8Array | null, end: Uint8Array | null, ascending: boolean, ndb: NodeDB | null, ) { this.start = start; this.end = end; this.err = null; this.ascending = ascending; this.ndb = ndb; this.nextFastNode = null; this.fastIterator = null; this.fastIteratorPromise = null; this.valid = false; // Note: Not calling next() here - will be called by create() factory method } /** * Creates and initializes a new FastIterator. * * This is the recommended way to create a FastIterator as it properly handles * async database initialization. * * @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 * @param ndb - NodeDB to iterate over * @returns Promise resolving to initialized FastIterator */ static async create( start: Uint8Array | null, end: Uint8Array | null, ascending: boolean, ndb: NodeDB | null, ): Promise { const iter = new FastIterator(start, end, ascending, ndb); await iter.nextAsync(); return iter; } /** * Domain returns the start and end keys of the iterator. * Maps the underlying nodedb iterator domain to the 'logical' keys involved. * * Based on Go IAVL fast_iterator.go lines 49-73 * * @returns Tuple of [start, end] keys */ domain(): [Uint8Array | null, Uint8Array | null] { // Our base Iterator interface doesn't have domain(), so we return our original bounds return [this.start, this.end]; } /** * Valid returns true if the iterator is positioned at a valid element. * * Based on Go IAVL fast_iterator.go lines 75-78 * * @returns True if iterator has a valid current element */ isValid(): boolean { return this.fastIterator !== null && this.fastIterator.valid() && this.valid; } /** * Key returns the key of the current element. * * Based on Go IAVL fast_iterator.go lines 80-86 * * @returns Current key, or null if invalid */ key(): Uint8Array | null { if (this.valid && this.nextFastNode !== null) { return this.nextFastNode.key; } return null; } /** * Value returns the value of the current element. * * Based on Go IAVL fast_iterator.go lines 88-94 * * @returns Current value, or null if invalid */ value(): Uint8Array | null { if (this.valid && this.nextFastNode !== null) { return this.nextFastNode.value; } return null; } /** * Next advances the iterator to the next element. * * IMPORTANT: In async database implementations (CrossKvDB), the first call to next() * will initialize the underlying iterator asynchronously. The iterator won't be valid * until the promise resolves. Call nextAsync() for proper async handling, or ensure * the iterator is pre-initialized. * * Based on Go IAVL fast_iterator.go lines 96-120 */ next(): void { if (this.ndb === null) { this.err = new ErrFastIteratorNilNdbGiven(); this.valid = false; return; } if (this.fastIterator === null && this.fastIteratorPromise === null) { // Initialize the fast iterator asynchronously this.fastIteratorPromise = this.ndb.getFastIterator( this.start, this.end, this.ascending, ); // Mark as not valid until promise resolves this.valid = false; // Resolve the promise and update state // Note: This is fire-and-forget, caller must check valid() repeatedly or use nextAsync() void this.fastIteratorPromise.then((iter) => { this.fastIterator = iter; this.fastIteratorPromise = null; this.updateState(); }).catch((err) => { this.err = err instanceof Error ? err : new Error(String(err)); this.valid = false; this.fastIteratorPromise = null; }); return; } if (this.fastIteratorPromise !== null) { // Still waiting for initialization - not valid yet this.valid = false; return; } // fastIterator is initialized, advance it if (this.fastIterator) { this.fastIterator.next(); this.updateState(); } } /** * Async version of next() that properly waits for iterator initialization. * Use this for async database implementations. */ async nextAsync(): Promise { if (this.ndb === null) { this.err = new ErrFastIteratorNilNdbGiven(); this.valid = false; return; } if (this.fastIterator === null) { this.fastIterator = await this.ndb.getFastIterator( this.start, this.end, this.ascending, ); } else { this.fastIterator.next(); } this.updateState(); } /** * Updates the iterator state based on the current fast iterator position. * @private */ private updateState(): void { if (!this.fastIterator) { this.valid = false; return; } this.valid = this.fastIterator.valid(); if (this.valid) { try { // Key from iterator has format: 'f' + actual key // Value is the serialized fast node const iterKey = this.fastIterator.key(); const iterValue = this.fastIterator.value(); if (iterKey === null || iterValue === null) { throw new Error("Iterator returned null key or value"); } // Strip the 'f' prefix from the key const actualKey = iterKey.slice(1); // Deserialize the fast node this.nextFastNode = FastNode.fromBytes(actualKey, iterValue); } catch (err) { this.err = err instanceof Error ? err : new Error(String(err)); this.valid = false; } } } /** * Close releases resources held by the iterator. * * Based on Go IAVL fast_iterator.go lines 122-130 */ close(): void { if (this.fastIterator !== null) { this.fastIterator.close(); } this.valid = false; this.fastIterator = null; } /** * Error returns any error that occurred during iteration. * * Based on Go IAVL fast_iterator.go lines 132-135 * * @returns Error if any, null otherwise */ error(): Error | null { return this.err; } }