lab 2 solution
Skeleton contracts / contracts (pull_request) Canceled after 0s

This commit is contained in:
2026-10-23 17:24:27 +03:00
parent 65003b6119
commit 5c193f24f7
70 changed files with 7881 additions and 17 deletions
+128
View File
@@ -0,0 +1,128 @@
"""Обработчики ошибок: единый конверт контракта и заголовки к нему."""
from __future__ import annotations
import logging
import uuid
from typing import Mapping
from fastapi import FastAPI, Request
from fastapi.exceptions import RequestValidationError
from fastapi.responses import JSONResponse
from redis.exceptions import RedisError
from sqlalchemy.exc import SQLAlchemyError
from starlette.exceptions import HTTPException as StarletteHTTPException
from .context import REQUEST_ID, request_context
from .errors import INTERNAL_ERROR, INVALID_REQUEST, UNAVAILABLE, ApiError, code_for_status
from .logging_setup import log
FALLBACK_MESSAGES: Mapping[int, str] = {
404: "Маршрут не найден",
405: "Метод не поддерживается для этого маршрута",
}
# Отказ критичной зависимости (PostgreSQL или Valkey): наружу 503 без деталей,
# подробности остаются в логе. Для клиента «сессии недоступны» и «база недоступна»
# выглядят одинаково — и это правильно, различать их он не должен.
DEPENDENCY_ERRORS = (SQLAlchemyError, RedisError, OSError)
DEPENDENCY_MESSAGE = "Сервис временно недоступен: критичная зависимость не отвечает"
def request_id_of(request: Request) -> str:
"""Идентификатор запроса; запасной вариант — если middleware не подключён."""
context = request_context(request)
identifier = context.get(REQUEST_ID)
if not identifier:
identifier = uuid.uuid4().hex
context[REQUEST_ID] = identifier
return identifier
def error_response(
request: Request,
status: int,
code: str,
message: str,
headers: Mapping[str, str] | None = None,
) -> JSONResponse:
"""Собирает конверт ошибки контракта; request_id совпадает с заголовком."""
identifier = request_id_of(request)
response_headers = {"X-Request-Id": identifier}
response_headers.update(headers or {})
return JSONResponse(
status_code=status,
content={"error": {"code": code, "message": message, "request_id": identifier}},
headers=response_headers,
)
def describe_validation_error(exc: RequestValidationError) -> str:
"""Краткое описание без значений полей: наружу уходит только расположение ошибки.
Значения сюда не попадают намеренно: среди них может быть пароль.
"""
errors = exc.errors()
if not errors:
return "Тело запроса не соответствует контракту"
first = errors[0]
if str(first.get("type", "")) == "json_invalid":
return "Тело запроса не является корректным JSON"
location = ".".join(
str(part)
for part in first.get("loc", ())
if part not in ("body", "query", "path", "header")
)
return f"Некорректный запрос: {location or 'body'}"
def register_error_handlers(app: FastAPI, logger: logging.Logger) -> None:
"""Ставит обработчики так, чтобы наружу не ушёл ответ без конверта."""
@app.exception_handler(ApiError)
async def handle_api_error(request: Request, exc: ApiError) -> JSONResponse:
return error_response(request, exc.status, exc.code, exc.message, exc.headers)
@app.exception_handler(RequestValidationError)
async def handle_validation_error(
request: Request, exc: RequestValidationError
) -> JSONResponse:
return error_response(request, 400, INVALID_REQUEST, describe_validation_error(exc))
@app.exception_handler(StarletteHTTPException)
async def handle_http_exception(
request: Request, exc: StarletteHTTPException
) -> JSONResponse:
status = exc.status_code
return error_response(
request,
status,
code_for_status(status),
FALLBACK_MESSAGES.get(status, "Запрос не может быть обработан"),
getattr(exc, "headers", None),
)
async def handle_dependency_failure(request: Request, exc: Exception) -> JSONResponse:
log(
logger,
logging.ERROR,
"dependency_unavailable",
exc_info=exc,
request_id=request_id_of(request),
error=type(exc).__name__,
)
return error_response(request, 503, UNAVAILABLE, DEPENDENCY_MESSAGE)
for error_type in DEPENDENCY_ERRORS:
app.add_exception_handler(error_type, handle_dependency_failure)
@app.exception_handler(Exception)
async def handle_unexpected(request: Request, exc: Exception) -> JSONResponse:
log(
logger,
logging.ERROR,
"unhandled_exception",
exc_info=exc,
request_id=request_id_of(request),
error=type(exc).__name__,
)
return error_response(request, 500, INTERNAL_ERROR, "Внутренняя ошибка сервера")