Free, Open Source, Self-Hosted WhatsApp API Gateway
TypeScript apibotgatewayself-hostedwhatsappwhatsapp-apiwhatsapp-automationwhatsapp-botwhatsapp-gatewaywhatsapp-gateway-apiwhatsapp-webwhatsapp-web-api
refactor(session): give the transient failure reason its own store
Yudhi Armyndharis2fa09073ed56
diff --git a/src/modules/session/logout-teardown-race.spec.ts b/src/modules/session/logout-teardown-race.spec.tsindex d3485935e..cf037b22e 100644--- a/src/modules/session/logout-teardown-race.spec.ts+++ b/src/modules/session/logout-teardown-race.spec.ts@@ -4,6 +4,7 @@ import { Repository, DataSource } from 'typeorm';import { BadGatewayException, ConflictException } from '@nestjs/common';import { ConfigService } from '@nestjs/config';import { SessionService } from './session.service';+import { SessionErrorStore } from './session-error-store.service';import { Session, SessionStatus } from './entities/session.entity';import { Message } from '../message/entities/message.entity';import { EngineFactory } from '../../engine/engine.factory';@@ -89,6 +90,7 @@ describe('SessionService logout() name-scoped teardown fence', () => {const module: TestingModule = await Test.createTestingModule({providers: [SessionService,+ SessionErrorStore,{ provide: getRepositoryToken(Session, 'data'), useValue: repository },{ provide: getRepositoryToken(Message, 'data'), useValue: messageRepository },{ provide: getDataSourceToken('data'), useValue: dataSource },diff --git a/src/modules/session/session-error-store.service.ts b/src/modules/session/session-error-store.service.tsnew file mode 100644index 000000000..38ac928bb--- /dev/null+++ b/src/modules/session/session-error-store.service.ts@@ -0,0 +1,51 @@+import { Injectable } from '@nestjs/common';+import { Session, SessionStatus } from './entities/session.entity';++/**+ * The transient reason a session last failed, or what the operator must do about it.+ *+ * It is deliberately in memory and not a column: it describes the CURRENT process's attempt, and a+ * restart that clears it is correct — a session whose reason was "Chromium failed to launch" should+ * not still say so after a successful restart.+ *+ * It lives here rather than in SessionService because it was the one piece of state that crossed a+ * boundary there: eight lifecycle paths write it, and exactly one reader — the session read model —+ * consumes it. Two concerns, one map.+ *+ * Every method is SYNCHRONOUS by contract. Two writers sit in synchronous void engine callbacks, and+ * one runs three statements before an `engines.delete(id)` whose ordering the surrounding comment+ * explicitly forbids reordering. An async setter here would silently reorder that.+ */+@Injectable()+export class SessionErrorStore {+ private readonly errors = new Map<string, string>();++ /** Record why a session failed, or what it is waiting on. */+ set(sessionId: string, reason: string): void {+ this.errors.set(sessionId, reason);+ }++ /** The recorded reason, if any. `attachTo` is the projection; this is the raw read. */+ get(sessionId: string): string | undefined {+ return this.errors.get(sessionId);+ }++ /** Drop the reason — the session recovered, re-initialised, or was deleted. */+ clear(sessionId: string): void {+ this.errors.delete(sessionId);+ }++ /**+ * Populate the transient `lastError` field. A FAILED session always carries its failure reason, and+ * an ACTION_REQUIRED session carries what the operator must do (e.g. the whatsapp-web.js+ * onboarding-modal fallback, #982); any other status clears it, so a recovered session never shows+ * a stale reason even while the entry is still held.+ */+ attachTo(session: Session): Session {+ session.lastError =+ session.status === SessionStatus.FAILED || session.status === SessionStatus.ACTION_REQUIRED+ ? this.errors.get(session.id)+ : undefined;+ return session;+ }+}diff --git a/src/modules/session/session.module.ts b/src/modules/session/session.module.tsindex 9e322345b..089577294 100644--- a/src/modules/session/session.module.ts+++ b/src/modules/session/session.module.ts@@ -6,6 +6,7 @@ import { SessionService } from './session.service';import { SessionLidResolver } from './session-lid-resolver.service';import { SessionLivenessWatchdog } from './session-liveness-watchdog.service';import { MessageProjector } from './message-projector.service';+import { SessionErrorStore } from './session-error-store.service';import { SessionController } from './session.controller';import { WebhookModule } from '../webhook/webhook.module';import { StatusStoreModule } from '../status-store/status-store.module';@@ -15,7 +16,7 @@ import { StatusStoreModule } from '../status-store/status-store.module';// one-directional — no forwardRef() needed.imports: [TypeOrmModule.forFeature([Session, Message], 'data'), WebhookModule, StatusStoreModule],controllers: [SessionController],- providers: [SessionService, SessionLidResolver, SessionLivenessWatchdog, MessageProjector],+ providers: [SessionService, SessionErrorStore, SessionLidResolver, SessionLivenessWatchdog, MessageProjector],exports: [SessionService, MessageProjector],})export class SessionModule {}diff --git a/src/modules/session/session.service.spec.ts b/src/modules/session/session.service.spec.tsindex 944996439..950d52b02 100644--- a/src/modules/session/session.service.spec.ts+++ b/src/modules/session/session.service.spec.ts@@ -1,3 +1,4 @@+import { SessionErrorStore } from './session-error-store.service';import { Test, TestingModule } from '@nestjs/testing';import { getRepositoryToken, getDataSourceToken } from '@nestjs/typeorm';import { Repository, DataSource, In } from 'typeorm';@@ -189,6 +190,7 @@ describe('SessionService', () => {const module: TestingModule = await Test.createTestingModule({providers: [SessionService,+ SessionErrorStore,{provide: getRepositoryToken(Session, 'data'),useValue: repository,@@ -1240,7 +1242,7 @@ describe('SessionService', () => {}expect(state.attempts).toBe(12);- expect(i.sessionErrors.has('sess-uuid-1')).toBe(false); // never terminally FAILED+ expect(i.sessionErrors.get('sess-uuid-1')).toBeUndefined(); // never terminally FAILEDexpect(jest.getTimerCount()).toBe(1); // still exactly one pending timer// The 12th schedule computed its delay with attempts=11: 5000*2^11 ≈ 10.24M ms, clamped to@@ -1302,7 +1304,7 @@ describe('SessionService', () => {i.scheduleReconnect('sess-uuid-1', createMockSession()); // attempt 3/3 still schedulesexpect(state.attempts).toBe(3);- expect(i.sessionErrors.has('sess-uuid-1')).toBe(false);+ expect(i.sessionErrors.get('sess-uuid-1')).toBeUndefined();i.scheduleReconnect('sess-uuid-1', createMockSession()); // budget exhausted → terminal FAILEDexpect(state.attempts).toBe(3); // no further attempt consumed@@ -1923,13 +1925,13 @@ describe('SessionService', () => {callbacks.onError?.('chromium missing');const sessionErrors = (service as unknown as { sessionErrors: Map<string, string> }).sessionErrors;- expect(sessionErrors.has('sess-uuid-1')).toBe(true); // precondition: the FAILED reason is recorded+ expect(sessionErrors.get('sess-uuid-1')).toBeDefined(); // precondition: the FAILED reason is recorded(repository.findOne as jest.Mock).mockResolvedValue(createMockSession({ status: SessionStatus.FAILED }));await service.delete('sess-uuid-1');// Without cleanup, the entry would linger forever keyed by a deleted UUID (unbounded growth).- expect(sessionErrors.has('sess-uuid-1')).toBe(false);+ expect(sessionErrors.get('sess-uuid-1')).toBeUndefined();});it('does not surface lastError once the session has recovered', async () => {@@ -5167,7 +5169,7 @@ describe('SessionService', () => {// clears it in its finally.expect(intern().initializingSessions.has('sess-uuid-1')).toBe(false);expect(intern().reconnectStates.has('sess-uuid-1')).toBe(false);- expect(intern().sessionErrors.has('sess-uuid-1')).toBe(false);+ expect(intern().sessionErrors.get('sess-uuid-1')).toBeUndefined();},);diff --git a/src/modules/session/session.service.ts b/src/modules/session/session.service.tsindex 128dd4296..c3e73aa00 100644--- a/src/modules/session/session.service.ts+++ b/src/modules/session/session.service.ts@@ -27,6 +27,7 @@ import { decideReconnect, type ReconnectAttemptState } from './reconnect-policy'import { SessionLidResolver } from './session-lid-resolver.service';import { SessionLivenessWatchdog } from './session-liveness-watchdog.service';import { MessageProjector } from './message-projector.service';+import { SessionErrorStore } from './session-error-store.service';import { resolveEngineInitTimeoutMs } from '../../engine/engine-init-timeout';import { paginate, ListOptions, resolveListWindow } from '../../common/utils/paginate';import { isUniqueConstraintError } from '../../common/utils/unique-constraint.util';@@ -154,10 +155,6 @@ export class SessionService implements OnModuleDestroy, OnModuleInit, OnApplicatprivate get engines(): EngineRegistry {return this.engineRegistry;}- // Transient, human-readable reason for the most recent terminal engine failure,- // keyed by session id. Surfaced on read so the dashboard can explain a FAILED- // status; cleared when the session re-initializes or becomes ready.- private sessionErrors: Map<string, string> = new Map();// Reconnection state per sessionprivate reconnectStates: Map<string, ReconnectState> = new Map();@@ -229,6 +226,7 @@ export class SessionService implements OnModuleDestroy, OnModuleInit, OnApplicatprivate readonly lidResolver: SessionLidResolver,private readonly watchdog: SessionLivenessWatchdog,private readonly messages: MessageProjector,+ private readonly sessionErrors: SessionErrorStore,private readonly eventsGateway: EventsGateway,private readonly webhookService: WebhookService,private readonly hookManager: HookManager,@@ -559,18 +557,9 @@ export class SessionService implements OnModuleDestroy, OnModuleInit, OnApplicatreturn this.attachLastError(session);}- /**- * Populate the transient `lastError` field from the in-memory error map. A FAILED session always- * carries its failure reason, and an ACTION_REQUIRED session carries what the operator must do- * (e.g. the whatsapp-web.js onboarding-modal fallback, #982); any other status clears it so a- * recovered session never shows a stale reason.- */+ /** See SessionErrorStore — the reason map and this projection live together. */private attachLastError(session: Session): Session {- session.lastError =- session.status === SessionStatus.FAILED || session.status === SessionStatus.ACTION_REQUIRED- ? this.sessionErrors.get(session.id)- : undefined;- return session;+ return this.sessionErrors.attachTo(session);}async findByName(name: string): Promise<Session> {@@ -695,7 +684,7 @@ export class SessionService implements OnModuleDestroy, OnModuleInit, OnApplicatthis.lastDispatchedStatus.delete(id);// Drop the FAILED-reason entry too: it's keyed by a now-deleted UUID that can never be read// again, so leaving it would grow the map without bound across create/fail/delete churn.- this.sessionErrors.delete(id);+ this.sessionErrors.clear(id);// The stuck-auth recovery budget is keyed by id; a committed delete frees it (and a recreated// session under the same name gets a fresh UUID + fresh budget). Left only on a committed// delete so a failed/409 delete — the session still exists — keeps the budget intact.@@ -932,7 +921,7 @@ export class SessionService implements OnModuleDestroy, OnModuleInit, OnApplicat});this.engines.set(id, engine);// Clear any prior failure reason before a fresh start.- this.sessionErrors.delete(id);+ this.sessionErrors.clear(id);// Mark INITIALIZING before engine.initialize(): the engine drives status forward// (QR_READY -> AUTHENTICATING -> READY) through the callbacks below while it@@ -1277,7 +1266,7 @@ export class SessionService implements OnModuleDestroy, OnModuleInit, OnApplicat}// A fresh READY stretch starts the watchdog's failure budget clean too.this.watchdog.clear(id);- this.sessionErrors.delete(id);+ this.sessionErrors.clear(id);// READY proves any in-flight stuck-auth recovery succeeded (or none was needed), so the// one-shot recovery budget is re-armed for a future episode.this.stuckAuthRecoveryUsed.delete(id);