Files
Kelx/tests/scheduler-redis-decouple.test.js
T
2026-11-30 16:32:37 +00:00

513 lines
29 KiB
JavaScript
Raw Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
"use strict";
// Structure pins for the scheduler Redis decoupling + read brake + failure
// streak (adpanel:scheduler-redis-decouple, adpanel:scheduler-read-brake,
// adpanel:scheduler-failure-streak).
//
// index.js is a ~56k-line application bundle (module side effects, DB and
// network at require time — never require() it from a test), so these tests
// pin the fixes structurally on well-anchored source windows, matching the
// convention of tests/agent-job-suspension-gate.test.js and
// tests/destructive-route-guards.test.js.
//
// The regression each pin exists to prevent:
// 1. any scheduler-side state riding the SESSION store's redisClient again
// (null under SESSION_STORE=file => the mutate limiter degrades to a
// per-process MemoryStore and the stall run-marker fails open forever);
// 2. the tasks list route losing its always-on read brake (fleet-wide
// 50k-job scan reachable by any scheduler_access holder);
// 3. the failure-streak hook dropping out of the worker's catch or the
// completed-path reset dropping out (the streak would either never
// disable a permanently broken schedule or disable healthy ones).
const test = require("node:test");
const assert = require("node:assert");
const fs = require("node:fs");
const path = require("node:path");
const ROOT = path.join(__dirname, "..");
const INDEX_SRC = fs.readFileSync(path.join(ROOT, "index.js"), "utf8");
function functionWindow(src, anchor, label) {
const start = src.indexOf(anchor);
assert.notStrictEqual(start, -1, `${label}: anchor not found: ${anchor}`);
const end = src.indexOf("\n}", start);
assert.notStrictEqual(end, -1, `${label}: no closing brace after: ${anchor}`);
return src.slice(start, end + 2);
}
// Window from an anchor to an explicit end anchor — deterministic slicing
// that survives unrelated edits elsewhere in the bundle.
function windowBetween(src, startAnchor, endAnchor, label) {
const start = src.indexOf(startAnchor);
assert.notStrictEqual(start, -1, `${label}: start anchor not found: ${startAnchor}`);
const end = src.indexOf(endAnchor, start + startAnchor.length);
assert.notStrictEqual(end, -1, `${label}: end anchor not found after start: ${endAnchor}`);
return src.slice(start, end);
}
// ─── 1. The dedicated scheduler Redis client ─────────────────────────────────
test("schedulerStateRedis is created from the SCHEDULER's URL+enable gate, never from the session store", () => {
// Pin the two CODE lines only — the explanatory comment above them
// legitimately names SESSION_STORE while documenting the bug.
const declLine = INDEX_SRC.split("\n").find((line) => line.includes("const schedulerStateRedis = getSchedulerStateRedis("));
assert.ok(declLine, "the scheduler state client declaration must exist");
assert.ok(
declLine.includes("getSchedulerStateRedis(SCHEDULER_ENABLED && SCHEDULER_REDIS_URL ? SCHEDULER_REDIS_URL : \"\")"),
"the scheduler state client must be gated by SCHEDULER_ENABLED && SCHEDULER_REDIS_URL — a null result must mean 'no scheduler Redis', never 'sessions are file-backed'"
);
assert.ok(
!declLine.includes("SESSION_STORE"),
"the scheduler client's gate must not read SESSION_STORE — that coupling is the bug being fixed"
);
const clientAt = INDEX_SRC.indexOf("const schedulerStateRedis = getSchedulerStateRedis(");
const urlAt = INDEX_SRC.indexOf("const SCHEDULER_REDIS_URL = REDIS_URL || process.env.SCHEDULER_REDIS_URL");
assert.notStrictEqual(urlAt, -1, "SCHEDULER_REDIS_URL must exist");
assert.ok(clientAt > urlAt, "the client must be created AFTER the scheduler URL is resolved (it is gated on it)");
});
test("the stall-guard run-marker claims through the scheduler's own client — never redisClient", () => {
const body = windowBetween(
INDEX_SRC,
"const runClaimKey = `adpanel:scheduler-run:${job.id}`;",
"if (alreadyRunning) {",
"stall-guard run-marker"
);
assert.ok(
body.includes("schedulerStateRedis.set(runClaimKey, \"1\", { NX: true, EX: 900 })"),
"the run-marker claim must use the scheduler's dedicated client — redisClient is null under SESSION_STORE=file and the claim used to fail open on every job"
);
assert.ok(
!body.includes("redisClient.set("),
"no session-client .set may remain in the run-marker"
);
assert.ok(
body.includes("if (!schedulerStateRedis) throw new Error(\"scheduler state Redis unavailable\");"),
"a null scheduler client must land in the EXISTING fail-open catch with a clear message, not an opaque TypeError"
);
});
test("the completed-path run-marker cleanup rides the scheduler's own client", () => {
const body = windowBetween(
INDEX_SRC,
"schedulerWorker.on(\"completed\", (job, result) => {",
"schedulerWorker.on(\"failed\"",
"completed handler"
);
assert.ok(
body.includes("schedulerStateRedis.del(`adpanel:scheduler-run:${job.id}`)"),
"the run-marker cleanup must use the scheduler's dedicated client"
);
assert.ok(
!body.includes("redisClient.del("),
"no session-client cleanup may remain — under SESSION_STORE=file it used to skip the cleanup entirely"
);
});
// ─── 2. The scheduler limiters ───────────────────────────────────────────────
test("schedulerMutateRateLimiter exists exactly once, rides the scheduler client, and sits after SCHEDULER_REDIS_URL", () => {
const declCount = INDEX_SRC.split("const schedulerMutateRateLimiter = rateLimit({").length - 1;
assert.strictEqual(declCount, 1, "the limiter must be defined exactly once (it was relocated, not forked)");
assert.ok(
!INDEX_SRC.includes('redisClient ? buildSharedRateLimitRedisStore("scheduler-mutate:'),
"the session-client wiring must be gone — that is the MemoryStore-degradation bug"
);
const decl = functionWindow(INDEX_SRC, "const schedulerMutateRateLimiter = rateLimit({", "schedulerMutateRateLimiter");
assert.ok(
decl.includes("store: schedulerStateRedis ? buildSharedRateLimitRedisStore(\"scheduler-mutate:\", 5 * 60 * 1000, schedulerStateRedis) : undefined"),
"the mutate limiter's store must ride the scheduler's dedicated client with its own \"scheduler-mutate:\" prefix"
);
assert.ok(
decl.includes("windowMs: 60 * 1000,") && decl.includes("max: 30,"),
"the mutate brake's strictness is part of the contract (30/min) — a wiring-correct limiter with a dropped ceiling is not the reviewed brake"
);
assert.ok(decl.includes("passOnStoreError: true"), "the mutate brake must fail open — abuse brake, not an auth control");
// adpanel:scheduler-mutate-brake — the sessionless skip was removed: under
// the shipped default (security.rate_limiting false) it handed anonymous
// POST/DELETE floods to global throttles that are no-ops, so unauth traffic
// reached the route auth with no brake at all (the fs-read-brake lesson).
assert.ok(!decl.includes("skip: (req)"), "the mutate brake must NOT skip sessionless requests — an anonymous flood must not hit no brake at all");
const limiterAt = INDEX_SRC.indexOf("const schedulerMutateRateLimiter = rateLimit({");
const urlAt = INDEX_SRC.indexOf("const SCHEDULER_REDIS_URL = REDIS_URL || process.env.SCHEDULER_REDIS_URL");
const postRouteAt = INDEX_SRC.indexOf("app.post(\"/api/scheduler/:serverName/tasks\"");
const deleteRouteAt = INDEX_SRC.indexOf("app.delete(\"/api/scheduler/:serverName/tasks/:taskId\"");
assert.ok(limiterAt > urlAt, "the limiter must be defined after SCHEDULER_REDIS_URL (its store needs the scheduler client)");
assert.ok(limiterAt < postRouteAt && limiterAt < deleteRouteAt, "the limiter must be defined before both mutating routes execute at module load");
});
test("the scheduler POST/DELETE routes still mount the mutate limiter", () => {
assert.ok(
INDEX_SRC.includes("app.post(\"/api/scheduler/:serverName/tasks\", schedulerMutateRateLimiter, async"),
"the POST create route must keep its brake"
);
assert.ok(
INDEX_SRC.includes("app.delete(\"/api/scheduler/:serverName/tasks/:taskId\", schedulerMutateRateLimiter, async"),
"the DELETE route must keep its brake"
);
});
test("schedulerTasksReadRateLimiter: always-on read brake on the tasks list, keyed per account, own prefix", () => {
const decl = functionWindow(INDEX_SRC, "const schedulerTasksReadRateLimiter = rateLimit({", "schedulerTasksReadRateLimiter");
assert.ok(
decl.includes("store: schedulerStateRedis ? buildSharedRateLimitRedisStore(\"scheduler-read:\", 10 * 60 * 1000, schedulerStateRedis) : undefined"),
"the read brake must use its own \"scheduler-read:\" prefix on the scheduler's dedicated client (one store instance + distinct prefix per limiter)"
);
assert.ok(decl.includes("passOnStoreError: true"), "the read brake must fail open — abuse brake, not an auth control");
assert.ok(
decl.includes("windowMs: 10 * 60 * 1000,") && decl.includes("max: 120,"),
"the read brake's strictness is part of the contract (120/10min) — a wiring-correct limiter with a dropped ceiling is not the reviewed brake"
);
assert.ok(
decl.includes('return email ? `scheduler-read:${email}` : `scheduler-read:ip:${ipKeyGenerator(String(req.ip || "unknown"))}`;'),
"authenticated traffic keys per ACCOUNT email; sessionless traffic shares a per-IP bucket via ipKeyGenerator (fs-read doctrine)"
);
assert.ok(!decl.includes("skip: (req)"), "the read brake must NOT skip sessionless requests — an anonymous flood must not hit no brake at all");
// The route mounts it as middleware next to rejectCrossSiteRead, before
// any handler code — the 50k-job scan must never run unbraked.
assert.ok(
INDEX_SRC.includes("app.get(\"/api/scheduler/:serverName/tasks\", rejectCrossSiteRead, schedulerTasksReadRateLimiter, async"),
"GET /api/scheduler/:serverName/tasks must mount schedulerTasksReadRateLimiter as route middleware"
);
// Prefix distinctness across every store builder call site — two limiters
// sharing a prefix share one budget.
const prefixes = [...INDEX_SRC.matchAll(/buildSharedRateLimitRedisStore\("([^"]+)"/g)].map((m) => m[1]);
assert.strictEqual(new Set(prefixes).size, prefixes.length, "rate-limit store prefixes must stay distinct fleet-wide");
});
// ─── 3. The failure streak ───────────────────────────────────────────────────
test("recordSchedulerFailureStreak: streak hook wired into the worker catch BEFORE the rethrow", () => {
const catchBody = windowBetween(
INDEX_SRC,
"console.error(`[scheduler] Job ${job.id} failed:`, err?.message || err);\n // adpanel:scheduler-failure-streak",
"throw err;",
"worker catch"
);
assert.ok(
catchBody.includes("await recordSchedulerFailureStreak(job, err);"),
"the catch must record the failed run against the streak before rethrowing"
);
});
test("recordSchedulerFailureStreak: threshold disable goes through the ONE disable machinery and resets the counter", () => {
const body = functionWindow(INDEX_SRC, "async function recordSchedulerFailureStreak", "recordSchedulerFailureStreak");
assert.ok(
body.includes("if (!job?.opts?.repeat) return;"),
"one-time jobs own no recurrence — they must never be counted toward a disable"
);
assert.ok(
body.includes("const repeatKey = job.repeatJobKey || job.opts?.repeat?.key || job.name;"),
"the streak identity must mirror the disable machinery's repeat identity"
);
assert.ok(
body.includes("threshold: SCHEDULER_MAX_CONSECUTIVE_FAILURES") && body.includes("ttlSeconds: DEFAULT_STREAK_TTL_SECONDS"),
"the threshold and sliding TTL must come from the module-level resolved constants"
);
assert.ok(
body.includes("await disableRecurringScheduleForJob(job, `failed ${outcome.count} consecutive runs (last error: ${lastError})`)"),
"the disable MUST route through disableRecurringScheduleForJob (the one-true-home) with the streak size and last error in the reason"
);
assert.ok(
body.includes("if (disabledAny) await resetSchedulerFailureStreak(schedulerStateRedis, repeatKey);"),
"the counter must be cleared after a SUCCESSFUL disable so a recreated schedule starts clean — a failed removal (BullMQ side) must keep the live fuse instead of restarting it from zero"
);
assert.ok(
body.includes("proceeding (fail-open)"),
"the hook must fail open — a tracking error must never mask the job's own failure"
);
// The client it counts on is the scheduler's own, never the session's.
assert.ok(
body.includes("bumpSchedulerFailureStreak(schedulerStateRedis") && !body.includes("redisClient"),
"the streak rides the scheduler's dedicated client"
);
});
test("a successful recurrence clears the streak, but intentional Agent skips leave it unchanged", () => {
const body = windowBetween(
INDEX_SRC,
"schedulerWorker.on(\"completed\", (job, result) => {",
"schedulerWorker.on(\"failed\"",
"completed handler"
);
assert.ok(
body.includes('if (job?.opts?.repeat && !["agent_disabled", "agent_occurrence_skipped", "agent_unavailable"].includes(result?.reason)) {') &&
body.includes("const repeatKey = job.repeatJobKey || job.opts?.repeat?.key || job.name;") &&
body.includes("resetSchedulerFailureStreak(schedulerStateRedis, repeatKey)"),
"a successful run must reset the streak (the streak counts CONSECUTIVE failures only)"
);
});
test("a failed Agent state read cannot complete an enabled one-shot as a skipped occurrence", async () => {
const { isAgentSchedule } = require("../AgentWorker/feature-http");
const { readAgentQueueState, agentOccurrencePredatesEnable } = require("../AgentWorker/queue-state");
const { AgentRpcError } = require("../AgentWorker/private-rpc");
const preflight = windowBetween(INDEX_SRC, 'schedulerWorker = new Worker("adpanel-scheduler", async (job, token) => {',
'console.log(`[scheduler] Processing job', "Agent schedule preflight");
const check = new Function("isAgentSchedule", "readAgentQueueState", "agentOccurrencePredatesEnable", "AgentRpcError",
`return async (job, agentFeature, db) => { ${preflight.slice(preflight.indexOf("const { actionType"))} };`)(
isAgentSchedule, readAgentQueueState, agentOccurrencePredatesEnable, AgentRpcError,
);
const job = { data: { actionType: "agent_prompt" }, timestamp: 100 };
const outage = new Error("MySQL connection lost");
const offline = { query: async () => { throw outage; } };
await assert.rejects(check(job, { enabled: true }, offline), (error) => error === outage);
assert.equal((await check(job, { enabled: false }, offline)).reason, "agent_disabled");
const after = { query: async () => [{ enabled: 1, generation: "1", enabled_since_ms: 200 }] };
assert.equal((await check(job, { enabled: true }, after)).reason, "agent_occurrence_skipped");
});
test("the streak's identity derivation is identical in both the failure and success paths", () => {
const failureBody = functionWindow(INDEX_SRC, "async function recordSchedulerFailureStreak", "recordSchedulerFailureStreak");
const completedBody = windowBetween(
INDEX_SRC,
"schedulerWorker.on(\"completed\", (job, result) => {",
"schedulerWorker.on(\"failed\"",
"completed handler"
);
const derivation = "const repeatKey = job.repeatJobKey || job.opts?.repeat?.key || job.name;";
const failureCount = failureBody.split(derivation).length - 1;
const completedCount = completedBody.split(derivation).length - 1;
assert.strictEqual(failureCount, 1, "exactly one identity derivation in the failure path");
assert.strictEqual(completedCount, 1, "exactly one identity derivation in the success path");
assert.ok(
failureBody.includes(derivation) && completedBody.includes(derivation),
"failure and success must count the SAME schedule — a diverging derivation would reset or disable the wrong counter"
);
});
// ─── 4. The shared store builder's client parameter ──────────────────────────
test("buildSharedRateLimitRedisStore takes an injectable client defaulting to the session client", () => {
const decl = functionWindow(INDEX_SRC, "const buildSharedRateLimitRedisStore = (prefix", "buildSharedRateLimitRedisStore");
assert.ok(
decl.includes("client = redisClient"),
"the default client must remain the session store's redisClient — all pre-existing limiters keep their exact wiring"
);
assert.ok(
decl.includes("await client.sendCommand(safeArgs);"),
"the store must dial through the injected client"
);
// The other two sibling builders (safeRedisStore, buildAssistantRedisStore)
// still dial the session client — the parameter must not have leaked into
// them, and they must not have been touched.
const sharedCount = INDEX_SRC.split("const buildSharedRateLimitRedisStore = (prefix").length - 1;
assert.strictEqual(sharedCount, 1, "the shared builder must exist exactly once");
});
// ─── 5. Review-driven remediations (round 1) ─────────────────────────────────
test("the default client factory forwards the config — a zero-argument default would dial 127.0.0.1:6379 and resurrect the wrong-server bug", () => {
const stateRedis = fs.readFileSync(path.join(ROOT, "utils", "scheduler-state-redis.js"), "utf8");
assert.ok(
stateRedis.includes('deps.createClientFn || ((cfg) => require("redis").createClient(cfg))'),
"the default createClientFn MUST pass the config through to redis.createClient — the url, reconnect strategy and connect timeout are the whole point of the dedicated client"
);
assert.ok(
stateRedis.includes('client.on("reconnecting"'),
"the 'reconnecting' listener must exist — node-redis emits 'error' on every reconnect attempt and the connected-once flag must silence them mid-outage"
);
});
test("the streak TTL exceeds every practical recurrence gap and the hook is deadline-raced", () => {
const streak = fs.readFileSync(path.join(ROOT, "utils", "scheduler-failure-streak.js"), "utf8");
assert.ok(
streak.includes("45 * 24 * 60 * 60"),
"the sliding TTL must exceed the longest monthly gap (31 days) — a 24h TTL made every daily/weekly/monthly schedule unable to accumulate the streak (real Redis expires the key before the next failure)"
);
assert.ok(
streak.includes("function raceWithDeadline"),
"raceWithDeadline must live with the streak bookkeeping it protects"
);
const hook = functionWindow(INDEX_SRC, "async function recordSchedulerFailureStreak", "recordSchedulerFailureStreak");
assert.ok(
hook.includes("await raceWithDeadline(run(), SCHEDULER_FAILURE_STREAK_DEADLINE_MS, null);"),
"the hook must be raced against a hard deadline — a Redis outage between the run-claim and the catch would otherwise wedge the finished job in `active` forever (node-redis queues commands while disconnected)"
);
assert.ok(
INDEX_SRC.includes("const SCHEDULER_FAILURE_STREAK_DEADLINE_MS = 5000;"),
"the deadline constant must exist (5s: generous for 2–4 roundtrips, far below any interval)"
);
});
test("manual DELETE clears the stale streak so an identical recreate starts clean", () => {
// Both repeatable-removal paths must clear the counter: the repeat key is a
// hash of the name JSON + pattern, so recreating unchanged reproduces it and
// would inherit the old count.
assert.ok(
INDEX_SRC.includes("resetSchedulerFailureStreak(schedulerStateRedis, repeatable.key).catch(() => { });"),
"the job-based recurring delete path must reset the streak"
);
assert.ok(
INDEX_SRC.includes("resetSchedulerFailureStreak(schedulerStateRedis, taskId).catch(() => { });"),
"the repeatable-key delete path must reset the streak"
);
});
// ─── 6. Review-driven remediations (round 2, wired review) ──────────────────
test("the disable machinery removes exactly the resolved repeat key and never falls through to loose matching", () => {
const body = functionWindow(INDEX_SRC, "async function disableRecurringScheduleForJob", "disableRecurringScheduleForJob");
const exactAt = body.indexOf("if (repeatKey) {");
const returnAt = body.indexOf(" return removedAny;", exactAt);
const fallbackAt = body.indexOf("const repeatableJobs = await schedulerQueue.getRepeatableJobs();");
assert.notStrictEqual(exactAt, -1, "the exact-key path must exist");
assert.notStrictEqual(returnAt, -1, "the exact-key path must return its removal outcome");
assert.notStrictEqual(fallbackAt, -1);
assert.ok(returnAt > exactAt && returnAt < fallbackAt, "a resolved repeat key must STOP after its own removal — the signature fallback tolerates legacy no-creator entries and the failure-streak hook is the first failure-driven (co-user-aimable) caller of this machinery");
assert.ok(
body.includes("let removedAny = false;") && body.includes("return removedAny;"),
"the machinery must report whether anything was removed — the hook gates its counter reset on it, so a failed removal keeps the live fuse"
);
assert.ok(
body.includes("if (removedOk) removedAny = true;") && body.includes("if (removedOk) {"),
"the Disabled warn fires only for a real removal (BullMQ's false = already-removed state, not a fresh removal)"
);
assert.ok(
body.includes("resetSchedulerFailureStreak(schedulerStateRedis, repeatKey).catch(() => { });") &&
body.includes("resetSchedulerFailureStreak(schedulerStateRedis, r.key).catch(() => { });"),
"every removal path through the ONE disable machinery must clear the streak counter"
);
});
test("every repeatable-removal site clears the streak (cancelSchedulesCreatedBy, deleteServerSchedules)", () => {
const cancelBody = functionWindow(INDEX_SRC, "async function cancelSchedulesCreatedBy", "cancelSchedulesCreatedBy");
assert.ok(
cancelBody.includes("await disableRecurringScheduleForJob(job, reason)"),
"cancelSchedulesCreatedBy must delegate recurrence removal and streak reset to the shared helper"
);
const deleteBody = functionWindow(INDEX_SRC, "async function deleteServerSchedules", "deleteServerSchedules");
assert.ok(
deleteBody.includes("resetSchedulerFailureStreak(schedulerStateRedis, job.key).catch(() => { });"),
"deleteServerSchedules must reset the streak per removed repeatable"
);
});
test("the stall-guard run-claim is deadline-raced and fails open on a deadline miss", () => {
const body = windowBetween(
INDEX_SRC,
"const runClaimKey = `adpanel:scheduler-run:${job.id}`;",
"if (alreadyRunning) {",
"stall-guard run-marker"
);
assert.ok(
body.includes("raceWithDeadline(") && body.includes("SCHEDULER_RUN_CLAIM_DEADLINE_MS"),
"the claim await must be raced against a hard deadline — node-redis queues commands while disconnected and an outage would wedge a concurrency slot on a finished job"
);
assert.ok(
body.includes("alreadyRunning = !claim; // null => NX lost => the id was already claimed"),
"a settled claim must keep the exact NX semantics (null => already claimed)"
);
assert.ok(
body.includes('console.warn(`[scheduler] Run-marker claim unresolved for job ${job.id}; proceeding (fail-open)`);'),
"a deadline miss must fail OPEN (proceed), never count as already-running"
);
assert.ok(
INDEX_SRC.includes("const SCHEDULER_RUN_CLAIM_DEADLINE_MS = 5000;"),
"the claim deadline constant must exist"
);
});
test("shutdown closes the dedicated state client with the rest of the scheduler family — without a shutdown-hang surface", () => {
const body = functionWindow(INDEX_SRC, "async function shutdownScheduler", "shutdownScheduler");
assert.ok(
body.includes("raceWithDeadline(schedulerStateRedis.quit()") && body.includes("schedulerStateRedis.disconnect();"),
"the state client must participate in graceful shutdown, and safely: a disconnected client's offline queue would hold the QUIT forever (force-close instead), and the ready-path quit is deadline-raced"
);
});
test("a SCHEDULER_REDIS_URL the parsers disagree on is named at boot", () => {
assert.ok(
INDEX_SRC.includes('is not plain digits ("/2")'),
"node-redis SELECTs the db path verbatim while parseRedisUrlForBullMQ floors/drops it — non-plain-digit paths silently split the queue and the state across databases; the operator must get a boot-time warning"
);
});
// ─── 7. The utils modules exist and are the single homes ────────────────────
test("the scheduler state client and failure streak have exactly one implementation each", () => {
const stateRedis = fs.readFileSync(path.join(ROOT, "utils", "scheduler-state-redis.js"), "utf8");
assert.strictEqual(
stateRedis.split("function createSchedulerStateRedis").length - 1, 1,
"utils/scheduler-state-redis.js must be the ONE home of the scheduler client factory"
);
// Pin the CODE, not the comments: the header comment legitimately names
// SESSION_STORE while documenting the coupling bug it prevents.
const stateRedisCode = stateRedis.split("\n").filter((line) => !line.trim().startsWith("//")).join("\n");
assert.ok(
!stateRedisCode.includes("SESSION_STORE"),
"the scheduler client factory's code must not know about the session store's configuration"
);
const streak = fs.readFileSync(path.join(ROOT, "utils", "scheduler-failure-streak.js"), "utf8");
assert.strictEqual(
streak.split("async function bumpSchedulerFailureStreak").length - 1, 1,
"utils/scheduler-failure-streak.js must be the ONE home of the streak bookkeeping"
);
// index.js consumes them through exactly these requires.
assert.ok(
INDEX_SRC.includes("require(\"./utils/scheduler-state-redis\")") &&
INDEX_SRC.includes("require(\"./utils/scheduler-failure-streak\")"),
"index.js must consume the two modules by require (no duplicated inline copies)"
);
});
// ─── 8. The mutate brake accounts sessionless traffic (adpanel:scheduler-mutate-brake) ───
test("schedulerMutateRateLimiter keys sessionless traffic into a shared per-IP bucket like the read brake", () => {
const decl = functionWindow(INDEX_SRC, "const schedulerMutateRateLimiter = rateLimit({", "schedulerMutateRateLimiter");
// Sessionless fallback: ipKeyGenerator is REQUIRED by express-rate-limit
// v8's keyGeneratorIpFallback validation (any keyGenerator source reading
// req.ip must wrap it), and it collapses native IPv6 into /56 subnets so
// address rotation cannot mint fresh buckets.
assert.ok(
decl.includes("`scheduler-mutate:ip:${ipKeyGenerator(String(req.ip || \"unknown\"))}`"),
"sessionless requests must share a per-IP bucket keyed scheduler-mutate:ip:<ipKeyGenerator(req.ip)> (the fs-read doctrine)"
);
// Authenticated traffic keeps the EXISTING key shape — the ip half stays.
assert.ok(
decl.includes("`scheduler-mutate:${getRequestIp(req)}:${email}`"),
"authenticated traffic must keep the original scheduler-mutate:<ip>:<email> key shape (getRequestIp, not req.ip)"
);
// The doctrine comment sits between the brake tag and the declaration.
const doctrine = windowBetween(INDEX_SRC, "adpanel:scheduler-mutate-brake", "const schedulerMutateRateLimiter = rateLimit({", "mutate brake doctrine comment");
assert.ok(
doctrine.includes("Sessionless requests are NOT skipped") && doctrine.includes("adpanel:fs-read-rate-limit-account"),
"the limiter comment must carry the no-skip doctrine with the fs-read-brake cross-reference — under the shipped default the old skip left anonymous floods unbraked"
);
});
// ─── 9. The status route parity (adpanel:scheduler-status-parity) ───────────
test("the status route mounts the tasks GET's middleware pair and reads the precomputed req.isAdmin", () => {
// The route line itself: rejectCrossSiteRead + the shared account-keyed read
// brake in front of the handler, exactly like the tasks list route — the
// queue counters are fleet-wide aggregates and must never run unbraked or
// cross-site readable.
assert.ok(
INDEX_SRC.includes('app.get("/api/scheduler/status", rejectCrossSiteRead, schedulerTasksReadRateLimiter, async'),
"GET /api/scheduler/status must mount rejectCrossSiteRead + schedulerTasksReadRateLimiter as route middleware, exactly like the tasks GET"
);
// The admin gate reads the global auth middleware's precomputed flag — the
// parity contract — never a second isAdmin(req) evaluation inside the route.
const routeStart = INDEX_SRC.indexOf('app.get("/api/scheduler/status"');
const routeEnd = INDEX_SRC.indexOf("\napp.", routeStart + 1);
const route = INDEX_SRC.slice(routeStart, routeEnd);
assert.ok(
route.includes("const isAdminUser = req.isAdmin === true;"),
"the queue-counter gate must read req.isAdmin === true (the global middleware's precomputed admin flag)"
);
assert.ok(
!route.includes("isAdmin(req)"),
"the status route must not re-run isAdmin(req) — the precomputed req.isAdmin is the reviewed parity contract"
);
assert.ok(
route.includes("await isAuthenticated(req)"),
"the session authentication check must stay — the parity arm covers the admin flag, not the auth check"
);
});