Free, Open Source, Self-Hosted WhatsApp API Gateway
TypeScript apibotgatewayself-hostedwhatsappwhatsapp-apiwhatsapp-automationwhatsapp-botwhatsapp-gatewaywhatsapp-gateway-apiwhatsapp-webwhatsapp-web-api
fix(baileys): memoise the blocklist when the answer arrives, and share the query
Yudhi Armyndharisa694c1ce35e9
diff --git a/src/engine/adapters/baileys-contact-blocked.spec.ts b/src/engine/adapters/baileys-contact-blocked.spec.tsindex 0f81c4620..a1564ad83 100644--- a/src/engine/adapters/baileys-contact-blocked.spec.ts+++ b/src/engine/adapters/baileys-contact-blocked.spec.ts@@ -106,3 +106,123 @@ describe('Baileys contact reads report real blocklist state', () => {expect(warn).toHaveBeenCalled();});});++/**+ * The memo exists to keep a contact read cheap, and every case above proves it with a query that+ * settles instantly — the one case that never needed a memo. Contact reads used to come straight+ * out of the in-memory store; they now await a blocklist query bounded only by the 30s engine+ * deadline, so the memo is what stands between a slow link and a status seed that resolves each+ * poster through getContactById paying that deadline again per poster.+ *+ * Both defects below are invisible to an instantly-resolving mock, which is why they shipped.+ */+describe('the blocklist memo holds under the conditions it exists for', () => {+ const contact = (id: string): Contact => ({+ id,+ number: id.split('@')[0],+ isMyContact: true,+ isBlocked: false,+ pushName: 'x',+ });++ /** Build an adapter whose blocklist query behaves however the test needs. */+ function withQuery(fetchBlocklist: jest.Mock): BaileysContacts {+ const host = {+ ensureReady: jest.fn(),+ getSocket: () =>+ ({ fetchBlocklist, updateBlockStatus: jest.fn().mockResolvedValue(undefined) }) as unknown as WASocket,+ logger: { ...createLogger('memo.spec'), warn: jest.fn() },+ listContacts: () => [contact('[email protected]')],+ findContact: (id: string) => contact(id),+ toNeutralJid: (jid: string) => jid,+ } as unknown as BaileysContactsHost;+ return new BaileysContacts(host);+ }++ afterEach(() => jest.restoreAllMocks());++ /**+ * The memo was stamped with the time read BEFORE the query, so an answer that took longer than+ * the 5s window was written already expired — the memo absorbed only the fast queries and+ * collapsed on exactly the slow ones it was added for.+ */+ it('memoises an answer that took longer than the memo window', async () => {+ let clock = 1_000_000;+ jest.spyOn(Date, 'now').mockImplementation(() => clock);+ // Each query costs 6s of virtual time — longer than BLOCKLIST_MEMO_MS (5s).+ const fetchBlocklist = jest.fn().mockImplementation(() => {+ clock += 6_000;+ return Promise.resolve([]);+ });+ const contacts = withQuery(fetchBlocklist);++ await contacts.getContactById('[email protected]');+ await contacts.getContactById('[email protected]');++ expect(fetchBlocklist).toHaveBeenCalledTimes(1);+ });++ // Control: the memo must still EXPIRE, or the test above would pass on a memo that never refreshes.+ it('still re-queries once the window has genuinely passed', async () => {+ let clock = 1_000_000;+ jest.spyOn(Date, 'now').mockImplementation(() => clock);+ const fetchBlocklist = jest.fn().mockResolvedValue([]);+ const contacts = withQuery(fetchBlocklist);++ await contacts.getContactById('[email protected]');+ clock += 5_001;+ await contacts.getContactById('[email protected]');++ expect(fetchBlocklist).toHaveBeenCalledTimes(2);+ });++ /**+ * Nothing held the in-flight query, so callers that arrived while one was open each started their+ * own — the burst the memo names as its reason was the burst it could not collapse.+ */+ /**+ * Sharing one in-flight query introduces a window the per-read query did not have: a block landing+ * while a query is open. That answer describes the state BEFORE the block, so memoising it would+ * re-establish, for the whole window, exactly the staleness the block's invalidation exists to+ * clear — and the caller who just blocked someone would read them as unblocked.+ */+ it('does not memoise an answer that a block overtook while it was in flight', async () => {+ let release: () => void = () => undefined;+ const gate = new Promise<void>(resolve => {+ release = resolve;+ });+ const fetchBlocklist = jest+ .fn()+ .mockImplementationOnce(() => gate.then(() => [])) // pre-block answer: nobody blocked+ .mockResolvedValue(['[email protected]']); // post-block truth+ const contacts = withQuery(fetchBlocklist);++ const inFlight = contacts.getContactById('[email protected]');+ await contacts.blockContact('[email protected]');+ release();+ await inFlight;++ // The stale answer must not be serving reads: this one has to go back to the socket.+ await expect(contacts.getContactById('[email protected]')).resolves.toMatchObject({ isBlocked: true });+ expect(fetchBlocklist).toHaveBeenCalledTimes(2);+ });++ it('collapses a burst of concurrent reads onto one query', async () => {+ let release: () => void = () => undefined;+ const gate = new Promise<void>(resolve => {+ release = resolve;+ });+ const fetchBlocklist = jest.fn().mockImplementation(() => gate.then(() => []));+ const contacts = withQuery(fetchBlocklist);++ const reads = Promise.all([+ contacts.getContactById('[email protected]'),+ contacts.getContactById('[email protected]'),+ contacts.getContactById('[email protected]'),+ ]);+ release();+ await reads;++ expect(fetchBlocklist).toHaveBeenCalledTimes(1);+ });+});diff --git a/src/engine/adapters/baileys-contacts.ts b/src/engine/adapters/baileys-contacts.tsindex 9dac687f4..5c5644631 100644--- a/src/engine/adapters/baileys-contacts.ts+++ b/src/engine/adapters/baileys-contacts.ts@@ -104,13 +104,13 @@ export class BaileysContacts {async blockContact(contactId: string): Promise<void> {this.host.ensureReady();await this.confirmed(this.sock().updateBlockStatus(contactId, 'block'), 'the block');- this.blocklistMemo = undefined;+ this.invalidateBlocklist();}async unblockContact(contactId: string): Promise<void> {this.host.ensureReady();await this.confirmed(this.sock().updateBlockStatus(contactId, 'unblock'), 'the unblock');- this.blocklistMemo = undefined;+ this.invalidateBlocklist();}/**@@ -199,6 +199,12 @@ export class BaileysContacts {/** Memoised blocklist. See {@link blockedIds} for why this is not queried per read. */private blocklistMemo?: { at: number; ids: Set<string> | null };+ /** The open query, shared by every caller that arrives while it is in flight. */+ private blocklistInFlight?: Promise<Set<string> | null>;++ /** Incremented on every block/unblock so a query started earlier cannot write a stale memo. */+ private blocklistGeneration = 0;+/*** How long one blocklist answer is reused. Short enough that a block made elsewhere shows up* quickly, long enough that a burst of reads costs one query.@@ -215,10 +221,21 @@ export class BaileysContacts {* queries either — and block/unblock invalidate it so a just-changed state is not read stale.*/private async blockedIds(): Promise<Set<string> | null> {- const now = Date.now();- if (this.blocklistMemo && now - this.blocklistMemo.at < BaileysContacts.BLOCKLIST_MEMO_MS) {+ if (this.blocklistMemo && Date.now() - this.blocklistMemo.at < BaileysContacts.BLOCKLIST_MEMO_MS) {return this.blocklistMemo.ids;}+ // Share one query with every caller that arrives while it is open. Without this the burst the+ // memo exists for — a status seed resolving each poster through getContactById — opened one+ // query per read, because the memo is only written once an answer is back.+ this.blocklistInFlight ??= this.queryBlockedIds();+ return this.blocklistInFlight;+ }++ private async queryBlockedIds(): Promise<Set<string> | null> {+ // Read before the query so an invalidation that lands DURING it can be detected: block/unblock+ // clears the memo, and a pre-change answer arriving afterwards would re-memoise the state the+ // caller just changed, for the whole window.+ const generation = this.blocklistGeneration;let ids: Set<string> | null;try {ids = new Set(await this.getBlockedContacts());@@ -227,11 +244,25 @@ export class BaileysContacts {error: error instanceof Error ? error.message : String(error),});ids = null;+ } finally {+ this.blocklistInFlight = undefined;+ }+ // Stamped with the time the ANSWER arrived, not the time the query started. Stamping the start+ // wrote an already-expired memo for any query slower than the window — so the memo absorbed+ // only the fast queries and collapsed on exactly the slow ones it was added for.+ if (generation === this.blocklistGeneration) {+ this.blocklistMemo = { at: Date.now(), ids };}- this.blocklistMemo = { at: now, ids };return ids;}+ /** Bumped by block/unblock so an in-flight query cannot memoise pre-change state afterwards. */+ private invalidateBlocklist(): void {+ this.blocklistMemo = undefined;+ this.blocklistInFlight = undefined;+ this.blocklistGeneration += 1;+ }+// eslint-disable-next-line @typescript-eslint/require-awaitasync resolveContactPhone(contactId: string): Promise<string | null> {this.host.ensureReady();