Files
mtusi2026lab2/openspec/changes/add-lab4-image-attachments/tasks.md
T
ArtyomandClaude Opus 5.5 f9760fc098 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>
2026-10-28 20:45:19 +03:00

57 lines
7.7 KiB
Markdown
Raw Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
## 1. Схема
- [x] 1.1 Миграция `0003_attachments.sql`: `attachments` (статус `pending`/`ready`, `object_key COLLATE "C"`, `UNIQUE (id, chat_id)`, FK на `chat_members`, частичный индекс `pending`), `message_attachments` (FK на `attachments (id, chat_id)` `ON DELETE RESTRICT`, индекс по `attachment_id`), ослабленный `messages_text_check`
- [x] 1.2 Проверка группы: тест миграций — версия `0003`, повтор без изменений, вложение не участника и ссылка на вложение другого чата отклоняются внешними ключами, пустой текст принимается схемой
## 2. Зона `attachments`: домен и приложение
- [x] 2.1 Домен: `Filename`, `ImageKind`, `ImageInfo`, агрегат `Attachment` (`stage` → `pending`, `store` → `ready` с событием `AttachmentStored`), ошибки зоны
- [x] 2.2 Порты: `ChatMembership`, `ObjectStorage` (`put`/`open`/`delete`, `ObjectContent`, `ObjectMissing`), `ImageInspector`, `AttachmentsUnitOfWork`, `AttachmentDirectory`
- [x] 2.3 Команда `UploadAttachment` и обработчик: членство → имя → `Content-Type` → поток со счётчиком и SHA-256 → проверка изображения → `pending` → `put` → `ready`; запросы `GetAttachment`, `OpenAttachment`
- [x] 2.4 Проверка группы: unit-тесты `Filename` (граничные и опасные имена), агрегата и порядка записи обработчика с фейковыми портами (сбой `put` даёт `503` и не делает вложение готовым)
## 3. Зона `attachments`: инфраструктура и HTTP
- [x] 3.1 Адаптер PostgreSQL: `add`, `save`, `get` готового; нарушение FK членства → `404`
- [x] 3.2 Адаптер `PillowImageInspector`: открытие только PNG/JPEG, подмена MIME, пиксели по заголовку, PNG `verify`, JPEG `draft` + `load`, `to_thread` под семафором
- [x] 3.3 Адаптер `S3ObjectStorage` на aiobotocore (path-style, SigV4, таймауты, checksum `when_required`), отображение ошибок в `ObjectMissing`/`Unavailable`; зависимости aiobotocore и Pillow в `uv.lock`
- [x] 3.4 Настройки зоны (`S3_*`, `MAX_UPLOAD_BYTES`, `MAX_IMAGE_PIXELS`, таймауты, параллелизм проверки), провайдер dishka, схемы `AttachmentOut`, роутер upload/метаданных/скачивания, реестр ошибок, журнал
- [ ] 3.5 Проверка группы: тест адаптера S3 против одноразового RustFS (put/open/delete, пропавший объект, недоступный endpoint → `Unavailable` за ограниченное время)
## 4. Связь зон и платформа
- [x] 4.1 Платформа: лимит тела по шаблону маршрута в конвейере
- [x] 4.2 `main.py`: зона `attachments`, адаптер `MessagingMembership` для порта `ChatMembership`, лимит upload, поля журнала, реестр ошибок; `create_app` принимает дополнительные провайдеры для тестов
- [x] 4.3 Проверка группы: тест графа импортов — `attachments` не импортирует `identity`/`messaging`, `messaging` не импортирует `attachments`, `shared` не знает зон
## 5. Зона `messaging`: `attachment_ids`
- [x] 5.1 Домен: `Message.attachment_ids`, `Chat.post` с проверкой списка вложений, `MessageText` с пустой строкой, ошибки `InvalidAttachmentList` и `UnknownAttachment`
- [x] 5.2 HTTP и команда: `CreateMessageRequest.attachment_ids` (по умолчанию `[]`, отпечаток), `MessageOut.attachment_ids`
- [x] 5.3 PostgreSQL: запись `message_attachments` в операторе отправки, FK → `404`, `attachment_ids` в повторе и истории подзапросом
- [x] 5.4 Проверка группы: тесты — пустой текст с вложением, порядок, другой чат и неизвестный id `404`, 11 и повторы `400`, посторонний `404` раньше `400`, повтор с вложением, отсутствующий ≡ `[]`, другой порядок `409`, история с `attachment_ids`
## 6. API-тесты вложений
- [x] 6.1 Генераторы тестовых PNG (произвольный размер в пикселях и байтах) и JPEG, фейковое `ObjectStorage` в `student-tests`
- [x] 6.2 Тесты: fixture `201` и побайтное скачивание вторым участником, посторонний `404` на метаданных и `/content`, ровно 10 MiB `201`, +1 байт `413` с `Content-Length` и chunked, 40 MP `201` и 40 MP+ `413`, подмена MIME, обрезанные PNG/JPEG, иной и пустой `Content-Type` `415`, опасные и пустые `filename` `400`, `variant=thumbnail` `400`, сбой хранилища `503` без готового вложения, пропавший объект `404`, заголовки на бинарном ответе
## 7. Стенд
- [ ] 7.1 `infra/s3/` (`init.sh`, `cli.sh`, `api-policy.json`, `lifecycle.json`) из заготовки
- [ ] 7.2 `compose.yaml`: `s3`, `s3-init`, `s3-cli`, volume `s3data`, секреты S3, якорь `x-s3-env` у `api`, зависимость от `s3-init`; `.env.example` (таймауты S3, параллелизм проверки)
- [ ] 7.3 `scripts/secrets.sh` (секреты S3), `scripts/restart.sh` (S3 в списке хранилищ), `scripts/evidence-stack.sh` (пакеты и образы лабы 4)
- [ ] 7.4 Проверка группы: `docker compose config --quiet`, у `api` только ключ API S3, `make up` из чистого состояния, все сервисы `healthy`, `s3-init` завершился кодом 0, опубликованы только порты `lb`
## 8. Сценарии отказов и обвязка
- [ ] 8.1 `scripts/lab4_scenarios.py` (`failover-upload`, `s3-outage`), `scripts/s3-check.sh`, `scripts/evidence-attachments.sh`; цели Makefile `scenario`, `s3-check`, `attachments-evidence`; ruff для новых `scripts/*.py`
- [ ] 8.2 CI-job под лабу 4: сценарии вложений после smoke
- [ ] 8.3 Проверка группы: `make test`, `make test-persistence ACTION_SCRIPT=scripts/restart.sh`, `make test-failover ACTION_SCRIPT=scripts/stop-one.sh` по обеим репликам с `make restore`, `make scenario SCENARIO=failover-upload`, `make scenario SCENARIO=s3-outage`, `make s3-check`
## 9. Отчёт
- [ ] 9.1 `evidence/`: smoke, contract-checks, student-tests, stack, storage-layout, failover-upload, failover по каждой реплике, persistence со `StartedAt` (включая `s3`), s3-outage, s3-security, схема и миграции, окружение
- [ ] 9.2 `REPORT.md`: запуск из чистого clone, архитектура и решения, таблица ролей и сервисов, соответствие переменных `.env.example`, строки уровня «3», таблица отказов уровня «3»
- [ ] 9.3 Проверка группы: `make check`, `make validate`, `make lint`, `make student-test`, `make test` и сценарии зелёные