Free, Open Source, Self-Hosted WhatsApp API Gateway
TypeScript apibotgatewayself-hostedwhatsappwhatsapp-apiwhatsapp-automationwhatsapp-botwhatsapp-gatewaywhatsapp-gateway-apiwhatsapp-webwhatsapp-web-api
docs(session): repoint stale SessionService ownership comments at SessionEngineLifecycle
Yudhi Armyndharis83e66513cc7c
diff --git a/docs/03-system-architecture.md b/docs/03-system-architecture.mdindex 11e2c7c43..9084317cc 100644--- a/docs/03-system-architecture.md+++ b/docs/03-system-architecture.md@@ -440,7 +440,7 @@ The diagram below is conceptual: `SessionManager` is the role played by `Session(`src/modules/session/session.service.ts`), which injects the TypeORM `Repository<Session>` directly —there is no `SessionRepository` class in the codebase. The live-engine map itself lives in`EngineRegistry` (`src/engine/engine-registry.service.ts`), the narrow port that capability services-inject when they only need the running engine for a session; `SessionService` is its only writer.+inject when they only need the running engine for a session; `SessionEngineLifecycle` is its only writer.```mermaidclassDiagramdiff --git a/docs/08-development-guidelines.md b/docs/08-development-guidelines.mdindex 2640cbaca..de23dd520 100644--- a/docs/08-development-guidelines.md+++ b/docs/08-development-guidelines.md@@ -202,8 +202,9 @@ resolve an engine directly from a controller. Engine-specific details belong behservices and engine adapters.A capability service reaches the live engine through `EngineRegistry`, the narrow port exported by-the (global) `EngineModule` — not through `SessionService`, which owns the session *lifecycle*-(start/stop/delete/reconnect) and should only be injected by code that actually drives it:+the (global) `EngineModule` — not through `SessionService`, which drives the session *lifecycle*+(start/stop/delete/reconnect, owned by `SessionEngineLifecycle`) and should only be injected by code+that actually drives it:```typescript@Injectable()diff --git a/docs/10-devops-infrastructure.md b/docs/10-devops-infrastructure.mdindex 8b1776aec..67e1b2e87 100644--- a/docs/10-devops-infrastructure.md+++ b/docs/10-devops-infrastructure.md@@ -265,7 +265,8 @@ volumes:> [!IMPORTANT]> **Keep `replicas: 1`.** OpenWA is a single-process application: live engine state lives in an-> in-memory `Map` in `SessionService` (`src/modules/session/session.service.ts`). Multi-replica is+> in-memory `Map` in `EngineRegistry` (`src/engine/engine-registry.service.ts`), written solely by+> `SessionEngineLifecycle`. Multi-replica is> **not** a supported topology — running two replicas against a shared `SESSION_DATA_PATH` makes two> browsers write the same WhatsApp LocalAuth directory and **corrupts the session** (forced logout /> ban). Shared storage and sticky sessions do **not** make multi-replica safe. Seediff --git a/src/common/metrics/session-reconnect-metrics.ts b/src/common/metrics/session-reconnect-metrics.tsindex d4f8eb8b9..934ca5ec3 100644--- a/src/common/metrics/session-reconnect-metrics.ts+++ b/src/common/metrics/session-reconnect-metrics.ts@@ -1,6 +1,6 @@/*** Process-local monotonic counters for session reconnect observability, incremented one-for-one in- * `SessionService.scheduleReconnect`. Kept as plain in-process counters rather than a `COUNT(*)` over+ * `SessionEngineLifecycle.scheduleReconnect`. Kept as plain in-process counters rather than a `COUNT(*)` over* any persisted table because reconnect scheduling itself is not persisted at all — there is no* durable source to count, and a pruned/rotated one would be non-monotonic and therefore invalid as a* Prometheus `counter` (a prune would look like a counter reset to `rate()`/`increase()`). Andiff --git a/src/core/plugins/conversation-send-facade.ts b/src/core/plugins/conversation-send-facade.tsindex 08a9085fb..44e10ab8b 100644--- a/src/core/plugins/conversation-send-facade.ts+++ b/src/core/plugins/conversation-send-facade.ts@@ -15,8 +15,8 @@ export interface ConversationSendDeps {resolveChatId: (env: ConversationSendEnvelope) => Promise<string>;// Seed the hook in-flight set so an adapter's own outbound message:sending hook cannot echo-loop// back into this same send. Only 'message:sending' is reachable this way — MessageService fires it- // synchronously inside sendText/reply. 'message:sent' is emitted later by SessionService's engine- // callback (onMessageCreate), outside this call's async scope, so seeding it here would be a no-op.+ // synchronously inside sendText/reply. 'message:sent' is emitted later by SessionEngineLifecycle's+ // engine callback (onMessageCreate), outside this call's async scope, so seeding it here would be a no-op.runGuarded: <T>(events: string[], run: () => Promise<T>) => Promise<T>;sendText: (sessionId: string, opts: { chatId: string; text: string }) => Promise<unknown>;reply: (sessionId: string, opts: { chatId: string; quotedMessageId: string; text: string }) => Promise<unknown>;diff --git a/src/core/plugins/plugin-host-services.ts b/src/core/plugins/plugin-host-services.tsindex b5e55f306..f526b7264 100644--- a/src/core/plugins/plugin-host-services.ts+++ b/src/core/plugins/plugin-host-services.ts@@ -17,7 +17,7 @@ import type { SearchProviderRegistry } from '../../modules/search/search-provide* which corrupts MessageService's constructor paramtype metadata (`SessionService -> undefined`)* at boot. The same reasoning covers the two integration services.* - `ModuleRef` rather than constructor injection avoids the provider cycle- * `PluginLoaderService -> SessionService -> EngineFactory -> PluginLoaderService`.+ * `PluginLoaderService -> SessionService -> SessionEngineLifecycle -> EngineFactory -> PluginLoaderService`.** Keeping the pair in one place means the loader no longer has to carry that reasoning, nor name the* five services it was resolving. Everything below is a resolution detail; nothing here decidesdiff --git a/src/core/plugins/plugin-loader.service.ts b/src/core/plugins/plugin-loader.service.tsindex 99be7410f..9673f6872 100644--- a/src/core/plugins/plugin-loader.service.ts+++ b/src/core/plugins/plugin-loader.service.ts@@ -190,7 +190,7 @@ export class PluginLoaderService implements OnModuleInit, OnApplicationBootstrapprivate readonly pluginStorage: PluginStorageService,// Handed straight to PluginHostServices below, which owns the reasoning: ModuleRef rather than// constructor injection avoids the provider cycle- // PluginLoaderService -> SessionService -> EngineFactory -> PluginLoaderService.+ // PluginLoaderService -> SessionService -> SessionEngineLifecycle -> EngineFactory -> PluginLoaderService.private readonly moduleRef: ModuleRef,// Shared lid->phone table (EngineModule is @Global and exports it). Optional so the many unit tests// that construct this service with the 4 prior args still compile; when absent, canonicalChatIddiff --git a/src/engine/engine-init-timeout.ts b/src/engine/engine-init-timeout.tsindex 6d84c5aeb..e2b46007e 100644--- a/src/engine/engine-init-timeout.ts+++ b/src/engine/engine-init-timeout.ts@@ -2,9 +2,10 @@* The deadline the session lifecycle races `engine.initialize()` against, and the whatsapp-web.js* auth window it is derived from.*- * These live outside the adapters because the OUTER deadline is engine-agnostic — SessionService- * applies it to every engine — while the value it must clear is set by whatsapp-web.js. Deriving it- * inside `session.service.ts` meant the lifecycle owner imported the wwjs adapter just to size a+ * These live outside the adapters because the OUTER deadline is engine-agnostic —+ * SessionEngineLifecycle applies it to every engine — while the value it must clear is set by+ * whatsapp-web.js. Deriving it inside the session lifecycle service meant the lifecycle owner+ * imported the wwjs adapter just to size a* timeout, which is why this pair now has one home instead of a cross-layer import.*/diff --git a/src/engine/engine-registry.service.ts b/src/engine/engine-registry.service.tsindex 071f295b8..5a1cfca91 100644--- a/src/engine/engine-registry.service.ts+++ b/src/engine/engine-registry.service.ts@@ -4,11 +4,11 @@ import type { IWhatsAppEngine } from './interfaces/whatsapp-engine.interface';/*** The single source of truth for which engine instance is live for a session.*- * This is the narrow port between session *lifecycle* (SessionService, which creates, retires and- * reconnects engines) and the ~10 feature services that only ever need "give me the running engine- * for this session". Those consumers previously injected the whole SessionService — a 2.9k-line- * lifecycle owner — purely to reach its private `engines` map, which coupled every feature module to- * start/stop/delete/reconnect semantics they never call.+ * This is the narrow port between session *lifecycle* (SessionEngineLifecycle, which creates,+ * retires and reconnects engines) and the ~10 feature services that only ever need "give me the+ * running engine for this session". Those consumers previously injected the whole SessionService —+ * a 2k-line lifecycle owner — purely to reach its private `engines` map, which coupled every+ * feature module to start/stop/delete/reconnect semantics they never call.** Identity, not just presence, is the invariant that matters. Each engine callback captures its own* engine instance; once a session is stopped (engine removed) or restarted/reconnected (enginediff --git a/src/modules/audit/intentionally-unemitted-actions.ts b/src/modules/audit/intentionally-unemitted-actions.tsindex f7c822f5f..10652aa75 100644--- a/src/modules/audit/intentionally-unemitted-actions.ts+++ b/src/modules/audit/intentionally-unemitted-actions.ts@@ -17,9 +17,9 @@ export const INTENTIONALLY_UNEMITTED_ACTIONS: Partial<Record<AuditAction, string[AuditAction.API_KEY_USED]:'Not emitted: would fire on every authenticated request, which is too high-volume for the audit log. Authentication failures are audited (API_KEY_AUTH_FAILED); successful authentication is intentionally not.',[AuditAction.SESSION_CONNECTED]:- 'Not emitted: an engine-level lifecycle transition, redundant with sessions.status and the SessionService lastDispatchedStatus map. User-initiated lifecycle (SESSION_STARTED / SESSION_STOPPED) is audited.',+ 'Not emitted: an engine-level lifecycle transition, redundant with sessions.status and the SessionEngineLifecycle lastDispatchedStatus map. User-initiated lifecycle (SESSION_STARTED / SESSION_STOPPED) is audited.',[AuditAction.SESSION_DISCONNECTED]:- 'Not emitted: an engine-level lifecycle transition, redundant with sessions.status and the SessionService lastDispatchedStatus map; reconnect storms would flood the audit log.',+ 'Not emitted: an engine-level lifecycle transition, redundant with sessions.status and the SessionEngineLifecycle lastDispatchedStatus map; reconnect storms would flood the audit log.',[AuditAction.MESSAGE_SENT]:'Not emitted: per outbound message, fully redundant with the messages table, which persists every send with its outcome.',[AuditAction.MESSAGE_FAILED]:diff --git a/src/modules/message/message.service.spec.ts b/src/modules/message/message.service.spec.tsindex ef693816f..e369ed520 100644--- a/src/modules/message/message.service.spec.ts+++ b/src/modules/message/message.service.spec.ts@@ -197,7 +197,8 @@ describe('MessageService', () => {expect.objectContaining({ type: 'text' }),expect.any(Object),);- // message:sent is no longer fired here — it is emitted solely by SessionService.onMessageCreate+ // message:sent is no longer fired here — it is emitted solely by the onMessageCreate wiring in+ // SessionEngineLifecycle (via MessageProjector)// with a consistent IncomingMessage payload for ALL sends (avoids the prior double dispatch).expect(hookManager.execute).not.toHaveBeenCalledWith('message:sent', expect.anything(), expect.anything());});diff --git a/src/modules/message/message.service.ts b/src/modules/message/message.service.tsindex 13eec8409..185b76675 100644--- a/src/modules/message/message.service.ts+++ b/src/modules/message/message.service.ts@@ -91,8 +91,9 @@ export class MessageService {return this.failSend(sessionId, 'text', message, finalDto, error);}- // Note: the `message:sent` hook is emitted solely by SessionService.onMessageCreate (engine- // `message_create`) with a consistent IncomingMessage payload for ALL sends (text, media,+ // Note: the `message:sent` hook is emitted solely by the onMessageCreate wiring in+ // SessionEngineLifecycle (engine `message_create`, handled by MessageProjector) with a+ // consistent IncomingMessage payload for ALL sends (text, media,// and phone-composed), so it is intentionally not fired here to avoid a double dispatch.return this.persistSentState(message, result);}diff --git a/src/modules/session/message-projector.service.ts b/src/modules/session/message-projector.service.tsindex d5ed0e6a5..fefbb7815 100644--- a/src/modules/session/message-projector.service.ts+++ b/src/modules/session/message-projector.service.ts@@ -37,7 +37,8 @@ import {** This is the data path for messages: inbound arrivals, own-send echoes, delivery acks, revokes,* reactions, edits, and the pre-connection history backfill. It is deliberately separate from- * SessionService, which owns the session *lifecycle* (start/stop/delete/reconnect). The two share+ * SessionEngineLifecycle, which owns the session *lifecycle* (start/stop/delete/reconnect). The two+ * share* only the engine identity guard — a late event from a superseded engine must never mutate a* session that now belongs to a different one, or to none — which both read from EngineRegistry.*diff --git a/src/modules/session/reconnect-policy.ts b/src/modules/session/reconnect-policy.tsindex 92c2e994f..283f0ab1c 100644--- a/src/modules/session/reconnect-policy.ts+++ b/src/modules/session/reconnect-policy.ts@@ -1,7 +1,7 @@/*** The reconnect backoff *decision*, separated from its effects.*- * `SessionService.scheduleReconnect` interleaves four rules (stability reset, budget exhaustion,+ * `SessionEngineLifecycle.scheduleReconnect` interleaves four rules (stability reset, budget exhaustion,* exponential backoff with jitter, periodic loop alerting) with the side effects they trigger* (status writes, engine eviction, webhooks, timers). The rules are the subtle part and the effects* are the untestable part, so the rules live here as a pure function over explicit state.diff --git a/test/session-teardown-pending-http.e2e-spec.ts b/test/session-teardown-pending-http.e2e-spec.tsindex aa06b51d8..f220212c8 100644--- a/test/session-teardown-pending-http.e2e-spec.ts+++ b/test/session-teardown-pending-http.e2e-spec.ts@@ -20,7 +20,7 @@ import { SessionService } from './../src/modules/session/session.service';** Driven through the real HTTP stack (AppModule + applyGlobalValidation, the exact production bootstrap)* with NO custom exception filter registered, so the object-response ConflictException that- * `SessionService.awaitPendingTeardown()` throws is serialized by Nest's default filter — proving the+ * `SessionEngineLifecycle.awaitPendingTeardown()` throws is serialized by Nest's default filter — proving the* stable `code` field reaches the response body unchanged. The service is overridden to throw the exact* ConflictException shape the source constructs, so this exercises the real Nest serialization path* (controller + DI + filter) rather than re-running the 10s bounded-wait (which needs fake timers and