Files
mtusi2026lab2/app/middleware.py
T
dawuduk 8f1d7e27c7
Skeleton contracts / contracts (pull_request) Canceled after 0s
Skeleton contracts / application (pull_request) Canceled after 0s
reworked
2026-11-07 11:56:38 +03:00

42 lines
1.5 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.errors import AppError, error_response, from_app_error
logger = logging.getLogger("messenger.access")
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",):
return error_response(503, "service is shutting down", request_id)
started = time.perf_counter()
try:
response = await call_next(request)
except AppError as exc:
return from_app_error(exc, request_id)
except Exception:
logger.exception("request_id=%s unhandled error path=%s", request_id, request.url.path)
return error_response(500, "internal error", request_id)
elapsed_ms = (time.perf_counter() - started) * 1000
response.headers["X-Request-Id"] = 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