1use 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
17pub(crate) const SEGMENT: &AsciiSet = &NON_ALPHANUMERIC
20 .remove(b'-')
21 .remove(b'.')
22 .remove(b'_')
23 .remove(b'~');
24
25const DEFAULT_TIMEOUT: Duration = Duration::from_secs(10);
28
29#[derive(Debug, thiserror::Error)]
31#[non_exhaustive]
32pub enum ConfigError {
33 #[error("invalid base URL {url:?}: want an absolute http(s) URL")]
35 InvalidBaseUrl {
36 url: String,
38 },
39 #[error("invalid header {name:?}")]
41 InvalidHeader {
42 name: String,
44 },
45 #[error("could not build the HTTP client")]
47 Transport(#[source] TransportError),
48}
49
50#[derive(Debug, thiserror::Error)]
56#[non_exhaustive]
57pub enum UnavailableReason {
58 #[error("unexpected HTTP status {0}")]
61 Status(http::StatusCode),
62 #[error("no response within {0:?}")]
64 Timeout(Duration),
65 #[error("transport failed")]
67 Transport(#[source] TransportError),
68 #[error("invalid JSON")]
70 Json(#[source] serde_json::Error),
71}
72
73pub 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
89impl<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 #[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 #[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 #[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 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 #[must_use]
157 pub fn headers(mut self, headers: http::HeaderMap) -> Self {
158 self.headers.extend(headers);
159 self
160 }
161
162 #[must_use]
164 pub fn timeout(mut self, timeout: Duration) -> Self {
165 self.timeout = timeout;
166 self
167 }
168
169 pub fn claim_check(self) -> Result<ClaimCheckClient<T>, ConfigError> {
177 Ok(ClaimCheckClient::from_core(Arc::new(self.into_core()?)))
178 }
179
180 pub fn routes(self) -> Result<RoutesClient<T>, ConfigError> {
186 Ok(RoutesClient::from_core(Arc::new(self.into_core()?)))
187 }
188
189 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 if let Some(error) = self.error {
202 return Err(error);
203 }
204 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 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
231pub(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 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 .map_err(|err| UnavailableReason::Transport(TransportError::new(err)))?;
265 *request.headers_mut() = headers;
266
267 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
277impl<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
288pub(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#[derive(Debug, Default)]
301pub(crate) struct Query(String);
302
303impl Query {
304 pub(crate) fn new() -> Self {
305 Self::default()
306 }
307
308 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 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 pub(crate) fn finish(self) -> String {
330 self.0
331 }
332}
333
334pub(crate) fn json_body<S: Serialize + ?Sized>(value: &S) -> Result<Bytes, UnavailableReason> {
336 serde_json::to_vec(value)
339 .map(Bytes::from)
340 .map_err(UnavailableReason::Json)
341}
342
343pub(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
353pub(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 use std::sync::{Arc, Mutex};
364
365 use bytes::Bytes;
366
367 use crate::transport::{Transport, TransportError};
368
369 #[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 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 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}