import fs from 'fs'; import path from 'path'; export interface FileLockOptions { /** How long to wait for another process to release the lock. */ waitMs: number; /** A lock older than this belongs to a process that died; it is taken over. */ staleMs: number; /** Pause between attempts. */ pollMs?: number; } function sleepSync(ms: number): void { Atomics.wait(new Int32Array(new SharedArrayBuffer(4)), 0, 0, ms); } /** * Windows answers EPERM (or EACCES, EBUSY) for a lock that is only briefly * out of reach: a deleted file stays "delete pending" while any process * still has a handle on it (another waiter's stat, the virus scanner), and * creating or removing that name fails until the last handle closes. On * POSIX the same codes mean a real permission problem, which waiting does * not fix. */ export function isTransientWindowsLockError(err: unknown): boolean { if (process.platform !== 'win32') return false; const code = (err as NodeJS.ErrnoException | undefined)?.code; return code === 'EPERM' || code === 'EACCES' || code === 'EBUSY'; } /** How long the release keeps retrying a lock Windows will not delete yet. */ const RELEASE_RETRY_MS = 250; /** What `tryWithFileLock` reports: the function's value, or why it did not run. */ export type FileLockOutcome = { taken: true; value: T } | { taken: false; reason: 'busy' | 'error'; error?: unknown }; /** * Run `fn` holding `.lock` (O_EXCL), so a read-modify-write of `file` * is serialised across processes. The lock is a file because the writers are * separate short-lived processes (hooks, CLI commands) with nothing else in * common. * * `fn` runs ONLY with the lock held. When the lock cannot be taken (another * process holds it past `waitMs`, or it cannot be created at all) the outcome * says so and `fn` does not run: running it anyway, as this helper once could, * let a writer overwrite the holder's records (seen on Windows CI, where the * holder re-took the lock before a sleeping waiter woke). An error thrown by * `fn` itself propagates. */ export function tryWithFileLock( filePath: string, fn: () => T, options: FileLockOptions ): FileLockOutcome { const lockPath = `${filePath}.lock`; const deadline = Date.now() + options.waitMs; try { fs.mkdirSync(path.dirname(filePath), { recursive: true }); } catch { /* the open below reports it */ } for (;;) { try { fs.closeSync(fs.openSync(lockPath, 'wx')); break; } catch (err) { const code = (err as NodeJS.ErrnoException).code; if (code !== 'EEXIST' && !isTransientWindowsLockError(err)) { return { taken: false, reason: 'error', error: err }; } // A lock being released (Windows: still delete pending) is a lock // somebody holds: wait for it. let stale = false; try { stale = Date.now() - fs.statSync(lockPath).mtimeMs > options.staleMs; } catch { /* the holder released it between our two calls: try again */ } if (stale) { try { fs.unlinkSync(lockPath); continue; } catch { /* another waiter took it over first */ } } if (Date.now() > deadline) return { taken: false, reason: 'busy' }; sleepSync(options.pollMs ?? 20); } } try { return { taken: true, value: fn() }; } finally { releaseLock(lockPath); } } /** * `tryWithFileLock` for a writer that must not run unserialised: a lock that * cannot be taken is an error. */ export function withFileLock(filePath: string, fn: () => T, options: FileLockOptions): T { const outcome = tryWithFileLock(filePath, fn, options); if (outcome.taken) return outcome.value; if (outcome.reason === 'error') throw outcome.error; throw new Error(`${filePath} is locked by another node9 process; try again.`); } /** * Remove the lock. On Windows the delete can fail while another process has a * handle on the file; left in place, every other writer would wait for it to * go stale and then run without it. Retry for a short while instead. */ function releaseLock(lockPath: string): void { const deadline = Date.now() + RELEASE_RETRY_MS; for (;;) { try { fs.unlinkSync(lockPath); return; } catch (err) { if ((err as NodeJS.ErrnoException).code === 'ENOENT') return; if (!isTransientWindowsLockError(err) || Date.now() > deadline) return; // best effort sleepSync(2); } } }