Free, Open Source, Self-Hosted WhatsApp API Gateway
TypeScript apibotgatewayself-hostedwhatsappwhatsapp-apiwhatsapp-automationwhatsapp-botwhatsapp-gatewaywhatsapp-gateway-apiwhatsapp-webwhatsapp-web-api
fix(engine): answer a WhatsApp rate limit on Baileys writes with 503
Yudhi Armyndharis73f8c1bab31b
diff --git a/src/engine/adapters/baileys-catalog.ts b/src/engine/adapters/baileys-catalog.tsindex 54b086fe4..6533438cd 100644--- a/src/engine/adapters/baileys-catalog.ts+++ b/src/engine/adapters/baileys-catalog.ts@@ -59,8 +59,9 @@ export class BaileysCatalog {} 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 });+ // BAILEYS_LOG_LEVEL, so without this line the 503 has no explanation anywhere. The message+ // tells a spent budget apart from a rate limit WhatsApp answered.+ this.host.logger.warn('Catalog query got no usable answer', { budgetMs: this.budgetMs, error: error.message });}throw error;}diff --git a/src/engine/adapters/baileys-contacts.ts b/src/engine/adapters/baileys-contacts.tsindex 502894a0a..c9545cdc1 100644--- a/src/engine/adapters/baileys-contacts.ts+++ b/src/engine/adapters/baileys-contacts.ts@@ -94,9 +94,14 @@ export class BaileysContacts {}// Only WhatsApp's own error answer (a numeric code: 404 item-not-found, 401 not-authorized) is// that verdict. A socket that closed mid-lookup carries none and must not read as "no picture".- if (refusedStatusCode(err) === undefined) {+ const code = refusedStatusCode(err);+ if (code === undefined) {throw new EngineTransportError('WhatsApp did not answer the profile picture lookup');}+ // A rate limit or server timeout (408/429) is not a verdict about the picture either.+ if (code === 408 || code === 429) {+ throw new EngineTransportError(`WhatsApp rate-limited or timed out the profile picture lookup (code ${code})`);+ }this.host.logger.debug('profilePictureUrl failed; no picture or hidden', {contactId,error: err instanceof Error ? err.message : String(err),diff --git a/src/engine/adapters/baileys-group-metadata.spec.ts b/src/engine/adapters/baileys-group-metadata.spec.tsindex 317f74d60..9fb8734dc 100644--- a/src/engine/adapters/baileys-group-metadata.spec.ts+++ b/src/engine/adapters/baileys-group-metadata.spec.ts@@ -69,6 +69,13 @@ describe('getGroupJoinInfo', () => {GroupNotFoundError,);});++ it('reports a rate-limited lookup as retryable instead of a missing invite', async () => {+ const groupGetInviteInfo = jest.fn().mockRejectedValue(new Boom('rate-overlimit', { data: 429 }));+ await expect(groups({ groupGetInviteInfo }, 500).getGroupJoinInfo('CODE')).rejects.toBeInstanceOf(+ EngineTransportError,+ );+ });});describe('createGroup', () => {@@ -85,6 +92,12 @@ describe('createGroup', () => {await expect(groups({ groupCreate }, 500).createGroup('G', [])).rejects.toBe(err);});+ it('lets a WA timeout propagate untouched, since the group may have been created', async () => {+ const err = new Boom('timeout', { data: 408 });+ const groupCreate = jest.fn().mockRejectedValue(err);+ await expect(groups({ groupCreate }, 500).createGroup('G', [])).rejects.toBe(err);+ });+it('still returns the created group', async () => {const groupCreate = jest.fn().mockResolvedValue(META);await expect(groups({ groupCreate }, 500).createGroup('G', [])).resolves.toMatchObject({diff --git a/src/engine/adapters/baileys-groups.ts b/src/engine/adapters/baileys-groups.tsindex 98a9e4bc8..cd28b816f 100644--- a/src/engine/adapters/baileys-groups.ts+++ b/src/engine/adapters/baileys-groups.ts@@ -73,6 +73,9 @@ export function refusedStatusCode(error: unknown): number | undefined {* failures (dropped socket, timeout) propagate untouched: folding them in would report a dead* connection as a permissions problem.*+ * WA codes 408 and 429 (timed out, rate limited) become EngineTransportError (503) instead: a+ * throttled caller has not been refused, and a retry may succeed.+ ** `notFound`, when given, takes WA code 404 (item-not-found) instead: a caller whose request names a* single resource maps it to that resource's not-found error rather than a permissions refusal.*/@@ -89,6 +92,9 @@ export async function mapServerRefusal<T>(if (code === 404 && notFound) {throw notFound();}+ if (code === 408 || code === 429) {+ throw new EngineTransportError(`${operation} was rate-limited or timed out by WhatsApp (code ${code})`);+ }if (code !== undefined && code >= 400 && code < 500) {throw new EngineRefusedError(`${operation} was refused by WhatsApp (code ${code}) — admin rights or permissions may be missing`,@@ -221,12 +227,18 @@ export class BaileysGroups {* the one non-idempotent operation here, and 503 is a backpressure status the Go SDK retries three* times for POST (sdk/go/retry.go) — an OpenWA deadline abandons the call without cancelling it,* so a slow-but-succeeding create could be issued four times and leave duplicate groups. An- * unanswered query therefore still surfaces opaquely rather than as something retryable.+ * unanswered query therefore still surfaces opaquely rather than as something retryable, and so+ * does WA code 408: a server timeout does not say whether the group was created.*/async createGroup(name: string, participants: string[]): Promise<Group> {this.host.ensureReady();- const metadata = await mapServerRefusal('Creating the group', () =>- this.sock().groupCreate(name, this.toEngineParticipants(participants)),+ const metadata = await mapServerRefusal(+ 'Creating the group',+ () => this.sock().groupCreate(name, this.toEngineParticipants(participants)),+ error => {+ const code = refusedStatusCode(error);+ return code === 408 ? undefined : code;+ },);return mapBaileysGroup(metadata, this.host.normalizedSelfJid(), jid => this.host.toNeutralJid(jid));}@@ -370,6 +382,9 @@ export class BaileysGroups {// Baileys throws a Boom carrying the WA code for an invalid/expired/revoked invite — the// route's documented 404 (matching whatsapp-web.js), not a 500. Transport failures propagate.const code = refusedStatusCode(error);+ if (code === 408 || code === 429) {+ throw new EngineTransportError(`WhatsApp rate-limited or timed out the invite-info query (code ${code})`);+ }if (code !== undefined && code >= 400 && code < 500) {throw new GroupNotFoundError(inviteCode);}@@ -413,6 +428,9 @@ export class BaileysGroups {if (code === undefined || code < 400 || code >= 500) {throw error;}+ if (code === 408 || code === 429) {+ throw new EngineTransportError(`WhatsApp rate-limited or timed out the group join (code ${code})`);+ }this.host.logger.warn('Group invite refused', { error: String(error) });jid = undefined;}diff --git a/src/engine/adapters/baileys-profile-picture.spec.ts b/src/engine/adapters/baileys-profile-picture.spec.tsindex 864701f65..4c715897c 100644--- a/src/engine/adapters/baileys-profile-picture.spec.ts+++ b/src/engine/adapters/baileys-profile-picture.spec.ts@@ -42,6 +42,13 @@ describe('getProfilePicture', () => {await expect(contacts({ profilePictureUrl }, 500).getProfilePicture('[email protected]')).resolves.toBeNull();});+ it('reports a rate-limited lookup instead of "no picture"', async () => {+ const profilePictureUrl = jest.fn().mockRejectedValue(new Boom('rate-overlimit', { data: 429 }));+ await expect(contacts({ profilePictureUrl }, 500).getProfilePicture('[email protected]')).rejects.toBeInstanceOf(+ EngineTransportError,+ );+ });+it('reports a connection that closed mid-lookup instead of "no picture"', async () => {const profilePictureUrl = jest.fn().mockRejectedValue(new Boom('Connection Closed', { statusCode: 428 }));await expect(contacts({ profilePictureUrl }, 500).getProfilePicture('[email protected]')).rejects.toBeInstanceOf(diff --git a/src/engine/adapters/baileys-refused-status.spec.ts b/src/engine/adapters/baileys-refused-status.spec.tsindex f50677169..932c65bcd 100644--- a/src/engine/adapters/baileys-refused-status.spec.ts+++ b/src/engine/adapters/baileys-refused-status.spec.ts@@ -1,6 +1,8 @@import { Boom } from '@hapi/boom';import { refusedStatusCode, mapServerRefusal } from './baileys-groups';+import { wmexRefusalCode } from './baileys-channels';import { EngineRefusedError } from '../../common/errors/engine-refused.error';+import { EngineTransportError } from '../../common/errors/engine-transport.error';/*** `refusedStatusCode` decides whether a Baileys failure was a SERVER refusal (map to 403/404) or a@@ -70,4 +72,17 @@ describe('mapServerRefusal', () => {const noAnswer = new Boom('Invalid group metadata response: missing <group> node', { data: undefined });await expect(mapServerRefusal('Setting the group subject', () => Promise.reject(noAnswer))).rejects.toBe(noAnswer);});++ it('answers a rate limit or a server timeout as 503, not a permissions refusal', async () => {+ const graphQl = (code: number) =>+ new Boom('GraphQL server error: rate limited', { statusCode: code, data: { extensions: { error_code: code } } });+ for (const code of [408, 429]) {+ await expect(+ mapServerRefusal('Adding participants', () => Promise.reject(new Boom('rate-overlimit', { data: code }))),+ ).rejects.toBeInstanceOf(EngineTransportError);+ await expect(+ mapServerRefusal('Deleting the channel', () => Promise.reject(graphQl(code)), wmexRefusalCode),+ ).rejects.toBeInstanceOf(EngineTransportError);+ }+ });});diff --git a/src/engine/adapters/baileys-transport-status.spec.ts b/src/engine/adapters/baileys-transport-status.spec.tsindex 189988a16..dbd2ea40a 100644--- a/src/engine/adapters/baileys-transport-status.spec.ts+++ b/src/engine/adapters/baileys-transport-status.spec.ts@@ -41,6 +41,13 @@ describe('joinGroupViaInviteCode', () => {);});+ it('reports a rate-limited join as retryable instead of calling the invite code invalid', async () => {+ const groupAcceptInvite = jest.fn().mockRejectedValue(new Boom('rate-overlimit', { data: 429 }));+ await expect(groups({ groupAcceptInvite }, 500).joinGroupViaInviteCode('CODE')).rejects.toBeInstanceOf(+ EngineTransportError,+ );+ });+it('still calls an answered-but-empty result invalid — that is a real refusal', async () => {const groupAcceptInvite = jest.fn().mockResolvedValue(undefined);await expect(groups({ groupAcceptInvite }, 500).joinGroupViaInviteCode('BAD')).rejects.toBeInstanceOf(