use std::time::Duration;
use jiff::Timestamp;
#[derive(Debug, thiserror::Error)]
pub enum Error {
#[error("invalid base URL {0:?}: expected an absolute http or https URL")]
BaseUrl(String),
#[error("no access key (accessId) configured")]
AccessIdMissing,
#[error("could not set up the HTTP client")]
Client(#[source] reqwest::Error),
#[error("the server did not answer in time")]
Timeout(#[source] reqwest::Error),
#[error("the request failed")]
Http(#[source] reqwest::Error),
#[error("the API answered {code}: {text}")]
Api {
status: Option<u16>,
code: String,
text: String,
retry_after: Option<Duration>,
},
#[error("the server answered {status}: {message}")]
Status {
status: u16,
message: String,
retry_after: Option<Duration>,
},
#[error("unexpected response: {0}")]
Decode(String),
}
impl Error {
pub(crate) fn from_reqwest(error: reqwest::Error) -> Self {
let error = error.without_url();
if error.is_timeout() {
Self::Timeout(error)
} else {
Self::Http(error)
}
}
pub fn code(&self) -> Option<&str> {
match self {
Self::Api { code, .. } => Some(code),
_ => None,
}
}
pub fn status(&self) -> Option<u16> {
match self {
Self::Api { status, .. } => *status,
Self::Status { status, .. } => Some(*status),
_ => None,
}
}
pub fn retry_after(&self) -> Option<Duration> {
match self {
Self::Api { retry_after, .. } | Self::Status { retry_after, .. } => *retry_after,
_ => None,
}
}
}
const MAX_MESSAGE: usize = 200;
#[derive(Debug, PartialEq)]
pub(crate) struct ApiError {
pub(crate) code: String,
pub(crate) text: String,
}
pub(crate) fn api_error(body: &[u8]) -> Option<ApiError> {
if serde_json::from_slice::<serde::de::IgnoredAny>(body).is_ok() {
json_error(body)
} else {
xml_error(body)
}
}
fn json_error(body: &[u8]) -> Option<ApiError> {
#[derive(serde::Deserialize)]
#[serde(rename_all = "camelCase")]
struct Body {
error_code: Option<String>,
error_text: Option<String>,
}
let body: Body = serde_json::from_slice(body).ok()?;
let code = body.error_code.filter(|code| !code.is_empty())?;
Some(ApiError {
code,
text: body.error_text.unwrap_or_default(),
})
}
fn xml_error(body: &[u8]) -> Option<ApiError> {
let text = std::str::from_utf8(body).ok()?;
let text = text.trim_start_matches('\u{feff}').trim_start();
let text = match text.strip_prefix("<?") {
Some(prolog) => prolog[prolog.find("?>")? + 2..].trim_start(),
None => text,
};
let element = text.strip_prefix("<Error")?;
let element = &element[..element.find('>')?];
let code = xml_attribute(element, "errorCode").filter(|code| !code.is_empty())?;
Some(ApiError {
code,
text: xml_attribute(element, "errorText").unwrap_or_default(),
})
}
fn xml_attribute(element: &str, name: &str) -> Option<String> {
let mut rest = element;
loop {
let at = rest.find(name)?;
let before = rest[..at].chars().next_back();
let after = rest[at + name.len()..].trim_start();
rest = &rest[at + name.len()..];
if !before.is_some_and(char::is_whitespace) {
continue;
}
let Some(value) = after.strip_prefix('=') else {
continue;
};
let value = value.trim_start();
let quote = value.chars().next()?;
if quote != '"' && quote != '\'' {
return None;
}
let value = &value[1..];
let end = value.find(quote)?;
return Some(unescape(&value[..end]));
}
}
fn unescape(value: &str) -> String {
value
.replace("<", "<")
.replace(">", ">")
.replace(""", "\"")
.replace("'", "'")
.replace("&", "&")
}
pub(crate) fn error_message(status: reqwest::StatusCode, text: &str) -> String {
let text = text.trim();
if text.is_empty() {
return status.canonical_reason().unwrap_or("error").to_owned();
}
text.chars().take(MAX_MESSAGE).collect()
}
pub(crate) fn retry_after(value: &str, now: Timestamp) -> Option<Duration> {
let value = value.trim();
if let Ok(seconds) = value.parse::<u64>() {
return Some(Duration::from_secs(seconds));
}
let at = jiff::fmt::rfc2822::DateTimeParser::new()
.parse_timestamp(value)
.ok()?;
let seconds = at.as_second().saturating_sub(now.as_second());
Some(Duration::from_secs(u64::try_from(seconds).unwrap_or(0)))
}
#[cfg(test)]
mod tests {
use super::*;
use reqwest::StatusCode;
fn error(code: &str, text: &str) -> ApiError {
ApiError {
code: code.to_owned(),
text: text.to_owned(),
}
}
#[test]
fn finds_the_error_of_a_json_body() {
let body = br#"{"serverVersion":"2.39.1","errorCode":"API_QUOTA","errorText":"quota exceeded","requestId":"x"}"#;
assert_eq!(api_error(body), Some(error("API_QUOTA", "quota exceeded")));
assert_eq!(
api_error(br#"{"errorCode":"API_PARAM"}"#),
Some(error("API_PARAM", ""))
);
assert_eq!(api_error(br#"{"errorCode":"","errorText":"x"}"#), None);
assert_eq!(api_error(br#"{"Departure":[]}"#), None);
let body = br#"{"Message":[{"text":"<Error errorCode='API_AUTH'/>"}]}"#;
assert_eq!(api_error(body), None);
}
#[test]
fn finds_the_error_of_an_xml_body() {
let body = br#"<?xml version="1.0" encoding="UTF-8"?>
<Error serverVersion="2.39.1" dialectVersion="2.39" errorCode="API_PARAM" errorText="Missing value for required param "accessId"" requestId="x" xmlns="http://hacon.de/hafas/proxy/hafas-proxy"/>"#;
assert_eq!(
api_error(body),
Some(error(
"API_PARAM",
r#"Missing value for required param "accessId""#
))
);
let body = br"<Error internalErrorCode='X' errorCode='SVC_LOC' />";
assert_eq!(api_error(body), Some(error("SVC_LOC", "")));
let body = br"<Error xerrorCode='X' errorCode errorCode='SVC_LOC'/>";
assert_eq!(api_error(body), Some(error("SVC_LOC", "")));
assert_eq!(api_error(b"<Error errorCode=API_AUTH/>"), None);
assert_eq!(api_error(b"<Error errorCode"), None);
assert_eq!(api_error(b"<html>Bad Gateway</html>"), None);
assert_eq!(api_error(b"<Other><Error errorCode='X'/></Other>"), None);
assert_eq!(api_error(b"<?xml version='1.0'"), None);
let body = "\u{feff}<Error errorCode='API_AUTH'/>".as_bytes();
assert_eq!(api_error(body), Some(error("API_AUTH", "")));
assert_eq!(api_error(&[0xff, 0xfe]), None);
}
#[test]
fn tells_the_code_the_status_and_the_wait() {
let wait = Some(Duration::from_secs(5));
let status = Error::Status {
status: 503,
message: "Service Unavailable".to_owned(),
retry_after: wait,
};
assert_eq!(status.code(), None);
assert_eq!(status.status(), Some(503));
assert_eq!(status.retry_after(), wait);
for other in [Error::AccessIdMissing, Error::BaseUrl("x".to_owned())] {
assert_eq!(other.code(), None);
assert_eq!(other.status(), None);
assert_eq!(other.retry_after(), None);
}
}
#[test]
fn takes_the_start_of_another_body() {
let body = format!(" {} ", "x".repeat(500));
let message = error_message(StatusCode::BAD_GATEWAY, &body);
assert_eq!(message, "x".repeat(MAX_MESSAGE));
}
#[test]
fn takes_the_reason_of_an_empty_body() {
assert_eq!(
error_message(StatusCode::SERVICE_UNAVAILABLE, " \n"),
"Service Unavailable"
);
assert_eq!(
error_message(StatusCode::from_u16(599).unwrap(), ""),
"error"
);
}
#[test]
fn parses_retry_after() {
let now: Timestamp = "2026-11-26T20:00:00Z".parse().unwrap();
assert_eq!(retry_after(" 120 ", now), Some(Duration::from_secs(120)));
assert_eq!(
retry_after("Thu, 26 Nov 2026 20:01:30 GMT", now),
Some(Duration::from_secs(90))
);
assert_eq!(
retry_after("Thu, 26 Nov 2026 19:00:00 GMT", now),
Some(Duration::ZERO)
);
assert_eq!(retry_after("soon", now), None);
}
}