"""Per-request trace context with a bounded, non-secret public identifier.""" from __future__ import annotations import uuid from collections.abc import Awaitable, Callable from fastapi import Request, Response REQUEST_ID_HEADER = "x-request-id" type CallNext = Callable[[Request], Awaitable[Response]] def _request_id(value: str | None) -> str: if value is not None: try: return str(uuid.UUID(value)) except (ValueError, AttributeError): pass return str(uuid.uuid4()) async def trace_request(request: Request, call_next: CallNext) -> Response: """Attach a UUID trace ID and return it without trusting arbitrary input.""" trace_id = _request_id(request.headers.get(REQUEST_ID_HEADER)) request.state.trace_id = trace_id response = await call_next(request) response.headers[REQUEST_ID_HEADER] = trace_id return response