|
| 1 | +import { test } from "node:test"; |
| 2 | +import { strictEqual } from "node:assert/strict"; |
| 3 | +import type { Callback, RedisKey } from "ioredis"; |
| 4 | +import { Buffer } from "node:buffer"; |
| 5 | +import { EventEmitter } from "node:events"; |
| 6 | +import { RedisMessageQueue } from "@fedify/redis/mq"; |
| 7 | + |
| 8 | +/** |
| 9 | + * Mock Redis client that allows manual control of subscribe callback timing. |
| 10 | + * |
| 11 | + * This enables deterministic reproduction of the race condition by: |
| 12 | + * 1. Capturing the subscribe callback without executing it |
| 13 | + * 2. Allowing publish() to fire before the callback runs |
| 14 | + * 3. Manually triggering the callback later |
| 15 | + */ |
| 16 | +class MockRedis extends EventEmitter { |
| 17 | + #subscribeCallback: (() => void) | null = null; |
| 18 | + #subscribed = false; |
| 19 | + #queue: Map<string, { score: number; value: string }[]> = new Map(); |
| 20 | + |
| 21 | + /** |
| 22 | + * Simulates Redis SUBSCRIBE command. |
| 23 | + * Captures callback for later execution (simulates async event loop behavior). |
| 24 | + */ |
| 25 | + subscribe( |
| 26 | + _channel: RedisKey, |
| 27 | + callback?: Callback<number>, |
| 28 | + ): Promise<number> { |
| 29 | + this.#subscribed = true; |
| 30 | + if (callback) { |
| 31 | + this.#subscribeCallback = () => callback(null, 1); |
| 32 | + } |
| 33 | + return Promise.resolve(1); |
| 34 | + } |
| 35 | + |
| 36 | + /** |
| 37 | + * Manually trigger the captured subscribe callback. |
| 38 | + * Call this to simulate the event loop executing the callback. |
| 39 | + */ |
| 40 | + triggerSubscribeCallback(): void { |
| 41 | + if (this.#subscribeCallback) { |
| 42 | + this.#subscribeCallback(); |
| 43 | + this.#subscribeCallback = null; |
| 44 | + } |
| 45 | + } |
| 46 | + |
| 47 | + /** |
| 48 | + * Check if subscribe callback is pending (not yet executed). |
| 49 | + */ |
| 50 | + hasSubscribeCallbackPending(): boolean { |
| 51 | + return this.#subscribeCallback !== null; |
| 52 | + } |
| 53 | + |
| 54 | + unsubscribe(_channel: RedisKey): Promise<number> { |
| 55 | + this.#subscribed = false; |
| 56 | + return Promise.resolve(1); |
| 57 | + } |
| 58 | + |
| 59 | + /** |
| 60 | + * Simulates Redis PUBLISH command. |
| 61 | + * If subscribed and has "message" listener, emits the message. |
| 62 | + */ |
| 63 | + publish(channel: RedisKey, message: string): Promise<number> { |
| 64 | + if (this.#subscribed && this.listenerCount("message") > 0) { |
| 65 | + // Emit to listeners (simulates Redis delivering the message) |
| 66 | + this.emit("message", channel, message); |
| 67 | + return Promise.resolve(1); |
| 68 | + } |
| 69 | + // No listeners - message is "lost" (this is the bug!) |
| 70 | + return Promise.resolve(0); |
| 71 | + } |
| 72 | + |
| 73 | + zadd(key: RedisKey, score: number, value: string): Promise<number> { |
| 74 | + if (!this.#queue.has(String(key))) { |
| 75 | + this.#queue.set(String(key), []); |
| 76 | + } |
| 77 | + this.#queue.get(String(key))!.push({ score, value }); |
| 78 | + return Promise.resolve(1); |
| 79 | + } |
| 80 | + |
| 81 | + zrangebyscoreBuffer( |
| 82 | + key: RedisKey, |
| 83 | + _min: number, |
| 84 | + _max: number, |
| 85 | + ): Promise<Buffer[]> { |
| 86 | + const items = this.#queue.get(String(key)) ?? []; |
| 87 | + return Promise.resolve(items.map((i) => Buffer.from(i.value))); |
| 88 | + } |
| 89 | + |
| 90 | + zrem(key: RedisKey, value: Buffer): Promise<number> { |
| 91 | + const items = this.#queue.get(String(key)); |
| 92 | + if (items) { |
| 93 | + const idx = items.findIndex((i) => i.value === value.toString()); |
| 94 | + if (idx >= 0) { |
| 95 | + items.splice(idx, 1); |
| 96 | + return Promise.resolve(1); |
| 97 | + } |
| 98 | + } |
| 99 | + return Promise.resolve(0); |
| 100 | + } |
| 101 | + |
| 102 | + set( |
| 103 | + _key: RedisKey, |
| 104 | + _value: string, |
| 105 | + _ex: string, |
| 106 | + _seconds: number, |
| 107 | + _nx: string, |
| 108 | + ): Promise<string | null> { |
| 109 | + return Promise.resolve("OK"); |
| 110 | + } |
| 111 | + |
| 112 | + del(_key: RedisKey): Promise<number> { |
| 113 | + return Promise.resolve(1); |
| 114 | + } |
| 115 | + |
| 116 | + multi(): MockMulti { |
| 117 | + return new MockMulti(this); |
| 118 | + } |
| 119 | + |
| 120 | + disconnect(): void { |
| 121 | + this.removeAllListeners(); |
| 122 | + } |
| 123 | +} |
| 124 | + |
| 125 | +/** |
| 126 | + * Mock Redis multi/transaction support. |
| 127 | + */ |
| 128 | +class MockMulti { |
| 129 | + #redis: MockRedis; |
| 130 | + #commands: (() => Promise<unknown>)[] = []; |
| 131 | + |
| 132 | + constructor(redis: MockRedis) { |
| 133 | + this.#redis = redis; |
| 134 | + } |
| 135 | + |
| 136 | + zadd(key: RedisKey, score: number, value: string): this { |
| 137 | + this.#commands.push(() => this.#redis.zadd(key, score, value)); |
| 138 | + return this; |
| 139 | + } |
| 140 | + |
| 141 | + async exec(): Promise<[Error | null, unknown][]> { |
| 142 | + const results: [Error | null, unknown][] = []; |
| 143 | + for (const cmd of this.#commands) { |
| 144 | + try { |
| 145 | + const result = await cmd(); |
| 146 | + results.push([null, result]); |
| 147 | + } catch (e) { |
| 148 | + results.push([e as Error, null]); |
| 149 | + } |
| 150 | + } |
| 151 | + return results; |
| 152 | + } |
| 153 | +} |
| 154 | + |
| 155 | +/** |
| 156 | + * DETERMINISTIC TEST: Reproduces the race condition 100% of the time. |
| 157 | + * |
| 158 | + * Proves the bug by controlling callback timing: |
| 159 | + * 1. subscribe() with callback - callback CAPTURED, not executed |
| 160 | + * 2. publish() fires - no handler exists yet |
| 161 | + * 3. Callback triggered - handler attached TOO LATE |
| 162 | + * 4. Assert: message lost (0 listeners at publish time) |
| 163 | + */ |
| 164 | +test("Deterministic: Race condition with callback approach", async () => { |
| 165 | + const receivedMessages: string[] = []; |
| 166 | + const mockSubRedis = new MockRedis(); |
| 167 | + |
| 168 | + // BUGGY: callback-based subscribe |
| 169 | + await mockSubRedis.subscribe("test-channel", () => { |
| 170 | + mockSubRedis.on("message", (_channel, message) => { |
| 171 | + receivedMessages.push(message); |
| 172 | + }); |
| 173 | + }); |
| 174 | + |
| 175 | + // Callback not executed yet |
| 176 | + strictEqual(mockSubRedis.hasSubscribeCallbackPending(), true); |
| 177 | + strictEqual(mockSubRedis.listenerCount("message"), 0); |
| 178 | + |
| 179 | + // Publish BEFORE callback runs |
| 180 | + const listenersAtPublish = mockSubRedis.listenerCount("message"); |
| 181 | + await mockSubRedis.publish("test-channel", "notification"); |
| 182 | + |
| 183 | + // NOW trigger callback (too late!) |
| 184 | + mockSubRedis.triggerSubscribeCallback(); |
| 185 | + |
| 186 | + // Assert: message was LOST |
| 187 | + strictEqual(listenersAtPublish, 0, "No listeners when publish() was called"); |
| 188 | + strictEqual( |
| 189 | + receivedMessages.length, |
| 190 | + 0, |
| 191 | + "Message lost due to race condition", |
| 192 | + ); |
| 193 | + |
| 194 | + mockSubRedis.disconnect(); |
| 195 | +}); |
| 196 | + |
| 197 | +/** |
| 198 | + * DETERMINISTIC TEST: Proves the fix works. |
| 199 | + * |
| 200 | + * With await + sync handler: |
| 201 | + * 1. await subscribe() - wait for confirmation |
| 202 | + * 2. Attach handler synchronously |
| 203 | + * 3. publish() - handler receives message |
| 204 | + * 4. Assert: message received (1 listener at publish time) |
| 205 | + */ |
| 206 | +test("Deterministic: Fixed approach (await + sync handler)", async () => { |
| 207 | + const receivedMessages: string[] = []; |
| 208 | + const mockSubRedis = new MockRedis(); |
| 209 | + |
| 210 | + // FIXED: await subscribe, then attach handler sync |
| 211 | + await mockSubRedis.subscribe("test-channel"); |
| 212 | + mockSubRedis.on("message", (_channel, message) => { |
| 213 | + receivedMessages.push(message); |
| 214 | + }); |
| 215 | + |
| 216 | + // Handler attached immediately |
| 217 | + strictEqual(mockSubRedis.listenerCount("message"), 1); |
| 218 | + |
| 219 | + // Publish AFTER handler attached |
| 220 | + const listenersAtPublish = mockSubRedis.listenerCount("message"); |
| 221 | + await mockSubRedis.publish("test-channel", "notification"); |
| 222 | + |
| 223 | + // Assert: message was RECEIVED |
| 224 | + strictEqual( |
| 225 | + listenersAtPublish, |
| 226 | + 1, |
| 227 | + "Handler attached when publish() was called", |
| 228 | + ); |
| 229 | + strictEqual( |
| 230 | + receivedMessages.length, |
| 231 | + 1, |
| 232 | + "Message received - no race condition", |
| 233 | + ); |
| 234 | + |
| 235 | + mockSubRedis.disconnect(); |
| 236 | +}); |
| 237 | + |
| 238 | +/** |
| 239 | + * REGRESSION TEST: Verifies handler is attached before enqueue is possible. |
| 240 | + * |
| 241 | + * With BUGGY impl: listen() returns before handler attached → race condition |
| 242 | + * With FIXED impl: listen() awaits subscription, attaches handler synchronously |
| 243 | + */ |
| 244 | +test("Regression: RedisMessageQueue handler attached before yield", async () => { |
| 245 | + let subRedisInstance: MockRedis | null = null; |
| 246 | + let callCount = 0; |
| 247 | + |
| 248 | + const mockRedisFactory = () => { |
| 249 | + callCount++; |
| 250 | + const mock = new MockRedis(); |
| 251 | + if (callCount === 2) subRedisInstance = mock; |
| 252 | + return mock as unknown as import("ioredis").Redis; |
| 253 | + }; |
| 254 | + |
| 255 | + const mq = new RedisMessageQueue(mockRedisFactory, { |
| 256 | + pollInterval: { seconds: 60 }, |
| 257 | + channelKey: "test-channel", |
| 258 | + queueKey: "test-queue", |
| 259 | + lockKey: "test-lock", |
| 260 | + }); |
| 261 | + |
| 262 | + const controller = new AbortController(); |
| 263 | + |
| 264 | + try { |
| 265 | + const listening = mq.listen(() => {}, { signal: controller.signal }); |
| 266 | + |
| 267 | + // Yield to let listen() progress |
| 268 | + await new Promise((r) => setTimeout(r, 50)); |
| 269 | + |
| 270 | + // FIXED impl: handler must be attached after yielding |
| 271 | + strictEqual( |
| 272 | + subRedisInstance!.listenerCount("message"), |
| 273 | + 1, |
| 274 | + "Handler must be attached after listen() yields control", |
| 275 | + ); |
| 276 | + |
| 277 | + controller.abort(); |
| 278 | + await listening; |
| 279 | + } finally { |
| 280 | + mq[Symbol.dispose](); |
| 281 | + } |
| 282 | +}); |
0 commit comments