Free, Open Source, Self-Hosted WhatsApp API Gateway
TypeScript apibotgatewayself-hostedwhatsappwhatsapp-apiwhatsapp-automationwhatsapp-botwhatsapp-gatewaywhatsapp-gateway-apiwhatsapp-webwhatsapp-web-api
perf(engine): baileys store eviction via createdAt+id cutoff, not NOT-IN(5000)
rmyndharis6119919ce0c6
diff --git a/src/engine/adapters/baileys-message-store.service.spec.ts b/src/engine/adapters/baileys-message-store.service.spec.tsindex 040cc0966..07e955089 100644--- a/src/engine/adapters/baileys-message-store.service.spec.ts+++ b/src/engine/adapters/baileys-message-store.service.spec.ts@@ -48,12 +48,40 @@ describe('BaileysMessageStoreService', () => {it('evicts oldest beyond the per-session cap', async () => {process.env.BAILEYS_MESSAGE_STORE_LIMIT = '2';const s = new BaileysMessageStoreService(repo);- await s.put('s1', msg('M1'));- await s.put('s1', msg('M2'));+ // Use distinct createdAt values so ordering is deterministic regardless of UUID tiebreaker.+ const t0 = new Date('2024-01-01T00:00:00.000Z');+ const t1 = new Date('2024-01-01T00:00:01.000Z');+ const t2 = new Date('2024-01-01T00:00:02.000Z');+ for (const [waMessageId, createdAt] of [+ ['M1', t0],+ ['M2', t1],+ ['M3', t2],+ ] as [string, Date][]) {+ await repo.save(repo.create({ sessionId: 's1', waMessageId, serializedMessage: '{}', createdAt }));+ }+ // Trigger eviction: put M3 again (idempotent upsert) so enforceLimit runs with 3 rows and cap=2.await s.put('s1', msg('M3'));- expect(await s.getMessage('s1', 'M1')).toBeNull(); // oldest evicted+ expect(await s.getMessage('s1', 'M1')).toBeNull(); // oldest (t0) evicted+ expect(await s.getMessage('s1', 'M2')).not.toBeNull();expect(await s.getMessage('s1', 'M3')).not.toBeNull();- expect(await repo.count({ where: { sessionId: 's1' } })).toBeLessThanOrEqual(2);+ expect(await repo.count({ where: { sessionId: 's1' } })).toBe(2);+ });++ it('keeps exactly limit rows when multiple share the same createdAt (tiebreaker via id)', async () => {+ process.env.BAILEYS_MESSAGE_STORE_LIMIT = '2';+ const s = new BaileysMessageStoreService(repo);+ // Insert 3 rows with identical createdAt to stress the (createdAt, id) tiebreaker.+ // With UUID primary keys, id ordering is lexicographic — we can only assert count, not which survive.+ const sharedTs = new Date('2024-01-01T00:00:00.000Z');+ for (const waMessageId of ['T1', 'T2', 'T3']) {+ await repo.save(repo.create({ sessionId: 's2', waMessageId, serializedMessage: '{}', createdAt: sharedTs }));+ }+ // Trigger eviction: put a 4th message (distinct, newer ts) through the service.+ await s.put('s2', msg('T4'));+ // Exactly limit rows must remain — no over- or under-deletion.+ expect(await repo.count({ where: { sessionId: 's2' } })).toBe(2);+ // T4 is the newest (distinct createdAt = now) and must survive.+ expect(await s.getMessage('s2', 'T4')).not.toBeNull();});it('clearSession removes only that session', async () => {diff --git a/src/engine/adapters/baileys-message-store.service.ts b/src/engine/adapters/baileys-message-store.service.tsindex 2299e8999..54b448588 100644--- a/src/engine/adapters/baileys-message-store.service.ts+++ b/src/engine/adapters/baileys-message-store.service.ts@@ -41,30 +41,25 @@ export class BaileysMessageStoreService implements BaileysMessageStore {await this.repo.delete({ sessionId });}- /**- * Per-session row cap: keep the newest N rows, delete the rest.- * Uses a NOT IN subquery over the N keep-IDs so ties in createdAt (fast inserts in tests)- * don't incorrectly evict recently added rows.- */+ /** Per-session row cap: keep the newest N, delete the rest. Deterministic via (createdAt, id). */private async enforceLimit(sessionId: string): Promise<void> {const limit = positiveIntFromEnv('BAILEYS_MESSAGE_STORE_LIMIT', 5000);- const total = await this.repo.count({ where: { sessionId } });- if (total <= limit) {- return;- }- // Find the IDs of the N rows to keep (newest N by insertion order; waMessageId as stable tiebreaker).- const keepRows = await this.repo.find({+ const cutoff = await this.repo.find({where: { sessionId },- order: { createdAt: 'DESC', waMessageId: 'DESC' },- take: limit,- select: ['id'],+ order: { createdAt: 'DESC', id: 'DESC' },+ skip: limit,+ take: 1,+ select: ['id', 'createdAt'],});- const keepIds = keepRows.map(r => r.id);+ if (cutoff.length === 0) {+ return; // under the cap — nothing to evict+ }+ const { id, createdAt } = cutoff[0];await this.repo.createQueryBuilder().delete().where('sessionId = :sessionId', { sessionId })- .andWhere('id NOT IN (:...keepIds)', { keepIds })+ .andWhere('(createdAt < :createdAt OR (createdAt = :createdAt AND id <= :id))', { createdAt, id }).execute();}}