Free, Open Source, Self-Hosted WhatsApp API Gateway
TypeScript apibotgatewayself-hostedwhatsappwhatsapp-apiwhatsapp-automationwhatsapp-botwhatsapp-gatewaywhatsapp-gateway-apiwhatsapp-webwhatsapp-web-api
docs(architecture): record the engine port, and extend the controller guard
Yudhi Armyndharisc5ed76f5baca
diff --git a/CHANGELOG.md b/CHANGELOG.mdindex 186387c93..e8e8b83d9 100644--- a/CHANGELOG.md+++ b/CHANGELOG.md@@ -7,6 +7,39 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0## [Unreleased]+### Changed++- **The live engine is reachable through its own narrow port instead of through the session lifecycle+ owner.** Ten feature services (contacts, groups, labels, channels, calls, profile, catalog, status,+ and both message services) injected the whole 2.9k-line `SessionService` purely to reach its private+ `engines` map, which coupled every one of them to start/stop/delete/reconnect semantics they never+ call. The map now lives in `EngineRegistry`, exported from the (already global) `EngineModule`, so+ those services depend on "give me the running engine for this session" and eight feature modules no+ longer import `SessionModule` at all. `SessionService` remains the only writer, and the services+ that genuinely drive the lifecycle (`MessageService` for `findOne`/edit recording, `InfraController`+ for orphan reaping) still hold it deliberately. No API change: each call site keeps its own error, so+ contacts/labels/groups/channels/calls/profile still answer 400 `Session is not started`,+ catalog/status still answer 404 `not found or not connected`, and the two message services keep their+ distinct wording. `openapi.json` is unchanged, byte for byte.++ The engine-identity rule that guards every lifecycle path — a late callback from a superseded engine+ must never mutate a session that now belongs to a different one, or to none — was open-coded at+ around twenty call sites as `isLiveEngine(id, e) && engines.delete(id)`. It is now `isLive` /+ `deleteIfLive` on the registry, written once.++- **Three self-contained concerns were lifted out of `SessionService`.** Each was previously reachable+ only by driving the full session lifecycle, so the trickiest logic in the file had the least direct+ coverage. The `@lid`→phone read-through cache became `SessionLidResolver` (and took an `@Optional`+ constructor dependency with it); the reconnect backoff *decision* became a pure `decideReconnect()`+ with injected clock and jitter, leaving the service to apply only the effects; and the per-message+ serialization chain became a general `KeyedMutationQueue`. Behaviour is unchanged — the existing+ session specs pass untouched — and the split adds 59 tests over branches that previously needed hours+ of uptime or live engine callbacks to reach: the FIFO eviction that bounds the lid cache, the+ stability reset that stops a long-lived session slowly wedging `FAILED` across unrelated transient+ drops, the loop-alert re-arm after a stable stretch, the non-finite-delay fallback that keeps an+ operator typo from becoming a relaunch storm, and the mutation-chain reclamation that stops the map+ growing once per message touched.+### Fixed- **The non-root smoke test can actually be run.** `scripts/smoke-test-non-root.sh` carried a UTF-8diff --git a/docs/03-system-architecture.md b/docs/03-system-architecture.mdindex 63b52f396..11e2c7c43 100644--- a/docs/03-system-architecture.md+++ b/docs/03-system-architecture.md@@ -78,7 +78,7 @@ sequenceDiagramOpenWA is designed with a **Pluggable Architecture** that allows infrastructure components to be swapped without changing application code. This enables flexible deployments ranging from minimal single-session bots to larger single-node, multi-session installs.> **Note — single-instance:** the live WhatsApp engine layer is stateful and held in-process-> (an in-memory `Map` in `SessionService`). OpenWA currently runs as **one API instance per+> (an in-memory `Map` in `EngineRegistry`). OpenWA currently runs as **one API instance per> session-data volume**; horizontal scaling across multiple API replicas is a future design> (not implemented). See [13 - Horizontal Scaling](13-horizontal-scaling.md).@@ -438,12 +438,14 @@ src/The diagram below is conceptual: `SessionManager` is the role played by `SessionService`(`src/modules/session/session.service.ts`), which injects the TypeORM `Repository<Session>` directly —-there is no `SessionRepository` class in the codebase.+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.```mermaidclassDiagramclass SessionManager {- -engines: Map~string, IWhatsAppEngine~+ -engines: EngineRegistry-sessionRepository: Repository~Session~-engineFactory: EngineFactory+createSession(config): Sessiondiff --git a/docs/08-development-guidelines.md b/docs/08-development-guidelines.mdindex c293a8795..2640cbaca 100644--- a/docs/08-development-guidelines.md+++ b/docs/08-development-guidelines.md@@ -70,7 +70,8 @@ listed explicitly because TypeScript 6 no longer auto-includes every `@types` paThe backend uses ESLint flat config in `eslint.config.mjs` with type-aware TypeScript rules,Prettier integration, and an architecture guard for controllers. HTTP controllers must call-capability services; they must not import `IWhatsAppEngine` or call `getEngine()` directly.+capability services; they must not import `IWhatsAppEngine` or `EngineRegistry`, call `getEngine()`,+or resolve an engine via `engines.require()` / `engines.get()`.```bashnpm run lint@@ -197,8 +198,25 @@ export class ExampleController {Controllers are protected by the global API key guard unless marked with `@Public()`. Keepcontrollers thin: validate transport input through DTOs, delegate behavior to services, and never-call `SessionService.getEngine()` directly from a controller. Engine-specific details belong behind-capability services and engine adapters.+resolve an engine directly from a controller. Engine-specific details belong behind capability+services 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:++```typescript+@Injectable()+export class ExampleService {+ constructor(private readonly engines: EngineRegistry) {}++ // require() throws 400 "Session is not started" by default; pass a factory to keep an+ // endpoint's own documented status/message.+ private getEngine(sessionId: string): IWhatsAppEngine {+ return this.engines.require(sessionId);+ }+}+```### Service Templatediff --git a/docs/13-horizontal-scaling.md b/docs/13-horizontal-scaling.mdindex 8dad36b7c..cbd3dc7f7 100644--- a/docs/13-horizontal-scaling.md+++ b/docs/13-horizontal-scaling.md@@ -4,7 +4,7 @@>> **OpenWA is currently a single-process, single-instance application.** Live WhatsApp> engine state (browser + WebSocket + reconnect/error state) lives in an in-memory `Map`-> in `SessionService`; there is **no** DB-backed session registry, **no** node-claim/lease,+> in `EngineRegistry`; there is **no** DB-backed session registry, **no** node-claim/lease,> and **no** Socket.IO Redis adapter.>> **Supported topology:** exactly **one** API instance per session-data volume. Runningdiff --git a/eslint.config.mjs b/eslint.config.mjsindex 865deaaaf..c9fcbc425 100644--- a/eslint.config.mjs+++ b/eslint.config.mjs@@ -36,7 +36,8 @@ export default tseslint.config(// Architecture guard: HTTP controllers must go through a per-capability service and// never reach for the raw WhatsApp engine. This keeps the "session not started" guard,// error mapping, and business rules behind the service boundary instead of leaking into- // controllers. `.getEngine(` (not `.getEngines()`) and the `IWhatsAppEngine` type are banned.+ // controllers. `.getEngine(` (not `.getEngines()`), the EngineRegistry accessors, and the+ // `IWhatsAppEngine` type are banned.files: ['**/*.controller.ts'],rules: {'no-restricted-syntax': [@@ -46,6 +47,16 @@ export default tseslint.config(message:'Controllers must not call getEngine(). Add a method to the capability service (e.g. GroupService) and call that instead.',},+ {+ // EngineRegistry.require()/get() resolve a live engine, so reaching for either from a+ // controller bypasses the capability service exactly as getEngine() used to. Matches+ // `this.engines.require(...)` (a MemberExpression callee object) as well as a bare+ // `engines.require(...)`.+ selector:+ "CallExpression[callee.property.name=/^(require|get)$/]:has(MemberExpression[property.name='engines'])",+ message:+ 'Controllers must not resolve an engine from EngineRegistry. Add a method to the capability service and call that instead.',+ },],'no-restricted-imports': ['error',@@ -59,6 +70,11 @@ export default tseslint.config(message:'Controllers must not import IWhatsAppEngine. Keep engine types behind a capability service.',},+ {+ group: ['**/engine/engine-registry.service'],+ message:+ 'Controllers must not import EngineRegistry. Keep engine access behind a capability service.',+ },],},],