"""`ChatService`: кэш после фиксации, откат составной операции, страницы.""" from uuid import UUID, uuid4 import pytest from builders import chat_dto, user_dto from fakes import FakeCache, FakeDatabase, FakeUnitOfWork from src.core import exceptions, services from src.core.repos import chat_cache from src.utils.cursor import chat_messages_scope, encode_cursor pytestmark = pytest.mark.anyio async def _users(uow: FakeUnitOfWork, count: int = 2) -> list[UUID]: users = [user_dto() for _ in range(count)] async with uow: for user in users: await uow.users.insert_user(user=user, password_hash="h") await uow.commit() return [user.id for user in users] async def test_create_chat_commits_then_caches( uow: FakeUnitOfWork, cache: FakeCache, database: FakeDatabase, ) -> None: alice, bob = await _users(uow) database.events.clear() chat = await services.ChatService(uow, cache).create_chat( current_user_id=alice, title="Team", member_ids=[alice, bob], ) assert database.chats[chat.id].member_ids == (alice, bob) assert database.events.index("commit") < database.events.index("cache.set") assert database.events.index("exit") < database.events.index("cache.set") assert await chat_cache.get_chat(cache, chat_id=chat.id) == chat @pytest.mark.parametrize("case", ["duplicates", "caller_missing"]) async def test_invalid_members_open_no_block( uow: FakeUnitOfWork, cache: FakeCache, database: FakeDatabase, case: str, ) -> None: alice, bob = await _users(uow) database.events.clear() members = [alice, alice] if case == "duplicates" else [bob] with pytest.raises(exceptions.InvalidChatMembers): await services.ChatService(uow, cache).create_chat( current_user_id=alice, title="Team", member_ids=members, ) assert "enter" not in database.events async def test_unknown_member_rejected( uow: FakeUnitOfWork, cache: FakeCache, database: FakeDatabase, ) -> None: alice, _ = await _users(uow) with pytest.raises(exceptions.InvalidChatMembers): await services.ChatService(uow, cache).create_chat( current_user_id=alice, title="Team", member_ids=[alice, uuid4()], ) assert database.chats == {} async def test_members_failure_rolls_back_chat_and_cache( uow: FakeUnitOfWork, cache: FakeCache, database: FakeDatabase, ) -> None: alice, bob = await _users(uow) database.fail_on["chats.insert_chat_members"] = ( exceptions.ServiceUnavailable() ) with pytest.raises(exceptions.ServiceUnavailable): await services.ChatService(uow, cache).create_chat( current_user_id=alice, title="Team", member_ids=[alice, bob], ) assert database.chats == {} assert cache.values == {} async def test_commit_failure_leaves_cache_empty( uow: FakeUnitOfWork, cache: FakeCache, database: FakeDatabase, ) -> None: alice, bob = await _users(uow) database.fail_commit = exceptions.ServiceUnavailable() with pytest.raises(exceptions.ServiceUnavailable): await services.ChatService(uow, cache).create_chat( current_user_id=alice, title="Team", member_ids=[alice, bob], ) assert database.chats == {} assert cache.values == {} async def test_cache_hit_does_not_touch_repo( uow: FakeUnitOfWork, cache: FakeCache, database: FakeDatabase, ) -> None: member = uuid4() chat = chat_dto(member_ids=(member,)) await chat_cache.put_chat(cache, chat=chat, ttl_seconds=60) database.events.clear() found = await services.ChatService(uow, cache).get_chat_for_member( chat_id=chat.id, user_id=member, ) assert found == chat assert "chats.get_chat" not in database.events async def test_cache_miss_reads_and_fills( uow: FakeUnitOfWork, cache: FakeCache, ) -> None: alice, _ = await _users(uow) chat = chat_dto(member_ids=(alice,)) async with uow: await uow.chats.insert_chat(chat=chat) await uow.chats.insert_chat_members(chat=chat) await uow.commit() found = await services.ChatService(uow, cache).get_chat_for_member( chat_id=chat.id, user_id=alice, ) assert found == chat assert await chat_cache.get_chat(cache, chat_id=chat.id) == chat async def test_outsider_and_missing_are_same_not_found( uow: FakeUnitOfWork, cache: FakeCache, ) -> None: alice, bob = await _users(uow) chat = chat_dto(member_ids=(alice,)) async with uow: await uow.chats.insert_chat(chat=chat) await uow.chats.insert_chat_members(chat=chat) await uow.commit() service = services.ChatService(uow, cache) with pytest.raises(exceptions.ChatNotFound): await service.get_chat_for_member(chat_id=chat.id, user_id=bob) absent = uuid4() with pytest.raises(exceptions.ChatNotFound): await service.get_chat_for_member(chat_id=absent, user_id=alice) # отсутствующий чат не кэшируется assert await chat_cache.get_chat(cache, chat_id=absent) is None async def test_failed_cache_falls_back_to_database( uow: FakeUnitOfWork, cache: FakeCache, ) -> None: alice, _ = await _users(uow) chat = chat_dto(member_ids=(alice,)) async with uow: await uow.chats.insert_chat(chat=chat) await uow.chats.insert_chat_members(chat=chat) await uow.commit() cache.failing = True found = await services.ChatService(uow, cache).get_chat_for_member( chat_id=chat.id, user_id=alice, ) assert found == chat async def test_pages_and_foreign_cursor( uow: FakeUnitOfWork, cache: FakeCache, ) -> None: alice, _ = await _users(uow) service = services.ChatService(uow, cache) created = [ await service.create_chat( current_user_id=alice, title=f"T{index}", member_ids=[alice], ) for index in range(3) ] first = await service.list_user_chats( user_id=alice, limit=2, cursor=None, ) assert [item.id for item in first.items] == [ chat.id for chat in created[:2] ] assert first.next_cursor is not None second = await service.list_user_chats( user_id=alice, limit=2, cursor=first.next_cursor, ) assert [item.id for item in second.items] == [created[2].id] assert second.next_cursor is None foreign = encode_cursor( scope=chat_messages_scope(uuid4()), created_at=created[0].created_at, item_id=created[0].id, ) with pytest.raises(exceptions.InvalidCursor): await service.list_user_chats(user_id=alice, limit=2, cursor=foreign)