Download src/monitoring/cache_optimizer.py from anaselamr/yaz: direct link, hf CLI and curl.
- Browser
- Download file 11.2 kB
-
https://huggingface.co/spaces/anaselamr/yaz/resolve/main/src/monitoring/cache_optimizer.py
- Command line
-
hf download hf://spaces/anaselamr/yaz/src/monitoring/cache_optimizer.py
-
curl -L -o cache_optimizer.py https://huggingface.co/spaces/anaselamr/yaz/resolve/main/src/monitoring/cache_optimizer.py
11.2 kB
| """ | |
| YAZ Care Platform - Advanced Caching Strategy Optimizer | |
| Multi-level caching with intelligent invalidation and performance optimization | |
| """ | |
| import asyncio | |
| import hashlib | |
| import pickle | |
| import time | |
| from dataclasses import dataclass | |
| from datetime import UTC, datetime, timedelta, timezone | |
| from enum import Enum | |
| from functools import wraps | |
| from typing import Any, Callable, Dict, List, Optional | |
| import structlog | |
| logger = structlog.get_logger(__name__) | |
| class CacheLevel(Enum): | |
| """Cache hierarchy levels""" | |
| L1_MEMORY = "l1_memory" # In-memory (fastest, limited size) | |
| L2_REDIS = "l2_redis" # Redis (fast, distributed) | |
| L3_DATABASE = "l3_database" # Database cache table (persistent) | |
| class CacheStrategy(Enum): | |
| """Caching strategies""" | |
| CACHE_ASIDE = "cache_aside" # Read: check cache, miss -> DB -> write cache | |
| WRITE_THROUGH = "write_through" # Write: update cache and DB synchronously | |
| WRITE_BEHIND = "write_behind" # Write: update cache, async DB write | |
| REFRESH_AHEAD = "refresh_ahead" # Proactively refresh before expiration | |
| class CacheMetrics: | |
| """Cache performance metrics""" | |
| hits: int = 0 | |
| misses: int = 0 | |
| writes: int = 0 | |
| invalidations: int = 0 | |
| errors: int = 0 | |
| total_latency_ms: float = 0.0 | |
| last_reset: datetime = None # type: ignore[arg-type, assignment] | |
| def hit_rate(self) -> float: | |
| """Calculate cache hit rate""" | |
| total = self.hits + self.misses | |
| return (self.hits / total * 100) if total > 0 else 0.0 | |
| def avg_latency_ms(self) -> float: | |
| """Calculate average latency""" | |
| total_ops = self.hits + self.misses + self.writes | |
| return self.total_latency_ms / total_ops if total_ops > 0 else 0.0 | |
| class CacheOptimizer: | |
| """ | |
| Advanced multi-level cache optimizer | |
| Features: | |
| - L1 (memory) -> L2 (Redis) -> L3 (database) hierarchy | |
| - Multiple caching strategies | |
| - Intelligent TTL management | |
| - Cache warming | |
| - Stampede prevention | |
| - Automatic invalidation | |
| - Performance metrics | |
| """ | |
| def __init__( | |
| self, | |
| l1_enabled: bool = True, | |
| l2_enabled: bool = True, | |
| l1_max_size: int = 10000, | |
| default_ttl: int = 300, | |
| ): | |
| self.l1_enabled = l1_enabled | |
| self.l2_enabled = l2_enabled | |
| self.l1_max_size = l1_max_size | |
| self.default_ttl = default_ttl | |
| # L1 cache (in-memory) | |
| self.l1_cache: dict[str, tuple] = {} # key -> (value, expires_at) | |
| # Metrics | |
| self.metrics = CacheMetrics(last_reset=datetime.now(UTC)) | |
| # Lock for stampede prevention | |
| self._locks: dict[str, asyncio.Lock] = {} | |
| def _generate_key(self, namespace: str, key: str) -> str: | |
| """Generate cache key with namespace""" | |
| return f"{namespace}:{key}" | |
| def _is_expired(self, expires_at: datetime) -> bool: | |
| """Check if cache entry is expired""" | |
| return datetime.now(UTC) >= expires_at | |
| async def get( | |
| self, | |
| namespace: str, | |
| key: str, | |
| fetch_func: Callable | None = None, | |
| ttl: int | None = None, | |
| ) -> Any | None: | |
| """ | |
| Get value from cache with multi-level fallback | |
| Args: | |
| namespace: Cache namespace (e.g., 'patient', 'surgery') | |
| key: Cache key | |
| fetch_func: Function to fetch data on cache miss | |
| ttl: Time to live in seconds | |
| Returns: | |
| Cached value or None | |
| """ | |
| start_time = time.time() | |
| cache_key = self._generate_key(namespace, key) | |
| ttl = ttl or self.default_ttl | |
| try: | |
| # Try L1 cache (memory) | |
| if self.l1_enabled and cache_key in self.l1_cache: | |
| value, expires_at = self.l1_cache[cache_key] | |
| if not self._is_expired(expires_at): | |
| self.metrics.hits += 1 | |
| latency = (time.time() - start_time) * 1000 | |
| self.metrics.total_latency_ms += latency | |
| logger.debug("🎯 L1 cache hit: %s (%.2fms)", cache_key, latency) | |
| return value | |
| else: | |
| # Remove expired entry | |
| del self.l1_cache[cache_key] | |
| # Try L2 cache (Redis) - would implement Redis connection here | |
| # For now, fall through to fetch | |
| # Cache miss - fetch data | |
| self.metrics.misses += 1 | |
| if fetch_func: | |
| # Stampede prevention: only one coroutine fetches | |
| if cache_key not in self._locks: | |
| self._locks[cache_key] = asyncio.Lock() | |
| async with self._locks[cache_key]: | |
| # Double-check cache after acquiring lock | |
| if self.l1_enabled and cache_key in self.l1_cache: | |
| value, expires_at = self.l1_cache[cache_key] | |
| if not self._is_expired(expires_at): | |
| return value | |
| # Fetch data | |
| logger.debug("🔍 Cache miss, fetching: %s", cache_key) | |
| if asyncio.iscoroutinefunction(fetch_func): | |
| value = await fetch_func() | |
| else: | |
| value = fetch_func() | |
| # Store in cache | |
| await self.set(namespace, key, value, ttl) | |
| latency = (time.time() - start_time) * 1000 | |
| self.metrics.total_latency_ms += latency | |
| logger.debug("💾 Fetched and cached: %s (%.2fms)", cache_key, latency) | |
| return value | |
| return None | |
| except Exception as e: | |
| self.metrics.errors += 1 | |
| logger.error("Cache get error for %s: %s", cache_key, str(e)) | |
| return None | |
| async def set(self, namespace: str, key: str, value: Any, ttl: int | None = None): | |
| """Set value in cache across all levels""" | |
| cache_key = self._generate_key(namespace, key) | |
| ttl = ttl or self.default_ttl | |
| expires_at = datetime.now(UTC) + timedelta(seconds=ttl) | |
| try: | |
| # L1 cache (memory) | |
| if self.l1_enabled: | |
| # Evict oldest entries if cache is full | |
| if len(self.l1_cache) >= self.l1_max_size: | |
| # Simple FIFO eviction | |
| oldest_key = next(iter(self.l1_cache)) | |
| del self.l1_cache[oldest_key] | |
| self.l1_cache[cache_key] = (value, expires_at) | |
| self.metrics.writes += 1 | |
| logger.debug("💾 L1 cache set: %s (ttl: %ds)", cache_key, ttl) | |
| # L2 cache (Redis) - would implement here | |
| # await redis.setex(cache_key, ttl, pickle.dumps(value)) | |
| except Exception as e: | |
| self.metrics.errors += 1 | |
| logger.error("Cache set error for %s: %s", cache_key, str(e)) | |
| async def delete(self, namespace: str, key: str): | |
| """Delete value from all cache levels""" | |
| cache_key = self._generate_key(namespace, key) | |
| try: | |
| # L1 cache | |
| if cache_key in self.l1_cache: | |
| del self.l1_cache[cache_key] | |
| # L2 cache (Redis) | |
| # await redis.delete(cache_key) | |
| self.metrics.invalidations += 1 | |
| logger.debug("🗑️ Cache invalidated: %s", cache_key) | |
| except Exception as e: | |
| self.metrics.errors += 1 | |
| logger.error("Cache delete error for %s: %s", cache_key, str(e)) | |
| async def invalidate_pattern(self, namespace: str, pattern: str): | |
| """Invalidate all keys matching pattern""" | |
| prefix = self._generate_key(namespace, pattern) | |
| # L1 cache | |
| keys_to_delete = [k for k in self.l1_cache.keys() if k.startswith(prefix)] | |
| for key in keys_to_delete: | |
| del self.l1_cache[key] | |
| self.metrics.invalidations += len(keys_to_delete) | |
| logger.info("🗑️ Invalidated %d keys with pattern: %s", len(keys_to_delete), prefix) | |
| async def warm_cache(self, items: list[tuple], namespace: str, ttl: int | None = None): | |
| """ | |
| Warm cache with frequently accessed data | |
| Args: | |
| items: List of (key, value) tuples | |
| namespace: Cache namespace | |
| ttl: Time to live in seconds | |
| """ | |
| logger.info("🔥 Warming cache for namespace: %s (%d items)", namespace, len(items)) | |
| for key, value in items: | |
| await self.set(namespace, key, value, ttl) | |
| logger.info("✅ Cache warming complete for namespace: %s", namespace) | |
| def get_metrics(self) -> dict[str, Any]: | |
| """Get cache performance metrics""" | |
| uptime = (datetime.now(UTC) - self.metrics.last_reset).total_seconds() | |
| return { | |
| "hit_rate": self.metrics.hit_rate, | |
| "hits": self.metrics.hits, | |
| "misses": self.metrics.misses, | |
| "writes": self.metrics.writes, | |
| "invalidations": self.metrics.invalidations, | |
| "errors": self.metrics.errors, | |
| "avg_latency_ms": self.metrics.avg_latency_ms, | |
| "l1_size": len(self.l1_cache), | |
| "l1_max_size": self.l1_max_size, | |
| "uptime_seconds": uptime, | |
| } | |
| def reset_metrics(self): | |
| """Reset cache metrics""" | |
| self.metrics = CacheMetrics(last_reset=datetime.now(UTC)) | |
| logger.info("Cache metrics reset") | |
| async def cleanup_expired(self): | |
| """Remove expired entries from L1 cache""" | |
| now = datetime.now(UTC) | |
| expired_keys = [k for k, (v, expires_at) in self.l1_cache.items() if expires_at <= now] | |
| for key in expired_keys: | |
| del self.l1_cache[key] | |
| if expired_keys: | |
| logger.debug("🧹 Cleaned up %d expired cache entries", len(expired_keys)) | |
| # Global cache optimizer instance | |
| cache_optimizer = CacheOptimizer( | |
| l1_enabled=True, l2_enabled=True, l1_max_size=10000, default_ttl=300 | |
| ) | |
| def cached(namespace: str, key_func: Callable | None = None, ttl: int = 300): | |
| """ | |
| Decorator for caching function results | |
| Usage: | |
| @cached(namespace='patient', ttl=600) | |
| async def get_patient(patient_id: str): | |
| return await db.fetch_patient(patient_id) | |
| """ | |
| def decorator(func): | |
| async def wrapper(*args, **kwargs): | |
| # Generate cache key | |
| if key_func: | |
| cache_key = key_func(*args, **kwargs) | |
| else: | |
| # Default: use function name and first arg | |
| cache_key = f"{func.__name__}:{args[0]}" if args else func.__name__ | |
| # Try to get from cache | |
| result = await cache_optimizer.get( | |
| namespace=namespace, | |
| key=cache_key, | |
| fetch_func=lambda: func(*args, **kwargs), | |
| ttl=ttl, | |
| ) | |
| return result | |
| return wrapper | |
| return decorator | |
| __all__ = [ | |
| "CacheOptimizer", | |
| "CacheLevel", | |
| "CacheStrategy", | |
| "CacheMetrics", | |
| "cache_optimizer", | |
| "cached", | |
| ] | |