Free, Open Source, Self-Hosted WhatsApp API Gateway
TypeScript apibotgatewayself-hostedwhatsappwhatsapp-apiwhatsapp-automationwhatsapp-botwhatsapp-gatewaywhatsapp-gateway-apiwhatsapp-webwhatsapp-web-api
fix(cache): recover the Redis cache from outages instead of dying permanently (#885)
Yudhi Armyndharis51bcf67f68b4
diff --git a/CHANGELOG.md b/CHANGELOG.mdindex e25defd8f..1c7f6afa9 100644--- a/CHANGELOG.md+++ b/CHANGELOG.md@@ -23,6 +23,14 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0### Fixed+- **Redis cache now recovers from an outage instead of dying permanently.** When Redis restarted — or+ was unreachable at startup and came back later — the cache client gave up reconnecting after a few+ attempts and was never re-established, so caching stayed off until the entire gateway was restarted.+ The client now reconnects for as long as it takes (bounded backoff) and self-heals the moment Redis+ returns, and a cache operation attempted while disconnected fails fast to the source of truth rather+ than stalling the request. Caching remains best-effort throughout, so an outage only removes the+ speedup — never correctness — and is no longer a latent, restart-only failure.+- **Session scoping on the audit-log and webhook delivery-failure list endpoints.** `GET /api/audit`and `GET /api/webhooks/delivery-failures` now scope their results to the calling key's allowedsessions, matching the rest of the API (`GET /webhooks`, `GET /search`). These two endpoints takediff --git a/src/common/cache/cache.service.spec.ts b/src/common/cache/cache.service.spec.tsindex c18459779..ca5a2355d 100644--- a/src/common/cache/cache.service.spec.ts+++ b/src/common/cache/cache.service.spec.ts@@ -1,6 +1,11 @@import { ConfigService } from '@nestjs/config';+import Redis from 'ioredis';import { CacheService, CACHE_QUIT_TIMEOUT_MS } from './cache.service';+// Auto-mock ioredis so no real socket is opened. The onModuleDestroy suite below injects its own fake+// `redis` and never constructs one, so the mock is inert there; the resilience suite drives it.+jest.mock('ioredis');+describe('CacheService.onModuleDestroy (bounded shutdown)', () => {const makeService = (): CacheService => {const configService = { get: jest.fn().mockReturnValue(false) } as unknown as ConfigService;@@ -42,3 +47,95 @@ describe('CacheService.onModuleDestroy (bounded shutdown)', () => {}});});++// Regression coverage for the Redis-outage recovery bug: the cache used to give up reconnecting after a+// fixed number of failures and never cleared a dead client, so a Redis restart (or a Redis that was down+// at boot and came back) left the cache permanently dead until the whole app was restarted.+describe('CacheService Redis-outage resilience', () => {+ const RedisMock = Redis as unknown as jest.Mock;++ interface FakeClient {+ connect: jest.Mock;+ ping: jest.Mock;+ on: jest.Mock;+ quit: jest.Mock;+ disconnect: jest.Mock;+ }+ const fakeClient = (ping: jest.Mock): FakeClient => ({+ connect: jest.fn().mockResolvedValue(undefined),+ ping,+ on: jest.fn(),+ quit: jest.fn().mockResolvedValue('OK'),+ disconnect: jest.fn(),+ });+ const useClient = (ping: jest.Mock): void => {+ RedisMock.mockImplementation(() => fakeClient(ping));+ };+ // enabled=true purely from config, so the suite is independent of the ambient REDIS_ENABLED env.+ const enabledConfig = (): ConfigService =>+ ({ get: (key: string, def?: unknown) => (key === 'cache.enabled' ? true : def) }) as unknown as ConfigService;++ let savedEnabled: string | undefined;+ beforeEach(() => {+ savedEnabled = process.env.REDIS_ENABLED;+ delete process.env.REDIS_ENABLED;+ RedisMock.mockReset();+ });+ afterEach(() => {+ if (savedEnabled === undefined) delete process.env.REDIS_ENABLED;+ else process.env.REDIS_ENABLED = savedEnabled;+ });++ it('self-heals across a Redis restart without recreating the client', async () => {+ const ping = jest+ .fn()+ .mockResolvedValueOnce('PONG') // connected+ .mockRejectedValueOnce(new Error('connection lost')) // Redis down+ .mockResolvedValueOnce('PONG'); // ioredis reconnected+ useClient(ping);+ const service = new CacheService(enabledConfig());++ expect(await service.isAvailable()).toBe(true);+ expect(await service.isAvailable()).toBe(false); // during the outage+ expect(await service.isAvailable()).toBe(true); // healed++ // One client for the whole lifetime — it is never torn down and recreated on the outage.+ expect(RedisMock).toHaveBeenCalledTimes(1);+ });++ it('never permanently gives up: recovers even after many boot-time failures', async () => {+ const ping = jest.fn();+ for (let i = 0; i < 8; i++) ping.mockRejectedValueOnce(new Error('down')); // 8 > the old hard cap of 5+ ping.mockResolvedValue('PONG'); // Redis finally reachable+ useClient(ping);+ const service = new CacheService(enabledConfig());++ for (let i = 0; i < 8; i++) expect(await service.isAvailable()).toBe(false);+ expect(await service.isAvailable()).toBe(true);++ expect(RedisMock).toHaveBeenCalledTimes(1);+ });++ it('configures ioredis to reconnect forever and fail fast while disconnected', async () => {+ useClient(jest.fn().mockResolvedValue('PONG'));+ const service = new CacheService(enabledConfig());+ await service.isAvailable();++ const opts = (+ RedisMock.mock.calls as Array<[{ retryStrategy: (t: number) => number | null; enableOfflineQueue: boolean }]>+ )[0][0];+ // Never returns null → ioredis keeps reconnecting for any attempt count, small or large.+ expect(opts.retryStrategy(1)).not.toBeNull();+ expect(typeof opts.retryStrategy(1000)).toBe('number');+ // Commands fail fast instead of queueing until reconnect.+ expect(opts.enableOfflineQueue).toBe(false);+ });++ it('does not construct a client when the cache is disabled', async () => {+ const disabled = { get: (_key: string, def?: unknown) => def } as unknown as ConfigService;+ const service = new CacheService(disabled);++ expect(await service.isAvailable()).toBe(false);+ expect(RedisMock).not.toHaveBeenCalled();+ });+});diff --git a/src/common/cache/cache.service.ts b/src/common/cache/cache.service.tsindex e6f27f088..55df15b98 100644--- a/src/common/cache/cache.service.ts+++ b/src/common/cache/cache.service.ts@@ -35,9 +35,6 @@ export class CacheService implements OnModuleDestroy {private readonly logger = createLogger('CacheService');private redis: Redis | null = null;private readonly enabled: boolean;- private connecting = false;- private connectionAttempts = 0;- private readonly maxConnectionAttempts = 5;constructor(private readonly configService: ConfigService) {// Check REDIS_ENABLED env var directly (from saved .env.generated)@@ -46,61 +43,58 @@ export class CacheService implements OnModuleDestroy {this.logger.log(`CacheService: enabled=${this.enabled}, REDIS_ENABLED=${process.env.REDIS_ENABLED}`);- // Don't connect immediately - wait for Redis container to be ready- // Connection will be established on first use via isAvailable()+ // Don't connect immediately - the client is created lazily on first use via isAvailable(), so a+ // Redis container that is not ready at boot doesn't fail startup.}/**- * Try to (re)connect to Redis- * Returns true if connection succeeded+ * Lazily create the single shared Redis client. ioredis owns all (re)connection: the retry strategy+ * never gives up, so the client heals itself whether Redis is down at boot or restarts later — it is+ * created once here and only torn down on shutdown (onModuleDestroy). The previous manual+ * connect/attempt-count logic gave up permanently after a fixed number of failures and never cleared+ * a dead client, so a Redis restart left the cache dead until the whole app was restarted.*/- async tryConnect(): Promise<boolean> {- if (!this.enabled) return false;- if (this.connecting) return false;- if (this.redis && (await this.ping())) return true;+ private ensureClient(): void {+ if (this.redis) return;++ const host = process.env.REDIS_HOST || this.configService.get<string>('REDIS_HOST', 'localhost');+ const port = parseInt(process.env.REDIS_PORT || '', 10) || this.configService.get<number>('REDIS_PORT', 6379);++ this.logger.log(`Connecting to Redis at ${host}:${port}`);++ const redis = new Redis({+ host,+ port,+ username: this.configService.get<string>('REDIS_USERNAME'),+ password: this.configService.get<string>('REDIS_PASSWORD'),+ db: this.configService.get<number>('REDIS_CACHE_DB', 1),+ lazyConnect: true,+ // Cache is best-effort: a command issued while disconnected fails fast (the caller falls back to+ // the source of truth) instead of being queued and stalling the request until reconnect.+ enableOfflineQueue: false,+ maxRetriesPerRequest: 3,+ connectTimeout: this.configService.get<number>('redis.connectTimeoutMs', 5000),+ // Reconnect forever with bounded backoff. Returning null (the previous behavior after 3 tries)+ // makes ioredis abandon reconnection permanently, which is exactly what left the cache dead+ // across a Redis restart.+ retryStrategy: times => Math.min(times * 500, 5000),+ });- this.connecting = true;- this.connectionAttempts++;+ redis.on('error', err => {+ this.logger.warn(`Redis error: ${err.message}`);+ });- try {- const host = process.env.REDIS_HOST || this.configService.get<string>('REDIS_HOST', 'localhost');- const port = parseInt(process.env.REDIS_PORT || '', 10) || this.configService.get<number>('REDIS_PORT', 6379);-- this.logger.log(`Connecting to Redis at ${host}:${port} (attempt ${this.connectionAttempts})`);-- this.redis = new Redis({- host,- port,- username: this.configService.get<string>('REDIS_USERNAME'),- password: this.configService.get<string>('REDIS_PASSWORD'),- db: this.configService.get<number>('REDIS_CACHE_DB', 1),- lazyConnect: true,- maxRetriesPerRequest: 3,- connectTimeout: this.configService.get<number>('redis.connectTimeoutMs', 5000),- retryStrategy: times => {- if (times > 3) return null;- return Math.min(times * 500, 3000);- },- });-- this.redis.on('error', err => {- this.logger.warn(`Redis error: ${err.message}`);- });-- this.redis.on('connect', () => {- this.logger.log('Redis cache connected');- this.connectionAttempts = 0; // Reset on success- });-- await this.redis.connect();- this.connecting = false;- return true;- } catch (error) {- this.logger.warn(`Redis connection failed (attempt ${this.connectionAttempts}): ${String(error)}`);- this.redis = null;- this.connecting = false;- return false;- }+ redis.on('connect', () => {+ this.logger.log('Redis cache connected');+ });++ this.redis = redis;++ // Kick off the initial connection but don't await it — ioredis keeps retrying per retryStrategy on+ // failure, and isAvailable()'s ping reflects the live state, so a down-at-boot Redis never blocks a+ // caller. The first isAvailable() while still connecting reports false; the next one, once ready,+ // reports true.+ redis.connect().catch(() => undefined);}private async ping(): Promise<boolean> {@@ -140,11 +134,10 @@ export class CacheService implements OnModuleDestroy {async isAvailable(): Promise<boolean> {if (!this.enabled) return false;- // If not connected, try to connect (with rate limiting)- if (!this.redis && this.connectionAttempts < this.maxConnectionAttempts) {- await this.tryConnect();- }-+ // Create the client on first use, then let ioredis manage (re)connection. A ping reflects whether+ // the connection is live right now — false during an outage (caller bypasses to the DB), true again+ // once ioredis has reconnected.+ this.ensureClient();return this.ping();}