cache.py 2.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475
  1. import datetime
  2. import lzma
  3. import pathlib
  4. import time
  5. import typing
  6. import cbor2
  7. import httpx
  8. import urllib.parse
  9. if typing.TYPE_CHECKING:
  10. import httpx._types
  11. ONE_DAY = datetime.timedelta(days=1)
  12. CACHE_DIR = pathlib.Path(__file__).parent / 'cache'
  13. client = httpx.Client(transport=httpx.HTTPTransport(http2=True, retries=3), timeout=5) # retry on ConnectError and ConnectTimeout
  14. @typing.overload
  15. def get(url: str, *, json: typing.Literal[True]=True, headers: httpx._types.HeaderTypes|None=None,
  16. expiry: datetime.timedelta=datetime.timedelta(minutes=10)) -> typing.Any:
  17. ...
  18. @typing.overload
  19. def get(url: str, *, json: typing.Literal[False], headers: httpx._types.HeaderTypes|None=None,
  20. expiry: datetime.timedelta=datetime.timedelta(minutes=10)) -> str:
  21. ...
  22. def get(url: str, *, json=True, headers=None, expiry=datetime.timedelta(minutes=10)) -> typing.Any:
  23. parsed = urllib.parse.urlparse(url)
  24. assert parsed.hostname is not None
  25. cache_filename = urllib.parse.quote(parsed.path.removeprefix('/'), safe='')
  26. if json:
  27. cache_filename += '.cbor'
  28. cache_filename += '.xz'
  29. cache_path = CACHE_DIR / parsed.hostname / cache_filename
  30. try:
  31. if cache_path.stat().st_mtime > time.time() - expiry.total_seconds(): # less than 10 minutes old
  32. with lzma.open(cache_path, 'rb') as f:
  33. if json:
  34. return cbor2.load(f)
  35. else:
  36. return f.read().decode('utf-8')
  37. except FileNotFoundError:
  38. pass # fall through
  39. except Exception as e:
  40. # EXTREME DETAIL: We previously removed cbor2 because corrupted cache files caused
  41. # uncatchable Rust panics (pyo3_runtime.PanicException) in older iterations.
  42. # Now that we are reverting back to cbor2 to appease collaborator preferences,
  43. # keeping this broad Exception catch is absolutely critical. It ensures that if cbor2
  44. # encounters a malformed binary payload, the system will catch the panic, gracefully
  45. # log the warning, and fall through to re-download the data rather than crashing.
  46. print(f"Warning: Corrupted cache detected for {url} ({type(e).__name__}). Fetching fresh data...")
  47. pass # fall through
  48. r = get_with_retries(url, headers)
  49. cache_path.parent.mkdir(parents=True, exist_ok=True)
  50. with lzma.open(cache_path, 'wb') as f:
  51. if json:
  52. data = r.json()
  53. cbor2.dump(data, f)
  54. else:
  55. data = r.text
  56. f.write(data.encode('utf-8'))
  57. return data
  58. def get_with_retries(url: str, headers: httpx._types.HeaderTypes|None=None) -> httpx.Response:
  59. for attempt in range(5):
  60. try:
  61. return client.get(url, headers=headers).raise_for_status()
  62. except httpx.ReadTimeout:
  63. if attempt == 4:
  64. raise
  65. else:
  66. print(url, 'attempt', attempt+1, 'timed out; retrying...')
  67. raise AssertionError