from collections.abc import Mapping from fastapi import Request from fastapi.responses import JSONResponse from domain.errors import ErrorBodySchema, ErrorCode, ErrorSchema REQUEST_ID_HEADER = "X-Request-Id" INSTANCE_ID_HEADER = "X-Instance-Id" def get_request_id(request: Request) -> str: """ID запроса, назначенный RequestContextMiddleware""" request_id: str = request.state.request_id return request_id def error_response( request_id: str, status_code: int, code: ErrorCode, message: str, headers: Mapping[str, str] | None = None, ) -> JSONResponse: """Ответ в едином формате ошибки контракта""" body = ErrorSchema( error=ErrorBodySchema(code=code, message=message, request_id=request_id) ) return JSONResponse( status_code=status_code, content=body.model_dump(mode="json"), headers={**(headers or {}), REQUEST_ID_HEADER: request_id}, )