macss-modular-api 0.7.2__tar.gz → 0.8.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 (80) hide show
  1. {macss_modular_api-0.7.2/src/macss_modular_api.egg-info → macss_modular_api-0.8.0}/PKG-INFO +1 -1
  2. {macss_modular_api-0.7.2 → macss_modular_api-0.8.0}/pyproject.toml +1 -1
  3. {macss_modular_api-0.7.2 → macss_modular_api-0.8.0/src/macss_modular_api.egg-info}/PKG-INFO +1 -1
  4. {macss_modular_api-0.7.2 → macss_modular_api-0.8.0}/src/macss_modular_api.egg-info/SOURCES.txt +4 -0
  5. {macss_modular_api-0.7.2 → macss_modular_api-0.8.0}/src/modular_api/__init__.py +3 -0
  6. {macss_modular_api-0.7.2 → macss_modular_api-0.8.0}/src/modular_api/core/metrics/metric_registry.py +7 -1
  7. {macss_modular_api-0.7.2 → macss_modular_api-0.8.0}/src/modular_api/core/modular_api.py +7 -0
  8. {macss_modular_api-0.7.2 → macss_modular_api-0.8.0}/src/modular_api/core/module_builder.py +16 -0
  9. macss_modular_api-0.8.0/src/modular_api/core/resolved_route.py +67 -0
  10. {macss_modular_api-0.7.2 → macss_modular_api-0.8.0}/src/modular_api/core/usecase_handler.py +33 -3
  11. macss_modular_api-0.8.0/tests/test_malformed_body.py +117 -0
  12. macss_modular_api-0.8.0/tests/test_routing.py +158 -0
  13. macss_modular_api-0.8.0/tests/test_routing_internal_middlewares.py +79 -0
  14. {macss_modular_api-0.7.2 → macss_modular_api-0.8.0}/LICENSE +0 -0
  15. {macss_modular_api-0.7.2 → macss_modular_api-0.8.0}/README.md +0 -0
  16. {macss_modular_api-0.7.2 → macss_modular_api-0.8.0}/setup.cfg +0 -0
  17. {macss_modular_api-0.7.2 → macss_modular_api-0.8.0}/src/macss_modular_api.egg-info/dependency_links.txt +0 -0
  18. {macss_modular_api-0.7.2 → macss_modular_api-0.8.0}/src/macss_modular_api.egg-info/requires.txt +0 -0
  19. {macss_modular_api-0.7.2 → macss_modular_api-0.8.0}/src/macss_modular_api.egg-info/top_level.txt +0 -0
  20. {macss_modular_api-0.7.2 → macss_modular_api-0.8.0}/src/modular_api/core/__init__.py +0 -0
  21. {macss_modular_api-0.7.2 → macss_modular_api-0.8.0}/src/modular_api/core/error_response_middleware.py +0 -0
  22. {macss_modular_api-0.7.2 → macss_modular_api-0.8.0}/src/modular_api/core/health/__init__.py +0 -0
  23. {macss_modular_api-0.7.2 → macss_modular_api-0.8.0}/src/modular_api/core/health/health_check.py +0 -0
  24. {macss_modular_api-0.7.2 → macss_modular_api-0.8.0}/src/modular_api/core/health/health_handler.py +0 -0
  25. {macss_modular_api-0.7.2 → macss_modular_api-0.8.0}/src/modular_api/core/health/health_service.py +0 -0
  26. {macss_modular_api-0.7.2 → macss_modular_api-0.8.0}/src/modular_api/core/logger/__init__.py +0 -0
  27. {macss_modular_api-0.7.2 → macss_modular_api-0.8.0}/src/modular_api/core/logger/logger.py +0 -0
  28. {macss_modular_api-0.7.2 → macss_modular_api-0.8.0}/src/modular_api/core/logger/logging_middleware.py +0 -0
  29. {macss_modular_api-0.7.2 → macss_modular_api-0.8.0}/src/modular_api/core/metrics/__init__.py +0 -0
  30. {macss_modular_api-0.7.2 → macss_modular_api-0.8.0}/src/modular_api/core/metrics/metric.py +0 -0
  31. {macss_modular_api-0.7.2 → macss_modular_api-0.8.0}/src/modular_api/core/metrics/metrics_middleware.py +0 -0
  32. {macss_modular_api-0.7.2 → macss_modular_api-0.8.0}/src/modular_api/core/official_plugins.py +0 -0
  33. {macss_modular_api-0.7.2 → macss_modular_api-0.8.0}/src/modular_api/core/plugin.py +0 -0
  34. {macss_modular_api-0.7.2 → macss_modular_api-0.8.0}/src/modular_api/core/registry.py +0 -0
  35. {macss_modular_api-0.7.2 → macss_modular_api-0.8.0}/src/modular_api/core/request_pipeline_audit.py +0 -0
  36. {macss_modular_api-0.7.2 → macss_modular_api-0.8.0}/src/modular_api/core/tracing/__init__.py +0 -0
  37. {macss_modular_api-0.7.2 → macss_modular_api-0.8.0}/src/modular_api/core/tracing/cloud_trace_propagator.py +0 -0
  38. {macss_modular_api-0.7.2 → macss_modular_api-0.8.0}/src/modular_api/core/tracing/propagation_policy.py +0 -0
  39. {macss_modular_api-0.7.2 → macss_modular_api-0.8.0}/src/modular_api/core/tracing/server_span.py +0 -0
  40. {macss_modular_api-0.7.2 → macss_modular_api-0.8.0}/src/modular_api/core/tracing/tracing_middleware.py +0 -0
  41. {macss_modular_api-0.7.2 → macss_modular_api-0.8.0}/src/modular_api/core/tracing/tracing_options.py +0 -0
  42. {macss_modular_api-0.7.2 → macss_modular_api-0.8.0}/src/modular_api/core/use_case_exception.py +0 -0
  43. {macss_modular_api-0.7.2 → macss_modular_api-0.8.0}/src/modular_api/core/usecase.py +0 -0
  44. {macss_modular_api-0.7.2 → macss_modular_api-0.8.0}/src/modular_api/dto.py +0 -0
  45. {macss_modular_api-0.7.2 → macss_modular_api-0.8.0}/src/modular_api/graphql/__init__.py +0 -0
  46. {macss_modular_api-0.7.2 → macss_modular_api-0.8.0}/src/modular_api/graphql/catalog/__init__.py +0 -0
  47. {macss_modular_api-0.7.2 → macss_modular_api-0.8.0}/src/modular_api/graphql/catalog/graphql_catalog_builder.py +0 -0
  48. {macss_modular_api-0.7.2 → macss_modular_api-0.8.0}/src/modular_api/graphql/metadata/__init__.py +0 -0
  49. {macss_modular_api-0.7.2 → macss_modular_api-0.8.0}/src/modular_api/graphql/metadata/graphql_metadata_parser.py +0 -0
  50. {macss_modular_api-0.7.2 → macss_modular_api-0.8.0}/src/modular_api/graphql/read/__init__.py +0 -0
  51. {macss_modular_api-0.7.2 → macss_modular_api-0.8.0}/src/modular_api/graphql/read/sql_read_contract.py +0 -0
  52. {macss_modular_api-0.7.2 → macss_modular_api-0.8.0}/src/modular_api/graphql/read/sqlserver_read_compiler.py +0 -0
  53. {macss_modular_api-0.7.2 → macss_modular_api-0.8.0}/src/modular_api/graphql/runtime/__init__.py +0 -0
  54. {macss_modular_api-0.7.2 → macss_modular_api-0.8.0}/src/modular_api/graphql/runtime/graphql_artifacts.py +0 -0
  55. {macss_modular_api-0.7.2 → macss_modular_api-0.8.0}/src/modular_api/graphql/runtime/graphql_runtime_options.py +0 -0
  56. {macss_modular_api-0.7.2 → macss_modular_api-0.8.0}/src/modular_api/graphql/runtime/graphql_runtime_plugin.py +0 -0
  57. {macss_modular_api-0.7.2 → macss_modular_api-0.8.0}/src/modular_api/graphql/schema/__init__.py +0 -0
  58. {macss_modular_api-0.7.2 → macss_modular_api-0.8.0}/src/modular_api/graphql/schema/graphql_schema_sdl_generator.py +0 -0
  59. {macss_modular_api-0.7.2 → macss_modular_api-0.8.0}/src/modular_api/graphql/sqlserver/__init__.py +0 -0
  60. {macss_modular_api-0.7.2 → macss_modular_api-0.8.0}/src/modular_api/graphql/sqlserver/physical_model.py +0 -0
  61. {macss_modular_api-0.7.2 → macss_modular_api-0.8.0}/src/modular_api/graphql/sqlserver/sql_server_connection_settings.py +0 -0
  62. {macss_modular_api-0.7.2 → macss_modular_api-0.8.0}/src/modular_api/graphql/sqlserver/sql_server_metadata_reader.py +0 -0
  63. {macss_modular_api-0.7.2 → macss_modular_api-0.8.0}/src/modular_api/middlewares/__init__.py +0 -0
  64. {macss_modular_api-0.7.2 → macss_modular_api-0.8.0}/src/modular_api/middlewares/cors.py +0 -0
  65. {macss_modular_api-0.7.2 → macss_modular_api-0.8.0}/src/modular_api/openapi/__init__.py +0 -0
  66. {macss_modular_api-0.7.2 → macss_modular_api-0.8.0}/src/modular_api/openapi/openapi.py +0 -0
  67. {macss_modular_api-0.7.2 → macss_modular_api-0.8.0}/src/modular_api/openapi/swagger_docs.py +0 -0
  68. {macss_modular_api-0.7.2 → macss_modular_api-0.8.0}/src/modular_api/py.typed +0 -0
  69. {macss_modular_api-0.7.2 → macss_modular_api-0.8.0}/tests/test_auto_schema.py +0 -0
  70. {macss_modular_api-0.7.2 → macss_modular_api-0.8.0}/tests/test_clean_room_driver_isolation.py +0 -0
  71. {macss_modular_api-0.7.2 → macss_modular_api-0.8.0}/tests/test_dto_typing.py +0 -0
  72. {macss_modular_api-0.7.2 → macss_modular_api-0.8.0}/tests/test_field_example.py +0 -0
  73. {macss_modular_api-0.7.2 → macss_modular_api-0.8.0}/tests/test_fromjson_validation.py +0 -0
  74. {macss_modular_api-0.7.2 → macss_modular_api-0.8.0}/tests/test_modular_api.py +0 -0
  75. {macss_modular_api-0.7.2 → macss_modular_api-0.8.0}/tests/test_module_builder.py +0 -0
  76. {macss_modular_api-0.7.2 → macss_modular_api-0.8.0}/tests/test_packaging.py +0 -0
  77. {macss_modular_api-0.7.2 → macss_modular_api-0.8.0}/tests/test_schema_conformance.py +0 -0
  78. {macss_modular_api-0.7.2 → macss_modular_api-0.8.0}/tests/test_use_case_exception.py +0 -0
  79. {macss_modular_api-0.7.2 → macss_modular_api-0.8.0}/tests/test_usecase.py +0 -0
  80. {macss_modular_api-0.7.2 → macss_modular_api-0.8.0}/tests/test_usecase_handler.py +0 -0
@@ -1,6 +1,6 @@
1
1
  Metadata-Version: 2.4
2
2
  Name: macss-modular-api
3
- Version: 0.7.2
3
+ Version: 0.8.0
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
@@ -4,7 +4,7 @@ build-backend = "setuptools.build_meta"
4
4
 
5
5
  [project]
6
6
  name = "macss-modular-api"
7
- version = "0.7.2"
7
+ version = "0.8.0"
8
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
9
  readme = "README.md"
10
10
  license = "MIT"
@@ -1,6 +1,6 @@
1
1
  Metadata-Version: 2.4
2
2
  Name: macss-modular-api
3
- Version: 0.7.2
3
+ Version: 0.8.0
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
@@ -17,6 +17,7 @@ src/modular_api/core/official_plugins.py
17
17
  src/modular_api/core/plugin.py
18
18
  src/modular_api/core/registry.py
19
19
  src/modular_api/core/request_pipeline_audit.py
20
+ src/modular_api/core/resolved_route.py
20
21
  src/modular_api/core/use_case_exception.py
21
22
  src/modular_api/core/usecase.py
22
23
  src/modular_api/core/usecase_handler.py
@@ -65,9 +66,12 @@ tests/test_clean_room_driver_isolation.py
65
66
  tests/test_dto_typing.py
66
67
  tests/test_field_example.py
67
68
  tests/test_fromjson_validation.py
69
+ tests/test_malformed_body.py
68
70
  tests/test_modular_api.py
69
71
  tests/test_module_builder.py
70
72
  tests/test_packaging.py
73
+ tests/test_routing.py
74
+ tests/test_routing_internal_middlewares.py
71
75
  tests/test_schema_conformance.py
72
76
  tests/test_use_case_exception.py
73
77
  tests/test_usecase.py
@@ -39,6 +39,7 @@ from modular_api.core.plugin import (
39
39
  RegisteredUseCaseView,
40
40
  RuntimePluginHost,
41
41
  )
42
+ from modular_api.core.resolved_route import ResolvedRoute, resolved_route
42
43
  from modular_api.core.registry import ApiRegistry, UseCaseDocMeta, UseCaseRegistration, api_registry
43
44
  from modular_api.core.use_case_exception import UseCaseException
44
45
  from modular_api.core.usecase import Input, Output, UseCase
@@ -72,6 +73,8 @@ __all__ = [
72
73
  "MetricSample",
73
74
  "MetricsRegistrar",
74
75
  "ModularApi",
76
+ "ResolvedRoute",
77
+ "resolved_route",
75
78
  "ModularLogger",
76
79
  "ModuleBuilder",
77
80
  "ModuleExtensionContribution",
@@ -126,7 +126,13 @@ class MetricRegistry:
126
126
 
127
127
  @staticmethod
128
128
  def _serialize_counter(parts: list[str], counter: Counter) -> None:
129
- for sample in counter.collect():
129
+ samples = counter.collect()
130
+ if not samples:
131
+ # Root counter with no labeled children — emit the root value, like a gauge.
132
+ # Once a labeled child exists, the root value is not serialized.
133
+ parts.append(f"{counter.name} {_format_value(counter.value)}")
134
+ return
135
+ for sample in samples:
130
136
  parts.append(
131
137
  f"{counter.name}{_format_labels(sample.labels)} {_format_value(sample.value)}"
132
138
  )
@@ -55,6 +55,7 @@ from modular_api.core.plugin import (
55
55
  order_plugins,
56
56
  )
57
57
  from modular_api.core.registry import api_registry
58
+ from modular_api.core.resolved_route import ResolvedRoute, route_resolver_middleware
58
59
  from modular_api.graphql.runtime import GraphqlOptions
59
60
 
60
61
 
@@ -93,6 +94,7 @@ class ModularApi:
93
94
 
94
95
  self._health_service = HealthService(version=version, release_id=self._release_id)
95
96
  self._module_routers: list[tuple[str, Router]] = []
97
+ self._resolved_routes: list[ResolvedRoute] = []
96
98
  self._custom_middlewares: list[type] = []
97
99
  self._plugins: list[Plugin] = []
98
100
 
@@ -141,6 +143,7 @@ class ModularApi:
141
143
  build(builder)
142
144
  mount_path = f"{self._normalize_base(self._base_path)}/{name}"
143
145
  self._module_routers.append((mount_path, builder.build_router()))
146
+ self._resolved_routes.extend(builder.resolved_routes)
144
147
  return self
145
148
 
146
149
  def use(self, middleware_factory: Any) -> ModularApi:
@@ -267,6 +270,10 @@ class ModularApi:
267
270
  for middleware in reversed(plugin_host.middlewares_for_slot("preRouting")):
268
271
  app.add_middleware(middleware.handler)
269
272
 
273
+ # 4a. Route resolution (#47): every plugin and custom middleware can read the use case
274
+ # that will run, so access control does not have to compare the raw path.
275
+ app.add_middleware(route_resolver_middleware(self._resolved_routes))
276
+
270
277
  # 4b. Error normalization middleware (wraps plugin middleware + routes)
271
278
  app.add_middleware(error_response_middleware())
272
279
 
@@ -26,6 +26,7 @@ from modular_api.core.registry import (
26
26
  UseCaseRegistration,
27
27
  api_registry,
28
28
  )
29
+ from modular_api.core.resolved_route import ResolvedRoute
29
30
  from modular_api.core.usecase import UseCase
30
31
  from modular_api.core.usecase_handler import usecase_handler
31
32
 
@@ -98,6 +99,7 @@ class ModuleBuilder:
98
99
  self._base_path = base_path
99
100
  self._module_name = module_name
100
101
  self._routes: list[Route] = []
102
+ self._resolved_routes: list[ResolvedRoute] = []
101
103
 
102
104
  # ── Public API ────────────────────────────────────────────
103
105
 
@@ -137,6 +139,15 @@ class ModuleBuilder:
137
139
  tags=[self._module_name],
138
140
  )
139
141
 
142
+ self._resolved_routes.append(
143
+ ResolvedRoute(
144
+ module=self._module_name,
145
+ use_case=clean_command,
146
+ method=method_upper,
147
+ path=full_path,
148
+ ),
149
+ )
150
+
140
151
  api_registry.routes.append(
141
152
  UseCaseRegistration(
142
153
  module=self._module_name,
@@ -151,6 +162,11 @@ class ModuleBuilder:
151
162
 
152
163
  return self
153
164
 
165
+ @property
166
+ def resolved_routes(self) -> list[ResolvedRoute]:
167
+ """The use cases registered on this module, as middlewares see them."""
168
+ return list(self._resolved_routes)
169
+
154
170
  def build_router(self) -> Router:
155
171
  """Create a Starlette Router containing all registered use-case routes."""
156
172
  return Router(routes=list(self._routes))
@@ -0,0 +1,67 @@
1
+ """The use case a request resolves to, readable by every middleware (#47).
2
+
3
+ A middleware that protects use cases should decide by what will run, not by comparing the raw
4
+ path. The framework resolves the request against its own route table before any plugin or
5
+ custom middleware runs and stores the result in the ASGI scope.
6
+
7
+ Mirrors ``resolvedRoute`` in Dart and TypeScript.
8
+ """
9
+
10
+ from __future__ import annotations
11
+
12
+ from collections.abc import Iterable
13
+ from dataclasses import dataclass
14
+
15
+ from starlette.requests import HTTPConnection
16
+ from starlette.types import ASGIApp, Receive, Scope, Send
17
+
18
+ ROUTE_SCOPE_KEY = "modular_api.route"
19
+
20
+
21
+ @dataclass(frozen=True)
22
+ class ResolvedRoute:
23
+ """A registered use case: its module, command, HTTP method and canonical path."""
24
+
25
+ module: str
26
+ use_case: str
27
+ method: str
28
+ path: str
29
+
30
+
31
+ def resolved_route(connection: HTTPConnection | Scope) -> ResolvedRoute | None:
32
+ """Return the use case this request will run, or ``None``.
33
+
34
+ ``None`` means no use case matches the method and path: a 404, a 405, or an operational
35
+ endpoint such as ``/health``. Deny by default: treat ``None`` as "not a public use case".
36
+ """
37
+ scope = connection.scope if isinstance(connection, HTTPConnection) else connection
38
+ route = scope.get(ROUTE_SCOPE_KEY)
39
+ return route if isinstance(route, ResolvedRoute) else None
40
+
41
+
42
+ def route_resolver_middleware(routes: Iterable[ResolvedRoute]) -> type:
43
+ """ASGI middleware that stores the resolved use case under ``ROUTE_SCOPE_KEY``.
44
+
45
+ Matching is exact on method and path, the same rule the router applies. HEAD resolves to the
46
+ GET use case, because Starlette runs the GET handler for it.
47
+ """
48
+ table = {(route.method, route.path): route for route in routes}
49
+
50
+ class _RouteResolverMiddleware:
51
+ def __init__(self, app: ASGIApp) -> None:
52
+ self.app = app
53
+
54
+ async def __call__(self, scope: Scope, receive: Receive, send: Send) -> None:
55
+ if scope["type"] == "http":
56
+ method = scope["method"]
57
+ path = scope["path"]
58
+ route = table.get((method, path))
59
+ if route is None and method == "HEAD":
60
+ route = table.get(("GET", path))
61
+ if route is not None:
62
+ scope[ROUTE_SCOPE_KEY] = route
63
+ else:
64
+ scope.pop(ROUTE_SCOPE_KEY, None)
65
+ await self.app(scope, receive, send)
66
+
67
+ return _RouteResolverMiddleware
@@ -52,6 +52,25 @@ def _format_validation_message(field: str, error_type: str) -> str:
52
52
  return f"Field '{field}' must be of type {openapi_type}"
53
53
 
54
54
 
55
+ def _bad_request(request: Request, message: str, cause: BaseException | None) -> Response:
56
+ """A 400 for a body that cannot become the use case input.
57
+
58
+ The cause goes to the log at warning level, never into the response: it is a client error,
59
+ not an unexpected server failure.
60
+ """
61
+ logger = getattr(request.state, LOGGER_STATE_KEY, None)
62
+ if logger is not None:
63
+ fields: dict[str, object] = {"status": 400}
64
+ if cause is not None:
65
+ fields["error"] = f"{type(cause).__name__}: {cause}"
66
+ logger.warning(message, fields=fields)
67
+ return Response(
68
+ content=json.dumps({"error": message}),
69
+ status_code=400,
70
+ media_type=_JSON_CONTENT_TYPE,
71
+ )
72
+
73
+
55
74
  def usecase_handler(factory: UseCaseFactory) -> Any:
56
75
  """Wraps a UseCase factory into an async Starlette endpoint.
57
76
 
@@ -78,7 +97,10 @@ def usecase_handler(factory: UseCaseFactory) -> Any:
78
97
  # a bare string, an array, a number — so the guard below is load-bearing. Declaring
79
98
  # the result a dict made a type checker call that guard dead code, which is exactly
80
99
  # backwards: the annotation was the thing that was wrong.
81
- payload: object = await request.json()
100
+ try:
101
+ payload: object = await request.json()
102
+ except ValueError: # json.JSONDecodeError, also for an empty body
103
+ return _bad_request(request, "Invalid JSON in request body", None)
82
104
 
83
105
  if not isinstance(payload, dict):
84
106
  return Response(
@@ -89,8 +111,16 @@ def usecase_handler(factory: UseCaseFactory) -> Any:
89
111
 
90
112
  data = cast("dict[str, Any]", payload)
91
113
 
92
- # 2. Build use case
93
- use_case = factory(data)
114
+ # 2. Build use case. `from_json` only maps untrusted input into the use case input, so a
115
+ # TypeError, KeyError or ValueError raised there means the body has the wrong shape:
116
+ # a client error. Pydantic's ValidationError and UseCaseException keep their own
117
+ # handling below.
118
+ try:
119
+ use_case = factory(data)
120
+ except (UseCaseException, ValidationError):
121
+ raise
122
+ except (TypeError, KeyError, ValueError) as exc:
123
+ return _bad_request(request, "Invalid request body", exc)
94
124
 
95
125
  # 2b. Inject request-scoped logger (if logging middleware placed one)
96
126
  logger = getattr(request.state, LOGGER_STATE_KEY, None)
@@ -0,0 +1,117 @@
1
+ """A body that cannot become the use case input is a client error: 400, not 500 (#44)."""
2
+
3
+ from __future__ import annotations
4
+
5
+ import json
6
+ from typing import Any
7
+
8
+ import pytest
9
+ from starlette.applications import Starlette
10
+ from starlette.routing import Route
11
+ from starlette.testclient import TestClient
12
+
13
+ from modular_api.core.use_case_exception import UseCaseException
14
+ from modular_api.core.usecase import Input, Output, UseCase
15
+ from modular_api.core.usecase_handler import usecase_handler
16
+
17
+
18
+ class CountInput(Input):
19
+ count: int = 0
20
+
21
+
22
+ class CountOutput(Output):
23
+ count: int = 0
24
+
25
+ @property
26
+ def status_code(self) -> int:
27
+ return 200
28
+
29
+
30
+ class CountUseCase(UseCase[CountInput, CountOutput]):
31
+ """A hand-written from_json that trusts the shape of the body, as fromJson code often does."""
32
+
33
+ def __init__(self, data: dict[str, Any]) -> None:
34
+ raw = data["count"] # KeyError when missing
35
+ if raw == "boom":
36
+ raise UseCaseException(status_code=422, message="No boom", error_code="BOOM")
37
+ self._input = CountInput(count=int(raw)) # ValueError / TypeError on a bad shape
38
+
39
+ @property
40
+ def input(self) -> CountInput:
41
+ return self._input
42
+
43
+ def validate(self) -> str | None:
44
+ return None
45
+
46
+ async def execute(self) -> CountOutput:
47
+ return CountOutput(count=self._input.count)
48
+
49
+
50
+ class _SpyLogger:
51
+ def __init__(self) -> None:
52
+ self.calls: list[tuple[str, str, dict[str, object] | None]] = []
53
+
54
+ def __getattr__(self, level: str) -> Any:
55
+ def log(msg: str, *, fields: dict[str, object] | None = None) -> None:
56
+ self.calls.append((level, msg, fields))
57
+
58
+ return log
59
+
60
+
61
+ def _client(logger: _SpyLogger | None = None) -> TestClient:
62
+ async def with_logger(request: Any) -> Any:
63
+ if logger is not None:
64
+ request.state.modular_logger = logger
65
+ return await usecase_handler(CountUseCase)(request)
66
+
67
+ app = Starlette(routes=[Route("/count", with_logger, methods=["POST"])])
68
+ return TestClient(app, raise_server_exceptions=False)
69
+
70
+
71
+ def _post(client: TestClient, body: str) -> Any:
72
+ return client.post("/count", content=body, headers={"content-type": "application/json"})
73
+
74
+
75
+ @pytest.mark.parametrize("body", ["{not json", "", "{", "nul"])
76
+ def test_unparseable_body_returns_400(body: str) -> None:
77
+ resp = _post(_client(), body)
78
+ assert resp.status_code == 400
79
+ assert resp.json() == {"error": "Invalid JSON in request body"}
80
+
81
+
82
+ @pytest.mark.parametrize("body", ["[1, 2]", '"text"', "42", "null", "true"])
83
+ def test_json_that_is_not_an_object_returns_400(body: str) -> None:
84
+ resp = _post(_client(), body)
85
+ assert resp.status_code == 400
86
+ assert resp.json() == {"error": "Request body must be a JSON object"}
87
+
88
+
89
+ @pytest.mark.parametrize(
90
+ "payload",
91
+ [
92
+ {}, # KeyError: missing field
93
+ {"count": "abc"}, # ValueError: int("abc")
94
+ {"count": [1]}, # TypeError: int([1])
95
+ ],
96
+ )
97
+ def test_error_inside_from_json_returns_400_without_details(payload: dict[str, Any]) -> None:
98
+ logger = _SpyLogger()
99
+ resp = _post(_client(logger), json.dumps(payload))
100
+
101
+ assert resp.status_code == 400
102
+ assert resp.json() == {"error": "Invalid request body"}
103
+ levels = [level for level, _, _ in logger.calls]
104
+ assert "warning" in levels
105
+ assert "error" not in levels
106
+
107
+
108
+ def test_use_case_exception_inside_from_json_keeps_its_status() -> None:
109
+ resp = _post(_client(), json.dumps({"count": "boom"}))
110
+ assert resp.status_code == 422
111
+ assert resp.json()["error"] == "BOOM"
112
+
113
+
114
+ def test_well_formed_body_still_succeeds() -> None:
115
+ resp = _post(_client(), json.dumps({"count": "7"}))
116
+ assert resp.status_code == 200
117
+ assert resp.json() == {"count": 7}
@@ -0,0 +1,158 @@
1
+ """Routing is strict, and middlewares can read the use case that will run (#47).
2
+
3
+ The variant table from the issue is kept as a regression test: a middleware that compares the
4
+ path exactly must not be bypassed by writing the path differently.
5
+ """
6
+
7
+ from __future__ import annotations
8
+
9
+ from typing import Any
10
+
11
+ import pytest
12
+ from starlette.middleware.base import BaseHTTPMiddleware
13
+ from starlette.requests import Request
14
+ from starlette.responses import JSONResponse, Response
15
+ from starlette.testclient import TestClient
16
+
17
+ from modular_api import ModularApi, ResolvedRoute, resolved_route
18
+ from modular_api.core.logger.logger import LogLevel
19
+ from modular_api.core.usecase import Input, Output, UseCase
20
+
21
+ CANONICAL = "/api/v1/payments/execute"
22
+ executions: list[str] = []
23
+ seen: list[ResolvedRoute | None] = []
24
+
25
+
26
+ class PayInput(Input):
27
+ note: str = ""
28
+
29
+
30
+ class PayOutput(Output):
31
+ paid: bool = True
32
+
33
+ @property
34
+ def status_code(self) -> int:
35
+ return 200
36
+
37
+
38
+ class ExecutePayment(UseCase[PayInput, PayOutput]):
39
+ def __init__(self, data: dict[str, Any]) -> None:
40
+ self._input = PayInput(note=str(data.get("note", "")))
41
+
42
+ @property
43
+ def input(self) -> PayInput:
44
+ return self._input
45
+
46
+ def validate(self) -> str | None:
47
+ return None
48
+
49
+ async def execute(self) -> PayOutput:
50
+ executions.append(self._input.note)
51
+ return PayOutput()
52
+
53
+
54
+ class ListPayments(ExecutePayment):
55
+ pass
56
+
57
+
58
+ class RequireToken(BaseHTTPMiddleware):
59
+ """The pattern the issue reproduces: protect one path by comparing it exactly."""
60
+
61
+ async def dispatch(self, request: Request, call_next: Any) -> Response:
62
+ seen.append(resolved_route(request))
63
+ if request.url.path == CANONICAL and request.headers.get("x-token") != "secret":
64
+ return JSONResponse({"error": "Unauthorized"}, status_code=401)
65
+ return await call_next(request)
66
+
67
+
68
+ @pytest.fixture
69
+ def client() -> TestClient:
70
+ executions.clear()
71
+ seen.clear()
72
+ api = ModularApi(base_path="/api/v1", log_level=LogLevel.emergency)
73
+ api.use(RequireToken)
74
+ api.module(
75
+ "payments",
76
+ lambda m: (
77
+ m.usecase("execute", ExecutePayment),
78
+ m.usecase("list", ListPayments, method="GET"),
79
+ ),
80
+ )
81
+ return TestClient(api.build(port=0), raise_server_exceptions=False)
82
+
83
+
84
+ def _post(client: TestClient, path: str, token: str | None = None) -> Any:
85
+ headers = {"content-type": "application/json"}
86
+ if token is not None:
87
+ headers["x-token"] = token
88
+ return client.post(path, content="{}", headers=headers, follow_redirects=False)
89
+
90
+
91
+ def test_canonical_path_runs_behind_the_middleware(client: TestClient) -> None:
92
+ assert _post(client, CANONICAL).status_code == 401
93
+ assert executions == []
94
+
95
+ resp = _post(client, CANONICAL, "secret")
96
+ assert resp.status_code == 200
97
+ assert executions == [""]
98
+
99
+
100
+ @pytest.mark.parametrize(
101
+ "path",
102
+ [
103
+ f"{CANONICAL}/",
104
+ "/API/v1/Payments/Execute",
105
+ "/api/v1/payments/Execute",
106
+ "/api/v1/payments//execute",
107
+ "/api/v1//payments/execute",
108
+ f"{CANONICAL}//",
109
+ "/api/v1/payments/%65xecute",
110
+ "/api/v1/payments%2Fexecute",
111
+ f"{CANONICAL};x",
112
+ "/api/v1/payments/./execute",
113
+ ],
114
+ )
115
+ def test_path_variant_does_not_reach_the_use_case_without_the_token(
116
+ client: TestClient, path: str
117
+ ) -> None:
118
+ resp = _post(client, path)
119
+
120
+ # 307 is Starlette's trailing-slash redirect: the handler does not run.
121
+ assert resp.status_code in (401, 404, 307)
122
+ assert executions == []
123
+
124
+
125
+ def test_middleware_reads_the_resolved_use_case(client: TestClient) -> None:
126
+ _post(client, CANONICAL, "secret")
127
+
128
+ assert seen == [
129
+ ResolvedRoute(module="payments", use_case="execute", method="POST", path=CANONICAL)
130
+ ]
131
+
132
+
133
+ def test_resolved_route_is_absent_on_a_404(client: TestClient) -> None:
134
+ resp = _post(client, "/api/v1/payments/missing", "secret")
135
+
136
+ assert resp.status_code == 404
137
+ assert seen == [None]
138
+
139
+
140
+ def test_resolved_route_is_absent_on_a_wrong_method(client: TestClient) -> None:
141
+ resp = client.get(CANONICAL, headers={"x-token": "secret"})
142
+
143
+ assert resp.status_code == 405
144
+ assert seen == [None]
145
+
146
+
147
+ def test_resolved_route_is_absent_for_operational_endpoints(client: TestClient) -> None:
148
+ assert client.get("/api/v1/health").status_code == 200
149
+ assert seen == [None]
150
+
151
+
152
+ def test_head_resolves_to_the_get_use_case(client: TestClient) -> None:
153
+ """HEAD runs the GET handler, so a guard must see the same route for it."""
154
+ client.head("/api/v1/payments/list")
155
+
156
+ assert seen == [
157
+ ResolvedRoute(module="payments", use_case="list", method="GET", path="/api/v1/payments/list")
158
+ ]
@@ -0,0 +1,79 @@
1
+ """Logging, metrics and tracing treat path variants consistently (#47).
2
+
3
+ The rule: an operational endpoint is excluded only on its exact path. A variant such as
4
+ ``/health/`` or ``/HEALTH`` is not that endpoint — the router rejects it (404, or Starlette's
5
+ trailing-slash redirect 307), so it is logged, traced and counted under ``route="UNMATCHED"``.
6
+ """
7
+
8
+ from __future__ import annotations
9
+
10
+ import json
11
+ from collections.abc import Iterator
12
+
13
+ import pytest
14
+ from opentelemetry.sdk.trace import TracerProvider
15
+ from opentelemetry.sdk.trace.export import SimpleSpanProcessor
16
+ from opentelemetry.sdk.trace.export.in_memory_span_exporter import InMemorySpanExporter
17
+ from starlette.testclient import TestClient
18
+
19
+ from modular_api import ModularApi
20
+ from modular_api.core.logger.logger import LogLevel
21
+ from modular_api.core.tracing.tracing_options import TracingOptions
22
+
23
+ _exporter = InMemorySpanExporter()
24
+ _provider = TracerProvider()
25
+ _provider.add_span_processor(SimpleSpanProcessor(_exporter))
26
+ _tracing = TracingOptions(tracer_provider=_provider)
27
+
28
+
29
+ @pytest.fixture(autouse=True)
30
+ def _clear_spans() -> Iterator[None]:
31
+ _exporter.clear()
32
+ yield
33
+
34
+
35
+ @pytest.fixture
36
+ def client() -> TestClient:
37
+ api = ModularApi(
38
+ base_path="/api", log_level=LogLevel.info, metrics_enabled=True, tracing=_tracing
39
+ )
40
+ return TestClient(api.build(port=0), raise_server_exceptions=False)
41
+
42
+
43
+ def _completed(capsys: pytest.CaptureFixture[str]) -> list[dict[str, object]]:
44
+ lines = [line for line in capsys.readouterr().out.splitlines() if line.startswith("{")]
45
+ logs = [json.loads(line) for line in lines]
46
+ return [log for log in logs if log.get("msg") == "request completed"]
47
+
48
+
49
+ def _request_metrics(client: TestClient) -> list[str]:
50
+ text = client.get("/api/metrics").text
51
+ return [line for line in text.splitlines() if line.startswith("http_requests_total{")]
52
+
53
+
54
+ def test_exact_operational_path_stays_excluded(
55
+ client: TestClient, capsys: pytest.CaptureFixture[str]
56
+ ) -> None:
57
+ assert client.get("/api/health").status_code == 200
58
+
59
+ assert _completed(capsys) == []
60
+ assert _exporter.get_finished_spans() == ()
61
+ assert _request_metrics(client) == []
62
+
63
+
64
+ @pytest.mark.parametrize(
65
+ ("path", "status"),
66
+ [("/api/health/", 307), ("/api/HEALTH", 404), ("/api//health", 404)],
67
+ )
68
+ def test_variant_is_logged_traced_and_unmatched(
69
+ client: TestClient, capsys: pytest.CaptureFixture[str], path: str, status: int
70
+ ) -> None:
71
+ assert client.get(path, follow_redirects=False).status_code == status
72
+
73
+ completed = _completed(capsys)
74
+ assert len(completed) == 1
75
+ assert completed[0]["status"] == status
76
+ assert len(_exporter.get_finished_spans()) == 1
77
+ assert _request_metrics(client) == [
78
+ f'http_requests_total{{method="GET",route="UNMATCHED",status_code="{status}"}} 1'
79
+ ]