feat-(lab3 started, X-Instance-ID, Idempotence-Key in send_message method added)
This commit is contained in:
@@ -0,0 +1,121 @@
|
||||
import base64
|
||||
from fastapi import HTTPException, APIRouter, Query, status, Request
|
||||
from typing import Optional
|
||||
from uuid import UUID
|
||||
from src.pydantic_valid.message import Message, CreateMessage
|
||||
from src.pydantic_valid.page_response import PageResponse
|
||||
from src.api.dependencies import DbSession, CurrentUser
|
||||
from src.api.repositories.main_repo import Repository
|
||||
from src.services.idempotency import get_cached, body_hash, save_cached
|
||||
from src.utils import generate_id, get_now_iso
|
||||
from datetime import datetime
|
||||
|
||||
|
||||
router = APIRouter()
|
||||
|
||||
|
||||
def _encode_msg_cursor(chat_id: str, created_at: str, msg_id: str) -> str:
|
||||
raw = f"m|{chat_id}|{created_at}|{msg_id}"
|
||||
return base64.urlsafe_b64encode(raw.encode("utf-8")).decode("ascii").rstrip("=")
|
||||
|
||||
|
||||
def _decode_msg_cursor(scope_chat_id: str, cursor: str) -> tuple[str, str]:
|
||||
try:
|
||||
padded = cursor + "=" * (-len(cursor) % 4)
|
||||
raw = base64.urlsafe_b64decode(padded).decode("utf-8")
|
||||
parts = raw.split("|", 3)
|
||||
if len(parts) != 4 or parts[0] != "m":
|
||||
raise ValueError("bad cursor structure")
|
||||
chat_id, created_at, msg_id = parts[1], parts[2], parts[3]
|
||||
except Exception as e:
|
||||
raise HTTPException(status_code=400, detail="invalid cursor") from e
|
||||
|
||||
if scope_chat_id != chat_id:
|
||||
raise HTTPException(status_code=400, detail="cursor from another chat")
|
||||
|
||||
return created_at, msg_id
|
||||
|
||||
|
||||
@router.post("/v1/chats/{chat_id}/messages", response_model=Message, status_code=201)
|
||||
async def send_message(chat_id: UUID, msg_in: CreateMessage, session: DbSession, current_user: CurrentUser, request: Request):
|
||||
repo = Repository(session)
|
||||
|
||||
idempotency_key = request.headers.get("Idempotency-Key")
|
||||
if not idempotency_key:
|
||||
raise HTTPException(status_code=status.HTTP_400_BAD_REQUEST, detail="Idempotency-Key is required")
|
||||
|
||||
chat = await repo.chats.get_by_id_with_members(chat_id)
|
||||
if not chat:
|
||||
raise HTTPException(status_code=status.HTTP_404_NOT_FOUND, detail="chat not found")
|
||||
|
||||
if not await repo.chats.is_user_member(chat_id, current_user.id):
|
||||
raise HTTPException(status_code=status.HTTP_404_NOT_FOUND,
|
||||
detail="chat not found")
|
||||
|
||||
current_hash = body_hash(msg_in.model_dump())
|
||||
cached = await get_cached(str(current_user.id), str(chat_id), idempotency_key)
|
||||
|
||||
if cached is not None:
|
||||
if cached["body_hash"] != current_hash:
|
||||
raise HTTPException(status_code=status.HTTP_409_CONFLICT, detail="Idempotency-Key is already using with different body")
|
||||
else:
|
||||
return cached["response"]
|
||||
|
||||
message = await repo.messages.create(chat_id=chat_id,
|
||||
sender_id=current_user.id,
|
||||
text=msg_in.text)
|
||||
|
||||
response_data = Message(
|
||||
id=str(message.id),
|
||||
chat_id=str(message.chat_id),
|
||||
sender_id=str(message.sender_id),
|
||||
text=message.text,
|
||||
created_at=message.created_at.strftime("%Y-%m-%dT%H:%M:%S.%f") + "Z"
|
||||
)
|
||||
|
||||
response_dict = response_data.model_dump()
|
||||
|
||||
await save_cached(
|
||||
str(current_user.id),
|
||||
str(chat_id),
|
||||
idempotency_key,
|
||||
current_hash,
|
||||
response_dict
|
||||
)
|
||||
|
||||
return response_dict
|
||||
|
||||
|
||||
@router.get("/v1/chats/{chat_id}/messages", response_model=PageResponse, status_code=200)
|
||||
async def list_messages(session: DbSession, current_user: CurrentUser, chat_id: UUID, limit: int = Query(default=50, ge=1, le=100), cursor: Optional[str] = Query(default=None, min_length=1)):
|
||||
repo = Repository(session)
|
||||
|
||||
chat = await repo.chats.get_by_id_with_members(chat_id)
|
||||
if not chat:
|
||||
raise HTTPException(status_code=status.HTTP_404_NOT_FOUND,
|
||||
detail="chat not found")
|
||||
|
||||
member_ids = {str(m.user_id) for m in chat.members}
|
||||
|
||||
if str(current_user.id) not in member_ids:
|
||||
raise HTTPException(status_code=status.HTTP_404_NOT_FOUND,
|
||||
detail="chat not found")
|
||||
cursor_created_at = None
|
||||
cursor_msg_id = None
|
||||
if cursor:
|
||||
created_at_str, msg_id_str = _decode_msg_cursor(str(chat_id), cursor)
|
||||
cursor_created_at = datetime.fromisoformat(created_at_str)
|
||||
cursor_msg_id = UUID(msg_id_str)
|
||||
|
||||
messages, has_more = await repo.messages.get_chat_messages(chat_id=chat_id, limit=limit, cursor_created_at=cursor_created_at, cursor_msg_id=cursor_msg_id)
|
||||
|
||||
next_cursor = None
|
||||
if has_more and messages:
|
||||
last = messages[-1]
|
||||
next_cursor = _encode_msg_cursor(chat_id=str(chat_id), created_at=last.created_at.isoformat(), msg_id=str(last.id))
|
||||
|
||||
return PageResponse(
|
||||
items=[Message(id=str(msg.id), chat_id=str(msg.chat_id), sender_id=str(msg.sender_id), text=msg.text, created_at=msg.created_at.strftime("%Y-%m-%dT%H:%M:%S.%f") + "Z")
|
||||
for msg in messages],
|
||||
next_cursor=next_cursor,
|
||||
)
|
||||
Reference in New Issue
Block a user