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:
@@ -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)
|
||||
|
||||
|
||||
Reference in New Issue
Block a user