Skip to content

Free, Open Source, Self-Hosted WhatsApp API Gateway

fix(webhook): correct outcome accounting on the replay path

Yudhi Armyndharis8a3b6e4a3ace
diff --git a/src/database/migrations/1786300000000-AddWebhookDeliveryFailureLookupIndex.ts b/src/database/migrations/1786300000000-AddWebhookDeliveryFailureLookupIndex.ts
new file mode 100644
index 000000000..d6078850e
--- /dev/null
+++ b/src/database/migrations/1786300000000-AddWebhookDeliveryFailureLookupIndex.ts
@@ -0,0 +1,32 @@
+import { MigrationInterface, QueryRunner } from 'typeorm';
+
+/**
+ * Composite index on `webhook_delivery_failures (webhookId, idempotencyKey)`, backing the
+ * before-insert lookup in `recordWebhookDeliveryFailure` that keeps one row per lost delivery
+ * rather than one per replay attempt. The table is append-only and never pruned, so without an
+ * index that lookup scans it once per terminal failure: during exactly the receiver outage the
+ * table exists to record, the scan grows with the rows the outage is adding.
+ *
+ * Hand-authored because `synchronize` is off for the data connection on PostgreSQL (and optional on
+ * SQLite). The explicit name matches the entity's @Index, so the synchronize and migration schema
+ * paths converge on one index. Idempotent via IF NOT EXISTS (supported by both dialects).
+ */
+export class AddWebhookDeliveryFailureLookupIndex1786300000000 implements MigrationInterface {
+ name = 'AddWebhookDeliveryFailureLookupIndex1786300000000';
+
+ public async up(queryRunner: QueryRunner): Promise<void> {
+ // The data pool boots with a runtime statement_timeout (default 30s), and MigrationExecutor
+ // wraps a lone pending migration in its own transaction, so no earlier SET LOCAL is in effect.
+ // Lift it for this transaction only, exactly like AddMessageMediaPathIndex.
+ if (queryRunner.dataSource.options.type === 'postgres') {
+ await queryRunner.query('SET LOCAL statement_timeout = 0');
+ }
+ await queryRunner.query(
+ `CREATE INDEX IF NOT EXISTS "IDX_webhook_delivery_failures_delivery" ON "webhook_delivery_failures" ("webhookId", "idempotencyKey")`,
+ );
+ }
+
+ public async down(queryRunner: QueryRunner): Promise<void> {
+ await queryRunner.query(`DROP INDEX IF EXISTS "IDX_webhook_delivery_failures_delivery"`);
+ }
+}
diff --git a/src/database/migrations/__tests__/1786300000000-AddWebhookDeliveryFailureLookupIndex.spec.ts b/src/database/migrations/__tests__/1786300000000-AddWebhookDeliveryFailureLookupIndex.spec.ts
new file mode 100644
index 000000000..b1e9346b1
--- /dev/null
+++ b/src/database/migrations/__tests__/1786300000000-AddWebhookDeliveryFailureLookupIndex.spec.ts
@@ -0,0 +1,70 @@
+import { DataSource } from 'typeorm';
+import { AddWebhookDeliveryFailureLookupIndex1786300000000 } from '../1786300000000-AddWebhookDeliveryFailureLookupIndex';
+
+describe('AddWebhookDeliveryFailureLookupIndex migration', () => {
+ let ds: DataSource;
+
+ beforeEach(async () => {
+ ds = new DataSource({ type: 'better-sqlite3', database: ':memory:' });
+ await ds.initialize();
+ // Post-AddWebhookDeliveryFailures shape, reduced to the columns this index covers.
+ await ds.query(
+ `CREATE TABLE "webhook_delivery_failures" ("id" varchar PRIMARY KEY NOT NULL, ` +
+ `"webhookId" varchar NOT NULL, "sessionId" varchar NOT NULL, "idempotencyKey" varchar NULL)`,
+ );
+ // Enough rows that the planner has a reason to prefer the index over a scan.
+ const rows: string[] = [];
+ for (let i = 0; i < 200; i++) {
+ rows.push(`('id${i}', 'wh-${i % 5}', 's1', 'key-${i}')`);
+ }
+ await ds.query(
+ `INSERT INTO "webhook_delivery_failures" ("id","webhookId","sessionId","idempotencyKey") VALUES ${rows.join(',')}`,
+ );
+ });
+
+ afterEach(async () => {
+ await ds.destroy();
+ });
+
+ const indexNames = async (): Promise<string[]> => {
+ const rows = await ds.query<{ name: string }[]>(`PRAGMA index_list("webhook_delivery_failures")`);
+ return rows.map(r => r.name).sort();
+ };
+
+ it('creates the delivery lookup index', async () => {
+ const runner = ds.createQueryRunner();
+ await new AddWebhookDeliveryFailureLookupIndex1786300000000().up(runner);
+
+ expect(await indexNames()).toContain('IDX_webhook_delivery_failures_delivery');
+ });
+
+ it('is idempotent (re-running up is a no-op) and down() drops the index', async () => {
+ const runner = ds.createQueryRunner();
+ const migration = new AddWebhookDeliveryFailureLookupIndex1786300000000();
+
+ await migration.up(runner);
+ await expect(migration.up(runner)).resolves.toBeUndefined();
+ expect(await indexNames()).toContain('IDX_webhook_delivery_failures_delivery');
+
+ await migration.down(runner);
+ expect(await indexNames()).not.toContain('IDX_webhook_delivery_failures_delivery');
+ });
+
+ it('the duplicate-record lookup is served by the index, not a table scan', async () => {
+ const runner = ds.createQueryRunner();
+ const countQuery =
+ `EXPLAIN QUERY PLAN SELECT COUNT(*) FROM "webhook_delivery_failures" ` +
+ `WHERE "webhookId" = 'wh-1' AND "idempotencyKey" = 'key-6'`;
+
+ // Baseline first: without the index this really is a scan, so the assertion below is measuring
+ // the index rather than a plan that was already index-served for some other reason.
+ const before = (await ds.query<{ detail: string }[]>(countQuery)).map(r => r.detail).join(' ');
+ expect(before).toContain('SCAN');
+
+ await new AddWebhookDeliveryFailureLookupIndex1786300000000().up(runner);
+
+ const after = (await ds.query<{ detail: string }[]>(countQuery)).map(r => r.detail).join(' ');
+ expect(after).toContain('IDX_webhook_delivery_failures_delivery');
+ expect(after).not.toContain('SCAN');
+ });
+});
diff --git a/src/modules/queue/processors/webhook.processor.spec.ts b/src/modules/queue/processors/webhook.processor.spec.ts
index 9ff5b0b3d..e7ef5f45a 100644
--- a/src/modules/queue/processors/webhook.processor.spec.ts
+++ b/src/modules/queue/processors/webhook.processor.spec.ts
@@ -23,7 +23,7 @@ jest.mock('undici', () => {
describe('WebhookProcessor', () => {
let processor: WebhookProcessor;
let repo: { update: jest.Mock };
- let failureRepo: { insert: jest.Mock };
+ let failureRepo: { insert: jest.Mock; count: jest.Mock };
let hookManager: { execute: jest.Mock };
let configService: { get: jest.Mock };
let mockFetch: jest.Mock;
@@ -54,7 +54,24 @@ describe('WebhookProcessor', () => {
beforeEach(() => {
repo = { update: jest.fn().mockResolvedValue({ affected: 1 }) };
- failureRepo = { insert: jest.fn().mockResolvedValue({}) };
+ // Stateful like the real table: the recorder counts existing rows for the delivery before it
+ // inserts, so a constant would leave that guard unexercised here and let a duplicated row pass.
+ const insertedFailures: Array<{ webhookId?: string; idempotencyKey?: string | null }> = [];
+ failureRepo = {
+ insert: jest.fn().mockImplementation((rowToInsert: { webhookId?: string; idempotencyKey?: string | null }) => {
+ insertedFailures.push(rowToInsert);
+ return Promise.resolve({});
+ }),
+ count: jest
+ .fn()
+ .mockImplementation((opts: { where: { webhookId?: string; idempotencyKey?: string } }) =>
+ Promise.resolve(
+ insertedFailures.filter(
+ r => r.webhookId === opts.where.webhookId && r.idempotencyKey === opts.where.idempotencyKey,
+ ).length,
+ ),
+ ),
+ };
hookManager = { execute: jest.fn().mockResolvedValue({ continue: true, data: {} }) };
configService = { get: jest.fn((key: string, def?: unknown) => (key === 'webhook.timeout' ? 25000 : def)) };
processor = new WebhookProcessor(
diff --git a/src/modules/queue/processors/webhook.processor.ts b/src/modules/queue/processors/webhook.processor.ts
index 766fe66d6..2b44c376f 100644
--- a/src/modules/queue/processors/webhook.processor.ts
+++ b/src/modules/queue/processors/webhook.processor.ts
@@ -214,7 +214,7 @@ export class WebhookProcessor extends WorkerHost {
},
{ sessionId, source: 'WebhookProcessor' },
);
- await recordWebhookDeliveryFailure(this.failureRepository, this.logger, {
+ const recorded = await recordWebhookDeliveryFailure(this.failureRepository, this.logger, {
webhookId,
sessionId,
event,
@@ -225,7 +225,9 @@ export class WebhookProcessor extends WorkerHost {
lastStatusCode: statusCodeFromError(errorMessage),
lastError: clientError,
});
- incrementWebhookDeliveryFailures();
+ if (recorded) {
+ incrementWebhookDeliveryFailures();
+ }
}
}
@@ -270,7 +272,7 @@ export class WebhookProcessor extends WorkerHost {
{ sessionId, source: 'WebhookProcessor' },
);
- await recordWebhookDeliveryFailure(this.failureRepository, this.logger, {
+ const recorded = await recordWebhookDeliveryFailure(this.failureRepository, this.logger, {
webhookId,
sessionId,
event,
@@ -281,6 +283,8 @@ export class WebhookProcessor extends WorkerHost {
lastStatusCode: null, // no HTTP exchange completed on the stalled attempts
lastError: error.message,
});
- incrementWebhookDeliveryFailures();
+ if (recorded) {
+ incrementWebhookDeliveryFailures();
+ }
}
}
diff --git a/src/modules/webhook/entities/webhook-delivery-failure.entity.ts b/src/modules/webhook/entities/webhook-delivery-failure.entity.ts
index 0d0d0bab2..2839c4e06 100644
--- a/src/modules/webhook/entities/webhook-delivery-failure.entity.ts
+++ b/src/modules/webhook/entities/webhook-delivery-failure.entity.ts
@@ -4,13 +4,17 @@ import { Entity, PrimaryGeneratedColumn, Column, CreateDateColumn, Index } from
* A durable record of a webhook delivery that exhausted all of its retries. The queued path (BullMQ)
* otherwise only leaves a `failed` job that the queue evicts after a day, and the direct fallback path
* swallowed the final error entirely — so a receiver outage longer than the retry window silently lost
- * events with no operator-visible trail. Each terminal failure is appended here (see
- * `recordWebhookDeliveryFailure`) and surfaced via the ADMIN `GET /webhooks/delivery-failures` endpoint.
+ * events with no operator-visible trail. Each lost delivery is appended here once (see
+ * `recordWebhookDeliveryFailure`, which skips a delivery it has already recorded so a replayed one is
+ * not reported several times) and surfaced via the ADMIN `GET /webhooks/delivery-failures` endpoint.
*
* Lives on the `data` connection (auto-loaded by the webhook entity glob).
*/
@Entity('webhook_delivery_failures')
@Index('IDX_webhook_delivery_failures_sessionId', ['sessionId'])
+// Backs the before-insert duplicate lookup that keeps one row per lost delivery rather than one per
+// reconciler replay. See AddWebhookDeliveryFailureLookupIndex1786300000000.
+@Index('IDX_webhook_delivery_failures_delivery', ['webhookId', 'idempotencyKey'])
export class WebhookDeliveryFailure {
@PrimaryGeneratedColumn('uuid')
id!: string;
diff --git a/src/modules/webhook/utils/deliver-once.ts b/src/modules/webhook/utils/deliver-once.ts
index dec98a4f2..acf475433 100644
--- a/src/modules/webhook/utils/deliver-once.ts
+++ b/src/modules/webhook/utils/deliver-once.ts
@@ -35,16 +35,17 @@ export async function postWebhookPayload(
/**
* Record a terminal webhook delivery failure (all retries exhausted) to the durable table. Shared
* wrapper so both paths write the identical row shape. Best-effort: never throws back into the
- * delivery result (the caller's semantics depend on that).
+ * delivery result (the caller's semantics depend on that). Returns false when an identical failure
+ * was already recorded, so the caller can keep the failure metric in step with the table.
*/
export async function recordTerminalFailure(
failureRepository: Repository<WebhookDeliveryFailure>,
logger: LoggerService,
input: Omit<Parameters<typeof recordWebhookDeliveryFailure>[2], 'lastStatusCode' | 'lastError'> & { error: unknown },
-): Promise<void> {
+): Promise<boolean> {
const { error, ...row } = input;
const errMessage = redactSsrfError(error);
- await recordWebhookDeliveryFailure(failureRepository, logger, {
+ return recordWebhookDeliveryFailure(failureRepository, logger, {
...row,
lastStatusCode: statusCodeFromError(errMessage),
lastError: errMessage,
diff --git a/src/modules/webhook/utils/record-delivery-failure.spec.ts b/src/modules/webhook/utils/record-delivery-failure.spec.ts
index 8c546b41e..005d3ddd3 100644
--- a/src/modules/webhook/utils/record-delivery-failure.spec.ts
+++ b/src/modules/webhook/utils/record-delivery-failure.spec.ts
@@ -27,23 +27,53 @@ describe('recordWebhookDeliveryFailure', () => {
lastError: 'HTTP 503: x',
};
+ const repoWith = (insert: jest.Mock, existing = 0): Repository<WebhookDeliveryFailure> =>
+ ({ insert, count: jest.fn().mockResolvedValue(existing) }) as unknown as Repository<WebhookDeliveryFailure>;
+
it('inserts the failure record, defaulting a missing lastStatusCode to null', async () => {
const insert = jest.fn().mockResolvedValue({});
- const repo = { insert } as unknown as Repository<WebhookDeliveryFailure>;
const logger = { error: jest.fn() };
- await recordWebhookDeliveryFailure(repo, logger, { ...input, lastStatusCode: undefined });
+ await expect(
+ recordWebhookDeliveryFailure(repoWith(insert), logger, { ...input, lastStatusCode: undefined }),
+ ).resolves.toBe(true);
expect(insert).toHaveBeenCalledWith(expect.objectContaining({ webhookId: 'wh-1', lastStatusCode: null }));
expect(logger.error).not.toHaveBeenCalled();
});
+ it('skips a delivery it has already recorded, so one lost event is one row', async () => {
+ // The reconciler replays a stranded delivery once per sweep until its budget is spent, and each
+ // failed replay lands here with the SAME idempotency key.
+ const insert = jest.fn().mockResolvedValue({});
+ const logger = { error: jest.fn() };
+
+ await expect(recordWebhookDeliveryFailure(repoWith(insert, 1), logger, input)).resolves.toBe(false);
+
+ expect(insert).not.toHaveBeenCalled();
+ expect(logger.error).not.toHaveBeenCalled();
+ });
+
+ it('still records a failure that carries no idempotency key', async () => {
+ // Control: without a key there is no identity to dedupe on, so the guard must not swallow the
+ // row. Otherwise "skips a duplicate" would be satisfied by a helper that stopped inserting.
+ const insert = jest.fn().mockResolvedValue({});
+ const logger = { error: jest.fn() };
+
+ await expect(
+ recordWebhookDeliveryFailure(repoWith(insert, 1), logger, { ...input, idempotencyKey: undefined }),
+ ).resolves.toBe(true);
+
+ expect(insert).toHaveBeenCalled();
+ });
+
it('swallows a repository error so a logging hiccup cannot re-poison the delivery', async () => {
const insert = jest.fn().mockRejectedValue(new Error('db down'));
- const repo = { insert } as unknown as Repository<WebhookDeliveryFailure>;
const logger = { error: jest.fn() };
- await expect(recordWebhookDeliveryFailure(repo, logger, input)).resolves.toBeUndefined();
+ // Reported as recorded even though the row was lost: the delivery really did fail, and the
+ // caller's failure metric must count it rather than hide it behind a database problem.
+ await expect(recordWebhookDeliveryFailure(repoWith(insert), logger, input)).resolves.toBe(true);
expect(logger.error).toHaveBeenCalled();
});
});
diff --git a/src/modules/webhook/utils/record-delivery-failure.ts b/src/modules/webhook/utils/record-delivery-failure.ts
index 523ce7c07..ee9a1f921 100644
--- a/src/modules/webhook/utils/record-delivery-failure.ts
+++ b/src/modules/webhook/utils/record-delivery-failure.ts
@@ -34,14 +34,30 @@ export async function recordWebhookDeliveryFailure(
repo: Repository<WebhookDeliveryFailure>,
logger: ErrorLogger,
input: WebhookDeliveryFailureInput,
-): Promise<void> {
+): Promise<boolean> {
try {
+ // One row per lost delivery, not one per attempt. The reconciler replays a pending outbox row
+ // up to its budget and every failed replay arrives here, so without this guard a single lost
+ // event is reported to the operator as several and counted that many times in the failure
+ // metric. An absent idempotencyKey carries no identity to dedupe on, so it is always appended.
+ if (input.idempotencyKey) {
+ const existing = await repo.count({
+ where: { webhookId: input.webhookId, idempotencyKey: input.idempotencyKey },
+ });
+ if (existing > 0) {
+ return false;
+ }
+ }
await repo.insert({ ...input, lastStatusCode: input.lastStatusCode ?? null });
+ return true;
} catch (err) {
logger.error(
'Failed to persist webhook delivery-failure record',
err instanceof Error ? err.message : String(err),
{ webhookId: input.webhookId, deliveryId: input.deliveryId, action: 'webhook_failure_record_error' },
);
+ // The delivery really did fail; only the bookkeeping did. Report it as recorded so the metric
+ // still counts the loss rather than hiding it behind a database problem.
+ return true;
}
}
diff --git a/src/modules/webhook/webhook-delivery.service.spec.ts b/src/modules/webhook/webhook-delivery.service.spec.ts
index 60299310c..237c2cd9b 100644
--- a/src/modules/webhook/webhook-delivery.service.spec.ts
+++ b/src/modules/webhook/webhook-delivery.service.spec.ts
@@ -65,8 +65,24 @@ describe('WebhookDeliveryService', () => {
update: jest.fn().mockResolvedValue({ affected: 1 }),
};
+ // Backed by the rows it accepts, not a constant: the dedupe guard reads count() before every
+ // insert, and a jest.fn() returning undefined would make the guard silently inert here while
+ // still passing every assertion.
+ const insertedFailures: Array<{ webhookId?: string; idempotencyKey?: string | null }> = [];
failureRepository = {
- insert: jest.fn().mockResolvedValue({}),
+ insert: jest.fn().mockImplementation((rowToInsert: { webhookId?: string; idempotencyKey?: string | null }) => {
+ insertedFailures.push(rowToInsert);
+ return Promise.resolve({});
+ }),
+ count: jest
+ .fn()
+ .mockImplementation((opts: { where: { webhookId?: string; idempotencyKey?: string } }) =>
+ Promise.resolve(
+ insertedFailures.filter(
+ r => r.webhookId === opts.where.webhookId && r.idempotencyKey === opts.where.idempotencyKey,
+ ).length,
+ ),
+ ),
find: jest.fn().mockResolvedValue([]),
delete: jest.fn().mockResolvedValue({ affected: 0 }),
};
@@ -631,6 +647,52 @@ describe('WebhookDeliveryService', () => {
).resolves.toBe('delivered');
});
+ it('reports a plugin-cancelled dispatch as cancelled, recording no failure and sending nothing', async () => {
+ // A before-hook that stops the dispatch is a deliberate drop. Reported as 'failed' it looked
+ // identical to a lost delivery, so the reconciler replayed it once per sweep until the budget
+ // ran out and then marked it terminally lost against a failure row nothing ever wrote.
+ const webhook = createMockWebhook({ events: ['message.received'], retryCount: 1 });
+ (hookManager.execute as jest.Mock).mockResolvedValue({ continue: false, data: {} });
+ const failuresBefore = getWebhookDeliveryFailuresTotal();
+ mockFetch.mockReset();
+
+ await expect(
+ service.redeliver(webhook, 'sess-1', 'message.received', 'cancelled-key', { from: '[email protected]' }),
+ ).resolves.toBe('cancelled');
+
+ expect(mockFetch).not.toHaveBeenCalled();
+ expect(failureRepository.insert).not.toHaveBeenCalled();
+ expect(getWebhookDeliveryFailuresTotal()).toBe(failuresBefore);
+ });
+
+ it('records one failure row per lost delivery however many times the reconciler replays it', async () => {
+ // The reconciler leaves a failed row pending and sweeps it again until the attempt budget is
+ // spent. Every replay reaching the dead-letter table turned one lost event into as many rows
+ // and as many increments of the loss metric as the budget allowed.
+ 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'));
+ const failuresBefore = getWebhookDeliveryFailuresTotal();
+
+ for (let sweep = 0; sweep < 3; sweep++) {
+ await expect(
+ service.redeliver(webhook, 'sess-1', 'message.received', 'stranded-key', { from: '[email protected]' }),
+ ).resolves.toBe('failed');
+ }
+
+ expect(failureRepository.insert).toHaveBeenCalledTimes(1);
+ expect(getWebhookDeliveryFailuresTotal()).toBe(failuresBefore + 1);
+
+ // Control: a genuinely different delivery must still be recorded, or the assertion above is
+ // satisfied by a guard that suppresses every row after the first.
+ await expect(
+ service.redeliver(webhook, 'sess-1', 'message.received', 'other-key', { from: '[email protected]' }),
+ ).resolves.toBe('failed');
+ expect(failureRepository.insert).toHaveBeenCalledTimes(2);
+ expect(getWebhookDeliveryFailuresTotal()).toBe(failuresBefore + 2);
+ });
+
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 6ba2fd7b7..898382b7d 100644
--- a/src/modules/webhook/webhook-delivery.service.ts
+++ b/src/modules/webhook/webhook-delivery.service.ts
@@ -63,9 +63,10 @@ const DEFAULT_WEBHOOK_SHUTDOWN_DRAIN_MS = 5000;
/**
* 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.
+ * event from a dead-lettered one. 'cancelled' is a plugin suppressing the dispatch on purpose: it
+ * is terminal like 'delivered' and must never be replayed, but nothing left the process.
*/
-export type WebhookDeliveryOutcome = 'delivered' | 'enqueued' | 'failed';
+export type WebhookDeliveryOutcome = 'delivered' | 'enqueued' | 'cancelled' | 'failed';
interface DispatchEventContext {
sessionId: string;
@@ -255,7 +256,7 @@ export class WebhookDeliveryService implements OnModuleInit, OnModuleDestroy {
): Promise<void> {
const { sessionId, event } = ctx;
const lastError = redactSsrfError(error, this.logger, 'webhook dispatch');
- await recordWebhookDeliveryFailure(this.failureRepository, this.logger, {
+ const recorded = await recordWebhookDeliveryFailure(this.failureRepository, this.logger, {
webhookId: webhook.id,
sessionId,
event,
@@ -266,7 +267,9 @@ export class WebhookDeliveryService implements OnModuleInit, OnModuleDestroy {
lastStatusCode: null,
lastError,
});
- incrementWebhookDeliveryFailures();
+ if (recorded) {
+ incrementWebhookDeliveryFailures();
+ }
try {
await this.hookManager.execute(
'webhook:error',
@@ -297,7 +300,7 @@ export class WebhookDeliveryService implements OnModuleInit, OnModuleDestroy {
deliveryId: string,
idempotencyKey: string,
ctx: DispatchEventContext,
- ): Promise<{ finalPayload: WebhookPayload; body: string; headers: Record<string, string> } | null> {
+ ): Promise<{ finalPayload: WebhookPayload; body: string; headers: Record<string, string> } | 'cancelled' | null> {
const { sessionId, event, baseData } = ctx;
try {
const payload: WebhookPayload = {
@@ -325,7 +328,7 @@ export class WebhookDeliveryService implements OnModuleInit, OnModuleDestroy {
webhookId: webhook.id,
action: 'webhook_cancelled_by_plugin',
});
- return null;
+ return 'cancelled';
}
// Null/undefined hook results mean "no override", matching an object without payload.
@@ -415,8 +418,14 @@ export class WebhookDeliveryService implements OnModuleInit, OnModuleDestroy {
ctx: DispatchEventContext,
): Promise<WebhookDeliveryOutcome> {
const preflight = await this.preflightDelivery(webhook, deliveryId, idempotencyKey, ctx);
+ if (preflight === 'cancelled') {
+ // A plugin suppressed this dispatch deliberately. There is no failure to record and nothing
+ // to retry: reporting it as failed made the reconciler replay a deliberately dropped event
+ // until the budget ran out, then mark it lost against a failure row that never existed.
+ return 'cancelled';
+ }
if (!preflight) {
- // Preflight records its own undelivered row and returns null; nothing left the process.
+ // The remaining bail-outs record their own undelivered row before returning null.
return 'failed';
}
const { finalPayload, body, headers } = preflight;
@@ -738,7 +747,7 @@ export class WebhookDeliveryService implements OnModuleInit, OnModuleDestroy {
}
// All direct-path retries exhausted — persist a durable failure record before giving up, mirroring
// the queued processor's final-attempt path so the queue-disabled path isn't a blind spot.
- await recordTerminalFailure(this.failureRepository, this.logger, {
+ const recorded = await recordTerminalFailure(this.failureRepository, this.logger, {
webhookId: webhook.id,
sessionId: payload.sessionId,
event: payload.event,
@@ -748,7 +757,9 @@ export class WebhookDeliveryService implements OnModuleInit, OnModuleDestroy {
attempts: attempt,
error,
});
- incrementWebhookDeliveryFailures();
+ if (recorded) {
+ incrementWebhookDeliveryFailures();
+ }
throw error;
}
}
diff --git a/src/modules/webhook/webhook-reconciler.service.spec.ts b/src/modules/webhook/webhook-reconciler.service.spec.ts
index 6d9188ada..23b6cf0ee 100644
--- a/src/modules/webhook/webhook-reconciler.service.spec.ts
+++ b/src/modules/webhook/webhook-reconciler.service.spec.ts
@@ -95,6 +95,19 @@ describe('WebhookReconcilerService', () => {
expect(stats).toMatchObject({ replayed: 1, failed: 0 });
});
+ it('retires the row when a plugin cancelled the dispatch, instead of replaying it to death', async () => {
+ // A cancelled dispatch is a deliberate drop, not a loss. Reported as 'failed' it was replayed
+ // once per sweep until the budget ran out and then marked terminally lost, pointing operators
+ // at a delivery-failure row that was never written.
+ outbox.findStale.mockResolvedValue([row({ attempts: 1 })]);
+ delivery.redeliver.mockResolvedValue('cancelled');
+
+ 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'));
diff --git a/src/modules/webhook/webhook-reconciler.service.ts b/src/modules/webhook/webhook-reconciler.service.ts
index 834540ded..b1360f184 100644
--- a/src/modules/webhook/webhook-reconciler.service.ts
+++ b/src/modules/webhook/webhook-reconciler.service.ts
@@ -127,6 +127,8 @@ export class WebhookReconcilerService implements OnModuleInit, OnModuleDestroy {
stats.failed++;
continue;
}
+ // 'delivered', 'enqueued' and 'cancelled' all retire the row: the delivery either reached a
+ // durable owner or a plugin dropped it on purpose. Only 'failed' is worth another sweep.
await this.outbox.close(row.webhookId, row.idempotencyKey, 'dispatched');
stats.replayed++;
} catch (error) {