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