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-roundtrip/tests/facett_reads_the_reply.rs

//! **Round trip through facett-osm's native decoder.** A `/v1/map/{kind}` reply, read by
//! facett-osm, gives the same `Way`s (field for field) that facett-osm gives when it reads
//! the rows of that bbox straight from the native file (selected by brute force over its
//! `bbox` covering, not by the server's pruning) — and the same points for `points`. For a
//! lod the server answers from a simplified copy (`geometry_z6/z9/z12`, WKB in the file),
//! the file side is facett-osm's WKB reader over that copy: the server's WKB → native
//! conversion is checked against an independent decoder.
//!
//! facett-osm reads Parquet, so the reply's batches are put into an in-memory Parquet
//! file under the reply's schema (which carries the `geo` document) before it reads them.
//!
//! Runs on a fixture region; with `KORP_MAP_WIRE_CUT=<dir of native files>` it also runs
//! on that cut (a Stockholm viewport and a Gotland viewport; release build advised).

use std::path::{Path, PathBuf};
use std::sync::Arc;

use arrow_array::cast::AsArray;
use arrow_array::types::{Float32Type, UInt8Type};
use arrow_array::{Array, BooleanArray, RecordBatch};
use arrow_schema::SchemaRef;
use bytes::Bytes;
use facett_core::Theme;
use http_body_util::{BodyExt, Empty};
use hyper_util::client::legacy::Client;
use hyper_util::rt::TokioExecutor;
use korp_map_wire::fixture::{self, Geom, Row, Table, ZStore};
use korp_map_wire::{BBox, FileSource, Kind, MapSource, ReplyMeta, ServerConfig};
use parquet::arrow::ArrowWriter;
use parquet::arrow::arrow_reader::ParquetRecordBatchReaderBuilder;

async fn start(source: Arc<FileSource>) -> String {
    let l = tokio::net::TcpListener::bind("127.0.0.1:0").await.unwrap();
    let addr = l.local_addr().unwrap();
    let cfg = ServerConfig {
        default_max: None,
        log: false,
        ..ServerConfig::default()
    };
    tokio::spawn(async move { korp_map_wire::serve(l, source, cfg).await });
    format!("http://{addr}")
}

async fn get(url: &str) -> Bytes {
    let client = Client::builder(TokioExecutor::new()).build_http::<Empty<Bytes>>();
    let res = client.get(url.parse().unwrap()).await.unwrap();
    assert_eq!(res.status(), 200, "{url}");
    res.into_body().collect().await.unwrap().to_bytes()
}

fn decode(body: Bytes) -> (SchemaRef, Vec<RecordBatch>) {
    let r = arrow_ipc_reader(body);
    let schema = r.schema();
    (schema, r.collect::<Result<Vec<_>, _>>().unwrap())
}

fn arrow_ipc_reader(body: Bytes) -> arrow_ipc::reader::StreamReader<std::io::Cursor<Bytes>> {
    arrow_ipc::reader::StreamReader::try_new(std::io::Cursor::new(body), None).unwrap()
}

/// The reply as an in-memory Parquet file (the only input facett-osm's readers take).
fn as_parquet(schema: &SchemaRef, batches: &[RecordBatch]) -> Bytes {
    let mut buf = Vec::new();
    let mut w = ArrowWriter::try_new(&mut buf, schema.clone(), None).unwrap();
    for b in batches {
        w.write(b).unwrap();
    }
    w.close().unwrap();
    Bytes::from(buf)
}

/// The simplified column a lines/areas query at `lod` reads (contract v1.1); `None` = full.
fn z_column(kind: Kind, lod: u8) -> Option<&'static str> {
    match (kind, lod) {
        (Kind::Points, _) => None,
        (_, 0..=6) => Some("geometry_z6"),
        (_, 7..=9) => Some("geometry_z9"),
        (_, 10..=12) => Some("geometry_z12"),
        _ => None,
    }
}

/// Is this WKB blob a shape the kind can carry (lines: (Multi)LineString, areas:
/// (Multi)Polygon)?
fn wkb_fits(kind: Kind, w: &[u8]) -> bool {
    if w.len() < 5 {
        return false;
    }
    let t = if w[0] == 1 {
        u32::from_le_bytes(w[1..5].try_into().unwrap())
    } else {
        u32::from_be_bytes(w[1..5].try_into().unwrap())
    };
    match kind {
        Kind::Lines => t == 2 || t == 5,
        Kind::Areas => t == 3 || t == 6,
        Kind::Points => t == 1,
    }
}

/// Brute force over one file, independent of the server: every row of the file, kept
/// when its `bbox` covering meets the viewport, `min_zoom` ≤ `lod`, a point is tagged and
/// the stored geometry the lod asks for is there and fits the kind. The kept rows come
/// back as an in-memory Parquet file of `id, tags, min_zoom, geometry` — the stored copy
/// the lod asks for under the file's own `geo` entry for it: native (facett-osm reads it
/// as it reads `geometry`), or, in an older export, **WKB** (declared `"encoding":"WKB"`,
/// so facett-osm decodes it with its WKB reader, not with anything the server used).
fn file_rows(path: &Path, kind: Kind, b: BBox, lod: u8) -> (Bytes, usize) {
    let bld = ParquetRecordBatchReaderBuilder::try_new(std::fs::File::open(path).unwrap()).unwrap();
    let fschema = bld.schema().clone();
    let zc = z_column(kind, lod);
    let gname = zc.unwrap_or("geometry");
    let gfield = fschema
        .field_with_name(gname)
        .unwrap()
        .clone()
        .with_name("geometry");
    let file_geo: serde_json::Value = serde_json::from_str(&fschema.metadata()["geo"]).unwrap();
    let wkb = file_geo["columns"][gname]["encoding"] == "WKB";
    let geo = match zc {
        Some(_) if wkb => r#"{"version":"1.1.0","primary_column":"geometry","columns":{"geometry":{"encoding":"WKB","geometry_types":[]}}}"#.to_string(),
        Some(_) => serde_json::json!({
            "version": "1.1.0",
            "primary_column": "geometry",
            "columns": { "geometry": file_geo["columns"][gname].clone() },
        })
        .to_string(),
        None => fschema.metadata()["geo"].clone(),
    };
    let schema: SchemaRef = Arc::new(arrow_schema::Schema::new_with_metadata(
        vec![
            fschema.field_with_name("id").unwrap().clone(),
            fschema.field_with_name("tags").unwrap().clone(),
            fschema.field_with_name("min_zoom").unwrap().clone(),
            gfield,
        ],
        [("geo".to_string(), geo)].into(),
    ));
    let mut kept = Vec::new();
    for batch in bld.with_batch_size(65536).build().unwrap() {
        let batch = batch.unwrap();
        let z = batch
            .column_by_name("min_zoom")
            .unwrap()
            .as_primitive::<UInt8Type>();
        let tags = batch
            .column_by_name("tags")
            .unwrap()
            .as_string::<i32>()
            .clone();
        let g = batch.column_by_name(gname).unwrap().clone();
        let bb = batch.column_by_name("bbox").unwrap().as_struct();
        let c = |n: &str| {
            bb.column_by_name(n)
                .unwrap()
                .as_primitive::<Float32Type>()
                .clone()
        };
        let (x0, y0, x1, y1) = (c("xmin"), c("ymin"), c("xmax"), c("ymax"));
        let mask: BooleanArray = (0..batch.num_rows())
            .map(|r| {
                let shown = match (kind, zc) {
                    (Kind::Points, _) => {
                        tags.is_valid(r) && !matches!(tags.value(r).trim(), "" | "{}")
                    }
                    (_, Some(_)) if wkb => {
                        g.is_valid(r) && wkb_fits(kind, g.as_binary::<i32>().value(r))
                    }
                    // A native copy (or the full geometry): NULL is not shown.
                    _ => g.is_valid(r),
                };
                Some(
                    shown
                        && bb.is_valid(r)
                        && f64::from(x0.value(r)) <= b.max_lon
                        && f64::from(x1.value(r)) >= b.min_lon
                        && f64::from(y0.value(r)) <= b.max_lat
                        && f64::from(y1.value(r)) >= b.min_lat
                        && z.value(r) <= lod,
                )
            })
            .collect();
        let cols =
            ["id", "tags", "min_zoom", gname].map(|n| batch.column_by_name(n).unwrap().clone());
        let slim = RecordBatch::try_new(schema.clone(), cols.to_vec()).unwrap();
        let f = arrow_select::filter::filter_record_batch(&slim, &mask).unwrap();
        if f.num_rows() > 0 {
            kept.push(f);
        }
    }
    let n = kept.iter().map(RecordBatch::num_rows).sum();
    (as_parquet(&schema, &kept), n)
}

/// One query through the server and through the files; returns how many items matched.
async fn round_trip(
    url: &str,
    source: &FileSource,
    region: &str,
    kind: Kind,
    b: BBox,
    lod: u8,
) -> usize {
    let [a, c, d, e] = b.to_array();
    let t = std::time::Instant::now();
    let body = get(&format!(
        "{url}/v1/map/{kind}?region={region}&bbox={a},{c},{d},{e}&lod={lod}"
    ))
    .await;
    let wire_s = t.elapsed().as_secs_f64();
    let (schema, batches) = decode(body.clone());
    let meta = ReplyMeta::from_metadata(schema.metadata()).unwrap();
    assert!(!meta.truncated, "no cap was set");
    let rows: usize = batches.iter().map(RecordBatch::num_rows).sum();
    let pq = as_parquet(&schema, &batches);
    let theme = Theme::default();
    let mut file_n = 0;
    let n = match kind {
        Kind::Points => {
            // read_points takes `max` literally (0 keeps one point), unlike read_ways.
            let got = facett_osm::read_points_bytes(pq, usize::MAX).unwrap();
            let mut want = Vec::new();
            for f in source.files(region, kind) {
                let (bytes, k) = file_rows(&f, kind, b, lod);
                file_n += k;
                if k > 0 {
                    want.extend(facett_osm::read_points_bytes(bytes, usize::MAX).unwrap());
                }
            }
            assert_eq!(got, want, "{kind}: points");
            got.len()
        }
        Kind::Lines | Kind::Areas => {
            let got = facett_osm::read_ways_bytes(pq, 0, &theme).unwrap();
            let mut want = Vec::new();
            for f in source.files(region, kind) {
                let (bytes, k) = file_rows(&f, kind, b, lod);
                file_n += k;
                if k > 0 {
                    want.extend(facett_osm::read_ways_bytes(bytes, 0, &theme).unwrap());
                }
            }
            assert_eq!(got.len(), want.len(), "{kind}: way count");
            for (i, (g, w)) in got.iter().zip(&want).enumerate() {
                assert_eq!(format!("{g:?}"), format!("{w:?}"), "{kind}: way {i}");
            }
            got.len()
        }
    };
    assert_eq!(
        rows, file_n,
        "{kind}: the reply holds exactly the file rows of the viewport"
    );
    eprintln!(
        "[round trip] {region} {kind} bbox {:?} lod {lod}: {rows} rows → {n} facett items, reply {} B in {wire_s:.3} s, rg {}/{}",
        b.to_array(),
        body.len(),
        meta.row_groups_scanned,
        meta.row_groups_total
    );
    assert!(n > 0, "{kind}: the viewport must hold something to compare");
    n
}

fn fixture_region(root: &Path, zs: ZStore) -> PathBuf {
    let dir = root.join("fixtureland");
    std::fs::create_dir_all(&dir).unwrap();
    let pts: Vec<(f64, f64)> = (0..400)
        .map(|k| {
            (
                17.5 + f64::from(k % 20) * 0.05 + 0.001,
                59.0 + f64::from(k / 20) * 0.05 + 0.002,
            )
        })
        .collect();
    let tag = |k: usize| {
        Some(
            [
                "{\"highway\":\"primary\"}",
                "{\"building\":\"yes\"}",
                "{\"natural\":\"water\"}",
                "{\"amenity\":\"bar\",\"name\":\"Kvarnen\"}",
                "{\"landuse\":\"forest\"}",
            ][k % 5]
                .to_string(),
        )
    };
    let sq = |x: f64, y: f64, d: f64| vec![(x, y), (x + d, y), (x + d, y + d), (x, y + d), (x, y)];
    let rows = |f: &dyn Fn(usize, f64, f64) -> Geom, base: i64| -> Vec<Row> {
        pts.iter()
            .enumerate()
            .map(|(k, &(x, y))| Row {
                id: base + k as i64,
                geom: Some(f(k, x, y)),
                tags: tag(k),
                min_zoom: [6, 9, 12, 15, 6][k % 5],
            })
            .collect()
    };
    fixture::write(
        &dir.join("nodes.point.parquet"),
        Kind::Points,
        Table::Nodes,
        &rows(&|_, x, y| Geom::Point(x, y), 1),
        32,
        zs,
    )
    .unwrap();
    fixture::write(
        &dir.join("ways.multilinestring.parquet"),
        Kind::Lines,
        Table::Ways,
        &rows(
            &|k, x, y| {
                Geom::Lines(if k % 3 == 0 {
                    vec![
                        vec![(x, y), (x + 0.03, y + 0.01)],
                        vec![(x, y + 0.02), (x + 0.01, y + 0.04)],
                    ]
                } else {
                    vec![vec![(x, y), (x + 0.02, y + 0.01), (x + 0.04, y)]]
                })
            },
            100_000,
        ),
        32,
        zs,
    )
    .unwrap();
    fixture::write(
        &dir.join("ways.multipolygon.parquet"),
        Kind::Areas,
        Table::Ways,
        &rows(
            &|_, x, y| Geom::Polygons(vec![vec![sq(x, y, 0.02)]]),
            200_000,
        ),
        32,
        zs,
    )
    .unwrap();
    fixture::write(
        &dir.join("relations.resolved.multipolygon.parquet"),
        Kind::Areas,
        Table::Relations,
        &rows(
            &|_, x, y| {
                Geom::Polygons(vec![
                    vec![sq(x, y, 0.04), sq(x + 0.01, y + 0.01, 0.01)],
                    vec![sq(x + 0.045, y, 0.004)],
                ])
            },
            300_000,
        ),
        16,
        zs,
    )
    .unwrap();
    dir
}

#[tokio::test(flavor = "multi_thread")]
async fn facett_reads_a_reply_as_it_reads_the_file_on_a_fixture() {
    // Simplified copies stored native (the export now) and WKB (older exports).
    for zs in [ZStore::Native, ZStore::Wkb] {
        let tmp = tempfile::tempdir().unwrap();
        let dir = fixture_region(tmp.path(), zs);
        let source = Arc::new(FileSource::open_dir(&dir).unwrap().with_batch_rows(37));
        let url = start(source.clone()).await;
        let b = BBox::new(17.6, 59.1, 17.9, 59.4).unwrap();
        for kind in Kind::ALL {
            for lod in [6, 9, 12, 15] {
                round_trip(&url, &source, "fixtureland", kind, b, lod).await;
            }
        }
    }
}

#[tokio::test(flavor = "multi_thread")]
async fn facett_reads_a_reply_as_it_reads_the_file_on_the_real_cut() {
    let Ok(cut) = std::env::var("KORP_MAP_WIRE_CUT") else {
        eprintln!("set KORP_MAP_WIRE_CUT=<dir of native files> to run on a real cut");
        return;
    };
    let dir = PathBuf::from(cut);
    let source = Arc::new(FileSource::open_dir(&dir).unwrap());
    let region = source.regions().unwrap()[0].name.clone();
    let url = start(source.clone()).await;
    // Stockholm's Gamla stan + Södermalm edge, and a stretch of Gotland's coast.
    for (b, lod) in [
        (BBox::new(18.060, 59.315, 18.085, 59.330).unwrap(), 15),
        (BBox::new(18.060, 59.315, 18.085, 59.330).unwrap(), 9),
        (BBox::new(18.20, 57.55, 18.40, 57.70).unwrap(), 12),
        (BBox::new(18.20, 57.55, 18.40, 57.70).unwrap(), 6),
    ] {
        for kind in Kind::ALL {
            round_trip(&url, &source, &region, kind, b, lod).await;
        }
    }
}