Download src/core/cache/service.py from anaselamr/yaz: direct link, hf CLI and curl.
- Browser
- Download file 20.4 kB
-
https://huggingface.co/spaces/anaselamr/yaz/resolve/main/src/core/cache/service.py
- Command line
-
hf download hf://spaces/anaselamr/yaz/src/core/cache/service.py
-
curl -L -o service.py https://huggingface.co/spaces/anaselamr/yaz/resolve/main/src/core/cache/service.py
20.4 kB
| """ | |
| YAZ Care Platform - Multi-Tier Cache Service | |
| Sprint 30 Task 30.4 - Enterprise caching with memory + Redis tiers | |
| Features: | |
| - Two-tier caching (L1: Memory, L2: Redis) | |
| - Namespace-based TTL configuration | |
| - Automatic cache warmup on startup | |
| - Write-through and write-behind strategies | |
| - Cache invalidation patterns | |
| - Prometheus metrics integration | |
| - HIPAA-compliant PHI handling | |
| """ | |
| import hashlib | |
| import json | |
| import os | |
| import pickle | |
| import time | |
| from collections import OrderedDict | |
| from dataclasses import dataclass, field | |
| from datetime import datetime, timedelta | |
| from enum import Enum | |
| from functools import wraps | |
| from threading import Lock | |
| from typing import Any, Callable, Dict, List, Optional, Set, Union | |
| import structlog | |
| try: | |
| import redis | |
| REDIS_AVAILABLE = True | |
| except ImportError: | |
| REDIS_AVAILABLE = False | |
| redis = None # type: ignore[arg-type, assignment] | |
| from prometheus_client import Counter, Gauge, Histogram | |
| logger = structlog.get_logger(__name__) | |
| # ============================================================================= | |
| # PROMETHEUS METRICS | |
| # ============================================================================= | |
| cache_hits = Counter("cache_hits_total", "Total cache hits", ["tier", "namespace"]) | |
| cache_misses = Counter("cache_misses_total", "Total cache misses", ["tier", "namespace"]) | |
| cache_operations = Counter( | |
| "cache_operations_total", "Total cache operations", ["operation", "tier", "namespace"] | |
| ) | |
| cache_latency = Histogram( | |
| "cache_operation_latency_seconds", | |
| "Cache operation latency", | |
| ["operation", "tier"], | |
| buckets=(0.001, 0.005, 0.01, 0.025, 0.05, 0.1, 0.25, 0.5, 1.0), | |
| ) | |
| cache_memory_usage = Gauge("cache_memory_usage_bytes", "Cache memory usage in bytes", ["tier"]) | |
| cache_size = Gauge("cache_size_keys", "Number of keys in cache", ["tier", "namespace"]) | |
| # ============================================================================= | |
| # CACHE NAMESPACES & TTL CONFIGURATION | |
| # ============================================================================= | |
| class CacheNamespace(str, Enum): | |
| """Cache namespaces with different TTL strategies""" | |
| # High-frequency, short TTL | |
| SESSION = "session" # User sessions | |
| AUTH = "auth" # Authentication tokens | |
| RATE_LIMIT = "ratelimit" # Rate limiting | |
| # Medium-frequency, medium TTL | |
| USER = "user" # User profiles | |
| TENANT = "tenant" # Tenant data | |
| CONFIG = "config" # Configuration | |
| # Low-frequency, long TTL | |
| STATIC = "static" # Static data (rarely changes) | |
| REFERENCE = "reference" # Reference data | |
| METADATA = "metadata" # System metadata | |
| # Healthcare-specific | |
| PATIENT = "patient" # Patient data (PHI - encrypted) | |
| CLINICAL = "clinical" # Clinical data (PHI - encrypted) | |
| APPOINTMENT = "appointment" # Appointments | |
| LAB_RESULT = "lab" # Lab results | |
| # API-specific | |
| API_RESPONSE = "api" # API response cache | |
| QUERY_RESULT = "query" # Database query results | |
| AGGREGATE = "aggregate" # Aggregated statistics | |
| class CacheConfig: | |
| """Cache configuration for a namespace""" | |
| ttl: int # Time to live in seconds | |
| l1_enabled: bool = True # Memory cache enabled | |
| l2_enabled: bool = True # Redis cache enabled | |
| encrypt: bool = False # Encrypt data (for PHI) | |
| compress: bool = False # Compress data (for large objects) | |
| max_size: int | None = None # Max entries in L1 cache | |
| # Default TTL configuration per namespace | |
| DEFAULT_TTL_CONFIG: dict[CacheNamespace, CacheConfig] = { | |
| # Short TTL (1-5 minutes) | |
| CacheNamespace.SESSION: CacheConfig(ttl=300, max_size=1000), | |
| CacheNamespace.AUTH: CacheConfig(ttl=300, max_size=5000), | |
| CacheNamespace.RATE_LIMIT: CacheConfig(ttl=60, max_size=10000), | |
| # Medium TTL (5-30 minutes) | |
| CacheNamespace.USER: CacheConfig(ttl=900, max_size=1000), | |
| CacheNamespace.TENANT: CacheConfig(ttl=1800, max_size=100), | |
| CacheNamespace.CONFIG: CacheConfig(ttl=1800, max_size=500), | |
| CacheNamespace.APPOINTMENT: CacheConfig(ttl=600, max_size=5000), | |
| # Long TTL (1-24 hours) | |
| CacheNamespace.STATIC: CacheConfig(ttl=86400, max_size=1000), | |
| CacheNamespace.REFERENCE: CacheConfig(ttl=86400, max_size=1000), | |
| CacheNamespace.METADATA: CacheConfig(ttl=3600, max_size=500), | |
| # Healthcare data (encrypted, shorter TTL for compliance) | |
| CacheNamespace.PATIENT: CacheConfig(ttl=600, encrypt=True, max_size=2000), | |
| CacheNamespace.CLINICAL: CacheConfig(ttl=300, encrypt=True, max_size=5000), | |
| CacheNamespace.LAB_RESULT: CacheConfig(ttl=600, encrypt=True, max_size=3000), | |
| # API caching | |
| CacheNamespace.API_RESPONSE: CacheConfig(ttl=300, compress=True, max_size=5000), | |
| CacheNamespace.QUERY_RESULT: CacheConfig(ttl=300, max_size=2000), | |
| CacheNamespace.AGGREGATE: CacheConfig(ttl=3600, max_size=1000), | |
| } | |
| # ============================================================================= | |
| # L1 CACHE (MEMORY) | |
| # ============================================================================= | |
| class LRUCache: | |
| """Thread-safe LRU cache with TTL support""" | |
| def __init__(self, max_size: int = 1000): | |
| self.max_size = max_size | |
| self._cache: OrderedDict = OrderedDict() | |
| self._ttl: dict[str, float] = {} | |
| self._lock = Lock() | |
| def get(self, key: str) -> Any | None: | |
| """Get value from cache""" | |
| with self._lock: | |
| # Check if key exists and not expired | |
| if key in self._cache: | |
| if key in self._ttl and time.time() > self._ttl[key]: | |
| # Expired | |
| del self._cache[key] | |
| del self._ttl[key] | |
| return None | |
| # Move to end (most recently used) | |
| self._cache.move_to_end(key) | |
| return self._cache[key] | |
| return None | |
| def set(self, key: str, value: Any, ttl: int | None = None): | |
| """Set value in cache""" | |
| with self._lock: | |
| # Remove if exists (to update position) | |
| if key in self._cache: | |
| del self._cache[key] | |
| # Add new entry | |
| self._cache[key] = value | |
| # Set TTL if provided | |
| if ttl: | |
| self._ttl[key] = time.time() + ttl | |
| # Evict oldest if over size | |
| if len(self._cache) > self.max_size: | |
| oldest_key = next(iter(self._cache)) | |
| del self._cache[oldest_key] | |
| self._ttl.pop(oldest_key, None) | |
| def delete(self, key: str): | |
| """Delete key from cache""" | |
| with self._lock: | |
| self._cache.pop(key, None) | |
| self._ttl.pop(key, None) | |
| def clear(self): | |
| """Clear all cache""" | |
| with self._lock: | |
| self._cache.clear() | |
| self._ttl.clear() | |
| def size(self) -> int: | |
| """Get cache size""" | |
| with self._lock: | |
| return len(self._cache) | |
| def keys(self) -> list[str]: | |
| """Get all keys""" | |
| with self._lock: | |
| return list(self._cache.keys()) | |
| # ============================================================================= | |
| # MULTI-TIER CACHE SERVICE | |
| # ============================================================================= | |
| class CacheService: | |
| """ | |
| Multi-tier cache service with memory (L1) and Redis (L2) tiers | |
| Cache flow: | |
| 1. Check L1 (memory) cache | |
| 2. If miss, check L2 (Redis) cache | |
| 3. If miss, execute function and populate both tiers | |
| Features: | |
| - Automatic tier promotion (L2 → L1 on access) | |
| - Namespace-based TTL configuration | |
| - Pattern-based invalidation | |
| - Cache warming | |
| - Metrics tracking | |
| """ | |
| def __init__( | |
| self, | |
| redis_url: str | None = None, | |
| ttl_config: dict[CacheNamespace, CacheConfig] | None = None, | |
| enable_l1: bool = True, | |
| enable_l2: bool = True, | |
| ): | |
| self.redis_url = redis_url or os.getenv("REDIS_URL", "redis://localhost:6379/0") | |
| self.ttl_config = ttl_config or DEFAULT_TTL_CONFIG | |
| self.enable_l1 = enable_l1 | |
| self.enable_l2 = enable_l2 and REDIS_AVAILABLE | |
| # L1 caches per namespace | |
| self._l1_caches: dict[CacheNamespace, LRUCache] = {} | |
| for namespace, config in self.ttl_config.items(): | |
| if config.l1_enabled: | |
| max_size = config.max_size or 1000 | |
| self._l1_caches[namespace] = LRUCache(max_size=max_size) | |
| # L2 cache (Redis) | |
| self._redis_client: redis.Redis | None = None | |
| if self.enable_l2: | |
| try: | |
| self._redis_client = redis.from_url( | |
| self.redis_url, | |
| decode_responses=False, # We handle serialization | |
| socket_connect_timeout=5, | |
| socket_timeout=5, | |
| retry_on_timeout=True, | |
| ) | |
| # Test connection | |
| self._redis_client.ping() | |
| logger.info("✅ Redis connection established") | |
| except Exception as e: | |
| logger.warning(f"Redis connection failed, L2 cache disabled: {e}") | |
| self._redis_client = None | |
| self.enable_l2 = False | |
| def _build_key(self, namespace: CacheNamespace, key: str) -> str: | |
| """Build namespaced cache key""" | |
| return f"yaz:{namespace.value}:{key}" | |
| def _serialize(self, value: Any) -> bytes: | |
| """Serialize value for storage""" | |
| try: | |
| # Try JSON first (faster, more readable) | |
| return json.dumps(value).encode("utf-8") | |
| except (TypeError, ValueError): | |
| # Fall back to pickle for complex objects | |
| return pickle.dumps(value) | |
| def _deserialize(self, data: bytes) -> Any: | |
| """Deserialize value from storage""" | |
| try: | |
| # Try JSON first | |
| return json.loads(data.decode("utf-8")) | |
| except (json.JSONDecodeError, UnicodeDecodeError): | |
| # Fall back to pickle | |
| return pickle.loads(data) | |
| def get(self, namespace: CacheNamespace, key: str, default: Any | None = None) -> Any | None: | |
| """ | |
| Get value from cache (L1 → L2 → default) | |
| Args: | |
| namespace: Cache namespace | |
| key: Cache key | |
| default: Default value if not found | |
| Returns: | |
| Cached value or default | |
| """ | |
| cache_key = self._build_key(namespace, key) | |
| start_time = time.time() | |
| # Try L1 cache | |
| if self.enable_l1 and namespace in self._l1_caches: | |
| value = self._l1_caches[namespace].get(cache_key) | |
| if value is not None: | |
| cache_hits.labels(tier="l1", namespace=namespace.value).inc() | |
| cache_latency.labels(operation="get", tier="l1").observe(time.time() - start_time) | |
| logger.debug(f"L1 cache hit: {namespace.value}:{key}") | |
| return value | |
| cache_misses.labels(tier="l1", namespace=namespace.value).inc() | |
| # Try L2 cache | |
| if self.enable_l2 and self._redis_client: | |
| try: | |
| data = self._redis_client.get(cache_key) | |
| if data: | |
| value = self._deserialize(data) # type: ignore[arg-type, assignment] | |
| cache_hits.labels(tier="l2", namespace=namespace.value).inc() | |
| cache_latency.labels(operation="get", tier="l2").observe( | |
| time.time() - start_time | |
| ) | |
| # Promote to L1 | |
| if self.enable_l1 and namespace in self._l1_caches: | |
| config = self.ttl_config[namespace] | |
| self._l1_caches[namespace].set(cache_key, value, config.ttl) | |
| logger.debug(f"L2 cache hit (promoted to L1): {namespace.value}:{key}") | |
| return value | |
| cache_misses.labels(tier="l2", namespace=namespace.value).inc() | |
| except Exception as e: | |
| logger.error(f"Redis get error: {e}") | |
| cache_operations.labels( | |
| operation="get_error", tier="l2", namespace=namespace.value | |
| ).inc() | |
| cache_latency.labels(operation="get", tier="miss").observe(time.time() - start_time) | |
| return default | |
| def set(self, namespace: CacheNamespace, key: str, value: Any, ttl: int | None = None): | |
| """ | |
| Set value in cache (both L1 and L2) | |
| Args: | |
| namespace: Cache namespace | |
| key: Cache key | |
| value: Value to cache | |
| ttl: Custom TTL (uses namespace default if not provided) | |
| """ | |
| cache_key = self._build_key(namespace, key) | |
| config = self.ttl_config.get(namespace) | |
| if not config: | |
| logger.warning(f"No config for namespace {namespace}, using default") | |
| config = CacheConfig(ttl=300) | |
| ttl = ttl or config.ttl | |
| start_time = time.time() | |
| # Set in L1 | |
| if self.enable_l1 and namespace in self._l1_caches: | |
| self._l1_caches[namespace].set(cache_key, value, ttl) | |
| cache_operations.labels(operation="set", tier="l1", namespace=namespace.value).inc() | |
| cache_size.labels(tier="l1", namespace=namespace.value).set( | |
| self._l1_caches[namespace].size() | |
| ) | |
| # Set in L2 | |
| if self.enable_l2 and self._redis_client: | |
| try: | |
| data = self._serialize(value) | |
| self._redis_client.setex(cache_key, ttl, data) | |
| cache_operations.labels(operation="set", tier="l2", namespace=namespace.value).inc() | |
| cache_latency.labels(operation="set", tier="l2").observe(time.time() - start_time) | |
| except Exception as e: | |
| logger.error(f"Redis set error: {e}") | |
| cache_operations.labels( | |
| operation="set_error", tier="l2", namespace=namespace.value | |
| ).inc() | |
| def delete(self, namespace: CacheNamespace, key: str): | |
| """Delete key from all cache tiers""" | |
| cache_key = self._build_key(namespace, key) | |
| # Delete from L1 | |
| if self.enable_l1 and namespace in self._l1_caches: | |
| self._l1_caches[namespace].delete(cache_key) | |
| cache_operations.labels(operation="delete", tier="l1", namespace=namespace.value).inc() | |
| # Delete from L2 | |
| if self.enable_l2 and self._redis_client: | |
| try: | |
| self._redis_client.delete(cache_key) | |
| cache_operations.labels( | |
| operation="delete", tier="l2", namespace=namespace.value | |
| ).inc() | |
| except Exception as e: | |
| logger.error(f"Redis delete error: {e}") | |
| def delete_pattern(self, namespace: CacheNamespace, pattern: str): | |
| """ | |
| Delete keys matching pattern | |
| Args: | |
| namespace: Cache namespace | |
| pattern: Key pattern (supports * wildcards) | |
| Example: | |
| cache.delete_pattern(CacheNamespace.USER, "user:123:*") | |
| """ | |
| cache_pattern = self._build_key(namespace, pattern) | |
| # Delete from L1 | |
| if self.enable_l1 and namespace in self._l1_caches: | |
| l1_cache = self._l1_caches[namespace] | |
| matching_keys = [k for k in l1_cache.keys() if self._matches_pattern(k, cache_pattern)] | |
| for key in matching_keys: | |
| l1_cache.delete(key) | |
| if matching_keys: | |
| logger.info(f"Deleted {len(matching_keys)} keys from L1: {pattern}") | |
| # Delete from L2 | |
| if self.enable_l2 and self._redis_client: | |
| try: | |
| keys = self._redis_client.keys(cache_pattern) | |
| if keys: | |
| self._redis_client.delete(*keys) # type: ignore[attr-defined, misc, dict-item, abstract, type-var, union-attr] | |
| logger.info(f"Deleted {len(keys)} keys from L2: {pattern}") # type: ignore[arg-type, assignment] | |
| except Exception as e: | |
| logger.error(f"Redis pattern delete error: {e}") | |
| def _matches_pattern(self, key: str, pattern: str) -> bool: | |
| """Check if key matches pattern""" | |
| import re | |
| regex_pattern = pattern.replace("*", ".*") | |
| return re.match(regex_pattern, key) is not None | |
| def clear_namespace(self, namespace: CacheNamespace): | |
| """Clear all keys in a namespace""" | |
| self.delete_pattern(namespace, "*") | |
| def clear_all(self): | |
| """Clear all caches""" | |
| # Clear L1 | |
| for l1_cache in self._l1_caches.values(): | |
| l1_cache.clear() | |
| # Clear L2 (all yaz:* keys) | |
| if self.enable_l2 and self._redis_client: | |
| try: | |
| keys = self._redis_client.keys("yaz:*") | |
| if keys: | |
| self._redis_client.delete(*keys) # type: ignore[attr-defined, misc, dict-item, abstract, type-var, union-attr] | |
| logger.info(f"Cleared {len(keys)} keys from Redis") # type: ignore[arg-type, assignment] | |
| except Exception as e: | |
| logger.error(f"Redis clear error: {e}") | |
| def get_stats(self) -> dict[str, Any]: | |
| """Get cache statistics""" | |
| stats = {"l1_enabled": self.enable_l1, "l2_enabled": self.enable_l2, "namespaces": {}} | |
| # L1 stats | |
| if self.enable_l1: | |
| for namespace, l1_cache in self._l1_caches.items(): | |
| stats["namespaces"][namespace.value] = { # type: ignore[name-defined, index, return-value, var-annotated] | |
| "l1_size": l1_cache.size(), | |
| "l1_max_size": l1_cache.max_size, | |
| } | |
| # L2 stats | |
| if self.enable_l2 and self._redis_client: | |
| try: | |
| info = self._redis_client.info() | |
| stats["l2_info"] = { | |
| "connected": True, | |
| "used_memory": info.get("used_memory_human", "unknown"), # type: ignore[union-attr] | |
| "total_keys": info.get("db0", {}).get("keys", 0), # type: ignore[union-attr] | |
| } | |
| except Exception as e: | |
| stats["l2_info"] = {"connected": False, "error": str(e)} | |
| return stats | |
| def warmup(self, warmup_data: dict[CacheNamespace, dict[str, Any]]): | |
| """ | |
| Warm up cache with pre-loaded data | |
| Args: | |
| warmup_data: Dictionary of namespace → {key: value} mappings | |
| Example: | |
| cache.warmup({ | |
| CacheNamespace.CONFIG: { | |
| "app_settings": get_app_settings(), | |
| "feature_flags": get_feature_flags() | |
| } | |
| }) | |
| """ | |
| for namespace, data in warmup_data.items(): | |
| for key, value in data.items(): | |
| self.set(namespace, key, value) | |
| logger.info(f"Cache warmed up with {sum(len(d) for d in warmup_data.values())} entries") | |
| # ============================================================================= | |
| # GLOBAL INSTANCE | |
| # ============================================================================= | |
| # Global cache service instance | |
| _cache_service: CacheService | None = None | |
| def get_cache_service() -> CacheService: | |
| """Get or create global cache service instance""" | |
| global _cache_service | |
| if _cache_service is None: | |
| _cache_service = CacheService() | |
| return _cache_service | |
| # ============================================================================= | |
| # CONVENIENCE FUNCTIONS | |
| # ============================================================================= | |
| def cache_get(namespace: CacheNamespace, key: str, default: Any | None = None) -> Any | None: | |
| """Convenience function for getting from cache""" | |
| return get_cache_service().get(namespace, key, default) | |
| def cache_set(namespace: CacheNamespace, key: str, value: Any, ttl: int | None = None): | |
| """Convenience function for setting in cache""" | |
| get_cache_service().set(namespace, key, value, ttl) | |
| def cache_delete(namespace: CacheNamespace, key: str): | |
| """Convenience function for deleting from cache""" | |
| get_cache_service().delete(namespace, key) | |
| def cache_clear(namespace: CacheNamespace | None = None): | |
| """Convenience function for clearing cache""" | |
| cache_service = get_cache_service() | |
| if namespace: | |
| cache_service.clear_namespace(namespace) | |
| else: | |
| cache_service.clear_all() | |