import { EventEmitter } from "node:events"; import RedisMock from "ioredis-mock"; import { afterEach, describe, expect, test } from "vitest"; import { RedisAdapter } from "./redis.js"; type RedisClient = import("ioredis").Redis; const adapters: RedisAdapter[] = []; afterEach(async () => { while (adapters.length > 0) { const adapter = adapters.pop(); if (adapter) { await adapter.close().catch(() => undefined); } } }); /** * Client double whose `quit()` rejects, forcing `safeQuit` to take the * `disconnect()` fallback branch. Records whether disconnect ran. */ class QuitFailingClientDouble extends EventEmitter { status = "ready"; quitCalled = false; disconnectCalled = false; async quit(): Promise { this.quitCalled = true; throw new Error("quit failed: connection already gone"); } disconnect(): void { this.disconnectCalled = true; } } /** * Client double that supports SCRIPT LOAD / EVALSHA / EVAL so the * adapter's SHA-cache and NOSCRIPT-recovery branches can be exercised * (ioredis-mock rejects SCRIPT LOAD and so never reaches EVALSHA). */ class EvalClientDouble extends EventEmitter { status = "ready"; loadCount = 0; evalshaCount = 0; evalCount = 0; constructor(private readonly behaviour: { noscriptOnce?: boolean; evalshaError?: string } = {}) { super(); } async script(_subcommand: string, body: string): Promise { this.loadCount += 1; return `sha:${body.length}`; } // Called positionally by the adapter (sha, numKeys, ...keys, ...args); the // double ignores the arguments and is reached via the `RedisClient` cast. async evalsha(): Promise { this.evalshaCount += 1; if (this.behaviour.evalshaError) { throw new Error(this.behaviour.evalshaError); } if (this.behaviour.noscriptOnce && this.evalshaCount === 1) { throw new Error("NOSCRIPT No matching script. Please use EVAL."); } return "via-evalsha"; } async eval(): Promise { this.evalCount += 1; return "via-eval"; } async quit(): Promise<"OK"> { return "OK"; } disconnect(): void { /* noop */ } } function buildEvalAdapter(primary: EvalClientDouble): RedisAdapter { const adapter = new RedisAdapter({ clientFactory: (role) => (role === "primary" ? primary : new EvalClientDouble()) as unknown as RedisClient, }); adapters.push(adapter); return adapter; } async function waitForFanout(): Promise { await new Promise((resolve) => setTimeout(resolve, 0)); } describe("RedisAdapter — default client construction (no url)", () => { test("builds three lazy clients without a url and closes cleanly", async () => { // No clientFactory, no redisUrl and no db exercises buildClient's // `new Redis(baseOptions)` plus the default db/timeout branches. // lazyConnect keeps it from dialing out, so close() is fast and clean. const adapter = new RedisAdapter(); adapters.push(adapter); await expect(adapter.close()).resolves.toBeUndefined(); // Closing twice is idempotent. await expect(adapter.close()).resolves.toBeUndefined(); }); }); describe("RedisAdapter — scan default COUNT", () => { test("iterates matching keys when no count hint is supplied", async () => { const adapter = new RedisAdapter({ clientFactory: () => new RedisMock() as unknown as RedisClient, }); adapters.push(adapter); await adapter.set("u:1", "a"); await adapter.set("u:2", "b"); await adapter.set("other:1", "c"); const seen: string[] = []; // No opts → buildClient's `opts.count ?? 100` default branch. for await (const key of adapter.scan("u:*")) { seen.push(key); } expect(seen.sort()).toEqual(["u:1", "u:2"]); }); }); describe("RedisAdapter — subscribe disposer idempotency", () => { test("calling the unsubscribe disposer twice is a safe noop", async () => { const adapter = new RedisAdapter({ clientFactory: () => new RedisMock() as unknown as RedisClient, }); adapters.push(adapter); const dispose = await adapter.subscribe("ch", () => undefined); await dispose(); // Second dispose finds no handler set for the channel and returns early. await expect(dispose()).resolves.toBeUndefined(); }); }); describe("RedisAdapter — eval SHA caching", () => { test("loads the script once, then reuses the cached SHA via EVALSHA", async () => { const primary = new EvalClientDouble(); const adapter = buildEvalAdapter(primary); expect(await adapter.eval("return 1", ["k"], ["a"])).toBe("via-evalsha"); expect(await adapter.eval("return 1", ["k"], ["b"])).toBe("via-evalsha"); // SCRIPT LOAD ran once; the second call hit the SHA cache. expect(primary.loadCount).toBe(1); expect(primary.evalshaCount).toBe(2); expect(primary.evalCount).toBe(0); }); test("recovers from NOSCRIPT by dropping the cache and falling back to EVAL", async () => { const primary = new EvalClientDouble({ noscriptOnce: true }); const adapter = buildEvalAdapter(primary); // First call: SCRIPT LOAD ok, EVALSHA throws NOSCRIPT → cache cleared, raw EVAL. expect(await adapter.eval("return 2", ["k"], [])).toBe("via-eval"); expect(primary.evalshaCount).toBe(1); expect(primary.evalCount).toBe(1); // Cache was cleared, so the next call must reload the script. expect(await adapter.eval("return 2", ["k"], [])).toBe("via-evalsha"); expect(primary.loadCount).toBe(2); }); test("rethrows non-NOSCRIPT errors from EVALSHA", async () => { const primary = new EvalClientDouble({ evalshaError: "ERR something unexpected" }); const adapter = buildEvalAdapter(primary); await expect(adapter.eval("return 3", [], [])).rejects.toThrow(/something unexpected/); expect(primary.evalCount).toBe(0); }); }); describe("RedisAdapter — onReconnect disposer", () => { test("the returned disposer unregisters only its own handler", async () => { const primary = new EvalClientDouble(); const adapter = buildEvalAdapter(primary); let removed = 0; let kept = 0; const off = adapter.onReconnect(() => { removed += 1; }); adapter.onReconnect(() => { kept += 1; }); off(); // The client is already "ready", so the next emitted "ready" fans out. primary.emit("ready"); await waitForFanout(); expect(removed).toBe(0); expect(kept).toBe(1); }); }); describe("RedisAdapter — safeQuit fallback", () => { test("falls back to disconnect() when quit() rejects on every client", async () => { const doubles: QuitFailingClientDouble[] = []; const adapter = new RedisAdapter({ clientFactory: () => { const client = new QuitFailingClientDouble(); doubles.push(client); return client as unknown as RedisClient; }, }); await adapter.close(); // One client per role: primary, subscriber, publisher. expect(doubles).toHaveLength(3); for (const client of doubles) { expect(client.quitCalled).toBe(true); expect(client.disconnectCalled).toBe(true); } }); });