Link messages to attachments of the same chat
A message now carries attachment_ids in the request, in every response, in the idempotent replay and in history, in the order they were sent. The chat aggregate checks membership first, then refuses whitespace text, more than ten or repeated attachments, and an empty text without attachments, so an outsider still gets 404 before any 400. The send statement inserts the links next to the message and the idempotency key, and the foreign key from message_attachments to attachments of the same chat turns an unknown or foreign attachment into 404 and rolls the whole send back, without the messaging zone reading the attachments table. Replay and history read the list with a subquery on the primary key. The request fingerprint covers the list, so a missing attachment_ids and [] are the same body while a different order is a conflict. The zone dependency test now covers three zones, and the SQL ownership test checks that every zone touches only its own tables. Co-Authored-By: Claude Opus 5.5 (1M context) <noreply@anthropic.com>
This commit is contained in:
co-authored by
Claude Opus 5.5
parent
00826a40d3
commit
f9760fc098
@@ -19,3 +19,4 @@ class PostMessage(Command):
|
||||
text: str
|
||||
key: str
|
||||
fingerprint: bytes
|
||||
attachment_ids: tuple[UUID, ...] = ()
|
||||
|
||||
@@ -51,6 +51,7 @@ class PostMessageHandler:
|
||||
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
|
||||
|
||||
@@ -23,3 +23,11 @@ class ChatNotFound(MessagingError):
|
||||
|
||||
class IdempotencyConflict(MessagingError):
|
||||
pass
|
||||
|
||||
|
||||
class InvalidAttachmentList(MessagingError):
|
||||
pass
|
||||
|
||||
|
||||
class UnknownAttachment(MessagingError):
|
||||
pass
|
||||
|
||||
@@ -3,10 +3,21 @@ from dataclasses import dataclass
|
||||
from datetime import datetime, timedelta
|
||||
from uuid import UUID
|
||||
|
||||
from messenger.messaging.domain.errors import ChatNotFound, IdempotencyConflict, InvalidChatData
|
||||
from messenger.messaging.domain.errors import (
|
||||
ChatNotFound,
|
||||
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, ChatTitle, MessageText
|
||||
from messenger.messaging.domain.values import (
|
||||
CHAT_MEMBERS_MAX,
|
||||
MESSAGE_ATTACHMENTS_MAX,
|
||||
ChatTitle,
|
||||
MessageText,
|
||||
)
|
||||
from messenger.shared.domain.events import DomainEvent
|
||||
|
||||
TICK = timedelta(microseconds=1)
|
||||
@@ -19,12 +30,25 @@ class Message:
|
||||
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 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
|
||||
@@ -114,16 +138,27 @@ class Chat:
|
||||
if not self.is_member(user_id):
|
||||
raise ChatNotFound("чат не найден")
|
||||
|
||||
def post(self, *, message_id: UUID, sender_id: UUID, text: str, now: datetime) -> Message:
|
||||
def post(
|
||||
self,
|
||||
*,
|
||||
message_id: UUID,
|
||||
sender_id: UUID,
|
||||
text: str,
|
||||
now: datetime,
|
||||
attachment_ids: Sequence[UUID] = (),
|
||||
) -> Message:
|
||||
self.require_member(sender_id)
|
||||
body = MessageText(text)
|
||||
attachments = attachment_list(body, attachment_ids)
|
||||
last = self.last_message_at
|
||||
created_at = now if last is None or now > last else last + TICK
|
||||
message = Message(
|
||||
id=message_id,
|
||||
chat_id=self.id,
|
||||
sender_id=sender_id,
|
||||
text=MessageText(text),
|
||||
text=body,
|
||||
created_at=created_at,
|
||||
attachment_ids=attachments,
|
||||
)
|
||||
self.last_message_at = created_at
|
||||
self.record(
|
||||
|
||||
@@ -5,6 +5,7 @@ from messenger.messaging.domain.errors import InvalidChatData, InvalidMessageTex
|
||||
CHAT_TITLE_MAX = 100
|
||||
MESSAGE_TEXT_MAX = 4000
|
||||
CHAT_MEMBERS_MAX = 100
|
||||
MESSAGE_ATTACHMENTS_MAX = 10
|
||||
|
||||
|
||||
@dataclass(frozen=True, slots=True)
|
||||
@@ -30,8 +31,8 @@ class MessageText:
|
||||
def __post_init__(self) -> None:
|
||||
if not isinstance(self.value, str):
|
||||
raise InvalidMessageText("поле text должно быть строкой")
|
||||
if not self.value.strip():
|
||||
raise InvalidMessageText("поле text не может быть пустым или состоять из пробелов")
|
||||
if self.value and not self.value.strip():
|
||||
raise InvalidMessageText("поле text не может состоять из пробелов")
|
||||
if len(self.value) > MESSAGE_TEXT_MAX:
|
||||
raise InvalidMessageText(f"поле text длиннее {MESSAGE_TEXT_MAX} символов Unicode")
|
||||
|
||||
|
||||
@@ -1,9 +1,11 @@
|
||||
from messenger.messaging.domain.errors import (
|
||||
ChatNotFound,
|
||||
IdempotencyConflict,
|
||||
InvalidAttachmentList,
|
||||
InvalidChatData,
|
||||
InvalidMessageText,
|
||||
InvalidPageRequest,
|
||||
UnknownAttachment,
|
||||
)
|
||||
from messenger.shared.domain.errors import DomainError
|
||||
|
||||
@@ -11,6 +13,8 @@ ERROR_CODES: dict[type[DomainError], tuple[str, int]] = {
|
||||
InvalidChatData: ("invalid_request", 400),
|
||||
InvalidMessageText: ("invalid_request", 400),
|
||||
InvalidPageRequest: ("invalid_request", 400),
|
||||
InvalidAttachmentList: ("invalid_request", 400),
|
||||
ChatNotFound: ("not_found", 404),
|
||||
UnknownAttachment: ("not_found", 404),
|
||||
IdempotencyConflict: ("conflict", 409),
|
||||
}
|
||||
|
||||
@@ -72,6 +72,7 @@ async def post_message(
|
||||
text=body.text,
|
||||
key=key,
|
||||
fingerprint=body.fingerprint(),
|
||||
attachment_ids=tuple(body.attachment_ids),
|
||||
)
|
||||
)
|
||||
return MessageOut.of(message)
|
||||
|
||||
@@ -29,6 +29,7 @@ class CreateMessageRequest(BaseModel):
|
||||
model_config = STRICT
|
||||
|
||||
text: str
|
||||
attachment_ids: list[Annotated[UUID, Field(strict=False)]] = Field(default_factory=list)
|
||||
|
||||
def fingerprint(self) -> bytes:
|
||||
return sha256(self.model_dump_json().encode()).digest()
|
||||
@@ -61,6 +62,7 @@ class MessageOut(BaseModel):
|
||||
sender_id: UUID
|
||||
text: str
|
||||
created_at: datetime
|
||||
attachment_ids: tuple[UUID, ...]
|
||||
|
||||
@classmethod
|
||||
def of(cls, message: Message) -> MessageOut:
|
||||
@@ -70,6 +72,7 @@ class MessageOut(BaseModel):
|
||||
sender_id=message.sender_id,
|
||||
text=message.text.value,
|
||||
created_at=message.created_at,
|
||||
attachment_ids=message.attachment_ids,
|
||||
)
|
||||
|
||||
|
||||
|
||||
@@ -4,7 +4,7 @@ from uuid import UUID
|
||||
|
||||
from asyncpg import ForeignKeyViolationError, Record
|
||||
|
||||
from messenger.messaging.domain.errors import InvalidChatData
|
||||
from messenger.messaging.domain.errors import InvalidChatData, UnknownAttachment
|
||||
from messenger.messaging.domain.keys import HistoryKey
|
||||
from messenger.messaging.domain.models import Chat, Message, Receipt
|
||||
from messenger.messaging.domain.values import ChatTitle, MessageText
|
||||
@@ -28,8 +28,11 @@ FROM chats c
|
||||
WHERE c.id = $1
|
||||
FOR UPDATE
|
||||
"""
|
||||
ATTACHMENT_FKEY = "message_attachments_attachment_fkey"
|
||||
RECEIPT = """
|
||||
SELECT k.fingerprint, m.id, m.chat_id, m.sender_id, m.text, m.created_at
|
||||
SELECT k.fingerprint, m.id, m.chat_id, m.sender_id, m.text, m.created_at,
|
||||
ARRAY(SELECT a.attachment_id FROM message_attachments a
|
||||
WHERE a.message_id = m.id ORDER BY a.position) AS attachment_ids
|
||||
FROM idempotency_keys k JOIN messages m ON m.id = k.message_id
|
||||
WHERE k.chat_id = $1 AND k.user_id = $2 AND k.key = $3 AND k.created_at > $4
|
||||
"""
|
||||
@@ -38,6 +41,10 @@ WITH message AS (
|
||||
INSERT INTO messages (id, chat_id, sender_id, text, created_at)
|
||||
VALUES ($1, $2, $3, $4, $5)
|
||||
RETURNING id, chat_id, sender_id, created_at
|
||||
), links AS (
|
||||
INSERT INTO message_attachments (message_id, position, chat_id, attachment_id)
|
||||
SELECT message.id, link.position - 1, message.chat_id, link.attachment_id
|
||||
FROM message, unnest($8::uuid[]) WITH ORDINALITY AS link (attachment_id, position)
|
||||
), receipt AS (
|
||||
INSERT INTO idempotency_keys (chat_id, user_id, key, fingerprint, message_id, created_at)
|
||||
SELECT chat_id, sender_id, $6, $7, id, created_at FROM message
|
||||
@@ -73,17 +80,21 @@ ORDER BY m.chat_created_at, m.chat_id
|
||||
LIMIT $4
|
||||
"""
|
||||
HISTORY_FIRST = """
|
||||
SELECT id, chat_id, sender_id, text, created_at
|
||||
FROM messages
|
||||
WHERE chat_id = $1
|
||||
ORDER BY created_at, id
|
||||
SELECT m.id, m.chat_id, m.sender_id, m.text, m.created_at,
|
||||
ARRAY(SELECT a.attachment_id FROM message_attachments a
|
||||
WHERE a.message_id = m.id ORDER BY a.position) AS attachment_ids
|
||||
FROM messages m
|
||||
WHERE m.chat_id = $1
|
||||
ORDER BY m.created_at, m.id
|
||||
LIMIT $2
|
||||
"""
|
||||
HISTORY_AFTER = """
|
||||
SELECT id, chat_id, sender_id, text, created_at
|
||||
FROM messages
|
||||
WHERE chat_id = $1 AND (created_at, id) > ($2, $3)
|
||||
ORDER BY created_at, id
|
||||
SELECT m.id, m.chat_id, m.sender_id, m.text, m.created_at,
|
||||
ARRAY(SELECT a.attachment_id FROM message_attachments a
|
||||
WHERE a.message_id = m.id ORDER BY a.position) AS attachment_ids
|
||||
FROM messages m
|
||||
WHERE m.chat_id = $1 AND (m.created_at, m.id) > ($2, $3)
|
||||
ORDER BY m.created_at, m.id
|
||||
LIMIT $4
|
||||
"""
|
||||
|
||||
@@ -105,6 +116,7 @@ def message_of(row: Record) -> Message:
|
||||
sender_id=row["sender_id"],
|
||||
text=MessageText(row["text"]),
|
||||
created_at=row["created_at"],
|
||||
attachment_ids=tuple(row["attachment_ids"]),
|
||||
)
|
||||
|
||||
|
||||
@@ -145,16 +157,22 @@ class PostgresChatRepository:
|
||||
|
||||
async def append(self, receipt: Receipt) -> None:
|
||||
message = receipt.message
|
||||
await self._connection.execute(
|
||||
APPEND_MESSAGE,
|
||||
message.id,
|
||||
message.chat_id,
|
||||
message.sender_id,
|
||||
message.text.value,
|
||||
message.created_at,
|
||||
receipt.key,
|
||||
receipt.fingerprint,
|
||||
)
|
||||
try:
|
||||
await self._connection.execute(
|
||||
APPEND_MESSAGE,
|
||||
message.id,
|
||||
message.chat_id,
|
||||
message.sender_id,
|
||||
message.text.value,
|
||||
message.created_at,
|
||||
receipt.key,
|
||||
receipt.fingerprint,
|
||||
list(message.attachment_ids),
|
||||
)
|
||||
except ForeignKeyViolationError as error:
|
||||
if getattr(error, "constraint_name", None) != ATTACHMENT_FKEY:
|
||||
raise
|
||||
raise UnknownAttachment("вложение не найдено в этом чате") from error
|
||||
|
||||
|
||||
class PostgresMessagingUnitOfWork(PostgresUnitOfWork):
|
||||
|
||||
Reference in New Issue
Block a user