Skip to content

Free, Open Source, Self-Hosted WhatsApp API Gateway

fix(identity): drop empty phone entries from the lid mapping cache

Yudhi Armyndharis75306643843d
diff --git a/src/engine/identity/lid-mapping-store.service.ts b/src/engine/identity/lid-mapping-store.service.ts
index 42f58f166..e325951c1 100644
--- a/src/engine/identity/lid-mapping-store.service.ts
+++ b/src/engine/identity/lid-mapping-store.service.ts
@@ -312,7 +312,7 @@ export class LidMappingStoreService implements LidMappingStore, OnModuleInit {
private index(lid: string, phone: string | null): void {
const prev = this.lidToPhone.get(lid);
if (prev && prev !== phone) {
- this.phoneToLids.get(prev)?.delete(lid);
+ this.unindex(lid, prev);
}
// Re-insert (delete + set) so the entry moves to the most-recent end of the LRU order even on update.
this.lidToPhone.delete(lid);
@@ -351,7 +351,13 @@ export class LidMappingStoreService implements LidMappingStore, OnModuleInit {
if (oldest === undefined) break;
const phone = this.lidToPhone.get(oldest);
this.lidToPhone.delete(oldest);
- if (phone) this.phoneToLids.get(phone)?.delete(oldest);
+ if (phone) this.unindex(oldest, phone);
}
}
+
+ /** Drop a lid from its phone's reverse entry, and the entry itself once no lid is left under it. */
+ private unindex(lid: string, phone: string): void {
+ const set = this.phoneToLids.get(phone);
+ if (set?.delete(lid) && set.size === 0) this.phoneToLids.delete(phone);
+ }
}
diff --git a/src/engine/identity/lid-mapping-store.spec.ts b/src/engine/identity/lid-mapping-store.spec.ts
index d984e46d8..5345b8d18 100644
--- a/src/engine/identity/lid-mapping-store.spec.ts
+++ b/src/engine/identity/lid-mapping-store.spec.ts
@@ -201,6 +201,23 @@ describe('LidMappingStoreService — LRU cap', () => {
expect(store.lidsForPhone('620002')).toEqual(['lid-c']);
});
+ it('drops a phone key from the reverse map once its last lid is evicted or re-mapped', async () => {
+ process.env.LID_MAPPING_CACHE_MAX = '2';
+ const repo = makeFakeRepo();
+ const store = new LidMappingStoreService(repo as unknown as Repository<LidMapping>);
+ await store.onModuleInit();
+ const phoneToLids = (store as unknown as { phoneToLids: Map<string, Set<string>> }).phoneToLids;
+
+ await store.remember('lid-a', '620001');
+ await store.remember('lid-b', '620002');
+ await store.remember('lid-c', '620003'); // evicts lid-a, the only lid under 620001
+ expect(phoneToLids.has('620001')).toBe(false);
+
+ await store.remember('lid-c', '620004'); // re-maps lid-c away from 620003
+ expect(phoneToLids.has('620003')).toBe(false);
+ expect([...phoneToLids.keys()].sort()).toEqual(['620002', '620004']);
+ });
+
it('LID_MAPPING_CACHE_MAX=0 disables the cap (legacy unbounded behaviour)', async () => {
process.env.LID_MAPPING_CACHE_MAX = '0';
const repo = makeFakeRepo();