Free, Open Source, Self-Hosted WhatsApp API Gateway
TypeScript apibotgatewayself-hostedwhatsappwhatsapp-apiwhatsapp-automationwhatsapp-botwhatsapp-gatewaywhatsapp-gateway-apiwhatsapp-webwhatsapp-web-api
fix(pacing): release the hold of a send that wrote no row
Yudhi Armyndharisc51505c2afee
diff --git a/src/modules/catalog/catalog.service.spec.ts b/src/modules/catalog/catalog.service.spec.tsindex 81c52d865..35ea87fb3 100644--- a/src/modules/catalog/catalog.service.spec.ts+++ b/src/modules/catalog/catalog.service.spec.ts@@ -192,6 +192,33 @@ describe('CatalogService', () => {expect(sendProduct).not.toHaveBeenCalled();});+ // A product send writes no row of its own, so one that provably never went out must stop counting+ // against the pacing caps at once; one whose outcome is unknown may still be echoed, and stays held.+ it.each([+ ['a plugin vetoes it', { veto: true }, true],+ ['the session is not started', { noEngine: true }, true],+ ['the engine cannot send products', { engineError: new EngineNotSupportedError('sendProduct') }, true],+ ['the engine fails with an unknown outcome', { engineError: new Error('socket closed') }, false],+ ])('when %s, releases its pacing admission: %p', async (_label, setup, released) => {+ const {+ veto = false,+ noEngine = false,+ engineError,+ } = setup as {+ veto?: boolean;+ noEngine?: boolean;+ engineError?: Error;+ };+ const release = jest.fn();+ const pacing = { assertSendAllowed: jest.fn().mockResolvedValue(release) };+ const hookManager = veto ? { execute: jest.fn().mockResolvedValue({ continue: false }) } : passThroughHooks();+ const sendProduct = jest.fn().mockRejectedValue(engineError);+ const { svc } = makeService(noEngine ? undefined : { sendProduct }, pacing, hookManager);++ await expect(svc.sendProduct('s1', '[email protected]', 'prod-1')).rejects.toBeDefined();+ expect(release).toHaveBeenCalledTimes(released ? 1 : 0);+ });+it('propagates an engine failure from sendProduct', async () => {const down = new Error('socket closed');const sendProduct = jest.fn().mockRejectedValue(down);diff --git a/src/modules/catalog/catalog.service.ts b/src/modules/catalog/catalog.service.tsindex 9929b0f13..16e91055f 100644--- a/src/modules/catalog/catalog.service.ts+++ b/src/modules/catalog/catalog.service.ts@@ -6,7 +6,7 @@ import type {PaginatedProducts,MessageResult,} from '../../engine/interfaces/whatsapp-engine.interface';-import { SendPacingService, countsTowardSendBreaker } from '../message/send-pacing.service';+import { SendPacingService, countsTowardSendBreaker, sentNothing } from '../message/send-pacing.service';import { HookManager, applySendingGate } from '../../core/hooks';@Injectable()@@ -53,29 +53,38 @@ export class CatalogService {* that row lands.*/async sendProduct(sessionId: string, chatId: string, productId: string, body?: string): Promise<MessageResult> {- await this.pacing.assertSendAllowed(sessionId, chatId);- const gated = await applySendingGate(- this.hookManager,- sessionId,- 'product',- // The DTO lets a JSON null through as "no body". Normalised here, so the checks below only ever- // judge what a plugin handed back, never the caller's own input.- { chatId, productId, body: body ?? undefined },- 'CatalogService',- );- const gatedProductId: unknown = gated.productId;- const gatedBody: unknown = gated.body;- if (typeof gatedProductId !== 'string' || gatedProductId === '') {- throw new BadRequestException('A message:sending handler returned an invalid productId');- }- if (gatedBody !== undefined && typeof gatedBody !== 'string') {- throw new BadRequestException('A message:sending handler returned an invalid body');+ const release = await this.pacing.assertSendAllowed(sessionId, chatId);+ let engineAsked = false;+ try {+ const gated = await applySendingGate(+ this.hookManager,+ sessionId,+ 'product',+ // The DTO lets a JSON null through as "no body". Normalised here, so the checks below only ever+ // judge what a plugin handed back, never the caller's own input.+ { chatId, productId, body: body ?? undefined },+ 'CatalogService',+ );+ const gatedProductId: unknown = gated.productId;+ const gatedBody: unknown = gated.body;+ if (typeof gatedProductId !== 'string' || gatedProductId === '') {+ throw new BadRequestException('A message:sending handler returned an invalid productId');+ }+ if (gatedBody !== undefined && typeof gatedBody !== 'string') {+ throw new BadRequestException('A message:sending handler returned an invalid body');+ }+ const engine = this.engines.require(+ sessionId,+ () => new NotFoundException(`Session ${sessionId} not found or not connected`),+ );+ engineAsked = true;+ return await this.recordedSend(sessionId, () => engine.sendProduct(chatId, gatedProductId, gatedBody));+ } catch (error) {+ // No row is written here, so a send that provably never went out gives its pacing admission back.+ // One whose outcome is unknown stays held: its own-send echo may still write the row.+ if (!engineAsked || sentNothing(error)) release?.();+ throw error;}- const engine = this.engines.require(- sessionId,- () => new NotFoundException(`Session ${sessionId} not found or not connected`),- );- return this.recordedSend(sessionId, () => engine.sendProduct(chatId, gatedProductId, gatedBody));}/**diff --git a/src/modules/message/bulk-message.service.spec.ts b/src/modules/message/bulk-message.service.spec.tsindex 2b645ac16..4a0f65eb0 100644--- a/src/modules/message/bulk-message.service.spec.ts+++ b/src/modules/message/bulk-message.service.spec.ts@@ -20,6 +20,9 @@ import { SessionOwnershipService } from '../session/session-ownership.service';import { HookManager } from '../../core/hooks';import { SsrfBlockedError } from '../../common/security/ssrf-guard';import { EnginePageError } from '../../common/errors/engine-page.error';+import { EngineRefusedError } from '../../common/errors/engine-refused.error';+import { EngineThrottledError } from '../../common/errors/engine-throttled.error';+import { EngineTransportError } from '../../common/errors/engine-transport.error';/** Regression lock for the terminal-status decision (cancel-clobber + stopOnError overwrite bugs). */describe('resolveFinalBatchStatus', () => {@@ -1022,6 +1025,48 @@ describe('BulkMessageService.processBatch', () => {expect(pacing.recordSendFailure).not.toHaveBeenCalled();});+ // Bulk writes an item's row only after the engine accepts it, so an item that fails first must stop+ // counting against the caps at once, or it refuses the next item for the rest of the hold.+ it.each([+ ['a plugin blocks it', () => hookManager.execute.mockResolvedValueOnce({ continue: false })],+ ['the engine refuses it', () => engine.sendTextMessage.mockRejectedValueOnce(new EngineRefusedError('refused'))],+ [+ 'WhatsApp throttles it',+ () => engine.sendTextMessage.mockRejectedValueOnce(new EngineThrottledError('rate-overlimit')),+ ],+ ['its media URL is blocked', () => engine.sendTextMessage.mockRejectedValueOnce(new SsrfBlockedError('blocked'))],+ ])('releases the pacing admission of an item that fails before its row when %s', async (_label, arrange) => {+ const release = jest.fn();+ pacing.assertSendAllowed.mockResolvedValue(release);+ repo.findOne.mockResolvedValue(makeBatch(1));+ arrange();++ await runProcessBatch();++ expect(release).toHaveBeenCalledTimes(1);+ });++ it.each([+ ['the engine accepts it', () => undefined],+ [+ 'the engine fails with an unknown outcome',+ () => engine.sendTextMessage.mockRejectedValueOnce(new Error('timeout')),+ ],+ [+ 'the engine transport fails',+ () => engine.sendTextMessage.mockRejectedValueOnce(new EngineTransportError('timeout')),+ ],+ ])('keeps the pacing admission held when %s', async (_label, arrange) => {+ const release = jest.fn();+ pacing.assertSendAllowed.mockResolvedValue(release);+ repo.findOne.mockResolvedValue(makeBatch(1));+ arrange();++ await runProcessBatch();++ expect(release).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 = {diff --git a/src/modules/message/bulk-message.service.ts b/src/modules/message/bulk-message.service.tsindex e8971706f..6b4cc52a2 100644--- a/src/modules/message/bulk-message.service.ts+++ b/src/modules/message/bulk-message.service.ts@@ -31,6 +31,7 @@ import {SendPacingService,isPacingLimitedError,countsTowardSendBreaker,+ sentNothing,SEND_PACING_LIMITED,} from './send-pacing.service';import { SessionOwnershipService } from '../session/session-ownership.service';@@ -553,6 +554,10 @@ export class BulkMessageService implements OnModuleInit, OnApplicationBootstrap,// decision (not a delivery failure) and skips message:failed — matching the single-send path,// where a block is a 400 with no failure hook.let blockedByPlugin = false;+ // The pacing admission's release. Bulk writes an item's row only after the engine accepts it, so an+ // item that fails first gives its admission back, or it would refuse the next item for the hold.+ let releaseAdmission: (() => void) | undefined;+ let engineAsked = false;try {// Apply template variablescontent = this.applyVariables(msg.content, msg.variables);@@ -560,7 +565,7 @@ export class BulkMessageService implements OnModuleInit, OnApplicationBootstrap,// Pacing runs BEFORE the moderation gate, matching MessageService: a send policy forbids is not// offered to plugins at all. A refusal is a 429 that fails THIS item (honouring stopOnError),// not the batch — the allowance may free up, and a batch killed outright could not resume.- await this.pacing.assertSendAllowed(batch.sessionId, msg.chatId);+ releaseAdmission = await this.pacing.assertSendAllowed(batch.sessionId, msg.chatId);// Per-message moderation gate — the SAME message:sending hook single sends use, so a// compliance/moderation plugin sees bulk traffic too (bulk previously bypassed it entirely).@@ -614,6 +619,7 @@ export class BulkMessageService implements OnModuleInit, OnApplicationBootstrap,// 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;+ engineAsked = true;try {messageResult = await this.sendMessage(engine, msg.chatId, msg.type, content);} catch (engineError) {@@ -622,6 +628,8 @@ export class BulkMessageService implements OnModuleInit, OnApplicationBootstrap,if (countsTowardSendBreaker(engineError)) {this.pacing.recordSendFailure(batch.sessionId);}+ // A failure that may still have sent the message keeps its admission until the echo row lands.+ if (sentNothing(engineError)) releaseAdmission?.();throw engineError;}this.pacing.recordSendSuccess(batch.sessionId);@@ -640,6 +648,7 @@ export class BulkMessageService implements OnModuleInit, OnApplicationBootstrap,this.logger.debug(`Batch ${batch.batchId}: Sent message ${i + 1}/${batch.messages.length} to ${msg.chatId}`);} catch (error) {+ if (!engineAsked) releaseAdmission?.();result.status = BatchMessageStatus.FAILED;// Sanitize: an SSRF block names an internal address — never store/return/log it verbatim.const sanitized = sanitizeBatchError(error);diff --git a/src/modules/message/message-send.service.spec.ts b/src/modules/message/message-send.service.spec.tsindex 6d4a26f35..8d175b9d4 100644--- a/src/modules/message/message-send.service.spec.ts+++ b/src/modules/message/message-send.service.spec.ts@@ -1358,6 +1358,48 @@ describe('MessageSendService', () => {});});+ // ── pacing admission release ──────────────────────────────────────++ // A send that fails before its PENDING row exists never counts into the daily caps, so its pacing+ // admission must go back at once; one that fails after keeps its row as FAILED, which is counted.+ describe('pacing admission release', () => {+ let release: jest.Mock;+ beforeEach(() => {+ release = jest.fn();+ const { assertSendAllowed } = (service as unknown as { pacing: { assertSendAllowed: jest.Mock } }).pacing;+ assertSendAllowed.mockResolvedValue(release);+ });++ it.each([+ [+ 'a plugin blocks it',+ () => {+ (hookManager.execute as jest.Mock).mockResolvedValueOnce({ continue: false });+ return service.sendText('sess-1', { chatId: '[email protected]', text: 'hi' });+ },+ ],+ [+ 'the session has no engine',+ () => service.sendLocation('no-engine', { chatId: '[email protected]', latitude: 1, longitude: 2 }),+ ],+ ['its media is invalid', () => service.sendImage('sess-1', { chatId: '[email protected]', url: '/files/x.png' })],+ ['its audio is invalid', () => service.sendAudio('sess-1', { chatId: '[email protected]', ptt: true })],+ ])('releases it when %s', async (_label, send) => {+ await expect(send()).rejects.toThrow();++ expect(release).toHaveBeenCalledTimes(1);+ expect(repository.save).not.toHaveBeenCalled();+ });++ it('keeps it when the engine fails after the row was written', async () => {+ mockEngine.sendTextMessage.mockRejectedValueOnce(new BadRequestException('refused'));++ await expect(service.sendText('sess-1', { chatId: '[email protected]', text: 'hi' })).rejects.toThrow('refused');++ expect(release).not.toHaveBeenCalled();+ });+ });+// ── buildMediaInput (via sendImage) ───────────────────────────────describe('buildMediaInput validation', () => {diff --git a/src/modules/message/message-send.service.ts b/src/modules/message/message-send.service.tsindex 2aa6e6ec4..ef287b2f6 100644--- a/src/modules/message/message-send.service.ts+++ b/src/modules/message/message-send.service.ts@@ -108,9 +108,7 @@ export class MessageSendService {if (dto.linkPreview === false && dto.customLinkPreview) {throw new BadRequestException('linkPreview: false cannot be combined with customLinkPreview');}- const finalDto = await this.applySendingGate(sessionId, 'text', dto);-- const engine = this.getEngine(sessionId);+ const { finalDto, engine } = await this.applySendingGate(sessionId, 'text', dto);// Save message as pending BEFORE sendingconst message = await this.saveOutgoingMessage(sessionId, {@@ -157,14 +155,20 @@ export class MessageSendService {/*** Run the pre-send `message:sending` plugin gate for one outbound message and return the- * (possibly plugin-modified) input, or throw BadRequestException if a plugin blocked the send.+ * (possibly plugin-modified) input with the session's engine and what `prepare` built from that+ * input, or throw BadRequestException if a plugin blocked the send.* Centralised so EVERY public sender in this class — text, media, extended (location/contact/* poll/sticker/reply/forward) — passes through the same moderation chokepoint, instead of only* `sendText`. The edit path is gated by the twin method in MessageService (the query side of* the send/query split), on the same core/hooks/sending-gate implementation shared with* StatusService.*/- private async applySendingGate<T extends object>(sessionId: string, type: string, input: T): Promise<T> {+ private async applySendingGate<T extends object, P = undefined>(+ sessionId: string,+ type: string,+ input: T,+ prepare?: (finalDto: T) => P,+ ): Promise<{ finalDto: T; engine: IWhatsAppEngine; prepared: P }> {// Pacing runs BEFORE the plugin gate, so a send that policy forbids never reaches a plugin at// all — plugins should not be asked to moderate, or given the chance to rewrite, traffic that is// not going to be sent. The consequence is deliberate and documented in the hook contract: a@@ -175,8 +179,18 @@ export class MessageSendService {// its persisted row still drained the cold budget. Edit carries a chatId too; the edited// message's own row already makes that chat warm, so the gate is a no-op there.const target = input as { chatId?: string; toChatId?: string };- await this.pacing.assertSendAllowed(sessionId, target.chatId ?? target.toChatId);- return applySendingGate(this.hookManager, sessionId, type, input, 'MessageService');+ const release = await this.pacing.assertSendAllowed(sessionId, target.chatId ?? target.toChatId);+ // Everything a sender does before its PENDING row is written runs in here (the plugin gate, the+ // engine lookup, `prepare`), so a send that fails on the way hands its pacing admission back: with no+ // row it never counts, and holding it would refuse the caller's next send near the cap.+ try {+ const finalDto = await applySendingGate(this.hookManager, sessionId, type, input, 'MessageService');+ const engine = this.getEngine(sessionId);+ return { finalDto, engine, prepared: prepare?.(finalDto) as P };+ } catch (error) {+ release?.();+ throw error;+ }}/**@@ -273,9 +287,11 @@ export class MessageSendService {}async sendImage(sessionId: string, dto: SendMediaMessageDto): Promise<MessageResponseDto> {- const finalDto = await this.applySendingGate(sessionId, 'image', dto);- const engine = this.getEngine(sessionId);- const media = this.buildMediaInput(finalDto);+ const {+ finalDto,+ engine,+ prepared: media,+ } = await this.applySendingGate(sessionId, 'image', dto, d => this.buildMediaInput(d));// Save message as pending BEFORE sendingconst message = await this.saveOutgoingMessage(sessionId, {@@ -298,9 +314,11 @@ export class MessageSendService {}async sendVideo(sessionId: string, dto: SendMediaMessageDto): Promise<MessageResponseDto> {- const finalDto = await this.applySendingGate(sessionId, 'video', dto);- const engine = this.getEngine(sessionId);- const media = this.buildMediaInput(finalDto);+ const {+ finalDto,+ engine,+ prepared: media,+ } = await this.applySendingGate(sessionId, 'video', dto, d => this.buildMediaInput(d));// Save message as pending BEFORE sendingconst message = await this.saveOutgoingMessage(sessionId, {@@ -326,15 +344,19 @@ export class MessageSendService {// Label a PTT send 'voice' in the gate (not 'audio') so message:sending, message:failed, and the// persisted row all carry the same type for one outbound voice note — failSend and the saved row// already use `finalDto.ptt ? 'voice' : 'audio'`.- const finalDto = await this.applySendingGate(sessionId, dto.ptt ? 'voice' : 'audio', dto);- const engine = this.getEngine(sessionId);- // Voice notes need a real audio codec; default to ogg/opus when the caller omits a mimetype so the- // wire message and the persisted record agree. Resolved BEFORE buildMediaInput so its base64- // mimetype guard sees the effective type. buildMediaInput itself stays generic (shared by all media).- const audioDto =- finalDto.ptt && !finalDto.mimetype ? { ...finalDto, mimetype: 'audio/ogg; codecs=opus' } : finalDto;- const media = this.buildMediaInput(audioDto);- media.ptt = finalDto.ptt;+ const {+ finalDto,+ engine,+ prepared: { audioDto, media },+ } = await this.applySendingGate(sessionId, dto.ptt ? 'voice' : 'audio', dto, gated => {+ // Voice notes need a real audio codec; default to ogg/opus when the caller omits a mimetype so the+ // wire message and the persisted record agree. Resolved BEFORE buildMediaInput so its base64+ // mimetype guard sees the effective type. buildMediaInput itself stays generic (shared by all media).+ const audioDto = gated.ptt && !gated.mimetype ? { ...gated, mimetype: 'audio/ogg; codecs=opus' } : gated;+ const media = this.buildMediaInput(audioDto);+ media.ptt = gated.ptt;+ return { audioDto, media };+ });// Save message as pending BEFORE sending. A PTT send is a 'voice' note (matches inbound// classification, the outbound webhook echo, stats, and the dashboard), not a plain 'audio' file.@@ -357,9 +379,11 @@ export class MessageSendService {}async sendDocument(sessionId: string, dto: SendMediaMessageDto): Promise<MessageResponseDto> {- const finalDto = await this.applySendingGate(sessionId, 'document', dto);- const engine = this.getEngine(sessionId);- const media = this.buildMediaInput(finalDto);+ const {+ finalDto,+ engine,+ prepared: media,+ } = await this.applySendingGate(sessionId, 'document', dto, d => this.buildMediaInput(d));// Save message as pending BEFORE sendingconst message = await this.saveOutgoingMessage(sessionId, {@@ -392,8 +416,7 @@ export class MessageSendService {quotedMessageId?: string;},): Promise<MessageResponseDto> {- const finalDto = await this.applySendingGate(sessionId, 'location', dto);- const engine = this.getEngine(sessionId);+ const { finalDto, engine } = await this.applySendingGate(sessionId, 'location', dto);// Save message as pending BEFORE sendingconst message = await this.saveOutgoingMessage(sessionId, {@@ -422,8 +445,7 @@ export class MessageSendService {sessionId: string,dto: { chatId: string; contactName: string; contactNumber: string; quotedMessageId?: string },): Promise<MessageResponseDto> {- const finalDto = await this.applySendingGate(sessionId, 'contact', dto);- const engine = this.getEngine(sessionId);+ const { finalDto, engine } = await this.applySendingGate(sessionId, 'contact', dto);// Save message as pending BEFORE sendingconst message = await this.saveOutgoingMessage(sessionId, {@@ -450,8 +472,7 @@ export class MessageSendService {sessionId: string,dto: { chatId: string; name: string; options: string[]; allowMultipleAnswers?: boolean; quotedMessageId?: string },): Promise<MessageResponseDto> {- const finalDto = await this.applySendingGate(sessionId, 'poll', dto);- const engine = this.getEngine(sessionId);+ const { finalDto, engine } = await this.applySendingGate(sessionId, 'poll', dto);// Save message as pending BEFORE sending. A poll has no plain-text body, so store the// question — that keeps the message history readable.@@ -477,9 +498,11 @@ export class MessageSendService {}async sendSticker(sessionId: string, dto: SendMediaMessageDto): Promise<MessageResponseDto> {- const finalDto = await this.applySendingGate(sessionId, 'sticker', dto);- const engine = this.getEngine(sessionId);- const media = this.buildMediaInput(finalDto);+ const {+ finalDto,+ engine,+ prepared: media,+ } = await this.applySendingGate(sessionId, 'sticker', dto, d => this.buildMediaInput(d));// Save message as pending BEFORE sendingconst message = await this.saveOutgoingMessage(sessionId, {@@ -504,8 +527,7 @@ export class MessageSendService {sessionId: string,dto: { chatId: string; quotedMessageId: string; text: string; mentions?: string[] },): Promise<MessageResponseDto> {- const finalDto = await this.applySendingGate(sessionId, 'reply', dto);- const engine = this.getEngine(sessionId);+ const { finalDto, engine } = await this.applySendingGate(sessionId, 'reply', dto);// Resolve the quoted message body (best-effort) so the dashboard can render the reply preview.const quotedBody = await this.resolveQuotedBody(sessionId, finalDto.quotedMessageId, finalDto.chatId);@@ -537,8 +559,7 @@ export class MessageSendService {sessionId: string,dto: { chatId: string; messageId: string; buttonId: string; text?: string },): Promise<MessageResponseDto> {- const finalDto = await this.applySendingGate(sessionId, 'click-button', dto);- const engine = this.getEngine(sessionId);+ const { finalDto, engine } = await this.applySendingGate(sessionId, 'click-button', dto);// A click IS a reply to the prompt, so resolve the prompt's body the way reply() does: the// dashboard renders the quote box from this field, and a hardcoded empty string left every@@ -577,8 +598,7 @@ export class MessageSendService {sessionId: string,dto: { fromChatId: string; toChatId: string; messageId: string },): Promise<MessageResponseDto> {- const finalDto = await this.applySendingGate(sessionId, 'forward', dto);- const engine = this.getEngine(sessionId);+ const { finalDto, engine } = await this.applySendingGate(sessionId, 'forward', dto);// Save message as pending BEFORE sendingconst message = await this.saveOutgoingMessage(sessionId, {diff --git a/src/modules/message/send-pacing-cold-query.spec.ts b/src/modules/message/send-pacing-cold-query.spec.tsindex 4035d5539..9e95bde17 100644--- a/src/modules/message/send-pacing-cold-query.spec.ts+++ b/src/modules/message/send-pacing-cold-query.spec.ts@@ -73,7 +73,7 @@ describe('cold-reachout counting against a real database', () => {await addMessage('[email protected]', TODAY);// Two cold reachouts used of three: a third stranger is still allowed.- await expect(service.assertSendAllowed('s1', '[email protected]')).resolves.toBeUndefined();+ await expect(service.assertSendAllowed('s1', '[email protected]')).resolves.toBeInstanceOf(Function);await addMessage('[email protected]', TODAY);await expect(service.assertSendAllowed('s1', '[email protected]')).rejects.toMatchObject({ status: 429 });@@ -88,9 +88,9 @@ describe('cold-reachout counting against a real database', () => {await addMessage('[email protected]', TODAY, MessageDirection.INCOMING);// Replying to any of them is never refused, however many there are…- await expect(service.assertSendAllowed('s1', '[email protected]')).resolves.toBeUndefined();+ await expect(service.assertSendAllowed('s1', '[email protected]')).resolves.toBeInstanceOf(Function);// …and none of them consumed the cold budget, so a stranger is still allowed.- await expect(service.assertSendAllowed('s1', '[email protected]')).resolves.toBeUndefined();+ await expect(service.assertSendAllowed('s1', '[email protected]')).resolves.toBeInstanceOf(Function);});// The class rule — answering someone who wrote first is not a reachout — must hold for the@@ -106,7 +106,7 @@ describe('cold-reachout counting against a real database', () => {await addMessage('[email protected]', '2026-08-03T10:00:00.000Z', MessageDirection.INCOMING);// Two of three used: the answered chat did not count, the replied-to reachout still does.- await expect(service.assertSendAllowed('s1', '[email protected]')).resolves.toBeUndefined();+ await expect(service.assertSendAllowed('s1', '[email protected]')).resolves.toBeInstanceOf(Function);await addMessage('[email protected]', TODAY);await expect(service.assertSendAllowed('s1', '[email protected]')).rejects.toMatchObject({ status: 429 });@@ -121,7 +121,7 @@ describe('cold-reachout counting against a real database', () => {[TODAY, TODAY, TODAY],);- await expect(service.assertSendAllowed('s1', '[email protected]')).resolves.toBeUndefined();+ await expect(service.assertSendAllowed('s1', '[email protected]')).resolves.toBeInstanceOf(Function);});// Whether a chat is new is a question about THIS account, not the deployment: another session@@ -151,7 +151,7 @@ describe('cold-reachout counting against a real database', () => {await addMessage('[email protected]', TODAY);// The budget of three is spent, but the @c.us spelling of a known contact stays warm.- await expect(service.assertSendAllowed('s1', '[email protected]')).resolves.toBeUndefined();+ await expect(service.assertSendAllowed('s1', '[email protected]')).resolves.toBeInstanceOf(Function);});// The per-send probe and the daily aggregate must agree about who is a stranger, or the aggregate@@ -166,7 +166,7 @@ describe('cold-reachout counting against a real database', () => {await addMessage('[email protected]', TODAY);// Two of three used (the warm contact counted zero, the double-spelled stranger counted once).- await expect(service.assertSendAllowed('s1', '[email protected]')).resolves.toBeUndefined();+ await expect(service.assertSendAllowed('s1', '[email protected]')).resolves.toBeInstanceOf(Function);await addMessage('[email protected]', TODAY);await expect(service.assertSendAllowed('s1', '[email protected]')).rejects.toMatchObject({ status: 429 });@@ -178,7 +178,7 @@ describe('cold-reachout counting against a real database', () => {await addMessage('[email protected]', YESTERDAY);await addMessage('[email protected]', YESTERDAY);- await expect(service.assertSendAllowed('s1', '[email protected]')).resolves.toBeUndefined();+ await expect(service.assertSendAllowed('s1', '[email protected]')).resolves.toBeInstanceOf(Function);});});@@ -619,6 +619,40 @@ describe('concurrent sends against a real database', () => {expect(sent).toEqual([true, true, true, true]);});+ it('stops counting an admitted send against the caps once it is released', async () => {+ const service = build([2], [2]);+ expect(await send(service, '[email protected]', 1)).toBe(true);+ // Admitted, then failed before writing a row (a plugin veto, an engine refusal).+ const release = await service.assertSendAllowed('s1', '[email protected]');+ release?.();++ expect(await send(service, '[email protected]', 2)).toBe(true);+ });++ it('answers a refusal caused only by held sends with the seconds until they lapse', async () => {+ const service = build([2], []);+ expect(await send(service, '[email protected]', 1)).toBe(true);+ await service.assertSendAllowed('s1', '[email protected]');+ jest.setSystemTime(NOW.getTime() + 3_000);++ await expect(service.assertSendAllowed('s1', '[email protected]')).rejects.toMatchObject({+ status: 429,+ response: { code: SEND_PACING_LIMITED, retryAfterSeconds: 7 },+ });+ });++ it('answers a cold refusal caused only by held sends with the seconds until they lapse', async () => {+ const service = build([10_000], [2]);+ expect(await send(service, '[email protected]', 1)).toBe(true);+ await service.assertSendAllowed('s1', '[email protected]');+ jest.setSystemTime(NOW.getTime() + 4_000);++ await expect(service.assertSendAllowed('s1', '[email protected]')).rejects.toMatchObject({+ status: 429,+ response: { code: SEND_PACING_LIMITED, retryAfterSeconds: 6 },+ });+ });+it('judges by the persisted rows alone once the hold has lapsed', async () => {const service = build([5], []);// A gated send that never writes a row (a plugin veto) is held only briefly.diff --git a/src/modules/message/send-pacing.service.spec.ts b/src/modules/message/send-pacing.service.spec.tsindex 398d5d561..d5a9cd5fd 100644--- a/src/modules/message/send-pacing.service.spec.ts+++ b/src/modules/message/send-pacing.service.spec.ts@@ -517,7 +517,7 @@ describe('SendPacingService cold-reachout cap', () => {it('does not count a chat this account already has history with', async () => {const { service, exists } = build(cold(), 0, sessionAged(0), { hasHistory: true, coldToday: 99 });- await expect(service.assertSendAllowed('s1', '[email protected]')).resolves.toBeUndefined();+ await expect(service.assertSendAllowed('s1', '[email protected]')).resolves.toBeInstanceOf(Function);// Probed under both user-id dialects: stored rows may carry either spelling.expect(exists).toHaveBeenCalledWith({@@ -531,7 +531,7 @@ describe('SendPacingService cold-reachout cap', () => {it("allows a cold reachout while the day's allowance remains", async () => {const { service } = build(cold(), 0, sessionAged(0), { hasHistory: false, coldToday: 2 });- await expect(service.assertSendAllowed('s1', '[email protected]')).resolves.toBeUndefined();+ await expect(service.assertSendAllowed('s1', '[email protected]')).resolves.toBeInstanceOf(Function);});it('refuses the cold reachout that would exceed the allowance', async () => {@@ -549,7 +549,7 @@ describe('SendPacingService cold-reachout cap', () => {await expectPacingRefusal(young.service.assertSendAllowed('s1', '[email protected]'));const older = build(cold({ coldSchedule: [3, 30] }), 0, sessionAged(1), { hasHistory: false, coldToday: 5 });- await expect(older.service.assertSendAllowed('s1', '[email protected]')).resolves.toBeUndefined();+ await expect(older.service.assertSendAllowed('s1', '[email protected]')).resolves.toBeInstanceOf(Function);});// A status post addresses no one in particular, so it is not a reachout and must never consume the@@ -568,7 +568,7 @@ describe('SendPacingService cold-reachout cap', () => {coldToday: 999,});- await expect(service.assertSendAllowed('s1', '[email protected]')).resolves.toBeUndefined();+ await expect(service.assertSendAllowed('s1', '[email protected]')).resolves.toBeInstanceOf(Function);expect(exists).not.toHaveBeenCalled();});diff --git a/src/modules/message/send-pacing.service.ts b/src/modules/message/send-pacing.service.tsindex 3fc8b0b8d..28a549e99 100644--- a/src/modules/message/send-pacing.service.ts+++ b/src/modules/message/send-pacing.service.ts@@ -8,6 +8,8 @@ import { resolveSendPacingConfig, type SendPacingConfig } from './send-pacing.coimport { incrementSendPacingRefusals, type SendPacingRefusalReason } from '../../common/metrics/send-pacing-metrics';import { createLogger } from '../../common/services/logger.service';import { EngineRefusedError } from '../../common/errors/engine-refused.error';+import { EngineNotSupportedError } from '../../common/errors/engine-not-supported.error';+import { EngineThrottledError } from '../../common/errors/engine-throttled.error';import { SsrfBlockedError } from '../../common/security/ssrf-guard';import { AuditService } from '../audit/audit.service';import { AuditAction } from '../audit/entities/audit-log.entity';@@ -52,6 +54,21 @@ export function countsTowardSendBreaker(error: unknown): boolean {return true;}+/**+ * Whether a send that threw provably never went out, so its admission can be handed back: a client or+ * refusal status (4xx), a 501 for something the engine cannot do, a media URL the SSRF guard blocked+ * before any fetch, or a WhatsApp rate limit (EngineThrottledError), turned away before it ran. Anything+ * else (a deadline, a dropped socket, a dead page) leaves the outcome unknown; WhatsApp may have taken+ * the message, so its admission stays held.+ */+export function sentNothing(error: unknown): boolean {+ return (+ error instanceof SsrfBlockedError ||+ (error instanceof HttpException &&+ (error.getStatus() < 500 || error instanceof EngineNotSupportedError || error instanceof EngineThrottledError))+ );+}+/*** Cold reachouts `assertReachoutAllowed` set aside on the group tally for one request, and the UTC* day they were taken from. Hand it back to `refundGroupReachouts` if the engine call fails.@@ -93,8 +110,9 @@ interface AdmissionHold {/*** How long each admitted send is held against the caps, from its own admission, before only its row- * counts. It only has to outlast the gap between the check and the row insert; a gated send that never- * writes a row (a plugin veto) is over-counted for at most this long.+ * counts. It only has to outlast the gap between the check and the row insert. A send that fails before+ * writing a row hands its admission back (see assertSendAllowed), so only one that may still have gone+ * out is over-counted, and for at most this long.*/const ADMISSION_WINDOW_MS = 10_000;@@ -186,8 +204,16 @@ export class SendPacingService {** `hold: false` judges the send without holding it in the admission window, for a gated send that* never writes a row (an edit): holding it would charge the caps for a message that is never sent.+ *+ * Returns the release for the admission it held, or undefined when it held none. A caller whose send+ * fails before writing a row, and before WhatsApp may have taken it, calls the release so that send+ * stops counting against the caps at once instead of refusing the next one.*/- async assertSendAllowed(sessionId: string, chatId?: string, opts: { hold?: boolean } = {}): Promise<void> {+ async assertSendAllowed(+ sessionId: string,+ chatId?: string,+ opts: { hold?: boolean } = {},+ ): Promise<(() => void) | undefined> {const config = resolveSendPacingConfig(this.configService);if (!config.enabled) return;@@ -227,6 +253,11 @@ export class SendPacingService {const hold = this.holds.get(sessionId);if (hold?.dayStartMs === dayStart.getTime()) hold.admissions.push(admission);else this.holds.set(sessionId, { dayStartMs: dayStart.getTime(), admissions: [admission] });+ return () => {+ const admissions = this.holds.get(sessionId)?.admissions;+ const index = admissions?.indexOf(admission) ?? -1;+ if (admissions && index !== -1) admissions.splice(index, 1);+ };}}@@ -457,7 +488,8 @@ export class SendPacingService {const sentToday = held.reduce((max, a, i) => Math.max(max, a.sentToday + held.length - i), persisted);if (sentToday < allowance) return;- this.refuse('daily_cap', sessionId, secondsUntilNextUtcDay(), {+ const retryAfter = persisted < allowance ? secondsUntilLapsed(held) : secondsUntilNextUtcDay();+ this.refuse('daily_cap', sessionId, retryAfter, {reason: `Daily send allowance of ${allowance} reached for a session ${ageDays} day(s) old`,allowance,sentToday,@@ -542,11 +574,15 @@ export class SendPacingService {): void {// Group adds share this budget: a day spent adding strangers to groups must leave fewer cold// chat reachouts, so fold the in-memory group tally in alongside the chat count.- const coldToday =- this.chatReachoutsToday(sessionId, dayStart, persisted) + this.groupReachoutsToday(sessionId, dayStart);+ const groupToday = this.groupReachoutsToday(sessionId, dayStart);+ const coldToday = this.chatReachoutsToday(sessionId, dayStart, persisted) + groupToday;if (coldToday < allowance) return;- this.refuse('cold_daily_cap', sessionId, secondsUntilNextUtcDay(), {+ const retryAfter =+ persisted + groupToday < allowance+ ? secondsUntilLapsed(this.heldAdmissions(sessionId, dayStart).filter(a => a.cold))+ : secondsUntilNextUtcDay();+ this.refuse('cold_daily_cap', sessionId, retryAfter, {reason: `Daily allowance of ${allowance} new conversation(s) reached for a session ${ageDays} day(s) old`,allowance,coldToday,@@ -669,6 +705,15 @@ function startOfUtcDay(at: Date): Date {return new Date(Date.UTC(at.getUTCFullYear(), at.getUTCMonth(), at.getUTCDate()));}+/**+ * Seconds until every one of these held admissions has lapsed: when the persisted count alone is under+ * the cap, the refusal lifts then, not at the next UTC day.+ */+function secondsUntilLapsed(held: Admission[]): number {+ const newest = held.at(-1)?.at ?? Date.now();+ return Math.max(1, Math.ceil((newest + ADMISSION_WINDOW_MS - Date.now()) / 1000));+}+function secondsUntilNextUtcDay(): number {const now = Date.now();return Math.max(1, Math.ceil((startOfUtcDay(new Date(now)).getTime() + DAY_MS - now) / 1000));