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

//! **The client side of the map wire** (feature `client`): one trait, [`MapClient`], and
//! the doors a reader can take to a map server.
//!
//! * [`HttpMapClient`] — `GET /v1/regions` and `GET /v1/map/{kind}` (Arrow IPC stream),
//!   `GET /v1/geocode` and `GET /v1/revgeocode` (JSON).
//! * [`FlightMapClient`] — Flight `ListFlights` and `DoGet` (ticket = the query JSON); the
//!   address lookups are JSON on the HTTP door of the same port.
//! * [`SourceClient`] — no wire at all: a [`MapSource`] in this process, asked exactly as
//!   the server asks it (the query checked, the server's default `max` applied).
//! * [`FakeMapClient`] — canned regions and replies for a caller's tests; it records what
//!   it was asked.
//!
//! The doors ask the same queries and give the same answers: a [`ClientReply`] carries
//! the reply schema (its metadata included), what the reply says about itself
//! ([`ReplyMeta`]) and the record batches, and a refusal is the server's own
//! [`WireError`] — the HTTP door reads it from the JSON body, the Flight door from the
//! status message, which is the same JSON. Two codes are the client's own:
//! [`Code::Unreachable`] (no answer from the server at all) and [`Code::BadReply`] (an
//! answer that is not the wire).
//!
//! **Native exports only.** A map server serves the GeoParquet 1.1 native exports a
//! region cut writes (`<table>.point|multilinestring|multipolygon.parquet`). A region cut
//! before the native export existed is not served and is not read by any client: it is
//! re-cut, not converted.

use std::collections::HashMap;
use std::io::Cursor;
use std::sync::{Arc, Mutex};

use arrow_array::RecordBatch;
use arrow_flight::decode::FlightRecordBatchStream;
use arrow_flight::flight_service_client::FlightServiceClient;
use arrow_flight::{Criteria, Ticket};
use arrow_ipc::reader::StreamReader;
use arrow_schema::{Schema, SchemaRef};
use bytes::Bytes;
use futures::TryStreamExt;
use http_body_util::{BodyExt, Empty};
use hyper_util::client::legacy::Client;
use hyper_util::client::legacy::connect::HttpConnector;
use hyper_util::rt::TokioExecutor;

use crate::error::{Code, WireError};
use crate::geocode::{GeocodeQuery, GeocodeReply, RevGeocodeQuery, RevGeocodeReply};
use crate::server::ServerConfig;
use crate::source::{MapQuery, MapSource, Region, ReplyMeta};

/// One answered map query, as a client holds it.
#[derive(Clone, Debug, PartialEq)]
pub struct ClientReply {
    /// The reply schema, metadata included (the GeoParquet `geo` key and [`ReplyMeta`]'s).
    pub schema: SchemaRef,
    /// What the reply says about itself.
    pub meta: ReplyMeta,
    /// The rows.
    pub batches: Vec<RecordBatch>,
}

impl ClientReply {
    /// A reply from its schema and batches; the meta is read from the schema metadata.
    pub fn from_parts(schema: SchemaRef, batches: Vec<RecordBatch>) -> Result<Self, WireError> {
        let meta = ReplyMeta::from_metadata(schema.metadata()).ok_or_else(|| {
            WireError::new(
                Code::BadReply,
                "the reply schema carries no map-wire metadata (data_version, truncated, …)",
            )
        })?;
        Ok(Self {
            schema,
            meta,
            batches,
        })
    }

    /// Rows across all batches.
    #[must_use]
    pub fn num_rows(&self) -> usize {
        self.batches.iter().map(RecordBatch::num_rows).sum()
    }
}

/// **A reader of a map server.** Every door answers the same five questions.
#[async_trait::async_trait]
pub trait MapClient: Send + Sync {
    /// Is the server there and answering?
    async fn health(&self) -> Result<(), WireError>;
    /// The regions it serves.
    async fn regions(&self) -> Result<Vec<Region>, WireError>;
    /// One map query.
    async fn query(&self, q: &MapQuery) -> Result<ClientReply, WireError>;
    /// One geocode: an address text to ranked addresses.
    async fn geocode(&self, q: &GeocodeQuery) -> Result<GeocodeReply, WireError>;
    /// One reverse geocode: a point to the nearest address.
    async fn revgeocode(&self, q: &RevGeocodeQuery) -> Result<RevGeocodeReply, WireError>;
}

#[async_trait::async_trait]
impl<T: MapClient + ?Sized> MapClient for Arc<T> {
    async fn health(&self) -> Result<(), WireError> {
        (**self).health().await
    }
    async fn regions(&self) -> Result<Vec<Region>, WireError> {
        (**self).regions().await
    }
    async fn query(&self, q: &MapQuery) -> Result<ClientReply, WireError> {
        (**self).query(q).await
    }
    async fn geocode(&self, q: &GeocodeQuery) -> Result<GeocodeReply, WireError> {
        (**self).geocode(q).await
    }
    async fn revgeocode(&self, q: &RevGeocodeQuery) -> Result<RevGeocodeReply, WireError> {
        (**self).revgeocode(q).await
    }
}

fn unreachable(base: &str, e: impl std::fmt::Display) -> WireError {
    WireError::new(
        Code::Unreachable,
        format!("map server {base} did not answer: {e}"),
    )
}

fn bad_reply(what: impl std::fmt::Display) -> WireError {
    WireError::new(
        Code::BadReply,
        format!("the map server's reply is not the wire: {what}"),
    )
}

/// A refusal body (`{"error": "...", "code": "korp-map-<n>"}`) as the server's error;
/// anything else is [`Code::BadReply`] naming what came back.
fn refusal(body: &[u8], status: impl std::fmt::Display) -> WireError {
    WireError::from_json(body).unwrap_or_else(|| {
        let text = String::from_utf8_lossy(&body[..body.len().min(200)]).into_owned();
        bad_reply(format!(
            "{status} with a body that is not a map-wire refusal: {text:?}"
        ))
    })
}

/// `minlon,minlat,maxlon,maxlat` and the rest of a `/v1/map/{kind}` query string.
fn query_string(q: &MapQuery) -> String {
    let b = q.bbox.to_array();
    let mut s = format!(
        "region={}&bbox={},{},{},{}&lod={}",
        percent_encode(&q.region),
        b[0],
        b[1],
        b[2],
        b[3],
        q.lod
    );
    if let Some(m) = q.max {
        s.push_str(&format!("&max={m}"));
    }
    s
}

/// The `/v1/geocode` path and query string.
fn geocode_path(q: &GeocodeQuery) -> String {
    let mut s = format!(
        "/v1/geocode?region={}&q={}",
        percent_encode(&q.region),
        percent_encode(&q.q)
    );
    if let Some(m) = q.max {
        s.push_str(&format!("&max={m}"));
    }
    s
}

/// The `/v1/revgeocode` path and query string.
fn revgeocode_path(q: &RevGeocodeQuery) -> String {
    format!(
        "/v1/revgeocode?region={}&lon={}&lat={}",
        percent_encode(&q.region),
        q.lon,
        q.lat
    )
}

/// Percent-encode everything but the unreserved characters.
fn percent_encode(s: &str) -> String {
    let mut out = String::with_capacity(s.len());
    for b in s.bytes() {
        if b.is_ascii_alphanumeric() || matches!(b, b'-' | b'_' | b'.' | b'~') {
            out.push(b as char);
        } else {
            out.push_str(&format!("%{b:02X}"));
        }
    }
    out
}

/// The connector under [`HttpMapClient`]: plain TCP, and with feature `client-tls`
/// https too (rustls on ring).
#[cfg(not(feature = "client-tls"))]
type Connector = HttpConnector;
#[cfg(feature = "client-tls")]
type Connector = hyper_rustls::HttpsConnector<HttpConnector>;

/// **The HTTP Arrow IPC door.** `base` is the server's root, e.g. `http://maps:8790`, or
/// with feature `client-tls` `https://maps.example.org:8443`.
pub struct HttpMapClient {
    base: String,
    http: Client<Connector, Empty<Bytes>>,
}

impl HttpMapClient {
    /// A client of the server at `base` (`http://host:port`, or `https://…` with feature
    /// `client-tls`, trusting the webpki roots; a trailing `/` is dropped).
    #[must_use]
    pub fn new(base: impl Into<String>) -> Self {
        #[cfg(not(feature = "client-tls"))]
        let http = Client::builder(TokioExecutor::new()).build_http();
        #[cfg(feature = "client-tls")]
        let http = Client::builder(TokioExecutor::new()).build(
            hyper_rustls::HttpsConnectorBuilder::new()
                .with_tls_config(crate::tls::webpki_client_config())
                .https_or_http()
                .enable_http1()
                .build(),
        );
        Self::with_client(base, http)
    }

    /// A client of the server at `base` whose https connections use `tls` (e.g.
    /// [`crate::tls::client_config_trusting`] for a self-signed server).
    #[cfg(feature = "client-tls")]
    #[must_use]
    pub fn with_tls(base: impl Into<String>, tls: rustls::ClientConfig) -> Self {
        let http = Client::builder(TokioExecutor::new()).build(
            hyper_rustls::HttpsConnectorBuilder::new()
                .with_tls_config(tls)
                .https_or_http()
                .enable_http1()
                .build(),
        );
        Self::with_client(base, http)
    }

    fn with_client(base: impl Into<String>, http: Client<Connector, Empty<Bytes>>) -> Self {
        Self {
            base: base.into().trim_end_matches('/').to_string(),
            http,
        }
    }

    /// The server's root.
    #[must_use]
    pub fn base(&self) -> &str {
        &self.base
    }

    async fn get(&self, path_and_query: &str) -> Result<Bytes, WireError> {
        #[cfg(not(feature = "client-tls"))]
        if self.base.starts_with("https:") {
            return Err(unreachable(
                &self.base,
                "this build has no https client (korp-map-wire feature `client-tls`)",
            ));
        }
        let url = format!("{}{path_and_query}", self.base);
        let req = http::Request::get(&url)
            .body(Empty::new())
            .map_err(|e| WireError::new(Code::BadReply, format!("request {url}: {e}")))?;
        let res = self
            .http
            .request(req)
            .await
            .map_err(|e| unreachable(&self.base, e))?;
        let status = res.status();
        let body = res
            .into_body()
            .collect()
            .await
            .map_err(|e| unreachable(&self.base, e))?
            .to_bytes();
        if status.is_success() {
            Ok(body)
        } else {
            Err(refusal(&body, format!("HTTP {status}")))
        }
    }
}

#[async_trait::async_trait]
impl MapClient for HttpMapClient {
    async fn health(&self) -> Result<(), WireError> {
        self.get("/v1/health").await.map(|_| ())
    }

    async fn regions(&self) -> Result<Vec<Region>, WireError> {
        let body = self.get("/v1/regions").await?;
        serde_json::from_slice(&body).map_err(|e| bad_reply(format!("regions JSON: {e}")))
    }

    async fn query(&self, q: &MapQuery) -> Result<ClientReply, WireError> {
        let body = self
            .get(&format!("/v1/map/{}?{}", q.kind, query_string(q)))
            .await?;
        let reader = StreamReader::try_new(Cursor::new(body), None)
            .map_err(|e| bad_reply(format!("Arrow IPC stream: {e}")))?;
        let schema = reader.schema();
        let batches = reader
            .collect::<Result<Vec<_>, _>>()
            .map_err(|e| bad_reply(format!("Arrow IPC batch: {e}")))?;
        ClientReply::from_parts(schema, batches)
    }

    async fn geocode(&self, q: &GeocodeQuery) -> Result<GeocodeReply, WireError> {
        let body = self.get(&geocode_path(q)).await?;
        serde_json::from_slice(&body).map_err(|e| bad_reply(format!("geocode JSON: {e}")))
    }

    async fn revgeocode(&self, q: &RevGeocodeQuery) -> Result<RevGeocodeReply, WireError> {
        let body = self.get(&revgeocode_path(q)).await?;
        serde_json::from_slice(&body).map_err(|e| bad_reply(format!("revgeocode JSON: {e}")))
    }
}

/// **The Arrow Flight door.** `base` is the same root the HTTP door answers on.
pub struct FlightMapClient {
    base: String,
    channel: tonic::transport::Channel,
    /// The address lookups: JSON on the HTTP door, which the same port serves.
    http: HttpMapClient,
}

impl FlightMapClient {
    /// A client of the server at `base` (`http://host:port`). The connection is made on
    /// first use, so a server that is down is an [`Code::Unreachable`] answer to a query,
    /// not a failure here.
    ///
    /// An `https://` base needs feature `client-tls`; the server is then checked against
    /// the webpki roots.
    pub fn new(base: impl Into<String>) -> Result<Self, WireError> {
        let base = base.into().trim_end_matches('/').to_string();
        let endpoint = Self::endpoint(&base)?;
        #[cfg(feature = "client-tls")]
        let endpoint = if base.starts_with("https:") {
            endpoint
                .tls_config(tonic::transport::ClientTlsConfig::new().with_webpki_roots())
                .map_err(|e| Self::bad_address(&base, e))?
        } else {
            endpoint
        };
        let http = HttpMapClient::new(base.clone());
        Ok(Self {
            channel: endpoint.connect_lazy(),
            base,
            http,
        })
    }

    /// A client of the `https://` server at `base` that trusts the certificates in
    /// `roots_pem` (a self-signed server's own certificate, or a private CA).
    #[cfg(feature = "client-tls")]
    pub fn with_tls_roots(base: impl Into<String>, roots_pem: &[u8]) -> Result<Self, WireError> {
        let base = base.into().trim_end_matches('/').to_string();
        let endpoint = Self::endpoint(&base)?
            .tls_config(
                tonic::transport::ClientTlsConfig::new()
                    .ca_certificate(tonic::transport::Certificate::from_pem(roots_pem)),
            )
            .map_err(|e| Self::bad_address(&base, e))?;
        let tls = crate::tls::client_config_trusting(roots_pem)
            .map_err(|e| WireError::new(Code::BadReply, e.to_string()))?;
        let http = HttpMapClient::with_tls(base.clone(), tls);
        Ok(Self {
            channel: endpoint.connect_lazy(),
            base,
            http,
        })
    }

    fn bad_address(base: &str, e: impl std::fmt::Display) -> WireError {
        WireError::new(Code::BadReply, format!("map server address {base:?}: {e}"))
    }

    fn endpoint(base: &str) -> Result<tonic::transport::Endpoint, WireError> {
        tonic::transport::Endpoint::from_shared(base.to_string())
            .map_err(|e| Self::bad_address(base, e))
    }

    fn client(&self) -> FlightServiceClient<tonic::transport::Channel> {
        FlightServiceClient::new(self.channel.clone()).max_decoding_message_size(usize::MAX)
    }

    /// A Flight status as the wire's error: the server's refusal JSON when the message is
    /// one, otherwise "no answer" for a transport failure and "not the wire" for the rest.
    fn status(&self, st: &tonic::Status) -> WireError {
        if let Some(e) = WireError::from_json(st.message().as_bytes()) {
            return e;
        }
        match st.code() {
            tonic::Code::Unavailable | tonic::Code::DeadlineExceeded | tonic::Code::Cancelled => {
                unreachable(&self.base, st.message())
            }
            c => bad_reply(format!("Flight status {c:?}: {}", st.message())),
        }
    }
}

#[async_trait::async_trait]
impl MapClient for FlightMapClient {
    async fn health(&self) -> Result<(), WireError> {
        self.regions().await.map(|_| ())
    }

    async fn regions(&self) -> Result<Vec<Region>, WireError> {
        let mut c = self.client();
        let mut infos = c
            .list_flights(Criteria::default())
            .await
            .map_err(|st| self.status(&st))?
            .into_inner();
        let mut out = Vec::new();
        while let Some(info) = infos.try_next().await.map_err(|st| self.status(&st))? {
            out.push(
                serde_json::from_slice::<Region>(&info.app_metadata)
                    .map_err(|e| bad_reply(format!("region JSON in a FlightInfo: {e}")))?,
            );
        }
        Ok(out)
    }

    async fn query(&self, q: &MapQuery) -> Result<ClientReply, WireError> {
        let ticket = serde_json::to_vec(q)
            .map_err(|e| WireError::new(Code::BadTicket, format!("query JSON: {e}")))?;
        let mut c = self.client();
        let data = c
            .do_get(Ticket {
                ticket: ticket.into(),
            })
            .await
            .map_err(|st| self.status(&st))?
            .into_inner();
        let mut stream = FlightRecordBatchStream::new_from_flight_data(data.map_err(Into::into));
        let mut batches = Vec::new();
        loop {
            match stream.try_next().await {
                Ok(Some(b)) => batches.push(b),
                Ok(None) => break,
                Err(arrow_flight::error::FlightError::Tonic(st)) => return Err(self.status(&st)),
                Err(e) => return Err(bad_reply(format!("Flight data: {e}"))),
            }
        }
        let schema = stream
            .schema()
            .cloned()
            .ok_or_else(|| bad_reply("the Flight reply carried no schema"))?;
        ClientReply::from_parts(schema, batches)
    }

    async fn geocode(&self, q: &GeocodeQuery) -> Result<GeocodeReply, WireError> {
        self.http.geocode(q).await
    }

    async fn revgeocode(&self, q: &RevGeocodeQuery) -> Result<RevGeocodeReply, WireError> {
        self.http.revgeocode(q).await
    }
}

/// **A [`MapSource`] in this process, asked as a server asks it.** The query is checked
/// and `max` defaults exactly as both doors do ([`ServerConfig::default_max`]), so a
/// caller reading in-process gets the reply a remote reader of the same source gets.
pub struct SourceClient<S> {
    source: Arc<S>,
    cfg: ServerConfig,
}

impl<S: MapSource> SourceClient<S> {
    /// A client of `source`, with the server's default settings.
    #[must_use]
    pub fn new(source: Arc<S>) -> Self {
        Self::with_config(source, ServerConfig::default())
    }

    /// A client of `source` with `cfg`'s default `max`.
    #[must_use]
    pub fn with_config(source: Arc<S>, cfg: ServerConfig) -> Self {
        Self { source, cfg }
    }
}

#[async_trait::async_trait]
impl<S: MapSource> MapClient for SourceClient<S> {
    async fn health(&self) -> Result<(), WireError> {
        Ok(())
    }

    async fn regions(&self) -> Result<Vec<Region>, WireError> {
        let s = self.source.clone();
        tokio::task::spawn_blocking(move || s.regions())
            .await
            .map_err(|e| WireError::new(Code::SourceFailed, format!("regions task: {e}")))?
    }

    async fn query(&self, q: &MapQuery) -> Result<ClientReply, WireError> {
        let mut q = q.clone();
        if q.max.is_none() {
            q.max = self.cfg.default_max;
        }
        q.validate()?;
        let s = self.source.clone();
        tokio::task::spawn_blocking(move || {
            let (schema, _meta, batches) = s.query(&q)?.into_parts();
            let batches = batches.collect::<Result<Vec<_>, _>>()?;
            ClientReply::from_parts(schema, batches)
        })
        .await
        .map_err(|e| WireError::new(Code::SourceFailed, format!("query task: {e}")))?
    }

    async fn geocode(&self, q: &GeocodeQuery) -> Result<GeocodeReply, WireError> {
        q.validate()?;
        let (s, q) = (self.source.clone(), q.clone());
        tokio::task::spawn_blocking(move || s.geocode(&q))
            .await
            .map_err(|e| WireError::new(Code::SourceFailed, format!("geocode task: {e}")))?
    }

    async fn revgeocode(&self, q: &RevGeocodeQuery) -> Result<RevGeocodeReply, WireError> {
        q.validate()?;
        let (s, q) = (self.source.clone(), q.clone());
        tokio::task::spawn_blocking(move || s.revgeocode(&q))
            .await
            .map_err(|e| WireError::new(Code::SourceFailed, format!("revgeocode task: {e}")))?
    }
}

/// **A scripted map server for a caller's tests.** Regions, per-kind replies and the two
/// address answers are canned; [`Self::refusing`] makes every call answer one error;
/// every map query is recorded ([`Self::asked`]), every address lookup too
/// ([`Self::asked_addresses`]).
#[derive(Default)]
pub struct FakeMapClient {
    regions: Vec<Region>,
    replies: HashMap<crate::source::Kind, ClientReply>,
    geocode: Option<GeocodeReply>,
    revgeocode: Option<RevGeocodeReply>,
    refusal: Option<WireError>,
    asked: Mutex<Vec<MapQuery>>,
    asked_addresses: Mutex<Vec<String>>,
}

impl FakeMapClient {
    /// A fake serving `regions` and no rows.
    #[must_use]
    pub fn new(regions: Vec<Region>) -> Self {
        Self {
            regions,
            ..Self::default()
        }
    }

    /// Answer every query of `reply`'s kind with `reply`.
    #[must_use]
    pub fn with_reply(mut self, kind: crate::source::Kind, reply: ClientReply) -> Self {
        self.replies.insert(kind, reply);
        self
    }

    /// Answer every geocode with `reply` (its `region` and `query` become the asked ones).
    #[must_use]
    pub fn with_geocode(mut self, reply: GeocodeReply) -> Self {
        self.geocode = Some(reply);
        self
    }

    /// Answer every reverse geocode with `reply` (its point becomes the asked one).
    #[must_use]
    pub fn with_revgeocode(mut self, reply: RevGeocodeReply) -> Self {
        self.revgeocode = Some(reply);
        self
    }

    /// The address lookups asked so far, in order: the path and query string each would
    /// send (`/v1/geocode?…`, `/v1/revgeocode?…`).
    #[must_use]
    pub fn asked_addresses(&self) -> Vec<String> {
        self.asked_addresses
            .lock()
            .unwrap_or_else(|e| e.into_inner())
            .clone()
    }

    /// The refusal, or [`Code::UnknownRegion`] for a region it does not serve.
    fn serving(&self, region: &str) -> Result<(), WireError> {
        if let Some(e) = &self.refusal {
            return Err(e.clone());
        }
        if !self.regions.iter().any(|r| r.name == region) {
            return Err(WireError::new(
                Code::UnknownRegion,
                format!("region {region:?} is not served here"),
            ));
        }
        Ok(())
    }

    fn no_address_index(region: &str) -> WireError {
        WireError::new(
            Code::NoAddressIndex,
            format!("region {region:?}: the fake has no address answer"),
        )
    }

    /// Answer every call with `e`.
    #[must_use]
    pub fn refusing(mut self, e: WireError) -> Self {
        self.refusal = Some(e);
        self
    }

    /// The queries asked so far, in order.
    #[must_use]
    pub fn asked(&self) -> Vec<MapQuery> {
        self.asked.lock().unwrap_or_else(|e| e.into_inner()).clone()
    }

    fn empty_reply(&self) -> ClientReply {
        let meta = ReplyMeta {
            data_version: "fake".to_string(),
            truncated: false,
            row_groups_total: 0,
            row_groups_scanned: 0,
            status: "ok".to_string(),
            geometry_source: "full".to_string(),
        };
        let schema = Arc::new(Schema::empty().with_metadata(meta.to_metadata()));
        ClientReply {
            schema,
            meta,
            batches: Vec::new(),
        }
    }
}

#[async_trait::async_trait]
impl MapClient for FakeMapClient {
    async fn health(&self) -> Result<(), WireError> {
        self.refusal.clone().map_or(Ok(()), Err)
    }

    async fn regions(&self) -> Result<Vec<Region>, WireError> {
        match &self.refusal {
            Some(e) => Err(e.clone()),
            None => Ok(self.regions.clone()),
        }
    }

    async fn query(&self, q: &MapQuery) -> Result<ClientReply, WireError> {
        self.asked
            .lock()
            .unwrap_or_else(|e| e.into_inner())
            .push(q.clone());
        self.serving(&q.region)?;
        Ok(self
            .replies
            .get(&q.kind)
            .cloned()
            .unwrap_or_else(|| self.empty_reply()))
    }

    async fn geocode(&self, q: &GeocodeQuery) -> Result<GeocodeReply, WireError> {
        self.asked_addresses
            .lock()
            .unwrap_or_else(|e| e.into_inner())
            .push(geocode_path(q));
        q.validate()?;
        self.serving(&q.region)?;
        let mut r = self
            .geocode
            .clone()
            .ok_or_else(|| Self::no_address_index(&q.region))?;
        r.region.clone_from(&q.region);
        r.query.clone_from(&q.q);
        r.hits
            .truncate(usize::try_from(q.limit()).unwrap_or(usize::MAX));
        Ok(r)
    }

    async fn revgeocode(&self, q: &RevGeocodeQuery) -> Result<RevGeocodeReply, WireError> {
        self.asked_addresses
            .lock()
            .unwrap_or_else(|e| e.into_inner())
            .push(revgeocode_path(q));
        q.validate()?;
        self.serving(&q.region)?;
        let mut r = self
            .revgeocode
            .clone()
            .ok_or_else(|| Self::no_address_index(&q.region))?;
        r.region.clone_from(&q.region);
        (r.lon, r.lat) = (q.lon, q.lat);
        Ok(r)
    }
}

#[cfg(test)]
mod tests {
    use super::*;
    use crate::source::{BBox, Kind};

    #[test]
    fn the_query_string_names_every_field_the_door_reads() {
        let q = MapQuery {
            region: "sweden north".to_string(),
            bbox: BBox::new(11.0, 55.5, 14.25, 57.0).unwrap(),
            lod: 12,
            kind: Kind::Lines,
            max: Some(9),
        };
        assert_eq!(
            query_string(&q),
            "region=sweden%20north&bbox=11,55.5,14.25,57&lod=12&max=9"
        );
        let (back, _) =
            crate::http::map_query_from("lines", Some(&query_string(&q)), &ServerConfig::default())
                .unwrap();
        assert_eq!(back, q, "what the client writes is what the door reads");
    }

    #[test]
    fn the_address_paths_are_what_the_door_reads() {
        let g = GeocodeQuery {
            region: "sweden north".to_string(),
            q: "Storgatan 5, Umeå".to_string(),
            max: Some(3),
        };
        let p = geocode_path(&g);
        let (path, query) = p.split_once('?').unwrap();
        assert_eq!(path, "/v1/geocode");
        assert_eq!(crate::geocode::geocode_query_from(Some(query)).unwrap(), g);
        let r = RevGeocodeQuery {
            region: "sweden".to_string(),
            lon: 20.263_035,
            lat: 63.825_847,
        };
        let p = revgeocode_path(&r);
        let (path, query) = p.split_once('?').unwrap();
        assert_eq!(path, "/v1/revgeocode");
        assert_eq!(
            crate::geocode::revgeocode_query_from(Some(query)).unwrap(),
            r
        );
    }

    #[test]
    fn a_body_that_is_not_a_refusal_is_a_bad_reply_naming_it() {
        let e = refusal(b"<html>gateway</html>", "HTTP 502");
        assert_eq!(e.code, Code::BadReply);
        assert!(
            e.message.contains("HTTP 502") && e.message.contains("gateway"),
            "{e}"
        );
        let e = refusal(
            br#"{"error":"region \"x\" is not served here","code":"korp-map-108"}"#,
            "HTTP 404",
        );
        assert_eq!(e.code, Code::UnknownRegion);
    }
}