hafas 1.0.0

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

use jiff::Timestamp;
use reqwest::header::{RETRY_AFTER, USER_AGENT};
use reqwest::{StatusCode, Url};
use rustls::{ClientConfig, RootCertStore};

use crate::error::{ApiError, Error, api_error, error_message, retry_after};
use crate::request::Request;
use crate::types::ResponseInfo;

/// The default time to wait for a response.
pub const DEFAULT_TIMEOUT: Duration = Duration::from_secs(20);

/// What stands in for the access key in texts of the API that echo it.
pub const REDACTED: &str = "[redacted]";

/// The name of the query parameter with the access key.
const ACCESS_ID: &str = "accessId";

/// Configures a [`Client`].
#[derive(Clone)]
pub struct ClientBuilder {
    base: String,
    access_id: Option<String>,
    lang: Option<String>,
    user_agent: Option<String>,
    timeout: Duration,
}

impl fmt::Debug for ClientBuilder {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        f.debug_struct("ClientBuilder")
            .field("base", &self.base)
            .field("access_id", &self.access_id.as_ref().map(|_| REDACTED))
            .field("lang", &self.lang)
            .field("user_agent", &self.user_agent)
            .field("timeout", &self.timeout)
            .finish()
    }
}

impl ClientBuilder {
    /// The access key, sent as `accessId` with every request. Without one,
    /// or with an empty one, [`Client::send`] fails with
    /// [`Error::AccessIdMissing`] before it opens a connection.
    #[must_use]
    pub fn access_id(mut self, access_id: impl Into<String>) -> Self {
        let access_id = access_id.into();
        self.access_id = (!access_id.trim().is_empty()).then_some(access_id);
        self
    }

    /// The language of texts, like `de` or `en`, sent as `lang`. The server
    /// takes its default if not set.
    #[must_use]
    pub fn lang(mut self, lang: impl Into<String>) -> Self {
        self.lang = Some(lang.into());
        self
    }

    /// The `User-Agent` header of every request.
    #[must_use]
    pub fn user_agent(mut self, user_agent: impl Into<String>) -> Self {
        self.user_agent = Some(user_agent.into());
        self
    }

    /// How long to wait for a response, [`DEFAULT_TIMEOUT`] if not set.
    #[must_use]
    pub fn timeout(mut self, timeout: Duration) -> Self {
        self.timeout = timeout;
        self
    }

    /// Builds the client.
    ///
    /// # Panics
    ///
    /// Never: the TLS provider supports the protocol versions it asks for.
    pub fn build(self) -> Result<Client, Error> {
        let base = parse_base(&self.base)?;
        let roots = RootCertStore {
            roots: webpki_roots::TLS_SERVER_ROOTS.to_vec(),
        };
        let tls =
            ClientConfig::builder_with_provider(Arc::new(rustls::crypto::ring::default_provider()))
                .with_safe_default_protocol_versions()
                .expect("ring supports the default protocol versions")
                .with_root_certificates(roots)
                .with_no_client_auth();
        let http = reqwest::Client::builder()
            .tls_backend_preconfigured(tls)
            .timeout(self.timeout)
            // Not even the protocol-level retries reqwest makes by default.
            .retry(reqwest::retry::never())
            .build()
            .map_err(Error::Client)?;
        Ok(Client {
            http,
            base,
            access_id: self.access_id,
            lang: self.lang,
            user_agent: self.user_agent,
        })
    }
}

/// Makes the base URL end in a slash, so the service paths go below it.
fn parse_base(base: &str) -> Result<Url, Error> {
    let invalid = || Error::BaseUrl(base.to_owned());
    let mut url = Url::parse(base).map_err(|_| invalid())?;
    if !matches!(url.scheme(), "http" | "https") {
        return Err(invalid());
    }
    if !url.path().ends_with('/') {
        let path = format!("{}/", url.path());
        url.set_path(&path);
    }
    url.set_query(None);
    url.set_fragment(None);
    Ok(url)
}

/// A client for one HAFAS server.
///
/// It sends every request once: it never retries.
#[derive(Clone)]
pub struct Client {
    http: reqwest::Client,
    base: Url,
    access_id: Option<String>,
    lang: Option<String>,
    user_agent: Option<String>,
}

impl fmt::Debug for Client {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        f.debug_struct("Client")
            .field("base", &self.base.as_str())
            .field("access_id", &self.access_id.as_ref().map(|_| REDACTED))
            .field("lang", &self.lang)
            .field("user_agent", &self.user_agent)
            .finish_non_exhaustive()
    }
}

impl Client {
    /// Starts configuring a client for the server at `base`, the path the
    /// services are below, like `https://example.org/hapi/`.
    pub fn builder(base: impl Into<String>) -> ClientBuilder {
        ClientBuilder {
            base: base.into(),
            access_id: None,
            lang: None,
            user_agent: None,
            timeout: DEFAULT_TIMEOUT,
        }
    }

    /// The base URL, ending in a slash.
    pub fn base_url(&self) -> &Url {
        &self.base
    }

    /// Whether an access key is configured.
    pub fn has_access_id(&self) -> bool {
        self.access_id.is_some()
    }

    /// The URL a request goes to, with its query but without the access key,
    /// so it can be shown or logged.
    ///
    /// # Panics
    ///
    /// Never: the service paths are relative URLs.
    pub fn url<R: Request>(&self, request: &R) -> Url {
        let mut url = self
            .base
            .join(R::PATH)
            .expect("the service paths are relative URLs");
        {
            let mut query = url.query_pairs_mut();
            query.extend_pairs(request.query());
            query.append_pair("format", "json");
            if let Some(lang) = &self.lang {
                query.append_pair("lang", lang);
            }
        }
        url
    }

    /// Sends a request and decodes the response.
    pub async fn send<R: Request>(&self, request: &R) -> Result<R::Response, Error> {
        let body = self.fetch(request).await?;
        self.decode::<R>(&body)
    }

    /// Sends a request and returns the body of a successful response.
    /// [`Client::decode`] turns it into the response type.
    pub async fn fetch<R: Request>(&self, request: &R) -> Result<Vec<u8>, Error> {
        let access_id = self.access_id.as_deref().ok_or(Error::AccessIdMissing)?;
        let url = self.url(request);
        tracing::debug!(%url, "request");
        let mut url = url;
        url.query_pairs_mut().append_pair(ACCESS_ID, access_id);
        let mut builder = self.http.get(url);
        if let Some(user_agent) = &self.user_agent {
            builder = builder.header(USER_AGENT, user_agent);
        }
        let response = builder.send().await.map_err(Error::from_reqwest)?;
        let status = response.status();
        tracing::debug!(%status, "response");
        if status.is_success() {
            let body = response.bytes().await.map_err(Error::from_reqwest)?;
            return Ok(body.to_vec());
        }
        let retry_after = response
            .headers()
            .get(RETRY_AFTER)
            .and_then(|value| value.to_str().ok())
            .and_then(|value| retry_after(value, Timestamp::now()));
        let body = response.bytes().await.unwrap_or_default();
        Err(self.status_error(status, &body, retry_after))
    }

    /// Decodes the body of a successful response. A body that reports a
    /// HAFAS error, in JSON or in XML, is an [`Error::Api`].
    pub fn decode<R: Request>(&self, body: &[u8]) -> Result<R::Response, Error> {
        if let Ok(info) = serde_json::from_slice::<ResponseInfo>(body) {
            // Texts of the server, which could echo the key.
            let server = self.redact(info.server_version.as_deref().unwrap_or("?"));
            let dialect = self.redact(info.dialect_version.as_deref().unwrap_or("?"));
            tracing::debug!(server_version = server, dialect_version = dialect, "server");
        }
        if let Some(error) = api_error(body) {
            return Err(self.api(&error, None, None));
        }
        serde_json::from_slice(body).map_err(|error| Error::Decode(self.redact(&error.to_string())))
    }

    fn status_error(
        &self,
        status: StatusCode,
        body: &[u8],
        retry_after: Option<Duration>,
    ) -> Error {
        match api_error(body) {
            Some(error) => self.api(&error, Some(status.as_u16()), retry_after),
            None => Error::Status {
                status: status.as_u16(),
                // Redacted before it is cut, so no part of the key stays.
                message: error_message(status, &self.redact(&String::from_utf8_lossy(body))),
                retry_after,
            },
        }
    }

    /// An [`Error::Api`], with the key redacted in the code and the text:
    /// both come from the server.
    fn api(&self, error: &ApiError, status: Option<u16>, retry_after: Option<Duration>) -> Error {
        Error::Api {
            status,
            code: self.redact(&error.code),
            text: self.redact(&error.text),
            retry_after,
        }
    }

    /// Replaces the access key in a text of the server, as it is and as it
    /// would be in a URL.
    fn redact(&self, text: &str) -> String {
        let Some(access_id) = &self.access_id else {
            return text.to_owned();
        };
        let encoded: String = url_encode(access_id);
        text.replace(access_id.as_str(), REDACTED)
            .replace(&encoded, REDACTED)
    }
}

fn url_encode(value: &str) -> String {
    let mut url = Url::parse("http://x/").expect("a valid URL");
    url.query_pairs_mut().append_pair("v", value);
    url.query()
        .and_then(|query| query.strip_prefix("v="))
        .unwrap_or(value)
        .to_owned()
}