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
+33
View File
@@ -27,6 +27,10 @@ FastAPI, один процесс на реплику; реплик ≥2 за HAP
Вложенный ресурс — префикс с параметром: `message.py` →
`prefix="/chats/{chat_id}/messages"`. Логгер модуля
`module="api_<domain>_router"`.
- Исключение — `attachment.py` (лаба 4): один роутер домена с двумя
префиксами путей, `APIRouter(tags=["attachments"])` и полные пути
`/chats/{chat_id}/attachments`, `/attachments/{attachment_id}` и
`/attachments/{attachment_id}/content` в декораторах.
- Версию задаёт `v1_router` (`API_V1_PREFIX` из `src/utils/constants.py`)
в `routers/v1/__init__.py`. Регистрация домена — импорт и
`v1_router.include_router(...)` там, больше нигде.
@@ -51,6 +55,35 @@ FastAPI, один процесс на реплику; реплик ≥2 за HAP
глобального `session_factory` (`src/infra/db/session.py`): одна на
запрос, закрывается после ответа, вся работа с БД ограничена сроком,
отказ БД — 503 (`infra.md`). Commit делает сервис (`service-layer.md`).
- Длинная передача байтов (вложения, лаба 4; design change
`attachments`, решение 5). `get_db_session` — зависимость с `yield`, и
FastAPI закрывает её после отправки ответа целиком: её срок
(`request_timeout_seconds`, 6 с) и соединение пула охватили бы чтение
тела 10 MiB, PUT в S3 и отдачу потока. Поэтому ручки вложений:
- вход — `CurrentUserBrief` (`get_current_user_brief`): Bearer, короткий
`async with db_session_scope()` вокруг `SessionService.authenticate`,
соединение вернулось в пул до тела запроса; обычная функция, не
генератор;
- сервис — `AttachmentServiceDep` без `DbSessionDep`: он получает
фабрику `db_session_scope` (контекст на один шаг с БД, тот же срок и
перевод отказа в 503, что у `get_db_session`), кэш и глобал
`object_storage`;
- загрузка объявляет `request: Request` и не объявляет параметр тела —
FastAPI тело не читает; схема тела (`image/png`, `image/jpeg`,
`format: binary`) — в `openapi_extra`. Тело уходит в сервис
асинхронным итератором поверх `request.stream()`, обёртка переводит
`ClientDisconnect` в доменное `UploadInterrupted` (400): в итоговой
записи 400, а не 500 с traceback. `Content-Type` — тип до `;`, без
пробелов, в нижнем регистре; `Content-Length` — `int` или `None`;
- скачивание — `StreamingResponse` над генератором блоков объекта S3:
`media_type` вложения (у `image/*` Starlette `charset` не добавляет),
`Content-Length`, `X-Content-Type-Options: nosniff`; генератор сам
закрывает объект в `finally`, тот же закрыватель — фоновой задачей
ответа на случай, если генератор не начался;
- `variant` — `Literal["original"]` с `Query(json_schema_extra={"enum":
["original"]})`: Literal из одного значения pydantic пишет как
`const`, а контракт — `enum`.
JSON-ручки по-прежнему на `get_db_session`.
- Ошибки — доменные исключения из сервиса. `HTTPException` не бросать.
Статус, `code` и заголовки ответа (`WWW-Authenticate` у 401)
назначает одна таблица в `errors.py`.