from uuid import UUID, uuid4 import hashlib import json from sqlalchemy import text from sqlalchemy.ext.asyncio import AsyncSession from src.models import Attachment, Chat, ChatPage, CreateChat, CreateUser, User, CreateMessage, Message, MessagePage from src.security import hash_password from src.errors import APIError from src.cursor import decode_cursor, encode_cursor, decode_chat_cursor, encode_chat_cursor async def create_user( session: AsyncSession, data: CreateUser, ) -> User: user_id = uuid4() password_hash = hash_password(data.password) result = await session.execute( text( """ INSERT INTO users ( id, username, display_name, password_hash ) VALUES ( :id, :username, :display_name, :password_hash ) RETURNING id, username, display_name, created_at """ ), { "id": user_id, "username": data.username, "display_name": data.display_name, "password_hash": password_hash, }, ) row = result.one() return User( id=UUID(str(row.id)), username=row.username, display_name=row.display_name, created_at=row.created_at, ) async def get_user_credentials_by_username( session: AsyncSession, username: str, ): result = await session.execute( text( """ SELECT id, username, display_name, password_hash, created_at FROM users WHERE username = :username """ ), { "username": username, }, ) return result.one_or_none() async def get_user_by_id( session: AsyncSession, user_id: UUID, ) -> User | None: result = await session.execute( text( """ SELECT id, username, display_name, created_at FROM users WHERE id = :user_id """ ), { "user_id": user_id, }, ) row = result.one_or_none() if row is None: return None return User( id=UUID(str(row.id)), username=row.username, display_name=row.display_name, created_at=row.created_at, ) async def create_chat( session: AsyncSession, data: CreateChat, current_user_id: UUID, ) -> Chat: if current_user_id not in data.member_ids: raise APIError( status_code=400, code="invalid_request", message="Current user must be a chat member", ) users_result = await session.execute( text( """ SELECT id FROM users WHERE id = ANY(:member_ids) """ ), { "member_ids": data.member_ids, }, ) existing_user_ids = { UUID(str(row.id)) for row in users_result } if existing_user_ids != set(data.member_ids): raise APIError( status_code=400, code="invalid_request", message="Unknown chat member", ) chat_id = uuid4() chat_result = await session.execute( text( """ INSERT INTO chats ( id, title ) VALUES ( :id, :title ) RETURNING id, title, created_at """ ), { "id": chat_id, "title": data.title, }, ) chat_row = chat_result.one() for member_id in data.member_ids: await session.execute( text( """ INSERT INTO chat_members ( chat_id, user_id ) VALUES ( :chat_id, :user_id ) """ ), { "chat_id": chat_id, "user_id": member_id, }, ) return Chat( id=UUID(str(chat_row.id)), title=chat_row.title, member_ids=data.member_ids, created_at=chat_row.created_at, ) async def get_chat_by_id( session: AsyncSession, chat_id: UUID, current_user_id: UUID, ) -> Chat | None: chat_result = await session.execute( text( """ SELECT c.id, c.title, c.created_at FROM chats AS c JOIN chat_members AS cm ON cm.chat_id = c.id WHERE c.id = :chat_id AND cm.user_id = :current_user_id """ ), { "chat_id": chat_id, "current_user_id": current_user_id, }, ) chat_row = chat_result.one_or_none() if chat_row is None: return None members_result = await session.execute( text( """ SELECT user_id FROM chat_members WHERE chat_id = :chat_id ORDER BY user_id """ ), { "chat_id": chat_id, }, ) member_ids = [ UUID(str(row.user_id)) for row in members_result ] return Chat( id=UUID(str(chat_row.id)), title=chat_row.title, member_ids=member_ids, created_at=chat_row.created_at, ) async def list_chats( session: AsyncSession, current_user_id: UUID, limit: int, cursor: str | None = None, ) -> ChatPage: cursor_created_at = None cursor_chat_id = None if cursor is not None: try: cursor_user_id, cursor_created_at, cursor_chat_id = decode_chat_cursor(cursor) except ValueError as exc: raise APIError(status_code=400, code="invalid_request", message="Invalid cursor") from exc if cursor_user_id != current_user_id: raise APIError(status_code=400, code="invalid_request", message="Invalid cursor") result = await session.execute( text( """ SELECT c.id, c.title, c.created_at FROM chats AS c JOIN chat_members AS cm ON cm.chat_id = c.id WHERE cm.user_id = :current_user_id AND ( CAST(:cursor_created_at AS timestamptz) IS NULL OR (c.created_at, c.id) > ( CAST(:cursor_created_at AS timestamptz), CAST(:cursor_chat_id AS uuid) ) ) ORDER BY c.created_at, c.id LIMIT :fetch_limit """ ), { "current_user_id": current_user_id, "cursor_created_at": cursor_created_at, "cursor_chat_id": cursor_chat_id, "fetch_limit": limit + 1, }, ) rows = result.all() has_more = len(rows) > limit page_rows = rows[:limit] items = [] for chat_row in page_rows: members_result = await session.execute( text( """ SELECT user_id FROM chat_members WHERE chat_id = :chat_id ORDER BY user_id """ ), {"chat_id": chat_row.id}, ) items.append( Chat( id=UUID(str(chat_row.id)), title=chat_row.title, member_ids=[UUID(str(row.user_id)) for row in members_result], created_at=chat_row.created_at, ) ) next_cursor = None if has_more: last = page_rows[-1] next_cursor = encode_chat_cursor( current_user_id, last.created_at, UUID(str(last.id)) ) return ChatPage(items=items, next_cursor=next_cursor) async def create_message( session: AsyncSession, chat_id: UUID, current_user_id: UUID, data: CreateMessage, idempotency_key: str, ) -> Message: membership_result = await session.execute( text(""" SELECT 1 FROM chat_members WHERE chat_id = :chat_id AND user_id = :user_id """), { "chat_id": chat_id, "user_id": current_user_id, }, ) if membership_result.scalar_one_or_none() is None: raise APIError( status_code=404, code="not_found", message="Chat not found", ) canonical_body = json.dumps( { "text": data.text, "attachment_ids": [str(attachment_id) for attachment_id in data.attachment_ids], }, sort_keys=True, ensure_ascii=False, separators=(",", ":"), ) request_hash = hashlib.sha256( canonical_body.encode("utf-8") ).hexdigest() scope = ( f"{current_user_id}:POST:" f"/api/v1/chats/{chat_id}/messages:" f"{idempotency_key}" ) await session.execute( text(""" SELECT pg_advisory_xact_lock( hashtextextended(:scope, 0) ) """), {"scope": scope}, ) await session.execute( text(""" DELETE FROM message_idempotency WHERE user_id = :user_id AND chat_id = :chat_id AND key = :key AND created_at <= clock_timestamp() - INTERVAL '24 hours' """), { "user_id": current_user_id, "chat_id": chat_id, "key": idempotency_key, }, ) existing_result = await session.execute( text(""" SELECT i.request_hash, m.id, m.chat_id, m.sender_id, m.text, m.created_at FROM message_idempotency AS i JOIN messages AS m ON m.id = i.message_id WHERE i.user_id = :user_id AND i.chat_id = :chat_id AND i.key = :key """), { "user_id": current_user_id, "chat_id": chat_id, "key": idempotency_key, }, ) existing = existing_result.one_or_none() if existing is not None: if existing.request_hash != request_hash: raise APIError( status_code=409, code="conflict", message=( "Idempotency key already used " "with different request body" ), ) attachment_result = await session.execute( text(""" SELECT attachment_id FROM message_attachments WHERE message_id = :message_id ORDER BY attachment_id """), {"message_id": existing.id}, ) attachment_ids = [ UUID(str(row.attachment_id)) for row in attachment_result.all() ] return Message( id=UUID(str(existing.id)), chat_id=UUID(str(existing.chat_id)), sender_id=UUID(str(existing.sender_id)), text=existing.text, created_at=existing.created_at, attachment_ids=attachment_ids, ) if data.attachment_ids: attachments_result = await session.execute( text(""" SELECT id FROM attachments WHERE id = ANY (:attachment_ids) AND chat_id = :chat_id AND status != 'failed' """), { "attachment_ids": data.attachment_ids, "chat_id": chat_id, }, ) valid_attachment_ids = { UUID(str(row.id)) for row in attachments_result.all() } if valid_attachment_ids != set(data.attachment_ids): raise APIError( status_code=400, code="invalid_request", message="Invalid attachments for this chat", ) message_id = uuid4() message_result = await session.execute( text(""" INSERT INTO messages ( id, chat_id, sender_id, text ) VALUES ( :id, :chat_id, :sender_id, :text ) RETURNING id, chat_id, sender_id, text, created_at """), { "id": message_id, "chat_id": chat_id, "sender_id": current_user_id, "text": data.text, }, ) row = message_result.one() for attachment_id in data.attachment_ids: await session.execute( text(""" INSERT INTO message_attachments (message_id, attachment_id) VALUES (:message_id, :attachment_id) """), { "message_id": message_id, "attachment_id": attachment_id, }, ) await session.execute( text(""" INSERT INTO message_idempotency ( user_id, chat_id, key, request_hash, message_id ) VALUES ( :user_id, :chat_id, :key, :request_hash, :message_id ) """), { "user_id": current_user_id, "chat_id": chat_id, "key": idempotency_key, "request_hash": request_hash, "message_id": message_id, }, ) return Message( id=UUID(str(row.id)), chat_id=UUID(str(row.chat_id)), sender_id=UUID(str(row.sender_id)), text=row.text, created_at=row.created_at, attachment_ids=data.attachment_ids, ) async def get_messages( session: AsyncSession, chat_id: UUID, current_user_id: UUID, limit: int, cursor: str | None, ) -> MessagePage: membership_result = await session.execute( text( """ SELECT 1 FROM chat_members WHERE chat_id = :chat_id AND user_id = :current_user_id """ ), { "chat_id": chat_id, "current_user_id": current_user_id, }, ) if membership_result.scalar_one_or_none() is None: raise APIError( status_code=404, code="not_found", message="Chat not found", ) cursor_created_at = None cursor_message_id = None if cursor is not None: try: ( cursor_chat_id, cursor_created_at, cursor_message_id, ) = decode_cursor(cursor) except ValueError: raise APIError( status_code=400, code="invalid_request", message="Invalid cursor", ) if cursor_chat_id != chat_id: raise APIError( status_code=400, code="invalid_request", message="Cursor belongs to another chat", ) if cursor is None: messages_result = await session.execute( text( """ SELECT id, chat_id, sender_id, text, created_at FROM messages WHERE chat_id = :chat_id ORDER BY created_at, id LIMIT :fetch_limit """ ), { "chat_id": chat_id, "fetch_limit": limit + 1, }, ) else: messages_result = await session.execute( text( """ SELECT id, chat_id, sender_id, text, created_at FROM messages WHERE chat_id = :chat_id AND (created_at, id) > ( :cursor_created_at, :cursor_message_id ) ORDER BY created_at, id LIMIT :fetch_limit """ ), { "chat_id": chat_id, "cursor_created_at": cursor_created_at, "cursor_message_id": cursor_message_id, "fetch_limit": limit + 1, }, ) rows = messages_result.all() has_more = len(rows) > limit rows = rows[:limit] attachments_by_message = {} if rows: attachment_result = await session.execute( text(""" SELECT message_id, attachment_id FROM message_attachments WHERE message_id = ANY(:message_ids) ORDER BY message_id, attachment_id """), { "message_ids": [row.id for row in rows], }, ) for attachment_row in attachment_result.all(): message_id = UUID(str(attachment_row.message_id)) attachment_id = UUID(str(attachment_row.attachment_id)) attachments_by_message.setdefault( message_id, [] ).append(attachment_id) items = [ Message( id=UUID(str(row.id)), chat_id=UUID(str(row.chat_id)), sender_id=UUID(str(row.sender_id)), text=row.text, created_at=row.created_at, attachment_ids=attachments_by_message.get( UUID(str(row.id)), [] ), ) for row in rows ] next_cursor = None if has_more: last_message = items[-1] next_cursor = encode_cursor( chat_id=chat_id, created_at=last_message.created_at, message_id=last_message.id, ) return MessagePage( items=items, next_cursor=next_cursor, ) def attachment_from_row(row) -> Attachment: return Attachment( id=UUID(str(row.id)), chat_id=UUID(str(row.chat_id)), owner_id=UUID(str(row.owner_id)), filename=row.filename, content_type=row.content_type, size_bytes=row.size_bytes, sha256=row.sha256, status=row.status, variants=row.variants, error_code=row.error_code, created_at=row.created_at, updated_at=row.updated_at, ) async def create_attachment( session: AsyncSession, attachment_id: UUID, chat_id: UUID, owner_id: UUID, filename: str, content_type: str, size_bytes: int, sha256: str, s3_key: str, ) -> Attachment: result = await session.execute( text( """ INSERT INTO attachments ( id, chat_id, owner_id, filename, content_type, size_bytes, sha256, s3_key, status ) VALUES ( :id, :chat_id, :owner_id, :filename, :content_type, :size_bytes, :sha256, :s3_key, 'queued' ) RETURNING id, chat_id, owner_id, filename, content_type, size_bytes, sha256, status, variants, error_code, created_at, updated_at """ ), { "id": attachment_id, "chat_id": chat_id, "owner_id": owner_id, "filename": filename, "content_type": content_type, "size_bytes": size_bytes, "sha256": sha256, "s3_key": s3_key, }, ) return attachment_from_row(result.one()) async def get_attachment( session: AsyncSession, attachment_id: UUID, current_user_id: UUID, ): result = await session.execute( text( """ SELECT a.id, a.chat_id, a.owner_id, a.filename, a.content_type, a.size_bytes, a.sha256, a.s3_key, a.status, a.variants, a.error_code, a.created_at, a.updated_at FROM attachments AS a JOIN chat_members AS cm ON cm.chat_id = a.chat_id WHERE a.id = :attachment_id AND cm.user_id = :current_user_id """ ), { "attachment_id": attachment_id, "current_user_id": current_user_id, }, ) row = result.one_or_none() if row is None: return None return attachment_from_row(row), row.s3_key async def attachment_key_exists(session: AsyncSession, s3_key: str) -> bool: result = await session.execute( text("SELECT 1 FROM attachments WHERE s3_key = :s3_key"), {"s3_key": s3_key}, ) return result.first() is not None