from __future__ import annotations import logging import sys import time import uuid from starlette.middleware.base import BaseHTTPMiddleware, RequestResponseEndpoint from starlette.requests import Request from starlette.responses import Response from app.config import INSTANCE_ID logging.basicConfig( level=logging.INFO, format="%(asctime)s [%(levelname)s] %(name)s: %(message)s", stream=sys.stdout, ) logger = logging.getLogger("app.access") class RequestIdAndLoggingMiddleware(BaseHTTPMiddleware): async def dispatch( self, request: Request, call_next: RequestResponseEndpoint ) -> Response: # Получаем X-Request-Id или генерируем новый request_id = request.headers.get("X-Request-Id") if not request_id or not request_id.strip(): request_id = str(uuid.uuid4()) request.state.request_id = request_id start_time = time.monotonic() if request.method in ("POST", "PUT", "PATCH") and request.url.path != "/api/v1/auth/sessions": is_attachment_upload = ( request.method == "POST" and "/attachments" in request.url.path and request.url.path.startswith("/api/v1/chats/") ) ct = request.headers.get("content-type") ct_clean = ct.split(";")[0].strip().lower() if ct else "" if is_attachment_upload: if not ct or ct_clean not in ("image/png", "image/jpeg"): from fastapi import status from app.errors import make_error_response from app.schemas import ErrorCode return make_error_response( status.HTTP_415_UNSUPPORTED_MEDIA_TYPE, ErrorCode.UNSUPPORTED_MEDIA_TYPE, f"Неподдерживаемый тип содержимого '{ct}'. Ожидается image/png или image/jpeg", request_id, ) elif ct and ct_clean != "application/json": from fastapi import status from app.errors import make_error_response from app.schemas import ErrorCode return make_error_response( status.HTTP_415_UNSUPPORTED_MEDIA_TYPE, ErrorCode.UNSUPPORTED_MEDIA_TYPE, f"Неподдерживаемый тип содержимого '{ct}'. Ожидается application/json", request_id, ) try: response = await call_next(request) except Exception: # Исключение перехватится exception_handler duration_ms = (time.monotonic() - start_time) * 1000 logger.error( "%s %s -> 500 error | duration=%.2fms | request_id=%s", request.method, request.url.path, duration_ms, request_id, ) raise duration_ms = (time.monotonic() - start_time) * 1000 response.headers["X-Request-Id"] = request_id response.headers["X-Instance-Id"] = INSTANCE_ID # лог без логирования тела запросов и текстов сообщений logger.info( "%s %s -> %d | duration=%.2fms | request_id=%s", request.method, request.url.path, response.status_code, duration_ms, request_id, ) return response