Skip to content

Free, Open Source, Self-Hosted WhatsApp API Gateway

fix(events): bound RedisIoAdapter shutdown so a Redis outage cannot hang app.close()

Yudhi Armyndharis72f3bb65cfba
diff --git a/src/modules/events/redis-io.adapter.spec.ts b/src/modules/events/redis-io.adapter.spec.ts
index 11bbd09c8..f13ca8701 100644
--- a/src/modules/events/redis-io.adapter.spec.ts
+++ b/src/modules/events/redis-io.adapter.spec.ts
@@ -10,6 +10,7 @@ const redisInstances: FakeRedis[] = [];
class FakeRedis {
readonly handlers: Record<string, (err: Error) => void> = {};
quit = jest.fn().mockResolvedValue('OK');
+ disconnect = jest.fn();
constructor(public readonly opts?: unknown) {
redisInstances.push(this);
}
@@ -32,7 +33,7 @@ jest.mock('@socket.io/redis-adapter', () => ({
createAdapter: (pub: unknown, sub: unknown) => createAdapterMock(pub, sub),
}));
-import { RedisIoAdapter, isWsRedisEnabled, wsRedisOptions } from './redis-io.adapter';
+import { RedisIoAdapter, isWsRedisEnabled, wsRedisOptions, WS_REDIS_QUIT_TIMEOUT_MS } from './redis-io.adapter';
import { IoAdapter } from '@nestjs/platform-socket.io';
import type { Server } from 'socket.io';
@@ -152,6 +153,9 @@ describe('RedisIoAdapter', () => {
expect(pub.quit).toHaveBeenCalledTimes(1);
expect(sub.quit).toHaveBeenCalledTimes(1);
+ // Always release the socket, so a clean quit still can't leave the reconnect timer alive.
+ expect(pub.disconnect).toHaveBeenCalledTimes(1);
+ expect(sub.disconnect).toHaveBeenCalledTimes(1);
expect(closeSpy).toHaveBeenCalledWith(server);
} finally {
createSpy.mockRestore();
@@ -159,6 +163,35 @@ describe('RedisIoAdapter', () => {
}
});
+ it('does not hang when quit() never resolves (Redis down at shutdown), then force-disconnects', async () => {
+ jest.useFakeTimers();
+ process.env.REDIS_ENABLED = 'true';
+ const { server } = fakeServer();
+ const createSpy = withBaseServer(server);
+ const closeSpy = jest.spyOn(IoAdapter.prototype, 'close').mockResolvedValue(undefined);
+ try {
+ const adapter = new RedisIoAdapter({} as never);
+ adapter.createIOServer(2785);
+ const [pub, sub] = redisInstances;
+ // The exact outage shape: quit() queued to the offline queue, never settles.
+ pub.quit.mockReturnValue(new Promise(() => undefined));
+ sub.quit.mockReturnValue(new Promise(() => undefined));
+
+ const closed = adapter.close(server);
+ // Drive the per-client deadline; without it the await would block forever.
+ await jest.advanceTimersByTimeAsync(WS_REDIS_QUIT_TIMEOUT_MS + 10);
+ await expect(closed).resolves.toBeUndefined();
+
+ expect(pub.disconnect).toHaveBeenCalledTimes(1);
+ expect(sub.disconnect).toHaveBeenCalledTimes(1);
+ expect(closeSpy).toHaveBeenCalledWith(server);
+ } finally {
+ jest.useRealTimers();
+ createSpy.mockRestore();
+ closeSpy.mockRestore();
+ }
+ });
+
it('is safe to close when Redis was never enabled (no clients to quit)', async () => {
delete process.env.REDIS_ENABLED;
const { server } = fakeServer();
diff --git a/src/modules/events/redis-io.adapter.ts b/src/modules/events/redis-io.adapter.ts
index 81b5c1736..7bf679ed9 100644
--- a/src/modules/events/redis-io.adapter.ts
+++ b/src/modules/events/redis-io.adapter.ts
@@ -7,6 +7,9 @@ import { createLogger } from '../../common/services/logger.service';
const logger = createLogger('RedisIoAdapter');
+/** Max time to await a graceful `quit()` per client on shutdown before force-disconnecting. */
+export const WS_REDIS_QUIT_TIMEOUT_MS = 2000;
+
/**
* Whether cross-replica WebSocket fan-out is switched on. Same `REDIS_ENABLED === 'true'` gate the
* throttler and cache read at boot, so a deployment already using Redis for those gets event
@@ -87,9 +90,32 @@ export class RedisIoAdapter extends IoAdapter {
/** Close the pub/sub connections so a shutdown does not leak them. Called by Nest on app close. */
async close(server: Server): Promise<void> {
- await Promise.allSettled([this.pubClient?.quit(), this.subClient?.quit()]);
+ await Promise.allSettled([this.quitClient(this.pubClient), this.quitClient(this.subClient)]);
this.pubClient = undefined;
this.subClient = undefined;
await super.close(server);
}
+
+ /**
+ * Release one client on shutdown without ever blocking. `quit()` waits for the QUIT reply, which
+ * never arrives on a half-open/partitioned socket — and with the never-give-up retryStrategy and
+ * ioredis's default `enableOfflineQueue:true`, quit() is queued and hangs indefinitely rather
+ * than rejecting. Race it against a short deadline, then ALWAYS `disconnect()` in the finally so
+ * the socket and its reconnect timer are gone regardless of connection state (mirrors
+ * CacheService/RedisThrottlerStorage). disconnect() is idempotent after a clean quit.
+ */
+ private async quitClient(client: Redis | undefined): Promise<void> {
+ if (!client) return;
+ let timer: NodeJS.Timeout | undefined;
+ const deadline = new Promise<void>(resolve => {
+ timer = setTimeout(resolve, WS_REDIS_QUIT_TIMEOUT_MS);
+ timer.unref();
+ });
+ try {
+ await Promise.race([client.quit().catch(() => undefined), deadline]);
+ } finally {
+ if (timer) clearTimeout(timer);
+ client.disconnect();
+ }
+ }
}