Skip to main content

ntex/client/
cfg.rs

1use std::{fmt, time::Duration};
2
3use base64::{Engine, engine::general_purpose::STANDARD as base64};
4
5use crate::http::header::{self, HeaderName, HeaderValue};
6use crate::http::{HeaderMap, error::HttpError};
7use crate::service::cfg::{CfgContext, Configuration};
8use crate::time::{Millis, Seconds};
9
10#[derive(Debug)]
11/// Runtime configuration for an HTTP [`Client`](super::Client).
12///
13/// The configuration is stored in [`SharedCfg`](crate::SharedCfg) and can be
14/// supplied before constructing a client with [`Client::with_config`](super::Client::with_config)
15/// or [`ClientBuilder::build`](super::ClientBuilder::build).
16pub struct ClientConfig {
17    pub(super) headers: HeaderMap,
18    pub(super) timeout: Millis,
19    pub(super) pl_limit: usize,
20    pub(super) pl_timeout: Millis,
21    pub(super) h1_lifetime: Duration,
22    pub(super) h1_keep_alive: Duration,
23    pub(super) h1_limit: usize,
24    pub(super) h2_lifetime: Duration,
25    pub(super) h2_keep_alive: Duration,
26    pub(super) h2_limit: usize,
27    pub(super) h2_max_streams: u32,
28
29    config: CfgContext,
30}
31
32impl Default for ClientConfig {
33    fn default() -> Self {
34        Self::new()
35    }
36}
37
38impl Configuration for ClientConfig {
39    const NAME: &str = "Http client configuration";
40
41    fn ctx(&self) -> &CfgContext {
42        &self.config
43    }
44
45    fn set_ctx(&mut self, ctx: CfgContext) {
46        self.config = ctx;
47    }
48}
49
50impl ClientConfig {
51    #[must_use]
52    /// Creates an HTTP client configuration with default values.
53    pub fn new() -> ClientConfig {
54        ClientConfig {
55            headers: HeaderMap::new(),
56            timeout: Millis(5_000),
57            pl_limit: 262_144,
58            pl_timeout: Millis(10_000),
59            h1_lifetime: Duration::from_secs(75),
60            h1_keep_alive: Duration::from_secs(15),
61            h1_limit: 8,
62            h2_lifetime: Duration::from_hours(1),
63            h2_keep_alive: Duration::from_mins(1),
64            h2_limit: 16,
65            h2_max_streams: 100,
66
67            config: CfgContext::default(),
68        }
69    }
70
71    /// Returns the headers added to every request.
72    pub fn headers(&self) -> &HeaderMap {
73        &self.headers
74    }
75
76    /// Returns the response-header timeout.
77    pub fn response_timeout(&self) -> Millis {
78        self.timeout
79    }
80
81    /// Returns the maximum response payload size.
82    ///
83    /// A value of zero disables the limit.
84    pub fn response_payload_limit(&self) -> usize {
85        self.pl_limit
86    }
87
88    /// Returns the timeout for reading a complete response payload.
89    pub fn response_payload_timeout(&self) -> Millis {
90        self.pl_timeout
91    }
92
93    /// Returns the maximum number of simultaneous HTTP/1 connections per connection pool.
94    pub fn h1_connection_limit(&self) -> usize {
95        self.h1_limit
96    }
97
98    /// Returns the maximum number of HTTP/2 connections per host.
99    pub fn h2_connection_limit(&self) -> usize {
100        self.h2_limit
101    }
102
103    /// Returns the maximum number of concurrent requests per HTTP/2 connection.
104    pub fn h2_max_streams(&self) -> u32 {
105        self.h2_max_streams
106    }
107
108    /// Returns the keep-alive period for idle HTTP/2 connections.
109    pub fn h2_keepalive(&self) -> Seconds {
110        Seconds(self.h2_keep_alive.as_secs().try_into().unwrap_or(u16::MAX))
111    }
112
113    /// Returns the maximum lifetime of an HTTP/2 connection.
114    pub fn h2_lifetime(&self) -> Seconds {
115        Seconds(self.h2_lifetime.as_secs().try_into().unwrap_or(u16::MAX))
116    }
117
118    #[must_use]
119    /// Sets the maximum number of simultaneous connections per connection pool.
120    ///
121    /// The limit is shared by all hosts. A client keeps separate pools for
122    /// plain and TLS connections, and each pool has its own limit. The limit
123    /// counts HTTP/1 connections in use and connections being opened;
124    /// HTTP/2 connections are limited by
125    /// [`set_h2_connection_limit`](Self::set_h2_connection_limit). A value of
126    /// zero disables the limit. The default is 8.
127    pub fn set_h1_connection_limit(mut self, limit: usize) -> Self {
128        self.h1_limit = limit;
129        self
130    }
131
132    #[must_use]
133    /// Sets the keep-alive period for idle pooled HTTP/1 connections.
134    ///
135    /// HTTP/2 connections use [`set_h2_keepalive`](Self::set_h2_keepalive).
136    /// A pooled connection that has been idle longer than this period is not
137    /// reused. Expiration is checked lazily, when a connection for the same
138    /// host is next requested; the expired connection is closed at that point.
139    /// A zero duration disables the idle check; use
140    /// [`ClientRequest::force_close`](super::ClientRequest::force_close) to
141    /// avoid reusing a connection. The default is 15 seconds.
142    pub fn set_h1_keepalive<T: Into<Seconds>>(mut self, dur: T) -> Self {
143        self.h1_keep_alive = dur.into().into();
144        self
145    }
146
147    #[must_use]
148    /// Sets the maximum lifetime of a pooled HTTP/1 connection.
149    ///
150    /// HTTP/2 connections use [`set_h2_lifetime`](Self::set_h2_lifetime).
151    /// A connection older than this period is not reused, regardless of how
152    /// recently it was used. Like the keep-alive period, this is checked when a
153    /// connection for the same host is next requested. A zero duration disables
154    /// the limit. The default is 75 seconds.
155    pub fn set_h1_lifetime<T: Into<Seconds>>(mut self, dur: T) -> Self {
156        self.h1_lifetime = dur.into().into();
157        self
158    }
159
160    #[must_use]
161    /// Sets the maximum number of HTTP/2 connections per host.
162    ///
163    /// HTTP/2 connections are shared by concurrent requests. A new connection
164    /// to a host is opened only when every existing HTTP/2 connection to that
165    /// host has reached its stream limit, see
166    /// [`set_h2_max_streams`](Self::set_h2_max_streams). When the limit is
167    /// reached, requests wait for a free stream.
168    ///
169    /// Requests on established HTTP/2 connections do not count against
170    /// [`set_h1_connection_limit`](Self::set_h1_connection_limit); opening a new
171    /// connection does, because the protocol is not known until the
172    /// connection is established. A value of zero disables the limit.
173    /// The default is 16.
174    pub fn set_h2_connection_limit(mut self, limit: usize) -> Self {
175        self.h2_limit = limit;
176        self
177    }
178
179    #[must_use]
180    /// Sets the maximum number of concurrent requests per HTTP/2 connection.
181    ///
182    /// The peer's `SETTINGS_MAX_CONCURRENT_STREAMS` also applies; the lower of
183    /// the two is used. A value of zero uses only the peer's setting.
184    /// The default is 100.
185    pub fn set_h2_max_streams(mut self, limit: u32) -> Self {
186        self.h2_max_streams = limit;
187        self
188    }
189
190    #[must_use]
191    /// Sets the keep-alive period for idle HTTP/2 connections.
192    ///
193    /// An HTTP/2 connection is idle when it has no in-flight requests; the
194    /// period is measured from the completion of its last request, including
195    /// the response payload. An idle connection older than this period is
196    /// closed when a connection for the same host is next requested.
197    /// A zero duration disables the idle check. The default is 60 seconds.
198    pub fn set_h2_keepalive<T: Into<Seconds>>(mut self, dur: T) -> Self {
199        self.h2_keep_alive = dur.into().into();
200        self
201    }
202
203    #[must_use]
204    /// Sets the maximum lifetime of an HTTP/2 connection.
205    ///
206    /// An HTTP/2 connection older than this period is not used for new
207    /// requests and is closed gracefully, after its in-flight requests
208    /// complete. This is checked when a connection for the same host is next
209    /// requested. A zero duration disables the limit. The default is 1 hour.
210    pub fn set_h2_lifetime<T: Into<Seconds>>(mut self, dur: T) -> Self {
211        self.h2_lifetime = dur.into().into();
212        self
213    }
214
215    #[must_use]
216    /// Sets the response-header timeout.
217    ///
218    /// The timeout covers receiving the response head after the request has
219    /// been sent. It does not cover waiting for a pooled connection,
220    /// connecting, sending the request body, or reading the response body;
221    /// the last is bounded separately by
222    /// [`set_response_payload_timeout`](Self::set_response_payload_timeout).
223    /// A zero duration disables the timeout. The default is 5 seconds.
224    pub fn set_response_timeout<T: Into<Millis>>(mut self, timeout: T) -> Self {
225        self.timeout = timeout.into();
226        self
227    }
228
229    #[must_use]
230    /// Disables the response-header timeout.
231    ///
232    /// This is the same as `set_response_timeout(Millis::ZERO)`. Only the
233    /// wait for the response head becomes unbounded. The response payload
234    /// timeout still applies to [`ClientResponse::body`](super::ClientResponse::body)
235    /// and [`ClientResponse::json`](super::ClientResponse::json); disable it
236    /// with `set_response_payload_timeout(Millis::ZERO)`. Connect and I/O
237    /// timeouts from [`IoConfig`](crate::io::IoConfig) are not affected.
238    pub fn disable_timeout(mut self) -> Self {
239        self.timeout = Millis::ZERO;
240        self
241    }
242
243    #[must_use]
244    /// Sets the maximum size of a buffered response payload.
245    ///
246    /// The default is 256 KiB. A value of zero disables the limit.
247    pub fn set_response_payload_limit(mut self, limit: usize) -> Self {
248        self.pl_limit = limit;
249        self
250    }
251
252    #[must_use]
253    /// Sets the timeout for reading a complete response payload.
254    ///
255    /// The timeout applies to [`ClientResponse::body`](super::ClientResponse::body)
256    /// and [`ClientResponse::json`](super::ClientResponse::json), starting when
257    /// either is called. Reading the response as a stream is not bounded. The timeout is independent of the response-header timeout.
258    /// The default is 10 seconds. A zero duration disables the timeout.
259    pub fn set_response_payload_timeout<T: Into<Millis>>(mut self, timeout: T) -> Self {
260        self.pl_timeout = timeout.into();
261        self
262    }
263
264    /// Adds a header to every request.
265    ///
266    /// Repeated calls with the same name add values; every value is sent. A
267    /// request replaces the default values with
268    /// [`ClientRequest::set_header()`](super::ClientRequest::set_header), while
269    /// [`ClientRequest::header()`](super::ClientRequest::header) appends to them.
270    pub fn set_header<K, V>(mut self, key: K, value: V) -> Result<Self, HttpError>
271    where
272        HeaderName: TryFrom<K>,
273        HeaderValue: TryFrom<V>,
274        <HeaderName as TryFrom<K>>::Error: Into<HttpError>,
275        <HeaderValue as TryFrom<V>>::Error: Into<HttpError>,
276    {
277        let key = HeaderName::try_from(key).map_err(Into::into)?;
278        let value = HeaderValue::try_from(value).map_err(Into::into)?;
279        self.headers.append(key, value);
280        Ok(self)
281    }
282
283    fn insert_header(mut self, key: HeaderName, value: String) -> Result<Self, HttpError> {
284        let value = HeaderValue::try_from(value).map_err(HttpError::from)?;
285        self.headers.insert(key, value);
286        Ok(self)
287    }
288
289    /// Sets a client-wide HTTP Basic authentication header.
290    ///
291    /// Replaces any previously configured `Authorization` header.
292    pub fn set_basic_auth<U>(self, username: U, password: Option<&str>) -> Result<Self, HttpError>
293    where
294        U: fmt::Display,
295    {
296        let auth = match password {
297            Some(password) => format!("{username}:{password}"),
298            None => format!("{username}:"),
299        };
300        self.insert_header(
301            header::AUTHORIZATION,
302            format!("Basic {}", base64.encode(auth)),
303        )
304    }
305
306    /// Sets a client-wide HTTP Bearer authentication header.
307    ///
308    /// Replaces any previously configured `Authorization` header.
309    pub fn set_bearer_auth<T>(self, token: T) -> Result<Self, HttpError>
310    where
311        T: fmt::Display,
312    {
313        self.insert_header(header::AUTHORIZATION, format!("Bearer {token}"))
314    }
315}
316
317#[cfg(test)]
318mod tests {
319    use super::*;
320
321    /// STATEMENT: HTTP/2 pool settings can be changed independently of HTTP/1 settings.
322    ///
323    /// HOW:
324    /// - Check defaults, replace HTTP/2 connection/stream limits and lifetimes, and verify HTTP/1 values remain unchanged.
325    #[test]
326    fn h2_settings() {
327        let cfg = ClientConfig::new();
328        assert_eq!(cfg.h2_connection_limit(), 16);
329        assert_eq!(cfg.h2_max_streams(), 100);
330        assert_eq!(cfg.h2_keepalive(), Seconds(60));
331        assert_eq!(cfg.h2_lifetime(), Seconds(3600));
332
333        let cfg = cfg
334            .set_h2_connection_limit(2)
335            .set_h2_max_streams(10)
336            .set_h2_keepalive(Seconds(5))
337            .set_h2_lifetime(Seconds(50));
338        assert_eq!(cfg.h2_connection_limit(), 2);
339        assert_eq!(cfg.h2_max_streams(), 10);
340        assert_eq!(cfg.h2_keepalive(), Seconds(5));
341        assert_eq!(cfg.h2_lifetime(), Seconds(50));
342        // http/1 settings are not affected
343        assert_eq!(cfg.h1_connection_limit(), 8);
344        assert_eq!(cfg.h1_keep_alive, Duration::from_secs(15));
345        assert_eq!(cfg.h1_lifetime, Duration::from_secs(75));
346    }
347
348    /// STATEMENT: Client configuration accepts a custom response payload limit.
349    ///
350    /// HOW:
351    /// - Check the default limit, replace it, and verify the configured limit.
352    #[test]
353    fn response_payload_limit() {
354        let cfg = ClientConfig::new();
355        assert_eq!(cfg.pl_limit, 262_144);
356
357        let cfg = cfg.set_response_payload_limit(10);
358        assert_eq!(cfg.pl_limit, 10);
359    }
360
361    /// STATEMENT: Client configuration accepts a custom response payload timeout.
362    ///
363    /// HOW:
364    /// - Check the default timeout, replace it, and verify the configured duration.
365    #[test]
366    fn response_payload_timeout() {
367        let cfg = ClientConfig::default();
368        assert_eq!(cfg.pl_timeout, Millis(10_000));
369
370        let cfg = cfg.set_response_payload_timeout(Millis(10));
371        assert_eq!(cfg.pl_timeout, Millis(10));
372    }
373
374    /// STATEMENT: A positive sub-millisecond `Duration` keeps client timeouts enabled.
375    ///
376    /// HOW:
377    /// - Set the response and payload timeouts to 500 us and check both are one millisecond, not the zero sentinel.
378    /// - Set `Duration::ZERO` and check it still disables the response timeout.
379    #[test]
380    fn submillisecond_timeouts() {
381        let cfg = ClientConfig::new()
382            .set_response_timeout(Duration::from_micros(500))
383            .set_response_payload_timeout(Duration::from_micros(500));
384        assert_eq!(cfg.response_timeout(), Millis(1));
385        assert_eq!(cfg.response_payload_timeout(), Millis(1));
386
387        let cfg = cfg.set_response_timeout(Duration::ZERO);
388        assert_eq!(cfg.response_timeout(), Millis::ZERO);
389    }
390
391    /// STATEMENT: Valid header names are accepted as client defaults.
392    ///
393    /// HOW:
394    /// - Configure a string header name and check that it appears in the default headers.
395    #[test]
396    fn valid_header_name() {
397        let cfg = ClientConfig::new().set_header("Content-Length", 1).unwrap();
398        assert!(cfg.headers.contains_key("Content-Length"));
399    }
400
401    /// STATEMENT: Invalid client-default header names are rejected.
402    ///
403    /// HOW:
404    /// - Configure a name containing spaces and verify an error is returned.
405    #[test]
406    fn invalid_header_name() {
407        let res = ClientConfig::new().set_header("no valid header name", 1);
408        assert!(res.is_err());
409    }
410
411    /// STATEMENT: Typed header values are preserved when configured as client defaults.
412    ///
413    /// HOW:
414    /// - Set a numeric `HeaderValue` by reference and compare the stored value.
415    #[test]
416    fn valid_header_value() {
417        let valid_header_value = HeaderValue::from(1234);
418        let cfg = ClientConfig::new()
419            .set_header("Content-Length", &valid_header_value)
420            .unwrap();
421        assert_eq!(cfg.headers.get("Content-Length"), Some(&valid_header_value));
422    }
423
424    /// STATEMENT: Invalid client-default header values are rejected.
425    ///
426    /// HOW:
427    /// - Configure a newline as a header value and verify construction fails.
428    #[test]
429    fn invalid_header_value() {
430        let res = ClientConfig::new()
431            .set_header("Content-Length", "\n")
432            .is_err();
433        assert!(res);
434    }
435
436    /// STATEMENT: Client Basic authentication encodes credentials with an optional password.
437    ///
438    /// HOW:
439    /// - Configure credentials with and without a password and compare the resulting authorization headers.
440    #[test]
441    fn client_basic_auth() {
442        let cfg = ClientConfig::new()
443            .set_basic_auth("username", Some("password"))
444            .unwrap();
445        assert_eq!(
446            cfg.headers
447                .get(header::AUTHORIZATION)
448                .unwrap()
449                .to_str()
450                .unwrap(),
451            "Basic dXNlcm5hbWU6cGFzc3dvcmQ="
452        );
453
454        let cfg = ClientConfig::new()
455            .set_basic_auth("username", None)
456            .unwrap();
457        assert_eq!(
458            cfg.headers
459                .get(header::AUTHORIZATION)
460                .unwrap()
461                .to_str()
462                .unwrap(),
463            "Basic dXNlcm5hbWU6"
464        );
465    }
466
467    /// STATEMENT: Client bearer authentication uses the configured token in its authorization header.
468    ///
469    /// HOW:
470    /// - Configure a token and compare the complete generated authorization value.
471    #[test]
472    fn client_bearer_auth() {
473        let cfg = ClientConfig::new()
474            .set_bearer_auth("someS3cr3tAutht0k3n")
475            .unwrap();
476        assert_eq!(
477            cfg.headers
478                .get(header::AUTHORIZATION)
479                .unwrap()
480                .to_str()
481                .unwrap(),
482            "Bearer someS3cr3tAutht0k3n"
483        );
484    }
485}