""" Query result caching for frequently accessed data In-memory cache with LRU eviction until Redis is available """ import hashlib import json from datetime import UTC, datetime, timedelta, timezone from functools import lru_cache, wraps from typing import Any, Callable, Optional import structlog logger = structlog.get_logger(__name__) class QueryCache: """ Simple in-memory query cache with TTL support Uses LRU cache for efficient memory management """ _cache = {} # type: ignore[name-defined, index, return-value, var-annotated] _timestamps = {} # type: ignore[name-defined, index, return-value, var-annotated] @classmethod def get(cls, key: str, ttl: timedelta) -> Any | None: """Get cached value if not expired""" if key not in cls._cache: return None timestamp = cls._timestamps.get(key) if timestamp and datetime.now(UTC) - timestamp > ttl: # Expired - remove from cache cls._cache.pop(key, None) cls._timestamps.pop(key, None) return None return cls._cache[key] @classmethod def set(cls, key: str, value: Any): """Set cached value with current timestamp""" cls._cache[key] = value cls._timestamps[key] = datetime.now(UTC) @classmethod def invalidate(cls, key: str): """Remove specific key from cache""" cls._cache.pop(key, None) cls._timestamps.pop(key, None) @classmethod def invalidate_pattern(cls, pattern: str): """Remove all keys matching pattern""" keys_to_remove = [k for k in cls._cache.keys() if pattern in k] for key in keys_to_remove: cls._cache.pop(key, None) cls._timestamps.pop(key, None) @classmethod def clear(cls): """Clear entire cache""" cls._cache.clear() cls._timestamps.clear() @classmethod def stats(cls) -> dict: """Get cache statistics""" return { "size": len(cls._cache), "keys": list(cls._cache.keys())[:10], # First 10 keys for monitoring } def cache_query_result(ttl: timedelta, key_prefix: str = ""): """ Decorator for caching query results Usage: @cache_query_result(ttl=timedelta(minutes=5), key_prefix="inventory") def get_inventory_item(self, item_id): return self.db.query(Inventory).filter(...).first() """ def decorator(func: Callable) -> Callable: @wraps(func) def wrapper(*args, **kwargs): # Generate cache key from function name and arguments key_parts = [key_prefix, func.__name__] # Add args (skip self) for arg in args[1:]: # Skip self key_parts.append(str(arg)) # Add kwargs for k, v in sorted(kwargs.items()): key_parts.append(f"{k}={v}") cache_key = ":".join(key_parts) # Try to get from cache cached_value = QueryCache.get(cache_key, ttl) if cached_value is not None: logger.debug(f"Cache hit: {cache_key}") return cached_value # Execute query result = func(*args, **kwargs) # Cache result if result is not None: QueryCache.set(cache_key, result) logger.debug(f"Cache set: {cache_key}") return result return wrapper return decorator @lru_cache(maxsize=1000) def cached_lookup(model_name: str, lookup_key: str, lookup_value: str) -> str | None: """ LRU cached lookup for reference data Returns ID as string for simple lookups """ # This is a placeholder - actual implementation would query DB # Used for frequently accessed reference data like warehouses, vendors, etc. return None def invalidate_model_cache(model_name: str): """Invalidate all cache entries for a model""" QueryCache.invalidate_pattern(model_name.lower()) logger.info(f"Invalidated cache for model: {model_name}") # Export utilities __all__ = [ "QueryCache", "cache_query_result", "cached_lookup", "invalidate_model_cache", ]