"""Сессии: PostgreSQL — источник истины, Redis/Valkey — read-through кэш с TTL. Политика (подробно — REPORT.md): * ключ sess:v1: хранит {user, expires_at}; TTL = min(SESSION_CACHE_TTL_SECONDS, остаток жизни сессии) — кэш никогда не переживает срок сессии; * logout: revoked_at + строка outbox в одной транзакции PostgreSQL, затем в Redis атомарно «надгробие» sess:v1:revoked: и DEL ключа. Заполнение кэша — Lua SET … только если надгробия нет, поэтому конкурентный read-through не вернёт отозванную сессию в кэш; * Redis недоступен → аутентификация идёт в PostgreSQL (fail-open только к источнику истины, не к анонимному доступу); после ошибки кэш не читается, пока фоновый цикл не проверит Redis и не дообработает outbox инвалидаций; * flush/restart Redis = холодный кэш: сессии остаются в PostgreSQL. """ from __future__ import annotations import asyncio import json import logging import time from dataclasses import dataclass from psycopg_pool import AsyncConnectionPool from redis import asyncio as aioredis from redis.exceptions import RedisError from .config import Settings log = logging.getLogger("messenger.sessions") KEY = "sess:v1:" TOMBSTONE = "sess:v1:revoked:" # KEYS[1]=session key, KEYS[2]=tombstone; ARGV[1]=value, ARGV[2]=ttl ms _SET_IF_NOT_REVOKED = """ if redis.call('EXISTS', KEYS[2]) == 1 then return 0 end redis.call('SET', KEYS[1], ARGV[1], 'PX', ARGV[2]) return 1 """ # KEYS[1]=session key, KEYS[2]=tombstone; ARGV[1]=tombstone ttl ms _INVALIDATE = """ redis.call('SET', KEYS[2], '1', 'PX', ARGV[1]) redis.call('DEL', KEYS[1]) return 1 """ @dataclass class Principal: user: dict expires_at: float # epoch seconds token_hash: bytes class SessionCache: def __init__(self, settings: Settings): self.settings = settings self.client: aioredis.Redis | None = None self._set_script = None self._invalidate_script = None # degraded=True: кэш не читаем (было исключение Redis или есть недообработанный outbox). self.degraded = True self._next_probe = 0.0 self.stats = {"hits": 0, "misses": 0, "errors": 0} if settings.cache_url: t = settings.cache_timeout_seconds self.client = aioredis.from_url( settings.cache_url, socket_timeout=t, socket_connect_timeout=t, retry_on_timeout=False, health_check_interval=0, max_connections=50, decode_responses=False) self._set_script = self.client.register_script(_SET_IF_NOT_REVOKED) self._invalidate_script = self.client.register_script(_INVALIDATE) @property def enabled(self) -> bool: return self.client is not None def _tombstone_ms(self) -> int: # Надгробие живёт дольше любой записи кэша и любого запроса в полёте. return int((self.settings.session_cache_ttl_seconds + self.settings.request_timeout_seconds + 5) * 1000) def _fail(self, op: str, exc: Exception) -> None: self.stats["errors"] += 1 if not self.degraded: log.warning("cache unavailable; falling back to PostgreSQL", extra={"op": op, "error": type(exc).__name__}) self.degraded = True self._next_probe = time.monotonic() + self.settings.cache_retry_seconds async def get(self, th: bytes) -> Principal | None: if not self.client or self.degraded: return None try: raw = await self.client.get(KEY + th.hex()) except (RedisError, OSError, asyncio.TimeoutError) as exc: self._fail("get", exc) return None if raw is None: self.stats["misses"] += 1 return None try: data = json.loads(raw) principal = Principal(user=data["user"], expires_at=float(data["exp"]), token_hash=th) except (ValueError, KeyError, TypeError): return None if principal.expires_at <= time.time(): return None self.stats["hits"] += 1 return principal async def put(self, p: Principal) -> None: if not self.client or self.degraded: return ttl_ms = int(min(self.settings.session_cache_ttl_seconds, p.expires_at - time.time()) * 1000) if ttl_ms < 1: return value = json.dumps({"user": p.user, "exp": p.expires_at}, separators=(",", ":")) try: await self._set_script(keys=[KEY + p.token_hash.hex(), TOMBSTONE + p.token_hash.hex()], args=[value, ttl_ms]) except (RedisError, OSError, asyncio.TimeoutError) as exc: self._fail("put", exc) async def invalidate(self, th: bytes) -> bool: if not self.client: return True try: await self._invalidate_script(keys=[KEY + th.hex(), TOMBSTONE + th.hex()], args=[self._tombstone_ms()]) return True except (RedisError, OSError, asyncio.TimeoutError) as exc: self._fail("invalidate", exc) return False async def ping(self) -> bool: if not self.client: return False try: return bool(await self.client.ping()) except (RedisError, OSError, asyncio.TimeoutError): return False async def drain_outbox(self, pool: AsyncConnectionPool) -> int: """Повторяет инвалидации из session_cache_invalidations. True-результат: outbox пуст.""" drained = 0 while True: async with pool.connection() as conn: rows = await (await conn.execute( "SELECT token_hash FROM session_cache_invalidations ORDER BY created_at LIMIT 500" )).fetchall() if not rows: return drained done = [] for row in rows: th = bytes(row["token_hash"]) if not await self.invalidate(th): raise ConnectionError("cache still unavailable") done.append(th) async with pool.connection() as conn: await conn.execute("DELETE FROM session_cache_invalidations WHERE token_hash = ANY(%s)", (done,)) drained += len(done) async def maintenance_loop(self, pool: AsyncConnectionPool, stop: asyncio.Event) -> None: """Возвращает кэш в работу только после успешного PING и пустого outbox.""" while not stop.is_set(): if self.client and time.monotonic() >= self._next_probe: try: if await self.ping(): drained = await self.drain_outbox(pool) if self.degraded: log.info("cache available again", extra={"replayed_invalidations": drained}) self.degraded = False else: self._fail("probe", ConnectionError("ping failed")) except ConnectionError as exc: self._fail("drain", exc) except Exception as exc: # noqa: BLE001 — БД недоступна: состояние кэша не меняем log.warning("outbox drain skipped", extra={"error": type(exc).__name__}) try: await asyncio.wait_for(stop.wait(), timeout=1.0) except asyncio.TimeoutError: pass async def close(self) -> None: if self.client: await self.client.aclose()