"""X-Request-Id и X-Instance-Id на каждом ответе, одна строка access-лога. Чистое ASGI-middleware: прямой вызов приложения и обёртка send. Без дочерней задачи и потока сообщений на каждый запрос: это уменьшает накладные расходы слоя, исследуемые в треке «5». Id запроса: входящий `X-Request-Id`, если он короткий и безопасный (`[A-Za-z0-9._-]{1,64}`), иначе новый uuid4. Так id проходит через балансировщик, а мусор из заголовка не попадает в логи. Тот же id — в заголовке ответа, в `request_id` тела ошибки и в каждой строке лога этого запроса. `X-Instance-Id` (лаба 3) — реплика, которая обслужила запрос: одно значение на процесс (`Settings.instance_id`). Ответы, которые создаёт сам HAProxy (502/503/504), его не имеют — контракт это допускает. """ import re import time from uuid import uuid4 from starlette.datastructures import Headers, MutableHeaders from starlette.types import ASGIApp, Message, Receive, Scope, Send from src.constants import HEALTH_PATHS, INSTANCE_ID_HEADER, REQUEST_ID_HEADER from src.log import get_logger, request_id_var log = get_logger("src.http") _SAFE_REQUEST_ID = re.compile(r"[A-Za-z0-9._-]{1,64}") def _request_id(scope: Scope) -> str: incoming = Headers(scope=scope).get(REQUEST_ID_HEADER) if incoming and _SAFE_REQUEST_ID.fullmatch(incoming): return incoming return uuid4().hex class RequestIdMiddleware: def __init__(self, app: ASGIApp, *, instance_id: str) -> None: self.app = app self.instance_id = instance_id async def __call__(self, scope: Scope, receive: Receive, send: Send) -> None: if scope["type"] != "http": await self.app(scope, receive, send) return request_id = _request_id(scope) # request.state.request_id — для обработчиков ошибок scope.setdefault("state", {})["request_id"] = request_id # не сбрасывается: у каждого запроса в uvicorn своя задача, а # traceback непредвиденной ошибки uvicorn пишет уже после выхода # отсюда, и в нём тоже нужен rid request_id_var.set(request_id) status_code = 500 started = time.perf_counter() async def send_with_ids(message: Message) -> None: nonlocal status_code if message["type"] == "http.response.start": status_code = message["status"] headers = MutableHeaders(scope=message) if REQUEST_ID_HEADER not in headers: headers.append(REQUEST_ID_HEADER, request_id) if INSTANCE_ID_HEADER not in headers: headers.append(INSTANCE_ID_HEADER, self.instance_id) await send(message) try: await self.app(scope, receive, send_with_ids) finally: # health дёргают healthcheck и балансировщик: в лог не пишем. # Путь без query; тела и заголовки идентификации не логируются if scope["path"] not in HEALTH_PATHS: log.info( "%s %s -> %d (%.1f ms)", scope["method"], scope["path"], status_code, (time.perf_counter() - started) * 1000, )