Skip to content

Free, Open Source, Self-Hosted WhatsApp API Gateway

fix(baileys): serialize chat-state writes per chat

Yudhi Armyndharis532dbb67788b
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 861dcf4ef..c3fdff5c3 100644
--- a/src/engine/adapters/baileys-chat-state-store.service.spec.ts
+++ b/src/engine/adapters/baileys-chat-state-store.service.spec.ts
@@ -172,6 +172,21 @@ describe('ChatStateStoreService', () => {
expect(repo.findOne).toHaveBeenCalledTimes(3); // 't' is still skipped
});
+ it('keeps both of two concurrent patches for a chat that is not cached yet', async () => {
+ const repo = makeRepo();
+ const svc = svcWith(repo);
+ await Promise.all([svc.remember('s', 'c', { archived: true }), svc.remember('s', 'c', { pinned: true })]);
+ expect(svc.get('s', 'c')).toEqual({ muteEndTime: null, archived: true, pinned: true });
+ expect(repo.rows.get(KEY('s', 'c'))).toMatchObject({ archived: true, pinned: true });
+ });
+
+ it('does not let a concurrent no-op patch reset the cached state of an uncached chat', async () => {
+ const repo = makeRepo();
+ const svc = svcWith(repo);
+ await Promise.all([svc.remember('s', 'c', { pinned: true }), svc.remember('s', 'c', { archived: false })]);
+ expect(svc.get('s', 'c')).toEqual({ muteEndTime: null, archived: false, pinned: true });
+ });
+
it('swallows a repo error on reload and remember (table may not exist yet)', async () => {
const repo = {
find: jest.fn(() => Promise.reject(new Error('no such table'))),
diff --git a/src/engine/adapters/baileys-chat-state-store.service.ts b/src/engine/adapters/baileys-chat-state-store.service.ts
index 409107073..1b45d48c4 100644
--- a/src/engine/adapters/baileys-chat-state-store.service.ts
+++ b/src/engine/adapters/baileys-chat-state-store.service.ts
@@ -4,6 +4,7 @@ import { Repository } from 'typeorm';
import { ChatState } from './baileys-chat-state.entity';
import { createLogger } from '../../common/services/logger.service';
import { resolveNonNegativeIntEnv } from '../../config/configuration';
+import { KeyedMutationQueue } from '../../common/utils/keyed-mutation-queue';
/** Durable chat app-state Baileys cannot re-deliver on reconnect. `muteEndTime` is canonical epoch ms. */
export type ChatStateValue = { muteEndTime: number | null; archived: boolean; pinned: boolean };
@@ -55,6 +56,8 @@ export class ChatStateStoreService implements ChatStateStore, OnModuleInit {
*/
private readonly absent = new Set<string>();
private readonly maxEntries: number;
+ /** One write chain per chat, so each remember() merges onto the state the previous one left. */
+ private readonly writes = new KeyedMutationQueue();
constructor(
@InjectRepository(ChatState, 'data')
@@ -102,8 +105,23 @@ export class ChatStateStoreService implements ChatStateStore, OnModuleInit {
return undefined;
}
- async remember(sessionId: string, chatId: string, patch: Partial<ChatStateValue>): Promise<void> {
+ /**
+ * Serialized per chat: the caller does not await, so two patches for an uncached chat would otherwise
+ * both merge onto the same pre-change row and the later full-row write would drop the earlier patch.
+ */
+ remember(sessionId: string, chatId: string, patch: Partial<ChatStateValue>): Promise<void> {
const k = this.key(sessionId, chatId);
+ return new Promise<void>((resolve, reject) =>
+ this.writes.enqueue(k, () => this.applyPatch(k, sessionId, chatId, patch).then(resolve, reject)),
+ );
+ }
+
+ private async applyPatch(
+ k: string,
+ sessionId: string,
+ chatId: string,
+ patch: Partial<ChatStateValue>,
+ ): Promise<void> {
// The merge base must be the CURRENT state, not DEFAULT_STATE, or a partial `chats.update` (Baileys
// emits single-field patches, e.g. `{ pinned }` alone) would reset the columns it omits. On a cache
// miss the persisted row is that base: the read path warms lazily, but the write path upserts every