Files
mtusi2026lab3/app/middleware.py
dawuduk 3601ca5443 Перенести API с общими сессиями и идемпотентной отправкой сообщения.
Реплика больше не держит корректность в своей памяти: сессия в Redis, а повтор POST сообщения фиксируется в Postgres вместе с X-Instance-Id.
2026-11-07 12:46:37 +03:00

49 lines
1.7 KiB
Python

import logging
import time
import uuid
from typing import Callable
from starlette.middleware.base import BaseHTTPMiddleware
from starlette.requests import Request
from starlette.responses import Response
from app.config import INSTANCE_ID
from app.errors import AppError, error_response, from_app_error
logger = logging.getLogger("messenger.access")
def _stamp(response: Response, request_id: str) -> Response:
response.headers["X-Request-Id"] = request_id
response.headers["X-Instance-Id"] = INSTANCE_ID
return response
class RequestContextMiddleware(BaseHTTPMiddleware):
async def dispatch(self, request: Request, call_next: Callable) -> Response:
request_id = request.headers.get("X-Request-Id") or str(uuid.uuid4())
request.state.request_id = request_id
if request.app.state.shutting_down and request.url.path not in ("/health/live", "/health/ready"):
return _stamp(error_response(503, "service is shutting down", request_id), request_id)
started = time.perf_counter()
try:
response = await call_next(request)
except AppError as exc:
return _stamp(from_app_error(exc, request_id), request_id)
except Exception:
logger.exception("request_id=%s unhandled error path=%s", request_id, request.url.path)
return _stamp(error_response(500, "internal error", request_id), request_id)
elapsed_ms = (time.perf_counter() - started) * 1000
_stamp(response, request_id)
logger.info(
"request_id=%s method=%s path=%s status=%s duration_ms=%.2f",
request_id,
request.method,
request.url.path,
response.status_code,
elapsed_ms,
)
return response