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

//! **The HTTP contract** (wire contract v1), endpoint by endpoint,
//! against a server over a fixture region.

mod common;

use arrow_array::Array;
use arrow_array::cast::AsArray;
use common::*;
use korp_map_wire::fixture::ZStore;
use korp_map_wire::source::meta_keys;
use korp_map_wire::{BBox, Kind, ReplyMeta, ServerConfig};

const ARROW: &str = "application/vnd.apache.arrow.stream";
const SOUTH: &str = "11,55,14.2,57.1";

fn meta(schema: &arrow_schema::Schema) -> ReplyMeta {
    ReplyMeta::from_metadata(schema.metadata()).expect("the five reply keys")
}

#[tokio::test(flavor = "multi_thread")]
async fn health_answers_ok() {
    let s = TestServer::start(ServerConfig::default()).await;
    let r = get(&s.url("/v1/health")).await;
    assert_eq!(r.status, 200);
    assert_eq!(&r.body[..], b"ok");
    assert_eq!(r.header("access-control-allow-origin"), Some("*"));
}

#[tokio::test(flavor = "multi_thread")]
async fn regions_list_name_bbox_and_data_version() {
    let s = TestServer::start(ServerConfig::default()).await;
    let r = get(&s.url("/v1/regions")).await;
    assert_eq!(r.status, 200);
    assert_eq!(r.header("content-type"), Some("application/json"));
    assert_eq!(r.header("access-control-allow-origin"), Some("*"));
    let v = r.json();
    let list = v.as_array().unwrap();
    assert_eq!(list.len(), 1);
    let o = list[0].as_object().unwrap();
    let mut keys: Vec<&str> = o.keys().map(String::as_str).collect();
    keys.sort_unstable();
    assert_eq!(keys, ["bbox", "data_version", "name"]);
    assert_eq!(o["name"], REGION);
    let b: Vec<f64> = o["bbox"]
        .as_array()
        .unwrap()
        .iter()
        .map(|x| x.as_f64().unwrap())
        .collect();
    assert_eq!(b.len(), 4);
    // The grid starts at (10.013, 55.007); its last relation reaches lon 19.993, lat 64.907.
    assert!(
        b[0] <= 10.013 && b[1] <= 55.007 && b[2] >= 19.993 && b[3] >= 64.907,
        "{b:?}"
    );
    assert!(
        b[0] > 10.01 && b[1] > 55.0 && b[2] < 19.994 && b[3] < 64.908,
        "{b:?}"
    );
    assert!(o["data_version"].as_str().unwrap().starts_with("files-"));
}

#[tokio::test(flavor = "multi_thread")]
async fn every_kind_answers_an_arrow_stream_of_id_tags_min_zoom_and_one_native_geometry() {
    let s = TestServer::start(ServerConfig::default()).await;
    let dv = get(&s.url("/v1/regions")).await.json()[0]["data_version"]
        .as_str()
        .unwrap()
        .to_string();
    for (kind, primary) in [
        (Kind::Points, "nodes.point.parquet"),
        (Kind::Lines, "ways.multilinestring.parquet"),
        (Kind::Areas, "ways.multipolygon.parquet"),
    ] {
        for (lod, source) in [(6u8, "z6"), (9, "z9"), (12, "z12"), (15, "full")] {
            let r = get(&s.url(&format!(
                "/v1/map/{kind}?region={REGION}&bbox={SOUTH}&lod={lod}"
            )))
            .await;
            assert_eq!(r.status, 200, "{kind}: {:?}", r.body);
            assert_eq!(r.header("content-type"), Some(ARROW));
            assert_eq!(r.header("access-control-allow-origin"), Some("*"));
            let (schema, batches) = decode(&r.body);
            let file = file_schema(&s.dir.join(primary));
            let names: Vec<&str> = schema.fields().iter().map(|f| f.name().as_str()).collect();
            assert_eq!(names, ["id", "tags", "min_zoom", "geometry"], "{kind}");
            // Each column as the file declares it — the geometry in the native type.
            for f in schema.fields() {
                assert_eq!(
                    f.as_ref(),
                    file.field_with_name(f.name()).unwrap(),
                    "{kind} {}",
                    f.name()
                );
            }
            for b in &batches {
                assert_eq!(b.schema().fields(), schema.fields());
            }
            let geo: serde_json::Value = serde_json::from_str(&schema.metadata()["geo"]).unwrap();
            let fgeo: serde_json::Value = serde_json::from_str(&file.metadata()["geo"]).unwrap();
            let cols = geo["columns"].as_object().unwrap();
            assert_eq!(
                cols.keys().collect::<Vec<_>>(),
                ["geometry"],
                "{kind}: one geometry column"
            );
            assert_eq!(
                geo["columns"]["geometry"]["encoding"],
                fgeo["columns"]["geometry"]["encoding"]
            );
            assert!(
                geo["columns"]["geometry"].get("covering").is_none(),
                "bbox is not sent"
            );
            let m = meta(&schema);
            let want_source = if kind == Kind::Points { "full" } else { source };
            assert_eq!(m.geometry_source, want_source, "{kind} lod {lod}");
            assert_eq!(m.data_version, dv);
            assert_eq!(m.status, "ok");
            assert!(!m.truncated);
            let total: u64 = s
                .source
                .files(REGION, kind)
                .iter()
                .map(|f| {
                    parquet::file::reader::FileReader::metadata(
                        &parquet::file::reader::SerializedFileReader::new(
                            std::fs::File::open(f).unwrap(),
                        )
                        .unwrap(),
                    )
                    .num_row_groups() as u64
                })
                .sum();
            assert_eq!(m.row_groups_total, total, "{kind}");
            assert!(
                m.row_groups_scanned > 0 && m.row_groups_scanned < total,
                "{kind}: pruning read {m:?}"
            );
            let want = expected_ids(&s.source, kind, SOUTH.parse().unwrap(), lod);
            assert!(!want.is_empty(), "{kind} lod {lod}");
            assert_eq!(
                ids_of(&batches),
                want,
                "{kind} lod {lod}: the rows, in file order"
            );
        }
    }
}

/// Vertex counts of every part (lines) or ring (areas) of a reply.
fn ring_lengths(batches: &[arrow_array::RecordBatch], kind: Kind) -> Vec<usize> {
    let mut out = Vec::new();
    for b in batches {
        let g = b.column_by_name("geometry").unwrap().as_list::<i32>();
        for r in 0..g.len() {
            let v = g.value(r);
            let parts: Vec<arrow_array::ArrayRef> = match kind {
                Kind::Lines => (0..v.len()).map(|i| v.as_list::<i32>().value(i)).collect(),
                _ => {
                    let polys = v.as_list::<i32>();
                    (0..polys.len())
                        .flat_map(|p| {
                            let rings = polys.value(p);
                            let rl = rings.as_list::<i32>().clone();
                            (0..rl.len()).map(move |i| rl.value(i))
                        })
                        .collect()
                }
            };
            out.extend(parts.iter().map(|p| p.len()));
        }
    }
    out
}

#[tokio::test(flavor = "multi_thread")]
async fn the_geometry_is_the_stored_copy_the_lod_asks_for() {
    let s = TestServer::start(ServerConfig::default()).await;
    let all = "10,55,20,65";
    let q = |kind: &str, lod: u8| format!("/v1/map/{kind}?region={REGION}&bbox={all}&lod={lod}");
    // The fixture's simplified lines keep each part's two ends; the full ones have 2 or 3.
    let (_, l9) = decode(&get(&s.url(&q("lines", 9))).await.body);
    assert!(ring_lengths(&l9, Kind::Lines).iter().all(|&n| n == 2));
    let (_, l15) = decode(&get(&s.url(&q("lines", 15))).await.body);
    assert!(ring_lengths(&l15, Kind::Lines).contains(&3));
    // Simplified rings keep three corners (closed: 4); the full squares have 5.
    let (_, a12) = decode(&get(&s.url(&q("areas", 12))).await.body);
    assert!(ring_lengths(&a12, Kind::Areas).iter().all(|&n| n == 4));
    let (_, a15) = decode(&get(&s.url(&q("areas", 15))).await.body);
    assert!(ring_lengths(&a15, Kind::Areas).iter().all(|&n| n == 5));
    // At z6 every fourth area has shrunk to a point: it is left out, the rest come.
    let (_, a6) = decode(&get(&s.url(&q("areas", 6))).await.body);
    let ids = ids_of(&a6);
    assert!(!ids.is_empty());
    assert!(
        ids.iter().all(|i| i % 4 != 0),
        "areas simplified to a point are left out"
    );
    assert_eq!(
        ids,
        expected_ids(&s.source, Kind::Areas, all.parse().unwrap(), 6)
    );
}

#[tokio::test(flavor = "multi_thread")]
async fn points_are_tagged_nodes_only() {
    let s = TestServer::start(ServerConfig::default()).await;
    let r = get(&s.url(&format!(
        "/v1/map/points?region={REGION}&bbox=10,55,20,65&lod=15&max=100000"
    )))
    .await;
    let (_, batches) = decode(&r.body);
    let ids = ids_of(&batches);
    // The fixture leaves every node with k % 11 == 5 untagged (id 1000 + k).
    assert!(ids.iter().all(|i| (i - 1000) % 11 != 5));
    assert!(ids.len() > 300);
    for b in &batches {
        let t = b.column_by_name("tags").unwrap().as_string::<i32>();
        assert_eq!(t.null_count(), 0);
    }
}

#[tokio::test(flavor = "multi_thread")]
async fn the_reply_metadata_carries_the_six_keys() {
    let s = TestServer::start(ServerConfig::default()).await;
    let r = get(&s.url(&format!(
        "/v1/map/lines?region={REGION}&bbox={SOUTH}&lod=15"
    )))
    .await;
    let (schema, _) = decode(&r.body);
    for k in meta_keys::ALL {
        assert!(schema.metadata().contains_key(k), "missing {k}");
    }
    assert_eq!(schema.metadata()["truncated"], "false");
    assert_eq!(schema.metadata()["status"], "ok");
}

#[tokio::test(flavor = "multi_thread")]
async fn lod_keeps_rows_whose_min_zoom_is_at_most_lod() {
    let s = TestServer::start(ServerConfig::default()).await;
    let all = "10,55,20,65";
    for lod in [0u8, 6, 9, 12, 15] {
        let r = get(&s.url(&format!(
            "/v1/map/points?region={REGION}&bbox={all}&lod={lod}"
        )))
        .await;
        let (schema, batches) = decode(&r.body);
        let want = expected_ids(&s.source, Kind::Points, all.parse().unwrap(), lod);
        assert!(!want.is_empty(), "lod {lod}");
        assert_eq!(ids_of(&batches), want, "lod {lod}");
        for b in &batches {
            let z = b
                .column_by_name("min_zoom")
                .unwrap()
                .as_primitive::<arrow_array::types::UInt8Type>();
            assert!(z.values().iter().all(|&z| z <= lod.max(LOWEST_LEVEL)));
        }
        // A lod below the lowest stored level is answered as that level, and says so.
        let src = meta(&schema).geometry_source;
        if lod < LOWEST_LEVEL {
            assert_eq!(src, format!("full (as lod {LOWEST_LEVEL})"), "lod {lod}");
        } else {
            assert_eq!(src, "full", "lod {lod}");
        }
    }
}

#[tokio::test]
async fn a_lod_below_the_lowest_stored_level_is_answered_as_that_level() {
    let s = TestServer::start(ServerConfig::default()).await;
    let all = "10,55,20,65";
    for kind in ["lines", "areas"] {
        let q = |lod: u8| format!("/v1/map/{kind}?region={REGION}&bbox={all}&lod={lod}");
        let (s6, b6) = decode(&get(&s.url(&q(6))).await.body);
        assert_eq!(meta(&s6).geometry_source, "z6");
        for lod in [0u8, 3, 5] {
            let (sl, bl) = decode(&get(&s.url(&q(lod))).await.body);
            assert_eq!(
                meta(&sl).geometry_source,
                "z6 (as lod 6)",
                "{kind} lod {lod}"
            );
            assert!(!bl.is_empty(), "{kind} lod {lod}");
            assert_eq!(ids_of(&bl), ids_of(&b6), "{kind} lod {lod}");
            let cols = |b: &[arrow_array::RecordBatch]| -> Vec<Vec<arrow_array::ArrayRef>> {
                b.iter().map(|b| b.columns().to_vec()).collect()
            };
            assert_eq!(
                cols(&bl),
                cols(&b6),
                "{kind} lod {lod}: the same z6 geometry"
            );
        }
    }
}

#[tokio::test(flavor = "multi_thread")]
async fn max_caps_the_rows_and_says_truncated() {
    let s = TestServer::start(ServerConfig::default()).await;
    let n = expected_ids(&s.source, Kind::Lines, SOUTH.parse().unwrap(), 15).len();
    for (max, truncated) in [(1, true), (7, true), (n, false), (n + 5, false)] {
        let r = get(&s.url(&format!(
            "/v1/map/lines?region={REGION}&bbox={SOUTH}&lod=15&max={max}"
        )))
        .await;
        let (schema, batches) = decode(&r.body);
        let got = ids_of(&batches);
        let (want, t) = expected_capped(&s.source, Kind::Lines, SOUTH.parse().unwrap(), 15, max);
        assert_eq!(got, want, "max {max}");
        assert_eq!(got.len(), max.min(n), "max {max}");
        assert_eq!(meta(&schema).truncated, truncated, "max {max}");
        assert_eq!(t, truncated);
    }
}

/// The fixture's ids are its grid index (`base + k`): its latitude row.
fn grid_row(id: i64) -> i64 {
    (id % 1000) / 20
}

#[tokio::test]
async fn a_capped_reply_takes_the_lowest_min_zoom_first_and_spreads_over_the_viewport() {
    let s = TestServer::start(ServerConfig::default()).await;
    let all = "10,55,20,65";
    let rows = expected_rows(&s.source, Kind::Lines, all.parse().unwrap(), 15);
    let level6 = rows.iter().filter(|(_, z)| *z == 6).count();
    let level9 = rows.iter().filter(|(_, z)| *z == 9).count();
    assert!(level6 > 20 && level9 > 20);
    // max cuts inside level 9: every level-6 row comes, and level 9 is spread.
    let max = level6 + level9 / 4;
    let r = get(&s.url(&format!(
        "/v1/map/lines?region={REGION}&bbox={all}&lod=15&max={max}"
    )))
    .await;
    let (schema, batches) = decode(&r.body);
    assert!(meta(&schema).truncated);
    let got = ids_of(&batches);
    assert_eq!(got.len(), max);
    let (want, _) = expected_capped(&s.source, Kind::Lines, all.parse().unwrap(), 15, max);
    assert_eq!(got, want);
    let zoom: Vec<u8> = batches
        .iter()
        .flat_map(|b| {
            b.column_by_name("min_zoom")
                .unwrap()
                .as_primitive::<arrow_array::types::UInt8Type>()
                .values()
                .to_vec()
        })
        .collect();
    assert_eq!(
        zoom.iter().filter(|&&z| z == 6).count(),
        level6,
        "every level-6 row"
    );
    assert!(
        zoom.iter().all(|&z| z <= 9),
        "nothing deeper than the cut level"
    );
    // The level-9 rows taken reach from the south quarter to the north quarter of the
    // grid (20 latitude rows), not the first rows in file order.
    let rows9: Vec<i64> = got
        .iter()
        .zip(&zoom)
        .filter(|(_, z)| **z == 9)
        .map(|(id, _)| grid_row(*id))
        .collect();
    assert!(rows9.iter().any(|&r| r < 5), "{rows9:?}");
    assert!(rows9.iter().any(|&r| r >= 15), "{rows9:?}");
}

#[tokio::test(flavor = "multi_thread")]
async fn the_server_default_max_applies_when_the_query_names_none() {
    let cfg = ServerConfig {
        default_max: Some(5),
        ..ServerConfig::default()
    };
    let s = TestServer::start(cfg).await;
    let r = get(&s.url(&format!(
        "/v1/map/points?region={REGION}&bbox=10,55,20,65&lod=15"
    )))
    .await;
    let (schema, batches) = decode(&r.body);
    assert_eq!(ids_of(&batches).len(), 5);
    assert!(meta(&schema).truncated);
}

#[tokio::test(flavor = "multi_thread")]
async fn areas_carry_the_relation_rows_too() {
    let s = TestServer::start(ServerConfig::default()).await;
    for lod in [9u8, 15] {
        let r = get(&s.url(&format!(
            "/v1/map/areas?region={REGION}&bbox=10,55,20,65&lod={lod}&max=100000"
        )))
        .await;
        let (schema, batches) = decode(&r.body);
        let ids = ids_of(&batches);
        assert!(
            ids.iter().any(|&i| i >= 9_000_000),
            "relation areas are served"
        );
        assert_eq!(
            ids,
            expected_ids(&s.source, Kind::Areas, "10,55,20,65".parse().unwrap(), lod)
        );
        assert_eq!(
            schema.fields().len(),
            4,
            "node_refs, members, bbox and z-columns are not sent"
        );
    }
}

#[tokio::test(flavor = "multi_thread")]
async fn an_empty_viewport_is_a_schema_and_no_rows_not_an_empty_body() {
    let s = TestServer::start(ServerConfig::default()).await;
    let r = get(&s.url(&format!(
        "/v1/map/areas?region={REGION}&bbox=-30,-40,-29,-39&lod=15"
    )))
    .await;
    assert_eq!(r.status, 200);
    assert!(!r.body.is_empty());
    let (schema, batches) = decode(&r.body);
    assert!(batches.iter().all(|b| b.num_rows() == 0));
    let m = meta(&schema);
    assert_eq!((m.row_groups_scanned, m.truncated), (0, false));
    assert!(m.row_groups_total > 0);
}

#[tokio::test(flavor = "multi_thread")]
async fn zstd_compression_decodes_to_the_same_batches() {
    let s = TestServer::start(ServerConfig::default()).await;
    let q = format!("/v1/map/areas?region={REGION}&bbox=10,55,20,65&lod=15");
    let plain = get(&s.url(&q)).await;
    let z = get(&s.url(&format!("{q}&compress=zstd"))).await;
    let none = get(&s.url(&format!("{q}&compress=none"))).await;
    assert_eq!(z.status, 200);
    assert_eq!(plain.body, none.body);
    let (s1, b1) = decode(&plain.body);
    let (s2, b2) = decode(&z.body);
    assert_eq!(s1, s2);
    assert_eq!(b1, b2);
    assert!(
        z.body.len() < plain.body.len(),
        "zstd {} vs plain {}",
        z.body.len(),
        plain.body.len()
    );
}

#[tokio::test(flavor = "multi_thread")]
async fn bbox_parameter_may_arrive_percent_encoded() {
    let s = TestServer::start(ServerConfig::default()).await;
    let a = get(&s.url(&format!(
        "/v1/map/points?region={REGION}&bbox=11%2C55%2C14.2%2C57.1&lod=12"
    )))
    .await;
    let b = get(&s.url(&format!(
        "/v1/map/points?region={REGION}&bbox={SOUTH}&lod=12"
    )))
    .await;
    assert_eq!(a.status, 200);
    assert_eq!(a.body, b.body);
}

async fn assert_refusal(s: &TestServer, method: &str, path: &str, status: u16, code: u32) {
    let r = request(method, &s.url(path)).await;
    assert_eq!(r.status, status, "{method} {path}: {:?}", r.body);
    assert_eq!(r.header("content-type"), Some("application/json"), "{path}");
    assert_eq!(
        r.header("access-control-allow-origin"),
        Some("*"),
        "errors carry CORS too: {path}"
    );
    let v = r.json();
    let o = v.as_object().unwrap();
    let mut keys: Vec<&str> = o.keys().map(String::as_str).collect();
    keys.sort_unstable();
    assert_eq!(keys, ["code", "error"], "{path}");
    assert_eq!(
        o["code"],
        format!("korp-map-{code}"),
        "{path}: {}",
        o["error"]
    );
    assert!(!o["error"].as_str().unwrap().is_empty());
}

#[tokio::test(flavor = "multi_thread")]
async fn every_refusal_is_json_with_a_korp_map_code() {
    let s = TestServer::start(ServerConfig::default()).await;
    let ok = format!("region={REGION}&bbox={SOUTH}&lod=12");
    assert_refusal(&s, "GET", "/v1/nothing", 404, 100).await;
    assert_refusal(&s, "GET", "/index.html", 404, 100).await;
    assert_refusal(&s, "POST", &format!("/v1/map/points?{ok}"), 405, 101).await;
    assert_refusal(&s, "DELETE", "/v1/regions", 405, 101).await;
    assert_refusal(&s, "GET", &format!("/v1/map/roads?{ok}"), 400, 102).await;
    assert_refusal(&s, "GET", &format!("/v1/map/?{ok}"), 400, 102).await;
    assert_refusal(
        &s,
        "GET",
        &format!("/v1/map/points?bbox={SOUTH}&lod=12"),
        400,
        103,
    )
    .await;
    assert_refusal(
        &s,
        "GET",
        &format!("/v1/map/points?region={REGION}&lod=12"),
        400,
        103,
    )
    .await;
    assert_refusal(
        &s,
        "GET",
        &format!("/v1/map/points?region={REGION}&bbox={SOUTH}"),
        400,
        103,
    )
    .await;
    for bad in [
        "1,2,3",
        "1,2,3,4,5",
        "a,2,3,4",
        "5,2,3,4",
        "1,5,3,4",
        "1,2,181,4",
        "1,-91,3,4",
        "NaN,2,3,4",
        "1,2,inf,4",
    ] {
        assert_refusal(
            &s,
            "GET",
            &format!("/v1/map/points?region={REGION}&bbox={bad}&lod=12"),
            400,
            104,
        )
        .await;
    }
    for bad in ["x", "-1", "31", "256", "1.5"] {
        assert_refusal(
            &s,
            "GET",
            &format!("/v1/map/points?region={REGION}&bbox={SOUTH}&lod={bad}"),
            400,
            105,
        )
        .await;
    }
    for bad in ["0", "-3", "many", ""] {
        assert_refusal(
            &s,
            "GET",
            &format!("/v1/map/points?{ok}&max={bad}"),
            400,
            106,
        )
        .await;
    }
    assert_refusal(
        &s,
        "GET",
        &format!("/v1/map/points?{ok}&compress=gzip"),
        400,
        107,
    )
    .await;
    assert_refusal(
        &s,
        "GET",
        &format!("/v1/map/points?region=atlantis&bbox={SOUTH}&lod=12"),
        404,
        108,
    )
    .await;
}

#[tokio::test(flavor = "multi_thread")]
async fn method_not_allowed_names_the_allowed_methods() {
    let s = TestServer::start(ServerConfig::default()).await;
    let r = request("PUT", &s.url("/v1/health")).await;
    assert_eq!(r.status, 405);
    assert_eq!(r.header("allow"), Some("GET, OPTIONS"));
}

#[tokio::test(flavor = "multi_thread")]
async fn a_preflight_is_answered_with_the_cors_headers() {
    let s = TestServer::start(ServerConfig::default()).await;
    let r = request("OPTIONS", &s.url("/v1/map/points")).await;
    assert_eq!(r.status, 204);
    assert_eq!(r.header("access-control-allow-origin"), Some("*"));
    assert_eq!(
        r.header("access-control-allow-methods"),
        Some("GET, OPTIONS")
    );
    assert!(r.header("access-control-allow-headers").is_some());
}

#[tokio::test(flavor = "multi_thread")]
async fn the_cors_origin_comes_from_the_server_flag() {
    let s = TestServer::start(ServerConfig {
        cors_origin: Some("http://localhost:8501".into()),
        ..ServerConfig::default()
    })
    .await;
    for p in ["/v1/health", "/v1/regions", "/v1/nothing"] {
        assert_eq!(
            get(&s.url(p)).await.header("access-control-allow-origin"),
            Some("http://localhost:8501"),
            "{p}"
        );
    }
    let off = TestServer::start(ServerConfig {
        cors_origin: None,
        ..ServerConfig::default()
    })
    .await;
    for p in ["/v1/health", "/v1/regions", "/v1/nothing"] {
        assert_eq!(
            get(&off.url(p)).await.header("access-control-allow-origin"),
            None,
            "{p}"
        );
    }
}

#[tokio::test(flavor = "multi_thread")]
async fn a_viewport_on_the_region_edge_keeps_rows_that_only_touch_it() {
    let s = TestServer::start(ServerConfig::default()).await;
    // A box that touches the first grid point exactly: the closed-box intersection keeps it.
    let b = BBox::new(9.0, 54.0, 10.013, 55.007).unwrap();
    let q = format!(
        "/v1/map/points?region={REGION}&bbox={},{},{},{}&lod=15",
        b.min_lon, b.min_lat, b.max_lon, b.max_lat
    );
    let (_, batches) = decode(&get(&s.url(&q)).await.body);
    assert_eq!(ids_of(&batches), vec![1000]);
}

#[tokio::test]
async fn max_counts_only_the_rows_that_are_sent() {
    // At lod 6 every fourth area has shrunk to a point and is not sent: `max` must count
    // the rows that are, so a reply says `truncated` only when it holds `max` rows and
    // one more was left out — whether the copies are stored native or WKB.
    for zs in [ZStore::Native, ZStore::Wkb] {
        let s = TestServer::start_with(ServerConfig::default(), zs).await;
        let all = "10,55,20,65";
        let n = expected_ids(&s.source, Kind::Areas, all.parse().unwrap(), 6).len();
        assert!(n > 2);
        for (max, truncated) in [(n - 1, true), (n, false), (n + 1, false)] {
            let r = get(&s.url(&format!(
                "/v1/map/areas?region={REGION}&bbox={all}&lod=6&max={max}"
            )))
            .await;
            let (schema, batches) = decode(&r.body);
            let (want, _) = expected_capped(&s.source, Kind::Areas, all.parse().unwrap(), 6, max);
            assert_eq!(ids_of(&batches), want, "{zs:?} max {max}");
            assert_eq!(want.len(), max.min(n));
            assert_eq!(meta(&schema).truncated, truncated, "{zs:?} max {max}");
        }
    }
}

#[tokio::test]
async fn wkb_stored_copies_give_the_same_reply_as_native_ones() {
    let native = TestServer::start_with(ServerConfig::default(), ZStore::Native).await;
    let wkb = TestServer::start_with(ServerConfig::default(), ZStore::Wkb).await;
    let all = "10,55,20,65";
    for kind in ["lines", "areas"] {
        for lod in [6u8, 9, 12, 15] {
            let q = format!("/v1/map/{kind}?region={REGION}&bbox={all}&lod={lod}");
            let (sn, bn) = decode(&get(&native.url(&q)).await.body);
            let (sw, bw) = decode(&get(&wkb.url(&q)).await.body);
            assert_eq!(sn.fields(), sw.fields(), "{kind} lod {lod}");
            assert_eq!(meta(&sn).geometry_source, meta(&sw).geometry_source);
            let n = arrow_select::concat::concat_batches(&sn, &bn).unwrap();
            let w = arrow_select::concat::concat_batches(&sw, &bw).unwrap();
            assert!(n.num_rows() > 0, "{kind} lod {lod}");
            assert_eq!(n.columns(), w.columns(), "{kind} lod {lod}");
        }
    }
}

/// The server's own paths, as fragments a refusal must not show: the whole directory and
/// every `a/b` of two neighbouring components in it.
fn path_fragments(dir: &std::path::Path) -> Vec<String> {
    let parts: Vec<String> = dir
        .components()
        .filter_map(|c| match c {
            std::path::Component::Normal(p) => Some(p.to_string_lossy().into_owned()),
            _ => None,
        })
        .collect();
    let mut out = vec![dir.to_string_lossy().into_owned()];
    out.extend(parts.windows(2).map(|w| format!("{}/{}", w[0], w[1])));
    out
}

#[tokio::test(flavor = "multi_thread")]
async fn no_refusal_shows_where_the_server_keeps_its_files() {
    let s = TestServer::start(ServerConfig::default()).await;
    let frags = path_fragments(&s.dir);
    // Break the lines file under the running server: its footer (read at start) stays,
    // its pages go, so a map read fails inside the file source with the file's path.
    let lines = s.dir.join("ways.multilinestring.parquet");
    let mut bytes = std::fs::read(&lines).unwrap();
    let n = bytes.len();
    bytes[4..n / 2].fill(0x5a);
    std::fs::write(&lines, &bytes).unwrap();
    let all = "10,54,25,70";
    let mut codes = std::collections::BTreeSet::new();
    for path in [
        format!("/v1/map/lines?region={REGION}&bbox={all}&lod=14"),
        format!("/v1/map/lines?region={REGION}&bbox={all}&lod=12&max=100000"),
        format!("/v1/map/points?region=nowhere&bbox={all}&lod=12"),
        format!("/v1/map/points?region={REGION}&bbox={all}&lod=99"),
        format!("/v1/geocode?region={REGION}&q=storgatan+1"),
        format!("/v1/revgeocode?region={REGION}&lon=18&lat=59"),
        "/v1/files/nowhere/native/lines.parquet".to_string(),
        "/v1/nothing".to_string(),
    ] {
        let r = get(&s.url(&path)).await;
        assert!(r.status >= 400, "{path}: {}", r.status);
        let body = String::from_utf8_lossy(&r.body).into_owned();
        codes.insert(r.json()["code"].as_str().unwrap_or("").to_string());
        for f in &frags {
            assert!(!body.contains(f.as_str()), "{path}: {f:?} in {body}");
        }
    }
    assert!(
        codes.contains("korp-map-110"),
        "the broken file was read: {codes:?}"
    );
}