Free, Open Source, Self-Hosted WhatsApp API Gateway
TypeScript apibotgatewayself-hostedwhatsappwhatsapp-apiwhatsapp-automationwhatsapp-botwhatsapp-gatewaywhatsapp-gateway-apiwhatsapp-webwhatsapp-web-api
fix(baileys): keep saved contacts out of the peer eviction path
Yudhi Armyndharis0d0d2cb4634b
diff --git a/src/engine/adapters/baileys-session-store.spec.ts b/src/engine/adapters/baileys-session-store.spec.tsindex 5bebc6381..6ef0959ae 100644--- a/src/engine/adapters/baileys-session-store.spec.ts+++ b/src/engine/adapters/baileys-session-store.spec.ts@@ -581,27 +581,39 @@ describe('BaileysSessionStore', () => {return new BaileysSessionStore(lidStore);};- it('evicts the oldest contact once over the cap; the miss reads as "unknown"', () => {+ it('evicts the oldest unsaved contact once over the cap; the miss reads as "unknown"', () => {const s = storeWithCap('2');- s.upsertContacts([{ id: '[email protected]', name: 'A' }]);- s.upsertContacts([{ id: '[email protected]', name: 'B' }]);- s.upsertContacts([{ id: '[email protected]', name: 'C' }]);- expect(s.listContacts()).toHaveLength(2);- expect(s.findContact('[email protected]')).toBeNull(); // evicted — same as never seen- expect(s.findContact('[email protected]')?.name).toBe('B');- expect(s.findContact('[email protected]')?.name).toBe('C');+ s.upsertContacts([{ id: '[email protected]', notify: 'A' }]);+ s.upsertContacts([{ id: '[email protected]', notify: 'B' }]);+ s.upsertContacts([{ id: '[email protected]', notify: 'C' }]);+ expect(s.findContact('[email protected]')).toBeNull(); // evicted, same as never seen+ expect(s.findContact('[email protected]')?.pushName).toBe('B');+ expect(s.findContact('[email protected]')?.pushName).toBe('C');});it('treats a read as usage: a refreshed entry survives while a stale one is evicted (LRU)', () => {const s = storeWithCap('2');- s.upsertContacts([{ id: '[email protected]', name: 'A' }]);- s.upsertContacts([{ id: '[email protected]', name: 'B' }]);- expect(s.findContact('[email protected]')?.name).toBe('A'); // refresh A- s.upsertContacts([{ id: '[email protected]', name: 'C' }]); // evicts B, not A- expect(s.findContact('[email protected]')?.name).toBe('A');+ s.upsertContacts([{ id: '[email protected]', notify: 'A' }]);+ s.upsertContacts([{ id: '[email protected]', notify: 'B' }]);+ expect(s.findContact('[email protected]')?.pushName).toBe('A'); // refresh A+ s.upsertContacts([{ id: '[email protected]', notify: 'C' }]); // evicts B, not A+ expect(s.findContact('[email protected]')?.pushName).toBe('A');expect(s.findContact('[email protected]')).toBeNull();});+ it('keeps the saved address book when unsaved peers overflow the cap', () => {+ // The two populations share one map: a handful of contacts the account saved, and every peer+ // seen once in a group or a broadcast. Only the second grows without limit, and it used to+ // evict the first, emptying GET /contacts on a busy session.+ const s = storeWithCap('3');+ s.upsertContacts([{ id: '[email protected]', name: 'Alice' }]);+ for (let i = 0; i < 50; i++) {+ s.upsertContacts([{ id: `62${9000 + i}@s.whatsapp.net`, notify: `peer ${i}` }]);+ }+ expect(s.findContact('[email protected]')?.name).toBe('Alice');+ expect(s.listContacts()).toEqual([expect.objectContaining({ name: 'Alice' })]);+ });+it('bounds chats: listChats stays at the cap and drops the oldest conversation', () => {const s = storeWithCap('2');s.upsertChats([{ id: '[email protected]', name: 'A' }]);@@ -678,16 +690,17 @@ describe('BaileysSessionStore', () => {it('falls back to the 5000 default for a garbage override', () => {const s = storeWithCap('not-a-number');- s.upsertContacts(Array.from({ length: 5001 }, (_, i) => ({ id: `62${100000 + i}@s.whatsapp.net`, name: 'x' })));- expect(s.listContacts()).toHaveLength(5000);+ // Unsaved peers: the cap governs exactly this population (a saved contact is pinned).+ s.upsertContacts(Array.from({ length: 5001 }, (_, i) => ({ id: `62${100000 + i}@s.whatsapp.net`, notify: 'x' })));expect(s.findContact('[email protected]')).toBeNull(); // the oldest went firstexpect(s.findContact('[email protected]')).not.toBeNull();});it('treats a blank override as unset, not as 0 (unbounded)', () => {const s = storeWithCap('');- s.upsertContacts(Array.from({ length: 5001 }, (_, i) => ({ id: `62${100000 + i}@s.whatsapp.net`, name: 'x' })));- expect(s.listContacts()).toHaveLength(5000);+ s.upsertContacts(Array.from({ length: 5001 }, (_, i) => ({ id: `62${100000 + i}@s.whatsapp.net`, notify: 'x' })));+ expect(s.findContact('[email protected]')).toBeNull();+ expect(s.findContact('[email protected]')).not.toBeNull();});});});diff --git a/src/engine/adapters/baileys-session-store.ts b/src/engine/adapters/baileys-session-store.tsindex 55f9e5c21..83730687d 100644--- a/src/engine/adapters/baileys-session-store.ts+++ b/src/engine/adapters/baileys-session-store.ts@@ -20,11 +20,19 @@ export const SESSION_STORE_MAP_CAP_DEFAULT = 5000;* Insertion-ordered Map with an LRU cap, the same discipline as LidMappingStoreService: a read or* write re-inserts the key at the most-recent end, and a set evicts the least-recently-used entry* while over `max`. `max = 0` means unbounded.+ *+ * `pinned` marks entries an eviction must skip while any unpinned entry is older. It exists for the+ * contacts map, where two populations share one cap: the account's own address book, which the+ * operator curated and which the API reports, and a much larger stream of peers seen once in a group+ * or a broadcast. Without it the second evicts the first.*/class LruMap<K, V> {private readonly map = new Map<K, V>();- constructor(private readonly max: number) {}+ constructor(+ private readonly max: number,+ private readonly pinned?: (value: V) => boolean,+ ) {}has(key: K): boolean {return this.map.has(key);@@ -47,12 +55,29 @@ class LruMap<K, V> {return;}while (this.map.size > this.max) {+ const victim = this.oldestEvictable();+ if (victim === undefined) {+ break; // every entry is pinned: keep them all rather than drop curated data+ }+ this.map.delete(victim);+ }+ }++ /**+ * The least-recently-used entry an eviction may take, or undefined when every entry is pinned.+ * Without a `pinned` predicate this is the map head, as before.+ */+ private oldestEvictable(): K | undefined {+ if (!this.pinned) {const oldest = this.map.keys().next().value;- if (oldest === undefined) {- break;+ return oldest;+ }+ for (const [key, value] of this.map) {+ if (!this.pinned(value)) {+ return key;}- this.map.delete(oldest);}+ return undefined;}values(): IterableIterator<V> {@@ -108,7 +133,10 @@ export class BaileysSessionStore {process.env.BAILEYS_SESSION_STORE_MAX_ENTRIES,SESSION_STORE_MAP_CAP_DEFAULT,);- this.contacts = new LruMap(maxEntries);+ // A saved name only ever arrives from the account's own app-state address book, never from peer+ // traffic, so pinning on it keeps the curated set out of reach of the peers this session happens+ // to observe. The pinned population is bounded by the account's own contact list.+ this.contacts = new LruMap(maxEntries, contact => Boolean(contact.name));this.chats = new LruMap(maxEntries);this.lastMessages = new LruMap(maxEntries);this.lidToPn = new LruMap(maxEntries);