import base64 import hashlib import json from datetime import datetime from uuid import UUID from fastapi import APIRouter, Depends, Header, HTTPException, Query from ..models.schemas import CreateMessage, Message, MessagePage, User from ..storage.postgres import storage from .security import current_user router = APIRouter(prefix="/api/v1/chats", tags=["messages"]) # Контракт: Idempotency-Key ASCII [A-Za-z0-9._:-]{1,128}. _IDEMPOTENCY_ALLOWED = set("ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789._:-") def _require_member(chat_id: UUID, user_id: UUID): chat = storage.get_chat(chat_id) if chat is None or user_id not in chat.member_ids: raise HTTPException(status_code=404, detail="not_found") return chat def _encode_cursor(chat_id: UUID, message: Message) -> str: data = {"chat_id": str(chat_id), "id": str(message.id), "created_at": message.created_at.isoformat()} return base64.urlsafe_b64encode(json.dumps(data).encode()).decode() def _decode_cursor(chat_id: UUID, cursor: str) -> tuple: try: data = json.loads(base64.urlsafe_b64decode(cursor.encode()).decode()) if data.get("chat_id") != str(chat_id): raise ValueError("cursor_chat_mismatch") return datetime.fromisoformat(data["created_at"]), UUID(data["id"]) except Exception: raise HTTPException(status_code=400, detail="invalid_request") def _canonical_body_hash(payload: CreateMessage) -> str: """sha256 канонизированного JSON. Поле attachment_ids присутствует в модели со значением по умолчанию [], поэтому payload {"text":"x"} и {"text":"x","attachment_ids":[]} дают одинаковый model_dump и одинаковый хэш — как требует контракт. """ data = payload.model_dump() canonical = json.dumps(data, sort_keys=True, ensure_ascii=False, separators=(",", ":")) return hashlib.sha256(canonical.encode("utf-8")).hexdigest() @router.post( path="/{chat_id}/messages", summary="Отправить сообщение в чат", response_model=Message, status_code=201, ) def create_message( chat_id: UUID, payload: CreateMessage, user: User = Depends(current_user), idempotency_key: str = Header(..., alias="Idempotency-Key"), ) -> Message: # Строго ASCII, как требует контракт: isalnum() пропускает кириллицу. if not (1 <= len(idempotency_key) <= 128): raise HTTPException(status_code=400, detail="invalid_request") if not all(c in _IDEMPOTENCY_ALLOWED for c in idempotency_key): raise HTTPException(status_code=400, detail="invalid_request") _require_member(chat_id, user.id) method = "POST" path = "/api/v1/chats/%s/messages" % chat_id body_hash = _canonical_body_hash(payload) # Атомарная операция: INSERT ключа + INSERT сообщения + UPDATE ключа # в ОДНОЙ транзакции. Сбой между ними невозможен: либо всё, либо ничего. state, message, info = storage.add_message_idempotent( chat_id=chat_id, sender_id=user.id, text=payload.text, user_id=user.id, method=method, path=path, key=idempotency_key, body_hash=body_hash, ) if state == "created": return message if state == "retry": raise HTTPException(status_code=503, detail="unavailable") # state == "replay" if info["body_hash"] != body_hash: raise HTTPException(status_code=409, detail="conflict") if info["response_status"] == 0: # Строка от старой версии кода: не зависаем, отдаём 503. raise HTTPException(status_code=503, detail="unavailable") return Message.model_validate(info["response_body"]) @router.get( path="/{chat_id}/messages", summary="Получить историю сообщений чата", response_model=MessagePage, ) def list_messages( chat_id: UUID, user: User = Depends(current_user), limit: int = Query(50, ge=1, le=100), cursor: str | None = None, ) -> MessagePage: """Keyset-пагинация в SQL: (created_at, id) по возрастанию""" _require_member(chat_id, user.id) after = _decode_cursor(chat_id, cursor) if cursor else None rows = storage.list_messages_page(chat_id, limit + 1, after=after) has_more = len(rows) > limit items = rows[:limit] next_cursor = _encode_cursor(chat_id, items[-1]) if has_more and items else None return MessagePage(items=items, next_cursor=next_cursor)