Spaces:
Paused

yaz / src /core /services /cache.py
anaselamr's picture
fix(collaboration): production-ready collaboration fixes — all 19 engines
0743ddc
Raw History Blame Contribute Delete
17.7 kB
"""
YAZ Care Platform - Advanced Caching Service
Comprehensive multi-tier caching with Redis backend for healthcare data
"""
import asyncio
import hashlib
import json
import pickle
from datetime import datetime, timedelta
from functools import wraps
from typing import Any, Callable, Dict, List, Optional, Union
import redis.asyncio as redis
import structlog
from redis.exceptions import ConnectionError, TimeoutError
logger = structlog.get_logger(__name__)
class CacheManager:
"""
Multi-tier caching manager with healthcare-specific optimizations
Tier 1: In-memory LRU cache (fastest, smallest capacity)
Tier 2: Redis cache (fast, distributed)
Tier 3: Database cache tables (persistent, largest capacity)
"""
def __init__(
self,
redis_url: str = "redis://localhost:6379",
memory_cache_size: int = 1000,
default_ttl: int = 300, # 5 minutes
healthcare_compliance: bool = True,
):
self.redis_url = redis_url
self.memory_cache_size = memory_cache_size
self.default_ttl = default_ttl
self.healthcare_compliance = healthcare_compliance
# Memory cache (LRU)
self._memory_cache: dict[str, dict] = {}
self._memory_access_order: list[str] = []
# Redis connection
self._redis: redis.Redis | None = None
self._redis_connected = False
# Cache statistics
self.stats: dict[str, Any] = {
"memory_hits": 0,
"redis_hits": 0,
"misses": 0,
"sets": 0,
"deletes": 0,
"errors": 0,
}
logger.info(
"Cache manager initialized",
memory_size=memory_cache_size,
healthcare_compliance=healthcare_compliance,
)
async def initialize(self):
"""Initialize Redis connection with bounded timeout."""
import asyncio
try:
self._redis = redis.from_url(
self.redis_url,
encoding="utf-8",
decode_responses=False, # We'll handle encoding ourselves
socket_keepalive=True,
socket_keepalive_options={},
health_check_interval=30,
retry_on_timeout=False, # Never retry indefinitely — fail fast
socket_connect_timeout=3,
socket_timeout=3,
)
# Test connection with hard 5s timeout so startup never hangs
await asyncio.wait_for(self._redis.ping(), timeout=5.0)
self._redis_connected = True
logger.info("Redis cache connected successfully", url=self.redis_url)
except Exception as e:
logger.warning(
"Redis cache unavailable — continuing with memory-only cache", error=str(e)
)
self._redis = None
self._redis_connected = False
async def get(
self, key: str, namespace: str = "default", healthcare_context: dict | None = None
) -> Any | None:
"""
Get value from cache with tier fallback
Args:
key: Cache key
namespace: Cache namespace for organization
healthcare_context: Healthcare-specific context for compliance
"""
cache_key = self._build_cache_key(key, namespace)
# Tier 1: Memory cache
memory_result = self._get_from_memory(cache_key)
if memory_result is not None:
self.stats["memory_hits"] += 1
logger.debug("Cache hit (memory)", key=cache_key)
return memory_result
# Tier 2: Redis cache
if self._redis_connected:
try:
redis_result = await self._get_from_redis(cache_key)
if redis_result is not None:
# Promote to memory cache
self._set_in_memory(cache_key, redis_result, self.default_ttl)
self.stats["redis_hits"] += 1
logger.debug("Cache hit (redis)", key=cache_key)
return redis_result
except Exception as e:
logger.warning("Redis get failed", key=cache_key, error=str(e))
self.stats["errors"] += 1
# Cache miss
self.stats["misses"] += 1
logger.debug("Cache miss", key=cache_key)
return None
async def set(
self,
key: str,
value: Any,
ttl: int | None = None,
namespace: str = "default",
healthcare_context: dict | None = None,
tier_preference: str = "all", # "memory", "redis", "all"
) -> bool:
"""
Set value in cache with healthcare compliance checks
Args:
key: Cache key
value: Value to cache
ttl: Time to live in seconds
namespace: Cache namespace
healthcare_context: Healthcare compliance context
tier_preference: Which cache tiers to use
"""
if self.healthcare_compliance and healthcare_context:
# Check if data contains PHI/PII
if self._contains_phi(value, healthcare_context):
logger.warning("Attempting to cache PHI data", key=key)
return False
cache_key = self._build_cache_key(key, namespace)
ttl = ttl or self.default_ttl
success = True
# Set in memory cache
if tier_preference in ["memory", "all"]:
self._set_in_memory(cache_key, value, ttl)
# Set in Redis cache
if tier_preference in ["redis", "all"] and self._redis_connected:
try:
success &= await self._set_in_redis(cache_key, value, ttl)
except Exception as e:
logger.warning("Redis set failed", key=cache_key, error=str(e))
self.stats["errors"] += 1
success = False
if success:
self.stats["sets"] += 1
logger.debug("Cache set", key=cache_key, ttl=ttl)
return success
async def delete(self, key: str, namespace: str = "default", pattern: bool = False) -> bool:
"""Delete key(s) from all cache tiers"""
cache_key = self._build_cache_key(key, namespace)
if pattern:
return await self._delete_pattern(cache_key)
else:
return await self._delete_single(cache_key)
async def clear_namespace(self, namespace: str) -> bool:
"""Clear all keys in a namespace"""
pattern = f"{namespace}:*"
return await self._delete_pattern(pattern)
async def get_stats(self) -> dict[str, Any]:
"""Get cache statistics"""
stats = self.stats.copy()
# Add Redis info if connected
if self._redis_connected:
try:
redis_info = await self._redis.info("memory") # type: ignore[union-attr]
stats["redis_memory_used"] = redis_info.get("used_memory_human", "N/A")
stats["redis_connected"] = True
except Exception:
stats["redis_connected"] = False
else:
stats["redis_connected"] = False
# Add memory cache info
stats["memory_cache_size"] = len(self._memory_cache)
stats["memory_cache_capacity"] = self.memory_cache_size
# Calculate hit ratios
total_requests = sum([stats["memory_hits"], stats["redis_hits"], stats["misses"]])
if total_requests > 0:
stats["hit_ratio"] = (stats["memory_hits"] + stats["redis_hits"]) / total_requests
stats["memory_hit_ratio"] = stats["memory_hits"] / total_requests
stats["redis_hit_ratio"] = stats["redis_hits"] / total_requests
else:
stats["hit_ratio"] = 0.0
stats["memory_hit_ratio"] = 0.0
stats["redis_hit_ratio"] = 0.0
return stats
def cache(
self,
ttl: int | None = None,
namespace: str = "default",
key_func: Callable | None = None,
healthcare_safe: bool = True,
):
"""
Decorator for caching function results
Usage:
@cache_manager.cache(ttl=300, namespace="topsis")
async def calculate_topsis(alternatives, criteria):
# Expensive calculation
return result
"""
def decorator(func: Callable):
@wraps(func)
async def wrapper(*args, **kwargs):
# Generate cache key
if key_func:
cache_key = key_func(*args, **kwargs)
else:
cache_key = self._generate_function_key(func, args, kwargs)
# Try to get from cache
cached_result = await self.get(cache_key, namespace)
if cached_result is not None:
logger.debug("Function cache hit", function=func.__name__, key=cache_key)
return cached_result
# Execute function
result = (
await func(*args, **kwargs)
if asyncio.iscoroutinefunction(func)
else func(*args, **kwargs)
)
# Cache result if healthcare safe
healthcare_context = None
if healthcare_safe:
healthcare_context = {"function": func.__name__, "safe": True}
await self.set(cache_key, result, ttl, namespace, healthcare_context)
return result
return wrapper
return decorator
# Private methods
def _build_cache_key(self, key: str, namespace: str) -> str:
"""Build namespaced cache key"""
return f"{namespace}:{key}"
def _get_from_memory(self, key: str) -> Any | None:
"""Get from in-memory cache"""
if key in self._memory_cache:
entry = self._memory_cache[key]
# Check expiration
if datetime.now() > entry["expires"]:
del self._memory_cache[key]
self._memory_access_order.remove(key)
return None
# Update access order (LRU)
self._memory_access_order.remove(key)
self._memory_access_order.append(key)
return entry["value"]
return None
def _set_in_memory(self, key: str, value: Any, ttl: int):
"""Set in memory cache with LRU eviction"""
# Evict if at capacity
while len(self._memory_cache) >= self.memory_cache_size:
oldest_key = self._memory_access_order.pop(0)
del self._memory_cache[oldest_key]
# Set new entry
expires = datetime.now() + timedelta(seconds=ttl)
self._memory_cache[key] = {"value": value, "expires": expires}
self._memory_access_order.append(key)
async def _get_from_redis(self, key: str) -> Any | None:
"""Get from Redis cache"""
try:
data = await self._redis.get(key) # type: ignore[union-attr]
if data is None:
return None
# Try to deserialize
try:
return pickle.loads(data)
except (pickle.UnpicklingError, TypeError):
# Fallback to JSON
return json.loads(data.decode("utf-8"))
except Exception as e:
logger.warning("Redis get error", key=key, error=str(e))
return None
async def _set_in_redis(self, key: str, value: Any, ttl: int) -> bool:
"""Set in Redis cache"""
try:
# Serialize value
try:
data = pickle.dumps(value)
except (pickle.PicklingError, TypeError):
# Fallback to JSON
data = json.dumps(value).encode("utf-8")
await self._redis.setex(key, ttl, data) # type: ignore[union-attr]
return True
except Exception as e:
logger.warning("Redis set error", key=key, error=str(e))
return False
async def _delete_single(self, key: str) -> bool:
"""Delete single key from all tiers"""
success = True
# Delete from memory
if key in self._memory_cache:
del self._memory_cache[key]
self._memory_access_order.remove(key)
# Delete from Redis
if self._redis_connected:
try:
await self._redis.delete(key) # type: ignore[union-attr]
except Exception as e:
logger.warning("Redis delete error", key=key, error=str(e))
success = False
if success:
self.stats["deletes"] += 1
return success
async def _delete_pattern(self, pattern: str) -> bool:
"""Delete keys matching pattern"""
success = True
# Delete from memory cache
keys_to_delete = [
key for key in self._memory_cache.keys() if self._pattern_match(key, pattern)
]
for key in keys_to_delete:
del self._memory_cache[key]
self._memory_access_order.remove(key)
# Delete from Redis
if self._redis_connected:
try:
keys = await self._redis.keys(pattern) # type: ignore[union-attr]
if keys:
await self._redis.delete(*keys) # type: ignore[union-attr]
except Exception as e:
logger.warning("Redis pattern delete error", pattern=pattern, error=str(e))
success = False
return success
def _pattern_match(self, key: str, pattern: str) -> bool:
"""Simple pattern matching for cache keys"""
if pattern.endswith("*"):
prefix = pattern[:-1]
return key.startswith(prefix)
return key == pattern
def _generate_function_key(self, func: Callable, args: tuple, kwargs: dict) -> str:
"""Generate cache key for function call"""
# Create a hash of function name and arguments
key_data = {
"function": func.__name__,
"args": args,
"kwargs": sorted(kwargs.items()), # Sort for consistency
}
key_string = json.dumps(key_data, sort_keys=True, default=str)
return hashlib.md5(key_string.encode()).hexdigest()
def _contains_phi(self, value: Any, healthcare_context: dict) -> bool:
"""Check if value contains Protected Health Information"""
if not healthcare_context or healthcare_context.get("safe", False):
return False
# Simple PHI detection (extend based on requirements)
phi_indicators = [
"ssn",
"social_security",
"patient_id",
"medical_record",
"phone",
"email",
"address",
"birth_date",
"dob",
]
value_str = str(value).lower()
return any(indicator in value_str for indicator in phi_indicators)
# Healthcare-specific cache namespaces
class HealthcareCacheNamespaces:
"""Predefined cache namespaces for healthcare data"""
TOPSIS_RESULTS = "topsis"
PATIENT_DATA = "patient" # Be very careful with PHI
MEDICATION_INFO = "medication"
VITAL_SIGNS = "vitals"
APPOINTMENTS = "appointments"
ANALYTICS = "analytics"
REPORTS = "reports"
USER_SESSIONS = "sessions"
CALCULATIONS = "calculations"
CONFIGURATIONS = "config"
# Surgical / Surgio engine namespaces
CASE_SCHEDULES = "case_schedules"
CLINICAL_DATA = "clinical_data"
SURVIVAL_ANALYSIS = "survival_analysis"
SURVIVAL_PREDICTIONS = "survival_predictions"
# Finance / Banko engine namespaces
FINANCIAL_DATA = "financial_data"
# Global cache manager instance
cache_manager = CacheManager()
# Utility functions for common caching patterns
async def cache_topsis_result(
alternatives: list[dict],
criteria: list[dict],
result: dict,
ttl: int = 3600, # 1 hour
) -> bool:
"""Cache TOPSIS calculation result"""
key_data = {
"alternatives": len(alternatives),
"criteria": len(criteria),
"alt_hash": hashlib.md5(str(alternatives).encode()).hexdigest()[:8],
"crit_hash": hashlib.md5(str(criteria).encode()).hexdigest()[:8],
}
cache_key = f"topsis_{key_data['alt_hash']}_{key_data['crit_hash']}"
return await cache_manager.set(
cache_key,
result,
ttl=ttl,
namespace=HealthcareCacheNamespaces.TOPSIS_RESULTS,
healthcare_context={"safe": True, "type": "calculation"},
)
async def get_cached_topsis_result(alternatives: list[dict], criteria: list[dict]) -> dict | None:
"""Get cached TOPSIS calculation result"""
key_data = {
"alt_hash": hashlib.md5(str(alternatives).encode()).hexdigest()[:8],
"crit_hash": hashlib.md5(str(criteria).encode()).hexdigest()[:8],
}
cache_key = f"topsis_{key_data['alt_hash']}_{key_data['crit_hash']}"
return await cache_manager.get(cache_key, namespace=HealthcareCacheNamespaces.TOPSIS_RESULTS)
# Cache warming functions
async def warm_cache():
"""Warm up cache with frequently accessed data"""
logger.info("Starting cache warming process")
# Warm common configuration
# This would be implemented based on your specific data access patterns
logger.info("Cache warming completed")
# Cache maintenance
async def cleanup_expired_cache():
"""Clean up expired cache entries (run periodically)"""
# Memory cache cleanup happens automatically
# Redis cleanup could be implemented here if needed
pass