Your browser sucks, JavaScript disabled! Gunnar's console needs JavaScript and WebAssembly. Git over SSH on port 2222 does not.

nordisk/korp-map

python/src/korp_map_client/_files.py

"""File downloads (``/v1/files``): listing, Range-resumed download, and Parquet reads
over HTTP Range that fetch only the row groups a bbox needs."""

from __future__ import annotations

import hashlib
import io
import json
import os
import re
import sys
from pathlib import Path
from typing import TYPE_CHECKING, Any, Callable, Sequence

import httpx
import pyarrow as pa
import pyarrow.compute as pc
import pyarrow.parquet as pq

if TYPE_CHECKING:  # pragma: no cover
    from ._client import Client

Progress = Callable[[int, "int | None"], None]
_CONTENT_RANGE = re.compile(r"bytes (\d+)-(\d+)/(\d+|\*)")


class HTTPRangeFile(io.RawIOBase):
    """A read-only, seekable file over HTTP Range requests (what pyarrow reads Parquet from).

    Each read that misses the cached block is one ``Range: bytes=a-b`` request of at
    least ``min_fetch`` bytes. ``requests`` and ``bytes_fetched`` count the traffic.
    A server that ignores Range (answers 200) is read once, whole.
    """

    def __init__(self, http: httpx.Client, url: str, size: int | None = None, *, min_fetch: int = 64 * 1024) -> None:
        super().__init__()
        self._http = http
        self.url = url
        self.min_fetch = min_fetch
        self.requests = 0
        self.bytes_fetched = 0
        self._pos = 0
        self._block_start = 0
        self._block = b""
        self._size = size if size is not None else self._head_size()

    def _head_size(self) -> int:
        from ._client import KorpMapError, _error_from

        r = self._http.head(self.url, headers={"accept-encoding": "identity"})
        self.requests += 1
        if r.status_code >= 400:
            raise _error_from(r)
        n = r.headers.get("content-length")
        if n is None:
            raise KorpMapError(f"HEAD {self.url} gave no content-length", status=r.status_code)
        return int(n)

    # -- io.RawIOBase ----------------------------------------------------------
    @property
    def size(self) -> int:
        return self._size

    def readable(self) -> bool:
        return True

    def seekable(self) -> bool:
        return True

    def tell(self) -> int:
        return self._pos

    def seek(self, offset: int, whence: int = io.SEEK_SET) -> int:
        if whence == io.SEEK_SET:
            pos = offset
        elif whence == io.SEEK_CUR:
            pos = self._pos + offset
        elif whence == io.SEEK_END:
            pos = self._size + offset
        else:
            raise ValueError(f"bad whence {whence}")
        if pos < 0:
            raise ValueError("negative seek position")
        self._pos = pos
        return pos

    def readinto(self, b: Any) -> int:
        mv = memoryview(b).cast("B")
        n = min(len(mv), max(0, self._size - self._pos))
        if n == 0:
            return 0
        start, end = self._pos, self._pos + n
        if not (self._block_start <= start and end <= self._block_start + len(self._block)):
            self._fetch(start, max(end, min(start + self.min_fetch, self._size)))
        off = start - self._block_start
        mv[:n] = self._block[off : off + n]
        self._pos = end
        return n

    def _fetch(self, start: int, end: int) -> None:
        from ._client import KorpMapError, _error_from

        r = self._http.get(self.url, headers={"range": f"bytes={start}-{end - 1}", "accept-encoding": "identity"})
        self.requests += 1
        if r.status_code >= 400:
            raise _error_from(r)
        body = r.content
        self.bytes_fetched += len(body)
        if r.status_code == 206:
            m = _CONTENT_RANGE.match(r.headers.get("content-range", ""))
            got = int(m.group(1)) if m else start
            if got != start or len(body) < end - start:
                raise KorpMapError(f"short range reply for bytes {start}-{end - 1} of {self.url}", status=206)
            self._block_start, self._block = start, body
        else:  # 200: the server ignored Range; keep the whole body
            if len(body) != self._size:
                raise KorpMapError(f"{self.url}: {len(body)} bytes, expected {self._size}", status=r.status_code)
            self._block_start, self._block = 0, body


# -- bbox pruning ----------------------------------------------------------------


def _geo_meta(pf: pq.ParquetFile) -> dict[str, Any]:
    raw = (pf.metadata.metadata or {}).get(b"geo")
    if not raw:
        return {}
    try:
        out = json.loads(raw)
    except ValueError:
        return {}
    return out if isinstance(out, dict) else {}


def primary_geometry(pf: pq.ParquetFile) -> str:
    geo = _geo_meta(pf)
    name = geo.get("primary_column")
    if isinstance(name, str):
        return name
    names = pf.schema_arrow.names
    return "geometry" if "geometry" in names else names[0]


def _covering(pf: pq.ParquetFile, geom: str) -> dict[str, list[str]] | None:
    """The GeoParquet 1.1 covering bbox paths ({"xmin": ["bbox", "xmin"], ...}) if present."""
    cov = (_geo_meta(pf).get("columns", {}).get(geom) or {}).get("covering", {}).get("bbox")
    if isinstance(cov, dict) and all(isinstance(cov.get(k), list) for k in ("xmin", "ymin", "xmax", "ymax")):
        return cov
    if "bbox" in pf.schema_arrow.names:  # the osm-katana convention, even without metadata
        t = pf.schema_arrow.field("bbox").type
        if pa.types.is_struct(t) and {"xmin", "ymin", "xmax", "ymax"} <= {f.name for f in t}:
            return {k: ["bbox", k] for k in ("xmin", "ymin", "xmax", "ymax")}
    return None


def _overlaps(xmin: float, ymin: float, xmax: float, ymax: float, q: Sequence[float]) -> bool:
    return not (xmin > q[2] or xmax < q[0] or ymin > q[3] or ymax < q[1])


def row_groups_for_bbox(pf: pq.ParquetFile, bbox: Sequence[float] | None) -> list[int]:
    """Row groups that may hold rows touching ``bbox``, from the covering column's
    statistics (GeoParquet 1.1) or the geometry column's geospatial statistics
    (GeoParquet 2.0 / Parquet GEOMETRY). A row group without statistics is kept."""
    md = pf.metadata
    every = list(range(md.num_row_groups))
    if bbox is None:
        return every
    geom = primary_geometry(pf)
    cov = _covering(pf, geom)
    keep: list[int] = []
    for i in every:
        rg = md.row_group(i)
        paths = {rg.column(j).path_in_schema: j for j in range(rg.num_columns)}
        box = None
        if cov is not None:
            idx = [paths.get(".".join(cov[k])) for k in ("xmin", "ymin", "xmax", "ymax")]
            if None not in idx:
                st = [rg.column(j).statistics for j in idx]  # type: ignore[arg-type]
                if all(s is not None and s.has_min_max for s in st):
                    box = (st[0].min, st[1].min, st[2].max, st[3].max)
        if box is None and geom in paths:
            c = rg.column(paths[geom])
            if getattr(c, "is_geo_stats_set", False):
                gs = c.geo_statistics
                if None not in (gs.xmin, gs.ymin, gs.xmax, gs.ymax):
                    box = (gs.xmin, gs.ymin, gs.xmax, gs.ymax)
        if box is None or _overlaps(*box, bbox):
            keep.append(i)
    return keep


def _is_wkb(t: pa.DataType) -> bool:
    if isinstance(t, pa.ExtensionType):
        t = t.storage_type
    return pa.types.is_binary(t) or pa.types.is_large_binary(t) or pa.types.is_binary_view(t)


def _field_path(col: pa.ChunkedArray, path: list[str]) -> pa.ChunkedArray:
    for name in path:
        col = pc.struct_field(col, name)
    return col


def _row_mask(table: pa.Table, pf: pq.ParquetFile, bbox: Sequence[float]) -> pa.ChunkedArray | None:
    """Rows whose bbox touches ``bbox``: from the covering column, else (for WKB
    geometry, when shapely is installed) from the geometry bounds; None = no filter."""
    geom = primary_geometry(pf)
    cov = _covering(pf, geom)
    if cov is not None and cov["xmin"][0] in table.column_names:
        col = table.column(cov["xmin"][0])
        part = {k: _field_path(col, cov[k][1:]) for k in ("xmin", "ymin", "xmax", "ymax")}
        return pc.and_(
            pc.and_(pc.less_equal(part["xmin"], bbox[2]), pc.greater_equal(part["xmax"], bbox[0])),
            pc.and_(pc.less_equal(part["ymin"], bbox[3]), pc.greater_equal(part["ymax"], bbox[1])),
        )
    if geom in table.column_names and _is_wkb(table.schema.field(geom).type):
        try:
            import numpy as np
            import shapely
        except ImportError:
            return None
        col = table.column(geom).combine_chunks()
        if isinstance(col, pa.ExtensionArray):
            col = col.storage
        g = shapely.from_wkb(np.asarray(col.to_numpy(zero_copy_only=False), dtype=object))
        b = shapely.bounds(g)
        with np.errstate(invalid="ignore"):
            m = (b[:, 0] <= bbox[2]) & (b[:, 2] >= bbox[0]) & (b[:, 1] <= bbox[3]) & (b[:, 3] >= bbox[1])
        return pa.chunked_array([pa.array(m)])
    return None


def read_parquet_http(
    http: httpx.Client,
    url: str,
    size: int | None,
    bbox: Sequence[float] | None = None,
    columns: Sequence[str] | None = None,
) -> tuple[pa.Table, dict[str, int]]:
    """Read ``url`` (a Parquet file) over HTTP Range, only the row groups ``bbox``
    needs, then keep the rows that touch ``bbox``. Returns the table and traffic counts."""
    f = HTTPRangeFile(http, url, size)
    pf = pq.ParquetFile(f, pre_buffer=True)
    rgs = row_groups_for_bbox(pf, bbox)
    cols = list(columns) if columns is not None else None
    extra: list[str] = []
    if bbox is not None and cols is not None:
        geom = primary_geometry(pf)
        cov = _covering(pf, geom)
        need = cov["xmin"][0] if cov is not None else geom
        if need in pf.schema_arrow.names and need not in cols:
            extra.append(need)
    read_cols = cols + extra if cols is not None else None
    if rgs:
        table = pf.read_row_groups(rgs, columns=read_cols)
    else:
        schema = pf.schema_arrow
        if read_cols is not None:
            schema = pa.schema([schema.field(c) for c in read_cols], metadata=schema.metadata)
        table = schema.empty_table()
    if bbox is not None and table.num_rows:
        mask = _row_mask(table, pf, bbox)
        if mask is not None:
            table = table.filter(mask)
    if extra:
        table = table.drop_columns(extra)
    stats = {
        "row_groups_total": pf.metadata.num_row_groups,
        "row_groups_read": len(rgs),
        "requests": f.requests,
        "bytes_fetched": f.bytes_fetched,
        "file_size": f.size,
    }
    return table, stats


# -- download --------------------------------------------------------------------


def _print_progress(name: str) -> Progress:
    def show(done: int, total: int | None) -> None:
        if total:
            sys.stderr.write(f"\r{name}: {done / 1e6:.1f} / {total / 1e6:.1f} MB ({100 * done / total:.0f} %)")
        else:
            sys.stderr.write(f"\r{name}: {done / 1e6:.1f} MB")
        if total is not None and done >= total:
            sys.stderr.write("\n")
        sys.stderr.flush()

    return show


def _sha256_of(path: Path, h: Any | None = None, chunk: int = 1 << 20) -> Any:
    h = h or hashlib.sha256()
    with open(path, "rb") as fh:
        while True:
            b = fh.read(chunk)
            if not b:
                return h
            h.update(b)


def download_file(
    http: httpx.Client,
    url: str,
    dest: Path,
    *,
    size: int | None,
    sha256: str | None,
    resume: bool = True,
    progress: Progress | bool | None = None,
) -> Path:
    """Stream ``url`` to ``dest`` through ``dest.part``; resume a ``.part`` with Range;
    verify size and sha256; rename into place. An intact ``dest`` is not fetched again."""
    from ._client import KorpMapError, _error_from

    want_sha = sha256.lower() if sha256 else None
    if dest.exists() and size is not None and dest.stat().st_size == size:
        if want_sha is None or _sha256_of(dest).hexdigest() == want_sha:
            return dest
    show: Progress | None = _print_progress(dest.name) if progress is True else (progress or None)
    part = dest.with_name(dest.name + ".part")
    dest.parent.mkdir(parents=True, exist_ok=True)
    have = part.stat().st_size if (resume and part.exists()) else 0
    if size is not None and have > size:
        have = 0
    h = _sha256_of(part) if have else hashlib.sha256()

    if size is None or have < size:
        headers = {"accept-encoding": "identity"}
        if have:
            headers["range"] = f"bytes={have}-"
        try:
            with http.stream("GET", url, headers=headers) as r:
                if r.status_code == 416 and have:  # nothing past what we have: start over
                    r.read()
                    part.unlink(missing_ok=True)
                    return download_file(http, url, dest, size=size, sha256=sha256, resume=False, progress=progress)
                if r.status_code >= 400:
                    r.read()
                    raise _error_from(r)
                if r.status_code == 206:
                    m = _CONTENT_RANGE.match(r.headers.get("content-range", ""))
                    if not m or int(m.group(1)) != have:
                        raise KorpMapError(f"range reply does not start at byte {have}", status=206)
                    mode = "ab"
                else:  # 200: the whole file
                    have, h, mode = 0, hashlib.sha256(), "wb"
                total = size
                if total is None:
                    cl = r.headers.get("content-length")
                    total = have + int(cl) if cl is not None else None
                done = have
                if show:
                    show(done, total)
                encoded = r.headers.get("content-encoding", "identity").lower() not in ("", "identity")
                if encoded and mode == "ab":
                    raise KorpMapError("the server encoded a range reply; cannot resume", status=206)
                chunks = r.iter_bytes() if encoded else r.iter_raw()  # as it arrives: a break keeps all of it
                with open(part, mode) as fh:
                    for chunk in chunks:
                        fh.write(chunk)
                        h.update(chunk)
                        done += len(chunk)
                        if show:
                            show(done, total)
        except httpx.HTTPError as e:
            raise KorpMapError(f"download of {url} broke off ({e}); call again to resume") from e

    got = part.stat().st_size
    if size is not None and got != size:
        raise KorpMapError(f"{dest.name}: {got} bytes, expected {size}; call again to resume")
    if want_sha is not None and h.hexdigest() != want_sha:
        part.unlink(missing_ok=True)
        raise KorpMapError(f"{dest.name}: sha256 {h.hexdigest()} does not match {want_sha}; the partial file was removed")
    os.replace(part, dest)
    return dest