/** * Change tracking functionality for MutableTree. * Tracks all changes (sets and deletes) made since the last SaveVersion. * * This is useful for: * - State synchronization between nodes * - Audit trails and debugging * - Replaying changes on other trees * - Understanding what changed in a specific version */ import { ChangeSet as ChangeSetCodec, } from "./generated/changeset.js"; import type { ChangeSet, KVPair, } from "./types/index.js"; import { toHex, } from "./utils/bytes.js"; /** * Tracks changes made to a tree since the last commit. * Thread-safe within the Node.js single-threaded context. */ export class ChangeTracker { /** * Map of key (hex string) to change record. * Using hex string as key for efficient lookups. */ private changes: Map = new Map(); /** * Whether change tracking is enabled. * Can be disabled for performance when not needed. */ private enabled: boolean = true; /** * Maximum number of changes to track. * Prevents unbounded memory growth. */ private maxChanges: number = 100000; constructor(enabled: boolean = true, maxChanges: number = 100000) { this.enabled = enabled; this.maxChanges = maxChanges; } /** * Enable or disable change tracking. */ setEnabled(enabled: boolean): void { this.enabled = enabled; if (!enabled) { this.clear(); } } /** * Check if change tracking is enabled. */ isEnabled(): boolean { return this.enabled; } /** * Record a set operation. * * @param key - The key being set * @param value - The new value */ recordSet(key: Uint8Array, value: Uint8Array): void { if (!this.enabled) return; const hexKey = toHex(key); // Check if we're updating an existing key or adding a new one const isUpdate = this.changes.has(hexKey); if (!isUpdate && this.changes.size >= this.maxChanges) { // Log warning but continue - in production we don't want to fail console.warn(`ChangeTracker: Maximum changes limit (${this.maxChanges}) reached`); return; } this.changes.set(hexKey, { delete: false, key: new Uint8Array(key), // Copy to avoid reference issues value: new Uint8Array(value), // Copy to avoid reference issues }); } /** * Record a delete operation. * * @param key - The key being deleted * @param previousValue - The value that was deleted (optional, for audit purposes) */ recordDelete(key: Uint8Array, previousValue?: Uint8Array): void { if (!this.enabled) return; const hexKey = toHex(key); // Check if we're updating an existing key or adding a new one const isUpdate = this.changes.has(hexKey); if (!isUpdate && this.changes.size >= this.maxChanges) { console.warn(`ChangeTracker: Maximum changes limit (${this.maxChanges}) reached`); return; } this.changes.set(hexKey, { delete: true, key: new Uint8Array(key), // Copy to avoid reference issues value: previousValue ? new Uint8Array(previousValue) : new Uint8Array(0), }); } /** * Get the current change set. * Returns a copy to prevent external modifications. * * @returns The current set of changes */ getChangeSet(): ChangeSet { const pairs: KVPair[] = Array.from(this.changes.values()).map(change => ({ delete: change.delete, key: new Uint8Array(change.key), value: new Uint8Array(change.value), })); // Sort by key for deterministic output pairs.sort((a, b) => { const aHex = toHex(a.key); const bHex = toHex(b.key); return aHex.localeCompare(bHex); }); return { pairs, }; } /** * Get the number of tracked changes. */ size(): number { return this.changes.size; } /** * Clear all tracked changes. * Should be called after SaveVersion. */ clear(): void { this.changes.clear(); } /** * Check if a specific key has been changed. * * @param key - The key to check * @returns True if the key has been modified */ hasChange(key: Uint8Array): boolean { if (!this.enabled) return false; return this.changes.has(toHex(key)); } /** * Get a specific change by key. * * @param key - The key to look up * @returns The change record or undefined */ getChange(key: Uint8Array): KVPair | undefined { if (!this.enabled) return undefined; const change = this.changes.get(toHex(key)); if (!change) return undefined; // Return a copy to prevent modifications return { delete: change.delete, key: new Uint8Array(change.key), value: new Uint8Array(change.value), }; } /** * Serialize the change set to protobuf bytes. * Useful for network transmission or storage. * * @returns Serialized change set */ serialize(): Uint8Array { const changeSet = this.getChangeSet(); const writer = ChangeSetCodec.encode(changeSet); return writer.finish(); } /** * Deserialize a change set from protobuf bytes. * * @param data - Serialized change set * @returns Deserialized change set */ static deserialize(data: Uint8Array): ChangeSet { return ChangeSetCodec.decode(data); } /** * Apply a change set to this tracker. * Useful for merging changes from multiple sources. * * @param changeSet - The change set to apply */ applyChangeSet(changeSet: ChangeSet): void { if (!this.enabled) return; for (const pair of changeSet.pairs) { const hexKey = toHex(pair.key); if (this.changes.size >= this.maxChanges) { console.warn(`ChangeTracker: Maximum changes limit (${this.maxChanges}) reached during apply`); break; } this.changes.set(hexKey, { delete: pair.delete, key: new Uint8Array(pair.key), value: new Uint8Array(pair.value), }); } } /** * Get statistics about the tracked changes. */ getStats(): { total: number sets: number deletes: number enabled: boolean maxChanges: number } { let sets = 0; let deletes = 0; for (const change of this.changes.values()) { if (change.delete) { deletes++; } else { sets++; } } return { total: this.changes.size, sets, deletes, enabled: this.enabled, maxChanges: this.maxChanges, }; } /** * Export changes as JSON for debugging. * Note: Values are base64 encoded. */ toJSON(): { enabled: boolean maxChanges: number stats: { total: number sets: number deletes: number enabled: boolean maxChanges: number } changes: Array<{ delete: boolean key: string value: string }> } { const changeSet = this.getChangeSet(); // Simple base64 encoding for JSON export const toBase64 = (bytes: Uint8Array): string => { return Buffer.from(bytes).toString("base64"); }; return { enabled: this.enabled, maxChanges: this.maxChanges, stats: this.getStats(), changes: changeSet.pairs.map(pair => ({ delete: pair.delete, key: toBase64(pair.key), value: toBase64(pair.value), })), }; } }