Spaces:
Running
Running
Download src/services/cache.py from reputeradar/ioc-core: direct link, hf CLI and curl.
- Browser
- Download file 5.12 kB
-
https://huggingface.co/spaces/reputeradar/ioc-core/resolve/main/src/services/cache.py
- Command line
-
hf download hf://spaces/reputeradar/ioc-core/src/services/cache.py
-
curl -L -o cache.py https://huggingface.co/spaces/reputeradar/ioc-core/resolve/main/src/services/cache.py
5.12 kB
| """Redis cache service for API response caching.""" | |
| import json | |
| import logging | |
| import redis | |
| from src.config import settings | |
| logger = logging.getLogger(__name__) | |
| # Default TTL: 48 hours (in seconds) | |
| DEFAULT_TTL = 48 * 60 * 60 # 172800 seconds | |
| class CacheService: | |
| """Redis-based caching service for API responses.""" | |
| def __init__(self, redis_url: str = None): | |
| """ | |
| Initialize the cache service. | |
| Args: | |
| redis_url: Redis connection URL (defaults to localhost:6379) | |
| """ | |
| self.redis_url = redis_url or settings.REDIS_URL or "redis://localhost:6379/0" | |
| self._client = None | |
| self._connected = False | |
| def client(self) -> redis.Redis: | |
| """Get Redis client, lazily initialized.""" | |
| if self._client is None: | |
| try: | |
| self._client = redis.from_url( | |
| self.redis_url, | |
| decode_responses=True, | |
| socket_connect_timeout=2, | |
| socket_timeout=2, | |
| ) | |
| # Test connection | |
| self._client.ping() | |
| self._connected = True | |
| logger.info("Redis cache connected successfully") | |
| except (redis.ConnectionError, redis.TimeoutError) as e: | |
| logger.warning(f"Redis connection failed: {e}. Cache disabled.") | |
| self._connected = False | |
| self._client = None | |
| return self._client | |
| def is_available(self) -> bool: | |
| """Check if cache is available.""" | |
| if self._client is None: | |
| # Try to connect | |
| _ = self.client | |
| return self._connected | |
| def _make_key(self, source: str, ioc_type: str, ioc: str) -> str: | |
| """ | |
| Generate a cache key. | |
| Args: | |
| source: Source name (e.g., 'virustotal', 'abuseipdb') | |
| ioc_type: IOC type (e.g., 'ip', 'domain', 'hash') | |
| ioc: The actual IOC value | |
| Returns: | |
| Cache key string | |
| """ | |
| # Normalize IOC (lowercase, strip whitespace) | |
| normalized_ioc = ioc.lower().strip() | |
| return f"ioc:{source}:{ioc_type}:{normalized_ioc}" | |
| def get(self, source: str, ioc_type: str, ioc: str) -> dict | None: | |
| """ | |
| Get cached response for an IOC. | |
| Args: | |
| source: Source name | |
| ioc_type: IOC type | |
| ioc: IOC value | |
| Returns: | |
| Cached data dict or None if not found | |
| """ | |
| if not self.is_available: | |
| return None | |
| key = self._make_key(source, ioc_type, ioc) | |
| try: | |
| cached = self.client.get(key) | |
| if cached: | |
| logger.debug(f"Cache HIT: {key}") | |
| return json.loads(cached) | |
| logger.debug(f"Cache MISS: {key}") | |
| return None | |
| except (redis.RedisError, json.JSONDecodeError) as e: | |
| logger.warning(f"Cache get error: {e}") | |
| return None | |
| def set(self, source: str, ioc_type: str, ioc: str, data: dict, ttl: int = DEFAULT_TTL) -> bool: | |
| """ | |
| Cache a response for an IOC. | |
| Args: | |
| source: Source name | |
| ioc_type: IOC type | |
| ioc: IOC value | |
| data: Data to cache | |
| ttl: Time-to-live in seconds (default: 48 hours) | |
| Returns: | |
| True if cached successfully | |
| """ | |
| if not self.is_available: | |
| return False | |
| key = self._make_key(source, ioc_type, ioc) | |
| try: | |
| self.client.setex(key, ttl, json.dumps(data)) | |
| logger.debug(f"Cache SET: {key} (TTL: {ttl}s)") | |
| return True | |
| except redis.RedisError as e: | |
| logger.warning(f"Cache set error: {e}") | |
| return False | |
| def delete(self, source: str, ioc_type: str, ioc: str) -> bool: | |
| """Delete a cached entry.""" | |
| if not self.is_available: | |
| return False | |
| key = self._make_key(source, ioc_type, ioc) | |
| try: | |
| self.client.delete(key) | |
| return True | |
| except redis.RedisError: | |
| return False | |
| def clear_source(self, source: str) -> int: | |
| """Clear all cache entries for a source.""" | |
| if not self.is_available: | |
| return 0 | |
| try: | |
| keys = self.client.keys(f"ioc:{source}:*") | |
| if keys: | |
| return self.client.delete(*keys) | |
| return 0 | |
| except redis.RedisError: | |
| return 0 | |
| def get_stats(self) -> dict: | |
| """Get cache statistics.""" | |
| if not self.is_available: | |
| return {"available": False} | |
| try: | |
| info = self.client.info("stats") | |
| dbsize = self.client.dbsize() | |
| return { | |
| "available": True, | |
| "total_keys": dbsize, | |
| "hits": info.get("keyspace_hits", 0), | |
| "misses": info.get("keyspace_misses", 0), | |
| } | |
| except redis.RedisError: | |
| return {"available": False} | |
| # Global cache instance | |
| cache = CacheService() | |