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/common/mod.rs

//! Shared test kit: a fixture region on disk, a server on a free port, an HTTP client.
#![allow(dead_code)]

use std::io::Cursor;
use std::net::SocketAddr;
use std::path::{Path, PathBuf};
use std::sync::Arc;

use arrow_array::RecordBatch;
use arrow_array::cast::AsArray;
use arrow_array::types::{Float32Type, Int64Type, UInt8Type};
use arrow_ipc::reader::StreamReader;
use arrow_schema::SchemaRef;
use bytes::Bytes;
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, ServerConfig};
use parquet::arrow::arrow_reader::ParquetRecordBatchReaderBuilder;

pub const REGION: &str = "testland";

/// A grid over lon 10..20, lat 55..65, sorted south→north so row groups are bands.
fn grid() -> Vec<(f64, f64)> {
    let mut v = Vec::new();
    for j in 0..20 {
        for i in 0..20 {
            v.push((
                10.0 + f64::from(i) * 0.5 + 0.013,
                55.0 + f64::from(j) * 0.5 + 0.007,
            ));
        }
    }
    v
}

fn zoom(k: usize) -> u8 {
    match k % 7 {
        0 => 6,
        1 | 2 => 9,
        3 => 15,
        _ => 12,
    }
}

fn tags(k: usize) -> Option<String> {
    let t = [
        "highway\":\"residential",
        "building\":\"yes",
        "natural\":\"water",
        "landuse\":\"forest",
    ];
    (k % 11 != 5).then(|| format!("{{\"{}\"}}", t[k % t.len()]))
}

/// Write the fixture region into `root/testland` and return that directory.
pub fn write_region(root: &Path) -> PathBuf {
    write_region_with(root, ZStore::Native)
}

/// [`write_region`] with the simplified copies stored as `zs` says.
pub fn write_region_with(root: &Path, zs: ZStore) -> PathBuf {
    let dir = root.join(REGION);
    std::fs::create_dir_all(&dir).unwrap();
    let g = grid();
    let nodes: Vec<Row> = g
        .iter()
        .enumerate()
        .map(|(k, &(x, y))| Row {
            id: 1000 + k as i64,
            geom: Some(Geom::Point(x, y)),
            tags: tags(k),
            min_zoom: zoom(k),
        })
        .collect();
    fixture::write(
        &dir.join("nodes.point.parquet"),
        Kind::Points,
        Table::Nodes,
        &nodes,
        16,
        zs,
    )
    .unwrap();
    let lines: Vec<Row> = g
        .iter()
        .enumerate()
        .map(|(k, &(x, y))| Row {
            id: 2000 + k as i64,
            geom: (k % 13 != 4).then(|| {
                let mut parts = vec![vec![(x, y), (x + 0.2, y + 0.1), (x + 0.3, y + 0.05)]];
                if k % 3 == 0 {
                    parts.push(vec![(x + 0.01, y + 0.2), (x + 0.02, y + 0.3)]);
                }
                Geom::Lines(parts)
            }),
            tags: tags(k),
            min_zoom: zoom(k),
        })
        .collect();
    fixture::write(
        &dir.join("ways.multilinestring.parquet"),
        Kind::Lines,
        Table::Ways,
        &lines,
        16,
        zs,
    )
    .unwrap();
    let sq = |x: f64, y: f64, d: f64| vec![(x, y), (x + d, y), (x + d, y + d), (x, y + d), (x, y)];
    let areas: Vec<Row> = g
        .iter()
        .enumerate()
        .map(|(k, &(x, y))| Row {
            id: 3000 + k as i64,
            geom: Some(Geom::Polygons(vec![vec![sq(x, y, 0.2)]])),
            tags: tags(k),
            min_zoom: zoom(k),
        })
        .collect();
    fixture::write(
        &dir.join("ways.multipolygon.parquet"),
        Kind::Areas,
        Table::Ways,
        &areas,
        16,
        zs,
    )
    .unwrap();
    let rels: Vec<Row> = g
        .iter()
        .enumerate()
        .step_by(9)
        .map(|(k, &(x, y))| Row {
            id: 9_000_000 + k as i64,
            geom: Some(Geom::Polygons(vec![
                vec![sq(x, y, 0.4), sq(x + 0.1, y + 0.1, 0.1)],
                vec![sq(x + 0.45, y, 0.03)],
            ])),
            tags: Some("{\"natural\":\"water\",\"type\":\"multipolygon\"}".into()),
            min_zoom: zoom(k),
        })
        .collect();
    fixture::write(
        &dir.join("relations.resolved.multipolygon.parquet"),
        Kind::Areas,
        Table::Relations,
        &rels,
        8,
        zs,
    )
    .unwrap();
    // A WKB table beside them is ignored by name.
    std::fs::write(dir.join("ways.parquet"), b"not a native file").unwrap();
    dir
}

/// A running server over a fresh fixture region.
pub struct TestServer {
    pub addr: SocketAddr,
    pub dir: PathBuf,
    pub source: Arc<FileSource>,
    _tmp: tempfile::TempDir,
}

impl TestServer {
    pub async fn start(cfg: ServerConfig) -> Self {
        Self::start_with(cfg, ZStore::Native).await
    }

    /// A server over a fixture region whose simplified copies are stored as `zs` says.
    pub async fn start_with(cfg: ServerConfig, zs: ZStore) -> Self {
        let tmp = tempfile::tempdir().unwrap();
        let dir = write_region_with(tmp.path(), zs);
        let source = Arc::new(FileSource::open_dir(&dir).unwrap().with_batch_rows(50));
        let listener = tokio::net::TcpListener::bind("127.0.0.1:0").await.unwrap();
        let addr = listener.local_addr().unwrap();
        let s = source.clone();
        tokio::spawn(async move { korp_map_wire::serve(listener, s, cfg).await });
        Self {
            addr,
            dir,
            source,
            _tmp: tmp,
        }
    }

    pub fn url(&self, path_and_query: &str) -> String {
        format!("http://{}{path_and_query}", self.addr)
    }
}

pub struct Reply {
    pub status: u16,
    pub headers: http::HeaderMap,
    pub body: Bytes,
}

impl Reply {
    pub fn json(&self) -> serde_json::Value {
        serde_json::from_slice(&self.body)
            .unwrap_or_else(|e| panic!("not JSON ({e}): {:?}", self.body))
    }
    pub fn header(&self, h: &str) -> Option<&str> {
        self.headers.get(h).and_then(|v| v.to_str().ok())
    }
}

pub async fn request(method: &str, url: &str) -> Reply {
    let client = Client::builder(TokioExecutor::new()).build_http::<Empty<Bytes>>();
    let req = http::Request::builder()
        .method(method)
        .uri(url)
        .body(Empty::new())
        .unwrap();
    let res = client.request(req).await.unwrap();
    let status = res.status().as_u16();
    let headers = res.headers().clone();
    let body = res.into_body().collect().await.unwrap().to_bytes();
    Reply {
        status,
        headers,
        body,
    }
}

pub async fn get(url: &str) -> Reply {
    request("GET", url).await
}

/// Decode an IPC stream body.
pub fn decode(body: &[u8]) -> (SchemaRef, Vec<RecordBatch>) {
    let r = StreamReader::try_new(Cursor::new(body.to_vec()), None).unwrap();
    let schema = r.schema();
    let batches = r.collect::<Result<Vec<_>, _>>().unwrap();
    (schema, batches)
}

/// The Arrow schema the parquet reader gives a file.
pub fn file_schema(path: &Path) -> SchemaRef {
    ParquetRecordBatchReaderBuilder::try_new(std::fs::File::open(path).unwrap())
        .unwrap()
        .schema()
        .clone()
}

/// All of a file's rows.
pub fn file_batches(path: &Path) -> Vec<RecordBatch> {
    ParquetRecordBatchReaderBuilder::try_new(std::fs::File::open(path).unwrap())
        .unwrap()
        .build()
        .unwrap()
        .collect::<Result<Vec<_>, _>>()
        .unwrap()
}

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

/// Is this WKB (little-endian, as the fixture writes) a shape the kind can carry?
pub fn wkb_fits(kind: Kind, w: &[u8]) -> bool {
    let t = u32::from_le_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,
    }
}

/// The lowest `min_zoom` the fixture stores: a lod below it is answered as it.
pub const LOWEST_LEVEL: u8 = 6;

/// The ids a query with no `max` must answer, by brute force over every row of every file
/// of the kind: viewport, `min_zoom`, tagged points, and a simplified geometry that fits.
pub fn expected_ids(source: &FileSource, kind: Kind, b: BBox, lod: u8) -> Vec<i64> {
    expected_rows(source, kind, b, lod)
        .into_iter()
        .map(|(id, _)| id)
        .collect()
}

/// The ids and the `truncated` flag a query with `max` must answer: everything when it
/// fits; else every row above the cut level `L` (the lowest level whose rows, with the
/// ones above, exceed `max`) and the rest of `max` spread evenly over the level-`L` rows
/// in file order — `floor((i+1)·take/count) > floor(i·take/count)` keeps the i-th.
pub fn expected_capped(
    source: &FileSource,
    kind: Kind,
    b: BBox,
    lod: u8,
    max: usize,
) -> (Vec<i64>, bool) {
    let rows = expected_rows(source, kind, b, lod);
    if rows.len() <= max {
        return (rows.into_iter().map(|(id, _)| id).collect(), false);
    }
    let mut per = [0usize; 256];
    for (_, z) in &rows {
        per[usize::from(*z)] += 1;
    }
    let (mut cum, mut cut) = (0usize, 0u8);
    for (l, n) in per.iter().enumerate() {
        if cum + n > max {
            cut = l as u8;
            break;
        }
        cum += n;
    }
    let (take, count) = (max - cum, per[usize::from(cut)]);
    let mut i = 0usize;
    let kept = rows
        .into_iter()
        .filter(|&(_, z)| {
            if z != cut {
                return z < cut;
            }
            let k = (i + 1) * take / count > i * take / count;
            i += 1;
            k
        })
        .map(|(id, _)| id)
        .collect();
    (kept, true)
}

/// [`expected_ids`] with each row's `min_zoom`, in file order.
pub fn expected_rows(source: &FileSource, kind: Kind, b: BBox, lod: u8) -> Vec<(i64, u8)> {
    let lod = lod.max(LOWEST_LEVEL);
    let mut out = Vec::new();
    for f in source.files(REGION, kind) {
        for batch in file_batches(&f) {
            let ids = batch
                .column_by_name("id")
                .unwrap()
                .as_primitive::<Int64Type>();
            let z = batch
                .column_by_name("min_zoom")
                .unwrap()
                .as_primitive::<UInt8Type>();
            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 tags = batch
                .column_by_name("tags")
                .unwrap()
                .as_string::<i32>()
                .clone();
            let zcol = z_column(kind, lod).map(|n| batch.column_by_name(n).unwrap().clone());
            let geom = batch.column_by_name("geometry").unwrap().clone();
            for r in 0..batch.num_rows() {
                let shown = match kind {
                    Kind::Points => tags.is_valid(r) && !matches!(tags.value(r).trim(), "" | "{}"),
                    _ => match &zcol {
                        // WKB copies (older exports): the copy must fit the kind.
                        Some(zc) if zc.data_type() == &arrow_schema::DataType::Binary => {
                            zc.is_valid(r) && wkb_fits(kind, zc.as_binary::<i32>().value(r))
                        }
                        // Native copies: a copy of another type is already NULL.
                        Some(zc) => zc.is_valid(r),
                        None => geom.is_valid(r),
                    },
                };
                if 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
                {
                    out.push((ids.value(r), z.value(r)));
                }
            }
        }
    }
    out
}

pub fn ids_of(batches: &[RecordBatch]) -> Vec<i64> {
    batches
        .iter()
        .flat_map(|b| {
            b.column_by_name("id")
                .unwrap()
                .as_primitive::<Int64Type>()
                .values()
                .to_vec()
        })
        .collect()
}

use arrow_array::Array as _;

// ── The address lookups (contract v1.2) ──────────────────────────────────────────────

/// The fixture region's addresses: twelve on Storgatan, one on Kungsgatan, one with no
/// city, spread over the grid.
pub fn addresses() -> Vec<korp_map_wire::GeocodeHit> {
    let mut v: Vec<korp_map_wire::GeocodeHit> = (1..=12)
        .map(|n| korp_map_wire::GeocodeHit {
            street: "Storgatan".to_string(),
            housenumber: n.to_string(),
            city: "Uppsala".to_string(),
            postcode: "753 20".to_string(),
            lon: 17.63 + f64::from(n) * 0.001,
            lat: 59.85,
            source: 500 + i64::from(n),
            score: 0,
        })
        .collect();
    v.push(korp_map_wire::GeocodeHit {
        street: "Kungsgatan".to_string(),
        housenumber: "3".to_string(),
        city: "Umeå".to_string(),
        postcode: "903 26".to_string(),
        lon: 20.26,
        lat: 63.83,
        source: 900,
        score: 0,
    });
    v.push(korp_map_wire::GeocodeHit {
        street: "Byvägen".to_string(),
        housenumber: "7".to_string(),
        city: String::new(),
        postcode: String::new(),
        lon: 14.5,
        lat: 61.0,
        source: 901,
        score: 0,
    });
    v
}

/// **A source with an address book**: the fixture region's map from a [`FileSource`],
/// and a plain lookup over [`addresses`] — every address whose `street number city`
/// holds each word of the text, in book order; the nearest by squared degrees for the
/// reverse. The ranking is korp-map's business (its own tests); the wire only carries it.
pub struct AddressBook {
    pub map: FileSource,
    pub book: Vec<korp_map_wire::GeocodeHit>,
}

impl AddressBook {
    fn served(&self, region: &str) -> Result<(), korp_map_wire::WireError> {
        if region == REGION {
            Ok(())
        } else {
            Err(korp_map_wire::WireError::new(
                korp_map_wire::Code::UnknownRegion,
                format!("region {region:?} is not served here"),
            ))
        }
    }
}

impl korp_map_wire::MapSource for AddressBook {
    fn regions(&self) -> Result<Vec<korp_map_wire::Region>, korp_map_wire::WireError> {
        self.map.regions()
    }
    fn query(
        &self,
        q: &korp_map_wire::MapQuery,
    ) -> Result<korp_map_wire::MapReply, korp_map_wire::WireError> {
        self.map.query(q)
    }
    fn geocode(
        &self,
        q: &korp_map_wire::GeocodeQuery,
    ) -> Result<korp_map_wire::GeocodeReply, korp_map_wire::WireError> {
        self.served(&q.region)?;
        let words: Vec<String> = q.q.split_whitespace().map(str::to_lowercase).collect();
        let hits = self
            .book
            .iter()
            .filter(|a| {
                let text = format!("{} {} {}", a.street, a.housenumber, a.city).to_lowercase();
                words.iter().all(|w| text.contains(w.as_str()))
            })
            .take(usize::try_from(q.limit()).unwrap())
            .map(|a| korp_map_wire::GeocodeHit {
                score: 80,
                ..a.clone()
            })
            .collect();
        Ok(korp_map_wire::GeocodeReply {
            region: q.region.clone(),
            query: q.q.clone(),
            indexed: self.book.len() as u64,
            hits,
        })
    }
    fn revgeocode(
        &self,
        q: &korp_map_wire::RevGeocodeQuery,
    ) -> Result<korp_map_wire::RevGeocodeReply, korp_map_wire::WireError> {
        self.served(&q.region)?;
        let d2 = |a: &korp_map_wire::GeocodeHit| (a.lon - q.lon).powi(2) + (a.lat - q.lat).powi(2);
        let hit = self
            .book
            .iter()
            .min_by(|a, b| d2(a).total_cmp(&d2(b)))
            .cloned();
        let distance_m = hit.as_ref().map_or(0.0, |h| d2(h).sqrt() * 111_000.0);
        Ok(korp_map_wire::RevGeocodeReply {
            region: q.region.clone(),
            lon: q.lon,
            lat: q.lat,
            indexed: self.book.len() as u64,
            hit,
            distance_m,
        })
    }
}

/// A running server over the fixture region and its address book.
pub struct AddressServer {
    pub addr: SocketAddr,
    pub source: Arc<AddressBook>,
    _tmp: tempfile::TempDir,
}

impl AddressServer {
    pub async fn start(cfg: ServerConfig) -> Self {
        let tmp = tempfile::tempdir().unwrap();
        let dir = write_region(tmp.path());
        let source = Arc::new(AddressBook {
            map: FileSource::open_dir(&dir).unwrap(),
            book: addresses(),
        });
        let listener = tokio::net::TcpListener::bind("127.0.0.1:0").await.unwrap();
        let addr = listener.local_addr().unwrap();
        let s = source.clone();
        tokio::spawn(async move { korp_map_wire::serve(listener, s, cfg).await });
        Self {
            addr,
            source,
            _tmp: tmp,
        }
    }

    pub fn url(&self, path_and_query: &str) -> String {
        format!("http://{}{path_and_query}", self.addr)
    }
}