Skip to content

Free, Open Source, Self-Hosted WhatsApp API Gateway

perf(engine): memoise the Baileys blocklist behind contact reads

Yudhi Armyndharis472f9e5bdf29
diff --git a/src/engine/adapters/baileys-contact-blocked.spec.ts b/src/engine/adapters/baileys-contact-blocked.spec.ts
index fa949084d..0d23779c0 100644
--- a/src/engine/adapters/baileys-contact-blocked.spec.ts
+++ b/src/engine/adapters/baileys-contact-blocked.spec.ts
@@ -23,6 +23,7 @@ describe('Baileys contact reads report real blocklist state', () => {
function make(opts: { blocklist?: string[]; blocklistError?: Error }): {
contacts: BaileysContacts;
warn: jest.Mock;
+ fetchBlocklist: jest.Mock;
} {
const warn = jest.fn();
const fetchBlocklist = opts.blocklistError
@@ -36,7 +37,7 @@ describe('Baileys contact reads report real blocklist state', () => {
findContact: (id: string) => contact(id),
toNeutralJid: (jid: string) => jid,
} as unknown as BaileysContactsHost;
- return { contacts: new BaileysContacts(host), warn };
+ return { contacts: new BaileysContacts(host), warn, fetchBlocklist };
}
it('marks a contact on the blocklist as blocked', async () => {
@@ -57,6 +58,20 @@ describe('Baileys contact reads report real blocklist state', () => {
// A blocklist query that fails is a transport fact, not a claim that nobody is blocked. The read
// must not fail outright either — contacts are still useful — so it degrades loudly.
+ // Regression guard for a cost this fix introduced: getContactById is called once per unique poster
+ // when a session seeds its status history (session-engine-leaf-events resolvePoster), purely to
+ // read a NAME. Querying the blocklist on each of those turned one connect into N network
+ // round-trips, each with its own deadline. Memoised so a burst shares one query.
+ it('issues ONE blocklist query for a burst of reads', async () => {
+ const { contacts, fetchBlocklist } = make({ blocklist: [] });
+
+ await contacts.getContactById('[email protected]');
+ await contacts.getContactById('[email protected]');
+ await contacts.getContacts();
+
+ expect(fetchBlocklist).toHaveBeenCalledTimes(1);
+ });
+
it('does not fail the contact read when the blocklist query does, and says so', async () => {
const { contacts, warn } = make({
blocklistError: new Error('WhatsApp did not answer the blocklist query in time'),
diff --git a/src/engine/adapters/baileys-contacts.ts b/src/engine/adapters/baileys-contacts.ts
index a07e8a0fa..9dac687f4 100644
--- a/src/engine/adapters/baileys-contacts.ts
+++ b/src/engine/adapters/baileys-contacts.ts
@@ -104,11 +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;
}
async unblockContact(contactId: string): Promise<void> {
this.host.ensureReady();
await this.confirmed(this.sock().updateBlockStatus(contactId, 'unblock'), 'the unblock');
+ this.blocklistMemo = undefined;
}
/**
@@ -189,16 +191,45 @@ export class BaileysContacts {
*/
private async withBlockedState(contacts: Contact[]): Promise<Contact[]> {
if (contacts.length === 0) return contacts;
- let blocked: Set<string>;
+ const blocked = await this.blockedIds();
+ if (!blocked) return contacts;
+ return contacts.map(contact => ({ ...contact, isBlocked: blocked.has(contact.id) }));
+ }
+
+ /** Memoised blocklist. See {@link blockedIds} for why this is not queried per read. */
+ private blocklistMemo?: { at: number; ids: Set<string> | null };
+
+ /**
+ * 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.
+ */
+ private static readonly BLOCKLIST_MEMO_MS = 5_000;
+
+ /**
+ * The account's blocked ids, or null when the query failed.
+ *
+ * Memoised because a single contact read is not the only caller: a session seeding its status
+ * history resolves each unique poster through getContactById purely to read a NAME
+ * (session-engine-leaf-events), so querying per read turned one connect into N network round-trips,
+ * each with its own deadline. The failure is memoised too — a broken blocklist must not cost N
+ * 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) {
+ return this.blocklistMemo.ids;
+ }
+ let ids: Set<string> | null;
try {
- blocked = new Set(await this.getBlockedContacts());
+ ids = new Set(await this.getBlockedContacts());
} catch (error) {
this.host.logger.warn('Blocklist unavailable; contact isBlocked left at its default', {
error: error instanceof Error ? error.message : String(error),
});
- return contacts;
+ ids = null;
}
- return contacts.map(contact => ({ ...contact, isBlocked: blocked.has(contact.id) }));
+ this.blocklistMemo = { at: now, ids };
+ return ids;
}
// eslint-disable-next-line @typescript-eslint/require-await