import json from typing import Any, Optional, Union import logging from app.core.redis import get_redis from redis.exceptions import ConnectionError, TimeoutError logger = logging.getLogger(__name__) class CacheService: def __init__(self): self.use_redis = True self._memory_cache = {} # Fallback async def get(self, key: str) -> Optional[Any]: if self.use_redis: try: redis = get_redis() val = await redis.get(key) if val: try: return json.loads(val) except json.JSONDecodeError: return val return None except (ConnectionError, TimeoutError, OSError): logger.warning("Redis connection failed. Switch to memory fallback (temporary).") self.use_redis = False return self._memory_cache.get(key) except Exception as e: logger.error(f"Cache get error: {e}") return None else: return self._memory_cache.get(key) async def set(self, key: str, value: Any, ttl: int = 3600): """ Set key with TTL (seconds). Default 1 hour. """ # Serialize if dict/list str_val = value if isinstance(value, (dict, list)): str_val = json.dumps(value, default=str) # handle datetimes properly in real implementation if self.use_redis: try: redis = get_redis() await redis.set(key, str_val, ex=ttl) except (ConnectionError, TimeoutError, OSError): self.use_redis = False self._memory_cache[key] = value # No TTL support in simple dict fallback except Exception as e: logger.error(f"Cache set error: {e}") else: self._memory_cache[key] = value async def delete(self, key: str): if self.use_redis: try: redis = get_redis() await redis.delete(key) except Exception: pass if key in self._memory_cache: del self._memory_cache[key] async def clear_prefix(self, prefix: str): """Clear all keys starting with prefix.""" if self.use_redis: try: redis = get_redis() keys = await redis.keys(f"{prefix}*") if keys: await redis.delete(*keys) except Exception as e: logger.error(f"Cache clear error: {e}") cache_service = CacheService()