Skip to content

Free, Open Source, Self-Hosted WhatsApp API Gateway

refactor(cache): remove unused session status helpers

Yudhi Armyndharisf99e9e0fe174
diff --git a/docs/03-system-architecture.md b/docs/03-system-architecture.md
index a68456781..ef3adfdd7 100644
--- a/docs/03-system-architecture.md
+++ b/docs/03-system-architecture.md
@@ -292,7 +292,7 @@ export class SomeService {
async saveMedia(filePath: string, data: Buffer) {
await this.storage.putFile(filePath, data); // path-safety guarded
- await this.cache.setSessionStatus('id', 'READY'); // no-op if Redis disabled
+ const cacheUp = await this.cache.isAvailable(); // false when Redis is disabled or unreachable
}
}
```
@@ -1488,11 +1488,12 @@ Migrations that must run on both dialects with different SQL take the same check
There is **no** cache-manager / `CacheModuleOptions` / `redisStore` setup and **no** in-memory cache.
`CacheService` (`src/common/cache/cache.service.ts`) talks to **ioredis directly** and is gated by
-`REDIS_ENABLED` (falling back to the `cache.enabled` config flag). When caching is disabled — or Redis
-is unreachable — the service **fails open**: every read returns `null` and every write is a silent
-no-op, so the app keeps serving from its source of truth. In other words, "no cache configured" means
-**no cache** (recompute), not an in-process LRU. Cache is never the source of truth, and today no
-request path reads from it: its only consumer is the infra status probe (`isAvailable`).
+`REDIS_ENABLED` (falling back to the `cache.enabled` config flag). It stores no values: its only
+consumer is the infra status probe, which calls `isAvailable()` to learn whether Redis answers a ping
+right now. When caching is disabled, or Redis is unreachable, `isAvailable()` returns `false` instead
+of throwing, so the app keeps serving from its source of truth. In other words, "no cache configured"
+means **no cache** (recompute), not an in-process LRU. Cache is never the source of truth, and no
+request path reads from it today.
```typescript
// src/common/cache/cache.service.ts
@@ -1513,25 +1514,6 @@ export class CacheService implements OnModuleDestroy {
this.ensureClient(); // create on first use; ioredis handles (re)connecting
return this.ping(); // reflects live state: false during an outage, true once back
}
-
- // Fail-open reads/writes: unavailable Redis is a no-op, never an error to the caller.
- async getSessionStatus(id: string): Promise<string | null> {
- if (!(await this.isAvailable())) return null;
- try {
- return await this.redis!.get(`session:${id}:status`);
- } catch {
- return null;
- }
- }
-
- async setSessionStatus(id: string, status: string): Promise<void> {
- if (!(await this.isAvailable())) return; // no-op when disabled/unreachable
- try {
- await this.redis!.setex(`session:${id}:status`, /* TTL */ 300, status);
- } catch {
- /* logged + swallowed */
- }
- }
}
```
diff --git a/docs/08-development-guidelines.md b/docs/08-development-guidelines.md
index 8687f9745..3996696b8 100644
--- a/docs/08-development-guidelines.md
+++ b/docs/08-development-guidelines.md
@@ -919,10 +919,9 @@ const sessions = await sessionRepo
### Caching Strategy
Memoize a hot, expensive read in-process with a TTL, as `StatsService` does for its aggregate
-responses (`STATS_CACHE_TTL_MS`, default 30000; `0` disables the memo). `CacheService` is an optional,
-fail-open Redis layer: when Redis is disabled or down every read returns `null` and every write is a
-no-op, so never make a request path depend on it. No request path reads from it today (see
-[3.13.3 Cache Service](./03-system-architecture.md#3133-cache-service)).
+responses (`STATS_CACHE_TTL_MS`, default 30000; `0` disables the memo). `CacheService` is an optional
+Redis client that stores no values and only answers `isAvailable()` for the infra status probe, so no
+request path reads from it (see [3.13.3 Cache Service](./03-system-architecture.md#3133-cache-service)).
### Async Operations
diff --git a/docs/09-testing-strategy.md b/docs/09-testing-strategy.md
index 07108ecfe..cb15a81aa 100644
--- a/docs/09-testing-strategy.md
+++ b/docs/09-testing-strategy.md
@@ -180,7 +180,7 @@ authoritative gate. Current policy:
| Scope | Branches | Functions | Lines | Statements |
| --------------------------- | -------- | --------- | ----- | ---------- |
| Global | 54% | 68% | 60% | 61% |
-| `src/common/cache/` | 34% | 33% | 42% | 42% |
+| `src/common/cache/` | 70% | 75% | 95% | 91% |
| `src/common/security/` | 85% | 95% | 93% | 92% |
| `src/common/services/` | 82% | 91% | 90% | 88% |
| `src/common/storage/` | 75% | 85% | 84% | 80% |
diff --git a/docs/10-devops-infrastructure.md b/docs/10-devops-infrastructure.md
index 785f1a88a..384ffdb14 100644
--- a/docs/10-devops-infrastructure.md
+++ b/docs/10-devops-infrastructure.md
@@ -431,7 +431,7 @@ LOG_FORMAT=json
# CACHE & QUEUE
# ===========================================
# Both are opt-in and both need a reachable Redis, configured with the discrete host/port pair
-# (there is no REDIS_URL). Defaults: no cache at all (CacheService is a no-op and every read falls
+# (there is no REDIS_URL). Defaults: no cache at all (CacheService stores nothing and every read falls
# through to the database — there is no in-memory tier) and inline (non-queued) dispatch.
# REDIS_ENABLED=false
# REDIS_HOST=localhost
diff --git a/package.json b/package.json
index f53357924..3f7302f0b 100644
--- a/package.json
+++ b/package.json
@@ -212,10 +212,10 @@
"statements": 61
},
"./src/common/cache/": {
- "branches": 34,
- "functions": 33,
- "lines": 42,
- "statements": 42
+ "branches": 70,
+ "functions": 75,
+ "lines": 95,
+ "statements": 91
},
"./src/common/security/": {
"branches": 85,
diff --git a/src/common/cache/cache.service.redis.spec.ts b/src/common/cache/cache.service.redis.spec.ts
index feb6d8c0e..ede034069 100644
--- a/src/common/cache/cache.service.redis.spec.ts
+++ b/src/common/cache/cache.service.redis.spec.ts
@@ -119,9 +119,11 @@ describe('CacheService connected response deadlines', () => {
blocked.add('get');
blocked.add('setex');
const recovered = new Promise<void>(resolve => client.once('ready', () => resolve()));
- expect(
- await withinDeadline(Promise.all([service.getSessionStatus('s1'), service.setSessionStatus('s1', 'ready')])),
- ).toEqual([null, undefined]);
+ // The client the service built carries the deadlines, so commands issued on it directly settle too.
+ expect(await withinDeadline(Promise.allSettled([client.get('s1'), client.setex('s1', 60, 'ready')]))).toEqual([
+ expect.objectContaining({ status: 'rejected' }),
+ expect.objectContaining({ status: 'rejected' }),
+ ]);
blocked.clear();
await recovered;
expect(await service.isAvailable()).toBe(true);
diff --git a/src/common/cache/cache.service.spec.ts b/src/common/cache/cache.service.spec.ts
index 774cb2940..a88b1d417 100644
--- a/src/common/cache/cache.service.spec.ts
+++ b/src/common/cache/cache.service.spec.ts
@@ -177,30 +177,6 @@ describe('CacheService Redis-outage resilience', () => {
expect(calls[1][0].db).toBe(1);
});
- it('parses a cached JSON value and reads a miss as null', async () => {
- const get = jest.fn().mockResolvedValueOnce('["a","b"]').mockResolvedValueOnce(null);
- RedisMock.mockImplementation(() => ({ ...fakeClient(jest.fn().mockResolvedValue('PONG')), get }));
- const service = new CacheService(enabledConfig());
-
- expect(await service.getSessionsList()).toEqual(['a', 'b']);
- expect(await service.getSessionsList()).toBeNull();
- });
-
- it('falls back to the source of truth when a cache command fails', async () => {
- const fail = jest.fn().mockRejectedValue(new Error('READONLY'));
- RedisMock.mockImplementation(() => ({
- ...fakeClient(jest.fn().mockResolvedValue('PONG')),
- get: fail,
- setex: fail,
- }));
- const service = new CacheService(enabledConfig());
-
- expect(await service.getSessionInfo('s1')).toBeNull();
- expect(await service.getSessionsStats()).toBeNull();
- await expect(service.setSessionInfo('s1', { id: 's1' } as never)).resolves.toBeUndefined();
- await expect(service.setSessionsStats({} as never)).resolves.toBeUndefined();
- });
-
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);
diff --git a/src/common/cache/cache.service.ts b/src/common/cache/cache.service.ts
index bd1ea6316..5a84512bb 100644
--- a/src/common/cache/cache.service.ts
+++ b/src/common/cache/cache.service.ts
@@ -5,30 +5,6 @@ import { createLogger } from '../services/logger.service';
import { resolveNonNegativeIntEnv } from '../../config/configuration';
import { redisConnectionOptions } from '../../config/redis-options';
-export interface SessionInfo {
- id: string;
- name: string;
- status: string;
- phone?: string;
- pushName?: string;
- connectedAt?: string;
-}
-
-export interface SessionStats {
- active: number;
- total: number;
- byStatus: Record<string, number>;
-}
-
-// TTL constants in seconds
-const TTL = {
- SESSION_STATUS: 300, // 5 min
- SESSION_INFO: 600, // 10 min
- SESSION_QR: 60, // 1 min
- SESSIONS_LIST: 30, // 30 sec
- SESSIONS_STATS: 15, // 15 sec
-};
-
/** Max time to await a cache command or release a socket that stops responding. */
const CACHE_COMMAND_TIMEOUT_MS = 2000;
@@ -147,112 +123,4 @@ export class CacheService implements OnModuleDestroy {
this.ensureClient();
return this.ping();
}
-
- // ========== Session Status ==========
-
- async getSessionStatus(id: string): Promise<string | null> {
- if (!(await this.isAvailable())) return null;
- try {
- return await this.redis!.get(`session:${id}:status`);
- } catch (error) {
- this.logger.warn(`Cache read failed (session:status): ${String(error)}`);
- return null;
- }
- }
-
- async setSessionStatus(id: string, status: string): Promise<void> {
- if (!(await this.isAvailable())) return;
- try {
- await this.redis!.setex(`session:${id}:status`, TTL.SESSION_STATUS, status);
- } catch (error) {
- this.logger.warn(`Cache write failed (session:status): ${String(error)}`);
- }
- }
-
- // ========== Session Info ==========
-
- async getSessionInfo(id: string): Promise<SessionInfo | null> {
- if (!(await this.isAvailable())) return null;
- try {
- const data = await this.redis!.get(`session:${id}:info`);
- return data ? (JSON.parse(data) as SessionInfo) : null;
- } catch (error) {
- this.logger.warn(`Cache read failed (session:info): ${String(error)}`);
- return null;
- }
- }
-
- async setSessionInfo(id: string, info: SessionInfo): Promise<void> {
- if (!(await this.isAvailable())) return;
- try {
- await this.redis!.setex(`session:${id}:info`, TTL.SESSION_INFO, JSON.stringify(info));
- } catch (error) {
- this.logger.warn(`Cache write failed (session:info): ${String(error)}`);
- }
- }
-
- // ========== Session QR ==========
-
- async getSessionQR(id: string): Promise<string | null> {
- if (!(await this.isAvailable())) return null;
- try {
- return await this.redis!.get(`session:${id}:qr`);
- } catch (error) {
- this.logger.warn(`Cache read failed (session:qr): ${String(error)}`);
- return null;
- }
- }
-
- async setSessionQR(id: string, qr: string): Promise<void> {
- if (!(await this.isAvailable())) return;
- try {
- await this.redis!.setex(`session:${id}:qr`, TTL.SESSION_QR, qr);
- } catch (error) {
- this.logger.warn(`Cache write failed (session:qr): ${String(error)}`);
- }
- }
-
- // ========== Sessions List ==========
-
- async getSessionsList(): Promise<string[] | null> {
- if (!(await this.isAvailable())) return null;
- try {
- const data = await this.redis!.get('sessions:list');
- return data ? (JSON.parse(data) as string[]) : null;
- } catch (error) {
- this.logger.warn(`Cache read failed (sessions:list): ${String(error)}`);
- return null;
- }
- }
-
- async setSessionsList(ids: string[]): Promise<void> {
- if (!(await this.isAvailable())) return;
- try {
- await this.redis!.setex('sessions:list', TTL.SESSIONS_LIST, JSON.stringify(ids));
- } catch (error) {
- this.logger.warn(`Cache write failed (sessions:list): ${String(error)}`);
- }
- }
-
- // ========== Sessions Stats ==========
-
- async getSessionsStats(): Promise<SessionStats | null> {
- if (!(await this.isAvailable())) return null;
- try {
- const data = await this.redis!.get('sessions:stats');
- return data ? (JSON.parse(data) as SessionStats) : null;
- } catch (error) {
- this.logger.warn(`Cache read failed (sessions:stats): ${String(error)}`);
- return null;
- }
- }
-
- async setSessionsStats(stats: SessionStats): Promise<void> {
- if (!(await this.isAvailable())) return;
- try {
- await this.redis!.setex('sessions:stats', TTL.SESSIONS_STATS, JSON.stringify(stats));
- } catch (error) {
- this.logger.warn(`Cache write failed (sessions:stats): ${String(error)}`);
- }
- }
}