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

//! **The wire's errors**: every refusal has a `korp-map-<n>` code, an HTTP status, a JSON
//! body `{"error": "...", "code": "korp-map-<n>"}` and a gRPC status for the Flight door.
//!
//! The numbers start at 100 so they cannot collide with korp's registered `korp-map-1`
//! … `korp-map-51` (`.nornir/korp-error-codes.md`).

use std::fmt;

/// One row per refusal the wire can give.
#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
pub enum Code {
    /// No such endpoint.
    NoRoute,
    /// The endpoint exists, the method does not.
    MethodNotAllowed,
    /// `{kind}` is not `points`, `lines` or `areas`.
    UnknownKind,
    /// A required query parameter is missing.
    MissingParam,
    /// `bbox` is not four finite numbers `minlon,minlat,maxlon,maxlat` in range, min ≤ max.
    BadBbox,
    /// `lod` is not an integer in `0..=30`.
    BadLod,
    /// `max` is not a positive integer.
    BadMax,
    /// `compress` is not `zstd` or `none`.
    BadCompress,
    /// The region is not served here.
    UnknownRegion,
    /// A Flight ticket is not the query JSON.
    BadTicket,
    /// The source could not read its data.
    SourceFailed,
    /// The reply could not be encoded as Arrow IPC.
    EncodeFailed,
    /// The Flight method is not part of the contract.
    Unimplemented,
    /// A client's own: the map server did not answer at all (down, wrong address,
    /// connection dropped).
    Unreachable,
    /// A client's own: the server answered with something that is not the wire (not an
    /// Arrow IPC stream, no map-wire metadata, a refusal body that is not one).
    BadReply,
    /// `lon` or `lat` of a reverse geocode is not a finite number in range.
    BadLonLat,
    /// The region's cut has no address index (or the source serves none), so it cannot
    /// geocode.
    NoAddressIndex,
    /// `/v1/files/…` names a region, set or file the server does not serve.
    NoFile,
    /// A `Range` request on a file asks for no byte inside it.
    RangeNotSatisfiable,
    /// A served file changed on disk since the server started.
    FileChanged,
}

impl Code {
    /// Every code, in number order.
    pub const ALL: [Code; 20] = [
        Code::NoRoute,
        Code::MethodNotAllowed,
        Code::UnknownKind,
        Code::MissingParam,
        Code::BadBbox,
        Code::BadLod,
        Code::BadMax,
        Code::BadCompress,
        Code::UnknownRegion,
        Code::BadTicket,
        Code::SourceFailed,
        Code::EncodeFailed,
        Code::Unimplemented,
        Code::Unreachable,
        Code::BadReply,
        Code::BadLonLat,
        Code::NoAddressIndex,
        Code::NoFile,
        Code::RangeNotSatisfiable,
        Code::FileChanged,
    ];

    /// The `n` in `korp-map-<n>`.
    #[must_use]
    pub const fn number(self) -> u32 {
        match self {
            Code::NoRoute => 100,
            Code::MethodNotAllowed => 101,
            Code::UnknownKind => 102,
            Code::MissingParam => 103,
            Code::BadBbox => 104,
            Code::BadLod => 105,
            Code::BadMax => 106,
            Code::BadCompress => 107,
            Code::UnknownRegion => 108,
            Code::BadTicket => 109,
            Code::SourceFailed => 110,
            Code::EncodeFailed => 111,
            Code::Unimplemented => 112,
            Code::Unreachable => 113,
            Code::BadReply => 114,
            Code::BadLonLat => 115,
            Code::NoAddressIndex => 116,
            Code::NoFile => 124,
            Code::RangeNotSatisfiable => 125,
            Code::FileChanged => 126,
        }
    }

    /// One sentence on what the code means (the row's message in korp-map's error-code
    /// table, held equal by its tests).
    #[must_use]
    pub const fn summary(self) -> &'static str {
        match self {
            Code::NoRoute => "no such endpoint on the map wire",
            Code::MethodNotAllowed => "the map wire endpoint exists, the method does not",
            Code::UnknownKind => "the requested kind is not points, lines or areas",
            Code::MissingParam => "a required query parameter is missing",
            Code::BadBbox => {
                "bbox is not four finite numbers minlon,minlat,maxlon,maxlat in range, min <= max"
            }
            Code::BadLod => "lod is not an integer in 0..=30",
            Code::BadMax => "max is not a positive integer",
            Code::BadCompress => "compress is not zstd or none",
            Code::UnknownRegion => "the region is not served here",
            Code::BadTicket => "a Flight ticket is not the query JSON",
            Code::SourceFailed => "the map source could not read its data",
            Code::EncodeFailed => "the reply could not be encoded as Arrow IPC",
            Code::Unimplemented => "the Flight method is not part of the map wire contract",
            Code::Unreachable => {
                "a client's own: the map server did not answer at all (down, wrong address, connection dropped)"
            }
            Code::BadReply => {
                "a client's own: the map server answered with something that is not the map wire"
            }
            Code::BadLonLat => "lon or lat of a reverse geocode is not a finite number in range",
            Code::NoAddressIndex => {
                "the region's cut has no address index (pipeline step `address` has not run on it), so it cannot geocode"
            }
            Code::NoFile => "no such region, set or file is served under /v1/files",
            Code::RangeNotSatisfiable => {
                "a Range request on a served file asks for no byte inside it"
            }
            Code::FileChanged => {
                "a served file changed on disk since the server started, so its listed size and sha256 no longer hold"
            }
        }
    }

    /// The code whose tag is `tag` (`korp-map-<n>`).
    #[must_use]
    pub fn from_tag(tag: &str) -> Option<Self> {
        Self::ALL.into_iter().find(|c| c.tag() == tag)
    }

    /// `korp-map-<n>`.
    #[must_use]
    pub fn tag(self) -> String {
        format!("korp-map-{}", self.number())
    }

    /// The HTTP status this code answers with.
    #[must_use]
    pub const fn http_status(self) -> u16 {
        match self {
            Code::NoRoute | Code::UnknownRegion | Code::NoAddressIndex | Code::NoFile => 404,
            Code::RangeNotSatisfiable => 416,
            Code::FileChanged => 503,
            Code::MethodNotAllowed => 405,
            Code::UnknownKind
            | Code::MissingParam
            | Code::BadBbox
            | Code::BadLod
            | Code::BadMax
            | Code::BadCompress
            | Code::BadTicket
            | Code::BadLonLat => 400,
            Code::SourceFailed | Code::EncodeFailed => 500,
            Code::Unimplemented => 501,
            Code::Unreachable | Code::BadReply => 502,
        }
    }

    /// The gRPC status code the Flight door answers with.
    #[must_use]
    pub const fn grpc_code(self) -> tonic::Code {
        match self {
            Code::NoRoute | Code::UnknownRegion | Code::NoAddressIndex | Code::NoFile => {
                tonic::Code::NotFound
            }
            Code::RangeNotSatisfiable => tonic::Code::OutOfRange,
            Code::FileChanged => tonic::Code::Unavailable,
            Code::MethodNotAllowed | Code::Unimplemented => tonic::Code::Unimplemented,
            Code::UnknownKind
            | Code::MissingParam
            | Code::BadBbox
            | Code::BadLod
            | Code::BadMax
            | Code::BadCompress
            | Code::BadTicket
            | Code::BadLonLat => tonic::Code::InvalidArgument,
            Code::SourceFailed | Code::EncodeFailed => tonic::Code::Internal,
            Code::Unreachable => tonic::Code::Unavailable,
            Code::BadReply => tonic::Code::DataLoss,
        }
    }
}

/// A refusal: its code and a sentence for a person.
#[derive(Clone, Debug, PartialEq, Eq)]
pub struct WireError {
    /// Which refusal.
    pub code: Code,
    /// What was wrong, for a person.
    pub message: String,
}

impl WireError {
    /// A refusal with this code and message.
    pub fn new(code: Code, message: impl Into<String>) -> Self {
        Self {
            code,
            message: message.into(),
        }
    }

    /// The message a client is sent: every filesystem path in [`Self::message`] cut to
    /// its last component (`/srv/cut/address.parquet` → `address.parquet`), so a refusal
    /// never shows where the server keeps its files. Wire paths (`/v1/…`) stay.
    #[must_use]
    pub fn public_message(&self) -> std::borrow::Cow<'_, str> {
        scrub_paths(&self.message)
    }

    /// The JSON body: `{"error": "...", "code": "korp-map-<n>"}`, with
    /// [`Self::public_message`]. A message that held a path is written whole to the
    /// server's log (stderr) instead.
    #[must_use]
    pub fn to_json(&self) -> String {
        let public = self.public_message();
        if public != self.message {
            eprintln!(
                "korp-map-wire: refusal {}: {}",
                self.code.tag(),
                self.message
            );
        }
        serde_json::json!({ "error": public, "code": self.code.tag() }).to_string()
    }

    /// A refusal body read back (a client's view of [`Self::to_json`]); `None` when `body`
    /// is not one or names a code this wire does not have.
    #[must_use]
    pub fn from_json(body: &[u8]) -> Option<Self> {
        let v: serde_json::Value = serde_json::from_slice(body).ok()?;
        let code = Code::from_tag(v.get("code")?.as_str()?)?;
        let message = v.get("error")?.as_str()?.to_string();
        Some(Self { code, message })
    }

    /// The Flight door's status; its message is the same JSON body the HTTP door sends.
    #[must_use]
    pub fn to_status(&self) -> tonic::Status {
        tonic::Status::new(self.code.grpc_code(), self.to_json())
    }
}

/// `s` with every filesystem path cut to its last component. A path is a run that starts
/// with `/` at the start of a word (after a space, a quote, a bracket, `=`, `:` or `,`),
/// holds at least two `/`, and is not a wire path (`/v1/…`, `/.well-known/…`).
fn scrub_paths(s: &str) -> std::borrow::Cow<'_, str> {
    const OPEN: &[char] = &['"', '\'', '(', '[', '{', '=', ':', ',', '`', '<'];
    const CLOSE: &[char] = &['"', '\'', ')', ']', '}', ',', ';', '`', '>'];
    let starts = |i: usize| {
        s[i..].starts_with('/')
            && s[..i]
                .chars()
                .next_back()
                .is_none_or(|c| c.is_whitespace() || OPEN.contains(&c))
    };
    if !(0..s.len()).any(|i| s.is_char_boundary(i) && starts(i)) {
        return std::borrow::Cow::Borrowed(s);
    }
    let mut out = String::with_capacity(s.len());
    let mut i = 0;
    while i < s.len() {
        if s.is_char_boundary(i) && starts(i) {
            let rest = &s[i..];
            let end = rest
                .find(|c: char| c.is_whitespace() || CLOSE.contains(&c))
                .unwrap_or(rest.len());
            // A sentence's own `:` or `.` after the path is not part of it.
            let run = rest[..end].trim_end_matches([':', '.']);
            let is_path = run.matches('/').count() >= 2
                && !run.starts_with("/v1/")
                && !run.starts_with("/.well-known/");
            if is_path {
                let last = run.rsplit('/').find(|p| !p.is_empty()).unwrap_or("");
                out.push_str(if last.is_empty() { "(a path)" } else { last });
                i += run.len();
                continue;
            }
            out.push_str(run);
            i += run.len().max(1);
            continue;
        }
        let c = s[i..].chars().next().expect("in bounds");
        out.push(c);
        i += c.len_utf8();
    }
    std::borrow::Cow::Owned(out)
}

impl fmt::Display for WireError {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        write!(f, "{}: {}", self.code.tag(), self.message)
    }
}

impl std::error::Error for WireError {}

impl From<WireError> for tonic::Status {
    fn from(e: WireError) -> Self {
        e.to_status()
    }
}

/// **The HTTPS door's setup failures**, `korp-map-117` … `korp-map-123`: what stops the
/// TLS listener from starting, and what a certificate order from Let's Encrypt can fail
/// with. They are never a reply to a request, so they have no HTTP or gRPC status; the
/// server prints them and exits (setup), or prints them and retries (an ACME order).
#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
pub enum TlsCode {
    /// The certificate PEM file could not be read or holds no certificate.
    CertFile,
    /// The private key PEM file could not be read or holds no private key.
    KeyFile,
    /// The certificate and the key do not go together, or the key type is not supported.
    CertKey,
    /// The TLS flags do not make one setup (a missing or a conflicting flag, a bad
    /// domain name or contact address).
    Flags,
    /// The ACME cache directory could not be created, written or read.
    AcmeCache,
    /// The HTTPS listener could not bind its address.
    Bind,
    /// A certificate order from the ACME server failed; it is retried with backoff.
    AcmeOrder,
}

impl TlsCode {
    /// Every code, in number order.
    pub const ALL: [TlsCode; 7] = [
        TlsCode::CertFile,
        TlsCode::KeyFile,
        TlsCode::CertKey,
        TlsCode::Flags,
        TlsCode::AcmeCache,
        TlsCode::Bind,
        TlsCode::AcmeOrder,
    ];

    /// The `n` in `korp-map-<n>`; the numbers follow [`Code`]'s.
    #[must_use]
    pub const fn number(self) -> u32 {
        match self {
            TlsCode::CertFile => 117,
            TlsCode::KeyFile => 118,
            TlsCode::CertKey => 119,
            TlsCode::Flags => 120,
            TlsCode::AcmeCache => 121,
            TlsCode::Bind => 122,
            TlsCode::AcmeOrder => 123,
        }
    }

    /// One sentence on what the code means (the row's message in korp-map's error-code
    /// table, held equal by its tests).
    #[must_use]
    pub const fn summary(self) -> &'static str {
        match self {
            TlsCode::CertFile => {
                "the TLS certificate PEM file could not be read or holds no certificate"
            }
            TlsCode::KeyFile => {
                "the TLS private key PEM file could not be read or holds no private key"
            }
            TlsCode::CertKey => {
                "the TLS certificate and key do not go together, or the key type is not supported"
            }
            TlsCode::Flags => {
                "the TLS flags do not make one setup (a missing or conflicting flag, a bad domain name or contact address)"
            }
            TlsCode::AcmeCache => "the ACME cache directory could not be created, written or read",
            TlsCode::Bind => "the HTTPS listener could not bind its address",
            TlsCode::AcmeOrder => {
                "a certificate order from the ACME server (Let's Encrypt) failed; it is retried with backoff"
            }
        }
    }

    /// `korp-map-<n>`.
    #[must_use]
    pub fn tag(self) -> String {
        format!("korp-map-{}", self.number())
    }
}

/// A TLS setup failure: its code and a sentence for a person.
#[derive(Clone, Debug, PartialEq, Eq)]
pub struct TlsError {
    /// Which failure.
    pub code: TlsCode,
    /// What went wrong, for a person.
    pub message: String,
}

impl TlsError {
    /// A failure with this code and message.
    pub fn new(code: TlsCode, message: impl Into<String>) -> Self {
        Self {
            code,
            message: message.into(),
        }
    }
}

impl fmt::Display for TlsError {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        write!(f, "{}: {}", self.code.tag(), self.message)
    }
}

impl std::error::Error for TlsError {}

#[cfg(test)]
mod scrub_tests {
    use super::scrub_paths;

    #[test]
    fn paths_are_cut_to_their_last_component_and_wire_paths_stay() {
        for (got, want) in [
            (
                "region \"x\": /home/a/lanes/cut5/address.parquet does not exist",
                "region \"x\": address.parquet does not exist",
            ),
            (
                "open \"/srv/cut/areas.parquet\": gone",
                "open \"areas.parquet\": gone",
            ),
            (
                "/srv/cut/areas.parquet: bad page",
                "areas.parquet: bad page",
            ),
            ("(from /srv/cut/)", "(from cut)"),
            ("dir=/data/x/y, next", "dir=y, next"),
            (
                "ask /v1/map/lines?res=4 instead",
                "ask /v1/map/lines?res=4 instead",
            ),
            (
                "see /.well-known/acme-challenge/x",
                "see /.well-known/acme-challenge/x",
            ),
            ("a / b and 1/2/3 and km/h", "a / b and 1/2/3 and km/h"),
            ("/tmp only", "/tmp only"),
            ("ö /home/å/ä.parquet ü", "ö ä.parquet ü"),
            ("", ""),
        ] {
            assert_eq!(scrub_paths(got), want, "{got}");
        }
    }
}