"""PostgreSQL repository: parameterised statements only, explicit transactions.""" from __future__ import annotations import uuid from datetime import datetime from typing import Any import psycopg from psycopg import AsyncCursor from .errors import ApiProblem from .pagination import format_timestamp # One expression keeps the member list of a chat consistent across endpoints. CHAT_COLUMNS = """ c.id, c.title, c.created_at, ARRAY( SELECT m.user_id::text FROM chat_members m WHERE m.chat_id = c.id ORDER BY m.user_id::text ) AS member_ids """ def user_json(row: dict[str, Any]) -> dict[str, Any]: return { "id": str(row["id"]), "username": row["username"], "display_name": row["display_name"], "created_at": format_timestamp(row["created_at"]), } def chat_json(row: dict[str, Any]) -> dict[str, Any]: return { "id": str(row["id"]), "title": row["title"], "member_ids": [str(member) for member in row["member_ids"]], "created_at": format_timestamp(row["created_at"]), } def message_json(row: dict[str, Any]) -> dict[str, Any]: return { "id": str(row["id"]), "chat_id": str(row["chat_id"]), "sender_id": str(row["sender_id"]), "text": row["text"], "created_at": format_timestamp(row["created_at"]), } async def create_user( cursor: AsyncCursor, *, username: str, display_name: str, password_hash: str, ) -> dict[str, Any]: try: await cursor.execute( """ INSERT INTO users (id, username, display_name, password_hash, created_at) VALUES (%s, %s, %s, %s, now()) RETURNING id, username, display_name, created_at """, (uuid.uuid4(), username, display_name, password_hash), ) except psycopg.errors.UniqueViolation: raise ApiProblem(409, "conflict", "Username is already taken") from None row = await cursor.fetchone() return user_json(row) async def user_credentials(cursor: AsyncCursor, username: str) -> dict[str, Any] | None: await cursor.execute( """ SELECT id, username, display_name, password_hash, created_at FROM users WHERE username = %s """, (username,), ) return await cursor.fetchone() async def user_by_id(cursor: AsyncCursor, user_id: uuid.UUID) -> dict[str, Any] | None: await cursor.execute( """ SELECT id, username, display_name, created_at FROM users WHERE id = %s """, (user_id,), ) return await cursor.fetchone() async def create_chat( cursor: AsyncCursor, *, actor_id: uuid.UUID, title: str, member_ids: list[uuid.UUID], ) -> dict[str, Any]: """Insert the chat and its membership in one transaction. Unknown members are rejected by the foreign key, so the failure rolls the already inserted chat row back instead of leaving a chat without members. """ if actor_id not in member_ids: raise ApiProblem(400, "invalid_request", "Current user must be a chat member") chat_id = uuid.uuid4() try: await cursor.execute( "INSERT INTO chats (id, title, created_at) VALUES (%s, %s, now())", (chat_id, title), ) await cursor.execute( """ INSERT INTO chat_members (chat_id, user_id, joined_at) SELECT %s, member_id, now() FROM unnest(%s::uuid[]) AS member_id """, (chat_id, member_ids), ) except psycopg.errors.ForeignKeyViolation: raise ApiProblem( 400, "invalid_request", "One or more members do not exist" ) from None except psycopg.errors.UniqueViolation: raise ApiProblem(400, "invalid_request", "Chat members must be unique") from None await cursor.execute( "SELECT " + CHAT_COLUMNS + " FROM chats c WHERE c.id = %s", (chat_id,), ) row = await cursor.fetchone() return chat_json(row) async def accessible_chat( cursor: AsyncCursor, *, actor_id: uuid.UUID, chat_id: uuid.UUID ) -> dict[str, Any]: await cursor.execute( """ SELECT """ + CHAT_COLUMNS + """ FROM chats c JOIN chat_members membership ON membership.chat_id = c.id AND membership.user_id = %s WHERE c.id = %s """, (actor_id, chat_id), ) row = await cursor.fetchone() if row is None: raise ApiProblem(404, "not_found", "Chat not found") return chat_json(row) async def chat_page( cursor: AsyncCursor, *, actor_id: uuid.UUID, limit: int, after: tuple[datetime, uuid.UUID] | None, ) -> list[dict[str, Any]]: query = ( "SELECT " + CHAT_COLUMNS + """ FROM chats c JOIN chat_members membership ON membership.chat_id = c.id AND membership.user_id = %(actor)s """ ) params: dict[str, Any] = {"actor": actor_id, "limit": limit + 1} if after is not None: query += " WHERE (c.created_at, c.id) > (%(after_ts)s, %(after_id)s)" params["after_ts"], params["after_id"] = after query += " ORDER BY c.created_at, c.id LIMIT %(limit)s" await cursor.execute(query, params) return [chat_json(row) for row in await cursor.fetchall()] async def require_membership( cursor: AsyncCursor, *, actor_id: uuid.UUID, chat_id: uuid.UUID ) -> None: await cursor.execute( "SELECT 1 FROM chat_members WHERE chat_id = %s AND user_id = %s", (chat_id, actor_id), ) if await cursor.fetchone() is None: raise ApiProblem(404, "not_found", "Chat not found") async def get_idempotency_key(cursor: AsyncCursor, key: str) -> dict[str, Any] | None: """Return the idempotency row (request_sha256, message_id, chat_id) if it exists.""" await cursor.execute( """ SELECT key, chat_id, request_sha256, message_id, created_at FROM idempotency_keys WHERE key = %s """, (key,), ) return await cursor.fetchone() async def insert_idempotency_key( cursor: AsyncCursor, *, key: str, chat_id: uuid.UUID, request_sha256: str ) -> None: try: await cursor.execute( """ INSERT INTO idempotency_keys (key, chat_id, request_sha256, created_at) VALUES (%s, %s, %s, now()) """, (key, chat_id, request_sha256), ) except psycopg.errors.UniqueViolation: raise ApiProblem(409, "conflict", "Idempotency-Key was already used") from None async def message_by_id(cursor: AsyncCursor, message_id: uuid.UUID) -> dict[str, Any] | None: await cursor.execute( """ SELECT id, chat_id, sender_id, text, created_at FROM messages WHERE id = %s """, (message_id,), ) row = await cursor.fetchone() if row is None: return None return message_json(row) async def create_message( cursor: AsyncCursor, *, actor_id: uuid.UUID, chat_id: uuid.UUID, text: str, request_sha256: str, key: str, ) -> dict[str, Any]: await require_membership(cursor, actor_id=actor_id, chat_id=chat_id) # The SHA-256 of the replayed body is recorded with the idempotency row so a # client cannot replay a request with different content under the same key. message_id = uuid.uuid4() await cursor.execute( """ INSERT INTO messages (id, chat_id, sender_id, text, created_at) VALUES (%s, %s, %s, %s, now()) RETURNING id, chat_id, sender_id, text, created_at """, (message_id, chat_id, actor_id, text), ) row = await cursor.fetchone() # Record the message_id so a replay can return the original message. await cursor.execute( "UPDATE idempotency_keys SET request_sha256 = %s, message_id = %s WHERE key = %s", (request_sha256, message_id, key), ) return message_json(row) async def message_page( cursor: AsyncCursor, *, chat_id: uuid.UUID, limit: int, after: tuple[datetime, uuid.UUID] | None, ) -> list[dict[str, Any]]: """Keyset page over (created_at, id); the composite index serves both branches.""" query = """ SELECT id, chat_id, sender_id, text, created_at FROM messages WHERE chat_id = %(chat)s """ params: dict[str, Any] = {"chat": chat_id, "limit": limit + 1} if after is not None: query += " AND (created_at, id) > (%(after_ts)s, %(after_id)s)" params["after_ts"], params["after_id"] = after query += " ORDER BY created_at, id LIMIT %(limit)s" await cursor.execute(query, params) return [message_json(row) for row in await cursor.fetchall()] async def insert_session( cursor: AsyncCursor, *, user_id: uuid.UUID, token_hash: str, ttl_seconds: int, ) -> datetime: await cursor.execute( """ INSERT INTO sessions (id, user_id, token_hash, created_at, expires_at) VALUES (%s, %s, %s, now(), now() + make_interval(secs => %s)) RETURNING expires_at """, (uuid.uuid4(), user_id, token_hash, ttl_seconds), ) row = await cursor.fetchone() return row["expires_at"] async def session_user(cursor: AsyncCursor, token_hash: str) -> dict[str, Any] | None: """Resolve a live session row; expired and revoked sessions never match.""" await cursor.execute( """ SELECT s.expires_at, u.id, u.username, u.display_name, u.created_at FROM sessions s JOIN users u ON u.id = s.user_id WHERE s.token_hash = %s AND s.revoked_at IS NULL AND s.expires_at > now() """, (token_hash,), ) return await cursor.fetchone() async def revoke_session(cursor: AsyncCursor, token_hash: str) -> datetime | None: """Revoke a live session and return its expiry, or None when it is not live.""" await cursor.execute( """ UPDATE sessions SET revoked_at = now() WHERE token_hash = %s AND revoked_at IS NULL AND expires_at > now() RETURNING expires_at """, (token_hash,), ) row = await cursor.fetchone() return None if row is None else row["expires_at"] async def purge_expired_sessions(cursor: AsyncCursor) -> int: await cursor.execute( """ DELETE FROM sessions WHERE expires_at < now() - interval '1 hour' OR (revoked_at IS NOT NULL AND revoked_at < now() - interval '1 hour') """ ) return cursor.rowcount