File size: 5,008 Bytes
a7d7463
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
"""Cache Manager - Handle application caching"""

import json
import time
import shutil
from pathlib import Path
from typing import Any, Optional, Dict
from dataclasses import dataclass, field


@dataclass
class CacheEntry:
    """Single cache entry"""

    key: str
    value: Any
    created_at: float = field(default_factory=time.time)
    expires_at: Optional[float] = None
    hits: int = 0

    def is_expired(self) -> bool:
        """Check if entry has expired"""
        if self.expires_at is None:
            return False
        return time.time() > self.expires_at


class CacheManager:
    """Manage application cache"""

    def __init__(self, cache_dir: Optional[str] = None, default_ttl: int = 3600):
        if cache_dir:
            self.cache_dir = Path(cache_dir)
        else:
            self.cache_dir = Path.home() / ".burme_coder" / "cache"

        self.cache_dir.mkdir(parents=True, exist_ok=True)
        self.default_ttl = default_ttl
        self.memory_cache: Dict[str, CacheEntry] = {}

    def get(self, key: str, use_memory: bool = True) -> Optional[Any]:
        """Get value from cache"""
        if use_memory and key in self.memory_cache:
            entry = self.memory_cache[key]
            if not entry.is_expired():
                entry.hits += 1
                return entry.value
            else:
                del self.memory_cache[key]

        cache_file = self._get_cache_file(key)
        if cache_file and cache_file.exists():
            try:
                data = json.loads(cache_file.read_text(encoding="utf-8"))
                entry = CacheEntry(
                    key=key,
                    value=data["value"],
                    created_at=data.get("created_at", time.time()),
                    expires_at=data.get("expires_at"),
                )

                if not entry.is_expired():
                    return entry.value
                else:
                    cache_file.unlink()
            except (json.JSONDecodeError, KeyError):
                pass

        return None

    def set(
        self, key: str, value: Any, ttl: Optional[int] = None, use_memory: bool = True
    ):
        """Set value in cache"""
        ttl = ttl if ttl is not None else self.default_ttl
        expires_at = time.time() + ttl if ttl > 0 else None

        if use_memory:
            self.memory_cache[key] = CacheEntry(key=key, value=value, expires_at=expires_at)

        cache_file = self._get_cache_file(key)
        if cache_file:
            cache_data = {
                "key": key,
                "value": value,
                "created_at": time.time(),
                "expires_at": expires_at,
            }
            cache_file.write_text(json.dumps(cache_data), encoding="utf-8")

    def delete(self, key: str):
        """Delete cache entry"""
        if key in self.memory_cache:
            del self.memory_cache[key]

        cache_file = self._get_cache_file(key)
        if cache_file and cache_file.exists():
            cache_file.unlink()

    def clear(self, pattern: Optional[str] = None):
        """Clear cache entries"""
        if pattern:
            for cache_file in self.cache_dir.glob(f"{pattern}*"):
                cache_file.unlink()
        else:
            for cache_file in self.cache_dir.glob("*.json"):
                cache_file.unlink()
            self.memory_cache.clear()

    def cleanup_expired(self):
        """Remove all expired entries"""
        expired_keys = [k for k, v in self.memory_cache.items() if v.is_expired()]
        for key in expired_keys:
            del self.memory_cache[key]

        for cache_file in self.cache_dir.glob("*.json"):
            try:
                data = json.loads(cache_file.read_text(encoding="utf-8"))
                if data.get("expires_at") and time.time() > data["expires_at"]:
                    cache_file.unlink()
            except (json.JSONDecodeError, KeyError):
                pass

    def get_stats(self) -> Dict:
        """Get cache statistics"""
        total_hits = sum(e.hits for e in self.memory_cache.values())
        entries_count = len(self.memory_cache)
        disk_files = len(list(self.cache_dir.glob("*.json")))

        return {
            "memory_entries": entries_count,
            "disk_files": disk_files,
            "total_hits": total_hits,
            "cache_dir": str(self.cache_dir),
        }

    def _get_cache_file(self, key: str) -> Optional[Path]:
        """Get cache file path for key"""
        safe_key = "".join(c if c.isalnum() or c in "-_" else "_" for c in key)
        if len(safe_key) > 50:
            import hashlib
            safe_key = hashlib.md5(key.encode()).hexdigest()

        return self.cache_dir / f"{safe_key}.json"

    def clear_all(self):
        """Clear all caches including memory"""
        self.memory_cache.clear()
        if self.cache_dir.exists():
            shutil.rmtree(self.cache_dir)
        self.cache_dir.mkdir(parents=True, exist_ok=True)