Skip to content

Free, Open Source, Self-Hosted WhatsApp API Gateway

fix(sdk-python): make API and timeout errors picklable

Yudhi Armyndharis29331cd8994a
diff --git a/sdk/python/openwa/errors.py b/sdk/python/openwa/errors.py
index 9131b6cbe..6a7108a23 100644
--- a/sdk/python/openwa/errors.py
+++ b/sdk/python/openwa/errors.py
@@ -57,6 +57,10 @@ class OpenWAApiError(OpenWAError):
header = next((v for k, v in (headers or {}).items() if k.lower() == "retry-after"), None)
self.retry_after_seconds = _retry_after_seconds(fields.get("retryAfterSeconds"), header)
+ def __reduce__(self) -> tuple[Any, ...]:
+ # Exception pickles only `args` (the message), which cannot rebuild an error that needs a status.
+ return (_rebuild_api_error, (type(self), self.args[0], self.status, self.body, self.error_kind, self.headers))
+
@classmethod
def from_response(
cls,
@@ -160,6 +164,10 @@ class OpenWATimeoutError(OpenWAError):
super().__init__(f"Request timed out after {timeout}s")
self.timeout = timeout
+ def __reduce__(self) -> tuple[Any, ...]:
+ # `args` holds the formatted message, which would be formatted again on the way back.
+ return (type(self), (self.timeout,))
+
def classify(
status: int, message: str, body: Any, error_kind: str | None, *, headers: Mapping[str, str] | None = None
@@ -177,6 +185,17 @@ def classify(
return cls(message, status, body, error_kind, headers=headers)
+def _rebuild_api_error(
+ cls: type[OpenWAApiError],
+ message: str,
+ status: int,
+ body: Any,
+ error_kind: str | None,
+ headers: Mapping[str, str] | None,
+) -> OpenWAApiError:
+ return cls(message, status, body, error_kind, headers=headers)
+
+
def _retry_after_seconds(from_body: Any, header: str | None) -> int | None:
"""The body's ``retryAfterSeconds`` wins: send pacing puts its wait (possibly hours) only there,
and a header added by a proxy must not shorten it. Otherwise read ``Retry-After`` as seconds or
diff --git a/sdk/python/tests/test_sdk.py b/sdk/python/tests/test_sdk.py
index 733c275b1..1ce6f6c4d 100644
--- a/sdk/python/tests/test_sdk.py
+++ b/sdk/python/tests/test_sdk.py
@@ -187,6 +187,27 @@ class TestClientCore:
assert caught.value.status == 429
assert caught.value.retry_after_seconds is None
+ def test_errors_survive_pickle_and_copy(self) -> None:
+ # Worker pools (multiprocessing, concurrent.futures) carry a raised exception across processes.
+ import copy
+ import pickle
+
+ err = OpenWAApiError.from_response(
+ 429,
+ '{"statusCode": 429, "message": "slow", "error": "Too Many Requests", "code": "SEND_PACING_LIMITED"}',
+ "POST /x",
+ headers={"Retry-After": "7"},
+ )
+ for clone in (pickle.loads(pickle.dumps(err)), copy.copy(err), copy.deepcopy(err)):
+ assert type(clone) is OpenWARateLimitError
+ assert str(clone) == str(err)
+ assert (clone.status, clone.body, clone.error_kind, clone.code) == (429, err.body, "Too Many Requests", err.code)
+ assert clone.retry_after_seconds == 7
+ assert clone.headers == {"Retry-After": "7"}
+ timeout = pickle.loads(pickle.dumps(OpenWATimeoutError(30.0)))
+ assert str(timeout) == "Request timed out after 30.0s"
+ assert timeout.timeout == 30.0
+
def test_strips_trailing_slash(self):
backend = MockBackend().on("GET", "/api/sessions", body=[])
client = OpenWAClient(base_url="http://localhost:2785/", api_key="k", transport=backend.as_transport())