Coverage for src / lexigram / admin / middleware / correlation.py: 0%

16 statements  

« prev     ^ index     » next       coverage.py v7.13.5, created at 2026-08-11 02:25 +0800

1"""Correlation ID middleware — sets and echoes X-Request-ID.""" 

2 

3from __future__ import annotations 

4 

5from starlette.middleware.base import BaseHTTPMiddleware, RequestResponseEndpoint 

6from starlette.requests import Request 

7from starlette.responses import Response 

8from starlette.types import ASGIApp 

9 

10from lexigram.admin.audit.correlation import new_correlation_id, set_correlation_id 

11 

12 

13class AdminCorrelationMiddleware(BaseHTTPMiddleware): 

14 """Middleware that propagates and echoes correlation IDs. 

15 

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 """ 

20 

21 def __init__(self, app: ASGIApp) -> None: 

22 super().__init__(app) 

23 

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 

32 

33 

34__all__ = ["AdminCorrelationMiddleware"]