feat: carry lab 2 over and add X-Instance-Id and idempotency keys

- carry the lab 2 solution over and plan lab 3 (PLAN.md, OpenSpec
  change instance-id-idempotency)
- rename the compose project to mtusi-lab3 and the image to :lab3
- add X-Instance-Id to every response and instance_id to every log
  record ([app] instance_id, hostname by default)
- require Idempotency-Key on POST messages: keys table in Postgres,
  key and message in one transaction, replay returns the same 201,
  another body gets 409, TTL from [idempotency] ttl_seconds
- send the key from student-tests, k6 scenarios and the skill driver;
  add idempotency, X-Instance-Id, key race and fault tests

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
2026-10-08 19:42:36 +03:00
co-authored by Claude Opus 5.5
parent 0ab3a341aa
commit af4bca08c9
294 changed files with 36586 additions and 15 deletions
+106
View File
@@ -0,0 +1,106 @@
"""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,
),
)