rmv-core 1.0.0

Configuration, retries, stop resolution and connection status for the RMV API
Documentation
//! The errors, each with a stable [`Error::status`] for scripts and agents.
//!
//! No error carries the access key: the errors of [`hafas`] have no URL,
//! and texts of the API that echo the key come redacted.

use crate::model::{ErrorBody, StopMatch};

/// How long to wait after a rate limit without `Retry-After`.
const DEFAULT_RETRY_AFTER_SECONDS: u64 = 60;

#[derive(Debug, thiserror::Error)]
pub enum Error {
    /// No access key is configured, so no request is sent.
    #[error(
        "no access key configured: every request to the RMV API needs one. \
         Set it with `rmv config set access_id <key>` or RMV_ACCESS_ID"
    )]
    AccessIdMissing,
    /// The server rejected the access key.
    #[error("the RMV API rejected the access key: {message}")]
    AccessDenied { message: String },
    /// The name fits several stops.
    #[error("{query:?} does not name one stop, pass the ID of one of the {} candidates", candidates.len())]
    AmbiguousStop {
        query: String,
        candidates: Vec<StopMatch>,
    },
    #[error("no stop matches {query:?}")]
    StopNotFound { query: String },
    /// The quota of the access key is used up, or too many requests came at
    /// once.
    #[error("too many requests: {message}, try again in {retry_after_seconds} s")]
    RateLimited {
        message: String,
        retry_after_seconds: u64,
    },
    /// The server cannot be reached or has a problem.
    #[error("the RMV API is unavailable: {message}")]
    Unavailable { message: String },
    #[error("the RMV API did not answer in time")]
    Timeout,
    /// The server rejected the request.
    #[error("bad request: {message}")]
    BadRequest { message: String },
    /// The server does not know the stop or journey.
    #[error("not found: {message}")]
    NotFound { message: String },
    /// The server answered something unexpected.
    #[error("unexpected answer from the RMV API: {message}")]
    Upstream { message: String },
    #[error(transparent)]
    Config(#[from] crate::config::Error),
}

impl Error {
    /// A stable name of the kind of error, like `ambiguous_stop`.
    pub fn status(&self) -> &'static str {
        match self {
            Self::AccessIdMissing => "access_id_missing",
            Self::AccessDenied { .. } => "access_denied",
            Self::Config(_) => "config_error",
            Self::AmbiguousStop { .. } => "ambiguous_stop",
            Self::StopNotFound { .. } => "stop_not_found",
            Self::RateLimited { .. } => "rate_limited",
            Self::Unavailable { .. } => "unavailable",
            Self::Timeout => "timeout",
            Self::BadRequest { .. } => "bad_request",
            Self::NotFound { .. } => "not_found",
            Self::Upstream { .. } => "upstream_error",
        }
    }

    /// When to try again, in seconds.
    pub fn retry_after_seconds(&self) -> Option<u64> {
        match self {
            Self::RateLimited {
                retry_after_seconds,
                ..
            } => Some(*retry_after_seconds),
            _ => None,
        }
    }

    /// The error as output.
    pub fn body(&self) -> ErrorBody {
        ErrorBody {
            error: self.to_string(),
            status: self.status().to_owned(),
            retry_after_seconds: self.retry_after_seconds(),
            candidates: match self {
                Self::AmbiguousStop { candidates, .. } => candidates.clone(),
                _ => Vec::new(),
            },
        }
    }
}

/// What a HAFAS error code means for the caller.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
enum Kind {
    AccessDenied,
    RateLimited,
    BadRequest,
    NotFound,
    Unavailable,
}

/// The meaning of a HAFAS error code, if it is a known one.
fn kind_of_code(code: &str) -> Option<Kind> {
    Some(match code {
        "API_AUTH" => Kind::AccessDenied,
        "API_QUOTA" | "API_TOO_MANY_REQUESTS" => Kind::RateLimited,
        "API_PARAM"
        | "API_FORMAT"
        | "SVC_PARAM"
        | "SVC_DATATIME"
        | "SVC_DATATIME_PERIOD"
        | "SVC_PROD"
        | "SVC_CTX"
        | "SVC_LOC_EQUAL"
        | "SVC_LOC_NEAR" => Kind::BadRequest,
        "SVC_LOC" | "SVC_LOC_ARR" | "SVC_LOC_DEP" | "SVC_LOC_VIA" | "SVC_NO_RESULT"
        | "SVC_NO_MATCH" => Kind::NotFound,
        "SVC_FAILED_SEARCH" => Kind::Unavailable,
        code if code.starts_with("INT_") => Kind::Unavailable,
        _ => return None,
    })
}

/// The meaning of an HTTP status, if it has one.
fn kind_of_status(status: u16) -> Option<Kind> {
    Some(match status {
        401 | 403 => Kind::AccessDenied,
        429 => Kind::RateLimited,
        400 | 422 => Kind::BadRequest,
        404 => Kind::NotFound,
        500.. => Kind::Unavailable,
        _ => return None,
    })
}

/// Whether the server reported that nothing matches: no connection, no
/// departure, no stop. The operations answer that with an empty list.
pub(crate) fn is_no_result(error: &hafas::Error) -> bool {
    matches!(error.code(), Some("SVC_NO_RESULT" | "SVC_NO_MATCH"))
}

impl From<hafas::Error> for Error {
    fn from(error: hafas::Error) -> Self {
        let kind = error
            .code()
            .and_then(kind_of_code)
            .or_else(|| error.status().and_then(kind_of_status));
        let message = || match &error {
            hafas::Error::Status {
                status, message, ..
            } => format!("{status}: {message}"),
            hafas::Error::Api { code, text, .. } if text.is_empty() => code.clone(),
            hafas::Error::Api { code, text, .. } => format!("{code}: {text}"),
            error => chain(error),
        };
        match (kind, &error) {
            (_, hafas::Error::AccessIdMissing) => Self::AccessIdMissing,
            (_, hafas::Error::Timeout(_)) => Self::Timeout,
            (_, hafas::Error::BaseUrl(_)) => Self::Config(crate::config::Error::InvalidValue {
                key: "base_url".to_owned(),
                reason: error.to_string(),
            }),
            (_, hafas::Error::Http(_) | hafas::Error::Client(_)) => Self::Unavailable {
                message: chain(&error),
            },
            (Some(Kind::AccessDenied), _) => Self::AccessDenied { message: message() },
            (Some(Kind::RateLimited), _) => Self::RateLimited {
                message: message(),
                retry_after_seconds: error
                    .retry_after()
                    .map_or(DEFAULT_RETRY_AFTER_SECONDS, |wait| wait.as_secs().max(1)),
            },
            (Some(Kind::BadRequest), _) => Self::BadRequest { message: message() },
            (Some(Kind::NotFound), _) => Self::NotFound { message: message() },
            (Some(Kind::Unavailable), _) => Self::Unavailable { message: message() },
            (None, _) => Self::Upstream { message: message() },
        }
    }
}

/// The message of an error and its sources.
fn chain(error: &dyn std::error::Error) -> String {
    let mut text = error.to_string();
    let mut source = error.source();
    while let Some(cause) = source {
        text.push_str(": ");
        text.push_str(&cause.to_string());
        source = cause.source();
    }
    text
}

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

    fn api(code: &str, status: Option<u16>) -> Error {
        hafas::Error::Api {
            status,
            code: code.to_owned(),
            text: "text".to_owned(),
            retry_after: None,
        }
        .into()
    }

    fn status(status: u16, retry_after: Option<Duration>) -> Error {
        hafas::Error::Status {
            status,
            message: "text".into(),
            retry_after,
        }
        .into()
    }

    #[test]
    fn maps_the_codes_of_hafas() {
        let cases = [
            ("API_AUTH", "access_denied"),
            ("API_QUOTA", "rate_limited"),
            ("API_TOO_MANY_REQUESTS", "rate_limited"),
            ("API_PARAM", "bad_request"),
            ("SVC_DATATIME", "bad_request"),
            ("SVC_CTX", "bad_request"),
            ("SVC_LOC_EQUAL", "bad_request"),
            ("SVC_LOC", "not_found"),
            ("SVC_LOC_DEP", "not_found"),
            ("SVC_NO_RESULT", "not_found"),
            ("SVC_NO_MATCH", "not_found"),
            ("SVC_FAILED_SEARCH", "unavailable"),
            ("INT_TIMEOUT", "unavailable"),
            ("INT_HAFAS_CONNECTION_ERROR", "unavailable"),
        ];
        for (code, expected) in cases {
            assert_eq!(api(code, Some(400)).status(), expected, "{code}");
        }
        let error = api("API_QUOTA", Some(400));
        assert_eq!(error.retry_after_seconds(), Some(60));
        assert_eq!(
            error.to_string(),
            "too many requests: API_QUOTA: text, try again in 60 s"
        );
    }

    #[test]
    fn an_unknown_code_falls_back_to_the_status() {
        assert_eq!(api("NEW_CODE", Some(403)).status(), "access_denied");
        assert_eq!(api("NEW_CODE", Some(503)).status(), "unavailable");
        assert_eq!(api("NEW_CODE", None).status(), "upstream_error");
        let empty = Error::from(hafas::Error::Api {
            status: None,
            code: "NEW_CODE".to_owned(),
            text: String::new(),
            retry_after: None,
        });
        assert_eq!(
            empty.to_string(),
            "unexpected answer from the RMV API: NEW_CODE"
        );
    }

    #[test]
    fn maps_the_statuses_of_the_server() {
        let error = status(429, Some(Duration::from_secs(7)));
        assert_eq!(error.status(), "rate_limited");
        assert_eq!(error.retry_after_seconds(), Some(7));
        assert_eq!(status(429, None).retry_after_seconds(), Some(60));
        assert_eq!(
            status(429, Some(Duration::ZERO)).retry_after_seconds(),
            Some(1)
        );
        assert_eq!(status(401, None).status(), "access_denied");
        assert_eq!(status(400, None).status(), "bad_request");
        assert_eq!(status(422, None).status(), "bad_request");
        assert_eq!(status(404, None).status(), "not_found");
        let error = status(503, None);
        assert_eq!(error.status(), "unavailable");
        assert_eq!(error.to_string(), "the RMV API is unavailable: 503: text");
        assert_eq!(status(418, None).status(), "upstream_error");
    }

    #[test]
    fn maps_other_client_errors() {
        let error = Error::from(hafas::Error::Decode("bad".into()));
        assert_eq!(error.status(), "upstream_error");
        assert_eq!(
            error.to_string(),
            "unexpected answer from the RMV API: unexpected response: bad"
        );
        let error = Error::from(hafas::Error::BaseUrl("x".into()));
        assert_eq!(error.status(), "config_error");
        assert_eq!(error.retry_after_seconds(), None);
        let error = Error::from(hafas::Error::AccessIdMissing);
        assert_eq!(error.status(), "access_id_missing");
    }

    #[test]
    fn tells_no_result_apart() {
        let no_result = |code: &str| hafas::Error::Api {
            status: Some(400),
            code: code.to_owned(),
            text: String::new(),
            retry_after: None,
        };
        assert!(is_no_result(&no_result("SVC_NO_RESULT")));
        assert!(is_no_result(&no_result("SVC_NO_MATCH")));
        assert!(!is_no_result(&no_result("SVC_LOC")));
        assert!(!is_no_result(&hafas::Error::AccessIdMissing));
    }

    #[test]
    fn names_every_status() {
        let errors = [
            Error::AccessIdMissing,
            Error::StopNotFound { query: "x".into() },
            Error::Timeout,
            Error::Upstream {
                message: "x".into(),
            },
        ];
        let statuses: Vec<&str> = errors.iter().map(Error::status).collect();
        assert_eq!(
            statuses,
            [
                "access_id_missing",
                "stop_not_found",
                "timeout",
                "upstream_error"
            ]
        );
    }

    #[test]
    fn the_body_lists_the_candidates() {
        let candidate = StopMatch {
            id: "1".into(),
            name: "Bahnhof".into(),
            area: None,
            dhid: None,
            lat: 0.0,
            lon: 0.0,
            modes: Vec::new(),
        };
        let body = Error::AmbiguousStop {
            query: "Bahnhof".into(),
            candidates: vec![candidate.clone()],
        }
        .body();
        assert_eq!(body.status, "ambiguous_stop");
        assert_eq!(
            body.error,
            "\"Bahnhof\" does not name one stop, pass the ID of one of the 1 candidates"
        );
        assert_eq!(body.candidates, [candidate]);
        assert_eq!(Error::Timeout.body().candidates, Vec::<StopMatch>::new());
    }
}