UNPKG

@sema-agent/core

Version:

Stateless, task-oriented AI agent core

964 lines (963 loc) • 36.7 kB
import { closeSync, constants as fsConstants, existsSync, fstatSync, ftruncateSync, readSync, statSync, writeSync, fsyncSync, } from "node:fs"; import { constants as bufferConstants } from "node:buffer"; import { dataRootSpelling, walkedDataRoot } from "../../core/data-root.js"; import { basename, dirname, join, resolve as resolvePath } from "node:path"; import { createHash } from "node:crypto"; import { PRIVATE_FILE_MODE } from "../../core/exclusive-temp.js"; import { fsyncDir } from "../../core/durable-sync.js"; import { descriptorPool, linkSync, mkdirSync, openExclusiveTemp, openSync, parkDownTo, queueStoreNotice, readFileSync, renameSync, setLostLockGuard, unlinkLockFile as unlinkLockFileSync, unlinkSync, writeFileSync } from "./descriptor-seat.js"; import { physicalPathOf, physicalPathOfExisting } from "../../core/physical-path.js"; import { processCensus } from "../../core/process-identity.js"; import { holdAnchor, lostLockCovering, sweepLeftoverAnchors } from "./process-anchor.js"; import { anchorNamesReferencedIn, judgeLockBytes, lockRefusalClause, readLockBytes, lockRecordOf, serializeLockRecord, } from "./lock-reading.js"; export { processFingerprint, isProcessLive } from "../../core/process-identity.js"; import { codedRefusal, thrownText } from "../../core/thrown-value.js"; import { holdsUnpairedSurrogate, unpairedSurrogateRefusal } from "../../core/principal-name.js"; import { callerText } from "../../core/caller-text.js"; import { deliverEngineNotice } from "../../core/engine-notice.js"; const SAFE_COMPONENT = /^[A-Za-z0-9_.-]+$/; export function sanitizePathComponent(raw) { if (typeof raw !== "string") throw new Error(`file store: unsafe path component ${callerText(raw)} (not a string)`); if (raw === "" || raw === "." || raw === ".." || !SAFE_COMPONENT.test(raw)) { throw new Error(`file store: unsafe path component ${JSON.stringify(raw)}`); } return raw; } export function sanitizeScope(scope) { if (typeof scope === "string") assertWellFormedKey(scope, "file store: the scope"); return scopeLabelOf(scope); } export function assertWellFormedKey(key, what) { if (typeof key === "string" && holdsUnpairedSurrogate(key)) throw codedRefusal("config.invalid_argument", unpairedSurrogateRefusal(what)); } export function scopeLabelOf(scope) { if (typeof scope !== "string") throw new Error(`file store: a scope must be a string (got ${callerText(scope)})`); const base = scope.replace(/[^A-Za-z0-9]/g, "-"); return `${(base || "_").slice(0, 120)}-${createHash("sha256").update(scope, "utf8").digest("hex")}`; } const PRIVATE_DIR_MODE = 0o700; export function resolveDataRoot(explicit, anchor) { const { spelling } = walkedDataRoot(explicit, anchor); mkdirSync(spelling, { recursive: true, mode: PRIVATE_DIR_MODE }); return physicalPathOf(spelling); } export function writeThenLink(target, content) { ensureDir(dirnameOf(target)); const { fd, path: tmp } = openExclusiveTemp(target); let linked = false; try { try { writeFileSync(fd, content); fsyncSync(fd); } finally { closeSync(fd); } linkSync(tmp, target); linked = true; } finally { try { unlinkSync(tmp); } catch { } } if (linked) fsyncDir(dirnameOf(target)); } export function ensureDir(dir) { mkdirSync(dir, { recursive: true, mode: PRIVATE_DIR_MODE }); } export function atomicWriteFile(tmpDir, target, bytes) { assertLockNotLost(target); ensureDir(tmpDir); const opened = openExclusiveTemp(join(tmpDir, basenameOf(target))); const tmp = opened.path; let fd = opened.fd; try { writeFileSync(fd, bytes); fsyncSync(fd); closeSync(fd); fd = undefined; renameSync(tmp, target); fsyncDir(dirnameOf(target)); } catch (err) { if (fd !== undefined) { try { closeSync(fd); } catch { } } try { if (existsSync(tmp)) unlinkSync(tmp); } catch { } throw err; } } function basenameOf(p) { return basename(p); } function dirnameOf(p) { return dirname(p); } const UTF8_STRICT = new TextDecoder("utf-8", { fatal: true, ignoreBOM: true }); function jsonlTextOf(bytes) { try { return UTF8_STRICT.decode(bytes); } catch { return undefined; } } function jsonlFormOf(line) { if (typeof line !== "string") { const text = jsonlTextOf(line); if (text === undefined) return { form: "not-text", whole: jsonlTextFormOf(Buffer.from(line.buffer, line.byteOffset, line.byteLength).toString("utf8")).form === "record" }; return jsonlTextFormOf(text); } return jsonlTextFormOf(line); } function jsonlTextFormOf(text) { let value; try { value = JSON.parse(text); } catch { return { form: "unparseable" }; } if (value === null || typeof value !== "object" || Array.isArray(value)) return { form: "not-an-object", value }; return { form: "record", record: value }; } export function readJsonlRecords(path, onCorrupt, judge) { const out = []; let dropped = 0; for (const read of judgeJsonlFile(path, "appended", judge)) { if (read.verdict === "record") out.push(read.record); else if (read.verdict === "damage") { dropped++; onCorrupt?.({ kind: "record", path, reason: `${read.form}: ${read.what} at line ${read.line} (skipped)`, line: read.line, form: read.form }); } } if (dropped > 0) { const total = out.length + dropped; const reason = out.length === 0 ? `replay: none of ${total} records readable (all skipped)` : `replay: ${dropped} of ${total} records skipped, ${out.length} kept`; onCorrupt?.({ kind: "replay", path, reason, kept: out.length, dropped, total }); } return out; } const TYPED_ARRAY_PROTO = Object.getPrototypeOf(Uint8Array.prototype); const TYPED_ARRAY_NAME = Object.getOwnPropertyDescriptor(TYPED_ARRAY_PROTO, Symbol.toStringTag).get; const TYPED_ARRAY_LENGTH = Object.getOwnPropertyDescriptor(TYPED_ARRAY_PROTO, "length").get; const TYPED_ARRAY_SET = TYPED_ARRAY_PROTO.set; export function judgeJsonlBytes(bytes, written, judge) { if (TYPED_ARRAY_NAME.call(bytes) !== "Uint8Array") { throw codedRefusal("config.invalid_argument", `judgeJsonlBytes: bytes must be a Uint8Array (a Buffer is one) (got ${callerText(bytes)})`); } if (written !== "appended" && written !== "whole") { throw codedRefusal("config.invalid_argument", `judgeJsonlBytes: written must be "appended" or "whole" (got ${callerText(written)})`); } const length = TYPED_ARRAY_LENGTH.call(bytes); const copy = new Uint8Array(length); if (length > 0) TYPED_ARRAY_SET.call(copy, bytes); const raw = Buffer.from(copy.buffer); const endsOnBoundary = raw.length === 0 || raw[raw.length - 1] === 0x0a; const whole = jsonlTextOf(raw); const parts = whole !== undefined ? whole.split("\n") : splitOnNewlineByte(raw); const out = []; for (let i = 0; i < parts.length; i++) { const part = parts[i]; if (part.length === 0) { if (i < parts.length - 1) out.push({ verdict: "blank", line: i + 1 }); continue; } const read = readJsonlLine(part, i === parts.length - 1, judge); if (read.verdict === "record") out.push({ verdict: "record", record: read.record, line: i + 1 }); else if (read.verdict === "skip") out.push({ verdict: "damage", line: i + 1, form: read.form, what: read.what }); else if (written === "appended") out.push({ verdict: "uncommitted-tail", line: i + 1, bytes: typeof part === "string" ? Buffer.byteLength(part, "utf8") : part.length }); else out.push({ verdict: "damage", line: i + 1, form: "torn-json", what: "an unterminated line in a file published whole (it has no append in flight)" }); } return { lines: out, endsOnBoundary }; } export function judgeJsonlFile(path, written, judge) { let raw; try { raw = readFileSync(path); } catch (err) { if (err.code === "ENOENT") raw = Buffer.alloc(0); else throw err; } return judgeJsonlBytes(raw, written, judge).lines; } function splitOnNewlineByte(bytes) { const parts = []; let from = 0; for (let nl = bytes.indexOf(0x0a); nl >= 0; nl = bytes.indexOf(0x0a, from)) { parts.push(bytes.subarray(from, nl)); from = nl + 1; } parts.push(bytes.subarray(from)); return parts; } function isCrashPrefix(read) { return read.form === "unparseable" || (read.form === "not-text" && !read.whole); } function readJsonlLine(line, unterminated, judge) { const read = jsonlFormOf(line); if (unterminated && isCrashPrefix(read)) return { verdict: "partial-tail" }; if (read.form === "unparseable") return { verdict: "skip", form: "torn-json", what: "unparseable jsonl record" }; if (read.form === "not-text") return { verdict: "skip", form: "torn-json", what: "a jsonl line whose bytes are not UTF-8 text" }; if (read.form === "not-an-object") return { verdict: "skip", form: "not-an-object", what: `jsonl record is ${jsonTypeName(read.value)}, not an object` }; if (judge !== undefined && !judge.accepts(read.record)) return { verdict: "skip", form: "missing-required", what: judge.what }; return { verdict: "record", record: read.record }; } function assertJudgeableLine(length) { if (length > JSONL_TAIL_SEGMENT_LIMIT) throw new Error(`jsonl record cursor: a line of ${length} bytes is past the judgeable bound (${JSONL_TAIL_SEGMENT_LIMIT})`); } function jsonlLineBytes(bytes) { assertJudgeableLine(bytes.length); return bytes; } export function firstJsonlRecord(fd, size, judge) { let carry = Buffer.alloc(0); for (let from = 0; from < size;) { const block = Buffer.allocUnsafe(Math.min(JSONL_TAIL_READ_BLOCK, size - from)); readExactly(fd, block, block.length, from); from += block.length; let data = carry.length > 0 ? Buffer.concat([carry, block]) : block; for (let nl = data.indexOf(0x0a); nl >= 0; nl = data.indexOf(0x0a)) { const line = jsonlLineBytes(data.subarray(0, nl)); data = data.subarray(nl + 1); if (line.length === 0) continue; const read = readJsonlLine(line, false, judge); if (read.verdict === "record") return read.record; } carry = Buffer.from(data); assertJudgeableLine(carry.length); } if (carry.length === 0) return undefined; const read = readJsonlLine(jsonlLineBytes(carry), true, judge); return read.verdict === "record" ? read.record : undefined; } export function lastJsonlRecord(fd, size, pick, judge) { let carry = Buffer.alloc(0); let segmentEndsFile = true; const visit = (bytes) => { const unterminated = segmentEndsFile; segmentEndsFile = false; if (bytes.length === 0) return undefined; const read = readJsonlLine(jsonlLineBytes(bytes), unterminated, judge); return read.verdict === "record" && pick(read.record) ? read.record : undefined; }; for (let end = size; end > 0;) { const from = Math.max(0, end - JSONL_TAIL_READ_BLOCK); const block = Buffer.allocUnsafe(end - from); readExactly(fd, block, block.length, from); end = from; const data = carry.length > 0 ? Buffer.concat([block, carry]) : block; let segEnd = data.length; for (let nl = segEnd > 0 ? data.lastIndexOf(0x0a, segEnd - 1) : -1; nl >= 0; nl = segEnd > 0 ? data.lastIndexOf(0x0a, segEnd - 1) : -1) { const hit = visit(data.subarray(nl + 1, segEnd)); if (hit !== undefined) return hit; segEnd = nl; } carry = Buffer.from(data.subarray(0, segEnd)); assertJudgeableLine(carry.length); } return visit(carry); } function jsonTypeName(value) { if (value === null) return "null"; if (Array.isArray(value)) return "an array"; return `a ${typeof value}`; } export function canonicalStoreKey(p) { return physicalPathOfExisting(p).toLowerCase(); } const APPEND_LOG_WITNESS_BYTES = 64; const PATH_NAMES_NO_FILE = new Set(["ENOENT", "ENOTDIR", "EISDIR"]); const errorCodeOf = (err) => err?.code; function closeAfterFault(fd) { try { closeSync(fd); } catch { } } function closedLogRefusal() { return Object.assign(new Error("append: this log was closed (its session/box was deleted or replaced) — refusing to write through a released descriptor"), { code: "log_closed" }); } function fileReplacedRefusal() { descriptorPool.refusals++; return Object.assign(new Error("append: the file at this log's path is not the one it was bound to (removed, replaced, or rewritten outside this log since it last wrote there) — refusing to write; nothing at the path was changed"), { code: "log_file_replaced" }); } export class AppendLog { fd = -1; disposed = false; path; boundary = -1; binding; witness; parker = () => this.park(); constructor(path) { this.path = path; ensureDir(dirnameOf(path)); try { this.takeDescriptor(); this.repairTail(); } catch (err) { this.releaseFd(); throw err; } } takeDescriptor() { if (this.fd >= 0) { if (!this.heldIsHere()) throw fileReplacedRefusal(); descriptorPool.held.delete(this); descriptorPool.held.set(this, this.parker); return; } parkDownTo(descriptorPool.budget - 1, this, "budget_reached"); let fd; if (this.binding === undefined) { fd = openSync(this.path, "a+", PRIVATE_FILE_MODE); try { const opened = fstatSync(fd, { bigint: true }); this.binding = { dev: opened.dev, ino: opened.ino }; } catch (err) { closeAfterFault(fd); throw err; } this.boundary = -1; this.witness = undefined; } else { const reopened = this.openIfHere(fsConstants.O_RDWR | fsConstants.O_APPEND); if (reopened === undefined) throw fileReplacedRefusal(); fd = reopened; descriptorPool.reopens++; } this.fd = fd; descriptorPool.held.set(this, this.parker); if (descriptorPool.held.size > descriptorPool.peak) descriptorPool.peak = descriptorPool.held.size; } heldIsHere() { let named; try { named = statSync(this.path, { bigint: true }); } catch (err) { if (PATH_NAMES_NO_FILE.has(errorCodeOf(err) ?? "")) return false; throw err; } return this.leftHere(this.fd, named); } openIfHere(flags) { let fd; try { fd = openSync(this.path, flags | fsConstants.O_NONBLOCK); } catch (err) { if (PATH_NAMES_NO_FILE.has(errorCodeOf(err) ?? "")) return undefined; throw err; } let here; try { here = this.leftHere(fd, fstatSync(fd, { bigint: true })); } catch (err) { closeAfterFault(fd); throw err; } if (here) return fd; closeAfterFault(fd); return undefined; } leftHere(fd, st) { const bound = this.binding; if (bound === undefined || !st.isFile() || st.dev !== bound.dev || st.ino !== bound.ino) return false; if (this.boundary < 0) return true; if (Number(st.size) < this.boundary) return false; const witness = this.witness; if (witness === undefined || witness.length === 0) return true; const found = Buffer.allocUnsafe(witness.length); const at = this.boundary - witness.length; let got = 0; while (got < witness.length) { const n = readSync(fd, found, got, witness.length - got, at + got); if (n <= 0) return false; got += n; } return found.equals(witness); } settleAt(size) { this.boundary = size; this.witness = undefined; if (size < 0) return; const length = Math.min(APPEND_LOG_WITNESS_BYTES, size); const witness = Buffer.allocUnsafe(length); try { readExactly(this.fd, witness, length, size - length); } catch { this.boundary = -1; return; } this.witness = witness; } settleAfterWrite(buf) { if (this.boundary < 0) return; const size = this.sizeOrUnknown(); if (size !== this.boundary + buf.length) { if (size > this.boundary && this.endsOnNewline(size)) this.settleAt(size); return; } this.boundary += buf.length; const joined = buf.length >= APPEND_LOG_WITNESS_BYTES || this.witness === undefined ? buf : Buffer.concat([this.witness, buf]); this.witness = Buffer.from(joined.subarray(Math.max(0, joined.length - Math.min(APPEND_LOG_WITNESS_BYTES, this.boundary)))); } endsOnNewline(size) { const last = Buffer.allocUnsafe(1); try { return readSync(this.fd, last, 0, 1, size - 1) === 1 && last[0] === 0x0a; } catch { return false; } } park() { if (this.fd < 0) return; this.releaseFd(); descriptorPool.parks++; } sizeOrUnknown() { try { return fstatSync(this.fd).size; } catch { return -1; } } repairTail() { const size = this.sizeOrUnknown(); if (size < 0) { this.settleAt(-1); return; } if (size === this.boundary) return; if (size === 0) { this.settleAt(0); return; } const tail = Buffer.allocUnsafe(1); try { if (readSync(this.fd, tail, 0, 1, size - 1) === 1 && tail[0] === 0x0a) { this.settleAt(size); return; } } catch { this.settleAt(-1); return; } this.settleAt(-1); repairJsonlTailAt(this.fd, this.path); this.settleAt(this.sizeOrUnknown()); } append(record, fsync) { if (this.disposed) throw closedLogRefusal(); const buf = Buffer.from(`${JSON.stringify(record)}\n`, "utf8"); if (this.disposed) throw closedLogRefusal(); assertLockNotLost(this.path); this.takeDescriptor(); this.repairTail(); const startedAt = this.boundary; let written = 0; try { while (written < buf.length) { const n = writeSync(this.fd, buf, written, buf.length - written); if (n <= 0) throw new Error(`append: write made no progress (${written}/${buf.length} bytes) — refusing to leave a torn record`); written += n; } } catch (err) { if (!this.rollBackFailedWrite(startedAt, written)) this.settleAt(-1); throw err; } this.settleAfterWrite(buf); if (fsync) fsyncSync(this.fd); } rollBackFailedWrite(startedAt, written) { if (startedAt < 0) return false; try { if (fstatSync(this.fd).size !== startedAt + written) return false; ftruncateSync(this.fd, startedAt); return true; } catch { return false; } } close() { this.disposed = true; this.releaseFd(); } isFileAtPath() { if (this.disposed || this.binding === undefined) return false; if (this.fd >= 0) return this.heldIsHere(); const fd = this.openIfHere(fsConstants.O_RDONLY); if (fd === undefined) return false; closeAfterFault(fd); return true; } closeForSwap() { this.releaseFd(); this.binding = undefined; this.settleAt(-1); } releaseFd() { descriptorPool.held.delete(this); if (this.fd < 0) return; const fd = this.fd; this.fd = -1; try { closeSync(fd); } catch { } } } export const JSONL_TAIL_READ_BLOCK = 64 * 1024; export const JSONL_TAIL_SEGMENT_LIMIT = bufferConstants.MAX_STRING_LENGTH; function readExactly(fd, into, length, position) { let got = 0; while (got < length) { const n = readSync(fd, into, got, length - got, position + got); if (n <= 0) throw new Error(`jsonl tail: the file ended ${length - got} bytes early while its last line was read — it shrank under the reader`); got += n; } } export function readTailSegment(fd, size, limit = JSONL_TAIL_SEGMENT_LIMIT) { const block = Buffer.allocUnsafe(Math.min(JSONL_TAIL_READ_BLOCK, size)); let start = 0; for (let end = size; end > 0;) { const from = Math.max(0, end - JSONL_TAIL_READ_BLOCK); readExactly(fd, block, end - from, from); const newline = block.subarray(0, end - from).lastIndexOf(0x0a); if (newline >= 0) { start = from + newline + 1; break; } end = from; if (size - end > limit) return { unjudgeable: true }; } if (size - start > limit) return { unjudgeable: true }; const bytes = Buffer.allocUnsafe(size - start); readExactly(fd, bytes, bytes.length, start); return { unjudgeable: false, start, bytes }; } function repairJsonlTailAt(fd, path) { const segment = readTailSegment(fd, fstatSync(fd).size); if (segment.unjudgeable) { endLastLine(fd); queueStoreNotice({ code: "store.tail_segment_unjudged", message: `[sema] file store: a tail segment larger than the judgeable bound (${JSONL_TAIL_SEGMENT_LIMIT} bytes) was ended as a line, not judged — ` + `${path}. Its bytes are untouched; a reader meets it as an ordinary line.`, detail: { path }, }); return; } if (segment.bytes.length === 0) return; if (isCrashPrefix(jsonlFormOf(segment.bytes))) ftruncateSync(fd, segment.start); else endLastLine(fd); } function endLastLine(fd) { const n = writeSync(fd, "\n"); if (n !== 1) throw new Error(`append log: the newline that ends the file's last line was not written (${n} bytes) — refusing to append onto that line`); } export class FileStoreLockError extends Error { code; lockPath; name = "FileStoreLockError"; remedies; constructor(code, message, lockPath, holder, remedies = []) { super(message); this.code = code; this.lockPath = lockPath; if (holder !== undefined) Object.defineProperty(this, "holder", { value: holder, enumerable: true, writable: false, configurable: false }); this.remedies = Object.freeze([...remedies]); } } export function rewordedLockRefusal(err, message, lockPath) { return new FileStoreLockError(err.code, message, lockPath, err.holder, err.remedies); } function assertLockNotLost(target) { const lost = lostLockCovering(target); if (lost === undefined) return; throw new FileStoreLockError("store.lock_lost", `file store: this process lost the lock ${lost} (its process anchor was closed or replaced), so it no longer writes under it; restart the process`, lost); } setLostLockGuard(assertLockNotLost); function announceReclaimOnDeclaration(lockPath, pid, root) { deliverEngineNotice(undefined, { code: "store.lock_reclaimed_on_declaration", message: `[sema] file store: removed the lock ${lockPath} left by pid ${pid} — its record names no pid namespace, and it was judged in ` + `this process table because the host declared that every process opening the data root ${root} runs in it ` + `(declareDataRoot, singleProcessTable); the process it names is gone from this table.`, detail: { path: lockPath, pid, root }, }); } const MAX_RECLAIM_DEPTH = 8; const MAX_ACQUIRE_ATTEMPTS = 4; const abandonedLocks = new Map(); export class BootLock { lockPath; reclaimUnjudgedAfterMs; held = false; spentVerdict; anchorHold; published; kind = "gate"; static fence(dir, name) { const lock = new BootLock(join(dir, name)); lock.kind = "fence"; return lock; } constructor(lockPath, reclaimUnjudgedAfterMs) { this.lockPath = lockPath; this.reclaimUnjudgedAfterMs = reclaimUnjudgedAfterMs; } outlivedUnjudgedBound() { const bound = this.reclaimUnjudgedAfterMs; if (bound === undefined) return false; try { return Date.now() - statSync(this.lockPath).mtimeMs > bound; } catch { return false; } } acquire() { this.acquireWithin(0); } acquireWithin(depth) { for (let attempt = 0; attempt < MAX_ACQUIRE_ATTEMPTS; attempt++) { try { this.writeLock(); this.held = true; abandonedLocks.delete(this.abandonKey); return; } catch (err) { if (err.code !== "EEXIST") throw err; } const bytes = readLockBytes(this.lockPath); if (bytes.state === "absent") continue; const record = lockRecordOf(bytes); if (record !== undefined && abandonedLocks.get(this.abandonKey) === bytes.raw) { this.pruneOwnAbandoned(); return; } const judged = judgeLockBytes(this.lockPath, bytes, processCensus()); const holder = judged.reading.holder; if (holder.state === "unread") { throw this.refusal("store.lock_unreadable", judged.reading); } if (holder.state === "running" || holder.state === "this_process") throw this.refusal("store.dir_in_use", judged.reading); if (holder.state === "uncheckable" && !this.outlivedUnjudgedBound()) { throw this.refusal("store.dir_in_use", judged.reading); } if (record === undefined) continue; if (depth >= MAX_RECLAIM_DEPTH) { throw new FileStoreLockError("store.lock_unreadable", `file store: the lock ${this.lockPath} is buried under ${depth} nested stale reclaim gates (repeated crashes mid-reclaim); ` + `if no process uses it, remove it and the ${basenameOf(this.lockPath)}.claim.* files beside it`, this.lockPath, undefined, [{ kind: "remove_lock", path: this.lockPath }]); } const gate = new BootLock(`${this.lockPath}.claim.${record.pid}`, this.reclaimUnjudgedAfterMs); try { gate.acquireWithin(depth + 1); } catch (err) { const claimant = err instanceof FileStoreLockError && err.code === "store.dir_in_use" ? err.holder : undefined; if (claimant !== undefined && (claimant.state === "running" || claimant.state === "this_process")) { const who = claimant.state === "running" ? ` (pid ${claimant.pid})` : ""; throw new FileStoreLockError("store.dir_claiming", `file store: a live process${who} is taking over the lock ${this.lockPath} from a holder that is gone; retry in a moment`, this.lockPath, claimant); } throw err; } try { const under = readLockBytes(this.lockPath); const again = under.state === "present" && under.raw === bytes.raw ? judgeLockBytes(this.lockPath, under, processCensus()) : undefined; const still = again?.reading.holder; if (again !== undefined && still !== undefined && (still.state === "gone" || (still.state === "uncheckable" && this.outlivedUnjudgedBound()))) { let removed = false; try { unlinkLockFileSync(this.lockPath); removed = true; } catch { } if (removed && still.state === "gone" && still.by === "declaration" && again.declaredRoot !== undefined) { announceReclaimOnDeclaration(this.lockPath, record.pid, again.declaredRoot); } } else if (under.state !== "absent") { continue; } this.publishOrLoseRace(); return; } finally { gate.release(); } } throw new FileStoreLockError("store.dir_in_use", `file store: ownership of this data dir (${dirnameOf(this.lockPath)}) kept changing under us ` + `(${MAX_ACQUIRE_ATTEMPTS} attempts); another instance is starting and stopping on the same directory`, this.lockPath); } publishOrLoseRace() { try { this.writeLock(); this.held = true; abandonedLocks.delete(this.abandonKey); } catch (err) { if (err.code === "EEXIST") { throw new FileStoreLockError("store.dir_in_use", `file store: another instance won the lock race for this data dir`, this.lockPath); } throw err; } } pruneOwnAbandoned() { try { unlinkLockFileSync(this.lockPath); } catch (err) { throw new FileStoreLockError("store.lock_unreadable", `file store: this process still owns the lock file at ${this.lockPath} from an earlier release that ` + `could not remove it, and removing it now failed too (${thrownText(err)}); ` + `remove it by hand`, this.lockPath, { state: "this_process" }, [{ kind: "remove_lock", path: this.lockPath }]); } abandonedLocks.delete(this.abandonKey); this.publishOrLoseRace(); } refusal(code, reading) { return new FileStoreLockError(code, `file store: ${lockRefusalClause(reading, `the lock ${this.lockPath}`)}`, this.lockPath, reading.holder, reading.remedies); } writeLock() { const hold = this.kind === "fence" ? holdAnchor(this.lockPath, dirnameOf(this.lockPath)) : undefined; const bytes = serializeLockRecord(hold?.record); try { writeThenLink(this.lockPath, bytes); } catch (err) { hold?.release(); throw err; } this.published = bytes; this.anchorHold?.release(); this.anchorHold = hold; if (hold?.fresh === true) { const dir = dirnameOf(this.lockPath); sweepLeftoverAnchors(dir, () => anchorNamesReferencedIn(dir)); } } get abandonKey() { return resolvePath(this.lockPath); } inspectLock() { const bytes = readLockBytes(this.lockPath); if (bytes.state === "absent") return "absent"; if (lockRecordOf(bytes) === undefined) return "unreadable"; return this.published !== undefined && bytes.raw === this.published ? "ours" : "another"; } release() { if (!this.held) { return this.spentVerdict ?? true; } this.held = false; this.spentVerdict = this.removeOwnLock(); if (this.spentVerdict) { this.anchorHold?.release(); this.anchorHold = undefined; } return this.spentVerdict; } removeOwnLock() { const before = this.inspectLock(); if (before === "absent" || before === "another") { abandonedLocks.delete(this.abandonKey); return true; } if (before === "unreadable") { this.noteAbandoned(); return false; } try { unlinkLockFileSync(this.lockPath); } catch { } const after = this.inspectLock(); const gone = after === "absent" || after === "another"; if (gone) abandonedLocks.delete(this.abandonKey); else this.noteAbandoned(); return gone; } noteAbandoned() { if (this.published !== undefined) abandonedLocks.set(this.abandonKey, this.published); } resumeAbandoned() { if (this.held) return true; if (!abandonedLocks.has(this.abandonKey)) return false; if (this.inspectLock() !== "ours") return false; this.held = true; this.spentVerdict = undefined; abandonedLocks.delete(this.abandonKey); return true; } } const heldStoreDirLocks = new Map(); export function acquireStoreDirLock(dir, opts) { const fileName = opts.fileName ?? "LOCK"; const lockPath = join(dir, fileName); const key = `${fileName}@${canonicalStoreKey(dir)}`; const lease = (entry) => { let released = false; return { lockPath, release: () => { if (released) return; released = true; if (heldStoreDirLocks.get(key) !== entry) return; entry.refs -= 1; if (entry.refs > 0) return; if (entry.lock.release()) { heldStoreDirLocks.delete(key); return; } deliverEngineNotice(undefined, { code: "store.lock_retained", message: `[sema] file store: the ${opts.label} directory fence at ${lockPath} could not be handed back — the ` + `removal could not be proven, so a lock file naming this live process (pid ${process.pid}) may still ` + `be there. While it is, another process opening that directory is refused by name; the next open of ` + `it in THIS process finishes the cleanup or refuses by name. After this process exits the file is ` + `reclaimed as a stale lock ONLY if it is readable and its directory writable — otherwise it has to ` + `be removed by hand.`, detail: { lock: "directory_fence", path: lockPath, pid: process.pid }, }); }, }; }; const existing = heldStoreDirLocks.get(key); if (existing !== undefined) { if (existing.refs > 0 || existing.lock.resumeAbandoned()) { existing.refs += 1; return lease(existing); } heldStoreDirLocks.delete(key); } const lock = BootLock.fence(dir, fileName); try { lock.acquire(); } catch (err) { if (err instanceof FileStoreLockError) { const what = `file store: the ${opts.label} directory cannot be opened`; throw rewordedLockRefusal(err, err.code === "store.dir_claiming" ? `${what}: ${err.message.replace(/^file store: /, "")}` : err.holder !== undefined || err.remedies.length > 0 ? `${what}: ${lockRefusalClause(err, `the lock ${err.lockPath}`)}` : `${what} — ${err.message}`, err.lockPath); } throw err; } const entry = { lock, refs: 1 }; heldStoreDirLocks.set(key, entry); return lease(entry); }