Free, Open Source, Self-Hosted WhatsApp API Gateway
TypeScript apibotgatewayself-hostedwhatsappwhatsapp-apiwhatsapp-automationwhatsapp-botwhatsapp-gatewaywhatsapp-gateway-apiwhatsapp-webwhatsapp-web-api
fix(baileys): drop expired group lists from memory
Yudhi Armyndharis23ef067683cf
diff --git a/src/engine/adapters/baileys-group-metadata-cache.spec.ts b/src/engine/adapters/baileys-group-metadata-cache.spec.tsindex 383d6e5d6..e99bc28d8 100644--- a/src/engine/adapters/baileys-group-metadata-cache.spec.ts+++ b/src/engine/adapters/baileys-group-metadata-cache.spec.ts@@ -14,6 +14,10 @@ describe('GroupMetadataCache', () => {beforeEach(() => {clock = 1_000_000;+ jest.useFakeTimers();+ });+ afterEach(() => {+ jest.useRealTimers();});describe('reading through', () => {@@ -171,6 +175,62 @@ describe('GroupMetadataCache', () => {});});+ // The TTL is checked when a group is read, so without a timer a group nobody sends to again would keep+ // its participant list in memory for as long as the socket lives. The manual clock does not move with the+ // fake timers, so each step advances both.+ describe('expiry', () => {+ const elapse = (ms: number): void => {+ clock += ms;+ jest.advanceTimersByTime(ms);+ };++ it('drops an entry whose TTL ran out without its group being read again', async () => {+ const cache = build();+ await cache.read(GROUP, () => Promise.resolve(group(GROUP)));+ await cache.read(OTHER, () => Promise.resolve(group(OTHER)));++ elapse(1000);++ expect(cache.size).toBe(0);+ });++ it('keeps an entry still within its TTL when the timer fires, drops it at the next, then stops', async () => {+ const cache = build();+ await cache.read(GROUP, () => Promise.resolve(group(GROUP)));+ elapse(600);+ await cache.read(OTHER, () => Promise.resolve(group(OTHER)));++ elapse(400); // GROUP is due, OTHER is 400 ms old+ expect(cache.size).toBe(1);++ elapse(1000);+ expect(cache.size).toBe(0);+ expect(jest.getTimerCount()).toBe(0);+ });++ it('stops its timer when the cache is cleared', async () => {+ const cache = build();+ await cache.read(GROUP, () => Promise.resolve(group(GROUP)));+ expect(jest.getTimerCount()).toBe(1);++ cache.clear();++ expect(jest.getTimerCount()).toBe(0);+ });++ it('never waits longer than a Node timer accepts, whatever the TTL', async () => {+ const arm = jest.spyOn(global, 'setTimeout');+ try {+ const cache = build(2 ** 40);+ await cache.read(GROUP, () => Promise.resolve(group(GROUP)));++ expect(arm).toHaveBeenLastCalledWith(expect.any(Function), 2 ** 31 - 1);+ } finally {+ arm.mockRestore();+ }+ });+ });+describe('groups.update batches', () => {it('drops a group whose partial change arrives, and leaves the others', async () => {const cache = build();diff --git a/src/engine/adapters/baileys-group-metadata-cache.ts b/src/engine/adapters/baileys-group-metadata-cache.tsindex 3c428f197..0b943f4de 100644--- a/src/engine/adapters/baileys-group-metadata-cache.ts+++ b/src/engine/adapters/baileys-group-metadata-cache.ts@@ -1,5 +1,5 @@import type { GroupMetadata } from '@whiskeysockets/baileys';-import { resolveNonNegativeIntEnv } from '../../config/configuration';+import { MAX_TIMER_MS, resolveNonNegativeIntEnv } from '../../config/configuration';/** How long a group's participant list is reused before Baileys reads it again; 0 switches the cache off. */const DEFAULT_GROUP_METADATA_CACHE_TTL_MS = 5 * 60_000;@@ -35,6 +35,8 @@ export class GroupMetadataCache {* it is not kept and no later read waits on it.*/private readonly inFlight = new Map<string, Promise<GroupMetadata>>();+ /** The pending timer that drops expired entries; armed while the cache holds any. */+ private expiryTimer?: ReturnType<typeof setTimeout>;constructor(private readonly ttlMs: number,@@ -113,6 +115,8 @@ export class GroupMetadataCache {clear(): void {this.entries.clear();this.inFlight.clear();+ clearTimeout(this.expiryTimer);+ this.expiryTimer = undefined;}/**@@ -135,5 +139,25 @@ export class GroupMetadataCache {const [oldest] = this.entries.keys();this.entries.delete(oldest);}+ this.scheduleExpiry();+ }++ /**+ * Expiry is otherwise checked only when a group is read, so a group nobody sends to again would keep+ * its participant list for as long as the socket lives. One timer drops what has expired, and runs+ * again only while the cache still holds entries.+ */+ private scheduleExpiry(): void {+ if (this.expiryTimer) return;+ const dropExpired = (): void => {+ this.expiryTimer = undefined;+ const now = this.now();+ for (const [jid, cached] of this.entries) {+ if (now - cached.storedAt >= this.ttlMs) this.entries.delete(jid);+ }+ if (this.entries.size > 0) this.scheduleExpiry();+ };+ this.expiryTimer = setTimeout(dropExpired, Math.min(this.ttlMs, MAX_TIMER_MS));+ this.expiryTimer.unref();}}