"""`MessageService`: один блок на отправку, порядок членство → вложения → ключ.""" from dataclasses import dataclass from uuid import UUID, uuid4 import pytest from builders import attachment_dto, chat_dto, user_dto from fakes import FakeCache, FakeDatabase, FakeUnitOfWork from src.core import exceptions, services from src.core.services.message import message_request_hash from src.schemas.enums import AttachmentErrorCode, AttachmentStatus pytestmark = pytest.mark.anyio KEY = "key-1" @dataclass class World: alice: UUID bob: UUID chat_id: UUID @pytest.fixture async def world(uow: FakeUnitOfWork, database: FakeDatabase) -> World: alice = user_dto() bob = user_dto() chat = chat_dto(member_ids=(alice.id,)) async with uow: await uow.users.insert_user(user=alice, password_hash="h") await uow.users.insert_user(user=bob, password_hash="h") await uow.chats.insert_chat(chat=chat) await uow.chats.insert_chat_members(chat=chat) await uow.commit() database.events.clear() return World(alice.id, bob.id, chat.id) @pytest.fixture def service(uow: FakeUnitOfWork, cache: FakeCache) -> services.MessageService: return services.MessageService(uow, cache) async def _attachment( uow: FakeUnitOfWork, world: World, *, status: AttachmentStatus = AttachmentStatus.READY, chat_id: UUID | None = None, ) -> UUID: row = attachment_dto( chat_id=chat_id or world.chat_id, owner_id=world.alice, status=status, ) async with uow: await uow.attachments.insert_attachment(attachment=row) await uow.commit() return row.id async def _failed(uow: FakeUnitOfWork, world: World) -> UUID: attachment_id = await _attachment( uow, world, status=AttachmentStatus.QUEUED, ) async with uow: await uow.attachments.commit_failed( attachment_id=attachment_id, error_code=AttachmentErrorCode.INVALID_IMAGE, updated_at=attachment_dto( chat_id=world.chat_id, owner_id=world.alice, ).created_at, ) await uow.commit() return attachment_id async def _send( service: services.MessageService, world: World, *, text: str = "hello", attachment_ids: tuple[UUID, ...] = (), sender: UUID | None = None, ): return await service.send_message( chat_id=world.chat_id, sender_id=sender or world.alice, text=text, idempotency_key=KEY, attachment_ids=attachment_ids, ) async def test_new_message_one_block( service: services.MessageService, database: FakeDatabase, world: World, ) -> None: message = await _send(service, world) assert database.messages[message.id].text == "hello" assert database.events.count("enter") == 1 assert database.events[-2:] == ["commit", "exit"] assert database.events.index( "idempotency.claim_key", ) < database.events.index("messages.insert_message") async def test_replay_same_body_returns_saved( service: services.MessageService, database: FakeDatabase, world: World, ) -> None: first = await _send(service, world) database.events.clear() second = await _send(service, world) assert second == first assert len(database.messages) == 1 assert "messages.insert_message" not in database.events # блокировка строки ключа снимается фиксацией до ответа assert database.events[-2:] == ["commit", "exit"] async def test_other_body_conflict_after_commit( service: services.MessageService, database: FakeDatabase, world: World, ) -> None: await _send(service, world) database.events.clear() with pytest.raises(exceptions.IdempotencyConflict): await _send(service, world, text="other") assert "commit" in database.events assert len(database.messages) == 1 async def test_failed_attachment_new_key_rolled_back( service: services.MessageService, uow: FakeUnitOfWork, database: FakeDatabase, world: World, ) -> None: failed = await _failed(uow, world) with pytest.raises(exceptions.AttachmentFailed): await _send(service, world, attachment_ids=(failed,)) assert database.idempotency == {} assert database.messages == {} # ключ свободен: то же тело без вложения проходит message = await _send(service, world) assert message.attachment_ids == () async def test_failed_attachment_taken_key_is_replay( service: services.MessageService, uow: FakeUnitOfWork, world: World, ) -> None: attachment_id = await _attachment( uow, world, status=AttachmentStatus.QUEUED, ) first = await _send(service, world, attachment_ids=(attachment_id,)) async with uow: await uow.attachments.commit_failed( attachment_id=attachment_id, error_code=AttachmentErrorCode.INVALID_IMAGE, updated_at=first.created_at, ) await uow.commit() replay = await _send(service, world, attachment_ids=(attachment_id,)) assert replay == first @pytest.mark.parametrize("case", ["unknown", "pending", "other_chat"]) async def test_bad_attachment_rejected_before_key( service: services.MessageService, uow: FakeUnitOfWork, database: FakeDatabase, world: World, case: str, ) -> None: attachment_id = uuid4() if case == "pending": attachment_id = await _attachment( uow, world, status=AttachmentStatus.PENDING, ) elif case == "other_chat": attachment_id = await _attachment(uow, world, chat_id=uuid4()) database.events.clear() with pytest.raises(exceptions.AttachmentNotFound): await _send(service, world, attachment_ids=(attachment_id,)) assert "idempotency.claim_key" not in database.events assert database.idempotency == {} async def test_attachment_order_kept( service: services.MessageService, uow: FakeUnitOfWork, database: FakeDatabase, world: World, ) -> None: ids = tuple( sorted( [await _attachment(uow, world) for _ in range(3)], reverse=True, ), ) message = await _send(service, world, attachment_ids=ids) assert message.attachment_ids == ids assert database.messages[message.id].attachment_ids == ids async def test_write_failure_leaves_key_free( service: services.MessageService, database: FakeDatabase, world: World, ) -> None: database.fail_on["messages.insert_message"] = ( exceptions.ServiceUnavailable() ) with pytest.raises(exceptions.ServiceUnavailable): await _send(service, world) assert database.idempotency == {} database.fail_on.clear() assert (await _send(service, world)).text == "hello" async def test_outsider_not_found_before_key( service: services.MessageService, database: FakeDatabase, world: World, ) -> None: with pytest.raises(exceptions.ChatNotFound): await _send(service, world, sender=world.bob) assert "idempotency.claim_key" not in database.events async def test_pages_outsider_and_foreign_cursor( service: services.MessageService, database: FakeDatabase, world: World, ) -> None: sent = [] for index in range(3): sent.append( await service.send_message( chat_id=world.chat_id, sender_id=world.alice, text=str(index), idempotency_key=f"key-{index}", ), ) first = await service.list_messages( chat_id=world.chat_id, user_id=world.alice, limit=2, cursor=None, ) assert [item.id for item in first.items] == [item.id for item in sent[:2]] second = await service.list_messages( chat_id=world.chat_id, user_id=world.alice, limit=2, cursor=first.next_cursor, ) assert [item.id for item in second.items] == [sent[2].id] assert second.next_cursor is None with pytest.raises(exceptions.ChatNotFound): await service.list_messages( chat_id=world.chat_id, user_id=world.bob, limit=2, cursor=None, ) with pytest.raises(exceptions.InvalidCursor): await service.list_messages( chat_id=world.chat_id, user_id=world.alice, limit=2, cursor="not-a-cursor", ) # чтение — один блок и без фиксации database.events.clear() await service.list_messages( chat_id=world.chat_id, user_id=world.alice, limit=2, cursor=None, ) assert database.events.count("enter") == 1 assert "commit" not in database.events def test_request_hash_rules() -> None: first, second = uuid4(), uuid4() empty = message_request_hash(text="a") assert empty == message_request_hash(text="a", attachment_ids=()) assert empty != message_request_hash(text="b") assert message_request_hash( text="a", attachment_ids=(first, second), ) != message_request_hash(text="a", attachment_ids=(second, first))