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-quality/src/wire.rs

//! **The wire, read the way a viewer reads it**: one GET per kind, timed (time to the
//! headers ≈ the server's answer time; then the body), and the Arrow IPC stream decoded
//! to lon/lat geometry, timed separately.

use std::collections::HashMap;
use std::io::Cursor;
use std::time::Instant;

use arrow_array::cast::AsArray;
use arrow_array::types::{Float64Type, Int64Type, UInt8Type};
use arrow_array::{Array, ArrayRef, ListArray, RecordBatch, StructArray};
use serde::Serialize;

use crate::view::Kind;

/// A lon/lat coordinate.
pub type Pt = [f64; 2];

/// One row's geometry.
#[derive(Clone, Debug, PartialEq)]
pub enum Geom {
    Point(Pt),
    /// A multilinestring.
    Lines(Vec<Vec<Pt>>),
    /// A multipolygon: polygons of rings, outer ring first.
    Areas(Vec<Vec<Vec<Pt>>>),
}

impl Geom {
    /// Vertex count.
    #[must_use]
    pub fn vertices(&self) -> usize {
        match self {
            Self::Point(_) => 1,
            Self::Lines(l) => l.iter().map(Vec::len).sum(),
            Self::Areas(a) => a.iter().flatten().map(Vec::len).sum(),
        }
    }
}

/// One decoded row.
#[derive(Clone, Debug, PartialEq)]
pub struct Feature {
    pub id: i64,
    pub tags: String,
    pub min_zoom: u8,
    pub geom: Geom,
}

/// One kind's reply: what it cost and what it held.
#[derive(Clone, Debug, Default, Serialize)]
pub struct Reply {
    pub kind: String,
    pub url: String,
    pub status: u16,
    /// Bytes on the wire (the IPC stream, zstd-compressed buffers).
    pub bytes: usize,
    /// Request sent → response headers in (the server's answer time plus one round trip).
    pub ttfb_ms: f64,
    /// Request sent → last body byte.
    pub total_ms: f64,
    /// IPC + geometry decode, native.
    pub decode_ms: f64,
    pub rows: usize,
    pub vertices: usize,
    /// The reply's schema metadata (`truncated`, `geometry_source`, …).
    pub meta: HashMap<String, String>,
    /// A refusal's words, when the server said no.
    pub error: Option<String>,
    #[serde(skip)]
    pub features: Vec<Feature>,
}

/// GET one query and decode it.
pub fn fetch(http: &ureq::Agent, kind: Kind, url: &str) -> Reply {
    let mut r = Reply {
        kind: kind.as_str().into(),
        url: url.into(),
        ..Reply::default()
    };
    let t0 = Instant::now();
    let resp = http.get(url).call();
    let mut resp = match resp {
        Ok(x) => x,
        Err(e) => {
            r.error = Some(e.to_string());
            return r;
        }
    };
    r.ttfb_ms = ms(t0);
    r.status = resp.status().as_u16();
    let body = resp.body_mut().with_config().limit(4 << 30).read_to_vec();
    r.total_ms = ms(t0);
    let body = match body {
        Ok(b) => b,
        Err(e) => {
            r.error = Some(format!("body: {e}"));
            return r;
        }
    };
    r.bytes = body.len();
    if r.status != 200 {
        r.error = Some(String::from_utf8_lossy(&body[..body.len().min(400)]).into_owned());
        return r;
    }
    let t1 = Instant::now();
    match decode(kind, &body) {
        Ok((features, meta)) => {
            r.decode_ms = ms(t1);
            r.rows = features.len();
            r.vertices = features.iter().map(|f| f.geom.vertices()).sum();
            r.meta = meta;
            r.features = features;
        }
        Err(e) => r.error = Some(format!("decode: {e}")),
    }
    r
}

fn ms(t: Instant) -> f64 {
    t.elapsed().as_secs_f64() * 1000.0
}

/// Decode one Arrow IPC stream reply of `kind`.
pub fn decode(kind: Kind, body: &[u8]) -> Result<(Vec<Feature>, HashMap<String, String>), String> {
    let reader = arrow_ipc::reader::StreamReader::try_new(Cursor::new(body), None)
        .map_err(|e| e.to_string())?;
    let meta = reader.schema().metadata().clone();
    let mut out = Vec::new();
    for batch in reader {
        let batch = batch.map_err(|e| e.to_string())?;
        decode_batch(kind, &batch, &mut out)?;
    }
    Ok((out, meta))
}

/// Decode one batch's rows onto `out`.
pub fn decode_batch(kind: Kind, b: &RecordBatch, out: &mut Vec<Feature>) -> Result<(), String> {
    let col = |n: &str| {
        b.column_by_name(n)
            .ok_or_else(|| format!("no `{n}` column"))
    };
    let id = col("id")?
        .as_primitive_opt::<Int64Type>()
        .ok_or("`id` is not Int64")?
        .clone();
    let tags = col("tags")?;
    let tags = tags.as_string_opt::<i32>().ok_or("`tags` is not Utf8")?;
    let mz = b
        .column_by_name("min_zoom")
        .and_then(|c| c.as_primitive_opt::<UInt8Type>().cloned());
    let g = col("geometry")?;
    for i in 0..b.num_rows() {
        if g.is_null(i) {
            continue;
        }
        let geom = match kind {
            Kind::Points => {
                let s = g.as_struct_opt().ok_or("points geometry is not a struct")?;
                Geom::Point(coord(s, i)?)
            }
            Kind::Lines => Geom::Lines(lines(&list(g)?.value(i))?),
            Kind::Areas => {
                let polys = list(g)?.value(i);
                let pl = list(&polys)?;
                let mut v = Vec::with_capacity(pl.len());
                for p in 0..pl.len() {
                    v.push(lines(&pl.value(p))?);
                }
                Geom::Areas(v)
            }
        };
        out.push(Feature {
            id: id.value(i),
            tags: if tags.is_null(i) {
                String::new()
            } else {
                tags.value(i).to_string()
            },
            min_zoom: mz.as_ref().map_or(0, |m| m.value(i)),
            geom,
        });
    }
    Ok(())
}

fn list(a: &ArrayRef) -> Result<&ListArray, String> {
    a.as_list_opt::<i32>()
        .ok_or_else(|| format!("expected a list, got {}", a.data_type()))
}

/// A `list<list<coord>>` value → runs of points.
fn lines(a: &ArrayRef) -> Result<Vec<Vec<Pt>>, String> {
    let l = list(a)?;
    let mut out = Vec::with_capacity(l.len());
    for j in 0..l.len() {
        out.push(run(&l.value(j))?);
    }
    Ok(out)
}

/// A `list<coord>` value's struct array → points.
fn run(a: &ArrayRef) -> Result<Vec<Pt>, String> {
    let s = a.as_struct_opt().ok_or("coordinates are not a struct")?;
    let x = s
        .column(0)
        .as_primitive_opt::<Float64Type>()
        .ok_or("x is not f64")?;
    let y = s
        .column(1)
        .as_primitive_opt::<Float64Type>()
        .ok_or("y is not f64")?;
    Ok(x.values()
        .iter()
        .zip(y.values().iter())
        .map(|(&x, &y)| [x, y])
        .collect())
}

fn coord(s: &StructArray, i: usize) -> Result<Pt, String> {
    let x = s
        .column(0)
        .as_primitive_opt::<Float64Type>()
        .ok_or("x is not f64")?;
    let y = s
        .column(1)
        .as_primitive_opt::<Float64Type>()
        .ok_or("y is not f64")?;
    Ok([x.value(i), y.value(i)])
}

/// `GET /v1/regions` → `name → bbox`.
pub fn regions(http: &ureq::Agent, server: &str) -> Result<HashMap<String, [f64; 4]>, String> {
    let url = format!("{}/v1/regions", server.trim_end_matches('/'));
    let body = http
        .get(&url)
        .call()
        .map_err(|e| format!("{url}: {e}"))?
        .body_mut()
        .read_to_string()
        .map_err(|e| e.to_string())?;
    #[derive(serde::Deserialize)]
    struct R {
        name: String,
        bbox: [f64; 4],
    }
    let v: Vec<R> = serde_json::from_str(&body).map_err(|e| format!("{url}: {e}"))?;
    Ok(v.into_iter().map(|r| (r.name, r.bbox)).collect())
}

/// A plain http: no HTTP content encoding asked (the viewer asks `compress=zstd`
/// inside the IPC stream instead), long timeouts for country replies.
#[must_use]
pub fn http_client() -> ureq::Agent {
    ureq::Agent::config_builder()
        .timeout_global(Some(std::time::Duration::from_secs(600)))
        .http_status_as_error(false)
        .build()
        .into()
}