Free, Open Source, Self-Hosted WhatsApp API Gateway
TypeScript apibotgatewayself-hostedwhatsappwhatsapp-apiwhatsapp-automationwhatsapp-botwhatsapp-gatewaywhatsapp-gateway-apiwhatsapp-webwhatsapp-web-api
fix(sdk): give the retryable status a type of its own
Yudhi Armyndharisca18cbf7bb22
diff --git a/CHANGELOG.md b/CHANGELOG.mdindex 95f59e1cd..dd3b3db94 100644--- a/CHANGELOG.md+++ b/CHANGELOG.md@@ -10,6 +10,7 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0### Fixed- **Two statements in the codebase that were not true** — a load-bearing comment justified skipping a lookup on the grounds that PostgreSQL would raise a 500 against a uuid column, when `sessions.id` is `varchar` on both dialects and a malformed id simply matches nothing; and the webhook event table stated all 22 events are actively dispatched by the engines without saying that four of them fire on Baileys only, which the same document states 2 200 lines later.+- **All five SDKs now give the retryable status a type of its own** — every one classified `401`, `403`, `404`, `409`, `429` and `501` into a dedicated error and let `503` fall through to the base class, which inverted the mapping against usefulness: `501 Not Implemented` is permanent and never worth retrying, while `503` is the transport failure a caller should retry — and 0.14.5 made it the standard answer for "WhatsApp never confirmed" across 47 of the 189 operations.### Fixeddiff --git a/sdk/go/client_test.go b/sdk/go/client_test.goindex 15712410d..96a92858d 100644--- a/sdk/go/client_test.go+++ b/sdk/go/client_test.go@@ -861,6 +861,25 @@ func TestUpdateGroupSettingsOmitsUnsetFields(t *testing.T) {}}+// A 503 is the gateway's answer when the engine never confirmed an operation — a transport failure,+// and the one sentinel here worth retrying. It used to have none, while the permanent 501 did.+func TestServiceUnavailableIsRetryableSentinel(t *testing.T) {+ rt := &recordTransport{+ status: 503,+ body: `{"statusCode":503,"message":"WhatsApp did not answer in time","error":"Service Unavailable"}`,+ }+ c := newTestClient(t, rt)++ _, err := c.Groups.Get(context.Background(), "s1", "g1")+ if !errors.Is(err, ErrServiceUnavailable) {+ t.Fatalf("errors.Is ErrServiceUnavailable = false for %v", err)+ }+ // It must not also satisfy a sentinel that would mislead a caller into NOT retrying.+ if errors.Is(err, ErrNotImplemented) {+ t.Fatal("a 503 must not match ErrNotImplemented")+ }+}+// Setting ephemeralSeconds on the whatsapp-web.js engine surfaces as 501.func TestUpdateGroupSettingsNotImplemented(t *testing.T) {rt := &recordTransport{diff --git a/sdk/go/errors.go b/sdk/go/errors.goindex 930ded586..d6a8ed622 100644--- a/sdk/go/errors.go+++ b/sdk/go/errors.go@@ -33,6 +33,12 @@ var (// ErrNotImplemented is returned for a 501 (the active engine does not// support this operation).ErrNotImplemented = errors.New("openwa: not implemented")+ // ErrServiceUnavailable is returned for a 503 — a transport failure rather+ // than a refusal: WhatsApp never replied, the socket was down, or the+ // request budget ran out. Unlike every other sentinel here it is+ // RETRYABLE. The non-idempotent sends are deliberately left unbounded by+ // the gateway so they never answer one.+ ErrServiceUnavailable = errors.New("openwa: service unavailable"))// APIError is returned when the API responds with a non-2xx status. A 3xx also@@ -76,6 +82,8 @@ func (e *APIError) Is(target error) bool {return target == ErrRateLimitedcase 501:return target == ErrNotImplemented+ case 503:+ return target == ErrServiceUnavailable}return false}diff --git a/sdk/java/src/main/java/com/rmyndharis/openwa/errors/OpenWAApiError.java b/sdk/java/src/main/java/com/rmyndharis/openwa/errors/OpenWAApiError.javaindex d66f00987..db39207df 100644--- a/sdk/java/src/main/java/com/rmyndharis/openwa/errors/OpenWAApiError.java+++ b/sdk/java/src/main/java/com/rmyndharis/openwa/errors/OpenWAApiError.java@@ -107,6 +107,7 @@ public class OpenWAApiError extends OpenWAError {case 409 -> new OpenWAConflictError(message, status, body, errorKind);case 429 -> new OpenWARateLimitError(message, status, body, errorKind);case 501 -> new OpenWANotImplementedError(message, status, body, errorKind);+ case 503 -> new OpenWAServiceUnavailableError(message, status, body, errorKind);default -> new OpenWAApiError(message, status, body, errorKind);};}diff --git a/sdk/java/src/main/java/com/rmyndharis/openwa/errors/OpenWAServiceUnavailableError.java b/sdk/java/src/main/java/com/rmyndharis/openwa/errors/OpenWAServiceUnavailableError.javanew file mode 100644index 000000000..8fa511e80--- /dev/null+++ b/sdk/java/src/main/java/com/rmyndharis/openwa/errors/OpenWAServiceUnavailableError.java@@ -0,0 +1,15 @@+package com.rmyndharis.openwa.errors;++/**+ * 503 Service Unavailable — a transport failure, not a refusal.+ *+ * <p>The gateway answers this when the engine did not confirm the operation in time: WhatsApp never+ * replied, the socket was down, or the request budget ran out. <b>Retryable</b>, unlike every other+ * typed error here. The non-idempotent sends are deliberately left unbounded by the gateway so they+ * never answer one.+ */+public class OpenWAServiceUnavailableError extends OpenWAApiError {+ public OpenWAServiceUnavailableError(String message, int status, Object body, String errorKind) {+ super(message, status, body, errorKind);+ }+}diff --git a/sdk/java/src/test/java/com/rmyndharis/openwa/errors/ErrorsTest.java b/sdk/java/src/test/java/com/rmyndharis/openwa/errors/ErrorsTest.javaindex bcc97cabe..661919f3e 100644--- a/sdk/java/src/test/java/com/rmyndharis/openwa/errors/ErrorsTest.java+++ b/sdk/java/src/test/java/com/rmyndharis/openwa/errors/ErrorsTest.java@@ -24,6 +24,17 @@ class ErrorsTest {assertTrue(e.getMessage().contains("a must be set, b invalid"));}+ @Test+ void mapsTheRetryableStatusToItsOwnSubclass() {+ // 503 is the gateway's answer when the engine never confirmed an operation — a transport+ // failure, and the only typed error here worth retrying. It used to fall through to the base+ // class while 501, which is permanent, had a subclass of its own.+ String body = "{\"statusCode\":503,\"message\":\"WhatsApp did not answer\",\"error\":\"Service Unavailable\"}";+ OpenWAApiError e = OpenWAApiError.fromResponse(503, "Service Unavailable", body, "POST /x");+ assertTrue(e instanceof OpenWAServiceUnavailableError);+ assertEquals(503, e.status());+ }+@Testvoid unmappedStatusFallsBackToBase() {OpenWAApiError e = OpenWAApiError.fromResponse(418, "I'm a teapot", "", "GET /x");diff --git a/sdk/javascript/src/errors.ts b/sdk/javascript/src/errors.tsindex 5a656a922..1fc2ba389 100644--- a/sdk/javascript/src/errors.ts+++ b/sdk/javascript/src/errors.ts@@ -80,6 +80,16 @@ export class OpenWARateLimitError extends OpenWAApiError {}/** 501 Not Implemented — the active engine does not support this operation. */export class OpenWANotImplementedError extends OpenWAApiError {}+/**+ * 503 Service Unavailable — a transport failure, not a refusal. The gateway answers this when the+ * engine did not confirm the operation in time: WhatsApp never replied, the socket was down, or the+ * request budget ran out. **Retryable**, unlike every other typed error here.+ *+ * Not every 503 is safe to repeat blindly: the non-idempotent sends (group create, channel create,+ * media send) are deliberately left unbounded by the gateway precisely so they never answer one.+ */+export class OpenWAServiceUnavailableError extends OpenWAApiError {}+/** Thrown when a request exceeds the configured timeout. */export class OpenWATimeoutError extends OpenWAError {constructor(timeoutMs: number) {@@ -106,6 +116,8 @@ export function classifyApiError(status: number, message: string, body: unknown,return new OpenWARateLimitError(message, status, body, errorKind);case 501:return new OpenWANotImplementedError(message, status, body, errorKind);+ case 503:+ return new OpenWAServiceUnavailableError(message, status, body, errorKind);default:return new OpenWAApiError(message, status, body, errorKind);}diff --git a/sdk/javascript/test/client.test.ts b/sdk/javascript/test/client.test.tsindex ca0a6377e..0c2f9db6a 100644--- a/sdk/javascript/test/client.test.ts+++ b/sdk/javascript/test/client.test.ts@@ -8,6 +8,7 @@ import {OpenWAConflictError,OpenWARateLimitError,OpenWANotImplementedError,+ OpenWAServiceUnavailableError,OpenWATimeoutError,} from '../src';import type { FetchLike } from '../src';@@ -100,6 +101,19 @@ describe('OpenWAClient', () => {await expect(client(t).sessions.get('missing')).rejects.toMatchObject({ status: 404 });});+ it('maps a 503 to OpenWAServiceUnavailableError', async () => {+ // The gateway answers 503 when the engine never confirmed an operation. It is the only typed error+ // here that is worth retrying, and it used to fall through to the base class while 501 — which is+ // permanent — had a subclass of its own.+ const t = new MockTransport().on('POST', '/api/sessions/s1/messages/send-text', {+ status: 503,+ body: { statusCode: 503, message: 'WhatsApp did not answer in time', error: 'Service Unavailable' },+ });+ await expect(client(t).messages.sendText('s1', { chatId: '[email protected]', text: 'x' })).rejects.toBeInstanceOf(+ OpenWAServiceUnavailableError,+ );+ });+it('exposes all expected resource properties', () => {const c = client(new MockTransport());for (const r of [diff --git a/sdk/php/src/Exceptions/OpenWAApiException.php b/sdk/php/src/Exceptions/OpenWAApiException.phpindex 7fd0edb1d..c19f11e36 100644--- a/sdk/php/src/Exceptions/OpenWAApiException.php+++ b/sdk/php/src/Exceptions/OpenWAApiException.php@@ -58,6 +58,7 @@ class OpenWAApiException extends OpenWAException409 => new OpenWAConflictException($message, $status, $body, $errorKind),429 => new OpenWARateLimitException($message, $status, $body, $errorKind),501 => new OpenWANotImplementedException($message, $status, $body, $errorKind),+ 503 => new OpenWAServiceUnavailableException($message, $status, $body, $errorKind),default => new OpenWAApiException($message, $status, $body, $errorKind),};}diff --git a/sdk/php/src/Exceptions/OpenWAServiceUnavailableException.php b/sdk/php/src/Exceptions/OpenWAServiceUnavailableException.phpnew file mode 100644index 000000000..0f48172f3--- /dev/null+++ b/sdk/php/src/Exceptions/OpenWAServiceUnavailableException.php@@ -0,0 +1,17 @@+<?php++declare(strict_types=1);++namespace OpenWA\Exceptions;++/**+ * 503 Service Unavailable — a transport failure, not a refusal.+ *+ * The gateway answers this when the engine did not confirm the operation in time: WhatsApp never+ * replied, the socket was down, or the request budget ran out. Retryable, unlike every other typed+ * exception here. The non-idempotent sends are deliberately left unbounded by the gateway so they+ * never answer one.+ */+class OpenWAServiceUnavailableException extends OpenWAApiException+{+}diff --git a/sdk/python/openwa/errors.py b/sdk/python/openwa/errors.pyindex 9b3dfc8d2..93c912f95 100644--- a/sdk/python/openwa/errors.py+++ b/sdk/python/openwa/errors.py@@ -78,6 +78,16 @@ class OpenWANotImplementedError(OpenWAApiError):"""501 Not Implemented — the active engine does not support this operation."""+class OpenWAServiceUnavailableError(OpenWAApiError):+ """503 Service Unavailable -- a transport failure, not a refusal.++ The gateway answers this when the engine did not confirm the operation in time: WhatsApp never+ replied, the socket was down, or the request budget ran out. Retryable, unlike every other typed+ error here. The non-idempotent sends are deliberately left unbounded by the gateway so they never+ answer one.+ """++class OpenWATimeoutError(OpenWAError):"""Raised when a request exceeds the configured timeout."""@@ -95,5 +105,6 @@ def classify(status: int, message: str, body: Any, error_kind: str | None) -> Op409: OpenWAConflictError,429: OpenWARateLimitError,501: OpenWANotImplementedError,+ 503: OpenWAServiceUnavailableError,}.get(status, OpenWAApiError)return cls(message, status, body, error_kind)diff --git a/sdk/python/tests/test_sdk.py b/sdk/python/tests/test_sdk.pyindex 9e4691707..a4a151fc4 100644--- a/sdk/python/tests/test_sdk.py+++ b/sdk/python/tests/test_sdk.py@@ -6,6 +6,7 @@ import httpximport pytestfrom openwa import OpenWAClient, OpenWAApiError, OpenWANotFoundError+from openwa.errors import OpenWAServiceUnavailableErrorfrom conftest import MockBackend, make_client@@ -109,6 +110,17 @@ class TestClientCore:with pytest.raises(OpenWANotFoundError):make_client(backend).sessions.get("missing")+ def test_maps_503_to_service_unavailable(self):+ # The gateway answers 503 when the engine never confirmed an operation -- the one typed error+ # here worth retrying. It used to fall through to the base class while the permanent 501 had a+ # subclass of its own.+ backend = MockBackend()+ backend.on("GET", "/api/sessions/s1", 503, {+ "statusCode": 503, "message": "WhatsApp did not answer", "error": "Service Unavailable"+ })+ with pytest.raises(OpenWAServiceUnavailableError):+ make_client(backend).sessions.get("s1")+def test_exposes_all_resources(self):client = make_client(MockBackend())for r in ["sessions", "messages", "contacts", "groups", "webhooks", "chats", "status", "health", "search", "profile", "calls"]: