Free, Open Source, Self-Hosted WhatsApp API Gateway
TypeScript apibotgatewayself-hostedwhatsappwhatsapp-apiwhatsapp-automationwhatsapp-botwhatsapp-gatewaywhatsapp-gateway-apiwhatsapp-webwhatsapp-web-api
fix(message): keep send admissions across UTC midnight
Yudhi Armyndharis2f47e191284e
diff --git a/src/modules/message/send-pacing-midnight.spec.ts b/src/modules/message/send-pacing-midnight.spec.tsnew file mode 100644index 000000000..2ee6ea665--- /dev/null+++ b/src/modules/message/send-pacing-midnight.spec.ts@@ -0,0 +1,166 @@+import { ConfigService } from '@nestjs/config';+import { DataSource } from 'typeorm';+import { Message, MessageDirection } from './entities/message.entity';+import { Session } from '../session/entities/session.entity';+import { computeSendPacingConfig } from './send-pacing.config';+import { SEND_PACING_LIMITED, SendPacingService, type SettleAdmission } from './send-pacing.service';++const BEFORE_MIDNIGHT = new Date('2026-08-03T23:59:59.000Z');+const AFTER_MIDNIGHT = new Date('2026-08-04T00:00:01.000Z');++function barrier() {+ let resolve!: () => void;+ const promise = new Promise<void>(yes => (resolve = yes));+ return { promise, resolve };+}++describe('send pacing UTC rollover', () => {+ let db: DataSource;+ let pacing: SendPacingService;+ const settlements: SettleAdmission[] = [];++ beforeEach(async () => {+ jest.useFakeTimers({ doNotFake: ['nextTick', 'setImmediate', 'queueMicrotask'] });+ jest.setSystemTime(BEFORE_MIDNIGHT);+ db = await new DataSource({+ type: 'better-sqlite3',+ database: ':memory:',+ entities: [Message, Session],+ synchronize: true,+ }).initialize();+ await db.getRepository(Session).save({ id: 's1', name: 'sender', createdAt: BEFORE_MIDNIGHT });+ });++ afterEach(async () => {+ for (const settle of settlements.splice(0)) settle();+ jest.restoreAllMocks();+ jest.useRealTimers();+ await db.destroy();+ });++ function configure(rule: 'daily' | 'cold', cap: number): void {+ pacing = new SendPacingService(+ db.getRepository(Message),+ db.getRepository(Session),+ new ConfigService({+ sendPacing: {+ ...computeSendPacingConfig({}),+ enabled: true,+ warmupSchedule: [rule === 'daily' ? cap : 1000],+ coldSchedule: rule === 'cold' ? [cap] : [],+ },+ }),+ );+ }++ const insertRow = (id: string, chatId: string) =>+ db.getRepository(Message).insert({+ id,+ sessionId: 's1',+ chatId,+ from: 'sender',+ to: chatId,+ type: 'text',+ direction: MessageDirection.OUTGOING,+ createdAt: new Date(),+ });++ const admit = async (chatId: string, options: { whilePreparing?: boolean; untilSettled?: boolean }) => {+ const settle = await pacing.assertSendAllowed('s1', chatId, options);+ if (settle) settlements.push(settle);+ return settle;+ };++ const limited = (chatId = '[email protected]') =>+ expect(admit(chatId, { whilePreparing: true })).rejects.toMatchObject({+ status: 429,+ response: { code: SEND_PACING_LIMITED },+ });++ it.each(['daily', 'cold'] as const)('rechecks a %s count that returned after midnight', async rule => {+ configure(rule, 2);+ const entered = barrier();+ const finish = barrier();+ if (rule === 'daily') {+ const repository = db.getRepository(Message);+ const count = repository.count.bind(repository);+ jest.spyOn(repository, 'count').mockImplementationOnce(async options => {+ const value = await count(options);+ entered.resolve();+ await finish.promise;+ return value;+ });+ } else {+ const counters = pacing as unknown as {+ countColdReachoutsToday(sessionId: string, dayStart: Date): Promise<number>;+ };+ const count = counters.countColdReachoutsToday.bind(pacing);+ jest.spyOn(counters, 'countColdReachoutsToday').mockImplementationOnce(async (...args) => {+ const value = await count(...args);+ entered.resolve();+ await finish.promise;+ return value;+ });+ }+ const oldCheck = admit('[email protected]', { whilePreparing: true });+ const outcome = oldCheck.then(+ () => null,+ (error: unknown) => error,+ );+ try {+ await entered.promise;+ jest.setSystemTime(AFTER_MIDNIGHT);+ await insertRow('phone', '[email protected]');+ await admit('[email protected]', { whilePreparing: true });+ finish.resolve();++ expect(await outcome).toMatchObject({ status: 429, response: { code: SEND_PACING_LIMITED } });+ await limited();+ } finally {+ finish.resolve();+ await outcome;+ }+ });++ it.each(['daily', 'cold'] as const)('keeps a %s admission until the engine settles after midnight', async rule => {+ configure(rule, 1);+ await admit('[email protected]', { untilSettled: true });++ jest.setSystemTime(AFTER_MIDNIGHT);++ await limited();+ });++ it.each(['daily', 'cold'] as const)('refunds an unsettled %s admission after midnight', async rule => {+ configure(rule, 1);+ const settle = await admit('[email protected]', { untilSettled: true });+ jest.setSystemTime(AFTER_MIDNIGHT);+ await limited();++ settle?.();++ await expect(admit('[email protected]', { whilePreparing: true })).resolves.toBeInstanceOf(Function);+ });++ it.each(['daily', 'cold'] as const)('gives a completed previous-day %s send a fresh allowance', async rule => {+ configure(rule, 1);+ const settle = await admit('[email protected]', { untilSettled: true });+ await insertRow('completed', '[email protected]');+ settle?.(true);++ jest.setSystemTime(AFTER_MIDNIGHT);++ await expect(admit('[email protected]', { whilePreparing: true })).resolves.toBeInstanceOf(Function);+ });++ it('keeps the original five-minute safety expiry across midnight', async () => {+ configure('daily', 1);+ await admit('[email protected]', { untilSettled: true });+ jest.setSystemTime(new Date('2026-08-04T00:04:58.000Z'));+ await limited();++ jest.setSystemTime(new Date('2026-08-04T00:04:59.000Z'));++ await expect(admit('[email protected]', { whilePreparing: true })).resolves.toBeInstanceOf(Function);+ });+});diff --git a/src/modules/message/send-pacing.service.ts b/src/modules/message/send-pacing.service.tsindex 2dccfff1a..627961e6b 100644--- a/src/modules/message/send-pacing.service.ts+++ b/src/modules/message/send-pacing.service.ts@@ -108,6 +108,8 @@ interface BreakerState {interface Admission {/** Epoch ms its own term ends: a window from its admission, or from its settle. */until: number;+ /** An untilSettled caller still has no engine outcome to count in the persisted day. */+ unsettled: boolean;/** Epoch ms it stops being held, so only its row counts from then on; refreshed by heldAdmissions. */heldUntil: number;/** Reset at UTC rollover, then filled from the first current-day count. */@@ -273,9 +275,16 @@ export class SendPacingService {const sentToday = await this.messageRepository.count({where: { sessionId, direction: MessageDirection.OUTGOING, createdAt: MoreThanOrEqual(dayStart) },});+ // A stale count must not reset the new day's held admissions.+ if (startOfUtcDay(new Date()).getTime() !== dayStart.getTime()) {+ return this.assertSendAllowed(sessionId, chatId, opts);+ }// The overall cap is the cheaper check and bounds everything, so it settles before the cold probe.this.assertUnderDailyCap(sessionId, dayStart, ageDays, allowance, sentToday);const cold = await this.readColdReachouts(sessionId, chatId, dayStart, ageDays, config);+ if (startOfUtcDay(new Date()).getTime() !== dayStart.getTime()) {+ return this.assertSendAllowed(sessionId, chatId, opts);+ }// Judged again, and admitted, with no await from here on: a concurrent request admitted while this// one was reading must count, and this one must count for the next.@@ -293,6 +302,7 @@ export class SendPacingService {: Date.now() + (opts.untilSettled ? UNSETTLED_ADMISSION_MAX_MS : ADMISSION_WINDOW_MS);const admission: Admission = {until,+ unsettled: opts.untilSettled === true,heldUntil: until,sentToday,cold: cold ? { key, coldToday: cold.coldToday } : null,@@ -304,6 +314,7 @@ export class SendPacingService {return (mayHaveSent = false) => {if (settled) return;settled = true;+ admission.unsettled = false;if (mayHaveSent) {admission.until = Date.now() + ADMISSION_WINDOW_MS;return;@@ -340,17 +351,16 @@ export class SendPacingService {private heldAdmissions(sessionId: string, dayStart: Date): Admission[] {const hold = this.holds.get(sessionId);if (!hold) return [];+ const now = Date.now();if (hold.dayStartMs !== dayStart.getTime()) {- // Preparing sends still have no row to count today. Keep their settlement identity and rebase- // their snapshots on the new day's first count; yesterday's finite holds have expired.- hold.admissions = hold.admissions.filter(a => a.until === Infinity);+ // Preparations and engine calls still running may write today; completed yesterday's sends do not.+ hold.admissions = hold.admissions.filter(a => a.until === Infinity || (a.unsettled && a.until > now));hold.dayStartMs = dayStart.getTime();for (const admission of hold.admissions) {admission.sentToday = null;if (admission.cold) admission.cold.coldToday = null;}}- const now = Date.now();// The cold terms lapse as a whole, once no cold admission's own term is running: a warm admission read no// cold count, so it cannot have missed a cold row, and letting it hold them would keep a cold send that// wrote no row counted for as long as warm sends keep arriving. Cleared rather than skipped, so a cold