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,223 @@
|
||||
"""Зависимости ручек: сессия БД, сервисы, вход и текущая сессия, страница.
|
||||
|
||||
Сервисы получают сессию БД, а чаты и сообщения — ещё и кэш процесса
|
||||
(`src/infra/cache/instance.py`).
|
||||
"""
|
||||
|
||||
import asyncio
|
||||
import base64
|
||||
import binascii
|
||||
import re
|
||||
from collections.abc import AsyncIterator
|
||||
from dataclasses import dataclass
|
||||
from typing import Annotated
|
||||
|
||||
from fastapi import Depends, Query, Security
|
||||
from fastapi.security import HTTPAuthorizationCredentials, HTTPBearer
|
||||
from fastapi.security.http import HTTPBase
|
||||
from sqlalchemy.ext.asyncio import AsyncSession
|
||||
|
||||
from src.config import settings
|
||||
from src.core import exceptions
|
||||
from src.core.services import (
|
||||
ChatService,
|
||||
MessageService,
|
||||
SessionService,
|
||||
UserService,
|
||||
)
|
||||
from src.infra.cache.instance import cache
|
||||
from src.infra.db import is_db_unavailable, ping
|
||||
from src.infra.db.session import engine, session_factory
|
||||
from src.infra.logger import AbstractLogger, current_user_id, get_logger
|
||||
from src.schemas import dataclasses
|
||||
from src.utils.constants import (
|
||||
PAGE_LIMIT_DEFAULT,
|
||||
PAGE_LIMIT_MAX,
|
||||
PAGE_LIMIT_MIN,
|
||||
PASSWORD_MAX_LENGTH,
|
||||
PASSWORD_MIN_LENGTH,
|
||||
READINESS_DB_TIMEOUT_SECONDS,
|
||||
USERNAME_PATTERN,
|
||||
)
|
||||
|
||||
logger: AbstractLogger = get_logger().bind(module="api_dependencies")
|
||||
|
||||
|
||||
async def get_db_session() -> AsyncIterator[AsyncSession]:
|
||||
"""Одна сессия БД на запрос; commit делает сервис.
|
||||
|
||||
Незакоммиченное при выходе откатывается. Вся работа запроса с БД
|
||||
ограничена `[database] request_timeout_seconds`: зависший Postgres не
|
||||
держит запрос бесконечно. Недоступность БД (`is_db_unavailable`) —
|
||||
503 `unavailable`, а соединение не возвращается в пул: его состояние
|
||||
неизвестно, а откат на зависшем сервере повис бы.
|
||||
"""
|
||||
async with session_factory() as db_session:
|
||||
try:
|
||||
async with asyncio.timeout(
|
||||
settings.database.request_timeout_seconds,
|
||||
):
|
||||
yield db_session
|
||||
except Exception as e:
|
||||
if not is_db_unavailable(e):
|
||||
raise
|
||||
await db_session.invalidate()
|
||||
logger.warning(
|
||||
"Database is unavailable",
|
||||
error_type=type(e).__name__,
|
||||
error=str(e),
|
||||
)
|
||||
raise exceptions.ServiceUnavailable from e
|
||||
|
||||
|
||||
DbSessionDep = Annotated[AsyncSession, Depends(get_db_session)]
|
||||
|
||||
|
||||
async def require_database() -> None:
|
||||
"""Readiness: Postgres отвечает на `SELECT 1` за отведённое время.
|
||||
|
||||
Любая ошибка — 503: готовность не должна отвечать 500. Не логирует:
|
||||
healthcheck спрашивает каждые несколько секунд.
|
||||
"""
|
||||
try:
|
||||
await ping(engine, timeout=READINESS_DB_TIMEOUT_SECONDS)
|
||||
except Exception as e:
|
||||
raise exceptions.ServiceUnavailable from e
|
||||
|
||||
|
||||
async def get_user_service(db_session: DbSessionDep) -> UserService:
|
||||
return UserService(db_session=db_session)
|
||||
|
||||
|
||||
async def get_chat_service(db_session: DbSessionDep) -> ChatService:
|
||||
return ChatService(db_session=db_session, cache=cache)
|
||||
|
||||
|
||||
async def get_message_service(db_session: DbSessionDep) -> MessageService:
|
||||
return MessageService(db_session=db_session, cache=cache)
|
||||
|
||||
|
||||
async def get_session_service(db_session: DbSessionDep) -> SessionService:
|
||||
return SessionService(db_session=db_session)
|
||||
|
||||
|
||||
UserServiceDep = Annotated[UserService, Depends(get_user_service)]
|
||||
ChatServiceDep = Annotated[ChatService, Depends(get_chat_service)]
|
||||
MessageServiceDep = Annotated[MessageService, Depends(get_message_service)]
|
||||
SessionServiceDep = Annotated[SessionService, Depends(get_session_service)]
|
||||
|
||||
|
||||
# схемы basicAuth и bearerAuth из contracts/openapi.json: объявлены в
|
||||
# /openapi.json и дают кнопку Authorize в /docs. auto_error=False — нет
|
||||
# заголовка или схема чужая даёт None, а 401 в формате контракта бросает
|
||||
# сервис. HTTPBase отдаёт credentials как есть: HTTPBasic FastAPI
|
||||
# декодирует ASCII и на пароле не из ASCII сам ответил бы 401
|
||||
basic_scheme = HTTPBase(
|
||||
scheme="basic",
|
||||
scheme_name="basicAuth",
|
||||
auto_error=False,
|
||||
)
|
||||
bearer_scheme = HTTPBearer(
|
||||
scheme_name="bearerAuth",
|
||||
bearerFormat="opaque session token",
|
||||
auto_error=False,
|
||||
)
|
||||
|
||||
|
||||
@dataclass(frozen=True, slots=True)
|
||||
class BasicCredentials:
|
||||
username: str
|
||||
password: str
|
||||
|
||||
|
||||
def parse_basic(
|
||||
credentials: HTTPAuthorizationCredentials | None,
|
||||
) -> BasicCredentials | None:
|
||||
"""username и пароль из `Authorization: Basic`; None — разбор не удался.
|
||||
|
||||
base64 строго, UTF-8, разделитель — первое двоеточие: в username его
|
||||
не бывает, в пароле оно допустимо. Значения, которые не могут быть
|
||||
верными (формат username и длина пароля публичны), отсекаются здесь:
|
||||
до БД и KDF не доходит ни мусор, ни пароль в мегабайт.
|
||||
"""
|
||||
if credentials is None or credentials.scheme.lower() != "basic":
|
||||
return None
|
||||
try:
|
||||
decoded = base64.b64decode(credentials.credentials, validate=True)
|
||||
username, separator, password = decoded.decode().partition(":")
|
||||
except (binascii.Error, UnicodeDecodeError):
|
||||
return None
|
||||
if not separator or not re.fullmatch(USERNAME_PATTERN, username):
|
||||
return None
|
||||
if not PASSWORD_MIN_LENGTH <= len(password) <= PASSWORD_MAX_LENGTH:
|
||||
return None
|
||||
return BasicCredentials(username=username, password=password)
|
||||
|
||||
|
||||
async def get_basic_credentials(
|
||||
credentials: Annotated[
|
||||
HTTPAuthorizationCredentials | None,
|
||||
Security(basic_scheme),
|
||||
],
|
||||
) -> BasicCredentials:
|
||||
"""Учётные данные входа; любой сбой разбора — тот же 401, что и
|
||||
неверный пароль."""
|
||||
parsed = parse_basic(credentials)
|
||||
if parsed is None:
|
||||
raise exceptions.InvalidCredentials
|
||||
return parsed
|
||||
|
||||
|
||||
BasicCredentialsDep = Annotated[
|
||||
BasicCredentials,
|
||||
Depends(get_basic_credentials),
|
||||
]
|
||||
|
||||
|
||||
async def get_current_session(
|
||||
credentials: Annotated[
|
||||
HTTPAuthorizationCredentials | None,
|
||||
Security(bearer_scheme),
|
||||
],
|
||||
sessions: SessionServiceDep,
|
||||
) -> dataclasses.CurrentSessionDTO:
|
||||
"""Действующая сессия по Bearer-токену; иначе 401."""
|
||||
current = await sessions.authenticate(
|
||||
token=credentials.credentials if credentials else None,
|
||||
)
|
||||
current_user_id.set(str(current.user.id))
|
||||
return current
|
||||
|
||||
|
||||
CurrentSession = Annotated[
|
||||
dataclasses.CurrentSessionDTO,
|
||||
Depends(get_current_session),
|
||||
]
|
||||
|
||||
|
||||
async def get_current_user(
|
||||
current: CurrentSession,
|
||||
) -> dataclasses.UserFullDTO:
|
||||
return current.user
|
||||
|
||||
|
||||
CurrentUser = Annotated[dataclasses.UserFullDTO, Depends(get_current_user)]
|
||||
|
||||
|
||||
@dataclass(frozen=True, slots=True)
|
||||
class PageQuery:
|
||||
limit: int
|
||||
cursor: str | None
|
||||
|
||||
|
||||
async def get_page_query(
|
||||
limit: Annotated[
|
||||
int,
|
||||
Query(ge=PAGE_LIMIT_MIN, le=PAGE_LIMIT_MAX),
|
||||
] = PAGE_LIMIT_DEFAULT,
|
||||
cursor: Annotated[str | None, Query(min_length=1)] = None,
|
||||
) -> PageQuery:
|
||||
return PageQuery(limit=limit, cursor=cursor)
|
||||
|
||||
|
||||
PageQueryDep = Annotated[PageQuery, Depends(get_page_query)]
|
||||
@@ -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)
|
||||
@@ -0,0 +1,5 @@
|
||||
from .request_context import RequestContextMiddleware
|
||||
|
||||
__all__ = [
|
||||
"RequestContextMiddleware",
|
||||
]
|
||||
@@ -0,0 +1,106 @@
|
||||
"""Request id, instance id и итоговая запись о запросе — чистое ASGI-middleware.
|
||||
|
||||
Без `BaseHTTPMiddleware`: тот на каждый запрос создаёт отдельную задачу и
|
||||
поток памяти для тела ответа (design, решение 7).
|
||||
"""
|
||||
|
||||
import time
|
||||
from uuid import uuid4
|
||||
|
||||
from fastapi import FastAPI
|
||||
from fastapi.routing import iter_route_contexts
|
||||
from starlette.types import ASGIApp, Message, Receive, Scope, Send
|
||||
|
||||
from src.config import settings
|
||||
from src.infra.logger import AbstractLogger, get_logger, http_request_id
|
||||
from src.utils.constants import (
|
||||
HEALTH_PATHS,
|
||||
INSTANCE_ID_HEADER,
|
||||
REQUEST_ID_HEADER,
|
||||
)
|
||||
|
||||
logger: AbstractLogger = get_logger().bind(middleware="http")
|
||||
|
||||
_REQUEST_ID_HEADER = REQUEST_ID_HEADER.lower().encode("ascii")
|
||||
_INSTANCE_ID_HEADER = INSTANCE_ID_HEADER.lower().encode("ascii")
|
||||
# одно значение на процесс: вычислено при загрузке настроек
|
||||
_INSTANCE_ID = settings.app.instance_id.encode("ascii")
|
||||
_UNMATCHED_PATH = "<unmatched>"
|
||||
|
||||
|
||||
def _route_templates(app: FastAPI) -> dict[int, str]:
|
||||
"""id маршрута → полный шаблон пути (`/api/v1/chats/{chat_id}`).
|
||||
|
||||
С FastAPI 0.137 роутеры включаются деревом, и `scope["route"].path`
|
||||
не содержит префикс `include_router`: префикс принадлежит включению,
|
||||
а не маршруту. Полный путь даёт публичный `iter_route_contexts`.
|
||||
Каждый наш роутер включён один раз, поэтому id маршрута однозначен.
|
||||
"""
|
||||
return {
|
||||
id(context.original_route): context.path_format
|
||||
for context in iter_route_contexts(app.routes)
|
||||
if context.path_format is not None
|
||||
}
|
||||
|
||||
|
||||
class RequestContextMiddleware:
|
||||
def __init__(self, app: ASGIApp) -> None:
|
||||
self.app = app
|
||||
# строится на первом запросе: к нему все роутеры уже подключены
|
||||
self._route_templates: dict[int, str] | None = None
|
||||
|
||||
async def __call__(
|
||||
self,
|
||||
scope: Scope,
|
||||
receive: Receive,
|
||||
send: Send,
|
||||
) -> None:
|
||||
if scope["type"] != "http":
|
||||
await self.app(scope, receive, send)
|
||||
return
|
||||
|
||||
request_id = uuid4().hex
|
||||
# request.state.request_id — для обработчиков ошибок
|
||||
scope.setdefault("state", {})["request_id"] = request_id
|
||||
# не сбрасывается: у каждого запроса в uvicorn своя задача, а
|
||||
# traceback непредвиденной ошибки uvicorn пишет после выхода
|
||||
# отсюда и тоже должен получить request_id
|
||||
http_request_id.set(request_id)
|
||||
status_code = 500
|
||||
started = time.perf_counter()
|
||||
|
||||
async def send_with_ids(message: Message) -> None:
|
||||
nonlocal status_code
|
||||
if message["type"] == "http.response.start":
|
||||
status_code = message["status"]
|
||||
headers = list(message.get("headers", []))
|
||||
present = {name.lower() for name, _ in headers}
|
||||
if _REQUEST_ID_HEADER not in present:
|
||||
headers.append(
|
||||
(_REQUEST_ID_HEADER, request_id.encode("ascii")),
|
||||
)
|
||||
if _INSTANCE_ID_HEADER not in present:
|
||||
headers.append((_INSTANCE_ID_HEADER, _INSTANCE_ID))
|
||||
message = {**message, "headers": headers}
|
||||
await send(message)
|
||||
|
||||
try:
|
||||
await self.app(scope, receive, send_with_ids)
|
||||
finally:
|
||||
if scope["path"] not in HEALTH_PATHS:
|
||||
# шаблон пути, а не фактический: id в пути не попадают в лог
|
||||
if self._route_templates is None:
|
||||
self._route_templates = _route_templates(scope["app"])
|
||||
logger.info(
|
||||
"HTTP request completed",
|
||||
method=scope["method"],
|
||||
path=self._route_templates.get(
|
||||
id(scope.get("route")),
|
||||
_UNMATCHED_PATH,
|
||||
),
|
||||
status=status_code,
|
||||
duration_ms=round(
|
||||
(time.perf_counter() - started) * 1000,
|
||||
3,
|
||||
),
|
||||
)
|
||||
@@ -0,0 +1,7 @@
|
||||
from .health import router as health_router
|
||||
from .v1 import v1_router
|
||||
|
||||
__all__ = [
|
||||
"health_router",
|
||||
"v1_router",
|
||||
]
|
||||
@@ -0,0 +1,25 @@
|
||||
from fastapi import APIRouter, Depends
|
||||
|
||||
from src.api.dependencies import require_database
|
||||
from src.api.schemas import Error, Health
|
||||
from src.utils.constants import HEALTH_LIVE_PATH, HEALTH_READY_PATH
|
||||
|
||||
# вне версии API и без идентификации; из итоговой записи о запросе исключены
|
||||
router = APIRouter(tags=["health"])
|
||||
|
||||
|
||||
@router.get(HEALTH_LIVE_PATH, response_model=Health)
|
||||
async def liveness() -> Health:
|
||||
"""Процесс жив и обслуживает HTTP."""
|
||||
return Health(status="ok")
|
||||
|
||||
|
||||
@router.get(
|
||||
HEALTH_READY_PATH,
|
||||
response_model=Health,
|
||||
responses={503: {"model": Error}},
|
||||
dependencies=[Depends(require_database)],
|
||||
)
|
||||
async def readiness() -> Health:
|
||||
"""Postgres отвечает — можно обслуживать запросы; иначе 503."""
|
||||
return Health(status="ok")
|
||||
@@ -0,0 +1,24 @@
|
||||
"""Ручки API версии 1.
|
||||
|
||||
Каждый модуль пакета — роутер домена; здесь они собираются в
|
||||
`v1_router` под `API_V1_PREFIX`. Новый домен регистрируется только тут.
|
||||
"""
|
||||
|
||||
from fastapi import APIRouter
|
||||
|
||||
from src.utils.constants import API_V1_PREFIX
|
||||
|
||||
from .chat import router as chat_router
|
||||
from .message import router as message_router
|
||||
from .session import router as session_router
|
||||
from .user import router as user_router
|
||||
|
||||
v1_router = APIRouter(prefix=API_V1_PREFIX)
|
||||
v1_router.include_router(user_router)
|
||||
v1_router.include_router(session_router)
|
||||
v1_router.include_router(chat_router)
|
||||
v1_router.include_router(message_router)
|
||||
|
||||
__all__ = [
|
||||
"v1_router",
|
||||
]
|
||||
@@ -0,0 +1,44 @@
|
||||
from fastapi import APIRouter
|
||||
|
||||
from src.api.dependencies import ChatServiceDep, CurrentUser, PageQueryDep
|
||||
from src.api.schemas import Chat, ChatPage, CreateChat, UuidIn
|
||||
|
||||
router = APIRouter(prefix="/chats", tags=["chats"])
|
||||
|
||||
|
||||
@router.post("", status_code=201, response_model=Chat)
|
||||
async def create_chat(
|
||||
user: CurrentUser,
|
||||
body: CreateChat,
|
||||
chats: ChatServiceDep,
|
||||
) -> Chat:
|
||||
chat = await chats.create_chat(
|
||||
current_user_id=user.id,
|
||||
title=body.title,
|
||||
member_ids=body.member_ids,
|
||||
)
|
||||
return Chat.model_validate(chat)
|
||||
|
||||
|
||||
@router.get("", response_model=ChatPage)
|
||||
async def list_chats(
|
||||
user: CurrentUser,
|
||||
page: PageQueryDep,
|
||||
chats: ChatServiceDep,
|
||||
) -> ChatPage:
|
||||
result = await chats.list_user_chats(
|
||||
user_id=user.id,
|
||||
limit=page.limit,
|
||||
cursor=page.cursor,
|
||||
)
|
||||
return ChatPage.model_validate(result)
|
||||
|
||||
|
||||
@router.get("/{chat_id}", response_model=Chat)
|
||||
async def get_chat(
|
||||
user: CurrentUser,
|
||||
chat_id: UuidIn,
|
||||
chats: ChatServiceDep,
|
||||
) -> Chat:
|
||||
chat = await chats.get_chat_for_member(chat_id=chat_id, user_id=user.id)
|
||||
return Chat.model_validate(chat)
|
||||
@@ -0,0 +1,61 @@
|
||||
from typing import Annotated
|
||||
|
||||
from fastapi import APIRouter, Header
|
||||
|
||||
from src.api.dependencies import CurrentUser, MessageServiceDep, PageQueryDep
|
||||
from src.api.schemas import CreateMessage, Message, MessagePage, UuidIn
|
||||
from src.utils.constants import (
|
||||
IDEMPOTENCY_KEY_HEADER,
|
||||
IDEMPOTENCY_KEY_MAX_LENGTH,
|
||||
IDEMPOTENCY_KEY_MIN_LENGTH,
|
||||
IDEMPOTENCY_KEY_PATTERN,
|
||||
)
|
||||
|
||||
router = APIRouter(prefix="/chats/{chat_id}/messages", tags=["messages"])
|
||||
|
||||
# параметр по схеме контракта: есть в /openapi.json, а отсутствие и
|
||||
# неверный формат дают 400 через общий обработчик валидации. Проверяется
|
||||
# после зависимостей, поэтому без сессии ответ 401, а не 400
|
||||
IdempotencyKeyHeader = Annotated[
|
||||
str,
|
||||
Header(
|
||||
alias=IDEMPOTENCY_KEY_HEADER,
|
||||
min_length=IDEMPOTENCY_KEY_MIN_LENGTH,
|
||||
max_length=IDEMPOTENCY_KEY_MAX_LENGTH,
|
||||
pattern=IDEMPOTENCY_KEY_PATTERN,
|
||||
),
|
||||
]
|
||||
|
||||
|
||||
@router.post("", status_code=201, response_model=Message)
|
||||
async def send_message(
|
||||
user: CurrentUser,
|
||||
chat_id: UuidIn,
|
||||
body: CreateMessage,
|
||||
idempotency_key: IdempotencyKeyHeader,
|
||||
messages: MessageServiceDep,
|
||||
) -> Message:
|
||||
"""Повтор с тем же ключом и телом отвечает тем же 201 и сообщением."""
|
||||
message = await messages.send_message(
|
||||
chat_id=chat_id,
|
||||
sender_id=user.id,
|
||||
text=body.text,
|
||||
idempotency_key=idempotency_key,
|
||||
)
|
||||
return Message.model_validate(message)
|
||||
|
||||
|
||||
@router.get("", response_model=MessagePage)
|
||||
async def list_messages(
|
||||
user: CurrentUser,
|
||||
chat_id: UuidIn,
|
||||
page: PageQueryDep,
|
||||
messages: MessageServiceDep,
|
||||
) -> MessagePage:
|
||||
result = await messages.list_messages(
|
||||
chat_id=chat_id,
|
||||
user_id=user.id,
|
||||
limit=page.limit,
|
||||
cursor=page.cursor,
|
||||
)
|
||||
return MessagePage.model_validate(result)
|
||||
@@ -0,0 +1,32 @@
|
||||
from fastapi import APIRouter, Response
|
||||
|
||||
from src.api.dependencies import (
|
||||
BasicCredentialsDep,
|
||||
CurrentSession,
|
||||
SessionServiceDep,
|
||||
)
|
||||
from src.api.schemas import Session
|
||||
|
||||
router = APIRouter(prefix="/auth/sessions", tags=["sessions"])
|
||||
|
||||
|
||||
@router.post("", status_code=201, response_model=Session)
|
||||
async def create_session(
|
||||
credentials: BasicCredentialsDep,
|
||||
sessions: SessionServiceDep,
|
||||
) -> Session:
|
||||
"""Вход по `Authorization: Basic`; тело запроса не читается."""
|
||||
issued = await sessions.login(
|
||||
username=credentials.username,
|
||||
password=credentials.password,
|
||||
)
|
||||
return Session.model_validate(issued)
|
||||
|
||||
|
||||
@router.delete("/current", status_code=204, response_class=Response)
|
||||
async def revoke_current_session(
|
||||
current: CurrentSession,
|
||||
sessions: SessionServiceDep,
|
||||
) -> Response:
|
||||
await sessions.revoke(session_id=current.id)
|
||||
return Response(status_code=204)
|
||||
@@ -0,0 +1,21 @@
|
||||
from fastapi import APIRouter
|
||||
|
||||
from src.api.dependencies import CurrentUser, UserServiceDep
|
||||
from src.api.schemas import CreateUser, User
|
||||
|
||||
router = APIRouter(prefix="/users", tags=["users"])
|
||||
|
||||
|
||||
@router.post("", status_code=201, response_model=User)
|
||||
async def register_user(body: CreateUser, users: UserServiceDep) -> User:
|
||||
user = await users.register(
|
||||
username=body.username,
|
||||
display_name=body.display_name,
|
||||
password=body.password,
|
||||
)
|
||||
return User.model_validate(user)
|
||||
|
||||
|
||||
@router.get("/me", response_model=User)
|
||||
async def get_me(user: CurrentUser) -> User:
|
||||
return User.model_validate(user)
|
||||
@@ -0,0 +1,22 @@
|
||||
from .chat import Chat, ChatPage, CreateChat
|
||||
from .common import Error, ErrorBody, ErrorCode, Health, UuidIn
|
||||
from .message import CreateMessage, Message, MessagePage
|
||||
from .session import Session
|
||||
from .user import CreateUser, User
|
||||
|
||||
__all__ = [
|
||||
"Chat",
|
||||
"ChatPage",
|
||||
"CreateChat",
|
||||
"CreateMessage",
|
||||
"CreateUser",
|
||||
"Error",
|
||||
"ErrorBody",
|
||||
"ErrorCode",
|
||||
"Health",
|
||||
"Message",
|
||||
"MessagePage",
|
||||
"Session",
|
||||
"User",
|
||||
"UuidIn",
|
||||
]
|
||||
@@ -0,0 +1,42 @@
|
||||
from uuid import UUID
|
||||
|
||||
from pydantic import BaseModel, ConfigDict, Field
|
||||
|
||||
from src.api.schemas.common import NonBlankStr, UtcDatetime, UuidIn
|
||||
from src.utils.constants import (
|
||||
CHAT_MEMBERS_MAX,
|
||||
CHAT_MEMBERS_MIN,
|
||||
CHAT_TITLE_MAX_LENGTH,
|
||||
CHAT_TITLE_MIN_LENGTH,
|
||||
)
|
||||
|
||||
|
||||
class CreateChat(BaseModel):
|
||||
model_config = ConfigDict(extra="forbid")
|
||||
|
||||
title: NonBlankStr = Field(
|
||||
min_length=CHAT_TITLE_MIN_LENGTH,
|
||||
max_length=CHAT_TITLE_MAX_LENGTH,
|
||||
)
|
||||
# только форма; повторы, существование и вызывающего в списке
|
||||
# проверяет ChatService.create_chat
|
||||
member_ids: list[UuidIn] = Field(
|
||||
min_length=CHAT_MEMBERS_MIN,
|
||||
max_length=CHAT_MEMBERS_MAX,
|
||||
)
|
||||
|
||||
|
||||
class Chat(BaseModel):
|
||||
model_config = ConfigDict(from_attributes=True)
|
||||
|
||||
id: UUID
|
||||
title: str
|
||||
member_ids: list[UUID]
|
||||
created_at: UtcDatetime
|
||||
|
||||
|
||||
class ChatPage(BaseModel):
|
||||
model_config = ConfigDict(from_attributes=True)
|
||||
|
||||
items: list[Chat]
|
||||
next_cursor: str | None
|
||||
@@ -0,0 +1,77 @@
|
||||
"""Общие типы HTTP-моделей: строки, UUID входа, время, ошибки, health."""
|
||||
|
||||
import re
|
||||
from datetime import datetime
|
||||
from enum import StrEnum
|
||||
from typing import Annotated, Literal
|
||||
from uuid import UUID
|
||||
|
||||
from pydantic import (
|
||||
AfterValidator,
|
||||
BaseModel,
|
||||
BeforeValidator,
|
||||
PlainSerializer,
|
||||
StrictStr,
|
||||
)
|
||||
|
||||
from src.utils.constants import UUID_PATTERN
|
||||
from src.utils.utc import to_rfc3339
|
||||
|
||||
|
||||
def _reject_blank(value: str) -> str:
|
||||
"""Строка из одних пробельных символов невалидна; значение не меняется."""
|
||||
if not value.strip():
|
||||
raise ValueError("must not be blank")
|
||||
return value
|
||||
|
||||
|
||||
def _require_uuid_form(value: object) -> object:
|
||||
"""Строка UUID — только в записи 8-4-4-4-12; не-строку разбирает `UUID`.
|
||||
|
||||
pydantic принимает и запись без дефисов, с `urn:uuid:` и в `{…}`, а
|
||||
контракт — только `format: uuid`. Тип не-строки (массив, число, bool)
|
||||
отвергает сам валидатор `UUID`.
|
||||
"""
|
||||
if isinstance(value, str) and not re.fullmatch(UUID_PATTERN, value):
|
||||
raise ValueError("must be a UUID in 8-4-4-4-12 form")
|
||||
return value
|
||||
|
||||
|
||||
# строгая строка: число не превращается в строку; пробелы не принимаются
|
||||
NonBlankStr = Annotated[StrictStr, AfterValidator(_reject_blank)]
|
||||
|
||||
# UUID, который передаёт клиент (путь и тело): запись контракта, цифры в
|
||||
# любом регистре. Модели ответов — обычный `UUID`
|
||||
UuidIn = Annotated[UUID, BeforeValidator(_require_uuid_form)]
|
||||
|
||||
# время в ответе: RFC 3339 UTC, всегда шесть знаков микросекунд и Z
|
||||
UtcDatetime = Annotated[
|
||||
datetime,
|
||||
PlainSerializer(to_rfc3339, return_type=str),
|
||||
]
|
||||
|
||||
|
||||
class ErrorCode(StrEnum):
|
||||
INVALID_REQUEST = "invalid_request"
|
||||
UNAUTHORIZED = "unauthorized"
|
||||
NOT_FOUND = "not_found"
|
||||
CONFLICT = "conflict"
|
||||
PAYLOAD_TOO_LARGE = "payload_too_large"
|
||||
UNSUPPORTED_MEDIA_TYPE = "unsupported_media_type"
|
||||
RATE_LIMITED = "rate_limited"
|
||||
UNAVAILABLE = "unavailable"
|
||||
INTERNAL_ERROR = "internal_error"
|
||||
|
||||
|
||||
class ErrorBody(BaseModel):
|
||||
code: ErrorCode
|
||||
message: str
|
||||
request_id: str
|
||||
|
||||
|
||||
class Error(BaseModel):
|
||||
error: ErrorBody
|
||||
|
||||
|
||||
class Health(BaseModel):
|
||||
status: Literal["ok"]
|
||||
@@ -0,0 +1,37 @@
|
||||
from uuid import UUID
|
||||
|
||||
from pydantic import BaseModel, ConfigDict, Field
|
||||
|
||||
from src.api.schemas.common import NonBlankStr, UtcDatetime
|
||||
from src.utils.constants import (
|
||||
MESSAGE_TEXT_MAX_LENGTH,
|
||||
MESSAGE_TEXT_MIN_LENGTH,
|
||||
)
|
||||
|
||||
|
||||
class CreateMessage(BaseModel):
|
||||
"""Отправитель берётся из идентификации; поле sender_id — 400."""
|
||||
|
||||
model_config = ConfigDict(extra="forbid")
|
||||
|
||||
text: NonBlankStr = Field(
|
||||
min_length=MESSAGE_TEXT_MIN_LENGTH,
|
||||
max_length=MESSAGE_TEXT_MAX_LENGTH,
|
||||
)
|
||||
|
||||
|
||||
class Message(BaseModel):
|
||||
model_config = ConfigDict(from_attributes=True)
|
||||
|
||||
id: UUID
|
||||
chat_id: UUID
|
||||
sender_id: UUID
|
||||
text: str
|
||||
created_at: UtcDatetime
|
||||
|
||||
|
||||
class MessagePage(BaseModel):
|
||||
model_config = ConfigDict(from_attributes=True)
|
||||
|
||||
items: list[Message]
|
||||
next_cursor: str | None
|
||||
@@ -0,0 +1,15 @@
|
||||
from typing import Literal
|
||||
|
||||
from pydantic import BaseModel, ConfigDict
|
||||
|
||||
from src.api.schemas.common import UtcDatetime
|
||||
from src.api.schemas.user import User
|
||||
|
||||
|
||||
class Session(BaseModel):
|
||||
model_config = ConfigDict(from_attributes=True)
|
||||
|
||||
token: str
|
||||
token_type: Literal["Bearer"] = "Bearer"
|
||||
expires_at: UtcDatetime
|
||||
user: User
|
||||
@@ -0,0 +1,37 @@
|
||||
from uuid import UUID
|
||||
|
||||
from pydantic import BaseModel, ConfigDict, Field, StrictStr
|
||||
|
||||
from src.api.schemas.common import NonBlankStr, UtcDatetime
|
||||
from src.utils.constants import (
|
||||
DISPLAY_NAME_MAX_LENGTH,
|
||||
DISPLAY_NAME_MIN_LENGTH,
|
||||
PASSWORD_MAX_LENGTH,
|
||||
PASSWORD_MIN_LENGTH,
|
||||
USERNAME_PATTERN,
|
||||
)
|
||||
|
||||
|
||||
class CreateUser(BaseModel):
|
||||
model_config = ConfigDict(extra="forbid")
|
||||
|
||||
username: StrictStr = Field(pattern=USERNAME_PATTERN)
|
||||
display_name: NonBlankStr = Field(
|
||||
min_length=DISPLAY_NAME_MIN_LENGTH,
|
||||
max_length=DISPLAY_NAME_MAX_LENGTH,
|
||||
)
|
||||
# длина в code points; значение не обрезается и не нормализуется
|
||||
password: NonBlankStr = Field(
|
||||
min_length=PASSWORD_MIN_LENGTH,
|
||||
max_length=PASSWORD_MAX_LENGTH,
|
||||
json_schema_extra={"writeOnly": True},
|
||||
)
|
||||
|
||||
|
||||
class User(BaseModel):
|
||||
model_config = ConfigDict(from_attributes=True)
|
||||
|
||||
id: UUID
|
||||
username: str
|
||||
display_name: str
|
||||
created_at: UtcDatetime
|
||||
Reference in New Issue
Block a user