from __future__ import annotations import json import logging import time from typing import Optional, Union import redis.asyncio as redis from redis.exceptions import RedisError from app import config logger = logging.getLogger("messenger.cache") REVOKED = "revoked" class SessionCache: def __init__(self, url: Optional[str]): self._client: Optional[redis.Redis] = None self._down_until = 0.0 if url: pool = redis.BlockingConnectionPool.from_url( url, max_connections=config.CACHE_POOL_MAX, timeout=config.CACHE_TIMEOUT, socket_timeout=config.CACHE_TIMEOUT, socket_connect_timeout=config.CACHE_TIMEOUT, decode_responses=True, ) self._client = redis.Redis(connection_pool=pool) @property def enabled(self) -> bool: return self._client is not None def _usable(self) -> bool: return self._client is not None and time.monotonic() >= self._down_until def _failed(self, op: str, exc: Exception) -> None: self._down_until = time.monotonic() + config.CACHE_RETRY_AFTER logger.warning("cache %s failed (%s); bypassing cache for %.0fs", op, type(exc).__name__, config.CACHE_RETRY_AFTER) @staticmethod def _key(token_hash: bytes) -> str: return "session:" + token_hash.hex() async def get(self, token_hash: bytes) -> Union[dict, str, None]: if not self._usable(): return None try: raw = await self._client.get(self._key(token_hash)) except (RedisError, OSError) as exc: self._failed("get", exc) return None if raw is None or raw == REVOKED: return raw try: return json.loads(raw) except ValueError: return None async def put(self, token_hash: bytes, entry: dict, ttl_seconds: int) -> None: ttl = min(ttl_seconds, config.SESSION_CACHE_MAX_SECONDS) if ttl <= 0 or not self._usable(): return try: await self._client.set(self._key(token_hash), json.dumps(entry), ex=ttl, nx=True) except (RedisError, OSError) as exc: self._failed("set", exc) async def revoke(self, token_hash: bytes, ttl_seconds: int) -> None: if self._client is None: return try: await self._client.set(self._key(token_hash), REVOKED, ex=max(1, min(ttl_seconds, config.SESSION_CACHE_MAX_SECONDS))) except (RedisError, OSError) as exc: self._failed("revoke", exc) async def ping(self) -> bool: if self._client is None: return False try: return bool(await self._client.ping()) except (RedisError, OSError): return False async def close(self) -> None: if self._client is not None: await self._client.aclose()