File size: 2,069 Bytes
f171e60
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
from abc import ABC, abstractmethod
from typing import Optional, Any
import hashlib
import json

class BaseCache(ABC):
    """
    Abstract base class cho cache implementations
    """
    
    @abstractmethod
    async def get(self, key: str) -> Optional[Any]:
        """
        Get value từ cache
        
        Args:
            key: Cache key
            
        Returns:
            Cached value hoặc None
        """
        pass
    
    @abstractmethod
    async def set(self, key: str, value: Any, ttl: Optional[int] = None) -> bool:
        """
        Set value vào cache
        
        Args:
            key: Cache key
            value: Value to cache
            ttl: Time to live in seconds
            
        Returns:
            True nếu success
        """
        pass
    
    @abstractmethod
    async def delete(self, key: str) -> bool:
        """
        Delete key từ cache
        
        Args:
            key: Cache key
            
        Returns:
            True nếu success
        """
        pass
    
    @abstractmethod
    async def clear(self) -> bool:
        """
        Clear toàn bộ cache
        
        Returns:
            True nếu success
        """
        pass
    
    @abstractmethod
    async def exists(self, key: str) -> bool:
        """
        Check xem key có tồn tại không
        
        Args:
            key: Cache key
            
        Returns:
            True nếu key exists
        """
        pass
    
    def generate_key(self, prefix: str, **kwargs) -> str:
        """
        Generate cache key từ parameters
        
        Args:
            prefix: Key prefix
            **kwargs: Parameters to include in key
            
        Returns:
            Generated cache key
        """
        # Sort kwargs để đảm bảo consistent key
        sorted_params = json.dumps(kwargs, sort_keys=True)
        
        # Hash parameters
        param_hash = hashlib.md5(sorted_params.encode()).hexdigest()
        
        return f"{prefix}:{param_hash}"