chore: carry over lab 1 solution into lab 2 skeleton
Copy the committed lab 1 sources as-is: src/, student-tests/, bench/, Dockerfile, docker-compose.yml, pyproject.toml, uv.lock, .python-version, config_example.toml, AGENTS.md, CLAUDE.md, .claude/, openspec/, .graphifyignore and KNOWN_ISSUES.md. Lab 1 evidence stays in the lab 1 repository. Merge the new skeleton files with own sections: Makefile (lab 2 targets plus own run, docker, bench and common targets), .gitignore, .dockerignore and .env.example. Rename the image to mtusi-messenger:lab2 and point AGENTS.md at lab 2. The application is still the in-memory lab 1 implementation. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
@@ -0,0 +1,128 @@
|
||||
"""Перевод исключений в формат ошибки контракта.
|
||||
|
||||
Одна таблица «доменное исключение → статус, 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.core import exceptions
|
||||
from src.utils.constants import REQUEST_ID_HEADER
|
||||
|
||||
DOMAIN_ERRORS: dict[type[exceptions.DomainError], tuple[int, ErrorCode]] = {
|
||||
exceptions.Unidentified: (401, ErrorCode.UNAUTHORIZED),
|
||||
exceptions.UsernameTaken: (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),
|
||||
}
|
||||
|
||||
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
|
||||
)
|
||||
return error_response(
|
||||
request_id=_request_id(request),
|
||||
status_code=status_code,
|
||||
code=code,
|
||||
message=str(exc),
|
||||
)
|
||||
|
||||
|
||||
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},
|
||||
)
|
||||
|
||||
|
||||
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