from __future__ import annotations import logging import os from typing import Optional import redis log = logging.getLogger("messenger.cache") _client: Optional[redis.Redis] = None _failures: int = 0 _MAX_FAILURES_BEFORE_DISABLE: int = 3 def _cache_url() -> Optional[str]: return os.environ.get("CACHE_URL") def init_cache() -> None: global _client, _failures url = _cache_url() if not url: log.warning("CACHE_URL not set; running without cache") _client = None return try: client = redis.Redis.from_url( url, decode_responses=True, socket_connect_timeout=1.0, socket_timeout=1.0, ) client.ping() _client = client _failures = 0 log.info("cache connected") except Exception as exc: log.warning("cache unavailable at startup: %s; running in degraded mode", exc) _client = None def close_cache() -> None: global _client if _client is not None: try: _client.close() except Exception: pass _client = None def _note_failure() -> None: global _client, _failures _failures += 1 if _failures >= _MAX_FAILURES_BEFORE_DISABLE and _client is not None: log.warning( "cache disabled after %d consecutive failures; running in degraded mode", _failures, ) try: _client.close() except Exception: pass _client = None def _note_success() -> None: global _failures _failures = 0 def is_available() -> bool: return _client is not None def mark_revoked(token_hash: str, ttl_seconds: int) -> None: if _client is None: log.warning( "cache unavailable; revocation not recorded in Redis " "(Postgres is the source of truth, next request will 401)" ) return if ttl_seconds <= 0: return try: _client.setex(f"revoked:{token_hash}", ttl_seconds, "1") _note_success() except Exception as exc: log.warning("mark_revoked failed: %s", exc) _note_failure() def is_revoked(token_hash: str) -> bool: if _client is None: return False try: exists = _client.exists(f"revoked:{token_hash}") _note_success() return exists == 1 except Exception as exc: log.warning("is_revoked failed: %s", exc) _note_failure() return False