diff --git a/docs/migration/to-2.x.md b/docs/migration/to-2.x.md index 67c535e..9dd367b 100644 --- a/docs/migration/to-2.x.md +++ b/docs/migration/to-2.x.md @@ -320,6 +320,14 @@ alternatives into entries, use `\x2c` for a literal comma, and rewrite bounded repetitions such as `a{1,3}` as `aa?a?`. Litestar accepts commas ([#417](https://github.com/modern-python/lite-bootstrap/pull/417)). +### Health and metrics trace exclusions + +Generated OpenTelemetry exclusions match the configured health and metrics +endpoints with or without a trailing slash, including a health endpoint at `/`. +Routes such as `/health/details` and `/metrics/report` now produce spans. Proxy +prefixes are respected and user-supplied exclusion regexes keep their behavior +([#453](https://github.com/modern-python/lite-bootstrap/issues/453)). + ## CORS methods on FastAPI and Litestar `cors_allowed_methods` defaults to `["*"]`. Configuring origins without a method diff --git a/lite_bootstrap/bootstrappers/litestar_bootstrapper.py b/lite_bootstrap/bootstrappers/litestar_bootstrapper.py index d1fad80..46241e3 100644 --- a/lite_bootstrap/bootstrappers/litestar_bootstrapper.py +++ b/lite_bootstrap/bootstrappers/litestar_bootstrapper.py @@ -361,18 +361,10 @@ def dependencies_installed() -> bool: return OpenTelemetryInstrument.dependencies_installed() and import_checker.is_litestar_opentelemetry_installed def _build_excluded_path_patterns(self) -> list[str]: - """Anchored patterns for the derived paths, plus the caller's own entries verbatim. - - The trailing slash is stripped and matched optionally, so ``/custom-health/`` excludes the - path with or without it. Anchoring is needed because Litestar searches its ``exclude`` - patterns unanchored: a bare ``/custom-health`` would also silence ``/custom-healthy``. - Caller-supplied entries stay untouched because they are regexes. - """ + """Match derived endpoints with an optional trailing slash, preserving the caller's regexes.""" anchored_patterns: typing.Final = { - rf"^{re.escape(normalized_path)}(?:/|$)" + rf"^{re.escape(excluded_path.rstrip('/'))}/?$" for excluded_path in self._build_infrastructure_excluded_paths() - # A bare "/" would anchor to every URL, so it is dropped along with empty values. - if (normalized_path := excluded_path.rstrip("/")) } return sorted(anchored_patterns | set(self.bootstrap_config.opentelemetry_excluded_urls)) diff --git a/lite_bootstrap/helpers/opentelemetry_asgi.py b/lite_bootstrap/helpers/opentelemetry_asgi.py index 99016dd..7dfea0d 100644 --- a/lite_bootstrap/helpers/opentelemetry_asgi.py +++ b/lite_bootstrap/helpers/opentelemetry_asgi.py @@ -14,12 +14,13 @@ class ExcludeInfrastructureTelemetry: def __init__(self, app: "OpenTelemetryMiddleware", excluded_paths: set[str]) -> None: self.app = app - self.excluded_paths = tuple(path for value in excluded_paths if (path := value.rstrip("/"))) + normalized_paths = {value.rstrip("/") for value in excluded_paths} + self.excluded_paths = normalized_paths | {f"{path}/" for path in normalized_paths} async def __call__(self, scope: "Scope", receive: "Receive", send: "Send") -> None: if scope["type"] in ("http", "websocket"): path = get_route_path(scope) - if any(path == excluded or path.startswith(excluded + "/") for excluded in self.excluded_paths): + if path in self.excluded_paths: await self.app.app(scope, receive, send) return await self.app(scope, receive, send) diff --git a/tests/test_fastapi_bootstrap.py b/tests/test_fastapi_bootstrap.py index d4dc1a9..40fc76e 100644 --- a/tests/test_fastapi_bootstrap.py +++ b/tests/test_fastapi_bootstrap.py @@ -706,7 +706,8 @@ async def from_env() -> str: try: with TestClient(bootstrapped_application, root_path=root_path) as client: for path in paths: - client.get(path, headers={"host": host}, follow_redirects=False) + response = client.get(path, headers={"host": host}, follow_redirects=False) + assert response.is_success or response.is_redirect finally: bootstrapper.teardown() return [span.name for span in exporter.get_finished_spans() if span.kind == SpanKind.SERVER] @@ -734,6 +735,38 @@ def test_fastapi_otel_leaves_the_health_check_untraced_by_default() -> None: assert _server_span_names_for(config, ["/custom-health/", "/custom-healthy"]) == ["GET /custom-healthy"] +@pytest.mark.parametrize("root_path", ["", "/api"]) +@pytest.mark.parametrize(("health_path", "metrics_path"), [("/health", "/metrics"), ("/", "/metrics/")]) +def test_fastapi_otel_excludes_only_exact_infrastructure_endpoints( + health_path: str, metrics_path: str, root_path: str +) -> None: + config = FastAPIConfig( + logging_enabled=False, + opentelemetry_log_traces=True, + health_checks_path=health_path, + prometheus_metrics_path=metrics_path, + opentelemetry_excluded_urls=[r"/items/\d+$"], + ) + + @config.app.get("/health/details") + @config.app.get("/health//") + @config.app.get("/metrics/report") + @config.app.get("/items/42") + @config.app.get("/items/abc") + async def work() -> str: + return "ok" + + paths = sorted({health_path, metrics_path, f"{health_path.rstrip('/')}/", f"{metrics_path.rstrip('/')}/"}) + paths.extend(["/health//", "/health/details", "/metrics/report", "/items/42", "/items/abc"]) + + assert sorted(_server_span_names_for(config, [f"{root_path}{path}" for path in paths], root_path=root_path)) == [ + "GET /health//", + "GET /health/details", + "GET /items/abc", + "GET /metrics/report", + ] + + def test_fastapi_otel_host_header_cannot_exclude_a_work_request(fastapi_config: FastAPIConfig) -> None: assert _server_span_names_for(fastapi_config, ["/custom-healthy"], host="x/custom-health") == [ "GET /custom-healthy" diff --git a/tests/test_litestar_bootstrap.py b/tests/test_litestar_bootstrap.py index 1a29912..f736e1f 100644 --- a/tests/test_litestar_bootstrap.py +++ b/tests/test_litestar_bootstrap.py @@ -651,6 +651,38 @@ def _server_spans(exporter: InMemorySpanExporter) -> list[ReadableSpan]: return [span for span in exporter.get_finished_spans() if span.kind == SpanKind.SERVER] +@pytest.mark.parametrize("root_path", ["", "/api"]) +@pytest.mark.parametrize(("health_path", "metrics_path"), [("/health", "/metrics"), ("/", "/metrics/")]) +def test_litestar_otel_excludes_only_exact_infrastructure_endpoints( + health_path: str, metrics_path: str, root_path: str +) -> None: + @litestar.get(["/health/details", "/metrics/report", "/items/42", "/items/abc"]) + async def work() -> str: + return "ok" + + config = LitestarConfig( + application_config=AppConfig(route_handlers=[work]), + logging_enabled=False, + opentelemetry_log_traces=True, + health_checks_path=health_path, + prometheus_metrics_path=metrics_path, + opentelemetry_excluded_urls=[r"/items/\d+$"], + ) + application, exporter = _bootstrap_with_span_exporter(config) + paths = sorted({health_path, metrics_path, f"{health_path.rstrip('/')}/", f"{metrics_path.rstrip('/')}/"}) + paths.extend(["/health/details", "/metrics/report", "/items/42", "/items/abc"]) + + with TestClient(app=application, root_path=root_path) as client: + for path in paths: + assert client.get(path).status_code == status_codes.HTTP_200_OK + + assert sorted(span.name for span in _server_spans(exporter)) == [ + "GET /health/details", + "GET /items/abc", + "GET /metrics/report", + ] + + def test_litestar_prometheus_excludes_infrastructure_and_user_paths() -> None: suffix = uuid.uuid4().hex normal_path = f"/health-{suffix}/report"