|
| 1 | +""" |
| 2 | +Cache Utilities for StillMe |
| 3 | +
|
| 4 | +Provides utilities for caching validation results and other expensive operations. |
| 5 | +Uses Redis if available, falls back to in-memory cache. |
| 6 | +""" |
| 7 | + |
| 8 | +import logging |
| 9 | +import hashlib |
| 10 | +import json |
| 11 | +from typing import Dict, Any, Optional |
| 12 | +from functools import wraps |
| 13 | + |
| 14 | +logger = logging.getLogger(__name__) |
| 15 | + |
| 16 | +# Try to import Redis cache |
| 17 | +try: |
| 18 | + from backend.services.redis_cache import get_cache_service |
| 19 | + REDIS_AVAILABLE = True |
| 20 | +except ImportError: |
| 21 | + REDIS_AVAILABLE = False |
| 22 | + get_cache_service = None |
| 23 | + |
| 24 | +# In-memory fallback cache |
| 25 | +_in_memory_cache: Dict[str, Dict[str, Any]] = {} |
| 26 | + |
| 27 | + |
| 28 | +def hash_query(query: str) -> str: |
| 29 | + """ |
| 30 | + Generate hash for query (normalized) |
| 31 | + |
| 32 | + Args: |
| 33 | + query: User query text |
| 34 | + |
| 35 | + Returns: |
| 36 | + MD5 hash (first 16 chars) |
| 37 | + """ |
| 38 | + if not query: |
| 39 | + return "empty" |
| 40 | + |
| 41 | + # Normalize: lowercase, strip whitespace |
| 42 | + normalized = query.lower().strip() |
| 43 | + return hashlib.md5(normalized.encode('utf-8')).hexdigest()[:16] |
| 44 | + |
| 45 | + |
| 46 | +def hash_context(context: Dict[str, Any]) -> str: |
| 47 | + """ |
| 48 | + Generate hash for context (document IDs + similarities) |
| 49 | + |
| 50 | + Args: |
| 51 | + context: RAG context dictionary |
| 52 | + |
| 53 | + Returns: |
| 54 | + MD5 hash (first 16 chars) |
| 55 | + """ |
| 56 | + if not context: |
| 57 | + return "no_context" |
| 58 | + |
| 59 | + # Extract document IDs and similarities |
| 60 | + docs = context.get("knowledge_docs", []) |
| 61 | + if not docs: |
| 62 | + return "no_docs" |
| 63 | + |
| 64 | + # Sort for consistent hashing |
| 65 | + doc_ids = sorted([str(doc.get("id", "")) for doc in docs if doc.get("id")]) |
| 66 | + similarities = sorted([round(doc.get("similarity", 0.0), 3) for doc in docs]) |
| 67 | + |
| 68 | + # Create hash from IDs and similarities |
| 69 | + context_str = json.dumps({"ids": doc_ids, "sims": similarities}, sort_keys=True) |
| 70 | + return hashlib.md5(context_str.encode('utf-8')).hexdigest()[:16] |
| 71 | + |
| 72 | + |
| 73 | +def get_cache_key(prefix: str, query: str, context: Optional[Dict[str, Any]] = None) -> str: |
| 74 | + """ |
| 75 | + Generate cache key from query and context |
| 76 | + |
| 77 | + Args: |
| 78 | + prefix: Cache key prefix (e.g., "validation") |
| 79 | + query: User query |
| 80 | + context: Optional RAG context |
| 81 | + |
| 82 | + Returns: |
| 83 | + Cache key string |
| 84 | + """ |
| 85 | + query_hash = hash_query(query) |
| 86 | + context_hash = hash_context(context) if context else "no_context" |
| 87 | + return f"{prefix}:{query_hash}:{context_hash}" |
| 88 | + |
| 89 | + |
| 90 | +def get_from_cache(cache_key: str) -> Optional[Any]: |
| 91 | + """ |
| 92 | + Get value from cache (Redis or in-memory) |
| 93 | + |
| 94 | + Args: |
| 95 | + cache_key: Cache key |
| 96 | + |
| 97 | + Returns: |
| 98 | + Cached value or None if not found |
| 99 | + """ |
| 100 | + # Try Redis first |
| 101 | + if REDIS_AVAILABLE: |
| 102 | + try: |
| 103 | + cache_service = get_cache_service() |
| 104 | + if cache_service: |
| 105 | + cached = cache_service.get(cache_key) |
| 106 | + if cached: |
| 107 | + logger.debug(f"Cache HIT (Redis): {cache_key[:50]}...") |
| 108 | + return cached |
| 109 | + except Exception as e: |
| 110 | + logger.debug(f"Redis cache error (falling back to memory): {e}") |
| 111 | + |
| 112 | + # Fallback to in-memory |
| 113 | + if cache_key in _in_memory_cache: |
| 114 | + cached_data = _in_memory_cache[cache_key] |
| 115 | + # Check TTL (simple implementation) |
| 116 | + import time |
| 117 | + if time.time() < cached_data.get("expires_at", 0): |
| 118 | + logger.debug(f"Cache HIT (Memory): {cache_key[:50]}...") |
| 119 | + return cached_data.get("value") |
| 120 | + else: |
| 121 | + # Expired, remove it |
| 122 | + del _in_memory_cache[cache_key] |
| 123 | + |
| 124 | + logger.debug(f"Cache MISS: {cache_key[:50]}...") |
| 125 | + return None |
| 126 | + |
| 127 | + |
| 128 | +def set_to_cache(cache_key: str, value: Any, ttl: int = 3600) -> None: |
| 129 | + """ |
| 130 | + Set value to cache (Redis or in-memory) |
| 131 | + |
| 132 | + Args: |
| 133 | + cache_key: Cache key |
| 134 | + value: Value to cache |
| 135 | + ttl: Time to live in seconds (default: 1 hour) |
| 136 | + """ |
| 137 | + # Try Redis first |
| 138 | + if REDIS_AVAILABLE: |
| 139 | + try: |
| 140 | + cache_service = get_cache_service() |
| 141 | + if cache_service: |
| 142 | + cache_service.set(cache_key, value, ttl=ttl) |
| 143 | + logger.debug(f"Cached (Redis): {cache_key[:50]}... (TTL: {ttl}s)") |
| 144 | + return |
| 145 | + except Exception as e: |
| 146 | + logger.debug(f"Redis cache error (falling back to memory): {e}") |
| 147 | + |
| 148 | + # Fallback to in-memory |
| 149 | + import time |
| 150 | + _in_memory_cache[cache_key] = { |
| 151 | + "value": value, |
| 152 | + "expires_at": time.time() + ttl |
| 153 | + } |
| 154 | + logger.debug(f"Cached (Memory): {cache_key[:50]}... (TTL: {ttl}s)") |
| 155 | + |
| 156 | + |
| 157 | +def clear_cache(cache_key: Optional[str] = None) -> None: |
| 158 | + """ |
| 159 | + Clear cache (specific key or all) |
| 160 | + |
| 161 | + Args: |
| 162 | + cache_key: Specific key to clear, or None to clear all |
| 163 | + """ |
| 164 | + if cache_key: |
| 165 | + # Clear specific key |
| 166 | + if REDIS_AVAILABLE: |
| 167 | + try: |
| 168 | + cache_service = get_cache_service() |
| 169 | + if cache_service: |
| 170 | + cache_service.delete(cache_key) |
| 171 | + except Exception: |
| 172 | + pass |
| 173 | + |
| 174 | + if cache_key in _in_memory_cache: |
| 175 | + del _in_memory_cache[cache_key] |
| 176 | + else: |
| 177 | + # Clear all |
| 178 | + if REDIS_AVAILABLE: |
| 179 | + try: |
| 180 | + cache_service = get_cache_service() |
| 181 | + if cache_service: |
| 182 | + cache_service.clear() |
| 183 | + except Exception: |
| 184 | + pass |
| 185 | + |
| 186 | + _in_memory_cache.clear() |
| 187 | + |
| 188 | + |
| 189 | +def get_cache_stats() -> Dict[str, Any]: |
| 190 | + """ |
| 191 | + Get cache statistics |
| 192 | + |
| 193 | + Returns: |
| 194 | + Dictionary with cache stats |
| 195 | + """ |
| 196 | + stats = { |
| 197 | + "redis_available": REDIS_AVAILABLE, |
| 198 | + "in_memory_size": len(_in_memory_cache), |
| 199 | + "in_memory_keys": list(_in_memory_cache.keys())[:10] # First 10 keys |
| 200 | + } |
| 201 | + |
| 202 | + if REDIS_AVAILABLE: |
| 203 | + try: |
| 204 | + cache_service = get_cache_service() |
| 205 | + if cache_service: |
| 206 | + redis_stats = cache_service.get_stats() |
| 207 | + stats.update(redis_stats) |
| 208 | + except Exception as e: |
| 209 | + stats["redis_error"] = str(e) |
| 210 | + |
| 211 | + return stats |
| 212 | + |
0 commit comments