306 lines
16 KiB
JavaScript
306 lines
16 KiB
JavaScript
"use strict";
|
|
|
|
// Behavioral tests for utils/scheduler-failure-streak.js — the
|
|
// consecutive-failure counter behind adpanel:scheduler-failure-streak. A
|
|
// Map-backed fake Redis stands in for the scheduler state client; the
|
|
// assertions pin the contract the worker relies on:
|
|
// 1. threshold resolution: env garbage -> default 20, clamped to [3,1000];
|
|
// 2. bump: INCR + sliding EXPIRE per bump, shouldDisable exactly at
|
|
// count >= threshold, untracked (and NEVER disable) without a client
|
|
// or repeat identity, Redis errors fail open;
|
|
// 3. reset: DEL, missing key is fine, null client is fine;
|
|
// 4. keys: namespaced, stable per repeat identity, distinct per schedule.
|
|
|
|
const test = require("node:test");
|
|
const assert = require("node:assert");
|
|
|
|
const {
|
|
DEFAULT_MAX_CONSECUTIVE_FAILURES,
|
|
DEFAULT_STREAK_TTL_SECONDS,
|
|
DEFAULT_BOOKKEEPING_DEADLINE_MS,
|
|
resolveSchedulerMaxConsecutiveFailures,
|
|
schedulerFailureStreakKey,
|
|
bumpSchedulerFailureStreak,
|
|
resetSchedulerFailureStreak,
|
|
raceWithDeadline,
|
|
} = require("./scheduler-failure-streak");
|
|
|
|
function fakeRedis() {
|
|
const store = new Map();
|
|
const calls = [];
|
|
return {
|
|
store,
|
|
calls,
|
|
async incr(key) {
|
|
calls.push(["incr", key]);
|
|
const next = (store.get(key) || 0) + 1;
|
|
store.set(key, next);
|
|
return next;
|
|
},
|
|
async expire(key, seconds) {
|
|
calls.push(["expire", key, seconds]);
|
|
if (!store.has(key)) return 0;
|
|
store.set(`${key}\u0000ttl`, seconds);
|
|
return 1;
|
|
},
|
|
async del(key) {
|
|
calls.push(["del", key]);
|
|
return store.delete(key) ? 1 : 0;
|
|
},
|
|
};
|
|
}
|
|
|
|
// Wrap the fake so specific commands can be made to reject (Redis outage).
|
|
function failingRedis(commandToFail) {
|
|
const real = fakeRedis();
|
|
const wrapped = { store: real.store, calls: real.calls };
|
|
for (const cmd of ["incr", "expire", "del"]) {
|
|
wrapped[cmd] = async (...args) => {
|
|
if (cmd === commandToFail) throw new Error(`${cmd} unavailable`);
|
|
return real[cmd](...args);
|
|
};
|
|
}
|
|
return wrapped;
|
|
}
|
|
|
|
// ─── 1. Threshold resolution ─────────────────────────────────────────────────
|
|
|
|
test("resolveSchedulerMaxConsecutiveFailures: default on absent/garbage input", () => {
|
|
assert.strictEqual(resolveSchedulerMaxConsecutiveFailures(undefined), DEFAULT_MAX_CONSECUTIVE_FAILURES);
|
|
assert.strictEqual(resolveSchedulerMaxConsecutiveFailures(null), DEFAULT_MAX_CONSECUTIVE_FAILURES);
|
|
assert.strictEqual(resolveSchedulerMaxConsecutiveFailures(""), DEFAULT_MAX_CONSECUTIVE_FAILURES);
|
|
assert.strictEqual(resolveSchedulerMaxConsecutiveFailures("abc"), DEFAULT_MAX_CONSECUTIVE_FAILURES);
|
|
});
|
|
|
|
test("resolveSchedulerMaxConsecutiveFailures: a parseable 0 clamps UP to the floor, never 'disable on first failure'", () => {
|
|
assert.strictEqual(resolveSchedulerMaxConsecutiveFailures("0"), 3, "0 parses fine — the clamp, not the default, must own it");
|
|
});
|
|
|
|
test("resolveSchedulerMaxConsecutiveFailures: clamps to [3, 1000] and passes valid values through", () => {
|
|
assert.strictEqual(resolveSchedulerMaxConsecutiveFailures("1"), 3, "below the floor — a nonsense env value must not make the disable near-immediate");
|
|
assert.strictEqual(resolveSchedulerMaxConsecutiveFailures("-5"), 3);
|
|
assert.strictEqual(resolveSchedulerMaxConsecutiveFailures("100000"), 1000, "above the ceiling — must stay reachable");
|
|
assert.strictEqual(resolveSchedulerMaxConsecutiveFailures("7"), 7);
|
|
assert.strictEqual(resolveSchedulerMaxConsecutiveFailures(" 20 "), 20, "whitespace-tolerant like every env parse in this codebase");
|
|
});
|
|
|
|
// ─── 2. Bump semantics ───────────────────────────────────────────────────────
|
|
|
|
test("bumpSchedulerFailureStreak: counts up, re-arms the sliding TTL on EVERY bump, disables exactly at the threshold", async () => {
|
|
const redis = fakeRedis();
|
|
const threshold = 3;
|
|
|
|
const first = await bumpSchedulerFailureStreak(redis, "sched-1", { threshold, ttlSeconds: 600 });
|
|
assert.deepStrictEqual(first, { tracked: true, count: 1, shouldDisable: false });
|
|
const second = await bumpSchedulerFailureStreak(redis, "sched-1", { threshold, ttlSeconds: 600 });
|
|
assert.deepStrictEqual(second, { tracked: true, count: 2, shouldDisable: false });
|
|
const third = await bumpSchedulerFailureStreak(redis, "sched-1", { threshold, ttlSeconds: 600 });
|
|
assert.deepStrictEqual(third, { tracked: true, count: 3, shouldDisable: true }, "count === threshold MUST disable (>=, not >)");
|
|
|
|
const expireCalls = redis.calls.filter(([cmd]) => cmd === "expire");
|
|
assert.strictEqual(expireCalls.length, 3, "the TTL must be re-armed on every bump (sliding 'consecutive' window)");
|
|
for (const [, , seconds] of expireCalls) assert.strictEqual(seconds, 600);
|
|
});
|
|
|
|
test("bumpSchedulerFailureStreak: distinct repeat identities never share a counter", async () => {
|
|
const redis = fakeRedis();
|
|
await bumpSchedulerFailureStreak(redis, "sched-A", { threshold: 2 });
|
|
const b = await bumpSchedulerFailureStreak(redis, "sched-B", { threshold: 2 });
|
|
assert.deepStrictEqual(b, { tracked: true, count: 1, shouldDisable: false }, "B must start at 1, not inherit A's failures");
|
|
});
|
|
|
|
test("bumpSchedulerFailureStreak: untracked WITHOUT a client or repeat identity — and never a disable", async () => {
|
|
const redis = fakeRedis();
|
|
for (const client of [null, undefined]) {
|
|
const outcome = await bumpSchedulerFailureStreak(client, "sched-1", { threshold: 1 });
|
|
assert.deepStrictEqual(outcome, { tracked: false, count: 0, shouldDisable: false }, "no scheduler Redis must mean keep-the-schedule, not disable");
|
|
}
|
|
for (const repeatKey of [null, undefined, ""]) {
|
|
const outcome = await bumpSchedulerFailureStreak(redis, repeatKey, { threshold: 1 });
|
|
assert.deepStrictEqual(outcome, { tracked: false, count: 0, shouldDisable: false }, `empty repeat identity (${JSON.stringify(repeatKey)}) must be untracked`);
|
|
assert.strictEqual(redis.calls.length, 0, "no Redis roundtrip may happen without an identity");
|
|
}
|
|
});
|
|
|
|
test("bumpSchedulerFailureStreak: Redis errors fail open (untracked, never throws, never disables)", async () => {
|
|
// incr failing: the count is not honestly known — untracked.
|
|
const incrFails = failingRedis("incr");
|
|
let outcome = await bumpSchedulerFailureStreak(incrFails, "sched-1", { threshold: 1 });
|
|
assert.deepStrictEqual(outcome, { tracked: false, count: 0, shouldDisable: false }, "a failed INCR means the count is not honestly known");
|
|
|
|
// expire failing: the count WAS honestly maintained — the streak stands,
|
|
// only the decay window failed to re-arm. With a realistic threshold a
|
|
// first failure must not disable.
|
|
const expireFails = failingRedis("expire");
|
|
outcome = await bumpSchedulerFailureStreak(expireFails, "sched-1", { threshold: 3 });
|
|
assert.deepStrictEqual(outcome, { tracked: true, count: 1, shouldDisable: false }, "a failed TTL re-arm must not discard the honest count");
|
|
});
|
|
|
|
test("bumpSchedulerFailureStreak: defaults apply when opts are omitted", async () => {
|
|
const redis = fakeRedis();
|
|
const twentieth = [];
|
|
let outcome;
|
|
for (let i = 0; i < DEFAULT_MAX_CONSECUTIVE_FAILURES; i += 1) {
|
|
outcome = await bumpSchedulerFailureStreak(redis, "sched-1");
|
|
twentieth.push(outcome.shouldDisable);
|
|
}
|
|
assert.strictEqual(outcome.count, DEFAULT_MAX_CONSECUTIVE_FAILURES);
|
|
assert.strictEqual(outcome.shouldDisable, true, "the default threshold must be reachable with no opts");
|
|
assert.ok(twentieth.slice(0, -1).every((v) => v === false), "no earlier bump may disable at the default threshold");
|
|
const expireCall = redis.calls.find(([cmd]) => cmd === "expire");
|
|
assert.strictEqual(expireCall[2], DEFAULT_STREAK_TTL_SECONDS);
|
|
});
|
|
|
|
// ─── 3. Reset semantics ──────────────────────────────────────────────────────
|
|
|
|
test("resetSchedulerFailureStreak: clears the counter so the next failure starts from 1", async () => {
|
|
const redis = fakeRedis();
|
|
await bumpSchedulerFailureStreak(redis, "sched-1", { threshold: 2 });
|
|
await bumpSchedulerFailureStreak(redis, "sched-1", { threshold: 2 }); // would disable
|
|
assert.strictEqual(await resetSchedulerFailureStreak(redis, "sched-1"), true);
|
|
const after = await bumpSchedulerFailureStreak(redis, "sched-1", { threshold: 2 });
|
|
assert.deepStrictEqual(after, { tracked: true, count: 1, shouldDisable: false }, "one success must fully reset the consecutive streak");
|
|
});
|
|
|
|
test("resetSchedulerFailureStreak: missing key, blank identity and null client are all safe no-ops", async () => {
|
|
const redis = fakeRedis();
|
|
assert.strictEqual(await resetSchedulerFailureStreak(redis, "never-bumped"), true, "a missing key is a successful reset — the counter is absent either way");
|
|
assert.strictEqual(await resetSchedulerFailureStreak(redis, ""), false);
|
|
assert.strictEqual(await resetSchedulerFailureStreak(null, "sched-1"), false);
|
|
const failing = failingRedis("del");
|
|
assert.strictEqual(await resetSchedulerFailureStreak(failing, "sched-1"), false, "a Redis error on reset must not throw");
|
|
});
|
|
|
|
// ─── 4. Key derivation ───────────────────────────────────────────────────────
|
|
|
|
test("schedulerFailureStreakKey: namespaced, stable per identity, distinct across identities, bounded length", () => {
|
|
const keyA1 = schedulerFailureStreakKey("mysched::repeat:abc:0 * * * *");
|
|
const keyA2 = schedulerFailureStreakKey("mysched::repeat:abc:0 * * * *");
|
|
const keyB = schedulerFailureStreakKey("othersched::repeat:abc:0 * * * *");
|
|
assert.ok(keyA1.startsWith("adpanel:scheduler-failstreak:"), "the key must live in its own namespace (never collides with adpanel:scheduler-run: or session keys)");
|
|
assert.strictEqual(keyA1, keyA2, "the same repeat identity must always map to the same counter");
|
|
assert.notStrictEqual(keyA1, keyB, "different schedules must never share a counter");
|
|
assert.ok(keyA1.length < 80, "the hash bounds the key length no matter how long the name JSON is");
|
|
assert.match(keyA1, /^adpanel:scheduler-failstreak:[0-9a-f]{32}$/, "the key is exactly namespace + 32 hex chars — safe against any repeat-identity content");
|
|
});
|
|
|
|
// ─── 5. Real-Redis expiry semantics (the 24h-TTL bug class) ──────────────────
|
|
// A plain Map fake never evicts, so it cannot see the flaw where an interval
|
|
// >= TTL schedule's key EXPIRES before its next failure and the count
|
|
// restarts. This fake honors the TTL on a controllable clock.
|
|
|
|
function expiringRedis(clock) {
|
|
const entries = new Map(); // key -> { value, expiresAt }
|
|
return {
|
|
async incr(key) {
|
|
const now = clock();
|
|
const entry = entries.get(key);
|
|
if (entry && entry.expiresAt !== null && now >= entry.expiresAt) {
|
|
entries.delete(key); // real Redis: lazy expiry
|
|
}
|
|
const next = (entries.get(key)?.value || 0) + 1;
|
|
entries.set(key, { value: next, expiresAt: entries.get(key)?.expiresAt ?? null });
|
|
return next;
|
|
},
|
|
async expire(key, seconds) {
|
|
const entry = entries.get(key);
|
|
if (!entry) return 0;
|
|
entry.expiresAt = clock() + seconds * 1000;
|
|
return 1;
|
|
},
|
|
async del(key) {
|
|
return entries.delete(key) ? 1 : 0;
|
|
},
|
|
};
|
|
}
|
|
|
|
const DAY_MS = 24 * 60 * 60 * 1000;
|
|
|
|
test("expiry semantics: a DAILY schedule accumulates across consecutive bad days (TTL must exceed the interval)", async () => {
|
|
let now = 1_000_000;
|
|
const redis = expiringRedis(() => now);
|
|
let outcome;
|
|
for (let day = 0; day < DEFAULT_MAX_CONSECUTIVE_FAILURES; day += 1) {
|
|
outcome = await bumpSchedulerFailureStreak(redis, "daily-sched", { threshold: DEFAULT_MAX_CONSECUTIVE_FAILURES });
|
|
now += DAY_MS + 60_000; // next fire strictly after the previous one + ε
|
|
}
|
|
assert.strictEqual(outcome.count, DEFAULT_MAX_CONSECUTIVE_FAILURES, "the daily streak must accumulate across days — a TTL shorter than the interval silently reset it to 1 forever");
|
|
assert.strictEqual(outcome.shouldDisable, true, "20 consecutive bad days must disable a daily schedule");
|
|
});
|
|
|
|
test("expiry semantics: a gap LONGER than the TTL starts a fresh streak", async () => {
|
|
let now = 1_000_000;
|
|
const redis = expiringRedis(() => now);
|
|
await bumpSchedulerFailureStreak(redis, "sched", { threshold: 3 });
|
|
await bumpSchedulerFailureStreak(redis, "sched", { threshold: 3 });
|
|
now += (DEFAULT_STREAK_TTL_SECONDS * 1000) + 60_000; // silence longer than the whole TTL
|
|
const outcome = await bumpSchedulerFailureStreak(redis, "sched", { threshold: 3 });
|
|
assert.deepStrictEqual(outcome, { tracked: true, count: 1, shouldDisable: false }, "a schedule silent beyond the TTL must start over — only genuinely consecutive failures count");
|
|
});
|
|
|
|
test("expiry semantics: the default TTL exceeds every practical recurrence gap", () => {
|
|
assert.ok(DEFAULT_STREAK_TTL_SECONDS > 31 * 24 * 60 * 60, "the TTL must exceed the longest monthly gap (31 days) — shorter TTLs made daily/weekly/monthly schedules unable to ever reach the threshold");
|
|
});
|
|
|
|
// ─── 6. raceWithDeadline (bookkeeping must never wedge a finished job) ──────
|
|
|
|
test("raceWithDeadline: returns the value when the promise settles inside the deadline, and clears the pending deadline timer", async () => {
|
|
const originalSetTimeout = globalThis.setTimeout;
|
|
let capturedTimer = null;
|
|
globalThis.setTimeout = (fn, ms, ...rest) => {
|
|
capturedTimer = originalSetTimeout(fn, ms, ...rest);
|
|
return capturedTimer;
|
|
};
|
|
try {
|
|
const value = await raceWithDeadline(Promise.resolve({ ok: true }), 1000, null);
|
|
assert.deepStrictEqual(value, { ok: true });
|
|
} finally {
|
|
globalThis.setTimeout = originalSetTimeout;
|
|
}
|
|
// The race settled while the 1000ms deadline timer was still pending —
|
|
// this is the leak-sensitive path (the deadline path's timer has already
|
|
// fired, so only here can a missed clearTimeout be detected): the finally
|
|
// must have destroyed the handle or every awaited call would hold the
|
|
// event loop for the full deadline.
|
|
await new Promise((resolve) => setImmediate(resolve));
|
|
assert.ok(capturedTimer && capturedTimer._destroyed, "the losing deadline timer must be destroyed once the race settles");
|
|
});
|
|
|
|
test("raceWithDeadline: a hung promise resolves to the fallback after the deadline and the timer is cleared", async () => {
|
|
const started = Date.now();
|
|
const never = new Promise(() => { }); // simulates node-redis offline-queue hang
|
|
const result = await raceWithDeadline(never, 50, { tracked: false, count: 0, shouldDisable: false });
|
|
assert.deepStrictEqual(result, { tracked: false, count: 0, shouldDisable: false }, "the deadline must release the caller");
|
|
assert.ok(Date.now() - started < 2000, "the deadline must actually bound the wait");
|
|
// Canary turns only: on this path the deadline timer has ALREADY fired, so
|
|
// these turns cannot detect a missed clearTimeout — the fast-settle test
|
|
// above owns the timer-clearance assertion with a captured handle.
|
|
await new Promise((resolve) => setImmediate(resolve));
|
|
await new Promise((resolve) => setImmediate(resolve));
|
|
});
|
|
|
|
test("raceWithDeadline: a LATE rejection after the deadline never surfaces as an unhandled rejection", async () => {
|
|
let rejectLater;
|
|
const lateRejector = new Promise((_, reject) => { rejectLater = reject; });
|
|
const result = await raceWithDeadline(lateRejector, 30, null);
|
|
assert.strictEqual(result, null, "the deadline fires first");
|
|
// Give the rejection time to land after the race settled.
|
|
await new Promise((resolve) => setTimeout(resolve, 60));
|
|
rejectLater(new Error("too late to matter"));
|
|
await new Promise((resolve) => setTimeout(resolve, 60));
|
|
// Reaching this line without an unhandledRejection crash is the assertion.
|
|
assert.ok(true);
|
|
});
|
|
|
|
test("raceWithDeadline: a fast rejection resolves to the fallback (fail-open), never throws", async () => {
|
|
const result = await raceWithDeadline(Promise.reject(new Error("boom")), 1000, { tracked: false });
|
|
assert.deepStrictEqual(result, { tracked: false });
|
|
});
|
|
|
|
test("raceWithDeadline: defaults apply (default deadline, null fallback)", async () => {
|
|
const started = Date.now();
|
|
const result = await raceWithDeadline(new Promise(() => { }));
|
|
assert.strictEqual(result, null);
|
|
assert.ok(Date.now() - started >= DEFAULT_BOOKKEEPING_DEADLINE_MS - 50, "the default deadline is the module constant");
|
|
});
|