chore: port lab 5 solution into the lab 6 skeleton
Source: mtusi2026lab5-safronov, solution/bvt2301-safronov, 046ec9e. Contracts, public tests and evidence of lab 5 are not carried over. The compose project, image and CI prefix are renamed to lab6; the first broker start defect is recorded in KNOWN_ISSUES.md; PLAN.md outlines the OpenSpec changes of lab 6. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
@@ -0,0 +1,134 @@
|
||||
from collections.abc import Sequence
|
||||
from uuid import UUID, uuid4
|
||||
|
||||
from src.config import settings
|
||||
from src.core import exceptions
|
||||
from src.core.ports.uow import AbstractUnitOfWork
|
||||
from src.core.repos import chat_cache as chat_cache_repo
|
||||
from src.core.services.pagination import decode_page_cursor, split_page
|
||||
from src.infra.cache import Cache
|
||||
from src.infra.logger import AbstractLogger, get_logger
|
||||
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")
|
||||
|
||||
|
||||
async def require_member(
|
||||
uow: AbstractUnitOfWork,
|
||||
cache: Cache,
|
||||
*,
|
||||
chat_id: UUID,
|
||||
user_id: UUID,
|
||||
) -> dataclasses.ChatFullDTO:
|
||||
"""Чат, если пользователь в нём состоит; иначе `ChatNotFound`. Требует
|
||||
открытый блок: членство нужно и внутри чужого блока (сообщение, вложение).
|
||||
|
||||
Нет чата и чужой чат неразличимы: 404 не раскрывает существование.
|
||||
Карточка — из кэша, при промахе — из БД с записью в кэш. Чат, которого
|
||||
нет, не кэшируется. При попадании в кэш соединение не выдаётся: выдача
|
||||
ленивая.
|
||||
"""
|
||||
chat = await chat_cache_repo.get_chat(cache=cache, chat_id=chat_id)
|
||||
if chat is None:
|
||||
chat = await uow.chats.get_chat(chat_id=chat_id)
|
||||
if chat is not None:
|
||||
await chat_cache_repo.put_chat(
|
||||
cache=cache,
|
||||
chat=chat,
|
||||
ttl_seconds=settings.cache.chat_ttl_seconds,
|
||||
)
|
||||
if chat is None or user_id not in chat.member_ids:
|
||||
raise exceptions.ChatNotFound
|
||||
return chat
|
||||
|
||||
|
||||
class ChatService:
|
||||
"""Чаты; карточка чата кэшируется в Valkey.
|
||||
|
||||
Карточка после создания не меняется, поэтому кэш не инвалидируется
|
||||
(design change `membership-cache`, решение 2).
|
||||
"""
|
||||
|
||||
def __init__(self, uow: AbstractUnitOfWork, cache: Cache) -> None:
|
||||
self.uow = uow
|
||||
self.cache = cache
|
||||
|
||||
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
|
||||
async with self.uow:
|
||||
# пользователей не удаляют, поэтому проверка до вставки не устареет
|
||||
existing_ids = await self.uow.users.get_existing_user_ids(
|
||||
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 self.uow.chats.insert_chat(chat=chat)
|
||||
await self.uow.chats.insert_chat_members(chat=chat)
|
||||
await self.uow.commit()
|
||||
log.info("Created chat", chat_id=chat.id)
|
||||
# после блока: откат создания не оставит в кэше чата, которого нет
|
||||
# в БД
|
||||
await chat_cache_repo.put_chat(
|
||||
cache=self.cache,
|
||||
chat=chat,
|
||||
ttl_seconds=settings.cache.chat_ttl_seconds,
|
||||
)
|
||||
return chat
|
||||
|
||||
async def get_chat_for_member(
|
||||
self,
|
||||
*,
|
||||
chat_id: UUID,
|
||||
user_id: UUID,
|
||||
) -> dataclasses.ChatFullDTO:
|
||||
"""Чат для участника; см. `require_member`."""
|
||||
async with self.uow:
|
||||
return await require_member(
|
||||
self.uow,
|
||||
self.cache,
|
||||
chat_id=chat_id,
|
||||
user_id=user_id,
|
||||
)
|
||||
|
||||
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)
|
||||
async with self.uow:
|
||||
rows = await self.uow.chats.get_user_chats_page(
|
||||
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)
|
||||
Reference in New Issue
Block a user