Free, Open Source, Self-Hosted WhatsApp API Gateway
TypeScript apibotgatewayself-hostedwhatsappwhatsapp-apiwhatsapp-automationwhatsapp-botwhatsapp-gatewaywhatsapp-gateway-apiwhatsapp-webwhatsapp-web-api
fix(integration): reconcile persisted ingress events that never reached dispatch (#924)
Yudhi Armyndharis86f7fb09f24f
diff --git a/docs/25-integration-fabric.md b/docs/25-integration-fabric.mdindex 7a12f6613..e00daba13 100644--- a/docs/25-integration-fabric.md+++ b/docs/25-integration-fabric.md@@ -130,7 +130,11 @@ Four tables live on the data connection, each created by a hand-authored dual-dia human-handled conversation deterministically stops the bot. `sessionId` is non-foreign-key provenancebecause a mapping outlives a session.- **`ingress_events`** — the persist-before-acknowledge row and the inbound deduplication oracle- (`UNIQUE(instanceId, providerDeliveryId)`, insert-or-skip).+ (`UNIQUE(instanceId, providerDeliveryId)`, insert-or-skip). It also carries the dispatch-lifecycle+ markers the reconciler sweeps on: `dispatchState` (`pending | dispatched | failed`, `NULL` on rows+ that predate the columns on a synchronize-bootstrapped DB — "not watched"), `dispatchAttempts`, and+ `lastDispatchAt`. New rows are `pending`; a recorded enqueue outcome flips them to `dispatched`;+ `failed` is terminal (recovery continues via the DLQ row + redrive).- **`integration_delivery_failures`** — a dead-letter record of last resort for both directions, with aredrive path (added in P1).@@ -172,6 +176,20 @@ PostgreSQL state. When the queue is disabled, ingress dispatches inline after peserialize concurrent same-conversation deliveries. Providers already deliver over unordered,at-least-once HTTP, so plugin handlers must be idempotent and treat ingress as a reconciliation trigger.+Persist-before-acknowledge alone is not delivery: a crash between the persist and the enqueue, or a+fire-and-forget enqueue on a `response` route whose outcome is never recorded, would strand the row+with the provider already acknowledged. The **ingress reconciler** closes that window: every+`INGRESS_RECONCILE_INTERVAL_MS` (default 60s, `<= 0` disables) it re-dispatches a bounded batch+(`INGRESS_RECONCILE_BATCH_SIZE`, default 50) of `pending` rows whose last activity is older than a+grace period (`INGRESS_RECONCILE_GRACE_MS`, default 60s), through the same queue-or-inline enqueue the+live path uses and with the original delivery id as job id, so a replay is idempotent against a job+the crashed live path may have enqueued. The stored row is sufficient for re-dispatch — it is the full+verified request (headers/query/body/rawBody) plus the route and session provenance; the conversation+lane is re-derived from the current manifest. After `INGRESS_RECONCILE_MAX_ATTEMPTS` (default 5) the+row goes `failed` (terminal) and a dead-letter row is guaranteed to exist, so recovery continues+through the bounded redrive path instead of an infinite replay loop; a successful replay retires any+live-path dead-letter row for the same delivery so a later redrive never double-delivers.+## 25.8 The Integration SDK (v1)The stable surface untrusted adapters consume. A plugin declares `sdkVersion: "1"` and an `ingress`diff --git a/src/database/migrations/1785112230000-AddIngressEventDispatchState.ts b/src/database/migrations/1785112230000-AddIngressEventDispatchState.tsnew file mode 100644index 000000000..3dd36f0a5--- /dev/null+++ b/src/database/migrations/1785112230000-AddIngressEventDispatchState.ts@@ -0,0 +1,72 @@+import { MigrationInterface, QueryRunner } from 'typeorm';++/**+ * Adds the dispatch-lifecycle columns the ingress reconciler sweeps on:+ * `dispatchState` ('pending' | 'dispatched' | 'failed'), `dispatchAttempts`, `lastDispatchAt`,+ * plus the (dispatchState, createdAt) sweep index.+ *+ * Backfill: `dispatchState` is added NULL-able with NO default and every EXISTING row is stamped+ * 'dispatched' in the same statement batch — history was delivered by definition (or is old enough+ * that replaying it now would be worse than losing nothing), so only rows persisted AFTER this+ * migration are watched. Deliberately NOT `DEFAULT 'pending'` + no backfill guard on new rows:+ * a default would also stamp pre-upgrade rows on a synchronize-bootstrapped DB (where this+ * migration never runs), and the reconciler would mass-replay the entire dedup log on deploy.+ * recordOrSkip writes 'pending' explicitly, so new rows need no default.+ *+ * Dual-dialect (SQLite + PostgreSQL), idempotent via an information_schema/PRAGMA column probe+ * (mirrors AddMessageAuthor). Hand-authored because `synchronize` is off for the `data` connection+ * on PostgreSQL (and optional on SQLite via DATABASE_SYNCHRONIZE=false).+ */+export class AddIngressEventDispatchState1785112230000 implements MigrationInterface {+ name = 'AddIngressEventDispatchState1785112230000';++ private async hasColumn(queryRunner: QueryRunner, name: string): Promise<boolean> {+ if (queryRunner.connection.options.type === 'postgres') {+ const rows = (await queryRunner.query(+ `SELECT 1 FROM information_schema.columns+ WHERE table_schema = current_schema() AND table_name = 'ingress_events' AND column_name = '${name}'`,+ )) as unknown[];+ return rows.length > 0;+ }+ const rows = (await queryRunner.query(`PRAGMA table_info("ingress_events")`)) as Array<{ name: string }>;+ return rows.some(r => r.name === name);+ }++ public async up(queryRunner: QueryRunner): Promise<void> {+ const isPostgres = queryRunner.connection.options.type === 'postgres';+ const ts = isPostgres ? 'timestamp' : 'datetime';++ if (!(await this.hasColumn(queryRunner, 'dispatchState'))) {+ await queryRunner.query(`ALTER TABLE "ingress_events" ADD COLUMN "dispatchState" varchar NULL`);+ // Backfill ONLY runs when this migration adds the column: every row that existed before the+ // upgrade is indistinguishable from a never-dispatched one (all read NULL), so stamp them all+ // 'dispatched'. Rows inserted after the migration are 'pending' (recordOrSkip) and must never+ // be re-stamped — the column-exists guard above makes a re-run skip this UPDATE entirely.+ await queryRunner.query(+ `UPDATE "ingress_events" SET "dispatchState" = 'dispatched' WHERE "dispatchState" IS NULL`,+ );+ }+ if (!(await this.hasColumn(queryRunner, 'dispatchAttempts'))) {+ await queryRunner.query(`ALTER TABLE "ingress_events" ADD COLUMN "dispatchAttempts" integer NOT NULL DEFAULT 0`);+ }+ if (!(await this.hasColumn(queryRunner, 'lastDispatchAt'))) {+ await queryRunner.query(`ALTER TABLE "ingress_events" ADD COLUMN "lastDispatchAt" ${ts} NULL`);+ }+ await queryRunner.query(+ `CREATE INDEX IF NOT EXISTS "IDX_ingress_events_dispatchState" ON "ingress_events" ("dispatchState", "createdAt")`,+ );+ }++ public async down(queryRunner: QueryRunner): Promise<void> {+ await queryRunner.query(`DROP INDEX IF EXISTS "IDX_ingress_events_dispatchState"`);+ if (await this.hasColumn(queryRunner, 'lastDispatchAt')) {+ await queryRunner.query(`ALTER TABLE "ingress_events" DROP COLUMN "lastDispatchAt"`);+ }+ if (await this.hasColumn(queryRunner, 'dispatchAttempts')) {+ await queryRunner.query(`ALTER TABLE "ingress_events" DROP COLUMN "dispatchAttempts"`);+ }+ if (await this.hasColumn(queryRunner, 'dispatchState')) {+ await queryRunner.query(`ALTER TABLE "ingress_events" DROP COLUMN "dispatchState"`);+ }+ }+}diff --git a/src/database/migrations/__tests__/1785112230000-AddIngressEventDispatchState.spec.ts b/src/database/migrations/__tests__/1785112230000-AddIngressEventDispatchState.spec.tsnew file mode 100644index 000000000..0a87d2aa4--- /dev/null+++ b/src/database/migrations/__tests__/1785112230000-AddIngressEventDispatchState.spec.ts@@ -0,0 +1,97 @@+import { DataSource, QueryRunner } from 'typeorm';+import { AddIntegrationFabric1781900000000 } from '../1781900000000-AddIntegrationFabric';+import { AddIngressEventDispatchState1785112230000 } from '../1785112230000-AddIngressEventDispatchState';++describe('AddIngressEventDispatchState migration (sqlite)', () => {+ let ds: DataSource;+ let runner: QueryRunner;++ beforeEach(async () => {+ ds = new DataSource({ type: 'better-sqlite3', database: ':memory:', entities: [], migrations: [] });+ await ds.initialize();+ runner = ds.createQueryRunner();+ await new AddIntegrationFabric1781900000000().up(runner);+ });++ afterEach(async () => {+ await runner.release();+ if (ds.isInitialized) await ds.destroy();+ });++ const columns = async (): Promise<string[]> => {+ const rows = (await runner.query(`PRAGMA table_info("ingress_events")`)) as Array<{ name: string }>;+ return rows.map(r => r.name);+ };++ const insertEvent = (id: string, dispatchState?: string) =>+ runner.query(+ `INSERT INTO "ingress_events" ("id","instanceId","pluginId","providerDeliveryId","route","payload","createdAt"${dispatchState === undefined ? '' : ',"dispatchState"'}) ` ++ `VALUES ('${id}','inst','plug','${id}','chatwoot','{}',datetime('now')${dispatchState === undefined ? '' : `,'${dispatchState}'`})`,+ );++ it('adds the three columns + sweep index and backfills EXISTING rows as dispatched', async () => {+ await insertEvent('legacy-1');+ await insertEvent('legacy-2');++ await new AddIngressEventDispatchState1785112230000().up(runner);++ for (const col of ['dispatchState', 'dispatchAttempts', 'lastDispatchAt']) {+ expect(await columns()).toContain(col);+ }+ const rows = (await runner.query(+ `SELECT "id","dispatchState","dispatchAttempts","lastDispatchAt" FROM "ingress_events" ORDER BY "id"`,+ )) as Array<{ id: string; dispatchState: string; dispatchAttempts: number; lastDispatchAt: unknown }>;+ // Pre-migration rows are history — already delivered; stamping them 'pending' would mass-replay+ // the whole dedup log on deploy.+ expect(rows.map(r => r.dispatchState)).toEqual(['dispatched', 'dispatched']);+ expect(rows.map(r => r.dispatchAttempts)).toEqual([0, 0]);+ expect(rows.map(r => r.lastDispatchAt)).toEqual([null, null]);++ const indexes = (await runner.query(+ `SELECT name FROM sqlite_master WHERE type='index' AND name='IDX_ingress_events_dispatchState'`,+ )) as Array<{ name: string }>;+ expect(indexes).toHaveLength(1);+ });++ it('is idempotent and never re-stamps a live pending row on re-run', async () => {+ const mig = new AddIngressEventDispatchState1785112230000();+ await mig.up(runner);+ await insertEvent('live-1', 'pending');++ await mig.up(runner); // column-exists guard → no-op; the backfill UPDATE must NOT fire again++ const row = (await runner.query(`SELECT "dispatchState" FROM "ingress_events" WHERE "id" = 'live-1'`)) as Array<{+ dispatchState: string;+ }>;+ expect(row[0].dispatchState).toBe('pending');+ });++ it('leaves a raw insert without the column NULL (unwatched) — the synchronize-path safety shape', async () => {+ await new AddIngressEventDispatchState1785112230000().up(runner);+ await insertEvent('raw-1');++ const row = (await runner.query(`SELECT "dispatchState" FROM "ingress_events" WHERE "id" = 'raw-1'`)) as Array<{+ dispatchState: string | null;+ }>;+ // recordOrSkip writes 'pending' explicitly; anything else stays NULL = "not watched", so a+ // synchronize-bootstrapped DB (no backfill) can never mass-replay history either.+ expect(row[0].dispatchState).toBeNull();+ });++ it('down() drops the columns and the index', async () => {+ const mig = new AddIngressEventDispatchState1785112230000();+ await mig.up(runner);+ await mig.down(runner);++ for (const col of ['dispatchState', 'dispatchAttempts', 'lastDispatchAt']) {+ expect(await columns()).not.toContain(col);+ }+ const indexes = (await runner.query(+ `SELECT name FROM sqlite_master WHERE type='index' AND name='IDX_ingress_events_dispatchState'`,+ )) as Array<{ name: string }>;+ expect(indexes).toHaveLength(0);++ // Tolerates a synchronize-bootstrapped DB where the columns/index never existed.+ await expect(mig.down(runner)).resolves.toBeUndefined();+ });+});diff --git a/src/modules/integration/entities/ingress-event.entity.ts b/src/modules/integration/entities/ingress-event.entity.tsindex 02d28ea44..d82b58d91 100644--- a/src/modules/integration/entities/ingress-event.entity.ts+++ b/src/modules/integration/entities/ingress-event.entity.ts@@ -1,5 +1,19 @@import { Column, CreateDateColumn, Entity, Index, PrimaryColumn } from 'typeorm';-import { jsonColumnType } from '../../../common/utils/column-types';+import { dateColumnType, jsonColumnType } from '../../../common/utils/column-types';+import { DateTransformer } from '../../../common/transformers/date.transformer';++// The enqueue-outcome lifecycle of a persisted event, recorded AFTER the fast ack (persist-before-ack+// means the row always exists before dispatch is attempted):+// - 'pending' — written by recordOrSkip; dispatch not (yet) confirmed. The reconciler sweeps these.+// - 'dispatched' — the event reached the dispatch tier (handed to BullMQ or delivered inline). A+// failure INSIDE the tier (BullMQ attempts exhausted) dead-letters separately, so a+// 'dispatched' row is never the reconciler's concern.+// - 'failed' — terminal: the reconciler exhausted its replay budget; recovery continues via the+// integration_delivery_failures row + RedriveService.+// NULL marks rows that predate these columns on synchronize-bootstrapped DBs (no backfill ran there);+// NULL reads as "not watched" — the reconciler never sweeps it, so an upgrade can never mass-replay+// the historical dedup log.+export type IngressDispatchState = 'pending' | 'dispatched' | 'failed';// Persist-before-ack durable row + inbound dedup oracle. UNIQUE(pluginId, instanceId, providerDeliveryId):// instanceId is only unique within a plugin, so pluginId must be part of the key or two plugins sharing an@@ -7,6 +21,7 @@ import { jsonColumnType } from '../../../common/utils/column-types';@Entity('ingress_events')@Index('UQ_ingress_events_instance_delivery', ['pluginId', 'instanceId', 'providerDeliveryId'], { unique: true })@Index('IDX_ingress_events_createdAt', ['createdAt'])+@Index('IDX_ingress_events_dispatchState', ['dispatchState', 'createdAt'])export class IngressEvent {// Host-minted uuid (crypto.randomUUID()), NOT DB-generated — the id and the jobId (= deliveryId)// are decoupled on purpose. @PrimaryColumn, not @PrimaryGeneratedColumn.@@ -31,6 +46,21 @@ export class IngressEvent {@Column({ type: 'varchar', nullable: true })sessionId: string | null;+ // Nullable by design (see the IngressDispatchState comment above): NO DB default, because the+ // default 'pending' would also stamp pre-upgrade rows on the synchronize path and the reconciler+ // would replay the whole dedup log on deploy. New rows are 'pending' via recordOrSkip explicitly;+ // migration-managed DBs backfill existing rows to 'dispatched' instead.+ @Column({ type: 'varchar', nullable: true })+ dispatchState: IngressDispatchState | null;++ // Dispatch-attempt counter the reconciler caps its replay budget against; the live path bumps it+ // on a swallowed inline-dispatch failure so those retries count too.+ @Column({ type: 'int', default: 0 })+ dispatchAttempts: number;++ @Column({ type: dateColumnType(), nullable: true, transformer: DateTransformer })+ lastDispatchAt: Date | null;+@CreateDateColumn()createdAt: Date;}diff --git a/src/modules/integration/ingress-event.service.spec.ts b/src/modules/integration/ingress-event.service.spec.tsindex 086036e44..c5308c2b0 100644--- a/src/modules/integration/ingress-event.service.spec.ts+++ b/src/modules/integration/ingress-event.service.spec.ts@@ -3,6 +3,7 @@ import { IngressEvent } from './entities/ingress-event.entity';import { IngressEventService } from './ingress-event.service';import { AddIntegrationFabric1781900000000 } from '../../database/migrations/1781900000000-AddIntegrationFabric';import { WidenIngressDedupKey1782100000000 } from '../../database/migrations/1782100000000-WidenIngressDedupKey';+import { AddIngressEventDispatchState1785112230000 } from '../../database/migrations/1785112230000-AddIngressEventDispatchState';describe('IngressEventService.recordOrSkip', () => {let ds: DataSource;@@ -13,6 +14,7 @@ describe('IngressEventService.recordOrSkip', () => {const runner = ds.createQueryRunner();await new AddIntegrationFabric1781900000000().up(runner);await new WidenIngressDedupKey1782100000000().up(runner);+ await new AddIngressEventDispatchState1785112230000().up(runner);await runner.release();service = new IngressEventService(ds.getRepository(IngressEvent));});@@ -28,6 +30,8 @@ describe('IngressEventService.recordOrSkip', () => {payload: { headers: {}, query: {}, body: '{}', rawBody: '{}' },sessionId: null,});+ const key = { pluginId: 'plug', instanceId: 'inst', providerDeliveryId: 'd1' };+ const stored = () => ds.getRepository(IngressEvent).findOneByOrFail(key);it('returns true for a first delivery and false for a replay of the same delivery id', async () => {expect(await service.recordOrSkip(row())).toBe(true);@@ -44,4 +48,38 @@ describe('IngressEventService.recordOrSkip', () => {expect(await service.recordOrSkip(row())).toBe(true);expect(await service.recordOrSkip({ ...row(), pluginId: 'other-plug' })).toBe(true);});++ it('writes new events as dispatchState pending with zero attempts (watched by the reconciler)', async () => {+ await service.recordOrSkip(row());+ const event = await stored();+ expect(event.dispatchState).toBe('pending');+ expect(event.dispatchAttempts).toBe(0);+ expect(event.lastDispatchAt).toBeNull();+ });++ it.each(['queued', 'dispatched'] as const)(+ 'marks outcome %s as dispatched with a dispatch timestamp',+ async outcome => {+ await service.recordOrSkip(row());+ await service.markDispatchOutcome(key, outcome);+ const event = await stored();+ expect(event.dispatchState).toBe('dispatched');+ expect(event.lastDispatchAt).toBeInstanceOf(Date);+ expect(event.dispatchAttempts).toBe(0);+ },+ );++ it('marks outcome failed as still-pending with the attempt counted (reconciler sweeps it)', async () => {+ await service.recordOrSkip(row());+ await service.markDispatchOutcome(key, 'failed');+ const event = await stored();+ expect(event.dispatchState).toBe('pending');+ expect(event.dispatchAttempts).toBe(1);+ expect(event.lastDispatchAt).toBeInstanceOf(Date);++ // Repeated failures accumulate against the reconciler's replay budget.+ await service.markDispatchOutcome(key, 'failed');+ expect((await stored()).dispatchAttempts).toBe(2);+ expect((await stored()).dispatchState).toBe('pending');+ });});diff --git a/src/modules/integration/ingress-event.service.ts b/src/modules/integration/ingress-event.service.tsindex 73fc64074..92c4fab55 100644--- a/src/modules/integration/ingress-event.service.ts+++ b/src/modules/integration/ingress-event.service.ts@@ -4,6 +4,7 @@ import { InjectRepository } from '@nestjs/typeorm';import { Repository } from 'typeorm';import { IngressEvent } from './entities/ingress-event.entity';import { isUniqueViolation } from '../../common/utils/db-errors';+import type { EnqueueOutcome } from './ingress-enqueue.service';export interface IngressEventInput {instanceId: string;@@ -14,18 +15,43 @@ export interface IngressEventInput {sessionId: string | null;}+// The dedup identity of a persisted event — the same key recordOrSkip's UNIQUE constraint enforces.+export interface IngressEventKey {+ pluginId: string;+ instanceId: string;+ providerDeliveryId: string;+}+@Injectable()export class IngressEventService {constructor(@InjectRepository(IngressEvent, 'data') private readonly repo: Repository<IngressEvent>) {}// Persist-before-ack + dedup. true = newly recorded (enqueue it); false = duplicate (drop, already handled).+ // New rows are stamped 'pending' EXPLICITLY (no DB default on dispatchState) so rows that predate the+ // dispatch columns on a synchronize-bootstrapped DB stay NULL = "not watched" and an upgrade can never+ // mass-replay the historical dedup log.async recordOrSkip(input: IngressEventInput): Promise<boolean> {try {- await this.repo.insert({ id: randomUUID(), ...input });+ await this.repo.insert({ id: randomUUID(), ...input, dispatchState: 'pending' });return true;} catch (err) {if (isUniqueViolation(err)) return false;throw err;}}++ /**+ * Record the enqueue outcome on the persisted event. 'queued'/'dispatched' mean the event reached+ * the dispatch tier → 'dispatched' (a later in-tier failure dead-letters via the processor/DLQ, not+ * this row). 'failed' (the swallowed inline-dispatch failure) bumps the attempt counter and leaves+ * the row 'pending' so the reconciler sweeps it — the live path's own retry signal.+ */+ async markDispatchOutcome(key: IngressEventKey, outcome: EnqueueOutcome['outcome']): Promise<void> {+ if (outcome === 'failed') {+ await this.repo.increment(key, 'dispatchAttempts', 1);+ await this.repo.update(key, { lastDispatchAt: new Date() });+ return;+ }+ await this.repo.update(key, { dispatchState: 'dispatched', lastDispatchAt: new Date() });+ }}diff --git a/src/modules/integration/ingress-reconciler.service.spec.ts b/src/modules/integration/ingress-reconciler.service.spec.tsnew file mode 100644index 000000000..ddc36cc78--- /dev/null+++ b/src/modules/integration/ingress-reconciler.service.spec.ts@@ -0,0 +1,299 @@+import { DataSource, Repository } from 'typeorm';+import { IngressEvent } from './entities/ingress-event.entity';+import { IntegrationDeliveryFailure } from './entities/integration-delivery-failure.entity';+import { IngressReconcilerService, IngressReconcilerOptions } from './ingress-reconciler.service';+import { IngressEnqueueService } from './ingress-enqueue.service';+import { PluginLoaderService } from '../../core/plugins/plugin-loader.service';+import { IngressJobData } from '../queue/processors/ingress.processor';++const OPTS: IngressReconcilerOptions = { intervalMs: 60_000, graceMs: 60_000, batchSize: 50, maxAttempts: 5 };++const minutesAgo = (m: number): Date => new Date(Date.now() - m * 60_000);+const secondsAgo = (s: number): Date => new Date(Date.now() - s * 1000);++describe('IngressReconcilerService.sweep', () => {+ let ds: DataSource;+ let events: Repository<IngressEvent>;+ let failures: Repository<IntegrationDeliveryFailure>;+ let enqueue: jest.Mock;+ let getPlugin: jest.Mock;+ let service: IngressReconcilerService;+ let seq: number;++ beforeEach(async () => {+ seq = 0;+ ds = new DataSource({+ type: 'better-sqlite3',+ database: ':memory:',+ entities: [IngressEvent, IntegrationDeliveryFailure],+ synchronize: true,+ });+ await ds.initialize();+ events = ds.getRepository(IngressEvent);+ failures = ds.getRepository(IntegrationDeliveryFailure);+ enqueue = jest.fn().mockResolvedValue({ outcome: 'queued' });+ getPlugin = jest.fn().mockReturnValue(undefined);+ service = new IngressReconcilerService(+ events,+ failures,+ { enqueue } as unknown as IngressEnqueueService,+ { getPlugin } as unknown as PluginLoaderService,+ );+ });++ afterEach(async () => {+ service.onModuleDestroy();+ if (ds.isInitialized) await ds.destroy();+ });++ // queryBuilder insert (not repo.save) so createdAt is set explicitly and the test controls the+ // grace window rather than the @CreateDateColumn "now" default.+ const insertEvent = async (over: Partial<IngressEvent> = {}): Promise<string> => {+ const n = ++seq;+ await events+ .createQueryBuilder()+ .insert()+ .values({+ id: `ev-${n}`,+ instanceId: 'inst',+ pluginId: 'plug',+ providerDeliveryId: `d-${n}`,+ route: 'chatwoot',+ payload: { headers: {}, query: {}, body: '{}', rawBody: '{}' },+ sessionId: 'sess-1',+ dispatchState: 'pending',+ dispatchAttempts: 0,+ createdAt: minutesAgo(5),+ ...over,+ })+ .execute();+ return `ev-${n}`;+ };+ const stored = (id: string) => events.findOneByOrFail({ id });+ const enqueuedJobs = () => enqueue.mock.calls as Array<[IngressJobData, string]>;++ it('replays a stale pending event with its original deliveryId as jobId, then marks it dispatched', async () => {+ const id = await insertEvent();++ const stats = await service.sweep(OPTS);++ expect(stats).toMatchObject({ scanned: 1, replayed: 1, failed: 0 });+ expect(enqueuedJobs()).toHaveLength(1);+ const [data, jobId] = enqueuedJobs()[0];+ expect(jobId).toBe('d-1'); // idempotent against a job the crashed live path may have enqueued+ expect(data).toMatchObject({+ pluginId: 'plug',+ instanceId: 'inst',+ route: 'chatwoot',+ deliveryId: 'd-1',+ sessionId: 'sess-1',+ payload: { headers: {}, query: {}, body: '{}', rawBody: '{}' },+ });+ const event = await stored(id);+ expect(event.dispatchState).toBe('dispatched');+ expect(event.lastDispatchAt).toBeInstanceOf(Date);+ });++ it('re-derives the conversation lane from the manifest route instead of degrading per-instance', async () => {+ getPlugin.mockReturnValue({+ manifest: { ingress: [{ route: 'chatwoot', conversationId: { jsonPointer: '/conversation/id' } }] },+ });+ await insertEvent({ payload: { headers: {}, query: {}, body: '{}', rawBody: '{"conversation":{"id":"conv-9"}}' } });++ await service.sweep(OPTS);++ expect(enqueuedJobs()[0][0].providerConversationId).toBe('conv-9');+ });++ it('never touches dispatched or failed rows', async () => {+ await insertEvent({ dispatchState: 'dispatched' });+ await insertEvent({ dispatchState: 'failed', dispatchAttempts: 5 });++ const stats = await service.sweep(OPTS);++ expect(stats.scanned).toBe(0);+ expect(enqueue).not.toHaveBeenCalled();+ });++ it('does not sweep a pending row younger than the grace period', async () => {+ await insertEvent({ createdAt: secondsAgo(10) });++ const stats = await service.sweep(OPTS);++ expect(stats.scanned).toBe(0);+ expect(enqueue).not.toHaveBeenCalled();+ });++ it('cools down a row whose last attempt is still inside the grace window', async () => {+ await insertEvent({ createdAt: minutesAgo(5), lastDispatchAt: secondsAgo(10), dispatchAttempts: 1 });++ const stats = await service.sweep(OPTS);++ expect(stats).toMatchObject({ scanned: 0, skipped: 1 });+ expect(enqueue).not.toHaveBeenCalled();+ });++ it('bounds the sweep to the batch size, oldest first', async () => {+ for (let i = 0; i < 5; i++) await insertEvent();+ const tight = { ...OPTS, batchSize: 3 };++ const stats = await service.sweep(tight);++ expect(enqueue).toHaveBeenCalledTimes(3);+ expect(stats.replayed).toBe(3);+ expect(await events.count({ where: { dispatchState: 'pending' } })).toBe(2);+ });++ it('keeps a failed replay pending under the attempt budget and writes no DLQ row yet', async () => {+ const id = await insertEvent();+ enqueue.mockResolvedValue({ outcome: 'failed', error: 'sandbox 5xx' });++ const stats = await service.sweep(OPTS);++ expect(stats).toMatchObject({ scanned: 1, replayed: 0, failed: 1 });+ const event = await stored(id);+ expect(event.dispatchState).toBe('pending');+ expect(event.dispatchAttempts).toBe(1);+ expect(await failures.count()).toBe(0);+ });++ it('marks the row failed (terminal) at the attempt budget, writes exactly one DLQ row, and never re-queues it', async () => {+ const id = await insertEvent({ dispatchAttempts: 4 });+ enqueue.mockResolvedValue({ outcome: 'failed', error: 'sandbox 5xx' });++ await service.sweep(OPTS);++ const event = await stored(id);+ expect(event.dispatchState).toBe('failed');+ expect(event.dispatchAttempts).toBe(5);+ const dlq = await failures.find({ where: { deliveryId: 'd-1' } });+ expect(dlq).toHaveLength(1);+ expect(dlq[0]).toMatchObject({+ direction: 'inbound',+ pluginId: 'plug',+ instanceId: 'inst',+ sessionId: 'sess-1',+ attempts: 5,+ lastError: 'sandbox 5xx',+ redriven: false,+ });+ expect((dlq[0].payload as { route?: string })?.route).toBe('chatwoot');++ // Terminal rows are out of the reconciler's scope for good: the next sweep leaves them alone.+ enqueue.mockClear();+ const stats = await service.sweep(OPTS);+ expect(stats.scanned).toBe(0);+ expect(enqueue).not.toHaveBeenCalled();+ });++ it('does not write a second DLQ row when the live path already dead-lettered the delivery', async () => {+ await insertEvent({ dispatchAttempts: 4 });+ await failures.save(+ failures.create({+ direction: 'inbound',+ pluginId: 'plug',+ instanceId: 'inst',+ sessionId: 'sess-1',+ deliveryId: 'd-1',+ attempts: 1,+ lastError: 'inline dispatch failed',+ payload: null,+ redriven: false,+ }),+ );+ enqueue.mockResolvedValue({ outcome: 'failed', error: 'still down' });++ await service.sweep(OPTS);++ expect(await failures.count({ where: { deliveryId: 'd-1' } })).toBe(1);+ });++ it('retires the live-path DLQ row when the replay succeeds (no double delivery via redrive)', async () => {+ await insertEvent();+ const dlq = await failures.save(+ failures.create({+ direction: 'inbound',+ pluginId: 'plug',+ instanceId: 'inst',+ sessionId: 'sess-1',+ deliveryId: 'd-1',+ attempts: 1,+ lastError: 'inline dispatch failed',+ payload: null,+ redriven: false,+ }),+ );+ enqueue.mockResolvedValue({ outcome: 'dispatched' });++ await service.sweep(OPTS);++ expect((await failures.findOneByOrFail({ id: dlq.id })).redriven).toBe(true);+ });++ it('keeps the batch alive when one row throws during bookkeeping', async () => {+ await insertEvent();+ await insertEvent();+ // First row's state update blows up; the second row must still be replayed.+ const updateSpy = jest+ .spyOn(events, 'update')+ .mockRejectedValueOnce(new Error('db hiccup'))+ .mockResolvedValue({ affected: 1, raw: {}, generatedMaps: [] });++ const stats = await service.sweep(OPTS);++ expect(stats).toMatchObject({ replayed: 1, skipped: 1 });+ expect(enqueue).toHaveBeenCalledTimes(2);+ updateSpy.mockRestore();+ });+});++describe('IngressReconcilerService.onModuleInit (scheduling)', () => {+ const original = process.env.INGRESS_RECONCILE_INTERVAL_MS;+ const repos = () =>+ [+ { find: jest.fn(), update: jest.fn() } as unknown as Repository<IngressEvent>,+ { update: jest.fn(), count: jest.fn(), save: jest.fn() } as unknown as Repository<IntegrationDeliveryFailure>,+ ] as const;++ afterEach(() => {+ if (original === undefined) delete process.env.INGRESS_RECONCILE_INTERVAL_MS;+ else process.env.INGRESS_RECONCILE_INTERVAL_MS = original;+ });++ it('does not schedule a timer when INGRESS_RECONCILE_INTERVAL_MS <= 0', () => {+ process.env.INGRESS_RECONCILE_INTERVAL_MS = '0';+ const [events, failures] = repos();+ const svc = new IngressReconcilerService(events, failures, {} as IngressEnqueueService, {} as PluginLoaderService);++ jest.useFakeTimers();+ try {+ const sweepSpy = jest.spyOn(svc, 'sweep');+ svc.onModuleInit();+ jest.advanceTimersByTime(10 * 60_000);+ expect(sweepSpy).not.toHaveBeenCalled();+ svc.onModuleDestroy();+ } finally {+ jest.useRealTimers();+ }+ });++ it('sweeps on the configured interval and stops after onModuleDestroy', () => {+ delete process.env.INGRESS_RECONCILE_INTERVAL_MS;+ const [events, failures] = repos();+ const svc = new IngressReconcilerService(events, failures, {} as IngressEnqueueService, {} as PluginLoaderService);++ jest.useFakeTimers();+ try {+ const sweepSpy = jest.spyOn(svc, 'sweep').mockResolvedValue({ scanned: 0, replayed: 0, failed: 0, skipped: 0 });+ svc.onModuleInit();+ jest.advanceTimersByTime(60_000);+ expect(sweepSpy).toHaveBeenCalledTimes(1);+ svc.onModuleDestroy();+ sweepSpy.mockClear();+ jest.advanceTimersByTime(60_000);+ expect(sweepSpy).not.toHaveBeenCalled();+ } finally {+ jest.useRealTimers();+ }+ });+});diff --git a/src/modules/integration/ingress-reconciler.service.ts b/src/modules/integration/ingress-reconciler.service.tsnew file mode 100644index 000000000..9aaee362e--- /dev/null+++ b/src/modules/integration/ingress-reconciler.service.ts@@ -0,0 +1,226 @@+import { Injectable, OnModuleDestroy, OnModuleInit } from '@nestjs/common';+import { InjectRepository } from '@nestjs/typeorm';+import { LessThan, Repository } from 'typeorm';+import { IngressEvent } from './entities/ingress-event.entity';+import { IntegrationDeliveryFailure } from './entities/integration-delivery-failure.entity';+import { IngressEnqueueService, buildIngressDeadLetterRow } from './ingress-enqueue.service';+import { extractConversationId } from './ingress.service';+import { PluginLoaderService } from '../../core/plugins/plugin-loader.service';+import { IngressJobData } from '../queue/processors/ingress.processor';+import { createLogger } from '../../common/services/logger.service';++export interface IngressReconcilerOptions {+ // Sweep cadence. <= 0 disables the reconciler (mirrors INGRESS_RETENTION_DAYS <= 0).+ intervalMs: number;+ // A 'pending' row only becomes sweep-eligible once its last activity (creation or latest attempt)+ // is older than this — the live path gets the whole window to record its own outcome first.+ graceMs: number;+ batchSize: number;+ // Replay budget per event. Exhaustion marks the row 'failed' (terminal) and guarantees a DLQ row+ // exists, so recovery continues through RedriveService instead of an infinite replay loop.+ maxAttempts: number;+}++export function resolveIngressReconcilerOptions(env: NodeJS.ProcessEnv = process.env): IngressReconcilerOptions {+ const interval = Number(env.INGRESS_RECONCILE_INTERVAL_MS);+ const grace = Number(env.INGRESS_RECONCILE_GRACE_MS);+ const batch = Number(env.INGRESS_RECONCILE_BATCH_SIZE);+ const maxAttempts = Number(env.INGRESS_RECONCILE_MAX_ATTEMPTS);+ return {+ intervalMs: Number.isInteger(interval) ? interval : 60_000,+ graceMs: Number.isInteger(grace) && grace >= 0 ? grace : 60_000,+ batchSize: Number.isInteger(batch) && batch >= 1 ? batch : 50,+ maxAttempts: Number.isInteger(maxAttempts) && maxAttempts >= 1 ? maxAttempts : 5,+ };+}++export interface IngressReconcileStats {+ scanned: number;+ replayed: number;+ failed: number;+ skipped: number;+}++/**+ * Closes the last silent-loss window of the fast-ack ingress pipeline. persist-before-ack makes the+ * ingress_events row durable, but durability alone is not delivery: a crash between the persist and+ * the enqueue, or a fire-and-forget enqueue whose outcome never gets recorded, strands the row+ * 'pending' forever — a provider retry only hits the dedup oracle and 200s as 'duplicate'.+ *+ * The reconciler sweeps small batches of stale 'pending' rows and re-dispatches them through the+ * exact same IngressEnqueueService the live path uses (same deliveryId as BullMQ jobId, so a replay+ * is idempotent against a job that did get enqueued). Re-dispatch from the row is sound because the+ * row IS the full verified request: payload carries headers/query/body/rawBody, providerDeliveryId is+ * the delivery id, and the manifest route re-derives the conversation lane. 'failed'/'dispatched'+ * rows are never re-queued: a terminal failure lives in the DLQ (RedriveService), a dispatched event+ * is the dispatch tier's concern.+ *+ * Mirrors IntegrationRetentionService's lifecycle: a raw unref'd setInterval started on module init+ * (first sweep after one interval, so plugin sandboxes have time to boot), cleared on destroy.+ */+@Injectable()+export class IngressReconcilerService implements OnModuleInit, OnModuleDestroy {+ private readonly logger = createLogger('IngressReconcilerService');+ private timer?: ReturnType<typeof setInterval>;+ private sweeping = false;++ constructor(+ @InjectRepository(IngressEvent, 'data') private readonly events: Repository<IngressEvent>,+ @InjectRepository(IntegrationDeliveryFailure, 'data')+ private readonly failures: Repository<IntegrationDeliveryFailure>,+ private readonly ingressEnqueue: IngressEnqueueService,+ private readonly loader: PluginLoaderService,+ ) {}++ onModuleInit(): void {+ const opts = resolveIngressReconcilerOptions();+ if (opts.intervalMs <= 0) {+ this.logger.log('Ingress event reconciler disabled (INGRESS_RECONCILE_INTERVAL_MS <= 0)');+ return;+ }+ this.timer = setInterval(() => {+ this.sweep(opts).catch(err =>+ this.logger.error('Ingress 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 stale 'pending' backlog. Overlap-guarded: a slow sweep (up to+ * batchSize sequential inline dispatch timeouts) never stacks a second pass on top of itself.+ */+ async sweep(opts: IngressReconcilerOptions, now: Date = new Date()): Promise<IngressReconcileStats> {+ const stats: IngressReconcileStats = { scanned: 0, replayed: 0, failed: 0, skipped: 0 };+ if (this.sweeping) return stats;+ this.sweeping = true;+ try {+ const cutoff = new Date(now.getTime() - opts.graceMs);+ const rows = await this.events.find({+ where: { dispatchState: 'pending', createdAt: LessThan(cutoff) },+ order: { createdAt: 'ASC' },+ take: opts.batchSize,+ });+ for (const row of rows) {+ // A row whose latest attempt is still inside the grace window cools down between replays;+ // it keeps its batch slot (bounded by maxAttempts, so the leak is capped) but is not hit again.+ if (row.lastDispatchAt && row.lastDispatchAt > cutoff) {+ stats.skipped++;+ continue;+ }+ stats.scanned++;+ try {+ const outcome = await this.reconcileRow(row, opts.maxAttempts, now);+ if (outcome === 'replayed') stats.replayed++;+ else stats.failed++;+ } catch (err) {+ // A bookkeeping failure (repo update/DLQ write) must not abort the batch; the row stays+ // 'pending' and is retried next sweep.+ this.logger.error('Ingress reconcile row failed', err instanceof Error ? err.message : String(err), {+ pluginId: row.pluginId,+ instanceId: row.instanceId,+ deliveryId: row.providerDeliveryId,+ action: 'ingress_reconcile_row_failed',+ });+ stats.skipped++;+ }+ }+ return stats;+ } finally {+ this.sweeping = false;+ }+ }++ private async reconcileRow(row: IngressEvent, maxAttempts: number, now: Date): Promise<'replayed' | 'failed'> {+ const jobData = this.jobDataFor(row);+ // jobId = the ORIGINAL deliveryId: BullMQ dedups a replay against a job that did get enqueued+ // before the crash, so re-dispatch never double-delivers on the queue path.+ const { outcome, error } = await this.ingressEnqueue.enqueue(jobData, row.providerDeliveryId);+ if (outcome !== 'failed') {+ await this.events.update({ id: row.id }, { dispatchState: 'dispatched', lastDispatchAt: now });+ // Retire any dead-letter row the live path already wrote for this delivery (the inline-failure+ // case) — the replay just delivered it, so a later manual redrive must not deliver it again.+ await this.failures.update(+ {+ direction: 'inbound',+ pluginId: row.pluginId,+ instanceId: row.instanceId,+ deliveryId: row.providerDeliveryId,+ redriven: false,+ },+ { redriven: true },+ );+ this.logger.log('Replayed stranded ingress event', {+ pluginId: row.pluginId,+ instanceId: row.instanceId,+ deliveryId: row.providerDeliveryId,+ outcome,+ action: 'ingress_event_replayed',+ });+ return 'replayed';+ }++ const attempts = (row.dispatchAttempts ?? 0) + 1;+ const terminal = attempts >= maxAttempts;+ await this.events.update(+ { id: row.id },+ {+ dispatchAttempts: attempts,+ lastDispatchAt: now,+ ...(terminal ? { dispatchState: 'failed' as const } : {}),+ },+ );+ if (terminal) {+ await this.ensureDeadLetterRow(jobData, attempts, error);+ this.logger.warn('Ingress event replay budget exhausted; event is dead-lettered', {+ pluginId: row.pluginId,+ instanceId: row.instanceId,+ deliveryId: row.providerDeliveryId,+ attempts,+ action: 'ingress_event_reconcile_exhausted',+ });+ }+ return 'failed';+ }++ /**+ * Rebuild the dispatch job from the persisted row. `method` is the one request field the row does+ * not persist — dispatchWebhookForInstance defaults it to 'POST' (the same tolerance RedriveService+ * applies to legacy DLQ rows). providerConversationId is re-derived from the CURRENT manifest route+ * so the replay joins the same per-conversation ordering lane as live deliveries instead of+ * degrading to the per-instance lane; a hot-swapped/missing route just yields no key.+ */+ private jobDataFor(row: IngressEvent): IngressJobData {+ const route = this.loader+ .getPlugin(row.pluginId)+ ?.manifest.ingress?.find(candidate => candidate.route === row.route);+ return {+ pluginId: row.pluginId,+ instanceId: row.instanceId,+ route: row.route,+ deliveryId: row.providerDeliveryId,+ sessionId: row.sessionId ?? undefined,+ providerConversationId: extractConversationId(route?.conversationId, row.payload.headers, row.payload.rawBody),+ payload: row.payload,+ };+ }++ // The live path dead-letters an inline-dispatch failure at request time, so a terminal row may+ // already have its DLQ entry — write one only if missing, and never a second copy.+ private async ensureDeadLetterRow(data: IngressJobData, attempts: number, error?: string): Promise<void> {+ const existing = await this.failures.count({+ where: {+ direction: 'inbound',+ pluginId: data.pluginId,+ instanceId: data.instanceId,+ deliveryId: data.deliveryId,+ },+ });+ if (existing > 0) return;+ await this.failures.save({ ...buildIngressDeadLetterRow(data, error), attempts });+ }+}diff --git a/src/modules/integration/integration.module.ts b/src/modules/integration/integration.module.tsindex 576636844..a5ecf862b 100644--- a/src/modules/integration/integration.module.ts+++ b/src/modules/integration/integration.module.ts@@ -9,6 +9,7 @@ import { IngressEventService } from './ingress-event.service';import { IngressService, IngressRouteDescriptor } from './ingress.service';import { IngressController } from './ingress.controller';import { IngressEnqueueService, buildIngressDeadLetterRow } from './ingress-enqueue.service';+import { IngressReconcilerService } from './ingress-reconciler.service';import { RedriveService } from './redrive.service';import { RedriveController } from './redrive.controller';import { IntegrationRetentionService } from './integration-retention.service';@@ -51,6 +52,7 @@ if (process.env.QUEUE_ENABLED === 'true') {PluginInstanceService,IngressEventService,IngressEnqueueService,+ IngressReconcilerService,RedriveService,ScopeBindingService,IntegrationRetentionService,@@ -86,13 +88,28 @@ if (process.env.QUEUE_ENABLED === 'true') {// Audit sink for preflight rejections (they leave no dedup/DLQ row). The Prometheus counter is// a separate follow-up (see plan notes); the structured log is the MVP audit surface.log: (event, meta) => ingressLogger.warn(event, meta),- // Live ingress delivery: on a swallowed inline-dispatch failure, persist a dead-letter row so- // RedriveService can replay it — IngressService.handle() ignores the outcome and always 202s, so- // nothing else would. RedriveService calls enqueue() directly (it is already replaying a DLQ- // row) so it never double-writes here. The DLQ save is itself best-effort: a failure must not- // 500 the ingress request (the delivery is already dedup-persisted, so the provider won't re-send).+ // Live ingress delivery: record the dispatch outcome on the event row (so the reconciler+ // can tell a stranded 'pending' row from one that reached the dispatch tier) and, on a+ // swallowed inline-dispatch failure, persist a dead-letter row so RedriveService can replay+ // it — IngressService.handle() always 202s, so nothing else would. RedriveService calls+ // enqueue() directly (it is already replaying a DLQ row) so it never double-writes here.+ // Both writes are best-effort: a failure must not 500 the ingress request (the delivery is+ // already dedup-persisted, so the provider won't re-send; an unmarked row stays 'pending'+ // and the reconciler replays it — at-least-once, plugin handlers are idempotent by contract).enqueue: async (data, jobId) => {const result = await ingressEnqueue.enqueue(data, jobId);+ try {+ await events.markDispatchOutcome(+ { pluginId: data.pluginId, instanceId: data.instanceId, providerDeliveryId: data.deliveryId },+ result.outcome,+ );+ } catch (err) {+ dlqLogger.error(+ 'Failed to mark ingress dispatch outcome',+ err instanceof Error ? err.message : String(err),+ { pluginId: data.pluginId, instanceId: data.instanceId, deliveryId: data.deliveryId },+ );+ }if (result.outcome === 'failed') {try {await failures.save(buildIngressDeadLetterRow(data, result.error));diff --git a/test/integration-fabric.e2e-spec.ts b/test/integration-fabric.e2e-spec.tsindex 3299fa882..639c29401 100644--- a/test/integration-fabric.e2e-spec.ts+++ b/test/integration-fabric.e2e-spec.ts@@ -16,6 +16,7 @@ import { AppModule } from './../src/app.module';import { applyGlobalValidation } from './../src/config/app-validation';import { PluginLoaderService } from './../src/core/plugins/plugin-loader.service';import { PluginInstance } from './../src/modules/integration/entities/plugin-instance.entity';+import { IngressEvent } from './../src/modules/integration/entities/ingress-event.entity';import { IntegrationDeliveryFailure } from './../src/modules/integration/entities/integration-delivery-failure.entity';/**@@ -172,10 +173,28 @@ describe('Integration Fabric ingress (e2e)', () => {expect(dispatchWebhookForInstance).not.toHaveBeenCalled();});+ it('marks the persisted event dispatched once a successful inline dispatch is recorded', async () => {+ const eventRepo = app.get<Repository<IngressEvent>>(getRepositoryToken(IngressEvent, 'data'));+ const res = await request(app.getHttpServer())+ .post(INGRESS_PATH)+ .set('X-Chatwoot-Signature', sig)+ .set('X-Chatwoot-Delivery', 'delivery-marked-1')+ .set('Content-Type', 'application/json')+ .send(raw);++ expect(res.status).toBe(202);+ // The no-`response` route awaits enqueue before the ack, so the outcome is already recorded:+ // a crash between persist and dispatch is the only way a fresh row stays 'pending'.+ const row = await eventRepo.findOneByOrFail({ providerDeliveryId: 'delivery-marked-1' });+ expect(row.dispatchState).toBe('dispatched');+ expect(row.lastDispatchAt).not.toBeNull();+ });+it('persists a redrivable dead-letter row (still 202) when inline dispatch fails', async () => {const failureRepo = app.get<Repository<IntegrationDeliveryFailure>>(getRepositoryToken(IntegrationDeliveryFailure, 'data'),);+ const eventRepo = app.get<Repository<IngressEvent>>(getRepositoryToken(IngressEvent, 'data'));// The plugin handler throws — the inline-dispatch fallback fails and is swallowed. Without a// dead-letter row the event would be stranded: handle() still 202s, and RedriveService only scans// this table (never ingress_events). The live-ingress wiring must therefore persist the failure here.@@ -198,5 +217,11 @@ describe('Integration Fabric ingress (e2e)', () => {redriven: false,lastError: 'sandbox handler 5xx',});++ // The event row itself stays 'pending' with the failure counted, so the reconciler retries the+ // dispatch on its next sweep instead of waiting for a manual redrive alone.+ const event = await eventRepo.findOneByOrFail({ providerDeliveryId: 'delivery-dlq-1' });+ expect(event.dispatchState).toBe('pending');+ expect(event.dispatchAttempts).toBe(1);});});