Free, Open Source, Self-Hosted WhatsApp API Gateway
TypeScript apibotgatewayself-hostedwhatsappwhatsapp-apiwhatsapp-automationwhatsapp-botwhatsapp-gatewaywhatsapp-gateway-apiwhatsapp-webwhatsapp-web-api
fix(baileys): keep persisted chat state when its read-through fails
Yudhi Armyndharis1cab9e162840
diff --git a/src/engine/adapters/baileys-chat-state-store.service.spec.ts b/src/engine/adapters/baileys-chat-state-store.service.spec.tsindex 2c8d9938d..5a194c79e 100644--- a/src/engine/adapters/baileys-chat-state-store.service.spec.ts+++ b/src/engine/adapters/baileys-chat-state-store.service.spec.ts@@ -21,8 +21,9 @@ function makeRepo(initial: Partial<ChatState>[] = []) {findOne: jest.fn(({ where }: { where: { sessionId: string; chatId: string } }) =>Promise.resolve(rows.get(KEY(where.sessionId, where.chatId))),),+ // TypeORM's upsert overwrites only the columns the entity carries, so a partial one merges.upsert: jest.fn((v: ChatState) => {- rows.set(KEY(v.sessionId, v.chatId), { ...v });+ rows.set(KEY(v.sessionId, v.chatId), { ...rows.get(KEY(v.sessionId, v.chatId)), ...v });return Promise.resolve(undefined);}),delete: jest.fn(({ sessionId }: { sessionId: string }) => {@@ -106,6 +107,18 @@ describe('ChatStateStoreService', () => {expect(repo.rows.get(KEY('s', 'c'))).toMatchObject({ muteEndTime: 999, archived: true, pinned: true });});+ it('writes only the patched column when the read-through for a cache-missed chat fails', async () => {+ const repo = makeRepo([{ sessionId: 's', chatId: 'c', muteEndTime: 999, archived: true, pinned: false }]);+ repo.findOne.mockRejectedValueOnce(new Error('SQLITE_BUSY'));+ const svc = svcWith(repo);+ await svc.remember('s', 'c', { pinned: true });+ expect(repo.rows.get(KEY('s', 'c'))).toMatchObject({ muteEndTime: 999, archived: true, pinned: true });+ // Nothing guessed is cached: the next read warms from the table.+ expect(svc.get('s', 'c')).toBeUndefined();+ await tick();+ expect(svc.get('s', 'c')).toEqual({ muteEndTime: 999, archived: true, pinned: true });+ });+it('does not churn a row when a cache-missed patch matches the persisted state', async () => {const repo = makeRepo([{ sessionId: 's', chatId: 'c', muteEndTime: 999, archived: true, pinned: false }]);const svc = svcWith(repo);@@ -131,7 +144,12 @@ describe('ChatStateStoreService', () => {const svc = new ChatStateStoreService(repo as unknown as Repository<ChatState>);await expect(svc.reload()).resolves.toBeUndefined();await expect(svc.remember('s', 'c', { archived: true })).resolves.toBeUndefined();- // the in-memory mirror still updated even though the write failed- expect(svc.get('s', 'c')).toEqual({ muteEndTime: null, archived: true, pinned: false });+ // The read failed too, so there is no merge base: only the patched column is written, and no+ // guessed state is cached (the chat reads from its live record until the table answers).+ const [written] = repo.upsert.mock.calls[0] as unknown as [Record<string, unknown>];+ expect(written).toMatchObject({ sessionId: 's', chatId: 'c', archived: true });+ expect(written).not.toHaveProperty('muteEndTime');+ expect(written).not.toHaveProperty('pinned');+ expect(svc.get('s', 'c')).toBeUndefined();});});diff --git a/src/engine/adapters/baileys-chat-state-store.service.ts b/src/engine/adapters/baileys-chat-state-store.service.tsindex 685c8b5d8..135d70bb5 100644--- a/src/engine/adapters/baileys-chat-state-store.service.ts+++ b/src/engine/adapters/baileys-chat-state-store.service.ts@@ -100,10 +100,17 @@ export class ChatStateStoreService implements ChatStateStore, OnModuleInit {// miss the persisted row is that base: the read path warms lazily, but the write path upserts every// column, so it has to read-through first or a lone pin update on an evicted muted chat wipes its// mute. A row absent from the table resolves to DEFAULT_STATE, which is the correct base for a chat- // whose state has never been persisted.+ // whose state has never been persisted. A read that FAILS is not an absent row: with no base to+ // merge onto, only the patched columns are written (upsert leaves the others as persisted) and the+ // cache stays cold, so the next read warms from the table instead of from a guess.let existing = this.states.get(k);if (!existing) {- const row = await this.repo.findOne({ where: { sessionId, chatId } }).catch(() => null);+ let row: ChatState | null;+ try {+ row = await this.repo.findOne({ where: { sessionId, chatId } });+ } catch {+ return this.persist(sessionId, chatId, patch);+ }existing = row ? { muteEndTime: row.muteEndTime, archived: row.archived, pinned: row.pinned } : DEFAULT_STATE;}const next: ChatStateValue = { ...existing, ...patch };@@ -116,8 +123,12 @@ export class ChatStateStoreService implements ChatStateStore, OnModuleInit {return; // nothing changed against the current state; skip the write that would just churn updatedAt}this.index(k, next);+ await this.persist(sessionId, chatId, next);+ }++ private async persist(sessionId: string, chatId: string, values: Partial<ChatStateValue>): Promise<void> {try {- await this.repo.upsert({ sessionId, chatId, ...next, updatedAt: new Date() }, ['sessionId', 'chatId']);+ await this.repo.upsert({ sessionId, chatId, ...values, updatedAt: new Date() }, ['sessionId', 'chatId']);} catch (err) {this.logger.warn(`Failed to persist chat state for ${chatId}: ${err instanceof Error ? err.message : String(err)}`,