Source code for seagrid.download.cache

"""Local cache files that survive interrupted downloads.

Every download in seagrid is written to ``<target>.partial`` and moved into
place only when it is complete (:func:`partial`, :func:`finish`).  A file or
Zarr store that exists under its final name is therefore either complete or
was written by something else, and :func:`is_complete` checks the second
case: a Zarr store with metadata but no data chunks, or a netCDF file that
cannot be opened.

Adapted from ``tracmass.seagrid.zarr_cache`` (tracmass_jax).
"""

from __future__ import annotations

import os
import pathlib
import shutil
import warnings

from seagrid.typing import PathLike

__all__ = ["cached", "discard", "finish", "has_zarr_data", "is_complete", "partial"]

PARTIAL_SUFFIX = ".partial"
_ZARR_METADATA = frozenset({"zarr.json", ".zarray", ".zattrs", ".zgroup", ".zmetadata"})
_NETCDF_SUFFIXES = frozenset({".nc", ".nc4", ".h5", ".hdf", ".he5", ".cdf"})


[docs] def partial(path: PathLike) -> pathlib.Path: """Return where a download of *path* is written until it is complete. Parameters ---------- path : str or os.PathLike Final file or Zarr store. Returns ------- pathlib.Path *path* with ``.partial`` appended to its name. Examples -------- >>> partial("/data/x.nc").name 'x.nc.partial' """ path = pathlib.Path(path) return path.with_name(path.name + PARTIAL_SUFFIX)
def _remove(path: pathlib.Path) -> None: if path.is_dir() and not path.is_symlink(): shutil.rmtree(path) elif path.exists() or path.is_symlink(): path.unlink()
[docs] def discard(path: PathLike) -> None: """Remove the partial download of *path*, if there is one. Parameters ---------- path : str or os.PathLike Final file or Zarr store (not the ``.partial`` name). """ _remove(partial(path))
[docs] def finish(path: PathLike) -> pathlib.Path: """Move a completed download from :func:`partial` into place at *path*. An existing file or store at *path* is replaced. Parameters ---------- path : str or os.PathLike Final file or Zarr store. Returns ------- pathlib.Path *path*. Raises ------ FileNotFoundError If there is no partial download of *path*. """ path = pathlib.Path(path) tmp = partial(path) if not tmp.exists(): raise FileNotFoundError(f"no partial download at {tmp}") _remove(path) os.replace(tmp, path) return path
[docs] def has_zarr_data(path: PathLike, name: str | None = None) -> bool: """Return True if a Zarr store holds data chunks. Parameters ---------- path : str or os.PathLike The store. name : str, optional Variable to check. Default: any variable. Returns ------- bool False if the store or variable is missing or holds only metadata. """ path = pathlib.Path(path) def var_has_chunks(vdir: pathlib.Path) -> bool: # os.scandir stops at the first chunk instead of listing thousands. try: with os.scandir(vdir) as entries: return any(e.name not in _ZARR_METADATA for e in entries) except (FileNotFoundError, NotADirectoryError): return False if name is not None: return var_has_chunks(path / name) try: with os.scandir(path) as entries: return any( e.is_dir() and var_has_chunks(pathlib.Path(e.path)) for e in entries ) except (FileNotFoundError, NotADirectoryError): return False
[docs] def is_complete(path: PathLike, data_var: str | None = None) -> bool: """Return True if *path* is a usable cached file or store. - A Zarr store (a directory) must hold data chunks, for *data_var* if given. - A netCDF/HDF file must open with :mod:`xarray` and contain *data_var* if given. - Any other file must be non-empty. Parameters ---------- path : str or os.PathLike The cached file or store. data_var : str, optional Variable that must be present. Returns ------- bool """ path = pathlib.Path(path) if path.is_dir(): return has_zarr_data(path, data_var) if not path.is_file() or path.stat().st_size == 0: return False if path.suffix.lower() not in _NETCDF_SUFFIXES: return True import xarray as xr try: with warnings.catch_warnings(): warnings.simplefilter("ignore") with xr.open_dataset(path) as ds: return data_var is None or data_var in ds.variables except (OSError, ValueError, RuntimeError): return False
[docs] def cached( path: PathLike, data_var: str | None = None, *, force: bool = False, label: str = "seagrid", ) -> bool: """Return True if *path* is cached and should not be downloaded again. Parameters ---------- path : str or os.PathLike The cached file or store. data_var : str, optional Variable that must be present. force : bool, optional If True, never cached (download again). Default False. label : str, optional Name used in the warning. Returns ------- bool Warns ----- UserWarning If *path* exists but is incomplete; it will be downloaded again. """ path = pathlib.Path(path) if force or not path.exists(): return False if is_complete(path, data_var): return True warnings.warn( f"{label}: {path} is incomplete (an interrupted download?); " "downloading it again", stacklevel=2, ) return False