feat: add image attachments to messages

- upload, metadata and download endpoints for PNG/JPEG attachments:
  limits before reading and decompression, type by content,
  structural integrity check without decoding pixels, safe filename
- write order: pending row with object key -> PUT to S3 -> ready;
  per-step DB sessions so no pool connection is held during transfers
- attachment_ids in messages (validation, idempotency hash, history);
  whitespace-only text allowed with an attachment (teacher, 2026-10-20)
- migration: attachments and message_attachments tables, text length
  CHECK relaxed with NOT VALID
- student tests, fault checks and driver commands for attachments;
  rollout profile starts from e1161f7 and checks the commit first
- sync attachments deltas into main specs; rules, AGENTS.md, PLAN.md

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
2026-10-21 01:08:56 +03:00
co-authored by Claude Opus 5.5
parent 73779f7acd
commit 116d8d3bf0
72 changed files with 5546 additions and 247 deletions
+215 -2
View File
@@ -1,12 +1,14 @@
"""Спек `messages`: отправка, валидация текста, история."""
"""Спек `messages`: отправка, валидация текста, история, вложения."""
import uuid
from typing import Any
import httpx
import pytest
import images
from api_client import Actor, Api, order_key
from contract import assert_error, assert_ok
from contract import assert_error, assert_errors, assert_ok
def send_raw(
@@ -30,6 +32,217 @@ def test_member_sends(
assert message["sender_id"] == alice.id
assert message["chat_id"] == chat["id"]
assert message["text"] == "Привет, мир 👋"
assert message["attachment_ids"] == []
def upload(api: Api, actor: Actor, chat_id: str) -> str:
"""Готовое вложение чата; id."""
return api.upload(actor, chat_id, images.sample_png())["id"]
@pytest.mark.spec("messages", "Сообщение с вложениями")
def test_message_with_attachments(
api: Api,
alice: Actor,
chat: dict[str, Any],
) -> None:
first, second = (
upload(api, alice, chat["id"]),
upload(api, alice, chat["id"]),
)
message = api.send_message(
alice,
chat["id"],
"два файла",
attachment_ids=[second, first],
)
assert message["attachment_ids"] == [second, first]
@pytest.mark.spec("messages", "Пустой текст с вложением")
def test_empty_text_with_attachment(
api: Api,
alice: Actor,
chat: dict[str, Any],
) -> None:
attachment_id = upload(api, alice, chat["id"])
message = api.send_message(
alice,
chat["id"],
"",
attachment_ids=[attachment_id],
)
assert message["text"] == ""
assert message["attachment_ids"] == [attachment_id]
@pytest.mark.spec("messages", "Пробелы с вложением")
def test_blank_text_with_attachment(
api: Api,
alice: Actor,
chat: dict[str, Any],
) -> None:
"""Согласовано с преподавателем 2026-10-20: пустой текст — и `""`, и
из одних пробелов; с вложением допустим и не нормализуется."""
attachment_id = upload(api, alice, chat["id"])
message = api.send_message(
alice,
chat["id"],
" ",
attachment_ids=[attachment_id],
)
assert message["text"] == " "
assert message["attachment_ids"] == [attachment_id]
assert_error(send_raw(api, alice, chat["id"], {"text": " "}), 400)
assert [item["id"] for item in api.all_messages(alice, chat["id"])] == [
message["id"],
]
@pytest.mark.spec("messages", "Вложения в истории")
def test_attachments_in_history(
api: Api,
alice: Actor,
bob: Actor,
chat: dict[str, Any],
) -> None:
first, second = (
upload(api, alice, chat["id"]),
upload(api, alice, chat["id"]),
)
with_files = api.send_message(
alice,
chat["id"],
"с файлами",
attachment_ids=[second, first],
)
plain = api.send_message(bob, chat["id"], "без файлов")
history = api.all_messages(bob, chat["id"])
assert history == sorted([with_files, plain], key=order_key)
by_id = {item["id"]: item["attachment_ids"] for item in history}
assert by_id == {with_files["id"]: [second, first], plain["id"]: []}
@pytest.mark.spec("messages", "Вложение другого участника")
def test_attachment_of_other_member(
api: Api,
alice: Actor,
bob: Actor,
chat: dict[str, Any],
) -> None:
attachment_id = upload(api, alice, chat["id"])
api.send_message(bob, chat["id"], "ответ", attachment_ids=[attachment_id])
@pytest.mark.spec("messages", "Вложение другого чата")
def test_attachment_of_other_chat(
api: Api,
alice: Actor,
bob: Actor,
chat: dict[str, Any],
) -> None:
other = api.create_chat(alice, bob, title="Y")
attachment_id = upload(api, alice, other["id"])
resp = send_raw(
api,
alice,
chat["id"],
{"text": "чужой чат", "attachment_ids": [attachment_id]},
)
assert_error(resp, 404)
assert api.all_messages(alice, chat["id"]) == []
@pytest.mark.spec("messages", "Чужое вложение")
def test_foreign_attachment(
api: Api,
alice: Actor,
eve: Actor,
chat: dict[str, Any],
) -> None:
eve_chat = api.create_chat(eve, title="Ева")
attachment_id = upload(api, eve, eve_chat["id"])
resp = send_raw(
api,
alice,
chat["id"],
{"text": "", "attachment_ids": [attachment_id]},
)
assert_error(resp, 404)
assert api.all_messages(alice, chat["id"]) == []
@pytest.mark.spec("messages", "Неизвестное вложение")
def test_unknown_attachment(
api: Api,
alice: Actor,
chat: dict[str, Any],
) -> None:
resp = send_raw(
api,
alice,
chat["id"],
{"text": "x", "attachment_ids": [str(uuid.uuid4())]},
)
assert_error(resp, 404)
assert api.all_messages(alice, chat["id"]) == []
@pytest.mark.spec("messages", "Неверный список вложений")
def test_bad_attachment_list(
api: Api,
alice: Actor,
chat: dict[str, Any],
) -> None:
attachment_id = upload(api, alice, chat["id"])
bodies = {
"repeat": [attachment_id, attachment_id],
"repeat upper": [attachment_id, attachment_id.upper()],
"eleven": [str(uuid.uuid4()) for _ in range(11)],
"string": attachment_id,
"number item": [123],
"123 item": ["123"],
}
assert_errors(
{
name: send_raw(
api,
alice,
chat["id"],
{"text": "x", "attachment_ids": value},
)
for name, value in bodies.items()
},
400,
)
assert api.all_messages(alice, chat["id"]) == []
@pytest.mark.spec("messages", "Одно вложение в двух сообщениях")
def test_one_attachment_in_two_messages(
api: Api,
alice: Actor,
chat: dict[str, Any],
) -> None:
attachment_id = upload(api, alice, chat["id"])
first = api.send_message(
alice,
chat["id"],
"раз",
attachment_ids=[attachment_id],
)
second = api.send_message(
alice,
chat["id"],
"два",
attachment_ids=[attachment_id],
)
assert first["id"] != second["id"]
history = api.all_messages(alice, chat["id"])
assert [item["attachment_ids"] for item in history] == [
[attachment_id],
[attachment_id],
]
@pytest.mark.spec("messages", "Граница длины")