"""PostgreSQL-backed users, chats and message history.""" import base64 import binascii import json from contextlib import contextmanager from datetime import datetime, timezone from uuid import UUID, uuid4 import psycopg from argon2 import PasswordHasher from fastapi import HTTPException from psycopg.errors import UniqueViolation from psycopg_pool import PoolTimeout from . import db password_hasher = PasswordHasher() def timestamp(value: datetime) -> str: return value.astimezone(timezone.utc).isoformat(timespec="microseconds").replace("+00:00", "Z") def encode_cursor(resource: str, item: dict) -> str: value = [resource, item["created_at"], item["id"]] return base64.urlsafe_b64encode(json.dumps(value, separators=(",", ":")).encode()).decode().rstrip("=") def decode_cursor(cursor: str | None, resource: str) -> tuple[datetime, UUID] | None: if cursor is None: return None try: raw = base64.b64decode(cursor + "=" * (-len(cursor) % 4), altchars=b"-_", validate=True) value = json.loads(raw) if not isinstance(value, list) or len(value) != 3 or value[0] != resource: raise ValueError date_text, item_id = value[1:] if not isinstance(date_text, str) or not date_text.endswith("Z") or not isinstance(item_id, str): raise ValueError date = datetime.fromisoformat(date_text[:-1] + "+00:00") if date.utcoffset().total_seconds() != 0: raise ValueError return date, UUID(item_id) except (binascii.Error, UnicodeError, ValueError, TypeError, AttributeError): raise HTTPException(400) from None @contextmanager def connection(): try: with db.pool().connection() as conn: yield conn except (psycopg.Error, PoolTimeout, OSError): raise HTTPException(503) from None def user_view(row: dict) -> dict: return { "id": str(row["id"]), "username": row["username"], "display_name": row["display_name"], "created_at": timestamp(row["created_at"]), } def chat_view(row: dict) -> dict: return { "id": str(row["id"]), "title": row["title"], "member_ids": [str(member_id) for member_id in row["member_ids"]], "created_at": timestamp(row["created_at"]), } def message_view(row: dict) -> dict: return { "id": str(row["id"]), "chat_id": str(row["chat_id"]), "sender_id": str(row["sender_id"]), "text": row["text"], "created_at": timestamp(row["created_at"]), } CHAT_COLUMNS = """c.id, c.title, c.created_at, ARRAY(SELECT m.user_id FROM memberships m WHERE m.chat_id=c.id ORDER BY m.position) AS member_ids""" class Store: def ready(self) -> dict: if not db.ready(): raise HTTPException(503) return {"status": "ok"} def register(self, username: str, display_name: str, password: str) -> dict: password_hash = password_hasher.hash(password) with connection() as conn: try: row = conn.execute( "INSERT INTO users (id, username, display_name, password_hash) VALUES (%s,%s,%s,%s) " "RETURNING id,username,display_name,created_at", (uuid4(), username, display_name, password_hash), ).fetchone() except UniqueViolation: raise HTTPException(409) from None return user_view(row) def user(self, user_id: str | None) -> dict: if not user_id: raise HTTPException(401) try: user_uuid = UUID(user_id) except (ValueError, TypeError): raise HTTPException(401) from None with connection() as conn: row = conn.execute( "SELECT id,username,display_name,created_at FROM users WHERE id=%s", (user_uuid,) ).fetchone() if row is None: raise HTTPException(401) return user_view(row) def create_chat(self, actor_id: str, title: str, member_ids: list[str]) -> dict: if actor_id not in member_ids: raise HTTPException(400) members = [UUID(member_id) for member_id in member_ids] with connection() as conn: count = conn.execute("SELECT count(*) AS n FROM users WHERE id=ANY(%s)", (members,)).fetchone()["n"] if count != len(members): raise HTTPException(400) row = conn.execute("INSERT INTO chats (id,title) VALUES (%s,%s) RETURNING id,title,created_at", (uuid4(), title)).fetchone() for position, member_id in enumerate(members): conn.execute( "INSERT INTO memberships (chat_id,user_id,position) VALUES (%s,%s,%s)", (row["id"], member_id, position), ) return chat_view({**row, "member_ids": members}) def chat(self, actor_id: str, chat_id: str) -> dict: with connection() as conn: row = conn.execute( f"SELECT {CHAT_COLUMNS} FROM chats c " "JOIN memberships access ON access.chat_id=c.id " "WHERE access.user_id=%s AND c.id=%s", (UUID(actor_id), UUID(chat_id)), ).fetchone() if row is None: raise HTTPException(404) return chat_view(row) def list_chats(self, actor_id: str, limit: int, cursor: str | None) -> dict: after = decode_cursor(cursor, f"chats:{actor_id}") query = (f"SELECT {CHAT_COLUMNS} FROM chats c " "JOIN memberships access ON access.chat_id=c.id WHERE access.user_id=%s") params = [UUID(actor_id)] if after: query += " AND (c.created_at,c.id)>(%s,%s)" params.extend(after) query += " ORDER BY c.created_at,c.id LIMIT %s" params.append(limit + 1) with connection() as conn: rows = conn.execute(query, params).fetchall() items = [chat_view(row) for row in rows[:limit]] return {"items": items, "next_cursor": encode_cursor(f"chats:{actor_id}", items[-1]) if len(rows) > limit else None} def create_message(self, actor_id: str, chat_id: str, text: str) -> dict: chat_uuid, actor_uuid = UUID(chat_id), UUID(actor_id) with connection() as conn: member = conn.execute( "SELECT 1 FROM memberships WHERE chat_id=%s AND user_id=%s", (chat_uuid, actor_uuid) ).fetchone() if member is None: raise HTTPException(404) 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_uuid, actor_uuid, text), ).fetchone() return message_view(row) def list_messages(self, actor_id: str, chat_id: str, limit: int, cursor: str | None) -> dict: after = decode_cursor(cursor, f"messages:{chat_id}") chat_uuid, actor_uuid = UUID(chat_id), UUID(actor_id) query = "SELECT id,chat_id,sender_id,text,created_at FROM messages WHERE chat_id=%s" params = [chat_uuid] if after: query += " AND (created_at,id)>(%s,%s)" params.extend(after) query += " ORDER BY created_at,id LIMIT %s" params.append(limit + 1) with connection() as conn: member = conn.execute( "SELECT 1 FROM memberships WHERE chat_id=%s AND user_id=%s", (chat_uuid, actor_uuid) ).fetchone() if member is None: raise HTTPException(404) rows = conn.execute(query, params).fetchall() items = [message_view(row) for row in rows[:limit]] return {"items": items, "next_cursor": encode_cursor(f"messages:{chat_id}", items[-1]) if len(rows) > limit else None} store = Store()