Free, Open Source, Self-Hosted WhatsApp API Gateway
TypeScript apibotgatewayself-hostedwhatsappwhatsapp-apiwhatsapp-automationwhatsapp-botwhatsapp-gatewaywhatsapp-gateway-apiwhatsapp-webwhatsapp-web-api
refactor: engine/session lifecycle correctness fixes
Yudhi Armyndharis0ae88bfac045
diff --git a/src/core/plugins/plugin-capability-context.ts b/src/core/plugins/plugin-capability-context.tsindex 78f02b367..343b94296 100644--- a/src/core/plugins/plugin-capability-context.ts+++ b/src/core/plugins/plugin-capability-context.ts@@ -3,7 +3,7 @@ import { AsyncLocalStorage } from 'async_hooks';import type { HookManager, HookEvent } from '../hooks';import type { LidMappingStore } from '../../engine/identity/lid-mapping-store.service';import type { IWhatsAppEngine } from '../../engine/interfaces/whatsapp-engine.interface';-import { toNeutralJid, userPart } from '../../engine/identity/wa-id';+import { toNeutralJid } from '../../engine/identity/wa-id';import { ConversationMappingConflict } from '../../modules/integration/conversation-mapping.service';import { createLogger } from '../../common/services/logger.service';import type { MessageService } from '../../modules/message/message.service';@@ -277,7 +277,7 @@ export class PluginCapabilityContext {// itself is a synchronous host lid->phone lookup, not an engine call, mirroring the webhook// from-filter. Not `async` (nothing to await) — a resolved promise satisfies the signature.this.resolveEngineRead(plugin, sessionId);- return Promise.resolve(toNeutralJid(chatId, jid => this.lidMappingStore?.getCached(userPart(jid)) ?? null));+ return Promise.resolve(toNeutralJid(chatId, jid => this.lidMappingStore?.resolveLid(jid) ?? null));},} satisfies PluginEngineReadCapability;}diff --git a/src/engine/adapters/baileys-lifecycle.ts b/src/engine/adapters/baileys-lifecycle.tsindex 59d840ce8..a26824cd3 100644--- a/src/engine/adapters/baileys-lifecycle.ts+++ b/src/engine/adapters/baileys-lifecycle.ts@@ -204,7 +204,7 @@ export class BaileysLifecycle {}// An internal reconnect (transient drop) overwrites this.sock WITHOUT going through- // disconnect/logout/destroy, so the previous socket's WebSocket and the 13 ev listeners we+ // disconnect/logout/destroy, so the previous socket's WebSocket and the 15 ev listeners we// register below would leak on every reconnect. Tear the prior socket down first. Detach OUR// connection.update listener BEFORE end(): Baileys' own end() synchronously emits a synthetic// connection.update {connection:'close'}, which — if still wired — would re-enter@@ -224,6 +224,7 @@ export class BaileysLifecycle {previous.ev.removeAllListeners('lid-mapping.update');previous.ev.removeAllListeners('group-participants.update');previous.ev.removeAllListeners('groups.update');+ previous.ev.removeAllListeners('group.join-request');previous.ev.removeAllListeners('call');previous.ev.removeAllListeners('presence.update');void previous.end(undefined);@@ -271,7 +272,16 @@ export class BaileysLifecycle {});this.sock = sock;- sock.ev.on('creds.update', () => void saveCreds());+ sock.ev.on(+ 'creds.update',+ () =>+ void saveCreds().catch(err => {+ this.host.logger.warn('Baileys creds.update save failed', {+ sessionId: this.host.config.sessionId,+ error: err instanceof Error ? err.message : String(err),+ });+ }),+ );sock.ev.on('connection.update', update => this.handleConnectionUpdate(update));sock.ev.on('messages.upsert', event => this.host.handleMessagesUpsert(event));sock.ev.on('messages.update', updates => this.host.handleMessagesUpdate(updates));diff --git a/src/engine/identity/lid-mapping-store.service.ts b/src/engine/identity/lid-mapping-store.service.tsindex 4595ba4e5..afea570d7 100644--- a/src/engine/identity/lid-mapping-store.service.ts+++ b/src/engine/identity/lid-mapping-store.service.ts@@ -2,6 +2,7 @@ import { Injectable, OnModuleInit } from '@nestjs/common';import { InjectRepository } from '@nestjs/typeorm';import { Repository } from 'typeorm';import { LidMapping } from './lid-mapping.entity';+import { userPart } from './wa-id';import { createLogger } from '../../common/services/logger.service';import { resolveNonNegativeIntEnv } from '../../config/configuration';@@ -22,6 +23,12 @@ export interface LidMappingStore {* seen. A miss is warmed from the persisted table in the background, so a later read can hit.*/getCached(lid: string): string | null | undefined;+ /**+ * Resolve any WA JID through the mirror: the phone digits for its user part, `null` when the lid+ * is known-unresolved or never seen. The webhook filter match, automation-rule match, plugin+ * engine reads, and status contact grouping all resolve through this one method so they agree.+ */+ resolveLid(jid: string): string | null;/** Sync reverse lookup: the lids currently mapped to this phone (used by the message from-filter). */lidsForPhone(phone: string): string[];/** Write-through, last-write-wins: update the cache + persist. A `null` phone records a negative result. */@@ -106,6 +113,10 @@ export class LidMappingStoreService implements LidMappingStore, OnModuleInit {return undefined;}+ resolveLid(jid: string): string | null {+ return this.getCached(userPart(jid)) ?? null;+ }+lidsForPhone(phone: string): string[] {const set = this.phoneToLids.get(phone);return set ? [...set] : [];diff --git a/src/engine/index.ts b/src/engine/index.tsnew file mode 100644index 000000000..4d71af89e--- /dev/null+++ b/src/engine/index.ts@@ -0,0 +1,4 @@+// Engine public surface for code outside src/engine: re-exported here so modules never reach into+// adapters/ internals. Intentionally narrow — add a symbol only when an outside consumer needs it.+export { BaileysStoredMessage } from './adapters/baileys-stored-message.entity';+export { inboundMediaMaxBytes } from './adapters/inbound-media-cap';diff --git a/src/modules/automation/automation-rules.service.ts b/src/modules/automation/automation-rules.service.tsindex ae4e4f108..383eb7860 100644--- a/src/modules/automation/automation-rules.service.ts+++ b/src/modules/automation/automation-rules.service.ts@@ -4,7 +4,6 @@ import { ConfigService } from '@nestjs/config';import { InjectRepository } from '@nestjs/typeorm';import { Repository } from 'typeorm';import { createLogger } from '../../common/services/logger.service';-import { userPart } from '../../engine/identity/wa-id';import { LidMappingStoreService } from '../../engine/identity/lid-mapping-store.service';import { evaluateFilters } from '../webhook/filters/filter-evaluator';import type { MessageService } from '../message/message.service';@@ -143,7 +142,7 @@ export class AutomationRulesService {// Same lid->phone resolution the webhook filter match uses, so a phone-valued sender condition// matches a lid-addressed sender identically in both places.- const resolveLid = (jid: string): string | null => this.lidMappingStore?.getCached(userPart(jid)) ?? null;+ const resolveLid = (jid: string): string | null => this.lidMappingStore?.resolveLid(jid) ?? null;// First match wins: one inbound message never produces more than one automated reply, and rule// order (creation order) is the tiebreak the operator can reason about.diff --git a/src/modules/message/bulk-message.service.ts b/src/modules/message/bulk-message.service.tsindex 12e6b64f5..92aa6621e 100644--- a/src/modules/message/bulk-message.service.ts+++ b/src/modules/message/bulk-message.service.ts@@ -10,6 +10,7 @@ import { ConfigService } from '@nestjs/config';import { InjectRepository } from '@nestjs/typeorm';import { In, Not, QueryDeepPartialEntity, Repository } from 'typeorm';import { createHash, randomUUID } from 'crypto';+import { setTimeout } from 'node:timers/promises';import {MessageBatch,BatchStatus,@@ -578,7 +579,7 @@ export class BulkMessageService implements OnApplicationBootstrap {// Delay before next message (except for last)if (i < batch.messages.length - 1 && this.processingBatches.get(batch.id)) {const delay = this.calculateDelay(batch.options);- await this.sleep(delay);+ await setTimeout(delay);}return true;}@@ -804,8 +805,4 @@ export class BulkMessageService implements OnApplicationBootstrap {}return delay;}-- private sleep(ms: number): Promise<void> {- return new Promise(resolve => setTimeout(resolve, ms));- }}diff --git a/src/modules/message/media-cap.util.ts b/src/modules/message/media-cap.util.tsindex 011b74131..cc8a06961 100644--- a/src/modules/message/media-cap.util.ts+++ b/src/modules/message/media-cap.util.ts@@ -1,5 +1,5 @@import { PayloadTooLargeException } from '@nestjs/common';-import { inboundMediaMaxBytes } from '../../engine/adapters/inbound-media-cap';+import { inboundMediaMaxBytes } from '../../engine';/*** Accept the historical `data:<mime>;base64,<payload>` form without passing its metadata prefix todiff --git a/src/modules/session/reconnect-policy.ts b/src/modules/session/reconnect-policy.tsindex 283f0ab1c..5c5daccbf 100644--- a/src/modules/session/reconnect-policy.ts+++ b/src/modules/session/reconnect-policy.ts@@ -59,7 +59,7 @@ export const RECONNECT_LOOP_ALERT_INTERVAL_ATTEMPTS = 5;/** Upper bound on a computed backoff delay (see clampReconnectDelay). */export const RECONNECT_DELAY_CAP_MS = 3_600_000;-function clampNumber(value: number, min: number, max: number): number {+export function clampNumber(value: number, min: number, max: number): number {return Math.min(Math.max(value, min), max);}diff --git a/src/modules/session/session-engine-controls.ts b/src/modules/session/session-engine-controls.tsindex a5dc479fa..451fc8e92 100644--- a/src/modules/session/session-engine-controls.ts+++ b/src/modules/session/session-engine-controls.ts@@ -6,7 +6,7 @@ import { Message } from '../message/entities/message.entity';import { MessageBatch } from '../message/entities/message-batch.entity';import { Webhook } from '../webhook/entities/webhook.entity';import { Template } from '../template/entities/template.entity';-import { BaileysStoredMessage } from '../../engine/adapters/baileys-stored-message.entity';+import { BaileysStoredMessage } from '../../engine';import { EngineFactory } from '../../engine/engine.factory';import { EngineRegistry } from '../../engine/engine-registry.service';import { SessionErrorStore } from './session-error-store.service';diff --git a/src/modules/session/session-engine-lifecycle.service.ts b/src/modules/session/session-engine-lifecycle.service.tsindex d9b868b63..3b44e6016 100644--- a/src/modules/session/session-engine-lifecycle.service.ts+++ b/src/modules/session/session-engine-lifecycle.service.ts@@ -5,7 +5,7 @@ import { Repository, DataSource } from 'typeorm';import { Session, SessionStatus } from './entities/session.entity';import { EngineFactory } from '../../engine/engine.factory';import { EngineRegistry } from '../../engine/engine-registry.service';-import { decideReconnect, type ReconnectAttemptState } from './reconnect-policy';+import { decideReconnect, clampNumber, type ReconnectAttemptState } from './reconnect-policy';import { SessionLivenessWatchdog } from './session-liveness-watchdog.service';import { MessageProjector } from './message-projector.service';import { SessionErrorStore } from './session-error-store.service';@@ -57,8 +57,6 @@ const RECONNECT_BASE_DELAY_MIN_MS = 1000;const RECONNECT_BASE_DELAY_MAX_MS = 300_000;const RECONNECT_MAX_ATTEMPTS_CAP = 20;-const clampNumber = (n: number, min: number, max: number): number => Math.min(Math.max(n, min), max);-/** Coerce + clamp the untyped session.config reconnect knobs to finite, bounded values. Defaults are* a 5000ms base delay and UNLIMITED attempts (`Infinity`): a long-lived session must keep retrying* (the backoff parks at the 1h cap) instead of dying permanently after ~2.5 minutes. An EXPLICITdiff --git a/src/modules/session/session.service.spec.ts b/src/modules/session/session.service.spec.tsindex 985fe9bb3..4c23e6911 100644--- a/src/modules/session/session.service.spec.ts+++ b/src/modules/session/session.service.spec.ts@@ -5732,15 +5732,20 @@ describe('SessionService', () => {{ id: 'a', name: 'A' },{ id: 'b', name: 'B' },]);- jest.spyOn(service as unknown as { delay: () => Promise<void> }, 'delay').mockResolvedValue(undefined);const startSpy = jest.spyOn(service, 'start').mockResolvedValue(undefined as never);- service.onApplicationBootstrap();- await autoStartRun();+ jest.useFakeTimers();+ try {+ service.onApplicationBootstrap();+ await jest.advanceTimersByTimeAsync(2_000); // the inter-launch throttle+ await autoStartRun();- expect(startSpy).toHaveBeenCalledTimes(2);- expect(startSpy).toHaveBeenCalledWith('a');- expect(startSpy).toHaveBeenCalledWith('b');+ expect(startSpy).toHaveBeenCalledTimes(2);+ expect(startSpy).toHaveBeenCalledWith('a');+ expect(startSpy).toHaveBeenCalledWith('b');+ } finally {+ jest.useRealTimers();+ }});it('keeps starting the remaining sessions when one fails', async () => {@@ -5749,16 +5754,21 @@ describe('SessionService', () => {{ id: 'a', name: 'A' },{ id: 'b', name: 'B' },]);- jest.spyOn(service as unknown as { delay: () => Promise<void> }, 'delay').mockResolvedValue(undefined);const startSpy = jest.spyOn(service, 'start').mockRejectedValueOnce(new Error('boom')).mockResolvedValueOnce(undefined as never);- service.onApplicationBootstrap();- await autoStartRun();+ jest.useFakeTimers();+ try {+ service.onApplicationBootstrap();+ await jest.advanceTimersByTimeAsync(2_000); // the inter-launch throttle+ await autoStartRun();- expect(startSpy).toHaveBeenCalledTimes(2);+ expect(startSpy).toHaveBeenCalledTimes(2);+ } finally {+ jest.useRealTimers();+ }});// Nest binds the HTTP listener only after every bootstrap hook settles, and a launch is a@@ -5790,16 +5800,21 @@ describe('SessionService', () => {{ id: 'b', name: 'B' },{ id: 'c', name: 'C' },]);- jest.spyOn(service as unknown as { delay: () => Promise<void> }, 'delay').mockResolvedValue(undefined);const startSpy = jest.spyOn(service, 'start').mockImplementation(() => {(service as unknown as { shuttingDown: boolean }).shuttingDown = true;return Promise.resolve(undefined as never);});- service.onApplicationBootstrap();- await autoStartRun();+ jest.useFakeTimers();+ try {+ service.onApplicationBootstrap();+ await jest.advanceTimersByTimeAsync(2_000); // the inter-launch throttle+ await autoStartRun();- expect(startSpy).toHaveBeenCalledTimes(1);+ expect(startSpy).toHaveBeenCalledTimes(1);+ } finally {+ jest.useRealTimers();+ }});// The other half of detaching it: a SIGTERM during boot must not leave a browser being launcheddiff --git a/src/modules/session/session.service.ts b/src/modules/session/session.service.tsindex 0ea59adc7..f495da284 100644--- a/src/modules/session/session.service.ts+++ b/src/modules/session/session.service.ts@@ -12,6 +12,7 @@ import { ConfigService } from '@nestjs/config';import { InjectRepository, InjectDataSource } from '@nestjs/typeorm';import { Repository, In, Not, IsNull, DataSource, FindManyOptions } from 'typeorm';import { QueryDeepPartialEntity } from 'typeorm/query-builder/QueryPartialEntity';+import { setTimeout } from 'node:timers/promises';import { Session, SessionStatus } from './entities/session.entity';import { CreateSessionDto, SessionConfigResponseDto, UpdateSessionConfigDto } from './dto';import { EngineRegistry } from '../../engine/engine-registry.service';@@ -191,7 +192,7 @@ export class SessionService implements OnModuleDestroy, OnModuleInit, OnApplicat}// Throttle between sequential Chromium launches; no need to wait after the last one.if (i < sessions.length - 1) {- await this.delay(2000);+ await setTimeout(2000);}}}@@ -778,8 +779,4 @@ export class SessionService implements OnModuleDestroy, OnModuleInit, OnApplicat): Promise<{ stopped: string[]; notRunning: string[]; failed: string[] }> {return this.engineLifecycle.stopOrphanEngines(sessionIds);}-- private delay(ms: number): Promise<void> {- return new Promise(resolve => setTimeout(resolve, ms));- }}diff --git a/src/modules/status-store/status-store.service.spec.ts b/src/modules/status-store/status-store.service.spec.tsindex 4d5f6f2fe..0fcb4cbde 100644--- a/src/modules/status-store/status-store.service.spec.ts+++ b/src/modules/status-store/status-store.service.spec.ts@@ -8,6 +8,7 @@ jest.mock('archiver', () => ({ default: jest.fn() }));import { StorageService } from '../../common/storage/storage.service';import { LidMappingStoreService } from '../../engine/identity/lid-mapping-store.service';+import { userPart } from '../../engine/identity/wa-id';import { StatusUpdate } from './entities/status-update.entity';import { StatusStoreService } from './status-store.service';@@ -408,14 +409,17 @@ describe('StatusStoreService contact identity (read-time lid resolution)', () =>fs.rmSync(baseDir, { recursive: true, force: true });});- const lidStore = (mappings: Record<string, string | null>): LidMappingStoreService =>- ({- getCached: (lid: string) => (lid in mappings ? mappings[lid] : undefined),+ const lidStore = (mappings: Record<string, string | null>): LidMappingStoreService => {+ const getCached = (lid: string): string | null | undefined => (lid in mappings ? mappings[lid] : undefined);+ return {+ getCached,+ resolveLid: (jid: string) => getCached(userPart(jid)) ?? null,lidsForPhone: (phone: string) =>Object.entries(mappings).filter(([, p]) => p === phone).map(([l]) => l),- }) as unknown as LidMappingStoreService;+ } as unknown as LidMappingStoreService;+ };it('resolves a @lid contact to the mapped phone at read time, so both forms group together', async () => {const svc = new StatusStoreService(repository, storageService, fakeConfigService(), lidStore({ '111': '628111' }));diff --git a/src/modules/status-store/status-store.service.ts b/src/modules/status-store/status-store.service.tsindex 0bf8e6485..268464eba 100644--- a/src/modules/status-store/status-store.service.ts+++ b/src/modules/status-store/status-store.service.ts@@ -266,7 +266,7 @@ export class StatusStoreService implements OnModuleInit, OnModuleDestroy {*/private canonicalContactJid(jid: string): string {if (!jid.endsWith('@lid')) return jid;- const phone = this.lidMappingStore?.getCached(userPart(jid));+ const phone = this.lidMappingStore?.resolveLid(jid);return phone ? `${phone}@c.us` : jid;}diff --git a/src/modules/takeover/session-takeover.service.ts b/src/modules/takeover/session-takeover.service.tsindex be8625db0..8cc22cf3a 100644--- a/src/modules/takeover/session-takeover.service.ts+++ b/src/modules/takeover/session-takeover.service.ts@@ -1,5 +1,6 @@import { ConflictException, Injectable, OnApplicationBootstrap, OnModuleDestroy, Optional } from '@nestjs/common';import { ConfigService } from '@nestjs/config';+import { setTimeout } from 'node:timers/promises';import { createLogger } from '../../common/services/logger.service';import { resolveFeatureFlags } from '../../config/feature-flags';import { Session, SessionStatus } from '../session/entities/session.entity';@@ -138,7 +139,7 @@ export class SessionTakeoverService implements OnApplicationBootstrap, OnModuleD}}if (i < eligible.length - 1) {- await new Promise(resolve => setTimeout(resolve, TAKEOVER_START_STAGGER_MS));+ await setTimeout(TAKEOVER_START_STAGGER_MS);}}}diff --git a/src/modules/webhook/webhook.service.spec.ts b/src/modules/webhook/webhook.service.spec.tsindex d08421cda..f28e153c3 100644--- a/src/modules/webhook/webhook.service.spec.ts+++ b/src/modules/webhook/webhook.service.spec.ts@@ -23,6 +23,7 @@ import { Webhook } from './entities/webhook.entity';import { WebhookDeliveryFailure } from './entities/webhook-delivery-failure.entity';import { WebhookFilters } from './filters/filter-types';import { LidMappingStoreService } from '../../engine/identity/lid-mapping-store.service';+import { userPart } from '../../engine/identity/wa-id';import { HookManager } from '../../core/hooks';import { QUEUE_NAMES } from '../queue/queue-names';import { Session } from '../session/entities/session.entity';@@ -55,7 +56,7 @@ describe('WebhookService', () => {let configService: jest.Mocked<Partial<ConfigService>>;let hookManager: jest.Mocked<Partial<HookManager>>;let webhookQueue: jest.Mocked<Record<string, jest.Mock>>;- let lidStore: { getCached: jest.Mock };+ let lidStore: { getCached: jest.Mock; resolveLid: jest.Mock };beforeEach(async () => {repository = {@@ -97,7 +98,11 @@ describe('WebhookService', () => {add: jest.fn().mockResolvedValue(undefined),};- lidStore = { getCached: jest.fn().mockReturnValue(null) };+ lidStore = {+ getCached: jest.fn().mockReturnValue(null),+ // Mirrors the real implementation so tests keep driving resolution through getCached mocks.+ resolveLid: jest.fn((jid: string) => (lidStore.getCached(userPart(jid)) as string | null | undefined) ?? null),+ };const module: TestingModule = await Test.createTestingModule({providers: [diff --git a/src/modules/webhook/webhook.service.ts b/src/modules/webhook/webhook.service.tsindex 0c9cf2b3f..2561db458 100644--- a/src/modules/webhook/webhook.service.ts+++ b/src/modules/webhook/webhook.service.ts@@ -12,6 +12,7 @@ import { ConfigService } from '@nestjs/config';import { InjectQueue } from '@nestjs/bullmq';import { Queue } from 'bullmq';import * as crypto from 'crypto';+import { setTimeout } from 'node:timers/promises';import { Webhook } from './entities/webhook.entity';import { WebhookDeliveryFailure } from './entities/webhook-delivery-failure.entity';import { recordWebhookDeliveryFailure, statusCodeFromError } from './utils/record-delivery-failure';@@ -24,7 +25,6 @@ import { QUEUE_NAMES } from '../queue/queue-names';import { generateIdempotencyKey, generateDeliveryId } from './utils/idempotency.util';import { evaluateFilters } from './filters/filter-evaluator';import { LidMappingStoreService } from '../../engine/identity/lid-mapping-store.service';-import { userPart } from '../../engine/identity/wa-id';import {assertSafeFetchUrl,withSafeFetch,@@ -204,7 +204,7 @@ export class WebhookService implements OnModuleInit, OnModuleDestroy {while (this.dispatchLimiter.activeCount > 0 || this.pendingBookkeeping.size > 0) {const remaining = deadline - Date.now();if (remaining <= 0) break;- await this.delay(Math.min(50, remaining));+ await setTimeout(Math.min(50, remaining));}for (const lost of this.inFlightDeliveries.values()) {this.logger.error('Webhook delivery abandoned during shutdown', undefined, {@@ -447,7 +447,7 @@ export class WebhookService implements OnModuleInit, OnModuleDestroy {private filterMatchingWebhooks(webhooks: Webhook[], event: string, data: Record<string, unknown>): Webhook[] {// Resolve a lid actor to its phone through the persistent table so a phone filter matches a// lid-addressed sender (e.g. an unresolved @lid group participant). Absent store -> no resolution.- const resolveLid = (jid: string): string | null => this.lidMappingStore?.getCached(userPart(jid)) ?? null;+ const resolveLid = (jid: string): string | null => this.lidMappingStore?.resolveLid(jid) ?? null;const subscribed = webhooks.filter(w => w.events.includes(event) || w.events.includes('*'));const matching = subscribed.filter(w => evaluateFilters(w.filters, event, data, resolveLid));// A subscribed webhook that a filter drops leaves no trace otherwise: dispatch() awaits an empty@@ -924,7 +924,7 @@ export class WebhookService implements OnModuleInit, OnModuleDestroy {if (attempt < webhook.retryCount) {const delay = this.configService.get<number>('webhook.retryDelay', 5000);- await this.delay(delay * attempt);+ await setTimeout(delay * attempt);return this.deliverWebhook(webhook, payload, headers, body, attempt + 1);}// All direct-path retries exhausted — persist a durable failure record before giving up, mirroring@@ -994,8 +994,4 @@ export class WebhookService implements OnModuleInit, OnModuleDestroy {hmac.update(payload);return `sha256=${hmac.digest('hex')}`;}-- private delay(ms: number): Promise<void> {- return new Promise(resolve => setTimeout(resolve, ms));- }}