Free, Open Source, Self-Hosted WhatsApp API Gateway
TypeScript apibotgatewayself-hostedwhatsappwhatsapp-apiwhatsapp-automationwhatsapp-botwhatsapp-gatewaywhatsapp-gateway-apiwhatsapp-webwhatsapp-web-api
fix(engine): read whatsapp-web.js contacts without starving the liveness probe
Yudhi Armyndharis01e87b5f7e37
diff --git a/docs/29-engine-capability-matrix.md b/docs/29-engine-capability-matrix.mdindex e9aed6da5..5aa06c8d0 100644--- a/docs/29-engine-capability-matrix.md+++ b/docs/29-engine-capability-matrix.md@@ -728,19 +728,19 @@ with zero OpenWA surface. Baileys-only; whatsapp-web.js has no community API at**Contacts & numbers** (11)-| Library method | OpenWA exposure |-| ------------------------------ | ----------------------------------------------------- |-| `deleteAddressbookContact` | ✅ `deleteContact` |-| `getBlockedContacts` | ✅ `getBlockedContacts` |-| `getContactById` | ✅ `getContactById`, `blockContact`, `unblockContact` |-| `getContactDeviceCount` | ❌ **not exposed** |-| `getContactLidAndPhone` | ✅ `resolveContactPhone` |-| `getContacts` | ✅ `getContacts` |-| `getCountryCode` | ❌ **not exposed** |-| `getFormattedNumber` | ❌ **not exposed** |-| `getNumberId` | ✅ `checkNumberExists`, `getNumberId` |-| `isRegisteredUser` | ❌ **not exposed** |-| `saveOrEditAddressbookContact` | ✅ `upsertContact` |+| Library method | OpenWA exposure |+| ------------------------------ | ---------------------------------------------------------------- |+| `deleteAddressbookContact` | ✅ `deleteContact` |+| `getBlockedContacts` | ✅ `getBlockedContacts` |+| `getContactById` | ✅ `getContactById`, `blockContact`, `unblockContact` |+| `getContactDeviceCount` | ❌ **not exposed** |+| `getContactLidAndPhone` | ✅ `resolveContactPhone` |+| `getContacts` | ⚙️ read via a direct page walk, not `Client.getContacts` (#1501) |+| `getCountryCode` | ❌ **not exposed** |+| `getFormattedNumber` | ❌ **not exposed** |+| `getNumberId` | ✅ `checkNumberExists`, `getNumberId` |+| `isRegisteredUser` | ❌ **not exposed** |+| `saveOrEditAddressbookContact` | ✅ `upsertContact` |**Business** (2)@@ -968,8 +968,8 @@ adapter sources — re-derive the same way when anything changes:**9** wwjs-only; `sendCatalog` (unavailable on both engines) is not exposed.- Full engine inventory (29.5), split by the exposure legend rather than lumped: Baileys **152**socket methods — 48 wired into interface methods, 5 internal wiring, 29 plumbing, **70 ❌ not- exposed** (incl. the whole 23-method community cluster); wwjs **81** Client methods — 44 wired,- 2 internal wiring, 1 class plumbing, **34 ❌ not exposed** (26 real capabilities + 8+ exposed** (incl. the whole 23-method community cluster); wwjs **81** Client methods — 43 wired,+ 3 internal wiring, 1 class plumbing, **34 ❌ not exposed** (26 real capabilities + 8session/transport settings that are not WhatsApp capabilities). The backlog is the ❌ rows minusthose 8 settings; 🔩 plumbing is correctly never exposed.- Events: Baileys **34** (15 consumed / 19 dropped), wwjs **31** (16 consumed / 15 dropped).diff --git a/src/engine/adapters/whatsapp-web-js.adapter.spec.ts b/src/engine/adapters/whatsapp-web-js.adapter.spec.tsindex 80ee6f968..a6fa32dcb 100644--- a/src/engine/adapters/whatsapp-web-js.adapter.spec.ts+++ b/src/engine/adapters/whatsapp-web-js.adapter.spec.ts@@ -5625,8 +5625,10 @@ describe('WhatsAppWebJsAdapter page transport error detection (wedged page fast-);it('converts a transport error from a getter into a 503 (getContacts)', async () => {- const getContacts = jest.fn().mockRejectedValue(new Error('Protocol error: Target closed'));- const { adapter, onDisconnected } = readyAdapter({ getContacts });+ // #1501: getContacts now reads via pupPage.evaluate(readLeanContacts) so the liveness probe is+ // not starved; a dead page rejects the evaluate the same way client.getContacts() used to.+ const evaluate = jest.fn().mockRejectedValue(new Error('Protocol error: Target closed'));+ const { adapter, onDisconnected } = readyAdapter({ pupPage: { evaluate } });await expect(adapter.getContacts()).rejects.toBeInstanceOf(EngineTransportError);expect(onDisconnected).toHaveBeenCalledWith('Page transport error during getContacts');@@ -5646,13 +5648,15 @@ describe('WhatsAppWebJsAdapter page transport error detection (wedged page fast-},{ id: { $1: '[email protected]' }, name: 'Bob', pushname: 'Bobby', number: '222', isMyContact: false, isBlocked: true },];- const getContacts = jest.fn().mockResolvedValue(raw);- const { adapter } = readyAdapter({ getContacts });+ const evaluate = jest.fn().mockResolvedValue(raw);+ const { adapter } = readyAdapter({ pupPage: { evaluate } });await expect(adapter.getContacts()).resolves.toEqual([{ id: '[email protected]', name: 'Alice', pushName: 'Ally', number: '111', isMyContact: true, isBlocked: false },{ id: '[email protected]', name: 'Bob', pushName: 'Bobby', number: '222', isMyContact: false, isBlocked: true },]);+ // The whole address book is read in a single in-page walk, not re-fetched per page.+ expect(evaluate).toHaveBeenCalledTimes(1);});// #1476: an entry with no readable wid under either name (a shape wwebjs itself sometimes returns)@@ -5661,8 +5665,8 @@ describe('WhatsAppWebJsAdapter page transport error detection (wedged page fast-const good1 = { id: { _serialized: '[email protected]' }, name: 'Alice', number: '111' };const unreadable = { id: {}, name: 'Ghost', number: '000' };const good2 = { id: { $1: '[email protected]' }, name: 'Bob', number: '222' };- const getContacts = jest.fn().mockResolvedValue([good1, unreadable, good2]);- const { adapter } = readyAdapter({ getContacts });+ const evaluate = jest.fn().mockResolvedValue([good1, unreadable, good2]);+ const { adapter } = readyAdapter({ pupPage: { evaluate } });const logger = (adapter as unknown as { logger: { warn: (m: string) => void } }).logger;const warnSpy = jest.spyOn(logger, 'warn').mockImplementation(() => undefined);@@ -5675,8 +5679,8 @@ describe('WhatsAppWebJsAdapter page transport error detection (wedged page fast-// A rejection that carries no transport-death signature is an ordinary failure, not a dead page —// it must reach the caller unchanged and leave the session READY, unlike the 503 case above.it('propagates a non-transport rejection from getContacts untouched and leaves the session READY', async () => {- const getContacts = jest.fn().mockRejectedValue(new Error('Evaluation failed: TypeError: x is not a function'));- const { adapter, onDisconnected } = readyAdapter({ getContacts });+ const evaluate = jest.fn().mockRejectedValue(new Error('Evaluation failed: TypeError: x is not a function'));+ const { adapter, onDisconnected } = readyAdapter({ pupPage: { evaluate } });await expect(adapter.getContacts()).rejects.toThrow('Evaluation failed: TypeError: x is not a function');diff --git a/src/engine/adapters/wwebjs-contacts.ts b/src/engine/adapters/wwebjs-contacts.tsindex 2ec4b54c7..7a15e5b46 100644--- a/src/engine/adapters/wwebjs-contacts.ts+++ b/src/engine/adapters/wwebjs-contacts.ts@@ -8,6 +8,64 @@ import { type WwebjsEngineHost, withPage } from './wwebjs-host';/** The raw whatsapp-web.js contact element type, kept local so the wwebjs `Contact` type never leaks. */type RawWwebjsContact = Awaited<ReturnType<Client['getContacts']>>[number];+/** The six fields {@link WwebjsContacts.toContact} reads, projected in-page by {@link readLeanContacts}. */+interface LeanContact {+ id: SerializedWid | string;+ name?: string;+ pushname?: string;+ number: string;+ isMyContact: boolean;+ isBlocked: boolean;+}++/**+ * Read the contact list IN-PAGE, projected to only the fields {@link WwebjsContacts.toContact} keeps,+ * yielding to the page event loop every 256 contacts so the liveness probe's queued `getState()`+ * evaluate can interleave (#1501). whatsapp-web.js's own `client.getContacts()` maps the same+ * `window.WWebJS.getContactModel`, but over a `Promise.all` with no await for personal contacts, so it+ * runs as one uninterrupted synchronous stretch that starves the probe on a large address book and+ * makes the watchdog tear a healthy session down mid-read. The per-contact `serialize()` cost is+ * unchanged; the yield is what makes the read probe-safe regardless of size.+ *+ * Reusing `getContactModel` keeps `id`/`number`/`name`/`pushname`/`isMyContact`/`isBlocked` byte+ * identical to `getContacts()` (`Contact.number` is `data.userid`), and the raw `id` stays readable by+ * {@link readWid} (`_serialized`, the post-rename `$1`, or a lid `phoneNumber` string all resolve).+ * `BusinessProfile.find` is skipped: its only output, `res.businessProfile`, is not one of the six+ * fields, so dropping it costs nothing and saves a network fetch per business contact.+ */+export async function readLeanContacts(): Promise<LeanContact[]> {+ const w = window as unknown as {+ require: (m: string) => { Contact: { getModelsArray: () => unknown[] } };+ WWebJS: {+ getContactModel: (contact: unknown) => {+ id: SerializedWid | string;+ name?: string;+ pushname?: string;+ userid: string;+ isMyContact: boolean;+ isBlocked: boolean;+ };+ };+ };+ const models = w.require('WAWebCollections').Contact.getModelsArray();+ const out: LeanContact[] = [];+ for (let i = 0; i < models.length; i++) {+ const m = w.WWebJS.getContactModel(models[i]);+ out.push({+ id: m.id,+ name: m.name,+ pushname: m.pushname,+ number: m.userid,+ isMyContact: m.isMyContact,+ isBlocked: m.isBlocked,+ });+ // ponytail: yield every 256 contacts so the getState() liveness probe can interleave (#1501);+ // raise the stride if the read ever gets too chatty on a very large address book.+ if ((i & 0xff) === 0xff) await new Promise(resolve => setTimeout(resolve));+ }+ return out;+}+/*** Contact operations extracted from WhatsAppWebJsAdapter. The adapter keeps the public methods as* thin forwarders and injects the shared host surface (./wwebjs-host) via closures, so the delegate@@ -45,7 +103,12 @@ export class WwebjsContacts {let raw: RawWwebjsContact[];try {- raw = await this.client().getContacts();+ // A direct in-page walk that yields so the liveness probe is not starved (see readLeanContacts,+ // #1501), instead of whatsapp-web.js's atomic client.getContacts(). The projected rows are a+ // strict subset of a Contact; the mapping below reads only those six fields.+ const page = (this.client() as unknown as { pupPage?: { evaluate: <T>(fn: () => Promise<T>) => Promise<T> } })+ .pupPage;+ raw = ((await page?.evaluate(readLeanContacts)) ?? []) as unknown as RawWwebjsContact[];} catch (error) {// A dead page surfaces here as a raw Puppeteer error; convert it to the documented transport// failure the way wwebjs-chats.ts does, so a transport death answers 503 instead of a bare 500.