Skip to content

Free, Open Source, Self-Hosted WhatsApp API Gateway

fix(baileys): refresh a session's chat states from the table on start

Yudhi Armyndharisa6f465107591
diff --git a/src/engine/adapters/baileys-chat-state-store.service.spec.ts b/src/engine/adapters/baileys-chat-state-store.service.spec.ts
index 7b2be4224..b8f27203f 100644
--- a/src/engine/adapters/baileys-chat-state-store.service.spec.ts
+++ b/src/engine/adapters/baileys-chat-state-store.service.spec.ts
@@ -17,7 +17,9 @@ function makeRepo(initial: Partial<ChatState>[] = []) {
}
const repo = {
rows,
- find: jest.fn(() => Promise.resolve([...rows.values()])),
+ find: jest.fn((opts?: { where?: { sessionId: string } }) =>
+ Promise.resolve([...rows.values()].filter(r => !opts?.where || r.sessionId === opts.where.sessionId)),
+ ),
findOne: jest.fn(({ where }: { where: { sessionId: string; chatId: string } }) =>
Promise.resolve(rows.get(KEY(where.sessionId, where.chatId))),
),
@@ -158,19 +160,43 @@ describe('ChatStateStoreService', () => {
expect(svc.get('s', 'c')).toEqual({ muteEndTime: null, archived: true, pinned: false });
});
- it('forgetAbsent makes one session read through again for chats it found no row for', async () => {
- const repo = makeRepo();
- const svc = svcWith(repo);
- svc.get('s', 'c');
- svc.get('t', 'c');
- await tick(); // both are now known to have no row
- await repo.upsert({ sessionId: 's', chatId: 'c', archived: true } as ChatState); // written by another node
- svc.forgetAbsent('s');
- svc.get('s', 'c');
- svc.get('t', 'c');
- await tick();
- expect(svc.get('s', 'c')).toEqual(expect.objectContaining({ archived: true }));
- expect(repo.findOne).toHaveBeenCalledTimes(3); // 't' is still skipped
+ describe('refreshSession (a start: another node may have written the rows since)', () => {
+ it('serves one session from the table on the very next read, cached or known absent', async () => {
+ const repo = makeRepo([
+ { sessionId: 's', chatId: 'muted', muteEndTime: -1 },
+ { sessionId: 's', chatId: 'gone', pinned: true },
+ { sessionId: 't', chatId: 'c', pinned: true },
+ ]);
+ const svc = svcWith(repo);
+ await svc.reload();
+ svc.get('s', 'new');
+ await tick(); // 'new' is now known to have no row
+ // Written by the node that held the session meanwhile.
+ await repo.upsert({ sessionId: 's', chatId: 'muted', muteEndTime: null } as ChatState);
+ await repo.upsert({ sessionId: 's', chatId: 'new', archived: true } as ChatState);
+ await repo.delete({ sessionId: 's', chatId: 'gone' });
+ await repo.upsert({ sessionId: 't', chatId: 'c', pinned: false } as ChatState);
+ await svc.refreshSession('s');
+ expect(svc.get('s', 'muted')).toEqual(expect.objectContaining({ muteEndTime: null }));
+ expect(svc.get('s', 'new')).toEqual(expect.objectContaining({ archived: true }));
+ expect(svc.get('s', 'gone')).toBeUndefined();
+ expect(svc.get('t', 'c')).toEqual(expect.objectContaining({ pinned: true })); // another session is untouched
+ });
+
+ it('keeps the cache when the table cannot be read, and reads the absent chats through again', async () => {
+ const repo = makeRepo([{ sessionId: 's', chatId: 'c', archived: true }]);
+ const svc = svcWith(repo);
+ await svc.reload();
+ svc.get('s', 'new');
+ await tick();
+ repo.find.mockRejectedValueOnce(new Error('SQLITE_BUSY'));
+ await expect(svc.refreshSession('s')).resolves.toBeUndefined();
+ expect(svc.get('s', 'c')).toEqual(expect.objectContaining({ archived: true }));
+ await repo.upsert({ sessionId: 's', chatId: 'new', pinned: true } as ChatState);
+ svc.get('s', 'new');
+ await tick();
+ expect(svc.get('s', 'new')).toEqual(expect.objectContaining({ pinned: true }));
+ });
});
it('forget drops the named chats of one session from the table and the cache, after their pending writes', async () => {
diff --git a/src/engine/adapters/baileys-chat-state-store.service.ts b/src/engine/adapters/baileys-chat-state-store.service.ts
index bfb0b70e6..d3bcd4143 100644
--- a/src/engine/adapters/baileys-chat-state-store.service.ts
+++ b/src/engine/adapters/baileys-chat-state-store.service.ts
@@ -25,8 +25,8 @@ export interface ChatStateStore {
clearSession(sessionId: string): Promise<void>;
/** Forget the named chats of one session (a deleted chat: one a later message re-creates starts clean). */
forget(sessionId: string, chatIds: string[]): Promise<void>;
- /** Re-read a session's chats known to have no row (a start: another node may have written them since). */
- forgetAbsent(sessionId: string): void;
+ /** Re-read one session's rows from the table (a start: another node may have written them since). */
+ refreshSession(sessionId: string): Promise<void>;
}
const DEFAULT_STATE: ChatStateValue = { muteEndTime: null, archived: false, pinned: false };
@@ -198,11 +198,42 @@ export class ChatStateStoreService implements ChatStateStore, OnModuleInit {
);
}
- forgetAbsent(sessionId: string): void {
+ /**
+ * Replaces the session's cached rows, the ones known absent included, with what the table holds now,
+ * so the first chat list after a start already reads it; a row changed or deleted while another node
+ * held the session would otherwise stay cached. Awaited before the socket opens: dropping the entries
+ * and warming them lazily instead would serve that first list from the live record, which carries no
+ * mute, archive or pin after a reconnect. A failed read keeps the cached rows, which are no worse
+ * than before, and only makes the absent ones read through again.
+ */
+ async refreshSession(sessionId: string): Promise<void> {
const prefix = `${sessionId}${SEP}`;
+ let rows: ChatState[] | undefined;
+ try {
+ rows = await this.repo.find({
+ where: { sessionId },
+ order: { updatedAt: 'DESC' },
+ take: this.maxEntries > 0 ? this.maxEntries : undefined,
+ });
+ } catch (err) {
+ this.logger.warn(
+ `Could not refresh chat states for ${sessionId}: ${err instanceof Error ? err.message : String(err)}`,
+ );
+ }
for (const k of [...this.absent]) {
if (k.startsWith(prefix)) this.absent.delete(k);
}
+ if (!rows) return;
+ for (const k of [...this.states.keys()]) {
+ if (k.startsWith(prefix)) this.states.delete(k);
+ }
+ for (const row of rows) {
+ this.index(this.key(sessionId, row.chatId), {
+ muteEndTime: row.muteEndTime,
+ archived: row.archived,
+ pinned: row.pinned,
+ });
+ }
}
/** Warm a cache miss from the table. This lookup still returns undefined (the read cannot await); the next hits. */
diff --git a/src/engine/adapters/baileys-lifecycle.ts b/src/engine/adapters/baileys-lifecycle.ts
index 863075903..f89233e05 100644
--- a/src/engine/adapters/baileys-lifecycle.ts
+++ b/src/engine/adapters/baileys-lifecycle.ts
@@ -238,7 +238,14 @@ export class BaileysLifecycle {
if (this.intentionalClose) {
return;
}
- this.host.config.chatStateStore?.forgetAbsent(this.host.config.sessionId);
+ const chatStateStore = this.host.config.chatStateStore;
+ if (chatStateStore) {
+ await chatStateStore.refreshSession(this.host.config.sessionId).catch(() => undefined);
+ // A teardown during that read must still keep this adapter from opening a socket.
+ if (this.intentionalClose) {
+ return;
+ }
+ }
// An install that skipped a Baileys patch fails later with errors that name no cause: an
// app-state resync that never terminates, a newsletter create that cannot parse its reply.
diff --git a/src/engine/adapters/baileys-session-store.spec.ts b/src/engine/adapters/baileys-session-store.spec.ts
index 893e5116d..dfdea3a7b 100644
--- a/src/engine/adapters/baileys-session-store.spec.ts
+++ b/src/engine/adapters/baileys-session-store.spec.ts
@@ -27,7 +27,9 @@ class FakeChatStateStore implements ChatStateStore {
for (const c of chatIds) this.rows.delete(this.key(s, c));
return Promise.resolve();
}
- forgetAbsent(): void {}
+ refreshSession(): Promise<void> {
+ return Promise.resolve();
+ }
}
describe('BaileysSessionStore', () => {
diff --git a/src/engine/adapters/baileys.adapter.spec.ts b/src/engine/adapters/baileys.adapter.spec.ts
index 8156ac5a4..19e282e84 100644
--- a/src/engine/adapters/baileys.adapter.spec.ts
+++ b/src/engine/adapters/baileys.adapter.spec.ts
@@ -4618,7 +4618,7 @@ describe('BaileysAdapter store-backed ops', () => {
reload: jest.fn().mockResolvedValue(undefined),
clearSession: jest.fn(),
forget: jest.fn().mockResolvedValue(undefined),
- forgetAbsent: jest.fn(),
+ refreshSession: jest.fn().mockResolvedValue(undefined),
};
const linked = async (onDisconnected = jest.fn()): Promise<BaileysAdapter> => {
// A failing clear must not change how either unlink ends.
@@ -4636,9 +4636,44 @@ describe('BaileysAdapter store-backed ops', () => {
};
// Another node may have written rows while it held the session (takeover).
- it('re-reads them on start for chats found without a row before', async () => {
+ // eslint-disable-next-line @typescript-eslint/no-unnecessary-type-assertion
+ const makeSocket = (): jest.Mock => (jest.requireMock('@whiskeysockets/baileys') as { default: jest.Mock }).default;
+
+ it('re-reads them on start, before the socket opens', async () => {
+ makeSocket().mockClear();
+ let opened = false;
+ chatStateStore.refreshSession.mockImplementationOnce(() => {
+ opened = makeSocket().mock.calls.length > 0;
+ return Promise.resolve();
+ });
await linked();
- expect(chatStateStore.forgetAbsent).toHaveBeenCalledWith('sess-1');
+ expect(chatStateStore.refreshSession).toHaveBeenCalledWith('sess-1');
+ expect(opened).toBe(false);
+ });
+
+ it('does not open a socket when the session is stopped during the re-read', async () => {
+ makeSocket().mockClear();
+ let finish!: () => void;
+ chatStateStore.refreshSession.mockReturnValueOnce(new Promise<void>(r => (finish = r)));
+ const adapter = new BaileysAdapter({
+ sessionId: 'sess-1',
+ dbSessionId: 'db-uuid-1',
+ authDir: './data/baileys',
+ messageStore: fakeStore,
+ chatStateStore,
+ });
+ const started = adapter.initialize({});
+ await adapter.disconnect();
+ finish();
+ await started;
+ expect(makeSocket()).not.toHaveBeenCalled();
+ expect(adapter.getStatus()).toBe(EngineStatus.DISCONNECTED);
+ });
+
+ it('still starts when the re-read fails', async () => {
+ chatStateStore.refreshSession.mockRejectedValueOnce(new Error('SQLITE_BUSY'));
+ const adapter = await linked();
+ expect(adapter.getStatus()).toBe(EngineStatus.READY);
});
it('clears them on logout', async () => {