from collections.abc import Sequence from uuid import UUID, uuid4 from sqlalchemy.ext.asyncio import AsyncSession from src.config import settings from src.core import exceptions from src.core.repos import chat as chat_repo from src.core.repos import chat_cache as chat_cache_repo from src.core.repos import user as user_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") class ChatService: """Чаты; карточка чата кэшируется в Valkey. Карточка после создания не меняется, поэтому кэш не инвалидируется (design change `membership-cache`, решение 2). """ def __init__(self, db_session: AsyncSession, cache: Cache) -> None: self.db_session = db_session 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 # пользователей не удаляют, поэтому проверка до вставки не устареет existing_ids = await user_repo.get_existing_user_ids( db_session=self.db_session, 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(db_session=self.db_session, chat=chat) await chat_repo.insert_chat_members( db_session=self.db_session, chat=chat, ) await self.db_session.commit() log.info("Created chat", chat_id=chat.id) # после commit: откат создания не оставит в кэше чата, которого # нет в БД 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: """Чат, если пользователь в нём состоит; иначе `ChatNotFound`. Нет чата и чужой чат неразличимы: 404 не раскрывает существование. Карточка — из кэша, при промахе — из БД с записью в кэш. Чат, которого нет, не кэшируется. """ chat = await chat_cache_repo.get_chat( cache=self.cache, chat_id=chat_id, ) if chat is None: chat = await chat_repo.get_chat( db_session=self.db_session, chat_id=chat_id, ) if chat is not None: await chat_cache_repo.put_chat( cache=self.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 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( db_session=self.db_session, 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)