Skip to content

Free, Open Source, Self-Hosted WhatsApp API Gateway

fix(engine): baileys store — ms-precise eviction (no SQLite wipe) + FK CASCADE on session delete

rmyndharis739c6e32d5cf
diff --git a/src/engine/adapters/baileys-message-store.service.spec.ts b/src/engine/adapters/baileys-message-store.service.spec.ts
index 07e955089..9c894dc65 100644
--- a/src/engine/adapters/baileys-message-store.service.spec.ts
+++ b/src/engine/adapters/baileys-message-store.service.spec.ts
@@ -1,14 +1,40 @@
import { DataSource, Repository } from 'typeorm';
import { BaileysStoredMessage } from './baileys-stored-message.entity';
import { BaileysMessageStoreService } from './baileys-message-store.service';
+import { Session, SessionStatus } from '../../modules/session/entities/session.entity';
describe('BaileysMessageStoreService', () => {
let ds: DataSource;
let repo: Repository<BaileysStoredMessage>;
let service: BaileysMessageStoreService;
+ // Seed a sessions row so FK constraints (if SQLite enables them) resolve correctly.
+ const seedSession = async (id: string): Promise<void> => {
+ await ds.getRepository(Session).save(
+ ds.getRepository(Session).create({
+ id,
+ name: `session-${id}`,
+ status: SessionStatus.READY,
+ phone: null,
+ pushName: null,
+ config: {},
+ proxyUrl: null,
+ proxyType: null,
+ connectedAt: null,
+ lastActiveAt: null,
+ }),
+ );
+ };
+
beforeEach(async () => {
- ds = new DataSource({ type: 'sqlite', database: ':memory:', entities: [BaileysStoredMessage], synchronize: true });
+ ds = new DataSource({
+ type: 'sqlite',
+ database: ':memory:',
+ // Session must be present so the @ManyToOne relation metadata resolves and synchronize
+ // can emit the CASCADE FK on the baileys_stored_messages table (I6).
+ entities: [BaileysStoredMessage, Session],
+ synchronize: true,
+ });
await ds.initialize();
repo = ds.getRepository(BaileysStoredMessage);
service = new BaileysMessageStoreService(repo);
@@ -27,6 +53,7 @@ describe('BaileysMessageStoreService', () => {
}) as unknown as Parameters<BaileysMessageStoreService['put']>[1];
it('round-trips a WAMessage through BufferJSON', async () => {
+ await seedSession('s1');
await service.put('s1', msg('M1'));
const got = await service.getMessage('s1', 'M1');
expect(got?.key?.id).toBe('M1');
@@ -34,19 +61,58 @@ describe('BaileysMessageStoreService', () => {
});
it('returns null for an unknown id and is session-scoped', async () => {
+ await seedSession('s1');
await service.put('s1', msg('M1'));
expect(await service.getMessage('s1', 'NOPE')).toBeNull();
expect(await service.getMessage('s2', 'M1')).toBeNull();
});
it('is idempotent on (sessionId, waMessageId)', async () => {
+ await seedSession('s1');
await service.put('s1', msg('M1'));
await service.put('s1', msg('M1'));
expect(await repo.count({ where: { sessionId: 's1' } })).toBe(1);
});
- it('evicts oldest beyond the per-session cap', async () => {
+ /**
+ * C1 regression test — drives eviction through the REAL put() path so the stored
+ * createdAt value comes from the upsert payload (millisecond precision), not from
+ * SQLite's datetime('now') (second precision). Without the `createdAt: new Date()`
+ * fix in put(), the string comparison '…:XX' < '…:XX.000' evaluates TRUE for every
+ * same-second row, and enforceLimit() deletes ALL rows instead of keeping the cap.
+ *
+ * This test MUST FAIL against the old code (no explicit createdAt in upsert) and
+ * PASS with the fix.
+ */
+ it('eviction via put() keeps exactly the cap — never wipes the store (C1)', async () => {
+ process.env.BAILEYS_MESSAGE_STORE_LIMIT = '3';
+ await seedSession('s_c1');
+ const s = new BaileysMessageStoreService(repo);
+
+ // Insert 6 messages via put() — each call sets createdAt: new Date(), so even within the
+ // same wall-clock second the stored values carry millisecond precision.
+ for (let i = 1; i <= 6; i++) {
+ await s.put('s_c1', msg(`C${i}`));
+ }
+
+ const count = await repo.count({ where: { sessionId: 's_c1' } });
+ // With the bug: count is 0 (all evicted). With the fix: count is exactly 3.
+ expect(count).toBe(3);
+
+ // The newest messages (C4, C5, C6) must survive — they have the latest createdAt.
+ expect(await s.getMessage('s_c1', 'C4')).not.toBeNull();
+ expect(await s.getMessage('s_c1', 'C5')).not.toBeNull();
+ expect(await s.getMessage('s_c1', 'C6')).not.toBeNull();
+
+ // The oldest messages must be evicted.
+ expect(await s.getMessage('s_c1', 'C1')).toBeNull();
+ expect(await s.getMessage('s_c1', 'C2')).toBeNull();
+ expect(await s.getMessage('s_c1', 'C3')).toBeNull();
+ });
+
+ it('evicts oldest beyond the per-session cap (pre-seeded rows, distinct timestamps)', async () => {
process.env.BAILEYS_MESSAGE_STORE_LIMIT = '2';
+ await seedSession('s1');
const s = new BaileysMessageStoreService(repo);
// Use distinct createdAt values so ordering is deterministic regardless of UUID tiebreaker.
const t0 = new Date('2024-01-01T00:00:00.000Z');
@@ -69,6 +135,7 @@ describe('BaileysMessageStoreService', () => {
it('keeps exactly limit rows when multiple share the same createdAt (tiebreaker via id)', async () => {
process.env.BAILEYS_MESSAGE_STORE_LIMIT = '2';
+ await seedSession('s2');
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.
@@ -85,6 +152,8 @@ describe('BaileysMessageStoreService', () => {
});
it('clearSession removes only that session', async () => {
+ await seedSession('s1');
+ await seedSession('s2');
await service.put('s1', msg('M1'));
await service.put('s2', msg('M2'));
await service.clearSession('s1');
diff --git a/src/engine/adapters/baileys-message-store.service.ts b/src/engine/adapters/baileys-message-store.service.ts
index f82095f49..0f6caf773 100644
--- a/src/engine/adapters/baileys-message-store.service.ts
+++ b/src/engine/adapters/baileys-message-store.service.ts
@@ -33,7 +33,15 @@ export class BaileysMessageStoreService implements BaileysMessageStore {
const { BufferJSON } = await this.loadLib();
const serializedMessage = JSON.stringify(msg, BufferJSON.replacer);
// Idempotent: the same message arrives from the send return AND the messages.upsert echo.
- await this.repo.upsert({ sessionId, waMessageId, serializedMessage }, ['sessionId', 'waMessageId']);
+ // createdAt is set explicitly so the stored value carries millisecond precision — matching the
+ // :createdAt bound param used in enforceLimit(). Without this, SQLite's datetime('now') stores
+ // second-precision (e.g. '…:11') while the JS Date bound serializes as '…:11.000', and SQLite
+ // string-compares '…:11' < '…:11.000' = TRUE, causing every same-second row to be over-evicted
+ // and the store to be wiped to ~0 (C1).
+ await this.repo.upsert({ sessionId, waMessageId, serializedMessage, createdAt: new Date() }, [
+ 'sessionId',
+ 'waMessageId',
+ ]);
await this.enforceLimit(sessionId);
}
diff --git a/src/engine/adapters/baileys-stored-message.entity.ts b/src/engine/adapters/baileys-stored-message.entity.ts
index 558846312..acb32d37a 100644
--- a/src/engine/adapters/baileys-stored-message.entity.ts
+++ b/src/engine/adapters/baileys-stored-message.entity.ts
@@ -1,9 +1,13 @@
-import { Column, CreateDateColumn, Entity, Index, PrimaryGeneratedColumn } from 'typeorm';
+import { Column, CreateDateColumn, Entity, Index, JoinColumn, ManyToOne, PrimaryGeneratedColumn } from 'typeorm';
+import { Session } from '../../modules/session/entities/session.entity';
/**
* Persisted Baileys message store (the lib ships none). Holds the serialized WAMessage proto
* (via BufferJSON) so reply/forward/react/delete can resolve the original message/key by id across
* restarts. Engine-specific — lives in the engine layer, not the neutral `messages` table.
+ *
+ * The `session` relation declares the CASCADE FK so both the `synchronize:true` SQLite path and
+ * the migration path clean up stored messages when the parent session row is deleted (I6).
*/
@Entity('baileys_stored_messages')
@Index(['sessionId', 'waMessageId'], { unique: true }) // lookup + dedup (send-return vs upsert echo)
@@ -15,6 +19,10 @@ export class BaileysStoredMessage {
@Column()
sessionId: string;
+ @ManyToOne(() => Session, { onDelete: 'CASCADE' })
+ @JoinColumn({ name: 'sessionId' })
+ session?: Session;
+
@Column()
waMessageId: string;