Skip to main content

hafas/
client.rs

1use std::fmt;
2use std::sync::Arc;
3use std::time::Duration;
4
5use jiff::Timestamp;
6use reqwest::header::{RETRY_AFTER, USER_AGENT};
7use reqwest::{StatusCode, Url};
8use rustls::{ClientConfig, RootCertStore};
9
10use crate::error::{ApiError, Error, api_error, error_message, retry_after};
11use crate::request::Request;
12use crate::types::ResponseInfo;
13
14/// The default time to wait for a response.
15pub const DEFAULT_TIMEOUT: Duration = Duration::from_secs(20);
16
17/// What stands in for the access key in texts of the API that echo it.
18pub const REDACTED: &str = "[redacted]";
19
20/// The name of the query parameter with the access key.
21const ACCESS_ID: &str = "accessId";
22
23/// Configures a [`Client`].
24#[derive(Clone)]
25pub struct ClientBuilder {
26    base: String,
27    access_id: Option<String>,
28    lang: Option<String>,
29    user_agent: Option<String>,
30    timeout: Duration,
31}
32
33impl fmt::Debug for ClientBuilder {
34    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
35        f.debug_struct("ClientBuilder")
36            .field("base", &self.base)
37            .field("access_id", &self.access_id.as_ref().map(|_| REDACTED))
38            .field("lang", &self.lang)
39            .field("user_agent", &self.user_agent)
40            .field("timeout", &self.timeout)
41            .finish()
42    }
43}
44
45impl ClientBuilder {
46    /// The access key, sent as `accessId` with every request. Without one,
47    /// or with an empty one, [`Client::send`] fails with
48    /// [`Error::AccessIdMissing`] before it opens a connection.
49    #[must_use]
50    pub fn access_id(mut self, access_id: impl Into<String>) -> Self {
51        let access_id = access_id.into();
52        self.access_id = (!access_id.trim().is_empty()).then_some(access_id);
53        self
54    }
55
56    /// The language of texts, like `de` or `en`, sent as `lang`. The server
57    /// takes its default if not set.
58    #[must_use]
59    pub fn lang(mut self, lang: impl Into<String>) -> Self {
60        self.lang = Some(lang.into());
61        self
62    }
63
64    /// The `User-Agent` header of every request.
65    #[must_use]
66    pub fn user_agent(mut self, user_agent: impl Into<String>) -> Self {
67        self.user_agent = Some(user_agent.into());
68        self
69    }
70
71    /// How long to wait for a response, [`DEFAULT_TIMEOUT`] if not set.
72    #[must_use]
73    pub fn timeout(mut self, timeout: Duration) -> Self {
74        self.timeout = timeout;
75        self
76    }
77
78    /// Builds the client.
79    ///
80    /// # Panics
81    ///
82    /// Never: the TLS provider supports the protocol versions it asks for.
83    pub fn build(self) -> Result<Client, Error> {
84        let base = parse_base(&self.base)?;
85        let roots = RootCertStore {
86            roots: webpki_roots::TLS_SERVER_ROOTS.to_vec(),
87        };
88        let tls =
89            ClientConfig::builder_with_provider(Arc::new(rustls::crypto::ring::default_provider()))
90                .with_safe_default_protocol_versions()
91                .expect("ring supports the default protocol versions")
92                .with_root_certificates(roots)
93                .with_no_client_auth();
94        let http = reqwest::Client::builder()
95            .tls_backend_preconfigured(tls)
96            .timeout(self.timeout)
97            // Not even the protocol-level retries reqwest makes by default.
98            .retry(reqwest::retry::never())
99            .build()
100            .map_err(Error::Client)?;
101        Ok(Client {
102            http,
103            base,
104            access_id: self.access_id,
105            lang: self.lang,
106            user_agent: self.user_agent,
107        })
108    }
109}
110
111/// Makes the base URL end in a slash, so the service paths go below it.
112fn parse_base(base: &str) -> Result<Url, Error> {
113    let invalid = || Error::BaseUrl(base.to_owned());
114    let mut url = Url::parse(base).map_err(|_| invalid())?;
115    if !matches!(url.scheme(), "http" | "https") {
116        return Err(invalid());
117    }
118    if !url.path().ends_with('/') {
119        let path = format!("{}/", url.path());
120        url.set_path(&path);
121    }
122    url.set_query(None);
123    url.set_fragment(None);
124    Ok(url)
125}
126
127/// A client for one HAFAS server.
128///
129/// It sends every request once: it never retries.
130#[derive(Clone)]
131pub struct Client {
132    http: reqwest::Client,
133    base: Url,
134    access_id: Option<String>,
135    lang: Option<String>,
136    user_agent: Option<String>,
137}
138
139impl fmt::Debug for Client {
140    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
141        f.debug_struct("Client")
142            .field("base", &self.base.as_str())
143            .field("access_id", &self.access_id.as_ref().map(|_| REDACTED))
144            .field("lang", &self.lang)
145            .field("user_agent", &self.user_agent)
146            .finish_non_exhaustive()
147    }
148}
149
150impl Client {
151    /// Starts configuring a client for the server at `base`, the path the
152    /// services are below, like `https://example.org/hapi/`.
153    pub fn builder(base: impl Into<String>) -> ClientBuilder {
154        ClientBuilder {
155            base: base.into(),
156            access_id: None,
157            lang: None,
158            user_agent: None,
159            timeout: DEFAULT_TIMEOUT,
160        }
161    }
162
163    /// The base URL, ending in a slash.
164    pub fn base_url(&self) -> &Url {
165        &self.base
166    }
167
168    /// Whether an access key is configured.
169    pub fn has_access_id(&self) -> bool {
170        self.access_id.is_some()
171    }
172
173    /// The URL a request goes to, with its query but without the access key,
174    /// so it can be shown or logged.
175    ///
176    /// # Panics
177    ///
178    /// Never: the service paths are relative URLs.
179    pub fn url<R: Request>(&self, request: &R) -> Url {
180        let mut url = self
181            .base
182            .join(R::PATH)
183            .expect("the service paths are relative URLs");
184        {
185            let mut query = url.query_pairs_mut();
186            query.extend_pairs(request.query());
187            query.append_pair("format", "json");
188            if let Some(lang) = &self.lang {
189                query.append_pair("lang", lang);
190            }
191        }
192        url
193    }
194
195    /// Sends a request and decodes the response.
196    pub async fn send<R: Request>(&self, request: &R) -> Result<R::Response, Error> {
197        let body = self.fetch(request).await?;
198        self.decode::<R>(&body)
199    }
200
201    /// Sends a request and returns the body of a successful response.
202    /// [`Client::decode`] turns it into the response type.
203    pub async fn fetch<R: Request>(&self, request: &R) -> Result<Vec<u8>, Error> {
204        let access_id = self.access_id.as_deref().ok_or(Error::AccessIdMissing)?;
205        let url = self.url(request);
206        tracing::debug!(%url, "request");
207        let mut url = url;
208        url.query_pairs_mut().append_pair(ACCESS_ID, access_id);
209        let mut builder = self.http.get(url);
210        if let Some(user_agent) = &self.user_agent {
211            builder = builder.header(USER_AGENT, user_agent);
212        }
213        let response = builder.send().await.map_err(Error::from_reqwest)?;
214        let status = response.status();
215        tracing::debug!(%status, "response");
216        if status.is_success() {
217            let body = response.bytes().await.map_err(Error::from_reqwest)?;
218            return Ok(body.to_vec());
219        }
220        let retry_after = response
221            .headers()
222            .get(RETRY_AFTER)
223            .and_then(|value| value.to_str().ok())
224            .and_then(|value| retry_after(value, Timestamp::now()));
225        let body = response.bytes().await.unwrap_or_default();
226        Err(self.status_error(status, &body, retry_after))
227    }
228
229    /// Decodes the body of a successful response. A body that reports a
230    /// HAFAS error, in JSON or in XML, is an [`Error::Api`].
231    pub fn decode<R: Request>(&self, body: &[u8]) -> Result<R::Response, Error> {
232        if let Ok(info) = serde_json::from_slice::<ResponseInfo>(body) {
233            // Texts of the server, which could echo the key.
234            let server = self.redact(info.server_version.as_deref().unwrap_or("?"));
235            let dialect = self.redact(info.dialect_version.as_deref().unwrap_or("?"));
236            tracing::debug!(server_version = server, dialect_version = dialect, "server");
237        }
238        if let Some(error) = api_error(body) {
239            return Err(self.api(&error, None, None));
240        }
241        serde_json::from_slice(body).map_err(|error| Error::Decode(self.redact(&error.to_string())))
242    }
243
244    fn status_error(
245        &self,
246        status: StatusCode,
247        body: &[u8],
248        retry_after: Option<Duration>,
249    ) -> Error {
250        match api_error(body) {
251            Some(error) => self.api(&error, Some(status.as_u16()), retry_after),
252            None => Error::Status {
253                status: status.as_u16(),
254                // Redacted before it is cut, so no part of the key stays.
255                message: error_message(status, &self.redact(&String::from_utf8_lossy(body))),
256                retry_after,
257            },
258        }
259    }
260
261    /// An [`Error::Api`], with the key redacted in the code and the text:
262    /// both come from the server.
263    fn api(&self, error: &ApiError, status: Option<u16>, retry_after: Option<Duration>) -> Error {
264        Error::Api {
265            status,
266            code: self.redact(&error.code),
267            text: self.redact(&error.text),
268            retry_after,
269        }
270    }
271
272    /// Replaces the access key in a text of the server, as it is and as it
273    /// would be in a URL.
274    fn redact(&self, text: &str) -> String {
275        let Some(access_id) = &self.access_id else {
276            return text.to_owned();
277        };
278        let encoded: String = url_encode(access_id);
279        text.replace(access_id.as_str(), REDACTED)
280            .replace(&encoded, REDACTED)
281    }
282}
283
284fn url_encode(value: &str) -> String {
285    let mut url = Url::parse("http://x/").expect("a valid URL");
286    url.query_pairs_mut().append_pair("v", value);
287    url.query()
288        .and_then(|query| query.strip_prefix("v="))
289        .unwrap_or(value)
290        .to_owned()
291}