Files
mtusi2026lab3/app/routers/messages.py
T

99 lines
3.8 KiB
Python

import hashlib
import json
import re
import uuid
from datetime import datetime, timedelta, timezone
from fastapi import APIRouter, Depends, Header, Query, Request, Security
from sqlalchemy import select
from sqlalchemy.exc import IntegrityError
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 ..schemas import CreateMessage, MessageOut, MessagePage
from .chats import _decode_cursor, _encode_cursor, _require_member
router = APIRouter()
_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)
return hashlib.sha256(canonical.encode("utf-8")).hexdigest()
@router.post("/api/v1/chats/{chat_id}/messages", response_model=MessageOut, status_code=201)
def create_message(
chat_id: str,
body: CreateMessage,
request: Request,
idempotency_key: str | None = Header(default=None, alias="Idempotency-Key"),
user: User = Security(current_user),
db: Session = Depends(get_db),
):
cid = parse_uuid(chat_id)
_require_member(db, cid, user.id)
if not body.text.strip():
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)
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)
msg = Message(chat_id=cid, sender_id=user.id, text=body.text)
db.add(msg)
db.flush()
db.add(IdempotencyKey(user_id=user.id, method="POST", path=path, key=idempotency_key, body_hash=bh, message_id=msg.id))
try:
db.commit()
except IntegrityError:
db.rollback()
existing = db.get(IdempotencyKey, (user.id, "POST", path, idempotency_key))
if existing is None:
raise ApiError(500, "internal_error", "Не удалось сохранить сообщение")
if existing.body_hash != bh:
raise ApiError(409, "conflict", "Ключ уже использован с другим телом")
msg = db.get(Message, existing.message_id)
return MessageOut.model_validate(msg, from_attributes=True)
db.refresh(msg)
return MessageOut.model_validate(msg, from_attributes=True)
@router.get("/api/v1/chats/{chat_id}/messages", response_model=MessagePage)
def list_messages(
chat_id: str,
limit: int = Query(50, ge=1, le=100),
cursor: str | None = Query(None),
user: User = Security(current_user),
db: Session = Depends(get_db),
):
cid = parse_uuid(chat_id)
_require_member(db, cid, user.id)
stmt = (
select(Message)
.where(Message.chat_id == cid)
.order_by(Message.created_at.asc(), Message.id.asc())
.limit(limit + 1)
)
if cursor:
t, i = _decode_cursor(cursor)
stmt = stmt.where((Message.created_at > t) | ((Message.created_at == t) & (Message.id > i)))
rows = list(db.scalars(stmt))
next_cursor = None
if len(rows) > limit:
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)