Skip to main content

ankusa/
client.rs

1//! The shared client core: base URL, headers, timeout, and the transport.
2
3use std::fmt;
4use std::sync::Arc;
5use std::time::Duration;
6
7use bytes::Bytes;
8use percent_encoding::{AsciiSet, NON_ALPHANUMERIC, utf8_percent_encode};
9use serde::Serialize;
10use serde::de::DeserializeOwned;
11
12use crate::admin::AdminClient;
13use crate::claim_check::ClaimCheckClient;
14use crate::routes::RoutesClient;
15use crate::transport::{ReqwestTransport, Transport, TransportError};
16
17/// The RFC 3986 unreserved set: everything else travels percent-encoded, so a
18/// route id, a cursor, or a filter value can never reshape its request.
19pub(crate) const SEGMENT: &AsciiSet = &NON_ALPHANUMERIC
20    .remove(b'-')
21    .remove(b'.')
22    .remove(b'_')
23    .remove(b'~');
24
25/// The request timeout every client starts with, matching the TypeScript and
26/// Python SDKs.
27const DEFAULT_TIMEOUT: Duration = Duration::from_secs(10);
28
29/// Something a client cannot be built with.
30#[derive(Debug, thiserror::Error)]
31#[non_exhaustive]
32pub enum ConfigError {
33    /// The base URL is not an absolute `http`/`https` URL.
34    #[error("invalid base URL {url:?}: want an absolute http(s) URL")]
35    InvalidBaseUrl {
36        /// The rejected URL, as passed.
37        url: String,
38    },
39    /// A header name or value the client refuses to send.
40    #[error("invalid header {name:?}")]
41    InvalidHeader {
42        /// The header name, as passed.
43        name: String,
44    },
45    /// The transport itself could not be built.
46    #[error("could not build the HTTP client")]
47    Transport(#[source] TransportError),
48}
49
50/// Why a request never produced an answer.
51///
52/// Every "the deployment is not answering the way this call needs" failure
53/// funnels through this type, so each client only has to add its own
54/// request-level classification on top.
55#[derive(Debug, thiserror::Error)]
56#[non_exhaustive]
57pub enum UnavailableReason {
58    /// A response with a status this call cannot use: a `3xx` redirect, a
59    /// `5xx`, or a `2xx` that is not the one the endpoint documents.
60    #[error("unexpected HTTP status {0}")]
61    Status(http::StatusCode),
62    /// No response before the client's timeout.
63    #[error("no response within {0:?}")]
64    Timeout(Duration),
65    /// The transport failed outright: no connection, or a dropped body.
66    #[error("transport failed")]
67    Transport(#[source] TransportError),
68    /// A response body that is not the JSON this call expects.
69    #[error("invalid JSON")]
70    Json(#[source] serde_json::Error),
71}
72
73/// Builds a client for one deployment, sharing its base URL, headers, and
74/// timeout.
75///
76/// Every request is bounded by `tokio::time::timeout`, so a Tokio runtime with
77/// the time driver enabled is required.
78///
79/// [`ClientBuilder::new`] uses the default [`ReqwestTransport`];
80/// [`ClientBuilder::with_transport`] takes any [`Transport`].
81pub struct ClientBuilder<T = ReqwestTransport> {
82    base_url: String,
83    headers: http::HeaderMap,
84    timeout: Duration,
85    transport: Result<T, ConfigError>,
86    error: Option<ConfigError>,
87}
88
89// Debug by hand: a header *value* can be a bearer token, and the derive would
90// print it. Only the shared configuration and the header names are shown.
91impl<T> fmt::Debug for ClientBuilder<T> {
92    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
93        f.debug_struct("ClientBuilder")
94            .field("base_url", &self.base_url)
95            .field("header_names", &HeaderNames(&self.headers))
96            .field("timeout", &self.timeout)
97            .finish_non_exhaustive()
98    }
99}
100
101impl ClientBuilder<ReqwestTransport> {
102    /// Starts a builder for `base_url`: `http://host:port`, optionally with a
103    /// path prefix.
104    #[must_use]
105    pub fn new(base_url: impl Into<String>) -> Self {
106        Self::connecting(base_url.into(), ReqwestTransport::new())
107    }
108}
109
110impl<T: Transport> ClientBuilder<T> {
111    /// Starts a builder around `transport`, so requests never touch the
112    /// network.
113    #[must_use]
114    pub fn with_transport(base_url: impl Into<String>, transport: T) -> Self {
115        Self::connecting(base_url.into(), Ok(transport))
116    }
117
118    fn connecting(base_url: String, transport: Result<T, ConfigError>) -> Self {
119        Self {
120            base_url,
121            headers: http::HeaderMap::new(),
122            timeout: DEFAULT_TIMEOUT,
123            transport,
124            error: None,
125        }
126    }
127
128    /// Adds a header sent with every request.
129    ///
130    /// A name or value that cannot be sent is not reported here: the terminal
131    /// builder methods return it, so one `?` at the end covers the whole
132    /// builder.
133    #[must_use]
134    pub fn header(mut self, name: &str, value: &str) -> Self {
135        match (
136            http::HeaderName::from_bytes(name.as_bytes()),
137            http::HeaderValue::from_str(value),
138        ) {
139            (Ok(name), Ok(value)) => {
140                self.headers.insert(name, value);
141            }
142            _ => {
143                // The first failure is kept: later ones are consequences of the
144                // config already being wrong.
145                if self.error.is_none() {
146                    self.error = Some(ConfigError::InvalidHeader {
147                        name: name.to_owned(),
148                    });
149                }
150            }
151        }
152        self
153    }
154
155    /// Adds every header in `headers`, replacing ones already set.
156    #[must_use]
157    pub fn headers(mut self, headers: http::HeaderMap) -> Self {
158        self.headers.extend(headers);
159        self
160    }
161
162    /// Sets the per-request timeout. Default: 10 seconds.
163    #[must_use]
164    pub fn timeout(mut self, timeout: Duration) -> Self {
165        self.timeout = timeout;
166        self
167    }
168
169    /// Builds a claim-check client.
170    ///
171    /// # Errors
172    ///
173    /// [`ConfigError`] for a header that cannot be sent, a transport that
174    /// could not be built, or a base URL that is not an absolute `http`/
175    /// `https` URL.
176    pub fn claim_check(self) -> Result<ClaimCheckClient<T>, ConfigError> {
177        Ok(ClaimCheckClient::from_core(Arc::new(self.into_core()?)))
178    }
179
180    /// Builds a route-management client.
181    ///
182    /// # Errors
183    ///
184    /// [`ConfigError`], as [`ClientBuilder::claim_check`] documents it.
185    pub fn routes(self) -> Result<RoutesClient<T>, ConfigError> {
186        Ok(RoutesClient::from_core(Arc::new(self.into_core()?)))
187    }
188
189    /// Builds an operator-API client.
190    ///
191    /// # Errors
192    ///
193    /// [`ConfigError`], as [`ClientBuilder::claim_check`] documents it.
194    pub fn admin(self) -> Result<AdminClient<T>, ConfigError> {
195        Ok(AdminClient::from_core(Arc::new(self.into_core()?)))
196    }
197
198    fn into_core(self) -> Result<Core<T>, ConfigError> {
199        // A misconfigured header is the most useful thing to report, then a
200        // transport that would not build, then a URL that cannot be asked for.
201        if let Some(error) = self.error {
202            return Err(error);
203        }
204        // The transport settles first, so a transport that cannot be built is
205        // reported ahead of a URL that cannot be asked for.
206        let transport = self.transport?;
207        let base_url = normalize_base_url(&self.base_url)?;
208        Ok(Core {
209            base_url,
210            headers: self.headers,
211            timeout: self.timeout,
212            transport,
213        })
214    }
215}
216
217fn normalize_base_url(base_url: &str) -> Result<Box<str>, ConfigError> {
218    let invalid = || ConfigError::InvalidBaseUrl {
219        url: base_url.to_owned(),
220    };
221    // A trailing slash only ever produces `//health`, so it is dropped here
222    // and every path below starts with one.
223    let trimmed = base_url.trim_end_matches('/');
224    let uri: http::Uri = trimmed.parse().map_err(|_| invalid())?;
225    if !matches!(uri.scheme_str(), Some("http" | "https")) || uri.authority().is_none() {
226        return Err(invalid());
227    }
228    Ok(trimmed.into())
229}
230
231/// What every client holds: one connection target, one timeout, one transport.
232///
233/// Cloning a client clones an `Arc` of this, so a client is cheap to hand to
234/// another task and never clones the transport.
235pub(crate) struct Core<T> {
236    pub(crate) base_url: Box<str>,
237    pub(crate) headers: http::HeaderMap,
238    pub(crate) timeout: Duration,
239    pub(crate) transport: T,
240}
241
242impl<T: Transport> Core<T> {
243    /// Sends one request, timed out by the client's own timeout.
244    pub(crate) async fn send(
245        &self,
246        method: http::Method,
247        path_and_query: &str,
248        json_body: Option<Bytes>,
249    ) -> Result<http::Response<Bytes>, UnavailableReason> {
250        let uri = format!("{}{path_and_query}", self.base_url);
251        let mut headers = self.headers.clone();
252        if json_body.is_some() && !headers.contains_key(http::header::CONTENT_TYPE) {
253            headers.insert(
254                http::header::CONTENT_TYPE,
255                http::header::HeaderValue::from_static("application/json"),
256            );
257        }
258        let mut request = http::Request::builder()
259            .method(method)
260            .uri(uri)
261            .body(json_body.unwrap_or_default())
262            // Unreachable: the base URL was parsed when the client was built,
263            // and every path segment and query value is percent-encoded.
264            .map_err(|err| UnavailableReason::Transport(TransportError::new(err)))?;
265        *request.headers_mut() = headers;
266
267        // The deadline is the client's own rather than the transport's, so it
268        // applies to an injected transport too.
269        match tokio::time::timeout(self.timeout, self.transport.send(request)).await {
270            Ok(Ok(response)) => Ok(response),
271            Ok(Err(err)) => Err(UnavailableReason::Transport(err)),
272            Err(_elapsed) => Err(UnavailableReason::Timeout(self.timeout)),
273        }
274    }
275}
276
277// Debug by hand: header *values* are bearer tokens and must never be printed.
278impl<T> fmt::Debug for Core<T> {
279    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
280        f.debug_struct("Core")
281            .field("base_url", &self.base_url)
282            .field("header_names", &HeaderNames(&self.headers))
283            .field("timeout", &self.timeout)
284            .finish_non_exhaustive()
285    }
286}
287
288/// The names of a header map, without the values.
289pub(crate) struct HeaderNames<'a>(pub(crate) &'a http::HeaderMap);
290
291impl fmt::Debug for HeaderNames<'_> {
292    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
293        f.debug_list()
294            .entries(self.0.keys().map(http::HeaderName::as_str))
295            .finish()
296    }
297}
298
299/// A path query under construction, in the order the fields are pushed.
300#[derive(Debug, Default)]
301pub(crate) struct Query(String);
302
303impl Query {
304    pub(crate) fn new() -> Self {
305        Self::default()
306    }
307
308    /// Appends `key=value`, percent-encoding the value.
309    pub(crate) fn push_str(&mut self, key: &'static str, value: &str) {
310        self.push_key(key);
311        self.0
312            .push_str(&utf8_percent_encode(value, SEGMENT).to_string());
313    }
314
315    /// Appends `key=value` for a number or a bool (bools print as
316    /// `true`/`false`, as the API expects).
317    pub(crate) fn push_display(&mut self, key: &'static str, value: impl fmt::Display) {
318        self.push_key(key);
319        self.0.push_str(&value.to_string());
320    }
321
322    fn push_key(&mut self, key: &'static str) {
323        self.0.push(if self.0.is_empty() { '?' } else { '&' });
324        self.0.push_str(key);
325        self.0.push('=');
326    }
327
328    /// `""` or `"?k=v&…"`, ready to append to a path.
329    pub(crate) fn finish(self) -> String {
330        self.0
331    }
332}
333
334/// Serializes a request body.
335pub(crate) fn json_body<S: Serialize + ?Sized>(value: &S) -> Result<Bytes, UnavailableReason> {
336    // Unreachable for the request types here: every field is a string, a
337    // number, a bool, or a map.
338    serde_json::to_vec(value)
339        .map(Bytes::from)
340        .map_err(UnavailableReason::Json)
341}
342
343/// A rejected response body as JSON: the parsed value, or — when it is not
344/// JSON at all — its text (empty body included).
345pub(crate) fn error_body(body: &[u8]) -> serde_json::Value {
346    if body.is_empty() {
347        return serde_json::Value::String(String::new());
348    }
349    serde_json::from_slice(body)
350        .unwrap_or_else(|_| serde_json::Value::String(String::from_utf8_lossy(body).into_owned()))
351}
352
353/// Decodes a success body into the endpoint's type.
354pub(crate) fn decode<R: DeserializeOwned>(body: &[u8]) -> Result<R, UnavailableReason> {
355    serde_json::from_slice(body).map_err(UnavailableReason::Json)
356}
357
358#[cfg(test)]
359pub(crate) mod test_support {
360    //! A transport that answers every request the same way and records the
361    //! request targets it saw.
362
363    use std::sync::{Arc, Mutex};
364
365    use bytes::Bytes;
366
367    use crate::transport::{Transport, TransportError};
368
369    /// Answers `status` with `body`, recording every request target.
370    #[derive(Debug, Clone)]
371    pub(crate) struct Recording {
372        status: http::StatusCode,
373        body: Bytes,
374        seen: Arc<Mutex<Vec<String>>>,
375    }
376
377    impl Recording {
378        pub(crate) fn new(status: u16, body: &str) -> Self {
379            Self {
380                status: http::StatusCode::from_u16(status).expect("valid status"),
381                body: Bytes::copy_from_slice(body.as_bytes()),
382                seen: Arc::new(Mutex::new(Vec::new())),
383            }
384        }
385
386        /// A handle on the requests this transport was handed, past and future.
387        pub(crate) fn targets(&self) -> Arc<Mutex<Vec<String>>> {
388            Arc::clone(&self.seen)
389        }
390    }
391
392    impl Transport for Recording {
393        fn send(
394            &self,
395            request: http::Request<Bytes>,
396        ) -> impl Future<Output = Result<http::Response<Bytes>, TransportError>> + Send {
397            let status = self.status;
398            let body = self.body.clone();
399            let seen = Arc::clone(&self.seen);
400            let target = request.uri().path_and_query().map(ToString::to_string);
401            async move {
402                seen.lock().expect("not poisoned").extend(target);
403                http::Response::builder()
404                    .status(status)
405                    .body(body)
406                    .map_err(TransportError::new)
407            }
408        }
409    }
410}
411
412#[cfg(test)]
413mod tests {
414    use super::{ClientBuilder, ConfigError, Query, test_support::Recording};
415    use crate::transport::TransportError;
416    use std::time::Duration;
417
418    #[test]
419    fn build_rejects_base_url_without_scheme() {
420        let builder = ClientBuilder::new("localhost:4001");
421        assert!(matches!(
422            builder.claim_check(),
423            Err(ConfigError::InvalidBaseUrl { .. })
424        ));
425    }
426
427    #[test]
428    fn build_rejects_invalid_header_value() {
429        let client = ClientBuilder::new("http://gateway.invalid")
430            .header("x-a", "bad\nvalue")
431            .claim_check();
432        match client {
433            Err(ConfigError::InvalidHeader { name }) => assert_eq!(name, "x-a"),
434            other => panic!("expected InvalidHeader, got {other:?}"),
435        }
436    }
437
438    #[test]
439    fn build_reports_a_bad_header_before_a_bad_base_url() {
440        let client = ClientBuilder::with_transport("localhost:4001", Recording::new(200, "{}"))
441            .header("x-a", "bad\nvalue")
442            .claim_check();
443        match client {
444            Err(ConfigError::InvalidHeader { name }) => assert_eq!(name, "x-a"),
445            other => panic!("expected InvalidHeader, got {other:?}"),
446        }
447    }
448
449    #[test]
450    fn build_reports_a_transport_failure_before_a_bad_base_url() {
451        let builder = ClientBuilder::<Recording>::connecting(
452            "localhost:4001".to_owned(),
453            Err(ConfigError::Transport(TransportError::new(
454                "no TLS backend",
455            ))),
456        );
457        match builder.claim_check() {
458            Err(ConfigError::Transport(_)) => {}
459            other => panic!("expected Transport, got {other:?}"),
460        }
461    }
462
463    #[test]
464    fn works_on_a_runtime_with_only_the_time_driver() {
465        // Every request is bounded by `tokio::time::timeout`, so the runtime
466        // needs the time driver and nothing more: no IO driver is required
467        // while the transport is injected.
468        let runtime = tokio::runtime::Builder::new_current_thread()
469            .enable_time()
470            .build()
471            .expect("runtime");
472        let client = ClientBuilder::with_transport(
473            "http://gateway.invalid",
474            Recording::new(200, r#"{"status":"ok"}"#),
475        )
476        .claim_check()
477        .expect("valid client");
478        let health = runtime.block_on(client.health()).expect("healthy");
479        assert_eq!(health.status, "ok");
480    }
481
482    #[test]
483    fn debug_output_omits_header_values() {
484        let builder =
485            ClientBuilder::with_transport("http://gateway.invalid", Recording::new(200, "{}"))
486                .header("authorization", "Bearer s3cret");
487        let builder_debug = format!("{builder:?}");
488        assert!(builder_debug.contains("authorization"), "{builder_debug}");
489        assert!(!builder_debug.contains("s3cret"), "{builder_debug}");
490
491        let client = builder.claim_check().expect("valid client");
492        let client_debug = format!("{client:?}");
493        assert!(client_debug.contains("authorization"), "{client_debug}");
494        assert!(!client_debug.contains("s3cret"), "{client_debug}");
495    }
496
497    #[tokio::test]
498    async fn trailing_slash_in_base_url_is_ignored() {
499        let transport = Recording::new(200, r#"{"status":"ok"}"#);
500        let targets = transport.targets();
501        let client = ClientBuilder::with_transport("http://gateway.invalid/", transport)
502            .timeout(Duration::from_secs(5))
503            .claim_check()
504            .expect("valid client");
505        client.health().await.expect("healthy");
506        assert_eq!(
507            targets.lock().expect("not poisoned").as_slice(),
508            ["/health"]
509        );
510    }
511
512    #[test]
513    fn query_percent_encodes_values() {
514        let mut query = Query::new();
515        query.push_display("enabled", true);
516        query.push_str("cursor", "a b&c/d");
517        assert_eq!(query.finish(), "?enabled=true&cursor=a%20b%26c%2Fd");
518    }
519}