"use strict"; // Tests for utils/cross-process-mutex.js: the file-backed replacement for the // three in-process admin-operation mutexes (database-config / mongodb-config / // pgadmin-config). The pm2 ecosystem runs the panel in cluster mode, so the // mutual exclusion these mutexes provide must hold ACROSS worker processes. // // Contract locked here: // - tryAcquire() returns a release function or null (fail-fast), release is // idempotent and never unlinks a foreign-owned lock; // - a lock whose owner provably died (ESRCH, recycled PID via startTicks, // zombie) or whose acquiredAt aged past the TTL is stolen by a contender; // - a live owner (same process, or a live foreign process with matching // start ticks) is never stolen from; // - while held, the heartbeat atomically refreshes acquiredAt so long // awaited sections (minute-long installs) are not stolen from; // - a holder whose lock was stolen from it stops heartbeating, logs ONE // loud error and NEVER re-creates the lock; // - acquire() fails with code MUTEX_LOCK_TIMEOUT when the budget expires; // - REAL cross-process exclusivity: concurrent child processes serializing // on one lock file never overlap their critical sections. const test = require("node:test"); const assert = require("node:assert"); const fs = require("node:fs"); const os = require("node:os"); const path = require("node:path"); const childProcess = require("node:child_process"); const { createCrossProcessOperationMutex } = require("./cross-process-mutex"); function makeTempDir() { return fs.mkdtempSync(path.join(os.tmpdir(), "adpanel-cpm-")); } function lockPathIn(dir) { return path.join(dir, "resource.lock"); } function readLock(lockPath) { return JSON.parse(fs.readFileSync(lockPath, "utf8")); } function writeLock(lockPath, owner) { fs.writeFileSync(lockPath, JSON.stringify(owner), "utf8"); } async function spawnDeadPid() { const child = childProcess.spawn(process.execPath, ["-e", ""], { stdio: "ignore" }); await new Promise((resolve) => child.on("exit", resolve)); return child.pid; } function readProcStartTicks(pid) { const stat = fs.readFileSync(`/proc/${pid}/stat`, "utf8"); // Field 2 (comm) may contain spaces/parens; after the last ")", fields start // at field 3 (state), so starttime (field 22) sits at index 19. const fields = stat.slice(stat.lastIndexOf(")") + 2).trim().split(" "); return Number(fields[19]); } // Start-ticks detection (PID recycle / zombie owners) is /proc-backed; on // platforms without a readable /proc the kill(2) fallback governs and these // tests have nothing to assert. const canReadProc = (() => { try { fs.readFileSync("/proc/self/stat", "utf8"); return true; } catch (_) { return false; } })(); test("acquire/release round-trip: lock file is created owner-stamped and removed on release", () => { const dir = makeTempDir(); try { const lockPath = lockPathIn(dir); const mutex = createCrossProcessOperationMutex({ label: "[t]", lockFilePath: lockPath }); const release = mutex.tryAcquire(); assert.ok(typeof release === "function", "tryAcquire must return a release function"); assert.ok(fs.existsSync(lockPath), "the lock file must exist while held"); const owner = readLock(lockPath); assert.equal(owner.pid, process.pid); assert.ok(typeof owner.token === "string" && owner.token.length > 0, "the owner must carry a token"); assert.ok(Number.isFinite(owner.acquiredAt) && Date.now() - owner.acquiredAt < 5000); if (canReadProc) { assert.equal(owner.startTicks, readProcStartTicks(process.pid), "the owner must record its real start ticks"); } release(); assert.equal(fs.existsSync(lockPath), false, "release must remove the lock file"); } finally { fs.rmSync(dir, { recursive: true, force: true }); } }); test("tryAcquire fails fast while the lock is held (same instance and second instance), and re-acquires after release", () => { const dir = makeTempDir(); try { const lockPath = lockPathIn(dir); const mutex = createCrossProcessOperationMutex({ label: "[t]", lockFilePath: lockPath }); const mutex2 = createCrossProcessOperationMutex({ label: "[t2]", lockFilePath: lockPath }); const release = mutex.tryAcquire(); assert.ok(release); assert.equal(mutex.tryAcquire(), null, "a second acquire in the same holder must fail fast"); assert.equal(mutex2.tryAcquire(), null, "a second mutex instance on the same path must fail fast (file-backed)"); release(); const release2 = mutex2.tryAcquire(); assert.ok(release2, "the lock must be re-acquirable after release"); release2(); assert.equal(fs.existsSync(lockPath), false); } finally { fs.rmSync(dir, { recursive: true, force: true }); } }); test("double release is a silent no-op and never removes a re-acquired lock", () => { const dir = makeTempDir(); try { const lockPath = lockPathIn(dir); const mutex = createCrossProcessOperationMutex({ label: "[t]", lockFilePath: lockPath }); const release = mutex.tryAcquire(); release(); release(); // second call: silent no-op, must not throw assert.equal(fs.existsSync(lockPath), false); // The stale release closure must not free a NEWER holder's section. const release2 = mutex.tryAcquire(); release(); // old, already-spent release function assert.ok(fs.existsSync(lockPath), "a spent release must not remove the new holder's lock"); release2(); assert.equal(fs.existsSync(lockPath), false); } finally { fs.rmSync(dir, { recursive: true, force: true }); } }); test("release never unlinks a lock owned by someone else (token mismatch)", () => { const dir = makeTempDir(); try { const lockPath = lockPathIn(dir); const mutex = createCrossProcessOperationMutex({ label: "[t]", lockFilePath: lockPath }); const release = mutex.tryAcquire(); assert.ok(release); // Simulate the theft aftermath: the file now belongs to another owner // (it stole our expired lock and re-created it under its own token). writeLock(lockPath, { pid: 999999, token: "foreign-owner", acquiredAt: Date.now() }); release(); // must NOT unlink the foreign lock assert.ok(fs.existsSync(lockPath), "a foreign-owned lock must survive someone else's release call"); assert.equal(readLock(lockPath).token, "foreign-owner"); } finally { fs.rmSync(dir, { recursive: true, force: true }); } }); test("a live foreign lock (fresh acquiredAt, live pid) is never stolen from", async () => { const dir = makeTempDir(); try { const lockPath = lockPathIn(dir); const mutex = createCrossProcessOperationMutex({ label: "[t]", lockFilePath: lockPath, acquireTimeoutMs: 400, }); // Our own pid is trivially alive; the lock is fresh. The contender must // time out rather than steal. writeLock(lockPath, { pid: process.pid, token: "live-owner", acquiredAt: Date.now() }); await assert.rejects( () => mutex.acquire(), (err) => { assert.equal(err.code, "MUTEX_LOCK_TIMEOUT"); return true; }, "a live fresh owner must hold the lock" ); assert.equal(readLock(lockPath).token, "live-owner", "the live owner's lock must be untouched"); } finally { fs.rmSync(dir, { recursive: true, force: true }); } }); test("a stale lock (acquiredAt past the TTL) is stolen by tryAcquire — even from an alive pid", () => { const dir = makeTempDir(); try { const lockPath = lockPathIn(dir); const mutex = createCrossProcessOperationMutex({ label: "[t]", lockFilePath: lockPath, staleAfterMs: 45000, }); // process.pid is alive and will answer the kill(2) probe — only the TTL // makes this lock stealable. This pins the fail-safe direction: a wedged // (alive but stalled) holder is recovered by age alone. writeLock(lockPath, { pid: process.pid, token: "wedged-writer", acquiredAt: Date.now() - 45000 - 1000, }); const release = mutex.tryAcquire(); assert.ok(release, "an aged-out lock must be stolen"); assert.equal(readLock(lockPath).token !== "wedged-writer", true, "the stolen lock must carry the new owner"); release(); } finally { fs.rmSync(dir, { recursive: true, force: true }); } }); test("an update-style lock outlives an expired heartbeat, but not its owner", async (t) => { const dir = makeTempDir(); t.after(() => fs.rmSync(dir, { recursive: true, force: true })); const lockPath = lockPathIn(dir); const mutex = createCrossProcessOperationMutex({ lockFilePath: lockPath, staleAfterMs: 45000, respectLiveOwner: true }); writeLock(lockPath, { pid: process.pid, token: "live-writer", acquiredAt: Date.now() - 46000 }); assert.equal(mutex.tryAcquire(), null); assert.equal(readLock(lockPath).token, "live-writer"); const deadPid = await spawnDeadPid(); writeLock(lockPath, { pid: deadPid, token: "dead-writer", acquiredAt: Date.now() }); const release = mutex.tryAcquire(); assert.ok(release); release(); }); test("a lock owned by a dead pid (ESRCH) is stolen immediately", async () => { const dir = makeTempDir(); try { const lockPath = lockPathIn(dir); const mutex = createCrossProcessOperationMutex({ label: "[t]", lockFilePath: lockPath }); const deadPid = await spawnDeadPid(); writeLock(lockPath, { pid: deadPid, token: "dead-writer", acquiredAt: Date.now() }); const release = mutex.tryAcquire(); assert.ok(release, "a dead writer's lock must be stolen via the kill(2) probe"); assert.notEqual(readLock(lockPath).token, "dead-writer"); release(); } finally { fs.rmSync(dir, { recursive: true, force: true }); } }); test("a lock whose recorded startTicks no longer match its live pid is stolen (PID recycle recovery)", () => { if (!canReadProc) return; const dir = makeTempDir(); try { const lockPath = lockPathIn(dir); const mutex = createCrossProcessOperationMutex({ label: "[t]", lockFilePath: lockPath }); // Same (alive) pid, different start ticks than recorded: exactly what a // recycled PID looks like. kill(pid, 0) alone would read this as alive. writeLock(lockPath, { pid: process.pid, token: "recycled-owner", acquiredAt: Date.now(), startTicks: readProcStartTicks(process.pid) + 1000, }); const release = mutex.tryAcquire(); assert.ok(release, "a recycled-PID lock must be stolen promptly"); assert.notEqual(readLock(lockPath).token, "recycled-owner"); release(); } finally { fs.rmSync(dir, { recursive: true, force: true }); } }); test("a live foreign process holding the lock with matching startTicks is not stolen from", async () => { if (!canReadProc) return; const dir = makeTempDir(); try { const lockPath = lockPathIn(dir); const mutex = createCrossProcessOperationMutex({ label: "[t]", lockFilePath: lockPath, acquireTimeoutMs: 400, }); const child = childProcess.spawn(process.execPath, ["-e", "setInterval(() => {}, 250)"], { stdio: "ignore" }); try { let ticks = NaN; for (let i = 0; i < 100 && !Number.isFinite(ticks); i += 1) { try { ticks = readProcStartTicks(child.pid); } catch (_) { } if (!Number.isFinite(ticks)) await new Promise((resolve) => setTimeout(resolve, 20)); } assert.ok(Number.isFinite(ticks), "the child must be visible in /proc"); writeLock(lockPath, { pid: child.pid, token: "live-foreign-owner", acquiredAt: Date.now(), startTicks: ticks }); await assert.rejects( () => mutex.acquire(), (err) => { assert.equal(err.code, "MUTEX_LOCK_TIMEOUT"); return true; }, "a live foreign owner with matching start ticks must hold the lock" ); assert.equal(readLock(lockPath).token, "live-foreign-owner", "the live foreign lock must be untouched"); } finally { child.kill("SIGKILL"); } } finally { fs.rmSync(dir, { recursive: true, force: true }); } }); test("an unreadable (empty) lock file is treated as held until its mtime ages past the TTL", () => { const dir = makeTempDir(); try { const lockPath = lockPathIn(dir); const mutex = createCrossProcessOperationMutex({ label: "[t]", lockFilePath: lockPath, acquireTimeoutMs: 400, }); // Reproduces the create/write window: the O_EXCL create makes the file // visible before its owner info lands. Stealing it would break mutual // exclusion between the two writers. fs.writeFileSync(lockPath, "", "utf8"); const before = fs.statSync(lockPath).mtimeMs; const release = mutex.tryAcquire(); assert.equal(release, null, "a fresh unreadable lock must be treated as held, not stolen"); assert.ok(fs.existsSync(lockPath), "the unreadable lock must be left alone"); // Once the garbage ages out (writer died between create and write), the // mtime fallback makes it stealable again — self-healing. const ancient = new Date(before - 45000 - 1000); fs.utimesSync(lockPath, ancient, ancient); const release2 = mutex.tryAcquire(); assert.ok(release2, "aged-out garbage must be stolen via the mtime fallback"); release2(); } finally { fs.rmSync(dir, { recursive: true, force: true }); } }); test("heartbeat refreshes acquiredAt while the lock is held", async () => { const dir = makeTempDir(); try { const lockPath = lockPathIn(dir); const mutex = createCrossProcessOperationMutex({ label: "[t]", lockFilePath: lockPath, heartbeatMs: 100, staleAfterMs: 45000, }); const release = mutex.tryAcquire(); assert.ok(release); const first = readLock(lockPath); await new Promise((resolve) => setTimeout(resolve, 380)); // > 3 heartbeat ticks const second = readLock(lockPath); assert.equal(second.token, first.token, "the refresh must keep the owner token"); assert.equal(second.pid, first.pid); assert.ok( second.acquiredAt > first.acquiredAt, `acquiredAt must be refreshed by the heartbeat (${first.acquiredAt} -> ${second.acquiredAt})` ); release(); assert.equal(fs.existsSync(lockPath), false, "release must still remove the refreshed lock"); } finally { fs.rmSync(dir, { recursive: true, force: true }); } }); test("a stolen holder stops its heartbeat, logs once and NEVER re-creates the lock", async () => { const dir = makeTempDir(); try { const lockPath = lockPathIn(dir); const mutex = createCrossProcessOperationMutex({ label: "[t-stolen]", lockFilePath: lockPath, heartbeatMs: 80, staleAfterMs: 45000, }); const errors = []; const originalError = console.error; console.error = (...args) => errors.push(args.join(" ")); let release; try { release = mutex.tryAcquire(); assert.ok(release); // Another process steals our expired lock and re-creates it under its // own token (its pid must look alive so nothing steals it back). const theft = { pid: process.pid, token: "thief-owner", acquiredAt: Date.now() }; writeLock(lockPath, theft); await new Promise((resolve) => setTimeout(resolve, 400)); // ~5 heartbeat ticks } finally { console.error = originalError; } // The heartbeat must have detected the theft (ONE loud error), stopped, // and never re-created/refreshed the file: the thief's record survives // byte-identical for the whole window. assert.ok( errors.some((e) => e.includes("[t-stolen]") && /stolen from|vanished/.test(e)), `the holder must log the theft loudly; got: ${JSON.stringify(errors)}` ); const after = readLock(lockPath); assert.equal(after.token, "thief-owner", "the stolen lock must NOT be re-created by the old holder"); // Release after the theft must not unlink the new owner's lock either. const errors2 = []; console.error = (...args) => errors2.push(args.join(" ")); try { release(); } finally { console.error = originalError; } assert.ok(fs.existsSync(lockPath), "release must not remove the new owner's lock"); assert.equal(readLock(lockPath).token, "thief-owner"); } finally { fs.rmSync(dir, { recursive: true, force: true }); } }); test("acquire() eventually wins the lock a same-process holder releases", async () => { const dir = makeTempDir(); try { const lockPath = lockPathIn(dir); const mutex = createCrossProcessOperationMutex({ label: "[t]", lockFilePath: lockPath, acquireTimeoutMs: 5000, }); const release = mutex.tryAcquire(); assert.ok(release); setTimeout(release, 150); // free the lock while acquire() is polling const release2 = await mutex.acquire(); assert.ok(typeof release2 === "function", "acquire() must resolve with a release function"); release2(); // runExclusive wraps acquire/release around the section. const result = await mutex.runExclusive(async () => { assert.ok(fs.existsSync(lockPath), "the section must run under the lock"); return 42; }); assert.equal(result, 42); assert.equal(fs.existsSync(lockPath), false); } finally { fs.rmSync(dir, { recursive: true, force: true }); } }); test("REAL cross-process exclusivity: concurrent child processes never overlap critical sections", async () => { const dir = makeTempDir(); try { const lockPath = lockPathIn(dir); const logPath = path.join(dir, "section-log.txt"); fs.writeFileSync(logPath, "", "utf8"); const CHILDREN = 3; const ITERATIONS = 3; const HOLD_MS = 400; // Each child loops: tryAcquire (fail-fast, retry after 25ms) -> append // "start" -> hold 400ms WITH heartbeats -> append "end" -> release. // The shared log is the ground truth for overlap detection. const childSource = ` const fs = require("fs"); const { createCrossProcessOperationMutex } = require(process.env.CPM_UTIL_PATH); const mutex = createCrossProcessOperationMutex({ label: "[cpm-child-" + process.env.CPM_ID + "]", lockFilePath: process.env.CPM_LOCK_PATH, heartbeatMs: 100, staleAfterMs: 5000, acquireTimeoutMs: 30000, }); const log = process.env.CPM_LOG_PATH; const hold = Number(process.env.CPM_HOLD_MS); const iterations = Number(process.env.CPM_ITERS); let done = 0; (function attempt() { const release = mutex.tryAcquire(); if (!release) return setTimeout(attempt, 25); fs.appendFileSync(log, "start" + process.env.CPM_ID + "\\n"); setTimeout(() => { fs.appendFileSync(log, "end" + process.env.CPM_ID + "\\n"); release(); done += 1; if (done < iterations) setTimeout(attempt, 10); else process.exit(0); }, hold); })(); `; const children = []; for (let i = 1; i <= CHILDREN; i += 1) { children.push(new Promise((resolve, reject) => { const child = childProcess.spawn( process.execPath, ["-e", childSource], { stdio: ["ignore", "inherit", "inherit"], env: { ...process.env, CPM_UTIL_PATH: require.resolve("./cross-process-mutex"), CPM_LOCK_PATH: lockPath, CPM_LOG_PATH: logPath, CPM_ID: String(i), CPM_ITERS: String(ITERATIONS), CPM_HOLD_MS: String(HOLD_MS), }, } ); child.on("exit", (code) => (code === 0 ? resolve() : reject(new Error(`child ${i} exited ${code}`)))); child.on("error", reject); })); } await Promise.all(children); const lines = fs.readFileSync(logPath, "utf8").split("\n").filter(Boolean); assert.equal(lines.length, CHILDREN * ITERATIONS * 2, "every section must log its start and end"); let depth = 0; let starts = 0; let ends = 0; for (const line of lines) { if (line.startsWith("start")) { depth += 1; starts += 1; assert.equal(depth, 1, `section overlap detected at line "${line}": ${JSON.stringify(lines)}`); } else if (line.startsWith("end")) { depth -= 1; ends += 1; assert.ok(depth >= 0, `an end appeared without its start: "${line}"`); } else { assert.fail(`unexpected log line: ${line}`); } } assert.equal(starts, CHILDREN * ITERATIONS, "every child iteration must have acquired the lock"); assert.equal(ends, starts, "every acquisition must have been released"); assert.equal(depth, 0, "all sections must have closed"); assert.equal(fs.existsSync(lockPath), false, "the lock file must be gone after all children finish"); } finally { fs.rmSync(dir, { recursive: true, force: true }); } }); test("an unwritable/missing lock directory fails closed as busy (null) and logs loudly, never throwing", async () => { const dir = makeTempDir(); try { const missingDir = path.join(dir, "does-not-exist"); const lockPath = path.join(missingDir, "resource.lock"); const mutex = createCrossProcessOperationMutex({ label: "[t]", lockFilePath: lockPath }); const errors = []; const origError = console.error; console.error = (...a) => { errors.push(a.join(" ")); }; try { const release = mutex.tryAcquire(); assert.strictEqual(release, null, "tryAcquire must fail closed as busy (null), not throw"); assert.ok(errors.some((l) => l.includes("could not create lock file")), "the failure must be logged loudly"); // acquire() must exhaust its budget as MUTEX_LOCK_TIMEOUT — the fs // error itself must never escape into the caller. const mutex2 = createCrossProcessOperationMutex({ label: "[t2]", lockFilePath: lockPath, acquireTimeoutMs: 250 }); await assert.rejects( () => mutex2.acquire(), (err) => err && err.code === "MUTEX_LOCK_TIMEOUT", "acquire must surface a lock timeout, not an fs exception" ); } finally { console.error = origError; } } finally { fs.rmSync(dir, { recursive: true, force: true }); } }); test("steal path re-verification: a slower stealer never unlinks the faster one's freshly re-created lock", () => { // Deterministic two-holder TOCTOU reproduction: contender A reads the // stale lock, is preempted, contender B takes over with a LIVE record, // then A resumes — its steal must bail at the token re-verification // instead of unlinking B's fresh lock and holding alongside it. const dir = makeTempDir(); try { const lockPath = lockPathIn(dir); const stale = { pid: 999999999, token: "stale-token", acquiredAt: Date.now() - 60_000 }; writeLock(lockPath, stale); const mutexA = createCrossProcessOperationMutex({ label: "[A]", lockFilePath: lockPath, staleAfterMs: 5000, heartbeatMs: 50 }); const realReadFileSync = fs.readFileSync; let aReads = 0; fs.readFileSync = function (p, ...rest) { const result = realReadFileSync.call(fs, p, ...rest); // Swap in B's live record exactly between A's FIRST read (the stale // judgment) and A's re-verification read. if (p === lockPath && aReads === 0) { aReads = 1; writeLock(lockPath, { pid: process.pid, token: "live-token-b", acquiredAt: Date.now() }); } return result; }; const errors = []; const origError = console.error; console.error = (...a) => { errors.push(a.join(" ")); }; let releaseA = null; try { releaseA = mutexA.tryAcquire(); } finally { fs.readFileSync = realReadFileSync; console.error = origError; } assert.strictEqual(releaseA, null, "A must lose the steal at the re-verification, not hold alongside B"); const onDisk = readLock(lockPath); assert.strictEqual(onDisk.token, "live-token-b", "B's fresh lock must be untouched by A's steal attempt"); assert.ok(fs.existsSync(lockPath), "the re-created lock file must survive A's failed steal"); } finally { fs.rmSync(dir, { recursive: true, force: true }); } }); test("release re-verification: a late holder never unlinks a lock stolen from it between the checks", () => { const dir = makeTempDir(); try { const lockPath = lockPathIn(dir); const mutex = createCrossProcessOperationMutex({ label: "[t]", lockFilePath: lockPath, staleAfterMs: 5000, heartbeatMs: 50 }); const release = mutex.tryAcquire(); assert.ok(release, "the holder must acquire first"); // Simulate a theft (only possible when the holder was event-loop-blocked // past the TTL): the thief's fresh record replaces ours on disk. The // holder's release must NOT unlink the thief's live lock. writeLock(lockPath, { pid: process.pid, token: "thief-token", acquiredAt: Date.now() }); const errors = []; const origError = console.error; console.error = (...a) => { errors.push(a.join(" ")); }; try { release(); } finally { console.error = origError; } assert.ok(fs.existsSync(lockPath), "the thief's lock file must survive the late release"); assert.strictEqual(readLock(lockPath).token, "thief-token"); assert.ok(errors.some((l) => l.includes("release skipped")), "the skipped release must be logged"); } finally { fs.rmSync(dir, { recursive: true, force: true }); } });