from __future__ import annotations import logging import re import time import uuid from opentelemetry.trace import SpanKind from starlette.middleware.base import BaseHTTPMiddleware, RequestResponseEndpoint from starlette.requests import Request from starlette.responses import Response from app.config import INSTANCE_ID from app.telemetry import ( get_tracer, record_http_request, ) logger = logging.getLogger("app.access") ROUTE_CHATS_MESSAGES = re.compile(r"^/api/v1/chats/[0-9a-fA-F-]+/messages$") ROUTE_CHATS_ATTACHMENTS = re.compile(r"^/api/v1/chats/[0-9a-fA-F-]+/attachments$") ROUTE_CHATS_ID = re.compile(r"^/api/v1/chats/[0-9a-fA-F-]+$") ROUTE_ATTACHMENTS_CONTENT = re.compile(r"^/api/v1/attachments/[0-9a-fA-F-]+/content$") ROUTE_ATTACHMENTS_ID = re.compile(r"^/api/v1/attachments/[0-9a-fA-F-]+$") def get_route_template(path: str) -> str: if ROUTE_CHATS_MESSAGES.match(path): return "/api/v1/chats/{chat_id}/messages" if ROUTE_CHATS_ATTACHMENTS.match(path): return "/api/v1/chats/{chat_id}/attachments" if ROUTE_CHATS_ID.match(path): return "/api/v1/chats/{chat_id}" if ROUTE_ATTACHMENTS_CONTENT.match(path): return "/api/v1/attachments/{attachment_id}/content" if ROUTE_ATTACHMENTS_ID.match(path): return "/api/v1/attachments/{attachment_id}" return path class RequestIdAndLoggingMiddleware(BaseHTTPMiddleware): async def dispatch( self, request: Request, call_next: RequestResponseEndpoint ) -> Response: 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() path = request.url.path route_template = get_route_template(path) if request.method in ("POST", "PUT", "PATCH") and path != "/api/v1/auth/sessions": is_attachment_upload = ( request.method == "POST" and "/attachments" in path and 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, ) tracer = get_tracer() with tracer.start_as_current_span( f"{request.method} {route_template}", kind=SpanKind.SERVER, ) as span: span.set_attribute("http.method", request.method) span.set_attribute("http.route", route_template) span.set_attribute("http.target", path) span.set_attribute("request.id", request_id) try: response = await call_next(request) except Exception: duration_sec = time.monotonic() - start_time span.set_attribute("http.status_code", 500) span.record_exception(Exception("Unhandled server error")) record_http_request(request.method, route_template, "500", duration_sec) logger.error( "%s %s -> 500 error | duration=%.2fms | request_id=%s", request.method, path, duration_sec * 1000, request_id, ) raise duration_sec = time.monotonic() - start_time span.set_attribute("http.status_code", response.status_code) record_http_request(request.method, route_template, str(response.status_code), duration_sec) response.headers["X-Request-Id"] = request_id response.headers["X-Instance-Id"] = INSTANCE_ID ctx = span.get_span_context() if ctx.is_valid: response.headers["X-Trace-Id"] = format(ctx.trace_id, "032x") logger.info( "%s %s -> %d | duration=%.2fms | request_id=%s", request.method, path, response.status_code, duration_sec * 1000, request_id, ) return response