- keep one upload body in memory: BytesIO + getvalue() without copy, fixed glibc mmap threshold in the image (no realloc copy on growth) - stop PNG inflate at expected size + 1 byte - reject filename that is not valid UTF-8 after percent-decoding (400) - failure stand: env limit variables do not change attachment limits; history with attachment_ids while S3 is stopped - drop dead constants; restate "old image on new schema" scenario Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
159 lines
5.7 KiB
Python
159 lines
5.7 KiB
Python
"""Перевод исключений в формат ошибки контракта.
|
||
|
||
Одна таблица «доменное исключение → статус, code». Ошибки валидации
|
||
FastAPI отдаются как 400, а не 422 (согласовано с преподавателем,
|
||
`.claude/rules/api-contract.md`). Непредвиденную ошибку логирует uvicorn:
|
||
Starlette повторно бросает её после ответа 500.
|
||
"""
|
||
|
||
from uuid import uuid4
|
||
|
||
from fastapi import FastAPI, Request
|
||
from fastapi.exceptions import RequestValidationError
|
||
from fastapi.responses import JSONResponse
|
||
from starlette.exceptions import HTTPException as StarletteHTTPException
|
||
|
||
from src.api.schemas import Error, ErrorBody, ErrorCode
|
||
from src.config import settings
|
||
from src.core import exceptions
|
||
from src.utils.constants import (
|
||
AUTH_REALM,
|
||
INSTANCE_ID_HEADER,
|
||
REQUEST_ID_HEADER,
|
||
)
|
||
|
||
DOMAIN_ERRORS: dict[type[exceptions.DomainError], tuple[int, ErrorCode]] = {
|
||
exceptions.InvalidCredentials: (401, ErrorCode.UNAUTHORIZED),
|
||
exceptions.Unauthenticated: (401, ErrorCode.UNAUTHORIZED),
|
||
exceptions.UsernameTaken: (409, ErrorCode.CONFLICT),
|
||
exceptions.IdempotencyConflict: (409, ErrorCode.CONFLICT),
|
||
exceptions.ChatNotFound: (404, ErrorCode.NOT_FOUND),
|
||
exceptions.AttachmentNotFound: (404, ErrorCode.NOT_FOUND),
|
||
exceptions.InvalidChatMembers: (400, ErrorCode.INVALID_REQUEST),
|
||
exceptions.InvalidCursor: (400, ErrorCode.INVALID_REQUEST),
|
||
exceptions.InvalidFilename: (400, ErrorCode.INVALID_REQUEST),
|
||
exceptions.UploadInterrupted: (400, ErrorCode.INVALID_REQUEST),
|
||
exceptions.PayloadTooLarge: (413, ErrorCode.PAYLOAD_TOO_LARGE),
|
||
exceptions.UnsupportedMediaType: (
|
||
415,
|
||
ErrorCode.UNSUPPORTED_MEDIA_TYPE,
|
||
),
|
||
# расхождение БД и S3, а не ошибка клиента: причина — в журнале
|
||
exceptions.AttachmentContentMissing: (500, ErrorCode.INTERNAL_ERROR),
|
||
exceptions.ServiceUnavailable: (503, ErrorCode.UNAVAILABLE),
|
||
# доменная ошибка без своей строки — некорректный запрос
|
||
exceptions.DomainError: (400, ErrorCode.INVALID_REQUEST),
|
||
}
|
||
|
||
# вызов в WWW-Authenticate у 401: какой схемой повторить запрос
|
||
CHALLENGES: dict[type[exceptions.DomainError], str] = {
|
||
exceptions.InvalidCredentials: (
|
||
f'Basic realm="{AUTH_REALM}", charset="UTF-8"'
|
||
),
|
||
exceptions.Unauthenticated: f'Bearer realm="{AUTH_REALM}"',
|
||
}
|
||
|
||
HTTP_ERRORS: dict[int, tuple[ErrorCode, str]] = {
|
||
404: (ErrorCode.NOT_FOUND, "Not found"),
|
||
405: (ErrorCode.INVALID_REQUEST, "Method not allowed"),
|
||
}
|
||
|
||
|
||
def _request_id(request: Request) -> str:
|
||
# ставит request-id middleware; запасной id — на случай ошибки до него
|
||
return getattr(request.state, "request_id", None) or uuid4().hex
|
||
|
||
|
||
def error_response(
|
||
*,
|
||
request_id: str,
|
||
status_code: int,
|
||
code: ErrorCode,
|
||
message: str,
|
||
headers: dict[str, str] | None = None,
|
||
) -> JSONResponse:
|
||
body = Error(
|
||
error=ErrorBody(code=code, message=message, request_id=request_id),
|
||
)
|
||
return JSONResponse(
|
||
status_code=status_code,
|
||
content=body.model_dump(mode="json"),
|
||
headers=headers,
|
||
)
|
||
|
||
|
||
async def handle_domain_error(
|
||
request: Request,
|
||
exc: exceptions.DomainError,
|
||
) -> JSONResponse:
|
||
status_code, code = next(
|
||
DOMAIN_ERRORS[cls] for cls in type(exc).__mro__ if cls in DOMAIN_ERRORS
|
||
)
|
||
challenge = CHALLENGES.get(type(exc))
|
||
return error_response(
|
||
request_id=_request_id(request),
|
||
status_code=status_code,
|
||
code=code,
|
||
message=str(exc),
|
||
headers={"WWW-Authenticate": challenge} if challenge else None,
|
||
)
|
||
|
||
|
||
async def handle_validation_error(
|
||
request: Request,
|
||
exc: RequestValidationError,
|
||
) -> JSONResponse:
|
||
# первая ошибка: где и что не так, без входного значения
|
||
first = exc.errors()[0] if exc.errors() else {}
|
||
location = ".".join(str(part) for part in first.get("loc", ()))
|
||
detail = first.get("msg", "Invalid request")
|
||
return error_response(
|
||
request_id=_request_id(request),
|
||
status_code=400,
|
||
code=ErrorCode.INVALID_REQUEST,
|
||
message=f"{location}: {detail}" if location else detail,
|
||
)
|
||
|
||
|
||
async def handle_http_error(
|
||
request: Request,
|
||
exc: StarletteHTTPException,
|
||
) -> JSONResponse:
|
||
code, message = HTTP_ERRORS.get(
|
||
exc.status_code,
|
||
(ErrorCode.INVALID_REQUEST, "Invalid request"),
|
||
)
|
||
return error_response(
|
||
request_id=_request_id(request),
|
||
status_code=exc.status_code,
|
||
code=code,
|
||
message=message,
|
||
headers=exc.headers,
|
||
)
|
||
|
||
|
||
async def handle_unexpected_error(
|
||
request: Request,
|
||
exc: Exception, # noqa: ARG001
|
||
) -> JSONResponse:
|
||
# ответ формирует ServerErrorMiddleware снаружи request-id middleware,
|
||
# поэтому заголовки ставим сами
|
||
request_id = _request_id(request)
|
||
return error_response(
|
||
request_id=request_id,
|
||
status_code=500,
|
||
code=ErrorCode.INTERNAL_ERROR,
|
||
message="Internal server error",
|
||
headers={
|
||
REQUEST_ID_HEADER: request_id,
|
||
INSTANCE_ID_HEADER: settings.app.instance_id,
|
||
},
|
||
)
|
||
|
||
|
||
def register(app: FastAPI) -> None:
|
||
app.add_exception_handler(exceptions.DomainError, handle_domain_error)
|
||
app.add_exception_handler(RequestValidationError, handle_validation_error)
|
||
app.add_exception_handler(StarletteHTTPException, handle_http_error)
|
||
app.add_exception_handler(Exception, handle_unexpected_error)
|