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:
+61
-4
@@ -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
|
||||
|
||||
@@ -28,8 +28,17 @@ DOMAIN_ERRORS: dict[type[exceptions.DomainError], tuple[int, ErrorCode]] = {
|
||||
exceptions.UsernameTaken: (409, ErrorCode.CONFLICT),
|
||||
exceptions.IdempotencyConflict: (409, ErrorCode.CONFLICT),
|
||||
exceptions.ChatNotFound: (404, ErrorCode.NOT_FOUND),
|
||||
exceptions.AttachmentNotFound: (404, ErrorCode.NOT_FOUND),
|
||||
exceptions.InvalidChatMembers: (400, ErrorCode.INVALID_REQUEST),
|
||||
exceptions.InvalidCursor: (400, ErrorCode.INVALID_REQUEST),
|
||||
exceptions.UploadInterrupted: (400, ErrorCode.INVALID_REQUEST),
|
||||
exceptions.PayloadTooLarge: (413, ErrorCode.PAYLOAD_TOO_LARGE),
|
||||
exceptions.UnsupportedMediaType: (
|
||||
415,
|
||||
ErrorCode.UNSUPPORTED_MEDIA_TYPE,
|
||||
),
|
||||
# расхождение БД и S3, а не ошибка клиента: причина — в журнале
|
||||
exceptions.AttachmentContentMissing: (500, ErrorCode.INTERNAL_ERROR),
|
||||
exceptions.ServiceUnavailable: (503, ErrorCode.UNAVAILABLE),
|
||||
# доменная ошибка без своей строки — некорректный запрос
|
||||
exceptions.DomainError: (400, ErrorCode.INVALID_REQUEST),
|
||||
|
||||
@@ -8,6 +8,7 @@ from fastapi import APIRouter
|
||||
|
||||
from src.utils.constants import API_V1_PREFIX
|
||||
|
||||
from .attachment import router as attachment_router
|
||||
from .chat import router as chat_router
|
||||
from .message import router as message_router
|
||||
from .session import router as session_router
|
||||
@@ -18,6 +19,7 @@ v1_router.include_router(user_router)
|
||||
v1_router.include_router(session_router)
|
||||
v1_router.include_router(chat_router)
|
||||
v1_router.include_router(message_router)
|
||||
v1_router.include_router(attachment_router)
|
||||
|
||||
__all__ = [
|
||||
"v1_router",
|
||||
|
||||
@@ -0,0 +1,153 @@
|
||||
"""Вложения: загрузка, метаданные, байты оригинала.
|
||||
|
||||
Один роутер с двумя префиксами путей — `/chats/{chat_id}/attachments` и
|
||||
`/attachments/{attachment_id}`: домен один. Сессии БД на весь запрос
|
||||
нет: вход — `CurrentUserBrief`, сервис открывает короткую сессию на
|
||||
каждый шаг (design change `attachments`, решение 5).
|
||||
"""
|
||||
|
||||
from collections.abc import AsyncIterator
|
||||
from typing import Annotated, Literal
|
||||
|
||||
from fastapi import APIRouter, Query, Request
|
||||
from fastapi.responses import StreamingResponse
|
||||
from starlette.background import BackgroundTask
|
||||
from starlette.requests import ClientDisconnect
|
||||
|
||||
from src.api.dependencies import AttachmentServiceDep, CurrentUserBrief
|
||||
from src.api.schemas import Attachment, DisplayFilename, UuidIn
|
||||
from src.core import exceptions
|
||||
from src.schemas.enums import ImageType
|
||||
from src.utils.constants import (
|
||||
ATTACHMENT_FILENAME_MAX_LENGTH,
|
||||
ATTACHMENT_FILENAME_MIN_LENGTH,
|
||||
)
|
||||
|
||||
router = APIRouter(tags=["attachments"])
|
||||
|
||||
_BINARY = {"schema": {"type": "string", "format": "binary"}}
|
||||
# тело загрузки — сырые байты, параметра тела у ручки нет (FastAPI его не
|
||||
# читает): схему для /openapi.json и /docs задаём как в контракте
|
||||
_UPLOAD_BODY = {
|
||||
"requestBody": {
|
||||
"required": True,
|
||||
"description": "Raw bytes of one PNG or JPEG image, not multipart.",
|
||||
"content": {image_type.value: _BINARY for image_type in ImageType},
|
||||
},
|
||||
}
|
||||
_DOWNLOAD_RESPONSES = {
|
||||
200: {
|
||||
"description": "Original bytes",
|
||||
"content": {image_type.value: _BINARY for image_type in ImageType},
|
||||
},
|
||||
}
|
||||
|
||||
FilenameQuery = Annotated[
|
||||
DisplayFilename,
|
||||
Query(
|
||||
min_length=ATTACHMENT_FILENAME_MIN_LENGTH,
|
||||
max_length=ATTACHMENT_FILENAME_MAX_LENGTH,
|
||||
),
|
||||
]
|
||||
|
||||
|
||||
def _media_type(request: Request) -> str | None:
|
||||
"""Тип из `Content-Type` без параметров и пробелов, в нижнем регистре."""
|
||||
value = request.headers.get("content-type")
|
||||
if value is None:
|
||||
return None
|
||||
return value.split(";", 1)[0].strip().lower() or None
|
||||
|
||||
|
||||
def _content_length(request: Request) -> int | None:
|
||||
value = request.headers.get("content-length")
|
||||
return int(value) if value is not None and value.isdigit() else None
|
||||
|
||||
|
||||
async def _body(request: Request) -> AsyncIterator[bytes]:
|
||||
"""Тело блоками по мере прихода; обрыв клиента — `UploadInterrupted`."""
|
||||
try:
|
||||
async for chunk in request.stream():
|
||||
if chunk:
|
||||
yield chunk
|
||||
except ClientDisconnect as e:
|
||||
raise exceptions.UploadInterrupted from e
|
||||
|
||||
|
||||
@router.post(
|
||||
"/chats/{chat_id}/attachments",
|
||||
status_code=201,
|
||||
response_model=Attachment,
|
||||
openapi_extra=_UPLOAD_BODY,
|
||||
)
|
||||
async def upload_attachment(
|
||||
user: CurrentUserBrief,
|
||||
chat_id: UuidIn,
|
||||
filename: FilenameQuery,
|
||||
request: Request,
|
||||
attachments: AttachmentServiceDep,
|
||||
) -> Attachment:
|
||||
"""201 — оригинал в S3 и метаданные в PostgreSQL сохранены.
|
||||
|
||||
Тело не читается, пока не пройдены вход, параметры, членство,
|
||||
`Content-Type` и `Content-Length` (спек «Порядок проверок загрузки»).
|
||||
"""
|
||||
attachment = await attachments.upload(
|
||||
chat_id=chat_id,
|
||||
owner_id=user.id,
|
||||
filename=filename,
|
||||
media_type=_media_type(request),
|
||||
content_length=_content_length(request),
|
||||
body=_body(request),
|
||||
)
|
||||
return Attachment.model_validate(attachment)
|
||||
|
||||
|
||||
@router.get("/attachments/{attachment_id}", response_model=Attachment)
|
||||
async def get_attachment(
|
||||
user: CurrentUserBrief,
|
||||
attachment_id: UuidIn,
|
||||
attachments: AttachmentServiceDep,
|
||||
) -> Attachment:
|
||||
attachment = await attachments.get_attachment(
|
||||
attachment_id=attachment_id,
|
||||
user_id=user.id,
|
||||
)
|
||||
return Attachment.model_validate(attachment)
|
||||
|
||||
|
||||
@router.get(
|
||||
"/attachments/{attachment_id}/content",
|
||||
response_class=StreamingResponse,
|
||||
responses=_DOWNLOAD_RESPONSES,
|
||||
)
|
||||
async def download_attachment(
|
||||
user: CurrentUserBrief,
|
||||
attachment_id: UuidIn,
|
||||
attachments: AttachmentServiceDep,
|
||||
# проверка значения — по схеме; вариант на лабе 4 один. enum — как в
|
||||
# контракте: Literal из одного значения pydantic пишет как const
|
||||
variant: Annotated[ # noqa: ARG001
|
||||
Literal["original"],
|
||||
Query(json_schema_extra={"enum": ["original"]}),
|
||||
] = "original",
|
||||
) -> StreamingResponse:
|
||||
"""Байты оригинала потоком из S3, без redirect.
|
||||
|
||||
`variant` — только `original` (перечисление контракта лабы 4).
|
||||
Отказ S3 до заголовков — 503; посреди потока соединение обрывается.
|
||||
"""
|
||||
content = await attachments.open_content(
|
||||
attachment_id=attachment_id,
|
||||
user_id=user.id,
|
||||
)
|
||||
return StreamingResponse(
|
||||
content.chunks,
|
||||
media_type=content.content_type.value,
|
||||
headers={
|
||||
"Content-Length": str(content.size_bytes),
|
||||
"X-Content-Type-Options": "nosniff",
|
||||
},
|
||||
# генератор сам закрывает объект; это — если он не начался
|
||||
background=BackgroundTask(content.close),
|
||||
)
|
||||
@@ -41,6 +41,7 @@ async def send_message(
|
||||
sender_id=user.id,
|
||||
text=body.text,
|
||||
idempotency_key=idempotency_key,
|
||||
attachment_ids=body.attachment_ids,
|
||||
)
|
||||
return Message.model_validate(message)
|
||||
|
||||
|
||||
@@ -1,3 +1,4 @@
|
||||
from .attachment import Attachment, DisplayFilename
|
||||
from .chat import Chat, ChatPage, CreateChat
|
||||
from .common import Error, ErrorBody, ErrorCode, Health, UuidIn
|
||||
from .message import CreateMessage, Message, MessagePage
|
||||
@@ -5,11 +6,13 @@ from .session import Session
|
||||
from .user import CreateUser, User
|
||||
|
||||
__all__ = [
|
||||
"Attachment",
|
||||
"Chat",
|
||||
"ChatPage",
|
||||
"CreateChat",
|
||||
"CreateMessage",
|
||||
"CreateUser",
|
||||
"DisplayFilename",
|
||||
"Error",
|
||||
"ErrorBody",
|
||||
"ErrorCode",
|
||||
|
||||
@@ -0,0 +1,64 @@
|
||||
import unicodedata
|
||||
from typing import Annotated, Any, Literal
|
||||
from uuid import UUID
|
||||
|
||||
from pydantic import AfterValidator, BaseModel, BeforeValidator, ConfigDict
|
||||
|
||||
from src.api.schemas.common import UtcDatetime
|
||||
from src.schemas.enums import ImageType
|
||||
from src.utils.constants import (
|
||||
ATTACHMENT_FILENAME_FORBIDDEN_CATEGORY,
|
||||
ATTACHMENT_FILENAME_FORBIDDEN_CHARS,
|
||||
)
|
||||
|
||||
|
||||
def _check_filename(value: str) -> str:
|
||||
"""Отображаемое имя: отказ только по списку контракта.
|
||||
|
||||
`/`, `\\`, управляющие символы категории Cc (U+0000–U+001F,
|
||||
U+007F–U+009F) и строка из одних пробелов — 400. Символы
|
||||
форматирования и направления текста (Cf), разделители строк и абзацев
|
||||
принимаются (design change `attachments`, решение 10). Значение не
|
||||
меняется.
|
||||
"""
|
||||
if not value.strip():
|
||||
raise ValueError("must not be blank")
|
||||
for char in value:
|
||||
if (
|
||||
char in ATTACHMENT_FILENAME_FORBIDDEN_CHARS
|
||||
or unicodedata.category(char)
|
||||
== ATTACHMENT_FILENAME_FORBIDDEN_CATEGORY
|
||||
):
|
||||
raise ValueError(
|
||||
"must not contain path separators or control characters",
|
||||
)
|
||||
return value
|
||||
|
||||
|
||||
def _sha256_hex(value: object) -> object:
|
||||
"""SHA-256 из DTO — байты; в ответе — hex в нижнем регистре."""
|
||||
return value.hex() if isinstance(value, bytes) else value
|
||||
|
||||
|
||||
# длина 1–255 — в Query ручки: так она есть в /openapi.json
|
||||
DisplayFilename = Annotated[str, AfterValidator(_check_filename)]
|
||||
|
||||
|
||||
class Attachment(BaseModel):
|
||||
"""Схема контракта `Attachment`; ключа объекта в ней нет."""
|
||||
|
||||
model_config = ConfigDict(from_attributes=True)
|
||||
|
||||
id: UUID
|
||||
chat_id: UUID
|
||||
owner_id: UUID
|
||||
filename: str
|
||||
content_type: ImageType
|
||||
size_bytes: int
|
||||
sha256: Annotated[str, BeforeValidator(_sha256_hex)]
|
||||
# API показывает только готовые вложения; варианты — с лабы 5
|
||||
status: Literal["ready"]
|
||||
variants: list[dict[str, Any]] = []
|
||||
error_code: None = None
|
||||
created_at: UtcDatetime
|
||||
updated_at: UtcDatetime
|
||||
@@ -1,24 +1,40 @@
|
||||
from typing import Self
|
||||
from uuid import UUID
|
||||
|
||||
from pydantic import BaseModel, ConfigDict, Field
|
||||
from pydantic import BaseModel, ConfigDict, Field, StrictStr, model_validator
|
||||
|
||||
from src.api.schemas.common import NonBlankStr, UtcDatetime
|
||||
from src.api.schemas.common import UtcDatetime, UuidIn
|
||||
from src.utils.constants import (
|
||||
MESSAGE_ATTACHMENTS_MAX,
|
||||
MESSAGE_TEXT_MAX_LENGTH,
|
||||
MESSAGE_TEXT_MIN_LENGTH,
|
||||
)
|
||||
|
||||
|
||||
class CreateMessage(BaseModel):
|
||||
"""Отправитель берётся из идентификации; поле sender_id — 400."""
|
||||
"""Отправитель берётся из идентификации; поле sender_id — 400.
|
||||
|
||||
Пустой текст — `""` или из одних пробельных символов — допустим
|
||||
только с хотя бы одним вложением (согласовано с преподавателем
|
||||
2026-10-20, AGENTS.md). Текст не обрезается и не нормализуется.
|
||||
"""
|
||||
|
||||
model_config = ConfigDict(extra="forbid")
|
||||
|
||||
text: NonBlankStr = Field(
|
||||
min_length=MESSAGE_TEXT_MIN_LENGTH,
|
||||
max_length=MESSAGE_TEXT_MAX_LENGTH,
|
||||
text: StrictStr = Field(max_length=MESSAGE_TEXT_MAX_LENGTH)
|
||||
# элементы — запись UUID контракта; повтор (и в другом регистре) — 400
|
||||
attachment_ids: list[UuidIn] = Field(
|
||||
default_factory=list,
|
||||
max_length=MESSAGE_ATTACHMENTS_MAX,
|
||||
)
|
||||
|
||||
@model_validator(mode="after")
|
||||
def _check_text_and_attachments(self) -> Self:
|
||||
if len(set(self.attachment_ids)) != len(self.attachment_ids):
|
||||
raise ValueError("attachment_ids must be unique")
|
||||
if not self.text.strip() and not self.attachment_ids:
|
||||
raise ValueError("text must not be blank without attachments")
|
||||
return self
|
||||
|
||||
|
||||
class Message(BaseModel):
|
||||
model_config = ConfigDict(from_attributes=True)
|
||||
@@ -28,6 +44,7 @@ class Message(BaseModel):
|
||||
sender_id: UUID
|
||||
text: str
|
||||
created_at: UtcDatetime
|
||||
attachment_ids: list[UUID]
|
||||
|
||||
|
||||
class MessagePage(BaseModel):
|
||||
|
||||
Reference in New Issue
Block a user