Skip to main content

ntex/client/
builder.rs

1use urly::Url;
2
3use crate::connect::{self, Connect as TcpConnect, Connector as TcpConnector};
4use crate::service::{Identity, IntoService, Middleware, Pipeline, Service, Stack, apply_fn};
5use crate::{SharedCfg, error::Error, io::IoBoxed};
6
7use super::connector::Connector;
8use super::error::{ClientError, ConnectError};
9use super::pool::ConnectionPool;
10use super::service::{ServiceRequest, ServiceResponse};
11use super::{Client, ClientConfig, Connect, ConnectorPipeline, sender::Sender};
12
13#[cfg(feature = "openssl")]
14use tls_openssl::ssl::SslConnector as OpensslConnector;
15
16#[cfg(feature = "rustls")]
17use tls_rustls::ClientConfig as RustlsClientConfig;
18
19/// An HTTP client builder.
20///
21/// This type configures connectors and middleware before constructing a
22/// [`Client`].
23#[derive(Debug)]
24pub struct ClientBuilder<M = Identity> {
25    middleware: M,
26    svc: ConnectorPipeline,
27    secure_svc: Option<ConnectorPipeline>,
28}
29
30impl Default for ClientBuilder<Identity> {
31    fn default() -> Self {
32        Self::new()
33    }
34}
35
36impl ClientBuilder<Identity> {
37    #[must_use]
38    /// Creates a client builder with default connectors.
39    ///
40    /// # TLS defaults
41    ///
42    /// With the `openssl` feature enabled (it takes precedence over `rustls`),
43    /// HTTPS connections verify the peer certificate against OpenSSL's default
44    /// trust store (the system roots) and check that it matches the request
45    /// host. With only the `rustls` feature, peers are verified against the
46    /// bundled `webpki-roots`. Without either feature, HTTPS is unavailable.
47    ///
48    /// To trust private roots, or to skip verification for testing, pass your
49    /// own configuration to `openssl()`, `rustls()` or
50    /// [`secure_connector`](Self::secure_connector).
51    pub fn new() -> Self {
52        let svc = ConnectorPipeline::new(
53            apply_fn(TcpConnector::new(), async move |msg: Connect, svc| {
54                svc.call(TcpConnect::new(msg.uri).set_addr(msg.addr)).await
55            })
56            .map(IoBoxed::from)
57            .map_err(|e| e.map(ConnectError::from)),
58        );
59
60        let builder = ClientBuilder {
61            svc,
62            secure_svc: None,
63            middleware: Identity,
64        };
65
66        #[cfg(feature = "openssl")]
67        {
68            use tls_openssl::ssl::SslMethod;
69
70            let mut ssl = OpensslConnector::builder(SslMethod::tls()).unwrap();
71            let _ = ssl
72                .set_alpn_protos(b"\x02h2\x08http/1.1")
73                .map_err(|e| log::error!("Cannot set ALPN protocol: {e:?}"));
74
75            builder.openssl(ssl.build())
76        }
77        #[cfg(all(not(feature = "openssl"), feature = "rustls"))]
78        {
79            use tls_rustls::RootCertStore;
80
81            let protos = vec![b"h2".to_vec(), b"http/1.1".to_vec()];
82            let cert_store = webpki_roots::TLS_SERVER_ROOTS
83                .iter()
84                .cloned()
85                .collect::<RootCertStore>();
86            let mut config = RustlsClientConfig::builder()
87                .with_root_certificates(cert_store)
88                .with_no_client_auth();
89            config.alpn_protocols = protos;
90            builder.rustls(config)
91        }
92        #[cfg(not(any(feature = "openssl", feature = "rustls")))]
93        {
94            builder
95        }
96    }
97}
98
99impl<M> ClientBuilder<M> {
100    #[must_use]
101    #[cfg(feature = "openssl")]
102    /// Uses an OpenSSL connector for secure connections.
103    ///
104    /// The connector's verification settings are used as given. Hostname
105    /// verification follows the connector's `configure()` defaults, so it is
106    /// enabled unless `set_verify(SslVerifyMode::NONE)` disables verification
107    /// altogether.
108    pub fn openssl(self, config: OpensslConnector) -> Self {
109        use crate::connect::openssl::SslConnector;
110
111        self.secure_connector(SslConnector::new(config))
112    }
113
114    #[must_use]
115    #[cfg(feature = "rustls")]
116    /// Uses a rustls connector for secure connections.
117    pub fn rustls(self, config: RustlsClientConfig) -> Self {
118        use crate::connect::rustls::TlsConnector;
119
120        self.secure_connector(TlsConnector::new(config))
121    }
122
123    #[must_use]
124    /// Uses a custom connector for unsecured connections.
125    pub fn connector<T>(mut self, f: impl IntoService<T, SharedCfg, TcpConnect<Url>>) -> Self
126    where
127        T: Service<SharedCfg, TcpConnect<Url>, Error = Error<connect::ConnectError>> + 'static,
128        IoBoxed: From<T::Res>,
129    {
130        self.svc = ConnectorPipeline::new(
131            apply_fn(f.into_service(), async move |msg: Connect, svc| {
132                svc.call(TcpConnect::new(msg.uri).set_addr(msg.addr)).await
133            })
134            .map(IoBoxed::from)
135            .map_err(|e| e.map(ConnectError::from)),
136        );
137        self
138    }
139
140    #[must_use]
141    /// Uses a custom connector for secure connections.
142    pub fn secure_connector<T>(mut self, f: impl IntoService<T, SharedCfg, TcpConnect<Url>>) -> Self
143    where
144        T: Service<SharedCfg, TcpConnect<Url>, Error = Error<connect::ConnectError>> + 'static,
145        IoBoxed: From<T::Res>,
146    {
147        self.secure_svc = Some(ConnectorPipeline::new(
148            apply_fn(f.into_service(), async move |msg: Connect, svc| {
149                svc.call(TcpConnect::new(msg.uri).set_addr(msg.addr)).await
150            })
151            .map(IoBoxed::from)
152            .map_err(|e| e.map(ConnectError::from)),
153        ));
154        self
155    }
156
157    #[must_use]
158    /// Applies middleware to the client request service.
159    ///
160    /// Middleware can inspect or modify every request and response.
161    ///
162    /// ```rust
163    /// use ntex::client::{Client, ServiceRequest};
164    /// use ntex::service::{fn_layer, cfg::SharedCfg};
165    ///
166    /// #[ntex::main]
167    /// async fn main() {
168    ///     let client = Client::builder()
169    ///         .middleware(fn_layer(
170    ///             async move |mut req: ServiceRequest, svc| {
171    ///                 println!("{:?}", req.head().uri);
172    ///                 svc.call(req).await
173    ///             }
174    ///         ))
175    ///         .build(SharedCfg::default());
176    /// }
177    /// ```
178    pub fn middleware<U>(self, mw: U) -> ClientBuilder<Stack<U, M>> {
179        ClientBuilder {
180            middleware: Stack::new(mw, self.middleware),
181            svc: self.svc,
182            secure_svc: self.secure_svc,
183        }
184    }
185
186    /// Builds the [`Client`] using the supplied shared configuration.
187    ///
188    /// Add a [`ClientConfig`] to [`SharedCfg`] to customize client behavior:
189    ///
190    /// ```rust
191    /// use ntex::SharedCfg;
192    /// use ntex::client::{Client, ClientConfig};
193    /// use ntex::time::Millis;
194    ///
195    /// #[ntex::main]
196    /// async fn main() {
197    ///     let cfg = SharedCfg::new("HTTP-CLIENT")
198    ///         .add(
199    ///             ClientConfig::new()
200    ///                 .set_response_timeout(Millis(10_000))
201    ///                 .set_response_payload_limit(1024 * 1024),
202    ///         )
203    ///         .build();
204    ///
205    ///     let _client = Client::builder().build(cfg);
206    /// }
207    /// ```
208    pub fn build(self, cfg: impl Into<SharedCfg>) -> Client
209    where
210        M: Middleware<Sender, SharedCfg>,
211        M::Service: Service<SharedCfg, ServiceRequest, Res = ServiceResponse, Error = Error<ClientError>>
212            + 'static,
213    {
214        let cfg = cfg.into();
215        let config = cfg.get::<ClientConfig>();
216
217        let connector = Connector {
218            tcp_pool: ConnectionPool::new(self.svc, config.clone()),
219            ssl_pool: self
220                .secure_svc
221                .map(|svc| ConnectionPool::new(svc, config.clone())),
222        };
223        let svc = self.middleware.create(&cfg, Sender::new(connector));
224
225        Client::with_service(config, Pipeline::new(cfg, svc))
226    }
227}