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
+61 -4
View File
@@ -1,7 +1,8 @@
"""Зависимости ручек: сессия БД, сервисы, вход и текущая сессия, страница.
Сервисы получают сессию БД, а чаты и сообщения — ещё и кэш процесса
(`src/infra/cache/instance.py`).
(`src/infra/cache/instance.py`). Вложения — фабрику короткой сессии на
шаг, кэш и хранилище объектов (`src/infra/s3/instance.py`).
"""
import asyncio
@@ -9,6 +10,7 @@ import base64
import binascii
import re
from collections.abc import AsyncIterator
from contextlib import asynccontextmanager
from dataclasses import dataclass
from typing import Annotated
@@ -20,6 +22,7 @@ from sqlalchemy.ext.asyncio import AsyncSession
from src.config import settings
from src.core import exceptions
from src.core.services import (
AttachmentService,
ChatService,
MessageService,
SessionService,
@@ -29,6 +32,7 @@ from src.infra.cache.instance import cache
from src.infra.db import is_db_unavailable, ping
from src.infra.db.session import engine, session_factory
from src.infra.logger import AbstractLogger, current_user_id, get_logger
from src.infra.s3.instance import object_storage
from src.schemas import dataclasses
from src.utils.constants import (
PAGE_LIMIT_DEFAULT,
@@ -43,10 +47,11 @@ from src.utils.constants import (
logger: AbstractLogger = get_logger().bind(module="api_dependencies")
async def get_db_session() -> AsyncIterator[AsyncSession]:
"""Одна сессия БД на запрос; commit делает сервис.
@asynccontextmanager
async def db_session_scope() -> AsyncIterator[AsyncSession]:
"""Сессия БД на один шаг; commit делает сервис.
Незакоммиченное при выходе откатывается. Вся работа запроса с БД
Незакоммиченное при выходе откатывается. Работа с БД внутри
ограничена `[database] request_timeout_seconds`: зависший Postgres не
держит запрос бесконечно. Недоступность БД (`is_db_unavailable`) —
503 `unavailable`, а соединение не возвращается в пул: его состояние
@@ -70,6 +75,19 @@ async def get_db_session() -> AsyncIterator[AsyncSession]:
raise exceptions.ServiceUnavailable from e
async def get_db_session() -> AsyncIterator[AsyncSession]:
"""Одна сессия БД на запрос — `db_session_scope` на весь запрос.
Зависимость с `yield` FastAPI закрывает после отправки ответа, поэтому
срок и соединение пула охватывают и отдачу тела. Ручкам с длинной
передачей (вложения) она не подходит: им — `CurrentUserBrief` и
сервис с `db_session_scope` на шаг (design change `attachments`,
решение 5).
"""
async with db_session_scope() as db_session:
yield db_session
DbSessionDep = Annotated[AsyncSession, Depends(get_db_session)]
@@ -101,10 +119,23 @@ async def get_session_service(db_session: DbSessionDep) -> SessionService:
return SessionService(db_session=db_session)
async def get_attachment_service() -> AttachmentService:
"""Без сессии запроса: сервис открывает `db_session_scope` на шаг."""
return AttachmentService(
db_scope=db_session_scope,
cache=cache,
storage=object_storage,
)
UserServiceDep = Annotated[UserService, Depends(get_user_service)]
ChatServiceDep = Annotated[ChatService, Depends(get_chat_service)]
MessageServiceDep = Annotated[MessageService, Depends(get_message_service)]
SessionServiceDep = Annotated[SessionService, Depends(get_session_service)]
AttachmentServiceDep = Annotated[
AttachmentService,
Depends(get_attachment_service),
]
# схемы basicAuth и bearerAuth из contracts/openapi.json: объявлены в
@@ -204,6 +235,32 @@ async def get_current_user(
CurrentUser = Annotated[dataclasses.UserFullDTO, Depends(get_current_user)]
async def get_current_user_brief(
credentials: Annotated[
HTTPAuthorizationCredentials | None,
Security(bearer_scheme),
],
) -> dataclasses.UserFullDTO:
"""Пользователь по Bearer-токену с короткой сессией БД; иначе 401.
Обычная функция, а не генератор: сессия закрыта и соединение
вернулось в пул до тела запроса. Для ручек с длинной передачей байтов
(design change `attachments`, решение 5).
"""
async with db_session_scope() as db_session:
current = await SessionService(db_session=db_session).authenticate(
token=credentials.credentials if credentials else None,
)
current_user_id.set(str(current.user.id))
return current.user
CurrentUserBrief = Annotated[
dataclasses.UserFullDTO,
Depends(get_current_user_brief),
]
@dataclass(frozen=True, slots=True)
class PageQuery:
limit: int