"""PostgreSQL-backed storage for users, chats, sessions, messages and idempotency keys. All state lives in one shared PostgreSQL instance so every API replica sees the same truth. Sessions and idempotency records are durable, which is what makes the service horizontally scalable and safe to restart. """ import asyncio import base64 import hashlib import json import os import secrets import uuid from datetime import datetime, timezone import asyncpg from .config import IDEM_TTL_SECONDS, SCRYPT_N, SCRYPT_P, SCRYPT_R from .errors import APIError def utc_now() -> datetime: return datetime.now(timezone.utc) def iso_z(dt: datetime) -> str: """RFC 3339 UTC with trailing Z, as required by the contract.""" if dt.tzinfo is None: dt = dt.replace(tzinfo=timezone.utc) return dt.astimezone(timezone.utc).isoformat().replace("+00:00", "Z") # --------------------------------------------------------------------------- # Password hashing (library KDF: scrypt via OpenSSL) # --------------------------------------------------------------------------- def hash_password(password: str) -> str: salt = os.urandom(16) derived = hashlib.scrypt( password.encode("utf-8"), salt=salt, n=SCRYPT_N, r=SCRYPT_R, p=SCRYPT_P, dklen=32 ) return "scrypt$%d$%d$%d$%s$%s" % (SCRYPT_N, SCRYPT_R, SCRYPT_P, salt.hex(), derived.hex()) def verify_password(password: str, stored: str) -> bool: try: parts = stored.split("$") if len(parts) != 6 or parts[0] != "scrypt": return False n, r, p = int(parts[1]), int(parts[2]), int(parts[3]) salt = bytes.fromhex(parts[4]) expected = bytes.fromhex(parts[5]) derived = hashlib.scrypt( password.encode("utf-8"), salt=salt, n=n, r=r, p=p, dklen=len(expected) ) return secrets.compare_digest(derived, expected) except (ValueError, TypeError): return False # --------------------------------------------------------------------------- # Opaque keyset cursors # --------------------------------------------------------------------------- def encode_cursor(chat_id, created_at: datetime, item_id) -> str: payload = json.dumps( {"c": str(chat_id), "t": iso_z(created_at), "i": str(item_id)}, separators=(",", ":") ) return base64.urlsafe_b64encode(payload.encode()).decode().rstrip("=") def decode_cursor(cursor: str, expected_chat_id): try: raw = base64.urlsafe_b64decode(cursor + "=" * (-len(cursor) % 4)) data = json.loads(raw) chat = uuid.UUID(str(data["c"])) when = datetime.fromisoformat(str(data["t"]).replace("Z", "+00:00")) item = uuid.UUID(str(data["i"])) except Exception: raise APIError(400, "invalid_request", "Invalid cursor") from None if expected_chat_id is not None and chat != expected_chat_id: raise APIError(400, "invalid_request", "Cursor belongs to a different resource") return when, item class Database: def __init__(self, dsn: str): self.dsn = dsn self._pool: asyncpg.Pool | None = None async def connect(self, retries: int = 30, delay: float = 1.0) -> None: last_err = None for _ in range(retries): try: self._pool = await asyncpg.create_pool(self.dsn, min_size=1, max_size=10) return except Exception as exc: # pragma: no cover - startup retry loop last_err = exc await asyncio.sleep(delay) raise RuntimeError(f"Could not connect to PostgreSQL: {last_err}") async def close(self) -> None: if self._pool is not None: await self._pool.close() self._pool = None async def health(self) -> bool: if self._pool is None: return False try: async with self._pool.acquire() as conn: await conn.execute("SELECT 1") return True except Exception: return False # -- users ---------------------------------------------------------------- async def create_user(self, user_id, username: str, display_name: str, password_hash: str, created_at): async with self._pool.acquire() as conn: try: return await conn.fetchrow( "INSERT INTO users (id, username, display_name, password_hash, created_at) " "VALUES ($1, $2, $3, $4, $5) RETURNING id, username, display_name, created_at", user_id, username, display_name, password_hash, created_at, ) except asyncpg.UniqueViolationError: raise APIError(409, "conflict", "Username already taken") from None async def get_user_by_username(self, username: str): async with self._pool.acquire() as conn: return await conn.fetchrow("SELECT * FROM users WHERE username = $1", username) async def get_user_by_id(self, user_id): async with self._pool.acquire() as conn: return await conn.fetchrow("SELECT * FROM users WHERE id = $1", user_id) # -- sessions ------------------------------------------------------------- async def create_session(self, token: str, user_id, expires_at) -> None: async with self._pool.acquire() as conn: await conn.execute( "INSERT INTO sessions (token, user_id, expires_at) VALUES ($1, $2, $3)", token, user_id, expires_at, ) async def get_session_user(self, token: str): async with self._pool.acquire() as conn: return await conn.fetchrow( "SELECT 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 = $1 AND s.expires_at > now()", token, ) async def revoke_session(self, token: str) -> None: async with self._pool.acquire() as conn: await conn.execute("DELETE FROM sessions WHERE token = $1", token) # -- chats ---------------------------------------------------------------- async def create_chat(self, chat_id, title: str, member_ids, created_at): async with self._pool.acquire() as conn: async with conn.transaction(): await conn.execute( "INSERT INTO chats (id, title, created_at) VALUES ($1, $2, $3)", chat_id, title, created_at, ) for uid in member_ids: await conn.execute( "INSERT INTO chat_members (chat_id, user_id) VALUES ($1, $2)", chat_id, uid, ) return await conn.fetchrow("SELECT * FROM chats WHERE id = $1", chat_id) async def get_chat(self, chat_id): async with self._pool.acquire() as conn: return await conn.fetchrow("SELECT * FROM chats WHERE id = $1", chat_id) async def get_chat_members(self, chat_id): async with self._pool.acquire() as conn: rows = await conn.fetch( "SELECT user_id FROM chat_members WHERE chat_id = $1 ORDER BY user_id", chat_id ) return [row["user_id"] for row in rows] async def users_exist(self, user_ids) -> bool: if not user_ids: return True async with self._pool.acquire() as conn: row = await conn.fetchrow( "SELECT COUNT(DISTINCT id) AS n FROM users WHERE id = ANY($1)", list(user_ids) ) return row["n"] == len(set(user_ids)) async def list_chats(self, user_id, limit: int, cursor: str | None): after_t, after_id = None, None if cursor is not None: after_t, after_id = decode_cursor(cursor, None) async with self._pool.acquire() as conn: rows = await conn.fetch( """ SELECT c.id, c.title, c.created_at, ARRAY(SELECT cm2.user_id FROM chat_members cm2 WHERE cm2.chat_id = c.id ORDER BY cm2.user_id) AS member_ids FROM chats c JOIN chat_members cm ON cm.chat_id = c.id AND cm.user_id = $1 WHERE $2::timestamptz IS NULL OR (c.created_at, c.id) > ($2, $3) ORDER BY c.created_at ASC, c.id ASC LIMIT $4 """, user_id, after_t, after_id, limit + 1, ) has_more = len(rows) > limit items = rows[:limit] next_cursor = None if has_more and items: last = items[-1] next_cursor = encode_cursor(last["id"], last["created_at"], last["id"]) return items, next_cursor # -- messages ------------------------------------------------------------- async def list_messages(self, chat_id, limit: int, cursor: str | None): after_t, after_id = None, None if cursor is not None: after_t, after_id = decode_cursor(cursor, chat_id) async with self._pool.acquire() as conn: rows = await conn.fetch( """ SELECT id, chat_id, sender_id, text, created_at FROM messages WHERE chat_id = $1 AND ($2::timestamptz IS NULL OR (created_at, id) > ($2, $3)) ORDER BY created_at ASC, id ASC LIMIT $4 """, chat_id, after_t, after_id, limit + 1, ) has_more = len(rows) > limit items = rows[:limit] next_cursor = None if has_more and items: last = items[-1] next_cursor = encode_cursor(chat_id, last["created_at"], last["id"]) return items, next_cursor async def create_message(self, user_id, chat_id, text: str, idem_key: str, body_hash: str): msg_id = uuid.uuid4() created_at = utc_now() response = { "id": str(msg_id), "chat_id": str(chat_id), "sender_id": str(user_id), "text": text, "created_at": iso_z(created_at), } path = f"/api/v1/chats/{chat_id}/messages" async with self._pool.acquire() as conn: async with conn.transaction(): inserted = await conn.fetchval( """ INSERT INTO idempotency_keys (user_id, method, path, idem_key, request_hash, response_json, status_code) VALUES ($1, 'POST', $2, $3, $4, $5, 201) ON CONFLICT (user_id, method, path, idem_key) DO NOTHING RETURNING 1 """, user_id, path, idem_key, body_hash, json.dumps(response), ) if inserted: await conn.execute( "INSERT INTO messages (id, chat_id, sender_id, text, created_at) " "VALUES ($1, $2, $3, $4, $5)", msg_id, chat_id, user_id, text, created_at, ) return response, 201 row = await conn.fetchrow( "SELECT request_hash, response_json, status_code FROM idempotency_keys " "WHERE user_id = $1 AND method = 'POST' AND path = $2 AND idem_key = $3", user_id, path, idem_key, ) if row is None: raise APIError(500, "internal_error", "Internal error") if row["request_hash"] != body_hash: raise APIError(409, "conflict", "Idempotency key reused with a different body") return json.loads(row["response_json"]), row["status_code"] # -- idempotency maintenance -------------------------------------------- async def cleanup_idempotency(self, ttl_seconds: int) -> None: if self._pool is None: return async with self._pool.acquire() as conn: await conn.execute( "DELETE FROM idempotency_keys WHERE created_at < now() - make_interval(secs => $1)", ttl_seconds, )