forked from mtusi2026/mtusi2026lab4
Перенести рабочий стенд lab3 в репозиторий lab4.
API, Postgres, Redis и HAProxy остаются базой для вложений: сессии и история уже общие для нескольких реплик.
This commit is contained in:
@@ -0,0 +1,48 @@
|
||||
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
|
||||
Reference in New Issue
Block a user