import asyncio from typing import Any, Optional from datetime import datetime, timedelta class CacheManager: """In-memory cache with TTL support""" def __init__(self): self._cache = {} self._expiry = {} self._lock = asyncio.Lock() async def get(self, key: str) -> Optional[Any]: """Get value from cache""" async with self._lock: if key not in self._cache: return None # Check expiry if key in self._expiry and datetime.now() > self._expiry[key]: del self._cache[key] del self._expiry[key] return None return self._cache[key] async def set(self, key: str, value: Any, ttl_hours: int = 24): """Set value in cache with TTL""" async with self._lock: self._cache[key] = value if ttl_hours > 0: self._expiry[key] = datetime.now() + timedelta(hours=ttl_hours) async def delete(self, key: str): """Delete key from cache""" async with self._lock: self._cache.pop(key, None) self._expiry.pop(key, None) async def clear(self): """Clear all cache""" async with self._lock: self._cache.clear() self._expiry.clear() async def cleanup_expired(self): """Remove expired entries""" async with self._lock: now = datetime.now() expired_keys = [ key for key, expiry in self._expiry.items() if now > expiry ] for key in expired_keys: self._cache.pop(key, None) self._expiry.pop(key, None)