{"version":3,"file":"batch-with-flusher.cjs","names":[],"sources":["../../src/db/batch-with-flusher.ts"],"sourcesContent":["/**\n * BatchWithFlusher implementation for IAVL.\n *\n * Wrapper around a batch that automatically flushes to disk when a configurable\n * size threshold is reached. This improves performance by batching writes while\n * preventing memory from growing unbounded.\n *\n * Based on Go IAVL batch.go\n */\n\nimport type {\n  Batch, Database,\n} from \"./types.js\";\n\n/**\n * Default flush threshold in bytes.\n * Based on Go IAVL options.go DefaultOptions().FlushThreshold\n */\nexport const DEFAULT_FLUSH_THRESHOLD = 100000; // 100KB\n\n/**\n * Overhead bytes to account for batch metadata.\n * Some batch implementations add extra metadata beyond key+value size.\n * Based on Go IAVL batch.go line 43\n */\nconst BATCH_OVERHEAD = 100;\n\n/**\n * BatchWithFlusher wraps a regular batch and automatically flushes\n * when the batch size exceeds a threshold.\n *\n * Thread-safety: While the Go implementation uses mutexes, Node.js is single-threaded\n * so we don't need explicit locking. Async operations are naturally serialized.\n *\n * Based on Go IAVL batch.go BatchWithFlusher\n */\nexport class BatchWithFlusher implements Batch {\n  private db: Database;\n  private batch: Batch;\n  private flushThreshold: number;\n  private currentSize: number;\n  private closed: boolean;\n\n  /**\n   * Creates a new BatchWithFlusher.\n   *\n   * @param db - Database to create batches from\n   * @param flushThreshold - Size threshold in bytes to trigger flush (default 100KB)\n   */\n  constructor(db: Database, flushThreshold = DEFAULT_FLUSH_THRESHOLD) {\n    this.db = db;\n    this.batch = db.batch();\n    this.flushThreshold = flushThreshold;\n    this.currentSize = 0;\n    this.closed = false;\n  }\n\n  /**\n   * Estimates the batch size after adding a key-value pair.\n   *\n   * Based on Go IAVL batch.go estimateSizeAfterSetting\n   *\n   * @param key - Key bytes\n   * @param value - Value bytes\n   * @returns Estimated size after addition\n   */\n  private estimateSizeAfterSetting(key: Uint8Array, value: Uint8Array): number {\n    // Current size + key length + value length + overhead\n    return this.currentSize + key.length + value.length + BATCH_OVERHEAD;\n  }\n\n  /**\n   * Sets a key-value pair in the batch.\n   * If this would exceed the flush threshold, flushes first.\n   *\n   * Based on Go IAVL batch.go Set\n   *\n   * @param key - Key to set\n   * @param value - Value to set\n   */\n  set(key: Uint8Array, value: Uint8Array): void {\n    if (this.closed) {\n      throw new Error(\"BatchWithFlusher is closed\");\n    }\n\n    const sizeAfter = this.estimateSizeAfterSetting(key, value);\n\n    if (sizeAfter > this.flushThreshold) {\n      // Need to flush before adding this entry\n      // Note: In Go, they unlock/lock mutex here for async flush\n      // In Node.js, we'll use async/await pattern\n      this.flushSync();\n    }\n\n    this.batch.set(key, value);\n    this.currentSize += key.length + value.length;\n  }\n\n  /**\n   * Deletes a key from the batch.\n   * If this would exceed the flush threshold, flushes first.\n   *\n   * Based on Go IAVL batch.go Delete\n   *\n   * @param key - Key to delete\n   */\n  delete(key: Uint8Array): void {\n    if (this.closed) {\n      throw new Error(\"BatchWithFlusher is closed\");\n    }\n\n    // Deletion entries also consume space (key + delete marker)\n    const sizeAfter = this.estimateSizeAfterSetting(key, new Uint8Array(0));\n\n    if (sizeAfter > this.flushThreshold) {\n      this.flushSync();\n    }\n\n    this.batch.delete(key);\n    this.currentSize += key.length;\n  }\n\n  /**\n   * Synchronously flushes the current batch and creates a new one.\n   * This is a private helper used during set/delete operations.\n   *\n   * Note: The Go implementation has async Write but we need sync here\n   * to maintain operation ordering within set/delete.\n   */\n  private flushSync(): void {\n    // We'll need to make this operation async-safe\n    // For now, we'll queue the flush operation\n    throw new Error(\"Sync flush required - use writeAsync instead\");\n  }\n\n  /**\n   * Writes the batch to the database and creates a new batch.\n   *\n   * Based on Go IAVL batch.go Write\n   */\n  async write(): Promise<void> {\n    if (this.closed) {\n      throw new Error(\"BatchWithFlusher is closed\");\n    }\n\n    await this.batch.write();\n    this.batch.close();\n\n    // Create new batch with pre-allocated size\n    this.batch = this.db.batch();\n    this.currentSize = 0;\n  }\n\n  /**\n   * Writes the batch to the database with sync flag and creates a new batch.\n   *\n   * Based on Go IAVL batch.go WriteSync\n   *\n   * Note: Our interface doesn't distinguish between Write and WriteSync,\n   * but we provide this for API compatibility.\n   */\n  async writeSync(): Promise<void> {\n    return this.write();\n  }\n\n  /**\n   * Closes the batch without writing.\n   *\n   * Based on Go IAVL batch.go Close\n   */\n  close(): void {\n    if (!this.closed) {\n      this.batch.close();\n      this.closed = true;\n    }\n  }\n\n  /**\n   * Gets the current byte size of the batch.\n   *\n   * Based on Go IAVL batch.go GetByteSize\n   *\n   * @returns Current batch size in bytes\n   */\n  getByteSize(): number {\n    return this.currentSize;\n  }\n}\n\n/**\n * Async version of BatchWithFlusher that properly handles async flushes.\n *\n * This version queues operations and processes them asynchronously,\n * allowing for proper async flush operations when threshold is exceeded.\n */\nexport class AsyncBatchWithFlusher {\n  private db: Database;\n  private batch: Batch;\n  private flushThreshold: number;\n  private currentSize: number;\n  private closed: boolean;\n  private operations: Array<{\n    type: \"set\" | \"delete\"\n    key: Uint8Array\n    value?: Uint8Array\n  }> = [];\n\n  private processing = false;\n  private processPromise?: Promise<void>;\n\n  /**\n   * Creates a new AsyncBatchWithFlusher.\n   *\n   * @param db - Database to create batches from\n   * @param flushThreshold - Size threshold in bytes to trigger flush (default 100KB)\n   */\n  constructor(db: Database, flushThreshold = DEFAULT_FLUSH_THRESHOLD) {\n    this.db = db;\n    this.batch = db.batch();\n    this.flushThreshold = flushThreshold;\n    this.currentSize = 0;\n    this.closed = false;\n  }\n\n  /**\n   * Queues a set operation.\n   *\n   * @param key - Key to set\n   * @param value - Value to set\n   * @returns Promise that resolves when operation is processed\n   */\n  async set(key: Uint8Array, value: Uint8Array): Promise<void> {\n    if (this.closed) {\n      throw new Error(\"AsyncBatchWithFlusher is closed\");\n    }\n\n    this.operations.push({\n      type: \"set\",\n      key,\n      value,\n    });\n    return this.processOperations();\n  }\n\n  /**\n   * Queues a delete operation.\n   *\n   * @param key - Key to delete\n   * @returns Promise that resolves when operation is processed\n   */\n  async delete(key: Uint8Array): Promise<void> {\n    if (this.closed) {\n      throw new Error(\"AsyncBatchWithFlusher is closed\");\n    }\n\n    this.operations.push({\n      type: \"delete\",\n      key,\n    });\n    return this.processOperations();\n  }\n\n  /**\n   * Processes queued operations, flushing when necessary.\n   */\n  private async processOperations(): Promise<void> {\n    if (this.processing) {\n      // Wait for current processing to complete\n      return this.processPromise;\n    }\n\n    this.processing = true;\n    this.processPromise = this.doProcessOperations();\n\n    try {\n      await this.processPromise;\n    }\n    finally {\n      this.processing = false;\n    }\n  }\n\n  /**\n   * Actually processes the operations.\n   */\n  private async doProcessOperations(): Promise<void> {\n    while (this.operations.length > 0) {\n      const op = this.operations.shift()!;\n\n      const sizeAfter = this.estimateSizeAfterOp(op);\n\n      if (sizeAfter > this.flushThreshold) {\n        // Flush current batch\n        await this.flush();\n      }\n\n      // Apply operation to batch\n      if (op.type === \"set\" && op.value) {\n        this.batch.set(op.key, op.value);\n        this.currentSize += op.key.length + op.value.length;\n      }\n      else if (op.type === \"delete\") {\n        this.batch.delete(op.key);\n        this.currentSize += op.key.length;\n      }\n    }\n  }\n\n  /**\n   * Estimates size after an operation.\n   */\n  private estimateSizeAfterOp(op: {\n    type: string\n    key: Uint8Array\n    value?: Uint8Array\n  }): number {\n    const valueSize = op.value ? op.value.length : 0;\n    return this.currentSize + op.key.length + valueSize + BATCH_OVERHEAD;\n  }\n\n  /**\n   * Flushes the current batch and creates a new one.\n   */\n  private async flush(): Promise<void> {\n    await this.batch.write();\n    this.batch.close();\n    this.batch = this.db.batch();\n    this.currentSize = 0;\n  }\n\n  /**\n   * Writes any pending operations and the final batch.\n   */\n  async write(): Promise<void> {\n    if (this.closed) {\n      throw new Error(\"AsyncBatchWithFlusher is closed\");\n    }\n\n    // Process any remaining operations\n    await this.processOperations();\n\n    // Write final batch\n    await this.batch.write();\n    this.batch.close();\n\n    // Create new batch\n    this.batch = this.db.batch();\n    this.currentSize = 0;\n  }\n\n  /**\n   * Writes any pending operations and the final batch with sync flag.\n   * This ensures data is flushed to disk (fsync) before returning.\n   *\n   * Based on Go IAVL batch.go WriteSync\n   */\n  async writeSync(): Promise<void> {\n    if (this.closed) {\n      throw new Error(\"AsyncBatchWithFlusher is closed\");\n    }\n\n    // Process any remaining operations\n    await this.processOperations();\n\n    // Write final batch with sync\n    await this.batch.write();\n    this.batch.close();\n\n    // Create new batch\n    this.batch = this.db.batch();\n    this.currentSize = 0;\n\n    // For databases that support it, ensure data is flushed to disk\n    // This is a placeholder - actual sync behavior depends on the database implementation\n  }\n\n  /**\n   * Closes the batch.\n   */\n  close(): void {\n    if (!this.closed) {\n      this.batch.close();\n      this.closed = true;\n      this.operations = [];\n    }\n  }\n\n  /**\n   * Gets the current byte size.\n   */\n  getByteSize(): number {\n    return this.currentSize;\n  }\n}\n"],"mappings":";;;;;;AAkBA,MAAa,0BAA0B;;;;;;AAOvC,MAAM,iBAAiB;;;;;;;;;;AAWvB,IAAa,mBAAb,MAA+C;CAC7C,AAAQ;CACR,AAAQ;CACR,AAAQ;CACR,AAAQ;CACR,AAAQ;;;;;;;CAQR,YAAY,IAAc,iBAAiB,yBAAyB;AAClE,OAAK,KAAK;AACV,OAAK,QAAQ,GAAG,OAAO;AACvB,OAAK,iBAAiB;AACtB,OAAK,cAAc;AACnB,OAAK,SAAS;;;;;;;;;;;CAYhB,AAAQ,yBAAyB,KAAiB,OAA2B;AAE3E,SAAO,KAAK,cAAc,IAAI,SAAS,MAAM,SAAS;;;;;;;;;;;CAYxD,IAAI,KAAiB,OAAyB;AAC5C,MAAI,KAAK,OACP,OAAM,IAAI,MAAM,6BAA6B;AAK/C,MAFkB,KAAK,yBAAyB,KAAK,MAAM,GAE3C,KAAK,eAInB,MAAK,WAAW;AAGlB,OAAK,MAAM,IAAI,KAAK,MAAM;AAC1B,OAAK,eAAe,IAAI,SAAS,MAAM;;;;;;;;;;CAWzC,OAAO,KAAuB;AAC5B,MAAI,KAAK,OACP,OAAM,IAAI,MAAM,6BAA6B;AAM/C,MAFkB,KAAK,yBAAyB,KAAK,IAAI,WAAW,EAAE,CAAC,GAEvD,KAAK,eACnB,MA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