"""Сессии: PostgreSQL — источник истины, Valkey — read-through кэш с TTL. Политика: - создание: INSERT в PostgreSQL (COMMIT), затем SET в кэш с TTL = min(остаток жизни, SESSION_CACHE_TTL_SECONDS); - проверка: кэш -> при промахе PostgreSQL -> заполнить кэш; - logout: UPDATE revoked_at в PostgreSQL (COMMIT), затем DEL из кэша; - любой сбой Valkey: работаем только с PostgreSQL и SESSION_CACHE_TTL_SECONDS не доверяем кэшу (все записи, сделанные до сбоя, за это время гарантированно истекут — например, не удалённая при logout копия отозванной сессии). Flush/рестарт Valkey = пустой кэш, сессии не теряются. """ import json import logging import time from dataclasses import dataclass from datetime import datetime, timezone from uuid import UUID import redis.asyncio as redis from redis.exceptions import RedisError from .config import Settings from .db import Database from .security import token_hash log = logging.getLogger('messenger.sessions') @dataclass(frozen=True) class Session: user_id: UUID expires_at: datetime class SessionCache: def __init__(self, url: str | None, ttl: int, timeout: float): self.ttl = ttl self.client = redis.Redis.from_url( url, socket_timeout=timeout, socket_connect_timeout=timeout, retry_on_timeout=False, health_check_interval=30, ) if url else None self._distrust_until = 0.0 @staticmethod def key(digest: bytes) -> str: return 'session:' + digest.hex() def usable(self) -> bool: return self.client is not None and time.monotonic() >= self._distrust_until def _failed(self, op: str) -> None: # Не знаем, что успело/не успело записаться: перестаём читать кэш на один максимальный TTL. self._distrust_until = time.monotonic() + self.ttl log.warning('valkey %s failed; bypassing cache for %ss', op, self.ttl) async def get(self, digest: bytes) -> Session | None: if not self.usable(): return None try: raw = await self.client.get(self.key(digest)) except (RedisError, OSError): self._failed('get') return None if raw is None: return None data = json.loads(raw) return Session(UUID(data['u']), datetime.fromtimestamp(data['e'], timezone.utc)) async def put(self, digest: bytes, session: Session) -> None: if not self.usable(): return remaining = int((session.expires_at - datetime.now(timezone.utc)).total_seconds()) ttl = min(self.ttl, remaining) if ttl <= 0: return value = json.dumps({'u': str(session.user_id), 'e': session.expires_at.timestamp()}) try: await self.client.set(self.key(digest), value, ex=ttl) except (RedisError, OSError): self._failed('set') async def delete(self, digest: bytes) -> None: if self.client is None: return try: await self.client.delete(self.key(digest)) except (RedisError, OSError): self._failed('delete') async def close(self) -> None: if self.client is not None: await self.client.aclose() class SessionStore: def __init__(self, settings: Settings, db: Database): self.ttl = settings.session_ttl self.db = db self.cache = SessionCache(settings.cache_url, settings.session_cache_ttl, settings.cache_timeout) async def create(self, user_id: UUID, token: str) -> Session: digest = token_hash(token) async with self.db.connection() as conn: # Время берём из БД, чтобы срок не зависел от часов конкретной реплики API. expires_at = await conn.fetchval( 'INSERT INTO sessions (token_hash, user_id, expires_at) ' 'VALUES ($1, $2, clock_timestamp() + make_interval(secs => $3)) RETURNING expires_at', digest, user_id, self.ttl, ) session = Session(user_id, expires_at) await self.cache.put(digest, session) return session async def resolve(self, token: str) -> Session | None: digest = token_hash(token) now = datetime.now(timezone.utc) cached = await self.cache.get(digest) if cached is not None and cached.expires_at > now: return cached async with self.db.connection() as conn: row = await conn.fetchrow( 'SELECT user_id, expires_at FROM sessions ' 'WHERE token_hash = $1 AND revoked_at IS NULL AND expires_at > clock_timestamp()', digest, ) if row is None: return None session = Session(row['user_id'], row['expires_at']) await self.cache.put(digest, session) return session async def revoke(self, token: str) -> bool: digest = token_hash(token) async with self.db.connection() as conn: status = await conn.execute( 'UPDATE sessions SET revoked_at = clock_timestamp() ' 'WHERE token_hash = $1 AND revoked_at IS NULL AND expires_at > clock_timestamp()', digest, ) # Инвалидация кэша строго после COMMIT в источнике истины. await self.cache.delete(digest) return status == 'UPDATE 1' async def purge_expired(self) -> int: async with self.db.connection() as conn: status = await conn.execute( "DELETE FROM sessions WHERE expires_at < clock_timestamp() - interval '1 day'") return int(status.split()[-1])