"""PostgreSQL repository functions for MTUSI Messenger Lab3.""" from __future__ import annotations from collections.abc import Iterable from datetime import datetime from typing import Any from uuid import UUID, uuid4 from sqlalchemy import text from sqlalchemy.exc import IntegrityError from sqlalchemy.ext.asyncio import AsyncSession async def create_user( db: AsyncSession, *, username: str, display_name: str, password_hash: str, ) -> dict[str, Any] | None: user_id = uuid4() try: result = await db.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": username, "display_name": display_name, "password_hash": password_hash, }, ) await db.commit() return dict(result.mappings().one()) except IntegrityError: await db.rollback() return None async def get_user_by_username( db: AsyncSession, username: str, ) -> dict[str, Any] | None: result = await db.execute( text( """ SELECT id, username, display_name, password_hash, created_at FROM users WHERE username = :username """ ), {"username": username}, ) row = result.mappings().first() return dict(row) if row is not None else None async def get_user_by_id( db: AsyncSession, user_id: UUID, ) -> dict[str, Any] | None: result = await db.execute( text( """ SELECT id, username, display_name, created_at FROM users WHERE id = :user_id """ ), {"user_id": user_id}, ) row = result.mappings().first() return dict(row) if row is not None else None async def user_ids_that_exist( db: AsyncSession, member_ids: Iterable[UUID], ) -> set[UUID]: values = list(member_ids) if not values: return set() result = await db.execute( text("SELECT id FROM users WHERE id = ANY(CAST(:member_ids AS uuid[]))"), {"member_ids": values}, ) return {row.id for row in result} async def create_session( db: AsyncSession, *, user_id: UUID, token_hash: str, expires_at: datetime, ) -> None: await db.execute( text( """ INSERT INTO sessions (id, user_id, token_hash, expires_at) VALUES (:id, :user_id, :token_hash, :expires_at) """ ), { "id": uuid4(), "user_id": user_id, "token_hash": token_hash, "expires_at": expires_at, }, ) await db.commit() async def get_active_session_user( db: AsyncSession, token_hash: str, ) -> dict[str, Any] | None: result = await db.execute( text( """ SELECT s.id AS session_id, s.token_hash, s.expires_at, u.id, u.username, u.display_name, u.created_at FROM sessions AS s JOIN users AS u ON u.id = s.user_id WHERE s.token_hash = :token_hash AND s.revoked_at IS NULL AND s.expires_at > now() """ ), {"token_hash": token_hash}, ) row = result.mappings().first() return dict(row) if row is not None else None async def revoke_active_session( db: AsyncSession, token_hash: str, ) -> bool: result = await db.execute( text( """ UPDATE sessions SET revoked_at = now() WHERE token_hash = :token_hash AND revoked_at IS NULL AND expires_at > now() """ ), {"token_hash": token_hash}, ) await db.commit() return result.rowcount == 1 async def create_chat_with_members( db: AsyncSession, *, title: str, member_ids: Iterable[UUID], ) -> dict[str, Any]: chat_id = uuid4() members = list(member_ids) try: result = await db.execute( text( """ INSERT INTO chats (id, title) VALUES (:id, :title) RETURNING id, title, created_at """ ), {"id": chat_id, "title": title}, ) chat = dict(result.mappings().one()) await db.execute( text( """ INSERT INTO chat_members (chat_id, user_id) VALUES (:chat_id, :user_id) """ ), [{"chat_id": chat_id, "user_id": user_id} for user_id in members], ) await db.commit() except Exception: await db.rollback() raise chat["member_ids"] = members return chat async def get_accessible_chat( db: AsyncSession, *, chat_id: UUID, user_id: UUID, ) -> dict[str, Any] | None: result = await db.execute( text( """ SELECT c.id, c.title, c.created_at FROM chats AS c JOIN chat_members AS own_membership ON own_membership.chat_id = c.id AND own_membership.user_id = :user_id WHERE c.id = :chat_id """ ), {"chat_id": chat_id, "user_id": user_id}, ) chat_row = result.mappings().first() if chat_row is None: return None members_result = await db.execute( text( """ SELECT user_id FROM chat_members WHERE chat_id = :chat_id ORDER BY user_id ASC """ ), {"chat_id": chat_id}, ) chat = dict(chat_row) chat["member_ids"] = [row.user_id for row in members_result] return chat async def list_chats_for_user( db: AsyncSession, *, user_id: UUID, limit: int, cursor_created_at: datetime | None, cursor_id: UUID | None, ) -> list[dict[str, Any]]: query = """ SELECT c.id, c.title, c.created_at FROM chats AS c JOIN chat_members AS own_membership ON own_membership.chat_id = c.id AND own_membership.user_id = :user_id \ """ params: dict[str, Any] = { "user_id": user_id, "limit_plus_one": limit + 1, } if cursor_created_at is not None and cursor_id is not None: query += """ WHERE (c.created_at, c.id) > (:cursor_created_at, :cursor_id) """ params["cursor_created_at"] = cursor_created_at params["cursor_id"] = cursor_id query += " ORDER BY c.created_at ASC, c.id ASC LIMIT :limit_plus_one" result = await db.execute(text(query), params) chats = [dict(row) for row in result.mappings().all()] if not chats: return [] chat_ids = [chat["id"] for chat in chats] members_result = await db.execute( text( """ SELECT chat_id, user_id FROM chat_members WHERE chat_id = ANY(CAST(:chat_ids AS uuid[])) ORDER BY chat_id ASC, user_id ASC """ ), {"chat_ids": chat_ids}, ) members_by_chat: dict[UUID, list[UUID]] = {chat_id: [] for chat_id in chat_ids} for row in members_result: members_by_chat[row.chat_id].append(row.user_id) for chat in chats: chat["member_ids"] = members_by_chat[chat["id"]] return chats async def create_message_idempotent( db: AsyncSession, *, chat_id: UUID, sender_id: UUID, text_value: str, idempotency_key: str, request_hash: str, ttl_seconds: int, ) -> tuple[dict[str, Any], bool] | None: """Insert a message at most once per idempotency key; one transaction. 1. INSERT the key row. Its primary key (user, chat, method, key) lives in the shared PostgreSQL, so a concurrent request with the same key on ANY replica blocks on this INSERT until the first transaction ends. 2. If the key was claimed: INSERT the message, link it to the key and COMMIT both together. A failure before COMMIT rolls back both, so a transient error is never stored as the final answer and a retry with the same key simply runs again. 3. If the key already exists (committed by someone else): return the stored message, or None when the body differs (-> 409). A key older than ttl_seconds is reclaimed by the ON CONFLICT ... WHERE. Returns (message, replayed) or None on a body mismatch. """ key_params = { "user_id": sender_id, "chat_id": chat_id, "key": idempotency_key, } try: claimed = await db.execute( text( """ INSERT INTO idempotency_keys AS k (user_id, chat_id, method, key, request_hash) VALUES (:user_id, :chat_id, 'POST', :key, :request_hash) ON CONFLICT (user_id, chat_id, method, key) DO UPDATE SET request_hash = EXCLUDED.request_hash, message_id = NULL, created_at = now() WHERE k.created_at < now() - make_interval(secs => :ttl) RETURNING 1 """ ), {**key_params, "request_hash": request_hash, "ttl": ttl_seconds}, ) if claimed.first() is not None: result = await db.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": uuid4(), "chat_id": chat_id, "sender_id": sender_id, "text": text_value, }, ) message = dict(result.mappings().one()) await db.execute( text( """ UPDATE idempotency_keys SET message_id = :message_id WHERE user_id = :user_id AND chat_id = :chat_id AND method = 'POST' AND key = :key """ ), {**key_params, "message_id": message["id"]}, ) await db.commit() return message, False stored = await db.execute( text( """ SELECT k.request_hash, m.id, m.chat_id, m.sender_id, m.text, m.created_at FROM idempotency_keys AS k JOIN messages AS m ON m.id = k.message_id WHERE k.user_id = :user_id AND k.chat_id = :chat_id AND k.method = 'POST' AND k.key = :key """ ), key_params, ) row = stored.mappings().first() await db.commit() except Exception: await db.rollback() raise if row is None: # Not reachable while the key row and the message commit together. raise RuntimeError("idempotency key without a message") message = dict(row) if message.pop("request_hash") != request_hash: return None return message, True async def list_messages_keyset( db: AsyncSession, *, chat_id: UUID, limit: int, cursor_created_at: datetime | None, cursor_id: UUID | None, ) -> list[dict[str, Any]]: query = """ SELECT id, chat_id, sender_id, text, created_at FROM messages WHERE chat_id = :chat_id \ """ params: dict[str, Any] = { "chat_id": chat_id, "limit_plus_one": limit + 1, } if cursor_created_at is not None and cursor_id is not None: query += """ AND (created_at, id) > (:cursor_created_at, :cursor_id) """ params["cursor_created_at"] = cursor_created_at params["cursor_id"] = cursor_id query += " ORDER BY created_at ASC, id ASC LIMIT :limit_plus_one" result = await db.execute(text(query), params) return [dict(row) for row in result.mappings().all()]