Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
8 changes: 8 additions & 0 deletions docs/migration/to-2.x.md
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down
12 changes: 2 additions & 10 deletions lite_bootstrap/bootstrappers/litestar_bootstrapper.py
Original file line number Diff line number Diff line change
Expand Up @@ -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))

Expand Down
5 changes: 3 additions & 2 deletions lite_bootstrap/helpers/opentelemetry_asgi.py
Original file line number Diff line number Diff line change
Expand Up @@ -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)
Expand Down
35 changes: 34 additions & 1 deletion tests/test_fastapi_bootstrap.py
Original file line number Diff line number Diff line change
Expand Up @@ -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]
Expand Down Expand Up @@ -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"
Expand Down
32 changes: 32 additions & 0 deletions tests/test_litestar_bootstrap.py
Original file line number Diff line number Diff line change
Expand Up @@ -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"
Expand Down
Loading