# korp-map

The map half of [korp](https://gunnar.rs/nordisk/korp), in its own repository: region
cuts from the OpenStreetMap planet, the map registry, the packed-cut read, and
**korp-map-server**, which serves the cuts over the **map wire** (HTTP Arrow IPC and
Arrow Flight on one port).

korp links `crates/korp-map` as its `map` module, as a sibling path dependency with a
version pin. korp-map knows no korp home: the host hands it its paths
(`korp_map::paths`), and korp-map-server takes them as flags.

| crate | what it is |
|---|---|
| `crates/korp-map` | the library (region clip, planet download and cache, map registry, provisioning, the packed-cut read) and the `korp-map-server` binary (feature `server`) |
| `crates/korp-map-wire` | the map wire contract: `MapSource`, the HTTP and Flight doors, the client side (feature `client`), and the `korp-map-1xx` wire error codes |
| `crates/korp-map-wire-roundtrip` | the contract read back through facett-osm's native decoder, as a reply is read like a file |
| `crates/korp-map-build-thing` | the build recipe; `.nornir/build-variants.toml` is emitted from it |

`korp-map-wire` and `korp-map-wire-roundtrip` are self-rooting workspaces with their own
locks, as they were in korp.

## The map wire, contract v1.2 (summary)

One producer (`MapSource`), two doors on one port:

* **HTTP**: `GET /v1/health`, `GET /v1/regions`, and
  `GET /v1/map/{points|lines|areas}?region=R&bbox=minlon,minlat,maxlon,maxlat&lod=N[&max=K][&compress=zstd]`.
  The reply is an Arrow IPC stream.
* **About the server**: `GET /` and `GET /v1/` serve a landing page (the regions,
  an example of every endpoint with a button that runs it, the Python client, the
  error codes), and `GET /openapi.json` the OpenAPI 3.1 description of every route.
* **Address lookups** (v1.2), JSON: `GET /v1/geocode?region=R&q=…[&max=K]` (ranked
  addresses, best first; `max` 1 to 1000, default 10) and
  `GET /v1/revgeocode?region=R&lon=…&lat=…` (the nearest address and its distance in
  metres), answered from the region cut's `address.parquet`.
* **Compression**: the HTTP door sends an Arrow or JSON reply of 1400 bytes or more
  `zstd`, `br` or `gzip` encoded when the request's `Accept-Encoding` allows one (zstd
  first, then brotli, then gzip, at equal `q`), with `Vary: Accept-Encoding`. All three
  are pure Rust (zstd on mzstd). A reply with `compress=zstd` (Arrow IPC buffer
  compression) is not encoded again. On a Stockholm `lines` reply at lod 14 (72 277
  rows, 19.4 MB) zstd sends 4.2 MB, brotli 3.9 MB and gzip 4.2 MB.
* **Caching**: every Arrow and JSON reply carries a strong `ETag`, a hash of the
  server build (crate version, git commit and `Cargo.lock`, so a new binary changes it),
  the region's `data_version` and the query as parsed (so a new cut changes it, and two
  spellings of one query share it; an encoded reply's tag ends in `-zstd`, `-br` or
  `-gzip`), and `Cache-Control: public, max-age=3600` (`/v1/regions`: 60;
  `--cache-max-age`, `--regions-max-age`, `--no-cache-control`). A request whose
  `If-None-Match` names the reply (any coding of it, or `*`) gets `304 Not Modified`,
  and the region data is not read.
* **Flight**: `DoGet` with the same query as a JSON ticket; `ListFlights` lists the
  regions. A request with `content-type: application/grpc…` goes to Flight, anything
  else goes to HTTP.
* **Rows** are the GeoParquet 1.1 native rows that osm-katana exports, column for
  column: `id`, `tags`, `min_zoom` and one `geometry` column (the coarsest stored
  geometry that is exact enough for the `lod`). `points` holds tagged nodes only.
* **Reply facts** travel in the Arrow schema metadata: `data_version`, `truncated`,
  `row_groups_total`, `row_groups_scanned`, `status` and `geometry_source`. A source
  plans the whole read before the first batch, so all of them are known when the
  schema is written.
* **Errors** are JSON with a `korp-map-<n>` code, `korp-map-100` to `korp-map-116`
  (`korp_map_wire::error::Code`). Each code is a row in korp-map's error-code table
  (`crates/korp-map/src/errcode.rs`), which sits on edda's `nornir-diag`.

## Error codes

korp-map's codes keep the names they had in korp (`korp-map-*`, `korp-landmass-*`,
`korp-clip-*`, `korp-roadgraph-*`, `korp-address-*`, `korp-s3-*`). The table is
append-only. The `map`, `roadgraph` and `s3` subsystems are shared with korp's table,
and the two tables are numbered as one: `HELD_BY_KORP` lists korp's numbers, and the
tests on both sides check that the numbering stays dense. korp's generated catalog
(`.nornir/korp-error-codes.md` in korp) lists both tables.

## Running

You need the sibling checkouts next to this one: `edda`, `facett`, `korp-collectors`,
`znippy-zoomies`, `Skidbladnir` and `draupnir` (the build recipe's `[build.toolchain]
siblings`, held by `crates/korp-map-build-thing/tests/siblings.rs`).

```sh
cargo build --release -p korp-map --features server --bin korp-map-server
./target/release/korp-map-server --home /srv/korp-map --listen 127.0.0.1:8765
```

Paths:

* `--home <dir>` holds `work/` (region cuts, the planet download),
  `maps/registry.json` and `server_state.json`.
* `--work-dir`, `--registry`, `--planet-cache`, `--probe-dir` (repeatable) and
  `--state` each set one path directly.
* With no flags, the paths come from `$KORP_MAP_HOME`, `$KORP_MAP_REGISTRY` and
  `$KORP_MAP_PLANET_CACHE`, falling back to `$XDG_DATA_HOME/korp-map`.

Other flags:

* `--region <name>=<dir>` serves an existing native export.
* `--config <file>` reads a map config. korp's config file works as one. Without it,
  the server provisions Sweden.
* `--no-provision`, `--cors <origin>` or `--no-cors`, `--default-max <rows>` or
  `--no-default-max`, `--cache-max-age <s>`, `--regions-max-age <s>` or
  `--no-cache-control`, and `--quiet`.
* `--version` prints `korp-map-server <version> (<git commit>)`; the same line opens
  the log.

### HTTPS

The public server is **https://karta.gunnar.rs** (its landing page:
https://karta.gunnar.rs/v1/). It runs behind a reverse proxy that holds the certificate
and routes `/v1/` and `/openapi.json` here, so it needs none of the flags below; they
are for a server that answers HTTPS itself.

HTTPS is the cargo feature **`tls`** (rustls on ring), off by default: the plain
`--features server` build links no TLS, and a TLS flag stops its start with
`korp-map-120`. Build with `--features tls` for the flags below.

```sh
cargo build --release -p korp-map --features tls --bin korp-map-server
```

`--listen-tls <addr:port>` adds an HTTPS listener beside the plain `--listen` one. Both
serve the same routes (HTTP and Flight; ALPN offers `h2` and `http/1.1`) with the same
CORS headers. TLS is rustls on the ring provider; nothing links aws-lc or OpenSSL.

The certificate comes from PEM files, from Let's Encrypt, or both:

* `--tls-cert <pem> --tls-key <pem>`: a certificate chain and its private key.
* `--tls-acme <domain>` (repeatable) with `--tls-acme-cache <dir>`, and optionally
  `--tls-acme-email <addr>` and `--tls-acme-staging`: a Let's Encrypt certificate,
  ordered and renewed by the server itself over the **TLS-ALPN-01** challenge on the
  HTTPS listener. The certificate and the account key are kept in the cache directory,
  so a restart serves the cached certificate and orders nothing until renewal is due.
* With both, the PEM certificate is served until the ACME one has been issued.

Let's Encrypt checks the challenge by connecting to **port 443** of the domain, so:

1. The domain must resolve to the server's public IP. Without a DNS name of your own,
   `a-b-c-d.sslip.io` resolves to the IP `a.b.c.d`.
2. Public port 443 must reach the HTTPS listener (on a router: forward TCP 443 to the
   host's `--listen-tls` port).

```sh
korp-map-server --home /srv/korp-map --listen 0.0.0.0:8765 \
  --listen-tls 0.0.0.0:8443 --tls-acme <D> --tls-acme-cache /srv/korp-map/acme
```

Try it with `--tls-acme-staging` first: staging certificates are not trusted by
browsers, but its rate limits are generous. While an order cannot complete (port 443
not forwarded yet, DNS not pointing here), the server keeps serving HTTP, and HTTPS with
a cached or PEM certificate; the failure is printed as `korp-map-123` with Let's
Encrypt's reason, and the order is tried again after 5 minutes, doubling to at most an
hour (Let's Encrypt allows 5 failed validations per name and hour). A restart tries at
once.

TLS setup failures stop the start with a code: `korp-map-117` (certificate file),
`korp-map-118` (key file), `korp-map-119` (certificate and key do not match),
`korp-map-120` (the TLS flags do not make one setup; exit code 2), `korp-map-121` (the
ACME cache directory) and `korp-map-122` (the HTTPS address cannot be bound).

The client side of the wire talks https with `korp-map-wire`'s feature `client-tls`
(`HttpMapClient::new("https://…")`, or `HttpMapClient::with_tls` and
`FlightMapClient::with_tls_roots` for a self-signed server).

### Files

`--files <region>[:<set>]=<dir>` (repeatable) serves every `*.parquet` file in `<dir>`
for download and remote querying, under `/v1/files/<region>/<set>/<file>`. Without
`:<set>` the set is named by the files' format: `native` (GeoParquet 1.1 native
encodings), `geoparquet2` (GeoParquet 2.0) or `parquet`.

```sh
korp-map-server … --files sweden=<cut>/sweden --files sweden=<cut>/sweden-gp2
```

* `GET /v1/files/<region>/` lists them as JSON: `name`, `format`
  (`geoparquet-1.1-native`, `geoparquet-2.0`, …), `size`, `sha256`, `url`, `set`,
  `last_modified`. The sha256 of every file is computed once, in the background at
  start (`null` until then).
* `GET`/`HEAD /v1/files/<region>/<set>/<file>` answers HTTP range requests (`206`,
  several ranges as `multipart/byteranges`, `416` past the end), with `Accept-Ranges`,
  `Content-Length`, `ETag` (the sha256), `Last-Modified`, `If-None-Match` and
  `If-Range`. Files are streamed from disk and never content-encoded.
* Only the listed files are served: a request is looked up by name in the list, never
  turned into a path. A file that changed on disk since the start is refused
  (`korp-map-126`); an unknown name is `korp-map-124`, a range past the end
  `korp-map-125`.

DuckDB reads only the footer and the row groups a query needs:

```sql
INSTALL httpfs; LOAD httpfs;
SELECT count(*)
FROM 'https://karta.gunnar.rs/v1/files/sweden/geoparquet2/areas.parquet'
WHERE bbox.xmin <= 18.1 AND bbox.xmax >= 18.0 AND bbox.ymin <= 59.35 AND bbox.ymax >= 59.3;
```

## Python

The `korp-map-client` package (`python/`) reads the map as pyarrow tables or
GeoDataFrames: `pip install "korp-map-client[geo]"`, then
`korp_map_client.Client("https://karta.gunnar.rs").map("lines", bbox=(17.9, 59.2, 18.2, 59.4), lod=14).table`.

## Tests

```sh
cargo test -p korp-map                      # the library
cargo test -p korp-map --features server    # and the server (plain HTTP)
cargo test -p korp-map --features tls       # and its HTTPS
(cd crates/korp-map-wire && cargo test --features client)           # contract, Flight, client
(cd crates/korp-map-wire && cargo test --features acme,client-tls)  # and HTTPS, ACME setup
KORP_MAP_PYTHON=<python with duckdb> cargo test --test files -- --ignored  # DuckDB over HTTP
(cd crates/korp-map-wire-roundtrip && cargo test)                   # facett reads the reply
cargo test -p korp-map-build-thing          # the recipe and the build gate
```

## License

Licensed under either of

- Apache License, Version 2.0 ([`LICENSE-APACHE`](LICENSE-APACHE))
- MIT license ([`LICENSE-MIT`](LICENSE-MIT))

at your option. Copyright (c) 2026 Ignalina ApS (Rickard Ernst Björn Lundin).

Unless you explicitly state otherwise, any contribution intentionally submitted for
inclusion in the work by you, as defined in the Apache-2.0 license, shall be dual
licensed as above, without any additional terms or conditions.

Data keeps its own license: `crates/korp-map/assets/sweden.poly` (compiled into the
library) is cut from OpenStreetMap, relation 52822, under **ODbL 1.0**, "© OpenStreetMap
contributors" (see `crates/korp-map/assets/sweden.poly.provenance.md`). So are the region
cuts, networks and tables korp-map builds from an OSM planet at run time.
