"""PostgreSQL-backed state store. All writes go through parameterised queries inside explicit transactions; reads use keyset pagination over indexed columns.""" from __future__ import annotations import datetime as dt import uuid from . import cursor as cursor_codec from . import security from .cache import SessionCache from .config import Config from .db import Database from .errors import Conflict, InvalidRequest, NotFound def utc_now(): return dt.datetime.now(dt.timezone.utc) def rfc3339(stamp): """RFC 3339 UTC with fixed microsecond precision and the Z suffix.""" return stamp.astimezone(dt.timezone.utc).isoformat(timespec='microseconds').replace('+00:00', 'Z') class Store: """PostgreSQL state: users, chats, membership, messages, sessions.""" def __init__(self, config: Config, database: Database, cache: SessionCache): self._config = config self._db = database self._cache = cache # ---------------------------------------------------------------- reads def stats(self): with self._db.cursor() as cur: cur.execute('SELECT (SELECT count(*) FROM users) AS users,' ' (SELECT count(*) FROM chats) AS chats,' ' (SELECT count(*) FROM messages) AS messages') row = cur.fetchone() return { 'users': row['users'], 'chats': row['chats'], 'messages': row['messages'], } def user(self, user_id): with self._db.cursor() as cur: cur.execute( 'SELECT id, username, display_name, created_at FROM users WHERE id = %s', (str(user_id),)) row = cur.fetchone() return self._public_user(row) if row else None def user_by_username(self, username): """Return user row including password_hash, or None.""" with self._db.cursor() as cur: cur.execute( 'SELECT id, username, password_hash, display_name, created_at FROM users ' 'WHERE username = %s', (username,)) return cur.fetchone() def users_exist(self, identifiers): if not identifiers: return True with self._db.cursor() as cur: cur.execute( 'SELECT count(*) AS c FROM users WHERE id = ANY(%s::uuid[])', ([str(i) for i in identifiers],)) row = cur.fetchone() return row['c'] == len(identifiers) # --------------------------------------------------------------- writes def create_user(self, username, display_name, password_hash): with self._db.cursor() as cur: try: cur.execute( 'INSERT INTO users (id, username, password_hash, display_name, created_at) ' 'VALUES (%s, %s, %s, %s, %s) ' 'RETURNING id, username, display_name, created_at', (str(uuid.uuid4()), username, password_hash, display_name, utc_now())) except Exception: # Unique violation on username -> conflict, rolled back by cursor context. raise Conflict('username уже занят') from None row = cur.fetchone() return self._public_user(row) def create_chat(self, title, member_ids): """Atomically create a chat and its membership. Rollback on any failure.""" identifier = str(uuid.uuid4()) stamp = utc_now() with self._db.cursor() as cur: try: cur.execute( 'INSERT INTO chats (id, title, created_at) VALUES (%s, %s, %s)', (identifier, title, stamp)) for member_id in member_ids: cur.execute( 'INSERT INTO chat_members (chat_id, user_id) VALUES (%s, %s)', (identifier, str(member_id))) except Exception: raise InvalidRequest('member_ids содержит неизвестных пользователей') from None return { 'id': identifier, 'title': title, 'member_ids': list(member_ids), 'created_at': rfc3339(stamp), } def add_message(self, chat_id, sender_id, text): identifier = str(uuid.uuid4()) stamp = utc_now() with self._db.cursor() as cur: cur.execute( 'INSERT INTO messages (id, chat_id, sender_id, text, created_at) ' 'VALUES (%s, %s, %s, %s, %s) ' 'RETURNING id, chat_id, sender_id, text, created_at', (identifier, str(chat_id), str(sender_id), text, stamp)) row = cur.fetchone() return self._public_message(row) # --------------------------------------------------------------- pages def page_messages(self, chat_id, after_key, limit): """Return (public messages, has_more) for a keyset window.""" with self._db.cursor() as cur: if after_key is None: cur.execute( 'SELECT id, chat_id, sender_id, text, created_at FROM messages ' 'WHERE chat_id = %s ' 'ORDER BY created_at, id ' 'LIMIT %s', (str(chat_id), limit + 1)) else: stamp, identifier = after_key cur.execute( 'SELECT id, chat_id, sender_id, text, created_at FROM messages ' 'WHERE chat_id = %s ' 'AND (created_at, id) > (%s, %s) ' 'ORDER BY created_at, id ' 'LIMIT %s', (str(chat_id), stamp, str(identifier), limit + 1)) rows = cur.fetchall() has_more = len(rows) > limit items = [self._public_message(dict(row)) for row in rows[:limit]] return items, has_more def page_chats(self, user_id, after_key, limit): """Return (chats visible to the user, has_more) ordered by (created_at, id).""" with self._db.cursor() as cur: if after_key is None: cur.execute( 'SELECT c.id, c.title, c.created_at FROM chats c ' 'JOIN chat_members cm ON cm.chat_id = c.id ' 'WHERE cm.user_id = %s ' 'ORDER BY c.created_at, c.id ' 'LIMIT %s', (str(user_id), limit + 1)) else: stamp, identifier = after_key cur.execute( 'SELECT c.id, c.title, c.created_at FROM chats c ' 'JOIN chat_members cm ON cm.chat_id = c.id ' 'WHERE cm.user_id = %s ' 'AND (c.created_at, c.id) > (%s, %s) ' 'ORDER BY c.created_at, c.id ' 'LIMIT %s', (str(user_id), stamp, str(identifier), limit + 1)) rows = cur.fetchall() has_more = len(rows) > limit items = [self._public_chat(dict(row)) for row in rows[:limit]] return items, has_more # ----------------------------------------------------------- projection def chat(self, chat_id): with self._db.cursor() as cur: cur.execute( 'SELECT id, title, created_at FROM chats WHERE id = %s', (str(chat_id),)) row = cur.fetchone() if row is None: return None chat = self._public_chat(dict(row)) cur.execute( 'SELECT user_id FROM chat_members WHERE chat_id = %s', (str(chat_id),)) chat['member_ids'] = [str(r['user_id']) for r in cur.fetchall()] return chat @staticmethod def is_member(chat, user_id): return str(user_id) in chat['member_ids'] @staticmethod def _public_user(row): return { 'id': str(row['id']), 'username': row['username'], 'display_name': row['display_name'], 'created_at': rfc3339(row['created_at']), } @staticmethod def _public_chat(row): return { 'id': str(row['id']), 'title': row['title'], 'member_ids': [], # filled by API when needed 'created_at': rfc3339(row['created_at']), } @staticmethod def _public_message(row): return { 'id': str(row['id']), 'chat_id': str(row['chat_id']), 'sender_id': str(row['sender_id']), 'text': row['text'], 'created_at': rfc3339(row['created_at']), } # --------------------------------------------------------------- sessions def create_session(self, token_hash, user_id, expires_at): with self._db.cursor() as cur: cur.execute( 'INSERT INTO sessions (token_hash, user_id, expires_at, created_at) ' 'VALUES (%s, %s, %s, %s)', (token_hash, str(user_id), expires_at, utc_now())) ttl = max(1, int((expires_at - utc_now()).total_seconds())) self._cache.set(token_hash, str(user_id), ttl) def get_session(self, token_hash): """Return user_id for a valid non-expired session, or None. Reads the look-aside cache first; on miss reads PostgreSQL and backfills the cache. Expired sessions found during lookup are deleted. """ cached = self._cache.get(token_hash) if cached is not None: return cached with self._db.cursor() as cur: cur.execute( 'SELECT user_id, expires_at FROM sessions WHERE token_hash = %s', (token_hash,)) row = cur.fetchone() if row is None: return None if row['expires_at'] <= utc_now(): cur.execute('DELETE FROM sessions WHERE token_hash = %s', (token_hash,)) return None user_id = str(row['user_id']) ttl = max(1, int((row['expires_at'] - utc_now()).total_seconds())) self._cache.set(token_hash, user_id, ttl) return user_id def delete_session(self, token_hash): self._cache.delete(token_hash) with self._db.cursor() as cur: cur.execute('DELETE FROM sessions WHERE token_hash = %s', (token_hash,)) def cleanup_expired_sessions(self): with self._db.cursor() as cur: cur.execute('DELETE FROM sessions WHERE expires_at <= %s', (utc_now(),))