Free, Open Source, Self-Hosted WhatsApp API Gateway
TypeScript apibotgatewayself-hostedwhatsappwhatsapp-apiwhatsapp-automationwhatsapp-botwhatsapp-gatewaywhatsapp-gateway-apiwhatsapp-webwhatsapp-web-api
feat(webhook): make an outbound delivery survive a hard crash
Yudhi Armyndharis5f3b0d84810c
diff --git a/.env.example b/.env.exampleindex ea706be29..d2b896b14 100644--- a/.env.example+++ b/.env.example@@ -613,6 +613,16 @@ WEBHOOK_SSRF_PROTECT=true# INGRESS_RECONCILE_BATCH_SIZE=50 # stale rows replayed per sweep, oldest first# INGRESS_RECONCILE_MAX_ATTEMPTS=5 # replays per event before it goes terminal + DLQ (min 1)+# Webhook delivery reconciler: the outbound twin of the block above. Fan-out is fire-and-forget, so+# a hard crash between persisting a message and completing its POST used to lose the delivery with+# nothing left behind. Each delivery is now recorded before it is attempted and retired once a+# durable owner has it (handed to the queue, or completed inline), and this sweep replays whatever+# is still stranded, reusing the STORED idempotency key so a receiver can dedup the retry.+# WEBHOOK_RECONCILE_INTERVAL_MS=60000 # sweep interval; <= 0 disables the reconciler+# WEBHOOK_RECONCILE_GRACE_MS=60000 # age a 'pending' row must pass before it counts as stranded+# WEBHOOK_RECONCILE_BATCH_SIZE=50 # stranded rows replayed per sweep, oldest first+# WEBHOOK_RECONCILE_MAX_ATTEMPTS=5 # replays before the row goes terminal (min 1)+# Concurrency of the BullMQ workers that process queued webhooks and ingress events. Only meaningful# when QUEUE_ENABLED=true. Ordering within one conversation is preserved by a per-conversation lock,# so raising these parallelizes unrelated conversations rather than reordering them.diff --git a/CHANGELOG.md b/CHANGELOG.mdindex 12a244202..c8ddb85e1 100644--- a/CHANGELOG.md+++ b/CHANGELOG.md@@ -10,6 +10,7 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0### Fixed- The dashboard CSP nonce is substituted at every occurrence in the served document, not only the first. One placeholder exists today, so a second would have been left reading the literal text and its script refused by the browser.+- Outbound webhook deliveries survive a hard crash. Fan-out is fire-and-forget, so a crash between persisting a message and completing its POST lost the delivery with no record in either mode, while the documented contract promises at-least-once. Each delivery is now recorded before it is attempted, retired once the queue or the inline send owns it, and a bounded sweep replays whatever is left stranded using the stored idempotency key so the retry stays deduplicable at the receiver.### Testsdiff --git a/docker-compose.dev.yml b/docker-compose.dev.ymlindex 14d51b728..84f636b9e 100644--- a/docker-compose.dev.yml+++ b/docker-compose.dev.yml@@ -209,6 +209,10 @@ services:- INGRESS_RECONCILE_GRACE_MS=${INGRESS_RECONCILE_GRACE_MS:-}- INGRESS_RECONCILE_BATCH_SIZE=${INGRESS_RECONCILE_BATCH_SIZE:-}- INGRESS_RECONCILE_MAX_ATTEMPTS=${INGRESS_RECONCILE_MAX_ATTEMPTS:-}+ - WEBHOOK_RECONCILE_INTERVAL_MS=${WEBHOOK_RECONCILE_INTERVAL_MS:-}+ - WEBHOOK_RECONCILE_GRACE_MS=${WEBHOOK_RECONCILE_GRACE_MS:-}+ - WEBHOOK_RECONCILE_BATCH_SIZE=${WEBHOOK_RECONCILE_BATCH_SIZE:-}+ - WEBHOOK_RECONCILE_MAX_ATTEMPTS=${WEBHOOK_RECONCILE_MAX_ATTEMPTS:-}- INGRESS_WORKER_CONCURRENCY=${INGRESS_WORKER_CONCURRENCY:-}# WebSocket gateway limits.- WS_RATE_LIMIT_FRAME_PER_SECOND=${WS_RATE_LIMIT_FRAME_PER_SECOND:-}diff --git a/docker-compose.yml b/docker-compose.ymlindex 76cd66ee5..c61f8fff4 100644--- a/docker-compose.yml+++ b/docker-compose.yml@@ -306,6 +306,10 @@ services:- INGRESS_RECONCILE_GRACE_MS=${INGRESS_RECONCILE_GRACE_MS:-}- INGRESS_RECONCILE_BATCH_SIZE=${INGRESS_RECONCILE_BATCH_SIZE:-}- INGRESS_RECONCILE_MAX_ATTEMPTS=${INGRESS_RECONCILE_MAX_ATTEMPTS:-}+ - WEBHOOK_RECONCILE_INTERVAL_MS=${WEBHOOK_RECONCILE_INTERVAL_MS:-}+ - WEBHOOK_RECONCILE_GRACE_MS=${WEBHOOK_RECONCILE_GRACE_MS:-}+ - WEBHOOK_RECONCILE_BATCH_SIZE=${WEBHOOK_RECONCILE_BATCH_SIZE:-}+ - WEBHOOK_RECONCILE_MAX_ATTEMPTS=${WEBHOOK_RECONCILE_MAX_ATTEMPTS:-}- INGRESS_WORKER_CONCURRENCY=${INGRESS_WORKER_CONCURRENCY:-}# WebSocket gateway limits (frames bypass the HTTP guard pipeline).- WS_RATE_LIMIT_FRAME_PER_SECOND=${WS_RATE_LIMIT_FRAME_PER_SECOND:-}diff --git a/docs/06-api-specification.md b/docs/06-api-specification.mdindex 2c1e6e158..a5da10226 100644--- a/docs/06-api-specification.md+++ b/docs/06-api-specification.md@@ -6776,7 +6776,7 @@ Webhook delivery is **at-least-once**. A consumer can legitimately receive the s- The underlying WhatsApp engine can re-fire an event for a single message.- A failed delivery (non-2xx response, timeout, or network error) is retried.-**Crash boundary.** With the queue off (the default), dispatch is fire-and-forget from memory: a hard crash (SIGKILL, OOM) loses deliveries that were in flight or parked at that moment, and no failure row is written for them (the table records exhausted retries, plus over-budget, dispatch-capacity-exceeded, and shutdown-rejected deliveries with attempts 0). Enabling the queue (`QUEUE_ENABLED=true`, needs Redis) makes the dispatch durable from the enqueue onward. In both modes, a graceful shutdown drains in-flight deliveries first: the queued path waits for each worker's current job, and the direct path waits up to `WEBHOOK_SHUTDOWN_DRAIN_MS` (default 5s; raise it to at least `WEBHOOK_TIMEOUT`, default 10s, if a slow receiver must finish).+**Crash boundary.** Every delivery is recorded before it is attempted, and the record is retired once something durable owns it: the queue job in queued mode, the completed send in direct mode. A hard crash (SIGKILL, OOM) therefore leaves the record behind, and a bounded sweep (`WEBHOOK_RECONCILE_INTERVAL_MS`, default 60s) replays whatever is still stranded, reusing the stored `X-OpenWA-Idempotency-Key` so the retry stays deduplicable at your receiver. A delivery that keeps failing exhausts `WEBHOOK_RECONCILE_MAX_ATTEMPTS` and goes terminal rather than replaying forever. One window remains open: a crash between persisting the message and writing that record loses the delivery, because the two are not yet one transaction. The failure table records exhausted retries, plus over-budget, dispatch-capacity-exceeded, and shutdown-rejected deliveries with attempts 0. Enabling the queue (`QUEUE_ENABLED=true`, needs Redis) makes the dispatch durable from the enqueue onward. In both modes, a graceful shutdown drains in-flight deliveries first: the queued path waits for each worker's current job, and the direct path waits up to `WEBHOOK_SHUTDOWN_DRAIN_MS` (default 5s; raise it to at least `WEBHOOK_TIMEOUT`, default 10s, if a slow receiver must finish).**Design your handler to be idempotent**, keyed on the `X-OpenWA-Idempotency-Key` header (see below). As a server-side safety net, OpenWA de-duplicates inbound `message.received` before dispatch (a re-fired event for an already-persisted message is dropped), so one webhook normally sees each inbound message once — but this is best-effort defense-in-depth and does not remove the need for consumer-side idempotency.diff --git a/openapi.json b/openapi.jsonindex 76b8a482a..8d4b75aae 100644--- a/openapi.json+++ b/openapi.json@@ -13585,6 +13585,12 @@"type": "object"}},+ "webhookOutboxEvents": {+ "type": "array",+ "items": {+ "type": "object"+ }+ },"integrationDeliveryFailures": {"type": "array","items": {@@ -13616,6 +13622,7 @@"conversationMappings","ingressEvents","webhookDeliveryFailures",+ "webhookOutboxEvents","integrationDeliveryFailures","statusUpdates","automationRules"@@ -13668,6 +13675,10 @@"type": "number","example": 0},+ "webhookOutboxEvents": {+ "type": "number",+ "example": 0+ },"integrationDeliveryFailures": {"type": "number","example": 0@@ -13693,6 +13704,7 @@"conversationMappings","ingressEvents","webhookDeliveryFailures",+ "webhookOutboxEvents","integrationDeliveryFailures","statusUpdates","automationRules"@@ -13807,6 +13819,9 @@"webhookDeliveryFailures": {"type": "array"},+ "webhookOutboxEvents": {+ "type": "array"+ },"integrationDeliveryFailures": {"type": "array"},diff --git a/src/config/env-precedence.ts b/src/config/env-precedence.tsindex 264505424..f198499ac 100644--- a/src/config/env-precedence.ts+++ b/src/config/env-precedence.ts@@ -173,6 +173,10 @@ export const BLANK_SHADOWED_ENV_KEYS: string[] = ['INGRESS_RECONCILE_GRACE_MS','INGRESS_RECONCILE_BATCH_SIZE','INGRESS_RECONCILE_MAX_ATTEMPTS',+ 'WEBHOOK_RECONCILE_INTERVAL_MS',+ 'WEBHOOK_RECONCILE_GRACE_MS',+ 'WEBHOOK_RECONCILE_BATCH_SIZE',+ 'WEBHOOK_RECONCILE_MAX_ATTEMPTS','INGRESS_WORKER_CONCURRENCY','WS_RATE_LIMIT_FRAME_PER_SECOND','WS_RATE_LIMIT_FRAME_BURST',diff --git a/src/database/migrations/1786200000000-AddWebhookOutboxEvents.ts b/src/database/migrations/1786200000000-AddWebhookOutboxEvents.tsnew file mode 100644index 000000000..6e9ccb693--- /dev/null+++ b/src/database/migrations/1786200000000-AddWebhookOutboxEvents.ts@@ -0,0 +1,53 @@+import { MigrationInterface, QueryRunner } from 'typeorm';++/**+ * Creates `webhook_outbox_events` - the durable record of an outbound delivery, written before the+ * attempt so a hard crash between persisting a message and completing its POST leaves something+ * behind to replay. Mirrors `ingress_events` on the inbound side, including the retired-payload+ * rule: only a 'pending' row carries a payload, so a dispatched or failed row costs a few columns.+ *+ * UNIQUE(webhookId, idempotencyKey) is the natural key: the key is already salted per webhook at+ * dispatch, so the pair names one delivery exactly and a replay reuses the STORED key.+ *+ * Hand-authored because `synchronize` is off on the `data` connection for Postgres. `payload` is+ * `text` on BOTH dialects to match `jsonColumnType()`, which resolves to 'simple-json' everywhere:+ * a `jsonb` column would be auto-parsed by the pg driver and hand back a shape the entity does not+ * expect.+ */+export class AddWebhookOutboxEvents1786200000000 implements MigrationInterface {+ name = 'AddWebhookOutboxEvents1786200000000';++ public async up(queryRunner: QueryRunner): Promise<void> {+ if (await queryRunner.hasTable('webhook_outbox_events')) return;+ const isPostgres = queryRunner.connection.options.type === 'postgres';+ const id = isPostgres+ ? `"id" varchar PRIMARY KEY NOT NULL DEFAULT gen_random_uuid()::varchar`+ : `"id" varchar PRIMARY KEY NOT NULL`;+ // SQLite side is `text` + DateTransformer, not `datetime`: that is what `dateColumnType()`+ // resolves to for this entity, and the drift gate compares the chain against that metadata.+ const ts = isPostgres ? 'timestamp' : 'text';+ const now = isPostgres ? 'NOW()' : `(datetime('now'))`;++ await queryRunner.query(+ `CREATE TABLE "webhook_outbox_events" (${id}, "webhookId" varchar NOT NULL, "sessionId" varchar NOT NULL, ` ++ `"event" varchar NOT NULL, "idempotencyKey" varchar NOT NULL, "deliveryId" varchar NOT NULL, ` ++ `"payload" text, "state" varchar, "attempts" integer NOT NULL DEFAULT (0), "lastAttemptAt" ${ts}, ` ++ `"createdAt" ${ts} NOT NULL DEFAULT ${now})`,+ );++ await queryRunner.query(+ `CREATE UNIQUE INDEX "UQ_webhook_outbox_events_webhook_key" ON "webhook_outbox_events" ("webhookId", "idempotencyKey")`,+ );+ await queryRunner.query(+ `CREATE INDEX "IDX_webhook_outbox_events_state_createdAt" ON "webhook_outbox_events" ("state", "createdAt")`,+ );+ }++ public async down(queryRunner: QueryRunner): Promise<void> {+ // IF EXISTS so revert is idempotent on a synchronize-bootstrapped DB, where up() took the+ // hasTable early return and the named indexes were never created.+ await queryRunner.query(`DROP INDEX IF EXISTS "IDX_webhook_outbox_events_state_createdAt"`);+ await queryRunner.query(`DROP INDEX IF EXISTS "UQ_webhook_outbox_events_webhook_key"`);+ await queryRunner.query(`DROP TABLE IF EXISTS "webhook_outbox_events"`);+ }+}diff --git a/src/database/migrations/__tests__/1786200000000-AddWebhookOutboxEvents.spec.ts b/src/database/migrations/__tests__/1786200000000-AddWebhookOutboxEvents.spec.tsnew file mode 100644index 000000000..22216fb85--- /dev/null+++ b/src/database/migrations/__tests__/1786200000000-AddWebhookOutboxEvents.spec.ts@@ -0,0 +1,66 @@+import { DataSource } from 'typeorm';+import { AddWebhookOutboxEvents1786200000000 } from '../1786200000000-AddWebhookOutboxEvents';++describe('AddWebhookOutboxEvents migration', () => {+ let ds: DataSource;+ const migration = new AddWebhookOutboxEvents1786200000000();++ beforeEach(async () => {+ ds = new DataSource({ type: 'better-sqlite3', database: ':memory:' });+ await ds.initialize();+ });++ afterEach(async () => {+ if (ds.isInitialized) await ds.destroy();+ });++ it('creates the table with both indexes', async () => {+ await migration.up(ds.createQueryRunner());++ const cols: { name: string }[] = await ds.query(`PRAGMA table_info("webhook_outbox_events")`);+ expect(cols.map(c => c.name).sort()).toEqual(+ [+ 'attempts',+ 'createdAt',+ 'deliveryId',+ 'event',+ 'id',+ 'idempotencyKey',+ 'lastAttemptAt',+ 'payload',+ 'sessionId',+ 'state',+ 'webhookId',+ ].sort(),+ );+ const indexes: { name: string }[] = await ds.query(`PRAGMA index_list("webhook_outbox_events")`);+ expect(indexes.map(i => i.name).sort()).toContain('UQ_webhook_outbox_events_webhook_key');+ expect(indexes.map(i => i.name)).toContain('IDX_webhook_outbox_events_state_createdAt');+ });++ it('refuses a second row for the same webhook and idempotency key', async () => {+ await migration.up(ds.createQueryRunner());+ const insert = (id: string): Promise<unknown> =>+ ds.query(+ `INSERT INTO "webhook_outbox_events" ("id","webhookId","sessionId","event","idempotencyKey","deliveryId","attempts") ` ++ `VALUES ('${id}','wh-1','sess-1','message.received','key-1','del-1',0)`,+ );++ await insert('row-1');+ // The unique key is what makes open() idempotent: a replay must reuse the row, not add one.+ await expect(insert('row-2')).rejects.toThrow();+ });++ it('is a no-op when the table already exists, and reverts idempotently', async () => {+ await migration.up(ds.createQueryRunner());+ await expect(migration.up(ds.createQueryRunner())).resolves.toBeUndefined();++ await migration.down(ds.createQueryRunner());+ const tables: unknown[] = await ds.query(+ `SELECT name FROM sqlite_master WHERE type='table' AND name='webhook_outbox_events'`,+ );+ expect(tables).toHaveLength(0);+ // Reverting a database where up() took the early return must not throw on a missing index.+ await expect(migration.down(ds.createQueryRunner())).resolves.toBeUndefined();+ });+});diff --git a/src/modules/infra/dto/infra-response.dto.ts b/src/modules/infra/dto/infra-response.dto.tsindex c91aff92a..1f6f2f597 100644--- a/src/modules/infra/dto/infra-response.dto.ts+++ b/src/modules/infra/dto/infra-response.dto.ts@@ -388,6 +388,7 @@ export class MigrationTablesDto {@ApiProperty({ type: [Object] }) conversationMappings!: object[];@ApiProperty({ type: [Object] }) ingressEvents!: object[];@ApiProperty({ type: [Object] }) webhookDeliveryFailures!: object[];+ @ApiProperty({ type: [Object] }) webhookOutboxEvents!: object[];@ApiProperty({ type: [Object] }) integrationDeliveryFailures!: object[];@ApiProperty({ type: [Object] }) statusUpdates!: object[];@ApiProperty({ type: [Object] }) automationRules!: object[];@@ -406,6 +407,7 @@ export class TableCountsDto {@ApiProperty({ example: 8 }) conversationMappings!: number;@ApiProperty({ example: 40 }) ingressEvents!: number;@ApiProperty({ example: 0 }) webhookDeliveryFailures!: number;+ @ApiProperty({ example: 0 }) webhookOutboxEvents!: number;@ApiProperty({ example: 0 }) integrationDeliveryFailures!: number;@ApiProperty({ example: 5 }) statusUpdates!: number;@ApiProperty({ example: 2 }) automationRules!: number;diff --git a/src/modules/infra/export-tables.ts b/src/modules/infra/export-tables.tsindex 237bff3e2..dcbc90204 100644--- a/src/modules/infra/export-tables.ts+++ b/src/modules/infra/export-tables.ts@@ -217,6 +217,7 @@ export const EXPORT_TABLES: AnyExportTable[] = [defineExportTable({ key: 'conversationMappings', table: 'conversation_mappings', optional: true }),defineExportTable({ key: 'ingressEvents', table: 'ingress_events', optional: true }),defineExportTable({ key: 'webhookDeliveryFailures', table: 'webhook_delivery_failures', optional: true }),+ defineExportTable({ key: 'webhookOutboxEvents', table: 'webhook_outbox_events', optional: true }),defineExportTable({key: 'integrationDeliveryFailures',table: 'integration_delivery_failures',diff --git a/src/modules/infra/infra-data.controller.spec.ts b/src/modules/infra/infra-data.controller.spec.tsindex 41ad37079..ef7cf2697 100644--- a/src/modules/infra/infra-data.controller.spec.ts+++ b/src/modules/infra/infra-data.controller.spec.ts@@ -38,6 +38,7 @@ import { PluginInstance } from '../integration/entities/plugin-instance.entity';import { ConversationMapping } from '../integration/entities/conversation-mapping.entity';import { IngressEvent } from '../integration/entities/ingress-event.entity';import { WebhookDeliveryFailure } from '../webhook/entities/webhook-delivery-failure.entity';+import { WebhookOutboxEvent } from '../webhook/entities/webhook-outbox-event.entity';import { IntegrationDeliveryFailure } from '../integration/entities/integration-delivery-failure.entity';import { StatusUpdate } from '../status-store/entities/status-update.entity';import { AutomationRule } from '../automation/entities/automation-rule.entity';@@ -74,6 +75,7 @@ describe('InfraDataController.importData round-trips export-data (no silent messConversationMapping,IngressEvent,WebhookDeliveryFailure,+ WebhookOutboxEvent,IntegrationDeliveryFailure,StatusUpdate,AutomationRule,@@ -1213,6 +1215,7 @@ describe('InfraDataController.import/export preserves every data-DB table', () =ConversationMapping,IngressEvent,WebhookDeliveryFailure,+ WebhookOutboxEvent,IntegrationDeliveryFailure,StatusUpdate,AutomationRule,@@ -1444,6 +1447,7 @@ describe('InfraDataController audit trail — import emits only on a committed rConversationMapping,IngressEvent,WebhookDeliveryFailure,+ WebhookOutboxEvent,IntegrationDeliveryFailure,StatusUpdate,AutomationRule,@@ -1588,6 +1592,7 @@ describe('InfraDataController.importData status_updates + runtime reconciliationConversationMapping,IngressEvent,WebhookDeliveryFailure,+ WebhookOutboxEvent,IntegrationDeliveryFailure,StatusUpdate,AutomationRule,diff --git a/src/modules/infra/migration-tables.types.ts b/src/modules/infra/migration-tables.types.tsindex 10e6635e2..af6922fa2 100644--- a/src/modules/infra/migration-tables.types.ts+++ b/src/modules/infra/migration-tables.types.ts@@ -173,6 +173,20 @@ export interface WebhookDeliveryFailureRow {createdAt: string;}+export interface WebhookOutboxEventRow {+ id: string;+ webhookId: string;+ sessionId: string;+ event: string;+ idempotencyKey: string;+ deliveryId: string;+ payload: string | null;+ state: string | null;+ attempts: number;+ lastAttemptAt: string | null;+ createdAt: string;+}+export interface IntegrationDeliveryFailureRow {id: string;direction: string;@@ -240,6 +254,7 @@ export interface MigrationTables {conversationMappings: ConversationMappingRow[];ingressEvents: IngressEventRow[];webhookDeliveryFailures: WebhookDeliveryFailureRow[];+ webhookOutboxEvents: WebhookOutboxEventRow[];integrationDeliveryFailures: IntegrationDeliveryFailureRow[];statusUpdates: StatusUpdateRow[];automationRules: AutomationRuleRow[];diff --git a/src/modules/infra/table-importers.ts b/src/modules/infra/table-importers.tsindex cb93328f4..77bfc9e56 100644--- a/src/modules/infra/table-importers.ts+++ b/src/modules/infra/table-importers.ts@@ -12,6 +12,7 @@ import type {ConversationMappingRow,IngressEventRow,WebhookDeliveryFailureRow,+ WebhookOutboxEventRow,IntegrationDeliveryFailureRow,StatusUpdateRow,AutomationRuleRow,@@ -312,6 +313,30 @@ export const TABLE_IMPORTERS: AnyTableImporter[] = [],}),+ // Import the outbound delivery record. Restoring it restores the replay backlog: a 'pending'+ // row still carries its payload, so the reconciler on the target instance picks up where the+ // source left off.+ defineTableImporter({+ key: 'webhookOutboxEvents',+ label: 'webhook outbox event',+ sql: `INSERT INTO webhook_outbox_events (id, "webhookId", "sessionId", event, "idempotencyKey", "deliveryId", payload, state, attempts, "lastAttemptAt", "createdAt")+ VALUES ($1, $2, $3, $4, $5, $6, $7, $8, $9, $10, $11)`,+ id: (row: WebhookOutboxEventRow) => row.id,+ map: (row: WebhookOutboxEventRow) => [+ row.id,+ row.webhookId,+ row.sessionId,+ row.event,+ row.idempotencyKey,+ row.deliveryId,+ row.payload,+ row.state,+ row.attempts,+ row.lastAttemptAt,+ row.createdAt,+ ],+ }),+// Import integration delivery failures (inbound + outbound DLQ)defineTableImporter({key: 'integrationDeliveryFailures',@@ -398,6 +423,7 @@ const EXPECTED_TABLE_KEYS: ReadonlyArray<keyof MigrationTables> = ['conversationMappings','ingressEvents','webhookDeliveryFailures',+ 'webhookOutboxEvents','integrationDeliveryFailures','statusUpdates','automationRules',diff --git a/src/modules/webhook/entities/webhook-outbox-event.entity.ts b/src/modules/webhook/entities/webhook-outbox-event.entity.tsnew file mode 100644index 000000000..cde73c128--- /dev/null+++ b/src/modules/webhook/entities/webhook-outbox-event.entity.ts@@ -0,0 +1,69 @@+import { Column, CreateDateColumn, Entity, Index, PrimaryGeneratedColumn } from 'typeorm';+import { dateColumnType, jsonColumnType } from '../../../common/utils/column-types';+import { DateTransformer } from '../../../common/transformers/date.transformer';++// The dispatch lifecycle of one outbound delivery, mirroring ingress_events on the inbound side:+// - 'pending' - the row was written before the attempt; nothing durable owns the delivery yet.+// The reconciler sweeps these.+// - 'dispatched' - the delivery reached a durable owner: handed to BullMQ, or completed inline in+// direct mode. A failure INSIDE that owner dead-letters separately through+// webhook_delivery_failures, so a 'dispatched' row is never the reconciler's+// concern. Retiring on ENQUEUE rather than on the POST is what stops the+// reconciler duplicating work BullMQ already owns.+// - 'failed' - terminal: the reconciler exhausted its replay budget. Recovery continues+// through the failure row.+// NULL marks rows that predate these columns on a synchronize-bootstrapped database. NULL reads as+// "not watched", so an upgrade can never mass-replay history.+export type WebhookOutboxState = 'pending' | 'dispatched' | 'failed';++/**+ * Durable record of an outbound webhook delivery, written before the attempt.+ *+ * Fan-out is fire-and-forget from the projector (`void dispatch(...)`), so until this row existed a+ * hard crash between persisting a message and completing its POST lost the delivery with nothing+ * left behind in either mode. The in-memory `inFlightDeliveries` map already tracked exactly this+ * set; the row is its durable twin.+ *+ * UNIQUE(webhookId, idempotencyKey): the key is already salted per webhook at dispatch, so the pair+ * names one delivery attempt-set exactly, and a replay reuses the STORED key rather than deriving a+ * new one, which is what keeps a redelivery deduplicable at the receiver.+ */+@Entity('webhook_outbox_events')+@Index('UQ_webhook_outbox_events_webhook_key', ['webhookId', 'idempotencyKey'], { unique: true })+@Index('IDX_webhook_outbox_events_state_createdAt', ['state', 'createdAt'])+export class WebhookOutboxEvent {+ @PrimaryGeneratedColumn('uuid')+ id!: string;++ @Column()+ webhookId!: string;++ @Column()+ sessionId!: string;++ @Column()+ event!: string;++ @Column()+ idempotencyKey!: string;++ @Column()+ deliveryId!: string;++ // Retired to NULL the moment an outcome is recorded: only 'pending' rows are replayable, and a+ // dispatched or failed row has no reason to keep a payload that can carry a whole message body.+ @Column({ type: jsonColumnType(), nullable: true })+ payload!: Record<string, unknown> | null;++ @Column({ type: 'varchar', nullable: true })+ state!: WebhookOutboxState | null;++ @Column({ type: 'int', default: 0 })+ attempts!: number;++ @Column({ type: dateColumnType(), nullable: true, transformer: DateTransformer })+ lastAttemptAt!: Date | null;++ @CreateDateColumn({ type: dateColumnType(), transformer: DateTransformer })+ createdAt!: Date;+}diff --git a/src/modules/webhook/webhook-delivery.service.spec.ts b/src/modules/webhook/webhook-delivery.service.spec.tsindex 68c6ad2f4..9a3143be1 100644--- a/src/modules/webhook/webhook-delivery.service.spec.ts+++ b/src/modules/webhook/webhook-delivery.service.spec.ts@@ -18,6 +18,7 @@ import { ConfigService } from '@nestjs/config';import * as crypto from 'crypto';import { fetch as undiciFetch } from 'undici';import { WebhookDeliveryService, WebhookPayload, WebhookJobData } from './webhook-delivery.service';+import { WebhookOutboxService } from './webhook-outbox.service';import { Webhook } from './entities/webhook.entity';import { WebhookDeliveryFailure } from './entities/webhook-delivery-failure.entity';import { Session } from '../session/entities/session.entity';@@ -56,6 +57,7 @@ describe('WebhookDeliveryService', () => {let hookManager: jest.Mocked<Partial<HookManager>>;let webhookQueue: jest.Mocked<Record<string, jest.Mock>>;let lidStore: { getCached: jest.Mock; resolveLid: jest.Mock };+ let outboxService: { open: jest.Mock; close: jest.Mock };beforeEach(async () => {repository = {@@ -98,11 +100,14 @@ describe('WebhookDeliveryService', () => {resolveLid: jest.fn((jid: string) => (lidStore.getCached(userPart(jid)) as string | null | undefined) ?? null),};+ outboxService = { open: jest.fn().mockResolvedValue(undefined), close: jest.fn().mockResolvedValue(undefined) };+const module: TestingModule = await Test.createTestingModule({providers: [WebhookDeliveryService,{ provide: getRepositoryToken(Webhook, 'data'), useValue: repository },{ provide: getRepositoryToken(WebhookDeliveryFailure, 'data'), useValue: failureRepository },+ { provide: WebhookOutboxService, useValue: outboxService },{ provide: ConfigService, useValue: configService },{ provide: HookManager, useValue: hookManager },{ provide: LidMappingStoreService, useValue: lidStore },@@ -176,6 +181,25 @@ describe('WebhookDeliveryService', () => {expect(mockFetch).not.toHaveBeenCalled();});+ it('records the delivery before attempting it, and retires the record once it lands', async () => {+ const webhook = createMockWebhook({ events: ['message.received'] });+ (repository.find as jest.Mock).mockResolvedValue([webhook]);+ (repository.update as jest.Mock).mockResolvedValue({ affected: 1 });++ await service.dispatch('sess-1', 'message.received', { from: '[email protected]' });++ // Durability is only worth anything if the row exists BEFORE the attempt: a crash during the+ // POST is exactly the window this closes.+ expect(outboxService.open).toHaveBeenCalledTimes(1);+ const opened = (outboxService.open.mock.calls as unknown as Record<string, unknown>[][])[0][0];+ expect(opened).toMatchObject({ webhookId: webhook.id, sessionId: 'sess-1', event: 'message.received' });+ expect(opened.idempotencyKey).toEqual(expect.stringContaining(webhook.id));+ expect(outboxService.open.mock.invocationCallOrder[0]).toBeLessThan(mockFetch.mock.invocationCallOrder[0]);++ // Retired once a durable owner has it, so the reconciler never replays a delivered event.+ expect(outboxService.close).toHaveBeenCalledWith(webhook.id, opened.idempotencyKey, 'dispatched');+ });+it('should dispatch to webhooks matching the event', async () => {const webhook = createMockWebhook({ events: ['message.received'] });(repository.find as jest.Mock).mockResolvedValue([webhook]);@@ -1140,6 +1164,8 @@ describe('WebhookDeliveryService', () => {WebhookDeliveryService,{ provide: getRepositoryToken(Webhook, 'data'), useValue: repository },{ provide: getRepositoryToken(WebhookDeliveryFailure, 'data'), useValue: failureRepository },+ { provide: WebhookOutboxService, useValue: outboxService },+ { provide: WebhookOutboxService, useValue: outboxService },{ provide: ConfigService, useValue: { get: jest.fn().mockImplementation(configGet) } },{ provide: HookManager, useValue: hookManager },{ provide: getQueueToken(QUEUE_NAMES.WEBHOOK), useValue: webhookQueue },diff --git a/src/modules/webhook/webhook-delivery.service.ts b/src/modules/webhook/webhook-delivery.service.tsindex 96c359ca2..af35ac00e 100644--- a/src/modules/webhook/webhook-delivery.service.ts+++ b/src/modules/webhook/webhook-delivery.service.ts@@ -7,6 +7,7 @@ import { Queue } from 'bullmq';import * as crypto from 'crypto';import { setTimeout } from 'node:timers/promises';import { Webhook } from './entities/webhook.entity';+import { WebhookOutboxService } from './webhook-outbox.service';import { WebhookDeliveryFailure } from './entities/webhook-delivery-failure.entity';import { recordWebhookDeliveryFailure } from './utils/record-delivery-failure';import { postWebhookPayload, recordTerminalFailure } from './utils/deliver-once';@@ -96,6 +97,7 @@ export class WebhookDeliveryService implements OnModuleInit, OnModuleDestroy {private readonly failureRepository: Repository<WebhookDeliveryFailure>,private readonly configService: ConfigService,private readonly hookManager: HookManager,+ private readonly outbox: WebhookOutboxService,@Optional()private readonly lidMappingStore?: LidMappingStoreService,@Optional()@@ -572,6 +574,16 @@ export class WebhookDeliveryService implements OnModuleInit, OnModuleDestroy {const deliveryId = generateDeliveryId();// Salt per webhook so sibling subscriptions cannot collide at the receiver's dedup boundary.const idempotencyKey = `${baseIdempotencyKey}_${webhook.id}`;+ // Durable record BEFORE anything is attempted. A hard crash from here until the delivery+ // reaches a durable owner leaves this row 'pending', which is what the reconciler replays.+ await this.outbox.open({+ webhookId: webhook.id,+ sessionId,+ event,+ idempotencyKey,+ deliveryId,+ payload: ctx.baseData,+ });await this.dispatchLimiter.run(async () => {this.inFlightDeliveries.set(deliveryId, {@@ -583,6 +595,9 @@ export class WebhookDeliveryService implements OnModuleInit, OnModuleDestroy {});try {await this.deliverOne(webhook, deliveryId, idempotencyKey, ctx);+ // Reached a durable owner: handed to the queue, or completed inline. A failure inside+ // either owner dead-letters through the failure row, so this is never replayed.+ await this.outbox.close(webhook.id, idempotencyKey, 'dispatched');} finally {this.inFlightDeliveries.delete(deliveryId);}@@ -623,6 +638,24 @@ export class WebhookDeliveryService implements OnModuleInit, OnModuleDestroy {});}+ /**+ * Replay one recorded delivery, reusing its STORED idempotency key.+ *+ * Deriving a fresh key would defeat the point: the receiver dedups on that value, so a replay+ * carrying a new one reads as a second event rather than a retry of the first. A new deliveryId+ * IS issued, because that identifies the attempt rather than the event.+ */+ async redeliver(+ webhook: Webhook,+ sessionId: string,+ event: string,+ idempotencyKey: string,+ data: Record<string, unknown>,+ ): Promise<void> {+ const deliveryId = generateDeliveryId();+ await this.deliverOne(webhook, deliveryId, idempotencyKey, { sessionId, event, baseData: data });+ }+/*** @deprecated Use job queue dispatch instead. This is kept for fallback.* `body` is the pre-serialized payload from preflight — the exact bytes the size gate checked anddiff --git a/src/modules/webhook/webhook-outbox.service.spec.ts b/src/modules/webhook/webhook-outbox.service.spec.tsnew file mode 100644index 000000000..6fba5c060--- /dev/null+++ b/src/modules/webhook/webhook-outbox.service.spec.ts@@ -0,0 +1,82 @@+import { WebhookOutboxService } from './webhook-outbox.service';+import { WebhookOutboxEvent } from './entities/webhook-outbox-event.entity';++const base = {+ webhookId: 'wh-1',+ sessionId: 'sess-1',+ event: 'message.received',+ idempotencyKey: 'key_wh-1',+ deliveryId: 'del-1',+ payload: { from: '[email protected]' },+};++describe('WebhookOutboxService', () => {+ let repo: { save: jest.Mock; create: jest.Mock; update: jest.Mock; find: jest.Mock };+ let service: WebhookOutboxService;++ beforeEach(() => {+ repo = {+ create: jest.fn((v: unknown) => v),+ save: jest.fn().mockResolvedValue(undefined),+ update: jest.fn().mockResolvedValue(undefined),+ find: jest.fn().mockResolvedValue([]),+ };+ service = new WebhookOutboxService(repo as never);+ });++ it('records the delivery as pending, carrying the payload a replay needs', async () => {+ await service.open(base);++ expect(repo.save).toHaveBeenCalledWith(expect.objectContaining({ ...base, state: 'pending', attempts: 0 }));+ });++ it('treats a duplicate as the replay it is, keeping the existing row', async () => {+ const conflict = Object.assign(new Error('UNIQUE constraint failed'), { code: 'SQLITE_CONSTRAINT_UNIQUE' });+ repo.save.mockRejectedValue(conflict);++ // A conflict on (webhookId, idempotencyKey) means this delivery is already recorded. Throwing+ // would surface as an unhandled rejection on a fire-and-forget path.+ await expect(service.open(base)).resolves.toBeUndefined();+ });++ it('never lets a repository failure reach a fire-and-forget caller', async () => {+ repo.save.mockRejectedValue(new Error('disk full'));+ await expect(service.open(base)).resolves.toBeUndefined();++ repo.update.mockRejectedValue(new Error('disk full'));+ await expect(service.close('wh-1', 'key_wh-1', 'dispatched')).resolves.toBeUndefined();+ await expect(service.countAttempt('row-1', 0)).resolves.toBeUndefined();+ });++ it('retires the payload when recording an outcome, so a settled row stops carrying a message body', async () => {+ await service.close('wh-1', 'key_wh-1', 'dispatched');++ expect(repo.update).toHaveBeenCalledWith(+ { webhookId: 'wh-1', idempotencyKey: 'key_wh-1' },+ expect.objectContaining({ state: 'dispatched', payload: null }),+ );+ });++ it('returns only rows that still carry a payload: a retired row is not replayable', async () => {+ const row = (over: Partial<WebhookOutboxEvent>): WebhookOutboxEvent => ({+ id: 'r',+ ...base,+ attempts: 0,+ state: 'pending',+ lastAttemptAt: null,+ createdAt: new Date(),+ ...over,+ });+ repo.find.mockResolvedValue([row({ id: 'keep' }), row({ id: 'retired', payload: null })]);++ const stale = await service.findStale(new Date(), 50);++ expect(stale.map(r => r.id)).toEqual(['keep']);+ });++ it('counts an attempt by incrementing the stored number, not by recomputing it', async () => {+ await service.countAttempt('row-1', 2);++ expect(repo.update).toHaveBeenCalledWith({ id: 'row-1' }, expect.objectContaining({ attempts: 3 }));+ });+});diff --git a/src/modules/webhook/webhook-outbox.service.ts b/src/modules/webhook/webhook-outbox.service.tsnew file mode 100644index 000000000..51c1dffdf--- /dev/null+++ b/src/modules/webhook/webhook-outbox.service.ts@@ -0,0 +1,110 @@+import { Injectable } from '@nestjs/common';+import { InjectRepository } from '@nestjs/typeorm';+import { LessThan, Repository } from 'typeorm';+import { WebhookOutboxEvent, WebhookOutboxState } from './entities/webhook-outbox-event.entity';+import { createLogger } from '../../common/services/logger.service';+import { isUniqueViolation } from '../../common/utils/db-errors';++/** What a replay needs to redispatch one delivery without deriving a new idempotency key. */+export interface ReplayableDelivery {+ id: string;+ webhookId: string;+ sessionId: string;+ event: string;+ idempotencyKey: string;+ payload: Record<string, unknown>;+ attempts: number;+}++/**+ * Row lifecycle for the outbound delivery record.+ *+ * Every write here is best-effort and swallowed: fan-out is fire-and-forget from the projector, so+ * a repository failure must not turn into an unhandled rejection or stop a delivery that would+ * otherwise succeed. Losing the record degrades to the behaviour that existed before it.+ */+@Injectable()+export class WebhookOutboxService {+ private readonly logger = createLogger('WebhookOutboxService');++ constructor(+ @InjectRepository(WebhookOutboxEvent, 'data')+ private readonly outbox: Repository<WebhookOutboxEvent>,+ ) {}++ /**+ * Record the delivery as pending, before anything durable owns it.+ *+ * A conflict on (webhookId, idempotencyKey) means this exact delivery is being replayed, so the+ * existing row is kept rather than duplicated: the stored key is what makes the retry+ * deduplicable at the receiver.+ */+ async open(row: Omit<ReplayableDelivery, 'id' | 'attempts'> & { deliveryId: string }): Promise<void> {+ try {+ await this.outbox.save(+ this.outbox.create({+ webhookId: row.webhookId,+ sessionId: row.sessionId,+ event: row.event,+ idempotencyKey: row.idempotencyKey,+ deliveryId: row.deliveryId,+ payload: row.payload,+ state: 'pending',+ attempts: 0,+ }),+ );+ } catch (error) {+ // A conflict means this exact delivery is already recorded, which is what a replay looks+ // like: keep the existing row rather than duplicating it.+ if (isUniqueViolation(error)) return;+ this.logger.warn(`Could not record outbound delivery ${row.deliveryId}: ${String(error)}`);+ }+ }++ /**+ * Record the outcome and retire the payload.+ *+ * `dispatched` covers both modes: handed to the queue, or completed inline. A failure INSIDE+ * either owner dead-letters through webhook_delivery_failures, so a dispatched row is never the+ * reconciler's concern, and retiring on ENQUEUE is what stops the reconciler duplicating work+ * BullMQ already holds.+ */+ async close(webhookId: string, idempotencyKey: string, state: Exclude<WebhookOutboxState, 'pending'>): Promise<void> {+ try {+ await this.outbox.update({ webhookId, idempotencyKey }, { state, payload: null, lastAttemptAt: new Date() });+ } catch (error) {+ this.logger.warn(`Could not close outbound delivery record: ${String(error)}`);+ }+ }++ /** Pending rows older than the staleness window, oldest first. Only these are replayable. */+ async findStale(olderThan: Date, limit: number): Promise<ReplayableDelivery[]> {+ const rows = await this.outbox.find({+ where: { state: 'pending', createdAt: LessThan(olderThan) },+ order: { createdAt: 'ASC' },+ take: limit,+ });+ // A pending row always carries its payload; the guard is for a row whose payload was retired by+ // a concurrent close between the query and this read.+ return rows+ .filter((r): r is WebhookOutboxEvent & { payload: Record<string, unknown> } => r.payload !== null)+ .map(r => ({+ id: r.id,+ webhookId: r.webhookId,+ sessionId: r.sessionId,+ event: r.event,+ idempotencyKey: r.idempotencyKey,+ payload: r.payload,+ attempts: r.attempts,+ }));+ }++ /** Count one replay attempt against the row's budget. */+ async countAttempt(id: string, attempts: number): Promise<void> {+ try {+ await this.outbox.update({ id }, { attempts: attempts + 1, lastAttemptAt: new Date() });+ } catch (error) {+ this.logger.warn(`Could not count a replay attempt: ${String(error)}`);+ }+ }+}diff --git a/src/modules/webhook/webhook-reconciler.service.spec.ts b/src/modules/webhook/webhook-reconciler.service.spec.tsnew file mode 100644index 000000000..083db916c--- /dev/null+++ b/src/modules/webhook/webhook-reconciler.service.spec.ts@@ -0,0 +1,134 @@+import { WebhookReconcilerService, resolveWebhookReconcilerOptions } from './webhook-reconciler.service';+import { ReplayableDelivery } from './webhook-outbox.service';++const OPTS = { intervalMs: 60_000, graceMs: 60_000, batchSize: 50, maxAttempts: 3 };++const row = (over: Partial<ReplayableDelivery> = {}): ReplayableDelivery => ({+ id: 'row-1',+ webhookId: 'wh-1',+ sessionId: 'sess-1',+ event: 'message.received',+ idempotencyKey: 'stored-key_wh-1',+ payload: { from: '[email protected]' },+ attempts: 0,+ ...over,+});++describe('resolveWebhookReconcilerOptions', () => {+ it('defaults, and treats a non-positive interval as disabled', () => {+ expect(resolveWebhookReconcilerOptions({})).toEqual({+ intervalMs: 60_000,+ graceMs: 60_000,+ batchSize: 50,+ maxAttempts: 5,+ });+ expect(resolveWebhookReconcilerOptions({ WEBHOOK_RECONCILE_INTERVAL_MS: '0' }).intervalMs).toBe(0);+ });++ it('rejects a batch size or attempt budget that is not a positive integer', () => {+ const opts = resolveWebhookReconcilerOptions({+ WEBHOOK_RECONCILE_BATCH_SIZE: '0',+ WEBHOOK_RECONCILE_MAX_ATTEMPTS: 'abc',+ });+ expect(opts.batchSize).toBe(50);+ expect(opts.maxAttempts).toBe(5);+ });+});++describe('WebhookReconcilerService', () => {+ let outbox: { findStale: jest.Mock; close: jest.Mock; countAttempt: jest.Mock };+ let delivery: { redeliver: jest.Mock };+ let webhooks: { findOne: jest.Mock };+ let service: WebhookReconcilerService;++ beforeEach(() => {+ outbox = { findStale: jest.fn().mockResolvedValue([]), close: jest.fn(), countAttempt: jest.fn() };+ delivery = { redeliver: jest.fn().mockResolvedValue(undefined) };+ webhooks = { findOne: jest.fn().mockResolvedValue({ id: 'wh-1', active: true }) };+ service = new WebhookReconcilerService(webhooks as never, outbox as never, delivery as never);+ });++ it('replays a stranded delivery with the STORED idempotency key', async () => {+ outbox.findStale.mockResolvedValue([row()]);++ const stats = await service.sweep(OPTS);++ // Deriving a fresh key would make the replay read as a second event at the receiver rather than+ // a retry of the first, which is the whole reason the key is stored rather than recomputed.+ expect(delivery.redeliver).toHaveBeenCalledWith(+ { id: 'wh-1', active: true },+ 'sess-1',+ 'message.received',+ 'stored-key_wh-1',+ { from: '[email protected]' },+ );+ expect(outbox.close).toHaveBeenCalledWith('wh-1', 'stored-key_wh-1', 'dispatched');+ expect(stats).toMatchObject({ scanned: 1, replayed: 1 });+ });++ it('counts the attempt BEFORE replaying, so a delivery that always throws still exhausts its budget', async () => {+ outbox.findStale.mockResolvedValue([row({ attempts: 1 })]);+ delivery.redeliver.mockRejectedValue(new Error('receiver down'));++ const stats = await service.sweep(OPTS);++ expect(outbox.countAttempt).toHaveBeenCalledWith('row-1', 1);+ expect(outbox.countAttempt.mock.invocationCallOrder[0]).toBeLessThan(+ delivery.redeliver.mock.invocationCallOrder[0],+ );+ // Left pending on purpose: the next sweep picks it up again until the budget runs out.+ expect(outbox.close).not.toHaveBeenCalled();+ expect(stats).toMatchObject({ replayed: 0, failed: 1 });+ });++ it('stops replaying once the budget is spent instead of looping forever', async () => {+ outbox.findStale.mockResolvedValue([row({ attempts: 3 })]);++ const stats = await service.sweep(OPTS);++ expect(delivery.redeliver).not.toHaveBeenCalled();+ expect(outbox.close).toHaveBeenCalledWith('wh-1', 'stored-key_wh-1', 'failed');+ expect(stats).toMatchObject({ failed: 1, replayed: 0 });+ });++ it('does not replay to a subscription that is gone or switched off', async () => {+ outbox.findStale.mockResolvedValue([row()]);+ webhooks.findOne.mockResolvedValue({ id: 'wh-1', active: false });++ const stats = await service.sweep(OPTS);++ // Replaying here would deliver an event the operator has already unsubscribed from.+ expect(delivery.redeliver).not.toHaveBeenCalled();+ expect(outbox.close).toHaveBeenCalledWith('wh-1', 'stored-key_wh-1', 'failed');+ expect(stats).toMatchObject({ skipped: 1 });+ });++ it('never stacks a second pass on top of a slow one', async () => {+ let release: () => void = () => {};+ outbox.findStale.mockImplementation(+ () => new Promise<ReplayableDelivery[]>(resolve => (release = () => resolve([]))),+ );++ const first = service.sweep(OPTS);+ const second = await service.sweep(OPTS);+ release();+ await first;++ expect(second).toEqual({ scanned: 0, replayed: 0, failed: 0, skipped: 0 });+ expect(outbox.findStale).toHaveBeenCalledTimes(1);+ });++ it('does not start a timer when the interval disables it', () => {+ const prev = process.env.WEBHOOK_RECONCILE_INTERVAL_MS;+ process.env.WEBHOOK_RECONCILE_INTERVAL_MS = '0';+ const spy = jest.spyOn(global, 'setInterval');+ try {+ service.onModuleInit();+ expect(spy).not.toHaveBeenCalled();+ } finally {+ spy.mockRestore();+ if (prev === undefined) delete process.env.WEBHOOK_RECONCILE_INTERVAL_MS;+ else process.env.WEBHOOK_RECONCILE_INTERVAL_MS = prev;+ }+ });+});diff --git a/src/modules/webhook/webhook-reconciler.service.ts b/src/modules/webhook/webhook-reconciler.service.tsnew file mode 100644index 000000000..a0104e8e1--- /dev/null+++ b/src/modules/webhook/webhook-reconciler.service.ts@@ -0,0 +1,121 @@+import { Injectable, OnModuleDestroy, OnModuleInit } from '@nestjs/common';+import { InjectRepository } from '@nestjs/typeorm';+import { Repository } from 'typeorm';+import { Webhook } from './entities/webhook.entity';+import { WebhookOutboxService } from './webhook-outbox.service';+import { WebhookDeliveryService } from './webhook-delivery.service';+import { createLogger } from '../../common/services/logger.service';+import { resolveNonNegativeIntEnv } from '../../config/configuration';++export interface WebhookReconcilerOptions {+ /** 0 disables the sweep entirely. */+ intervalMs: number;+ /** How long a row may sit 'pending' before it counts as stranded rather than in flight. */+ graceMs: number;+ batchSize: number;+ /**+ * Replay budget per row. Past it the row is marked 'failed' and left alone: a stuck delivery must+ * not become an infinite replay loop, and the failure row is where recovery continues.+ */+ maxAttempts: number;+}++export function resolveWebhookReconcilerOptions(env: NodeJS.ProcessEnv = process.env): WebhookReconcilerOptions {+ const batch = Number(env.WEBHOOK_RECONCILE_BATCH_SIZE);+ const maxAttempts = Number(env.WEBHOOK_RECONCILE_MAX_ATTEMPTS);+ return {+ intervalMs: resolveNonNegativeIntEnv(env.WEBHOOK_RECONCILE_INTERVAL_MS, 60_000),+ graceMs: resolveNonNegativeIntEnv(env.WEBHOOK_RECONCILE_GRACE_MS, 60_000),+ batchSize: Number.isInteger(batch) && batch >= 1 ? batch : 50,+ maxAttempts: Number.isInteger(maxAttempts) && maxAttempts >= 1 ? maxAttempts : 5,+ };+}++export interface WebhookReconcileStats {+ scanned: number;+ replayed: number;+ failed: number;+ skipped: number;+}++/**+ * Closes the crash window on outbound webhook delivery.+ *+ * Fan-out is fire-and-forget from the projector, so before the outbox row existed a hard crash+ * between persisting a message and completing its POST lost the delivery with nothing left behind+ * in either mode, while the documented contract promises at-least-once. The row makes the intent+ * durable; this sweep is what turns durability into delivery.+ *+ * Mirrors IngressReconcilerService on the inbound side: an unref'd interval started on module init,+ * an overlap guard so a slow pass never stacks, a bounded batch, and a per-row replay budget.+ */+@Injectable()+export class WebhookReconcilerService implements OnModuleInit, OnModuleDestroy {+ private readonly logger = createLogger('WebhookReconcilerService');+ private timer?: ReturnType<typeof setInterval>;+ private sweeping = false;++ constructor(+ @InjectRepository(Webhook, 'data') private readonly webhooks: Repository<Webhook>,+ private readonly outbox: WebhookOutboxService,+ private readonly delivery: WebhookDeliveryService,+ ) {}++ onModuleInit(): void {+ const opts = resolveWebhookReconcilerOptions();+ if (opts.intervalMs <= 0) {+ this.logger.log('Webhook delivery reconciler disabled (WEBHOOK_RECONCILE_INTERVAL_MS <= 0)');+ return;+ }+ this.timer = setInterval(() => {+ this.sweep(opts).catch(err =>+ this.logger.error('Webhook reconcile sweep failed', err instanceof Error ? err.stack : String(err)),+ );+ }, opts.intervalMs);+ this.timer.unref?.();+ }++ onModuleDestroy(): void {+ if (this.timer) clearInterval(this.timer);+ }++ /** One bounded pass over the stranded backlog. Overlap-guarded. */+ async sweep(opts: WebhookReconcilerOptions, now: Date = new Date()): Promise<WebhookReconcileStats> {+ const stats: WebhookReconcileStats = { scanned: 0, replayed: 0, failed: 0, skipped: 0 };+ if (this.sweeping) return stats;+ this.sweeping = true;+ try {+ const rows = await this.outbox.findStale(new Date(now.getTime() - opts.graceMs), opts.batchSize);+ stats.scanned = rows.length;+ for (const row of rows) {+ if (row.attempts >= opts.maxAttempts) {+ // Budget spent: stop replaying and leave the failure row as the recovery path.+ await this.outbox.close(row.webhookId, row.idempotencyKey, 'failed');+ stats.failed++;+ continue;+ }+ const webhook = await this.webhooks.findOne({ where: { id: row.webhookId } });+ if (!webhook || !webhook.active) {+ // The subscription is gone or switched off; replaying it would deliver an event the+ // operator has already unsubscribed from.+ await this.outbox.close(row.webhookId, row.idempotencyKey, 'failed');+ stats.skipped++;+ continue;+ }+ await this.outbox.countAttempt(row.id, row.attempts);+ try {+ await this.delivery.redeliver(webhook, row.sessionId, row.event, row.idempotencyKey, row.payload);+ await this.outbox.close(row.webhookId, row.idempotencyKey, 'dispatched');+ stats.replayed++;+ } catch (error) {+ // Left 'pending' on purpose: the next sweep retries it until the budget is spent.+ this.logger.warn(`Replay of ${row.event} to webhook ${row.webhookId} failed: ${String(error)}`);+ stats.failed++;+ }+ }+ } finally {+ this.sweeping = false;+ }+ return stats;+ }+}diff --git a/src/modules/webhook/webhook.module.ts b/src/modules/webhook/webhook.module.tsindex a0c0e3899..0e86cdf47 100644--- a/src/modules/webhook/webhook.module.ts+++ b/src/modules/webhook/webhook.module.ts@@ -2,6 +2,9 @@ import { Module, DynamicModule, Type } from '@nestjs/common';import { TypeOrmModule } from '@nestjs/typeorm';import { Webhook } from './entities/webhook.entity';import { WebhookDeliveryFailure } from './entities/webhook-delivery-failure.entity';+import { WebhookOutboxEvent } from './entities/webhook-outbox-event.entity';+import { WebhookOutboxService } from './webhook-outbox.service';+import { WebhookReconcilerService } from './webhook-reconciler.service';import { Session } from '../session/entities/session.entity';import { WebhookService } from './webhook.service';import { WebhookDeliveryService } from './webhook-delivery.service';@@ -21,12 +24,12 @@ if (process.env.QUEUE_ENABLED === 'true') {@Module({imports: [- TypeOrmModule.forFeature([Webhook, WebhookDeliveryFailure, Session], 'data'),+ TypeOrmModule.forFeature([Webhook, WebhookDeliveryFailure, WebhookOutboxEvent, Session], 'data'),EngineModule,...queueModules,],controllers: [WebhookController, WebhooksListController],- providers: [WebhookService, WebhookDeliveryService],+ providers: [WebhookService, WebhookDeliveryService, WebhookOutboxService, WebhookReconcilerService],exports: [WebhookService],})export class WebhookModule {}diff --git a/src/modules/webhook/webhook.service.spec.ts b/src/modules/webhook/webhook.service.spec.tsindex 5efafe61d..d0034f5ef 100644--- a/src/modules/webhook/webhook.service.spec.ts+++ b/src/modules/webhook/webhook.service.spec.ts@@ -18,6 +18,7 @@ import { NotFoundException } from '@nestjs/common';import { ConfigService } from '@nestjs/config';import { fetch as undiciFetch } from 'undici';import { WebhookService } from './webhook.service';+import { WebhookOutboxService } from './webhook-outbox.service';import { WebhookDeliveryService } from './webhook-delivery.service';import { Webhook } from './entities/webhook.entity';import { WebhookDeliveryFailure } from './entities/webhook-delivery-failure.entity';@@ -114,6 +115,10 @@ describe('WebhookService', () => {WebhookDeliveryService,{ provide: getRepositoryToken(Webhook, 'data'), useValue: repository },{ provide: getRepositoryToken(WebhookDeliveryFailure, 'data'), useValue: failureRepository },+ {+ provide: WebhookOutboxService,+ useValue: { open: jest.fn().mockResolvedValue(undefined), close: jest.fn().mockResolvedValue(undefined) },+ },{ provide: getRepositoryToken(Session, 'data'), useValue: sessionRepository },{ provide: ConfigService, useValue: configService },{ provide: HookManager, useValue: hookManager },