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:
Artyom
2026-10-28 20:45:19 +03:00
co-authored by Claude Opus 5.5
parent 00826a40d3
commit f9760fc098
14 changed files with 298 additions and 52 deletions
@@ -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):