import uuid import json import base64 import re from datetime import timezone, datetime from typing import Optional from fastapi import APIRouter, status, Request from ..utils import authenticate_user, validate_uuid, get_utc_now, format_iso from ..exceptions import ApiException from ..models import SendMessageRequest from ..db import get_pool router = APIRouter(tags=["messages"]) @router.post("/chats/{chat_id}/messages", status_code=status.HTTP_201_CREATED) @router.post("/chats/{chat_id}/messages", status_code=status.HTTP_201_CREATED) async def send_message(chat_id: str, body: SendMessageRequest, request: Request): caller_id = await authenticate_user(request) validate_uuid(chat_id) pool = get_pool() is_member = await pool.fetchval( "SELECT 1 FROM chat_members WHERE chat_id = $1 AND user_id = $2", uuid.UUID(chat_id), uuid.UUID(caller_id) ) if not is_member: raise ApiException(404, "not_found", "Chat not found") if not body.text.strip() or len(body.text) > 4000: raise ApiException(400, "invalid_request", "Invalid text") key = request.headers.get("Idempotency-Key") if not key or not re.fullmatch(r"[A-Za-z0-9._:-]{1,128}", key): raise ApiException(400, "invalid_request", "Invalid Idempotency-Key") async with pool.acquire() as conn: async with conn.transaction(): row = await conn.fetchrow( """ INSERT INTO messages (id, chat_id, sender_id, text, created_at, idempotency_key) VALUES ($1, $2, $3, $4, $5, $6) ON CONFLICT (sender_id, chat_id, idempotency_key) DO NOTHING RETURNING id, chat_id, sender_id, text, created_at """, uuid.uuid4(), uuid.UUID(chat_id), uuid.UUID(caller_id), body.text, get_utc_now(), key ) if row is None: row = await conn.fetchrow( """ SELECT id, chat_id, sender_id, text, created_at FROM messages WHERE sender_id = $1 AND chat_id = $2 AND idempotency_key = $3 """, uuid.UUID(caller_id), uuid.UUID(chat_id), key ) if row["text"] != body.text: raise ApiException( 409, "conflict", "Idempotency key conflict" ) return { "id": str(row["id"]), "chat_id": str(row["chat_id"]), "sender_id": str(row["sender_id"]), "text": row["text"], "created_at": format_iso(row["created_at"]) } @router.get("/chats/{chat_id}/messages") async def get_messages( chat_id: str, request: Request, limit: int = 50, cursor: Optional[str] = None ): caller_id = await authenticate_user(request) validate_uuid(chat_id) pool = get_pool() chat_uuid = uuid.UUID(chat_id) is_member = await pool.fetchval( "SELECT 1 FROM chat_members WHERE chat_id = $1 AND user_id = $2", chat_uuid, uuid.UUID(caller_id) ) if not is_member: raise ApiException(404, "not_found", "Chat not found") if limit < 1 or limit > 100: raise ApiException(400, "invalid_request", "Invalid limit") cursor_time = None cursor_id = None if cursor is not None: try: decoded = base64.urlsafe_b64decode( cursor + "=" * (-len(cursor) % 4) ) data = json.loads(decoded) cursor_time = datetime.fromisoformat( data["created_at"].replace("Z", "+00:00") ) cursor_id = uuid.UUID(data["id"]) if cursor_time.tzinfo is None: raise ValueError() cursor_time = cursor_time.astimezone(timezone.utc) except (ValueError, KeyError, TypeError, UnicodeDecodeError): raise ApiException( 400, "invalid_request", "Invalid cursor" ) rows = await pool.fetch( """ SELECT id, chat_id, sender_id, text, created_at FROM messages WHERE chat_id = $1 AND ( $2::timestamptz IS NULL OR (created_at, id) > ($2::timestamptz, $3::uuid) ) ORDER BY created_at ASC, id ASC LIMIT $4 """, chat_uuid, cursor_time, cursor_id, limit + 1 ) has_more = len(rows) > limit rows = rows[:limit] items = [ { "id": str(row["id"]), "chat_id": str(row["chat_id"]), "sender_id": str(row["sender_id"]), "text": row["text"], "created_at": format_iso(row["created_at"]) } for row in rows ] next_cursor = None if has_more and rows: last = rows[-1] cursor_data = { "created_at": format_iso(last["created_at"]), "id": str(last["id"]) } next_cursor = base64.urlsafe_b64encode( json.dumps(cursor_data).encode("utf-8") ).decode("ascii").rstrip("=") return { "items": items, "next_cursor": next_cursor }