Free, Open Source, Self-Hosted WhatsApp API Gateway
TypeScript apibotgatewayself-hostedwhatsappwhatsapp-apiwhatsapp-automationwhatsapp-botwhatsapp-gatewaywhatsapp-gateway-apiwhatsapp-webwhatsapp-web-api
fix(message): reap outbound rows stuck PENDING after a crash (#958)
Yudhi Armyndharis6702c6826479
diff --git a/src/modules/message/message.module.ts b/src/modules/message/message.module.tsindex 724ef35c2..9abbb7041 100644--- a/src/modules/message/message.module.ts+++ b/src/modules/message/message.module.ts@@ -3,6 +3,7 @@ import { TypeOrmModule } from '@nestjs/typeorm';import { MessageService } from './message.service';import { BulkMessageService } from './bulk-message.service';import { MessageTypeBackfillService } from './message-type-backfill.service';+import { PendingMessageReaperService } from './pending-message-reaper.service';import { MessageController } from './message.controller';import { SessionModule } from '../session/session.module';import { TemplateModule } from '../template/template.module';@@ -12,7 +13,7 @@ import { MessageBatch } from './entities/message-batch.entity';@Module({imports: [TypeOrmModule.forFeature([Message, MessageBatch], 'data'), SessionModule, TemplateModule],controllers: [MessageController],- providers: [MessageService, BulkMessageService, MessageTypeBackfillService],+ providers: [MessageService, BulkMessageService, MessageTypeBackfillService, PendingMessageReaperService],exports: [MessageService, BulkMessageService],})export class MessageModule {}diff --git a/src/modules/message/pending-message-reaper.service.spec.ts b/src/modules/message/pending-message-reaper.service.spec.tsnew file mode 100644index 000000000..b5d8924a1--- /dev/null+++ b/src/modules/message/pending-message-reaper.service.spec.ts@@ -0,0 +1,267 @@+import { DataSource, Repository } from 'typeorm';+import { Message, MessageDirection, MessageStatus } from './entities/message.entity';+import {+ PendingMessageReaperService,+ PendingMessageReaperOptions,+ resolvePendingMessageReaperOptions,+} from './pending-message-reaper.service';+import { HookManager } from '../../core/hooks';++const OPTS: PendingMessageReaperOptions = { intervalMs: 600_000, graceMs: 3_600_000, batchSize: 50 };++const hoursAgo = (h: number): Date => new Date(Date.now() - h * 3_600_000);+const minutesAgo = (m: number): Date => new Date(Date.now() - m * 60_000);++describe('PendingMessageReaperService.sweep', () => {+ let ds: DataSource;+ let messages: Repository<Message>;+ let execute: jest.Mock;+ let service: PendingMessageReaperService;+ let seq: number;++ beforeEach(async () => {+ seq = 0;+ ds = new DataSource({+ type: 'better-sqlite3',+ database: ':memory:',+ entities: [Message],+ synchronize: true,+ });+ await ds.initialize();+ messages = ds.getRepository(Message);+ execute = jest.fn().mockResolvedValue(undefined);+ service = new PendingMessageReaperService(messages, { execute } as unknown as HookManager);+ });++ 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 insertMessage = async (over: Record<string, unknown> = {}): Promise<string> => {+ const n = ++seq;+ await messages+ .createQueryBuilder()+ .insert()+ .values({+ id: `msg-${n}`,+ sessionId: 'sess-1',+ chatId: '[email protected]',+ from: 'me',+ to: '[email protected]',+ body: `hello ${n}`,+ type: 'text',+ direction: MessageDirection.OUTGOING,+ status: MessageStatus.PENDING,+ createdAt: hoursAgo(2),+ ...over,+ })+ .execute();+ return `msg-${n}`;+ };+ const stored = (id: string) => messages.findOneByOrFail({ id });+ const persistedCalls = () =>+ execute.mock.calls.filter(([event]) => event === 'message:persisted') as Array<+ [string, { sessionId: string; message: Message }, { sessionId: string; source: string }]+ >;++ it('fails a stale outgoing PENDING row, marks it reapedAt, and emits message:persisted', async () => {+ const id = await insertMessage();++ const stats = await service.sweep(OPTS);++ expect(stats).toEqual({ scanned: 1, reaped: 1, failed: 0 });+ const row = await stored(id);+ expect(row.status).toBe(MessageStatus.FAILED);+ expect(typeof (row.metadata as { reapedAt?: string }).reapedAt).toBe('string');++ expect(persistedCalls()).toHaveLength(1);+ const [event, payload, context] = persistedCalls()[0];+ expect(event).toBe('message:persisted');+ expect(payload.sessionId).toBe('sess-1');+ expect(payload.message.id).toBe(id);+ expect(payload.message.status).toBe(MessageStatus.FAILED);+ expect((payload.message.metadata as { reapedAt?: string }).reapedAt).toBeDefined();+ expect(context).toEqual({ sessionId: 'sess-1', source: 'PendingMessageReaperService' });+ });++ it('does not touch an outgoing PENDING row younger than the grace window', async () => {+ const id = await insertMessage({ createdAt: minutesAgo(10) });++ const stats = await service.sweep(OPTS);++ expect(stats).toEqual({ scanned: 0, reaped: 0, failed: 0 });+ expect((await stored(id)).status).toBe(MessageStatus.PENDING);+ expect(execute).not.toHaveBeenCalled();+ });++ it('never touches outgoing rows that already reached a post-pending state', async () => {+ const sent = await insertMessage({ status: MessageStatus.SENT });+ const failed = await insertMessage({ status: MessageStatus.FAILED });++ const stats = await service.sweep(OPTS);++ expect(stats).toEqual({ scanned: 0, reaped: 0, failed: 0 });+ expect((await stored(sent)).status).toBe(MessageStatus.SENT);+ expect((await stored(failed)).status).toBe(MessageStatus.FAILED);+ expect(execute).not.toHaveBeenCalled();+ });++ it('never touches incoming rows, even a stale PENDING one', async () => {+ const id = await insertMessage({ direction: MessageDirection.INCOMING });++ const stats = await service.sweep(OPTS);++ expect(stats).toEqual({ scanned: 0, reaped: 0, failed: 0 });+ expect((await stored(id)).status).toBe(MessageStatus.PENDING);+ expect(execute).not.toHaveBeenCalled();+ });++ it('bounds the sweep to the batch size, oldest first, and drains the rest on the next pass', async () => {+ const ids: string[] = [];+ for (const age of [5, 4, 3, 2, 1.5]) ids.push(await insertMessage({ createdAt: hoursAgo(age) }));+ const tight = { ...OPTS, batchSize: 3 };++ const first = await service.sweep(tight);++ expect(first).toEqual({ scanned: 3, reaped: 3, failed: 0 });+ for (const id of ids.slice(0, 3)) expect((await stored(id)).status).toBe(MessageStatus.FAILED);+ for (const id of ids.slice(3)) expect((await stored(id)).status).toBe(MessageStatus.PENDING);+ expect(persistedCalls()).toHaveLength(3);++ const second = await service.sweep(tight);+ expect(second).toEqual({ scanned: 2, reaped: 2, failed: 0 });+ for (const id of ids) expect((await stored(id)).status).toBe(MessageStatus.FAILED);+ });++ it('drops the outbound media payload on reap but keeps mimetype/filename and other metadata', async () => {+ const id = await insertMessage({+ type: 'image',+ metadata: { media: { mimetype: 'image/jpeg', filename: 'a.jpg', data: 'aGVsbG8=' }, quotedMessage: { id: 'q1' } },+ });++ await service.sweep(OPTS);++ const metadata = (await stored(id)).metadata as {+ media: { mimetype?: string; filename?: string; data?: string };+ quotedMessage: { id: string };+ reapedAt: string;+ };+ expect(metadata.media.data).toBeUndefined();+ expect(metadata.media.mimetype).toBe('image/jpeg');+ expect(metadata.media.filename).toBe('a.jpg');+ expect(metadata.quotedMessage).toEqual({ id: 'q1' });+ expect(metadata.reapedAt).toBeDefined();+ // The emitted snapshot carries the same slimmed metadata.+ const [, payload] = persistedCalls()[0];+ expect((payload.message.metadata as { media: { data?: string } }).media.data).toBeUndefined();+ });++ it('keeps the batch alive when one row fails to save', async () => {+ const first = await insertMessage();+ const second = await insertMessage();+ const saveSpy = jest.spyOn(messages, 'save').mockRejectedValueOnce(new Error('db hiccup'));++ const stats = await service.sweep(OPTS);++ expect(stats).toEqual({ scanned: 2, reaped: 1, failed: 1 });+ expect((await stored(first)).status).toBe(MessageStatus.PENDING);+ expect((await stored(second)).status).toBe(MessageStatus.FAILED);+ expect(persistedCalls()).toHaveLength(1);+ saveSpy.mockRestore();+ });+});++describe('resolvePendingMessageReaperOptions', () => {+ it('defaults to a 10-minute interval, 1-hour grace, and a batch of 50', () => {+ expect(resolvePendingMessageReaperOptions({})).toEqual({+ intervalMs: 600_000,+ graceMs: 3_600_000,+ batchSize: 50,+ });+ });++ it('reads interval, grace, and batch size from the environment', () => {+ expect(+ resolvePendingMessageReaperOptions({+ MESSAGE_REAPER_INTERVAL_MS: '300000',+ MESSAGE_REAPER_GRACE_MS: '120000',+ MESSAGE_REAPER_BATCH_SIZE: '7',+ }),+ ).toEqual({ intervalMs: 300_000, graceMs: 120_000, batchSize: 7 });+ });++ it('falls back to defaults on non-numeric or out-of-range values', () => {+ expect(+ resolvePendingMessageReaperOptions({+ MESSAGE_REAPER_INTERVAL_MS: 'abc',+ MESSAGE_REAPER_GRACE_MS: '-5',+ MESSAGE_REAPER_BATCH_SIZE: '0',+ }),+ ).toEqual({ intervalMs: 600_000, graceMs: 3_600_000, batchSize: 50 });+ });+});++describe('PendingMessageReaperService.onModuleInit (scheduling)', () => {+ const ENV_KEYS = ['MESSAGE_REAPER_INTERVAL_MS', 'MESSAGE_REAPER_GRACE_MS', 'MESSAGE_REAPER_BATCH_SIZE'] as const;+ const originals = new Map<string, string | undefined>();++ beforeEach(() => {+ for (const key of ENV_KEYS) {+ originals.set(key, process.env[key]);+ delete process.env[key];+ }+ });++ afterEach(() => {+ for (const key of ENV_KEYS) {+ const value = originals.get(key);+ if (value === undefined) delete process.env[key];+ else process.env[key] = value;+ }+ originals.clear();+ });++ const makeService = () =>+ new PendingMessageReaperService(+ { find: jest.fn() } as unknown as Repository<Message>,+ { execute: jest.fn() } as unknown as HookManager,+ );++ it('does not schedule a timer when MESSAGE_REAPER_INTERVAL_MS <= 0', () => {+ process.env.MESSAGE_REAPER_INTERVAL_MS = '0';+ const svc = makeService();++ jest.useFakeTimers();+ try {+ const sweepSpy = jest.spyOn(svc, 'sweep');+ svc.onModuleInit();+ jest.advanceTimersByTime(10 * 600_000);+ expect(sweepSpy).not.toHaveBeenCalled();+ svc.onModuleDestroy();+ } finally {+ jest.useRealTimers();+ }+ });++ it('sweeps on the configured interval and stops after onModuleDestroy', () => {+ process.env.MESSAGE_REAPER_INTERVAL_MS = '60000';+ const svc = makeService();++ jest.useFakeTimers();+ try {+ const sweepSpy = jest.spyOn(svc, 'sweep').mockResolvedValue({ scanned: 0, reaped: 0, failed: 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/message/pending-message-reaper.service.ts b/src/modules/message/pending-message-reaper.service.tsnew file mode 100644index 000000000..7a01b4cb2--- /dev/null+++ b/src/modules/message/pending-message-reaper.service.ts@@ -0,0 +1,149 @@+import { Injectable, OnModuleDestroy, OnModuleInit } from '@nestjs/common';+import { InjectRepository } from '@nestjs/typeorm';+import { LessThan, Repository } from 'typeorm';+import { Message, MessageDirection, MessageStatus } from './entities/message.entity';+import { HookManager } from '../../core/hooks';+import { createLogger } from '../../common/services/logger.service';++export interface PendingMessageReaperOptions {+ // Sweep cadence. <= 0 disables the reaper (mirrors INGRESS_RECONCILE_INTERVAL_MS <= 0).+ intervalMs: number;+ // An outgoing PENDING row only becomes reap-eligible once it is older than this — the live send+ // path gets the whole window to persist its own SENT/FAILED outcome first.+ graceMs: number;+ batchSize: number;+}++export function resolvePendingMessageReaperOptions(env: NodeJS.ProcessEnv = process.env): PendingMessageReaperOptions {+ const interval = Number(env.MESSAGE_REAPER_INTERVAL_MS);+ const grace = Number(env.MESSAGE_REAPER_GRACE_MS);+ const batch = Number(env.MESSAGE_REAPER_BATCH_SIZE);+ return {+ intervalMs: Number.isInteger(interval) ? interval : 10 * 60_000,+ graceMs: Number.isInteger(grace) && grace >= 0 ? grace : 60 * 60_000,+ batchSize: Number.isInteger(batch) && batch >= 1 ? batch : 50,+ };+}++export interface PendingMessageReaperStats {+ scanned: number;+ reaped: number;+ // Rows whose bookkeeping write failed; they stay PENDING and are retried next sweep.+ failed: number;+}++/**+ * Closes the crash window of the outbound persist-before-send flow. Every sender saves the row+ * PENDING before handing it to the engine and transitions it to SENT/FAILED right after; a process+ * crash between those two writes strands the row PENDING forever — it sits in the messages table,+ * and in any search provider's index fed by `message:persisted`, as a message that never resolves.+ *+ * The reaper sweeps small batches of stale outgoing PENDING rows (older than the grace window),+ * marks them FAILED with a `reapedAt` metadata marker (distinguishable from a genuine send failure+ * without a new column), and re-emits `message:persisted` for each — the same emission MessageService+ * performs for every persisted outbound state — so a provider's copy reconciles to the terminal+ * state instead of staying stuck at the initial PENDING write.+ *+ * Mirrors IngressReconcilerService's lifecycle: a raw unref'd setInterval started on module init+ * (first sweep after one interval), cleared on destroy. Young PENDING rows (a send still in flight)+ * and non-outgoing rows are never touched.+ */+@Injectable()+export class PendingMessageReaperService implements OnModuleInit, OnModuleDestroy {+ private readonly logger = createLogger('PendingMessageReaperService');+ private timer?: ReturnType<typeof setInterval>;+ private sweeping = false;++ constructor(+ @InjectRepository(Message, 'data') private readonly messages: Repository<Message>,+ private readonly hookManager: HookManager,+ ) {}++ onModuleInit(): void {+ const opts = resolvePendingMessageReaperOptions();+ if (opts.intervalMs <= 0) {+ this.logger.log('Pending message reaper disabled (MESSAGE_REAPER_INTERVAL_MS <= 0)');+ return;+ }+ this.timer = setInterval(() => {+ this.sweep(opts).catch(err =>+ this.logger.error('Pending message reaper 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 outgoing-PENDING backlog. Overlap-guarded: a slow sweep never+ * stacks a second pass on top of itself.+ */+ async sweep(opts: PendingMessageReaperOptions, now: Date = new Date()): Promise<PendingMessageReaperStats> {+ const stats: PendingMessageReaperStats = { scanned: 0, reaped: 0, failed: 0 };+ if (this.sweeping) return stats;+ this.sweeping = true;+ try {+ const cutoff = new Date(now.getTime() - opts.graceMs);+ const rows = await this.messages.find({+ where: {+ direction: MessageDirection.OUTGOING,+ status: MessageStatus.PENDING,+ createdAt: LessThan(cutoff),+ },+ order: { createdAt: 'ASC' },+ take: opts.batchSize,+ });+ for (const row of rows) {+ stats.scanned++;+ try {+ await this.reapRow(row, now);+ stats.reaped++;+ } catch (err) {+ // A bookkeeping failure (repo save) must not abort the batch; the row stays PENDING and+ // is retried next sweep.+ this.logger.error(+ 'Reaping a stuck pending message failed',+ err instanceof Error ? err.message : String(err),+ { messageId: row.id, sessionId: row.sessionId, action: 'pending_message_reap_failed' },+ );+ stats.failed++;+ }+ }+ if (stats.reaped > 0) {+ this.logger.log(`Reaped ${stats.reaped} outbound message(s) stuck PENDING past the grace window`, {+ action: 'pending_messages_reaped',+ });+ }+ return stats;+ } finally {+ this.sweeping = false;+ }+ }++ private async reapRow(row: Message, now: Date): Promise<void> {+ // A reaped row is terminal: it is never retried and its media is never rendered, so drop the+ // base64 payload exactly as MessageService.saveFailedMessage does for a genuine send failure —+ // keeping a multi-MB payload in a terminal row only bloats the messages table. The reapedAt+ // marker tells the reaper's FAILED apart from a real send failure.+ const media = (row.metadata as { media?: { data?: unknown } } | undefined)?.media;+ if (media) {+ delete media.data;+ }+ row.metadata = { ...(row.metadata ?? {}), reapedAt: now.toISOString() };+ row.status = MessageStatus.FAILED;+ await this.messages.save(row);+ // Reconcile provider copies of the earlier PENDING emission: fire-and-forget with a shallow+ // snapshot, the exact shape of MessageService.emitPersisted — a plugin handler must never+ // break the sweep.+ void this.hookManager+ .execute(+ 'message:persisted',+ { sessionId: row.sessionId, message: { ...row } },+ { sessionId: row.sessionId, source: 'PendingMessageReaperService' },+ )+ .catch(() => undefined);+ }+}