Free, Open Source, Self-Hosted WhatsApp API Gateway
TypeScript apibotgatewayself-hostedwhatsappwhatsapp-apiwhatsapp-automationwhatsapp-botwhatsapp-gatewaywhatsapp-gateway-apiwhatsapp-webwhatsapp-web-api
fix(engine): map WhatsApp catalog refusals to HTTP errors on Baileys
Yudhi Armyndharis58063c781f37
diff --git a/src/engine/adapters/baileys-catalog.spec.ts b/src/engine/adapters/baileys-catalog.spec.tsindex 2ca90c902..916ede847 100644--- a/src/engine/adapters/baileys-catalog.spec.ts+++ b/src/engine/adapters/baileys-catalog.spec.ts@@ -1,6 +1,8 @@import type { WASocket } from '@whiskeysockets/baileys';import { BaileysCatalog, BaileysCatalogHost } from './baileys-catalog';+import { Boom } from '@hapi/boom';import { EngineTransportError } from '../../common/errors/engine-transport.error';+import { EngineRefusedError } from '../../common/errors/engine-refused.error';/*** Baileys' query() resolves `undefined` when WhatsApp never answers (it catches its own 60s@@ -119,3 +121,41 @@ describe('BaileysCatalog answers within the deadline', () => {});});});++describe('BaileysCatalog server refusals', () => {+ // assertNodeErrorFree turns an <error code="..."> answer into a Boom carrying the numeric code.+ const refusal = (code: number) => new Boom('refused', { data: code });++ it('maps a refused collections query to EngineRefusedError instead of a raw Boom', async () => {+ const { catalog } = build({ getCollections: jest.fn().mockRejectedValue(refusal(403)) }, 500);+ await expect(catalog.getCatalog()).rejects.toBeInstanceOf(EngineRefusedError);+ });++ it('reads item-not-found as an account with no catalog, as the routes document', async () => {+ const { catalog } = build(+ {+ getCollections: jest.fn().mockRejectedValue(refusal(404)),+ getCatalog: jest.fn().mockRejectedValue(refusal(404)),+ },+ 500,+ );+ await expect(catalog.getCatalog()).resolves.toBeNull();+ await expect(catalog.getProduct('a')).resolves.toBeNull();+ await expect(catalog.getProducts()).resolves.toMatchObject({ products: [], pagination: { total: 0 } });+ });++ it('fails a walk that hits item-not-found after the first page instead of truncating it', async () => {+ const getCatalog = jest+ .fn()+ .mockResolvedValueOnce({ products: [product('a')], nextPageCursor: 'c1' })+ .mockRejectedValueOnce(refusal(404));+ const { catalog } = build({ getCatalog }, 500);+ await expect(catalog.getProducts()).rejects.toBeInstanceOf(EngineRefusedError);+ });++ it('leaves a dropped connection unmapped', async () => {+ const closed = new Boom('Connection Closed', { statusCode: 428 });+ const { catalog } = build({ getCatalog: jest.fn().mockRejectedValue(closed) }, 500);+ await expect(catalog.getProducts()).rejects.toBe(closed);+ });+});diff --git a/src/engine/adapters/baileys-catalog.ts b/src/engine/adapters/baileys-catalog.tsindex 7b61aa9c9..19a22e3ef 100644--- a/src/engine/adapters/baileys-catalog.ts+++ b/src/engine/adapters/baileys-catalog.ts@@ -2,6 +2,7 @@ import type { Product as BaileysProduct, WASocket } from '@whiskeysockets/baileyimport { Catalog, PaginatedProducts, Product, ProductQueryOptions } from '../interfaces/whatsapp-engine.interface';import { EngineTransportError } from '../../common/errors/engine-transport.error';import { withQueryDeadline } from './baileys-query-deadline';+import { mapServerRefusal, refusedStatusCode } from './baileys-groups';import { type createLogger } from '../../common/services/logger.service';/**@@ -36,10 +37,25 @@ export class BaileysCatalog {private readonly budgetMs: number = CATALOG_QUERY_BUDGET_MS,) {}- /** Spend part of one request-wide budget on a single query, and say so when it runs out. */- private async bounded<T>(work: Promise<T>, deadline: number): Promise<T> {+ /**+ * Spend part of one request-wide budget on a single query, and say so when it runs out. A WhatsApp+ * error answer (a Boom with a numeric code) becomes an HTTP refusal rather than a raw 500. A 404+ * (item-not-found) on the first query means the account has no catalog, which the routes answer as+ * an empty body, so it resolves `empty` instead. Without `empty` (a later page of the walk) the 404+ * stays a refusal, so a walk that breaks halfway fails rather than returning a short list.+ */+ private async bounded<T>(work: () => Promise<T>, deadline: number, empty?: T): Promise<T> {try {- return await withQueryDeadline(work, deadline - Date.now(), 'WhatsApp did not answer the catalog query in time');+ return await withQueryDeadline(+ mapServerRefusal('Reading the catalog', () =>+ work().catch((error: unknown) => {+ if (empty !== undefined && refusedStatusCode(error) === 404) return empty;+ throw error;+ }),+ ),+ deadline - Date.now(),+ 'WhatsApp did not answer the catalog query in time',+ );} catch (error) {if (error instanceof EngineTransportError) {// Baileys' own "timed out waiting for message" warn is silent at the default@@ -63,7 +79,9 @@ export class BaileysCatalog {async getCatalog(): Promise<Catalog | null> {this.host.ensureReady();const jid = this.host.normalizedSelfJid();- const { collections } = await this.bounded(this.sock().getCollections(jid), Date.now() + this.budgetMs);+ const { collections } = await this.bounded(() => this.sock().getCollections(jid), Date.now() + this.budgetMs, {+ collections: [],+ });const first = collections[0];if (!first) {return null;@@ -112,7 +130,11 @@ export class BaileysCatalog {const products: BaileysProduct[] = [];let cursor: string | undefined;do {- const page = await this.bounded(this.sock().getCatalog({ jid, limit: CATALOG_PAGE_SIZE, cursor }), deadline);+ const page = await this.bounded(+ () => this.sock().getCatalog({ jid, limit: CATALOG_PAGE_SIZE, cursor }),+ deadline,+ cursor === undefined ? { products: [], nextPageCursor: undefined } : undefined,+ );products.push(...page.products);// A server echoing back the cursor it was handed would otherwise spin this loop until the// process runs out of heap — the accumulator grows on every pass.