cache_metadata.py 8.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232
  1. from __future__ import annotations
  2. import os
  3. import pickle
  4. import time
  5. from typing import TYPE_CHECKING
  6. from fsspec.utils import atomic_write
  7. try:
  8. import ujson as json
  9. except ImportError:
  10. if not TYPE_CHECKING:
  11. import json
  12. if TYPE_CHECKING:
  13. from typing import Any, Dict, Iterator, Literal
  14. from typing_extensions import TypeAlias
  15. from .cached import CachingFileSystem
  16. Detail: TypeAlias = Dict[str, Any]
  17. class CacheMetadata:
  18. """Cache metadata.
  19. All reading and writing of cache metadata is performed by this class,
  20. accessing the cached files and blocks is not.
  21. Metadata is stored in a single file per storage directory in JSON format.
  22. For backward compatibility, also reads metadata stored in pickle format
  23. which is converted to JSON when next saved.
  24. """
  25. def __init__(self, storage: list[str]):
  26. """
  27. Parameters
  28. ----------
  29. storage: list[str]
  30. Directories containing cached files, must be at least one. Metadata
  31. is stored in the last of these directories by convention.
  32. """
  33. if not storage:
  34. raise ValueError("CacheMetadata expects at least one storage location")
  35. self._storage = storage
  36. self.cached_files: list[Detail] = [{}]
  37. # Private attribute to force saving of metadata in pickle format rather than
  38. # JSON for use in tests to confirm can read both pickle and JSON formats.
  39. self._force_save_pickle = False
  40. def _load(self, fn: str) -> Detail:
  41. """Low-level function to load metadata from specific file"""
  42. try:
  43. with open(fn, "r") as f:
  44. loaded = json.load(f)
  45. except ValueError:
  46. with open(fn, "rb") as f:
  47. loaded = pickle.load(f)
  48. for c in loaded.values():
  49. if isinstance(c.get("blocks"), list):
  50. c["blocks"] = set(c["blocks"])
  51. return loaded
  52. def _save(self, metadata_to_save: Detail, fn: str) -> None:
  53. """Low-level function to save metadata to specific file"""
  54. if self._force_save_pickle:
  55. with atomic_write(fn) as f:
  56. pickle.dump(metadata_to_save, f)
  57. else:
  58. with atomic_write(fn, mode="w") as f:
  59. json.dump(metadata_to_save, f)
  60. def _scan_locations(
  61. self, writable_only: bool = False
  62. ) -> Iterator[tuple[str, str, bool]]:
  63. """Yield locations (filenames) where metadata is stored, and whether
  64. writable or not.
  65. Parameters
  66. ----------
  67. writable: bool
  68. Set to True to only yield writable locations.
  69. Returns
  70. -------
  71. Yields (str, str, bool)
  72. """
  73. n = len(self._storage)
  74. for i, storage in enumerate(self._storage):
  75. writable = i == n - 1
  76. if writable_only and not writable:
  77. continue
  78. yield os.path.join(storage, "cache"), storage, writable
  79. def check_file(
  80. self, path: str, cfs: CachingFileSystem | None
  81. ) -> Literal[False] | tuple[Detail, str]:
  82. """If path is in cache return its details, otherwise return ``False``.
  83. If the optional CachingFileSystem is specified then it is used to
  84. perform extra checks to reject possible matches, such as if they are
  85. too old.
  86. """
  87. for (fn, base, _), cache in zip(self._scan_locations(), self.cached_files):
  88. if path not in cache:
  89. continue
  90. detail = cache[path].copy()
  91. if cfs is not None:
  92. if cfs.check_files and detail["uid"] != cfs.fs.ukey(path):
  93. # Wrong file as determined by hash of file properties
  94. continue
  95. if cfs.expiry and time.time() - detail["time"] > cfs.expiry:
  96. # Cached file has expired
  97. continue
  98. fn = os.path.join(base, detail["fn"])
  99. if os.path.exists(fn):
  100. return detail, fn
  101. return False
  102. def clear_expired(self, expiry_time: int) -> tuple[list[str], bool]:
  103. """Remove expired metadata from the cache.
  104. Returns names of files corresponding to expired metadata and a boolean
  105. flag indicating whether the writable cache is empty. Caller is
  106. responsible for deleting the expired files.
  107. """
  108. expired_files = []
  109. for path, detail in self.cached_files[-1].copy().items():
  110. if time.time() - detail["time"] > expiry_time:
  111. fn = detail.get("fn", "")
  112. if not fn:
  113. raise RuntimeError(
  114. f"Cache metadata does not contain 'fn' for {path}"
  115. )
  116. fn = os.path.join(self._storage[-1], fn)
  117. expired_files.append(fn)
  118. self.cached_files[-1].pop(path)
  119. if self.cached_files[-1]:
  120. cache_path = os.path.join(self._storage[-1], "cache")
  121. self._save(self.cached_files[-1], cache_path)
  122. writable_cache_empty = not self.cached_files[-1]
  123. return expired_files, writable_cache_empty
  124. def load(self) -> None:
  125. """Load all metadata from disk and store in ``self.cached_files``"""
  126. cached_files = []
  127. for fn, _, _ in self._scan_locations():
  128. if os.path.exists(fn):
  129. # TODO: consolidate blocks here
  130. cached_files.append(self._load(fn))
  131. else:
  132. cached_files.append({})
  133. self.cached_files = cached_files or [{}]
  134. def on_close_cached_file(self, f: Any, path: str) -> None:
  135. """Perform side-effect actions on closing a cached file.
  136. The actual closing of the file is the responsibility of the caller.
  137. """
  138. # File must be writeble, so in self.cached_files[-1]
  139. c = self.cached_files[-1][path]
  140. if c["blocks"] is not True and len(c["blocks"]) * f.blocksize >= f.size:
  141. c["blocks"] = True
  142. def pop_file(self, path: str) -> str | None:
  143. """Remove metadata of cached file.
  144. If path is in the cache, return the filename of the cached file,
  145. otherwise return ``None``. Caller is responsible for deleting the
  146. cached file.
  147. """
  148. details = self.check_file(path, None)
  149. if not details:
  150. return None
  151. _, fn = details
  152. if fn.startswith(self._storage[-1]):
  153. self.cached_files[-1].pop(path)
  154. self.save()
  155. else:
  156. raise PermissionError(
  157. "Can only delete cached file in last, writable cache location"
  158. )
  159. return fn
  160. def save(self) -> None:
  161. """Save metadata to disk"""
  162. for (fn, _, writable), cache in zip(self._scan_locations(), self.cached_files):
  163. if not writable:
  164. continue
  165. if os.path.exists(fn):
  166. cached_files = self._load(fn)
  167. for k, c in cached_files.items():
  168. if k in cache:
  169. if c["blocks"] is True or cache[k]["blocks"] is True:
  170. c["blocks"] = True
  171. else:
  172. # self.cached_files[*][*]["blocks"] must continue to
  173. # point to the same set object so that updates
  174. # performed by MMapCache are propagated back to
  175. # self.cached_files.
  176. blocks = cache[k]["blocks"]
  177. blocks.update(c["blocks"])
  178. c["blocks"] = blocks
  179. c["time"] = max(c["time"], cache[k]["time"])
  180. c["uid"] = cache[k]["uid"]
  181. # Files can be added to cache after it was written once
  182. for k, c in cache.items():
  183. if k not in cached_files:
  184. cached_files[k] = c
  185. else:
  186. cached_files = cache
  187. cache = {k: v.copy() for k, v in cached_files.items()}
  188. for c in cache.values():
  189. if isinstance(c["blocks"], set):
  190. c["blocks"] = list(c["blocks"])
  191. self._save(cache, fn)
  192. self.cached_files[-1] = cached_files
  193. def update_file(self, path: str, detail: Detail) -> None:
  194. """Update metadata for specific file in memory, do not save"""
  195. self.cached_files[-1][path] = detail