import { promises as fs } from "node:fs"; import { dirname } from "node:path"; const LOCK_POLL_INTERVAL = 100; // ms between retries const LOCK_MAX_WAIT = 10_000; // 30s total timeout const LOCK_STALE_TIMEOUT = 10_000; // 30s before a lock is considered stale /** * Acquire an exclusive file lock. Returns a release function that must be called in a finally block. * Uses O_EXCL (exclusive create) for atomic lock acquisition on POSIX filesystems. * Stale locks (older than LOCK_STALE_TIMEOUT) are automatically removed and re-acquired. */ export async function acquireLock(lockPath: string) { const lockFile = `${lockPath}.lock`; const start = Date.now(); await fs.mkdir(dirname(lockFile), { recursive: true }); while (true) { try { const fd = await fs.open(lockFile, "wx"); await fd.writeFile(`${Date.now()}`); await fd.close(); return async () => { await fs.unlink(lockFile).catch(() => {}); }; } catch (err: unknown) { if ((err as NodeJS.ErrnoException).code !== "EEXIST") throw err; // Stale lock detection via mtime — no need to read file contents try { const stat = await fs.stat(lockFile); if (Date.now() - stat.mtimeMs > LOCK_STALE_TIMEOUT) { await fs.unlink(lockFile).catch(() => {}); continue; } } catch {} if (Date.now() - start > LOCK_MAX_WAIT) { throw new Error(`Timeout waiting for lock on ${lockPath}`); } await new Promise((r) => setTimeout(r, LOCK_POLL_INTERVAL)); } } } /** * Run `fn` with an exclusive file lock. The lock is always released, even if `fn` throws. */ export async function withLock(lockPath: string, fn: () => Promise): Promise { const releaseLock = await acquireLock(lockPath); try { return await fn(); } finally { await releaseLock(); } }