Free, Open Source, Self-Hosted WhatsApp API Gateway
TypeScript apibotgatewayself-hostedwhatsappwhatsapp-apiwhatsapp-automationwhatsapp-botwhatsapp-gatewaywhatsapp-gateway-apiwhatsapp-webwhatsapp-web-api
fix(group): keep cold reachouts charged when the outcome is unknown
Yudhi Armyndharise2b1a67c16f3
diff --git a/src/modules/group/group.service.spec.ts b/src/modules/group/group.service.spec.tsindex 50db54ea3..1cad0e824 100644--- a/src/modules/group/group.service.spec.ts+++ b/src/modules/group/group.service.spec.ts@@ -4,6 +4,7 @@ import { EngineRegistry } from '../../engine/engine-registry.service';import { IWhatsAppEngine } from '../../engine/interfaces/whatsapp-engine.interface';import { EngineNotSupportedError } from '../../common/errors/engine-not-supported.error';import { EngineRefusedError } from '../../common/errors/engine-refused.error';+import { EngineTransportError } from '../../common/errors/engine-transport.error';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. */@@ -131,7 +132,7 @@ describe('GroupService', () => {});it('refunds the reservation when the engine refuses the add (the participants were never contacted)', async () => {- const addParticipants = jest.fn().mockRejectedValue(new Error('no admin rights'));+ const addParticipants = jest.fn().mockRejectedValue(new EngineRefusedError('no admin rights'));const reservation = { coldCount: 3, dayStartMs: 1 };const { svc, pacing } = makeServiceWithPacing({ addParticipants },@@ -145,7 +146,7 @@ describe('GroupService', () => {});it('refunds the reservation when createGroup fails (whatsapp-web.js always 501s)', async () => {- const createGroup = jest.fn().mockRejectedValue(new Error('EngineNotSupportedError'));+ const createGroup = jest.fn().mockRejectedValue(new EngineNotSupportedError('createGroup'));const reservation = { coldCount: 2, dayStartMs: 1 };const { svc, pacing } = makeServiceWithPacing({ createGroup },@@ -158,6 +159,24 @@ describe('GroupService', () => {expect(pacing.refundGroupReachouts).toHaveBeenCalledWith('s1', reservation);});+ it.each([+ ['a timed-out add (WhatsApp may still apply it)', new EngineTransportError('did not answer in time')],+ ['a raw socket error', new Error('Connection Closed')],+ ])('keeps the reservation charged after %s: the outcome is unknown', async (_label, error) => {+ const addParticipants = jest.fn().mockRejectedValue(error);+ const createGroup = jest.fn().mockRejectedValue(error);+ const { svc, pacing } = makeServiceWithPacing(+ { addParticipants, createGroup },+ {+ assertReachoutAllowed: jest.fn().mockResolvedValue({ coldCount: 3, dayStartMs: 1 }),+ refundGroupReachouts: jest.fn(),+ },+ );+ await expect(svc.addParticipants('s1', 'g1', ['[email protected]'])).rejects.toBe(error);+ await expect(svc.createGroup('s1', 'G', ['[email protected]'])).rejects.toBe(error);+ expect(pacing.refundGroupReachouts).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 c37c65118..91cba8c50 100644--- a/src/modules/group/group.service.ts+++ b/src/modules/group/group.service.ts@@ -8,6 +8,18 @@ import { SetGroupPictureDto } from './dto/group.dto';import { paginate, ListOptions } from '../../common/utils/paginate';import { SendPacingService } from '../message/send-pacing.service';import { createLogger } from '../../common/services/logger.service';+import { EngineNotSupportedError } from '../../common/errors/engine-not-supported.error';++/**+ * Whether a failed paced write provably contacted nobody, so its reserved budget can go back: a+ * client or refusal status (400 bad input, 403 refused, 404 no such group, 409 not ready) or a 501+ * for an operation the engine lacks. Anything else (a 503 deadline that abandoned an IQ still in+ * flight, a dropped socket, a dead page) leaves the outcome unknown, and WhatsApp may already have+ * added the participants, so the batch stays charged.+ */+function contactedNobody(error: unknown): boolean {+ return error instanceof HttpException && (error.getStatus() < 500 || error instanceof EngineNotSupportedError);+}/*** Owns engine access for group operations. Controllers depend on this service instead of@@ -74,8 +86,9 @@ export class GroupService {try {return await this.getEngine(sessionId).createGroup(name, participants);} catch (error) {- // Nobody was invited, so the reserved budget goes back (whatsapp-web.js always 501s here).- this.pacing.refundGroupReachouts(sessionId, reservation);+ // A refusal invited nobody, so the reserved budget goes back (whatsapp-web.js always 501s here).+ // An outcome-unknown failure stays charged.+ if (contactedNobody(error)) this.pacing.refundGroupReachouts(sessionId, reservation);throw error;}}@@ -92,8 +105,8 @@ export class GroupService {return await this.getEngine(sessionId).addParticipants(groupId, participants);} catch (error) {// A refused add contacted nobody. Per-participant failures an engine reports without throwing- // stay charged: the batch was attempted.- this.pacing.refundGroupReachouts(sessionId, reservation);+ // stay charged: the batch was attempted. So does an outcome-unknown failure.+ if (contactedNobody(error)) this.pacing.refundGroupReachouts(sessionId, reservation);throw error;}}