"""Redis TTL cache for active sessions; PostgreSQL remains authoritative.""" import os import socket from urllib.parse import urlparse from redis import Redis from redis.backoff import NoBackoff from redis.exceptions import RedisError from redis.retry import Retry CACHE_URL = os.getenv("CACHE_URL", "redis://redis:6379/0") _cache_address = urlparse(CACHE_URL) _cache_host = _cache_address.hostname or "redis" _cache_port = _cache_address.port or (6380 if _cache_address.scheme == "rediss" else 6379) try: _cache_ips = tuple(dict.fromkeys(item[4][0] for item in socket.getaddrinfo( _cache_host, _cache_port, type=socket.SOCK_STREAM))) except OSError: _cache_ips = (_cache_host,) client = Redis.from_url(CACHE_URL, decode_responses=True, socket_connect_timeout=0.2, socket_timeout=0.2, health_check_interval=15, retry=Retry(NoBackoff(), 0)) class CacheUnavailable(Exception): """The required session cache cannot be reached within its short timeout.""" def _check_port(): # Fail fast when the Redis container is stopped. redis-py may otherwise # spend several seconds cycling through connection retries on Docker DNS. try: for address in _cache_ips: try: with socket.create_connection((address, _cache_port), timeout=0.2): return except OSError: continue raise OSError("Redis is not accepting connections") except OSError as exc: raise CacheUnavailable from exc def get(token: str): try: _check_port() return client.get("session:" + token) except RedisError as exc: raise CacheUnavailable from exc def put(token: str, user_id: str, ttl_seconds: int): try: _check_port() client.set("session:" + token, user_id, ex=max(1, ttl_seconds)) except RedisError as exc: raise CacheUnavailable from exc def delete(token: str): try: _check_port() client.delete("session:" + token) except RedisError as exc: raise CacheUnavailable from exc def ping(): try: _check_port() return bool(client.ping()) except RedisError as exc: raise CacheUnavailable from exc