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

//! **The address lookups** (contract v1.2): a free-text address to ranked places, and a
//! lon/lat to the nearest address. Both answer small results, so both are JSON.
//!
//! * `GET /v1/geocode?region=R&q=…[&max=K]` → [`GeocodeReply`]
//! * `GET /v1/revgeocode?region=R&lon=…&lat=…` → [`RevGeocodeReply`]
//!
//! The lookup itself belongs to the source ([`crate::MapSource::geocode`] and
//! [`crate::MapSource::revgeocode`]); korp-map's store answers from the region cut's
//! `address.parquet`. A source without an address index refuses with
//! [`Code::NoAddressIndex`].

use serde::{Deserialize, Serialize};

use crate::error::{Code, WireError};
use crate::http::{parse_query, required};

/// The hits a geocode without `max` gets.
pub const DEFAULT_GEOCODE_MAX: u64 = 10;
/// The most hits one geocode may ask for.
pub const MAX_GEOCODE_MAX: u64 = 1000;

/// One address, as both lookups answer it.
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
pub struct GeocodeHit {
    /// `addr:street`.
    pub street: String,
    /// `addr:housenumber`.
    pub housenumber: String,
    /// `addr:city` (may be empty).
    pub city: String,
    /// `addr:postcode` (may be empty).
    pub postcode: String,
    /// Where the address is, WGS-84.
    pub lon: f64,
    /// Where the address is, WGS-84.
    pub lat: f64,
    /// The OSM id of the node or way the address came from.
    pub source: i64,
    /// The rank a geocode gave it (higher is better); `0` from a reverse lookup.
    pub score: u32,
}

/// One geocode: `q` searched in `region`'s addresses.
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
pub struct GeocodeQuery {
    /// The region.
    pub region: String,
    /// The address text, e.g. `storgatan 5 uppsala`.
    pub q: String,
    /// At most this many hits; `None` takes [`DEFAULT_GEOCODE_MAX`].
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub max: Option<u64>,
}

impl GeocodeQuery {
    /// The hit cap this query asks for.
    #[must_use]
    pub fn limit(&self) -> u64 {
        self.max.unwrap_or(DEFAULT_GEOCODE_MAX)
    }

    /// Check what a type cannot hold: a non-blank `q`, `max` in `1..=1000`.
    pub fn validate(&self) -> Result<(), WireError> {
        if self.q.trim().is_empty() {
            return Err(WireError::new(
                Code::MissingParam,
                "query parameter \"q\" is missing",
            ));
        }
        match self.max {
            Some(0) => Err(WireError::new(Code::BadMax, "max must be at least 1")),
            Some(m) if m > MAX_GEOCODE_MAX => Err(WireError::new(
                Code::BadMax,
                format!("max {m} is above {MAX_GEOCODE_MAX} for a geocode"),
            )),
            _ => Ok(()),
        }
    }
}

/// What a geocode answers: the ranked hits, best first, and the size of the index they
/// came from (a fixture and a country are told apart by it).
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
pub struct GeocodeReply {
    /// The region asked.
    pub region: String,
    /// The text asked.
    pub query: String,
    /// Addresses in the region's index.
    pub indexed: u64,
    /// Best first; empty when nothing matches.
    pub hits: Vec<GeocodeHit>,
}

/// One reverse geocode: the address nearest `lon`, `lat` in `region`.
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
pub struct RevGeocodeQuery {
    /// The region.
    pub region: String,
    /// WGS-84 longitude, `-180..=180`.
    pub lon: f64,
    /// WGS-84 latitude, `-90..=90`.
    pub lat: f64,
}

impl RevGeocodeQuery {
    /// Check the point: finite, in range.
    pub fn validate(&self) -> Result<(), WireError> {
        if !self.lon.is_finite() || !(-180.0..=180.0).contains(&self.lon) {
            return Err(WireError::new(
                Code::BadLonLat,
                format!("lon {} is not a number in -180..=180", self.lon),
            ));
        }
        if !self.lat.is_finite() || !(-90.0..=90.0).contains(&self.lat) {
            return Err(WireError::new(
                Code::BadLonLat,
                format!("lat {} is not a number in -90..=90", self.lat),
            ));
        }
        Ok(())
    }
}

/// What a reverse geocode answers: the nearest address and how far it is.
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
pub struct RevGeocodeReply {
    /// The region asked.
    pub region: String,
    /// The point asked.
    pub lon: f64,
    /// The point asked.
    pub lat: f64,
    /// Addresses in the region's index.
    pub indexed: u64,
    /// The nearest address; `None` only when the index is empty.
    pub hit: Option<GeocodeHit>,
    /// Metres from the point to `hit` (`0` without one).
    pub distance_m: f64,
}

/// The geocode a `/v1/geocode` query string asks.
pub fn geocode_query_from(query: Option<&str>) -> Result<GeocodeQuery, WireError> {
    let p = parse_query(query);
    let region = required(&p, "region")?.to_string();
    let q = required(&p, "q")?.to_string();
    let max = match p.get("max") {
        None => None,
        Some(m) => Some(m.parse::<u64>().map_err(|_| {
            WireError::new(Code::BadMax, format!("max {m:?} is not a positive integer"))
        })?),
    };
    let g = GeocodeQuery { region, q, max };
    g.validate()?;
    Ok(g)
}

/// The reverse geocode a `/v1/revgeocode` query string asks.
pub fn revgeocode_query_from(query: Option<&str>) -> Result<RevGeocodeQuery, WireError> {
    let p = parse_query(query);
    let region = required(&p, "region")?.to_string();
    let num = |name: &str| -> Result<f64, WireError> {
        let s = required(&p, name)?;
        s.trim()
            .parse::<f64>()
            .map_err(|_| WireError::new(Code::BadLonLat, format!("{name} {s:?} is not a number")))
    };
    let r = RevGeocodeQuery {
        region,
        lon: num("lon")?,
        lat: num("lat")?,
    };
    r.validate()?;
    Ok(r)
}

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

    #[test]
    fn a_geocode_query_string_reads_region_text_and_max() {
        let g = geocode_query_from(Some("region=sweden&q=storgatan+5%20uppsala&max=3")).unwrap();
        assert_eq!(g.region, "sweden");
        assert_eq!(g.q, "storgatan 5 uppsala");
        assert_eq!(g.limit(), 3);
        let g = geocode_query_from(Some("region=sweden&q=storgatan")).unwrap();
        assert_eq!(g.limit(), DEFAULT_GEOCODE_MAX);
    }

    #[test]
    fn a_blank_text_or_a_max_out_of_range_is_refused() {
        let e = geocode_query_from(Some("region=sweden&q=+++")).unwrap_err();
        assert_eq!(e.code, Code::MissingParam);
        for m in ["0", "1001", "x"] {
            let e = geocode_query_from(Some(&format!("region=sweden&q=a&max={m}"))).unwrap_err();
            assert_eq!(e.code, Code::BadMax, "max={m}");
        }
    }

    #[test]
    fn a_reverse_query_needs_a_point_in_range() {
        let r = revgeocode_query_from(Some("region=sweden&lon=18.07&lat=59.33")).unwrap();
        assert_eq!((r.lon, r.lat), (18.07, 59.33));
        for q in [
            "lon=181&lat=0",
            "lon=0&lat=-91",
            "lon=nan&lat=0",
            "lon=a&lat=0",
        ] {
            let e = revgeocode_query_from(Some(&format!("region=r&{q}"))).unwrap_err();
            assert_eq!(e.code, Code::BadLonLat, "{q}");
        }
        let e = revgeocode_query_from(Some("region=r&lon=1")).unwrap_err();
        assert_eq!(e.code, Code::MissingParam);
    }
}