Skip to main content

rmv_core/
error.rs

1//! The errors, each with a stable [`Error::status`] for scripts and agents.
2//!
3//! No error carries the access key: the errors of [`hafas`] have no URL,
4//! and texts of the API that echo the key come redacted.
5
6use crate::model::{ErrorBody, StopMatch};
7
8/// How long to wait after a rate limit without `Retry-After`.
9const DEFAULT_RETRY_AFTER_SECONDS: u64 = 60;
10
11#[derive(Debug, thiserror::Error)]
12pub enum Error {
13    /// No access key is configured, so no request is sent.
14    #[error(
15        "no access key configured: every request to the RMV API needs one. \
16         Set it with `rmv config set access_id <key>` or RMV_ACCESS_ID"
17    )]
18    AccessIdMissing,
19    /// The server rejected the access key.
20    #[error("the RMV API rejected the access key: {message}")]
21    AccessDenied { message: String },
22    /// The name fits several stops.
23    #[error("{query:?} does not name one stop, pass the ID of one of the {} candidates", candidates.len())]
24    AmbiguousStop {
25        query: String,
26        candidates: Vec<StopMatch>,
27    },
28    #[error("no stop matches {query:?}")]
29    StopNotFound { query: String },
30    /// The quota of the access key is used up, or too many requests came at
31    /// once.
32    #[error("too many requests: {message}, try again in {retry_after_seconds} s")]
33    RateLimited {
34        message: String,
35        retry_after_seconds: u64,
36    },
37    /// The server cannot be reached or has a problem.
38    #[error("the RMV API is unavailable: {message}")]
39    Unavailable { message: String },
40    #[error("the RMV API did not answer in time")]
41    Timeout,
42    /// The server rejected the request.
43    #[error("bad request: {message}")]
44    BadRequest { message: String },
45    /// The server does not know the stop or journey.
46    #[error("not found: {message}")]
47    NotFound { message: String },
48    /// The server answered something unexpected.
49    #[error("unexpected answer from the RMV API: {message}")]
50    Upstream { message: String },
51    #[error(transparent)]
52    Config(#[from] crate::config::Error),
53}
54
55impl Error {
56    /// A stable name of the kind of error, like `ambiguous_stop`.
57    pub fn status(&self) -> &'static str {
58        match self {
59            Self::AccessIdMissing => "access_id_missing",
60            Self::AccessDenied { .. } => "access_denied",
61            Self::Config(_) => "config_error",
62            Self::AmbiguousStop { .. } => "ambiguous_stop",
63            Self::StopNotFound { .. } => "stop_not_found",
64            Self::RateLimited { .. } => "rate_limited",
65            Self::Unavailable { .. } => "unavailable",
66            Self::Timeout => "timeout",
67            Self::BadRequest { .. } => "bad_request",
68            Self::NotFound { .. } => "not_found",
69            Self::Upstream { .. } => "upstream_error",
70        }
71    }
72
73    /// When to try again, in seconds.
74    pub fn retry_after_seconds(&self) -> Option<u64> {
75        match self {
76            Self::RateLimited {
77                retry_after_seconds,
78                ..
79            } => Some(*retry_after_seconds),
80            _ => None,
81        }
82    }
83
84    /// The error as output.
85    pub fn body(&self) -> ErrorBody {
86        ErrorBody {
87            error: self.to_string(),
88            status: self.status().to_owned(),
89            retry_after_seconds: self.retry_after_seconds(),
90            candidates: match self {
91                Self::AmbiguousStop { candidates, .. } => candidates.clone(),
92                _ => Vec::new(),
93            },
94        }
95    }
96}
97
98/// What a HAFAS error code means for the caller.
99#[derive(Debug, Clone, Copy, PartialEq, Eq)]
100enum Kind {
101    AccessDenied,
102    RateLimited,
103    BadRequest,
104    NotFound,
105    Unavailable,
106}
107
108/// The meaning of a HAFAS error code, if it is a known one.
109fn kind_of_code(code: &str) -> Option<Kind> {
110    Some(match code {
111        "API_AUTH" => Kind::AccessDenied,
112        "API_QUOTA" | "API_TOO_MANY_REQUESTS" => Kind::RateLimited,
113        "API_PARAM"
114        | "API_FORMAT"
115        | "SVC_PARAM"
116        | "SVC_DATATIME"
117        | "SVC_DATATIME_PERIOD"
118        | "SVC_PROD"
119        | "SVC_CTX"
120        | "SVC_LOC_EQUAL"
121        | "SVC_LOC_NEAR" => Kind::BadRequest,
122        "SVC_LOC" | "SVC_LOC_ARR" | "SVC_LOC_DEP" | "SVC_LOC_VIA" | "SVC_NO_RESULT"
123        | "SVC_NO_MATCH" => Kind::NotFound,
124        "SVC_FAILED_SEARCH" => Kind::Unavailable,
125        code if code.starts_with("INT_") => Kind::Unavailable,
126        _ => return None,
127    })
128}
129
130/// The meaning of an HTTP status, if it has one.
131fn kind_of_status(status: u16) -> Option<Kind> {
132    Some(match status {
133        401 | 403 => Kind::AccessDenied,
134        429 => Kind::RateLimited,
135        400 | 422 => Kind::BadRequest,
136        404 => Kind::NotFound,
137        500.. => Kind::Unavailable,
138        _ => return None,
139    })
140}
141
142/// Whether the server reported that nothing matches: no connection, no
143/// departure, no stop. The operations answer that with an empty list.
144pub(crate) fn is_no_result(error: &hafas::Error) -> bool {
145    matches!(error.code(), Some("SVC_NO_RESULT" | "SVC_NO_MATCH"))
146}
147
148impl From<hafas::Error> for Error {
149    fn from(error: hafas::Error) -> Self {
150        let kind = error
151            .code()
152            .and_then(kind_of_code)
153            .or_else(|| error.status().and_then(kind_of_status));
154        let message = || match &error {
155            hafas::Error::Status {
156                status, message, ..
157            } => format!("{status}: {message}"),
158            hafas::Error::Api { code, text, .. } if text.is_empty() => code.clone(),
159            hafas::Error::Api { code, text, .. } => format!("{code}: {text}"),
160            error => chain(error),
161        };
162        match (kind, &error) {
163            (_, hafas::Error::AccessIdMissing) => Self::AccessIdMissing,
164            (_, hafas::Error::Timeout(_)) => Self::Timeout,
165            (_, hafas::Error::BaseUrl(_)) => Self::Config(crate::config::Error::InvalidValue {
166                key: "base_url".to_owned(),
167                reason: error.to_string(),
168            }),
169            (_, hafas::Error::Http(_) | hafas::Error::Client(_)) => Self::Unavailable {
170                message: chain(&error),
171            },
172            (Some(Kind::AccessDenied), _) => Self::AccessDenied { message: message() },
173            (Some(Kind::RateLimited), _) => Self::RateLimited {
174                message: message(),
175                retry_after_seconds: error
176                    .retry_after()
177                    .map_or(DEFAULT_RETRY_AFTER_SECONDS, |wait| wait.as_secs().max(1)),
178            },
179            (Some(Kind::BadRequest), _) => Self::BadRequest { message: message() },
180            (Some(Kind::NotFound), _) => Self::NotFound { message: message() },
181            (Some(Kind::Unavailable), _) => Self::Unavailable { message: message() },
182            (None, _) => Self::Upstream { message: message() },
183        }
184    }
185}
186
187/// The message of an error and its sources.
188fn chain(error: &dyn std::error::Error) -> String {
189    let mut text = error.to_string();
190    let mut source = error.source();
191    while let Some(cause) = source {
192        text.push_str(": ");
193        text.push_str(&cause.to_string());
194        source = cause.source();
195    }
196    text
197}
198
199#[cfg(test)]
200mod tests {
201    use super::*;
202    use std::time::Duration;
203
204    fn api(code: &str, status: Option<u16>) -> Error {
205        hafas::Error::Api {
206            status,
207            code: code.to_owned(),
208            text: "text".to_owned(),
209            retry_after: None,
210        }
211        .into()
212    }
213
214    fn status(status: u16, retry_after: Option<Duration>) -> Error {
215        hafas::Error::Status {
216            status,
217            message: "text".into(),
218            retry_after,
219        }
220        .into()
221    }
222
223    #[test]
224    fn maps_the_codes_of_hafas() {
225        let cases = [
226            ("API_AUTH", "access_denied"),
227            ("API_QUOTA", "rate_limited"),
228            ("API_TOO_MANY_REQUESTS", "rate_limited"),
229            ("API_PARAM", "bad_request"),
230            ("SVC_DATATIME", "bad_request"),
231            ("SVC_CTX", "bad_request"),
232            ("SVC_LOC_EQUAL", "bad_request"),
233            ("SVC_LOC", "not_found"),
234            ("SVC_LOC_DEP", "not_found"),
235            ("SVC_NO_RESULT", "not_found"),
236            ("SVC_NO_MATCH", "not_found"),
237            ("SVC_FAILED_SEARCH", "unavailable"),
238            ("INT_TIMEOUT", "unavailable"),
239            ("INT_HAFAS_CONNECTION_ERROR", "unavailable"),
240        ];
241        for (code, expected) in cases {
242            assert_eq!(api(code, Some(400)).status(), expected, "{code}");
243        }
244        let error = api("API_QUOTA", Some(400));
245        assert_eq!(error.retry_after_seconds(), Some(60));
246        assert_eq!(
247            error.to_string(),
248            "too many requests: API_QUOTA: text, try again in 60 s"
249        );
250    }
251
252    #[test]
253    fn an_unknown_code_falls_back_to_the_status() {
254        assert_eq!(api("NEW_CODE", Some(403)).status(), "access_denied");
255        assert_eq!(api("NEW_CODE", Some(503)).status(), "unavailable");
256        assert_eq!(api("NEW_CODE", None).status(), "upstream_error");
257        let empty = Error::from(hafas::Error::Api {
258            status: None,
259            code: "NEW_CODE".to_owned(),
260            text: String::new(),
261            retry_after: None,
262        });
263        assert_eq!(
264            empty.to_string(),
265            "unexpected answer from the RMV API: NEW_CODE"
266        );
267    }
268
269    #[test]
270    fn maps_the_statuses_of_the_server() {
271        let error = status(429, Some(Duration::from_secs(7)));
272        assert_eq!(error.status(), "rate_limited");
273        assert_eq!(error.retry_after_seconds(), Some(7));
274        assert_eq!(status(429, None).retry_after_seconds(), Some(60));
275        assert_eq!(
276            status(429, Some(Duration::ZERO)).retry_after_seconds(),
277            Some(1)
278        );
279        assert_eq!(status(401, None).status(), "access_denied");
280        assert_eq!(status(400, None).status(), "bad_request");
281        assert_eq!(status(422, None).status(), "bad_request");
282        assert_eq!(status(404, None).status(), "not_found");
283        let error = status(503, None);
284        assert_eq!(error.status(), "unavailable");
285        assert_eq!(error.to_string(), "the RMV API is unavailable: 503: text");
286        assert_eq!(status(418, None).status(), "upstream_error");
287    }
288
289    #[test]
290    fn maps_other_client_errors() {
291        let error = Error::from(hafas::Error::Decode("bad".into()));
292        assert_eq!(error.status(), "upstream_error");
293        assert_eq!(
294            error.to_string(),
295            "unexpected answer from the RMV API: unexpected response: bad"
296        );
297        let error = Error::from(hafas::Error::BaseUrl("x".into()));
298        assert_eq!(error.status(), "config_error");
299        assert_eq!(error.retry_after_seconds(), None);
300        let error = Error::from(hafas::Error::AccessIdMissing);
301        assert_eq!(error.status(), "access_id_missing");
302    }
303
304    #[test]
305    fn tells_no_result_apart() {
306        let no_result = |code: &str| hafas::Error::Api {
307            status: Some(400),
308            code: code.to_owned(),
309            text: String::new(),
310            retry_after: None,
311        };
312        assert!(is_no_result(&no_result("SVC_NO_RESULT")));
313        assert!(is_no_result(&no_result("SVC_NO_MATCH")));
314        assert!(!is_no_result(&no_result("SVC_LOC")));
315        assert!(!is_no_result(&hafas::Error::AccessIdMissing));
316    }
317
318    #[test]
319    fn names_every_status() {
320        let errors = [
321            Error::AccessIdMissing,
322            Error::StopNotFound { query: "x".into() },
323            Error::Timeout,
324            Error::Upstream {
325                message: "x".into(),
326            },
327        ];
328        let statuses: Vec<&str> = errors.iter().map(Error::status).collect();
329        assert_eq!(
330            statuses,
331            [
332                "access_id_missing",
333                "stop_not_found",
334                "timeout",
335                "upstream_error"
336            ]
337        );
338    }
339
340    #[test]
341    fn the_body_lists_the_candidates() {
342        let candidate = StopMatch {
343            id: "1".into(),
344            name: "Bahnhof".into(),
345            area: None,
346            dhid: None,
347            lat: 0.0,
348            lon: 0.0,
349            modes: Vec::new(),
350        };
351        let body = Error::AmbiguousStop {
352            query: "Bahnhof".into(),
353            candidates: vec![candidate.clone()],
354        }
355        .body();
356        assert_eq!(body.status, "ambiguous_stop");
357        assert_eq!(
358            body.error,
359            "\"Bahnhof\" does not name one stop, pass the ID of one of the 1 candidates"
360        );
361        assert_eq!(body.candidates, [candidate]);
362        assert_eq!(Error::Timeout.body().candidates, Vec::<StopMatch>::new());
363    }
364}