forked from mtusi2026/mtusi2026lab2
93 lines
3.6 KiB
Python
93 lines
3.6 KiB
Python
"""Внешний ASGI-слой: X-Request-Id (в том числе на 500) и структурный access-лог."""
|
|
from __future__ import annotations
|
|
|
|
import logging
|
|
import re
|
|
import time
|
|
import uuid
|
|
from typing import Any, Awaitable, Callable, MutableMapping
|
|
|
|
from .context import REQUEST_ID, USER_ID, context_of
|
|
from .logging_setup import log
|
|
|
|
SAFE_REQUEST_ID = re.compile(r"^[A-Za-z0-9._:-]{1,128}$")
|
|
|
|
Scope = MutableMapping[str, Any]
|
|
Message = MutableMapping[str, Any]
|
|
Receive = Callable[[], Awaitable[Message]]
|
|
Send = Callable[[Message], Awaitable[None]]
|
|
ASGIApp = Callable[[Scope, Receive, Send], Awaitable[None]]
|
|
|
|
|
|
def incoming_request_id(scope: Scope) -> str | None:
|
|
"""Возвращает заголовок клиента, если он безопасен для логирования и ответа."""
|
|
for name, value in scope.get("headers") or ():
|
|
if name.lower() != b"x-request-id":
|
|
continue
|
|
try:
|
|
candidate = value.decode("ascii")
|
|
except UnicodeDecodeError:
|
|
return None
|
|
return candidate if SAFE_REQUEST_ID.match(candidate) else None
|
|
return None
|
|
|
|
|
|
def set_response_header(message: Message, name: bytes, value: bytes) -> None:
|
|
"""Идемпотентно выставляет заголовок в ASGI-сообщении ответа."""
|
|
headers = message.setdefault("headers", [])
|
|
lowered = name.lower()
|
|
for index, (key, _) in enumerate(headers):
|
|
if key.lower() == lowered:
|
|
headers[index] = (name, value)
|
|
return
|
|
headers.append((name, value))
|
|
|
|
|
|
class RequestContextMiddleware:
|
|
"""Присваивает запросу идентификатор, гарантирует заголовок и пишет access-лог."""
|
|
|
|
def __init__(self, app: ASGIApp, logger: logging.Logger) -> None:
|
|
self._app = app
|
|
self._logger = logger
|
|
|
|
async def __call__(self, scope: Scope, receive: Receive, send: Send) -> None:
|
|
if scope["type"] != "http":
|
|
await self._app(scope, receive, send)
|
|
return
|
|
|
|
request_id = incoming_request_id(scope) or uuid.uuid4().hex
|
|
context = context_of(scope)
|
|
context[REQUEST_ID] = request_id
|
|
started = time.perf_counter()
|
|
status_holder: dict[str, int] = {}
|
|
|
|
async def send_with_request_id(message: Message) -> None:
|
|
if message["type"] == "http.response.start":
|
|
status_holder["status"] = int(message["status"])
|
|
set_response_header(message, b"x-request-id", request_id.encode("ascii"))
|
|
await send(message)
|
|
|
|
try:
|
|
await self._app(scope, receive, send_with_request_id)
|
|
finally:
|
|
self._write_access_log(scope, status_holder.get("status"), started)
|
|
|
|
def _write_access_log(self, scope: Scope, status: int | None, started: float) -> None:
|
|
context = context_of(scope)
|
|
# Логируется шаблон маршрута, а не сырой путь: query-строка в лог не попадает.
|
|
route = getattr(scope.get("route"), "path", None)
|
|
endpoint = scope.get("endpoint")
|
|
log(
|
|
self._logger,
|
|
logging.INFO,
|
|
"request",
|
|
request_id=context.get(REQUEST_ID),
|
|
method=scope.get("method"),
|
|
route=route,
|
|
operation=None if endpoint is None else getattr(endpoint, "__name__", None),
|
|
matched=route is not None,
|
|
status=status,
|
|
duration_ms=round((time.perf_counter() - started) * 1000, 3),
|
|
user_id=context.get(USER_ID),
|
|
)
|