"""Caching utilities for data that doesn't change frequently."""
import logging
from typing import Any, Optional
from datetime import datetime, timedelta
from dataclasses import dataclass
logger = logging.getLogger(__name__)
@dataclass
class CacheEntry:
"""Cache entry with expiration."""
value: Any
expires_at: datetime
class SimpleCache:
"""Simple in-memory cache with TTL support."""
def __init__(self):
self._cache: dict[str, CacheEntry] = {}
def get(self, key: str) -> Optional[Any]:
"""Get value from cache if not expired."""
entry = self._cache.get(key)
if entry is None:
return None
if datetime.now() > entry.expires_at:
# Expired, remove from cache
del self._cache[key]
return None
return entry.value
def set(self, key: str, value: Any, ttl_seconds: int):
"""Set value in cache with TTL."""
expires_at = datetime.now() + timedelta(seconds=ttl_seconds)
self._cache[key] = CacheEntry(value=value, expires_at=expires_at)
def clear(self):
"""Clear all cache entries."""
self._cache.clear()
def remove(self, key: str):
"""Remove specific key from cache."""
self._cache.pop(key, None)
# Global cache instance
cache = SimpleCache()