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/_client.py

"""The HTTP client for the korp-map wire (contract v1.2)."""

from __future__ import annotations

import json
import os
from dataclasses import dataclass, field
from pathlib import Path
from typing import TYPE_CHECKING, Any, Callable, Literal, Sequence
from urllib.parse import quote, urljoin

import httpx
import pyarrow as pa

from ._version import __version__

if TYPE_CHECKING:  # pragma: no cover
    import geopandas

Kind = Literal["points", "lines", "areas"]
BBox = Sequence[float]

KINDS: tuple[str, ...] = ("points", "lines", "areas")
ARROW_STREAM = "application/vnd.apache.arrow.stream"
USER_AGENT = f"korp-map-client/{__version__}"
DEFAULT_URL = "https://karta.gunnar.rs"


class KorpMapError(Exception):
    """A refusal from the server (``code`` = ``korp-map-1xx``) or a failed request.

    ``code`` is the wire error code when the server sent one, else ``None``
    (transport failure, a body that is not the contract's JSON error).
    ``status`` is the HTTP status, or ``None`` when no reply came.
    """

    def __init__(self, message: str, code: str | None = None, status: int | None = None) -> None:
        super().__init__(message)
        self.message = message
        self.code = code
        self.status = status

    def __str__(self) -> str:
        parts = [p for p in (self.code, f"HTTP {self.status}" if self.status else None) if p]
        return f"{self.message} ({', '.join(parts)})" if parts else self.message


@dataclass(frozen=True)
class MapResult:
    """One map reply: the Arrow table plus the reply facts from its schema metadata.

    ``table`` keeps the schema metadata as sent (``geo``, ``data_version``, ...).
    The object also speaks the Arrow PyCapsule stream protocol, so
    ``polars.from_arrow(res)`` / ``duckdb.sql("from res")`` work directly.
    """

    table: pa.Table
    kind: str
    data_version: str | None
    truncated: bool
    row_groups_total: int | None
    row_groups_scanned: int | None
    status: str | None
    geometry_source: str | None
    metadata: dict[str, str] = field(repr=False)

    @classmethod
    def from_table(cls, table: pa.Table, kind: str) -> "MapResult":
        raw = table.schema.metadata or {}
        md = {k.decode("utf-8", "replace"): v.decode("utf-8", "replace") for k, v in raw.items()}
        return cls(
            table=table,
            kind=kind,
            data_version=md.get("data_version"),
            truncated=md.get("truncated", "false").strip().lower() == "true",
            row_groups_total=_int_or_none(md.get("row_groups_total")),
            row_groups_scanned=_int_or_none(md.get("row_groups_scanned")),
            status=md.get("status"),
            geometry_source=md.get("geometry_source"),
            metadata=md,
        )

    @property
    def num_rows(self) -> int:
        return self.table.num_rows

    def __len__(self) -> int:
        return self.table.num_rows

    def __arrow_c_stream__(self, requested_schema: Any = None) -> Any:
        return self.table.__arrow_c_stream__(requested_schema)

    def to_pandas(self, **kwargs: Any) -> Any:
        return self.table.to_pandas(**kwargs)

    def to_geodataframe(self) -> "geopandas.GeoDataFrame":
        """The rows as a GeoDataFrame in EPSG:4326 (needs the ``[geo]`` extra)."""
        from ._geo import table_to_geodataframe

        return table_to_geodataframe(self.table)


class Client:
    """A korp-map server client.

    ``base_url`` is the server root; the default is the public server
    ``https://karta.gunnar.rs``. Any korp-map server works (``http://host:8765``).
    ``region`` defaults to the first region the server lists, looked up on first use.
    Extra keyword arguments go to :class:`httpx.Client` (``verify=``, ``proxy=``, ...).
    Compressed replies (gzip, deflate, and br / zstd when ``brotli`` / ``zstandard``
    are installed) are decoded transparently; ``Accept-Encoding`` names what is installed.
    """

    def __init__(
        self,
        base_url: str = DEFAULT_URL,
        region: str | None = None,
        *,
        timeout: float | httpx.Timeout = 120.0,
        headers: dict[str, str] | None = None,
        transport: httpx.BaseTransport | None = None,
        **httpx_kwargs: Any,
    ) -> None:
        hdrs = {"user-agent": USER_AGENT}
        hdrs.update(headers or {})
        self.base_url = base_url.rstrip("/")
        self._region = region
        self._files: dict[str, list[dict[str, Any]]] = {}
        self.last_read: dict[str, int] = {}
        self._http = httpx.Client(
            base_url=self.base_url,
            timeout=timeout,
            headers=hdrs,
            transport=transport,
            follow_redirects=True,
            **httpx_kwargs,
        )

    # -- lifecycle -------------------------------------------------------------
    def close(self) -> None:
        self._http.close()

    def __enter__(self) -> "Client":
        return self

    def __exit__(self, *exc: object) -> None:
        self.close()

    def __repr__(self) -> str:
        return f"korp_map_client.Client({self.base_url!r}, region={self._region!r})"

    # -- plain endpoints -------------------------------------------------------
    def health(self) -> bool:
        """True when ``/v1/health`` answers 200."""
        r = self._get("/v1/health")
        return r.status_code == 200

    def regions(self) -> list[dict[str, Any]]:
        """The served regions: ``[{"name", "bbox": [minlon, minlat, maxlon, maxlat], "data_version"}]``."""
        out = self._get("/v1/regions").json()
        if not isinstance(out, list):
            raise KorpMapError("/v1/regions did not answer a JSON list")
        return out

    @property
    def region(self) -> str:
        """The region used when a call names none (the first served region by default)."""
        if self._region is None:
            regs = self.regions()
            if not regs:
                raise KorpMapError("the server serves no regions")
            self._region = str(regs[0]["name"])
        return self._region

    @region.setter
    def region(self, name: str) -> None:
        self._region = name

    # -- the map ---------------------------------------------------------------
    def map(
        self,
        kind: Kind,
        bbox: BBox,
        lod: int,
        max: int | None = None,
        *,
        region: str | None = None,
        compress: Literal["zstd"] | None = None,
    ) -> MapResult:
        """Rows of ``kind`` inside ``bbox = (minlon, minlat, maxlon, maxlat)`` at ``lod``.

        ``max`` caps the row count (the reply says ``truncated``); ``compress="zstd"``
        asks for zstd Arrow IPC buffers (pyarrow decodes them natively).
        """
        if kind not in KINDS:
            raise ValueError(f"kind must be one of {KINDS}, not {kind!r}")
        params: dict[str, str] = {
            "region": region or self.region,
            "bbox": _bbox_param(bbox),
            "lod": str(int(lod)),
        }
        if max is not None:
            params["max"] = str(int(max))
        if compress is not None:
            params["compress"] = compress
        r = self._get(f"/v1/map/{kind}", params)
        ctype = r.headers.get("content-type", "").split(";")[0].strip().lower()
        if ctype and ctype != ARROW_STREAM:
            raise KorpMapError(f"expected {ARROW_STREAM}, got {ctype!r}", status=r.status_code)
        try:
            table = pa.ipc.open_stream(pa.py_buffer(r.content)).read_all()
        except pa.ArrowInvalid as e:
            raise KorpMapError(f"the reply is not an Arrow IPC stream: {e}", status=r.status_code) from e
        return MapResult.from_table(table, kind)

    def map_table(self, kind: Kind, bbox: BBox, lod: int, max: int | None = None, **kw: Any) -> pa.Table:
        """Like :meth:`map`, the bare :class:`pyarrow.Table` (schema metadata kept)."""
        return self.map(kind, bbox, lod, max, **kw).table

    def map_gdf(self, kind: Kind, bbox: BBox, lod: int, max: int | None = None, **kw: Any) -> "geopandas.GeoDataFrame":
        """Like :meth:`map`, as a GeoDataFrame in EPSG:4326 (needs the ``[geo]`` extra).

        The reply facts ride in ``gdf.attrs`` (``truncated``, ``data_version``, ...).
        """
        res = self.map(kind, bbox, lod, max, **kw)
        gdf = res.to_geodataframe()
        gdf.attrs.update(
            kind=res.kind,
            data_version=res.data_version,
            truncated=res.truncated,
            row_groups_total=res.row_groups_total,
            row_groups_scanned=res.row_groups_scanned,
            status=res.status,
            geometry_source=res.geometry_source,
        )
        return gdf

    # -- addresses (v1.2) ------------------------------------------------------
    def geocode(self, q: str, max: int | None = None, *, region: str | None = None) -> list[dict[str, Any]]:
        """Addresses matching ``q``, best first: ``[{"street", "housenumber", "city",
        "postcode", "lon", "lat", "source", "score"}]``; no match is ``[]``."""
        params = {"region": region or self.region, "q": q}
        if max is not None:
            params["max"] = str(int(max))
        out = self._get("/v1/geocode", params).json()
        return list(out.get("hits") or [])

    def revgeocode(self, lon: float, lat: float, *, region: str | None = None) -> dict[str, Any] | None:
        """The nearest address to ``(lon, lat)`` or ``None``; the hit carries ``distance_m``."""
        params = {"region": region or self.region, "lon": repr(float(lon)), "lat": repr(float(lat))}
        out = self._get("/v1/revgeocode", params).json()
        hit = out.get("hit")
        if hit is None:
            return None
        hit = dict(hit)
        hit["distance_m"] = out.get("distance_m")
        return hit

    # -- files (/v1/files) ------------------------------------------------------
    def files(self, region: str | None = None) -> list[dict[str, Any]]:
        """The region's downloadable files: ``[{"name", "set", "format", "size", "sha256",
        "url", "last_modified", ...}]`` (``sha256`` is null until the server has hashed it).

        Sets: ``native`` (the served GeoParquet 1.1 files) and ``geoparquet2``
        (GeoParquet 2.0 points / lines / areas).
        """
        reg = region or self.region
        out = self._get(f"/v1/files/{quote(reg, safe='')}/").json()
        if isinstance(out, dict) and isinstance(out.get("files"), list):
            out = out["files"]
        if not isinstance(out, list):
            raise KorpMapError(f"/v1/files/{reg}/ did not answer a JSON list")
        self._files[reg] = out
        return out

    def file_info(self, name: str, region: str | None = None) -> dict[str, Any]:
        """The listing entry for ``name`` (a file name, or ``<set>/<file>``)."""
        reg = region or self.region
        entries = self._files.get(reg)
        if entries is None:
            entries = self.files(reg)
        hit = _pick_file(entries, name)
        if hit is None and reg in self._files:  # the listing may be stale
            hit = _pick_file(self.files(reg), name)
        if hit is None:
            names = ", ".join(str(e.get("name")) for e in self._files.get(reg, []))
            raise KorpMapError(f"no file {name!r} in region {reg!r} (files: {names})")
        return hit

    def file_url(self, name: str, region: str | None = None) -> str:
        """The absolute URL of a file, for DuckDB (``read_parquet('<url>')``), GDAL
        (``/vsicurl/<url>``) or any HTTP Range reader."""
        reg = region or self.region
        e = self.file_info(name, reg)
        url = e.get("url")
        if not url:
            url = f"/v1/files/{quote(reg, safe='')}/{_set_of(e)}/{e['name']}"
        return urljoin(self.base_url + "/", str(url))

    def download(
        self,
        name: str,
        dest: str | os.PathLike[str] = ".",
        *,
        resume: bool = True,
        progress: Callable[[int, int | None], None] | bool | None = None,
        region: str | None = None,
    ) -> Path:
        """Stream a file to disk; returns its path.

        ``dest`` is a directory (the file keeps its name) or a file path. The bytes go
        to ``<dest>.part`` first; with ``resume`` a ``.part`` left by a broken download
        continues with an HTTP Range request. Size and sha256 are checked against the
        listing before the file is renamed into place; a file already there and intact
        is not fetched again. ``progress=True`` prints to stderr, or pass
        ``callable(done_bytes, total_bytes)``.
        """
        from ._files import download_file

        e = self.file_info(name, region)
        target = Path(dest)
        if target.is_dir() or str(dest).endswith(("/", os.sep)):
            target = target / str(e["name"]).rsplit("/", 1)[-1]
        size = e.get("size")
        return download_file(
            self._http,
            self.file_url(name, region),
            target,
            size=int(size) if size is not None else None,
            sha256=e.get("sha256"),
            resume=resume,
            progress=progress,
        )

    def read_parquet(
        self,
        name: str,
        bbox: BBox | None = None,
        columns: Sequence[str] | None = None,
        *,
        region: str | None = None,
    ) -> pa.Table:
        """Read a Parquet file straight from the server with HTTP Range requests.

        With ``bbox`` only the row groups whose statistics touch it are fetched
        (the GeoParquet 1.1 covering ``bbox`` column, or the GeoParquet 2.0 geometry
        statistics), and the rows are cut to those touching ``bbox`` (exact by the
        covering column; for 2.0 WKB files by the geometry bounds when shapely is
        installed, else whole row groups). ``columns`` picks columns. The traffic of
        the call is in ``client.last_read``.
        """
        from ._files import read_parquet_http

        e = self.file_info(name, region)
        size = e.get("size")
        table, stats = read_parquet_http(
            self._http,
            self.file_url(name, region),
            int(size) if size is not None else None,
            [float(v) for v in bbox] if bbox is not None else None,
            columns,
        )
        self.last_read = stats
        return table

    def read_gdf(
        self,
        name: str,
        bbox: BBox | None = None,
        columns: Sequence[str] | None = None,
        *,
        region: str | None = None,
    ) -> "geopandas.GeoDataFrame":
        """Like :meth:`read_parquet`, as a GeoDataFrame (needs the ``[geo]`` extra).

        Reads GeoParquet 2.0 (WKB / Parquet GEOMETRY) and the native separated layout.
        """
        from ._geo import table_to_geodataframe

        table = self.read_parquet(name, bbox, columns, region=region)
        geom = _primary_from_table(table)
        return table_to_geodataframe(table, geom)

    # -- plumbing --------------------------------------------------------------
    def _get(self, path: str, params: dict[str, str] | None = None) -> httpx.Response:
        try:
            r = self._http.get(path, params=params)
        except httpx.HTTPError as e:
            raise KorpMapError(f"GET {path} failed: {e}") from e
        if r.status_code >= 400:
            raise _error_from(r)
        return r


def _error_from(r: httpx.Response) -> KorpMapError:
    code: str | None = None
    message = r.text.strip() or r.reason_phrase or "request failed"
    try:
        body = r.json()
    except ValueError:
        body = None
    if isinstance(body, dict):
        code = body.get("code") if isinstance(body.get("code"), str) else None
        if isinstance(body.get("error"), str):
            message = body["error"]
    return KorpMapError(message, code=code, status=r.status_code)


def _set_of(entry: dict[str, Any]) -> str:
    """The set a listing row is served under (``native``, ``geoparquet2``, ...)."""
    s = entry.get("set")
    if isinstance(s, str) and s:
        return s
    url = str(entry.get("url") or "").split("?")[0].rstrip("/").split("/")
    return url[-2] if len(url) >= 2 else ""


def _pick_file(entries: list[dict[str, Any]], name: str) -> dict[str, Any] | None:
    exact = [e for e in entries if e.get("name") == name]
    if len(exact) == 1:
        return exact[0]
    by_path = [
        e
        for e in entries
        if f"{_set_of(e)}/{e.get('name', '')}" == name
        or str(e.get("url", "")).split("?")[0].endswith("/" + name)
    ]
    if len(by_path) == 1:
        return by_path[0]
    if len(exact) > 1:
        sets = ", ".join(f"{_set_of(e)}/{e.get('name')}" for e in exact)
        raise KorpMapError(f"file name {name!r} is in more than one set; name it as <set>/<file>: {sets}")
    return None


def _primary_from_table(table: pa.Table) -> str:
    raw = (table.schema.metadata or {}).get(b"geo")
    if raw:
        try:
            name = json.loads(raw).get("primary_column")
            if isinstance(name, str) and name in table.column_names:
                return name
        except ValueError:
            pass
    for f in table.schema:
        if (f.metadata or {}).get(b"ARROW:extension:name", b"").startswith(b"geoarrow."):
            return f.name
        if isinstance(f.type, pa.ExtensionType) and f.type.extension_name.startswith("geoarrow."):
            return f.name
    return "geometry"


def _bbox_param(bbox: BBox) -> str:
    vals = [float(v) for v in bbox]
    if len(vals) != 4:
        raise ValueError("bbox must be (minlon, minlat, maxlon, maxlat)")
    return ",".join(repr(v) for v in vals)


def _int_or_none(s: str | None) -> int | None:
    try:
        return int(s) if s is not None else None
    except ValueError:
        return None