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/src/http.rs

//! **The HTTP door** (the browser's; also curl-able).
//!
//! * `GET /v1/health` → `200 ok`
//! * `GET /v1/regions` → JSON `[{"name","bbox":[minlon,minlat,maxlon,maxlat],"data_version"}]`
//! * `GET /v1/map/{kind}?region=R&bbox=minlon,minlat,maxlon,maxlat&lod=N[&max=K][&compress=zstd]`
//!   → `200`, `application/vnd.apache.arrow.stream`, an Arrow IPC stream (schema + ≥ 0 batches)
//! * `GET /v1/geocode?region=R&q=…[&max=K]` → JSON [`GeocodeReply`](crate::GeocodeReply)
//! * `GET /v1/revgeocode?region=R&lon=…&lat=…` → JSON [`RevGeocodeReply`](crate::RevGeocodeReply)
//! * `GET /` and `GET /v1/` → the landing page ([`crate::landing`]); `GET /openapi.json`
//!   → the OpenAPI 3.1 description ([`crate::openapi`])
//! * any refusal → `4xx/5xx` with `{"error": "...", "code": "korp-map-<n>"}`
//!
//! Every response carries `Access-Control-Allow-Origin` when the server has a CORS origin;
//! `OPTIONS` answers a preflight.
//!
//! The Arrow and JSON replies are sent zstd, brotli or gzip encoded when the request's
//! `Accept-Encoding` allows one and the reply is at least [`MIN_SIZE`] bytes
//! ([`crate::encoding`]); they carry `Vary: Accept-Encoding` either way.
//!
//! They carry a strong `ETag` (the region's `data_version` and the parsed query,
//! [`crate::cache`]) and `Cache-Control: public, max-age=…`; a request whose
//! `If-None-Match` matches is answered `304 Not Modified` without reading the source.

use std::collections::HashMap;
use std::pin::Pin;
use std::sync::Arc;
use std::task::{Context, Poll};
use std::time::Instant;

use bytes::Bytes;
use http::{HeaderValue, Method, Request, Response, StatusCode, header};
use http_body::Frame;
use http_body_util::{BodyExt, Full, combinators::UnsyncBoxBody};
use tokio::sync::mpsc;

use crate::cache;
use crate::encoding::{ContentEncoding, MIN_SIZE};
use crate::error::{Code, WireError};
use crate::geocode::{geocode_query_from, revgeocode_query_from};
use crate::ipc::{CONTENT_TYPE, Compression, IpcChunks};
use crate::server::ServerConfig;
use crate::source::{BBox, Kind, MapQuery, MapSource};

/// Any error a body may end with.
pub type BoxError = Box<dyn std::error::Error + Send + Sync>;
/// Every response body the server sends (HTTP and Flight alike).
pub type Body = UnsyncBoxBody<Bytes, BoxError>;

/// A whole body from bytes.
pub fn full(b: impl Into<Bytes>) -> Body {
    Full::new(b.into())
        .map_err(|never| match never {})
        .boxed_unsync()
}

/// A body fed by a channel: each message is one frame; an `Err` aborts the response.
pub(crate) struct ChannelBody {
    pub(crate) rx: mpsc::Receiver<Result<Bytes, BoxError>>,
}

impl http_body::Body for ChannelBody {
    type Data = Bytes;
    type Error = BoxError;
    fn poll_frame(
        mut self: Pin<&mut Self>,
        cx: &mut Context<'_>,
    ) -> Poll<Option<Result<Frame<Bytes>, BoxError>>> {
        self.rx.poll_recv(cx).map(|o| o.map(|r| r.map(Frame::data)))
    }
}

fn with_cors(mut r: Response<Body>, cfg: &ServerConfig) -> Response<Body> {
    if let Some(origin) = cfg
        .cors_origin
        .as_deref()
        .and_then(|o| HeaderValue::from_str(o).ok())
    {
        r.headers_mut()
            .insert(header::ACCESS_CONTROL_ALLOW_ORIGIN, origin);
    }
    r
}

fn response(status: u16, content_type: &str, body: Body) -> Response<Body> {
    let mut r = Response::new(body);
    *r.status_mut() = StatusCode::from_u16(status).unwrap_or(StatusCode::INTERNAL_SERVER_ERROR);
    if let Ok(v) = HeaderValue::from_str(content_type) {
        r.headers_mut().insert(header::CONTENT_TYPE, v);
    }
    r
}

/// The JSON refusal for `e`.
#[must_use]
pub fn error_response(e: &WireError) -> Response<Body> {
    let mut r = response(e.code.http_status(), "application/json", full(e.to_json()));
    if e.code == Code::MethodNotAllowed {
        r.headers_mut()
            .insert(header::ALLOW, HeaderValue::from_static("GET, OPTIONS"));
    }
    r
}

/// Decode `%XX` and `+` in a query-string piece.
fn percent_decode(s: &str) -> String {
    let b = s.as_bytes();
    let mut out = Vec::with_capacity(b.len());
    let mut i = 0;
    while i < b.len() {
        match b[i] {
            b'+' => out.push(b' '),
            b'%' if i + 2 < b.len() => {
                let hex = std::str::from_utf8(&b[i + 1..i + 3])
                    .ok()
                    .and_then(|h| u8::from_str_radix(h, 16).ok());
                match hex {
                    Some(v) => {
                        out.push(v);
                        i += 3;
                        continue;
                    }
                    None => out.push(b'%'),
                }
            }
            c => out.push(c),
        }
        i += 1;
    }
    String::from_utf8_lossy(&out).into_owned()
}

/// The query string as a map (the last of a repeated key wins).
#[must_use]
pub fn parse_query(q: Option<&str>) -> HashMap<String, String> {
    q.unwrap_or("")
        .split('&')
        .filter(|p| !p.is_empty())
        .map(|p| match p.split_once('=') {
            Some((k, v)) => (percent_decode(k), percent_decode(v)),
            None => (percent_decode(p), String::new()),
        })
        .collect()
}

pub(crate) fn required<'a>(
    p: &'a HashMap<String, String>,
    name: &str,
) -> Result<&'a str, WireError> {
    p.get(name)
        .map(String::as_str)
        .filter(|v| !v.is_empty())
        .ok_or_else(|| {
            WireError::new(
                Code::MissingParam,
                format!("query parameter {name:?} is missing"),
            )
        })
}

/// The map query a `/v1/map/{kind}` request asks, with the server's default `max` applied.
pub fn map_query_from(
    kind: &str,
    query: Option<&str>,
    cfg: &ServerConfig,
) -> Result<(MapQuery, Compression), WireError> {
    let kind: Kind = kind.parse()?;
    let p = parse_query(query);
    let region = required(&p, "region")?.to_string();
    let bbox: BBox = required(&p, "bbox")?.parse()?;
    let lod_s = required(&p, "lod")?;
    let lod: u8 = lod_s.parse().map_err(|_| {
        WireError::new(
            Code::BadLod,
            format!("lod {lod_s:?} is not an integer in 0..=30"),
        )
    })?;
    let max = match p.get("max") {
        None => cfg.default_max,
        // A number is parsed here and judged by `MapQuery::validate`, the one place the
        // Flight ticket is judged too, so `max=0` gets the same sentence on both doors.
        Some(m) => Some(m.parse::<u64>().map_err(|_| {
            WireError::new(Code::BadMax, format!("max {m:?} is not a positive integer"))
        })?),
    };
    let compress = match p.get("compress") {
        None => Compression::None,
        Some(c) => c.parse()?,
    };
    let q = MapQuery {
        region,
        bbox,
        lod,
        kind,
        max,
    };
    q.validate()?;
    Ok((q, compress))
}

/// `Vary: Accept-Encoding` and, when `enc` is one, `Content-Encoding`.
fn with_encoding(mut r: Response<Body>, enc: Option<ContentEncoding>) -> Response<Body> {
    let h = r.headers_mut();
    h.insert(header::VARY, HeaderValue::from_static("accept-encoding"));
    if let Some(e) = enc {
        h.insert(
            header::CONTENT_ENCODING,
            HeaderValue::from_static(e.token()),
        );
    }
    r
}

/// **Every route of the HTTP door**, as path templates. The router serves these and
/// nothing else, and the OpenAPI description lists exactly these.
pub const ROUTES: &[&str] = &[
    "/",
    "/v1/",
    "/openapi.json",
    "/v1/health",
    "/v1/regions",
    "/v1/map/{kind}",
    "/v1/geocode",
    "/v1/revgeocode",
    "/v1/files/",
    "/v1/files/{region}/",
    "/v1/files/{region}/{set}/{file}",
];

/// The route template `path` is served under (`/v1` is the landing page too).
#[must_use]
pub fn route_of(path: &str) -> Option<&'static str> {
    if path == "/v1" {
        return Some("/v1/");
    }
    if path.starts_with("/v1/map/") {
        return Some("/v1/map/{kind}");
    }
    if let Some(rest) = path
        .strip_prefix("/v1/files")
        .map(|r| r.trim_start_matches('/'))
        && (path.len() == "/v1/files".len() || path.as_bytes()["/v1/files".len()] == b'/')
    {
        let segs: Vec<&str> = rest.split('/').collect();
        return match segs.as_slice() {
            [""] => Some("/v1/files/"),
            [r] | [r, ""] if !r.is_empty() => Some("/v1/files/{region}/"),
            [r, s, f] if !r.is_empty() && !s.is_empty() && !f.is_empty() => {
                Some("/v1/files/{region}/{set}/{file}")
            }
            _ => None,
        };
    }
    ROUTES
        .iter()
        .copied()
        .find(|r| *r == path && !r.contains('{'))
}

/// Serve one HTTP request.
pub async fn handle<S: MapSource, B>(
    source: Arc<S>,
    cfg: Arc<ServerConfig>,
    req: Request<B>,
) -> Response<Body> {
    let accept = ContentEncoding::negotiate(
        req.headers()
            .get(header::ACCEPT_ENCODING)
            .and_then(|v| v.to_str().ok()),
    );
    let if_none_match = req
        .headers()
        .get(header::IF_NONE_MATCH)
        .and_then(|v| v.to_str().ok());
    let r = if req.uri().path().starts_with("/v1/files") {
        files_route(&cfg, req.method(), req.uri().path(), req.headers())
    } else {
        route(source, &cfg, req.method(), req.uri(), accept, if_none_match).await
    };
    with_cors(r, &cfg)
}

/// **`/v1/files/…`**: listings and the files themselves; `GET` and `HEAD`, never
/// content-encoded ([`crate::files`]).
fn files_route(
    cfg: &ServerConfig,
    method: &Method,
    path: &str,
    headers: &http::HeaderMap,
) -> Response<Body> {
    let Some(route) = route_of(path) else {
        return error_response(&WireError::new(
            Code::NoRoute,
            format!("no endpoint at {path}"),
        ));
    };
    if method == Method::OPTIONS {
        let mut r = preflight();
        r.headers_mut().insert(
            header::ACCESS_CONTROL_ALLOW_METHODS,
            HeaderValue::from_static("GET, HEAD, OPTIONS"),
        );
        r.headers_mut().insert(
            header::ACCESS_CONTROL_EXPOSE_HEADERS,
            HeaderValue::from_static("content-length, content-range, accept-ranges, etag"),
        );
        return r;
    }
    let head = method == Method::HEAD;
    if method != Method::GET && !head {
        let mut r = error_response(&WireError::new(
            Code::MethodNotAllowed,
            format!("{method} is not served at {path}; use GET or HEAD"),
        ));
        r.headers_mut().insert(
            header::ALLOW,
            HeaderValue::from_static("GET, HEAD, OPTIONS"),
        );
        return r;
    }
    let segs: Vec<&str> = path["/v1/files".len()..]
        .split('/')
        .filter(|s| !s.is_empty())
        .collect();
    let mut r = match (route, segs.as_slice()) {
        ("/v1/files/", _) => crate::files::listing_response(&cfg.files, None),
        ("/v1/files/{region}/", [region]) => {
            crate::files::listing_response(&cfg.files, Some(&percent_decode(region)))
        }
        (_, [region, set, file]) => crate::files::file_response(
            &cfg.files,
            (
                &percent_decode(region),
                &percent_decode(set),
                &percent_decode(file),
            ),
            head,
            headers,
            cfg.cache_max_age,
        ),
        _ => error_response(&WireError::new(
            Code::NoRoute,
            format!("no endpoint at {path}"),
        )),
    };
    if head && route != "/v1/files/{region}/{set}/{file}" {
        // A listing's HEAD: its headers, no body.
        let len = http_body::Body::size_hint(r.body()).exact();
        *r.body_mut() = full(Bytes::new());
        if let Some(n) = len {
            r.headers_mut()
                .insert(header::CONTENT_LENGTH, HeaderValue::from(n));
        }
    }
    r
}

/// `204` to a CORS preflight, allowing any request header for ten minutes.
fn preflight() -> Response<Body> {
    let mut r = response(204, "text/plain", full(Bytes::new()));
    r.headers_mut().remove(header::CONTENT_TYPE);
    let h = r.headers_mut();
    h.insert(
        header::ACCESS_CONTROL_ALLOW_METHODS,
        HeaderValue::from_static("GET, OPTIONS"),
    );
    h.insert(
        header::ACCESS_CONTROL_ALLOW_HEADERS,
        HeaderValue::from_static("*"),
    );
    h.insert(
        header::ACCESS_CONTROL_MAX_AGE,
        HeaderValue::from_static("600"),
    );
    r
}

/// What a cacheable reply is tagged with: its tag and its `max-age`.
struct Tagged {
    tag: String,
    max_age: Option<u32>,
}

impl Tagged {
    /// The tag of the reply to `query` on `region`, from the region's `data_version`;
    /// `None` when the region is not served (the reply is then a refusal) or the source
    /// cannot list its regions.
    async fn of_region<S: MapSource>(
        source: &Arc<S>,
        build: &str,
        region: &str,
        query: String,
        max_age: Option<u32>,
    ) -> Option<Self> {
        let s = source.clone();
        let regions = tokio::task::spawn_blocking(move || s.regions())
            .await
            .ok()?
            .ok()?;
        let r = regions.iter().find(|r| r.name == region)?;
        Some(Self {
            tag: cache::tag_for(build, &r.data_version, &query),
            max_age,
        })
    }

    /// `304 Not Modified` when `if_none_match` names this reply.
    fn not_modified(&self, if_none_match: Option<&str>) -> Option<Response<Body>> {
        let sent = cache::matching(if_none_match?, &self.tag)?;
        let mut r = response(304, "text/plain", full(Bytes::new()));
        r.headers_mut().remove(header::CONTENT_TYPE);
        let etag = if sent == "*" {
            cache::etag(&self.tag, None)
        } else {
            sent.trim_start_matches("W/").to_string()
        };
        Some(self.headers(with_encoding(r, None), &etag))
    }

    /// `ETag` and `Cache-Control` on a `200` (a refusal is not tagged).
    fn apply(this: Option<&Self>, r: Response<Body>) -> Response<Body> {
        match this {
            Some(t) if r.status() == StatusCode::OK => t.on(r),
            _ => r,
        }
    }

    fn on(&self, r: Response<Body>) -> Response<Body> {
        let coding = r
            .headers()
            .get(header::CONTENT_ENCODING)
            .and_then(|v| v.to_str().ok())
            .map(str::to_string);
        let etag = cache::etag(&self.tag, coding.as_deref());
        self.headers(r, &etag)
    }

    fn headers(&self, mut r: Response<Body>, etag: &str) -> Response<Body> {
        let h = r.headers_mut();
        if let Ok(v) = HeaderValue::from_str(etag) {
            h.insert(header::ETAG, v);
        }
        if let Some(s) = self.max_age
            && let Ok(v) = HeaderValue::from_str(&format!("public, max-age={s}"))
        {
            h.insert(header::CACHE_CONTROL, v);
        }
        r
    }
}

async fn route<S: MapSource>(
    source: Arc<S>,
    cfg: &Arc<ServerConfig>,
    method: &Method,
    uri: &http::Uri,
    accept: Option<ContentEncoding>,
    if_none_match: Option<&str>,
) -> Response<Body> {
    let path = uri.path();
    let Some(route) = route_of(path) else {
        return error_response(&WireError::new(
            Code::NoRoute,
            format!("no endpoint at {path}"),
        ));
    };
    if method == Method::OPTIONS {
        return preflight();
    }
    if method != Method::GET {
        return error_response(&WireError::new(
            Code::MethodNotAllowed,
            format!("{method} is not served at {path}; use GET"),
        ));
    }
    match route {
        "/" | "/v1/" => {
            let mut r = response(
                200,
                "text/html; charset=utf-8",
                full(crate::landing::page(
                    cfg,
                    &crate::files::landing_section(&cfg.files),
                )),
            );
            r.headers_mut().insert(
                header::CACHE_CONTROL,
                HeaderValue::from_static("public, max-age=300"),
            );
            r
        }
        "/openapi.json" => match serde_json::to_vec_pretty(&crate::openapi::document()) {
            Ok(j) => response(200, "application/json", full(j)),
            Err(e) => error_response(&WireError::new(
                Code::EncodeFailed,
                format!("openapi json: {e}"),
            )),
        },
        "/v1/health" => response(200, "text/plain", full("ok")),
        "/v1/regions" => {
            let s = source.clone();
            let tagged = match tokio::task::spawn_blocking(move || s.regions()).await {
                Ok(Ok(regions)) => Some(Tagged {
                    tag: cache::regions_tag(&cfg.build_id, &regions),
                    max_age: cfg.regions_max_age,
                }),
                _ => None,
            };
            if let Some(r) = tagged.as_ref().and_then(|t| t.not_modified(if_none_match)) {
                return r;
            }
            let r = json_answer(source, "regions", accept, |s| s.regions()).await;
            Tagged::apply(tagged.as_ref(), r)
        }
        "/v1/geocode" => match geocode_query_from(uri.query()) {
            Err(e) => error_response(&e),
            Ok(q) => {
                let key = format!("geocode\0{}\0{}\0{}", q.region, q.q, q.limit());
                let tagged =
                    Tagged::of_region(&source, &cfg.build_id, &q.region, key, cfg.cache_max_age)
                        .await;
                if let Some(r) = tagged.as_ref().and_then(|t| t.not_modified(if_none_match)) {
                    return r;
                }
                let t0 = Instant::now();
                let line = format!("region={} q={:?} max={}", q.region, q.q, q.limit());
                let r = json_answer(source, "geocode", accept, move |s| s.geocode(&q)).await;
                log_lookup(cfg, "geocode", &line, &r, t0);
                Tagged::apply(tagged.as_ref(), r)
            }
        },
        "/v1/revgeocode" => match revgeocode_query_from(uri.query()) {
            Err(e) => error_response(&e),
            Ok(q) => {
                let key = format!("revgeocode\0{}\0{}\0{}", q.region, q.lon, q.lat);
                let tagged =
                    Tagged::of_region(&source, &cfg.build_id, &q.region, key, cfg.cache_max_age)
                        .await;
                if let Some(r) = tagged.as_ref().and_then(|t| t.not_modified(if_none_match)) {
                    return r;
                }
                let t0 = Instant::now();
                let line = format!("region={} lon={} lat={}", q.region, q.lon, q.lat);
                let r = json_answer(source, "revgeocode", accept, move |s| s.revgeocode(&q)).await;
                log_lookup(cfg, "revgeocode", &line, &r, t0);
                Tagged::apply(tagged.as_ref(), r)
            }
        },
        _ => {
            let kind = &path["/v1/map/".len()..];
            let (q, compress) = match map_query_from(kind, uri.query(), cfg) {
                Ok(v) => v,
                Err(e) => return error_response(&e),
            };
            let b = q.bbox.to_array();
            let key = format!(
                "map\0{}\0{}\0{},{},{},{}\0{}\0{:?}\0{:?}",
                q.kind, q.region, b[0], b[1], b[2], b[3], q.lod, q.max, compress
            );
            let tagged =
                Tagged::of_region(&source, &cfg.build_id, &q.region, key, cfg.cache_max_age).await;
            if let Some(r) = tagged.as_ref().and_then(|t| t.not_modified(if_none_match)) {
                return r;
            }
            match map_reply(source, cfg, q, compress, accept).await {
                Ok(r) => Tagged::apply(tagged.as_ref(), r),
                Err(e) => error_response(&e),
            }
        }
    }
}

/// A source answer on the blocking pool, as a JSON `200` (encoded as `accept` allows,
/// when it is at least [`MIN_SIZE`] bytes) or the refusal.
async fn json_answer<S, T, F>(
    source: Arc<S>,
    what: &'static str,
    accept: Option<ContentEncoding>,
    f: F,
) -> Response<Body>
where
    S: MapSource,
    T: serde::Serialize + Send + 'static,
    F: FnOnce(&S) -> Result<T, WireError> + Send + 'static,
{
    let answer = tokio::task::spawn_blocking(move || {
        f(&source).and_then(|v| {
            let j = serde_json::to_vec(&v)
                .map_err(|e| WireError::new(Code::EncodeFailed, format!("{what} json: {e}")))?;
            match accept.filter(|_| j.len() >= MIN_SIZE) {
                None => Ok((j, None)),
                Some(c) => c.encode_all(&j).map(|z| (z, Some(c))).map_err(|e| {
                    WireError::new(Code::EncodeFailed, format!("{what} {}: {e}", c.token()))
                }),
            }
        })
    })
    .await;
    match answer {
        Ok(Ok((body, enc))) => with_encoding(response(200, "application/json", full(body)), enc),
        Ok(Err(e)) => error_response(&e),
        Err(e) => error_response(&WireError::new(
            Code::SourceFailed,
            format!("{what} task: {e}"),
        )),
    }
}

/// One stderr line per answered address lookup, when the server logs.
fn log_lookup(cfg: &ServerConfig, what: &str, line: &str, r: &Response<Body>, t0: Instant) {
    if cfg.log {
        eprintln!(
            "korp-map-wire: http {what} {line} status={} total_ms={:.1}",
            r.status().as_u16(),
            t0.elapsed().as_secs_f64() * 1e3
        );
    }
}

/// **One map reply, whole**: it waits for a work slot ([`ServerConfig::work_slots`],
/// holding no thread), then runs the query, encodes the IPC stream and applies the
/// content coding (when the reply is at least [`MIN_SIZE`] bytes) on one blocking
/// thread, and goes out with a `Content-Length`. A slow client holds its bytes, never a
/// thread or a slot, and the computing replies never outnumber the cores.
async fn map_reply<S: MapSource>(
    source: Arc<S>,
    cfg: &Arc<ServerConfig>,
    q: MapQuery,
    compress: Compression,
    accept: Option<ContentEncoding>,
) -> Result<Response<Body>, WireError> {
    let t0 = Instant::now();
    let slot = cfg
        .work_slots
        .clone()
        .acquire_owned()
        .await
        .map_err(|_| WireError::new(Code::SourceFailed, "the server is stopping"))?;
    let wait_ms = t0.elapsed().as_secs_f64() * 1e3;
    // A reply with IPC compression inside is not compressed again.
    let want = accept.filter(|_| compress == Compression::None);
    let log = cfg.log;
    let (body, enc) = tokio::task::spawn_blocking(move || {
        let _slot = slot;
        let t1 = Instant::now();
        let reply = source.query(&q)?;
        let plan_ms = t1.elapsed().as_secs_f64() * 1e3;
        let (schema, meta, batches) = reply.into_parts();
        let (mut w, mut ipc) = IpcChunks::begin(&schema, compress)?;
        let (mut rows, mut nb) = (0usize, 0usize);
        for b in batches {
            let b = b?;
            rows += b.num_rows();
            nb += 1;
            ipc.extend(w.batch(&b)?);
        }
        ipc.extend(w.finish()?);
        let bytes = ipc.len();
        let (body, enc) = match want.filter(|_| bytes >= MIN_SIZE) {
            Some(c) => (
                c.encode_all(&ipc).map_err(|e| {
                    WireError::new(Code::EncodeFailed, format!("map reply {}: {e}", c.token()))
                })?,
                Some(c),
            ),
            None => (ipc, None),
        };
        if log {
            eprintln!(
                "korp-map-wire: http {} region={} bbox={:?} lod={} max={:?} compress={:?} rows={rows} batches={nb} \
                 bytes={bytes} encoding={} sent={} truncated={} rg={}/{} wait_ms={wait_ms:.1} plan_ms={plan_ms:.1} total_ms={:.1}",
                q.kind,
                q.region,
                q.bbox.to_array(),
                q.lod,
                q.max,
                compress,
                enc.map_or("none", ContentEncoding::token),
                body.len(),
                meta.truncated,
                meta.row_groups_scanned,
                meta.row_groups_total,
                t0.elapsed().as_secs_f64() * 1e3
            );
        }
        Ok::<_, WireError>((body, enc))
    })
    .await
    .map_err(|e| WireError::new(Code::SourceFailed, format!("query task: {e}")))??;
    Ok(with_encoding(response(200, CONTENT_TYPE, full(body)), enc))
}

#[cfg(test)]
mod tests {
    use super::*;

    #[test]
    fn every_route_is_in_the_openapi_description_and_nothing_else_is() {
        let doc = crate::openapi::document();
        let paths: Vec<&str> = doc["paths"]
            .as_object()
            .unwrap()
            .keys()
            .map(String::as_str)
            .collect();
        for r in ROUTES {
            assert!(paths.contains(r), "{r} is served but not described");
        }
        for p in &paths {
            assert!(ROUTES.contains(p), "{p} is described but not served");
        }
        assert_eq!(doc["openapi"], "3.1.0");
    }

    #[test]
    fn every_route_template_is_what_its_paths_resolve_to() {
        for r in ROUTES {
            let concrete = r
                .replace("{kind}", "lines")
                .replace("{region}", "sweden")
                .replace("{set}", "geoparquet2")
                .replace("{file}", "areas.parquet");
            assert_eq!(route_of(&concrete), Some(*r), "{concrete}");
        }
        assert_eq!(route_of("/v1"), Some("/v1/"));
        assert_eq!(route_of("/v1/nothing"), None);
        assert_eq!(route_of("/index.html"), None);
        assert_eq!(route_of("/v1/health/"), None);
        assert_eq!(route_of("/v1/files"), Some("/v1/files/"));
        assert_eq!(route_of("/v1/files/sweden"), Some("/v1/files/{region}/"));
        assert_eq!(route_of("/v1/filesx"), None);
        assert_eq!(route_of("/v1/files/sweden/native"), None);
        assert_eq!(route_of("/v1/files/a/b/c/d"), None);
        assert_eq!(route_of("/v1/files/a//c"), None);
    }

    #[test]
    fn query_strings_decode_percent_escapes_and_plus() {
        let p = parse_query(Some("bbox=1%2C2%2C3%2C4&region=a+b&x"));
        assert_eq!(p["bbox"], "1,2,3,4");
        assert_eq!(p["region"], "a b");
        assert_eq!(p["x"], "");
        assert_eq!(percent_decode("%zz%4"), "%zz%4");
    }
}