File size: 1,643 Bytes
ec37394
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
"""🏆 LRU Cache for Analysis Results"""
from functools import lru_cache
from typing import Optional, Dict, Any
import hashlib
import logging

logger = logging.getLogger(__name__)

# Cache storage
_cache_store: Dict[str, Any] = {}

def get_cache_key(language: str, code: str) -> str:
    """Generate cache key from code hash"""
    code_hash = hashlib.sha256(code.encode()).hexdigest()
    return f"{language}:{code_hash[:16]}"

def get_cached_analysis(key: str) -> Optional[Dict[str, Any]]:
    """Get cached analysis result"""
    try:
        if key in _cache_store:
            logger.info(f"Cache hit for key: {key[:20]}...")
            return _cache_store[key]
        return None
    except Exception as e:
        logger.error(f"Cache retrieval error: {e}")
        return None

def cache_analysis(key: str, result: Dict[str, Any]) -> None:
    """Store analysis result in cache"""
    try:
        _cache_store[key] = result
        logger.debug(f"Cached result for key: {key[:20]}...")
        
        # Evict oldest if cache too large
        if len(_cache_store) > 1000:
            oldest = next(iter(_cache_store))
            del _cache_store[oldest]
            logger.debug(f"Evicted cache key: {oldest[:20]}...")
    except Exception as e:
        logger.error(f"Cache storage error: {e}")

def clear_cache() -> None:
    """Clear entire cache"""
    _cache_store.clear()
    logger.info("Cache cleared")

def get_cache_stats() -> Dict[str, Any]:
    """Get cache statistics"""
    return {
        "size": len(_cache_store),
        "max_size": 1000,
        "utilization": f"{len(_cache_store) / 1000 * 100:.1f}%"
    }