"use strict"; // Unit tests for the ONE shared stat-key revalidation helper // (utils/config-revalidation.js): hot-swapped config state is worker-local in // a multi-worker deployment, so every consumer re-stats its backing file and // reloads on change — worker-local memory is a cache of the file, never the // source of truth. These tests pin the helper's contract: // - stat-key (mtime+size) change → reload // - same key → cached value, no reload // - load failure → last known-good state preserved + one warn per episode // - put() seeds a save this worker performed without a reload // The per-consumer wiring (maintenance / captcha / global alerts / // dashboard-assistant config) is pinned in config-stat-revalidation-consumers.test.js. 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 { createStatKeyedCache } = require("../utils/config-revalidation"); const { atomicWriteFileSync } = require("../utils/atomic-file"); function makeTmpDir() { return fs.mkdtempSync(path.join(os.tmpdir(), "adpanel-config-reval-")); } // Rename-replacement writers (atomicWriteFileSync) bump mtime to "now"; this // helper forces an explicit fresh mtime so the test cannot flake on a // filesystem with coarse (1s) mtime granularity. function freshMtime(file) { const now = new Date(Date.now() + Math.floor(Math.random() * 1e9)); fs.utimesSync(file, now, now); } function writeConfig(file, content) { fs.writeFileSync(file, content, "utf8"); freshMtime(file); } test("stat-key change reloads on the next get (two worker instances over one file)", () => { const dir = makeTmpDir(); try { const file = path.join(dir, "config.json"); writeConfig(file, JSON.stringify({ enabled: false })); // "Worker A" and "worker B": two independent cache instances sharing the // file the way pm2 cluster workers share the filesystem. let loadsA = 0; let loadsB = 0; const workerA = createStatKeyedCache({ filePath: file, load: () => { loadsA += 1; return JSON.parse(fs.readFileSync(file, "utf8")); }, ttlMs: 60_000, label: "[a]", }); const workerB = createStatKeyedCache({ filePath: file, load: () => { loadsB += 1; return JSON.parse(fs.readFileSync(file, "utf8")); }, ttlMs: 60_000, label: "[b]", }); assert.deepEqual(workerA.get(), { enabled: false }); assert.deepEqual(workerB.get(), { enabled: false }); assert.equal(loadsA, 1); assert.equal(loadsB, 1); // Worker A "saves": file replaced via atomic rename semantics. writeConfig(file, JSON.stringify({ enabled: true })); // Worker B's next read revalidates and sees the sibling's write — the // whole point of the pattern. assert.deepEqual(workerB.get(), { enabled: true }); assert.equal(loadsB, 2); // Worker A, which performed the write through put(), needs no reload. assert.equal(loadsA, 1); } finally { fs.rmSync(dir, { recursive: true, force: true }); } }); test("same stat key serves the cached value without reloading", () => { const dir = makeTmpDir(); try { const file = path.join(dir, "config.json"); writeConfig(file, '{"a":1}'); let loads = 0; const cache = createStatKeyedCache({ filePath: file, load: () => { loads += 1; return JSON.parse(fs.readFileSync(file, "utf8")); }, ttlMs: 60_000, label: "[t]", }); assert.deepEqual(cache.get(), { a: 1 }); assert.deepEqual(cache.get(), { a: 1 }); assert.equal(loads, 1, "unchanged mtime+size must not reload"); } finally { fs.rmSync(dir, { recursive: true, force: true }); } }); test("atomic replacement invalidates a same-size same-mtime cached configuration", () => { const dir = makeTmpDir(); let originalFd; try { const file = path.join(dir, "config.json"); const stamp = new Date(1700000000000); atomicWriteFileSync(file, '{"a":1}'); fs.utimesSync(file, stamp, stamp); originalFd = fs.openSync(file, "r"); const before = fs.statSync(file); let loads = 0; const cache = createStatKeyedCache({ filePath: file, load: () => { loads += 1; return JSON.parse(fs.readFileSync(file, "utf8")); }, ttlMs: 60_000, }); assert.deepEqual(cache.get(), { a: 1 }); atomicWriteFileSync(file, '{"a":2}'); fs.utimesSync(file, stamp, stamp); const after = fs.statSync(file); assert.equal(after.mtimeMs, before.mtimeMs); assert.equal(after.size, before.size); assert.notEqual(after.ino, before.ino); assert.deepEqual(cache.get(), { a: 2 }); assert.equal(loads, 2); } finally { if (originalFd !== undefined) fs.closeSync(originalFd); fs.rmSync(dir, { recursive: true, force: true }); } }); test("a size change alone triggers a reload (coarse-mtime armor)", () => { const dir = makeTmpDir(); try { const file = path.join(dir, "config.json"); writeConfig(file, '{"a":1}'); let loads = 0; const cache = createStatKeyedCache({ filePath: file, load: () => { loads += 1; return JSON.parse(fs.readFileSync(file, "utf8")); }, ttlMs: 0, label: "[t]", }); cache.get(); // Different-length content, mtime pinned back to the recorded value: only // the SIZE field differs, and that alone must invalidate the cache (the // hardening the mtime-only check lacked). const before = fs.statSync(file).mtimeMs; fs.writeFileSync(file, '{"a":22}', "utf8"); fs.utimesSync(file, new Date(before), new Date(before)); assert.deepEqual(cache.get(), { a: 22 }); assert.equal(loads, 2); } finally { fs.rmSync(dir, { recursive: true, force: true }); } }); test("an mtime change alone triggers a reload (same-size rewrite)", () => { const dir = makeTmpDir(); try { const file = path.join(dir, "config.json"); writeConfig(file, '{"a":1}'); let loads = 0; const cache = createStatKeyedCache({ filePath: file, load: () => { loads += 1; return JSON.parse(fs.readFileSync(file, "utf8")); }, ttlMs: 0, label: "[t]", }); cache.get(); // Byte-LENGTH-identical rewrite ("enabled": true → false is same-size on // many payloads): mtime is the only field that moves. const before = fs.statSync(file).mtimeMs; fs.writeFileSync(file, '{"a":2}', "utf8"); assert.notEqual(fs.statSync(file).size, fs.statSync(file).size === 7 ? 8 : 7); // same length fs.utimesSync(file, new Date(before + 5000), new Date(before + 5000)); assert.deepEqual(cache.get(), { a: 2 }); assert.equal(loads, 2); } finally { fs.rmSync(dir, { recursive: true, force: true }); } }); test("TTL expiry forces a reload even when the stat key is unchanged", () => { const dir = makeTmpDir(); try { const file = path.join(dir, "config.json"); writeConfig(file, '{"a":1}'); let loads = 0; const cache = createStatKeyedCache({ filePath: file, load: () => { loads += 1; return JSON.parse(fs.readFileSync(file, "utf8")); }, ttlMs: 15, label: "[t]", }); // Pin the mtime BEFORE the first get() (utimesSync via Date truncates // sub-ms precision, so the recorded key must come from the same pinned // value the same-key rewrite below restores). const pinnedDate = new Date(Math.floor(fs.statSync(file).mtimeMs)); fs.utimesSync(file, pinnedDate, pinnedDate); cache.get(); cache.get(); assert.equal(loads, 1); // Byte-identical rewrite with the mtime pinned back (a same-key save — // the only scenario where the stat key cannot see a real write) inside // the TTL window: served from cache. fs.writeFileSync(file, '{"a":1}', "utf8"); fs.utimesSync(file, pinnedDate, pinnedDate); cache.get(); assert.equal(loads, 1); // Past the TTL: the backstop re-reads despite the identical stat key — // the residual hole no stat can see (byte-identical save / hidden mtime). const deadline = Date.now() + 1000; while (Date.now() < deadline - 20) { /* busy-spin past the 15ms TTL */ } assert.deepEqual(cache.get(), { a: 1 }); assert.equal(loads, 2); } finally { fs.rmSync(dir, { recursive: true, force: true }); } }); test("ttlMs 0 disables the TTL backstop (stat-key-only revalidation)", () => { const dir = makeTmpDir(); try { const file = path.join(dir, "config.json"); writeConfig(file, '{"a":1}'); let loads = 0; const cache = createStatKeyedCache({ filePath: file, load: () => { loads += 1; return JSON.parse(fs.readFileSync(file, "utf8")); }, ttlMs: 0, label: "[t]", }); cache.get(); const deadline = Date.now() + 40; while (Date.now() < deadline) { /* busy-spin past any short TTL */ } cache.get(); assert.equal(loads, 1, "no TTL backstop reload without a stat-key change"); } finally { fs.rmSync(dir, { recursive: true, force: true }); } }); test("load failure keeps the last known-good state and warns once per episode", () => { const dir = makeTmpDir(); try { const file = path.join(dir, "config.json"); writeConfig(file, '{"a":1}'); let shouldThrow = false; let loads = 0; const cache = createStatKeyedCache({ filePath: file, load: () => { loads += 1; if (shouldThrow) throw new Error("disk gone"); return JSON.parse(fs.readFileSync(file, "utf8")); }, ttlMs: 0, label: "[t]", }); const good = cache.get(); const warnings = []; const originalWarn = console.warn; console.warn = (...args) => warnings.push(args.join(" ")); try { // Force a reload attempt with a failing load: the warm cache keeps // serving the last known-good value. shouldThrow = true; writeConfig(file, '{"a":2}'); assert.deepEqual(cache.get(), good, "a failed re-read must never wipe working config"); assert.equal(loads, 2); // Every failed attempt during the SAME episode stays silent. writeConfig(file, '{"a":3}'); assert.deepEqual(cache.get(), good); assert.equal(loads, 3); assert.equal(warnings.length, 1, "one warn per failure episode, not one per request"); // A successful reload re-arms the episode: the NEXT failure warns again. shouldThrow = false; writeConfig(file, '{"a":4}'); assert.deepEqual(cache.get(), { a: 4 }); assert.equal(warnings.length, 1); shouldThrow = true; writeConfig(file, '{"a":5}'); assert.deepEqual(cache.get(), { a: 4 }, "still the last known-good value"); assert.equal(warnings.length, 2); assert.match(warnings[0], /\[t\]/); assert.ok(!warnings[0].includes("config content"), "warn must not leak file content"); } finally { console.warn = originalWarn; } } finally { fs.rmSync(dir, { recursive: true, force: true }); } }); test("a vanished file forces a reload attempt through the {-1,-1} stat key", () => { const dir = makeTmpDir(); try { const file = path.join(dir, "config.json"); writeConfig(file, '{"a":1}'); let loads = 0; const cache = createStatKeyedCache({ filePath: file, load: () => { loads += 1; return { fallback: loads }; }, ttlMs: 0, label: "[t]", }); assert.deepEqual(cache.get(), { fallback: 1 }); fs.rmSync(file, { force: true }); // The {-1,-1} key mismatches the recorded real values → reload attempt; // the caller's load defines the fail-safe shape for a missing file. assert.deepEqual(cache.get(), { fallback: 2 }); // Now stable (both keys {-1,-1}): no repeat reloads. assert.deepEqual(cache.get(), { fallback: 2 }); assert.equal(loads, 2); } finally { fs.rmSync(dir, { recursive: true, force: true }); } }); test("cold-cache load failure surfaces the error instead of fabricating a value", () => { const dir = makeTmpDir(); try { const file = path.join(dir, "config.json"); const cache = createStatKeyedCache({ filePath: file, load: () => { throw new Error("boom"); }, ttlMs: 0, label: "[t]", }); assert.throws(() => cache.get(), /boom/); } finally { fs.rmSync(dir, { recursive: true, force: true }); } }); test("put seeds a save this worker performed without triggering a load", () => { const dir = makeTmpDir(); try { const file = path.join(dir, "config.json"); writeConfig(file, '{"a":1}'); let loads = 0; const cache = createStatKeyedCache({ filePath: file, load: () => { loads += 1; return JSON.parse(fs.readFileSync(file, "utf8")); }, ttlMs: 60_000, label: "[t]", }); // The writer shape: replace the file, then seed the cache with the value // just written. put() re-stats so the key pairs with the post-write file. fs.writeFileSync(file, '{"a":2}', "utf8"); freshMtime(file); cache.put({ a: 2 }); assert.deepEqual(cache.get(), { a: 2 }); assert.equal(loads, 0, "the writing worker must not re-read its own save"); // A sibling's later write still revalidates normally. writeConfig(file, '{"a":3}'); assert.deepEqual(cache.get(), { a: 3 }); assert.equal(loads, 1); } finally { fs.rmSync(dir, { recursive: true, force: true }); } }); test("put with an explicit key pairs the value with that captured stat", () => { const dir = makeTmpDir(); try { const file = path.join(dir, "config.json"); writeConfig(file, '{"a":1}'); let loads = 0; const cache = createStatKeyedCache({ filePath: file, load: () => { loads += 1; return { read: loads }; }, ttlMs: 60_000, label: "[t]", }); // The dashboard-assistant save captures the stat BEFORE its readback // verification and seeds the verified value with that key: a sibling // writing byte-identical content in between only costs one spurious // reload, whereas pairing with a LATER stat could pin stale content. const preReadbackKey = cache.statKey(); cache.put({ saved: true }, preReadbackKey); assert.deepEqual(cache.get(), { saved: true }); assert.equal(loads, 0); // A stale/fabricated key mismatches the real file → reload on next get. cache.put({ stale: true }, { mtimeMs: 12345, size: 999 }); assert.deepEqual(cache.get(), { read: 1 }); assert.equal(loads, 1); } finally { fs.rmSync(dir, { recursive: true, force: true }); } }); test("statKey never throws and reports {-1,-1} for a missing file", () => { const dir = makeTmpDir(); try { const file = path.join(dir, "missing.json"); const cache = createStatKeyedCache({ filePath: file, load: () => ({}), ttlMs: 0, label: "[t]" }); assert.deepEqual(cache.statKey(), { mtimeMs: -1, size: -1 }); writeConfig(file, "{}"); const key = cache.statKey(); assert.equal(typeof key.mtimeMs, "number"); assert.equal(typeof key.size, "number"); assert.ok(key.mtimeMs >= 0); } finally { fs.rmSync(dir, { recursive: true, force: true }); } }); test("rejects a construction without a load callback or filePath", () => { assert.throws(() => createStatKeyedCache({ load: () => ({}) }), /filePath/); assert.throws(() => createStatKeyedCache({ filePath: "/tmp/x" }), /load/); });