Free, Open Source, Self-Hosted WhatsApp API Gateway
TypeScript apibotgatewayself-hostedwhatsappwhatsapp-apiwhatsapp-automationwhatsapp-botwhatsapp-gatewaywhatsapp-gateway-apiwhatsapp-webwhatsapp-web-api
fix(sdk-python): name the status of an empty error and check the timeout
Yudhi Armyndharis87fdb9d97623
diff --git a/sdk/python/openwa/_http.py b/sdk/python/openwa/_http.pyindex 497882b8e..6a15f4dd3 100644--- a/sdk/python/openwa/_http.py+++ b/sdk/python/openwa/_http.py@@ -9,6 +9,7 @@ consumers intercept/observability-wrap outbound calls.from __future__ import annotations+import mathfrom typing import Any, Mappingfrom urllib.parse import quote@@ -64,6 +65,22 @@ def build_url(base_url: str, path: str, query: Mapping[str, Any] | None = None)return str(httpx.URL(url).copy_merge_params(params))+def resolve_timeout(timeout: float | None) -> float | None:+ """The timeout httpx is given: seconds per network operation, or ``None`` for none.++ ``None``, ``0`` and ``math.inf`` mean no timeout, as ``0`` does in the JavaScript and PHP clients;+ httpx would otherwise take ``0`` literally and fail every connect. Anything that is not a+ non-negative number raises at construction rather than at the first request.+ """+ if timeout is None:+ return None+ if isinstance(timeout, bool) or not isinstance(timeout, (int, float)) or math.isnan(timeout) or timeout < 0:+ raise ValueError(+ f"OpenWAClient: timeout must be a non-negative number of seconds, or None for none (got {timeout!r})"+ )+ return None if timeout == 0 or math.isinf(timeout) else float(timeout)++class HttpExecutor:"""Owns the :class:`httpx.Client` and performs JSON requests.@@ -75,10 +92,11 @@ class HttpExecutor:self,base_url: str,api_key: str,- timeout: float = 30.0,+ timeout: float | None = 30.0,default_headers: Mapping[str, str] | None = None,transport: httpx.BaseTransport | None = None,) -> None:+ timeout = resolve_timeout(timeout)# Caller-supplied default headers are applied FIRST so the auth/JSON# headers below always win and can never be clobbered (mirrors the JS SDK).# httpx.Headers matches names case-insensitively, so a lowercase copy is@@ -155,11 +173,13 @@ class HttpExecutor:try:res = self._client.request(method, url, json=body if body is not None else None, headers=headers)except httpx.TimeoutException as e:- raise OpenWATimeoutError(self._timeout) from e+ raise OpenWATimeoutError(self._timeout or 0) from e# Treat any non-2xx as an error, including 3xx: redirects are deliberately not followed# (so the API key is never re-sent to the target), which makes an unfollowed 3xx unusable# rather than a success. Matches the JS transport's `!res.ok`.if res.status_code >= 300:context = f"{method} {path}"- raise OpenWAApiError.from_response(res.status_code, res.text, context, headers=res.headers)+ raise OpenWAApiError.from_response(+ res.status_code, res.text, context, headers=res.headers, reason=res.reason_phrase+ )return resdiff --git a/sdk/python/openwa/client.py b/sdk/python/openwa/client.pyindex d8d599f33..d91b669a4 100644--- a/sdk/python/openwa/client.py+++ b/sdk/python/openwa/client.py@@ -85,7 +85,9 @@ class OpenWAClient:base_url: str,api_key: str,*,- timeout: float = 30.0,+ # Seconds per network operation (connect, read, write, pool), not for the whole call: a response+ # that keeps trickling bytes is not cut off. 0 or None means no timeout.+ timeout: float | None = 30.0,default_headers: Mapping[str, str] | None = None,transport: httpx.BaseTransport | None = None,) -> None:diff --git a/sdk/python/openwa/errors.py b/sdk/python/openwa/errors.pyindex c5bfffe10..fa1279313 100644--- a/sdk/python/openwa/errors.py+++ b/sdk/python/openwa/errors.py@@ -59,7 +59,13 @@ class OpenWAApiError(OpenWAError):@classmethoddef from_response(- cls, status_code: int, text: str, context: str, *, headers: Mapping[str, str] | None = None+ cls,+ status_code: int,+ text: str,+ context: str,+ *,+ headers: Mapping[str, str] | None = None,+ reason: str | None = None,) -> "OpenWAApiError":import json@@ -75,6 +81,10 @@ class OpenWAApiError(OpenWAError):message_text = ", ".join(str(m) for m in raw_message)elif isinstance(raw_message, str):message_text = raw_message+ elif raw_message is None:+ # An empty body (a proxy's bare 502) or an envelope with no message: the status text is all+ # there is, and "None" would be read as the reason.+ message_text = reason or "no response body"else:message_text = str(raw_message)message = f"OpenWA API {status_code} — {context}: {message_text}"diff --git a/sdk/python/tests/test_sdk.py b/sdk/python/tests/test_sdk.pyindex 8bb44c2a4..54ec28e0c 100644--- a/sdk/python/tests/test_sdk.py+++ b/sdk/python/tests/test_sdk.py@@ -254,6 +254,25 @@ class TestClientCore:plain = fail(500, text="oops")assert plain.code is None and plain.retry_after_seconds is None+ def test_an_error_with_no_body_names_the_status_text_not_none(self):+ # A proxy in front of the gateway answers 502 and 504 with nothing.+ transport = httpx.MockTransport(lambda _: httpx.Response(502, content=b""))+ client = OpenWAClient(base_url="https://x", api_key="k", transport=transport)+ with pytest.raises(OpenWAApiError) as caught:+ client.health.live()+ assert "Bad Gateway" in str(caught.value)+ assert "None" not in str(caught.value)++ def test_timeout_zero_none_and_inf_mean_none_and_a_bad_value_raises(self):+ for none in (0, None, float("inf")):+ client = OpenWAClient(base_url="https://x", api_key="k", timeout=none)+ assert client._http._client.timeout == httpx.Timeout(None)+ client = OpenWAClient(base_url="https://x", api_key="k", timeout=2.5)+ assert client._http._client.timeout == httpx.Timeout(2.5)+ for bad in (-1, float("nan"), "30", True):+ with pytest.raises(ValueError, match="timeout"):+ OpenWAClient(base_url="https://x", api_key="k", timeout=bad) # type: ignore[arg-type]+def test_maps_503_to_service_unavailable(self):# The gateway answers 503 when the engine never confirmed an operation: a transport failure,# which is worth retrying, as a 429 is. It used to fall through to the base class while the