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
+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)