|
| 1 | +import json |
| 2 | +import logging |
| 3 | +from datetime import datetime |
| 4 | +from typing import Any, Optional |
| 5 | + |
| 6 | +from pydantic import BaseModel, ValidationError, field_validator |
| 7 | + |
| 8 | +from twyn.base.exceptions import PackageNormalizingError |
| 9 | +from twyn.base.utils import normalize_packages |
| 10 | +from twyn.file_handler.exceptions import PathIsNotFileError, PathNotFoundError |
| 11 | +from twyn.file_handler.file_handler import FileHandler |
| 12 | +from twyn.trusted_packages.constants import TRUSTED_PACKAGES_MAX_RETENTION_DAYS |
| 13 | + |
| 14 | +logger = logging.getLogger("twyn") |
| 15 | + |
| 16 | + |
| 17 | +class CacheEntry(BaseModel): |
| 18 | + saved_date: str |
| 19 | + packages: set[str] |
| 20 | + |
| 21 | + @field_validator("saved_date") |
| 22 | + @classmethod |
| 23 | + def validate_saved_date(cls, v: str) -> str: |
| 24 | + try: |
| 25 | + datetime.fromisoformat(v) |
| 26 | + except (ValueError, TypeError) as e: |
| 27 | + raise ValueError(f"Invalid saved_date format: {e}") from e |
| 28 | + else: |
| 29 | + return v |
| 30 | + |
| 31 | + @field_validator("packages") |
| 32 | + @classmethod |
| 33 | + def validate_packages(cls, v: set[str]) -> set[str]: |
| 34 | + try: |
| 35 | + return normalize_packages(v) |
| 36 | + except PackageNormalizingError as e: |
| 37 | + raise ValueError(f"Failed to normalize packages: {e}") from e |
| 38 | + |
| 39 | + |
| 40 | +class CacheContent(BaseModel): |
| 41 | + entries: dict[str, CacheEntry] |
| 42 | + |
| 43 | + def get_entry(self, source: str) -> Optional[CacheEntry]: |
| 44 | + return self.entries.get(source, None) |
| 45 | + |
| 46 | + def add_or_modify_entry(self, source: str, data: CacheEntry) -> None: |
| 47 | + self.entries[source] = data |
| 48 | + |
| 49 | + |
| 50 | +class CacheHandler: |
| 51 | + """Cache class that provides basic read/write/delete operation for the caching system, as well as integrity validation checks.""" |
| 52 | + |
| 53 | + def __init__(self, file_handler: FileHandler) -> None: |
| 54 | + self._file_handler = file_handler |
| 55 | + self._content: Optional[CacheContent] = None |
| 56 | + |
| 57 | + @property |
| 58 | + def content(self) -> CacheContent: |
| 59 | + if self._content: |
| 60 | + return self._content |
| 61 | + self._content = self._get_cache_content() |
| 62 | + return self._content |
| 63 | + |
| 64 | + def exists(self) -> bool: |
| 65 | + """Check if cache file exists.""" |
| 66 | + return self._file_handler.exists() |
| 67 | + |
| 68 | + def is_entry_outdated(self, entry: CacheEntry) -> bool: |
| 69 | + """Check if a cache entry is outdated based on retention days.""" |
| 70 | + try: |
| 71 | + saved_date = datetime.fromisoformat(entry.saved_date).date() |
| 72 | + days_diff = (datetime.today().date() - saved_date).days |
| 73 | + except (ValueError, AttributeError): |
| 74 | + logger.warning("Invalid date format in cache entry") |
| 75 | + return True |
| 76 | + else: |
| 77 | + return days_diff > TRUSTED_PACKAGES_MAX_RETENTION_DAYS |
| 78 | + |
| 79 | + def write_entry(self, source: str, data: CacheEntry) -> None: |
| 80 | + """Given a source and a CacheEntry, saves to contents to cache.""" |
| 81 | + self.content.add_or_modify_entry(source, data) |
| 82 | + self._write(json.loads(self.content.model_dump_json())) |
| 83 | + |
| 84 | + def get_cache_entry(self, source: str) -> Optional[CacheEntry]: |
| 85 | + """Retrieve cache contents from a given source.""" |
| 86 | + entry = self.content.get_entry(source) |
| 87 | + if entry and not self.is_entry_outdated(entry): |
| 88 | + return entry |
| 89 | + return None |
| 90 | + |
| 91 | + def clear(self) -> None: |
| 92 | + """Delete cache file and its parent directory if empty.""" |
| 93 | + self._file_handler.delete(delete_parent_dir=True) |
| 94 | + |
| 95 | + def _read(self) -> dict[str, Any]: |
| 96 | + """Read and parse cache file as JSON.""" |
| 97 | + try: |
| 98 | + content = self._file_handler.read() |
| 99 | + except (PathNotFoundError, PathIsNotFileError): |
| 100 | + logger.info("Cache file not found") |
| 101 | + return {} |
| 102 | + |
| 103 | + try: |
| 104 | + return json.loads(content) |
| 105 | + except json.JSONDecodeError as e: |
| 106 | + logger.warning("Failed to decode JSON from cache file: %s", e) |
| 107 | + return {} |
| 108 | + |
| 109 | + def _write(self, data: dict[str, Any]) -> None: |
| 110 | + """Write data to cache file as JSON.""" |
| 111 | + try: |
| 112 | + json_content = json.dumps(data) |
| 113 | + except (TypeError, ValueError): |
| 114 | + logger.exception("Failed to serialize data to JSON") |
| 115 | + return None |
| 116 | + |
| 117 | + # Ensure parent directory exists |
| 118 | + self._file_handler.file_path.parent.mkdir(parents=True, exist_ok=True) |
| 119 | + self._file_handler.write(json_content) |
| 120 | + logger.debug("Successfully wrote cache data to %s", self._file_handler.file_path) |
| 121 | + |
| 122 | + def _get_cache_content(self) -> CacheContent: |
| 123 | + """Get all cache content.""" |
| 124 | + content = self._read() |
| 125 | + try: |
| 126 | + if content: |
| 127 | + return CacheContent(**content) |
| 128 | + except ValidationError: |
| 129 | + logger.exception("Could not read cache. Cache is corrupt.") |
| 130 | + |
| 131 | + return CacheContent(entries={}) |
0 commit comments