Files
mtusi2026lab2/src/messenger/messaging/application/handlers.py
T
ArtyomandClaude Opus 5.5 34741dc2d2 Refuse failed attachments in messages through a zone port
The messaging zone asks a new AttachmentStates port whether any listed
attachment of the chat has failed and answers 409 conflict before the
message is stored; queued and processing attachments can still be
sent right after the upload. The check runs only on the first execution
of a key, so a replay returns the original 201 even if the attachment
failed later. main.py wires the port to the attachments directory, so
neither zone reads the other's tables.

Co-Authored-By: Claude Opus 5.5 (1M context) <noreply@anthropic.com>
2026-10-29 01:09:31 +03:00

74 lines
2.7 KiB
Python

from datetime import timedelta
from messenger.messaging.application.commands import CreateChat, PostMessage
from messenger.messaging.application.ports import AttachmentStates, MessagingUnitOfWork
from messenger.messaging.domain.errors import AttachmentUnavailable, ChatNotFound
from messenger.messaging.domain.models import Chat, Message, Receipt
from messenger.shared.application.ports import Clock, IdGenerator
class CreateChatHandler:
__slots__ = ("_clock", "_ids", "_uow")
def __init__(self, uow: MessagingUnitOfWork, clock: Clock, ids: IdGenerator) -> None:
self._uow = uow
self._clock = clock
self._ids = ids
async def __call__(self, command: CreateChat) -> Chat:
chat = Chat.create(
chat_id=self._ids.new_id(),
title=command.title,
member_ids=command.member_ids,
creator_id=command.creator_id,
created_at=self._clock.now(),
)
async with self._uow.transaction():
await self._uow.chats.add(chat)
await self._uow.commit()
return chat
class PostMessageHandler:
__slots__ = ("_attachments", "_clock", "_ids", "_ttl", "_uow")
def __init__(
self,
uow: MessagingUnitOfWork,
attachments: AttachmentStates,
clock: Clock,
ids: IdGenerator,
ttl: timedelta,
) -> None:
self._uow = uow
self._attachments = attachments
self._clock = clock
self._ids = ids
self._ttl = ttl
async def __call__(self, command: PostMessage) -> Message:
async with self._uow.transaction():
chat = await self._uow.chats.get(command.chat_id)
if chat is None:
raise ChatNotFound("чат не найден")
now = self._clock.now()
message = chat.post(
message_id=self._ids.new_id(),
sender_id=command.sender_id,
text=command.text,
now=now,
attachment_ids=command.attachment_ids,
)
known = await self._uow.chats.receipt(
chat.id, command.sender_id, command.key, now - self._ttl
)
if known is not None:
return known.replay(command.fingerprint)
if message.attachment_ids and await self._attachments.unusable(
chat.id, message.attachment_ids
):
raise AttachmentUnavailable("вложение не обработано и не может быть отправлено")
await self._uow.chats.append(Receipt(command.key, command.fingerprint, message))
await self._uow.commit()
return message