from contextlib import contextmanager from datetime import datetime import logging import hashlib import json import secrets from uuid import UUID, uuid4 import psycopg from psycopg.rows import dict_row from psycopg.types.json import Jsonb from psycopg_pool import ConnectionPool, PoolTimeout, TooManyRequests from .config import idempotency_ttl, secret, session_ttl from .errors import ApiError, invalid, not_found from .pagination import Pagination from .security import hash_password, token_hash, unauthorized, verify_password USER_FIELDS = "id, username, display_name, created_at" CHAT_FIELDS = """ c.id, c.title, c.created_at, ARRAY(SELECT cm.user_id FROM chat_members cm WHERE cm.chat_id=c.id ORDER BY cm.user_id) AS member_ids """ def serialize(value): if isinstance(value, UUID): return str(value) if isinstance(value, datetime): return value.isoformat(timespec="microseconds").replace("+00:00", "Z") if isinstance(value, dict): return {key: serialize(item) for key, item in value.items()} if isinstance(value, list): return [serialize(item) for item in value] return value class PostgresStore: def __init__(self): logging.getLogger("psycopg.pool").setLevel(logging.CRITICAL) self.pool = ConnectionPool( secret("DATABASE_URL_FILE"), min_size=1, max_size=10, timeout=3, max_waiting=40, open=False, check=ConnectionPool.check_connection, kwargs={"row_factory": dict_row, "connect_timeout": 3, "options": "-c timezone=UTC -c statement_timeout=5000 -c lock_timeout=2000"}, ) self.pagination = Pagination(secret("CURSOR_SECRET_FILE").encode("ascii")) self.ttl = session_ttl() self.idempotency_ttl = idempotency_ttl() def open(self): self.pool.open() def close(self): self.pool.close() @contextmanager def connection(self): try: with self.pool.connection() as connection: yield connection except (psycopg.OperationalError, psycopg.InterfaceError, PoolTimeout, TooManyRequests, psycopg.errors.QueryCanceled, psycopg.errors.LockNotAvailable): raise ApiError(503, "unavailable", "Хранилище временно недоступно") from None def ready(self): try: with self.connection() as connection: row = connection.execute( "SELECT version FROM schema_migrations WHERE version=%s", ("002_idempotency.sql",) ).fetchone() if not row: raise ApiError(503, "unavailable", "Схема ещё не готова") except psycopg.errors.UndefinedTable: raise ApiError(503, "unavailable", "Схема ещё не готова") from None return {"status": "ok"} def create_user(self, body): password_hash = hash_password(body.password) try: with self.connection() as connection: row = connection.execute( "INSERT INTO users(id,username,display_name,password_hash) VALUES (%s,%s,%s,%s) RETURNING " + USER_FIELDS, (uuid4(), body.username, body.display_name, password_hash), ).fetchone() return serialize(row) except psycopg.errors.UniqueViolation: raise ApiError(409, "conflict", "Username уже занят") from None def create_session(self, username, password): with self.connection() as connection: row = connection.execute( "SELECT " + USER_FIELDS + ", password_hash FROM users WHERE username=%s", (username,) ).fetchone() if not verify_password(row["password_hash"] if row else None, password) or row is None: raise unauthorized() token = secrets.token_urlsafe(32) with self.connection() as connection: session = connection.execute(""" INSERT INTO sessions(token_hash,user_id,created_at,expires_at) VALUES (%s,%s,CURRENT_TIMESTAMP,CURRENT_TIMESTAMP + %s * INTERVAL '1 second') RETURNING expires_at """, (token_hash(token), row["id"], self.ttl)).fetchone() user = {key: value for key, value in row.items() if key != "password_hash"} return {"token": token, "token_type": "Bearer", "expires_at": serialize(session["expires_at"]), "user": serialize(user)} def authenticate(self, token): with self.connection() as connection: row = connection.execute(""" SELECT user_id FROM sessions WHERE token_hash=%s AND expires_at > CURRENT_TIMESTAMP """, (token_hash(token),)).fetchone() if row is None: raise unauthorized() return row["user_id"] def logout(self, token): with self.connection() as connection: result = connection.execute("DELETE FROM sessions WHERE token_hash=%s", (token_hash(token),)) if result.rowcount != 1: raise unauthorized() def user(self, user_id): with self.connection() as connection: row = connection.execute("SELECT " + USER_FIELDS + " FROM users WHERE id=%s", (user_id,)).fetchone() if not row: raise unauthorized() return serialize(row) def create_chat(self, user_id, body): members = body.member_ids if user_id not in members: raise invalid("Неверный список участников") with self.connection() as connection: found = connection.execute("SELECT id FROM users WHERE id=ANY(%s)", (members,)).fetchall() if len(found) != len(members): raise invalid("Неверный список участников") chat_id = uuid4() # чат и участники коммитятся вместе connection.execute("INSERT INTO chats(id,title) VALUES (%s,%s)", (chat_id, body.title)) with connection.cursor() as cursor: cursor.executemany( "INSERT INTO chat_members(chat_id,user_id) VALUES (%s,%s)", [(chat_id, member) for member in members], ) return serialize(self.require_chat(connection, user_id, chat_id)) def require_chat(self, connection, user_id, chat_id): row = connection.execute( "SELECT " + CHAT_FIELDS + """ FROM chats c WHERE c.id=%s AND EXISTS (SELECT 1 FROM chat_members m WHERE m.chat_id=c.id AND m.user_id=%s) """, (chat_id, user_id) ).fetchone() if row is None: raise not_found() return row def chat(self, user_id, chat_id): with self.connection() as connection: return serialize(self.require_chat(connection, user_id, chat_id)) def list_chats(self, user_id, limit, cursor): scope = "chats:" + str(user_id) after = self.pagination.decode(scope, cursor) if cursor is not None else None condition = " AND (c.created_at,c.id) > (%s,%s)" if after else "" with self.connection() as connection: rows = connection.execute( "SELECT " + CHAT_FIELDS + """ FROM chats c WHERE EXISTS (SELECT 1 FROM chat_members m WHERE m.chat_id=c.id AND m.user_id=%s)""" + condition + " ORDER BY c.created_at,c.id LIMIT %s", [user_id, *(after or ()), limit + 1], ).fetchall() return self.pagination.page(serialize(rows), scope, limit) def create_message(self, user_id, chat_id, body, key): path = f"/api/v1/chats/{chat_id}/messages" scope = (user_id, "POST", path, key) canonical = json.dumps(body.model_dump(), sort_keys=True, ensure_ascii=False, separators=(",", ":")) request_hash = hashlib.sha256(canonical.encode("utf-8")).hexdigest() lock_data = json.dumps([str(user_id), "POST", path, key], separators=(",", ":")).encode() lock_id = int.from_bytes(hashlib.sha256(lock_data).digest()[:8], "big", signed=True) with self.connection() as connection: self.require_chat(connection, user_id, chat_id) # один ключ блокируется сразу для обеих реплик connection.execute("SELECT pg_advisory_xact_lock(%s)", (lock_id,)) saved = connection.execute(""" SELECT request_hash,response_body,expires_at > clock_timestamp() AS active FROM idempotency_keys WHERE user_id=%s AND method=%s AND path=%s AND request_key=%s """, scope).fetchone() if saved and saved["active"]: if saved["request_hash"] != request_hash: raise ApiError(409, "conflict", "С этим ключом уже отправлен другой запрос") return saved["response_body"] if saved: connection.execute(""" DELETE FROM idempotency_keys WHERE user_id=%s AND method=%s AND path=%s AND request_key=%s """, scope) row = connection.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_id, user_id, body.text)).fetchone() message = serialize(row) connection.execute(""" INSERT INTO idempotency_keys (user_id,method,path,request_key,request_hash,message_id,response_status,response_body,expires_at) VALUES (%s,%s,%s,%s,%s,%s,201,%s,clock_timestamp() + %s * INTERVAL '1 second') """, (*scope, request_hash, row["id"], Jsonb(message), self.idempotency_ttl)) return message def list_messages(self, user_id, chat_id, limit, cursor): scope = "messages:" + str(chat_id) after = self.pagination.decode(scope, cursor) if cursor is not None else None condition = " AND (created_at,id) > (%s,%s)" if after else "" with self.connection() as connection: self.require_chat(connection, user_id, chat_id) rows = connection.execute( "SELECT id,chat_id,sender_id,text,created_at FROM messages WHERE chat_id=%s" + condition + " ORDER BY created_at,id LIMIT %s", [chat_id, *(after or ()), limit + 1], ).fetchall() return self.pagination.page(serialize(rows), scope, limit)