from datetime import datetime from hashlib import sha256 from pathlib import Path from secrets import token_urlsafe from uuid import UUID, uuid4 import asyncpg from argon2 import PasswordHasher from argon2.exceptions import InvalidHashError, VerificationError from ..errors import ApiError ROOT = Path(__file__).resolve().parents[2] MIGRATIONS = ROOT / "migrations" PASSWORD_HASHER = PasswordHasher() DB_ERRORS = (asyncpg.PostgresError, asyncpg.InterfaceError, OSError) class PostgresStore: def __init__(self, database_url: str) -> None: self._database_url = database_url self._pool: asyncpg.Pool | None = None async def connect(self) -> None: try: self._pool = await asyncpg.create_pool( self._database_url, min_size=1, max_size=10, command_timeout=5 ) except DB_ERRORS as error: raise RuntimeError("PostgreSQL is unavailable") from error async def close(self) -> None: if self._pool is not None: await self._pool.close() @property def pool(self) -> asyncpg.Pool: if self._pool is None: raise RuntimeError("PostgreSQL pool has not been initialized") return self._pool async def migrate(self) -> None: async with self.pool.acquire() as connection: await connection.execute( "CREATE TABLE IF NOT EXISTS schema_migrations (version text PRIMARY KEY, applied_at timestamptz NOT NULL DEFAULT now())" ) for migration in sorted(MIGRATIONS.glob("*.sql")): applied = await connection.fetchval( "SELECT 1 FROM schema_migrations WHERE version = $1", migration.name ) if applied: continue async with connection.transaction(): await connection.execute(migration.read_text(encoding="utf-8")) await connection.execute( "INSERT INTO schema_migrations (version) VALUES ($1)", migration.name ) @staticmethod def _user(row: asyncpg.Record) -> dict: return { "id": row["id"], "username": row["username"], "display_name": row["display_name"], "created_at": row["created_at"], } @staticmethod def _chat(row: asyncpg.Record) -> dict: return { "id": row["id"], "title": row["title"], "member_ids": row["member_ids"], "created_at": row["created_at"], } @staticmethod def _message(row: asyncpg.Record) -> dict: return { "id": row["id"], "chat_id": row["chat_id"], "sender_id": row["sender_id"], "text": row["text"], "created_at": row["created_at"], } async def ready(self) -> None: try: await self.pool.fetchval("SELECT 1") except DB_ERRORS as error: raise ApiError(503, "unavailable", "PostgreSQL недоступен") from error async def create_user(self, username: str, display_name: str, password: str) -> dict: try: row = await self.pool.fetchrow( "INSERT INTO users (id, username, display_name, password_hash) VALUES ($1, $2, $3, $4) RETURNING id, username, display_name, created_at", uuid4(), username, display_name, PASSWORD_HASHER.hash(password), ) except asyncpg.UniqueViolationError as error: raise ApiError(409, "conflict", "Username уже занят") from error except DB_ERRORS as error: raise ApiError(503, "unavailable", "PostgreSQL недоступен") from error return self._user(row) async def authenticate(self, username: str, password: str) -> dict | None: try: row = await self.pool.fetchrow( "SELECT id, username, display_name, created_at, password_hash FROM users WHERE username = $1", username, ) except DB_ERRORS as error: raise ApiError(503, "unavailable", "PostgreSQL недоступен") from error if row is None: return None try: valid = PASSWORD_HASHER.verify(row["password_hash"], password) except (InvalidHashError, VerificationError): valid = False return self._user(row) if valid else None async def create_session(self, user: dict, ttl_seconds: int) -> dict: token = token_urlsafe(32) token_hash = sha256(token.encode("ascii")).hexdigest() try: row = await self.pool.fetchrow( "INSERT INTO sessions (token_hash, user_id, expires_at) VALUES ($1, $2, now() + $3 * interval '1 second') RETURNING expires_at", token_hash, user["id"], ttl_seconds, ) except DB_ERRORS as error: raise ApiError(503, "unavailable", "PostgreSQL недоступен") from error return {"token": token, "token_type": "Bearer", "expires_at": row["expires_at"], "user": user} async def user_for_token(self, token: str) -> dict | None: token_hash = sha256(token.encode("ascii")).hexdigest() try: row = await self.pool.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_hash = $1 AND s.expires_at > now()", token_hash, ) except DB_ERRORS as error: raise ApiError(503, "unavailable", "PostgreSQL недоступен") from error return self._user(row) if row else None async def revoke_session(self, token: str) -> None: try: await self.pool.execute( "DELETE FROM sessions WHERE token_hash = $1", sha256(token.encode("ascii")).hexdigest() ) except DB_ERRORS as error: raise ApiError(503, "unavailable", "PostgreSQL недоступен") from error async def create_chat(self, creator_id: UUID, title: str, member_ids: list[UUID]) -> dict: if len(member_ids) != len(set(member_ids)) or creator_id not in member_ids: raise ApiError(400, "invalid_request", "Некорректный список участников") try: async with self.pool.acquire() as connection, connection.transaction(): existing = await connection.fetchval( "SELECT count(*) FROM users WHERE id = ANY($1::uuid[])", member_ids ) if existing != len(member_ids): raise ApiError(400, "invalid_request", "Один или несколько участников не существуют") row = await connection.fetchrow( "INSERT INTO chats (id, title) VALUES ($1, $2) RETURNING id, title, created_at", uuid4(), title, ) await connection.executemany( "INSERT INTO chat_members (chat_id, user_id) VALUES ($1, $2)", [(row["id"], member_id) for member_id in member_ids], ) except DB_ERRORS as error: raise ApiError(503, "unavailable", "PostgreSQL недоступен") from error return { "id": row["id"], "title": row["title"], "member_ids": member_ids, "created_at": row["created_at"], } async def get_chat_for_member(self, chat_id: UUID, user_id: UUID) -> dict: try: row = await self.pool.fetchrow( "SELECT c.id, c.title, c.created_at, array_agg(cm_all.user_id ORDER BY cm_all.user_id) AS member_ids FROM chats c JOIN chat_members mine ON mine.chat_id = c.id AND mine.user_id = $2 JOIN chat_members cm_all ON cm_all.chat_id = c.id WHERE c.id = $1 GROUP BY c.id", chat_id, user_id, ) except DB_ERRORS as error: raise ApiError(503, "unavailable", "PostgreSQL недоступен") from error if row is None: raise ApiError(404, "not_found", "Чат не найден") return self._chat(row) async def list_chats_for_member( self, user_id: UUID, after: tuple[datetime, UUID] | None, limit: int ) -> list[dict]: query = "SELECT c.id, c.title, c.created_at, array_agg(cm_all.user_id ORDER BY cm_all.user_id) AS member_ids FROM chats c JOIN chat_members mine ON mine.chat_id = c.id AND mine.user_id = $1 JOIN chat_members cm_all ON cm_all.chat_id = c.id" args: list = [user_id] if after is not None: query += " WHERE (c.created_at, c.id) > ($2, $3)" args.extend(after) query += " GROUP BY c.id ORDER BY c.created_at, c.id LIMIT $" + str(len(args) + 1) args.append(limit + 1) try: rows = await self.pool.fetch(query, *args) except DB_ERRORS as error: raise ApiError(503, "unavailable", "PostgreSQL недоступен") from error return [self._chat(row) for row in rows] async def create_message(self, chat_id: UUID, sender_id: UUID, text: str) -> dict: try: async with self.pool.acquire() as connection, connection.transaction(): member = await connection.fetchval( "SELECT 1 FROM chat_members WHERE chat_id = $1 AND user_id = $2", chat_id, sender_id, ) if member is None: raise ApiError(404, "not_found", "Чат не найден") row = await connection.fetchrow( "INSERT INTO messages (id, chat_id, sender_id, text) VALUES ($1, $2, $3, $4) RETURNING id, chat_id, sender_id, text, created_at", uuid4(), chat_id, sender_id, text, ) await connection.execute( "UPDATE chats SET history_version = history_version + 1 WHERE id = $1", chat_id, ) except DB_ERRORS as error: raise ApiError(503, "unavailable", "PostgreSQL недоступен") from error return self._message(row) async def history_version_for_member(self, chat_id: UUID, user_id: UUID) -> int: try: version = await self.pool.fetchval( "SELECT c.history_version FROM chats c JOIN chat_members cm ON cm.chat_id = c.id WHERE c.id = $1 AND cm.user_id = $2", chat_id, user_id, ) except DB_ERRORS as error: raise ApiError(503, "unavailable", "PostgreSQL недоступен") from error if version is None: raise ApiError(404, "not_found", "Чат не найден") return version async def list_messages_for_member( self, chat_id: UUID, user_id: UUID, after: tuple[datetime, UUID] | None, limit: int ) -> list[dict]: await self.get_chat_for_member(chat_id, user_id) query = "SELECT id, chat_id, sender_id, text, created_at FROM messages WHERE chat_id = $1" args: list = [chat_id] if after is not None: query += " AND (created_at, id) > ($2, $3)" args.extend(after) query += " ORDER BY created_at, id LIMIT $" + str(len(args) + 1) args.append(limit + 1) try: rows = await self.pool.fetch(query, *args) except DB_ERRORS as error: raise ApiError(503, "unavailable", "PostgreSQL недоступен") from error return [self._message(row) for row in rows]