Free, Open Source, Self-Hosted WhatsApp API Gateway
TypeScript apibotgatewayself-hostedwhatsappwhatsapp-apiwhatsapp-automationwhatsapp-botwhatsapp-gatewaywhatsapp-gateway-apiwhatsapp-webwhatsapp-web-api
fix(engine): charge the cold-reachout budget only after the group call resolves
Yudhi Armyndharis6033ced1c70f
diff --git a/CHANGELOG.md b/CHANGELOG.mdindex ca82f3fc6..3c5976e04 100644--- a/CHANGELOG.md+++ b/CHANGELOG.md@@ -9,6 +9,7 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0### Fixed+- The cold-reachout budget is charged only after the group engine call resolves; a createGroup that 501s (whatsapp-web.js, always) or an add the engine refuses no longer burns the day's allowance for participants never contacted.- docs/06 repair pass over the Errors lines: the ingress `401` is the signature failure (not an API-key error), label writes have no `404`, the catalog product lookup answers `200` empty (not `404`), search's `501` names the no-provider case, multi-line Errors blocks were re-joined (no severed sentences, duplicate codes, or `· ·` separators), and the gate now reads wrapped blocks.- docs/14 corrects four hazard-table release labels (instance-config is 0.18.0, the reload `409` is 0.15.0, the group-summary retypes are 0.14.6, Baileys 5xx is 0.14.5), docs/03 drops a duplicated `health/`, and docs/10's scaling note matches docs/13's "still deploy replicas: 1" stance.- docs/06's audit section scopes the always-null columns correctly (`userAgent`/`statusCode` always null; `method`/`path` populated on auth-failure, key-lifecycle and queue-board rows), the Chats quote box renders identically under system-dark and explicit dark, and the Logs empty state gives server-filter guidance when only the severity filter is active (13 locales).diff --git a/src/modules/group/group.service.spec.ts b/src/modules/group/group.service.spec.tsindex a484b6f4e..676524d6f 100644--- a/src/modules/group/group.service.spec.ts+++ b/src/modules/group/group.service.spec.ts@@ -8,7 +8,10 @@ import { SendPacingService } from '../message/send-pacing.service';/** Pacing is off by default; its own spec covers the governor, so here it must simply not refuse. */const inertPacing = (): SendPacingService =>- ({ assertReachoutAllowed: jest.fn().mockResolvedValue(undefined) }) as unknown as SendPacingService;+ ({+ assertReachoutAllowed: jest.fn().mockResolvedValue(0),+ chargeGroupReachouts: jest.fn(),+ }) as unknown as SendPacingService;describe('GroupService', () => {const makeService = (engine: Partial<IWhatsAppEngine> | undefined, pacing: SendPacingService = inertPacing()) => {@@ -17,6 +20,15 @@ describe('GroupService', () => {return new GroupService(engines, pacing);};+ const makeServiceWithPacing = (+ engine: Partial<IWhatsAppEngine>,+ pacing: Record<string, jest.Mock>,+ ): { svc: GroupService; pacing: Record<string, jest.Mock> } => {+ const engines = new EngineRegistry();+ engines.set('s1', engine as IWhatsAppEngine);+ return { svc: new GroupService(engines, pacing as unknown as SendPacingService), pacing };+ };+// On Baileys the id reaches sock.updateProfilePicture/removeProfilePicture verbatim, and Baileys// omits the `target` attribute whenever the jid is the account's own — so a 1:1 id passed where a// group id belongs replaced or PERMANENTLY DELETED the account's own profile picture and answered@@ -105,6 +117,45 @@ describe('GroupService', () => {await expect(svc.getGroupInfo('s1', 'g1')).resolves.toEqual({ id: 'g1', name: 'G' });});+ it('charges the cold-reachout budget only after the engine call resolves', async () => {+ const addParticipants = jest.fn().mockResolvedValue(undefined);+ const { svc, pacing } = makeServiceWithPacing(+ { addParticipants },+ {+ assertReachoutAllowed: jest.fn().mockResolvedValue(3),+ chargeGroupReachouts: jest.fn(),+ },+ );+ await svc.addParticipants('s1', 'g1', ['[email protected]']);+ expect(pacing.chargeGroupReachouts).toHaveBeenCalledWith('s1', 3);+ });++ it('does not charge the budget when the engine refuses the add (the participants were never contacted)', async () => {+ const addParticipants = jest.fn().mockRejectedValue(new Error('no admin rights'));+ const { svc, pacing } = makeServiceWithPacing(+ { addParticipants },+ {+ assertReachoutAllowed: jest.fn().mockResolvedValue(3),+ chargeGroupReachouts: jest.fn(),+ },+ );+ await expect(svc.addParticipants('s1', 'g1', ['[email protected]'])).rejects.toThrow('no admin rights');+ expect(pacing.chargeGroupReachouts).not.toHaveBeenCalled();+ });++ it('does not charge the budget when createGroup fails (whatsapp-web.js always 501s)', async () => {+ const createGroup = jest.fn().mockRejectedValue(new Error('EngineNotSupportedError'));+ const { svc, pacing } = makeServiceWithPacing(+ { createGroup },+ {+ assertReachoutAllowed: jest.fn().mockResolvedValue(2),+ chargeGroupReachouts: jest.fn(),+ },+ );+ await expect(svc.createGroup('s1', 'G', ['[email protected]', '[email protected]'])).rejects.toThrow();+ expect(pacing.chargeGroupReachouts).not.toHaveBeenCalled();+ });+it('passes participant lists straight through to the engine', async () => {const addParticipants = jest.fn().mockResolvedValue(undefined);const svc = makeService({ addParticipants });diff --git a/src/modules/group/group.service.ts b/src/modules/group/group.service.tsindex 76f4bffc1..9c8fac00e 100644--- a/src/modules/group/group.service.ts+++ b/src/modules/group/group.service.ts@@ -67,8 +67,10 @@ export class GroupService {*/async createGroup(sessionId: string, name: string, participants: string[]) {this.assertAddressableParticipants(participants);- await this.pacing.assertReachoutAllowed(sessionId, participants);- return this.getEngine(sessionId).createGroup(name, participants);+ const coldCount = await this.pacing.assertReachoutAllowed(sessionId, participants);+ const group = await this.getEngine(sessionId).createGroup(name, participants);+ this.pacing.chargeGroupReachouts(sessionId, coldCount);+ return group;}/**@@ -78,8 +80,10 @@ export class GroupService {*/async addParticipants(sessionId: string, groupId: string, participants: string[]) {this.assertAddressableParticipants(participants);- await this.pacing.assertReachoutAllowed(sessionId, participants);- return this.getEngine(sessionId).addParticipants(groupId, participants);+ const coldCount = await this.pacing.assertReachoutAllowed(sessionId, participants);+ const result = await this.getEngine(sessionId).addParticipants(groupId, participants);+ this.pacing.chargeGroupReachouts(sessionId, coldCount);+ return result;}removeParticipants(sessionId: string, groupId: string, participants: string[]) {diff --git a/src/modules/message/send-pacing-cold-query.spec.ts b/src/modules/message/send-pacing-cold-query.spec.tsindex c65d253c4..05f893710 100644--- a/src/modules/message/send-pacing-cold-query.spec.ts+++ b/src/modules/message/send-pacing-cold-query.spec.ts@@ -221,14 +221,20 @@ describe('group reachouts against a real database', () => {await ds.destroy();});+ // The group callers charge only after the engine call resolves; mirror that flow so the tally+ // semantics below (accumulation, day reset, shared budget) are tested through the real seam.+ const reachout = async (sessionId: string, ids: string[]): Promise<void> => {+ service.chargeGroupReachouts(sessionId, await service.assertReachoutAllowed(sessionId, ids));+ };+it("allows a batch that fits inside the day's remaining allowance", async () => {- await expect(service.assertReachoutAllowed('s1', ['[email protected]', '[email protected]', '[email protected]'])).resolves.toBeUndefined();+ await expect(reachout('s1', ['[email protected]', '[email protected]', '[email protected]'])).resolves.toBeUndefined();});// The cost is per stranger, not per call — otherwise one request adding two hundred numbers would// cost exactly as much as adding one, which is the abuse the rule exists to bound.it('charges the batch per new contact, not per call', async () => {- await expect(service.assertReachoutAllowed('s1', ['[email protected]', '[email protected]', '[email protected]', '[email protected]'])).rejects.toMatchObject({+ await expect(reachout('s1', ['[email protected]', '[email protected]', '[email protected]', '[email protected]'])).rejects.toMatchObject({status: 429,});});@@ -239,7 +245,7 @@ describe('group reachouts against a real database', () => {// Five participants, but only three are strangers — exactly the allowance.await expect(- service.assertReachoutAllowed('s1', ['[email protected]', '[email protected]', '[email protected]', '[email protected]', '[email protected]']),+ reachout('s1', ['[email protected]', '[email protected]', '[email protected]', '[email protected]', '[email protected]']),).resolves.toBeUndefined();});@@ -247,9 +253,7 @@ describe('group reachouts against a real database', () => {await addMessage('[email protected]', YESTERDAY);// Four participants, but the dialect twin is known — three strangers, exactly the allowance.- await expect(- service.assertReachoutAllowed('s1', ['[email protected]', '[email protected]', '[email protected]', '[email protected]']),- ).resolves.toBeUndefined();+ await expect(reachout('s1', ['[email protected]', '[email protected]', '[email protected]', '[email protected]'])).resolves.toBeUndefined();});// The group endpoints accept a bare number and the engines qualify it themselves, so the probe@@ -258,15 +262,11 @@ describe('group reachouts against a real database', () => {await addMessage('[email protected]', YESTERDAY);// Four participants, but the bare-number form of a known contact is not a stranger — three are.- await expect(- service.assertReachoutAllowed('s1', ['628555', '[email protected]', '[email protected]', '[email protected]']),- ).resolves.toBeUndefined();+ await expect(reachout('s1', ['628555', '[email protected]', '[email protected]', '[email protected]'])).resolves.toBeUndefined();});it('counts a repeated id once', async () => {- await expect(- service.assertReachoutAllowed('s1', ['[email protected]', '[email protected]', '[email protected]', '[email protected]', '[email protected]']),- ).resolves.toBeUndefined();+ await expect(reachout('s1', ['[email protected]', '[email protected]', '[email protected]', '[email protected]', '[email protected]'])).resolves.toBeUndefined();});// The two paths share one budget, so a day spent on direct messages leaves nothing for group adds.@@ -274,32 +274,32 @@ describe('group reachouts against a real database', () => {await addMessage('[email protected]', TODAY);await addMessage('[email protected]', TODAY);- await expect(service.assertReachoutAllowed('s1', ['[email protected]'])).resolves.toBeUndefined();+ await expect(reachout('s1', ['[email protected]'])).resolves.toBeUndefined();await addMessage('[email protected]', TODAY);- await expect(service.assertReachoutAllowed('s1', ['[email protected]'])).rejects.toMatchObject({ status: 429 });+ await expect(reachout('s1', ['[email protected]'])).rejects.toMatchObject({ status: 429 });});// The regression this file exists to lock: group adds persist no message row, so the cap must be// charged in memory or every request gets the full allowance afresh (per-request, not per-day).it('accumulates across calls in the same day — the allowance is per-day, not per-request', async () => {- await expect(service.assertReachoutAllowed('s1', ['[email protected]', '[email protected]', '[email protected]'])).resolves.toBeUndefined();+ await expect(reachout('s1', ['[email protected]', '[email protected]', '[email protected]'])).resolves.toBeUndefined();// The allowance (3) is now spent for the day, even though no message row was written.- await expect(service.assertReachoutAllowed('s1', ['[email protected]'])).rejects.toMatchObject({ status: 429 });+ await expect(reachout('s1', ['[email protected]'])).rejects.toMatchObject({ status: 429 });});it('charges the chat cold cap too, so group adds leave fewer direct cold reachouts', async () => {- await service.assertReachoutAllowed('s1', ['[email protected]', '[email protected]', '[email protected]']);// Budget consumed by group adds; a fresh cold direct message must now be refused.await expect(service.assertSendAllowed('s1', '[email protected]')).rejects.toMatchObject({ status: 429 });});it('resets the group tally on the UTC day boundary', async () => {- await service.assertReachoutAllowed('s1', ['[email protected]', '[email protected]', '[email protected]']);- await expect(service.assertReachoutAllowed('s1', ['[email protected]'])).rejects.toMatchObject({ status: 429 });+ await expect(reachout('s1', ['[email protected]'])).rejects.toMatchObject({ status: 429 });// Roll into the next UTC day: the tally is keyed by day, so the allowance is fresh.jest.setSystemTime(new Date(NOW.getTime() + DAY_MS));- await expect(service.assertReachoutAllowed('s1', ['[email protected]', '[email protected]', '[email protected]'])).resolves.toBeUndefined();+ await expect(reachout('s1', ['[email protected]', '[email protected]', '[email protected]'])).resolves.toBeUndefined();});it('is inert for an empty participant list', async () => {@@ -307,6 +307,6 @@ describe('group reachouts against a real database', () => {await addMessage('[email protected]', TODAY);await addMessage('[email protected]', TODAY);- await expect(service.assertReachoutAllowed('s1', [])).resolves.toBeUndefined();+ await expect(service.assertReachoutAllowed('s1', [])).resolves.toBe(0);});});diff --git a/src/modules/message/send-pacing.service.ts b/src/modules/message/send-pacing.service.tsindex 06c98ea7b..0e54b4329 100644--- a/src/modules/message/send-pacing.service.ts+++ b/src/modules/message/send-pacing.service.ts@@ -166,12 +166,12 @@ export class SendPacingService {* report per-participant outcomes for real failures already — a pacing refusal must not be* mistaken for one of those.*/- async assertReachoutAllowed(sessionId: string, contactIds: string[]): Promise<void> {+ async assertReachoutAllowed(sessionId: string, contactIds: string[]): Promise<number> {const config = resolveSendPacingConfig(this.configService);- if (!config.enabled) return;+ if (!config.enabled) return 0;this.assertBreakerClosed(sessionId, config);- if (config.coldSchedule.length === 0 || contactIds.length === 0) return;+ if (config.coldSchedule.length === 0 || contactIds.length === 0) return 0;// The same id twice in one request is one contact, and must cost one. Each contact is probed// under both user-id dialects (see dialectVariants) — a contact known under the other spelling@@ -186,10 +186,10 @@ export class SendPacingService {.getRawMany<{ chatId: string }>();const knownIds = new Set(knownRows.map(row => row.chatId));const coldCount = unique.filter(id => !variantsByContact.get(id)!.some(v => knownIds.has(v))).length;- if (coldCount === 0) return;+ if (coldCount === 0) return 0;const session = await this.sessionRepository.findOne({ where: { id: sessionId } });- if (!session) return;+ if (!session) return 0;const dayStart = startOfUtcDay(new Date());const ageDays = Math.floor((dayStart.getTime() - startOfUtcDay(session.createdAt).getTime()) / DAY_MS);@@ -200,9 +200,10 @@ export class SendPacingService {const usedToday =(await this.countColdReachoutsToday(sessionId, dayStart)) + this.groupReachoutsToday(sessionId, dayStart);if (usedToday + coldCount <= allowance) {- // Charge the budget now, on the allowed path, so a second add request in the same day sees it.- this.addGroupReachouts(sessionId, dayStart, coldCount);- return;+ // Caller charges this AFTER the engine call resolves (chargeGroupReachouts): a createGroup+ // that 501s on whatsapp-web.js (always) or an add the engine refuses must not burn the+ // day's cold allowance for participants never contacted.+ return coldCount;}this.refuse('cold_daily_cap', sessionId, secondsUntilNextUtcDay(), {@@ -215,6 +216,15 @@ export class SendPacingService {});}+ /**+ * Charge `coldCount` cold reachouts against the in-memory group tally. Split out of+ * assertReachoutAllowed so the group callers charge only after the engine call resolves.+ */+ chargeGroupReachouts(sessionId: string, coldCount: number): void {+ if (coldCount <= 0) return;+ this.addGroupReachouts(sessionId, startOfUtcDay(new Date()), coldCount);+ }+/** Cold group-add reachouts charged to this session today (0 once the stored day rolls over). */private groupReachoutsToday(sessionId: string, dayStart: Date): number {const tally = this.groupReachoutTally.get(sessionId);