macss-modular-api-rest-client 0.4.7__tar.gz

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.
@@ -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,36 @@
1
+ # macss-modular-api-rest-client
2
+
3
+ Official MACSS outbound REST client for Python.
4
+
5
+ ## Quick start
6
+
7
+ ```python
8
+ from modular_api_rest_client import ServiceClientConfig, ServiceRequest, http_client
9
+
10
+ result = http_client(
11
+ config=ServiceClientConfig(
12
+ service_id="users",
13
+ base_url="https://api.example.test",
14
+ redacted_summary="users@example",
15
+ default_headers={"accept": "application/json"},
16
+ ),
17
+ request=ServiceRequest(
18
+ operation_id="users.list",
19
+ method="GET",
20
+ path="/users",
21
+ ),
22
+ )
23
+
24
+ if result.is_success:
25
+ print(result.value.data)
26
+ else:
27
+ print(result.failure.message)
28
+ ```
29
+
30
+ ## Current slice
31
+
32
+ - normalized `ServiceResult[T]` and `ServiceFailure`
33
+ - persistent `HttpServiceClient`
34
+ - one-shot `http_client()` helper
35
+ - explicit request metadata via `ServiceRequest`
36
+ - JSON-first response decoding and HTTP metadata preservation
@@ -0,0 +1,46 @@
1
+ [build-system]
2
+ requires = ["setuptools>=68", "wheel"]
3
+ build-backend = "setuptools.build_meta"
4
+
5
+ [project]
6
+ name = "macss-modular-api-rest-client"
7
+ version = "0.4.7"
8
+ description = "Official MACSS outbound REST client for Python."
9
+ readme = "README.md"
10
+ license = "MIT"
11
+ requires-python = ">=3.11"
12
+ authors = [{ name = "ccisne.dev" }]
13
+ keywords = ["macss", "http", "rest", "client"]
14
+ classifiers = [
15
+ "Development Status :: 4 - Beta",
16
+ "Intended Audience :: Developers",
17
+ "Programming Language :: Python :: 3",
18
+ "Programming Language :: Python :: 3.11",
19
+ "Programming Language :: Python :: 3.12",
20
+ "Programming Language :: Python :: 3.13",
21
+ "Topic :: Internet :: WWW/HTTP :: Dynamic Content",
22
+ "Typing :: Typed",
23
+ ]
24
+ dependencies = []
25
+
26
+ [project.optional-dependencies]
27
+ dev = [
28
+ "pytest>=8.0",
29
+ ]
30
+
31
+ [project.urls]
32
+ Homepage = "https://github.com/macss-dev/modular_api"
33
+ Repository = "https://github.com/macss-dev/modular_api/tree/main/code/py/modular_api_rest_client"
34
+ Issues = "https://github.com/macss-dev/modular_api/issues"
35
+ Documentation = "https://github.com/macss-dev/modular_api/tree/main/code/py/modular_api_rest_client#readme"
36
+
37
+ [tool.setuptools.packages.find]
38
+ where = ["src"]
39
+
40
+ [tool.pytest.ini_options]
41
+ testpaths = ["tests"]
42
+ pythonpath = ["src"]
43
+
44
+ [tool.pyright]
45
+ pythonVersion = "3.11"
46
+ typeCheckingMode = "strict"
@@ -0,0 +1,4 @@
1
+ [egg_info]
2
+ tag_build =
3
+ tag_date = 0
4
+
@@ -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,10 @@
1
+ README.md
2
+ pyproject.toml
3
+ src/macss_modular_api_rest_client.egg-info/PKG-INFO
4
+ src/macss_modular_api_rest_client.egg-info/SOURCES.txt
5
+ src/macss_modular_api_rest_client.egg-info/dependency_links.txt
6
+ src/macss_modular_api_rest_client.egg-info/requires.txt
7
+ src/macss_modular_api_rest_client.egg-info/top_level.txt
8
+ src/modular_api_rest_client/__init__.py
9
+ src/modular_api_rest_client/client.py
10
+ tests/test_http_client.py
@@ -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
@@ -0,0 +1,262 @@
1
+ from __future__ import annotations
2
+
3
+ import json
4
+ import threading
5
+ import time
6
+ import urllib.parse
7
+ from dataclasses import dataclass
8
+ from http.server import BaseHTTPRequestHandler, ThreadingHTTPServer
9
+
10
+ from modular_api_rest_client import (
11
+ HttpServiceClient,
12
+ ServiceClientConfig,
13
+ ServiceFailureCategory,
14
+ ServiceRequest,
15
+ http_client,
16
+ )
17
+
18
+
19
+ @dataclass(slots=True)
20
+ class _ServerHandle:
21
+ base_url: str
22
+ server: ThreadingHTTPServer
23
+ thread: threading.Thread
24
+
25
+ def close(self) -> None:
26
+ self.server.shutdown()
27
+ self.server.server_close()
28
+ self.thread.join(timeout=2)
29
+
30
+
31
+ def test_http_client_sends_a_get_request_decodes_json_and_preserves_metadata() -> None:
32
+ def handler(request: BaseHTTPRequestHandler) -> None:
33
+ parsed = urllib.parse.urlparse(request.path)
34
+ query = urllib.parse.parse_qs(parsed.query)
35
+
36
+ assert request.command == "GET"
37
+ assert parsed.path == "/users"
38
+ assert query["name"] == ["ana"]
39
+ assert request.headers["x-default"] == "package"
40
+ assert request.headers["x-request"] == "test"
41
+
42
+ request.send_response(200)
43
+ request.send_header("Content-Type", "application/json")
44
+ request.send_header("X-Request-Id", "req-123")
45
+ request.end_headers()
46
+ request.wfile.write(json.dumps({"ok": True, "name": "Ana"}).encode("utf-8"))
47
+
48
+ server = _start_server(handler)
49
+ try:
50
+ result = http_client(
51
+ config=ServiceClientConfig(
52
+ service_id="users",
53
+ base_url=server.base_url,
54
+ redacted_summary="users@local",
55
+ default_headers={"x-default": "package"},
56
+ ),
57
+ request=ServiceRequest(
58
+ operation_id="get-users",
59
+ method="GET",
60
+ path="/users",
61
+ query={"name": "ana"},
62
+ headers={"x-request": "test"},
63
+ ),
64
+ decoder=lambda value: dict(value),
65
+ )
66
+
67
+ assert result.is_success is True
68
+ assert result.value.data["ok"] is True
69
+ assert result.value.data["name"] == "Ana"
70
+ assert result.value.metadata.status_code == 200
71
+ assert result.value.metadata.transport_id == "http"
72
+ assert result.value.metadata.request_id == "req-123"
73
+ assert result.value.metadata.headers["x-request-id"] == "req-123"
74
+ finally:
75
+ server.close()
76
+
77
+
78
+ def test_http_client_returns_a_decode_failure_for_invalid_json_responses() -> None:
79
+ def handler(request: BaseHTTPRequestHandler) -> None:
80
+ request.send_response(200)
81
+ request.send_header("Content-Type", "application/json")
82
+ request.end_headers()
83
+ request.wfile.write(b"{broken-json")
84
+
85
+ server = _start_server(handler)
86
+ try:
87
+ result = http_client(
88
+ config=ServiceClientConfig(
89
+ service_id="broken",
90
+ base_url=server.base_url,
91
+ redacted_summary="broken@local",
92
+ ),
93
+ request=ServiceRequest(
94
+ operation_id="decode-failure",
95
+ method="GET",
96
+ path="/broken",
97
+ ),
98
+ )
99
+
100
+ assert result.is_failure is True
101
+ assert result.failure.category is ServiceFailureCategory.DECODE
102
+ assert result.failure.code == "invalid_json"
103
+ finally:
104
+ server.close()
105
+
106
+
107
+ def test_http_client_injects_auth_headers_from_the_auth_provider() -> None:
108
+ def handler(request: BaseHTTPRequestHandler) -> None:
109
+ assert request.headers["authorization"] == "Bearer token-123"
110
+
111
+ request.send_response(200)
112
+ request.send_header("Content-Type", "application/json")
113
+ request.end_headers()
114
+ request.wfile.write(json.dumps({"ok": True}).encode("utf-8"))
115
+
116
+ server = _start_server(handler)
117
+ try:
118
+ result = http_client(
119
+ config=ServiceClientConfig(
120
+ service_id="users",
121
+ base_url=server.base_url,
122
+ redacted_summary="users@local",
123
+ auth_provider=lambda operation: {"authorization": "Bearer token-123"},
124
+ ),
125
+ request=ServiceRequest(
126
+ operation_id="auth-check",
127
+ method="GET",
128
+ path="/users",
129
+ ),
130
+ decoder=lambda value: dict(value),
131
+ )
132
+
133
+ assert result.is_success is True
134
+ assert result.value.data["ok"] is True
135
+ finally:
136
+ server.close()
137
+
138
+
139
+ def test_http_client_returns_a_timeout_failure_when_the_request_exceeds_the_configured_timeout() -> None:
140
+ def handler(request: BaseHTTPRequestHandler) -> None:
141
+ time.sleep(0.2)
142
+ request.send_response(200)
143
+ request.send_header("Content-Type", "application/json")
144
+ request.end_headers()
145
+ request.wfile.write(json.dumps({"late": True}).encode("utf-8"))
146
+
147
+ server = _start_server(handler)
148
+ try:
149
+ result = http_client(
150
+ config=ServiceClientConfig(
151
+ service_id="slow",
152
+ base_url=server.base_url,
153
+ redacted_summary="slow@local",
154
+ timeout=0.02,
155
+ ),
156
+ request=ServiceRequest(
157
+ operation_id="timeout-check",
158
+ method="GET",
159
+ path="/slow",
160
+ ),
161
+ )
162
+
163
+ assert result.is_failure is True
164
+ assert result.failure.category is ServiceFailureCategory.TIMEOUT
165
+ assert result.failure.code == "timeout"
166
+ assert result.failure.retryable is True
167
+ finally:
168
+ server.close()
169
+
170
+
171
+ def test_http_client_normalizes_auth_failures_for_non_2xx_http_responses() -> None:
172
+ def handler(request: BaseHTTPRequestHandler) -> None:
173
+ request.send_response(401)
174
+ request.end_headers()
175
+ request.wfile.write(b"missing token")
176
+
177
+ server = _start_server(handler)
178
+ try:
179
+ result = http_client(
180
+ config=ServiceClientConfig(
181
+ service_id="auth",
182
+ base_url=server.base_url,
183
+ redacted_summary="auth@local",
184
+ ),
185
+ request=ServiceRequest(
186
+ operation_id="unauthorized",
187
+ method="GET",
188
+ path="/auth",
189
+ ),
190
+ )
191
+
192
+ assert result.is_failure is True
193
+ assert result.failure.category is ServiceFailureCategory.AUTH
194
+ assert result.failure.code == "unauthorized"
195
+ assert result.failure.status_code == 401
196
+ assert result.failure.details == "missing token"
197
+ finally:
198
+ server.close()
199
+
200
+
201
+ def test_http_client_normalizes_rate_limit_failures_for_non_2xx_http_responses() -> None:
202
+ def handler(request: BaseHTTPRequestHandler) -> None:
203
+ request.send_response(429)
204
+ request.end_headers()
205
+ request.wfile.write(b"retry later")
206
+
207
+ server = _start_server(handler)
208
+ try:
209
+ result = http_client(
210
+ config=ServiceClientConfig(
211
+ service_id="rate-limit",
212
+ base_url=server.base_url,
213
+ redacted_summary="rate-limit@local",
214
+ ),
215
+ request=ServiceRequest(
216
+ operation_id="too-many",
217
+ method="GET",
218
+ path="/rate-limit",
219
+ ),
220
+ )
221
+
222
+ assert result.is_failure is True
223
+ assert result.failure.category is ServiceFailureCategory.RATE_LIMIT
224
+ assert result.failure.code == "rate_limit"
225
+ assert result.failure.retryable is True
226
+ assert result.failure.status_code == 429
227
+ finally:
228
+ server.close()
229
+
230
+
231
+ def test_http_service_client_describes_its_config_and_closes_cleanly() -> None:
232
+ client = HttpServiceClient(
233
+ ServiceClientConfig(
234
+ service_id="users",
235
+ base_url="https://example.test",
236
+ redacted_summary="users@example",
237
+ )
238
+ )
239
+
240
+ assert client.describe().service_id == "users"
241
+ assert client.describe().transport_id == "http"
242
+
243
+ closed = client.close()
244
+ assert closed.is_success is True
245
+
246
+
247
+ def _start_server(handler):
248
+ class _Handler(BaseHTTPRequestHandler):
249
+ def do_GET(self) -> None: # noqa: N802
250
+ handler(self)
251
+
252
+ def log_message(self, format: str, *args) -> None: # noqa: A003
253
+ return None
254
+
255
+ server = ThreadingHTTPServer(("127.0.0.1", 0), _Handler)
256
+ thread = threading.Thread(target=server.serve_forever, daemon=True)
257
+ thread.start()
258
+ return _ServerHandle(
259
+ base_url=f"http://127.0.0.1:{server.server_address[1]}",
260
+ server=server,
261
+ thread=thread,
262
+ )