Free, Open Source, Self-Hosted WhatsApp API Gateway
TypeScript apibotgatewayself-hostedwhatsappwhatsapp-apiwhatsapp-automationwhatsapp-botwhatsapp-gatewaywhatsapp-gateway-apiwhatsapp-webwhatsapp-web-api
fix(engine): let chat state stamps follow a clock set back
Yudhi Armyndharis7acbb63770a0
diff --git a/src/engine/adapters/baileys-chat-state-store.service.spec.ts b/src/engine/adapters/baileys-chat-state-store.service.spec.tsindex eeecf4aae..14c56f4f9 100644--- a/src/engine/adapters/baileys-chat-state-store.service.spec.ts+++ b/src/engine/adapters/baileys-chat-state-store.service.spec.ts@@ -768,29 +768,31 @@ describe('ChatStateStoreService', () => {expect(store.listChats()[0]).toMatchObject({ muteExpiration: NEW_END, archived: true });});+ // Only Date is faked; the promises and setImmediate the store and the fake repo use still run.+ const fakeDate = (now: number) =>+ jest.useFakeTimers({+ now,+ doNotFake: [+ 'hrtime',+ 'nextTick',+ 'performance',+ 'queueMicrotask',+ 'requestAnimationFrame',+ 'cancelAnimationFrame',+ 'requestIdleCallback',+ 'cancelIdleCallback',+ 'setImmediate',+ 'clearImmediate',+ 'setInterval',+ 'clearInterval',+ 'setTimeout',+ 'clearTimeout',+ ],+ });+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',- ],- }),- );+ // Date stands still.+ beforeEach(() => fakeDate(10_000));afterEach(() => jest.useRealTimers());it('ranks a pin of the twin written after a fold of the chat as the newer row', async () => {@@ -818,6 +820,39 @@ describe('ChatStateStoreService', () => {expect(mergeTwinStates([svc.get('s', PHONE)!, svc.get('s', LID)!])).toMatchObject({ pinned: true });});});++ describe('a clock that steps back', () => {+ const T = 1_800_000_000_000;+ afterEach(() => jest.useRealTimers());++ it('keeps a lead of under a minute, so the later write still ranks newer', async () => {+ const repo = makeRepo();+ const svc = svcWith(repo);+ fakeDate(T + 59_000);+ await svc.remember('s', PHONE, { pinned: false });+ jest.setSystemTime(T); // the stamp is now as far ahead as a burst of writes could have run it+ await svc.remember('s', LID, { pinned: true });+ expect(repo.rows.get(KEY('s', LID))!.updatedAt.getTime()).toBe(T + 59_001);+ expect(mergeTwinStates([svc.get('s', PHONE)!, svc.get('s', LID)!])).toMatchObject({ pinned: true });+ });++ it('follows the clock again after it steps back hours, so a twin written after a restart ranks newer', async () => {+ const repo = makeRepo();+ fakeDate(T + 7 * 3_600_000); // booted with the clock seven hours ahead+ const first = svcWith(repo);+ await first.remember('s', PHONE, { pinned: true });+ jest.setSystemTime(T + 60_000); // set right, a minute on+ await first.remember('s', PHONE, { pinned: false });+ expect(repo.rows.get(KEY('s', PHONE))!.updatedAt.getTime()).toBe(T + 60_000);+ jest.setSystemTime(T + 11 * 60_000);+ const restarted = svcWith(repo);+ await restarted.reload();+ await restarted.remember('s', LID, { pinned: true });+ expect(mergeTwinStates([restarted.get('s', PHONE)!, restarted.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.tsindex d56b42790..fc210a9c6 100644--- a/src/engine/adapters/baileys-chat-state-store.service.ts+++ b/src/engine/adapters/baileys-chat-state-store.service.ts@@ -305,9 +305,13 @@ export class ChatStateStoreService implements ChatStateStore, OnModuleInit {* 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.+ * A lead of more than a minute is no burst (5000 writes at once lead by about 4 s) but the clock set+ * back, and the stamp follows the clock again: kept, it would date every later write up to that far+ * ahead, past a twin row a restarted process or another node writes in the meantime.*/private stamp(): Date {- this.lastStamp = Math.max(Date.now(), this.lastStamp + 1);+ const now = Date.now();+ this.lastStamp = this.lastStamp - now > 60_000 ? now : Math.max(now, this.lastStamp + 1);return new Date(this.lastStamp);}