Download src/core/cache/redis_manager.py from anaselamr/yaz: direct link, hf CLI and curl.
- Browser
- Download file 19.4 kB
-
https://huggingface.co/spaces/anaselamr/yaz/resolve/main/src/core/cache/redis_manager.py
- Command line
-
hf download hf://spaces/anaselamr/yaz/src/core/cache/redis_manager.py
-
curl -L -o redis_manager.py https://huggingface.co/spaces/anaselamr/yaz/resolve/main/src/core/cache/redis_manager.py
19.4 kB
| """ | |
| YAZ Care Platform - Redis Cache Manager | |
| High-performance caching system with HIPAA compliance and multi-strategy support | |
| """ | |
| import asyncio | |
| import hashlib | |
| import json | |
| import os | |
| import pickle | |
| from dataclasses import dataclass | |
| from datetime import datetime, timedelta | |
| from enum import Enum | |
| from typing import Any, Callable, Dict, List, Optional, Union | |
| import structlog | |
| try: | |
| import redis | |
| import redis.asyncio as aioredis | |
| REDIS_AVAILABLE = True | |
| except ImportError: | |
| REDIS_AVAILABLE = False | |
| logger = structlog.get_logger(__name__) | |
| class CacheStrategy(Enum): | |
| """Cache eviction strategies""" | |
| LRU = "lru" # Least Recently Used | |
| LFU = "lfu" # Least Frequently Used | |
| TTL = "ttl" # Time To Live only | |
| HYBRID = "hybrid" # Combination of LRU + TTL | |
| class CacheKeyType(Enum): | |
| """Cache key types for healthcare data classification""" | |
| PHI = "phi" # Protected Health Information - encrypted | |
| CLINICAL = "clinical" # Clinical data - encrypted | |
| ANALYTICS = "analytics" # Analytics data - can be cached longer | |
| CONFIG = "config" # Configuration data | |
| SESSION = "session" # Session data | |
| API_RESPONSE = "api" # API response caching | |
| class CacheMetrics: | |
| """Cache performance metrics""" | |
| hits: int = 0 | |
| misses: int = 0 | |
| sets: int = 0 | |
| deletes: int = 0 | |
| expires: int = 0 | |
| memory_used: int = 0 | |
| def hit_ratio(self) -> float: | |
| total = self.hits + self.misses | |
| return (self.hits / total) if total > 0 else 0.0 | |
| class RedisManager: | |
| """ | |
| Advanced Redis cache manager with healthcare-specific features | |
| Features: Encryption, TTL management, metrics tracking, HIPAA compliance | |
| """ | |
| def __init__(self): | |
| self.redis_url = os.getenv("REDIS_URL", "redis://localhost:6379/0") | |
| self.enabled = os.getenv("CACHE_ENABLED", "true").lower() == "true" | |
| self.strategy = CacheStrategy(os.getenv("CACHE_STRATEGY", "hybrid")) | |
| self.default_ttl = int(os.getenv("CACHE_TTL_SECONDS", "300")) # 5 minutes | |
| self.max_size = int(os.getenv("CACHE_MAX_SIZE", "1000")) | |
| # Healthcare compliance | |
| self.phi_encryption = os.getenv("PHI_ENCRYPTION_ENABLED", "true").lower() == "true" | |
| self.audit_enabled = os.getenv("CACHE_AUDIT_ENABLED", "true").lower() == "true" | |
| # Connection pools | |
| self.redis_client = None | |
| self.connection_pool = None | |
| # Metrics tracking | |
| self.metrics = CacheMetrics() | |
| # Encryption key for PHI data — fail-fast in production | |
| self.encryption_key = os.getenv("CACHE_ENCRYPTION_KEY", "") | |
| if not self.encryption_key: | |
| env = os.getenv("ENVIRONMENT", "development") | |
| if env in ("production", "staging"): | |
| raise RuntimeError( | |
| "CACHE_ENCRYPTION_KEY must be set in production/staging. " | |
| 'Generate with: python -c "import secrets; print(secrets.token_urlsafe(32))"' | |
| ) | |
| self.encryption_key = "dev-only-insecure-key" | |
| logger.warning("Using insecure default CACHE_ENCRYPTION_KEY — development only") | |
| async def initialize(self) -> bool: | |
| """Initialize Redis connection""" | |
| if not REDIS_AVAILABLE: | |
| logger.warning("Redis not available, caching disabled") | |
| self.enabled = False | |
| return False | |
| if not self.enabled: | |
| logger.info("Caching disabled by configuration") | |
| return True | |
| try: | |
| import asyncio | |
| # Create connection pool with bounded timeouts (never hang startup) | |
| self.connection_pool = aioredis.ConnectionPool.from_url( | |
| self.redis_url, | |
| max_connections=20, | |
| retry_on_timeout=False, | |
| socket_connect_timeout=3, | |
| socket_timeout=3, | |
| health_check_interval=30, | |
| ) | |
| # Create Redis client | |
| self.redis_client = aioredis.Redis(connection_pool=self.connection_pool) | |
| # Test connection with hard timeout so startup never hangs | |
| await asyncio.wait_for(self.redis_client.ping(), timeout=5.0) | |
| # Setup cache configuration | |
| await self._configure_redis() | |
| logger.info(f"✅ Redis cache initialized - Strategy: {self.strategy.value}") | |
| return True | |
| except Exception as e: | |
| logger.error(f"❌ Redis initialization failed: {e}") | |
| self.enabled = False | |
| return False | |
| async def _configure_redis(self): | |
| """Configure Redis for optimal performance""" | |
| try: | |
| # Set memory policy based on strategy | |
| if self.strategy == CacheStrategy.LRU: | |
| await self.redis_client.config_set("maxmemory-policy", "allkeys-lru") # type: ignore[union-attr] | |
| elif self.strategy == CacheStrategy.LFU: | |
| await self.redis_client.config_set("maxmemory-policy", "allkeys-lfu") # type: ignore[union-attr] | |
| else: # TTL or HYBRID | |
| await self.redis_client.config_set("maxmemory-policy", "volatile-ttl") # type: ignore[union-attr] | |
| # Set max memory if specified | |
| max_memory = os.getenv("REDIS_MAX_MEMORY") | |
| if max_memory: | |
| await self.redis_client.config_set("maxmemory", max_memory) # type: ignore[union-attr] | |
| except Exception as e: | |
| logger.warning(f"Redis configuration warning: {e}") | |
| def _generate_key(self, key: str, key_type: CacheKeyType, tenant_id: str = None) -> str: # type: ignore[arg-type, assignment] | |
| """Generate cache key with tenant isolation and type classification""" | |
| # Add tenant isolation for multi-tenant deployments | |
| if tenant_id: | |
| key = f"tenant:{tenant_id}:{key}" | |
| # Add key type prefix for organization | |
| key = f"{key_type.value}:{key}" | |
| # Add platform prefix | |
| key = f"yaz:{key}" | |
| # Hash long keys to avoid Redis key size limits | |
| if len(key) > 250: | |
| key_hash = hashlib.sha256(key.encode()).hexdigest()[:16] | |
| key = f"yaz:hash:{key_hash}" | |
| return key | |
| def _encrypt_data(self, data: Any) -> bytes: | |
| """Encrypt sensitive healthcare data""" | |
| if not self.phi_encryption: | |
| return pickle.dumps(data) | |
| # Simple encryption for demo - use proper encryption in production | |
| try: | |
| from cryptography.fernet import Fernet | |
| # In production, use a proper key derivation function | |
| key = hashlib.sha256(self.encryption_key.encode()).digest() | |
| key_b64 = base64.urlsafe_b64encode(key) # type: ignore[name-defined, index, return-value, var-annotated] | |
| cipher = Fernet(key_b64) | |
| serialized = pickle.dumps(data) | |
| encrypted = cipher.encrypt(serialized) | |
| return encrypted | |
| except ImportError: | |
| # Fallback to simple obfuscation if cryptography not available | |
| serialized = pickle.dumps(data) | |
| return base64.b64encode(serialized) # type: ignore[name-defined, index, return-value, var-annotated] | |
| def _decrypt_data(self, encrypted_data: bytes) -> Any: | |
| """Decrypt sensitive healthcare data""" | |
| if not self.phi_encryption: | |
| return pickle.loads(encrypted_data) | |
| try: | |
| import base64 | |
| from cryptography.fernet import Fernet | |
| key = hashlib.sha256(self.encryption_key.encode()).digest() | |
| key_b64 = base64.urlsafe_b64encode(key) | |
| cipher = Fernet(key_b64) | |
| decrypted = cipher.decrypt(encrypted_data) | |
| return pickle.loads(decrypted) | |
| except ImportError: | |
| import base64 | |
| # Fallback decryption | |
| decoded = base64.b64decode(encrypted_data) | |
| return pickle.loads(decoded) | |
| async def set( | |
| self, | |
| key: str, | |
| value: Any, | |
| ttl: int | None = None, | |
| key_type: CacheKeyType = CacheKeyType.API_RESPONSE, | |
| tenant_id: str | None = None, | |
| ) -> bool: | |
| """Set cache value with encryption for healthcare data""" | |
| if not self.enabled or not self.redis_client: | |
| return False | |
| try: | |
| cache_key = self._generate_key(key, key_type, tenant_id) # type: ignore[arg-type, assignment] | |
| # Encrypt sensitive data types | |
| if key_type in [CacheKeyType.PHI, CacheKeyType.CLINICAL]: | |
| serialized_value = self._encrypt_data(value) | |
| else: | |
| serialized_value = pickle.dumps(value) | |
| # Set TTL based on data type and configuration | |
| if ttl is None: | |
| if key_type == CacheKeyType.PHI: | |
| ttl = 300 # 5 minutes for PHI | |
| elif key_type == CacheKeyType.SESSION: | |
| ttl = 3600 # 1 hour for sessions | |
| else: | |
| ttl = self.default_ttl | |
| # Store in Redis | |
| await self.redis_client.setex(cache_key, ttl, serialized_value) | |
| # Update metrics | |
| self.metrics.sets += 1 | |
| # Audit logging for healthcare compliance | |
| if self.audit_enabled and key_type in [CacheKeyType.PHI, CacheKeyType.CLINICAL]: | |
| await self._audit_log("cache_set", cache_key, {"ttl": ttl, "type": key_type.value}) | |
| return True | |
| except Exception as e: | |
| logger.error(f"Cache set failed for key {key}: {e}") | |
| return False | |
| async def get( | |
| self, | |
| key: str, | |
| key_type: CacheKeyType = CacheKeyType.API_RESPONSE, | |
| tenant_id: str | None = None, | |
| ) -> Any | None: | |
| """Get cache value with decryption for healthcare data""" | |
| if not self.enabled or not self.redis_client: | |
| return None | |
| try: | |
| cache_key = self._generate_key(key, key_type, tenant_id) # type: ignore[arg-type, assignment] | |
| # Get from Redis | |
| cached_value = await self.redis_client.get(cache_key) | |
| if cached_value is None: | |
| self.metrics.misses += 1 | |
| return None | |
| # Decrypt if necessary | |
| if key_type in [CacheKeyType.PHI, CacheKeyType.CLINICAL]: | |
| value = self._decrypt_data(cached_value) | |
| else: | |
| value = pickle.loads(cached_value) | |
| # Update metrics | |
| self.metrics.hits += 1 | |
| # Audit logging for healthcare compliance | |
| if self.audit_enabled and key_type in [CacheKeyType.PHI, CacheKeyType.CLINICAL]: | |
| await self._audit_log("cache_get", cache_key, {"type": key_type.value}) | |
| return value | |
| except Exception as e: | |
| logger.error(f"Cache get failed for key {key}: {e}") | |
| self.metrics.misses += 1 | |
| return None | |
| async def delete( | |
| self, | |
| key: str, | |
| key_type: CacheKeyType = CacheKeyType.API_RESPONSE, | |
| tenant_id: str | None = None, | |
| ) -> bool: | |
| """Delete cache entry""" | |
| if not self.enabled or not self.redis_client: | |
| return False | |
| try: | |
| cache_key = self._generate_key(key, key_type, tenant_id) # type: ignore[arg-type, assignment] | |
| result = await self.redis_client.delete(cache_key) | |
| if result: | |
| self.metrics.deletes += 1 | |
| # Audit logging for healthcare compliance | |
| if self.audit_enabled and key_type in [CacheKeyType.PHI, CacheKeyType.CLINICAL]: | |
| await self._audit_log("cache_delete", cache_key, {"type": key_type.value}) | |
| return bool(result) | |
| except Exception as e: | |
| logger.error(f"Cache delete failed for key {key}: {e}") | |
| return False | |
| async def clear_tenant_cache(self, tenant_id: str) -> bool: | |
| """Clear all cache entries for a specific tenant""" | |
| if not self.enabled or not self.redis_client: | |
| return False | |
| try: | |
| pattern = f"yaz:*:tenant:{tenant_id}:*" | |
| keys = [] | |
| async for key in self.redis_client.scan_iter(match=pattern): | |
| keys.append(key) | |
| if keys: | |
| deleted = await self.redis_client.delete(*keys) | |
| logger.info(f"Cleared {deleted} cache entries for tenant {tenant_id}") | |
| return True | |
| return True | |
| except Exception as e: | |
| logger.error(f"Failed to clear tenant cache: {e}") | |
| return False | |
| async def get_metrics(self) -> dict[str, Any]: | |
| """Get comprehensive cache metrics""" | |
| if not self.enabled or not self.redis_client: | |
| return {"enabled": False, "metrics": self.metrics.__dict__} | |
| try: | |
| # Redis info | |
| info = await self.redis_client.info() | |
| # Memory usage | |
| memory_info = { | |
| "used_memory": info.get("used_memory", 0), | |
| "used_memory_human": info.get("used_memory_human", "0B"), | |
| "used_memory_peak": info.get("used_memory_peak", 0), | |
| "maxmemory": info.get("maxmemory", 0), | |
| } | |
| # Connection info | |
| connection_info = { | |
| "connected_clients": info.get("connected_clients", 0), | |
| "total_commands_processed": info.get("total_commands_processed", 0), | |
| } | |
| return { | |
| "enabled": True, | |
| "strategy": self.strategy.value, | |
| "hit_ratio": self.metrics.hit_ratio, | |
| "metrics": self.metrics.__dict__, | |
| "memory": memory_info, | |
| "connections": connection_info, | |
| "redis_version": info.get("redis_version", "unknown"), | |
| } | |
| except Exception as e: | |
| logger.error(f"Failed to get cache metrics: {e}") | |
| return {"enabled": True, "error": str(e), "metrics": self.metrics.__dict__} | |
| async def health_check(self) -> dict[str, Any]: | |
| """Cache system health check""" | |
| if not self.enabled: | |
| return {"status": "disabled", "enabled": False} | |
| if not self.redis_client: | |
| return {"status": "error", "message": "Redis client not initialized"} | |
| try: | |
| # Test basic operations | |
| test_key = "health_check_test" | |
| test_value = {"timestamp": datetime.now().isoformat(), "test": True} | |
| # Set test value | |
| await self.redis_client.setex(test_key, 10, pickle.dumps(test_value)) | |
| # Get test value | |
| cached = await self.redis_client.get(test_key) | |
| if cached: | |
| retrieved = pickle.loads(cached) | |
| # Clean up | |
| await self.redis_client.delete(test_key) | |
| # Check memory usage | |
| info = await self.redis_client.info() | |
| memory_usage_percent = 0 | |
| if info.get("maxmemory", 0) > 0: | |
| memory_usage_percent = (info.get("used_memory", 0) / info.get("maxmemory", 1)) * 100 | |
| return { | |
| "status": "healthy", | |
| "enabled": True, | |
| "hit_ratio": self.metrics.hit_ratio, | |
| "memory_usage_percent": memory_usage_percent, | |
| "connected_clients": info.get("connected_clients", 0), | |
| "redis_version": info.get("redis_version", "unknown"), | |
| } | |
| except Exception as e: | |
| return {"status": "error", "enabled": True, "message": str(e)} | |
| async def _audit_log(self, action: str, key: str, metadata: dict[str, Any]): | |
| """Log cache operations for HIPAA compliance""" | |
| if not self.audit_enabled: | |
| return | |
| try: | |
| # Simple audit logging - in production, use proper audit system | |
| audit_entry = { | |
| "timestamp": datetime.now().isoformat(), | |
| "action": action, | |
| "cache_key": key, | |
| "metadata": metadata, | |
| "source": "redis_cache_manager", | |
| } | |
| # Log to application logs | |
| logger.info(f"CACHE_AUDIT: {json.dumps(audit_entry)}") | |
| except Exception as e: | |
| logger.error(f"Cache audit logging failed: {e}") | |
| async def close(self): | |
| """Close Redis connections""" | |
| if self.redis_client: | |
| await self.redis_client.close() | |
| if self.connection_pool: | |
| await self.connection_pool.disconnect() | |
| logger.info("Redis connections closed") | |
| # Global cache manager instance | |
| cache_manager = RedisManager() | |
| # Convenience functions for common operations | |
| async def cache_set(key: str, value: Any, ttl: int | None = None, **kwargs): | |
| """Convenience function to set cache value""" | |
| return await cache_manager.set(key, value, ttl, **kwargs) | |
| async def cache_get(key: str, **kwargs): | |
| """Convenience function to get cache value""" | |
| return await cache_manager.get(key, **kwargs) | |
| async def cache_delete(key: str, **kwargs): | |
| """Convenience function to delete cache value""" | |
| return await cache_manager.delete(key, **kwargs) | |
| # Cache decorator for functions | |
| def cached( | |
| ttl: int | None = None, | |
| key_type: CacheKeyType = CacheKeyType.API_RESPONSE, | |
| key_prefix: str = "func", | |
| ): | |
| """Decorator to cache function results""" | |
| def decorator(func: Callable): | |
| async def async_wrapper(*args, **kwargs): | |
| # Generate cache key from function name and arguments | |
| key_parts = [key_prefix, func.__name__] | |
| if args: | |
| key_parts.append(str(hash(str(args)))) | |
| if kwargs: | |
| key_parts.append(str(hash(str(sorted(kwargs.items()))))) | |
| cache_key = ":".join(key_parts) | |
| # Try to get from cache | |
| cached_result = await cache_manager.get(cache_key, key_type) | |
| if cached_result is not None: | |
| return cached_result | |
| # Execute function and cache result | |
| result = await func(*args, **kwargs) | |
| await cache_manager.set(cache_key, result, ttl, key_type) | |
| return result | |
| def sync_wrapper(*args, **kwargs): | |
| """Sync wrapper that handles event loop safely""" | |
| try: | |
| loop = asyncio.get_running_loop() | |
| # If we're in an async context, we shouldn't use asyncio.run | |
| # Instead, schedule it properly or raise error | |
| import concurrent.futures | |
| with concurrent.futures.ThreadPoolExecutor() as pool: | |
| future = pool.submit(asyncio.run, async_wrapper(*args, **kwargs)) | |
| return future.result(timeout=30.0) | |
| except RuntimeError: | |
| # No running loop - safe to use asyncio.run | |
| return asyncio.run(async_wrapper(*args, **kwargs)) | |
| return async_wrapper if asyncio.iscoroutinefunction(func) else sync_wrapper | |
| return decorator | |
| # Initialize cache system | |
| async def init_cache(): | |
| """Initialize cache system""" | |
| return await cache_manager.initialize() | |
| # Export main components | |
| __all__ = [ | |
| "RedisManager", | |
| "CacheStrategy", | |
| "CacheKeyType", | |
| "CacheMetrics", | |
| "cache_manager", | |
| "cache_set", | |
| "cache_get", | |
| "cache_delete", | |
| "cached", | |
| "init_cache", | |
| ] | |