Files
Kelx/utils/scheduler-state-redis.js
2026-11-30 16:32:37 +00:00

130 lines
7.0 KiB
JavaScript

"use strict";
// adpanel:scheduler-redis-decouple — ONE dedicated Redis client for the
// scheduler's own state: the mutate/read limiter stores, the stall-guard
// run-marker and the failure-streak counters. That state used to piggyback
// on the session store's redisClient (index.js), which is created only when
// SESSION_STORE !== "file" — so the supported deployment SESSION_STORE=file +
// a scheduler Redis URL left the queue itself (which resolves its URL
// independently) fully working while the mutate limiter silently degraded to
// a bare per-process MemoryStore and the run-marker failed open on every
// job. The client here is therefore gated by the SCHEDULER's URL only, never
// by the session store's configuration, and no consumer may fall back to the
// session client: null means "no scheduler Redis", and every consumer's
// existing fail-open path handles that exactly like a Redis outage.
//
// The connection posture mirrors the session client's (index.js): capped
// reconnect backoff, 5s connect timeout, an 'error' listener on the client
// itself (an unlistened 'error' emitter is the recurring worker-crash class
// in this codebase) and a fire-and-forget connect — boot must never block on
// the scheduler state store, and consumers fail open while the client is
// connecting or down.
let memo = null; // { url, client } — one client per resolved URL per process
function createSchedulerStateRedis(url, deps = {}) {
const logger = Object.assign({ log: console.log, error: console.error }, deps.logger);
// The config MUST be forwarded: a zero-argument default here would silently
// drop { url, socket } and dial node-redis's own defaults (127.0.0.1:6379,
// db 0, no auth) — resurrecting exactly the wrong-server/fail-open bug this
// module exists to fix. Injected test factories receive the same config.
const createClientFn = deps.createClientFn || ((cfg) => require("redis").createClient(cfg));
const trimmed = String(url ?? "").trim();
if (!trimmed) return null;
try {
const client = createClientFn({
url: trimmed,
// adpanel:scheduler-offline-queue-bound — the decoupled scheduler client
// must also fail fast during a reconnect window (symmetry with
// adpanel:redis-offline-queue-bound); every consumer handles rejection
// as fail-open/default state (census: the scheduler-mutate and
// scheduler-read limiter stores fail open via the shared sendCommand
// catch + passOnStoreError, bump/resetSchedulerFailureStreak catch to
// untracked/false with TTL-decayed stale counters, the stall-guard
// run-claim raceWithDeadline-fails OPEN by design, the worker-completed
// run-marker del is fire-and-forget, and shutdown disconnects a
// non-ready client instead of queueing a QUIT). Nothing depends on
// queue-then-flush: no boot-time write rides this client — the BullMQ
// queue resolves its URL independently, and limiter/streak/claim
// commands only fire on requests and job events.
disableOfflineQueue: true,
// Reviewed residual (LOW) of failing fast: a completed run's run-marker
// del that lands in a reconnect window is now rejected immediately and
// swallowed (the worker-completed cleanup is fire-and-forget), so that
// marker can survive up to its 900s EX. The blast radius is ONE
// iteration: the marker is keyed per job id and BullMQ repeatable ids
// are unique per firing (repeat:<customKey>:<nextMillis>), so a
// stranded marker blocks only a stall re-run of its OWN iteration
// ("Duplicate execution blocked" — operator-visible); the next firing
// claims a fresh key and runs normally, and that success resets the
// CONSECUTIVE failure streak — one stranded marker therefore cannot
// accumulate blocked re-runs toward the threshold-20 auto-disable.
// Residual, recoverable (the marker self-expires), and the whole
// exposure is bounded at 900s by the marker's EX. The counterweight:
// disabling the queue REMOVES a worse pre-existing hazard — with
// queue-then-flush, a claim-SET queued during a blip could flush AFTER
// the run's del and strand a marker with no bound (its scheduled
// cleanup has already fired; nothing would ever target it again).
socket: {
reconnectStrategy: (retries) => {
const delay = Math.min(500 + retries * 250, 5000);
logger.log(`[scheduler-state] Redis reconnecting in ${delay}ms (attempt ${retries})...`);
return delay;
},
connectTimeout: 5000,
},
});
// Same listener set as the session client (index.js): TWO flags, exactly
// like the session client's redisSessionReady/redisHasConnected pair —
// one flag alone cannot serve both jobs, because node-redis emits
// 'reconnecting' BEFORE the recovery 'ready' of every outage→recovery
// cycle, so a flag cleared on 'reconnecting' is always false at the
// recovery 'ready' and a "connection restored" log gated on it is dead
// code.
let connectedOnce = false; // gates error loudness: quiet until the first ready
let everConnected = false; // NEVER cleared: gates the restored log
client.on("error", (err) => {
if (!connectedOnce) return;
logger.error(`[scheduler-state] Redis error: ${err?.message || err}`);
});
client.on("ready", () => {
if (everConnected) logger.log("[scheduler-state] Redis connection restored");
everConnected = true;
connectedOnce = true;
});
// node-redis emits 'error' on every reconnect attempt; clearing the
// loudness flag here keeps a prolonged outage at one reconnectStrategy
// line per attempt instead of one error line per attempt (the session
// client's posture). everConnected deliberately survives.
client.on("reconnecting", () => {
connectedOnce = false;
});
client.on("end", () => {
connectedOnce = false;
});
// Fire-and-forget connect: consumers fail open until the client is
// ready, exactly like a Redis outage mid-run.
Promise.resolve(client.connect()).catch((err) => {
logger.error(`[scheduler-state] Redis initial connect failed: ${err?.message || err}`);
});
return client;
} catch (err) {
logger.error(`[scheduler-state] Redis client unavailable: ${err?.message || err}`);
return null;
}
}
// Memoized accessor used by index.js. The URL is fixed at boot (env), so a
// changed memo key only happens across tests; the previous client is simply
// dropped, not disconnected. deps passes through to createSchedulerStateRedis
// (injected logger/createClientFn for tests); the memo key is the URL only.
function getSchedulerStateRedis(url, deps = {}) {
const trimmed = String(url ?? "").trim();
if (!trimmed) return null;
if (memo && memo.url === trimmed) return memo.client;
memo = { url: trimmed, client: createSchedulerStateRedis(trimmed, deps) };
return memo.client;
}
module.exports = { createSchedulerStateRedis, getSchedulerStateRedis };