|
| 1 | +import json |
| 2 | +import logging |
| 3 | +import os |
| 4 | +from datetime import datetime |
| 5 | +from hashlib import md5 |
| 6 | +from pathlib import Path |
| 7 | +from typing import Optional |
| 8 | + |
| 9 | +from pydantic import BaseModel, ValidationError, field_validator |
| 10 | + |
| 11 | +from twyn.base.exceptions import PackageNormalizingError |
| 12 | +from twyn.base.utils import normalize_packages |
| 13 | +from twyn.file_handler.exceptions import PathIsNotFileError, PathNotFoundError |
| 14 | +from twyn.file_handler.file_handler import FileHandler |
| 15 | +from twyn.trusted_packages.constants import CACHE_DIR, TRUSTED_PACKAGES_MAX_RETENTION_DAYS |
| 16 | + |
| 17 | +logger = logging.getLogger("twyn") |
| 18 | + |
| 19 | + |
| 20 | +class CacheEntry(BaseModel): |
| 21 | + saved_date: str |
| 22 | + packages: set[str] |
| 23 | + |
| 24 | + @field_validator("saved_date") |
| 25 | + @classmethod |
| 26 | + def validate_saved_date(cls, v: str) -> str: |
| 27 | + try: |
| 28 | + datetime.fromisoformat(v) |
| 29 | + except (ValueError, TypeError) as e: |
| 30 | + raise ValueError(f"Invalid saved_date format: {e}") from e |
| 31 | + else: |
| 32 | + return v |
| 33 | + |
| 34 | + @field_validator("packages") |
| 35 | + @classmethod |
| 36 | + def validate_packages(cls, v: set[str]) -> set[str]: |
| 37 | + try: |
| 38 | + return normalize_packages(v) |
| 39 | + except PackageNormalizingError as e: |
| 40 | + raise ValueError(f"Failed to normalize packages: {e}") from e |
| 41 | + |
| 42 | + |
| 43 | +class CacheHandler: |
| 44 | + """Cache class that provides basic read/write/delete operation for individual source cache files.""" |
| 45 | + |
| 46 | + def __init__(self, cache_dir: str = CACHE_DIR) -> None: |
| 47 | + self.cache_dir = cache_dir |
| 48 | + |
| 49 | + def write_entry(self, source: str, data: CacheEntry) -> None: |
| 50 | + """Save cache entry to source-specific cache file.""" |
| 51 | + file_handler = self._get_file_handler(source) |
| 52 | + # Ensure parent directory exists |
| 53 | + file_handler.file_path.parent.mkdir(parents=True, exist_ok=True) |
| 54 | + file_handler.write(data.model_dump_json()) |
| 55 | + logger.debug("Successfully wrote cache data to %s", file_handler.file_path) |
| 56 | + |
| 57 | + def get_cache_entry(self, source: str) -> Optional[CacheEntry]: |
| 58 | + """Retrieve cache entry from source-specific cache file.""" |
| 59 | + file_handler = self._get_file_handler(source) |
| 60 | + try: |
| 61 | + content = file_handler.read() |
| 62 | + except (PathNotFoundError, PathIsNotFileError): |
| 63 | + logger.debug("Cache file not found: %s", file_handler.file_path) |
| 64 | + return None |
| 65 | + |
| 66 | + try: |
| 67 | + json_content = json.loads(content) |
| 68 | + except json.JSONDecodeError as e: |
| 69 | + logger.warning("Failed to decode JSON from cache file %s: %s", file_handler.file_path, e) |
| 70 | + return None |
| 71 | + |
| 72 | + if not json_content: |
| 73 | + return None |
| 74 | + |
| 75 | + try: |
| 76 | + entry = CacheEntry(**json_content) |
| 77 | + if not self.is_entry_outdated(entry): |
| 78 | + return entry |
| 79 | + except ValidationError: |
| 80 | + logger.warning("Could not read cache for source %s. Cache is corrupt.", source) |
| 81 | + self._clear_entry(source) |
| 82 | + |
| 83 | + return None |
| 84 | + |
| 85 | + def is_entry_outdated(self, entry: CacheEntry) -> bool: |
| 86 | + """Check if a cache entry is outdated based on retention days.""" |
| 87 | + try: |
| 88 | + saved_date = datetime.fromisoformat(entry.saved_date).date() |
| 89 | + days_diff = (datetime.today().date() - saved_date).days |
| 90 | + except (ValueError, AttributeError): |
| 91 | + logger.warning("Invalid date format in cache entry") |
| 92 | + return True |
| 93 | + else: |
| 94 | + return days_diff > TRUSTED_PACKAGES_MAX_RETENTION_DAYS |
| 95 | + |
| 96 | + def clear_all(self) -> None: |
| 97 | + """Delete all cache files in the cache directory.""" |
| 98 | + for root, _dirs, files in os.walk(self.cache_dir): |
| 99 | + for file in files: |
| 100 | + if file.endswith(".json"): |
| 101 | + FileHandler(os.path.join(root, file)).delete() |
| 102 | + |
| 103 | + # Remove parent directory if it exists and is empty |
| 104 | + cache_path = Path(self.cache_dir) |
| 105 | + if cache_path.exists() and cache_path.is_dir(): |
| 106 | + try: |
| 107 | + cache_path.rmdir() |
| 108 | + except OSError: |
| 109 | + logger.exception("Could not delete cache directory.") |
| 110 | + |
| 111 | + def get_cache_file_path(self, source: str) -> str: |
| 112 | + """Generate cache file path for a specific source.""" |
| 113 | + safe_filename = md5(source.encode()).hexdigest() |
| 114 | + return str(Path(self.cache_dir) / f"{safe_filename}.json") |
| 115 | + |
| 116 | + def _get_file_handler(self, source: str) -> FileHandler: |
| 117 | + """Get file handler for a specific source cache file.""" |
| 118 | + cache_file_path = self.get_cache_file_path(source) |
| 119 | + return FileHandler(cache_file_path) |
| 120 | + |
| 121 | + def _clear_entry(self, source: str) -> None: |
| 122 | + """Delete cache file for a specific source.""" |
| 123 | + file_handler = self._get_file_handler(source) |
| 124 | + file_handler.delete(delete_parent_dir=False) |
0 commit comments