import { mkdir, stat, unlink } from 'node:fs/promises'; import * as fs from 'node:fs'; import { dirname, resolve } from 'node:path'; import { setTimeout as delay } from 'node:timers/promises'; import lockfile from 'proper-lockfile'; /** Hosts before this protocol wrote a plain `.lock` file without heartbeat and * reclaimed each other's after 120s (memory) / 30s (runtime). A file older than * that is abandoned by the old protocol's own rule. Refusing it forever turned a * crash of the previous version into a permanent memory/runtime outage that only * a manual delete could end. A younger one is a live old host: wait, never steal. */ const LEGACY_LOCK_STALE_MS = 120_000; /** Shared heartbeat protocol for local file-backed stores, not a database lock. * proper-lockfile fails closed on compromised ownership (its default handler). */ export async function acquireStateFileLock( path: string, options: { signal?: AbortSignal; waitMs?: number; label?: string } = {}, ): Promise<() => Promise> { const { signal, waitMs = 15_000, label = 'STATE' } = options; signal?.throwIfAborted(); const target = resolve(path); await mkdir(dirname(target), { recursive: true, mode: 0o700 }); const deadline = Date.now() + waitMs; while (true) { signal?.throwIfAborted(); const legacy = await stat(`${target}.lock`).catch((error) => { if (error.code === 'ENOENT') return null; throw error; }); if (legacy?.isFile()) { if (Date.now() - legacy.mtimeMs > LEGACY_LOCK_STALE_MS) { await unlink(`${target}.lock`).catch((error) => { if (error.code !== 'ENOENT') throw error; }); continue; } if (Date.now() >= deadline) throw new Error(`${label}_LEGACY_LOCK:旧版本宿主正持有锁,请停止旧版本后重试:${target}.lock`); await delay(40, undefined, { signal }); continue; } try { let owned = false; let identity: fs.Stats | undefined; const guardedFs = { ...fs, rmdir(lockPath: fs.PathLike, callback: fs.NoParamCallback) { if (!owned) return fs.rmdir(lockPath, callback); // Also guard immediate release, before the next heartbeat could detect // replacement. Never recursively remove a lock directory. fs.stat(lockPath, (error, current) => { if (error || !identity || current.dev !== identity.dev || current.ino !== identity.ino || current.birthtimeMs !== identity.birthtimeMs) { callback(Object.assign(new Error(`锁所有权已丢失:${target}`), { code: 'ECOMPROMISED' })); return; } fs.rmdir(lockPath, callback); }); }, }; const release = await lockfile.lock(target, { fs: guardedFs, realpath: false, retries: 0, stale: 120_000, update: 10_000, }); owned = true; try { identity = await stat(`${target}.lock`); } catch (error) { await release().catch(() => undefined); throw error; } if (signal?.aborted) { await release(); signal.throwIfAborted(); } return release; } catch (error) { if ((error as NodeJS.ErrnoException).code !== 'ELOCKED') throw error; if (Date.now() >= deadline) throw new Error(`${label}_LOCK_TIMEOUT:等待文件锁超时:${target}`); await delay(40, undefined, { signal }); } } }