Free, Open Source, Self-Hosted WhatsApp API Gateway
TypeScript apibotgatewayself-hostedwhatsappwhatsapp-apiwhatsapp-automationwhatsapp-botwhatsapp-gatewaywhatsapp-gateway-apiwhatsapp-webwhatsapp-web-api
fix(pacing): charge group participant adds against the daily cold-reachout cap
Yudhi Armyndharis2f468b3c7e97
diff --git a/src/modules/message/send-pacing-cold-query.spec.ts b/src/modules/message/send-pacing-cold-query.spec.tsindex 0c6e2c00f..83d1bbc11 100644--- a/src/modules/message/send-pacing-cold-query.spec.ts+++ b/src/modules/message/send-pacing-cold-query.spec.ts@@ -210,6 +210,29 @@ describe('group reachouts against a real database', () => {await expect(service.assertReachoutAllowed('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();+ // 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 });+ });++ 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 });++ // 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();+ });+it('is inert for an empty participant list', async () => {await addMessage('[email protected]', TODAY);await addMessage('[email protected]', TODAY);diff --git a/src/modules/message/send-pacing.service.ts b/src/modules/message/send-pacing.service.tsindex 52984850d..8e2b77b07 100644--- a/src/modules/message/send-pacing.service.ts+++ b/src/modules/message/send-pacing.service.ts@@ -73,6 +73,15 @@ const MAX_REFUSAL_KEYS = 1000;export class SendPacingService {private readonly logger = createLogger('SendPacingService');private readonly breakers = new Map<string, BreakerState>();+ /**+ * Per-session count of cold GROUP-ADD reachouts used today. Group adds (createGroup/+ * addParticipants) persist no message row, so `countColdReachoutsToday` — which reads the messages+ * table — cannot see them; without this tally each add request would get the full daily allowance+ * afresh, making the cap per-request instead of per-day. In memory like the breaker (the service+ * doc explains why); it resets by UTC day and on restart, which for an anti-ban budget errs toward+ * fewer reachouts, never more.+ */+ private readonly groupReachoutTally = new Map<string, { dayStartMs: number; count: number }>();private readonly refusalSamples = new Map<string, RefusalSample>();constructor(@@ -143,19 +152,41 @@ export class SendPacingService {const dayStart = startOfUtcDay(new Date());const ageDays = Math.floor((dayStart.getTime() - startOfUtcDay(session.createdAt).getTime()) / DAY_MS);const allowance = this.allowanceForAge(config.coldSchedule, ageDays);- const coldToday = await this.countColdReachoutsToday(sessionId, dayStart);- if (coldToday + coldCount <= allowance) return;+ // Both sources of the day's reachouts: cold chat messages (persisted rows) and prior group adds+ // (the in-memory tally). Group adds persist nothing, so without the tally they would not count+ // against themselves and the cap would reset every request.+ 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;+ }this.refuse('cold_daily_cap', sessionId, secondsUntilNextUtcDay(), {reason:`Reaching ${coldCount} new contact(s) would exceed the daily allowance of ${allowance} ` +- `new conversation(s) for a session ${ageDays} day(s) old (${coldToday} already used)`,+ `new conversation(s) for a session ${ageDays} day(s) old (${usedToday} already used)`,allowance,- coldToday,+ coldToday: usedToday,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);+ return tally && tally.dayStartMs === dayStart.getTime() ? tally.count : 0;+ }++ /** Add to today's group-add tally, resetting it first when the stored entry is from an earlier day. */+ private addGroupReachouts(sessionId: string, dayStart: Date, n: number): void {+ const dayStartMs = dayStart.getTime();+ const tally = this.groupReachoutTally.get(sessionId);+ if (tally && tally.dayStartMs === dayStartMs) tally.count += n;+ else this.groupReachoutTally.set(sessionId, { dayStartMs, count: n });+ }+/*** Record a send that failed. A run of these trips the breaker.*@@ -316,7 +347,10 @@ export class SendPacingService {const dayStart = startOfUtcDay(new Date());const ageDays = Math.floor((dayStart.getTime() - startOfUtcDay(session.createdAt).getTime()) / DAY_MS);const allowance = this.allowanceForAge(config.coldSchedule, ageDays);- const coldToday = await this.countColdReachoutsToday(sessionId, dayStart);+ // 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 persisted chat count.+ const coldToday =+ (await this.countColdReachoutsToday(sessionId, dayStart)) + this.groupReachoutsToday(sessionId, dayStart);if (coldToday < allowance) return;this.refuse('cold_daily_cap', sessionId, secondsUntilNextUtcDay(), {