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

//! **HTTP content encoding on the HTTP door**: a reply asked for with
//! `Accept-Encoding: zstd`, `br` or `gzip` decodes to exactly the bytes of the plain
//! reply; short replies and replies with Arrow IPC compression inside go out as they
//! are; every Arrow and JSON reply says `Vary: Accept-Encoding`.

mod common;

use std::io::Read;

use bytes::Bytes;
use common::*;
use http_body_util::{BodyExt, Empty};
use hyper_util::client::legacy::Client;
use hyper_util::rt::TokioExecutor;
use korp_map_wire::encoding::MIN_SIZE;
use korp_map_wire::{ContentEncoding, ServerConfig};

async fn get_with(url: &str, accept: Option<&str>) -> Reply {
    let client = Client::builder(TokioExecutor::new()).build_http::<Empty<Bytes>>();
    let mut req = http::Request::get(url);
    if let Some(a) = accept {
        req = req.header("accept-encoding", a);
    }
    let res = client
        .request(req.body(Empty::new()).unwrap())
        .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,
    }
}

fn decode(token: &str, data: &[u8]) -> Vec<u8> {
    let mut out = Vec::new();
    match token {
        "zstd" => out = zstd::stream::decode_all(data).unwrap(),
        "br" => {
            brotli::Decompressor::new(data, 4096)
                .read_to_end(&mut out)
                .unwrap();
        }
        "gzip" => {
            flate2::read::GzDecoder::new(data)
                .read_to_end(&mut out)
                .unwrap();
        }
        other => panic!("{other}"),
    }
    out
}

const BIG: &str = "/v1/map/lines?region=testland&bbox=10,55,20,65&lod=15";

#[tokio::test(flavor = "multi_thread")]
async fn every_coding_decodes_to_the_plain_reply_for_arrow_and_json() {
    let s = AddressServer::start(ServerConfig::default()).await;
    let geocode = format!("/v1/geocode?region={REGION}&q=storgatan&max=1000");
    for path in [
        BIG,
        "/v1/map/areas?region=testland&bbox=10,55,20,65&lod=9",
        &geocode,
    ] {
        let plain = get_with(&s.url(path), None).await;
        assert_eq!(plain.status, 200);
        assert_eq!(plain.header("content-encoding"), None, "{path}");
        assert_eq!(plain.header("vary"), Some("accept-encoding"), "{path}");
        assert!(
            plain.body.len() >= MIN_SIZE,
            "{path}: {} bytes",
            plain.body.len()
        );
        for c in ContentEncoding::ALL {
            let r = get_with(&s.url(path), Some(c.token())).await;
            assert_eq!(r.status, 200);
            assert_eq!(r.header("content-encoding"), Some(c.token()), "{path}");
            assert_eq!(r.header("vary"), Some("accept-encoding"), "{path}");
            assert_eq!(r.header("access-control-allow-origin"), Some("*"));
            assert_eq!(r.header("content-type"), plain.header("content-type"));
            assert!(r.body.len() < plain.body.len(), "{path} {c:?}: smaller");
            assert_eq!(
                decode(c.token(), &r.body),
                plain.body,
                "{path} {c:?}: the same bytes"
            );
        }
    }
}

#[tokio::test(flavor = "multi_thread")]
async fn a_browsers_accept_encoding_gets_zstd() {
    let s = TestServer::start(ServerConfig::default()).await;
    let r = get_with(&s.url(BIG), Some("gzip, deflate, br, zstd")).await;
    assert_eq!(r.header("content-encoding"), Some("zstd"));
    let r = get_with(&s.url(BIG), Some("gzip, deflate, br")).await;
    assert_eq!(r.header("content-encoding"), Some("br"));
    let r = get_with(&s.url(BIG), Some("identity")).await;
    assert_eq!(r.header("content-encoding"), None);
}

#[tokio::test(flavor = "multi_thread")]
async fn short_replies_go_out_as_they_are() {
    let s = TestServer::start(ServerConfig::default()).await;
    for path in [
        "/v1/map/lines?region=testland&bbox=0,0,1,1&lod=12".to_string(),
        "/v1/regions".to_string(),
    ] {
        let plain = get_with(&s.url(&path), None).await;
        assert!(plain.body.len() < MIN_SIZE, "{path}: {}", plain.body.len());
        let r = get_with(&s.url(&path), Some("zstd, br, gzip")).await;
        assert_eq!(r.status, 200);
        assert_eq!(r.header("content-encoding"), None, "{path}");
        assert_eq!(r.header("vary"), Some("accept-encoding"), "{path}");
        assert_eq!(r.body, plain.body, "{path}");
    }
}

#[tokio::test(flavor = "multi_thread")]
async fn ipc_compression_is_not_compressed_again() {
    let s = TestServer::start(ServerConfig::default()).await;
    let path = format!("{BIG}&compress=zstd");
    let plain = get_with(&s.url(&path), None).await;
    let r = get_with(&s.url(&path), Some("zstd, br, gzip")).await;
    assert_eq!(r.status, 200);
    assert_eq!(r.header("content-encoding"), None);
    let (schema, batches) = decode_ipc(&r.body);
    let (want_schema, want) = decode_ipc(&plain.body);
    assert_eq!((schema, batches), (want_schema, want));
}

#[tokio::test(flavor = "multi_thread")]
async fn a_refusal_is_not_encoded() {
    let s = TestServer::start(ServerConfig::default()).await;
    let r = get_with(
        &s.url("/v1/map/lines?region=atlantis&bbox=10,55,20,65&lod=15"),
        Some("zstd"),
    )
    .await;
    assert_eq!(r.status, 404);
    assert_eq!(r.header("content-encoding"), None);
    assert_eq!(r.json()["code"], "korp-map-108");
}

fn decode_ipc(body: &[u8]) -> (arrow_schema::SchemaRef, Vec<arrow_array::RecordBatch>) {
    common::decode(body)
}