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:
2026-09-30 22:11:46 +03:00
co-authored by Claude Opus 5.5
parent 65003b6119
commit 7b775a29a9
174 changed files with 19023 additions and 11 deletions
View File
+96
View File
@@ -0,0 +1,96 @@
"""Зависимости ручек: хранилище, сервисы, текущий пользователь, страница."""
from dataclasses import dataclass
from typing import Annotated
from fastapi import Depends, Query, Request, Security
from fastapi.security import APIKeyHeader
from src.core import exceptions
from src.core.services import ChatService, MessageService, UserService
from src.infra.logger import current_user_id
from src.infra.memory import MemoryStore
from src.schemas import dataclasses
from src.utils.constants import (
PAGE_LIMIT_DEFAULT,
PAGE_LIMIT_MAX,
PAGE_LIMIT_MIN,
USER_ID_HEADER,
)
async def get_store(request: Request) -> MemoryStore:
"""Хранилище из lifespan; до его создания — 503."""
store: MemoryStore | None = getattr(request.app.state, "store", None)
if store is None:
raise exceptions.ServiceUnavailable
return store
StoreDep = Annotated[MemoryStore, Depends(get_store)]
async def get_user_service(store: StoreDep) -> UserService:
return UserService(store=store)
async def get_chat_service(store: StoreDep) -> ChatService:
return ChatService(store=store)
async def get_message_service(store: StoreDep) -> MessageService:
return MessageService(store=store)
UserServiceDep = Annotated[UserService, Depends(get_user_service)]
ChatServiceDep = Annotated[ChatService, Depends(get_chat_service)]
MessageServiceDep = Annotated[MessageService, Depends(get_message_service)]
# схема devUser из contracts/openapi.json: кнопка Authorize в /docs.
# auto_error=False — нет заголовка даёт None, а не ошибку FastAPI: 401 в
# формате контракта бросает сервис. Типизированный `Header()` не подходит:
# он уходит в валидацию и дал бы 400 вместо 401
user_id_scheme = APIKeyHeader(
name=USER_ID_HEADER,
scheme_name="devUser",
description=(
"Только учебная lab1: существующий UUID. Не является аутентификацией."
),
auto_error=False,
)
async def get_current_user(
raw_user_id: Annotated[str | None, Security(user_id_scheme)],
users: UserServiceDep,
) -> dataclasses.UserFullDTO:
"""Текущий пользователь по X-User-Id; иначе 401.
С лабы 2 здесь будет Bearer-сессия (своя схема безопасности).
"""
user = await users.identify(raw_user_id=raw_user_id)
current_user_id.set(str(user.id))
return 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)]
+128
View File
@@ -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)
+5
View File
@@ -0,0 +1,5 @@
from .request_context import RequestContextMiddleware
__all__ = [
"RequestContextMiddleware",
]
+97
View File
@@ -0,0 +1,97 @@
"""Request 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.infra.logger import AbstractLogger, get_logger, http_request_id
from src.utils.constants import HEALTH_PATHS, REQUEST_ID_HEADER
logger: AbstractLogger = get_logger().bind(middleware="http")
_REQUEST_ID_HEADER = REQUEST_ID_HEADER.lower().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_request_id(message: Message) -> None:
nonlocal status_code
if message["type"] == "http.response.start":
status_code = message["status"]
headers = list(message.get("headers", []))
if not any(
name.lower() == _REQUEST_ID_HEADER for name, _ in headers
):
headers.append(
(_REQUEST_ID_HEADER, request_id.encode("ascii")),
)
message = {**message, "headers": headers}
await send(message)
try:
await self.app(scope, receive, send_with_request_id)
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,
),
)
+7
View File
@@ -0,0 +1,7 @@
from .health import router as health_router
from .v1 import v1_router
__all__ = [
"health_router",
"v1_router",
]
+25
View File
@@ -0,0 +1,25 @@
from fastapi import APIRouter, Depends
from src.api.dependencies import get_store
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(get_store)],
)
async def readiness() -> Health:
"""Хранилище создано — можно обслуживать запросы; иначе 503."""
return Health(status="ok")
+22
View File
@@ -0,0 +1,22 @@
"""Ручки 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 .user import router as user_router
v1_router = APIRouter(prefix=API_V1_PREFIX)
v1_router.include_router(user_router)
v1_router.include_router(chat_router)
v1_router.include_router(message_router)
__all__ = [
"v1_router",
]
+46
View File
@@ -0,0 +1,46 @@
from uuid import UUID
from fastapi import APIRouter
from src.api.dependencies import ChatServiceDep, CurrentUser, PageQueryDep
from src.api.schemas import Chat, ChatPage, CreateChat
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: UUID,
chats: ChatServiceDep,
) -> Chat:
chat = await chats.get_chat_for_member(chat_id=chat_id, user_id=user.id)
return Chat.model_validate(chat)
+39
View File
@@ -0,0 +1,39 @@
from uuid import UUID
from fastapi import APIRouter
from src.api.dependencies import CurrentUser, MessageServiceDep, PageQueryDep
from src.api.schemas import CreateMessage, Message, MessagePage
router = APIRouter(prefix="/chats/{chat_id}/messages", tags=["messages"])
@router.post("", status_code=201, response_model=Message)
async def send_message(
user: CurrentUser,
chat_id: UUID,
body: CreateMessage,
messages: MessageServiceDep,
) -> Message:
message = await messages.send_message(
chat_id=chat_id,
sender_id=user.id,
text=body.text,
)
return Message.model_validate(message)
@router.get("", response_model=MessagePage)
async def list_messages(
user: CurrentUser,
chat_id: UUID,
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)
+20
View File
@@ -0,0 +1,20 @@
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,
)
return User.model_validate(user)
@router.get("/me", response_model=User)
async def get_me(user: CurrentUser) -> User:
return User.model_validate(user)
+19
View File
@@ -0,0 +1,19 @@
from .chat import Chat, ChatPage, CreateChat
from .common import Error, ErrorBody, ErrorCode, Health
from .message import CreateMessage, Message, MessagePage
from .user import CreateUser, User
__all__ = [
"Chat",
"ChatPage",
"CreateChat",
"CreateMessage",
"CreateUser",
"Error",
"ErrorBody",
"ErrorCode",
"Health",
"Message",
"MessagePage",
"User",
]
+42
View File
@@ -0,0 +1,42 @@
from uuid import UUID
from pydantic import BaseModel, ConfigDict, Field
from src.api.schemas.common import NonBlankStr, UtcDatetime
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[UUID] = 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
+52
View File
@@ -0,0 +1,52 @@
"""Общие типы HTTP-моделей: строки, время, ошибки, health."""
from datetime import datetime
from enum import StrEnum
from typing import Annotated, Literal
from pydantic import AfterValidator, BaseModel, PlainSerializer, StrictStr
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
# строгая строка: число не превращается в строку; пробелы не принимаются
NonBlankStr = Annotated[StrictStr, AfterValidator(_reject_blank)]
# время в ответе: 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"]
+37
View File
@@ -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
+29
View File
@@ -0,0 +1,29 @@
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,
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,
)
class User(BaseModel):
model_config = ConfigDict(from_attributes=True)
id: UUID
username: str
display_name: str
created_at: UtcDatetime