"""ASGI-middleware: X-Request-Id, ответ 500 при сбое и строка лога на запрос.""" import time import traceback import uuid from starlette.datastructures import MutableHeaders from starlette.types import ASGIApp, Message, Receive, Scope, Send from .errors import error_response from .logging_setup import get_logger class RequestContextMiddleware: """Request id, обработка необработанных исключений, журнал запросов.""" def __init__(self, app: ASGIApp) -> None: """Сохранить следующее приложение в цепочке.""" self.app = app async def __call__(self, scope: Scope, receive: Receive, send: Send) -> None: """Обработать один HTTP-запрос.""" if scope["type"] != "http": await self.app(scope, receive, send) return request_id = uuid.uuid4().hex scope.setdefault("state", {})["request_id"] = request_id started = time.perf_counter() state = {"status": 500, "response_started": False} async def send_with_request_id(message: Message) -> None: if message["type"] == "http.response.start": state["status"] = message["status"] state["response_started"] = True MutableHeaders(scope=message)["X-Request-Id"] = request_id await send(message) try: await self.app(scope, receive, send_with_request_id) except Exception as exc: frames = traceback.extract_tb(exc.__traceback__) where = " <- ".join( "%s:%s" % (f.filename.split("/")[-1], f.lineno) for f in reversed(frames[-3:]) ) get_logger().error( "unhandled_error request_id=%s type=%s where=%s", request_id, type(exc).__name__, where, ) if state["response_started"]: raise response = error_response( request_id, 500, "internal_error", "Внутренняя ошибка сервера" ) await response(scope, receive, send_with_request_id) finally: get_logger().info( "request request_id=%s method=%s path=%s status=%s duration_ms=%.1f", request_id, scope.get("method"), scope.get("path"), state["status"], (time.perf_counter() - started) * 1000, )