Skip to content

Utils — geocatalog.utils

Path and URI parsing, the shared retry policy and the UTC time helpers the catalog uses internally, at a public path.

Paths and URIs

geocatalog.utils.parse_uri(uri)

Split a path or URI into a ParsedURI (see the module rules).

Source code in packages/geotoolz-catalog/src/geocatalog/_src/utils/uri.py
def parse_uri(uri: str | os.PathLike[str]) -> ParsedURI:
    """Split a path or URI into a `ParsedURI` (see the module rules)."""
    if isinstance(uri, PurePath):
        text = str(uri)
        return ParsedURI(raw=text, scheme="", netloc="", path=text)
    text = os.fspath(uri)
    head, sep, _ = text.partition("://")
    if not sep or _DRIVE.match(text) or not _SCHEME.match(head):
        return ParsedURI(raw=text, scheme="", netloc="", path=text)
    parts = urlsplit(text)
    return ParsedURI(
        raw=text,
        scheme=parts.scheme.lower(),
        netloc=parts.netloc,
        path=parts.path,
        query=parts.query,
    )

geocatalog.utils.ParsedURI dataclass

A location split into the parts the catalog cares about.

Attributes:

Name Type Description
raw str

The input as a string.

scheme str

Lower-case scheme; "" for a plain local path, "file" for a file:// URI.

netloc str

Authority of a URI (bucket, host, container); "" for local paths.

path str

The path component — the URL path of a URI, the input itself for a plain local path.

query str

The raw query string of a URI ("" for local paths).

Source code in packages/geotoolz-catalog/src/geocatalog/_src/utils/uri.py
@dataclass(frozen=True)
class ParsedURI:
    """A location split into the parts the catalog cares about.

    Attributes:
        raw: The input as a string.
        scheme: Lower-case scheme; ``""`` for a plain local path,
            ``"file"`` for a ``file://`` URI.
        netloc: Authority of a URI (bucket, host, container); ``""`` for
            local paths.
        path: The path component — the URL path of a URI, the input
            itself for a plain local path.
        query: The raw query string of a URI (``""`` for local paths).
    """

    raw: str
    scheme: str
    netloc: str
    path: str
    query: str = ""

    @property
    def is_local(self) -> bool:
        """True for plain paths and ``file://`` URIs."""
        return self.scheme in ("", "file")

    @property
    def is_remote(self) -> bool:
        """True for every ``<scheme>://`` URI except ``file://``."""
        return not self.is_local

    @property
    def name(self) -> str:
        """Final path component (``""`` for a bare bucket or host)."""
        return self.path.rstrip("/\\").replace("\\", "/").rsplit("/", 1)[-1]

    @property
    def suffix(self) -> str:
        """Extension of `name`, with the dot (``""`` if none)."""
        name = self.name
        return "." + name.rsplit(".", 1)[-1] if "." in name.lstrip(".") else ""

    @property
    def is_zarr(self) -> bool:
        """True when the location is a ``.zarr`` store (trailing slash allowed)."""
        return self.suffix == ".zarr"

    def local_path(self) -> Path | None:
        """The filesystem path of a local location; ``None`` for remote URIs."""
        if self.scheme == "":
            return Path(self.raw)
        if self.scheme == "file":
            path = self.path
            if self.netloc and self.netloc != "localhost":
                path = f"//{self.netloc}{path}"  # UNC share
            return Path(url2pathname(path))
        return None

    def gdal_path(self) -> str | None:
        """GDAL ``/vsi*/`` path for a remote URI GDAL can read, else ``None``.

        ``s3://bucket/key`` → ``/vsis3/bucket/key``; ``http(s)://…`` →
        ``/vsicurl/http(s)://…``; ``abfs[s]://container@account…/key`` →
        ``/vsiaz/container/key``. Credentials come from GDAL's usual
        configuration (``AWS_*``, ``GOOGLE_APPLICATION_CREDENTIALS``,
        ``AZURE_STORAGE_*``, …).
        """
        if self.scheme in ("http", "https"):
            return f"/vsicurl/{self.raw}"
        prefix = _GDAL_VSI_PREFIXES.get(self.scheme)
        if prefix is None:
            return None
        container = self.netloc
        if self.scheme in ("abfs", "abfss"):
            container = container.split("@", 1)[0]
        return f"{prefix}{container}{self.path}"

is_local property

True for plain paths and file:// URIs.

is_remote property

True for every <scheme>:// URI except file://.

is_zarr property

True when the location is a .zarr store (trailing slash allowed).

name property

Final path component ("" for a bare bucket or host).

suffix property

Extension of name, with the dot ("" if none).

gdal_path()

GDAL /vsi*/ path for a remote URI GDAL can read, else None.

s3://bucket/key → /vsis3/bucket/key; http(s)://… → /vsicurl/http(s)://…; abfs[s]://container@account…/key → /vsiaz/container/key. Credentials come from GDAL's usual configuration (AWS_*, GOOGLE_APPLICATION_CREDENTIALS, AZURE_STORAGE_*, …).

Source code in packages/geotoolz-catalog/src/geocatalog/_src/utils/uri.py
def gdal_path(self) -> str | None:
    """GDAL ``/vsi*/`` path for a remote URI GDAL can read, else ``None``.

    ``s3://bucket/key`` → ``/vsis3/bucket/key``; ``http(s)://…`` →
    ``/vsicurl/http(s)://…``; ``abfs[s]://container@account…/key`` →
    ``/vsiaz/container/key``. Credentials come from GDAL's usual
    configuration (``AWS_*``, ``GOOGLE_APPLICATION_CREDENTIALS``,
    ``AZURE_STORAGE_*``, …).
    """
    if self.scheme in ("http", "https"):
        return f"/vsicurl/{self.raw}"
    prefix = _GDAL_VSI_PREFIXES.get(self.scheme)
    if prefix is None:
        return None
    container = self.netloc
    if self.scheme in ("abfs", "abfss"):
        container = container.split("@", 1)[0]
    return f"{prefix}{container}{self.path}"

local_path()

The filesystem path of a local location; None for remote URIs.

Source code in packages/geotoolz-catalog/src/geocatalog/_src/utils/uri.py
def local_path(self) -> Path | None:
    """The filesystem path of a local location; ``None`` for remote URIs."""
    if self.scheme == "":
        return Path(self.raw)
    if self.scheme == "file":
        path = self.path
        if self.netloc and self.netloc != "localhost":
            path = f"//{self.netloc}{path}"  # UNC share
        return Path(url2pathname(path))
    return None

Retries

geocatalog.utils.retry_transient_io(fn, *args, retries, **kwargs)

Call fn with retries for transient remote I/O exceptions.

Parameters:

Name Type Description Default
fn Callable[..., T]

Callable to invoke.

required
*args Any

Positional args forwarded to fn.

()
retries int

Number of retries after the initial attempt. 0 disables retry/backoff (the call runs exactly once and any exception propagates immediately). Must be >= 0.

required
**kwargs Any

Keyword args forwarded to fn.

{}

Returns:

Type Description
T

Whatever fn returns.

Notes

Only RasterioIOError, urllib3.exceptions.ReadTimeoutError, and non-fatal OSError instances are retried; an HTTP error (urllib's HTTPError or one carrying a response.status_code) only for 408 / 425 / 429 and any 5xx. Fatal OSError subclasses (FileNotFoundError, PermissionError, IsADirectoryError, NotADirectoryError, InterruptedError) are re-raised on the first attempt — there is no benefit to waiting on them.

Source code in packages/geotoolz-catalog/src/geocatalog/_src/utils/retry.py
def retry_transient_io[T](
    fn: Callable[..., T],
    *args: Any,
    retries: int,
    **kwargs: Any,
) -> T:
    """Call ``fn`` with retries for transient remote I/O exceptions.

    Args:
        fn: Callable to invoke.
        *args: Positional args forwarded to ``fn``.
        retries: Number of retries after the initial attempt. ``0`` disables
            retry/backoff (the call runs exactly once and any exception
            propagates immediately). Must be ``>= 0``.
        **kwargs: Keyword args forwarded to ``fn``.

    Returns:
        Whatever ``fn`` returns.

    Notes:
        Only `RasterioIOError`, `urllib3.exceptions.ReadTimeoutError`, and
        non-fatal `OSError` instances are retried; an HTTP error (urllib's
        `HTTPError` or one carrying a ``response.status_code``) only for
        408 / 425 / 429 and any 5xx. Fatal `OSError` subclasses
        (`FileNotFoundError`, `PermissionError`, `IsADirectoryError`,
        `NotADirectoryError`, `InterruptedError`) are re-raised on the first
        attempt — there is no benefit to waiting on them.
    """
    if retries < 0:
        raise ValueError(f"retries must be >= 0; got {retries}")
    if retries == 0:
        return fn(*args, **kwargs)

    retryer = Retrying(
        retry=retry_if_exception(_is_transient),
        stop=stop_after_attempt(retries + 1),
        wait=_RETRY_WAIT,
        before_sleep=_log_before_sleep,
        reraise=True,
    )
    return retryer(fn, *args, **kwargs)

Time

geocatalog.utils.to_utc_ts(value)

Coerce any datetime-like to a UTC-aware pd.Timestamp.

Naive inputs are assumed UTC (the catalog's stored time-axis contract) and localised; tz-aware inputs in other zones are converted.

Parameters:

Name Type Description Default
value Any

Anything pd.Timestamp accepts — ISO string, datetime, pd.Timestamp, epoch-like.

required

Returns:

Type Description
Timestamp

A tz-aware pd.Timestamp in UTC.

Source code in packages/geotoolz-catalog/src/geocatalog/_src/utils/timeutil.py
def to_utc_ts(value: Any) -> pd.Timestamp:
    """Coerce any datetime-like to a UTC-aware `pd.Timestamp`.

    Naive inputs are assumed UTC (the catalog's stored time-axis
    contract) and localised; tz-aware inputs in other zones are
    converted.

    Args:
        value: Anything `pd.Timestamp` accepts — ISO string, ``datetime``,
            ``pd.Timestamp``, epoch-like.

    Returns:
        A tz-aware ``pd.Timestamp`` in UTC.
    """
    ts = pd.Timestamp(value)
    return ts.tz_localize("UTC") if ts.tzinfo is None else ts.tz_convert("UTC")

geocatalog.utils.to_naive_utc(value)

Coerce a datetime-like to the catalog's stored form: naive, in UTC.

Naive inputs are returned unchanged (they are UTC by contract); tz-aware inputs are converted to UTC and the zone dropped. NaT passes through.

Parameters:

Name Type Description Default
value Any

Anything pd.Timestamp accepts.

required

Returns:

Type Description
Timestamp

A tz-naive pd.Timestamp (or pd.NaT).

Source code in packages/geotoolz-catalog/src/geocatalog/_src/utils/timeutil.py
def to_naive_utc(value: Any) -> pd.Timestamp:
    """Coerce a datetime-like to the catalog's stored form: naive, in UTC.

    Naive inputs are returned unchanged (they are UTC by contract);
    tz-aware inputs are converted to UTC and the zone dropped. ``NaT``
    passes through.

    Args:
        value: Anything `pd.Timestamp` accepts.

    Returns:
        A tz-naive ``pd.Timestamp`` (or ``pd.NaT``).
    """
    ts = pd.Timestamp(value)
    if ts is pd.NaT or ts.tzinfo is None:
        return ts
    return ts.tz_convert("UTC").tz_localize(None)

geocatalog.utils.to_rfc3339(value)

Serialize a datetime-like as RFC 3339 in UTC with a Z suffix.

.isoformat() on a UTC-aware Timestamp yields ...+00:00; the STAC-canonical form uses Z, so the offset is normalised.

Parameters:

Name Type Description Default
value Any

Anything pd.Timestamp accepts. Naive inputs are assumed UTC (see to_utc_ts).

required

Returns:

Type Description
An RFC 3339 string, e.g. ``"2024-06-15T10

00:00Z"``.

Source code in packages/geotoolz-catalog/src/geocatalog/_src/utils/timeutil.py
def to_rfc3339(value: Any) -> str:
    """Serialize a datetime-like as RFC 3339 in UTC with a ``Z`` suffix.

    ``.isoformat()`` on a UTC-aware Timestamp yields ``...+00:00``; the
    STAC-canonical form uses ``Z``, so the offset is normalised.

    Args:
        value: Anything `pd.Timestamp` accepts. Naive inputs are assumed
            UTC (see `to_utc_ts`).

    Returns:
        An RFC 3339 string, e.g. ``"2024-06-15T10:00:00Z"``.
    """
    return to_utc_ts(value).isoformat().replace("+00:00", "Z")

geocatalog.utils.is_time_invariant(interval)

True for the sentinel interval of a time-invariant row.

Source code in packages/geotoolz-catalog/src/geocatalog/_src/utils/timeutil.py
def is_time_invariant(interval: pd.Interval) -> bool:
    """True for the sentinel interval of a time-invariant row."""
    return (
        interval.left == TIME_INVARIANT_START and interval.right == TIME_INVARIANT_END
    )

geocatalog.utils.TIME_INVARIANT_START = pd.Timestamp('1900-01-01') module-attribute

geocatalog.utils.TIME_INVARIANT_END = pd.Timestamp('2100-01-01') module-attribute