Skip to main content

ic_bn_lib/http/client/
mod.rs

1pub mod cli;
2#[cfg(feature = "clients-hyper")]
3pub mod clients_hyper;
4pub mod clients_reqwest;
5
6use std::{fmt, net::SocketAddr, sync::Arc, time::Duration};
7
8use async_trait::async_trait;
9use http::HeaderValue;
10use prometheus::{
11    HistogramVec, IntCounterVec, IntGaugeVec, Registry, register_histogram_vec_with_registry,
12    register_int_counter_vec_with_registry, register_int_gauge_vec_with_registry,
13};
14use strum::{Display, EnumString};
15
16use crate::http::Error;
17
18/// Generic HTTP client trait that is using Reqwest types
19#[cfg_attr(test, mockall::automock)]
20#[async_trait]
21pub trait Client: Send + Sync + fmt::Debug {
22    async fn execute(&self, req: reqwest::Request) -> Result<reqwest::Response, reqwest::Error>;
23}
24
25/// Generic HTTP client trait that is using `http` crate types
26#[async_trait]
27pub trait ClientHttp<B1, B2 = axum::body::Body>: Send + Sync + fmt::Debug {
28    async fn execute(&self, req: http::Request<B1>) -> Result<http::Response<B2>, Error>;
29}
30
31/// HTTP versions to use
32#[derive(Debug, Clone, Copy, Eq, PartialEq, Display, EnumString)]
33#[strum(serialize_all = "snake_case")]
34pub enum HttpVersion {
35    Http1,
36    Http2,
37    All,
38}
39
40/// HTTP client options
41#[derive(Debug, Clone)]
42pub struct ClientOptions {
43    pub timeout_connect: Duration,
44    pub timeout_read: Duration,
45    pub timeout: Duration,
46    pub pool_idle_timeout: Option<Duration>,
47    pub pool_idle_max: Option<usize>,
48    pub tcp_keepalive_delay: Option<Duration>,
49    pub tcp_keepalive_interval: Option<Duration>,
50    pub tcp_keepalive_retries: Option<u32>,
51    pub http2_keepalive: Option<Duration>,
52    pub http2_keepalive_timeout: Option<Duration>,
53    pub http2_keepalive_idle: bool,
54    pub happy_eyeballs_timeout: Duration,
55    pub http_version: HttpVersion,
56    pub user_agent: String,
57    pub tls_config: Option<rustls::ClientConfig>,
58    pub tls_fixed_name: Option<String>,
59    pub dns_overrides: Vec<(String, SocketAddr)>,
60}
61
62impl Default for ClientOptions {
63    fn default() -> Self {
64        Self {
65            timeout_connect: Duration::from_secs(10),
66            timeout_read: Duration::from_secs(60),
67            timeout: Duration::from_secs(120),
68            pool_idle_timeout: None,
69            pool_idle_max: None,
70            tcp_keepalive_delay: None,
71            tcp_keepalive_interval: None,
72            tcp_keepalive_retries: None,
73            http2_keepalive: None,
74            http2_keepalive_timeout: None,
75            http2_keepalive_idle: false,
76            happy_eyeballs_timeout: Duration::from_millis(500),
77            http_version: HttpVersion::All,
78            user_agent: "Crab".into(),
79            tls_config: None,
80            tls_fixed_name: None,
81            dns_overrides: vec![],
82        }
83    }
84}
85
86/// HTTP Client stats
87#[derive(Debug, Clone)]
88pub struct ClientStats {
89    pub pool_size: usize,
90    pub outstanding: usize,
91}
92
93/// Trait to get `ClientStats`
94pub trait Stats {
95    fn stats(&self) -> ClientStats;
96}
97
98/// `Client` that also emits `Stats`
99pub trait ClientWithStats: Client + Stats {
100    fn to_client(self: Arc<Self>) -> Arc<dyn Client>;
101}
102
103/// HTTP Client metrics
104#[derive(Clone, Debug)]
105struct Metrics {
106    requests: IntCounterVec,
107    requests_inflight: IntGaugeVec,
108    request_duration: HistogramVec,
109}
110
111impl Metrics {
112    pub fn new(registry: &Registry) -> Self {
113        const LABELS: &[&str] = &["host"];
114
115        Self {
116            requests: register_int_counter_vec_with_registry!(
117                "http_client_requests_total",
118                "Counts the number of requests",
119                LABELS,
120                registry
121            )
122            .unwrap(),
123
124            requests_inflight: register_int_gauge_vec_with_registry!(
125                "http_client_requests_inflight",
126                "Counts the number of requests that are currently executed",
127                LABELS,
128                registry
129            )
130            .unwrap(),
131
132            request_duration: register_histogram_vec_with_registry!(
133                "http_client_request_duration_sec",
134                "Records the duration of requests in seconds",
135                LABELS,
136                [0.01, 0.05, 0.1, 0.2, 0.4, 0.8, 1.6, 3.2].to_vec(),
137                registry
138            )
139            .unwrap(),
140        }
141    }
142}
143
144/// Create an HTTP header for Basic auth
145pub fn basic_auth<U, P>(username: U, password: Option<P>) -> HeaderValue
146where
147    U: fmt::Display,
148    P: fmt::Display,
149{
150    use base64::prelude::BASE64_STANDARD;
151    use base64::write::EncoderWriter;
152    use std::io::Write;
153
154    let mut buf = b"Basic ".to_vec();
155    {
156        let mut encoder = EncoderWriter::new(&mut buf, &BASE64_STANDARD);
157        let _ = write!(encoder, "{username}:");
158        if let Some(password) = password {
159            let _ = write!(encoder, "{password}");
160        }
161    }
162
163    let mut header = HeaderValue::from_bytes(&buf).expect("base64 is always valid HeaderValue");
164    header.set_sensitive(true);
165    header
166}
167
168#[cfg(test)]
169mod test {
170    use std::str::FromStr;
171
172    use super::*;
173
174    #[test]
175    fn test_basic_auth() {
176        // RFC 7617's own example vector
177        assert_eq!(
178            basic_auth("Aladdin", Some("open sesame")),
179            "Basic QWxhZGRpbjpvcGVuIHNlc2FtZQ=="
180        );
181
182        assert_eq!(basic_auth("user", Some("pass")), "Basic dXNlcjpwYXNz");
183
184        // A missing password still has to emit the ":" separator...
185        assert_eq!(basic_auth("user", None::<&str>), "Basic dXNlcjo=");
186        // ...which makes it indistinguishable from an empty one
187        assert_eq!(
188            basic_auth("user", Some("")),
189            basic_auth("user", None::<&str>)
190        );
191
192        // Empty username
193        assert_eq!(basic_auth("", Some("pass")), "Basic OnBhc3M=");
194        assert_eq!(basic_auth("", None::<&str>), "Basic Og==");
195
196        // Any Display type is accepted, not just strings
197        assert_eq!(basic_auth(42, Some(7)), "Basic NDI6Nw==");
198
199        // Non-ASCII is passed through as UTF-8 bytes before base64
200        assert_eq!(basic_auth("üser", Some("päss")), "Basic w7xzZXI6cMOkc3M=");
201    }
202
203    #[test]
204    fn test_basic_auth_is_sensitive() {
205        assert!(basic_auth("user", Some("pass")).is_sensitive());
206        assert!(basic_auth("user", None::<&str>).is_sensitive());
207    }
208
209    #[test]
210    fn test_http_version_display_from_str_roundtrip() {
211        for (v, s) in [
212            (HttpVersion::Http1, "http1"),
213            (HttpVersion::Http2, "http2"),
214            (HttpVersion::All, "all"),
215        ] {
216            assert_eq!(v.to_string(), s);
217            assert_eq!(HttpVersion::from_str(s).unwrap(), v);
218            assert_eq!(HttpVersion::from_str(&v.to_string()).unwrap(), v);
219        }
220
221        // Only the snake_case spellings are accepted
222        assert!(HttpVersion::from_str("Http1").is_err());
223        assert!(HttpVersion::from_str("http3").is_err());
224        assert!(HttpVersion::from_str("").is_err());
225        assert!(HttpVersion::from_str("ALL").is_err());
226    }
227
228    #[test]
229    fn test_client_options_default() {
230        let o = ClientOptions::default();
231
232        assert_eq!(o.timeout_connect, Duration::from_secs(10));
233        assert_eq!(o.timeout_read, Duration::from_secs(60));
234        assert_eq!(o.timeout, Duration::from_secs(120));
235        assert_eq!(o.happy_eyeballs_timeout, Duration::from_millis(500));
236        assert_eq!(o.http_version, HttpVersion::All);
237        assert_eq!(o.user_agent, "Crab");
238
239        assert_eq!(o.pool_idle_timeout, None);
240        assert_eq!(o.pool_idle_max, None);
241        assert_eq!(o.tcp_keepalive_delay, None);
242        assert_eq!(o.tcp_keepalive_interval, None);
243        assert_eq!(o.tcp_keepalive_retries, None);
244        assert_eq!(o.http2_keepalive, None);
245        assert_eq!(o.http2_keepalive_timeout, None);
246        assert!(!o.http2_keepalive_idle);
247        assert!(o.tls_config.is_none());
248        assert_eq!(o.tls_fixed_name, None);
249        assert!(o.dns_overrides.is_empty());
250    }
251
252    #[test]
253    fn test_metrics_registration() {
254        let registry = Registry::new();
255        let metrics = Metrics::new(&registry);
256
257        // Touch every metric so the families carry a child with our label
258        metrics.requests.with_label_values(&["foo:443"]).inc_by(3);
259        metrics
260            .requests_inflight
261            .with_label_values(&["foo:443"])
262            .set(5);
263        metrics
264            .request_duration
265            .with_label_values(&["foo:443"])
266            .observe(0.5);
267
268        let families = registry.gather();
269        let mut names = families
270            .iter()
271            .map(|x| x.name().to_owned())
272            .collect::<Vec<_>>();
273        names.sort();
274        assert_eq!(
275            names,
276            vec![
277                "http_client_request_duration_sec",
278                "http_client_requests_inflight",
279                "http_client_requests_total",
280            ]
281        );
282
283        // Every metric is labelled by host and only by host
284        for f in &families {
285            assert_eq!(f.get_metric().len(), 1);
286            let labels = f.get_metric()[0].get_label();
287            assert_eq!(labels.len(), 1);
288            assert_eq!(labels[0].name(), "host");
289            assert_eq!(labels[0].value(), "foo:443");
290        }
291
292        let by_name = |name: &str| {
293            families
294                .iter()
295                .find(|x| x.name() == name)
296                .unwrap()
297                .get_metric()[0]
298                .clone()
299        };
300
301        assert_eq!(
302            by_name("http_client_requests_total").get_counter().value(),
303            3.0
304        );
305        assert_eq!(
306            by_name("http_client_requests_inflight").get_gauge().value(),
307            5.0
308        );
309
310        let hist = by_name("http_client_request_duration_sec");
311        let hist = hist.get_histogram();
312        assert_eq!(hist.get_sample_count(), 1);
313        assert_eq!(
314            hist.get_bucket()
315                .iter()
316                .map(|x| x.upper_bound())
317                .collect::<Vec<_>>(),
318            vec![0.01, 0.05, 0.1, 0.2, 0.4, 0.8, 1.6, 3.2]
319        );
320    }
321}