macss-modular-api-rest-client 0.4.7__py3-none-any.whl
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- macss_modular_api_rest_client-0.4.7.dist-info/METADATA +60 -0
- macss_modular_api_rest_client-0.4.7.dist-info/RECORD +6 -0
- macss_modular_api_rest_client-0.4.7.dist-info/WHEEL +5 -0
- macss_modular_api_rest_client-0.4.7.dist-info/top_level.txt +1 -0
- modular_api_rest_client/__init__.py +33 -0
- modular_api_rest_client/client.py +424 -0
|
@@ -0,0 +1,60 @@
|
|
|
1
|
+
Metadata-Version: 2.4
|
|
2
|
+
Name: macss-modular-api-rest-client
|
|
3
|
+
Version: 0.4.7
|
|
4
|
+
Summary: Official MACSS outbound REST client for Python.
|
|
5
|
+
Author: ccisne.dev
|
|
6
|
+
License-Expression: MIT
|
|
7
|
+
Project-URL: Homepage, https://github.com/macss-dev/modular_api
|
|
8
|
+
Project-URL: Repository, https://github.com/macss-dev/modular_api/tree/main/code/py/modular_api_rest_client
|
|
9
|
+
Project-URL: Issues, https://github.com/macss-dev/modular_api/issues
|
|
10
|
+
Project-URL: Documentation, https://github.com/macss-dev/modular_api/tree/main/code/py/modular_api_rest_client#readme
|
|
11
|
+
Keywords: macss,http,rest,client
|
|
12
|
+
Classifier: Development Status :: 4 - Beta
|
|
13
|
+
Classifier: Intended Audience :: Developers
|
|
14
|
+
Classifier: Programming Language :: Python :: 3
|
|
15
|
+
Classifier: Programming Language :: Python :: 3.11
|
|
16
|
+
Classifier: Programming Language :: Python :: 3.12
|
|
17
|
+
Classifier: Programming Language :: Python :: 3.13
|
|
18
|
+
Classifier: Topic :: Internet :: WWW/HTTP :: Dynamic Content
|
|
19
|
+
Classifier: Typing :: Typed
|
|
20
|
+
Requires-Python: >=3.11
|
|
21
|
+
Description-Content-Type: text/markdown
|
|
22
|
+
Provides-Extra: dev
|
|
23
|
+
Requires-Dist: pytest>=8.0; extra == "dev"
|
|
24
|
+
|
|
25
|
+
# macss-modular-api-rest-client
|
|
26
|
+
|
|
27
|
+
Official MACSS outbound REST client for Python.
|
|
28
|
+
|
|
29
|
+
## Quick start
|
|
30
|
+
|
|
31
|
+
```python
|
|
32
|
+
from modular_api_rest_client import ServiceClientConfig, ServiceRequest, http_client
|
|
33
|
+
|
|
34
|
+
result = http_client(
|
|
35
|
+
config=ServiceClientConfig(
|
|
36
|
+
service_id="users",
|
|
37
|
+
base_url="https://api.example.test",
|
|
38
|
+
redacted_summary="users@example",
|
|
39
|
+
default_headers={"accept": "application/json"},
|
|
40
|
+
),
|
|
41
|
+
request=ServiceRequest(
|
|
42
|
+
operation_id="users.list",
|
|
43
|
+
method="GET",
|
|
44
|
+
path="/users",
|
|
45
|
+
),
|
|
46
|
+
)
|
|
47
|
+
|
|
48
|
+
if result.is_success:
|
|
49
|
+
print(result.value.data)
|
|
50
|
+
else:
|
|
51
|
+
print(result.failure.message)
|
|
52
|
+
```
|
|
53
|
+
|
|
54
|
+
## Current slice
|
|
55
|
+
|
|
56
|
+
- normalized `ServiceResult[T]` and `ServiceFailure`
|
|
57
|
+
- persistent `HttpServiceClient`
|
|
58
|
+
- one-shot `http_client()` helper
|
|
59
|
+
- explicit request metadata via `ServiceRequest`
|
|
60
|
+
- JSON-first response decoding and HTTP metadata preservation
|
|
@@ -0,0 +1,6 @@
|
|
|
1
|
+
modular_api_rest_client/__init__.py,sha256=woGVbw989rPpVzYJ9ZVYspzR1KDHF5Y3CTUPsLdAj30,655
|
|
2
|
+
modular_api_rest_client/client.py,sha256=gAjIRXL711naJ3Qn39V8bhND-AslU3ZYBiFlm3mg7Uk,14031
|
|
3
|
+
macss_modular_api_rest_client-0.4.7.dist-info/METADATA,sha256=R7TcuPnSITTn-XttUok3Oayg7VWbDF_nQDz7mnPfLy0,1899
|
|
4
|
+
macss_modular_api_rest_client-0.4.7.dist-info/WHEEL,sha256=aeYiig01lYGDzBgS8HxWXOg3uV61G9ijOsup-k9o1sk,91
|
|
5
|
+
macss_modular_api_rest_client-0.4.7.dist-info/top_level.txt,sha256=u8BcPcR38NdAaXMLyTj7SeCx-hvDenHhX8W-hIGG9LA,24
|
|
6
|
+
macss_modular_api_rest_client-0.4.7.dist-info/RECORD,,
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
modular_api_rest_client
|
|
@@ -0,0 +1,33 @@
|
|
|
1
|
+
"""Public package exports for modular_api_rest_client."""
|
|
2
|
+
|
|
3
|
+
from .client import (
|
|
4
|
+
HttpServiceClient,
|
|
5
|
+
ServiceClientConfig,
|
|
6
|
+
ServiceClientDescription,
|
|
7
|
+
ServiceFailure,
|
|
8
|
+
ServiceFailureCategory,
|
|
9
|
+
ServiceOperation,
|
|
10
|
+
ServiceRequest,
|
|
11
|
+
ServiceResponse,
|
|
12
|
+
ServiceResponseMetadata,
|
|
13
|
+
ServiceResult,
|
|
14
|
+
ServiceRetryPolicy,
|
|
15
|
+
ServiceTelemetryHooks,
|
|
16
|
+
http_client,
|
|
17
|
+
)
|
|
18
|
+
|
|
19
|
+
__all__ = [
|
|
20
|
+
"HttpServiceClient",
|
|
21
|
+
"ServiceClientConfig",
|
|
22
|
+
"ServiceClientDescription",
|
|
23
|
+
"ServiceFailure",
|
|
24
|
+
"ServiceFailureCategory",
|
|
25
|
+
"ServiceOperation",
|
|
26
|
+
"ServiceRequest",
|
|
27
|
+
"ServiceResponse",
|
|
28
|
+
"ServiceResponseMetadata",
|
|
29
|
+
"ServiceResult",
|
|
30
|
+
"ServiceRetryPolicy",
|
|
31
|
+
"ServiceTelemetryHooks",
|
|
32
|
+
"http_client",
|
|
33
|
+
]
|
|
@@ -0,0 +1,424 @@
|
|
|
1
|
+
from __future__ import annotations
|
|
2
|
+
|
|
3
|
+
import json
|
|
4
|
+
import socket
|
|
5
|
+
import time
|
|
6
|
+
import urllib.error
|
|
7
|
+
import urllib.parse
|
|
8
|
+
import urllib.request
|
|
9
|
+
from dataclasses import dataclass, field
|
|
10
|
+
from enum import Enum
|
|
11
|
+
from typing import Any, Callable, Generic, Mapping, TypeVar, cast
|
|
12
|
+
|
|
13
|
+
T = TypeVar("T")
|
|
14
|
+
_MISSING = object()
|
|
15
|
+
|
|
16
|
+
ServiceDecoder = Callable[[object | None], T]
|
|
17
|
+
ServiceAuthProvider = Callable[["ServiceOperation"], Mapping[str, str]]
|
|
18
|
+
|
|
19
|
+
|
|
20
|
+
@dataclass(frozen=True, slots=True)
|
|
21
|
+
class ServiceRetryPolicy:
|
|
22
|
+
max_attempts: int = 1
|
|
23
|
+
|
|
24
|
+
|
|
25
|
+
@dataclass(frozen=True, slots=True)
|
|
26
|
+
class ServiceTelemetryHooks:
|
|
27
|
+
on_started: Callable[["ServiceOperation"], None] | None = None
|
|
28
|
+
on_completed: Callable[["ServiceOperation", "ServiceResult[object]"], None] | None = None
|
|
29
|
+
|
|
30
|
+
|
|
31
|
+
@dataclass(frozen=True, slots=True)
|
|
32
|
+
class ServiceClientConfig:
|
|
33
|
+
service_id: str
|
|
34
|
+
base_url: str
|
|
35
|
+
redacted_summary: str
|
|
36
|
+
default_headers: Mapping[str, str] = field(default_factory=dict)
|
|
37
|
+
auth_provider: ServiceAuthProvider | None = None
|
|
38
|
+
timeout: float | None = None
|
|
39
|
+
retry_policy: ServiceRetryPolicy | None = None
|
|
40
|
+
user_agent: str | None = None
|
|
41
|
+
telemetry_hooks: ServiceTelemetryHooks | None = None
|
|
42
|
+
|
|
43
|
+
|
|
44
|
+
@dataclass(frozen=True, slots=True)
|
|
45
|
+
class ServiceOperation:
|
|
46
|
+
transport_id: str
|
|
47
|
+
operation_id: str
|
|
48
|
+
headers: Mapping[str, str] = field(default_factory=dict)
|
|
49
|
+
method: str | None = None
|
|
50
|
+
path: str | None = None
|
|
51
|
+
query: Mapping[str, object] | None = None
|
|
52
|
+
body: object | None = None
|
|
53
|
+
document: str | None = None
|
|
54
|
+
variables: Mapping[str, object] | None = None
|
|
55
|
+
operation_name: str | None = None
|
|
56
|
+
|
|
57
|
+
|
|
58
|
+
class ServiceRequest(ServiceOperation):
|
|
59
|
+
def __init__(
|
|
60
|
+
self,
|
|
61
|
+
*,
|
|
62
|
+
operation_id: str,
|
|
63
|
+
method: str,
|
|
64
|
+
path: str,
|
|
65
|
+
headers: Mapping[str, str] | None = None,
|
|
66
|
+
query: Mapping[str, object] | None = None,
|
|
67
|
+
body: object | None = None,
|
|
68
|
+
) -> None:
|
|
69
|
+
super().__init__(
|
|
70
|
+
transport_id="http",
|
|
71
|
+
operation_id=operation_id,
|
|
72
|
+
headers={} if headers is None else dict(headers),
|
|
73
|
+
method=method,
|
|
74
|
+
path=path,
|
|
75
|
+
query=query,
|
|
76
|
+
body=body,
|
|
77
|
+
)
|
|
78
|
+
|
|
79
|
+
|
|
80
|
+
@dataclass(frozen=True, slots=True)
|
|
81
|
+
class ServiceResponseMetadata:
|
|
82
|
+
status_code: int
|
|
83
|
+
headers: Mapping[str, str]
|
|
84
|
+
transport_id: str
|
|
85
|
+
duration: float
|
|
86
|
+
request_id: str | None = None
|
|
87
|
+
|
|
88
|
+
|
|
89
|
+
@dataclass(frozen=True, slots=True)
|
|
90
|
+
class ServiceResponse(Generic[T]):
|
|
91
|
+
data: T
|
|
92
|
+
metadata: ServiceResponseMetadata
|
|
93
|
+
|
|
94
|
+
|
|
95
|
+
class ServiceFailureCategory(str, Enum):
|
|
96
|
+
TRANSPORT = "transport"
|
|
97
|
+
TIMEOUT = "timeout"
|
|
98
|
+
AUTH = "auth"
|
|
99
|
+
RATE_LIMIT = "rate_limit"
|
|
100
|
+
PROTOCOL = "protocol"
|
|
101
|
+
DECODE = "decode"
|
|
102
|
+
GRAPHQL = "graphql"
|
|
103
|
+
UNEXPECTED = "unexpected"
|
|
104
|
+
|
|
105
|
+
|
|
106
|
+
@dataclass(frozen=True, slots=True)
|
|
107
|
+
class ServiceFailure:
|
|
108
|
+
category: ServiceFailureCategory
|
|
109
|
+
code: str
|
|
110
|
+
message: str
|
|
111
|
+
retryable: bool
|
|
112
|
+
status_code: int | None = None
|
|
113
|
+
transport_id: str | None = None
|
|
114
|
+
details: object | None = None
|
|
115
|
+
cause_summary: str | None = None
|
|
116
|
+
|
|
117
|
+
|
|
118
|
+
class ServiceResult(Generic[T]):
|
|
119
|
+
def __init__(
|
|
120
|
+
self,
|
|
121
|
+
value: object = _MISSING,
|
|
122
|
+
failure: ServiceFailure | None = None,
|
|
123
|
+
) -> None:
|
|
124
|
+
self._value = value
|
|
125
|
+
self._failure = failure
|
|
126
|
+
|
|
127
|
+
@classmethod
|
|
128
|
+
def success(cls, value: T) -> ServiceResult[T]:
|
|
129
|
+
return cls(value=value)
|
|
130
|
+
|
|
131
|
+
@classmethod
|
|
132
|
+
def from_failure(cls, failure: ServiceFailure) -> ServiceResult[T]:
|
|
133
|
+
return cls(failure=failure)
|
|
134
|
+
|
|
135
|
+
@property
|
|
136
|
+
def is_success(self) -> bool:
|
|
137
|
+
return self._failure is None
|
|
138
|
+
|
|
139
|
+
@property
|
|
140
|
+
def is_failure(self) -> bool:
|
|
141
|
+
return self._failure is not None
|
|
142
|
+
|
|
143
|
+
@property
|
|
144
|
+
def value(self) -> T:
|
|
145
|
+
if self._failure is not None or self._value is _MISSING:
|
|
146
|
+
raise RuntimeError("ServiceResult does not contain a success value.")
|
|
147
|
+
return cast(T, self._value)
|
|
148
|
+
|
|
149
|
+
@property
|
|
150
|
+
def failure(self) -> ServiceFailure:
|
|
151
|
+
if self._failure is None:
|
|
152
|
+
raise RuntimeError("ServiceResult does not contain a failure value.")
|
|
153
|
+
return self._failure
|
|
154
|
+
|
|
155
|
+
|
|
156
|
+
@dataclass(frozen=True, slots=True)
|
|
157
|
+
class ServiceClientDescription:
|
|
158
|
+
service_id: str
|
|
159
|
+
transport_id: str
|
|
160
|
+
base_url: str
|
|
161
|
+
redacted_summary: str
|
|
162
|
+
|
|
163
|
+
|
|
164
|
+
class HttpServiceClient:
|
|
165
|
+
def __init__(self, config: ServiceClientConfig) -> None:
|
|
166
|
+
self._config = config
|
|
167
|
+
self._opener = urllib.request.build_opener()
|
|
168
|
+
self._closed = False
|
|
169
|
+
|
|
170
|
+
def describe(self) -> ServiceClientDescription:
|
|
171
|
+
return ServiceClientDescription(
|
|
172
|
+
service_id=self._config.service_id,
|
|
173
|
+
transport_id="http",
|
|
174
|
+
base_url=self._config.base_url,
|
|
175
|
+
redacted_summary=self._config.redacted_summary,
|
|
176
|
+
)
|
|
177
|
+
|
|
178
|
+
def execute(
|
|
179
|
+
self,
|
|
180
|
+
operation: ServiceOperation,
|
|
181
|
+
*,
|
|
182
|
+
decoder: ServiceDecoder[T] | None = None,
|
|
183
|
+
) -> ServiceResult[ServiceResponse[T]]:
|
|
184
|
+
if self._closed:
|
|
185
|
+
return ServiceResult.from_failure(
|
|
186
|
+
ServiceFailure(
|
|
187
|
+
category=ServiceFailureCategory.UNEXPECTED,
|
|
188
|
+
code="client_closed",
|
|
189
|
+
message="The HTTP service client is already closed.",
|
|
190
|
+
retryable=False,
|
|
191
|
+
transport_id="http",
|
|
192
|
+
)
|
|
193
|
+
)
|
|
194
|
+
|
|
195
|
+
if operation.transport_id != "http" or operation.method is None or operation.path is None:
|
|
196
|
+
return ServiceResult.from_failure(
|
|
197
|
+
ServiceFailure(
|
|
198
|
+
category=ServiceFailureCategory.PROTOCOL,
|
|
199
|
+
code="invalid_operation",
|
|
200
|
+
message="HTTP execution requires transportId, method, and path.",
|
|
201
|
+
retryable=False,
|
|
202
|
+
transport_id="http",
|
|
203
|
+
)
|
|
204
|
+
)
|
|
205
|
+
|
|
206
|
+
self._config.telemetry_hooks.on_started(operation) if self._config.telemetry_hooks and self._config.telemetry_hooks.on_started else None
|
|
207
|
+
|
|
208
|
+
started_at = time.monotonic()
|
|
209
|
+
result: ServiceResult[ServiceResponse[T]]
|
|
210
|
+
|
|
211
|
+
try:
|
|
212
|
+
headers = self._build_headers(operation)
|
|
213
|
+
request = urllib.request.Request(
|
|
214
|
+
_resolve_url(self._config.base_url, operation.path, operation.query),
|
|
215
|
+
data=_encode_body(operation.body, headers),
|
|
216
|
+
headers=headers,
|
|
217
|
+
method=operation.method,
|
|
218
|
+
)
|
|
219
|
+
|
|
220
|
+
with self._opener.open(request, timeout=self._config.timeout) as response:
|
|
221
|
+
status_code = getattr(response, "status", response.getcode())
|
|
222
|
+
response_text = response.read().decode("utf-8")
|
|
223
|
+
header_map = _headers_to_record(response.headers)
|
|
224
|
+
|
|
225
|
+
decoded = _decode_body(response_text, response.headers.get_content_type(), decoder)
|
|
226
|
+
if isinstance(decoded, ServiceFailure):
|
|
227
|
+
result = ServiceResult.from_failure(decoded)
|
|
228
|
+
else:
|
|
229
|
+
result = ServiceResult.success(
|
|
230
|
+
ServiceResponse(
|
|
231
|
+
data=decoded,
|
|
232
|
+
metadata=ServiceResponseMetadata(
|
|
233
|
+
status_code=status_code,
|
|
234
|
+
headers=header_map,
|
|
235
|
+
transport_id="http",
|
|
236
|
+
duration=time.monotonic() - started_at,
|
|
237
|
+
request_id=header_map.get("x-request-id"),
|
|
238
|
+
),
|
|
239
|
+
)
|
|
240
|
+
)
|
|
241
|
+
except urllib.error.HTTPError as error:
|
|
242
|
+
details = error.read().decode("utf-8")
|
|
243
|
+
result = ServiceResult.from_failure(
|
|
244
|
+
ServiceFailure(
|
|
245
|
+
category=_category_for_status(error.code),
|
|
246
|
+
code=_code_for_status(error.code),
|
|
247
|
+
message=details if details else f"HTTP request failed with status {error.code}.",
|
|
248
|
+
retryable=_is_retryable_status(error.code),
|
|
249
|
+
status_code=error.code,
|
|
250
|
+
transport_id="http",
|
|
251
|
+
details=details if details else None,
|
|
252
|
+
)
|
|
253
|
+
)
|
|
254
|
+
except urllib.error.URLError as error:
|
|
255
|
+
reason = error.reason
|
|
256
|
+
if isinstance(reason, (TimeoutError, socket.timeout)):
|
|
257
|
+
result = ServiceResult.from_failure(
|
|
258
|
+
ServiceFailure(
|
|
259
|
+
category=ServiceFailureCategory.TIMEOUT,
|
|
260
|
+
code="timeout",
|
|
261
|
+
message="The HTTP request timed out.",
|
|
262
|
+
retryable=True,
|
|
263
|
+
transport_id="http",
|
|
264
|
+
cause_summary=str(reason),
|
|
265
|
+
)
|
|
266
|
+
)
|
|
267
|
+
else:
|
|
268
|
+
result = ServiceResult.from_failure(
|
|
269
|
+
ServiceFailure(
|
|
270
|
+
category=ServiceFailureCategory.TRANSPORT,
|
|
271
|
+
code="transport_error",
|
|
272
|
+
message="The HTTP request failed to reach the remote service.",
|
|
273
|
+
retryable=True,
|
|
274
|
+
transport_id="http",
|
|
275
|
+
cause_summary=str(reason),
|
|
276
|
+
)
|
|
277
|
+
)
|
|
278
|
+
except (TimeoutError, socket.timeout) as error:
|
|
279
|
+
result = ServiceResult.from_failure(
|
|
280
|
+
ServiceFailure(
|
|
281
|
+
category=ServiceFailureCategory.TIMEOUT,
|
|
282
|
+
code="timeout",
|
|
283
|
+
message="The HTTP request timed out.",
|
|
284
|
+
retryable=True,
|
|
285
|
+
transport_id="http",
|
|
286
|
+
cause_summary=str(error),
|
|
287
|
+
)
|
|
288
|
+
)
|
|
289
|
+
except Exception as error: # noqa: BLE001
|
|
290
|
+
result = ServiceResult.from_failure(
|
|
291
|
+
ServiceFailure(
|
|
292
|
+
category=ServiceFailureCategory.UNEXPECTED,
|
|
293
|
+
code="unexpected_error",
|
|
294
|
+
message="The HTTP request failed unexpectedly.",
|
|
295
|
+
retryable=False,
|
|
296
|
+
transport_id="http",
|
|
297
|
+
cause_summary=str(error),
|
|
298
|
+
)
|
|
299
|
+
)
|
|
300
|
+
|
|
301
|
+
if self._config.telemetry_hooks and self._config.telemetry_hooks.on_completed:
|
|
302
|
+
self._config.telemetry_hooks.on_completed(operation, cast(ServiceResult[object], result))
|
|
303
|
+
return result
|
|
304
|
+
|
|
305
|
+
def close(self) -> ServiceResult[None]:
|
|
306
|
+
self._closed = True
|
|
307
|
+
return ServiceResult.success(None)
|
|
308
|
+
|
|
309
|
+
def _build_headers(self, operation: ServiceOperation) -> dict[str, str]:
|
|
310
|
+
headers = {
|
|
311
|
+
**dict(self._config.default_headers),
|
|
312
|
+
**dict(operation.headers),
|
|
313
|
+
}
|
|
314
|
+
|
|
315
|
+
if self._config.auth_provider is not None:
|
|
316
|
+
headers.update(dict(self._config.auth_provider(operation)))
|
|
317
|
+
|
|
318
|
+
if self._config.user_agent is not None and "User-Agent" not in headers and "user-agent" not in headers:
|
|
319
|
+
headers["User-Agent"] = self._config.user_agent
|
|
320
|
+
|
|
321
|
+
return headers
|
|
322
|
+
|
|
323
|
+
|
|
324
|
+
def http_client(
|
|
325
|
+
*,
|
|
326
|
+
config: ServiceClientConfig,
|
|
327
|
+
request: ServiceRequest,
|
|
328
|
+
decoder: ServiceDecoder[T] | None = None,
|
|
329
|
+
) -> ServiceResult[ServiceResponse[T]]:
|
|
330
|
+
client = HttpServiceClient(config)
|
|
331
|
+
try:
|
|
332
|
+
return client.execute(request, decoder=decoder)
|
|
333
|
+
finally:
|
|
334
|
+
client.close()
|
|
335
|
+
|
|
336
|
+
|
|
337
|
+
def _resolve_url(base_url: str, path: str, query: Mapping[str, object] | None) -> str:
|
|
338
|
+
base = urllib.parse.urlsplit(base_url)
|
|
339
|
+
path_segments = [segment for segment in base.path.split("/") if segment]
|
|
340
|
+
path_segments.extend(segment for segment in path.lstrip("/").split("/") if segment)
|
|
341
|
+
normalized_path = "/" + "/".join(path_segments)
|
|
342
|
+
|
|
343
|
+
query_string = urllib.parse.urlencode(
|
|
344
|
+
{
|
|
345
|
+
key: str(value)
|
|
346
|
+
for key, value in (query or {}).items()
|
|
347
|
+
if value is not None
|
|
348
|
+
}
|
|
349
|
+
)
|
|
350
|
+
|
|
351
|
+
return urllib.parse.urlunsplit(
|
|
352
|
+
(base.scheme, base.netloc, normalized_path, query_string, "")
|
|
353
|
+
)
|
|
354
|
+
|
|
355
|
+
|
|
356
|
+
def _encode_body(body: object | None, headers: dict[str, str]) -> bytes | None:
|
|
357
|
+
if body is None:
|
|
358
|
+
return None
|
|
359
|
+
|
|
360
|
+
if "Content-Type" not in headers and "content-type" not in headers:
|
|
361
|
+
headers["Content-Type"] = "application/json"
|
|
362
|
+
|
|
363
|
+
return json.dumps(body).encode("utf-8")
|
|
364
|
+
|
|
365
|
+
|
|
366
|
+
def _headers_to_record(headers: Any) -> dict[str, str]:
|
|
367
|
+
return {key.lower(): value for key, value in headers.items()}
|
|
368
|
+
|
|
369
|
+
|
|
370
|
+
def _decode_body(
|
|
371
|
+
body: str,
|
|
372
|
+
content_type: str | None,
|
|
373
|
+
decoder: ServiceDecoder[T] | None,
|
|
374
|
+
) -> T | ServiceFailure:
|
|
375
|
+
if body == "":
|
|
376
|
+
decoded: object | None = None
|
|
377
|
+
elif _looks_like_json(content_type, body):
|
|
378
|
+
try:
|
|
379
|
+
decoded = json.loads(body)
|
|
380
|
+
except json.JSONDecodeError as error:
|
|
381
|
+
return ServiceFailure(
|
|
382
|
+
category=ServiceFailureCategory.DECODE,
|
|
383
|
+
code="invalid_json",
|
|
384
|
+
message="The HTTP response body is not valid JSON.",
|
|
385
|
+
retryable=False,
|
|
386
|
+
transport_id="http",
|
|
387
|
+
cause_summary=str(error),
|
|
388
|
+
)
|
|
389
|
+
else:
|
|
390
|
+
decoded = body
|
|
391
|
+
|
|
392
|
+
return decoder(decoded) if decoder is not None else cast(T, decoded)
|
|
393
|
+
|
|
394
|
+
|
|
395
|
+
def _looks_like_json(content_type: str | None, body: str) -> bool:
|
|
396
|
+
if content_type is not None:
|
|
397
|
+
normalized = content_type.lower()
|
|
398
|
+
if normalized == "application/json" or normalized.endswith("+json"):
|
|
399
|
+
return True
|
|
400
|
+
|
|
401
|
+
trimmed = body.lstrip()
|
|
402
|
+
return trimmed.startswith("{") or trimmed.startswith("[")
|
|
403
|
+
|
|
404
|
+
|
|
405
|
+
def _category_for_status(status_code: int) -> ServiceFailureCategory:
|
|
406
|
+
if status_code in {401, 403}:
|
|
407
|
+
return ServiceFailureCategory.AUTH
|
|
408
|
+
if status_code == 429:
|
|
409
|
+
return ServiceFailureCategory.RATE_LIMIT
|
|
410
|
+
return ServiceFailureCategory.PROTOCOL
|
|
411
|
+
|
|
412
|
+
|
|
413
|
+
def _code_for_status(status_code: int) -> str:
|
|
414
|
+
if status_code == 401:
|
|
415
|
+
return "unauthorized"
|
|
416
|
+
if status_code == 403:
|
|
417
|
+
return "forbidden"
|
|
418
|
+
if status_code == 429:
|
|
419
|
+
return "rate_limit"
|
|
420
|
+
return f"http_{status_code}"
|
|
421
|
+
|
|
422
|
+
|
|
423
|
+
def _is_retryable_status(status_code: int) -> bool:
|
|
424
|
+
return status_code == 429 or status_code >= 500
|