import uuid from collections.abc import Callable from fastapi import Request, Response from app.core.constants import HttpHeader from app.core.http.request_context import reset_request_id, set_request_id async def request_id_middleware(request: Request, call_next: Callable) -> Response: request_id = request.headers.get(HttpHeader.X_REQUEST_ID) or uuid.uuid4().hex token = set_request_id(request_id) try: response = await call_next(request) response.headers[HttpHeader.X_REQUEST_ID] = request_id return response finally: reset_request_id(token)