222 lines
12 KiB
JavaScript
222 lines
12 KiB
JavaScript
"use strict";
|
|
|
|
// Behavioral tests for utils/scheduler-state-redis.js — the scheduler's own
|
|
// Redis client (adpanel:scheduler-redis-decouple). The client factory is
|
|
// exercised with an injected createClientFn so no real connection is opened;
|
|
// the assertions pin the contract index.js relies on:
|
|
// 1. falsy/blank URL -> null, and NO client is ever constructed;
|
|
// 2. a real URL -> a client built with that exact URL, with 'error'
|
|
// (and 'ready'/'end') listeners attached before any connect — the
|
|
// unlistened-'error'-emitter class has crashed workers before;
|
|
// 3. connect failure -> never throws out of the factory (boot must not
|
|
// block or crash on the state store); consumers fail open;
|
|
// 4. createClient throwing -> null + logged, never thrown;
|
|
// 5. getSchedulerStateRedis memoizes per URL and treats "" as "no client";
|
|
// 6. the client config pins disableOfflineQueue: true (adpanel:scheduler-
|
|
// offline-queue-bound) — reconnect-window commands must fail fast,
|
|
// never queue-then-flush.
|
|
|
|
const test = require("node:test");
|
|
const assert = require("node:assert");
|
|
|
|
const { createSchedulerStateRedis, getSchedulerStateRedis } = require("./scheduler-state-redis");
|
|
|
|
// Minimal node-redis-shaped fake: records the config it was built with and
|
|
// the listeners attached, exposes connect() as a controllable promise.
|
|
function fakeClientFactory(overrides = {}) {
|
|
const built = [];
|
|
const makeClient = (config) => {
|
|
const client = {
|
|
config,
|
|
listeners: {},
|
|
connectCalls: 0,
|
|
on(event, fn) {
|
|
(client.listeners[event] = client.listeners[event] || []).push(fn);
|
|
},
|
|
connect() {
|
|
client.connectCalls += 1;
|
|
return overrides.connectImpl
|
|
? overrides.connectImpl(client)
|
|
: Promise.resolve();
|
|
},
|
|
emit(event, arg) {
|
|
for (const fn of client.listeners[event] || []) fn(arg);
|
|
},
|
|
};
|
|
Object.assign(client, overrides.clientExtras);
|
|
return client;
|
|
};
|
|
const factory = (config) => {
|
|
built.push(config);
|
|
if (overrides.throwOnCreate) throw overrides.throwOnCreate;
|
|
return makeClient(config);
|
|
};
|
|
factory.built = built;
|
|
return factory;
|
|
}
|
|
|
|
function silentLogger() {
|
|
const calls = { log: [], error: [] };
|
|
return {
|
|
calls,
|
|
log: (...a) => calls.log.push(a.join(" ")),
|
|
error: (...a) => calls.error.push(a.join(" ")),
|
|
};
|
|
}
|
|
|
|
test("createSchedulerStateRedis: blank/falsy URL returns null and never constructs a client", () => {
|
|
for (const url of [undefined, null, "", " ", "\t"]) {
|
|
const factory = fakeClientFactory();
|
|
const client = createSchedulerStateRedis(url, { createClientFn: factory });
|
|
assert.strictEqual(client, null, `url=${JSON.stringify(url)} must yield null`);
|
|
assert.strictEqual(factory.built.length, 0, "no client may be constructed without a URL");
|
|
}
|
|
});
|
|
|
|
test("createSchedulerStateRedis: builds the client with the exact URL and attaches listeners BEFORE connecting", () => {
|
|
const factory = fakeClientFactory();
|
|
const logger = silentLogger();
|
|
const client = createSchedulerStateRedis("redis://scheduler.example:6380", { createClientFn: factory, logger });
|
|
|
|
assert.ok(client, "a valid URL must yield a client");
|
|
assert.strictEqual(factory.built.length, 1);
|
|
assert.strictEqual(factory.built[0].url, "redis://scheduler.example:6380");
|
|
// adpanel:scheduler-offline-queue-bound — pin so the option cannot be
|
|
// silently removed: a re-enabled offline queue would wedge claims/dels in
|
|
// reconnect windows again (see the reviewed residual in the source comment).
|
|
assert.strictEqual(factory.built[0].disableOfflineQueue, true, "the client MUST fail fast during reconnect windows, never queue-then-flush");
|
|
assert.ok(factory.built[0].socket && typeof factory.built[0].socket.reconnectStrategy === "function", "reconnect strategy must be configured");
|
|
assert.ok(Array.isArray(client.listeners.error) && client.listeners.error.length > 0, "an 'error' listener MUST exist — an unlistened error emitter crashes the worker");
|
|
assert.ok(Array.isArray(client.listeners.ready) && client.listeners.ready.length > 0, "the 'ready' listener tracks the connected-once posture");
|
|
assert.ok(Array.isArray(client.listeners.end) && client.listeners.end.length > 0, "the 'end' listener resets the connected-once posture");
|
|
assert.strictEqual(client.connectCalls, 1, "the factory connects eagerly (fire-and-forget)");
|
|
});
|
|
|
|
test("createSchedulerStateRedis: a rejected connect() must not throw out of the factory", async () => {
|
|
const factory = fakeClientFactory({ connectImpl: () => Promise.reject(new Error("ECONNREFUSED at boot")) });
|
|
const logger = silentLogger();
|
|
const client = createSchedulerStateRedis("redis://down.example:6379", { createClientFn: factory, logger });
|
|
|
|
assert.ok(client, "the client is still returned — consumers fail open until Redis is up");
|
|
// Let the fire-and-forget connect rejection settle, then assert it was
|
|
// logged (operator signal) and did NOT escape as an unhandled rejection.
|
|
await new Promise((resolve) => setImmediate(resolve));
|
|
await new Promise((resolve) => setImmediate(resolve));
|
|
assert.ok(logger.calls.error.some((line) => line.includes("ECONNREFUSED at boot")), "the connect failure must be logged");
|
|
});
|
|
|
|
test("createSchedulerStateRedis: a throwing createClient yields null + logged error, never throws", () => {
|
|
const factory = fakeClientFactory({ throwOnCreate: new Error("createClient exploded") });
|
|
const logger = silentLogger();
|
|
const client = createSchedulerStateRedis("redis://x:6379", { createClientFn: factory, logger });
|
|
assert.strictEqual(client, null);
|
|
assert.ok(logger.calls.error.some((line) => line.includes("createClient exploded")));
|
|
});
|
|
|
|
test("the DEFAULT createClientFn forwards { url, socket } to redis.createClient — a zero-argument default would dial 127.0.0.1:6379 defaults and resurrect the wrong-server bug", () => {
|
|
// Stub the "redis" module in require cache so the production default path
|
|
// (no injected deps) is exercised without opening real sockets.
|
|
const redisPath = require.resolve("redis");
|
|
const saved = require.cache[redisPath];
|
|
let receivedConfig;
|
|
const stubExports = {
|
|
createClient: (cfg) => {
|
|
receivedConfig = cfg;
|
|
return {
|
|
listeners: {},
|
|
on(event, fn) {
|
|
(this.listeners[event] = this.listeners[event] || []).push(fn);
|
|
},
|
|
connect() {
|
|
return Promise.resolve();
|
|
},
|
|
};
|
|
},
|
|
};
|
|
require.cache[redisPath] = { id: redisPath, filename: redisPath, loaded: true, exports: stubExports };
|
|
try {
|
|
const client = createSchedulerStateRedis("redis://scheduler-host:6380/2");
|
|
assert.ok(client, "the default path must still build a client");
|
|
assert.ok(receivedConfig, "the config object MUST reach redis.createClient");
|
|
assert.strictEqual(receivedConfig.url, "redis://scheduler-host:6380/2", "SCHEDULER_REDIS_URL must reach the real client — a dropped url dials the library defaults");
|
|
assert.ok(receivedConfig.socket && typeof receivedConfig.socket.reconnectStrategy === "function", "the reconnect posture must reach the real client");
|
|
assert.strictEqual(receivedConfig.socket.connectTimeout, 5000);
|
|
} finally {
|
|
if (saved) require.cache[redisPath] = saved;
|
|
else delete require.cache[redisPath];
|
|
}
|
|
});
|
|
|
|
test("the 'reconnecting' listener resets the connected-once posture (outage logs stay at one line per attempt)", () => {
|
|
const factory = fakeClientFactory();
|
|
const logger = silentLogger();
|
|
const client = createSchedulerStateRedis("redis://x:6379", { createClientFn: factory, logger });
|
|
assert.ok(Array.isArray(client.listeners.reconnecting) && client.listeners.reconnecting.length > 0, "a 'reconnecting' listener must exist — node-redis emits 'error' on every retry and the flag must silence them mid-outage");
|
|
// Ready → error is loud; reconnecting → error is quiet again.
|
|
client.emit("ready");
|
|
client.emit("error", new Error("during healthy period"));
|
|
assert.ok(logger.calls.error.some((line) => line.includes("during healthy period")));
|
|
client.emit("reconnecting");
|
|
client.emit("error", new Error("during outage"));
|
|
assert.ok(!logger.calls.error.some((line) => line.includes("during outage")), "mid-outage errors are silenced like the session client's");
|
|
});
|
|
|
|
test("createSchedulerStateRedis: 'error' events never escape as unhandled exceptions", () => {
|
|
const factory = fakeClientFactory();
|
|
const logger = silentLogger();
|
|
const client = createSchedulerStateRedis("redis://x:6379", { createClientFn: factory, logger });
|
|
|
|
// Before first ready: quiet (the connect failure path owns pre-boot noise).
|
|
assert.doesNotThrow(() => client.emit("error", new Error("pre-ready noise")));
|
|
assert.strictEqual(logger.calls.error.length, 0, "pre-ready errors are silenced like the session client's");
|
|
|
|
// After ready: loud — a reconnect-loop failure is operator signal.
|
|
client.emit("ready");
|
|
client.emit("error", new Error("post-ready boom"));
|
|
assert.ok(logger.calls.error.some((line) => line.includes("post-ready boom")));
|
|
|
|
// After 'end': quiet again (connection gone, reconnect loop owns signaling).
|
|
client.emit("end");
|
|
client.emit("error", new Error("post-end noise"));
|
|
assert.ok(!logger.calls.error.some((line) => line.includes("post-end noise")));
|
|
});
|
|
|
|
test("the 'ready' recovery log fires after an outage — the everConnected flag must survive reconnecting/end", () => {
|
|
const factory = fakeClientFactory();
|
|
const logger = silentLogger();
|
|
const client = createSchedulerStateRedis("redis://x:6379", { createClientFn: factory, logger });
|
|
|
|
// First ready: connected, no "restored" line (nothing was ever lost).
|
|
client.emit("ready");
|
|
assert.strictEqual(logger.calls.log.filter((line) => line.includes("Redis connection restored")).length, 0);
|
|
|
|
// Outage then recovery: the restored line MUST fire — node-redis emits
|
|
// 'reconnecting' BEFORE the recovery 'ready', so a single flag cleared on
|
|
// 'reconnecting' makes this log dead code (the two-flag session-client
|
|
// posture exists precisely for this).
|
|
client.emit("reconnecting");
|
|
client.emit("ready");
|
|
assert.strictEqual(logger.calls.log.filter((line) => line.includes("Redis connection restored")).length, 1, "recovery after an outage must be visible to the operator");
|
|
});
|
|
|
|
|
|
test("getSchedulerStateRedis: memoizes per URL, null for blank, separate clients per URL", () => {
|
|
const factoryA = fakeClientFactory();
|
|
const factoryB = fakeClientFactory();
|
|
const logger = silentLogger();
|
|
// Injected factories keep the event loop free of real connection attempts
|
|
// — the singleton must never be allowed to dial an unreachable Redis from
|
|
// a test.
|
|
const first = getSchedulerStateRedis("redis://memo-a:6379", { createClientFn: factoryA, logger });
|
|
const again = getSchedulerStateRedis("redis://memo-a:6379", { createClientFn: factoryA, logger });
|
|
assert.strictEqual(first, again, "the same URL must return the SAME client instance (one client per process)");
|
|
assert.strictEqual(getSchedulerStateRedis(""), null);
|
|
assert.strictEqual(getSchedulerStateRedis(" "), null);
|
|
// A different URL builds a different client (and does not disturb the memo
|
|
// of the first: re-reading the first URL still returns the first client).
|
|
const secondFactoryRef = createSchedulerStateRedis("redis://memo-b:6379", { createClientFn: factoryB });
|
|
assert.notStrictEqual(secondFactoryRef, first);
|
|
assert.strictEqual(getSchedulerStateRedis("redis://memo-a:6379", { createClientFn: factoryA, logger }), first, "the original memo must survive an unrelated factory call");
|
|
assert.strictEqual(factoryA.built.length, 1, "the memo prevents re-construction for the same URL");
|
|
});
|