Skip to content

Free, Open Source, Self-Hosted WhatsApp API Gateway

fix(webhook): report the delivery outcome and clear the outbox on import

Yudhi Armyndharis8071d898c13f
diff --git a/CHANGELOG.md b/CHANGELOG.md
index db42eddd2..a96f182bd 100644
--- a/CHANGELOG.md
+++ b/CHANGELOG.md
@@ -20,6 +20,8 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0
- 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 was fire-and-forget, so a crash between persisting a message and completing its POST lost the delivery, against a documented at-least-once contract. Deliveries are now recorded before they are attempted, and a bounded sweep replays whatever is stranded under its stored idempotency key.
+- A stranded webhook delivery now gets the replay budget it was promised. The reconciler read success from a call that cannot fail, so a replay that never delivered was retired as dispatched on the first sweep and its payload dropped. Delivery reports an outcome instead, and a failed replay stays pending.
+- Restoring a backup no longer aborts when the target already holds the outbound delivery records. The table has no session foreign key, so the replace never cleared it and every overlapping row collided, rolling the whole import back.
- Settled outbound delivery records are pruned after `WEBHOOK_OUTBOX_RETENTION_DAYS` (default 7). A record that can still be replayed is never pruned on age, and a non-positive window falls back to the default rather than letting the table grow without bound.
- `PLUGIN_STATE_DIR` moves the plugin registry and per-plugin storage off the default `./data`. It was the one piece of state with no path knob, so a test run rewrote the developer's own registry.
- The e2e lane sweeps the throwaway state roots it creates. Each suite gets its own, nothing removed them, and the temp directory accumulated hundreds of entries over a few days of runs.
diff --git a/src/modules/infra/infra-data.controller.spec.ts b/src/modules/infra/infra-data.controller.spec.ts
index ef7cf2697..67642fb8a 100644
--- a/src/modules/infra/infra-data.controller.spec.ts
+++ b/src/modules/infra/infra-data.controller.spec.ts
@@ -1268,6 +1268,38 @@ describe('InfraDataController.import/export preserves every data-DB table', () =
expect((await lidRepo.findOneByOrFail({ lid: '222' })).phone).toBeNull();
});
+ // Restoring ONTO the instance that produced the archive is the rollback flow, and it is the one the
+ // outbox broke. The table carries no FK to sessions, so the sessions DELETE never reached it, and
+ // UNIQUE(webhookId, idempotencyKey) then collided on every row until the all-or-nothing gate rolled
+ // the entire import back. Every other table's test clears first, which is why nothing caught it;
+ // this one deliberately does not.
+ it('restores webhook_outbox_events onto an instance that already holds them', async () => {
+ await seedSession('s1');
+ const outboxRepo = ds.getRepository(WebhookOutboxEvent);
+ await outboxRepo.save(
+ outboxRepo.create({
+ webhookId: 'wh-1',
+ sessionId: 's1',
+ event: 'message.received',
+ idempotencyKey: 'key-1',
+ deliveryId: 'del-1',
+ payload: { from: '[email protected]' },
+ state: 'pending',
+ attempts: 0,
+ }),
+ );
+
+ const dump = await controller.exportData();
+ expect((dump.tables as unknown as { webhookOutboxEvents?: unknown[] }).webhookOutboxEvents).toHaveLength(1);
+
+ const res = await controller.importData({ tables: dump.tables });
+
+ expect(res.warnings).toEqual([]);
+ expect(res.imported).toBe(true);
+ expect(await outboxRepo.count()).toBe(1);
+ expect((await outboxRepo.findOneByOrFail({ idempotencyKey: 'key-1' })).state).toBe('pending');
+ });
+
// The messages import column list must carry every later-added column; `author` (the group
// sender identity) was the one that drifted — a restored backup silently lost all attribution.
it('restores the group-sender author column on a backup→restore', async () => {
diff --git a/src/modules/infra/infra-data.service.ts b/src/modules/infra/infra-data.service.ts
index 3e1c5f2f0..8d19c8d62 100644
--- a/src/modules/infra/infra-data.service.ts
+++ b/src/modules/infra/infra-data.service.ts
@@ -602,6 +602,12 @@ export class InfraDataService {
await clearTable('conversation_mappings');
await clearTable('ingress_events');
await clearTable('webhook_delivery_failures');
+ // Same rule, and it bites harder here: webhook_outbox_events carries UNIQUE(webhookId,
+ // idempotencyKey), so without this clear a restore onto an instance that already holds the
+ // archive's rows collides on every one of them, and the all-or-nothing gate below rolls the
+ // whole import back. Restoring a backup onto the instance that produced it is exactly the
+ // rollback flow, so leaving it out broke the recovery path rather than a corner of it.
+ await clearTable('webhook_outbox_events');
await clearTable('integration_delivery_failures');
// status_updates has no FK to sessions; clear it explicitly so the replace is complete.
await clearTable('status_updates');
diff --git a/src/modules/webhook/webhook-delivery.service.spec.ts b/src/modules/webhook/webhook-delivery.service.spec.ts
index 9a3143be1..60299310c 100644
--- a/src/modules/webhook/webhook-delivery.service.spec.ts
+++ b/src/modules/webhook/webhook-delivery.service.spec.ts
@@ -608,6 +608,29 @@ describe('WebhookDeliveryService', () => {
expect(hookManager.execute).not.toHaveBeenCalledWith('webhook:error', expect.anything(), expect.anything());
});
+ // The reconciler branches on this VALUE, never on a throw: every failing path inside redeliver
+ // dead-letters in place, so nothing reaches the caller as an exception. When this reported
+ // nothing, a replay that never delivered was retired 'dispatched' on the first sweep and the
+ // documented WEBHOOK_RECONCILE_MAX_ATTEMPTS budget was unreachable.
+ it('redeliver reports failed when the receiver never accepts, and delivered when it does', async () => {
+ const webhook = createMockWebhook({ events: ['message.received'], retryCount: 1 });
+ (hookManager.execute as jest.Mock).mockResolvedValue({ continue: true, data: {} });
+
+ mockFetch.mockReset();
+ mockFetch.mockRejectedValue(new Error('receiver down'));
+ await expect(
+ service.redeliver(webhook, 'sess-1', 'message.received', 'stored-key-1', { from: '[email protected]' }),
+ ).resolves.toBe('failed');
+
+ // Control: the same call on a receiver that answers 2xx must NOT report 'failed', otherwise
+ // the assertion above is satisfied by a method that reports failure unconditionally.
+ mockFetch.mockReset();
+ mockFetch.mockResolvedValue({ ok: true, status: 200 });
+ await expect(
+ service.redeliver(webhook, 'sess-1', 'message.received', 'stored-key-2', { from: '[email protected]' }),
+ ).resolves.toBe('delivered');
+ });
+
it("isolates each webhook's data so an in-place before-hook mutation cannot bleed across webhooks", async () => {
const a = createMockWebhook({ id: 'wh-a', events: ['message.received'] });
const b = createMockWebhook({ id: 'wh-b', events: ['message.received'] });
diff --git a/src/modules/webhook/webhook-delivery.service.ts b/src/modules/webhook/webhook-delivery.service.ts
index af35ac00e..6ba2fd7b7 100644
--- a/src/modules/webhook/webhook-delivery.service.ts
+++ b/src/modules/webhook/webhook-delivery.service.ts
@@ -60,6 +60,13 @@ const DEFAULT_WEBHOOK_MAX_PAYLOAD_BYTES = 1024 * 1024;
const DEFAULT_WEBHOOK_SHUTDOWN_DRAIN_MS = 5000;
/** Per-event-occurrence context threaded through the dispatch pipeline stages (was closure state). */
+/**
+ * The result of one delivery attempt. Reported, not thrown: every failure below is already handled
+ * in place, so nothing reaches a caller as an exception and a try/catch cannot tell a delivered
+ * event from a dead-lettered one.
+ */
+export type WebhookDeliveryOutcome = 'delivered' | 'enqueued' | 'failed';
+
interface DispatchEventContext {
sessionId: string;
event: string;
@@ -392,23 +399,32 @@ export class WebhookDeliveryService implements OnModuleInit, OnModuleDestroy {
}
}
+ /**
+ * What became of one delivery attempt, reported rather than thrown.
+ *
+ * Every failure path here is already handled in place (a dead-letter row, a hook, a log), so none
+ * of them reach the caller as an exception. The reconciler has to tell a delivered event from a
+ * dead-lettered one to know whether the outbox row may be retired, and a caught throw cannot tell
+ * it: there is none. This mirrors the inbound twin, where `ingressEnqueue.enqueue` returns an
+ * outcome and the caller retires the payload only when it is not 'failed'.
+ */
private async deliverOne(
webhook: Webhook,
deliveryId: string,
idempotencyKey: string,
ctx: DispatchEventContext,
- ): Promise<void> {
+ ): Promise<WebhookDeliveryOutcome> {
const preflight = await this.preflightDelivery(webhook, deliveryId, idempotencyKey, ctx);
if (!preflight) {
- return;
+ // Preflight records its own undelivered row and returns null; nothing left the process.
+ return 'failed';
}
const { finalPayload, body, headers } = preflight;
// Use queue if available, otherwise fallback to direct delivery
if (this.queueEnabled && this.webhookQueue) {
- await this.enqueueWithFallback(webhook, finalPayload, body, headers, deliveryId, idempotencyKey, ctx);
- } else {
- await this.deliverDirect(webhook, finalPayload, body, headers, deliveryId, ctx);
+ return this.enqueueWithFallback(webhook, finalPayload, body, headers, deliveryId, idempotencyKey, ctx);
}
+ return this.deliverDirect(webhook, finalPayload, body, headers, deliveryId, ctx);
}
private async enqueueWithFallback(
@@ -419,7 +435,7 @@ export class WebhookDeliveryService implements OnModuleInit, OnModuleDestroy {
deliveryId: string,
idempotencyKey: string,
ctx: DispatchEventContext,
- ): Promise<void> {
+ ): Promise<WebhookDeliveryOutcome> {
const { sessionId, event } = ctx;
try {
// Sign the exact pre-serialized body from preflight. The processor re-serializes the same
@@ -515,8 +531,13 @@ export class WebhookDeliveryService implements OnModuleInit, OnModuleDestroy {
webhookId: webhook.id,
action: 'webhook_queue_fallback_failed',
});
+ return 'failed';
}
+ // The queue never took it, but the fallback POST did.
+ return 'delivered';
}
+ // Handed to BullMQ, which owns the retries and the dead-letter row from here.
+ return 'enqueued';
}
/** Direct delivery when the queue is disabled. */
@@ -527,7 +548,7 @@ export class WebhookDeliveryService implements OnModuleInit, OnModuleDestroy {
headers: Record<string, string>,
deliveryId: string,
ctx: DispatchEventContext,
- ): Promise<void> {
+ ): Promise<WebhookDeliveryOutcome> {
const { sessionId, event } = ctx;
try {
await this.deliverWebhook(webhook, finalPayload, headers, body);
@@ -557,7 +578,9 @@ export class WebhookDeliveryService implements OnModuleInit, OnModuleDestroy {
webhookId: webhook.id,
action: 'webhook_delivery_failed',
});
+ return 'failed';
}
+ return 'delivered';
}
/**
@@ -651,9 +674,9 @@ export class WebhookDeliveryService implements OnModuleInit, OnModuleDestroy {
event: string,
idempotencyKey: string,
data: Record<string, unknown>,
- ): Promise<void> {
+ ): Promise<WebhookDeliveryOutcome> {
const deliveryId = generateDeliveryId();
- await this.deliverOne(webhook, deliveryId, idempotencyKey, { sessionId, event, baseData: data });
+ return this.deliverOne(webhook, deliveryId, idempotencyKey, { sessionId, event, baseData: data });
}
/**
diff --git a/src/modules/webhook/webhook-reconciler.service.spec.ts b/src/modules/webhook/webhook-reconciler.service.spec.ts
index 083db916c..6d9188ada 100644
--- a/src/modules/webhook/webhook-reconciler.service.spec.ts
+++ b/src/modules/webhook/webhook-reconciler.service.spec.ts
@@ -43,7 +43,7 @@ describe('WebhookReconcilerService', () => {
beforeEach(() => {
outbox = { findStale: jest.fn().mockResolvedValue([]), close: jest.fn(), countAttempt: jest.fn() };
- delivery = { redeliver: jest.fn().mockResolvedValue(undefined) };
+ delivery = { redeliver: jest.fn().mockResolvedValue('delivered') };
webhooks = { findOne: jest.fn().mockResolvedValue({ id: 'wh-1', active: true }) };
service = new WebhookReconcilerService(webhooks as never, outbox as never, delivery as never);
});
@@ -66,9 +66,13 @@ describe('WebhookReconcilerService', () => {
expect(stats).toMatchObject({ scanned: 1, replayed: 1 });
});
- it('counts the attempt BEFORE replaying, so a delivery that always throws still exhausts its budget', async () => {
+ // The REAL shape of a delivery failure. redeliver resolves 'failed' rather than rejecting, because
+ // every failing path inside it already dead-letters and logs; an earlier version of this test
+ // mocked a rejection instead, which the collaborator cannot produce, so the budget it claimed to
+ // guard was never exercised and a dead-lettered event was retired as 'dispatched' on sweep one.
+ it('leaves a row pending when the replay did not deliver, so the budget is actually spent', async () => {
outbox.findStale.mockResolvedValue([row({ attempts: 1 })]);
- delivery.redeliver.mockRejectedValue(new Error('receiver down'));
+ delivery.redeliver.mockResolvedValue('failed');
const stats = await service.sweep(OPTS);
@@ -81,6 +85,26 @@ describe('WebhookReconcilerService', () => {
expect(stats).toMatchObject({ replayed: 0, failed: 1 });
});
+ it('retires the row when the replay was handed to the queue rather than delivered inline', async () => {
+ outbox.findStale.mockResolvedValue([row({ attempts: 1 })]);
+ delivery.redeliver.mockResolvedValue('enqueued');
+
+ const stats = await service.sweep(OPTS);
+
+ expect(outbox.close).toHaveBeenCalledWith('wh-1', 'stored-key_wh-1', 'dispatched');
+ expect(stats).toMatchObject({ replayed: 1, failed: 0 });
+ });
+
+ it('keeps a row pending when the replay throws an unexpected fault', async () => {
+ outbox.findStale.mockResolvedValue([row({ attempts: 1 })]);
+ delivery.redeliver.mockRejectedValue(new Error('boom'));
+
+ const stats = await service.sweep(OPTS);
+
+ 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 })]);
diff --git a/src/modules/webhook/webhook-reconciler.service.ts b/src/modules/webhook/webhook-reconciler.service.ts
index 354fcec8e..834540ded 100644
--- a/src/modules/webhook/webhook-reconciler.service.ts
+++ b/src/modules/webhook/webhook-reconciler.service.ts
@@ -110,11 +110,28 @@ export class WebhookReconcilerService implements OnModuleInit, OnModuleDestroy {
}
await this.outbox.countAttempt(row.id, row.attempts);
try {
- await this.delivery.redeliver(webhook, row.sessionId, row.event, row.idempotencyKey, row.payload);
+ // The outcome is a RETURN VALUE, not an exception. Every delivery failure is handled in
+ // place (dead-letter row, hook, log), so redeliver resolves either way and a catch here
+ // would see nothing: retiring on resolve alone marked dead-lettered events 'dispatched'
+ // and nulled their payload, spending the whole budget on one sweep.
+ const outcome = await this.delivery.redeliver(
+ webhook,
+ row.sessionId,
+ row.event,
+ row.idempotencyKey,
+ row.payload,
+ );
+ if (outcome === 'failed') {
+ // 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} did not deliver`);
+ stats.failed++;
+ continue;
+ }
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.
+ // An exception is an unexpected fault rather than a delivery failure; the row stays
+ // pending either way.
this.logger.warn(`Replay of ${row.event} to webhook ${row.webhookId} failed: ${String(error)}`);
stats.failed++;
}