cache.py 1.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960
  1. import os
  2. import time
  3. from typing import Optional, Tuple
  4. from pathlib import Path
  5. import urllib.parse
  6. from gpustack.config.config import get_global_config
  7. import logging
  8. logger = logging.getLogger(__name__)
  9. def _make_filepath(namespace: str, key: str) -> Path:
  10. config = get_global_config()
  11. safe_key = urllib.parse.quote(key, ".")
  12. return Path(config.cache_dir) / namespace / safe_key
  13. def is_cached(namespace: str, key: str, cache_expiration: Optional[int] = None) -> bool:
  14. if not namespace or not key:
  15. return False
  16. dst_file = _make_filepath(namespace, key)
  17. if not dst_file.exists():
  18. return False
  19. if cache_expiration and time.time() - os.path.getmtime(dst_file) > cache_expiration:
  20. return False
  21. return True
  22. def load_cache(
  23. namespace: str, key: str, cache_expiration: Optional[int] = None
  24. ) -> Tuple[Optional[str], bool]:
  25. try:
  26. if not is_cached(namespace, key, cache_expiration):
  27. return None, False
  28. dst_file = _make_filepath(namespace, key)
  29. with dst_file.open('r') as f:
  30. data = f.read()
  31. return data, True
  32. except Exception as e:
  33. logger.warning(f"Failed to load cache {namespace} {key} : {e}")
  34. return None, False
  35. def save_cache(namespace: str, key: str, value: str) -> bool:
  36. if not namespace or not key:
  37. return False
  38. dst_file = _make_filepath(namespace, key)
  39. dst_file.parent.mkdir(parents=True, exist_ok=True)
  40. try:
  41. with dst_file.open('w') as f:
  42. f.write(value)
  43. return True
  44. except Exception as e:
  45. logger.warning(f"Failed to save cache {namespace} {key} : {e}")
  46. return False