forked from mtusi2026/mtusi2026lab2
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,15 @@
|
||||
from .base import DomainError
|
||||
from .chat import ChatNotFound, InvalidChatMembers
|
||||
from .pagination import InvalidCursor
|
||||
from .service import ServiceUnavailable
|
||||
from .user import Unidentified, UsernameTaken
|
||||
|
||||
__all__ = [
|
||||
"ChatNotFound",
|
||||
"DomainError",
|
||||
"InvalidChatMembers",
|
||||
"InvalidCursor",
|
||||
"ServiceUnavailable",
|
||||
"Unidentified",
|
||||
"UsernameTaken",
|
||||
]
|
||||
@@ -0,0 +1,12 @@
|
||||
class DomainError(Exception):
|
||||
"""Базовое доменное исключение.
|
||||
|
||||
Текст уходит клиенту в `error.message`, поэтому он на английском, без
|
||||
внутренних деталей и без признаков существования чужих объектов.
|
||||
Статус и `code` назначает `src/api/errors.py`.
|
||||
"""
|
||||
|
||||
default_message = "Invalid request"
|
||||
|
||||
def __init__(self, message: str | None = None) -> None:
|
||||
super().__init__(message or self.default_message)
|
||||
@@ -0,0 +1,17 @@
|
||||
from .base import DomainError
|
||||
|
||||
|
||||
class ChatNotFound(DomainError):
|
||||
"""Чата нет или текущий пользователь в нём не состоит.
|
||||
|
||||
Оба случая дают одно исключение, чтобы не раскрывать существование
|
||||
чужого чата.
|
||||
"""
|
||||
|
||||
default_message = "Not found"
|
||||
|
||||
|
||||
class InvalidChatMembers(DomainError):
|
||||
"""Участник не существует или вызывающего нет в member_ids."""
|
||||
|
||||
default_message = "Invalid chat members"
|
||||
@@ -0,0 +1,7 @@
|
||||
from .base import DomainError
|
||||
|
||||
|
||||
class InvalidCursor(DomainError):
|
||||
"""Курсор повреждён или выдан для другого списка."""
|
||||
|
||||
default_message = "Invalid cursor"
|
||||
@@ -0,0 +1,7 @@
|
||||
from .base import DomainError
|
||||
|
||||
|
||||
class ServiceUnavailable(DomainError):
|
||||
"""Сервис ещё не готов обслуживать запросы: хранилище не создано."""
|
||||
|
||||
default_message = "Service is not ready"
|
||||
@@ -0,0 +1,13 @@
|
||||
from .base import DomainError
|
||||
|
||||
|
||||
class Unidentified(DomainError):
|
||||
"""Нет X-User-Id, он не UUID или такого пользователя нет."""
|
||||
|
||||
default_message = "User identification required"
|
||||
|
||||
|
||||
class UsernameTaken(DomainError):
|
||||
"""username уже занят."""
|
||||
|
||||
default_message = "Username is already taken"
|
||||
@@ -0,0 +1,50 @@
|
||||
import bisect
|
||||
from uuid import UUID
|
||||
|
||||
from src.infra.memory import MemoryStore
|
||||
from src.schemas import dataclasses
|
||||
from src.utils.cursor import CursorKey
|
||||
|
||||
|
||||
def _chat_key(chat: dataclasses.ChatFullDTO) -> CursorKey:
|
||||
return (chat.created_at, chat.id)
|
||||
|
||||
|
||||
async def insert_chat(
|
||||
store: MemoryStore,
|
||||
*,
|
||||
chat: dataclasses.ChatFullDTO,
|
||||
) -> dataclasses.ChatFullDTO:
|
||||
"""Чат, его место в списках всех участников и пустая история — разом."""
|
||||
store.chats[chat.id] = chat
|
||||
for member_id in chat.member_ids:
|
||||
bisect.insort(
|
||||
store.chats_by_user.setdefault(member_id, []),
|
||||
chat,
|
||||
key=_chat_key,
|
||||
)
|
||||
store.messages_by_chat[chat.id] = []
|
||||
return chat
|
||||
|
||||
|
||||
async def get_chat(
|
||||
store: MemoryStore,
|
||||
*,
|
||||
chat_id: UUID,
|
||||
) -> dataclasses.ChatFullDTO | None:
|
||||
return store.chats.get(chat_id)
|
||||
|
||||
|
||||
async def get_user_chats_page(
|
||||
store: MemoryStore,
|
||||
*,
|
||||
user_id: UUID,
|
||||
after: CursorKey | None,
|
||||
limit: int,
|
||||
) -> list[dataclasses.ChatFullDTO]:
|
||||
"""До `limit + 1` чатов пользователя строго после ключа `after`."""
|
||||
chats = store.chats_by_user.get(user_id, [])
|
||||
start = 0
|
||||
if after is not None:
|
||||
start = bisect.bisect_right(chats, after, key=_chat_key)
|
||||
return chats[start : start + limit + 1]
|
||||
@@ -0,0 +1,38 @@
|
||||
import bisect
|
||||
from uuid import UUID
|
||||
|
||||
from src.infra.memory import MemoryStore
|
||||
from src.schemas import dataclasses
|
||||
from src.utils.cursor import CursorKey
|
||||
|
||||
|
||||
def _message_key(message: dataclasses.MessageFullDTO) -> CursorKey:
|
||||
return (message.created_at, message.id)
|
||||
|
||||
|
||||
async def insert_message(
|
||||
store: MemoryStore,
|
||||
*,
|
||||
message: dataclasses.MessageFullDTO,
|
||||
) -> dataclasses.MessageFullDTO:
|
||||
bisect.insort(
|
||||
store.messages_by_chat[message.chat_id],
|
||||
message,
|
||||
key=_message_key,
|
||||
)
|
||||
return message
|
||||
|
||||
|
||||
async def get_chat_messages_page(
|
||||
store: MemoryStore,
|
||||
*,
|
||||
chat_id: UUID,
|
||||
after: CursorKey | None,
|
||||
limit: int,
|
||||
) -> list[dataclasses.MessageFullDTO]:
|
||||
"""До `limit + 1` сообщений чата строго после ключа `after`."""
|
||||
messages = store.messages_by_chat.get(chat_id, [])
|
||||
start = 0
|
||||
if after is not None:
|
||||
start = bisect.bisect_right(messages, after, key=_message_key)
|
||||
return messages[start : start + limit + 1]
|
||||
@@ -0,0 +1,36 @@
|
||||
from collections.abc import Iterable
|
||||
from uuid import UUID
|
||||
|
||||
from src.infra.memory import MemoryStore
|
||||
from src.schemas import dataclasses
|
||||
|
||||
|
||||
async def insert_user(
|
||||
store: MemoryStore,
|
||||
*,
|
||||
user: dataclasses.UserFullDTO,
|
||||
) -> dataclasses.UserFullDTO | None:
|
||||
"""Вставка с проверкой уникальности username; конфликт — None."""
|
||||
if user.username in store.user_id_by_username:
|
||||
return None
|
||||
store.users[user.id] = user
|
||||
store.user_id_by_username[user.username] = user.id
|
||||
store.chats_by_user[user.id] = []
|
||||
return user
|
||||
|
||||
|
||||
async def get_user(
|
||||
store: MemoryStore,
|
||||
*,
|
||||
user_id: UUID,
|
||||
) -> dataclasses.UserFullDTO | None:
|
||||
return store.users.get(user_id)
|
||||
|
||||
|
||||
async def get_existing_user_ids(
|
||||
store: MemoryStore,
|
||||
*,
|
||||
user_ids: Iterable[UUID],
|
||||
) -> set[UUID]:
|
||||
"""Те из переданных id, для которых пользователь существует."""
|
||||
return {user_id for user_id in user_ids if user_id in store.users}
|
||||
@@ -0,0 +1,9 @@
|
||||
from .chat import ChatService
|
||||
from .message import MessageService
|
||||
from .user import UserService
|
||||
|
||||
__all__ = [
|
||||
"ChatService",
|
||||
"MessageService",
|
||||
"UserService",
|
||||
]
|
||||
@@ -0,0 +1,86 @@
|
||||
from collections.abc import Sequence
|
||||
from uuid import UUID, uuid4
|
||||
|
||||
from src.core import exceptions
|
||||
from src.core.repos import chat as chat_repo
|
||||
from src.core.repos import user as user_repo
|
||||
from src.core.services.pagination import decode_page_cursor, split_page
|
||||
from src.infra.logger import AbstractLogger, get_logger
|
||||
from src.infra.memory import MemoryStore
|
||||
from src.schemas import dataclasses
|
||||
from src.utils.cursor import user_chats_scope
|
||||
from src.utils.utc import utcnow
|
||||
|
||||
logger: AbstractLogger = get_logger().bind(module="chat_service")
|
||||
|
||||
|
||||
class ChatService:
|
||||
def __init__(self, store: MemoryStore) -> None:
|
||||
self.store = store
|
||||
|
||||
async def create_chat(
|
||||
self,
|
||||
*,
|
||||
current_user_id: UUID,
|
||||
title: str,
|
||||
member_ids: Sequence[UUID],
|
||||
) -> dataclasses.ChatFullDTO:
|
||||
log = logger.bind(method="create_chat", members_count=len(member_ids))
|
||||
unique_ids = set(member_ids)
|
||||
if (
|
||||
len(unique_ids) != len(member_ids)
|
||||
or current_user_id not in unique_ids
|
||||
):
|
||||
log.info("Rejected chat members: duplicates or caller missing")
|
||||
raise exceptions.InvalidChatMembers
|
||||
# пользователей не удаляют, поэтому проверка до вставки не устареет
|
||||
existing_ids = await user_repo.get_existing_user_ids(
|
||||
store=self.store,
|
||||
user_ids=unique_ids,
|
||||
)
|
||||
if existing_ids != unique_ids:
|
||||
log.info("Rejected chat members: unknown users")
|
||||
raise exceptions.InvalidChatMembers
|
||||
|
||||
chat = dataclasses.ChatFullDTO(
|
||||
id=uuid4(),
|
||||
title=title,
|
||||
member_ids=tuple(member_ids),
|
||||
created_at=utcnow(),
|
||||
)
|
||||
await chat_repo.insert_chat(store=self.store, chat=chat)
|
||||
log.info("Created chat", chat_id=chat.id)
|
||||
return chat
|
||||
|
||||
async def get_chat_for_member(
|
||||
self,
|
||||
*,
|
||||
chat_id: UUID,
|
||||
user_id: UUID,
|
||||
) -> dataclasses.ChatFullDTO:
|
||||
"""Чат, если пользователь в нём состоит; иначе `ChatNotFound`.
|
||||
|
||||
Нет чата и чужой чат неразличимы: 404 не раскрывает существование.
|
||||
"""
|
||||
chat = await chat_repo.get_chat(store=self.store, chat_id=chat_id)
|
||||
if chat is None or user_id not in chat.member_ids:
|
||||
raise exceptions.ChatNotFound
|
||||
return chat
|
||||
|
||||
async def list_user_chats(
|
||||
self,
|
||||
*,
|
||||
user_id: UUID,
|
||||
limit: int,
|
||||
cursor: str | None,
|
||||
) -> dataclasses.ChatPageDTO:
|
||||
scope = user_chats_scope(user_id)
|
||||
after = decode_page_cursor(cursor, scope=scope)
|
||||
rows = await chat_repo.get_user_chats_page(
|
||||
store=self.store,
|
||||
user_id=user_id,
|
||||
after=after,
|
||||
limit=limit,
|
||||
)
|
||||
items, next_cursor = split_page(rows, limit=limit, scope=scope)
|
||||
return dataclasses.ChatPageDTO(items=items, next_cursor=next_cursor)
|
||||
@@ -0,0 +1,68 @@
|
||||
from uuid import UUID, uuid4
|
||||
|
||||
from src.core.repos import message as message_repo
|
||||
from src.core.services.chat import ChatService
|
||||
from src.core.services.pagination import decode_page_cursor, split_page
|
||||
from src.infra.logger import AbstractLogger, get_logger
|
||||
from src.infra.memory import MemoryStore
|
||||
from src.schemas import dataclasses
|
||||
from src.utils.cursor import chat_messages_scope
|
||||
from src.utils.utc import utcnow
|
||||
|
||||
logger: AbstractLogger = get_logger().bind(module="message_service")
|
||||
|
||||
|
||||
class MessageService:
|
||||
def __init__(self, store: MemoryStore) -> None:
|
||||
self.store = store
|
||||
|
||||
async def send_message(
|
||||
self,
|
||||
*,
|
||||
chat_id: UUID,
|
||||
sender_id: UUID,
|
||||
text: str,
|
||||
) -> dataclasses.MessageFullDTO:
|
||||
log = logger.bind(method="send_message", chat_id=chat_id)
|
||||
# состав чата не меняется, поэтому проверка членства не устареет
|
||||
await ChatService(store=self.store).get_chat_for_member(
|
||||
chat_id=chat_id,
|
||||
user_id=sender_id,
|
||||
)
|
||||
message = dataclasses.MessageFullDTO(
|
||||
id=uuid4(),
|
||||
chat_id=chat_id,
|
||||
sender_id=sender_id,
|
||||
text=text,
|
||||
created_at=utcnow(),
|
||||
)
|
||||
await message_repo.insert_message(store=self.store, message=message)
|
||||
log.info(
|
||||
"Created message",
|
||||
message_id=message.id,
|
||||
text_length=len(text),
|
||||
)
|
||||
return message
|
||||
|
||||
async def list_messages(
|
||||
self,
|
||||
*,
|
||||
chat_id: UUID,
|
||||
user_id: UUID,
|
||||
limit: int,
|
||||
cursor: str | None,
|
||||
) -> dataclasses.MessagePageDTO:
|
||||
await ChatService(store=self.store).get_chat_for_member(
|
||||
chat_id=chat_id,
|
||||
user_id=user_id,
|
||||
)
|
||||
scope = chat_messages_scope(chat_id)
|
||||
after = decode_page_cursor(cursor, scope=scope)
|
||||
rows = await message_repo.get_chat_messages_page(
|
||||
store=self.store,
|
||||
chat_id=chat_id,
|
||||
after=after,
|
||||
limit=limit,
|
||||
)
|
||||
items, next_cursor = split_page(rows, limit=limit, scope=scope)
|
||||
return dataclasses.MessagePageDTO(items=items, next_cursor=next_cursor)
|
||||
@@ -0,0 +1,47 @@
|
||||
"""Общие шаги keyset-пагинации для сервисов списков."""
|
||||
|
||||
from collections.abc import Sequence
|
||||
|
||||
from src.core import exceptions
|
||||
from src.schemas import dataclasses
|
||||
from src.utils.cursor import (
|
||||
CursorError,
|
||||
CursorKey,
|
||||
decode_cursor,
|
||||
encode_cursor,
|
||||
)
|
||||
|
||||
type PageItem = dataclasses.ChatFullDTO | dataclasses.MessageFullDTO
|
||||
|
||||
|
||||
def decode_page_cursor(cursor: str | None, *, scope: str) -> CursorKey | None:
|
||||
"""Ключ из курсора; нет курсора — первая страница."""
|
||||
if cursor is None:
|
||||
return None
|
||||
try:
|
||||
return decode_cursor(cursor, scope=scope)
|
||||
except CursorError as e:
|
||||
raise exceptions.InvalidCursor from e
|
||||
|
||||
|
||||
def split_page[T: PageItem](
|
||||
rows: Sequence[T],
|
||||
*,
|
||||
limit: int,
|
||||
scope: str,
|
||||
) -> tuple[tuple[T, ...], str | None]:
|
||||
"""Страница и next_cursor из выборки repo длиной до `limit + 1`.
|
||||
|
||||
Лишний элемент означает, что следующая страница есть; курсор строится
|
||||
из последнего элемента страницы, а не из лишнего.
|
||||
"""
|
||||
items = tuple(rows[:limit])
|
||||
if len(rows) <= limit:
|
||||
return items, None
|
||||
last = items[-1]
|
||||
next_cursor = encode_cursor(
|
||||
scope=scope,
|
||||
created_at=last.created_at,
|
||||
item_id=last.id,
|
||||
)
|
||||
return items, next_cursor
|
||||
@@ -0,0 +1,56 @@
|
||||
from uuid import UUID, uuid4
|
||||
|
||||
from src.core import exceptions
|
||||
from src.core.repos import user as user_repo
|
||||
from src.infra.logger import AbstractLogger, get_logger
|
||||
from src.infra.memory import MemoryStore
|
||||
from src.schemas import dataclasses
|
||||
from src.utils.utc import utcnow
|
||||
|
||||
logger: AbstractLogger = get_logger().bind(module="user_service")
|
||||
|
||||
|
||||
class UserService:
|
||||
def __init__(self, store: MemoryStore) -> None:
|
||||
self.store = store
|
||||
|
||||
async def register(
|
||||
self,
|
||||
*,
|
||||
username: str,
|
||||
display_name: str,
|
||||
) -> dataclasses.UserFullDTO:
|
||||
log = logger.bind(method="register")
|
||||
user = dataclasses.UserFullDTO(
|
||||
id=uuid4(),
|
||||
username=username,
|
||||
display_name=display_name,
|
||||
created_at=utcnow(),
|
||||
)
|
||||
created = await user_repo.insert_user(store=self.store, user=user)
|
||||
if created is None:
|
||||
log.info("Username is already taken")
|
||||
raise exceptions.UsernameTaken
|
||||
log.info("Created user", created_user_id=created.id)
|
||||
return created
|
||||
|
||||
async def identify(
|
||||
self,
|
||||
*,
|
||||
raw_user_id: str | None,
|
||||
) -> dataclasses.UserFullDTO:
|
||||
"""Текущий пользователь по значению X-User-Id.
|
||||
|
||||
Нет заголовка, не UUID или пользователя нет — одинаковое
|
||||
`Unidentified`.
|
||||
"""
|
||||
if raw_user_id is None:
|
||||
raise exceptions.Unidentified
|
||||
try:
|
||||
user_id = UUID(raw_user_id)
|
||||
except ValueError:
|
||||
raise exceptions.Unidentified from None
|
||||
user = await user_repo.get_user(store=self.store, user_id=user_id)
|
||||
if user is None:
|
||||
raise exceptions.Unidentified
|
||||
return user
|
||||
Reference in New Issue
Block a user