- carry the lab 3 solution over from mtusi2026lab3-safronov (solution/bvt2301-safronov, ce89eba): src, migrations, student-tests, bench, openspec, .claude, infra/haproxy and infra/valkey, own scripts, Dockerfile, compose, pyproject and uv lock - merge Makefile, .gitignore and .dockerignore (the lab 3 versions only add lines to the skeleton, which is the same in lab 4) and .env.example (lab 4 skeleton names listed in the header) - rename the compose project to mtusi-lab4 and the image to :lab4 so the stand does not reuse the lab 3 containers and volumes - update AGENTS.md for lab 4: current lab, origin commit, contract and test files of the new skeleton Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
107 lines
4.5 KiB
Python
107 lines
4.5 KiB
Python
"""Request id, instance id и итоговая запись о запросе — чистое ASGI-middleware.
|
||
|
||
Без `BaseHTTPMiddleware`: тот на каждый запрос создаёт отдельную задачу и
|
||
поток памяти для тела ответа (design, решение 7).
|
||
"""
|
||
|
||
import time
|
||
from uuid import uuid4
|
||
|
||
from fastapi import FastAPI
|
||
from fastapi.routing import iter_route_contexts
|
||
from starlette.types import ASGIApp, Message, Receive, Scope, Send
|
||
|
||
from src.config import settings
|
||
from src.infra.logger import AbstractLogger, get_logger, http_request_id
|
||
from src.utils.constants import (
|
||
HEALTH_PATHS,
|
||
INSTANCE_ID_HEADER,
|
||
REQUEST_ID_HEADER,
|
||
)
|
||
|
||
logger: AbstractLogger = get_logger().bind(middleware="http")
|
||
|
||
_REQUEST_ID_HEADER = REQUEST_ID_HEADER.lower().encode("ascii")
|
||
_INSTANCE_ID_HEADER = INSTANCE_ID_HEADER.lower().encode("ascii")
|
||
# одно значение на процесс: вычислено при загрузке настроек
|
||
_INSTANCE_ID = settings.app.instance_id.encode("ascii")
|
||
_UNMATCHED_PATH = "<unmatched>"
|
||
|
||
|
||
def _route_templates(app: FastAPI) -> dict[int, str]:
|
||
"""id маршрута → полный шаблон пути (`/api/v1/chats/{chat_id}`).
|
||
|
||
С FastAPI 0.137 роутеры включаются деревом, и `scope["route"].path`
|
||
не содержит префикс `include_router`: префикс принадлежит включению,
|
||
а не маршруту. Полный путь даёт публичный `iter_route_contexts`.
|
||
Каждый наш роутер включён один раз, поэтому id маршрута однозначен.
|
||
"""
|
||
return {
|
||
id(context.original_route): context.path_format
|
||
for context in iter_route_contexts(app.routes)
|
||
if context.path_format is not None
|
||
}
|
||
|
||
|
||
class RequestContextMiddleware:
|
||
def __init__(self, app: ASGIApp) -> None:
|
||
self.app = app
|
||
# строится на первом запросе: к нему все роутеры уже подключены
|
||
self._route_templates: dict[int, str] | None = None
|
||
|
||
async def __call__(
|
||
self,
|
||
scope: Scope,
|
||
receive: Receive,
|
||
send: Send,
|
||
) -> None:
|
||
if scope["type"] != "http":
|
||
await self.app(scope, receive, send)
|
||
return
|
||
|
||
request_id = uuid4().hex
|
||
# request.state.request_id — для обработчиков ошибок
|
||
scope.setdefault("state", {})["request_id"] = request_id
|
||
# не сбрасывается: у каждого запроса в uvicorn своя задача, а
|
||
# traceback непредвиденной ошибки uvicorn пишет после выхода
|
||
# отсюда и тоже должен получить request_id
|
||
http_request_id.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 = list(message.get("headers", []))
|
||
present = {name.lower() for name, _ in headers}
|
||
if _REQUEST_ID_HEADER not in present:
|
||
headers.append(
|
||
(_REQUEST_ID_HEADER, request_id.encode("ascii")),
|
||
)
|
||
if _INSTANCE_ID_HEADER not in present:
|
||
headers.append((_INSTANCE_ID_HEADER, _INSTANCE_ID))
|
||
message = {**message, "headers": headers}
|
||
await send(message)
|
||
|
||
try:
|
||
await self.app(scope, receive, send_with_ids)
|
||
finally:
|
||
if scope["path"] not in HEALTH_PATHS:
|
||
# шаблон пути, а не фактический: id в пути не попадают в лог
|
||
if self._route_templates is None:
|
||
self._route_templates = _route_templates(scope["app"])
|
||
logger.info(
|
||
"HTTP request completed",
|
||
method=scope["method"],
|
||
path=self._route_templates.get(
|
||
id(scope.get("route")),
|
||
_UNMATCHED_PATH,
|
||
),
|
||
status=status_code,
|
||
duration_ms=round(
|
||
(time.perf_counter() - started) * 1000,
|
||
3,
|
||
),
|
||
)
|