import uuid from datetime import datetime, timezone from typing import Optional from app.cache import Cache import asyncpg import asyncio def _now_iso(value: datetime) -> str: if value.tzinfo is None: value = value.replace(tzinfo=timezone.utc) return value.astimezone(timezone.utc).isoformat().replace("+00:00", "Z") class Storage: def __init__(self, pool: asyncpg.Pool, cache: Cache) -> None: self._pool = pool self._cache = cache async def create_user( self, username: str, display_name: str, password_hash: str, ) -> dict: user_id = str(uuid.uuid4()) try: async with self._pool.acquire() as conn: row = await conn.fetchrow( """ INSERT INTO users (id, username, display_name, password_hash) VALUES ($1, $2, $3, $4) RETURNING id, username, display_name, created_at """, user_id, username, display_name, password_hash, ) except asyncpg.UniqueViolationError: raise ValueError("conflict") return self._user_row(row) async def get_user(self, user_id: str) -> Optional[dict]: async with self._pool.acquire() as conn: row = await conn.fetchrow( "SELECT id, username, display_name, created_at FROM users WHERE id = $1", user_id, ) return self._user_row(row) if row else None async def get_user_by_username(self, username: str) -> Optional[dict]: async with self._pool.acquire() as conn: row = await conn.fetchrow( """ SELECT id, username, display_name, password_hash, created_at FROM users WHERE username = $1 """, username, ) return dict(row) if row else None async def create_chat( self, title: str, member_ids: list[str], creator_id: str, ) -> dict: unique = list(dict.fromkeys(member_ids)) if creator_id not in unique: raise ValueError("creator_not_member") chat_id = str(uuid.uuid4()) async with self._pool.acquire() as conn: async with conn.transaction(): existing = await conn.fetchval( "SELECT count(*) FROM users WHERE id = ANY($1::uuid[])", unique, ) if existing != len(unique): raise ValueError("invalid_member") await conn.execute( "INSERT INTO chats (id, title) VALUES ($1, $2)", chat_id, title, ) await conn.executemany( "INSERT INTO chat_members (chat_id, user_id) VALUES ($1, $2)", [(chat_id, uid) for uid in unique], ) created = await conn.fetchval( "SELECT created_at FROM chats WHERE id = $1", chat_id, ) return { "id": chat_id, "title": title, "member_ids": unique, "created_at": _now_iso(created), } async def get_chat(self, chat_id: str, actor_id: str) -> Optional[dict]: async with self._pool.acquire() as conn: row = await conn.fetchrow( "SELECT id, title, created_at FROM chats WHERE id = $1", chat_id, ) if row is None: return None members = await conn.fetch( "SELECT user_id FROM chat_members WHERE chat_id = $1", chat_id, ) member_ids = [str(m["user_id"]) for m in members] if actor_id not in member_ids: return None return { "id": str(row["id"]), "title": row["title"], "member_ids": member_ids, "created_at": _now_iso(row["created_at"]), } async def list_chats( self, actor_id: str, limit: int, cursor: Optional[str], ) -> tuple[list[dict], Optional[str]]: async with self._pool.acquire() as conn: params: list = [actor_id] where = "" if cursor: try: cur_created, cur_id = cursor.split("|", 1) except ValueError: raise ValueError("bad_cursor") where = "AND (c.created_at, c.id) > ($2, $3)" params += [ datetime.fromisoformat(cur_created.replace("Z", "+00:00")), cur_id, ] rows = await conn.fetch( f""" SELECT c.id, c.title, c.created_at FROM chats c JOIN chat_members m ON m.chat_id = c.id WHERE m.user_id = $1 {where} ORDER BY c.created_at, c.id LIMIT ${len(params) + 1} """, *params, limit + 1, ) items = [] for row in rows[:limit]: members = await conn.fetch( "SELECT user_id FROM chat_members WHERE chat_id = $1", row["id"], ) items.append({ "id": str(row["id"]), "title": row["title"], "member_ids": [str(m["user_id"]) for m in members], "created_at": _now_iso(row["created_at"]), }) next_cursor = None if len(rows) > limit: last = rows[limit - 1] next_cursor = f"{_now_iso(last['created_at'])}|{last['id']}" return items, next_cursor async def add_message( self, chat_id: str, sender_id: str, text: str, ) -> dict: message_id = str(uuid.uuid4()) async with self._pool.acquire() as conn: is_member = await conn.fetchval( "SELECT 1 FROM chat_members WHERE chat_id = $1 AND user_id = $2", chat_id, sender_id, ) if is_member is None: raise ValueError("not_found") row = await conn.fetchrow( """ INSERT INTO messages (id, chat_id, sender_id, text) VALUES ($1, $2, $3, $4) RETURNING id, chat_id, sender_id, text, created_at """, message_id, chat_id, sender_id, text, ) await self._cache.invalidate_chat(chat_id) return self._message_row(row) async def list_messages( self, chat_id: str, actor_id: str, limit: int, cursor: Optional[str], ) -> tuple[list[dict], Optional[str]]: cache_key = f"messages:{chat_id}:{limit}:{cursor or ''}" cached = await self._cache.get_json(cache_key) if cached is not None: return cached["items"], cached["next_cursor"] lock_key = f"lock:{cache_key}" got_lock = await self._cache.try_lock(lock_key, ttl=10) if not got_lock: for _ in range(50): await asyncio.sleep(0.1) cached = await self._cache.get_json(cache_key) if cached is not None: return cached["items"], cached["next_cursor"] cached = await self._cache.get_json(cache_key) if cached is not None: return cached["items"], cached["next_cursor"] try: async with self._pool.acquire() as conn: is_member = await conn.fetchval( "SELECT 1 FROM chat_members WHERE chat_id = $1 AND user_id = $2", chat_id, actor_id, ) if is_member is None: raise ValueError("not_found") params: list = [chat_id] where = "" if cursor: try: cur_created, cur_id = cursor.split("|", 1) except ValueError: raise ValueError("bad_cursor") where = "AND (created_at, id) > ($2, $3)" params += [ datetime.fromisoformat(cur_created.replace("Z", "+00:00")), cur_id, ] rows = await conn.fetch( f""" SELECT id, chat_id, sender_id, text, created_at FROM messages WHERE chat_id = $1 {where} ORDER BY created_at, id LIMIT ${len(params) + 1} """, *params, limit + 1, ) items = [self._message_row(row) for row in rows[:limit]] next_cursor = None if len(rows) > limit: last = rows[limit - 1] next_cursor = f"{_now_iso(last['created_at'])}|{last['id']}" if got_lock: await self._cache.set_json( cache_key, {"items": items, "next_cursor": next_cursor}, ) return items, next_cursor finally: if got_lock: await self._cache.unlock(lock_key) @staticmethod def _user_row(row) -> dict: return { "id": str(row["id"]), "username": row["username"], "display_name": row["display_name"], "created_at": _now_iso(row["created_at"]), } @staticmethod def _message_row(row) -> dict: return { "id": str(row["id"]), "chat_id": str(row["chat_id"]), "sender_id": str(row["sender_id"]), "text": row["text"], "created_at": _now_iso(row["created_at"]), }