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:
@@ -18,9 +18,11 @@ from typing import Any
|
||||
import httpx
|
||||
import pytest
|
||||
|
||||
import images
|
||||
from api_client import API, Actor, Api, new_key
|
||||
from contract import (
|
||||
BEARER_CHALLENGE,
|
||||
assert_content,
|
||||
assert_error,
|
||||
assert_ok,
|
||||
assert_unauthorized,
|
||||
@@ -45,6 +47,8 @@ READINESS_TIMEOUT_S = 2
|
||||
# health без S3: проверка к S3 не обращается, ответ быстрее секунды (спек
|
||||
# health, «Хранилище объектов недоступно»); срок вызова S3 — 5 с
|
||||
OBJECT_STORAGE_HEALTH_S = 1
|
||||
# [s3] timeout_seconds по умолчанию: срок одного вызова S3
|
||||
S3_TIMEOUT_S = 5
|
||||
# сколько секунд hook держит слоты max_connections; clear-connections
|
||||
# освобождает их раньше
|
||||
FILL_HOLD_S = 30
|
||||
@@ -526,3 +530,162 @@ def test_key_free_after_ttl(tight_api: Api) -> None:
|
||||
assert second["id"] != first["id"]
|
||||
history = tight_api.all_messages(alice, chat["id"])
|
||||
assert [item["id"] for item in history] == [first["id"], second["id"]]
|
||||
|
||||
|
||||
# ---------------------------------------------------------------------------
|
||||
# Вложения: S3 остановлен или заморожен, счётчики строк и объектов — hook
|
||||
# ---------------------------------------------------------------------------
|
||||
|
||||
|
||||
def attachment_counts(stand: Stand) -> dict[str, int]:
|
||||
"""Вложения стенда по статусам: `pending=N ready=M` от hook."""
|
||||
return {
|
||||
name: int(value)
|
||||
for name, value in (
|
||||
item.split("=") for item in stand("count-attachments").split()
|
||||
)
|
||||
}
|
||||
|
||||
|
||||
def object_count(stand: Stand) -> int:
|
||||
return int(stand("count-objects"))
|
||||
|
||||
|
||||
def upload_raw(
|
||||
api: Api,
|
||||
actor: Actor,
|
||||
chat: dict[str, Any],
|
||||
data: Any,
|
||||
**kwargs: Any,
|
||||
) -> httpx.Response:
|
||||
return api.post_attachment(actor, chat["id"], data, **kwargs)
|
||||
|
||||
|
||||
@pytest.mark.spec("attachments", "Запись в S3 не удалась")
|
||||
def test_upload_with_object_storage_stopped(
|
||||
api: Api,
|
||||
stand: Stand,
|
||||
alice: Actor,
|
||||
chat: dict[str, Any],
|
||||
) -> None:
|
||||
data = images.sample_png()
|
||||
before = attachment_counts(stand)
|
||||
with outage(stand, "stop", "s3"):
|
||||
resp, elapsed = timed(lambda: upload_raw(api, alice, chat, data))
|
||||
assert_error(resp, 503)
|
||||
assert elapsed < S3_TIMEOUT_S + SLACK_S, f"503 after {elapsed:.2f}s"
|
||||
after = attachment_counts(stand)
|
||||
# строка-намерение осталась, готовых не прибавилось; её уберёт
|
||||
# уборщик change upload-consistency
|
||||
assert after == {
|
||||
"pending": before["pending"] + 1,
|
||||
"ready": before["ready"],
|
||||
}
|
||||
api.send_message(alice, chat["id"], "текст без S3")
|
||||
api.upload(alice, chat["id"], data)
|
||||
|
||||
|
||||
@pytest.mark.spec("attachments", "Отклонённая загрузка ничего не оставляет")
|
||||
def test_rejected_uploads_leave_nothing(
|
||||
api: Api,
|
||||
stand: Stand,
|
||||
alice: Actor,
|
||||
eve: Actor,
|
||||
chat: dict[str, Any],
|
||||
) -> None:
|
||||
big = images.PNG_SIGNATURE + bytes(images.MAX_BYTES * 2)
|
||||
|
||||
def chunked() -> Iterator[bytes]:
|
||||
for offset in range(0, len(big), 1024 * 1024):
|
||||
yield big[offset : offset + 1024 * 1024]
|
||||
|
||||
# хотя бы одно готовое вложение: счётчики hook не нулевые случайно
|
||||
api.upload(alice, chat["id"], images.sample_png())
|
||||
before = (attachment_counts(stand), object_count(stand))
|
||||
assert before[0]["ready"] >= 1, before
|
||||
assert before[1] >= 1, before
|
||||
rejected = (
|
||||
(404, upload_raw(api, eve, chat, images.sample_png())),
|
||||
(413, upload_raw(api, alice, chat, big)),
|
||||
(413, upload_raw(api, alice, chat, chunked())),
|
||||
(413, upload_raw(api, alice, chat, images.png_huge(8000, 5001))),
|
||||
(
|
||||
415,
|
||||
upload_raw(
|
||||
api,
|
||||
alice,
|
||||
chat,
|
||||
images.sample_png(),
|
||||
content_type="text/plain",
|
||||
),
|
||||
),
|
||||
(415, upload_raw(api, alice, chat, images.png_idat_byte_changed())),
|
||||
)
|
||||
for status, resp in rejected:
|
||||
assert_error(resp, status)
|
||||
assert (attachment_counts(stand), object_count(stand)) == before
|
||||
|
||||
|
||||
@pytest.mark.spec("attachments", "S3 остановлен")
|
||||
def test_object_storage_stopped(
|
||||
api: Api,
|
||||
stand: Stand,
|
||||
alice: Actor,
|
||||
bob: Actor,
|
||||
chat: dict[str, Any],
|
||||
) -> None:
|
||||
data = images.sample_png()
|
||||
attachment = api.upload(alice, chat["id"], data)
|
||||
with outage(stand, "stop", "s3"):
|
||||
resp, elapsed = timed(
|
||||
lambda: api.attachment_content(bob, attachment["id"]),
|
||||
)
|
||||
assert_error(resp, 503)
|
||||
assert elapsed < S3_TIMEOUT_S + SLACK_S, f"503 after {elapsed:.2f}s"
|
||||
meta = assert_ok(
|
||||
api.attachment_meta(bob, attachment["id"]),
|
||||
200,
|
||||
"Attachment",
|
||||
)
|
||||
assert meta == attachment
|
||||
api.send_message(
|
||||
bob,
|
||||
chat["id"],
|
||||
"",
|
||||
attachment_ids=[attachment["id"]],
|
||||
)
|
||||
assert_ok(api.request("GET", "/health/ready"), 200, "Health")
|
||||
assert_content(
|
||||
api.attachment_content(bob, attachment["id"]),
|
||||
data,
|
||||
"image/png",
|
||||
)
|
||||
|
||||
|
||||
@pytest.mark.spec("attachments", "S3 завис")
|
||||
def test_object_storage_paused(
|
||||
api: Api,
|
||||
stand: Stand,
|
||||
alice: Actor,
|
||||
chat: dict[str, Any],
|
||||
) -> None:
|
||||
data = images.sample_png()
|
||||
attachment = api.upload(alice, chat["id"], data)
|
||||
# срок клиента больше срока вызова S3: ждём ответ API, а не свой обрыв
|
||||
slow = Api(str(api.client.base_url), timeout=3 * S3_TIMEOUT_S)
|
||||
with slow, outage(stand, "pause", "s3"):
|
||||
for call in (
|
||||
lambda: upload_raw(slow, alice, chat, data),
|
||||
lambda: slow.attachment_content(alice, attachment["id"]),
|
||||
):
|
||||
resp, elapsed = timed(call)
|
||||
assert_error(resp, 503)
|
||||
# срок вызова S3 и немного на шаги с БД, а не зависание
|
||||
assert elapsed < S3_TIMEOUT_S + 2 * SLACK_S, (
|
||||
f"503 after {elapsed:.2f}s"
|
||||
)
|
||||
assert_content(
|
||||
api.attachment_content(alice, attachment["id"]),
|
||||
data,
|
||||
"image/png",
|
||||
)
|
||||
|
||||
Reference in New Issue
Block a user