Skip to content

Free, Open Source, Self-Hosted WhatsApp API Gateway

fix(baileys): bound the catalog walk with a request budget

Yudhi Armyndharise1bac075d191
diff --git a/CHANGELOG.md b/CHANGELOG.md
index 16ff8f4cc..69abff9dc 100644
--- a/CHANGELOG.md
+++ b/CHANGELOG.md
@@ -9,6 +9,7 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0
### Fixed
+- **A catalog read no longer stalls for a minute and then reports an empty catalog** — Baileys answers an unanswered query with `undefined` rather than an error and its catalog parsers are null-safe, so a request WhatsApp never replied to was indistinguishable from a business with no products: `GET /catalog` and `/catalog/products` returned `200` with nothing in them after a silent 60 seconds, and `send-product` reported `404 Product not found` for a product it had simply never heard about. The walk now spends one 30-second budget across every page and answers `503`, and a server that repeats a page cursor instead of advancing no longer spins the walk until the process exhausts its heap.
- **A benign whatsapp-web.js rejection no longer reads like a crash** — the same un-awaited `framenavigated` re-injection that already logs at `WARN` when the page goes away was logged at `ERROR` in its other shape, where the navigation lands before WhatsApp Web has defined its module registry; it appears at the first boot after the pinned WhatsApp Web build moves under a warm profile, and the session reaches ready unaided.
### Fixed
diff --git a/openapi.json b/openapi.json
index 57551ac5b..dfb2b0d0f 100644
--- a/openapi.json
+++ b/openapi.json
@@ -5872,6 +5872,9 @@
"responses": {
"501": {
"description": "Not supported by the active engine: whatsapp-web.js has no catalog API."
+ },
+ "503": {
+ "description": "WhatsApp did not answer the catalog query within the request budget — retry shortly."
}
},
"summary": "Get business catalog info (Baileys engine only)",
@@ -5918,6 +5921,9 @@
"responses": {
"501": {
"description": "Not supported by the active engine: whatsapp-web.js has no catalog API."
+ },
+ "503": {
+ "description": "WhatsApp did not answer the catalog query within the request budget — retry shortly."
}
},
"summary": "List catalog products (Baileys engine only)",
@@ -5950,6 +5956,9 @@
"responses": {
"501": {
"description": "Not supported by the active engine: whatsapp-web.js has no catalog API."
+ },
+ "503": {
+ "description": "WhatsApp did not answer the catalog query within the request budget — retry shortly."
}
},
"summary": "Get a specific product (Baileys engine only)",
@@ -5990,6 +5999,9 @@
},
"501": {
"description": "Not supported by the active engine: whatsapp-web.js cannot send product messages."
+ },
+ "503": {
+ "description": "WhatsApp did not answer the catalog query within the request budget — retry shortly."
}
},
"summary": "Send a product message (Baileys engine only)",
diff --git a/src/common/errors/engine-transport.error.ts b/src/common/errors/engine-transport.error.ts
index 05c4260c0..d53d06f27 100644
--- a/src/common/errors/engine-transport.error.ts
+++ b/src/common/errors/engine-transport.error.ts
@@ -1,11 +1,12 @@
import { ServiceUnavailableException } from '@nestjs/common';
/**
- * Thrown by an engine adapter when an operation fails because the engine's TRANSPORT is dead —
- * the Chromium page/CDP connection is gone (whatsapp-web.js) or the WebSocket dropped (Baileys) —
- * rather than because the requested resource does not exist. A broad catch that folds this into a
- * not-found result makes a crashed session look like a missing group/channel (404) or a refused
- * invite (400), which is how operators end up debugging the wrong layer.
+ * Thrown by an engine adapter when an operation fails at the TRANSPORT rather than because the
+ * requested resource does not exist: the Chromium page/CDP connection is gone (whatsapp-web.js),
+ * the WebSocket dropped (Baileys), or the socket is up but WhatsApp left our query unanswered
+ * past a deadline we own. A broad catch that folds this into a not-found result makes a crashed
+ * session look like a missing group/channel (404) or a refused invite (400), which is how
+ * operators end up debugging the wrong layer.
*
* Extends NestJS `ServiceUnavailableException` so it maps to **HTTP 503** through the built-in
* exception handler — no custom global filter required. Mirrors {@link EngineNotReadyError} (409).
diff --git a/src/engine/adapters/baileys-catalog.spec.ts b/src/engine/adapters/baileys-catalog.spec.ts
new file mode 100644
index 000000000..2ca90c902
--- /dev/null
+++ b/src/engine/adapters/baileys-catalog.spec.ts
@@ -0,0 +1,121 @@
+import type { WASocket } from '@whiskeysockets/baileys';
+import { BaileysCatalog, BaileysCatalogHost } from './baileys-catalog';
+import { EngineTransportError } from '../../common/errors/engine-transport.error';
+
+/**
+ * Baileys' query() resolves `undefined` when WhatsApp never answers (it catches its own 60s
+ * timeout rather than throwing), and the catalog parsers are null-safe — so an unanswered
+ * catalog IQ is byte-identical to a genuinely empty catalog. These tests pin the only thing
+ * that can tell the two apart: OpenWA's own deadline.
+ */
+
+type SockStub = {
+ getCollections: jest.Mock;
+ getCatalog: jest.Mock;
+};
+
+const never = (): Promise<never> => new Promise<never>(() => undefined);
+
+function build(sock: Partial<SockStub>, budgetMs: number): { catalog: BaileysCatalog; logger: { warn: jest.Mock } } {
+ const logger = { warn: jest.fn() };
+ const host: BaileysCatalogHost = {
+ ensureReady: () => undefined,
+ getSocket: () => sock as unknown as WASocket,
+ normalizedSelfJid: () => '[email protected]',
+ logger: logger as unknown as BaileysCatalogHost['logger'],
+ };
+ return { catalog: new BaileysCatalog(host, budgetMs), logger };
+}
+
+const product = (id: string) => ({
+ id,
+ name: `product ${id}`,
+ price: 1000,
+ currency: 'IDR',
+ imageUrls: { requested: 'https://example.test/i.jpg' },
+ url: 'https://example.test/p',
+ availability: 'in stock',
+ retailerId: `r-${id}`,
+});
+
+describe('BaileysCatalog deadline', () => {
+ it('rejects getCatalog when WhatsApp never answers the collections query', async () => {
+ const { catalog } = build({ getCollections: jest.fn(never) }, 20);
+ await expect(catalog.getCatalog()).rejects.toBeInstanceOf(EngineTransportError);
+ });
+
+ it('rejects getProducts when WhatsApp never answers the catalog query', async () => {
+ const { catalog } = build({ getCatalog: jest.fn(never) }, 20);
+ await expect(catalog.getProducts()).rejects.toBeInstanceOf(EngineTransportError);
+ });
+
+ it('spends ONE budget across the whole page walk, not one per page', async () => {
+ // Each page costs ~30ms against a 70ms budget: a per-call deadline would let the walk run
+ // forever, a shared one must give up on the third page.
+ const getCatalog = jest.fn(
+ () =>
+ new Promise(resolve => {
+ setTimeout(
+ () => resolve({ products: [product('a')], nextPageCursor: `c${getCatalog.mock.calls.length}` }),
+ 30,
+ );
+ }),
+ );
+ const { catalog } = build({ getCatalog }, 70);
+
+ await expect(catalog.getProducts()).rejects.toBeInstanceOf(EngineTransportError);
+ expect(getCatalog.mock.calls.length).toBeLessThanOrEqual(3);
+ });
+
+ it('stops walking when the server repeats a cursor instead of advancing', async () => {
+ const getCatalog = jest.fn(({ cursor }: { cursor?: string }) =>
+ Promise.resolve({ products: [product(cursor ?? 'first')], nextPageCursor: 'stuck' }),
+ );
+ const { catalog } = build({ getCatalog }, 500);
+
+ const page = await catalog.getProducts();
+ expect(getCatalog).toHaveBeenCalledTimes(2);
+ expect(page.pagination.total).toBe(2);
+ });
+
+ it('logs the expiry so the operator can see why the request failed', async () => {
+ const { catalog, logger } = build({ getCollections: jest.fn(never) }, 20);
+ await expect(catalog.getCatalog()).rejects.toBeInstanceOf(EngineTransportError);
+ expect(logger.warn).toHaveBeenCalledTimes(1);
+ });
+});
+
+describe('BaileysCatalog answers within the deadline', () => {
+ it('still reports a genuinely empty catalog as null, not an error', async () => {
+ const { catalog } = build({ getCollections: jest.fn().mockResolvedValue({ collections: [] }) }, 500);
+ await expect(catalog.getCatalog()).resolves.toBeNull();
+ });
+
+ it('still reports a genuinely empty product list as an empty page, not an error', async () => {
+ const { catalog } = build(
+ { getCatalog: jest.fn().mockResolvedValue({ products: [], nextPageCursor: undefined }) },
+ 500,
+ );
+ await expect(catalog.getProducts()).resolves.toEqual({
+ products: [],
+ pagination: { page: 1, limit: 20, total: 0, totalPages: 0 },
+ });
+ });
+
+ it('maps a populated catalog unchanged', async () => {
+ const { catalog } = build(
+ {
+ getCollections: jest.fn().mockResolvedValue({
+ collections: [{ id: 'col-1', name: 'Default', products: [product('a'), product('b')] }],
+ }),
+ },
+ 500,
+ );
+ await expect(catalog.getCatalog()).resolves.toEqual({
+ id: 'col-1',
+ name: 'Default',
+ productCount: 2,
+ url: 'https://wa.me/c/628177',
+ });
+ });
+});
diff --git a/src/engine/adapters/baileys-catalog.ts b/src/engine/adapters/baileys-catalog.ts
index 45a126c1f..49f7c7977 100644
--- a/src/engine/adapters/baileys-catalog.ts
+++ b/src/engine/adapters/baileys-catalog.ts
@@ -1,5 +1,7 @@
import type { Product as BaileysProduct, WASocket } from '@whiskeysockets/baileys';
import { Catalog, PaginatedProducts, Product, ProductQueryOptions } from '../interfaces/whatsapp-engine.interface';
+import { EngineTransportError } from '../../common/errors/engine-transport.error';
+import { type createLogger } from '../../common/services/logger.service';
/**
* Catalog-domain operations extracted from BaileysAdapter (#905). makeBusinessSocket already
@@ -11,14 +13,73 @@ export interface BaileysCatalogHost {
ensureReady(): void;
/** Post-ensureReady socket handle — call host.ensureReady() first. */
getSocket(): WASocket;
+ readonly logger: ReturnType<typeof createLogger>;
normalizedSelfJid(): string;
}
/** Fetch page size for the catalog walk; larger pages mean fewer round trips to WhatsApp. */
const CATALOG_PAGE_SIZE = 50;
+/**
+ * Whole-request budget for a catalog read, spent across every page of the walk rather than
+ * per query. Anchored to MEDIA_DOWNLOAD_TIMEOUT_MS (inbound-media-cap.ts), this repo's existing
+ * number for one bounded network round trip over WhatsApp. It must stay below Baileys'
+ * defaultQueryTimeoutMs (60s) to be observable at all, and below session.proxyTimeoutMs so a
+ * multi-node deployment does not race two deadlines.
+ */
+export const CATALOG_QUERY_BUDGET_MS = 30_000;
+
+/**
+ * Bound one catalog query against the request's remaining budget.
+ *
+ * Baileys catches its own query timeout and resolves `undefined` rather than throwing
+ * (Socket/socket.js: "Catch timeout and return undefined instead of throwing"), and the catalog
+ * parsers are null-safe, so an unanswered IQ is byte-identical to a genuinely empty catalog. No
+ * inspection of the value can separate them — only a clock we own. Shape follows
+ * withInboundDownloadTimeout (inbound-media-cap.ts): unref'd timer, cleared in a finally, and the
+ * abandoned query's late rejection defused.
+ */
+async function withDeadline<T>(work: Promise<T>, remainingMs: number): Promise<T> {
+ let timer: NodeJS.Timeout | undefined;
+ // Defuse a post-settle rejection from the query we may stop awaiting.
+ work.catch(() => undefined);
+ try {
+ return await Promise.race([
+ work,
+ new Promise<never>((_, reject) => {
+ timer = setTimeout(
+ () => reject(new EngineTransportError('WhatsApp did not answer the catalog query in time')),
+ Math.max(0, remainingMs),
+ );
+ timer.unref?.();
+ }),
+ ]);
+ } finally {
+ if (timer) {
+ clearTimeout(timer);
+ }
+ }
+}
+
export class BaileysCatalog {
- constructor(private readonly host: BaileysCatalogHost) {}
+ constructor(
+ private readonly host: BaileysCatalogHost,
+ 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> {
+ try {
+ return await withDeadline(work, deadline - Date.now());
+ } catch (error) {
+ if (error instanceof EngineTransportError) {
+ // Baileys' own "timed out waiting for message" warn is silent at the default
+ // BAILEYS_LOG_LEVEL, so without this line the 503 has no explanation anywhere.
+ this.host.logger.warn('Catalog query exceeded its budget', { budgetMs: this.budgetMs });
+ }
+ throw error;
+ }
+ }
/** Post-ensureReady socket handle. */
private sock(): WASocket {
@@ -33,7 +94,7 @@ export class BaileysCatalog {
async getCatalog(): Promise<Catalog | null> {
this.host.ensureReady();
const jid = this.host.normalizedSelfJid();
- const { collections } = await this.sock().getCollections(jid);
+ const { collections } = await this.bounded(this.sock().getCollections(jid), Date.now() + this.budgetMs);
const first = collections[0];
if (!first) {
return null;
@@ -71,15 +132,24 @@ export class BaileysCatalog {
* ponytail: walks the whole cursor chain on every call (no cursor cache), so page N costs the
* full catalog. WhatsApp caps catalogs at ~500 products; if profiling shows the walk matters,
* cache pages keyed by cursor and serve offsets from the cache.
+ *
+ * The budget is computed once and shared by every page: a per-query deadline would multiply by
+ * the page count, making a ten-page walk slower than the 60s stall it replaces.
*/
private async fetchAllProducts(): Promise<BaileysProduct[]> {
this.host.ensureReady();
const jid = this.host.normalizedSelfJid();
+ const deadline = Date.now() + this.budgetMs;
const products: BaileysProduct[] = [];
let cursor: string | undefined;
do {
- const page = await this.sock().getCatalog({ jid, limit: CATALOG_PAGE_SIZE, cursor });
+ const page = await this.bounded(this.sock().getCatalog({ jid, limit: CATALOG_PAGE_SIZE, cursor }), deadline);
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.
+ if (page.nextPageCursor === cursor) {
+ break;
+ }
cursor = page.nextPageCursor;
} while (cursor);
return products;
diff --git a/src/engine/adapters/baileys.adapter.ts b/src/engine/adapters/baileys.adapter.ts
index 6573a966c..be022f261 100644
--- a/src/engine/adapters/baileys.adapter.ts
+++ b/src/engine/adapters/baileys.adapter.ts
@@ -189,6 +189,7 @@ export class BaileysAdapter implements IWhatsAppEngine {
this.catalog = new BaileysCatalog({
ensureReady: () => this.ensureReady(),
getSocket: () => this.sock!,
+ logger: this.logger,
normalizedSelfJid: () => this.normalizedSelfJid(),
});
this.history = new BaileysHistory({
diff --git a/src/modules/catalog/catalog.controller.ts b/src/modules/catalog/catalog.controller.ts
index fea195e8b..cfb83956d 100644
--- a/src/modules/catalog/catalog.controller.ts
+++ b/src/modules/catalog/catalog.controller.ts
@@ -5,6 +5,13 @@ import { SendProductDto, SendCatalogDto, ProductQueryDto } from './dto/send-prod
import { RequireRole } from '../auth/decorators/auth.decorators';
import { ApiKeyRole } from '../auth/entities/api-key.entity';
+/**
+ * Every catalog read walks WhatsApp's business-catalog IQ, which the server simply leaves
+ * unanswered for an account without a catalog. The adapter bounds that walk with its own budget
+ * rather than reporting an unanswered query as an empty catalog.
+ */
+const CATALOG_TIMEOUT_503 = 'WhatsApp did not answer the catalog query within the request budget — retry shortly.';
+
@ApiTags('catalog')
@Controller('sessions/:sessionId')
export class CatalogController {
@@ -16,6 +23,7 @@ export class CatalogController {
status: 501,
description: 'Not supported by the active engine: whatsapp-web.js has no catalog API.',
})
+ @ApiResponse({ status: 503, description: CATALOG_TIMEOUT_503 })
async getCatalog(@Param('sessionId') sessionId: string) {
return this.catalogService.getCatalog(sessionId);
}
@@ -26,6 +34,7 @@ export class CatalogController {
status: 501,
description: 'Not supported by the active engine: whatsapp-web.js has no catalog API.',
})
+ @ApiResponse({ status: 503, description: CATALOG_TIMEOUT_503 })
async getProducts(@Param('sessionId') sessionId: string, @Query() query: ProductQueryDto) {
return this.catalogService.getProducts(sessionId, query.page, query.limit);
}
@@ -36,6 +45,7 @@ export class CatalogController {
status: 501,
description: 'Not supported by the active engine: whatsapp-web.js has no catalog API.',
})
+ @ApiResponse({ status: 503, description: CATALOG_TIMEOUT_503 })
async getProduct(@Param('sessionId') sessionId: string, @Param('productId') productId: string) {
return this.catalogService.getProduct(sessionId, productId);
}
@@ -49,6 +59,7 @@ export class CatalogController {
status: 501,
description: 'Not supported by the active engine: whatsapp-web.js cannot send product messages.',
})
+ @ApiResponse({ status: 503, description: CATALOG_TIMEOUT_503 })
async sendProduct(@Param('sessionId') sessionId: string, @Body() dto: SendProductDto) {
return this.catalogService.sendProduct(sessionId, dto.chatId, dto.productId, dto.body);
}