Free, Open Source, Self-Hosted WhatsApp API Gateway
TypeScript apibotgatewayself-hostedwhatsappwhatsapp-apiwhatsapp-automationwhatsapp-botwhatsapp-gatewaywhatsapp-gateway-apiwhatsapp-webwhatsapp-web-api
fix(message,search): reconcile outbound message state for hook-driven providers (#906) (#919)
Yudhi Armyndharis16a45e1e3334
diff --git a/docs/19-plugin-architecture.md b/docs/19-plugin-architecture.mdindex 63bb32013..f19e509ba 100644--- a/docs/19-plugin-architecture.md+++ b/docs/19-plugin-architecture.md@@ -400,12 +400,16 @@ export type HookEvent =| 'message:sent'| 'message:failed'| 'message:ack'+ | 'message:persisted'+ | 'message:deleted'// Webhook lifecycle| 'webhook:before'| 'webhook:queued'| 'webhook:delivered'| 'webhook:after'- | 'webhook:error';+ | 'webhook:error'+ // Ingress (inbound provider webhook -> plugin) lifecycle+ | 'ingress:error';```### Hook context and resultdiff --git a/docs/26-global-search.md b/docs/26-global-search.mdindex e4090b748..c327538cd 100644--- a/docs/26-global-search.md+++ b/docs/26-global-search.md@@ -163,9 +163,10 @@ provider when you need capabilities the SQL engines do not give you:The upgrade path is the **Meilisearch provider plugin** (the reference plugin backend, Spec 2). Itregisters as a `SearchProvider`, indexes via the `message:persisted` plugin hook (so it stays current-without coupling to the message/session services), and is selected by setting `SEARCH_PROVIDER` to its-id. Because the route and the response shape are identical across providers, dashboard panels and SDKs-keep working unchanged when you switch backends.+without coupling to the message/session services — outbound rows are re-emitted as upserts on every+state transition, and `message:deleted` fires when a redundant pending row is dropped), and is+selected by setting `SEARCH_PROVIDER` to its id. Because the route and the response shape are+identical across providers, dashboard panels and SDKs keep working unchanged when you switch backends.> **Backfill is the plugin's responsibility.** The `message:persisted` hook fires only for **live**> traffic — outbound on send, inbound on receive — never for history-backfill persistence. So a plugindiff --git a/docs/27-plugin-search-providers.md b/docs/27-plugin-search-providers.mdindex 511b11c84..4d4bd30f9 100644--- a/docs/27-plugin-search-providers.md+++ b/docs/27-plugin-search-providers.md@@ -79,6 +79,22 @@ ctx.registerHook('message:persisted', async (hookCtx) => {});```+**Outbound rows are re-emitted on every state transition.** An API-originated send first emits the row+as `PENDING` (usually with `waMessageId` still null), then emits it **again** with the same `id` once it+reaches its terminal state (`SENT` with the engine id, or `FAILED`). Key your documents by the row `id`+and treat every emission as an upsert, and your index always converges to the finalized state.++One race remains visible by design: when the engine's own-send echo wins, the redundant PENDING row is+merged into the echo's row and then dropped. The core emits `message:persisted` for the surviving row+(upsert it) followed by `message:deleted` for the dropped one — delete that document by its `id`:++```ts+ctx.registerHook('message:deleted', async (hookCtx) => {+ const { message } = hookCtx.data;+ await myBackend.delete(message.id);+});+```+**Backfill is the plugin's responsibility.** The hook fires only for live traffic. A plugin installed ona deployment with existing message history must perform its own one-time backfill (read the `messages`table via `ctx.engine.getChatHistory` or a direct query, and index) at `onEnable`. The built-in DB-FTSdiff --git a/src/core/hooks/hook.interfaces.spec.ts b/src/core/hooks/hook.interfaces.spec.tsindex 04e78b7e5..5cd24232e 100644--- a/src/core/hooks/hook.interfaces.spec.ts+++ b/src/core/hooks/hook.interfaces.spec.ts@@ -6,3 +6,10 @@ describe('message:persisted hook event', () => {expect(KNOWN_HOOK_EVENTS.has('message:persisted')).toBe(true);});});++describe('message:deleted hook event', () => {+ it('is a known event (search providers reconcile dropped rows via it, #906)', () => {+ expect(isKnownHookEvent('message:deleted')).toBe(true);+ expect(KNOWN_HOOK_EVENTS.has('message:deleted')).toBe(true);+ });+});diff --git a/src/core/hooks/hook.interfaces.ts b/src/core/hooks/hook.interfaces.tsindex 6c18697a7..92518a2fd 100644--- a/src/core/hooks/hook.interfaces.ts+++ b/src/core/hooks/hook.interfaces.ts@@ -19,6 +19,7 @@ export type HookEvent =| 'message:failed'| 'message:ack'| 'message:persisted'+ | 'message:deleted'// Webhook lifecycle| 'webhook:before'| 'webhook:queued' // After webhook job added to queue (queue mode only)@@ -46,6 +47,7 @@ const HOOK_EVENT_REGISTRY: Record<HookEvent, true> = {'message:failed': true,'message:ack': true,'message:persisted': true,+ 'message:deleted': true,'webhook:before': true,'webhook:queued': true,'webhook:delivered': true,diff --git a/src/modules/message/message.service.spec.ts b/src/modules/message/message.service.spec.tsindex 4c5e8a5f1..a0a490ace 100644--- a/src/modules/message/message.service.spec.ts+++ b/src/modules/message/message.service.spec.ts@@ -192,17 +192,73 @@ describe('MessageService', () => {expect(hookManager.execute).not.toHaveBeenCalledWith('message:sent', expect.anything(), expect.anything());});- it('emits message:persisted after saving an outbound message', async () => {+ it('emits message:persisted on BOTH the pending save and the finalized sent save (#906)', async () => {await service.sendText('sess-1', { chatId: '[email protected]', text: 'hello' });const calls = (hookManager.execute as jest.Mock).mock.calls.filter(([ev]: unknown[]) => ev === 'message:persisted',) as unknown[][];- expect(calls).toHaveLength(1);- expect(calls[0][1]).toMatchObject({ sessionId: 'sess-1', message: { chatId: '[email protected]' } });+ expect(calls).toHaveLength(2);+ expect(calls[0][1]).toMatchObject({+ sessionId: 'sess-1',+ message: { chatId: '[email protected]', status: MessageStatus.PENDING },+ });+ expect(calls[1][1]).toMatchObject({+ sessionId: 'sess-1',+ message: { status: MessageStatus.SENT, waMessageId: 'wa-msg-1' },+ });expect(calls[0][2]).toMatchObject({ sessionId: 'sess-1', source: 'MessageService' });});+ it('re-emits message:persisted with FAILED when the send itself fails (#906)', async () => {+ mockEngine.sendTextMessage.mockRejectedValueOnce(new Error('engine down'));++ await expect(service.sendText('sess-1', { chatId: '[email protected]', text: 'hi' })).rejects.toThrow();++ const calls = (hookManager.execute as jest.Mock).mock.calls.filter(+ ([ev]: unknown[]) => ev === 'message:persisted',+ ) as unknown[][];+ expect(calls).toHaveLength(2);+ expect(calls[0][1]).toMatchObject({ message: { status: MessageStatus.PENDING } });+ expect(calls[1][1]).toMatchObject({ message: { status: MessageStatus.FAILED } });+ });++ it('reconciles provider indexes when the send echo won the race: upsert the surviving row + drop the ghost (#906)', async () => {+ const echoRow = {+ id: 'echo-uuid-9',+ sessionId: 'sess-1',+ waMessageId: 'wa-msg-1',+ status: MessageStatus.SENT,+ } as Message;+ (repository.save as jest.Mock)+ .mockImplementationOnce((msg: unknown) => Promise.resolve(msg)) // PENDING save+ .mockRejectedValueOnce(+ Object.assign(new Error('UNIQUE constraint failed'), { code: 'SQLITE_CONSTRAINT_UNIQUE' }),+ ); // SENT save collides with the echo row+ (repository.findOne as jest.Mock).mockResolvedValueOnce(echoRow);++ await service.sendText('sess-1', { chatId: '[email protected]', text: 'hi' });++ // SENT state merged onto the echo row; the redundant PENDING row dropped.+ expect(repository.update).toHaveBeenCalledWith(+ { sessionId: 'sess-1', waMessageId: 'wa-msg-1' },+ expect.objectContaining({ status: MessageStatus.SENT }),+ );+ expect(repository.delete).toHaveBeenCalledWith({ id: 'msg-uuid-1' });+ const persisted = (hookManager.execute as jest.Mock).mock.calls.filter(+ ([ev]: unknown[]) => ev === 'message:persisted',+ ) as unknown[][];+ // PENDING + the surviving echo row (the failed SENT save itself emits nothing).+ expect(persisted).toHaveLength(2);+ expect(persisted[1][1]).toMatchObject({ message: { id: 'echo-uuid-9' } });+ const deleted = (hookManager.execute as jest.Mock).mock.calls.filter(+ ([ev]: unknown[]) => ev === 'message:deleted',+ ) as unknown[][];+ expect(deleted).toHaveLength(1);+ expect(deleted[0][1]).toMatchObject({ sessionId: 'sess-1', message: { id: 'msg-uuid-1' } });+ expect(deleted[0][2]).toMatchObject({ sessionId: 'sess-1', source: 'MessageService' });+ });+it('should throw BadRequestException when plugin blocks sending', async () => {(hookManager.execute as jest.Mock).mockResolvedValueOnce({ continue: false, data: {} });diff --git a/src/modules/message/message.service.ts b/src/modules/message/message.service.tsindex f996d19c7..906a7cc42 100644--- a/src/modules/message/message.service.ts+++ b/src/modules/message/message.service.ts@@ -536,12 +536,20 @@ export class MessageService {metadata: data.metadata,});const saved = await this.messageRepository.save(message);- // Fire-and-forget: a plugin handler must never break the send path. The built-in FTS search provider- // is DB-synced and does NOT consume this; it exists for plugin providers (Spec 2) + general use.+ this.emitPersisted(sessionId, saved);+ return saved;+ }++ // Fire-and-forget: a plugin handler must never break the send path. The built-in FTS search provider+ // is DB-synced and does NOT consume this; it exists for plugin providers (Spec 2) + general use.+ // Emitted for EVERY persisted state of an outbound row — the initial PENDING write AND each later+ // transition (SENT / FAILED / merge) — so a provider's copy never stays stuck at PENDING (#906).+ // The payload is a shallow snapshot: the same entity instance is mutated as the send progresses+ // (PENDING → SENT/FAILED), and fire-and-forget execution must still see the state at emission time.+ private emitPersisted(sessionId: string, message: Message): void {void this.hookManager- .execute('message:persisted', { sessionId, message: saved }, { sessionId, source: 'MessageService' })+ .execute('message:persisted', { sessionId, message: { ...message } }, { sessionId, source: 'MessageService' }).catch(() => undefined);- return saved;}/**@@ -556,6 +564,8 @@ export class MessageService {}message.status = MessageStatus.FAILED;await this.messageRepository.save(message);+ // Reconcile the earlier PENDING emission (#906): a provider must see the terminal FAILED state.+ this.emitPersisted(message.sessionId, message);}/**@@ -573,6 +583,8 @@ export class MessageService {message.timestamp = result.timestamp;try {await this.messageRepository.save(message);+ // Reconcile the earlier PENDING emission with the finalized row (#906).+ this.emitPersisted(message.sessionId, message);} catch (persistError) {if (result.id && isUniqueConstraintError(persistError)) {// The engine's own-send echo (onMessageCreate) won the race and already persisted a row with@@ -598,6 +610,19 @@ export class MessageService {}),);await this.messageRepository.delete({ id: message.id }).catch(() => undefined);+ // Reconcile provider indexes (#906): upsert the surviving echo row (now carrying our SENT+ // state + media) and drop the ghost PENDING document this redundant row produced earlier.+ const surviving = await this.messageRepository+ .findOne({ where: { sessionId: message.sessionId, waMessageId: result.id } })+ .catch(() => null);+ if (surviving) this.emitPersisted(message.sessionId, surviving);+ void this.hookManager+ .execute(+ 'message:deleted',+ { sessionId: message.sessionId, message: { ...message } },+ { sessionId: message.sessionId, source: 'MessageService' },+ )+ .catch(() => undefined);} else {this.logger.warn(`Persisting SENT state failed after a successful send (id=${result.id})`, {error: persistError instanceof Error ? persistError.message : String(persistError),