import uuid import asyncpg from app.core.errors import ApiError from app.core.security import new_token from app.repositories.memory import ( ChatRow, MessageRow, UserRow, iso_z, ) def _user(row: asyncpg.Record | None) -> UserRow | None: if row is None: return None return UserRow( id=str(row['id']), username=row['username'], display_name=row['display_name'], password_hash=row['password_hash'], created_at=iso_z(row['created_at']), ) def _chat(row: asyncpg.Record) -> ChatRow: moment = row['created_at'] return ChatRow( id=str(row['id']), title=row['title'], member_ids=[str(x) for x in row['member_ids']], created_dt=moment, created_at=iso_z(moment), ) def _message(row: asyncpg.Record) -> MessageRow: moment = row['created_at'] return MessageRow( id=str(row['id']), chat_id=str(row['chat_id']), sender_id=str(row['sender_id']), text=row['text'], created_dt=moment, created_at=iso_z(moment), ) class PgStorage: """Хранилище пользователей, сессий, чатов, участников и сообщений на PostgreSQL.""" def __init__(self, pool: asyncpg.Pool, session_store): self.pool = pool self.session_store = session_store async def ready(self) -> bool: try: async with self.pool.acquire() as connection: database_ready = await connection.fetchval('SELECT 1') == 1 return database_ready and await self.session_store.ready() except (asyncpg.PostgresError, OSError, TimeoutError): return False async def create_user(self, username: str, display_name: str, password_hash: str) -> UserRow: try: async with self.pool.acquire() as connection: row = await connection.fetchrow( 'INSERT INTO users (id, username, display_name, password_hash) ' 'VALUES ($1, $2, $3, $4) RETURNING *', uuid.uuid4(), username, display_name, password_hash, ) except asyncpg.UniqueViolationError as exc: if exc.constraint_name == 'users_username_key': raise ApiError(409, 'Username is already taken') from None raise return _user(row) async def user_by_username(self, username: str) -> UserRow | None: async with self.pool.acquire() as connection: return _user(await connection.fetchrow( 'SELECT * FROM users WHERE username = $1', username )) async def user(self, user_id: str) -> UserRow | None: async with self.pool.acquire() as connection: return _user(await connection.fetchrow( 'SELECT * FROM users WHERE id = $1', uuid.UUID(user_id) )) async def create_session(self, user_id: str, ttl_seconds: int): return await self.session_store.create_session(user_id, ttl_seconds) async def session(self, token: str): return await self.session_store.session(token) async def revoke(self, token: str) -> bool: return await self.session_store.revoke(token) async def create_chat(self, title: str, member_ids: list[str], caller_id: str) -> ChatRow: if caller_id not in member_ids: raise ApiError(400, 'Creator must be included in member_ids') chat_id = uuid.uuid4() try: async with self.pool.acquire() as connection: async with connection.transaction(): created_at = await connection.fetchval( 'INSERT INTO chats (id, title) VALUES ($1, $2) RETURNING created_at', chat_id, title, ) await connection.executemany( 'INSERT INTO chat_members (chat_id, user_id) VALUES ($1, $2)', [(chat_id, uuid.UUID(member_id)) for member_id in member_ids], ) except asyncpg.ForeignKeyViolationError: raise ApiError(400, 'Unknown member id') from None return ChatRow( id=str(chat_id), title=title, member_ids=list(member_ids), created_dt=created_at, created_at=iso_z(created_at), ) async def chat(self, chat_id: str) -> ChatRow | None: async with self.pool.acquire() as connection: row = await connection.fetchrow( 'SELECT c.id, c.title, c.created_at, ' 'array_agg(cm.user_id ORDER BY cm.user_id) AS member_ids ' 'FROM chats c JOIN chat_members cm ON cm.chat_id = c.id ' 'WHERE c.id = $1 GROUP BY c.id', uuid.UUID(chat_id), ) return _chat(row) if row else None async def chats_of(self, user_id: str) -> list[ChatRow]: async with self.pool.acquire() as connection: rows = await connection.fetch( '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 ' 'JOIN chat_members cm_all ON cm_all.chat_id = c.id ' 'WHERE mine.user_id = $1 ' 'GROUP BY c.id ORDER BY c.created_at, c.id', uuid.UUID(user_id), ) return [_chat(row) for row in rows] async def add_message(self, chat_id: str, sender_id: str, text: str) -> MessageRow: async with self.pool.acquire() as connection: row = await connection.fetchrow( 'INSERT INTO messages (id, chat_id, sender_id, text) ' 'VALUES ($1, $2, $3, $4) RETURNING *', uuid.uuid4(), uuid.UUID(chat_id), uuid.UUID(sender_id), text, ) return _message(row) async def add_idempotent_message( self, chat_id: str, sender_id: str, text: str, idempotency_key: str, request_hash: bytes, ) -> MessageRow: """Создать сообщение и запись повтора одной транзакцией для всех API-реплик.""" chat_uuid = uuid.UUID(chat_id) sender_uuid = uuid.UUID(sender_id) lock_scope = f'{sender_uuid}:POST:/api/v1/chats/{chat_uuid}/messages:{idempotency_key}' async with self.pool.acquire() as connection: async with connection.transaction(): # Advisory lock общий для всех API и сериализует запросы с одинаковым ключом. await connection.fetchval( 'SELECT pg_advisory_xact_lock(hashtextextended($1, 0))', lock_scope, ) existing = await connection.fetchrow( 'SELECT k.request_hash, m.* FROM message_idempotency k ' 'JOIN messages m ON m.id = k.message_id ' 'WHERE k.user_id = $1 AND k.chat_id = $2 AND k.idempotency_key = $3 ' "AND k.created_at > now() - interval '24 hours'", sender_uuid, chat_uuid, idempotency_key, ) if existing is not None: if bytes(existing['request_hash']) != request_hash: raise ApiError(409, 'Idempotency-Key was already used with another request') return _message(existing) # После 24 часов ключ можно использовать снова; удаляем старые записи партиями. await connection.execute( 'DELETE FROM message_idempotency ' 'WHERE user_id = $1 AND chat_id = $2 AND idempotency_key = $3', sender_uuid, chat_uuid, idempotency_key, ) await connection.execute( "DELETE FROM message_idempotency WHERE ctid IN (" 'SELECT ctid FROM message_idempotency ' "WHERE created_at <= now() - interval '24 hours' " 'ORDER BY created_at LIMIT 100)' ) row = await connection.fetchrow( 'INSERT INTO messages (id, chat_id, sender_id, text) ' 'VALUES ($1, $2, $3, $4) RETURNING *', uuid.uuid4(), chat_uuid, sender_uuid, text, ) await connection.execute( 'INSERT INTO message_idempotency ' '(user_id, chat_id, idempotency_key, request_hash, message_id) ' 'VALUES ($1, $2, $3, $4, $5)', sender_uuid, chat_uuid, idempotency_key, request_hash, row['id'], ) return _message(row) async def messages_page(self, chat_id: str, cursor_key, limit: int): """Прочитать одну отсортированную keyset-страницу и одну строку для проверки продолжения.""" chat_uuid = uuid.UUID(chat_id) async with self.pool.acquire() as connection: if cursor_key is None: rows = await connection.fetch( 'SELECT * FROM messages WHERE chat_id = $1 ' 'ORDER BY created_at, id LIMIT $2', chat_uuid, limit + 1, ) else: created_at, id_value = cursor_key rows = await connection.fetch( 'SELECT * FROM messages WHERE chat_id = $1 ' 'AND (created_at, id) > ($2, $3) ' 'ORDER BY created_at, id LIMIT $4', chat_uuid, created_at, uuid.UUID(int=id_value), limit + 1, ) has_more = len(rows) > limit return [_message(row) for row in rows[:limit]], has_more