import base64 import binascii import json import hashlib import re from datetime import datetime from uuid import UUID,uuid4 from fastapi import APIRouter,Depends,HTTPException,Query,Header from app.dependencies import current_user from app.models.messages import CreateMessage,Message,MessagePage from app.routers.chats import get_chat_row from app.storage import db router=APIRouter() MESSAGE_SELECT = """SELECT m.id,m.chat_id,m.sender_id,m.text,m.created_at, COALESCE((SELECT array_agg(ma.attachment_id ORDER BY ma.position) FROM message_attachments ma WHERE ma.message_id=m.id), ARRAY[]::uuid[]) AS attachment_ids FROM messages m""" def encode_cursor(chat_id,row): raw=json.dumps({'chat_id':str(chat_id),'created_at':row['created_at'].isoformat(),'id':str(row['id'])}).encode() return base64.urlsafe_b64encode(raw).decode().rstrip('=') def decode_cursor(chat_id,cursor): try: raw=base64.b64decode(cursor+'='*(-len(cursor)%4),altchars=b'-_',validate=True) data=json.loads(raw) ts=datetime.fromisoformat(data['created_at']) ident=UUID(data['id']) if data['chat_id']!=str(chat_id) or ts.tzinfo is None: raise ValueError('Wrong cursor') return ts,ident except (ValueError,KeyError,TypeError,UnicodeDecodeError,binascii.Error): raise HTTPException(status_code=400,detail='Invalid cursor') IDEMPOTENCY_KEY_RE = re.compile(r'^[A-Za-z0-9._:-]{1,128}$', re.ASCII) def canonical_message_hash(payload): # Canonical semantics, not raw JSON bytes or field order. data = payload.model_dump(mode='json', exclude_none=True) data.setdefault('attachment_ids', []) return hashlib.sha256(json.dumps(data, sort_keys=True, separators=(',', ':'), ensure_ascii=False).encode('utf-8')).hexdigest() def advisory_lock_id(user_id,chat_id,key): scope = f'{user_id}:{chat_id}:{key}'.encode('utf-8') return int.from_bytes(hashlib.sha256(scope).digest()[:8], 'big', signed=True) @router.post('/api/v1/chats/{chat_id}/messages',response_model=Message,status_code=201) def create_message(chat_id:UUID,payload:CreateMessage,user=Depends(current_user), idempotency_key:str|None=Header(default=None,alias='Idempotency-Key')): if idempotency_key is None or not IDEMPOTENCY_KEY_RE.fullmatch(idempotency_key): raise HTTPException(status_code=400,detail='Invalid or missing Idempotency-Key') request_hash=canonical_message_hash(payload) with db() as conn: # Explicit authorization is checked on EVERY replay, not just initial POST. if get_chat_row(conn,chat_id,user['id']) is None: raise HTTPException(status_code=404,detail='Chat not found') # Same key on different processes serializes in PostgreSQL. The message and # key record commit together, so a network timeout cannot create duplicates. conn.execute('SELECT pg_advisory_xact_lock(%s)', (advisory_lock_id(user['id'],chat_id,idempotency_key),)) saved=conn.execute("""SELECT request_hash,message_id,created_at FROM message_idempotency WHERE user_id=%s AND chat_id=%s AND idem_key=%s FOR UPDATE""", (user['id'],chat_id,idempotency_key)).fetchone() if saved is not None: # Contract promises a replay window of at least 24 hours; retaining # keys longer is safe and prevents late duplicate deliveries. if saved['request_hash'] != request_hash: raise HTTPException(status_code=409,detail='Idempotency-Key used with another body') return conn.execute(MESSAGE_SELECT + """ WHERE m.id=%s""",(saved['message_id'],)).fetchone() if payload.attachment_ids: authorized=conn.execute("""SELECT id FROM attachments WHERE chat_id=%s AND id=ANY(%s) AND status='ready' FOR SHARE""", (chat_id,payload.attachment_ids)).fetchall() if len(authorized)!=len(payload.attachment_ids): raise HTTPException(status_code=404,detail='Attachment not found') row=conn.execute("""INSERT INTO messages(id,chat_id,sender_id,text) VALUES (%s,%s,%s,%s) RETURNING id,chat_id,sender_id,text,created_at""", (uuid4(),chat_id,user['id'],payload.text)).fetchone() for pos,attachment_id in enumerate(payload.attachment_ids): conn.execute("""INSERT INTO message_attachments(message_id,attachment_id,position) VALUES (%s,%s,%s)""",(row['id'],attachment_id,pos)) row['attachment_ids']=payload.attachment_ids conn.execute("""INSERT INTO message_idempotency(user_id,chat_id,idem_key,request_hash,message_id) VALUES (%s,%s,%s,%s,%s)""", (user['id'],chat_id,idempotency_key,request_hash,row['id'])) return row @router.get('/api/v1/chats/{chat_id}/messages',response_model=MessagePage) def list_messages(chat_id:UUID,limit:int=Query(default=50,ge=1,le=100), cursor:str|None=Query(default=None,min_length=1),user=Depends(current_user)): with db() as conn: if get_chat_row(conn,chat_id,user['id']) is None: raise HTTPException(status_code=404,detail='Chat not found') if cursor is not None: ts,ident=decode_cursor(chat_id,cursor) rows=conn.execute(MESSAGE_SELECT + """ WHERE m.chat_id=%s AND (m.created_at,m.id)>(%s,%s) ORDER BY m.created_at,m.id LIMIT %s""",(chat_id,ts,ident,limit+1)).fetchall() else: rows=conn.execute(MESSAGE_SELECT + """ WHERE m.chat_id=%s ORDER BY m.created_at,m.id LIMIT %s""",(chat_id,limit+1)).fetchall() items=rows[:limit] next_cursor=encode_cursor(chat_id,items[-1]) if len(rows)>limit else None return {'items':items,'next_cursor':next_cursor}