hafas 1.0.0

Client for the HAFAS ReST public transport API
Documentation
use std::time::Duration;

use jiff::Timestamp;

/// What can go wrong talking to the API.
///
/// No error carries a request URL, as every one contains the access key.
#[derive(Debug, thiserror::Error)]
pub enum Error {
    /// The base URL is not an absolute `http` or `https` URL.
    #[error("invalid base URL {0:?}: expected an absolute http or https URL")]
    BaseUrl(String),
    /// No access key is configured. Comes before any connection is opened.
    #[error("no access key (accessId) configured")]
    AccessIdMissing,
    /// The HTTP client could not be set up.
    #[error("could not set up the HTTP client")]
    Client(#[source] reqwest::Error),
    /// The server did not answer in time.
    #[error("the server did not answer in time")]
    Timeout(#[source] reqwest::Error),
    /// The request could not be sent or the response not be read.
    #[error("the request failed")]
    Http(#[source] reqwest::Error),
    /// The API reported an error with a HAFAS error code, like `API_AUTH`
    /// or `API_QUOTA`.
    #[error("the API answered {code}: {text}")]
    Api {
        /// The HTTP status, if it was not a success.
        status: Option<u16>,
        code: String,
        /// The `errorText`, with the access key redacted.
        text: String,
        /// How long to wait before asking again, from `Retry-After`.
        retry_after: Option<Duration>,
    },
    /// The server answered with an error status and no HAFAS error.
    #[error("the server answered {status}: {message}")]
    Status {
        status: u16,
        /// The start of the body, or the status reason.
        message: String,
        retry_after: Option<Duration>,
    },
    /// The response does not have the expected form. The diagnostic of the
    /// decoder, with the access key redacted: it can quote values of the
    /// response.
    #[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)
        }
    }

    /// The HAFAS error code, for [`Error::Api`].
    pub fn code(&self) -> Option<&str> {
        match self {
            Self::Api { code, .. } => Some(code),
            _ => None,
        }
    }

    /// The HTTP status of an error response.
    pub fn status(&self) -> Option<u16> {
        match self {
            Self::Api { status, .. } => *status,
            Self::Status { status, .. } => Some(*status),
            _ => None,
        }
    }

    /// The wait the server asked for with `Retry-After`.
    pub fn retry_after(&self) -> Option<Duration> {
        match self {
            Self::Api { retry_after, .. } | Self::Status { retry_after, .. } => *retry_after,
            _ => None,
        }
    }
}

/// The longest message taken from an error response that is not a HAFAS
/// error.
const MAX_MESSAGE: usize = 200;

/// A HAFAS error found in a response body.
#[derive(Debug, PartialEq)]
pub(crate) struct ApiError {
    pub(crate) code: String,
    pub(crate) text: String,
}

/// Finds the HAFAS error of a body: `errorCode` and `errorText` of the JSON
/// object, or of the root element `Error` of an XML body. A JSON body is
/// never read as XML, so texts of the data cannot pass for an error.
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(),
    })
}

/// The value of an attribute in the start tag `element`, with the entities
/// of XML resolved.
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("&lt;", "<")
        .replace("&gt;", ">")
        .replace("&quot;", "\"")
        .replace("&apos;", "'")
        .replace("&amp;", "&")
}

/// The message of an error response without a HAFAS error: the start of the
/// body, or else the reason phrase of the status.
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()
}

/// Parses `Retry-After`: seconds, or an HTTP date relative to `now`.
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 &quot;accessId&quot;" 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);
    }
}