Files
mtusi2026lab7/src/messenger/routers/messages.py
T
2026-11-27 16:42:18 +03:00

74 lines
3.4 KiB
Python

"""Отправка и чтение истории сообщений."""
from __future__ import annotations
from typing import Annotated
from uuid import UUID
from fastapi import APIRouter, Header, Path, Query, status
from ..access import visible_chat
from ..cursor import KIND_MESSAGES
from ..deps import CursorsDep, CurrentUser, RepositoryDep
from ..domain import AttachmentNotReady, AttachmentUnknown, IdempotencyConflict
from ..errors import conflict, not_found
from ..idempotency import message_request_hash, require_idempotency_key
from ..models import DEFAULT_LIMIT, MAX_LIMIT, CreateMessage, Message, MessagePage
from ..pagination import build_next_cursor, decoded_cursor
router = APIRouter(prefix="/api/v1/chats/{chat_id}/messages", tags=["messages"])
@router.post("", status_code=status.HTTP_201_CREATED, summary="Отправить сообщение")
async def create_message(
chat_id: Annotated[UUID, Path()],
payload: CreateMessage,
repository: RepositoryDep,
user: CurrentUser,
idempotency_key: Annotated[str | None, Header(alias="Idempotency-Key")] = None,
) -> Message:
"""Отправитель выводится из идентификации; sender_id в теле не принимается.
Порядок проверок контракта: аутентификация (зависимость user), доступ к
чату (404 для чужого), затем ключ идемпотентности. Повтор с тем же ключом
и телом возвращает то же сообщение и тот же код 201.
"""
await visible_chat(repository, chat_id, user)
try:
await repository.validate_message_attachments(chat_id, payload.attachment_ids)
except AttachmentUnknown:
# Чужое и несуществующее вложение неотличимы от отсутствующего (404).
raise not_found("Вложение не найдено") from None
except AttachmentNotReady:
raise conflict("Вложение ещё не готово") from None
key = require_idempotency_key(idempotency_key)
try:
record = await repository.append_message_idempotent(
chat_id,
user.id,
payload.text,
payload.attachment_ids,
key,
message_request_hash(payload.text, payload.attachment_ids),
)
except IdempotencyConflict:
raise conflict("Idempotency-Key уже использован с другим телом запроса") from None
return Message.from_record(record)
@router.get("", summary="Сообщения по (created_at, id) по возрастанию")
async def list_messages(
chat_id: Annotated[UUID, Path()],
repository: RepositoryDep,
cursors: CursorsDep,
user: CurrentUser,
limit: Annotated[int, Query(ge=1, le=MAX_LIMIT)] = DEFAULT_LIMIT,
cursor: Annotated[str | None, Query(min_length=1)] = None,
) -> MessagePage:
"""Keyset-пагинация: страница читается по индексу, предыдущие не повторяются."""
await visible_chat(repository, chat_id, user)
scope = str(chat_id)
after = decoded_cursor(cursors, cursor, kind=KIND_MESSAGES, scope=scope)
records, has_more = await repository.list_messages(chat_id, after, limit)
return MessagePage.from_records(
records, build_next_cursor(cursors, KIND_MESSAGES, scope, records, has_more)
)