Free, Open Source, Self-Hosted WhatsApp API Gateway
TypeScript apibotgatewayself-hostedwhatsappwhatsapp-apiwhatsapp-automationwhatsapp-botwhatsapp-gatewaywhatsapp-gateway-apiwhatsapp-webwhatsapp-web-api
fix(integration): stop an operator redrive at its next row on shutdown
Yudhi Armyndharisfe6b12d88096
diff --git a/CHANGELOG.md b/CHANGELOG.mdindex b474f8892..446e2bf98 100644--- a/CHANGELOG.md+++ b/CHANGELOG.md@@ -49,6 +49,7 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0- Stop a dashboard Logs export from downloading rows after sign-out when its last page was throttled.- Stop reopening a just-saved dashboard template from loading its old values, which a second save wrote back.- Stop an operator webhook redrive at its next row on shutdown.+- Stop an operator ingress dead-letter redrive at its next row on shutdown, leaving the rows it did not reach unchanged.- Run a plugin's `onDisable` once when shutdown, uninstall or an update overlaps a disable already in progress.- Answer `503` and keep the previous version when shutdown begins before an update of a plugin the operator switched on has applied.- Disable plugins whose enable is still running at shutdown, after the running ones, and refuse new plugin enables during teardown.diff --git a/src/modules/integration/redrive.service.spec.ts b/src/modules/integration/redrive.service.spec.tsindex 37d571b6e..a1b328d76 100644--- a/src/modules/integration/redrive.service.spec.ts+++ b/src/modules/integration/redrive.service.spec.ts@@ -3,6 +3,7 @@ import { IngressEnqueueService } from './ingress-enqueue.service';import { IntegrationDeliveryFailure } from './entities/integration-delivery-failure.entity';import { IngressEvent } from './entities/ingress-event.entity';import { Repository } from 'typeorm';+import { INGRESS_DISPATCH_TIMEOUT_MS } from './integration.constants';describe('RedriveService', () => {let repo: jest.Mocked<Partial<Repository<IntegrationDeliveryFailure>>>;@@ -71,6 +72,7 @@ describe('RedriveService', () => {payload: { headers: {}, query: {}, body: '{}', rawBody: '{}' },},'redrive:f1',+ expect.any(AbortSignal),);expect(repo.update).toHaveBeenCalledWith({ id: 'f1' }, { redriven: true });expect(repo.update).toHaveBeenCalledWith({ id: 'f2' }, { redriven: true });@@ -214,8 +216,94 @@ describe('RedriveService', () => {expect(ingressEnqueue.enqueue).toHaveBeenCalledWith(expect.objectContaining({ deliveryId: 'f3', sessionId: undefined }),'redrive:f3',+ expect.any(AbortSignal),);// A legacy row without a deliveryId predates persist-before-ack — there is no event row to retire.expect(events.update).not.toHaveBeenCalled();});++ describe('shutdown', () => {+ const failure = (id: string, deliveryId: string) => ({+ id,+ direction: 'inbound',+ pluginId: 'p',+ instanceId: 'i',+ deliveryId,+ payload: { route: 'chatwoot', ingress: { headers: {}, query: {}, body: '{}', rawBody: '{}' } },+ sessionId: 's',+ redriven: false,+ attempts: 0,+ });+ const tick = () => new Promise<void>(resolve => setImmediate(resolve));++ it('stops at the next row and leaves the rows it did not reach open and unchanged', async () => {+ (repo.find as jest.Mock).mockResolvedValue([failure('f1', 'd1'), failure('f2', 'd2'), failure('f3', 'd3')]);+ (repo.count as jest.Mock).mockResolvedValue(2);+ let finishFirst!: () => void;+ (ingressEnqueue.enqueue as jest.Mock).mockImplementationOnce(+ () => new Promise(resolve => (finishFirst = () => resolve({ outcome: 'queued' }))),+ );+ const svc = makeSvc();+ const running = svc.redriveInstance('p', 'i', null);+ while (!finishFirst) await tick();++ const destroyed = svc.onModuleDestroy();+ finishFirst();++ expect(await running).toEqual({ redriven: 1, remaining: 2, batchSize: 100 });+ await destroyed;+ expect(ingressEnqueue.enqueue).toHaveBeenCalledTimes(1);+ expect(repo.update).toHaveBeenCalledTimes(1);+ expect(repo.update).toHaveBeenCalledWith({ id: 'f1' }, { redriven: true });+ });++ it('leaves a row open and unchanged when its enqueue is refused because shutdown began', async () => {+ (repo.find as jest.Mock).mockResolvedValue([failure('f1', 'd1'), failure('f2', 'd2')]);+ (repo.count as jest.Mock).mockResolvedValue(2);+ const svc = makeSvc();+ let destroyed: Promise<void> | undefined;+ (ingressEnqueue.enqueue as jest.Mock).mockImplementationOnce(() => {+ destroyed = svc.onModuleDestroy();+ return Promise.reject(new Error('The operation was aborted'));+ });++ expect(await svc.redriveInstance('p', 'i', null)).toEqual({ redriven: 0, remaining: 2, batchSize: 100 });+ await destroyed;+ expect(ingressEnqueue.enqueue).toHaveBeenCalledTimes(1);+ expect(repo.update).not.toHaveBeenCalled();+ expect(events.update).not.toHaveBeenCalled();+ });++ it('still surfaces an enqueue failure that is not a shutdown', async () => {+ (repo.find as jest.Mock).mockResolvedValue([failure('f1', 'd1')]);+ (ingressEnqueue.enqueue as jest.Mock).mockRejectedValueOnce(new Error('database is gone'));++ await expect(makeSvc().redriveInstance('p', 'i', null)).rejects.toThrow('database is gone');+ });++ it('waits at most the dispatch timeout for a replay still in hand', async () => {+ jest.useFakeTimers();+ try {+ (repo.find as jest.Mock).mockResolvedValue([failure('f1', 'd1')]);+ (ingressEnqueue.enqueue as jest.Mock).mockReturnValueOnce(new Promise(() => undefined));+ const svc = makeSvc();+ void svc.redriveInstance('p', 'i', null);+ await jest.advanceTimersByTimeAsync(0);+ let settled = false;+ const destroyed = svc.onModuleDestroy().then(() => (settled = true));++ await jest.advanceTimersByTimeAsync(INGRESS_DISPATCH_TIMEOUT_MS - 1);+ expect(settled).toBe(false);+ await jest.advanceTimersByTimeAsync(1);+ await destroyed;+ expect(settled).toBe(true);+ } finally {+ jest.useRealTimers();+ }+ });++ it('has nothing to wait for when no redrive is running', async () => {+ await expect(makeSvc().onModuleDestroy()).resolves.toBeUndefined();+ });+ });});diff --git a/src/modules/integration/redrive.service.ts b/src/modules/integration/redrive.service.tsindex d6d4fce12..c069b0579 100644--- a/src/modules/integration/redrive.service.ts+++ b/src/modules/integration/redrive.service.ts@@ -1,4 +1,4 @@-import { Injectable } from '@nestjs/common';+import { Injectable, OnModuleDestroy } from '@nestjs/common';import { InjectRepository } from '@nestjs/typeorm';import { Repository } from 'typeorm';import { IntegrationDeliveryFailure } from './entities/integration-delivery-failure.entity';@@ -6,6 +6,8 @@ import { IngressEvent } from './entities/ingress-event.entity';import { IngressEnqueueService } from './ingress-enqueue.service';import { IngressJobData } from '../queue/processors/ingress.processor';import { KeyedAsyncLock } from './ordering-lock';+import { INGRESS_DISPATCH_TIMEOUT_MS } from './integration.constants';+import { createLogger } from '../../common/services/logger.service';const REDRIVE_BATCH_SIZE = 100;@@ -20,8 +22,12 @@ interface StoredDlqPayload {}@Injectable()-export class RedriveService {+export class RedriveService implements OnModuleDestroy {+ private readonly logger = createLogger('IntegrationRedrive');private readonly lock = new KeyedAsyncLock();+ // Aborted on destroy: a batch in progress takes no further row.+ private readonly stop = new AbortController();+ private readonly inFlight = new Set<Promise<unknown>>();constructor(@InjectRepository(IntegrationDeliveryFailure, 'data') private readonly repo: Repository<IntegrationDeliveryFailure>,@@ -29,14 +35,42 @@ export class RedriveService {private readonly ingressEnqueue: IngressEnqueueService,) {}+ /**+ * A redrive runs inside an admitted HTTP request, which shutdown lets finish, and nothing else waits+ * for it: left alone it would go on replaying while the plugins are disabled and the database closes,+ * raising the attempts of rows no live plugin ever saw. Stop at the next row and wait for the replay+ * in hand, as the webhook redrive and the ingress reconciler do. Rows not reached stay open and are+ * counted in `remaining`.+ */+ async onModuleDestroy(): Promise<void> {+ this.stop.abort();+ if (this.inFlight.size === 0) return;+ let timer: NodeJS.Timeout | undefined;+ const settled = await Promise.race([+ Promise.allSettled([...this.inFlight]).then(() => true),+ new Promise<false>(resolve => (timer = setTimeout(resolve, INGRESS_DISPATCH_TIMEOUT_MS, false))),+ ]);+ clearTimeout(timer);+ if (!settled) {+ this.logger.warn('Ingress redrive still running at shutdown; continuing without it', {+ waitMs: INGRESS_DISPATCH_TIMEOUT_MS,+ action: 'ingress_redrive_shutdown_timeout',+ });+ }+ }+redriveInstance(pluginId: string,instanceId: string,sessionIdFilter: string | null,): Promise<{ redriven: number; remaining: number; batchSize: number }> {- return this.lock.run(`redrive:${pluginId}:${instanceId}`, () =>+ const run = this.lock.run(`redrive:${pluginId}:${instanceId}`, () =>this.redriveBatch(pluginId, instanceId, sessionIdFilter),);+ this.inFlight.add(run);+ const forget = () => void this.inFlight.delete(run);+ run.then(forget, forget);+ return run;}private async redriveBatch(@@ -61,22 +95,33 @@ export class RedriveService {let redriven = 0;for (const row of rows) {+ if (this.stop.signal.aborted) break;const stored = (row.payload ?? {}) as StoredDlqPayload;// Re-mint a jobId so BullMQ accepts the replay even if the original jobId lingers.const jobId = `redrive:${row.id}`;- const { outcome, error } = await this.ingressEnqueue.enqueue(- {- pluginId,- instanceId,- route: stored.route ?? '',- method: stored.method ?? 'POST',- deliveryId: row.deliveryId ?? row.id,- sessionId: row.sessionId ?? undefined,- providerConversationId: stored.providerConversationId,- payload: stored.ingress as IngressJobData['payload'],- },- jobId,- );+ // Given the stop signal, enqueue() throws instead of dispatching inline once it has aborted: the+ // row is left open and unchanged, since the plugin may already be torn down.+ const result = await this.ingressEnqueue+ .enqueue(+ {+ pluginId,+ instanceId,+ route: stored.route ?? '',+ method: stored.method ?? 'POST',+ deliveryId: row.deliveryId ?? row.id,+ sessionId: row.sessionId ?? undefined,+ providerConversationId: stored.providerConversationId,+ payload: stored.ingress as IngressJobData['payload'],+ },+ jobId,+ this.stop.signal,+ )+ .catch(err => {+ if (this.stop.signal.aborted) return undefined;+ throw err;+ });+ if (!result) break;+ const { outcome, error } = result;// Only retire the DLQ row once the replay was actually accepted (queued) or delivered. A swallowed// inline-dispatch failure ('failed') leaves the row redriven=false so it stays redrivable, instead// of silently marking it handled and permanently losing the event.