feat: добавить вложения с хранением в MinIO и отчёт lab4

Co-authored-by: aider (deepseek/deepseek-chat) <aider@aider.chat>
This commit is contained in:
Evgeny Bushkov
2026-11-06 15:18:08 +03:00
co-authored by aider
parent 7542225498
commit 7537719fc6
17 changed files with 1005 additions and 24 deletions
+26 -1
View File
@@ -2,14 +2,39 @@ import os
import uuid
def _read_secret(env_name: str, file_env_name: str) -> str | None:
"""Значение из env или из файла (Docker secrets)."""
value = os.environ.get(env_name)
if value:
return value
path = os.environ.get(file_env_name)
if path and os.path.isfile(path):
with open(path, "r", encoding="utf-8") as fh:
return fh.read().strip()
return None
class Settings:
def __init__(self) -> None:
self.database_url = os.environ["DATABASE_URL"]
self.database_url = _read_secret("DATABASE_URL", "DATABASE_URL_FILE") or os.environ["DATABASE_URL"]
self.session_ttl_seconds = int(os.environ.get("SESSION_TTL_SECONDS", "3600"))
self.idempotency_ttl_seconds = int(os.environ.get("IDEMPOTENCY_TTL_SECONDS", "86400"))
self.instance_id = os.environ.get("INSTANCE_ID") or uuid.uuid4().hex
self.host = os.environ.get("APP_HOST", "0.0.0.0")
self.port = int(os.environ.get("APP_PORT", "8080"))
# S3 / MinIO
self.s3_endpoint = os.environ.get("S3_ENDPOINT", "http://s3:9000")
self.s3_region = os.environ.get("S3_REGION", "us-east-1")
self.s3_bucket = os.environ.get("S3_BUCKET", "messenger-attachments")
self.s3_access_key_id = _read_secret("S3_ACCESS_KEY_ID", "S3_ACCESS_KEY_ID_FILE")
self.s3_secret_access_key = _read_secret("S3_SECRET_ACCESS_KEY", "S3_SECRET_ACCESS_KEY_FILE")
self.s3_use_ssl = os.environ.get("S3_USE_SSL", "false").lower() == "true"
# Лимиты вложений
self.max_upload_bytes = int(os.environ.get("MAX_UPLOAD_BYTES", str(10 * 1024 * 1024)))
self.max_image_pixels = int(os.environ.get("MAX_IMAGE_PIXELS", "40000000"))
self.upload_chunk_size = int(os.environ.get("UPLOAD_CHUNK_SIZE", str(64 * 1024)))
settings = Settings()
+2 -1
View File
@@ -10,7 +10,7 @@ from starlette.exceptions import HTTPException as StarletteHTTPException
from .config import settings
from .errors import ApiError, error_response
from .routers import auth, chats, health, messages, users
from .routers import attachments, auth, chats, health, messages, users
logging.basicConfig(level=logging.INFO, format="%(asctime)s %(levelname)s %(name)s %(message)s")
log = logging.getLogger("app")
@@ -58,6 +58,7 @@ app.include_router(users.router)
app.include_router(auth.router)
app.include_router(chats.router)
app.include_router(messages.router)
app.include_router(attachments.router)
def _shutdown(signum, frame):
@@ -0,0 +1,45 @@
"""attachments
Revision ID: 0002
Revises: 0001
Create Date: 2026-11-06
"""
from alembic import op
import sqlalchemy as sa
from sqlalchemy.dialects import postgresql
revision = "0002"
down_revision = "0001"
branch_labels = None
depends_on = None
def upgrade() -> None:
op.create_table(
"attachments",
sa.Column("id", postgresql.UUID(as_uuid=True), primary_key=True),
sa.Column("chat_id", postgresql.UUID(as_uuid=True), sa.ForeignKey("chats.id", ondelete="CASCADE"), nullable=False),
sa.Column("owner_id", postgresql.UUID(as_uuid=True), sa.ForeignKey("users.id"), nullable=False),
sa.Column("filename", sa.String(255), nullable=False),
sa.Column("content_type", sa.String(32), nullable=False),
sa.Column("size_bytes", sa.Integer(), nullable=False),
sa.Column("sha256", sa.String(64), nullable=False),
sa.Column("object_key", sa.String(255), nullable=False, unique=True),
sa.Column("status", sa.String(16), nullable=False, server_default="ready"),
sa.Column("error_code", sa.String(64), nullable=True),
sa.Column("created_at", sa.DateTime(timezone=True), server_default=sa.func.now(), nullable=False),
sa.Column("updated_at", sa.DateTime(timezone=True), server_default=sa.func.now(), nullable=False),
)
op.create_index("ix_attachments_chat_id", "attachments", ["chat_id"])
op.create_table(
"message_attachments",
sa.Column("message_id", postgresql.UUID(as_uuid=True), sa.ForeignKey("messages.id", ondelete="CASCADE"), primary_key=True),
sa.Column("attachment_id", postgresql.UUID(as_uuid=True), sa.ForeignKey("attachments.id", ondelete="CASCADE"), primary_key=True),
sa.Column("position", sa.Integer(), nullable=False, server_default="0"),
)
def downgrade() -> None:
op.drop_table("message_attachments")
op.drop_index("ix_attachments_chat_id", table_name="attachments")
op.drop_table("attachments")
+23
View File
@@ -63,6 +63,29 @@ class Message(Base):
__table_args__ = (Index("ix_messages_chat_created_id", "chat_id", "created_at", "id"),)
class Attachment(Base):
__tablename__ = "attachments"
id: Mapped[uuid.UUID] = mapped_column(UUID(as_uuid=True), primary_key=True, default=_uuid)
chat_id: Mapped[uuid.UUID] = mapped_column(UUID(as_uuid=True), ForeignKey("chats.id", ondelete="CASCADE"), nullable=False, index=True)
owner_id: Mapped[uuid.UUID] = mapped_column(UUID(as_uuid=True), ForeignKey("users.id"), nullable=False)
filename: Mapped[str] = mapped_column(String(255), nullable=False)
content_type: Mapped[str] = mapped_column(String(32), nullable=False)
size_bytes: Mapped[int] = mapped_column(Integer, nullable=False)
sha256: Mapped[str] = mapped_column(String(64), nullable=False)
object_key: Mapped[str] = mapped_column(String(255), nullable=False, unique=True)
status: Mapped[str] = mapped_column(String(16), nullable=False, default="ready")
error_code: Mapped[str | None] = mapped_column(String(64), nullable=True)
created_at: Mapped[datetime] = mapped_column(DateTime(timezone=True), server_default=func.now(), nullable=False)
updated_at: Mapped[datetime] = mapped_column(DateTime(timezone=True), server_default=func.now(), onupdate=func.now(), nullable=False)
class MessageAttachment(Base):
__tablename__ = "message_attachments"
message_id: Mapped[uuid.UUID] = mapped_column(UUID(as_uuid=True), ForeignKey("messages.id", ondelete="CASCADE"), primary_key=True)
attachment_id: Mapped[uuid.UUID] = mapped_column(UUID(as_uuid=True), ForeignKey("attachments.id", ondelete="CASCADE"), primary_key=True)
position: Mapped[int] = mapped_column(Integer, nullable=False, default=0)
class IdempotencyKey(Base):
__tablename__ = "idempotency_keys"
user_id: Mapped[uuid.UUID] = mapped_column(UUID(as_uuid=True), ForeignKey("users.id", ondelete="CASCADE"), primary_key=True)
+132
View File
@@ -0,0 +1,132 @@
"""Вложения: upload в S3, метаданные в PostgreSQL, download через API."""
import re
import uuid
from fastapi import APIRouter, Depends, Query, Request, Security
from fastapi.responses import Response
from sqlalchemy.orm import Session
from ..deps import current_user, get_db, parse_uuid
from ..errors import ApiError
from ..models import Attachment, ChatMember, User
from ..schemas import AttachmentOut
from .. import s3
router = APIRouter()
_FILENAME_BAD = re.compile(r"[/\\\x00-\x1f\x7f]")
def _validate_filename(raw: str) -> str:
if not isinstance(raw, str) or not (1 <= len(raw) <= 255):
raise ApiError(400, "invalid_request", "Некорректный filename")
if _FILENAME_BAD.search(raw):
raise ApiError(400, "invalid_request", "Некорректный filename")
return raw
def _require_member(db: Session, chat_id: uuid.UUID, user_id: uuid.UUID) -> None:
if db.get(ChatMember, (chat_id, user_id)) is None:
raise ApiError(404, "not_found", "Чат не найден")
def _to_out(att: Attachment) -> AttachmentOut:
return AttachmentOut(
id=att.id,
chat_id=att.chat_id,
owner_id=att.owner_id,
filename=att.filename,
content_type=att.content_type,
size_bytes=att.size_bytes,
sha256=att.sha256,
status=att.status,
variants=[],
error_code=att.error_code,
created_at=att.created_at,
updated_at=att.updated_at,
)
@router.post(
"/api/v1/chats/{chat_id}/attachments",
response_model=AttachmentOut,
status_code=201,
)
async def upload_attachment(
chat_id: str,
request: Request,
filename: str = Query(...),
user: User = Security(current_user),
db: Session = Depends(get_db),
):
cid = parse_uuid(chat_id)
_require_member(db, cid, user.id)
name = _validate_filename(filename)
declared = (request.headers.get("content-type") or "").split(";")[0].strip().lower()
if declared not in ("image/png", "image/jpeg"):
raise ApiError(415, "unsupported_media_type", "Ожидается image/png или image/jpeg")
# Читаем тело потоково с жёстким лимитом.
data, sha, actual = s3.read_upload(request.stream(), declared)
att_id = uuid.uuid4()
key = s3.new_object_key(str(cid), str(att_id))
s3.put_object(key, data, actual)
att = Attachment(
id=att_id,
chat_id=cid,
owner_id=user.id,
filename=name,
content_type=actual,
size_bytes=len(data),
sha256=sha,
object_key=key,
status="ready",
error_code=None,
)
db.add(att)
try:
db.commit()
except Exception:
db.rollback()
# Компенсация: удаляем объект, чтобы не оставить orphan в S3.
s3.delete_object(key)
raise
db.refresh(att)
return _to_out(att)
@router.get("/api/v1/attachments/{attachment_id}", response_model=AttachmentOut)
def get_attachment(
attachment_id: str,
user: User = Security(current_user),
db: Session = Depends(get_db),
):
aid = parse_uuid(attachment_id)
att = db.get(Attachment, aid)
if att is None:
raise ApiError(404, "not_found", "Вложение не найдено")
_require_member(db, att.chat_id, user.id)
return _to_out(att)
@router.get("/api/v1/attachments/{attachment_id}/content")
def download_attachment(
attachment_id: str,
variant: str = Query("original"),
user: User = Security(current_user),
db: Session = Depends(get_db),
):
aid = parse_uuid(attachment_id)
att = db.get(Attachment, aid)
if att is None:
raise ApiError(404, "not_found", "Вложение не найдено")
_require_member(db, att.chat_id, user.id)
if variant != "original":
raise ApiError(404, "not_found", "Вариант не найден")
if att.status != "ready":
raise ApiError(409, "conflict", "Вложение не готово")
body, ctype = s3.get_object(att.object_key)
return Response(content=body, media_type=ctype)
+56 -8
View File
@@ -12,7 +12,7 @@ from sqlalchemy.orm import Session
from ..config import settings
from ..deps import current_user, get_db, parse_uuid
from ..errors import ApiError
from ..models import Chat, ChatMember, IdempotencyKey, Message, User
from ..models import Attachment, Chat, ChatMember, IdempotencyKey, Message, MessageAttachment, User
from ..schemas import CreateMessage, MessageOut, MessagePage
from .chats import _decode_cursor, _encode_cursor, _require_member
@@ -22,10 +22,55 @@ _KEY_RE = re.compile(r"^[A-Za-z0-9._:-]{1,128}$")
def _body_hash(body: CreateMessage) -> str:
canonical = json.dumps({"text": body.text}, sort_keys=True, ensure_ascii=False)
canonical = json.dumps(
{
"text": body.text,
"attachment_ids": sorted(str(a) for a in body.attachment_ids),
},
sort_keys=True,
ensure_ascii=False,
)
return hashlib.sha256(canonical.encode("utf-8")).hexdigest()
def _attachment_ids_for(db: Session, message_id) -> list:
rows = db.scalars(
select(MessageAttachment.attachment_id)
.where(MessageAttachment.message_id == message_id)
.order_by(MessageAttachment.position.asc())
)
return list(rows)
def _to_out(db: Session, msg: Message) -> MessageOut:
return MessageOut(
id=msg.id,
chat_id=msg.chat_id,
sender_id=msg.sender_id,
text=msg.text,
created_at=msg.created_at,
attachment_ids=_attachment_ids_for(db, msg.id),
)
def _validate_attachments(db: Session, chat_id, ids: list) -> list:
"""Все вложения должны принадлежать этому чату и быть ready."""
if not ids:
return []
unique = list(dict.fromkeys(ids))
if len(unique) != len(ids):
raise ApiError(400, "invalid_request", "attachment_ids содержит дубликаты")
rows = list(db.scalars(select(Attachment).where(Attachment.id.in_(unique))))
by_id = {a.id: a for a in rows}
for aid in unique:
att = by_id.get(aid)
if att is None or att.chat_id != chat_id:
raise ApiError(404, "not_found", "Вложение не найдено")
if att.status == "failed":
raise ApiError(409, "conflict", "Вложение в состоянии failed")
return unique
@router.post("/api/v1/chats/{chat_id}/messages", response_model=MessageOut, status_code=201)
def create_message(
chat_id: str,
@@ -37,23 +82,26 @@ def create_message(
):
cid = parse_uuid(chat_id)
_require_member(db, cid, user.id)
if not body.text.strip():
raise ApiError(400, "invalid_request", "text не может быть пустым")
if not body.text.strip() and not body.attachment_ids:
raise ApiError(400, "invalid_request", "text не может быть пустым без вложений")
if not idempotency_key or not _KEY_RE.match(idempotency_key):
raise ApiError(400, "invalid_request", "Некорректный Idempotency-Key")
path = f"/api/v1/chats/{cid}/messages"
bh = _body_hash(body)
attachment_ids = _validate_attachments(db, cid, list(body.attachment_ids))
existing = db.get(IdempotencyKey, (user.id, "POST", path, idempotency_key))
if existing is not None:
if existing.body_hash != bh:
raise ApiError(409, "conflict", "Ключ уже использован с другим телом")
msg = db.get(Message, existing.message_id)
return MessageOut.model_validate(msg, from_attributes=True)
return _to_out(db, msg)
msg = Message(chat_id=cid, sender_id=user.id, text=body.text)
db.add(msg)
db.flush()
for pos, aid in enumerate(attachment_ids):
db.add(MessageAttachment(message_id=msg.id, attachment_id=aid, position=pos))
db.add(IdempotencyKey(user_id=user.id, method="POST", path=path, key=idempotency_key, body_hash=bh, message_id=msg.id))
try:
db.commit()
@@ -65,9 +113,9 @@ def create_message(
if existing.body_hash != bh:
raise ApiError(409, "conflict", "Ключ уже использован с другим телом")
msg = db.get(Message, existing.message_id)
return MessageOut.model_validate(msg, from_attributes=True)
return _to_out(db, msg)
db.refresh(msg)
return MessageOut.model_validate(msg, from_attributes=True)
return _to_out(db, msg)
@router.get("/api/v1/chats/{chat_id}/messages", response_model=MessagePage)
@@ -95,4 +143,4 @@ def list_messages(
rows = rows[:limit]
last = rows[-1]
next_cursor = _encode_cursor(last.created_at, last.id)
return MessagePage(items=[MessageOut.model_validate(m, from_attributes=True) for m in rows], next_cursor=next_cursor)
return MessagePage(items=[_to_out(db, m) for m in rows], next_cursor=next_cursor)
+150
View File
@@ -0,0 +1,150 @@
"""S3-клиент (MinIO) и потоковая валидация изображений.
Потоковая загрузка: читаем тело запроса чанками, считаем SHA-256 и размер,
не держим весь файл в памяти. MIME определяем по magic bytes, пиксели —
через Pillow с защитой от decompression bomb.
"""
import hashlib
import io
import logging
import uuid
from typing import BinaryIO
import boto3
from botocore.client import Config as BotoConfig
from botocore.exceptions import BotoCoreError, ClientError
from PIL import Image, UnidentifiedImageError
from .config import settings
from .errors import ApiError
logger = logging.getLogger("messenger.s3")
PNG_MAGIC = b"\x89PNG\r\n\x1a\n"
JPEG_MAGIC = b"\xff\xd8\xff"
def _client():
return boto3.client(
"s3",
endpoint_url=settings.s3_endpoint,
region_name=settings.s3_region,
aws_access_key_id=settings.s3_access_key_id,
aws_secret_access_key=settings.s3_secret_access_key,
use_ssl=settings.s3_use_ssl,
config=BotoConfig(signature_version="s3v4", s3={"addressing_style": "path"}),
)
def ensure_bucket() -> None:
"""Идемпотентно создаёт bucket, если его нет."""
client = _client()
try:
client.head_bucket(Bucket=settings.s3_bucket)
except ClientError as exc:
code = exc.response.get("Error", {}).get("Code", "")
if code in ("404", "NoSuchBucket", "NotFound"):
client.create_bucket(Bucket=settings.s3_bucket)
logger.info("created bucket %s", settings.s3_bucket)
else:
raise
def new_object_key(chat_id: str, attachment_id: str) -> str:
"""Случайный ключ; filename не используется как путь."""
return f"chats/{chat_id}/{attachment_id}/{uuid.uuid4().hex}"
def _detect_mime(head: bytes) -> str | None:
if head.startswith(PNG_MAGIC):
return "image/png"
if head.startswith(JPEG_MAGIC):
return "image/jpeg"
return None
def _validate_image(data: bytes, declared_mime: str) -> str:
"""Проверяет magic bytes, декодирует заголовок, считает пиксели.
Возвращает фактический MIME. Бросает ApiError(415/413).
"""
actual = _detect_mime(data[:16])
if actual is None:
raise ApiError(415, "unsupported_media_type", "Поддерживаются только PNG и JPEG")
if actual != declared_mime:
raise ApiError(415, "unsupported_media_type", "Content-Type не совпадает с содержимым")
try:
with Image.open(io.BytesIO(data)) as img:
width, height = img.size
except (UnidentifiedImageError, OSError):
raise ApiError(415, "unsupported_media_type", "Повреждённое изображение")
if width <= 0 or height <= 0:
raise ApiError(415, "unsupported_media_type", "Повреждённое изображение")
if width * height > settings.max_image_pixels:
raise ApiError(413, "payload_too_large", "Слишком много пикселей")
return actual
def read_upload(stream: BinaryIO, declared_mime: str) -> tuple[bytes, str, str]:
"""Читает поток с лимитом, возвращает (bytes, sha256, actual_mime).
Файл ≤10 MiB, поэтому держим его в памяти — это упрощает валидацию
и не создаёт неограниченного потребления RAM (лимит жёсткий).
"""
limit = settings.max_upload_bytes
buf = bytearray()
hasher = hashlib.sha256()
while True:
chunk = stream.read(settings.upload_chunk_size)
if not chunk:
break
buf.extend(chunk)
hasher.update(chunk)
if len(buf) > limit:
raise ApiError(413, "payload_too_large", "Файл больше 10 MiB")
if not buf:
raise ApiError(400, "invalid_request", "Пустое тело запроса")
data = bytes(buf)
actual = _validate_image(data, declared_mime)
return data, hasher.hexdigest(), actual
def put_object(key: str, data: bytes, content_type: str) -> None:
client = _client()
try:
client.put_object(
Bucket=settings.s3_bucket,
Key=key,
Body=data,
ContentType=content_type,
)
except (BotoCoreError, ClientError) as exc:
logger.error("s3 put failed: %s", type(exc).__name__)
raise ApiError(503, "unavailable", "Хранилище недоступно")
def get_object(key: str) -> tuple[bytes, str]:
client = _client()
try:
resp = client.get_object(Bucket=settings.s3_bucket, Key=key)
body = resp["Body"].read()
ctype = resp.get("ContentType") or "application/octet-stream"
return body, ctype
except ClientError as exc:
code = exc.response.get("Error", {}).get("Code", "")
if code in ("NoSuchKey", "404", "NotFound"):
raise ApiError(404, "not_found", "Объект не найден")
logger.error("s3 get failed: %s", type(exc).__name__)
raise ApiError(503, "unavailable", "Хранилище недоступно")
except BotoCoreError as exc:
logger.error("s3 get failed: %s", type(exc).__name__)
raise ApiError(503, "unavailable", "Хранилище недоступно")
def delete_object(key: str) -> None:
"""Best-effort удаление для компенсации при сбое между S3 и БД."""
client = _client()
try:
client.delete_object(Bucket=settings.s3_bucket, Key=key)
except (BotoCoreError, ClientError) as exc:
logger.warning("s3 delete failed: %s", type(exc).__name__)
+29 -1
View File
@@ -49,11 +49,39 @@ class MessageOut(BaseModel):
sender_id: uuid.UUID
text: str
created_at: datetime
attachment_ids: List[uuid.UUID] = Field(default_factory=list)
class CreateMessage(BaseModel):
model_config = ConfigDict(extra="forbid")
text: str = Field(min_length=1, max_length=4000)
text: str = Field(default="", max_length=4000)
attachment_ids: List[uuid.UUID] = Field(default_factory=list, max_length=10)
class VariantOut(BaseModel):
model_config = ConfigDict(extra="forbid")
name: str
content_type: str
size_bytes: int
width: int
height: int
sha256: str
class AttachmentOut(BaseModel):
model_config = ConfigDict(extra="forbid")
id: uuid.UUID
chat_id: uuid.UUID
owner_id: uuid.UUID
filename: str
content_type: str
size_bytes: int
sha256: str
status: str
variants: List[VariantOut] = Field(default_factory=list)
error_code: Optional[str] = None
created_at: datetime
updated_at: datetime
class ChatPage(BaseModel):