macss-modular-api 0.6.1__tar.gz → 0.7.1__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 (77) hide show
  1. {macss_modular_api-0.6.1/src/macss_modular_api.egg-info → macss_modular_api-0.7.1}/PKG-INFO +4 -1
  2. macss_modular_api-0.7.1/pyproject.toml +115 -0
  3. {macss_modular_api-0.6.1 → macss_modular_api-0.7.1/src/macss_modular_api.egg-info}/PKG-INFO +4 -1
  4. {macss_modular_api-0.6.1 → macss_modular_api-0.7.1}/src/macss_modular_api.egg-info/SOURCES.txt +8 -0
  5. {macss_modular_api-0.6.1 → macss_modular_api-0.7.1}/src/macss_modular_api.egg-info/requires.txt +3 -0
  6. {macss_modular_api-0.6.1 → macss_modular_api-0.7.1}/src/modular_api/__init__.py +1 -0
  7. {macss_modular_api-0.6.1 → macss_modular_api-0.7.1}/src/modular_api/core/logger/logger.py +34 -2
  8. {macss_modular_api-0.6.1 → macss_modular_api-0.7.1}/src/modular_api/core/logger/logging_middleware.py +48 -12
  9. {macss_modular_api-0.6.1 → macss_modular_api-0.7.1}/src/modular_api/core/metrics/metric.py +16 -2
  10. {macss_modular_api-0.6.1 → macss_modular_api-0.7.1}/src/modular_api/core/metrics/metrics_middleware.py +6 -4
  11. {macss_modular_api-0.6.1 → macss_modular_api-0.7.1}/src/modular_api/core/modular_api.py +96 -4
  12. {macss_modular_api-0.6.1 → macss_modular_api-0.7.1}/src/modular_api/core/module_builder.py +20 -8
  13. {macss_modular_api-0.6.1 → macss_modular_api-0.7.1}/src/modular_api/core/plugin.py +22 -7
  14. {macss_modular_api-0.6.1 → macss_modular_api-0.7.1}/src/modular_api/core/registry.py +2 -2
  15. macss_modular_api-0.7.1/src/modular_api/core/tracing/__init__.py +47 -0
  16. macss_modular_api-0.7.1/src/modular_api/core/tracing/cloud_trace_propagator.py +143 -0
  17. macss_modular_api-0.7.1/src/modular_api/core/tracing/propagation_policy.py +126 -0
  18. macss_modular_api-0.7.1/src/modular_api/core/tracing/server_span.py +96 -0
  19. macss_modular_api-0.7.1/src/modular_api/core/tracing/tracing_middleware.py +111 -0
  20. macss_modular_api-0.7.1/src/modular_api/core/tracing/tracing_options.py +88 -0
  21. {macss_modular_api-0.6.1 → macss_modular_api-0.7.1}/src/modular_api/core/usecase.py +31 -7
  22. {macss_modular_api-0.6.1 → macss_modular_api-0.7.1}/src/modular_api/core/usecase_handler.py +10 -6
  23. {macss_modular_api-0.6.1 → macss_modular_api-0.7.1}/src/modular_api/graphql/catalog/graphql_catalog_builder.py +4 -5
  24. {macss_modular_api-0.6.1 → macss_modular_api-0.7.1}/src/modular_api/graphql/metadata/graphql_metadata_parser.py +55 -28
  25. {macss_modular_api-0.6.1 → macss_modular_api-0.7.1}/src/modular_api/graphql/read/sql_read_contract.py +1 -1
  26. {macss_modular_api-0.6.1 → macss_modular_api-0.7.1}/src/modular_api/graphql/read/sqlserver_read_compiler.py +15 -2
  27. {macss_modular_api-0.6.1 → macss_modular_api-0.7.1}/src/modular_api/graphql/runtime/graphql_artifacts.py +13 -8
  28. {macss_modular_api-0.6.1 → macss_modular_api-0.7.1}/src/modular_api/graphql/runtime/graphql_runtime_plugin.py +131 -55
  29. {macss_modular_api-0.6.1 → macss_modular_api-0.7.1}/src/modular_api/graphql/schema/graphql_schema_sdl_generator.py +0 -1
  30. {macss_modular_api-0.6.1 → macss_modular_api-0.7.1}/src/modular_api/graphql/sqlserver/sql_server_metadata_reader.py +10 -11
  31. {macss_modular_api-0.6.1 → macss_modular_api-0.7.1}/src/modular_api/middlewares/cors.py +2 -1
  32. {macss_modular_api-0.6.1 → macss_modular_api-0.7.1}/src/modular_api/openapi/openapi.py +39 -10
  33. {macss_modular_api-0.6.1 → macss_modular_api-0.7.1}/src/modular_api/openapi/swagger_docs.py +3 -1
  34. {macss_modular_api-0.6.1 → macss_modular_api-0.7.1}/tests/test_auto_schema.py +19 -6
  35. macss_modular_api-0.7.1/tests/test_dto_typing.py +67 -0
  36. {macss_modular_api-0.6.1 → macss_modular_api-0.7.1}/tests/test_field_example.py +19 -6
  37. {macss_modular_api-0.6.1 → macss_modular_api-0.7.1}/tests/test_fromjson_validation.py +0 -1
  38. {macss_modular_api-0.6.1 → macss_modular_api-0.7.1}/tests/test_modular_api.py +7 -6
  39. macss_modular_api-0.7.1/tests/test_packaging.py +96 -0
  40. {macss_modular_api-0.6.1 → macss_modular_api-0.7.1}/tests/test_usecase_handler.py +0 -1
  41. macss_modular_api-0.6.1/pyproject.toml +0 -59
  42. {macss_modular_api-0.6.1 → macss_modular_api-0.7.1}/LICENSE +0 -0
  43. {macss_modular_api-0.6.1 → macss_modular_api-0.7.1}/README.md +0 -0
  44. {macss_modular_api-0.6.1 → macss_modular_api-0.7.1}/setup.cfg +0 -0
  45. {macss_modular_api-0.6.1 → macss_modular_api-0.7.1}/src/macss_modular_api.egg-info/dependency_links.txt +0 -0
  46. {macss_modular_api-0.6.1 → macss_modular_api-0.7.1}/src/macss_modular_api.egg-info/top_level.txt +0 -0
  47. {macss_modular_api-0.6.1 → macss_modular_api-0.7.1}/src/modular_api/core/__init__.py +0 -0
  48. {macss_modular_api-0.6.1 → macss_modular_api-0.7.1}/src/modular_api/core/error_response_middleware.py +0 -0
  49. {macss_modular_api-0.6.1 → macss_modular_api-0.7.1}/src/modular_api/core/health/__init__.py +0 -0
  50. {macss_modular_api-0.6.1 → macss_modular_api-0.7.1}/src/modular_api/core/health/health_check.py +0 -0
  51. {macss_modular_api-0.6.1 → macss_modular_api-0.7.1}/src/modular_api/core/health/health_handler.py +0 -0
  52. {macss_modular_api-0.6.1 → macss_modular_api-0.7.1}/src/modular_api/core/health/health_service.py +0 -0
  53. {macss_modular_api-0.6.1 → macss_modular_api-0.7.1}/src/modular_api/core/logger/__init__.py +0 -0
  54. {macss_modular_api-0.6.1 → macss_modular_api-0.7.1}/src/modular_api/core/metrics/__init__.py +0 -0
  55. {macss_modular_api-0.6.1 → macss_modular_api-0.7.1}/src/modular_api/core/metrics/metric_registry.py +0 -0
  56. {macss_modular_api-0.6.1 → macss_modular_api-0.7.1}/src/modular_api/core/official_plugins.py +0 -0
  57. {macss_modular_api-0.6.1 → macss_modular_api-0.7.1}/src/modular_api/core/request_pipeline_audit.py +0 -0
  58. {macss_modular_api-0.6.1 → macss_modular_api-0.7.1}/src/modular_api/core/use_case_exception.py +0 -0
  59. {macss_modular_api-0.6.1 → macss_modular_api-0.7.1}/src/modular_api/dto.py +0 -0
  60. {macss_modular_api-0.6.1 → macss_modular_api-0.7.1}/src/modular_api/graphql/__init__.py +0 -0
  61. {macss_modular_api-0.6.1 → macss_modular_api-0.7.1}/src/modular_api/graphql/catalog/__init__.py +0 -0
  62. {macss_modular_api-0.6.1 → macss_modular_api-0.7.1}/src/modular_api/graphql/metadata/__init__.py +0 -0
  63. {macss_modular_api-0.6.1 → macss_modular_api-0.7.1}/src/modular_api/graphql/read/__init__.py +0 -0
  64. {macss_modular_api-0.6.1 → macss_modular_api-0.7.1}/src/modular_api/graphql/runtime/__init__.py +0 -0
  65. {macss_modular_api-0.6.1 → macss_modular_api-0.7.1}/src/modular_api/graphql/runtime/graphql_runtime_options.py +0 -0
  66. {macss_modular_api-0.6.1 → macss_modular_api-0.7.1}/src/modular_api/graphql/schema/__init__.py +0 -0
  67. {macss_modular_api-0.6.1 → macss_modular_api-0.7.1}/src/modular_api/graphql/sqlserver/__init__.py +0 -0
  68. {macss_modular_api-0.6.1 → macss_modular_api-0.7.1}/src/modular_api/graphql/sqlserver/physical_model.py +0 -0
  69. {macss_modular_api-0.6.1 → macss_modular_api-0.7.1}/src/modular_api/graphql/sqlserver/sql_server_connection_settings.py +0 -0
  70. {macss_modular_api-0.6.1 → macss_modular_api-0.7.1}/src/modular_api/middlewares/__init__.py +0 -0
  71. {macss_modular_api-0.6.1 → macss_modular_api-0.7.1}/src/modular_api/openapi/__init__.py +0 -0
  72. {macss_modular_api-0.6.1 → macss_modular_api-0.7.1}/src/modular_api/py.typed +0 -0
  73. {macss_modular_api-0.6.1 → macss_modular_api-0.7.1}/tests/test_clean_room_driver_isolation.py +0 -0
  74. {macss_modular_api-0.6.1 → macss_modular_api-0.7.1}/tests/test_module_builder.py +0 -0
  75. {macss_modular_api-0.6.1 → macss_modular_api-0.7.1}/tests/test_schema_conformance.py +0 -0
  76. {macss_modular_api-0.6.1 → macss_modular_api-0.7.1}/tests/test_use_case_exception.py +0 -0
  77. {macss_modular_api-0.6.1 → macss_modular_api-0.7.1}/tests/test_usecase.py +0 -0
@@ -1,6 +1,6 @@
1
1
  Metadata-Version: 2.4
2
2
  Name: macss-modular-api
3
- Version: 0.6.1
3
+ Version: 0.7.1
4
4
  Summary: Use-case-centric toolkit for building modular APIs with Starlette. Define UseCase classes (input → validate → execute → output), connect them to HTTP routes, and expose OpenAPI documentation automatically.
5
5
  Author: ccisne.dev
6
6
  License-Expression: MIT
@@ -24,14 +24,17 @@ Description-Content-Type: text/markdown
24
24
  License-File: LICENSE
25
25
  Requires-Dist: starlette>=0.40
26
26
  Requires-Dist: pydantic>=2.0
27
+ Requires-Dist: opentelemetry-api<2,>=1.44
27
28
  Provides-Extra: serve
28
29
  Requires-Dist: uvicorn>=0.30; extra == "serve"
29
30
  Provides-Extra: graphql
30
31
  Requires-Dist: json5>=0.9.14; extra == "graphql"
31
32
  Requires-Dist: graphql-core<3.3,>=3.2; extra == "graphql"
32
33
  Provides-Extra: dev
34
+ Requires-Dist: pyright>=1.1.400; extra == "dev"
33
35
  Requires-Dist: json5>=0.9.14; extra == "dev"
34
36
  Requires-Dist: graphql-core<3.3,>=3.2; extra == "dev"
37
+ Requires-Dist: opentelemetry-sdk<2,>=1.44; extra == "dev"
35
38
  Requires-Dist: pytest>=8.0; extra == "dev"
36
39
  Requires-Dist: pytest-asyncio>=0.24; extra == "dev"
37
40
  Requires-Dist: httpx>=0.27; extra == "dev"
@@ -0,0 +1,115 @@
1
+ [build-system]
2
+ requires = ["setuptools>=68", "wheel"]
3
+ build-backend = "setuptools.build_meta"
4
+
5
+ [project]
6
+ name = "macss-modular-api"
7
+ version = "0.7.1"
8
+ description = "Use-case-centric toolkit for building modular APIs with Starlette. Define UseCase classes (input → validate → execute → output), connect them to HTTP routes, and expose OpenAPI documentation automatically."
9
+ readme = "README.md"
10
+ license = "MIT"
11
+ requires-python = ">=3.11"
12
+ authors = [{ name = "ccisne.dev" }]
13
+ keywords = ["api", "usecase", "openapi", "starlette", "modular", "macss"]
14
+ classifiers = [
15
+ "Development Status :: 4 - Beta",
16
+ "Framework :: AsyncIO",
17
+ "Intended Audience :: Developers",
18
+ "Programming Language :: Python :: 3",
19
+ "Programming Language :: Python :: 3.11",
20
+ "Programming Language :: Python :: 3.12",
21
+ "Programming Language :: Python :: 3.13",
22
+ "Topic :: Internet :: WWW/HTTP :: HTTP Servers",
23
+ "Topic :: Software Development :: Libraries :: Application Frameworks",
24
+ "Typing :: Typed",
25
+ ]
26
+ dependencies = [
27
+ "starlette>=0.40",
28
+ "pydantic>=2.0",
29
+ # OpenTelemetry API only — never the SDK, an exporter, grpcio or protobuf.
30
+ # The API is no-op without an SDK, so tracing costs nothing until the
31
+ # application configures a TracerProvider. See ADR-0005 (amended) A1/A2, and
32
+ # tests/tracing/test_dependency_boundary.py, which enforces this.
33
+ "opentelemetry-api>=1.44,<2",
34
+ ]
35
+
36
+ [project.optional-dependencies]
37
+ serve = ["uvicorn>=0.30"]
38
+ graphql = ["json5>=0.9.14", "graphql-core>=3.2,<3.3"]
39
+ dev = [
40
+ # Configured below at `typeCheckingMode = "strict"`. Declared here because a checker the
41
+ # repo configures and never installs is a checker that has never run.
42
+ "pyright>=1.1.400",
43
+ "json5>=0.9.14",
44
+ "graphql-core>=3.2,<3.3",
45
+ # The SDK is what makes spans observable at all — the API alone is no-op (runbook D22).
46
+ # Declared here and never in `dependencies`, which the boundary test enforces.
47
+ "opentelemetry-sdk>=1.44,<2",
48
+ "pytest>=8.0",
49
+ "pytest-asyncio>=0.24",
50
+ "httpx>=0.27",
51
+ "uvicorn>=0.30",
52
+ ]
53
+
54
+ [project.urls]
55
+ Homepage = "https://github.com/macss-dev/modular_api"
56
+ Repository = "https://github.com/macss-dev/modular_api/tree/main/code/py/modular_api"
57
+ Issues = "https://github.com/macss-dev/modular_api/issues"
58
+ Documentation = "https://github.com/macss-dev/modular_api/tree/main/code/py/modular_api#readme"
59
+
60
+ [tool.setuptools.packages.find]
61
+ where = ["src"]
62
+
63
+ [tool.pytest.ini_options]
64
+ testpaths = ["tests"]
65
+ pythonpath = ["src"]
66
+ asyncio_mode = "auto"
67
+
68
+ [tool.pyright]
69
+ pythonVersion = "3.11"
70
+ typeCheckingMode = "strict"
71
+
72
+ [[tool.pyright.executionEnvironments]]
73
+ root = "tests"
74
+ reportUnknownMemberType = false
75
+ reportUnknownArgumentType = false
76
+ reportUnknownVariableType = false
77
+ reportUnknownParameterType = false
78
+ reportUnknownLambdaType = false
79
+ reportMissingParameterType = false
80
+ reportMissingTypeArgument = false
81
+ # A pytest fixture is called by name through collection, never by a reference the checker can see, so
82
+ # `reportUnusedFunction` reports every `autouse` fixture in this tree. Likewise a test that asserts a
83
+ # class body raises a warning has to define a class it then never mentions. Both are the tool not
84
+ # modelling pytest, not dead code. `reportUnusedImport` and `reportUnusedVariable` stay on — those do
85
+ # find dead code, and they did.
86
+ reportUnusedFunction = false
87
+ reportUnusedClass = false
88
+ # Tests legitimately reach into internals to exercise them directly. In `src/` this rule found real
89
+ # coupling — a middleware importing another module's private default, a metric reading a private field
90
+ # off a different object — and both were fixed rather than silenced.
91
+ reportPrivateUsage = false
92
+ # `tools/` are developer scripts run by hand from this repository — same standing as `tests/`: they
93
+ # bind nobody outside it. Sin esta entrada quedaban bajo strict completo, y `tools/dump_span_shape.py`
94
+ # fallaba por el tipo parcial de `httpx.post`. Lo descubrio CI, no una corrida local.
95
+ [[tool.pyright.executionEnvironments]]
96
+ root = "tools"
97
+ reportUnknownMemberType = false
98
+ reportUnknownArgumentType = false
99
+ reportUnknownVariableType = false
100
+ reportUnknownParameterType = false
101
+ reportUnknownLambdaType = false
102
+ reportMissingParameterType = false
103
+ reportMissingTypeArgument = false
104
+
105
+ # `example/` is documentation a consumer copies, not a published typed surface — same relaxed family
106
+ # as `tests/`, and the same expectation that nothing which can indicate a real defect is silenced.
107
+ [[tool.pyright.executionEnvironments]]
108
+ root = "example"
109
+ reportUnknownMemberType = false
110
+ reportUnknownArgumentType = false
111
+ reportUnknownVariableType = false
112
+ reportUnknownParameterType = false
113
+ reportUnknownLambdaType = false
114
+ reportMissingParameterType = false
115
+ reportMissingTypeArgument = false
@@ -1,6 +1,6 @@
1
1
  Metadata-Version: 2.4
2
2
  Name: macss-modular-api
3
- Version: 0.6.1
3
+ Version: 0.7.1
4
4
  Summary: Use-case-centric toolkit for building modular APIs with Starlette. Define UseCase classes (input → validate → execute → output), connect them to HTTP routes, and expose OpenAPI documentation automatically.
5
5
  Author: ccisne.dev
6
6
  License-Expression: MIT
@@ -24,14 +24,17 @@ Description-Content-Type: text/markdown
24
24
  License-File: LICENSE
25
25
  Requires-Dist: starlette>=0.40
26
26
  Requires-Dist: pydantic>=2.0
27
+ Requires-Dist: opentelemetry-api<2,>=1.44
27
28
  Provides-Extra: serve
28
29
  Requires-Dist: uvicorn>=0.30; extra == "serve"
29
30
  Provides-Extra: graphql
30
31
  Requires-Dist: json5>=0.9.14; extra == "graphql"
31
32
  Requires-Dist: graphql-core<3.3,>=3.2; extra == "graphql"
32
33
  Provides-Extra: dev
34
+ Requires-Dist: pyright>=1.1.400; extra == "dev"
33
35
  Requires-Dist: json5>=0.9.14; extra == "dev"
34
36
  Requires-Dist: graphql-core<3.3,>=3.2; extra == "dev"
37
+ Requires-Dist: opentelemetry-sdk<2,>=1.44; extra == "dev"
35
38
  Requires-Dist: pytest>=8.0; extra == "dev"
36
39
  Requires-Dist: pytest-asyncio>=0.24; extra == "dev"
37
40
  Requires-Dist: httpx>=0.27; extra == "dev"
@@ -31,6 +31,12 @@ src/modular_api/core/metrics/__init__.py
31
31
  src/modular_api/core/metrics/metric.py
32
32
  src/modular_api/core/metrics/metric_registry.py
33
33
  src/modular_api/core/metrics/metrics_middleware.py
34
+ src/modular_api/core/tracing/__init__.py
35
+ src/modular_api/core/tracing/cloud_trace_propagator.py
36
+ src/modular_api/core/tracing/propagation_policy.py
37
+ src/modular_api/core/tracing/server_span.py
38
+ src/modular_api/core/tracing/tracing_middleware.py
39
+ src/modular_api/core/tracing/tracing_options.py
34
40
  src/modular_api/graphql/__init__.py
35
41
  src/modular_api/graphql/catalog/__init__.py
36
42
  src/modular_api/graphql/catalog/graphql_catalog_builder.py
@@ -56,10 +62,12 @@ src/modular_api/openapi/openapi.py
56
62
  src/modular_api/openapi/swagger_docs.py
57
63
  tests/test_auto_schema.py
58
64
  tests/test_clean_room_driver_isolation.py
65
+ tests/test_dto_typing.py
59
66
  tests/test_field_example.py
60
67
  tests/test_fromjson_validation.py
61
68
  tests/test_modular_api.py
62
69
  tests/test_module_builder.py
70
+ tests/test_packaging.py
63
71
  tests/test_schema_conformance.py
64
72
  tests/test_use_case_exception.py
65
73
  tests/test_usecase.py
@@ -1,9 +1,12 @@
1
1
  starlette>=0.40
2
2
  pydantic>=2.0
3
+ opentelemetry-api<2,>=1.44
3
4
 
4
5
  [dev]
6
+ pyright>=1.1.400
5
7
  json5>=0.9.14
6
8
  graphql-core<3.3,>=3.2
9
+ opentelemetry-sdk<2,>=1.44
7
10
  pytest>=8.0
8
11
  pytest-asyncio>=0.24
9
12
  httpx>=0.27
@@ -54,6 +54,7 @@ from modular_api.openapi.openapi import (
54
54
  from modular_api.openapi.swagger_docs import swagger_docs_handler
55
55
 
56
56
  __all__ = [
57
+ "HostMetadata",
57
58
  "ApiRegistry",
58
59
  "Counter",
59
60
  "Field",
@@ -57,6 +57,14 @@ def _default_write(line: str) -> None:
57
57
  sys.stdout.write(line + "\n")
58
58
 
59
59
 
60
+ #: Builds platform-specific correlation fields from the ids the framework resolved.
61
+ #:
62
+ #: The framework emits open formats and nothing vendor-specific (roadmap invariant 7), so
63
+ #: a field like Google's ``logging.googleapis.com/trace`` — which needs a project id the
64
+ #: framework has no business knowing — is produced by the application.
65
+ TraceFieldFormatter = Callable[[str, str | None], dict[str, object]]
66
+
67
+
60
68
  class RequestScopedLogger:
61
69
  """Per-request logger carrying ``trace_id`` with ``log_level`` filtering.
62
70
 
@@ -72,12 +80,26 @@ class RequestScopedLogger:
72
80
  trace_id: str,
73
81
  log_level: LogLevel,
74
82
  service_name: str,
75
- write_fn: WriteFn = _default_write,
83
+ # `None` selects the default sink, so a caller holding an optional write function can pass it
84
+ # straight through instead of importing the module-private default. This is what the TypeScript
85
+ # constructor already does with an omitted `writeFn` and Dart with an omitted `LogSink`.
86
+ write_fn: WriteFn | None = None,
87
+ span_id: str | None = None,
88
+ request_id: str | None = None,
89
+ trace_field_formatter: TraceFieldFormatter | None = None,
76
90
  ) -> None:
77
91
  self._trace_id = trace_id
78
92
  self._log_level = log_level
79
93
  self._service_name = service_name
80
- self._write_fn = write_fn
94
+ self._write_fn: WriteFn = _default_write if write_fn is None else write_fn
95
+ # Known at construction because the tracing middleware is outermost (runbook D12
96
+ # as reversed): the span already exists when logging_middleware creates this
97
+ # logger, so nothing needs mutating afterwards.
98
+ self._span_id = span_id
99
+ # The caller's X-Request-ID, preserved beside the trace id rather than promoted
100
+ # into it (runbook D6).
101
+ self._request_id = request_id
102
+ self._trace_field_formatter = trace_field_formatter
81
103
 
82
104
  @property
83
105
  def trace_id(self) -> str:
@@ -164,6 +186,16 @@ class RequestScopedLogger:
164
186
  "trace_id": self._trace_id,
165
187
  }
166
188
 
189
+ if self._span_id is not None:
190
+ entry["span_id"] = self._span_id
191
+ if self._request_id is not None:
192
+ entry["request_id"] = self._request_id
193
+
194
+ # Only when there is trace context to point at. A platform field naming a trace
195
+ # that does not exist is worse than no field.
196
+ if self._trace_field_formatter is not None and self._span_id is not None:
197
+ entry.update(self._trace_field_formatter(self._trace_id, self._span_id))
198
+
167
199
  if extra is not None:
168
200
  entry.update(extra)
169
201
  if fields is not None:
@@ -17,13 +17,18 @@ from __future__ import annotations
17
17
 
18
18
  import time
19
19
  import uuid
20
- from typing import Callable
20
+ from typing import cast
21
21
 
22
+ from opentelemetry import trace
22
23
  from starlette.requests import Request
23
- from starlette.responses import Response
24
- from starlette.types import ASGIApp, Receive, Scope, Send
25
-
26
- from modular_api.core.logger.logger import LogLevel, RequestScopedLogger, WriteFn, _default_write
24
+ from starlette.types import ASGIApp, Message, Receive, Scope, Send
25
+
26
+ from modular_api.core.logger.logger import (
27
+ LogLevel,
28
+ RequestScopedLogger,
29
+ TraceFieldFormatter,
30
+ WriteFn,
31
+ )
27
32
  from modular_api.core.request_pipeline_audit import ensure_request_pipeline_audit
28
33
 
29
34
  # Key used in request.state to propagate the logger downstream.
@@ -36,6 +41,7 @@ def logging_middleware(
36
41
  service_name: str,
37
42
  excluded_routes: list[str] | None = None,
38
43
  write_fn: WriteFn | None = None,
44
+ trace_field_formatter: TraceFieldFormatter | None = None,
39
45
  ) -> type:
40
46
  """Returns a Starlette middleware class (not an instance).
41
47
 
@@ -67,16 +73,41 @@ def logging_middleware(
67
73
  await self.app(scope, receive, send)
68
74
  return
69
75
 
70
- # 1. Resolve trace_id
76
+ # 1. Resolve the ids from the ambient span.
77
+ #
78
+ # The tracing middleware is outermost (D12 as reversed), so when tracing is
79
+ # configured a recording span is already active here — and contextvars keep it
80
+ # active for `request completed` too. Both lines therefore carry the same ids
81
+ # with nothing mutated afterwards.
82
+ #
83
+ # With no recording span this is byte-for-byte the behaviour it always had: the
84
+ # caller's X-Request-ID or a fresh UUID. D5b's compatibility guarantee is
85
+ # structural rather than conditional — there is no tracing flag to consult,
86
+ # only whether a span exists.
87
+ active_span_context = trace.get_current_span().get_span_context()
88
+ tracing_active = active_span_context.is_valid
89
+
71
90
  header_value = request.headers.get("x-request-id", "")
72
- trace_id = header_value if header_value else str(uuid.uuid4())
91
+ caller_request_id = header_value if header_value else None
92
+
93
+ if tracing_active:
94
+ trace_id = f"{active_span_context.trace_id:032x}"
95
+ span_id: str | None = f"{active_span_context.span_id:016x}"
96
+ request_id = caller_request_id
97
+ else:
98
+ trace_id = caller_request_id or str(uuid.uuid4())
99
+ span_id = None
100
+ request_id = None
73
101
 
74
102
  # 2. Create per-request logger
75
103
  logger = RequestScopedLogger(
76
104
  trace_id=trace_id,
77
105
  log_level=log_level,
78
106
  service_name=service_name,
79
- write_fn=write_fn or _default_write,
107
+ write_fn=write_fn,
108
+ span_id=span_id,
109
+ request_id=request_id,
110
+ trace_field_formatter=trace_field_formatter,
80
111
  )
81
112
 
82
113
  method = request.method.upper()
@@ -93,13 +124,18 @@ def logging_middleware(
93
124
  status_code = 500 # default for unhandled errors
94
125
 
95
126
  # Intercept the response start to capture status_code.
96
- async def send_wrapper(message: dict) -> None:
127
+ # `Message` is the ASGI event type Starlette already declares, and it is what `Send`
128
+ # expects: a bare `dict` made this wrapper unassignable to `Send`, which is the signature
129
+ # the line below passes it as.
130
+ async def send_wrapper(message: Message) -> None:
97
131
  nonlocal status_code
98
132
  if message["type"] == "http.response.start":
99
- status_code = message["status"]
133
+ status_code = cast(int, message["status"])
100
134
  # Inject X-Request-ID header into the response.
101
- headers = list(message.get("headers", []))
102
- headers.append((b"x-request-id", trace_id.encode()))
135
+ headers = [
136
+ *cast("list[tuple[bytes, bytes]]", message.get("headers", [])),
137
+ (b"x-request-id", trace_id.encode()),
138
+ ]
103
139
  message = {**message, "headers": headers}
104
140
  await send(message)
105
141
 
@@ -50,6 +50,15 @@ class LabeledCounter:
50
50
  def value(self) -> float:
51
51
  return self._value
52
52
 
53
+ @property
54
+ def labels(self) -> dict[str, str]:
55
+ """The label set this child holds, copied — the parent's ``collect()`` reads it.
56
+
57
+ A read property for the same reason ``value`` is one: the parent was reaching into ``_labels``,
58
+ which is private to this class and belongs to a different object than the one reading it.
59
+ """
60
+ return dict(self._labels)
61
+
53
62
  def inc(self, amount: float = 1) -> None:
54
63
  """Increments by *amount* (must be > 0)."""
55
64
  if amount <= 0:
@@ -92,7 +101,7 @@ class Counter:
92
101
  return [
93
102
  MetricSample(
94
103
  name=self.name,
95
- labels=dict(child._labels),
104
+ labels=child.labels,
96
105
  value=child.value,
97
106
  suffix="",
98
107
  )
@@ -116,6 +125,11 @@ class LabeledGauge:
116
125
  def value(self) -> float:
117
126
  return self._value
118
127
 
128
+ @property
129
+ def labels(self) -> dict[str, str]:
130
+ """The label set this child holds, copied — see ``LabeledCounter.labels``."""
131
+ return dict(self._labels)
132
+
119
133
  def set(self, v: float) -> None:
120
134
  self._value = float(v)
121
135
 
@@ -164,7 +178,7 @@ class Gauge:
164
178
  return [
165
179
  MetricSample(
166
180
  name=self.name,
167
- labels=dict(child._labels),
181
+ labels=child.labels,
168
182
  value=child.value,
169
183
  suffix="",
170
184
  )
@@ -12,11 +12,11 @@ Records per-request:
12
12
  from __future__ import annotations
13
13
 
14
14
  import time
15
- from typing import Any
15
+ from typing import Any, cast
16
16
 
17
17
  from starlette.requests import Request
18
18
  from starlette.responses import Response
19
- from starlette.types import ASGIApp, Receive, Scope, Send
19
+ from starlette.types import ASGIApp, Message, Receive, Scope, Send
20
20
 
21
21
  from modular_api.core.metrics.metric import Counter, Gauge, Histogram
22
22
  from modular_api.core.metrics.metric_registry import MetricRegistry
@@ -61,10 +61,12 @@ def metrics_middleware(
61
61
  start = time.perf_counter()
62
62
  status_code = 500 # default for unhandled errors
63
63
 
64
- async def send_wrapper(message: dict) -> None:
64
+ # `Message` is the ASGI event type `Send` expects; a bare `dict` made this wrapper
65
+ # unassignable to it. Same fix as the logging middleware.
66
+ async def send_wrapper(message: Message) -> None:
65
67
  nonlocal status_code
66
68
  if message["type"] == "http.response.start":
67
- status_code = message["status"]
69
+ status_code = cast(int, message["status"])
68
70
  await send(message)
69
71
 
70
72
  try:
@@ -22,6 +22,7 @@ Usage::
22
22
 
23
23
  from __future__ import annotations
24
24
 
25
+ import inspect
25
26
  from contextlib import asynccontextmanager
26
27
  from typing import Any, Callable
27
28
 
@@ -33,11 +34,26 @@ from modular_api.core.error_response_middleware import error_response_middleware
33
34
  from modular_api.core.health.health_service import HealthService
34
35
  from modular_api.core.logger.logger import LogLevel
35
36
  from modular_api.core.logger.logging_middleware import logging_middleware
37
+ from opentelemetry.propagate import set_global_textmap
38
+ from opentelemetry.propagators.composite import CompositePropagator
39
+
40
+ from modular_api.core.tracing.tracing_middleware import tracing_middleware
41
+ from modular_api.core.tracing.tracing_options import TracingOptions
36
42
  from modular_api.core.metrics.metric import Counter, Gauge, Histogram
37
43
  from modular_api.core.metrics.metric_registry import MetricRegistry, MetricsRegistrar
38
44
  from modular_api.core.module_builder import ModuleBuilder
39
- from modular_api.core.official_plugins import build_runtime_plugins, operational_route_paths
40
- from modular_api.core.plugin import Plugin, PluginHostError, RuntimePluginHost, order_plugins
45
+ from modular_api.core.official_plugins import (
46
+ OperationalRoutePaths,
47
+ build_runtime_plugins,
48
+ operational_route_paths,
49
+ )
50
+ from modular_api.core.plugin import (
51
+ Plugin,
52
+ PluginHostError,
53
+ PluginValidationResult,
54
+ RuntimePluginHost,
55
+ order_plugins,
56
+ )
41
57
  from modular_api.core.registry import api_registry
42
58
  from modular_api.graphql.runtime import GraphqlOptions
43
59
 
@@ -61,6 +77,7 @@ class ModularApi:
61
77
  metrics_path: str = "/metrics",
62
78
  log_level: LogLevel = LogLevel.info,
63
79
  graphql: GraphqlOptions | None = None,
80
+ tracing: TracingOptions | None = None,
64
81
  ) -> None:
65
82
  self._base_path = base_path
66
83
  self._title = title
@@ -71,6 +88,8 @@ class ModularApi:
71
88
  self._metrics_path = metrics_path
72
89
  self._log_level = log_level
73
90
  self._graphql = graphql
91
+ # Distributed tracing options, or None when tracing is off (ADR-0005).
92
+ self._tracing = tracing
74
93
 
75
94
  self._health_service = HealthService(version=version, release_id=self._release_id)
76
95
  self._module_routers: list[tuple[str, Router]] = []
@@ -196,7 +215,7 @@ class ModularApi:
196
215
  plugin_host.end_plugin_setup()
197
216
  plugin_host.on_shutdown(plugin.shutdown)
198
217
  plugin_host.freeze()
199
- validation_results = []
218
+ validation_results: list[PluginValidationResult] = []
200
219
  for plugin in ordered_plugins:
201
220
  validation_results.extend(plugin.validate(plugin_host))
202
221
  plugin_host.assert_valid(validation_results)
@@ -212,6 +231,21 @@ class ModularApi:
212
231
  try:
213
232
  yield
214
233
  finally:
234
+ # Tracing's shutdown callback runs alongside the plugin host's, not as a
235
+ # plugin. There is deliberately no tracing plugin: every responsibility
236
+ # ADR-0005 decision 4 gave one was reassigned by a later decision, and what
237
+ # remained was a plugin whose setup() did nothing (see ADR-0005 A7).
238
+ #
239
+ # The framework owns the timing; the application owns the provider. A
240
+ # callback that raises is swallowed — losing telemetry is bad, failing to
241
+ # stop is worse.
242
+ if self._tracing is not None and self._tracing.on_shutdown is not None:
243
+ try:
244
+ result = self._tracing.on_shutdown()
245
+ if inspect.isawaitable(result):
246
+ await result
247
+ except Exception: # noqa: BLE001 - see comment above
248
+ pass
215
249
  await plugin_host.shutdown()
216
250
 
217
251
  app = Starlette(routes=routes, lifespan=lifespan)
@@ -236,7 +270,7 @@ class ModularApi:
236
270
  # 4b. Error normalization middleware (wraps plugin middleware + routes)
237
271
  app.add_middleware(error_response_middleware())
238
272
 
239
- # 5. Logging middleware (outermost — wraps everything)
273
+ # 5. Logging middleware (inside tracing — see step 6 below)
240
274
  excluded_log_routes = [
241
275
  operational_paths.health_path,
242
276
  operational_paths.docs_path,
@@ -250,9 +284,46 @@ class ModularApi:
250
284
  log_level=self._log_level,
251
285
  service_name=self._title,
252
286
  excluded_routes=excluded_log_routes,
287
+ trace_field_formatter=(
288
+ self._tracing.trace_field_formatter if self._tracing else None
289
+ ),
253
290
  ),
254
291
  )
255
292
 
293
+ # 6. Tracing — added LAST, so Starlette's LIFO ordering makes it the OUTERMOST
294
+ # middleware with logging inside it (runbook D12 as reversed). The logger then
295
+ # runs within the span's active scope and reads trace_id and span_id from the
296
+ # ambient span on every line, including `request completed`, because contextvars
297
+ # keep the span active there.
298
+ #
299
+ # An earlier design had tracing inside logging, which forced the logger to own the
300
+ # trace id and the span to adopt it — expressible in Dart but not in TypeScript
301
+ # without seeding a parent, where the seeded trace flags made the sampler drop the
302
+ # span. Absent options add nothing, which is what makes tracing free when it is off
303
+ # (gate G3).
304
+ if self._tracing is not None:
305
+ # Publish the chain as the global propagator, which is how satellite packages
306
+ # inject it. macss-modular-api-rest-client does not depend on this package
307
+ # (D21), so it cannot reach our propagator — and per the OpenTelemetry API's
308
+ # guidance it should not: instrumentation libraries read the global, the host
309
+ # sets it. That also means whatever chain the application configured is honoured
310
+ # on outbound calls, including a Cloud Trace propagator it appended.
311
+ propagators = list(self._tracing.policy.propagators)
312
+ if propagators:
313
+ set_global_textmap(
314
+ propagators[0]
315
+ if len(propagators) == 1
316
+ else CompositePropagator(propagators)
317
+ )
318
+
319
+ app.add_middleware(
320
+ tracing_middleware(
321
+ tracer=self._tracing.tracer,
322
+ policy=self._tracing.policy,
323
+ excluded_routes=_tracing_excluded_routes(operational_paths),
324
+ ),
325
+ )
326
+
256
327
  return app
257
328
 
258
329
  def serve(self, *, port: int = 8000, host: str = "0.0.0.0") -> None:
@@ -279,3 +350,24 @@ class ModularApi:
279
350
  if not path:
280
351
  return ""
281
352
  return path if path.startswith("/") else f"/{path}"
353
+
354
+
355
+ def _tracing_excluded_routes(operational_paths: OperationalRoutePaths) -> tuple[str, ...]:
356
+ """Operational routes kept out of the trace store.
357
+
358
+ Derived from ``operational_paths`` rather than hardcoded, so it cannot drift apart
359
+ from the logger's own exclusions — health, docs, openapi and metrics are noise in a
360
+ trace store.
361
+ """
362
+ # The parameter was `object` with a `type: ignore` on each read. `OperationalRoutePaths` is what the
363
+ # caller already builds, so naming it makes all five reads checked instead of suppressed.
364
+ paths = [
365
+ operational_paths.health_path,
366
+ operational_paths.docs_path,
367
+ operational_paths.openapi_json_path,
368
+ operational_paths.openapi_yaml_path,
369
+ ]
370
+ metrics_path = operational_paths.metrics_path
371
+ if metrics_path is not None:
372
+ paths.append(metrics_path)
373
+ return tuple(paths)