File size: 1,850 Bytes
57fda34
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
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)