forked from mtusi2026/mtusi2026lab2
Bring the application, own tests, Dockerfile, toolchain, compose stack, migrations, secret generator, restart hook, evidence scripts and CI job from the lab 2 solution commit 8cddb09 unchanged, merge the lab 2 Makefile targets into the lab 3 skeleton Makefile without touching its targets, and append the lab 2 solution variables to the skeleton .env.example. The package version follows the contract version 1.3.0. This is the starting point of the lab 3 cycle: lint, own tests and the offline skeleton check pass before any lab 3 change. Co-Authored-By: Claude Opus 5.5 (1M context) <noreply@anthropic.com>
134 lines
5.1 KiB
Python
134 lines
5.1 KiB
Python
from collections.abc import Callable, Mapping
|
|
|
|
from fastapi import FastAPI, Request, Response, status
|
|
from fastapi.exceptions import RequestValidationError
|
|
from starlette.exceptions import HTTPException
|
|
|
|
from messenger.shared.application.errors import Unavailable
|
|
from messenger.shared.application.ports import Logger
|
|
from messenger.shared.domain.errors import DomainError
|
|
from messenger.shared.entrypoints.schemas import ErrorEnvelope
|
|
|
|
REQUEST_ID_HEADER = "X-Request-Id"
|
|
|
|
type ErrorCodes = Mapping[type[DomainError], tuple[str, int]]
|
|
type Challenge = Callable[[str], str]
|
|
|
|
MESSAGES = {
|
|
"invalid_request": "Запрос не соответствует контракту",
|
|
"unauthorized": "Аутентификация не предоставлена или недействительна",
|
|
"not_found": "Объект не найден",
|
|
"conflict": "Конфликт состояния",
|
|
"payload_too_large": "Тело запроса больше допустимого",
|
|
"unsupported_media_type": "Неподдерживаемый тип содержимого",
|
|
"rate_limited": "Слишком много запросов",
|
|
"unavailable": "Сервис временно недоступен",
|
|
"internal_error": "Внутренняя ошибка",
|
|
}
|
|
|
|
STATUS_CODES = {
|
|
status.HTTP_400_BAD_REQUEST: "invalid_request",
|
|
status.HTTP_401_UNAUTHORIZED: "unauthorized",
|
|
status.HTTP_404_NOT_FOUND: "not_found",
|
|
status.HTTP_409_CONFLICT: "conflict",
|
|
status.HTTP_413_CONTENT_TOO_LARGE: "payload_too_large",
|
|
status.HTTP_415_UNSUPPORTED_MEDIA_TYPE: "unsupported_media_type",
|
|
status.HTTP_422_UNPROCESSABLE_CONTENT: "invalid_request",
|
|
status.HTTP_429_TOO_MANY_REQUESTS: "rate_limited",
|
|
status.HTTP_503_SERVICE_UNAVAILABLE: "unavailable",
|
|
}
|
|
|
|
|
|
class Unauthenticated(Exception):
|
|
pass
|
|
|
|
|
|
def classify(error: DomainError, codes: ErrorCodes) -> tuple[str, int]:
|
|
for kind in type(error).__mro__:
|
|
known = codes.get(kind) # type: ignore[arg-type]
|
|
if known is not None:
|
|
return known
|
|
return "internal_error", status.HTTP_500_INTERNAL_SERVER_ERROR
|
|
|
|
|
|
def route_of(request: Request) -> str:
|
|
route = request.scope.get("route")
|
|
return getattr(route, "path", request.url.path)
|
|
|
|
|
|
def install(app: FastAPI, logger: Logger, codes: ErrorCodes, challenge: Challenge) -> None:
|
|
def error_response(request: Request, code: str, detail: str, http_status: int) -> Response:
|
|
request_id = getattr(request.state, "request_id", "") or "unknown"
|
|
headers = {REQUEST_ID_HEADER: request_id}
|
|
if http_status == status.HTTP_401_UNAUTHORIZED:
|
|
headers["WWW-Authenticate"] = challenge(request.url.path)
|
|
return Response(
|
|
status_code=http_status,
|
|
content=ErrorEnvelope.of(code, detail, request_id).model_dump_json(),
|
|
media_type="application/json",
|
|
headers=headers,
|
|
)
|
|
|
|
@app.exception_handler(DomainError)
|
|
async def _domain(request: Request, exc: DomainError) -> Response:
|
|
code, http_status = classify(exc, codes)
|
|
return error_response(request, code, exc.detail, http_status)
|
|
|
|
@app.exception_handler(Unavailable)
|
|
async def _unavailable(request: Request, exc: Unavailable) -> Response:
|
|
logger.warning(
|
|
"dependency.unavailable",
|
|
route=route_of(request),
|
|
error=type(exc.__cause__ or exc).__name__,
|
|
request_id=getattr(request.state, "request_id", None),
|
|
)
|
|
return error_response(
|
|
request,
|
|
"unavailable",
|
|
MESSAGES["unavailable"],
|
|
status.HTTP_503_SERVICE_UNAVAILABLE,
|
|
)
|
|
|
|
@app.exception_handler(Unauthenticated)
|
|
async def _unauthenticated(request: Request, _exc: Unauthenticated) -> Response:
|
|
return error_response(
|
|
request,
|
|
"unauthorized",
|
|
MESSAGES["unauthorized"],
|
|
status.HTTP_401_UNAUTHORIZED,
|
|
)
|
|
|
|
@app.exception_handler(RequestValidationError)
|
|
async def _validation(request: Request, _exc: RequestValidationError) -> Response:
|
|
return error_response(
|
|
request,
|
|
"invalid_request",
|
|
MESSAGES["invalid_request"],
|
|
status.HTTP_400_BAD_REQUEST,
|
|
)
|
|
|
|
@app.exception_handler(HTTPException)
|
|
async def _http(request: Request, exc: HTTPException) -> Response:
|
|
http_status = exc.status_code
|
|
if http_status == status.HTTP_405_METHOD_NOT_ALLOWED:
|
|
http_status = status.HTTP_404_NOT_FOUND
|
|
code = STATUS_CODES.get(http_status, "internal_error")
|
|
return error_response(
|
|
request, code, MESSAGES.get(code, MESSAGES["internal_error"]), http_status
|
|
)
|
|
|
|
@app.exception_handler(Exception)
|
|
async def _unexpected(request: Request, exc: Exception) -> Response:
|
|
logger.error(
|
|
"request.failed",
|
|
route=route_of(request),
|
|
error=type(exc).__name__,
|
|
request_id=getattr(request.state, "request_id", None),
|
|
)
|
|
return error_response(
|
|
request,
|
|
"internal_error",
|
|
MESSAGES["internal_error"],
|
|
status.HTTP_500_INTERNAL_SERVER_ERROR,
|
|
)
|