macss-modular-api-rest-client 0.5.0__tar.gz → 0.7.0__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.
Files changed (18) hide show
  1. {macss_modular_api_rest_client-0.5.0 → macss_modular_api_rest_client-0.7.0}/PKG-INFO +4 -1
  2. macss_modular_api_rest_client-0.7.0/pyproject.toml +96 -0
  3. {macss_modular_api_rest_client-0.5.0 → macss_modular_api_rest_client-0.7.0}/src/macss_modular_api_rest_client.egg-info/PKG-INFO +4 -1
  4. {macss_modular_api_rest_client-0.5.0 → macss_modular_api_rest_client-0.7.0}/src/macss_modular_api_rest_client.egg-info/SOURCES.txt +5 -1
  5. macss_modular_api_rest_client-0.7.0/src/macss_modular_api_rest_client.egg-info/requires.txt +6 -0
  6. {macss_modular_api_rest_client-0.5.0 → macss_modular_api_rest_client-0.7.0}/src/modular_api_rest_client/client.py +49 -13
  7. macss_modular_api_rest_client-0.7.0/src/modular_api_rest_client/client_tracing.py +122 -0
  8. macss_modular_api_rest_client-0.7.0/src/modular_api_rest_client/py.typed +0 -0
  9. macss_modular_api_rest_client-0.7.0/tests/test_dependency_boundary.py +72 -0
  10. {macss_modular_api_rest_client-0.5.0 → macss_modular_api_rest_client-0.7.0}/tests/test_http_client.py +3 -2
  11. macss_modular_api_rest_client-0.7.0/tests/test_tracing.py +310 -0
  12. macss_modular_api_rest_client-0.5.0/pyproject.toml +0 -46
  13. macss_modular_api_rest_client-0.5.0/src/macss_modular_api_rest_client.egg-info/requires.txt +0 -3
  14. {macss_modular_api_rest_client-0.5.0 → macss_modular_api_rest_client-0.7.0}/README.md +0 -0
  15. {macss_modular_api_rest_client-0.5.0 → macss_modular_api_rest_client-0.7.0}/setup.cfg +0 -0
  16. {macss_modular_api_rest_client-0.5.0 → macss_modular_api_rest_client-0.7.0}/src/macss_modular_api_rest_client.egg-info/dependency_links.txt +0 -0
  17. {macss_modular_api_rest_client-0.5.0 → macss_modular_api_rest_client-0.7.0}/src/macss_modular_api_rest_client.egg-info/top_level.txt +0 -0
  18. {macss_modular_api_rest_client-0.5.0 → macss_modular_api_rest_client-0.7.0}/src/modular_api_rest_client/__init__.py +0 -0
@@ -1,6 +1,6 @@
1
1
  Metadata-Version: 2.4
2
2
  Name: macss-modular-api-rest-client
3
- Version: 0.5.0
3
+ Version: 0.7.0
4
4
  Summary: Official MACSS outbound REST client for Python.
5
5
  Author: ccisne.dev
6
6
  License-Expression: MIT
@@ -19,7 +19,10 @@ Classifier: Topic :: Internet :: WWW/HTTP :: Dynamic Content
19
19
  Classifier: Typing :: Typed
20
20
  Requires-Python: >=3.11
21
21
  Description-Content-Type: text/markdown
22
+ Requires-Dist: opentelemetry-api<2,>=1.44
22
23
  Provides-Extra: dev
24
+ Requires-Dist: opentelemetry-sdk<2,>=1.44; extra == "dev"
25
+ Requires-Dist: pyright>=1.1.400; extra == "dev"
23
26
  Requires-Dist: pytest>=8.0; extra == "dev"
24
27
 
25
28
  # macss-modular-api-rest-client
@@ -0,0 +1,96 @@
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.7.0"
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
+ # OpenTelemetry API only — never the SDK, an exporter, grpcio or protobuf. Declared
26
+ # directly rather than inherited, because this package does not depend on
27
+ # macss-modular-api (runbook D21). The API is no-op without an SDK.
28
+ "opentelemetry-api>=1.44,<2",
29
+ ]
30
+
31
+ [project.optional-dependencies]
32
+ dev = [
33
+ # `tests/test_tracing.py` imports `opentelemetry.sdk.trace`: the API alone is no-op, so asserting
34
+ # that spans are emitted needs an SDK. A test dependency, not a runtime one — the published package
35
+ # still declares only the API (ADR-0005 A1/A2). `modular_api_postgres` already declared this; this
36
+ # package did not, which is why its publish job failed with `No module named 'opentelemetry.sdk'`
37
+ # once the workflow started installing what each package declares.
38
+ "opentelemetry-sdk>=1.44,<2",
39
+ # Configured below at `typeCheckingMode = "strict"`. Declared here because a checker the
40
+ # repo configures and never installs is a checker that has never run.
41
+ "pyright>=1.1.400",
42
+ "pytest>=8.0",
43
+ ]
44
+
45
+ [project.urls]
46
+ Homepage = "https://github.com/macss-dev/modular_api"
47
+ Repository = "https://github.com/macss-dev/modular_api/tree/main/code/py/modular_api_rest_client"
48
+ Issues = "https://github.com/macss-dev/modular_api/issues"
49
+ Documentation = "https://github.com/macss-dev/modular_api/tree/main/code/py/modular_api_rest_client#readme"
50
+
51
+ [tool.setuptools.packages.find]
52
+ where = ["src"]
53
+
54
+ [tool.pytest.ini_options]
55
+ testpaths = ["tests"]
56
+ pythonpath = ["src"]
57
+
58
+ [tool.pyright]
59
+ pythonVersion = "3.11"
60
+ # `src/` is checked at full strict, because it is what a consumer's own type checker sees: these
61
+ # packages ship `py.typed`, so every annotation here becomes part of the public contract.
62
+ typeCheckingMode = "strict"
63
+
64
+ # `tests/` is strict too, minus the family that means "annotate this expression". Test code binds
65
+ # only this repo, and most of those diagnostics come from incomplete third-party stubs — annotating
66
+ # around them adds noise to a test without making anything more correct. Everything that can indicate
67
+ # a real defect stays on.
68
+ [[tool.pyright.executionEnvironments]]
69
+ root = "tests"
70
+ reportUnknownMemberType = false
71
+ reportUnknownArgumentType = false
72
+ reportUnknownVariableType = false
73
+ reportUnknownParameterType = false
74
+ reportUnknownLambdaType = false
75
+ reportMissingParameterType = false
76
+ reportMissingTypeArgument = false
77
+ # A pytest fixture is called by name through collection, never by a reference the checker can see, so
78
+ # `reportUnusedFunction` reports every `autouse` fixture in this tree. That is the tool not modelling
79
+ # pytest, not dead code. `reportUnusedImport` and `reportUnusedVariable` stay on — those do find dead
80
+ # code, and they did.
81
+ reportUnusedFunction = false
82
+ reportUnusedClass = false
83
+ # Tests legitimately reach into internals to exercise them directly. In `src/` this rule found real
84
+ # coupling and it was fixed rather than silenced.
85
+ reportPrivateUsage = false
86
+ # `example/` is documentation a consumer copies, not a published typed surface — same relaxed family
87
+ # as `tests/`, and the same expectation that nothing which can indicate a real defect is silenced.
88
+ [[tool.pyright.executionEnvironments]]
89
+ root = "example"
90
+ reportUnknownMemberType = false
91
+ reportUnknownArgumentType = false
92
+ reportUnknownVariableType = false
93
+ reportUnknownParameterType = false
94
+ reportUnknownLambdaType = false
95
+ reportMissingParameterType = false
96
+ reportMissingTypeArgument = false
@@ -1,6 +1,6 @@
1
1
  Metadata-Version: 2.4
2
2
  Name: macss-modular-api-rest-client
3
- Version: 0.5.0
3
+ Version: 0.7.0
4
4
  Summary: Official MACSS outbound REST client for Python.
5
5
  Author: ccisne.dev
6
6
  License-Expression: MIT
@@ -19,7 +19,10 @@ Classifier: Topic :: Internet :: WWW/HTTP :: Dynamic Content
19
19
  Classifier: Typing :: Typed
20
20
  Requires-Python: >=3.11
21
21
  Description-Content-Type: text/markdown
22
+ Requires-Dist: opentelemetry-api<2,>=1.44
22
23
  Provides-Extra: dev
24
+ Requires-Dist: opentelemetry-sdk<2,>=1.44; extra == "dev"
25
+ Requires-Dist: pyright>=1.1.400; extra == "dev"
23
26
  Requires-Dist: pytest>=8.0; extra == "dev"
24
27
 
25
28
  # macss-modular-api-rest-client
@@ -7,4 +7,8 @@ src/macss_modular_api_rest_client.egg-info/requires.txt
7
7
  src/macss_modular_api_rest_client.egg-info/top_level.txt
8
8
  src/modular_api_rest_client/__init__.py
9
9
  src/modular_api_rest_client/client.py
10
- tests/test_http_client.py
10
+ src/modular_api_rest_client/client_tracing.py
11
+ src/modular_api_rest_client/py.typed
12
+ tests/test_dependency_boundary.py
13
+ tests/test_http_client.py
14
+ tests/test_tracing.py
@@ -0,0 +1,6 @@
1
+ opentelemetry-api<2,>=1.44
2
+
3
+ [dev]
4
+ opentelemetry-sdk<2,>=1.44
5
+ pyright>=1.1.400
6
+ pytest>=8.0
@@ -10,6 +10,11 @@ from dataclasses import dataclass, field
10
10
  from enum import Enum
11
11
  from typing import Any, Callable, Generic, Mapping, TypeVar, cast
12
12
 
13
+ from modular_api_rest_client.client_tracing import (
14
+ REQUEST_ID_HEADER,
15
+ ClientCallTracing,
16
+ )
17
+
13
18
  T = TypeVar("T")
14
19
  _MISSING = object()
15
20
 
@@ -33,7 +38,7 @@ class ServiceClientConfig:
33
38
  service_id: str
34
39
  base_url: str
35
40
  redacted_summary: str
36
- default_headers: Mapping[str, str] = field(default_factory=dict)
41
+ default_headers: Mapping[str, str] = field(default_factory=dict[str, str])
37
42
  auth_provider: ServiceAuthProvider | None = None
38
43
  timeout: float | None = None
39
44
  retry_policy: ServiceRetryPolicy | None = None
@@ -45,7 +50,7 @@ class ServiceClientConfig:
45
50
  class ServiceOperation:
46
51
  transport_id: str
47
52
  operation_id: str
48
- headers: Mapping[str, str] = field(default_factory=dict)
53
+ headers: Mapping[str, str] = field(default_factory=dict[str, str])
49
54
  method: str | None = None
50
55
  path: str | None = None
51
56
  query: Mapping[str, object] | None = None
@@ -182,7 +187,7 @@ class HttpServiceClient:
182
187
  decoder: ServiceDecoder[T] | None = None,
183
188
  ) -> ServiceResult[ServiceResponse[T]]:
184
189
  if self._closed:
185
- return ServiceResult.from_failure(
190
+ return ServiceResult[ServiceResponse[T]].from_failure(
186
191
  ServiceFailure(
187
192
  category=ServiceFailureCategory.UNEXPECTED,
188
193
  code="client_closed",
@@ -193,7 +198,7 @@ class HttpServiceClient:
193
198
  )
194
199
 
195
200
  if operation.transport_id != "http" or operation.method is None or operation.path is None:
196
- return ServiceResult.from_failure(
201
+ return ServiceResult[ServiceResponse[T]].from_failure(
197
202
  ServiceFailure(
198
203
  category=ServiceFailureCategory.PROTOCOL,
199
204
  code="invalid_operation",
@@ -208,10 +213,24 @@ class HttpServiceClient:
208
213
  started_at = time.monotonic()
209
214
  result: ServiceResult[ServiceResponse[T]]
210
215
 
216
+ tracing: ClientCallTracing | None = None
211
217
  try:
212
218
  headers = self._build_headers(operation)
219
+ url = _resolve_url(self._config.base_url, operation.path, operation.query)
220
+
221
+ # Client span plus trace-context and request-id injection. Zero configuration:
222
+ # the parent is the ambient server span carried by contextvars, and the tracer is
223
+ # the global provider — both no-ops when no OpenTelemetry SDK is configured.
224
+ tracing = ClientCallTracing.start(
225
+ method=operation.method,
226
+ operation_id=operation.operation_id,
227
+ url=url,
228
+ headers=headers,
229
+ inbound_request_id=headers.get(REQUEST_ID_HEADER),
230
+ )
231
+
213
232
  request = urllib.request.Request(
214
- _resolve_url(self._config.base_url, operation.path, operation.query),
233
+ url,
215
234
  data=_encode_body(operation.body, headers),
216
235
  headers=headers,
217
236
  method=operation.method,
@@ -219,14 +238,17 @@ class HttpServiceClient:
219
238
 
220
239
  with self._opener.open(request, timeout=self._config.timeout) as response:
221
240
  status_code = getattr(response, "status", response.getcode())
241
+ # Closed as soon as the response is in hand, so the span measures the call
242
+ # rather than the decoding that follows it.
243
+ tracing.complete(status_code=status_code)
222
244
  response_text = response.read().decode("utf-8")
223
245
  header_map = _headers_to_record(response.headers)
224
246
 
225
247
  decoded = _decode_body(response_text, response.headers.get_content_type(), decoder)
226
248
  if isinstance(decoded, ServiceFailure):
227
- result = ServiceResult.from_failure(decoded)
249
+ result = ServiceResult[ServiceResponse[T]].from_failure(decoded)
228
250
  else:
229
- result = ServiceResult.success(
251
+ result = ServiceResult[ServiceResponse[T]].success(
230
252
  ServiceResponse(
231
253
  data=decoded,
232
254
  metadata=ServiceResponseMetadata(
@@ -239,8 +261,10 @@ class HttpServiceClient:
239
261
  )
240
262
  )
241
263
  except urllib.error.HTTPError as error:
264
+ if tracing is not None:
265
+ tracing.complete(status_code=error.code)
242
266
  details = error.read().decode("utf-8")
243
- result = ServiceResult.from_failure(
267
+ result = ServiceResult[ServiceResponse[T]].from_failure(
244
268
  ServiceFailure(
245
269
  category=_category_for_status(error.code),
246
270
  code=_code_for_status(error.code),
@@ -252,9 +276,13 @@ class HttpServiceClient:
252
276
  )
253
277
  )
254
278
  except urllib.error.URLError as error:
279
+ # No response at all: a timeout, a refused connection, a DNS failure. The case
280
+ # that matters most for the socia burst, and unambiguously an error.
281
+ if tracing is not None:
282
+ tracing.complete(error=error)
255
283
  reason = error.reason
256
284
  if isinstance(reason, (TimeoutError, socket.timeout)):
257
- result = ServiceResult.from_failure(
285
+ result = ServiceResult[ServiceResponse[T]].from_failure(
258
286
  ServiceFailure(
259
287
  category=ServiceFailureCategory.TIMEOUT,
260
288
  code="timeout",
@@ -265,7 +293,7 @@ class HttpServiceClient:
265
293
  )
266
294
  )
267
295
  else:
268
- result = ServiceResult.from_failure(
296
+ result = ServiceResult[ServiceResponse[T]].from_failure(
269
297
  ServiceFailure(
270
298
  category=ServiceFailureCategory.TRANSPORT,
271
299
  code="transport_error",
@@ -276,7 +304,11 @@ class HttpServiceClient:
276
304
  )
277
305
  )
278
306
  except (TimeoutError, socket.timeout) as error:
279
- result = ServiceResult.from_failure(
307
+ # No response at all: a timeout, a refused connection, a DNS failure. The case
308
+ # that matters most for the socia burst, and unambiguously an error.
309
+ if tracing is not None:
310
+ tracing.complete(error=error)
311
+ result = ServiceResult[ServiceResponse[T]].from_failure(
280
312
  ServiceFailure(
281
313
  category=ServiceFailureCategory.TIMEOUT,
282
314
  code="timeout",
@@ -287,7 +319,11 @@ class HttpServiceClient:
287
319
  )
288
320
  )
289
321
  except Exception as error: # noqa: BLE001
290
- result = ServiceResult.from_failure(
322
+ # No response at all: a timeout, a refused connection, a DNS failure. The case
323
+ # that matters most for the socia burst, and unambiguously an error.
324
+ if tracing is not None:
325
+ tracing.complete(error=error)
326
+ result = ServiceResult[ServiceResponse[T]].from_failure(
291
327
  ServiceFailure(
292
328
  category=ServiceFailureCategory.UNEXPECTED,
293
329
  code="unexpected_error",
@@ -304,7 +340,7 @@ class HttpServiceClient:
304
340
 
305
341
  def close(self) -> ServiceResult[None]:
306
342
  self._closed = True
307
- return ServiceResult.success(None)
343
+ return ServiceResult[None].success(None)
308
344
 
309
345
  def _build_headers(self, operation: ServiceOperation) -> dict[str, str]:
310
346
  headers = {
@@ -0,0 +1,122 @@
1
+ """Instrumentation for one outbound call.
2
+
3
+ **Zero configuration on purpose.** The parent comes from the ambient context — the server
4
+ span the host made active, which ``contextvars`` carry here without anything being threaded
5
+ through call signatures — and the tracer from the global provider. When no OpenTelemetry SDK
6
+ is configured both are no-ops, so a consumer who never enables tracing gets no spans, no
7
+ headers and no measurable cost. Nothing is threaded into ``ServiceClientConfig``.
8
+
9
+ **Injection goes through the global propagator**, never a propagator of our own. This package
10
+ does not depend on ``macss-modular-api`` (runbook D21), so it cannot reach the framework's
11
+ propagator — and per the OpenTelemetry API's own guidance it should not: instrumentation
12
+ libraries read the global and leave setting it to the SDK or the host. That also means
13
+ whatever chain the application configured is honoured here, including a Cloud Trace
14
+ propagator it appended, without this package knowing such a thing exists.
15
+
16
+ The Dart and TypeScript counterparts are ``lib/src/client_tracing.dart`` and
17
+ ``src/clientTracing.ts``.
18
+ """
19
+
20
+ from __future__ import annotations
21
+
22
+ from urllib.parse import urlparse
23
+
24
+ from opentelemetry import propagate, trace
25
+ from opentelemetry.trace import SpanKind, Status, StatusCode
26
+ from opentelemetry.util.types import AttributeValue
27
+
28
+ #: The header carrying a caller-supplied correlation id.
29
+ REQUEST_ID_HEADER = "x-request-id"
30
+
31
+
32
+ class ClientCallTracing:
33
+ """Handle for one instrumented outbound call. ``complete`` must be called once."""
34
+
35
+ __slots__ = ("_span",)
36
+
37
+ def __init__(self, span: trace.Span | None) -> None:
38
+ self._span = span
39
+
40
+ @classmethod
41
+ def start(
42
+ cls,
43
+ *,
44
+ method: str,
45
+ operation_id: str,
46
+ url: str,
47
+ headers: dict[str, str],
48
+ inbound_request_id: str | None = None,
49
+ ) -> ClientCallTracing:
50
+ """Start a client span and inject trace context plus the request id into ``headers``."""
51
+ # Forwarded whether or not tracing is on. Envoy's tracing documentation lists
52
+ # x-request-id propagation as an obligation separate from trace context, and it is the
53
+ # one correlation header nearly every stack implements — so it survives a hop into a
54
+ # service with no tracing at all (runbook D23). We forward, never invent: a chain with
55
+ # no request id keeps having none.
56
+ if inbound_request_id:
57
+ headers.setdefault(REQUEST_ID_HEADER, inbound_request_id)
58
+
59
+ parent_span = trace.get_current_span()
60
+
61
+ # No recording parent means tracing is off for this request. A non-recording span and
62
+ # a header nobody will read would be cost with no benefit.
63
+ if not parent_span.is_recording():
64
+ return cls(None)
65
+
66
+ target = urlparse(url)
67
+ # `AttributeValue`, not `object`: OpenTelemetry accepts only primitives and sequences of
68
+ # primitives, and silently drops an attribute whose value is anything else. Naming the type
69
+ # turns a dropped attribute — invisible at runtime, and exactly the kind of gap that makes an
70
+ # instrumentation look broken — into an error here.
71
+ attributes: dict[str, AttributeValue] = {"http.request.method": method}
72
+ if target.hostname:
73
+ # server.address plus url.path rather than the full URL, which can carry
74
+ # identifiers in its path or query.
75
+ attributes["server.address"] = target.hostname
76
+ if target.port is not None:
77
+ attributes["server.port"] = target.port
78
+ attributes["url.path"] = target.path
79
+
80
+ span = trace.get_tracer("modular_api_rest_client").start_span(
81
+ # Semantic convention for a client span: the method, qualified by what was called.
82
+ # The operation id is more useful than a bare method and safer than a full URL.
83
+ f"{method} {operation_id}",
84
+ kind=SpanKind.CLIENT,
85
+ attributes=attributes,
86
+ )
87
+
88
+ propagate.inject(headers, context=trace.set_span_in_context(span))
89
+
90
+ return cls(span)
91
+
92
+ def complete(
93
+ self,
94
+ *,
95
+ status_code: int | None = None,
96
+ error: BaseException | None = None,
97
+ ) -> None:
98
+ """End the span, recording the outcome.
99
+
100
+ ``status_code`` is ``None`` when the call never produced a response — a timeout, a DNS
101
+ failure, a refused connection. That is always an error; a status code is an error at
102
+ 4xx and above, because a client span's failure is the *call* failing rather than the
103
+ server disagreeing.
104
+ """
105
+ span = self._span
106
+ if span is None:
107
+ return
108
+
109
+ if status_code is not None:
110
+ span.set_attribute("http.response.status_code", status_code)
111
+
112
+ if error is not None:
113
+ span.record_exception(error)
114
+ span.set_status(Status(StatusCode.ERROR, "request failed"))
115
+ elif status_code is None:
116
+ span.set_status(Status(StatusCode.ERROR, "no response"))
117
+ elif status_code >= 400:
118
+ # Unlike a server span, where 4xx is the caller's mistake, a 4xx here means *our*
119
+ # outbound call failed. The distinction matters when reading a waterfall.
120
+ span.set_status(Status(StatusCode.ERROR, f"HTTP {status_code}"))
121
+
122
+ span.end()
@@ -0,0 +1,72 @@
1
+ """Guards the dependency boundary for a satellite package (runbook D21).
2
+
3
+ This package does **not** depend on ``macss-modular-api``, so it cannot inherit the
4
+ OpenTelemetry API transitively and must declare it itself. What it must never declare as a
5
+ runtime dependency is an OTel SDK, an exporter, grpcio or protobuf: those belong to the
6
+ application (ADR-0005 A2).
7
+
8
+ ``optional-dependencies`` may carry them, and does — the in-memory exporter is needed to
9
+ observe instrumentation at all, since the API alone produces no-op spans (D22).
10
+ """
11
+
12
+ from __future__ import annotations
13
+
14
+ import re
15
+ import tomllib
16
+ from pathlib import Path
17
+
18
+ import pytest
19
+
20
+ _PYPROJECT = Path(__file__).resolve().parents[1] / "pyproject.toml"
21
+
22
+ _FORBIDDEN_PREFIXES = (
23
+ "opentelemetry-sdk",
24
+ "opentelemetry-exporter",
25
+ "grpcio",
26
+ "protobuf",
27
+ )
28
+
29
+
30
+ def _requirement_name(requirement: str) -> str:
31
+ return re.split(r"[<>=!~\[\s;]", requirement, maxsplit=1)[0].strip().lower()
32
+
33
+
34
+ @pytest.fixture(scope="module")
35
+ def runtime_dependencies() -> list[str]:
36
+ manifest = tomllib.loads(_PYPROJECT.read_text(encoding="utf-8"))
37
+ return list(manifest["project"]["dependencies"])
38
+
39
+
40
+ def test_declares_the_opentelemetry_api_directly(runtime_dependencies: list[str]) -> None:
41
+ names = {_requirement_name(r) for r in runtime_dependencies}
42
+
43
+ assert "opentelemetry-api" in names, (
44
+ "this package does not depend on macss-modular-api, so the API cannot arrive "
45
+ "transitively (D21)"
46
+ )
47
+
48
+
49
+ def test_declares_no_sdk_exporter_grpc_or_protobuf(
50
+ runtime_dependencies: list[str],
51
+ ) -> None:
52
+ offenders = [
53
+ r
54
+ for r in runtime_dependencies
55
+ if _requirement_name(r).startswith(_FORBIDDEN_PREFIXES)
56
+ ]
57
+
58
+ assert offenders == [], (
59
+ f"those belong to the application, not the framework (A2). Found: {offenders}"
60
+ )
61
+
62
+
63
+ def test_the_api_requirement_is_bounded(runtime_dependencies: list[str]) -> None:
64
+ requirement = next(
65
+ (r for r in runtime_dependencies if _requirement_name(r) == "opentelemetry-api"),
66
+ None,
67
+ )
68
+
69
+ assert requirement is not None, "opentelemetry-api is not declared at all (D21)"
70
+ assert re.search(r"<\s*\d", requirement), (
71
+ f"needs an upper bound so a future major cannot arrive silently. Found: {requirement!r}"
72
+ )
@@ -6,6 +6,7 @@ import time
6
6
  import urllib.parse
7
7
  from dataclasses import dataclass
8
8
  from http.server import BaseHTTPRequestHandler, ThreadingHTTPServer
9
+ from typing import Any, cast
9
10
 
10
11
  from modular_api_rest_client import (
11
12
  HttpServiceClient,
@@ -61,7 +62,7 @@ def test_http_client_sends_a_get_request_decodes_json_and_preserves_metadata() -
61
62
  query={"name": "ana"},
62
63
  headers={"x-request": "test"},
63
64
  ),
64
- decoder=lambda value: dict(value),
65
+ decoder=lambda value: dict(cast("dict[str, Any]", value)),
65
66
  )
66
67
 
67
68
  assert result.is_success is True
@@ -127,7 +128,7 @@ def test_http_client_injects_auth_headers_from_the_auth_provider() -> None:
127
128
  method="GET",
128
129
  path="/users",
129
130
  ),
130
- decoder=lambda value: dict(value),
131
+ decoder=lambda value: dict(cast("dict[str, Any]", value)),
131
132
  )
132
133
 
133
134
  assert result.is_success is True
@@ -0,0 +1,310 @@
1
+ """Python mirror of ``test/tracing_test.dart``.
2
+
3
+ **This is the stage that satisfies G7 for socia.** Its
4
+ ``POST /api/cuenta/get-cuenta-detalle`` performs no database work at all — it is an HTTP
5
+ proxy to an upstream ``impulsa`` service (runbook D17) — so the client span is what shows
6
+ whether those 8–20 second bursts are spent in the outbound call or before it.
7
+
8
+ The propagator is set here, in the test, standing in for whatever the host configures
9
+ globally. The package under test never sets it: it reads ``propagate.inject``, which is what
10
+ lets it stay free of any dependency on the framework (runbook D21).
11
+ """
12
+
13
+ from __future__ import annotations
14
+
15
+ import io
16
+ import json
17
+ import urllib.error
18
+ import urllib.request
19
+ from collections.abc import Iterator, Mapping
20
+ from email.message import Message
21
+ from typing import cast
22
+
23
+ import pytest
24
+ from opentelemetry import trace
25
+ from opentelemetry.propagate import set_global_textmap
26
+ from opentelemetry.sdk.trace import TracerProvider
27
+ from opentelemetry.sdk.trace.export import SimpleSpanProcessor
28
+ from opentelemetry.sdk.trace.export.in_memory_span_exporter import InMemorySpanExporter
29
+ from opentelemetry.sdk.trace import ReadableSpan
30
+ from opentelemetry.trace import SpanContext, SpanKind, StatusCode
31
+ from opentelemetry.util.types import AttributeValue
32
+ from opentelemetry.trace.propagation.tracecontext import TraceContextTextMapPropagator
33
+
34
+ from modular_api_rest_client.client import (
35
+ HttpServiceClient,
36
+ ServiceClientConfig,
37
+ ServiceRequest,
38
+ )
39
+ from modular_api_rest_client.client_tracing import REQUEST_ID_HEADER
40
+
41
+ _exporter = InMemorySpanExporter()
42
+ _provider = TracerProvider()
43
+ _provider.add_span_processor(SimpleSpanProcessor(_exporter))
44
+ trace.set_tracer_provider(_provider)
45
+ set_global_textmap(TraceContextTextMapPropagator())
46
+
47
+ _tracer = _provider.get_tracer("test-host")
48
+
49
+ #: Headers the client actually sent, captured by the fake opener.
50
+ _sent: dict[str, str] = {}
51
+
52
+
53
+ @pytest.fixture(autouse=True)
54
+ def _reset() -> Iterator[None]:
55
+ _exporter.clear()
56
+ _sent.clear()
57
+ yield
58
+
59
+
60
+ def _span_named(name: str) -> ReadableSpan | None:
61
+ for span in _exporter.get_finished_spans():
62
+ if span.name == name:
63
+ return span
64
+ return None
65
+
66
+
67
+ # The SDK types are honestly optional — a span may have no context, no attributes. A test that named a
68
+ # span and got nothing should say *that*, not fail with AttributeError on `None.trace_id` further down.
69
+ def _require_span(name: str) -> ReadableSpan:
70
+ span = _span_named(name)
71
+ assert span is not None, f"no span named {name!r} was exported"
72
+ return span
73
+
74
+
75
+ def _attributes(span: ReadableSpan) -> Mapping[str, AttributeValue]:
76
+ assert span.attributes is not None, f"span {span.name!r} carries no attributes"
77
+ return span.attributes
78
+
79
+
80
+ def _context(span: ReadableSpan) -> SpanContext:
81
+ assert span.context is not None, f"span {span.name!r} has no context"
82
+ return span.context
83
+
84
+
85
+ def _parent(span: ReadableSpan) -> SpanContext:
86
+ assert span.parent is not None, f"span {span.name!r} has no parent"
87
+ return span.parent
88
+
89
+
90
+ class _FakeResponse(io.BytesIO):
91
+ def __init__(self, status: int) -> None:
92
+ super().__init__(json.dumps({"ok": True}).encode())
93
+ self.status = status
94
+ self.headers = _FakeHeaders()
95
+
96
+ def getcode(self) -> int:
97
+ return self.status
98
+
99
+ def __enter__(self): # noqa: ANN204
100
+ return self
101
+
102
+ def __exit__(self, *_args: object) -> None:
103
+ return None
104
+
105
+
106
+ class _FakeHeaders:
107
+ """What the client reads off a response: the content type and the header pairs.
108
+
109
+ Not a `dict` subclass. It was one, with an `items()` that returned a list instead of a
110
+ `dict_items` — a narrower return type than the base class promises, which is exactly the override
111
+ a caller holding it as a `dict` would be broken by.
112
+ """
113
+
114
+ def get_content_type(self) -> str:
115
+ return "application/json"
116
+
117
+ def items(self) -> list[tuple[str, str]]:
118
+ return []
119
+
120
+
121
+ class _FakeOpener:
122
+ def __init__(self, status: int = 200, raises: BaseException | None = None) -> None:
123
+ self._status = status
124
+ self._raises = raises
125
+
126
+ def open(self, request: urllib.request.Request, timeout: float | None = None): # noqa: ANN201, ARG002
127
+ _sent.update({key.lower(): value for key, value in request.header_items()})
128
+ if self._raises is not None:
129
+ raise self._raises
130
+ return _FakeResponse(self._status)
131
+
132
+
133
+ def _client(
134
+ *,
135
+ status: int = 200,
136
+ default_headers: dict[str, str] | None = None,
137
+ raises: BaseException | None = None,
138
+ ) -> HttpServiceClient:
139
+ client = HttpServiceClient(
140
+ ServiceClientConfig(
141
+ service_id="impulsa",
142
+ base_url="https://impulsa.example/api",
143
+ redacted_summary="impulsa.example",
144
+ default_headers=default_headers or {},
145
+ )
146
+ )
147
+ # No injection seam exists for the opener, so the test reaches past the type. Recorded with a cast
148
+ # rather than left as a silent mismatch: the fake implements `open()` and nothing else of
149
+ # `OpenerDirector`, which is all the client calls.
150
+ client._opener = cast("urllib.request.OpenerDirector", _FakeOpener(status=status, raises=raises)) # noqa: SLF001
151
+ return client
152
+
153
+
154
+ def _call(client: HttpServiceClient, operation_id: str = "get-cuenta-detalle"): # noqa: ANN201
155
+ return client.execute(
156
+ ServiceRequest(
157
+ operation_id=operation_id,
158
+ method="POST",
159
+ path=operation_id,
160
+ body={"dni": "12345678"},
161
+ ),
162
+ decoder=lambda json_value: json_value,
163
+ )
164
+
165
+
166
+ def _within_server_span(body) -> None: # noqa: ANN001
167
+ server_span = _tracer.start_span(
168
+ "POST /api/cuenta/get-cuenta-detalle", kind=SpanKind.SERVER
169
+ )
170
+ with trace.use_span(server_span, end_on_exit=True):
171
+ body()
172
+
173
+
174
+ # --- with an active server span ---------------------------------------------
175
+
176
+
177
+ def test_emits_a_client_span_named_by_method_and_operation() -> None:
178
+ _within_server_span(lambda: _call(_client()))
179
+
180
+ assert _span_named("POST get-cuenta-detalle") is not None
181
+
182
+
183
+ def test_the_client_span_is_kind_client_and_a_child_of_the_server_span() -> None:
184
+ _within_server_span(lambda: _call(_client()))
185
+
186
+ server = _require_span("POST /api/cuenta/get-cuenta-detalle")
187
+ client = _require_span("POST get-cuenta-detalle")
188
+
189
+ assert client.kind is SpanKind.CLIENT
190
+ assert _context(client).trace_id == _context(server).trace_id
191
+ assert _parent(client).span_id == _context(server).span_id
192
+
193
+
194
+ def test_records_the_upstream_host_and_path_not_the_full_url() -> None:
195
+ # A full URL can carry identifiers in its path or query. server.address plus url.path is
196
+ # what the conventions ask for and what is safe to store.
197
+ _within_server_span(lambda: _call(_client()))
198
+
199
+ attributes = _attributes(_require_span("POST get-cuenta-detalle"))
200
+
201
+ assert attributes["server.address"] == "impulsa.example"
202
+ assert "get-cuenta-detalle" in str(attributes["url.path"])
203
+ assert attributes["http.request.method"] == "POST"
204
+
205
+
206
+ def test_injects_traceparent_derived_from_the_client_span() -> None:
207
+ # The header a downstream service would read. It names the CLIENT span, not the server
208
+ # span, so a downstream hop attaches to the call rather than to its parent.
209
+ _within_server_span(lambda: _call(_client()))
210
+
211
+ client = _require_span("POST get-cuenta-detalle")
212
+ traceparent = _sent.get("traceparent")
213
+
214
+ assert traceparent is not None
215
+ assert f"{_context(client).trace_id:032x}" in traceparent
216
+ assert f"{_context(client).span_id:016x}" in traceparent
217
+
218
+
219
+ def test_a_500_from_upstream_sets_the_client_span_to_error() -> None:
220
+ error = urllib.error.HTTPError(
221
+ "https://impulsa.example/api", 500, "boom", Message(), io.BytesIO(b"")
222
+ )
223
+ _within_server_span(lambda: _call(_client(raises=error)))
224
+
225
+ client = _require_span("POST get-cuenta-detalle")
226
+
227
+ assert client.status.status_code is StatusCode.ERROR
228
+ assert _attributes(client)["http.response.status_code"] == 500
229
+
230
+
231
+ def test_a_404_from_upstream_also_sets_error_unlike_a_server_span() -> None:
232
+ # On a server span a 4xx is the caller's mistake. Here it means OUR outbound call failed,
233
+ # which is a different thing and worth distinguishing in a waterfall.
234
+ error = urllib.error.HTTPError(
235
+ "https://impulsa.example/api", 404, "missing", Message(), io.BytesIO(b"")
236
+ )
237
+ _within_server_span(lambda: _call(_client(raises=error)))
238
+
239
+ assert _require_span("POST get-cuenta-detalle").status.status_code is StatusCode.ERROR
240
+
241
+
242
+ def test_a_transport_failure_ends_the_span_with_error_and_no_status_code() -> None:
243
+ # The case that matters for the socia investigation: a call that never returns.
244
+ _within_server_span(
245
+ lambda: _call(_client(raises=urllib.error.URLError("connection reset")))
246
+ )
247
+
248
+ client = _require_span("POST get-cuenta-detalle")
249
+
250
+ assert client.status.status_code is StatusCode.ERROR
251
+ assert "http.response.status_code" not in _attributes(client)
252
+
253
+
254
+ def test_the_span_is_ended_which_is_the_g7_measurement() -> None:
255
+ # What the whole effort is for: separating "time spent calling impulsa" from "time spent
256
+ # everywhere else". The number itself is production's to report.
257
+ _within_server_span(lambda: _call(_client()))
258
+
259
+ assert _require_span("POST get-cuenta-detalle").end_time is not None
260
+
261
+
262
+ # --- X-Request-ID forwarding (D23) ------------------------------------------
263
+
264
+
265
+ def test_an_inbound_request_id_is_forwarded_on_the_outbound_call() -> None:
266
+ _within_server_span(
267
+ lambda: _call(_client(default_headers={REQUEST_ID_HEADER: "order-42"}))
268
+ )
269
+
270
+ assert _sent[REQUEST_ID_HEADER] == "order-42"
271
+
272
+
273
+ def test_it_is_forwarded_even_with_tracing_off() -> None:
274
+ # The half of D23 that repairs D20: impulsa does not run modular_api, so trace context
275
+ # dies there. If it logs the request id, log correlation still crosses the boundary — and
276
+ # that must not depend on tracing being enabled.
277
+ _call(_client(default_headers={REQUEST_ID_HEADER: "order-42"}))
278
+
279
+ assert _sent[REQUEST_ID_HEADER] == "order-42"
280
+
281
+
282
+ def test_none_is_invented_when_the_caller_sent_none() -> None:
283
+ # We forward, we do not generate. Minting one belongs at an edge that knows it is the edge.
284
+ _call(_client())
285
+
286
+ assert REQUEST_ID_HEADER not in _sent
287
+
288
+
289
+ # --- without an active server span (gate G3) --------------------------------
290
+
291
+
292
+ def test_no_client_span_is_emitted() -> None:
293
+ # Not "a non-recording span": none at all.
294
+ _call(_client())
295
+
296
+ assert _exporter.get_finished_spans() == ()
297
+
298
+
299
+ def test_no_traceparent_is_injected() -> None:
300
+ # A header naming a span that does not exist would mislead a downstream service into
301
+ # attaching to nothing.
302
+ _call(_client())
303
+
304
+ assert "traceparent" not in _sent
305
+
306
+
307
+ def test_the_call_still_succeeds() -> None:
308
+ result = _call(_client())
309
+
310
+ assert result.is_success
@@ -1,46 +0,0 @@
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.5.0"
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"