Coverage for src/lexigram/admin/middleware/correlation.py: 0%
16 statements
« prev ^ index » next coverage.py v7.15.4, created at 2026-08-24 23:18 +0800
« prev ^ index » next coverage.py v7.15.4, created at 2026-08-24 23:18 +0800
1"""Correlation ID middleware — sets and echoes X-Request-ID."""
3from __future__ import annotations
5from starlette.middleware.base import BaseHTTPMiddleware, RequestResponseEndpoint
6from starlette.requests import Request
7from starlette.responses import Response
8from starlette.types import ASGIApp
10from lexigram.admin.audit.correlation import new_correlation_id, set_correlation_id
13class AdminCorrelationMiddleware(BaseHTTPMiddleware):
14 """Middleware that propagates and echoes correlation IDs.
16 Reads the incoming ``X-Request-ID`` header (if present) or generates
17 a new UUID hex identifier, sets it on the current contextvar, and
18 echoes it back on the response.
19 """
21 def __init__(self, app: ASGIApp) -> None:
22 super().__init__(app)
24 async def dispatch(
25 self, request: Request, call_next: RequestResponseEndpoint
26 ) -> Response:
27 cid = request.headers.get("X-Request-ID") or new_correlation_id()
28 set_correlation_id(cid)
29 response = await call_next(request)
30 response.headers["X-Request-ID"] = cid
31 return response
34__all__ = ["AdminCorrelationMiddleware"]