Files
mtusi2026labs/src/messenger/messaging/domain/models.py
T
ArtyomandClaude Opus 5.5 22f0e6244d Post a message with one statement under the chat lock
Sending a message used to be BEGIN, a SELECT ... FOR UPDATE of the
chat with its members, a lookup of the idempotency key, the insert CTE
and COMMIT. Three of those round trips ran under the chat row lock, and
each one waited for the replica's event loop, so under load the lock
holders sat idle in transaction while everyone else queued behind
them.

The new MessageLog port has one PostgreSQL adapter that does it all in
a single statement with an implicit transaction: lock the chat row
joined with the sender's membership, stamp the message with the later
of the replica clock and the last message plus one microsecond, claim
the key (overwriting it only if it has expired), insert the message
only when the key was claimed, and move last_message_at. The foreign
key from the key to the message is checked at the end of the statement,
so the key may be written first. When the key is already taken the
adapter reads the stored result with a second statement outside the
lock, which also covers a concurrent duplicate that waited for the
first one; the handler then replays it or answers 409 as before.

The chat aggregate no longer takes part in posting, so its post,
membership and last_message_at members and their unit tests are gone;
Message.posted() builds the event. An invalid text is still answered
404 for an outsider: only then the handler reads the membership. A new
API test pins the clock rule against a real database: a lagging
replica clock gets the last stamp plus one microsecond, a clock ahead
is kept. The concurrency, same-key race, expiry and access tests pass
unchanged.

Co-Authored-By: Claude Opus 5.5 (1M context) <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01V1d3RLHNBBMA6UqBLLJv27
2026-10-29 01:06:49 +03:00

109 lines
3.3 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, InvalidChatData
from messenger.messaging.domain.events import ChatCreated, MessagePosted
from messenger.messaging.domain.keys import HistoryKey
from messenger.messaging.domain.values import CHAT_MEMBERS_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
@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,
)
@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