Skip to content

Free, Open Source, Self-Hosted WhatsApp API Gateway

fix(integration): keep the retention hand-off moving past a deferred run or failing row (#1838)

Yudhi Armyndharis98611962b88a
diff --git a/CHANGELOG.md b/CHANGELOG.md
index 3f340cee6..ebc8fbe96 100644
--- a/CHANGELOG.md
+++ b/CHANGELOG.md
@@ -28,6 +28,8 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0
### Fixed
+- Run the daily ingress retention hand-off after a reconcile sweep in progress instead of skipping it.
+- Try each failing ingress retention hand-off row once per run instead of stopping at the first batch of them.
- Retire the ingress replay sweep's duplicate dead letter when it races another dead-letter write, and stop logging an event a redrive delivered meanwhile as dead-lettered.
- Fall back instead of hanging when an ingress, webhook or infra status queue call runs before Redis has ever connected.
- Drop whatsapp-web.js inbound media over `MEDIA_DOWNLOAD_MAX_BYTES` in the page when the sender understates its size.
diff --git a/src/modules/integration/ingress-reconciler.service.ts b/src/modules/integration/ingress-reconciler.service.ts
index 843f8eb65..305af6fc1 100644
--- a/src/modules/integration/ingress-reconciler.service.ts
+++ b/src/modules/integration/ingress-reconciler.service.ts
@@ -1,7 +1,7 @@
import { Injectable, OnModuleDestroy, OnModuleInit } from '@nestjs/common';
import { isUUID } from 'class-validator';
import { InjectRepository } from '@nestjs/typeorm';
-import { IsNull, LessThan, Not, Repository, UpdateResult } from 'typeorm';
+import { In, IsNull, LessThan, Not, Repository, UpdateResult } from 'typeorm';
import { IngressDispatchState, IngressEvent } from './entities/ingress-event.entity';
import { IntegrationDeliveryFailure } from './entities/integration-delivery-failure.entity';
import { PluginInstance } from './entities/plugin-instance.entity';
@@ -229,28 +229,43 @@ export class IngressReconcilerService implements OnModuleInit, OnModuleDestroy {
* retire the payload with a 'failed' mark, so the dedup-window prune never deletes an acknowledged
* delivery that was never dispatched: one stranded across downtime longer than the window, one of an
* instance disabled for that long, or any stranded row while the sweep is disabled. Same
- * DLQ-before-retire order as the replay budget path. A row whose writes fail stays 'pending' with its
- * payload, which the prune keeps, and is retried on the next run. Skipped while a sweep is running,
- * and stopped at the next row once shutdown begins, like a sweep.
+ * DLQ-before-retire order as the replay budget path. A row the run could not settle, because its
+ * hand-off threw or its stored payload reads back as null, is not fetched again in this run, so every
+ * row is fetched at most once per run; one still 'pending' keeps its payload, which the prune keeps,
+ * and the next run retries it. Once 10 batches' worth of rows could not be settled, the run stops with
+ * one warning, which bounds a run against a store that rejects every write. A row whose payload reads
+ * back as null never settles on its own: ten batches of them ahead of healthy rows hold those rows
+ * back on every run until an operator removes them. Waits for a running sweep rather than skipping
+ * the day's run; once shutdown begins, the wait ends with the sweep and the hand-off does nothing,
+ * and a running hand-off stops at the next row, like a sweep.
* A row whose instance or session was deleted, or whose queue job still owns the delivery, gets no
* dead letter. Returns the number of rows dead-lettered.
*/
async deadLetterAgedPending(cutoff: Date, batchSize = 100): Promise<number> {
- if (this.inFlight || this.stop.signal.aborted) return 0;
+ while (this.inFlight && !this.stop.signal.aborted) await this.inFlight;
+ if (this.stop.signal.aborted) return 0;
let settle!: () => void;
this.inFlight = new Promise(resolve => (settle = resolve));
let retired = 0;
+ const kept: string[] = [];
try {
for (;;) {
const rows = await this.events.find({
- where: { dispatchState: 'pending', createdAt: LessThan(cutoff), payload: Not(IsNull()) },
+ where: {
+ dispatchState: 'pending',
+ createdAt: LessThan(cutoff),
+ payload: Not(IsNull()),
+ ...(kept.length ? { id: Not(In(kept)) } : {}),
+ },
order: { createdAt: 'ASC' },
take: batchSize,
});
- let progressed = 0;
for (const row of rows) {
if (this.stop.signal.aborted) return retired;
- if (!hasPayload(row)) continue;
+ if (!hasPayload(row)) {
+ kept.push(row.id);
+ continue;
+ }
const meta = { pluginId: row.pluginId, instanceId: row.instanceId, deliveryId: row.providerDeliveryId };
try {
if (await this.ownerDeleted(row)) {
@@ -260,7 +275,6 @@ export class IngressReconcilerService implements OnModuleInit, OnModuleDestroy {
{ id: row.id, dispatchState: 'pending' },
{ dispatchState: 'failed', payload: null },
);
- progressed++;
this.logger.warn('Undispatched ingress event of a deleted instance or session dropped', {
...meta,
action: 'ingress_event_retention_dropped',
@@ -280,7 +294,6 @@ export class IngressReconcilerService implements OnModuleInit, OnModuleDestroy {
);
// As in reconcileRow: the job delivers it, so an inline-failure dead letter must close.
if (settled.affected) await this.retireOpenDeadLetters(row);
- progressed++;
continue;
}
const written = await this.ensureDeadLetterRow(
@@ -292,7 +305,6 @@ export class IngressReconcilerService implements OnModuleInit, OnModuleDestroy {
{ id: row.id, dispatchState: 'pending' },
{ dispatchState: 'failed', payload: null },
);
- progressed++;
if (written) await this.settleDeadLetter(row, written, marked);
if (!marked.affected) continue;
retired++;
@@ -301,6 +313,7 @@ export class IngressReconcilerService implements OnModuleInit, OnModuleDestroy {
action: 'ingress_event_retention_dead_lettered',
});
} catch (err) {
+ kept.push(row.id);
this.logger.error(
'Failed to dead-letter an undispatched ingress event; kept for the next run',
err instanceof Error ? err.message : String(err),
@@ -308,7 +321,14 @@ export class IngressReconcilerService implements OnModuleInit, OnModuleDestroy {
);
}
}
- if (rows.length < batchSize || progressed === 0) return retired;
+ if (rows.length < batchSize) return retired;
+ if (kept.length >= 10 * batchSize) {
+ this.logger.warn('Ingress retention hand-off stopped early; the remaining events wait for the next run', {
+ kept: kept.length,
+ action: 'ingress_event_retention_handoff_stopped',
+ });
+ return retired;
+ }
}
} finally {
this.inFlight = undefined;
diff --git a/src/modules/integration/integration-retention.service.spec.ts b/src/modules/integration/integration-retention.service.spec.ts
index 85636533e..ef437eb25 100644
--- a/src/modules/integration/integration-retention.service.spec.ts
+++ b/src/modules/integration/integration-retention.service.spec.ts
@@ -274,6 +274,7 @@ describe('IntegrationRetentionService.pruneOlderThan with undispatched events',
let resolveInstance: jest.Mock;
let existingJobState: jest.Mock;
let logError: jest.SpyInstance;
+ let logWarn: jest.SpyInstance;
const SESSION_ID = '11111111-1111-4111-8111-111111111111';
beforeEach(async () => {
@@ -299,7 +300,7 @@ describe('IntegrationRetentionService.pruneOlderThan with undispatched events',
{ resolve: resolveInstance } as unknown as PluginInstanceService,
);
service = new IntegrationRetentionService(events, failures, reconciler);
- jest.spyOn(LoggerService.prototype, 'warn').mockImplementation(() => undefined);
+ logWarn = jest.spyOn(LoggerService.prototype, 'warn').mockImplementation(() => undefined);
logError = jest.spyOn(LoggerService.prototype, 'error').mockImplementation(() => undefined);
});
@@ -628,7 +629,7 @@ describe('IntegrationRetentionService.pruneOlderThan with undispatched events',
expect((await events.find()).map(e => e.id)).toEqual(['stranded']);
});
- it('stops and keeps every row when no dead-letter write succeeds', async () => {
+ it('keeps every row when no dead-letter write succeeds', async () => {
for (let i = 0; i < 100; i++) await insertEvent(`f${i}`, {});
jest.spyOn(failures, 'save').mockRejectedValue(new Error('disk full'));
@@ -644,13 +645,114 @@ describe('IntegrationRetentionService.pruneOlderThan with undispatched events',
);
});
- it('keeps aged pending rows while a reconcile sweep holds the guard', async () => {
+ it('tries a row whose dead-letter write keeps failing once per run and hands off the rows behind it', async () => {
+ // A full batch of older rows whose write always fails, ahead of rows that hand off normally.
+ for (let i = 0; i < 100; i++) await insertEvent(`bad${i}`, { createdAt: daysAgo(9) });
+ for (let i = 0; i < 20; i++) await insertEvent(`ok${i}`, {});
+ const realSave = failures.save.bind(failures) as (
+ row: IntegrationDeliveryFailure,
+ ) => Promise<IntegrationDeliveryFailure>;
+ jest.spyOn(failures, 'save').mockImplementation(async row => {
+ const dlq = row as IntegrationDeliveryFailure;
+ if (dlq.deliveryId?.startsWith('d-bad')) throw new Error('row rejected');
+ return realSave(dlq);
+ });
+
+ await service.pruneOlderThan(7, 90);
+
+ expect(logError).toHaveBeenCalledTimes(100);
+ expect(await events.count({ where: { dispatchState: 'pending' } })).toBe(100);
+ expect(await events.count({ where: { dispatchState: 'failed' } })).toBe(20);
+ expect(await failures.count()).toBe(20);
+ });
+
+ it('stops a run once ten batches of rows could not be handed off', async () => {
+ for (let i = 0; i < 25; i++) await insertEvent(`f${i}`, {});
+ jest.spyOn(failures, 'save').mockRejectedValue(new Error('disk full'));
+
+ expect(await reconciler.deadLetterAgedPending(daysAgo(7), 2)).toBe(0);
+
+ expect(logError).toHaveBeenCalledTimes(20);
+ expect(await events.count({ where: { dispatchState: 'pending' } })).toBe(25);
+ expect(logWarn).toHaveBeenCalledWith(
+ 'Ingress retention hand-off stopped early; the remaining events wait for the next run',
+ expect.objectContaining({ kept: 20, action: 'ingress_event_retention_handoff_stopped' }),
+ );
+ });
+
+ it('passes over pending rows whose payload is unreadable and hands off the rows behind them', async () => {
+ await insertEvent('unreadable1', { createdAt: daysAgo(9) });
+ await insertEvent('unreadable2', { createdAt: daysAgo(9) });
await insertEvent('stranded', {});
- (reconciler as unknown as { inFlight?: Promise<void> }).inFlight = new Promise(() => undefined);
+ // A JSON null passes the payload IS NOT NULL filter but reads back as no payload.
+ await events.query(`UPDATE ingress_events SET payload = 'null' WHERE id LIKE 'unreadable%'`);
+ const find = events.find.bind(events);
+ let fetches = 0;
+ jest.spyOn(events, 'find').mockImplementation(opts => {
+ if (++fetches > 5) throw new Error('the hand-off keeps fetching the same rows');
+ return find(opts);
+ });
- const result = await service.pruneOlderThan(7, 90);
+ expect(await reconciler.deadLetterAgedPending(daysAgo(7), 2)).toBe(1);
+
+ expect(await events.findOneByOrFail({ id: 'stranded' })).toMatchObject({ dispatchState: 'failed', payload: null });
+ expect(await events.count({ where: { dispatchState: 'pending' } })).toBe(2);
+ });
+
+ // Stands in for a reconcile sweep holding the guard the hand-off shares with it.
+ const holdSweep = () => {
+ const guarded = reconciler as unknown as { inFlight?: Promise<void> };
+ let settle!: () => void;
+ guarded.inFlight = new Promise(resolve => (settle = resolve));
+ return () => {
+ guarded.inFlight = undefined;
+ settle();
+ };
+ };
+
+ // Resolves once the retention run has called the hand-off, with the hand-off's own promise.
+ const handOffCalled = () =>
+ new Promise<{ running: Promise<number> }>(resolve => {
+ const handOff = reconciler.deadLetterAgedPending.bind(reconciler);
+ jest.spyOn(reconciler, 'deadLetterAgedPending').mockImplementation((...args) => {
+ const running = handOff(...args);
+ resolve({ running });
+ return running;
+ });
+ });
+
+ it('waits for a running reconcile sweep, then hands off the aged pending rows', async () => {
+ await insertEvent('stranded', {});
+ const finishSweep = holdSweep();
+
+ const called = handOffCalled();
+ const pruned = service.pruneOlderThan(7, 90);
+ const { running } = await called;
+ const stateDuringSweep = await Promise.race([
+ running.then(() => 'returned'),
+ new Promise(resolve => setImmediate(resolve, 'waiting')),
+ ]);
+ const duringSweep = await events.findOneByOrFail({ id: 'stranded' });
+ finishSweep();
+ await pruned;
+
+ expect(stateDuringSweep).toBe('waiting');
+ expect(duringSweep.payload).not.toBeNull();
+ expect(await events.findOneByOrFail({ id: 'stranded' })).toMatchObject({ dispatchState: 'failed', payload: null });
+ expect(await failures.count()).toBe(1);
+ });
+
+ it('stops waiting for a running sweep once shutdown begins, and keeps the rows', async () => {
+ await insertEvent('stranded', {});
+ const finishSweep = holdSweep();
+
+ const called = handOffCalled();
+ const pruned = service.pruneOlderThan(7, 90);
+ await called;
+ const destroyed = reconciler.onModuleDestroy();
+ finishSweep();
+ await Promise.all([pruned, destroyed]);
- expect(result.events).toBe(0);
expect((await events.findOneByOrFail({ id: 'stranded' })).payload).not.toBeNull();
expect(await failures.count()).toBe(0);
});
diff --git a/src/modules/integration/integration-retention.service.ts b/src/modules/integration/integration-retention.service.ts
index 20b5c04ba..c0cd5da33 100644
--- a/src/modules/integration/integration-retention.service.ts
+++ b/src/modules/integration/integration-retention.service.ts
@@ -102,8 +102,9 @@ export class IntegrationRetentionService implements OnModuleInit, OnModuleDestro
if (failuresDays !== null) failuresCutoff.setDate(failuresCutoff.getDate() - failuresDays);
// DLQ first, so an undispatched event whose only dead letter just aged out is handed a fresh one.
// The dedup delete keeps every 'pending' row that still carries its payload, so it runs before the
- // hand-off, which can wait on an unreachable queue for its job-state lookup; the rows the hand-off
- // settles go on the next run. A failed step is logged and never blocks the next one.
+ // hand-off, which can wait on a running sweep or on an unreachable queue for its job-state lookup;
+ // the rows the hand-off settles go on the next run. A failed step is logged and never blocks the
+ // next one.
const logFailure = (step: string) => (err: unknown) => {
this.logger.error(
`Integration ingress retention: ${step} failed`,