Files
mtusi2026lab6/src/messenger/messaging/domain/models.py
T
Artyom 12db77133f Forward the lab 5 foundation while preserving lab 6 telemetry
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.
2026-11-06 12:29:35 +03:00

132 lines
4.1 KiB
Python

from collections.abc import Sequence
from dataclasses import dataclass
from datetime import datetime
from uuid import UUID
from messenger.messaging.domain.errors import (
IdempotencyConflict,
InvalidAttachmentList,
InvalidChatData,
InvalidMessageText,
)
from messenger.messaging.domain.events import ChatCreated, MessagePosted
from messenger.messaging.domain.keys import HistoryKey
from messenger.messaging.domain.values import (
CHAT_MEMBERS_MAX,
MESSAGE_ATTACHMENTS_MAX,
ChatTitle,
MessageText,
)
from messenger.shared.domain.events import DomainEvent
@dataclass(frozen=True, slots=True)
class Message:
id: UUID
chat_id: UUID
sender_id: UUID
text: MessageText
created_at: datetime
attachment_ids: tuple[UUID, ...] = ()
@property
def key(self) -> HistoryKey:
return (self.created_at, self.id.int)
def posted(self) -> MessagePosted:
return MessagePosted(
message_id=self.id,
chat_id=self.chat_id,
sender_id=self.sender_id,
text_length=len(self.text.value),
created_at=self.created_at,
)
def attachment_list(text: MessageText, attachment_ids: Sequence[UUID]) -> tuple[UUID, ...]:
if len(attachment_ids) > MESSAGE_ATTACHMENTS_MAX:
raise InvalidAttachmentList(
f"поле attachment_ids содержит больше {MESSAGE_ATTACHMENTS_MAX} вложений"
)
if len(set(attachment_ids)) != len(attachment_ids):
raise InvalidAttachmentList("поле attachment_ids содержит дубликаты")
if not text.value and not attachment_ids:
raise InvalidMessageText("пустой text допустим только с вложением")
return tuple(attachment_ids)
@dataclass(frozen=True, slots=True)
class Receipt:
key: str
fingerprint: bytes
message: Message
def replay(self, fingerprint: bytes) -> Message:
if fingerprint != self.fingerprint:
raise IdempotencyConflict("ключ идемпотентности уже использован с другим телом")
return self.message
class Chat:
__slots__ = ("_events", "created_at", "id", "member_ids", "title")
def __init__(
self,
*,
chat_id: UUID,
title: ChatTitle,
member_ids: Sequence[UUID],
created_at: datetime,
) -> None:
self.id = chat_id
self.title = title
self.member_ids: tuple[UUID, ...] = tuple(member_ids)
self.created_at = created_at
self._events: list[DomainEvent] = []
@classmethod
def create(
cls,
*,
chat_id: UUID,
title: str,
member_ids: Sequence[UUID],
creator_id: UUID,
created_at: datetime,
) -> Chat:
if not member_ids:
raise InvalidChatData("поле member_ids не может быть пустым")
if len(member_ids) > CHAT_MEMBERS_MAX:
raise InvalidChatData(f"поле member_ids содержит больше {CHAT_MEMBERS_MAX} участников")
unique = set(member_ids)
if len(unique) != len(member_ids):
raise InvalidChatData("поле member_ids содержит дубликаты")
if creator_id not in unique:
raise InvalidChatData("создатель чата обязан входить в список member_ids")
chat = cls(
chat_id=chat_id,
title=ChatTitle(title),
member_ids=member_ids,
created_at=created_at,
)
chat.record(
ChatCreated(
chat_id=chat.id,
creator_id=creator_id,
member_count=len(unique),
created_at=created_at,
)
)
return chat
@property
def key(self) -> HistoryKey:
return (self.created_at, self.id.int)
def record(self, event: DomainEvent) -> None:
self._events.append(event)
def collect_events(self) -> list[DomainEvent]:
events, self._events = self._events, []
return events