Skip to main content

ic_bn_lib/http/client/
cli.rs

1use std::time::Duration;
2
3use clap::Args;
4use humantime::parse_duration;
5
6use crate::http::client::{ClientOptions, HttpVersion};
7
8/// HTTP Client CLI
9#[derive(Args, Clone, Debug, Eq, PartialEq)]
10pub struct HttpClientCli {
11    /// Timeout for HTTP connection phase
12    #[clap(env, long, default_value = "5s", value_parser = parse_duration)]
13    pub http_client_timeout_connect: Duration,
14
15    /// Timeout for a single read request
16    #[clap(env, long, default_value = "15s", value_parser = parse_duration)]
17    pub http_client_timeout_read: Duration,
18
19    /// Timeout for the whole HTTP call: this includes connecting, sending request,
20    /// receiving response etc.
21    #[clap(env, long, default_value = "60s", value_parser = parse_duration)]
22    pub http_client_timeout: Duration,
23
24    /// How long to keep idle HTTP connections open.
25    /// Default is 90s.
26    #[clap(env, long, value_parser = parse_duration)]
27    pub http_client_pool_idle_timeout: Option<Duration>,
28
29    /// How many idle connections maximum to keep per-host.
30    /// Default is unlimited.
31    #[clap(env, long)]
32    pub http_client_pool_idle_max: Option<usize>,
33
34    /// TCP Keepalive delay.
35    /// It's the time between when the connection became idle and when the keepalive packet is sent.
36    /// If not specified - keepalives are disabled.
37    #[clap(env, long, value_parser = parse_duration)]
38    pub http_client_tcp_keepalive_delay: Option<Duration>,
39
40    /// TCP Keepalive interval.
41    /// If the acknowledgement for the 1st keepalive wasn't received - retry after this time.
42    /// If not specified - use system default.
43    #[clap(env, long, value_parser = parse_duration)]
44    pub http_client_tcp_keepalive_interval: Option<Duration>,
45
46    /// TCP Keepalive retries.
47    /// If this many keepalives in a row weren't acknowledged - close the connection.
48    /// If not specified - use system default.
49    #[clap(env, long)]
50    pub http_client_tcp_keepalive_retries: Option<u32>,
51
52    /// HTTP2 Keepalive interval.
53    /// If not specified - the keepalives are not sent.
54    #[clap(env, long, value_parser = parse_duration)]
55    pub http_client_http2_keepalive: Option<Duration>,
56
57    /// HTTP2 Keepalive timeout
58    #[clap(env, long, value_parser = parse_duration)]
59    pub http_client_http2_keepalive_timeout: Option<Duration>,
60
61    /// Whether to send HTTP2 Keepalives while connection is idle (no active streams)
62    #[clap(env, long)]
63    pub http_client_http2_keepalive_idle: bool,
64
65    /// Which HTTP versions to use.
66    /// Can be "http1", "http2" or "all". Defaults to "all".
67    #[clap(env, long, default_value = "all")]
68    pub http_client_http_version: HttpVersion,
69
70    /// If the target hostname resolves to both IPv6 and IPv4,
71    /// we first try the preferred family and, if the connection isn't established
72    /// in this time, we in parallel try the other family.
73    /// See RFC6555.
74    #[clap(env, long, value_parser = parse_duration, default_value = "500ms")]
75    pub http_client_happy_eyeballs_timeout: Duration,
76
77    /// Fixed name to use when checking TLS certificates, instead of the host name.
78    #[clap(env, long)]
79    pub http_client_tls_fixed_name: Option<String>,
80}
81
82impl From<&HttpClientCli> for ClientOptions {
83    fn from(c: &HttpClientCli) -> Self {
84        Self {
85            timeout_connect: c.http_client_timeout_connect,
86            timeout_read: c.http_client_timeout_read,
87            timeout: c.http_client_timeout,
88            pool_idle_timeout: c.http_client_pool_idle_timeout,
89            pool_idle_max: c.http_client_pool_idle_max,
90            tcp_keepalive_delay: c.http_client_tcp_keepalive_delay,
91            tcp_keepalive_interval: c.http_client_tcp_keepalive_interval,
92            tcp_keepalive_retries: c.http_client_tcp_keepalive_retries,
93            http2_keepalive: c.http_client_http2_keepalive,
94            http2_keepalive_timeout: c.http_client_http2_keepalive_timeout,
95            http2_keepalive_idle: c.http_client_http2_keepalive_idle,
96            happy_eyeballs_timeout: c.http_client_happy_eyeballs_timeout,
97            http_version: c.http_client_http_version,
98            user_agent: "ic-bn-lib".into(),
99            tls_config: None,
100            tls_fixed_name: c.http_client_tls_fixed_name.clone(),
101            dns_overrides: vec![],
102        }
103    }
104}
105
106#[cfg(test)]
107mod test {
108    use clap::Parser;
109
110    use super::*;
111
112    /// `HttpClientCli` is an `Args` group, so it needs a `Parser` host to be parsed standalone.
113    #[derive(Parser)]
114    struct Cli {
115        #[command(flatten)]
116        http_client: HttpClientCli,
117    }
118
119    fn parse(args: &[&str]) -> Result<HttpClientCli, clap::Error> {
120        let mut argv = vec!["test"];
121        argv.extend_from_slice(args);
122        Cli::try_parse_from(argv).map(|x| x.http_client)
123    }
124
125    #[test]
126    fn test_defaults() {
127        let c = parse(&[]).unwrap();
128
129        assert_eq!(c.http_client_timeout_connect, Duration::from_secs(5));
130        assert_eq!(c.http_client_timeout_read, Duration::from_secs(15));
131        assert_eq!(c.http_client_timeout, Duration::from_secs(60));
132        assert_eq!(
133            c.http_client_happy_eyeballs_timeout,
134            Duration::from_millis(500)
135        );
136        assert_eq!(c.http_client_http_version, HttpVersion::All);
137
138        // Everything optional stays unset and the bool flag stays off
139        assert_eq!(c.http_client_pool_idle_timeout, None);
140        assert_eq!(c.http_client_pool_idle_max, None);
141        assert_eq!(c.http_client_tcp_keepalive_delay, None);
142        assert_eq!(c.http_client_tcp_keepalive_interval, None);
143        assert_eq!(c.http_client_tcp_keepalive_retries, None);
144        assert_eq!(c.http_client_http2_keepalive, None);
145        assert_eq!(c.http_client_http2_keepalive_timeout, None);
146        assert!(!c.http_client_http2_keepalive_idle);
147        assert_eq!(c.http_client_tls_fixed_name, None);
148    }
149
150    /// Every field gets a distinct value so a mis-wired `--flag` or a swapped field
151    /// in `From<&HttpClientCli>` shows up.
152    fn full_args() -> Vec<&'static str> {
153        vec![
154            "--http-client-timeout-connect=1s",
155            "--http-client-timeout-read=2s",
156            "--http-client-timeout=3s",
157            "--http-client-pool-idle-timeout=4s",
158            "--http-client-pool-idle-max=11",
159            "--http-client-tcp-keepalive-delay=5s",
160            "--http-client-tcp-keepalive-interval=6s",
161            "--http-client-tcp-keepalive-retries=12",
162            "--http-client-http2-keepalive=7s",
163            "--http-client-http2-keepalive-timeout=8s",
164            "--http-client-http2-keepalive-idle",
165            "--http-client-http-version=http2",
166            "--http-client-happy-eyeballs-timeout=9s",
167            "--http-client-tls-fixed-name=foo.bar",
168        ]
169    }
170
171    #[test]
172    fn test_explicit_values() {
173        let c = parse(&full_args()).unwrap();
174
175        assert_eq!(c.http_client_timeout_connect, Duration::from_secs(1));
176        assert_eq!(c.http_client_timeout_read, Duration::from_secs(2));
177        assert_eq!(c.http_client_timeout, Duration::from_secs(3));
178        assert_eq!(
179            c.http_client_pool_idle_timeout,
180            Some(Duration::from_secs(4))
181        );
182        assert_eq!(c.http_client_pool_idle_max, Some(11));
183        assert_eq!(
184            c.http_client_tcp_keepalive_delay,
185            Some(Duration::from_secs(5))
186        );
187        assert_eq!(
188            c.http_client_tcp_keepalive_interval,
189            Some(Duration::from_secs(6))
190        );
191        assert_eq!(c.http_client_tcp_keepalive_retries, Some(12));
192        assert_eq!(c.http_client_http2_keepalive, Some(Duration::from_secs(7)));
193        assert_eq!(
194            c.http_client_http2_keepalive_timeout,
195            Some(Duration::from_secs(8))
196        );
197        assert!(c.http_client_http2_keepalive_idle);
198        assert_eq!(c.http_client_http_version, HttpVersion::Http2);
199        assert_eq!(c.http_client_happy_eyeballs_timeout, Duration::from_secs(9));
200        assert_eq!(c.http_client_tls_fixed_name.as_deref(), Some("foo.bar"));
201    }
202
203    #[test]
204    fn test_humantime_parser_accepts_compound_and_subsecond() {
205        let c = parse(&[
206            "--http-client-timeout=1m30s",
207            "--http-client-timeout-connect=250ms",
208            "--http-client-happy-eyeballs-timeout=1h",
209        ])
210        .unwrap();
211
212        assert_eq!(c.http_client_timeout, Duration::from_secs(90));
213        assert_eq!(c.http_client_timeout_connect, Duration::from_millis(250));
214        assert_eq!(
215            c.http_client_happy_eyeballs_timeout,
216            Duration::from_secs(3600)
217        );
218    }
219
220    #[test]
221    fn test_invalid_values_are_rejected() {
222        // Bare numbers have no unit, so humantime rejects them
223        assert!(parse(&["--http-client-timeout=60"]).is_err());
224        assert!(parse(&["--http-client-timeout=notaduration"]).is_err());
225        assert!(parse(&["--http-client-timeout="]).is_err());
226        // Negative durations aren't representable
227        assert!(parse(&["--http-client-timeout=-5s"]).is_err());
228        // Optional duration fields use the same parser
229        assert!(parse(&["--http-client-pool-idle-timeout=bogus"]).is_err());
230        assert!(parse(&["--http-client-happy-eyeballs-timeout=1 potato"]).is_err());
231
232        // HttpVersion only accepts the snake_case strum spellings
233        assert!(parse(&["--http-client-http-version=http3"]).is_err());
234        assert!(parse(&["--http-client-http-version=Http1"]).is_err());
235
236        // Numeric fields
237        assert!(parse(&["--http-client-pool-idle-max=-1"]).is_err());
238        assert!(parse(&["--http-client-pool-idle-max=lots"]).is_err());
239        assert!(parse(&["--http-client-tcp-keepalive-retries=1.5"]).is_err());
240
241        // Unknown flags
242        assert!(parse(&["--http-client-nope=1"]).is_err());
243        // The bool flag takes no value
244        assert!(parse(&["--http-client-http2-keepalive-idle=yes"]).is_err());
245    }
246
247    #[test]
248    fn test_client_options_conversion() {
249        let c = parse(&full_args()).unwrap();
250        let o = ClientOptions::from(&c);
251
252        assert_eq!(o.timeout_connect, Duration::from_secs(1));
253        assert_eq!(o.timeout_read, Duration::from_secs(2));
254        assert_eq!(o.timeout, Duration::from_secs(3));
255        assert_eq!(o.pool_idle_timeout, Some(Duration::from_secs(4)));
256        assert_eq!(o.pool_idle_max, Some(11));
257        assert_eq!(o.tcp_keepalive_delay, Some(Duration::from_secs(5)));
258        assert_eq!(o.tcp_keepalive_interval, Some(Duration::from_secs(6)));
259        assert_eq!(o.tcp_keepalive_retries, Some(12));
260        assert_eq!(o.http2_keepalive, Some(Duration::from_secs(7)));
261        assert_eq!(o.http2_keepalive_timeout, Some(Duration::from_secs(8)));
262        assert!(o.http2_keepalive_idle);
263        assert_eq!(o.happy_eyeballs_timeout, Duration::from_secs(9));
264        assert_eq!(o.http_version, HttpVersion::Http2);
265        assert_eq!(o.tls_fixed_name.as_deref(), Some("foo.bar"));
266
267        // Not derived from the CLI
268        assert_eq!(o.user_agent, "ic-bn-lib");
269        assert!(o.tls_config.is_none());
270        assert!(o.dns_overrides.is_empty());
271    }
272
273    /// The conversion must not silently fall back to `ClientOptions::default()`
274    /// for the fields the CLI leaves unset.
275    #[test]
276    fn test_client_options_conversion_defaults() {
277        let o = ClientOptions::from(&parse(&[]).unwrap());
278        let d = ClientOptions::default();
279
280        // CLI defaults deliberately differ from `ClientOptions::default()`
281        assert_eq!(o.timeout_connect, Duration::from_secs(5));
282        assert_ne!(o.timeout_connect, d.timeout_connect);
283        assert_eq!(o.timeout_read, Duration::from_secs(15));
284        assert_ne!(o.timeout_read, d.timeout_read);
285        assert_eq!(o.timeout, Duration::from_secs(60));
286        assert_ne!(o.timeout, d.timeout);
287        assert_ne!(o.user_agent, d.user_agent);
288
289        assert_eq!(o.pool_idle_timeout, None);
290        assert_eq!(o.pool_idle_max, None);
291        assert!(!o.http2_keepalive_idle);
292        assert_eq!(o.http_version, HttpVersion::All);
293        assert_eq!(o.tls_fixed_name, None);
294    }
295}