Source: immutable lab5 snapshot f88e9ba43cdfd7eb6a5a7ae5feb4247b4e820071; forward the allowed diff from 64d5c67. Carry SQLAlchemy, Alembic, reliability fixes, versioned jobs, infrastructure and student tests without changing protected coursework files. Validation: make check, validate, lint; 515 student tests passed with one Linux-only skip; public smoke with telemetry enabled and repeat migration passed. Stop the owned stack and retain volumes. Preserve the existing OTel work in progress; grade implementation remains a separate phase.
76 lines
2.6 KiB
Python
76 lines
2.6 KiB
Python
from datetime import timedelta
|
|
|
|
from messenger.messaging.application.commands import CreateChat, PostMessage
|
|
from messenger.messaging.application.ports import ChatDirectory, MessageLog, MessagingUnitOfWork
|
|
from messenger.messaging.domain.errors import (
|
|
ChatNotFound,
|
|
InvalidAttachmentList,
|
|
InvalidMessageText,
|
|
)
|
|
from messenger.messaging.domain.models import Chat, Message, attachment_list
|
|
from messenger.messaging.domain.values import MessageText
|
|
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__ = ("_chats", "_clock", "_ids", "_log", "_ttl", "_uow")
|
|
|
|
def __init__(
|
|
self,
|
|
uow: MessagingUnitOfWork,
|
|
log: MessageLog,
|
|
chats: ChatDirectory,
|
|
clock: Clock,
|
|
ids: IdGenerator,
|
|
*,
|
|
ttl: timedelta,
|
|
) -> None:
|
|
self._uow = uow
|
|
self._log = log
|
|
self._chats = chats
|
|
self._clock = clock
|
|
self._ids = ids
|
|
self._ttl = ttl
|
|
|
|
async def __call__(self, command: PostMessage) -> Message:
|
|
try:
|
|
text = MessageText(command.text)
|
|
attachments = attachment_list(text, command.attachment_ids)
|
|
except InvalidMessageText, InvalidAttachmentList:
|
|
if await self._chats.chat_for_member(command.chat_id, command.sender_id) is None:
|
|
raise ChatNotFound("чат не найден") from None
|
|
raise
|
|
now = self._clock.now()
|
|
draft = Message(
|
|
self._ids.new_id(), command.chat_id, command.sender_id, text, now, attachments
|
|
)
|
|
receipt = await self._log.post(draft, command.key, command.fingerprint, now - self._ttl)
|
|
if receipt is None:
|
|
raise ChatNotFound("чат не найден")
|
|
message = receipt.replay(command.fingerprint)
|
|
if message.id == draft.id:
|
|
self._uow.record(message.posted())
|
|
return message
|