// withFileLock / tryWithFileLock: the lock file that serialises a // read-modify-write across node9's short-lived processes. import { describe, it, expect, beforeEach, afterEach, vi } from 'vitest'; import fs from 'fs'; import os from 'os'; import path from 'path'; import { tryWithFileLock, withFileLock } from '../utils/file-lock'; let dir: string; const file = () => path.join(dir, 'state.json'); const lock = () => `${file()}.lock`; beforeEach(() => { dir = fs.mkdtempSync(path.join(os.tmpdir(), 'node9-file-lock-')); }); afterEach(() => { fs.rmSync(dir, { recursive: true, force: true }); }); describe('withFileLock', () => { it('holds the lock while the function runs and releases it after', () => { const seen = withFileLock(file(), () => fs.existsSync(lock()), { waitMs: 100, staleMs: 1000 }); expect(seen).toBe(true); expect(fs.existsSync(lock())).toBe(false); }); it('releases the lock when the function throws', () => { expect(() => withFileLock( file(), () => { throw new Error('boom'); }, { waitMs: 100, staleMs: 1000 } ) ).toThrow('boom'); expect(fs.existsSync(lock())).toBe(false); }); it('creates the directory of a file that does not exist yet', () => { const nested = path.join(dir, 'a', 'b', 'state.json'); expect(withFileLock(nested, () => 'ran', { waitMs: 100, staleMs: 1000 })).toBe('ran'); }); it("refuses after the wait and leaves the holder's lock", () => { fs.writeFileSync(lock(), ''); const started = Date.now(); expect(() => withFileLock(file(), () => 'ran', { waitMs: 60, staleMs: 60_000, pollMs: 5 }) ).toThrow(/locked by another node9 process/); expect(Date.now() - started).toBeLessThan(2000); expect(fs.existsSync(lock())).toBe(true); }); it('takes over a lock left by a process that died', () => { fs.writeFileSync(lock(), ''); const old = new Date(Date.now() - 10_000); fs.utimesSync(lock(), old, old); expect(withFileLock(file(), () => 'ran', { waitMs: 60, staleMs: 2000, pollMs: 5 })).toBe('ran'); expect(fs.existsSync(lock())).toBe(false); }); it('rethrows the error of a lock that cannot be created', () => { // The lock's directory is a file: the open fails with ENOTDIR, not EEXIST. fs.writeFileSync(file(), ''); const blocked = path.join(file(), 'state.json'); expect(() => withFileLock(blocked, () => 'ran', { waitMs: 60, staleMs: 1000 })).toThrow(); }); }); describe('tryWithFileLock', () => { it('never runs the function without the lock', () => { // REGRESSION (CI windows-latest, 2026-11-29, 1 of 60 loop records lost): // a writer that waited past its limit ran anyway, beside the holder, and // wrote back a file without the holder's record. fs.writeFileSync(lock(), ''); const fn = vi.fn(() => 'ran'); const started = Date.now(); expect(tryWithFileLock(file(), fn, { waitMs: 60, staleMs: 60_000, pollMs: 5 })).toEqual({ taken: false, reason: 'busy', }); expect(fn).not.toHaveBeenCalled(); expect(Date.now() - started).toBeGreaterThanOrEqual(50); // Not ours: removing it would let a third process in beside the holder. expect(fs.existsSync(lock())).toBe(true); }); it('reports a lock that cannot be created, without running the function', () => { fs.writeFileSync(file(), ''); const fn = vi.fn(() => 'ran'); const outcome = tryWithFileLock(path.join(file(), 'state.json'), fn, { waitMs: 60, staleMs: 1000, }); expect(outcome).toMatchObject({ taken: false, reason: 'error' }); expect(fn).not.toHaveBeenCalled(); }); it("returns the function's value when it holds the lock", () => { expect(tryWithFileLock(file(), () => 7, { waitMs: 60, staleMs: 1000 })).toEqual({ taken: true, value: 7, }); }); }); // Windows answers EPERM for a lock file that is still "delete pending" (its // holder removed it while another process had a handle on it). Simulated by // making the platform win32 and the fs call fail the way Windows does. describe('the lock on Windows', () => { const realPlatform = process.platform; const eperm = () => Object.assign(new Error('EPERM: operation not permitted'), { code: 'EPERM' }); beforeEach(() => { Object.defineProperty(process, 'platform', { value: 'win32' }); }); afterEach(() => { Object.defineProperty(process, 'platform', { value: realPlatform }); vi.restoreAllMocks(); }); it('waits for a lock that is delete pending instead of giving up on it', () => { // REGRESSION (CI windows-latest, 2026-11-29, 2 of 60 loop records lost): // EPERM from the create was taken for "cannot lock". const realOpen = fs.openSync; let failures = 2; vi.spyOn(fs, 'openSync').mockImplementation(((...a: Parameters) => { if (String(a[0]).endsWith('.lock') && failures > 0) { failures--; throw eperm(); } return realOpen(...a); }) as typeof fs.openSync); const outcome = tryWithFileLock(file(), () => fs.existsSync(lock()), { waitMs: 1000, staleMs: 60_000, pollMs: 1, }); expect(failures).toBe(0); expect(outcome).toEqual({ taken: true, value: true }); expect(fs.existsSync(lock())).toBe(false); }); it('reports busy, after the wait, when the lock stays out of reach', () => { vi.spyOn(fs, 'openSync').mockImplementation((() => { throw eperm(); }) as typeof fs.openSync); const started = Date.now(); expect( tryWithFileLock(file(), () => 'ran', { waitMs: 60, staleMs: 60_000, pollMs: 5 }) ).toEqual({ taken: false, reason: 'busy' }); expect(Date.now() - started).toBeGreaterThanOrEqual(50); }); it('retries a release that Windows refuses for a moment', () => { const realUnlink = fs.unlinkSync; let failures = 2; vi.spyOn(fs, 'unlinkSync').mockImplementation(((p: fs.PathLike) => { if (String(p).endsWith('.lock') && failures > 0) { failures--; throw eperm(); } return realUnlink(p); }) as typeof fs.unlinkSync); withFileLock(file(), () => undefined, { waitMs: 100, staleMs: 60_000 }); expect(failures).toBe(0); // Left behind, every other writer would wait for it to go stale. expect(fs.existsSync(lock())).toBe(false); }); it('on other platforms EPERM is a real permission error, not a wait', () => { Object.defineProperty(process, 'platform', { value: 'linux' }); vi.spyOn(fs, 'openSync').mockImplementation((() => { throw eperm(); }) as typeof fs.openSync); const started = Date.now(); expect(tryWithFileLock(file(), () => 'ran', { waitMs: 5000, staleMs: 60_000 })).toMatchObject({ taken: false, reason: 'error', }); expect(Date.now() - started).toBeLessThan(1000); }); });