"""Async Redis cache wrapper with graceful degradation.""" from __future__ import annotations import json import hashlib from typing import Any, Optional import redis.asyncio as aioredis from app.config import settings from app.utils.logger import logger class CacheService: def __init__(self) -> None: self._client: Optional[aioredis.Redis] = None self._enabled = True async def client(self) -> Optional[aioredis.Redis]: if self._client is None and self._enabled: try: self._client = aioredis.from_url( settings.redis_url, decode_responses=True ) await self._client.ping() except Exception as e: logger.warning(f"Redis unavailable, caching disabled: {e}") self._enabled = False self._client = None return self._client @staticmethod def key(*parts: Any) -> str: raw = "|".join(str(p) for p in parts) return "rasta:" + hashlib.sha1(raw.encode()).hexdigest() async def get_json(self, key: str) -> Optional[dict]: c = await self.client() if not c: return None try: raw = await c.get(key) return json.loads(raw) if raw else None except Exception as e: logger.warning(f"Cache get failed: {e}") return None async def set_json(self, key: str, value: dict, ttl: Optional[int] = None) -> None: c = await self.client() if not c: return try: await c.set(key, json.dumps(value, default=str), ex=ttl or settings.cache_ttl_seconds) except Exception as e: logger.warning(f"Cache set failed: {e}") async def ping(self) -> bool: c = await self.client() if not c: return False try: return bool(await c.ping()) except Exception: return False cache = CacheService()