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
+27
View File
@@ -67,6 +67,33 @@ paths:
транзиентной ошибки не сохраняется;
- лог: `Created message` или `Replayed message` с `message_id` и
`replayed`, без ключа и текста (`logging.md`).
- Вложения (лаба 4, design change `attachments`, решения 1, 5–9):
- `AttachmentService(db_scope, cache, storage)` — отличие от правила
выше: вместо `db_session` фабрика короткой сессии на шаг
(`db_session_scope`), каждый шаг с БД — свой `async with
self.db_scope()`, без вложенных: соединение пула не занято передачей
тела, на запрос не больше одного соединения. `storage` — глобал
`object_storage` из зависимости;
- порядок записи загрузки: проверки (членство, `Content-Type`,
`Content-Length`) → чтение тела со счётчиком → структура
изображения и SHA-256 одним `anyio.to_thread.run_sync` → строка
`pending` с `object_key` (commit) → PUT (`attachment_object_repo`) →
`mark_ready` (commit) → DTO. Отказ S3 или БД после `pending` — 503,
строка остаётся до уборщика (`upload-consistency`); `mark_ready` не
нашёл `pending` — `RuntimeError`. Отклонённая до `pending` загрузка
ничего не пишет;
- чтение: `pending`, нет строки, не участник — одно
`AttachmentNotFound`; скачивание — `open_original` вне транзакции,
нет объекта или другой размер — `error` в журнале и
`AttachmentContentMissing` (500), строка не меняется;
- `MessageService.send_message(..., attachment_ids)`: членство →
`get_attachments` (все найдены, чат этого сообщения, `ready`; иначе
`AttachmentNotFound` до захвата ключа) → хэш → ключ → сообщение →
`insert_message_attachments` (если список непустой) → один commit;
- хэш: `message_request_hash(text, attachment_ids)` — `attachment_ids`
в каноническом JSON только непустым, id — `str(UUID)` (нижний
регистр), порядок значим. Пустой список хэш версии `e1161f7` не
меняет: ключ, сохранённый до замены реплик, повторяется.
- Недоступность Postgres (там же хранятся сессии) — доменное
`ServiceUnavailable` (→ 503), не 500 и никогда не пропуск запроса без
аутентификации (`infra.md`). Недоступность Valkey — не ошибка, а