"""Redis session cache with TTL and graceful degradation. PostgreSQL is the source of truth for sessions. Redis is a look-aside cache: - write: session is persisted in PostgreSQL first, then copied to Redis with TTL - read: Redis first (fast); on miss, read PostgreSQL and backfill Redis - when Redis is unavailable: fall back to PostgreSQL only, never treat an anonymous request as trusted """ from __future__ import annotations import logging import redis from .config import Config logger = logging.getLogger('messenger.cache') class SessionCache: """Look-aside cache for session tokens in Redis/Valkey.""" def __init__(self, config: Config): self._config = config self._client = None self._available = False def open(self): if not self._config.cache_url: self._available = False return try: self._client = redis.Redis.from_url( self._config.cache_url, socket_connect_timeout=2, socket_timeout=2, socket_keepalive=True, health_check_interval=30, decode_responses=True, ) self._client.ping() self._available = True logger.info('cache_connected', extra={'event': 'cache_connected'}) except Exception as exc: # noqa: BLE001 - Redis is optional, degrade safely self._available = False self._client = None logger.warning('cache_unavailable', extra={ 'event': 'cache_unavailable', 'detail': 'falling back to PostgreSQL'}) def close(self): if self._client is not None: try: self._client.close() except Exception: pass self._client = None self._available = False @property def available(self): return self._available and self._client is not None def get(self, token_hash): """Return cached user_id or None (miss or unavailable).""" if not self.available: return None try: value = self._client.get('session:%s' % token_hash) return value except Exception as exc: # noqa: BLE001 logger.warning('cache_read_failed', extra={ 'event': 'cache_read_failed', 'detail': 'falling back to PostgreSQL'}) self._available = False return None def set(self, token_hash, user_id, ttl_seconds): """Cache a session with TTL. Failure is non-fatal.""" if not self.available: return try: self._client.setex('session:%s' % token_hash, ttl_seconds, user_id) except Exception as exc: # noqa: BLE001 logger.warning('cache_write_failed', extra={ 'event': 'cache_write_failed', 'detail': 'continuing without cache'}) self._available = False def delete(self, token_hash): """Remove a session from the cache (logout). Failure is non-fatal.""" if not self.available: return try: self._client.delete('session:%s' % token_hash) except Exception as exc: # noqa: BLE001 logger.warning('cache_delete_failed', extra={ 'event': 'cache_delete_failed'})