Free, Open Source, Self-Hosted WhatsApp API Gateway
TypeScript apibotgatewayself-hostedwhatsappwhatsapp-apiwhatsapp-automationwhatsapp-botwhatsapp-gatewaywhatsapp-gateway-apiwhatsapp-webwhatsapp-web-api
fix(pacing): feed the send breaker from the bulk and status paths, and don't treat a pacing 429 as a delivery failure
Yudhi Armyndharis2adec596b41f
diff --git a/src/modules/message/bulk-message.service.spec.ts b/src/modules/message/bulk-message.service.spec.tsindex df57f8437..0c355c8b1 100644--- a/src/modules/message/bulk-message.service.spec.ts+++ b/src/modules/message/bulk-message.service.spec.ts@@ -1,5 +1,5 @@import { Test, TestingModule } from '@nestjs/testing';-import { PayloadTooLargeException } from '@nestjs/common';+import { HttpException, PayloadTooLargeException } from '@nestjs/common';import { getRepositoryToken } from '@nestjs/typeorm';import { In, Not } from 'typeorm';import {@@ -14,7 +14,7 @@ import { SendBulkMessageDto } from './dto/bulk-message.dto';import { EngineRegistry } from '../../engine/engine-registry.service';import type { IWhatsAppEngine } from '../../engine/interfaces/whatsapp-engine.interface';import { MessageService } from './message.service';-import { SendPacingService } from './send-pacing.service';+import { SendPacingService, SEND_PACING_LIMITED } from './send-pacing.service';import { SessionOwnershipService } from '../session/session-ownership.service';import { HookManager } from '../../core/hooks';import { SsrfBlockedError } from '../../common/security/ssrf-guard';@@ -76,7 +76,11 @@ describe('BulkMessageService.onApplicationBootstrap', () => {// Pacing is off by default; its own spec covers the governor. Here it must simply not// refuse, so the bulk assertions exercise the paths they were written for.provide: SendPacingService,- useValue: { assertSendAllowed: jest.fn().mockResolvedValue(undefined) },+ useValue: {+ assertSendAllowed: jest.fn().mockResolvedValue(undefined),+ recordSendFailure: jest.fn(),+ recordSendSuccess: jest.fn(),+ },},{provide: HookManager,@@ -145,7 +149,14 @@ describe('BulkMessageService.onApplicationBootstrap', () => {{ provide: getRepositoryToken(MessageBatch, 'data'), useValue: repo },EngineRegistry,{ provide: MessageService, useValue: { saveOutgoingMessage: jest.fn() } },- { provide: SendPacingService, useValue: { assertSendAllowed: jest.fn().mockResolvedValue(undefined) } },+ {+ provide: SendPacingService,+ useValue: {+ assertSendAllowed: jest.fn().mockResolvedValue(undefined),+ recordSendFailure: jest.fn(),+ recordSendSuccess: jest.fn(),+ },+ },{provide: HookManager,useValue: {@@ -227,6 +238,7 @@ describe('BulkMessageService.processBatch', () => {};let engines: EngineRegistry;let hookManager: { execute: jest.Mock };+ let pacing: { assertSendAllowed: jest.Mock; recordSendFailure: jest.Mock; recordSendSuccess: jest.Mock };const makeBatch = (messageCount: number): MessageBatch =>({@@ -253,6 +265,11 @@ describe('BulkMessageService.processBatch', () => {hookManager = {execute: jest.fn().mockImplementation((_e: string, data: unknown) => Promise.resolve({ continue: true, data })),};+ pacing = {+ assertSendAllowed: jest.fn().mockResolvedValue(undefined),+ recordSendFailure: jest.fn(),+ recordSendSuccess: jest.fn(),+ };repo = {findOne: jest.fn(),save: jest.fn().mockImplementation(b => Promise.resolve(b)),@@ -267,7 +284,7 @@ describe('BulkMessageService.processBatch', () => {{ provide: MessageService, useValue: messageService },{provide: SendPacingService,- useValue: { assertSendAllowed: jest.fn().mockResolvedValue(undefined) },+ useValue: pacing,},{ provide: HookManager, useValue: hookManager },],@@ -377,6 +394,42 @@ describe('BulkMessageService.processBatch', () => {expect(hookManager.execute).not.toHaveBeenCalledWith('message:failed', expect.anything(), expect.anything());});+ it('feeds the pacing breaker: a successful bulk send records success, so bulk can reset a streak', async () => {+ repo.findOne.mockResolvedValue(makeBatch(1));++ await runProcessBatch();++ expect(pacing.recordSendSuccess).toHaveBeenCalledWith('s1');+ expect(pacing.recordSendFailure).not.toHaveBeenCalled();+ });++ it('feeds the pacing breaker: an engine refusal records a failure, so bulk can trip the streak', async () => {+ repo.findOne.mockResolvedValue(makeBatch(1));+ engine.sendTextMessage.mockRejectedValueOnce(new Error('boom'));++ await runProcessBatch();++ // The engine was asked and refused — exactly what the breaker's streak counts, just like the+ // single-send path (message.service failSend). A success never happened, so no reset.+ expect(pacing.recordSendFailure).toHaveBeenCalledWith('s1');+ expect(pacing.recordSendSuccess).not.toHaveBeenCalled();+ });++ it('a pacing 429 fails the item WITHOUT a message:failed hook or a breaker increment (policy, not delivery)', async () => {+ repo.findOne.mockResolvedValue(makeBatch(1));+ pacing.assertSendAllowed.mockRejectedValueOnce(+ new HttpException({ statusCode: 429, code: SEND_PACING_LIMITED }, 429),+ );++ await runProcessBatch();++ // Thrown before the engine was asked: not a delivery failure (no message:failed), and it must+ // not feed the breaker — matching single send, where a pacing refusal is a bare 429.+ expect(engine.sendTextMessage).not.toHaveBeenCalled();+ expect(hookManager.execute).not.toHaveBeenCalledWith('message:failed', expect.anything(), expect.anything());+ expect(pacing.recordSendFailure).not.toHaveBeenCalled();+ });+it('sends a bulk audio item with ptt as a voice note and persists type "voice"', async () => {engine.sendAudioMessage = jest.fn().mockResolvedValue({ id: 'wa2', timestamp: 222 });const batch = {@@ -683,7 +736,11 @@ describe('BulkMessageService.cancelBatch', () => {{ provide: MessageService, useValue: {} },{provide: SendPacingService,- useValue: { assertSendAllowed: jest.fn().mockResolvedValue(undefined) },+ useValue: {+ assertSendAllowed: jest.fn().mockResolvedValue(undefined),+ recordSendFailure: jest.fn(),+ recordSendSuccess: jest.fn(),+ },},{ provide: HookManager, useValue: { execute: jest.fn() } },],@@ -762,7 +819,11 @@ describe('BulkMessageService.createBatch base64 media cap', () => {{ provide: MessageService, useValue: messageService },{provide: SendPacingService,- useValue: { assertSendAllowed: jest.fn().mockResolvedValue(undefined) },+ useValue: {+ assertSendAllowed: jest.fn().mockResolvedValue(undefined),+ recordSendFailure: jest.fn(),+ recordSendSuccess: jest.fn(),+ },},{provide: HookManager,diff --git a/src/modules/message/bulk-message.service.ts b/src/modules/message/bulk-message.service.tsindex 6fa64a7cb..75cdc3288 100644--- a/src/modules/message/bulk-message.service.ts+++ b/src/modules/message/bulk-message.service.ts@@ -20,7 +20,7 @@ import { SendBulkMessageDto } from './dto/bulk-message.dto';import { MessageStatus } from './entities/message.entity';import { EngineRegistry } from '../../engine/engine-registry.service';import { MessageService } from './message.service';-import { SendPacingService } from './send-pacing.service';+import { SendPacingService, isPacingLimitedError } from './send-pacing.service';import { SessionOwnershipService } from '../session/session-ownership.service';import { HookManager } from '../../core/hooks';import { assertBase64WithinMediaCap, stripBase64DataUri } from './media-cap.util';@@ -460,8 +460,19 @@ export class BulkMessageService implements OnApplicationBootstrap {// A violation fails just this item (honouring stopOnError) instead of sending it.this.assertContentMediaWithinCap(content);- // Send message based on type- const messageResult = await this.sendMessage(engine, msg.chatId, msg.type, content);+ // Send message based on type. The engine call is bracketed on its own so the pacing breaker+ // hears exactly what the single-send path feeds it (message.service failSend/persistSentState):+ // recordSendFailure only when the ENGINE was asked and refused — never for the pre-engine+ // pacing/plugin/media-cap throws above — and recordSendSuccess the moment it accepts. Without+ // this the breaker was blind to bulk, the highest-volume path it exists to protect.+ let messageResult;+ try {+ messageResult = await this.sendMessage(engine, msg.chatId, msg.type, content);+ } catch (engineError) {+ this.pacing.recordSendFailure(batch.sessionId);+ throw engineError;+ }+ this.pacing.recordSendSuccess(batch.sessionId);result.status = BatchMessageStatus.SENT;result.messageId = messageResult.id;@@ -484,9 +495,10 @@ export class BulkMessageService implements OnApplicationBootstrap {batch.progress.pending--;// Fire message:failed so alerting/analytics plugins observe bulk failures too (previously- // none) — but NOT for a plugin gate-block, which is a moderation decision, not a delivery- // failure (matches single send, where a block is a 400 with no message:failed).- if (!blockedByPlugin) {+ // none) — but NOT for a plugin gate-block (a moderation decision) nor a pacing refusal (a+ // policy 429, thrown before the engine was asked): neither is a delivery failure, matching+ // single send where a block is a 400 and a pacing refusal is a 429, neither firing the hook.+ if (!blockedByPlugin && !isPacingLimitedError(error)) {await this.hookManager.execute('message:failed',{ sessionId: batch.sessionId, error: sanitized.message, input: content, type: msg.type },diff --git a/src/modules/message/send-pacing.service.ts b/src/modules/message/send-pacing.service.tsindex 4a692da54..52984850d 100644--- a/src/modules/message/send-pacing.service.ts+++ b/src/modules/message/send-pacing.service.ts@@ -13,6 +13,17 @@ import { AuditAction } from '../audit/entities/audit-log.entity';/** Body code on a pacing refusal. The throttler's own 429 carries no `code`, which is what tells the two apart. */export const SEND_PACING_LIMITED = 'SEND_PACING_LIMITED';+/**+ * True for the 429 `assertSendAllowed` throws — a policy refusal, distinguished from any other 429+ * by the `code` on its body. Callers use it to treat a paced-out send as a refusal-to-send rather+ * than a delivery failure (no `message:failed`, no breaker increment — the engine was never asked).+ */+export function isPacingLimitedError(error: unknown): boolean {+ if (!(error instanceof HttpException)) return false;+ const body = error.getResponse();+ return typeof body === 'object' && body !== null && (body as { code?: string }).code === SEND_PACING_LIMITED;+}+/** Per-session breaker state. Deliberately in memory — see the class doc. */interface BreakerState {consecutiveFailures: number;diff --git a/src/modules/status/status.service.spec.ts b/src/modules/status/status.service.spec.tsindex d55646e6f..9b74c7a8c 100644--- a/src/modules/status/status.service.spec.ts+++ b/src/modules/status/status.service.spec.ts@@ -30,14 +30,17 @@ describe('StatusService media validation and selection', () => {const hookManager = { execute: jest.fn(passThrough) };const store = { list: jest.fn(), listByContact: jest.fn(), getMedia: jest.fn() };const storageService = { getFile: jest.fn() };+ const pacing = {+ assertSendAllowed: jest.fn().mockResolvedValue(undefined),+ recordSendFailure: jest.fn(),+ recordSendSuccess: jest.fn(),+ };const service = new StatusService(engines,hookManager as unknown as HookManager,store as unknown as StatusStoreService,storageService as unknown as StorageService,- {- assertSendAllowed: jest.fn().mockResolvedValue(undefined),- } as unknown as SendPacingService,+ pacing as unknown as SendPacingService,);beforeEach(() => {@@ -45,6 +48,21 @@ describe('StatusService media validation and selection', () => {hookManager.execute.mockImplementation(passThrough);});+ describe('pacing breaker feed', () => {+ it('records success when the engine accepts a status post', async () => {+ await service.postTextStatus('s1', 'hello', { recipients: [] });+ expect(pacing.recordSendSuccess).toHaveBeenCalledWith('s1');+ expect(pacing.recordSendFailure).not.toHaveBeenCalled();+ });++ it('records a failure when the engine refuses a status post', async () => {+ engine.postTextStatus.mockRejectedValueOnce(new Error('refused'));+ await expect(service.postTextStatus('s1', 'hello', { recipients: [] })).rejects.toThrow('refused');+ expect(pacing.recordSendFailure).toHaveBeenCalledWith('s1');+ expect(pacing.recordSendSuccess).not.toHaveBeenCalled();+ });+ });+describe('reading statuses', () => {it('reads statuses from the store, not the engine', async () => {store.list.mockResolvedValue([{ id: 'w1' } as any]);diff --git a/src/modules/status/status.service.ts b/src/modules/status/status.service.tsindex b272253a3..d8024b6b2 100644--- a/src/modules/status/status.service.ts+++ b/src/modules/status/status.service.ts@@ -87,13 +87,30 @@ export class StatusService {}}+ /**+ * Report the engine post's outcome to the pacing breaker, exactly as the chat send path does+ * (message.service failSend/persistSentState): the engine was asked, so a refusal counts toward+ * the failure streak and an accept resets it. The pre-engine pacing/plugin gate runs OUTSIDE this+ * wrapper, so a policy refusal never feeds the breaker — only a genuine engine refusal does.+ */+ private async recordedPost(sessionId: string, post: () => Promise<StatusResult>): Promise<StatusResult> {+ try {+ const result = await post();+ this.pacing.recordSendSuccess(sessionId);+ return result;+ } catch (error) {+ this.pacing.recordSendFailure(sessionId);+ throw error;+ }+ }+async postTextStatus(sessionId: string, text: string, options: StatusPostOptions): Promise<StatusResult> {const engine = this.engines.require(sessionId,() => new NotFoundException(`Session ${sessionId} not found or not connected`),);const gated = await this.gate(sessionId, 'status-text', { text, options });- return engine.postTextStatus(gated.text, gated.options);+ return this.recordedPost(sessionId, () => engine.postTextStatus(gated.text, gated.options));}async postImageStatus(@@ -116,7 +133,7 @@ export class StatusService {media: { mimetype: mimetype ?? 'image/jpeg', data: base64 || url || '' },options,});- return engine.postImageStatus(this.guardGatedMedia(gated.media), gated.options);+ return this.recordedPost(sessionId, () => engine.postImageStatus(this.guardGatedMedia(gated.media), gated.options));}async postVideoStatus(@@ -139,7 +156,7 @@ export class StatusService {media: { mimetype: mimetype ?? 'video/mp4', data: base64 || url || '' },options,});- return engine.postVideoStatus(this.guardGatedMedia(gated.media), gated.options);+ return this.recordedPost(sessionId, () => engine.postVideoStatus(this.guardGatedMedia(gated.media), gated.options));}/**@@ -172,7 +189,7 @@ export class StatusService {media: { mimetype: mimetype ?? 'audio/ogg; codecs=opus', data: base64 || url || '' },options,});- return engine.postVoiceStatus(this.guardGatedMedia(gated.media), gated.options);+ return this.recordedPost(sessionId, () => engine.postVoiceStatus(this.guardGatedMedia(gated.media), gated.options));}async deleteStatus(sessionId: string, statusId: string): Promise<void> {