Skip to content

Free, Open Source, Self-Hosted WhatsApp API Gateway

refactor(session): split handleInboundMessage into projection stages

Yudhi Armyndharis9c5ec08f489e
diff --git a/src/modules/session/message-projector.service.ts b/src/modules/session/message-projector.service.ts
index fefbb7815..d2e5d3fae 100644
--- a/src/modules/session/message-projector.service.ts
+++ b/src/modules/session/message-projector.service.ts
@@ -53,6 +53,20 @@ import {
*/
export const ACK_RECONCILE_DELAY_MS = 750;
+/** Persist-stage outcome threaded into the inbound dispatch stage (was closure state in the hook continuation). */
+interface InboundPersistOutcome {
+ dbMessage: Message;
+ persisted: boolean;
+}
+
+/**
+ * Type of the `{ ...message }` copy the `message:received` hook returns (was the closure-inferred
+ * spread type in handleInboundMessage). Kept as an object type rather than the IncomingMessage
+ * interface so it stays assignable to the Record<string, unknown> dispatch/emit params — interfaces
+ * carry no implicit index signature.
+ */
+type InboundMessageData = { [K in keyof IncomingMessage]: IncomingMessage[K] };
+
@Injectable()
export class MessageProjector {
private readonly logger = createLogger('MessageProjector');
@@ -85,35 +99,64 @@ export class MessageProjector {
/** Engine callback body, lifted out of initializeEngine so the wiring table stays readable. */
handleInboundMessage(id: string, engine: IWhatsAppEngine, message: IncomingMessage): void {
if (!this.engines.isLive(id, engine)) return;
+ if (message.isStatusBroadcast) {
+ this.ingestInboundStatus(id, engine, message);
+ return;
+ }
+ if (this.shouldSkipEphemeralMessage(id, message)) return;
+ this.logger.debug(`Message received from ${message.from}`, {
+ sessionId: id,
+ messageId: message.id,
+ from: message.from,
+ action: 'message_received',
+ });
+ // Update last active timestamp
+ void this.sessionRepository.update(id, { lastActiveAt: new Date() }).catch(() => undefined);
+ // Convert IncomingMessage to plain object for dispatch
+ const messageData = { ...message };
+
+ // Execute hook for message received - plugins can modify or stop processing
+ void this.hookManager
+ .execute('message:received', messageData, {
+ sessionId: id,
+ source: 'Engine',
+ })
+ .then(({ data: finalMessage }) => this.projectInboundMessage(id, engine, finalMessage))
+ .catch(err => this.logger.error(`onMessage handler failed for ${id}`, String(err)));
+ }
+
+ /** `isStatusBroadcast` arm of {@link handleInboundMessage}: ingest into the status store, not the message pipeline. */
+ private ingestInboundStatus(id: string, engine: IWhatsAppEngine, message: IncomingMessage): void {
// Status/Story posts arrive via the inbound path for some engines; ingest them into the
// status store instead of the message pipeline. Mirrors the isStatusBroadcast guard in
// onMessageCreate below: an own-send echo (fromMe) stays a plain drop — never ingested,
// never dispatched — so a status you posted never re-appears in your own webhooks/API as
// if a contact had posted it.
- if (message.isStatusBroadcast) {
- if (message.fromMe) return;
- const status = buildIncomingStatus(message);
- if (status) {
- void this.statusStore
- .ingest(id, status)
- // Dispatch only on a fresh insert: ingest also resolves with the pre-existing row
- // for a duplicate delivery (or the winner's row after a lost insert race), and the
- // webhook must fire once per status, not once per (re)delivery.
- .then(({ row, created }) => {
- // The ingest awaited; a stop()/delete() can retire this engine mid-flight — don't
- // dispatch for a session that no longer exists (mirrors message.received's re-check).
- if (!this.engines.isLive(id, engine)) return;
- if (created) this.dispatchStatusReceived(id, row);
- })
- .catch(err =>
- this.logger.warn('Status ingest failed', {
- sessionId: id,
- error: err instanceof Error ? err.message : String(err),
- }),
- );
- }
- return;
+ if (message.fromMe) return;
+ const status = buildIncomingStatus(message);
+ if (status) {
+ void this.statusStore
+ .ingest(id, status)
+ // Dispatch only on a fresh insert: ingest also resolves with the pre-existing row
+ // for a duplicate delivery (or the winner's row after a lost insert race), and the
+ // webhook must fire once per status, not once per (re)delivery.
+ .then(({ row, created }) => {
+ // The ingest awaited; a stop()/delete() can retire this engine mid-flight — don't
+ // dispatch for a session that no longer exists (mirrors message.received's re-check).
+ if (!this.engines.isLive(id, engine)) return;
+ if (created) this.dispatchStatusReceived(id, row);
+ })
+ .catch(err =>
+ this.logger.warn('Status ingest failed', {
+ sessionId: id,
+ error: err instanceof Error ? err.message : String(err),
+ }),
+ );
}
+ }
+
+ /** Operator opt-out gate for disappearing messages: true when the message must be skipped entirely. */
+ private shouldSkipEphemeralMessage(id: string, message: IncomingMessage): boolean {
// Ephemeral/disappearing messages: skip persist + dispatch when the operator opted out.
// A message is ephemeral when its chat has a disappearing-messages timer (ephemeralDuration > 0).
if (
@@ -127,135 +170,143 @@ export class MessageProjector {
chatId: message.chatId,
ephemeralDuration: message.ephemeralDuration,
});
- return;
+ return true;
}
- this.logger.debug(`Message received from ${message.from}`, {
- sessionId: id,
- messageId: message.id,
- from: message.from,
- action: 'message_received',
- });
- // Update last active timestamp
- void this.sessionRepository.update(id, { lastActiveAt: new Date() }).catch(() => undefined);
- // Convert IncomingMessage to plain object for dispatch
- const messageData = { ...message };
+ return false;
+ }
- // Execute hook for message received - plugins can modify or stop processing
- void this.hookManager
- .execute('message:received', messageData, {
- sessionId: id,
- source: 'Engine',
- })
- .then(async ({ data: finalMessage }) => {
- // `continue: false` is deliberately NOT read here. It means "stop the handler chain", which
- // HookManager has already done — the plugins after the one that returned it never ran. It
- // does not mean "this message never happened".
- //
- // Honouring it here used to skip everything below: the message was never written to the
- // messages table, never dispatched to webhooks, and never emitted over the websocket. An
- // auto-reply plugin returning `false` for its ordinary purpose — keeping other bots from
- // answering the same message — silently erased the customer's message from the operator's
- // own history, leaving a thread of bot replies answering nothing. Nothing in the hook
- // contract (`HookResult.continue`, docs/19) or the webhook contract (`message.received`
- // fires when "an inbound message arrives", docs/06) hinted at that, and a sandboxed
- // marketplace plugin could swallow a session's entire inbound traffic with no audit trail.
- //
- // The message has already arrived at WhatsApp. A plugin can stop other plugins from acting
- // on it; it cannot make the gateway forget it. Pre-action hooks are where a veto belongs —
- // `message:sending` blocks a send that has not happened yet (core/hooks/sending-gate.ts).
-
- // Persist the incoming message so the dashboard chats view can render history.
- const incoming: IncomingMessage = finalMessage;
-
- // Inline @lid -> phone resolution (#263), opt-in via RESOLVE_LID_TO_PHONE. Best-effort:
- // attaches senderPhone (digits or null) before persist/dispatch so webhook/ws consumers
- // get it in a single pass. Only for privacy-id senders, so no lookup for normal numbers.
- if (resolveFeatureFlags(this.configService).resolveLidToPhone && incoming.isLidSender && !incoming.fromMe) {
- incoming.senderPhone = await this.lidResolver.resolveSenderPhone(id, incoming.author ?? incoming.from);
- }
+ /** Post-hook continuation of {@link handleInboundMessage}: resolve sender, persist, dispatch. */
+ private async projectInboundMessage(
+ id: string,
+ engine: IWhatsAppEngine,
+ finalMessage: InboundMessageData,
+ ): Promise<void> {
+ // `continue: false` is deliberately NOT read here. It means "stop the handler chain", which
+ // HookManager has already done — the plugins after the one that returned it never ran. It
+ // does not mean "this message never happened".
+ //
+ // Honouring it here used to skip everything below: the message was never written to the
+ // messages table, never dispatched to webhooks, and never emitted over the websocket. An
+ // auto-reply plugin returning `false` for its ordinary purpose — keeping other bots from
+ // answering the same message — silently erased the customer's message from the operator's
+ // own history, leaving a thread of bot replies answering nothing. Nothing in the hook
+ // contract (`HookResult.continue`, docs/19) or the webhook contract (`message.received`
+ // fires when "an inbound message arrives", docs/06) hinted at that, and a sandboxed
+ // marketplace plugin could swallow a session's entire inbound traffic with no audit trail.
+ //
+ // The message has already arrived at WhatsApp. A plugin can stop other plugins from acting
+ // on it; it cannot make the gateway forget it. Pre-action hooks are where a veto belongs —
+ // `message:sending` blocks a send that has not happened yet (core/hooks/sending-gate.ts).
+
+ // Persist the incoming message so the dashboard chats view can render history.
+ const incoming: IncomingMessage = finalMessage;
+
+ // Inline @lid -> phone resolution (#263), opt-in via RESOLVE_LID_TO_PHONE. Best-effort:
+ // attaches senderPhone (digits or null) before persist/dispatch so webhook/ws consumers
+ // get it in a single pass. Only for privacy-id senders, so no lookup for normal numbers.
+ if (resolveFeatureFlags(this.configService).resolveLidToPhone && incoming.isLidSender && !incoming.fromMe) {
+ incoming.senderPhone = await this.lidResolver.resolveSenderPhone(id, incoming.author ?? incoming.from);
+ }
- const metadata = buildMessageMetadata(incoming);
+ const outcome = await this.persistInboundMessage(id, engine, incoming);
+ if (!outcome) return;
+ this.dispatchInboundMessage(id, finalMessage, outcome);
+ }
- const chatName = incoming.contact?.pushName ?? incoming.contact?.name ?? undefined;
+ /**
+ * Build the inbound row and insert it under the UNIQUE dedup oracle. Returns the row plus whether
+ * the insert landed, or null when the pipeline must stop (stale engine, or duplicate re-fire).
+ */
+ private async persistInboundMessage(
+ id: string,
+ engine: IWhatsAppEngine,
+ incoming: IncomingMessage,
+ ): Promise<InboundPersistOutcome | null> {
+ const metadata = buildMessageMetadata(incoming);
- const dbMessage = this.messageRepository.create({
- sessionId: id,
- waMessageId: storableWaMessageId(incoming.id),
- chatId: incoming.chatId,
- chatName,
- // Group poster (participant JID) — `from` is the group JID, so this is the stable
- // sender identity the chat view keys attribution runs/colors on. Undefined for 1:1.
- author: incoming.author,
- from: incoming.from,
- to: incoming.to,
- body: incoming.body,
- type: incoming.type,
- direction: incoming.fromMe ? MessageDirection.OUTGOING : MessageDirection.INCOMING,
- timestamp: incoming.timestamp,
- status: MessageStatus.SENT,
- metadata,
- });
+ const chatName = incoming.contact?.pushName ?? incoming.contact?.name ?? undefined;
- // The hook chain above is async; a delete()/teardown can retire this engine while it
- // awaits. Re-check liveness so a late continuation can't persist an orphan messages row
- // (the row has no FK, so a session-delete cleanup would never reap it) or dispatch for a
- // session that no longer exists. Mirrors the synchronous isLiveEngine gate at entry.
- if (!this.engines.isLive(id, engine)) return;
-
- // De-duplicate at the source: the engine can re-fire `message` for one inbound message
- // (#464). UNIQUE(sessionId, waMessageId) makes the insert the atomic dedup oracle — a
- // near-simultaneous re-fire loses the race and is skipped here, so persist + webhook + WS
- // happen exactly once. Fail-open: a non-conflict DB error still dispatches, so a real
- // message is never dropped by a transient DB failure.
- let isNewMessage = true;
- let persisted = false;
- try {
- // `insert()` (not `save()`) is load-bearing: the UNIQUE(sessionId, waMessageId) constraint
- // makes a duplicate insert throw, which is the atomic dedup oracle for #464 re-fires.
- // Unlike `save()`, `insert()` does NOT merge DB-generated columns (@PrimaryGeneratedColumn,
- // @CreateDateColumn) back onto the entity instance — so merge them explicitly here, before
- // the `message:persisted` emit. `identifiers[0]` always carries the PK on both SQLite and
- // Postgres; `generatedMaps[0]` adds createdAt where the driver returns it (Postgres yes;
- // SQLite historically does not — acceptable; the PK is the load-bearing field for plugins).
- const result = await this.messageRepository.insert(dbMessage as unknown as QueryDeepPartialEntity<Message>);
- Object.assign(dbMessage, result.identifiers[0] ?? {}, result.generatedMaps?.[0] ?? {});
- persisted = true;
- } catch (err) {
- if (isUniqueConstraintError(err)) {
- isNewMessage = false;
- } else {
- this.logger.error(`Failed to save incoming message ${incoming.id} to database`, String(err));
- }
- }
- if (!isNewMessage) {
- return; // duplicate re-fire — the original already persisted and dispatched
- }
+ const dbMessage = this.messageRepository.create({
+ sessionId: id,
+ waMessageId: storableWaMessageId(incoming.id),
+ chatId: incoming.chatId,
+ chatName,
+ // Group poster (participant JID) — `from` is the group JID, so this is the stable
+ // sender identity the chat view keys attribution runs/colors on. Undefined for 1:1.
+ author: incoming.author,
+ from: incoming.from,
+ to: incoming.to,
+ body: incoming.body,
+ type: incoming.type,
+ direction: incoming.fromMe ? MessageDirection.OUTGOING : MessageDirection.INCOMING,
+ timestamp: incoming.timestamp,
+ status: MessageStatus.SENT,
+ metadata,
+ });
- // Fire-and-forget: a plugin handler must never break the receive path. Both engine adapters
- // (wwjs `message` and Baileys `upsert`) converge on this persist, so one emit covers inbound.
- // The built-in FTS search provider is DB-synced and does NOT consume this; it exists for
- // plugin providers (Spec 2) + general use.
- // Gate ONLY the hook on `persisted`: on a non-unique insert error (transient SQLITE_BUSY /
- // lock-timeout / connection drop) the row was never stored and `dbMessage.id` is undefined,
- // so emitting `message:persisted` would hand plugins an id-less payload for a row that isn't
- // in the DB. The webhook/WS dispatch below stays fail-open — a real inbound message must
- // never be dropped on a transient DB failure; only the hook requires a durable row.
- if (persisted) {
- void this.hookManager
- .execute(
- 'message:persisted',
- { sessionId: id, message: dbMessage },
- { sessionId: id, source: 'SessionService' },
- )
- .catch(() => undefined);
- }
+ // The hook chain above is async; a delete()/teardown can retire this engine while it
+ // awaits. Re-check liveness so a late continuation can't persist an orphan messages row
+ // (the row has no FK, so a session-delete cleanup would never reap it) or dispatch for a
+ // session that no longer exists. Mirrors the synchronous isLiveEngine gate at entry.
+ if (!this.engines.isLive(id, engine)) return null;
+
+ // De-duplicate at the source: the engine can re-fire `message` for one inbound message
+ // (#464). UNIQUE(sessionId, waMessageId) makes the insert the atomic dedup oracle — a
+ // near-simultaneous re-fire loses the race and is skipped here, so persist + webhook + WS
+ // happen exactly once. Fail-open: a non-conflict DB error still dispatches, so a real
+ // message is never dropped by a transient DB failure.
+ let isNewMessage = true;
+ let persisted = false;
+ try {
+ // `insert()` (not `save()`) is load-bearing: the UNIQUE(sessionId, waMessageId) constraint
+ // makes a duplicate insert throw, which is the atomic dedup oracle for #464 re-fires.
+ // Unlike `save()`, `insert()` does NOT merge DB-generated columns (@PrimaryGeneratedColumn,
+ // @CreateDateColumn) back onto the entity instance — so merge them explicitly here, before
+ // the `message:persisted` emit. `identifiers[0]` always carries the PK on both SQLite and
+ // Postgres; `generatedMaps[0]` adds createdAt where the driver returns it (Postgres yes;
+ // SQLite historically does not — acceptable; the PK is the load-bearing field for plugins).
+ const result = await this.messageRepository.insert(dbMessage as unknown as QueryDeepPartialEntity<Message>);
+ Object.assign(dbMessage, result.identifiers[0] ?? {}, result.generatedMaps?.[0] ?? {});
+ persisted = true;
+ } catch (err) {
+ if (isUniqueConstraintError(err)) {
+ isNewMessage = false;
+ } else {
+ this.logger.error(`Failed to save incoming message ${incoming.id} to database`, String(err));
+ }
+ }
+ if (!isNewMessage) {
+ return null; // duplicate re-fire — the original already persisted and dispatched
+ }
+ return { dbMessage, persisted };
+ }
- // Dispatch to webhooks with potentially modified message
- void this.webhookService.dispatch(id, 'message.received', finalMessage);
- // Emit real-time event to WebSocket clients
- this.eventsGateway.emitMessage(id, finalMessage);
- })
- .catch(err => this.logger.error(`onMessage handler failed for ${id}`, String(err)));
+ /** Fan an accepted inbound message out: `message:persisted` plugin hook, webhook, websocket emit. */
+ private dispatchInboundMessage(id: string, finalMessage: InboundMessageData, outcome: InboundPersistOutcome): void {
+ const { dbMessage, persisted } = outcome;
+ // Fire-and-forget: a plugin handler must never break the receive path. Both engine adapters
+ // (wwjs `message` and Baileys `upsert`) converge on this persist, so one emit covers inbound.
+ // The built-in FTS search provider is DB-synced and does NOT consume this; it exists for
+ // plugin providers (Spec 2) + general use.
+ // Gate ONLY the hook on `persisted`: on a non-unique insert error (transient SQLITE_BUSY /
+ // lock-timeout / connection drop) the row was never stored and `dbMessage.id` is undefined,
+ // so emitting `message:persisted` would hand plugins an id-less payload for a row that isn't
+ // in the DB. The webhook/WS dispatch below stays fail-open — a real inbound message must
+ // never be dropped on a transient DB failure; only the hook requires a durable row.
+ if (persisted) {
+ void this.hookManager
+ .execute(
+ 'message:persisted',
+ { sessionId: id, message: dbMessage },
+ { sessionId: id, source: 'SessionService' },
+ )
+ .catch(() => undefined);
+ }
+
+ // Dispatch to webhooks with potentially modified message
+ void this.webhookService.dispatch(id, 'message.received', finalMessage);
+ // Emit real-time event to WebSocket clients
+ this.eventsGateway.emitMessage(id, finalMessage);
}
/** Engine callback body, lifted out of initializeEngine so the wiring table stays readable. */