1use crate::model::{ErrorBody, StopMatch};
4
5#[derive(Debug, thiserror::Error)]
6pub enum Error {
7 #[error(
9 "no contact configured: Transitous asks for one in every request. \
10 Set it with `transitous config set contact <url or email>` or TRANSITOUS_CONTACT"
11 )]
12 ContactMissing,
13 #[error("the contact is not valid: {0}")]
14 InvalidContact(String),
15 #[error("{query:?} does not name one stop, pass the ID of one of the {} candidates", candidates.len())]
17 AmbiguousStop {
18 query: String,
19 candidates: Vec<StopMatch>,
20 },
21 #[error("no stop matches {query:?}")]
22 StopNotFound { query: String },
23 #[error("too many requests, try again in {retry_after_seconds} s")]
25 RateLimited { retry_after_seconds: u64 },
26 #[error(
29 "{limit} plan requests in 24 hours reached, try again in {retry_after_seconds} s. \
30 Raise plan_daily_limit only after agreeing on more with Transitous"
31 )]
32 DailyLimit {
33 limit: u32,
34 retry_after_seconds: u64,
35 },
36 #[error("Transitous is unavailable: {message}")]
38 Unavailable { message: String },
39 #[error("Transitous did not answer in time")]
40 Timeout,
41 #[error("bad request: {message}")]
43 BadRequest { message: String },
44 #[error("not found: {message}")]
46 NotFound { message: String },
47 #[error("unexpected answer from Transitous: {message}")]
49 Upstream { message: String },
50 #[error(transparent)]
51 Config(#[from] crate::config::Error),
52 #[error("cannot update the usage counter at {path}: {source}")]
54 Usage {
55 path: String,
56 source: std::io::Error,
57 },
58}
59
60impl Error {
61 pub fn status(&self) -> &'static str {
63 match self {
64 Self::ContactMissing => "contact_missing",
65 Self::InvalidContact(_) | Self::Config(_) => "config_error",
66 Self::AmbiguousStop { .. } => "ambiguous_stop",
67 Self::StopNotFound { .. } => "stop_not_found",
68 Self::RateLimited { .. } => "rate_limited",
69 Self::DailyLimit { .. } => "daily_limit",
70 Self::Unavailable { .. } => "unavailable",
71 Self::Timeout => "timeout",
72 Self::BadRequest { .. } => "bad_request",
73 Self::NotFound { .. } => "not_found",
74 Self::Upstream { .. } => "upstream_error",
75 Self::Usage { .. } => "usage_error",
76 }
77 }
78
79 pub fn retry_after_seconds(&self) -> Option<u64> {
81 match self {
82 Self::RateLimited {
83 retry_after_seconds,
84 }
85 | Self::DailyLimit {
86 retry_after_seconds,
87 ..
88 } => Some(*retry_after_seconds),
89 _ => None,
90 }
91 }
92
93 pub fn body(&self) -> ErrorBody {
95 ErrorBody {
96 error: self.to_string(),
97 status: self.status().to_owned(),
98 retry_after_seconds: self.retry_after_seconds(),
99 candidates: match self {
100 Self::AmbiguousStop { candidates, .. } => candidates.clone(),
101 _ => Vec::new(),
102 },
103 }
104 }
105}
106
107impl From<motis::Error> for Error {
108 fn from(error: motis::Error) -> Self {
109 match error {
110 motis::Error::Status {
111 status: 429,
112 retry_after,
113 ..
114 } => Self::RateLimited {
115 retry_after_seconds: retry_after.map_or(60, |d| d.as_secs()),
116 },
117 motis::Error::Status {
118 status: 400 | 422,
119 message,
120 ..
121 } => Self::BadRequest { message },
122 motis::Error::Status {
123 status: 404,
124 message,
125 ..
126 } => Self::NotFound { message },
127 motis::Error::Status {
128 status, message, ..
129 } if status >= 500 => Self::Unavailable {
130 message: format!("{status}: {message}"),
131 },
132 motis::Error::Timeout(_) => Self::Timeout,
133 error @ (motis::Error::Http(_) | motis::Error::Client(_)) => Self::Unavailable {
134 message: chain(&error),
135 },
136 error @ motis::Error::BaseUrl(_) => Self::Config(crate::config::Error::InvalidValue {
137 key: "base_url".to_owned(),
138 reason: error.to_string(),
139 }),
140 error => Self::Upstream {
141 message: chain(&error),
142 },
143 }
144 }
145}
146
147fn chain(error: &dyn std::error::Error) -> String {
149 let mut text = error.to_string();
150 let mut source = error.source();
151 while let Some(cause) = source {
152 text.push_str(": ");
153 text.push_str(&cause.to_string());
154 source = cause.source();
155 }
156 text
157}
158
159#[cfg(test)]
160mod tests {
161 use super::*;
162 use std::time::Duration;
163
164 fn status(status: u16, retry_after: Option<Duration>) -> Error {
165 motis::Error::Status {
166 status,
167 message: "text".into(),
168 retry_after,
169 }
170 .into()
171 }
172
173 #[test]
174 fn maps_the_statuses_of_the_server() {
175 let error = status(429, Some(Duration::from_secs(7)));
176 assert_eq!(error.status(), "rate_limited");
177 assert_eq!(error.retry_after_seconds(), Some(7));
178 assert_eq!(status(429, None).retry_after_seconds(), Some(60));
179 assert_eq!(status(400, None).status(), "bad_request");
180 assert_eq!(status(422, None).status(), "bad_request");
181 assert_eq!(status(404, None).status(), "not_found");
182 let error = status(503, None);
183 assert_eq!(error.status(), "unavailable");
184 assert_eq!(error.to_string(), "Transitous is unavailable: 503: text");
185 assert_eq!(status(418, None).status(), "upstream_error");
186 }
187
188 #[test]
189 fn maps_other_client_errors() {
190 let decode = serde_json::from_str::<u8>("x").unwrap_err();
191 let error = Error::from(motis::Error::Decode(decode));
192 assert_eq!(error.status(), "upstream_error");
193 assert!(
194 error
195 .to_string()
196 .starts_with("unexpected answer from Transitous: unexpected response: "),
197 "{error}"
198 );
199 let error = Error::from(motis::Error::BaseUrl("x".into()));
200 assert_eq!(error.status(), "config_error");
201 assert_eq!(error.retry_after_seconds(), None);
202 }
203
204 #[test]
205 fn names_every_status() {
206 let errors = [
207 Error::ContactMissing,
208 Error::InvalidContact("x".into()),
209 Error::StopNotFound { query: "x".into() },
210 Error::DailyLimit {
211 limit: 720,
212 retry_after_seconds: 5,
213 },
214 Error::Timeout,
215 ];
216 let statuses: Vec<&str> = errors.iter().map(Error::status).collect();
217 assert_eq!(
218 statuses,
219 [
220 "contact_missing",
221 "config_error",
222 "stop_not_found",
223 "daily_limit",
224 "timeout"
225 ]
226 );
227 assert_eq!(errors[3].retry_after_seconds(), Some(5));
228 }
229
230 #[test]
231 fn the_body_lists_the_candidates() {
232 let candidate = StopMatch {
233 id: "1".into(),
234 name: "Bahnhof".into(),
235 area: None,
236 lat: 0.0,
237 lon: 0.0,
238 modes: Vec::new(),
239 };
240 let body = Error::AmbiguousStop {
241 query: "Bahnhof".into(),
242 candidates: vec![candidate.clone()],
243 }
244 .body();
245 assert_eq!(body.status, "ambiguous_stop");
246 assert_eq!(
247 body.error,
248 "\"Bahnhof\" does not name one stop, pass the ID of one of the 1 candidates"
249 );
250 assert_eq!(body.candidates, [candidate]);
251 assert_eq!(Error::Timeout.body().candidates, Vec::<StopMatch>::new());
252 }
253}