chore: carry lab 3 over
- carry the lab 3 solution over from mtusi2026lab3-safronov (solution/bvt2301-safronov, ce89eba): src, migrations, student-tests, bench, openspec, .claude, infra/haproxy and infra/valkey, own scripts, Dockerfile, compose, pyproject and uv lock - merge Makefile, .gitignore and .dockerignore (the lab 3 versions only add lines to the skeleton, which is the same in lab 4) and .env.example (lab 4 skeleton names listed in the header) - rename the compose project to mtusi-lab4 and the image to :lab4 so the stand does not reuse the lab 3 containers and volumes - update AGENTS.md for lab 4: current lab, origin commit, contract and test files of the new skeleton Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
@@ -0,0 +1,148 @@
|
||||
"""Перевод исключений в формат ошибки контракта.
|
||||
|
||||
Одна таблица «доменное исключение → статус, 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.InvalidChatMembers: (400, ErrorCode.INVALID_REQUEST),
|
||||
exceptions.InvalidCursor: (400, ErrorCode.INVALID_REQUEST),
|
||||
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)
|
||||
Reference in New Issue
Block a user