Перенести исходную базу лабораторной 4 для контракта лабораторной 5
This commit is contained in:
@@ -0,0 +1,85 @@
|
||||
from uuid import UUID
|
||||
import re
|
||||
import os
|
||||
|
||||
from fastapi import APIRouter, Depends, HTTPException, Request
|
||||
|
||||
from src.models import CreateMessage, Message, MessagePage
|
||||
from src.routes.common import get_request_id, make_error, require_user
|
||||
from src.storage import NotFoundError, ConflictError, LimitExceeded, ValidationError, storage
|
||||
|
||||
router = APIRouter()
|
||||
|
||||
|
||||
@router.post("/api/v1/chats/{chat_id}/messages", response_model=Message, status_code=201)
|
||||
def create_message(
|
||||
request: Request,
|
||||
chat_id: UUID,
|
||||
body: CreateMessage,
|
||||
x_user_id: str = Depends(require_user),
|
||||
):
|
||||
"""Отправить сообщение от владельца Bearer-сессии с общей защитой повторов."""
|
||||
request_id = get_request_id(request)
|
||||
|
||||
chat_id_str = str(chat_id)
|
||||
if os.getenv('OPTIMIZED_WRITES','1') == '1':
|
||||
allowed = storage.is_chat_member(chat_id_str, x_user_id)
|
||||
else:
|
||||
chat = storage.get_chat(chat_id_str)
|
||||
allowed = bool(chat and x_user_id in chat.member_ids)
|
||||
if not allowed:
|
||||
raise HTTPException(
|
||||
status_code=404,
|
||||
detail=make_error("not_found", "чат не найден", request_id).model_dump(),
|
||||
)
|
||||
|
||||
try:
|
||||
key = request.headers.get('Idempotency-Key', '')
|
||||
if not re.fullmatch(r'[A-Za-z0-9._:-]{1,128}', key):
|
||||
raise HTTPException(400, detail=make_error('invalid_request', 'неверный Idempotency-Key', request_id).model_dump())
|
||||
msg = storage.create_message(chat_id_str, x_user_id, body.text, key, body.attachment_ids)
|
||||
return msg
|
||||
except NotFoundError as e:
|
||||
raise HTTPException(404, detail=make_error('not_found', str(e), request_id).model_dump())
|
||||
except ConflictError as e:
|
||||
raise HTTPException(409, detail=make_error('conflict', str(e), request_id).model_dump())
|
||||
except LimitExceeded as e:
|
||||
raise HTTPException(
|
||||
status_code=429,
|
||||
detail=make_error("rate_limited", str(e), request_id).model_dump(),
|
||||
)
|
||||
|
||||
|
||||
@router.get("/api/v1/chats/{chat_id}/messages", response_model=MessagePage)
|
||||
def list_messages(
|
||||
request: Request,
|
||||
chat_id: UUID,
|
||||
x_user_id: str = Depends(require_user),
|
||||
limit: int = 50,
|
||||
cursor: str | None = None,
|
||||
):
|
||||
"""История сообщений чата с курсорной пагинацией. Доступно только участникам."""
|
||||
request_id = get_request_id(request)
|
||||
|
||||
chat_id_str = str(chat_id)
|
||||
chat = storage.get_chat(chat_id_str)
|
||||
if not chat or x_user_id not in chat.member_ids:
|
||||
raise HTTPException(
|
||||
status_code=404,
|
||||
detail=make_error("not_found", "чат не найден", request_id).model_dump(),
|
||||
)
|
||||
|
||||
if limit < 1 or limit > 100:
|
||||
raise HTTPException(
|
||||
status_code=400,
|
||||
detail=make_error("invalid_request", "limit должен быть от 1 до 100", request_id).model_dump(),
|
||||
)
|
||||
|
||||
try:
|
||||
items, next_cursor = storage.list_messages(chat_id_str, cursor, limit)
|
||||
return MessagePage(items=items, next_cursor=next_cursor)
|
||||
except ValidationError as e:
|
||||
raise HTTPException(
|
||||
status_code=400,
|
||||
detail=make_error("invalid_request", str(e), request_id).model_dump(),
|
||||
)
|
||||
Reference in New Issue
Block a user