File size: 7,984 Bytes
7cfdc4c | 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 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 | import json
from typing import Optional, Dict, List
from datetime import timedelta
from core.utils.logger import logger
class ToolGuideCache:
DEFAULT_TTL = timedelta(hours=1)
CACHE_KEY_PREFIX = "tool_guide:"
CACHE_VERSION = "v1"
def __init__(self, ttl: Optional[timedelta] = None):
self.ttl = ttl or self.DEFAULT_TTL
self.enabled = True
logger.info(f"β‘ [TOOL CACHE] Initialized with TTL={self.ttl}, using shared async Redis pool")
def _make_cache_key(self, tool_name: str) -> str:
return f"{self.CACHE_KEY_PREFIX}{self.CACHE_VERSION}:{tool_name}"
async def get_tool_guide(self, tool_name: str) -> Optional[str]:
if not self.enabled:
return None
try:
from core.services import redis as redis_service
cache_key = self._make_cache_key(tool_name)
# Use module-level function with timeout protection
cached_data = await redis_service.get(cache_key, timeout=5.0)
if cached_data:
data = json.loads(cached_data)
logger.debug(f"β
[TOOL CACHE] Hit: {tool_name}")
return data['guide']
logger.debug(f"β [TOOL CACHE] Miss: {tool_name}")
return None
except Exception as e:
logger.error(f"β [TOOL CACHE] Error reading cache for {tool_name}: {e}")
return None
async def set_tool_guide(self, tool_name: str, guide: str) -> bool:
if not self.enabled or not guide:
return False
try:
from core.services import redis as redis_service
cache_key = self._make_cache_key(tool_name)
data = {
'tool_name': tool_name,
'guide': guide,
'version': self.CACHE_VERSION
}
# Use module-level function with timeout protection
await redis_service.setex(
cache_key,
int(self.ttl.total_seconds()),
json.dumps(data),
timeout=5.0
)
logger.debug(f"πΎ [TOOL CACHE] Stored: {tool_name} (TTL={self.ttl})")
return True
except Exception as e:
logger.error(f"β [TOOL CACHE] Error caching {tool_name}: {e}")
return False
async def get_multiple(self, tool_names: List[str]) -> Dict[str, Optional[str]]:
if not self.enabled or not tool_names:
return {name: None for name in tool_names}
try:
from core.services import redis as redis_service
# Use individual gets with timeout - pipelining can be added later if needed
guides = {}
hits = 0
for tool_name in tool_names:
cache_key = self._make_cache_key(tool_name)
cached_data = await redis_service.get(cache_key, timeout=5.0)
if cached_data:
data = json.loads(cached_data)
guides[tool_name] = data['guide']
hits += 1
else:
guides[tool_name] = None
logger.info(f"β‘ [TOOL CACHE] Batch fetch: {hits}/{len(tool_names)} hits")
return guides
except Exception as e:
logger.error(f"β [TOOL CACHE] Error in batch fetch: {e}")
return {name: None for name in tool_names}
async def set_multiple(self, guides: Dict[str, str]) -> int:
if not self.enabled or not guides:
return 0
try:
from core.services import redis as redis_service
# Use individual sets with timeout - pipelining can be added later if needed
for tool_name, guide in guides.items():
if guide:
cache_key = self._make_cache_key(tool_name)
data = {
'tool_name': tool_name,
'guide': guide,
'version': self.CACHE_VERSION
}
await redis_service.setex(
cache_key,
int(self.ttl.total_seconds()),
json.dumps(data),
timeout=5.0
)
logger.info(f"πΎ [TOOL CACHE] Batch stored: {len(guides)} guides")
return len(guides)
except Exception as e:
logger.error(f"β [TOOL CACHE] Error in batch store: {e}")
return 0
async def invalidate(self, tool_name: str) -> bool:
if not self.enabled:
return False
try:
from core.services import redis as redis_service
cache_key = self._make_cache_key(tool_name)
await redis_service.delete(cache_key, timeout=2.0)
logger.info(f"ποΈ [TOOL CACHE] Invalidated: {tool_name}")
return True
except Exception as e:
logger.error(f"β [TOOL CACHE] Error invalidating {tool_name}: {e}")
return False
async def invalidate_all(self) -> int:
if not self.enabled:
return 0
try:
from core.services import redis as redis_service
pattern = f"{self.CACHE_KEY_PREFIX}{self.CACHE_VERSION}:*"
# Use scan_keys with timeout protection
keys = await redis_service.scan_keys(pattern, count=100, timeout=10.0)
if keys:
# Use batch delete for efficiency
from core.services.redis import delete_multiple
count = await delete_multiple(keys, timeout=5.0)
logger.info(f"ποΈ [TOOL CACHE] Invalidated all: {count} guides")
return count
return 0
except Exception as e:
logger.error(f"β [TOOL CACHE] Error invalidating all: {e}")
return 0
async def warm_cache(self, tool_names: List[str]) -> int:
if not self.enabled:
return 0
try:
from core.tools.tool_guide_registry import get_tool_guide
guides = {}
for tool_name in tool_names:
guide = get_tool_guide(tool_name)
if guide:
guides[tool_name] = guide
count = await self.set_multiple(guides)
logger.info(f"π₯ [TOOL CACHE] Cache warmed: {count}/{len(tool_names)} guides")
return count
except Exception as e:
logger.error(f"β [TOOL CACHE] Error warming cache: {e}")
return 0
async def get_stats(self) -> Dict[str, any]:
if not self.enabled:
return {'enabled': False}
try:
from core.services import redis as redis_service
pattern = f"{self.CACHE_KEY_PREFIX}{self.CACHE_VERSION}:*"
# Use scan_keys with timeout protection
keys = await redis_service.scan_keys(pattern, count=100, timeout=10.0)
return {
'enabled': True,
'cached_tools': len(keys),
'ttl': str(self.ttl),
'version': self.CACHE_VERSION
}
except Exception as e:
logger.error(f"β [TOOL CACHE] Error getting stats: {e}")
return {'enabled': True, 'error': str(e)}
_cache_instance: Optional[ToolGuideCache] = None
def get_tool_cache() -> ToolGuideCache:
global _cache_instance
if _cache_instance is None:
_cache_instance = ToolGuideCache()
return _cache_instance
|