Skip to content

Free, Open Source, Self-Hosted WhatsApp API Gateway

fix(engine): give each chat state write its own millisecond

Yudhi Armyndharis486fc8e3a0cd
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 e5b1c8d89..eeecf4aae 100644
--- a/src/engine/adapters/baileys-chat-state-store.service.spec.ts
+++ b/src/engine/adapters/baileys-chat-state-store.service.spec.ts
@@ -767,6 +767,57 @@ describe('ChatStateStoreService', () => {
expect(repo.rows.get(KEY('s', PHONE))).toMatchObject({ muteEndTime: NEW_END, archived: true });
expect(store.listChats()[0]).toMatchObject({ muteExpiration: NEW_END, archived: true });
});
+
+ describe('two writes in one millisecond', () => {
+ // Only Date stands still; the promises and setImmediate the store and the fake repo use still run.
+ beforeEach(() =>
+ jest.useFakeTimers({
+ now: 10_000,
+ doNotFake: [
+ 'hrtime',
+ 'nextTick',
+ 'performance',
+ 'queueMicrotask',
+ 'requestAnimationFrame',
+ 'cancelAnimationFrame',
+ 'requestIdleCallback',
+ 'cancelIdleCallback',
+ 'setImmediate',
+ 'clearImmediate',
+ 'setInterval',
+ 'clearInterval',
+ 'setTimeout',
+ 'clearTimeout',
+ ],
+ }),
+ );
+ afterEach(() => jest.useRealTimers());
+
+ it('ranks a pin of the twin written after a fold of the chat as the newer row', async () => {
+ const repo = makeRepo([
+ { sessionId: 's', chatId: PHONE, pinned: false, observed: 'pinned', updatedAt: new Date(1000) },
+ ]);
+ const svc = svcWith(repo);
+ await svc.fold('s', PHONE, [LID], { muteEndTime: 5000 });
+ await svc.remember('s', LID, { pinned: true });
+ expect(mergeTwinStates([svc.get('s', PHONE)!, svc.get('s', LID)!])).toMatchObject({
+ muteEndTime: 5000,
+ pinned: true,
+ });
+ const at = (chatId: string) => repo.rows.get(KEY('s', chatId))!.updatedAt.getTime();
+ expect(at(LID)).toBeGreaterThan(at(PHONE));
+ });
+
+ it('ranks a write made after a failed read as newer than the write before it', async () => {
+ const repo = makeRepo();
+ const svc = svcWith(repo);
+ await svc.remember('s', PHONE, { pinned: false });
+ repo.findOne.mockRejectedValueOnce(new Error('SQLITE_BUSY'));
+ await svc.remember('s', LID, { pinned: true });
+ await svc.reload();
+ expect(mergeTwinStates([svc.get('s', PHONE)!, svc.get('s', LID)!])).toMatchObject({ pinned: true });
+ });
+ });
});
it('swallows a repo error on reload and remember (table may not exist yet)', async () => {
diff --git a/src/engine/adapters/baileys-chat-state-store.service.ts b/src/engine/adapters/baileys-chat-state-store.service.ts
index ab534733c..d56b42790 100644
--- a/src/engine/adapters/baileys-chat-state-store.service.ts
+++ b/src/engine/adapters/baileys-chat-state-store.service.ts
@@ -176,6 +176,8 @@ export class ChatStateStoreService implements ChatStateStore, OnModuleInit {
private touchSeq = 0;
private touchedFloor = 0;
private readonly touched = new Map<string, number>();
+ /** The `updatedAt` of the last write, so the next one never shares it (see {@link stamp}). */
+ private lastStamp = 0;
constructor(
@InjectRepository(ChatState, 'data')
@@ -298,6 +300,17 @@ export class ChatStateStoreService implements ChatStateStore, OnModuleInit {
return done;
}
+ /**
+ * The `updatedAt` of a write: the clock, or one millisecond past the previous write when the clock has
+ * not moved past it. Twin rows rank by it and a tie goes to the phone row, so a write of a twin made in
+ * the same millisecond as one of the phone row would rank older however late it came. A burst of
+ * writes runs it ahead of the clock by its writes beyond one per millisecond, until the clock catches up.
+ */
+ private stamp(): Date {
+ this.lastStamp = Math.max(Date.now(), this.lastStamp + 1);
+ return new Date(this.lastStamp);
+ }
+
private writesOf(sessionId: string): SessionWrites {
let writes = this.sessionWrites.get(sessionId);
if (!writes) {
@@ -465,7 +478,7 @@ export class ChatStateStoreService implements ChatStateStore, OnModuleInit {
this.index(k, next); // warm the cache even on a no-op so the next read is a hit
return true; // nothing changed against the current state; skip the write that would just churn updatedAt
}
- const at = new Date();
+ const at = this.stamp();
next.updatedAt = at.getTime();
this.bumpWriteSeq(sessionId);
this.index(k, next);
@@ -476,7 +489,7 @@ export class ChatStateStoreService implements ChatStateStore, OnModuleInit {
sessionId: string,
chatId: string,
values: Partial<ChatStateValue>,
- at = new Date(),
+ at: Date,
): Promise<boolean> {
const columns: Record<string, unknown> = { ...values, observed: values.observed?.join(',') };
delete columns.updatedAt;
@@ -504,7 +517,7 @@ export class ChatStateStoreService implements ChatStateStore, OnModuleInit {
): Promise<boolean> {
const carried = FIELDS.filter(f => Object.hasOwn(patch, f));
const columns = Object.fromEntries(carried.map(f => [f, patch[f]]));
- const updatedAt = new Date();
+ const updatedAt = this.stamp();
try {
if (create) {
await this.repo