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/flight.rs

//! **The Flight door**: a Flight client on the same port gets the same schema and batches
//! the HTTP door sends, the regions from `ListFlights`, and coded refusals.

mod common;

use arrow_flight::decode::FlightRecordBatchStream;
use arrow_flight::flight_service_client::FlightServiceClient;
use arrow_flight::{Criteria, FlightDescriptor, Ticket};
use common::*;
use futures::TryStreamExt;
use korp_map_wire::{Region, ServerConfig};

async fn client(s: &TestServer) -> FlightServiceClient<tonic::transport::Channel> {
    let ch = tonic::transport::Endpoint::from_shared(format!("http://{}", s.addr))
        .unwrap()
        .connect()
        .await
        .unwrap();
    FlightServiceClient::new(ch).max_decoding_message_size(usize::MAX)
}

async fn do_get(
    c: &mut FlightServiceClient<tonic::transport::Channel>,
    ticket: &str,
) -> Result<FlightRecordBatchStream, tonic::Status> {
    let s = c
        .do_get(Ticket {
            ticket: ticket.as_bytes().to_vec().into(),
        })
        .await?
        .into_inner();
    Ok(FlightRecordBatchStream::new_from_flight_data(
        s.map_err(Into::into),
    ))
}

#[tokio::test(flavor = "multi_thread")]
async fn do_get_returns_the_same_schema_and_batches_as_http() {
    let s = TestServer::start(ServerConfig::default()).await;
    let mut c = client(&s).await;
    for kind in ["points", "lines", "areas"] {
        for (bbox, lod, max) in [
            ("11,55,14.2,57.1", 12, None),
            ("10,55,20,65", 15, None),
            ("10,55,20,65", 15, Some(9)),
        ] {
            let max_q = max.map(|m| format!("&max={m}")).unwrap_or_default();
            let http = get(&s.url(&format!(
                "/v1/map/{kind}?region={REGION}&bbox={bbox}&lod={lod}{max_q}"
            )))
            .await;
            let (hs, hb) = decode(&http.body);
            let max_t = max.map(|m| format!(",\"max\":{m}")).unwrap_or_default();
            let t = format!(
                r#"{{"region":"{REGION}","bbox":[{bbox}],"lod":{lod},"kind":"{kind}"{max_t}}}"#
            );
            let mut st = do_get(&mut c, &t).await.unwrap();
            let mut fb = Vec::new();
            while let Some(b) = st.try_next().await.unwrap() {
                fb.push(b);
            }
            let fs = st.schema().cloned().expect("schema");
            assert_eq!(*fs, *hs, "{kind} {bbox}: schema and metadata");
            assert_eq!(fb.len(), hb.len(), "{kind} {bbox}: batch boundaries");
            assert_eq!(fb, hb, "{kind} {bbox}");
        }
    }
}

#[tokio::test(flavor = "multi_thread")]
async fn do_get_on_an_empty_viewport_still_sends_the_schema() {
    let s = TestServer::start(ServerConfig::default()).await;
    let mut c = client(&s).await;
    let t = format!(r#"{{"region":"{REGION}","bbox":[-30,-40,-29,-39],"lod":12,"kind":"areas"}}"#);
    let mut st = do_get(&mut c, &t).await.unwrap();
    let mut n = 0;
    while let Some(b) = st.try_next().await.unwrap() {
        n += b.num_rows();
    }
    assert_eq!(n, 0);
    let schema = st.schema().cloned().expect("schema sent with no batches");
    assert_eq!(schema.metadata()["row_groups_scanned"], "0");
    assert!(schema.metadata().contains_key("geo"));
}

#[tokio::test(flavor = "multi_thread")]
async fn list_flights_lists_the_regions() {
    let s = TestServer::start(ServerConfig::default()).await;
    let mut c = client(&s).await;
    let infos: Vec<_> = c
        .list_flights(Criteria::default())
        .await
        .unwrap()
        .into_inner()
        .try_collect()
        .await
        .unwrap();
    assert_eq!(infos.len(), 1);
    let http: Vec<Region> = serde_json::from_slice(&get(&s.url("/v1/regions")).await.body).unwrap();
    let r: Region = serde_json::from_slice(&infos[0].app_metadata).unwrap();
    assert_eq!(r, http[0]);
    assert_eq!(
        infos[0].flight_descriptor,
        Some(FlightDescriptor::new_path(vec![REGION.to_string()]))
    );
}

fn code_of(st: &tonic::Status) -> String {
    let v: serde_json::Value =
        serde_json::from_str(st.message()).expect("the message is the JSON error body");
    v["code"].as_str().unwrap().to_string()
}

#[tokio::test(flavor = "multi_thread")]
async fn flight_refusals_carry_the_korp_map_code() {
    let s = TestServer::start(ServerConfig::default()).await;
    let mut c = client(&s).await;
    let cases = [
        ("not json", tonic::Code::InvalidArgument, 109),
        (
            r#"{"region":"testland","bbox":[1,2,3],"lod":1,"kind":"points"}"#,
            tonic::Code::InvalidArgument,
            109,
        ),
        (
            r#"{"region":"testland","bbox":[1,2,3,4],"lod":1,"kind":"roads"}"#,
            tonic::Code::InvalidArgument,
            109,
        ),
        (
            r#"{"region":"testland","bbox":[1,2,3,4],"lod":31,"kind":"points"}"#,
            tonic::Code::InvalidArgument,
            105,
        ),
        (
            r#"{"region":"testland","bbox":[1,2,3,4],"lod":3,"kind":"points","max":0}"#,
            tonic::Code::InvalidArgument,
            106,
        ),
        (
            r#"{"region":"atlantis","bbox":[1,2,3,4],"lod":3,"kind":"points"}"#,
            tonic::Code::NotFound,
            108,
        ),
    ];
    for (t, grpc, code) in cases {
        let st = match do_get(&mut c, t).await {
            Err(st) => st,
            Ok(mut stream) => stream.try_next().await.expect_err("refused").into(),
        };
        assert_eq!(st.code(), grpc, "{t}");
        assert_eq!(code_of(&st), format!("korp-map-{code}"), "{t}");
    }
    let st = c
        .get_schema(FlightDescriptor::new_path(vec![REGION.into()]))
        .await
        .unwrap_err();
    assert_eq!(st.code(), tonic::Code::Unimplemented);
    assert_eq!(code_of(&st), "korp-map-112");
}