"""Valkey session cache. PostgreSQL is the source of truth for sessions. Valkey only keeps a short lived copy of "token hash -> user" to avoid a SQL lookup on every request: - key: messenger:session:, the raw token is never stored; - value TTL: min(SESSION_CACHE_TTL_SECONDS, remaining session lifetime), and expires_at is checked again on every read; - logout writes a "revoked" tombstone (SET ... EX, overwrite), while cache population uses SET ... NX, so a concurrent request cannot resurrect a revoked session in the cache; - any Valkey error or timeout is a cache miss: requests go to PostgreSQL and the cache is skipped for CACHE_RETRY_AFTER_SECONDS. After such an error, and on every API process start, the cache is flushed before its next use, because an invalidation may have been lost while Valkey was unreachable (also by a previous API process). """ from __future__ import annotations import asyncio import json import logging import math import time from datetime import datetime, timezone from typing import Any from uuid import UUID from redis.asyncio import ConnectionPool, Redis from redis.exceptions import RedisError from app.config import settings logger = logging.getLogger("messenger.cache") KEY_PREFIX = "messenger:session:" REVOKED = "revoked" class Revoked: """Marker returned when the cache knows the session was revoked.""" REVOKED_SESSION = Revoked() def _key(token_hash: str) -> str: return KEY_PREFIX + token_hash def _serialize(user: dict[str, Any], expires_at: datetime) -> str: return json.dumps( { "id": str(user["id"]), "username": user["username"], "display_name": user["display_name"], "created_at": user["created_at"].isoformat(), "expires_at": expires_at.isoformat(), }, separators=(",", ":"), ) def _deserialize(raw: str) -> tuple[dict[str, Any], datetime]: payload = json.loads(raw) user = { "id": UUID(payload["id"]), "username": payload["username"], "display_name": payload["display_name"], "created_at": datetime.fromisoformat(payload["created_at"]), } return user, datetime.fromisoformat(payload["expires_at"]) class SessionCache: def __init__(self, url: str | None) -> None: self._client: Redis | None = None self._unavailable_until = 0.0 # A process never trusts a cache it has not flushed itself: an # earlier process may have lost an invalidation (logout while # Valkey was unreachable) and that knowledge died with it. # Cleared only after a successful FLUSHDB. self._needs_flush = True if url: pool = ConnectionPool.from_url( url, max_connections=settings.cache_max_connections, socket_timeout=settings.cache_timeout_seconds, socket_connect_timeout=settings.cache_timeout_seconds, decode_responses=True, ) self._client = Redis(connection_pool=pool) @property def enabled(self) -> bool: return self._client is not None async def _run(self, operation): """Run one cache operation; return (ok, result).""" if self._client is None: return False, None if time.monotonic() < self._unavailable_until: return False, None try: async with asyncio.timeout(settings.cache_timeout_seconds * 2): if self._needs_flush: await self._client.flushdb() self._needs_flush = False logger.warning("session cache flushed before use") return True, await operation(self._client) except (RedisError, OSError, TimeoutError) as exc: self._unavailable_until = ( time.monotonic() + settings.cache_retry_after_seconds ) self._needs_flush = True logger.warning( "session cache unavailable, falling back to PostgreSQL: %s", type(exc).__name__, ) return False, None async def get( self, token_hash: str, ) -> dict[str, Any] | Revoked | None: ok, raw = await self._run(lambda client: client.get(_key(token_hash))) if not ok or raw is None: return None if raw == REVOKED: return REVOKED_SESSION try: user, expires_at = _deserialize(raw) except (ValueError, KeyError, TypeError): return None if expires_at <= datetime.now(timezone.utc): return None return user async def put( self, token_hash: str, user: dict[str, Any], expires_at: datetime, ) -> None: remaining = (expires_at - datetime.now(timezone.utc)).total_seconds() ttl = min(settings.session_cache_ttl_seconds, math.floor(remaining)) if ttl < 1: return value = _serialize(user, expires_at) await self._run( lambda client: client.set(_key(token_hash), value, ex=ttl, nx=True) ) async def revoke(self, token_hash: str) -> None: await self._run( lambda client: client.set( _key(token_hash), REVOKED, ex=settings.session_cache_ttl_seconds, ) ) async def close(self) -> None: if self._client is not None: await self._client.aclose() session_cache = SessionCache(settings.cache_url)