Free, Open Source, Self-Hosted WhatsApp API Gateway
TypeScript apibotgatewayself-hostedwhatsappwhatsapp-apiwhatsapp-automationwhatsapp-botwhatsapp-gatewaywhatsapp-gateway-apiwhatsapp-webwhatsapp-web-api
fix(automation): keep a raised cooldown through the cooldown sweep
Yudhi Armyndharisdf5e6b74f987
diff --git a/src/modules/automation/automation-rules.service.spec.ts b/src/modules/automation/automation-rules.service.spec.tsindex 0372eba36..c12d47f7c 100644--- a/src/modules/automation/automation-rules.service.spec.ts+++ b/src/modules/automation/automation-rules.service.spec.ts@@ -283,6 +283,28 @@ describe('AutomationRulesService', () => {expect(sends).toHaveLength(2);});+ it('cooldown: a raised cooldownSeconds survives the sweep of a large cooldown map', async () => {+ const rule = await service.create('sessA', { name: 'all', replyText: 'ack', cooldownSeconds: 60 });+ const start = Date.now();+ const now = jest.spyOn(Date, 'now').mockReturnValue(start);+ try {+ await service.evaluateInbound('sessA', inbound());+ await service.update('sessA', rule.id, { cooldownSeconds: 3600 });+ // Pad the map past the sweep threshold with copies of the live entry.+ const cooldowns = (service as unknown as { cooldowns: Map<string, unknown> }).cooldowns;+ const entry = cooldowns.values().next().value;+ for (let i = 0; i < 10_000; i++) cooldowns.set(`pad:${i}`, entry);+ now.mockReturnValue(start + 120_000);+ // Another chat fires, which sweeps the map before it enters its own cooldown.+ await service.evaluateInbound('sessA', inbound({ id: 'wamid.2', chatId: '[email protected]', from: '[email protected]' }));+ await service.evaluateInbound('sessA', inbound({ id: 'wamid.3' }));+ } finally {+ now.mockRestore();+ }++ expect(sends.map(s => s.chatId)).toEqual(['[email protected]', '[email protected]']);+ });+it('cooldownSeconds 0 disables the quiet period', async () => {await service.create('sessA', { name: 'all', replyText: 'ack', cooldownSeconds: 0 });diff --git a/src/modules/automation/automation-rules.service.ts b/src/modules/automation/automation-rules.service.tsindex 8fc398a16..5fa771f5a 100644--- a/src/modules/automation/automation-rules.service.ts+++ b/src/modules/automation/automation-rules.service.ts@@ -10,7 +10,11 @@ import { evaluateFilters } from '../webhook/filters/filter-evaluator';import { PLUGIN_MESSAGE_PORT, type PluginMessagePort } from '../../core/plugins/plugin-host-ports';import { AutomationRule } from './entities/automation-rule.entity';import { Session } from '../session/entities/session.entity';-import { CreateAutomationRuleDto, UpdateAutomationRuleDto } from './dto/automation-rule.dto';+import {+ AUTOMATION_COOLDOWN_MAX_SECONDS,+ CreateAutomationRuleDto,+ UpdateAutomationRuleDto,+} from './dto/automation-rule.dto';/** Entries above this size trigger a sweep of expired cooldowns before inserting the next one. */const COOLDOWN_SWEEP_THRESHOLD = 10_000;@@ -46,11 +50,11 @@ export class AutomationRulesService {private readonly logger = createLogger('AutomationRulesService');/**- * `${ruleId}:${chatId}` -> when the rule last fired in that chat, and the expiry its cooldown at- * that time implied. The quiet period is judged against the rule's CURRENT cooldownSeconds, so an- * edit takes effect on a window already running; `until` only drives the sweep. Per-process.+ * `${ruleId}:${chatId}` -> when the rule last fired in that chat. The quiet period is judged against+ * the rule's CURRENT cooldownSeconds, so an edit takes effect on a window already running; the sweep+ * only drops an entry older than the longest cooldown a rule may have. Per-process.*/- private readonly cooldowns = new Map<string, { firedAt: number; until: number }>();+ private readonly cooldowns = new Map<string, number>();private messagePort?: PluginMessagePort;@@ -234,18 +238,18 @@ export class AutomationRulesService {private inCooldown(rule: AutomationRule, chatId: string): boolean {if (!rule.cooldownSeconds) return false;- const entry = this.cooldowns.get(`${rule.id}:${chatId}`);- return entry !== undefined && entry.firedAt + rule.cooldownSeconds * 1000 > Date.now();+ const firedAt = this.cooldowns.get(`${rule.id}:${chatId}`);+ return firedAt !== undefined && firedAt + rule.cooldownSeconds * 1000 > Date.now();}private enterCooldown(rule: AutomationRule, chatId: string): void {if (!rule.cooldownSeconds) return;const now = Date.now();if (this.cooldowns.size >= COOLDOWN_SWEEP_THRESHOLD) {- for (const [key, { until }] of this.cooldowns) {- if (until <= now) this.cooldowns.delete(key);+ for (const [key, firedAt] of this.cooldowns) {+ if (firedAt + AUTOMATION_COOLDOWN_MAX_SECONDS * 1000 <= now) this.cooldowns.delete(key);}}- this.cooldowns.set(`${rule.id}:${chatId}`, { firedAt: now, until: now + rule.cooldownSeconds * 1000 });+ this.cooldowns.set(`${rule.id}:${chatId}`, now);}}