UNPKG

@code-yeongyu/senpi

Version:

Coding agent CLI with read, bash, edit, write tools and session management

250 lines • 9.22 kB
import { dirname, join } from "node:path"; import { open, rm } from "node:fs/promises"; import { randomUUID } from "node:crypto"; import { recoveryAgentDir, RecoveryStorageHealth } from "./compact-storage-health.js"; import { CompactReadError } from "./compact-read-lease.js"; import { createSpoolDir, removeSpoolDir } from "./compact-spool-dir.js"; import { CompactStorageReadError, describeCause, } from "./compact-storage-io.js"; /** * The spool file path of compact current-state storage (senpi#4272, R3.C6.4): one serial * asynchronous job chain, the private epoch directory, spool file writes, reads and reclamation, * and the failure ledger. `CompactContentStore` adds leaf ownership and spilling on top. */ export const RECLAIM_WORK_ALLOWANCE_BYTES = 1024 * 1024; const RECLAIM_RETRY_DELAYS_MS = [100, 400, 1_600, 6_400, 25_600]; const FAILURE_HISTORY = 32; /** Spool file name prefixes by the write that creates them; any other write is a page. */ const FILE_PREFIX = { spill_write: "leaf", value_write: "value", node_write: "node", }; /** A failed write of accepted content halts spilling: its bytes stay resident instead of on disk. */ const HALTING = new Set([ "spill_write", "value_write", "node_write", "spool_create", ]); export class CompactSpoolStorage { assertReadable() { if (this.retired) throw new CompactReadError("retired"); } beginRead() { this.assertReadable(); this.reads++; this.reading ??= Promise.withResolvers(); let done = false; return () => { if (done) return; done = true; if (--this.reads === 0) { this.reading?.resolve(); this.reading = undefined; } }; } constructor(dir, io, health = new RecoveryStorageHealth(recoveryAgentDir)) { this.failures = []; this.nextFile = 1; this.chain = Promise.resolve(); this.queued = 0; this.spillQueued = false; this.halted = false; this.retired = false; this.pendingIoCopyBytes = 0; this.spillBytesWritten = 0; this.reclaimDebtBytes = 0; this.reads = 0; this.dir = dir; this.io = io; this.health = health; } /** Explicit availability repair: a real fsynced probe, then retry retained writes without changing accepted state. */ async repair() { const revision = await this.health.recover(async () => { const path = join(dirname(this.dir), `.senpi-repair-${randomUUID()}`); try { const file = await open(path, "wx", 0o600); try { await file.writeFile("repair"); await file.sync(); } finally { await file.close(); } } finally { await rm(path, { force: true }); } }); this.halted = false; if (this.spoolToken === undefined) this.dirReady = undefined; this.scheduleSpill(); await this.idle(); return revision; } /** Resolves once every queued storage job, including the ones they queued, has completed. */ async idle() { while (this.queued > 0) await this.chain; } /** * Invalidates spilling, joins owned I/O, then removes the epoch directory only when this store * created it and it still passes the ownership checks; otherwise rejects with `CompactSpoolRefusedError`. */ async retire() { this.retired = true; await this.reading?.promise; await this.idle(); const token = this.spoolToken; if (token !== undefined) { try { await removeSpoolDir(this.dir, token); } catch (cause) { this.fail("reclaim", this.dir, cause, 0); throw cause; } this.spoolToken = undefined; this.reclaimDebtBytes = 0; } } /** Reads a committed file, or the `range` of it, and rejects a missing, unreadable or short one. */ async readFile(path, bytes, operation, range) { const done = this.beginRead(); try { const result = await this.readCommittedFile(path, bytes, operation, range); this.assertReadable(); return result; } finally { done(); } } async readCommittedFile(path, bytes, operation, range) { let data; try { data = await this.io.readFile(path, range); } catch (cause) { throw this.readFailure(operation, path, cause); } if (data.byteLength !== bytes) { throw this.readFailure(operation, path, new Error(`expected ${bytes} bytes, found ${data.byteLength}`)); } return data; } /** Writes one new spool file; undefined means the write failed and was reported (a spill write also halts spilling). */ async writeFile(data, operation, retainedInMemoryBytes) { const path = await this.ensureDir(retainedInMemoryBytes); if (path === undefined) return undefined; const file = join(path, `${FILE_PREFIX[operation] ?? "page"}-${this.nextFile++}.bin`); this.pendingIoCopyBytes += data.byteLength; try { if (this.health.needsRecovery) await this.health.recover(() => this.io.writeFile(file, data)); else await this.io.writeFile(file, data); this.spillBytesWritten += data.byteLength; return file; } catch (cause) { try { this.fail(operation, file, cause, retainedInMemoryBytes); } finally { this.discard(file, data.byteLength); } return undefined; } finally { this.pendingIoCopyBytes -= data.byteLength; } } /** * An unreferenced (or partially written) spool file: reclamation debt until its unlink completes or * finds it gone. Files dropped after retirement started belong to the directory retirement removes. */ discard(path, bytes) { if (this.retired) return; this.reclaimDebtBytes += bytes; this.enqueue("reclaim", () => this.reclaim(path, bytes, 0)); } /** A failed unlink keeps its debt and is retried with bounded backoff outside the job chain. */ async reclaim(path, bytes, attempt) { try { await this.io.unlink(path); } catch (cause) { if (cause.code !== "ENOENT") { this.fail("reclaim", path, cause, 0); const delay = RECLAIM_RETRY_DELAYS_MS[attempt]; if (delay !== undefined) { setTimeout(() => { if (!this.retired) this.enqueue("reclaim", () => this.reclaim(path, bytes, attempt + 1)); }, delay).unref?.(); } return; } } this.reclaimDebtBytes -= bytes; this.scheduleSpill(); } get spillAllowed() { return !this.halted && !this.retired; } /** True while a storage failure or unreclaimed debt above the work allowance holds spilling back. */ get spillStopped() { return this.halted || this.reclaimDebtBytes > RECLAIM_WORK_ALLOWANCE_BYTES; } enqueue(operation, job) { this.queued++; this.chain = this.chain .then(job) .catch((cause) => { if (operation === "spill_write") this.spillQueued = false; if (this.retired && cause instanceof CompactReadError && cause.reason === "retired") return; this.fail(operation, this.dir, cause, 0); }) .finally(() => { this.queued--; }); } /** Creates the private epoch directory once; a refusal or failure halts spilling and is reported. */ ensureDir(retained) { this.dirReady ??= createSpoolDir(this.dir).then((token) => { this.spoolToken = token; return this.dir; }, (cause) => { this.fail("spool_create", this.dir, cause, retained); return undefined; }); return this.dirReady; } readFailure(operation, path, cause) { this.fail(operation, path, cause, 0); return new CompactStorageReadError(operation, path, cause); } fail(operation, path, cause, retained) { if (HALTING.has(operation) || operation === "page_write") this.health.unavailable(); if (HALTING.has(operation)) this.halted = true; this.record({ operation, path, cause: describeCause(cause), retainedInMemoryBytes: retained }); } record(failure) { this.failures.push(failure); if (this.failures.length > FAILURE_HISTORY) this.failures.shift(); } } //# sourceMappingURL=compact-spool-storage.js.map