cache.py 2.48 KB
"""Small file-backed cache helpers."""

import json
from pathlib import Path
from typing import Any, Optional


class DictCache:
    """
    Simple dictionary-based cache for query rewrite rules, translations, etc.
    """

    def __init__(self, cache_file: str = ".cache/dict_cache.json"):
        self.cache_file = Path(cache_file)
        self.cache_file.parent.mkdir(parents=True, exist_ok=True)
        self.cache = self._load()

    def _load(self) -> dict:
        """Load cache from file."""
        if self.cache_file.exists():
            try:
                with open(self.cache_file, 'r', encoding='utf-8') as f:
                    return json.load(f)
            except Exception as e:
                print(f"Failed to load cache: {e}")
                return {}
        return {}

    def _save(self) -> bool:
        """Save cache to file."""
        try:
            with open(self.cache_file, 'w', encoding='utf-8') as f:
                json.dump(self.cache, f, ensure_ascii=False, indent=2)
            return True
        except Exception as e:
            print(f"Failed to save cache: {e}")
            return False

    def get(self, key: str, category: str = "default") -> Optional[Any]:
        """
        Get cached value.

        Args:
            key: Cache key
            category: Cache category (for organizing different types of data)

        Returns:
            Cached value or None
        """
        return self.cache.get(category, {}).get(key)

    def set(self, key: str, value: Any, category: str = "default") -> bool:
        """
        Store value in cache.

        Args:
            key: Cache key
            value: Value to cache
            category: Cache category

        Returns:
            True if successful
        """
        if category not in self.cache:
            self.cache[category] = {}
        self.cache[category][key] = value
        return self._save()

    def exists(self, key: str, category: str = "default") -> bool:
        """Check if key exists in cache."""
        return category in self.cache and key in self.cache[category]

    def clear(self, category: Optional[str] = None) -> bool:
        """
        Clear cache.

        Args:
            category: If specified, clear only this category. Otherwise clear all.

        Returns:
            True if successful
        """
        if category:
            if category in self.cache:
                del self.cache[category]
        else:
            self.cache = {}
        return self._save()