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

nordisk/korp-map

crates/korp-map-wire/src/source.rs

//! **The server-side trait** [`MapSource`] and the query/reply types both doors share.

use std::collections::HashMap;
use std::fmt;
use std::str::FromStr;
use std::sync::Arc;

use arrow_array::RecordBatch;
use arrow_schema::{Schema, SchemaRef};
use serde::{Deserialize, Serialize};

use crate::error::{Code, WireError};
use crate::geocode::{GeocodeQuery, GeocodeReply, RevGeocodeQuery, RevGeocodeReply};

/// The highest `lod` a query may ask for.
pub const MAX_LOD: u8 = 30;

/// The reply metadata keys, as the contract names them. They ride in the Arrow schema
/// metadata of every reply, beside the GeoParquet `geo` key.
pub mod meta_keys {
    /// Which cut of the data answered (opaque; a client only asks whether it changed).
    pub const DATA_VERSION: &str = "data_version";
    /// `"true"` when more rows matched than `max` let through.
    pub const TRUNCATED: &str = "truncated";
    /// Row groups the queried files hold.
    pub const ROW_GROUPS_TOTAL: &str = "row_groups_total";
    /// Row groups the query read (those the statistics did not prune).
    pub const ROW_GROUPS_SCANNED: &str = "row_groups_scanned";
    /// `"ok"` for an answered query.
    pub const STATUS: &str = "status";
    /// Which stored geometry the `geometry` column carries: `z6`, `z9`, `z12` or `full`.
    pub const GEOMETRY_SOURCE: &str = "geometry_source";
    /// All six.
    pub const ALL: [&str; 6] = [
        GEOMETRY_SOURCE,
        DATA_VERSION,
        TRUNCATED,
        ROW_GROUPS_TOTAL,
        ROW_GROUPS_SCANNED,
        STATUS,
    ];
}

/// What a map reply holds: one GeoParquet native geometry type.
#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash, PartialOrd, Ord, Serialize, Deserialize)]
#[serde(rename_all = "lowercase")]
pub enum Kind {
    /// `<table>.point.parquet` rows.
    Points,
    /// `<table>.multilinestring.parquet` rows.
    Lines,
    /// `<table>.multipolygon.parquet` rows.
    Areas,
}

impl Kind {
    /// The three kinds.
    pub const ALL: [Kind; 3] = [Kind::Points, Kind::Lines, Kind::Areas];

    /// The wire spelling.
    #[must_use]
    pub const fn as_str(self) -> &'static str {
        match self {
            Kind::Points => "points",
            Kind::Lines => "lines",
            Kind::Areas => "areas",
        }
    }

    /// The GeoParquet 1.1 native `encoding` (and the file-name infix) of this kind.
    #[must_use]
    pub const fn native_encoding(self) -> &'static str {
        match self {
            Kind::Points => "point",
            Kind::Lines => "multilinestring",
            Kind::Areas => "multipolygon",
        }
    }

    /// The kind whose native encoding is `enc`.
    #[must_use]
    pub fn from_native_encoding(enc: &str) -> Option<Self> {
        Kind::ALL.into_iter().find(|k| k.native_encoding() == enc)
    }
}

impl FromStr for Kind {
    type Err = WireError;
    fn from_str(s: &str) -> Result<Self, WireError> {
        Kind::ALL
            .into_iter()
            .find(|k| k.as_str() == s)
            .ok_or_else(|| {
                WireError::new(
                    Code::UnknownKind,
                    format!("kind {s:?} is not one of points, lines, areas"),
                )
            })
    }
}

impl fmt::Display for Kind {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        f.write_str(self.as_str())
    }
}

/// A WGS-84 box `[minlon, minlat, maxlon, maxlat]`.
#[derive(Clone, Copy, Debug, PartialEq)]
pub struct BBox {
    /// West edge.
    pub min_lon: f64,
    /// South edge.
    pub min_lat: f64,
    /// East edge.
    pub max_lon: f64,
    /// North edge.
    pub max_lat: f64,
}

impl BBox {
    /// A checked box: finite, lon in `-180..=180`, lat in `-90..=90`, min ≤ max.
    pub fn new(min_lon: f64, min_lat: f64, max_lon: f64, max_lat: f64) -> Result<Self, WireError> {
        let b = Self {
            min_lon,
            min_lat,
            max_lon,
            max_lat,
        };
        let v = b.to_array();
        if v.iter().any(|x| !x.is_finite()) {
            return Err(WireError::new(
                Code::BadBbox,
                "bbox holds a value that is not a finite number",
            ));
        }
        if !(-180.0..=180.0).contains(&min_lon) || !(-180.0..=180.0).contains(&max_lon) {
            return Err(WireError::new(
                Code::BadBbox,
                "bbox longitude outside -180..=180",
            ));
        }
        if !(-90.0..=90.0).contains(&min_lat) || !(-90.0..=90.0).contains(&max_lat) {
            return Err(WireError::new(
                Code::BadBbox,
                "bbox latitude outside -90..=90",
            ));
        }
        if min_lon > max_lon || min_lat > max_lat {
            return Err(WireError::new(
                Code::BadBbox,
                "bbox min is greater than max",
            ));
        }
        Ok(b)
    }

    /// From `[minlon, minlat, maxlon, maxlat]`.
    pub fn from_slice(v: &[f64]) -> Result<Self, WireError> {
        match v {
            [a, b, c, d] => Self::new(*a, *b, *c, *d),
            _ => Err(WireError::new(
                Code::BadBbox,
                format!(
                    "bbox needs 4 numbers minlon,minlat,maxlon,maxlat, got {}",
                    v.len()
                ),
            )),
        }
    }

    /// `[minlon, minlat, maxlon, maxlat]`.
    #[must_use]
    pub const fn to_array(&self) -> [f64; 4] {
        [self.min_lon, self.min_lat, self.max_lon, self.max_lat]
    }

    /// Do the two closed boxes share a point?
    #[must_use]
    pub fn intersects(&self, o: &BBox) -> bool {
        self.min_lon <= o.max_lon
            && o.min_lon <= self.max_lon
            && self.min_lat <= o.max_lat
            && o.min_lat <= self.max_lat
    }
}

impl FromStr for BBox {
    type Err = WireError;
    /// `minlon,minlat,maxlon,maxlat`.
    fn from_str(s: &str) -> Result<Self, WireError> {
        let v = s
            .split(',')
            .map(|p| p.trim().parse::<f64>())
            .collect::<Result<Vec<_>, _>>()
            .map_err(|e| WireError::new(Code::BadBbox, format!("bbox {s:?}: {e}")))?;
        Self::from_slice(&v)
    }
}

impl Serialize for BBox {
    fn serialize<S: serde::Serializer>(&self, s: S) -> Result<S::Ok, S::Error> {
        self.to_array().serialize(s)
    }
}

impl<'de> Deserialize<'de> for BBox {
    fn deserialize<D: serde::Deserializer<'de>>(d: D) -> Result<Self, D::Error> {
        let v = Vec::<f64>::deserialize(d)?;
        BBox::from_slice(&v).map_err(serde::de::Error::custom)
    }
}

/// One served region, as `GET /v1/regions` lists it.
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
pub struct Region {
    /// The name a query names.
    pub name: String,
    /// Where its data lies.
    pub bbox: BBox,
    /// Which cut is served (opaque).
    pub data_version: String,
}

/// One map query — the HTTP query string and the Flight ticket carry the same fields.
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
pub struct MapQuery {
    /// The region.
    pub region: String,
    /// The viewport.
    pub bbox: BBox,
    /// Level of detail (zoom); the file source keeps rows whose `min_zoom` ≤ `lod`.
    pub lod: u8,
    /// Which geometry type.
    pub kind: Kind,
    /// At most this many rows; `None` takes the server's default cap.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub max: Option<u64>,
}

impl MapQuery {
    /// Check the fields a type cannot hold (`lod` range, `max` ≥ 1).
    pub fn validate(&self) -> Result<(), WireError> {
        if self.lod > MAX_LOD {
            return Err(WireError::new(
                Code::BadLod,
                format!("lod {} is above {MAX_LOD}", self.lod),
            ));
        }
        if self.max == Some(0) {
            return Err(WireError::new(Code::BadMax, "max must be at least 1"));
        }
        Ok(())
    }
}

/// What a reply says about itself — what `MapQueryReply` carried beside the geometry.
#[derive(Clone, Debug, PartialEq, Eq)]
pub struct ReplyMeta {
    /// Which cut answered.
    pub data_version: String,
    /// More rows matched than `max` let through.
    pub truncated: bool,
    /// Row groups the queried files hold.
    pub row_groups_total: u64,
    /// Row groups read.
    pub row_groups_scanned: u64,
    /// `"ok"`.
    pub status: String,
    /// Which stored geometry the reply's `geometry` is (`z6|z9|z12|full`).
    pub geometry_source: String,
}

impl ReplyMeta {
    /// The keys as schema metadata.
    #[must_use]
    pub fn to_metadata(&self) -> HashMap<String, String> {
        HashMap::from([
            (
                meta_keys::DATA_VERSION.to_string(),
                self.data_version.clone(),
            ),
            (meta_keys::TRUNCATED.to_string(), self.truncated.to_string()),
            (
                meta_keys::ROW_GROUPS_TOTAL.to_string(),
                self.row_groups_total.to_string(),
            ),
            (
                meta_keys::ROW_GROUPS_SCANNED.to_string(),
                self.row_groups_scanned.to_string(),
            ),
            (meta_keys::STATUS.to_string(), self.status.clone()),
            (
                meta_keys::GEOMETRY_SOURCE.to_string(),
                self.geometry_source.clone(),
            ),
        ])
    }

    /// Read the keys back (a client's view); `None` when one is missing or malformed.
    #[must_use]
    pub fn from_metadata(m: &HashMap<String, String>) -> Option<Self> {
        Some(Self {
            data_version: m.get(meta_keys::DATA_VERSION)?.clone(),
            truncated: m.get(meta_keys::TRUNCATED)?.parse().ok()?,
            row_groups_total: m.get(meta_keys::ROW_GROUPS_TOTAL)?.parse().ok()?,
            row_groups_scanned: m.get(meta_keys::ROW_GROUPS_SCANNED)?.parse().ok()?,
            status: m.get(meta_keys::STATUS)?.clone(),
            geometry_source: m.get(meta_keys::GEOMETRY_SOURCE)?.clone(),
        })
    }
}

/// The batches of a reply, produced on a blocking thread.
pub type BatchIter = Box<dyn Iterator<Item = Result<RecordBatch, WireError>> + Send>;

/// A planned reply: the schema (metadata included), what it says, and its batches.
pub struct MapReply {
    schema: SchemaRef,
    meta: ReplyMeta,
    batches: BatchIter,
}

impl MapReply {
    /// A reply over `batches` of `data_schema`. The reply schema is `data_schema` with
    /// `meta`'s keys added to its metadata; every batch is re-labelled with it.
    #[must_use]
    pub fn new(data_schema: &Schema, meta: ReplyMeta, batches: BatchIter) -> Self {
        let mut md = data_schema.metadata().clone();
        md.extend(meta.to_metadata());
        let schema: SchemaRef =
            Arc::new(Schema::new_with_metadata(data_schema.fields().clone(), md));
        let s = schema.clone();
        let batches: BatchIter = Box::new(batches.map(move |b| {
            b.and_then(|b| {
                b.with_schema(s.clone()).map_err(|e| {
                    WireError::new(
                        Code::SourceFailed,
                        format!("batch does not fit the reply schema: {e}"),
                    )
                })
            })
        }));
        Self {
            schema,
            meta,
            batches,
        }
    }

    /// The reply schema (metadata included).
    #[must_use]
    pub fn schema(&self) -> &SchemaRef {
        &self.schema
    }

    /// What the reply says about itself.
    #[must_use]
    pub fn meta(&self) -> &ReplyMeta {
        &self.meta
    }

    /// Take the batches.
    #[must_use]
    pub fn into_parts(self) -> (SchemaRef, ReplyMeta, BatchIter) {
        (self.schema, self.meta, self.batches)
    }
}

/// **The server-side source of map data.** Both doors call it; neither knows what is behind.
///
/// Implementations: korp-map's store (after the cut), and [`crate::FileSource`] — the
/// file-backed fake over GeoParquet native files. `query` plans the read (pruning,
/// counting against `max`) before it returns, so the reply's metadata is final; the
/// batches are then pulled on a blocking thread.
pub trait MapSource: Send + Sync + 'static {
    /// The regions served.
    fn regions(&self) -> Result<Vec<Region>, WireError>;

    /// Answer one query. `q.max` is already resolved (the server applied its default).
    fn query(&self, q: &MapQuery) -> Result<MapReply, WireError>;

    /// Answer one geocode (contract v1.2); `q` is already checked. A source without an
    /// address index keeps this refusal.
    fn geocode(&self, q: &GeocodeQuery) -> Result<GeocodeReply, WireError> {
        Err(no_address_index(&q.region))
    }

    /// Answer one reverse geocode (contract v1.2); `q` is already checked. A source
    /// without an address index keeps this refusal.
    fn revgeocode(&self, q: &RevGeocodeQuery) -> Result<RevGeocodeReply, WireError> {
        Err(no_address_index(&q.region))
    }
}

fn no_address_index(region: &str) -> WireError {
    WireError::new(
        Code::NoAddressIndex,
        format!("region {region:?}: this map source serves no address index"),
    )
}

impl<T: MapSource + ?Sized> MapSource for Arc<T> {
    fn regions(&self) -> Result<Vec<Region>, WireError> {
        (**self).regions()
    }
    fn query(&self, q: &MapQuery) -> Result<MapReply, WireError> {
        (**self).query(q)
    }
    fn geocode(&self, q: &GeocodeQuery) -> Result<GeocodeReply, WireError> {
        (**self).geocode(q)
    }
    fn revgeocode(&self, q: &RevGeocodeQuery) -> Result<RevGeocodeReply, WireError> {
        (**self).revgeocode(q)
    }
}