Skip to content

Staging — geocatalog.staging

Copy the remote assets a catalog points at into a local cache, and get back the same catalog with its paths rewritten to the local copies. Hand the result to the loaders or to field_for.

Staging

geocatalog.staging.stage(catalog, *, dest=None, assets=None, parallel=8, cache=None, retries=3, on_error='raise')

Resolve every URI in catalog into a local file.

Parameters:

Name Type Description Default
catalog GeoCatalog

Catalog whose rows reference remote URIs. Currently only InMemoryGeoCatalog is supported — the function returns a fresh in-memory catalog rather than mutating the input.

required
dest PathLike[str] | str | None

The cache root when cache is None. None uses geocloud.cache.LocalCache's default ($GEOCLOUD_CACHE, else ~/.cache/geocloud).

None
assets list[str] | None

When rows carry an asset map (see CatalogBundle.ingest), only fetch these keys. None stages every asset present on each row. Rows that have no asset map stage filepath regardless.

None
parallel int

Max concurrent fetches via a ThreadPoolExecutor. obstore releases the GIL on I/O, so threads scale well.

8
cache LocalCache | None

The geocloud.cache.LocalCache to fetch into. None builds one bound to dest when a remote URI needs it.

None
retries int

Per-URI retry budget for transient failures only (network failures left after the object-store client's own retries, short reads — the shared policy of geocatalog._src.utils.retry.retry_transient_io). Fatal errors such as FileNotFoundError or PermissionError fail the URI immediately; either way a failed URI is then subject to on_error.

3
on_error str

"raise" (default) — the first failure cancels the downloads not yet started and propagates. "skip" — keep the original URI in the asset map and continue; the row is emitted with whatever did succeed.

'raise'

Returns:

Type Description
GeoCatalog

A new InMemoryGeoCatalog (the input is not mutated). Each row's

GeoCatalog

filepath points at the local copy of its primary asset

GeoCatalog

(the asset whose URI was the row's filepath); it keeps

GeoCatalog

its original URI when that asset was not staged. An asset map

GeoCatalog

is rewritten to local paths. The original URIs are kept in

GeoCatalog

the staged_from column (extras["staged_from"]), a JSON

GeoCatalog

dict keyed like assets.

Raises:

Type Description
ValueError

If assets is empty or names a key that no row carries, or an argument is out of range.

ModuleNotFoundError

If a remote URI needs geotoolz-cloud (the [cloud] extra) and it is not installed.

Source code in packages/geotoolz-catalog/src/geocatalog/_src/staging/stage.py
def stage(
    catalog: GeoCatalog,
    *,
    dest: PathLike[str] | str | None = None,
    assets: list[str] | None = None,
    parallel: int = 8,
    cache: LocalCache | None = None,
    retries: int = 3,
    on_error: str = "raise",
) -> GeoCatalog:
    """Resolve every URI in ``catalog`` into a local file.

    Args:
        catalog: Catalog whose rows reference remote URIs. Currently
            only `InMemoryGeoCatalog` is supported — the function
            returns a fresh in-memory catalog rather than mutating
            the input.
        dest: The cache root when ``cache`` is ``None``. ``None`` uses
            `geocloud.cache.LocalCache`'s default (``$GEOCLOUD_CACHE``,
            else ``~/.cache/geocloud``).
        assets: When rows carry an asset map (see
            `CatalogBundle.ingest`), only fetch these keys. ``None``
            stages every asset present on each row. Rows that have
            no asset map stage ``filepath`` regardless.
        parallel: Max concurrent fetches via a
            `ThreadPoolExecutor`. obstore releases the GIL on I/O, so
            threads scale well.
        cache: The `geocloud.cache.LocalCache` to fetch into. ``None``
            builds one bound to ``dest`` when a remote URI needs it.
        retries: Per-URI retry budget for *transient* failures only
            (network failures left after the object-store client's own
            retries, short reads — the shared policy of
            `geocatalog._src.utils.retry.retry_transient_io`). Fatal errors
            such as `FileNotFoundError` or `PermissionError` fail the
            URI immediately; either way a failed URI is then subject
            to ``on_error``.
        on_error: ``"raise"`` (default) — the first failure cancels
            the downloads not yet started and propagates. ``"skip"``
            — keep the original URI in the asset map and continue;
            the row is emitted with whatever did succeed.

    Returns:
        A new `InMemoryGeoCatalog` (the input is not mutated). Each row's
        ``filepath`` points at the local copy of its primary asset
        (the asset whose URI was the row's ``filepath``); it keeps
        its original URI when that asset was not staged. An asset map
        is rewritten to local paths. The original URIs are kept in
        the ``staged_from`` column (``extras["staged_from"]``), a JSON
        dict keyed like ``assets``.

    Raises:
        ValueError: If ``assets`` is empty or names a key that no row
            carries, or an argument is out of range.
        ModuleNotFoundError: If a remote URI needs geotoolz-cloud (the
            ``[cloud]`` extra) and it is not installed.
    """
    from geocatalog._src.backends.memory import InMemoryGeoCatalog

    if not isinstance(catalog, InMemoryGeoCatalog):
        raise TypeError(
            "stage() currently supports InMemoryGeoCatalog only; got "
            f"{type(catalog).__name__}. Convert via "
            "`from_geoparquet(...)` first if you have a "
            "DuckDB-backed catalog."
        )
    if on_error not in {"raise", "skip"}:
        raise ValueError(f"on_error must be 'raise' or 'skip'; got {on_error!r}")
    if retries < 0:
        raise ValueError(f"retries must be >= 0; got {retries!r}")
    if assets is not None and not list(assets):
        raise ValueError("stage(assets=[]) stages nothing; pass assets=None for all")

    plans = [
        _plan_row(row, idx, asset_filter=assets)
        for idx, row in enumerate(catalog.gdf.itertuples())
    ]
    known = {k for plan in plans for k in plan.all_keys}
    # Rows without an asset map stage `filepath` whatever `assets` says,
    # so a filter only has keys to check when some row carries a map.
    if assets is not None and known:
        unknown = sorted(set(assets) - known)
        if unknown:
            raise ValueError(
                f"stage(assets=...) names keys no row carries: {unknown}; "
                f"known keys: {sorted(known)}"
            )

    # One unit of work per distinct URI, however many rows share it.
    users: dict[str, list[tuple[int, str]]] = {}
    for plan in plans:
        for key, uri in plan.assets.items():
            users.setdefault(uri, []).append((plan.row_idx, key))

    if cache is None and any(_local_path(uri) is None for uri in users):
        cache = _cloud_cache().LocalCache(root=dest)

    failures: dict[tuple[int, str], Exception] = {}
    pool = ThreadPoolExecutor(max_workers=max(1, parallel))
    try:
        futures: dict[Future[Path], str] = {
            pool.submit(_fetch_one, uri, cache, retries): uri for uri in users
        }
        for fut in as_completed(futures):
            uri = futures[fut]
            try:
                local_path = fut.result()
            except Exception as exc:
                # `Exception`, not `BaseException`: KeyboardInterrupt /
                # SystemExit still stop staging immediately.
                if on_error == "raise":
                    pool.shutdown(wait=True, cancel_futures=True)
                    raise
                logger.warning("stage: skipping {!r}: {}", uri, exc)
                for user in users[uri]:
                    failures[user] = exc
                continue
            for row_idx, key in users[uri]:
                plans[row_idx].results[key] = str(local_path)
    finally:
        pool.shutdown(wait=True, cancel_futures=True)

    new_gdf = _rewrite_gdf(catalog.gdf, plans, failures=failures)
    return InMemoryGeoCatalog(new_gdf, kind=catalog.kind)

The cache it fetches into is geocloud.cache.LocalCache.

Object-store pool

stage() downloads through geocloud.files on the stack's one pooled obstore client (the [cloud] extra), with credentials from geocloud.credentials; the builders read through rasterio / GDAL. To read the staged or catalogued objects with range requests, take the client from geocloud.store — one pool per process for the whole stack.