Skip to content

Free, Open Source, Self-Hosted WhatsApp API Gateway

fix(identity): preload lid mappings oldest first into the LRU

Yudhi Armyndharis50456fb6b59b
diff --git a/src/engine/identity/lid-mapping-store.service.ts b/src/engine/identity/lid-mapping-store.service.ts
index cc2c1be15..42f58f166 100644
--- a/src/engine/identity/lid-mapping-store.service.ts
+++ b/src/engine/identity/lid-mapping-store.service.ts
@@ -131,7 +131,9 @@ export class LidMappingStoreService implements LidMappingStore, OnModuleInit {
this.phoneToLids.clear();
// A reload re-reads the table, so every recorded absence is a fresh question again.
this.absentFromTable.clear();
- for (const row of rows) {
+ // Oldest first, so the newest row ends at the most-recent end of the LRU rather than the first
+ // one evicted.
+ for (const row of rows.reverse()) {
this.index(row.lid, row.phone);
}
this.logger.log(
diff --git a/src/engine/identity/lid-mapping-store.spec.ts b/src/engine/identity/lid-mapping-store.spec.ts
index ced6e01ec..d984e46d8 100644
--- a/src/engine/identity/lid-mapping-store.spec.ts
+++ b/src/engine/identity/lid-mapping-store.spec.ts
@@ -247,6 +247,24 @@ describe('LidMappingStoreService — deterministic preload + repository fallback
expect(repo.find).toHaveBeenCalledWith({ order: { updatedAt: 'DESC' }, take: 3 });
});
+ // The query answers newest first; indexed in that order the newest row sat at the LRU's eviction
+ // end, so the first mapping learned after boot evicted the most recently written one.
+ it('keeps the newest preloaded row when a new mapping evicts', async () => {
+ process.env.LID_MAPPING_CACHE_MAX = '2';
+ const repo = makeFakeRepo();
+ repo.find.mockResolvedValueOnce([
+ { lid: 'lid-new', phone: '620002', sessionId: null, updatedAt: new Date(2000) },
+ { lid: 'lid-old', phone: '620001', sessionId: null, updatedAt: new Date(1000) },
+ ]);
+ const store = await newStore(repo);
+
+ await store.remember('lid-fresh', '620003');
+
+ expect(store.getCached('lid-new')).toBe('620002');
+ expect(store.getCached('lid-fresh')).toBe('620003');
+ expect(store.getCached('lid-old')).toBeUndefined();
+ });
+
it('preloads without a take when the cap is disabled (0)', async () => {
process.env.LID_MAPPING_CACHE_MAX = '0';
const repo = makeFakeRepo();