hyper_util/client/legacy/
client.rs

1//! The legacy HTTP Client from 0.14.x
2//!
3//! This `Client` will eventually be deconstructed into more composable parts.
4//! For now, to enable people to use hyper 1.0 quicker, this `Client` exists
5//! in much the same way it did in hyper 0.14.
6
7use std::error::Error as StdError;
8use std::fmt;
9use std::future::Future;
10use std::pin::Pin;
11use std::task::{self, Poll};
12use std::time::Duration;
13
14use futures_util::future::{self, Either, FutureExt, TryFutureExt};
15use http::uri::Scheme;
16use hyper::client::conn::TrySendError as ConnTrySendError;
17use hyper::header::{HeaderValue, HOST};
18use hyper::rt::Timer;
19use hyper::{body::Body, Method, Request, Response, Uri, Version};
20use tracing::{debug, trace, warn};
21
22use super::connect::capture::CaptureConnectionExtension;
23#[cfg(feature = "tokio")]
24use super::connect::HttpConnector;
25use super::connect::{Alpn, Connect, Connected, Connection};
26use super::pool::{self, Ver};
27
28use crate::common::{lazy as hyper_lazy, timer, Exec, Lazy, SyncWrapper};
29
30type BoxSendFuture = Pin<Box<dyn Future<Output = ()> + Send>>;
31
32/// A Client to make outgoing HTTP requests.
33///
34/// `Client` is cheap to clone and cloning is the recommended way to share a `Client`. The
35/// underlying connection pool will be reused.
36#[cfg_attr(docsrs, doc(cfg(any(feature = "http1", feature = "http2"))))]
37pub struct Client<C, B> {
38    config: Config,
39    connector: C,
40    exec: Exec,
41    #[cfg(feature = "http1")]
42    h1_builder: hyper::client::conn::http1::Builder,
43    #[cfg(feature = "http2")]
44    h2_builder: hyper::client::conn::http2::Builder<Exec>,
45    pool: pool::Pool<PoolClient<B>, PoolKey>,
46}
47
48#[derive(Clone, Copy, Debug)]
49struct Config {
50    retry_canceled_requests: bool,
51    set_host: bool,
52    ver: Ver,
53}
54
55/// Client errors
56pub struct Error {
57    kind: ErrorKind,
58    source: Option<Box<dyn StdError + Send + Sync>>,
59    #[cfg(any(feature = "http1", feature = "http2"))]
60    connect_info: Option<Connected>,
61}
62
63#[derive(Debug)]
64enum ErrorKind {
65    Canceled,
66    ChannelClosed,
67    Connect,
68    UserUnsupportedRequestMethod,
69    UserUnsupportedVersion,
70    UserAbsoluteUriRequired,
71    SendRequest,
72}
73
74macro_rules! e {
75    ($kind:ident) => {
76        Error {
77            kind: ErrorKind::$kind,
78            source: None,
79            connect_info: None,
80        }
81    };
82    ($kind:ident, $src:expr) => {
83        Error {
84            kind: ErrorKind::$kind,
85            source: Some($src.into()),
86            connect_info: None,
87        }
88    };
89}
90
91// We might change this... :shrug:
92type PoolKey = (http::uri::Scheme, http::uri::Authority);
93
94enum TrySendError<B> {
95    Retryable {
96        error: Error,
97        req: Request<B>,
98        connection_reused: bool,
99    },
100    Nope(Error),
101}
102
103/// A `Future` that will resolve to an HTTP Response.
104///
105/// This is returned by `Client::request` (and `Client::get`).
106#[must_use = "futures do nothing unless polled"]
107pub struct ResponseFuture {
108    inner: SyncWrapper<
109        Pin<Box<dyn Future<Output = Result<Response<hyper::body::Incoming>, Error>> + Send>>,
110    >,
111}
112
113// ===== impl Client =====
114
115impl Client<(), ()> {
116    /// Create a builder to configure a new `Client`.
117    ///
118    /// # Example
119    ///
120    /// ```
121    /// # #[cfg(feature = "tokio")]
122    /// # fn run () {
123    /// use std::time::Duration;
124    /// use hyper_util::client::legacy::Client;
125    /// use hyper_util::rt::{TokioExecutor, TokioTimer};
126    ///
127    /// let client = Client::builder(TokioExecutor::new())
128    ///     .pool_timer(TokioTimer::new())
129    ///     .pool_idle_timeout(Duration::from_secs(30))
130    ///     .http2_only(true)
131    ///     .build_http();
132    /// # let infer: Client<_, http_body_util::Full<bytes::Bytes>> = client;
133    /// # drop(infer);
134    /// # }
135    /// # fn main() {}
136    /// ```
137    pub fn builder<E>(executor: E) -> Builder
138    where
139        E: hyper::rt::Executor<BoxSendFuture> + Send + Sync + Clone + 'static,
140    {
141        Builder::new(executor)
142    }
143}
144
145impl<C, B> Client<C, B>
146where
147    C: Connect + Clone + Send + Sync + 'static,
148    B: Body + Send + 'static + Unpin,
149    B::Data: Send,
150    B::Error: Into<Box<dyn StdError + Send + Sync>>,
151{
152    /// Send a `GET` request to the supplied `Uri`.
153    ///
154    /// # Note
155    ///
156    /// This requires that the `Body` type have a `Default` implementation.
157    /// It *should* return an "empty" version of itself, such that
158    /// `Body::is_end_stream` is `true`.
159    ///
160    /// # Example
161    ///
162    /// ```
163    /// # #[cfg(feature = "tokio")]
164    /// # fn run () {
165    /// use hyper::Uri;
166    /// use hyper_util::client::legacy::Client;
167    /// use hyper_util::rt::TokioExecutor;
168    /// use bytes::Bytes;
169    /// use http_body_util::Full;
170    ///
171    /// let client: Client<_, Full<Bytes>> = Client::builder(TokioExecutor::new()).build_http();
172    ///
173    /// let future = client.get(Uri::from_static("http://httpbin.org/ip"));
174    /// # }
175    /// # fn main() {}
176    /// ```
177    pub fn get(&self, uri: Uri) -> ResponseFuture
178    where
179        B: Default,
180    {
181        let body = B::default();
182        if !body.is_end_stream() {
183            warn!("default Body used for get() does not return true for is_end_stream");
184        }
185
186        let mut req = Request::new(body);
187        *req.uri_mut() = uri;
188        self.request(req)
189    }
190
191    /// Send a constructed `Request` using this `Client`.
192    ///
193    /// # Example
194    ///
195    /// ```
196    /// # #[cfg(feature = "tokio")]
197    /// # fn run () {
198    /// use hyper::{Method, Request};
199    /// use hyper_util::client::legacy::Client;
200    /// use http_body_util::Full;
201    /// use hyper_util::rt::TokioExecutor;
202    /// use bytes::Bytes;
203    ///
204    /// let client: Client<_, Full<Bytes>> = Client::builder(TokioExecutor::new()).build_http();
205    ///
206    /// let req: Request<Full<Bytes>> = Request::builder()
207    ///     .method(Method::POST)
208    ///     .uri("http://httpbin.org/post")
209    ///     .body(Full::from("Hallo!"))
210    ///     .expect("request builder");
211    ///
212    /// let future = client.request(req);
213    /// # }
214    /// # fn main() {}
215    /// ```
216    pub fn request(&self, mut req: Request<B>) -> ResponseFuture {
217        let is_http_connect = req.method() == Method::CONNECT;
218        match req.version() {
219            Version::HTTP_11 => (),
220            Version::HTTP_10 => {
221                if is_http_connect {
222                    warn!("CONNECT is not allowed for HTTP/1.0");
223                    return ResponseFuture::new(future::err(e!(UserUnsupportedRequestMethod)));
224                }
225            }
226            Version::HTTP_2 => (),
227            // completely unsupported HTTP version (like HTTP/0.9)!
228            other => return ResponseFuture::error_version(other),
229        };
230
231        let pool_key = match extract_domain(req.uri_mut(), is_http_connect) {
232            Ok(s) => s,
233            Err(err) => {
234                return ResponseFuture::new(future::err(err));
235            }
236        };
237
238        ResponseFuture::new(self.clone().send_request(req, pool_key))
239    }
240
241    async fn send_request(
242        self,
243        mut req: Request<B>,
244        pool_key: PoolKey,
245    ) -> Result<Response<hyper::body::Incoming>, Error> {
246        let uri = req.uri().clone();
247
248        loop {
249            req = match self.try_send_request(req, pool_key.clone()).await {
250                Ok(resp) => return Ok(resp),
251                Err(TrySendError::Nope(err)) => return Err(err),
252                Err(TrySendError::Retryable {
253                    mut req,
254                    error,
255                    connection_reused,
256                }) => {
257                    if !self.config.retry_canceled_requests || !connection_reused {
258                        // if client disabled, don't retry
259                        // a fresh connection means we definitely can't retry
260                        return Err(error);
261                    }
262
263                    trace!(
264                        "unstarted request canceled, trying again (reason={:?})",
265                        error
266                    );
267                    *req.uri_mut() = uri.clone();
268                    req
269                }
270            }
271        }
272    }
273
274    async fn try_send_request(
275        &self,
276        mut req: Request<B>,
277        pool_key: PoolKey,
278    ) -> Result<Response<hyper::body::Incoming>, TrySendError<B>> {
279        let mut pooled = self
280            .connection_for(pool_key)
281            .await
282            // `connection_for` already retries checkout errors, so if
283            // it returns an error, there's not much else to retry
284            .map_err(TrySendError::Nope)?;
285
286        req.extensions_mut()
287            .get_mut::<CaptureConnectionExtension>()
288            .map(|conn| conn.set(&pooled.conn_info));
289
290        if pooled.is_http1() {
291            if req.version() == Version::HTTP_2 {
292                warn!("Connection is HTTP/1, but request requires HTTP/2");
293                return Err(TrySendError::Nope(
294                    e!(UserUnsupportedVersion).with_connect_info(pooled.conn_info.clone()),
295                ));
296            }
297
298            if self.config.set_host {
299                let uri = req.uri().clone();
300                req.headers_mut().entry(HOST).or_insert_with(|| {
301                    let hostname = uri.host().expect("authority implies host");
302                    if let Some(port) = get_non_default_port(&uri) {
303                        let s = format!("{}:{}", hostname, port);
304                        HeaderValue::from_str(&s)
305                    } else {
306                        HeaderValue::from_str(hostname)
307                    }
308                    .expect("uri host is valid header value")
309                });
310            }
311
312            // CONNECT always sends authority-form, so check it first...
313            if req.method() == Method::CONNECT {
314                authority_form(req.uri_mut());
315            } else if pooled.conn_info.is_proxied {
316                absolute_form(req.uri_mut());
317            } else {
318                origin_form(req.uri_mut());
319            }
320        } else if req.method() == Method::CONNECT && !pooled.is_http2() {
321            authority_form(req.uri_mut());
322        }
323
324        let mut res = match pooled.try_send_request(req).await {
325            Ok(res) => res,
326            Err(mut err) => {
327                return if let Some(req) = err.take_message() {
328                    Err(TrySendError::Retryable {
329                        connection_reused: pooled.is_reused(),
330                        error: e!(Canceled, err.into_error())
331                            .with_connect_info(pooled.conn_info.clone()),
332                        req,
333                    })
334                } else {
335                    Err(TrySendError::Nope(
336                        e!(SendRequest, err.into_error())
337                            .with_connect_info(pooled.conn_info.clone()),
338                    ))
339                }
340            }
341        };
342
343        // If the Connector included 'extra' info, add to Response...
344        if let Some(extra) = &pooled.conn_info.extra {
345            extra.set(res.extensions_mut());
346        }
347
348        // If pooled is HTTP/2, we can toss this reference immediately.
349        //
350        // when pooled is dropped, it will try to insert back into the
351        // pool. To delay that, spawn a future that completes once the
352        // sender is ready again.
353        //
354        // This *should* only be once the related `Connection` has polled
355        // for a new request to start.
356        //
357        // It won't be ready if there is a body to stream.
358        if pooled.is_http2() || !pooled.is_pool_enabled() || pooled.is_ready() {
359            drop(pooled);
360        } else if !res.body().is_end_stream() {
361            //let (delayed_tx, delayed_rx) = oneshot::channel::<()>();
362            //res.body_mut().delayed_eof(delayed_rx);
363            let on_idle = future::poll_fn(move |cx| pooled.poll_ready(cx)).map(move |_| {
364                // At this point, `pooled` is dropped, and had a chance
365                // to insert into the pool (if conn was idle)
366                //drop(delayed_tx);
367            });
368
369            self.exec.execute(on_idle);
370        } else {
371            // There's no body to delay, but the connection isn't
372            // ready yet. Only re-insert when it's ready
373            let on_idle = future::poll_fn(move |cx| pooled.poll_ready(cx)).map(|_| ());
374
375            self.exec.execute(on_idle);
376        }
377
378        Ok(res)
379    }
380
381    async fn connection_for(
382        &self,
383        pool_key: PoolKey,
384    ) -> Result<pool::Pooled<PoolClient<B>, PoolKey>, Error> {
385        loop {
386            match self.one_connection_for(pool_key.clone()).await {
387                Ok(pooled) => return Ok(pooled),
388                Err(ClientConnectError::Normal(err)) => return Err(err),
389                Err(ClientConnectError::CheckoutIsClosed(reason)) => {
390                    if !self.config.retry_canceled_requests {
391                        return Err(e!(Connect, reason));
392                    }
393
394                    trace!(
395                        "unstarted request canceled, trying again (reason={:?})",
396                        reason,
397                    );
398                    continue;
399                }
400            };
401        }
402    }
403
404    async fn one_connection_for(
405        &self,
406        pool_key: PoolKey,
407    ) -> Result<pool::Pooled<PoolClient<B>, PoolKey>, ClientConnectError> {
408        // Return a single connection if pooling is not enabled
409        if !self.pool.is_enabled() {
410            return self
411                .connect_to(pool_key)
412                .await
413                .map_err(ClientConnectError::Normal);
414        }
415
416        // This actually races 2 different futures to try to get a ready
417        // connection the fastest, and to reduce connection churn.
418        //
419        // - If the pool has an idle connection waiting, that's used
420        //   immediately.
421        // - Otherwise, the Connector is asked to start connecting to
422        //   the destination Uri.
423        // - Meanwhile, the pool Checkout is watching to see if any other
424        //   request finishes and tries to insert an idle connection.
425        // - If a new connection is started, but the Checkout wins after
426        //   (an idle connection became available first), the started
427        //   connection future is spawned into the runtime to complete,
428        //   and then be inserted into the pool as an idle connection.
429        let checkout = self.pool.checkout(pool_key.clone());
430        let connect = self.connect_to(pool_key);
431        let is_ver_h2 = self.config.ver == Ver::Http2;
432
433        // The order of the `select` is depended on below...
434
435        match future::select(checkout, connect).await {
436            // Checkout won, connect future may have been started or not.
437            //
438            // If it has, let it finish and insert back into the pool,
439            // so as to not waste the socket...
440            Either::Left((Ok(checked_out), connecting)) => {
441                // This depends on the `select` above having the correct
442                // order, such that if the checkout future were ready
443                // immediately, the connect future will never have been
444                // started.
445                //
446                // If it *wasn't* ready yet, then the connect future will
447                // have been started...
448                if connecting.started() {
449                    let bg = connecting
450                        .map_err(|err| {
451                            trace!("background connect error: {}", err);
452                        })
453                        .map(|_pooled| {
454                            // dropping here should just place it in
455                            // the Pool for us...
456                        });
457                    // An execute error here isn't important, we're just trying
458                    // to prevent a waste of a socket...
459                    self.exec.execute(bg);
460                }
461                Ok(checked_out)
462            }
463            // Connect won, checkout can just be dropped.
464            Either::Right((Ok(connected), _checkout)) => Ok(connected),
465            // Either checkout or connect could get canceled:
466            //
467            // 1. Connect is canceled if this is HTTP/2 and there is
468            //    an outstanding HTTP/2 connecting task.
469            // 2. Checkout is canceled if the pool cannot deliver an
470            //    idle connection reliably.
471            //
472            // In both cases, we should just wait for the other future.
473            Either::Left((Err(err), connecting)) => {
474                if err.is_canceled() {
475                    connecting.await.map_err(ClientConnectError::Normal)
476                } else {
477                    Err(ClientConnectError::Normal(e!(Connect, err)))
478                }
479            }
480            Either::Right((Err(err), checkout)) => {
481                if err.is_canceled() {
482                    checkout.await.map_err(move |err| {
483                        if is_ver_h2 && err.is_canceled() {
484                            ClientConnectError::CheckoutIsClosed(err)
485                        } else {
486                            ClientConnectError::Normal(e!(Connect, err))
487                        }
488                    })
489                } else {
490                    Err(ClientConnectError::Normal(err))
491                }
492            }
493        }
494    }
495
496    #[cfg(any(feature = "http1", feature = "http2"))]
497    fn connect_to(
498        &self,
499        pool_key: PoolKey,
500    ) -> impl Lazy<Output = Result<pool::Pooled<PoolClient<B>, PoolKey>, Error>> + Send + Unpin
501    {
502        let executor = self.exec.clone();
503        let pool = self.pool.clone();
504        #[cfg(feature = "http1")]
505        let h1_builder = self.h1_builder.clone();
506        #[cfg(feature = "http2")]
507        let h2_builder = self.h2_builder.clone();
508        let ver = self.config.ver;
509        let is_ver_h2 = ver == Ver::Http2;
510        let connector = self.connector.clone();
511        let dst = domain_as_uri(pool_key.clone());
512        hyper_lazy(move || {
513            // Try to take a "connecting lock".
514            //
515            // If the pool_key is for HTTP/2, and there is already a
516            // connection being established, then this can't take a
517            // second lock. The "connect_to" future is Canceled.
518            let connecting = match pool.connecting(&pool_key, ver) {
519                Some(lock) => lock,
520                None => {
521                    let canceled = e!(Canceled);
522                    // TODO
523                    //crate::Error::new_canceled().with("HTTP/2 connection in progress");
524                    return Either::Right(future::err(canceled));
525                }
526            };
527            Either::Left(
528                connector
529                    .connect(super::connect::sealed::Internal, dst)
530                    .map_err(|src| e!(Connect, src))
531                    .and_then(move |io| {
532                        let connected = io.connected();
533                        // If ALPN is h2 and we aren't http2_only already,
534                        // then we need to convert our pool checkout into
535                        // a single HTTP2 one.
536                        let connecting = if connected.alpn == Alpn::H2 && !is_ver_h2 {
537                            match connecting.alpn_h2(&pool) {
538                                Some(lock) => {
539                                    trace!("ALPN negotiated h2, updating pool");
540                                    lock
541                                }
542                                None => {
543                                    // Another connection has already upgraded,
544                                    // the pool checkout should finish up for us.
545                                    let canceled = e!(Canceled, "ALPN upgraded to HTTP/2");
546                                    return Either::Right(future::err(canceled));
547                                }
548                            }
549                        } else {
550                            connecting
551                        };
552
553                        #[cfg_attr(not(feature = "http2"), allow(unused))]
554                        let is_h2 = is_ver_h2 || connected.alpn == Alpn::H2;
555
556                        Either::Left(Box::pin(async move {
557                            let tx = if is_h2 {
558                                #[cfg(feature = "http2")] {
559                                    let (mut tx, conn) =
560                                        h2_builder.handshake(io).await.map_err(Error::tx)?;
561
562                                    trace!(
563                                        "http2 handshake complete, spawning background dispatcher task"
564                                    );
565                                    executor.execute(
566                                        conn.map_err(|e| debug!("client connection error: {}", e))
567                                            .map(|_| ()),
568                                    );
569
570                                    // Wait for 'conn' to ready up before we
571                                    // declare this tx as usable
572                                    tx.ready().await.map_err(Error::tx)?;
573                                    PoolTx::Http2(tx)
574                                }
575                                #[cfg(not(feature = "http2"))]
576                                panic!("http2 feature is not enabled");
577                            } else {
578                                #[cfg(feature = "http1")] {
579                                    let (mut tx, conn) =
580                                        h1_builder.handshake(io).await.map_err(Error::tx)?;
581
582                                    trace!(
583                                        "http1 handshake complete, spawning background dispatcher task"
584                                    );
585                                    executor.execute(
586                                        conn.with_upgrades()
587                                            .map_err(|e| debug!("client connection error: {}", e))
588                                            .map(|_| ()),
589                                    );
590
591                                    // Wait for 'conn' to ready up before we
592                                    // declare this tx as usable
593                                    tx.ready().await.map_err(Error::tx)?;
594                                    PoolTx::Http1(tx)
595                                }
596                                #[cfg(not(feature = "http1"))] {
597                                    panic!("http1 feature is not enabled");
598                                }
599                            };
600
601                            Ok(pool.pooled(
602                                connecting,
603                                PoolClient {
604                                    conn_info: connected,
605                                    tx,
606                                },
607                            ))
608                        }))
609                    }),
610            )
611        })
612    }
613}
614
615impl<C, B> tower_service::Service<Request<B>> for Client<C, B>
616where
617    C: Connect + Clone + Send + Sync + 'static,
618    B: Body + Send + 'static + Unpin,
619    B::Data: Send,
620    B::Error: Into<Box<dyn StdError + Send + Sync>>,
621{
622    type Response = Response<hyper::body::Incoming>;
623    type Error = Error;
624    type Future = ResponseFuture;
625
626    fn poll_ready(&mut self, _: &mut task::Context<'_>) -> Poll<Result<(), Self::Error>> {
627        Poll::Ready(Ok(()))
628    }
629
630    fn call(&mut self, req: Request<B>) -> Self::Future {
631        self.request(req)
632    }
633}
634
635impl<C, B> tower_service::Service<Request<B>> for &'_ Client<C, B>
636where
637    C: Connect + Clone + Send + Sync + 'static,
638    B: Body + Send + 'static + Unpin,
639    B::Data: Send,
640    B::Error: Into<Box<dyn StdError + Send + Sync>>,
641{
642    type Response = Response<hyper::body::Incoming>;
643    type Error = Error;
644    type Future = ResponseFuture;
645
646    fn poll_ready(&mut self, _: &mut task::Context<'_>) -> Poll<Result<(), Self::Error>> {
647        Poll::Ready(Ok(()))
648    }
649
650    fn call(&mut self, req: Request<B>) -> Self::Future {
651        self.request(req)
652    }
653}
654
655impl<C: Clone, B> Clone for Client<C, B> {
656    fn clone(&self) -> Client<C, B> {
657        Client {
658            config: self.config,
659            exec: self.exec.clone(),
660            #[cfg(feature = "http1")]
661            h1_builder: self.h1_builder.clone(),
662            #[cfg(feature = "http2")]
663            h2_builder: self.h2_builder.clone(),
664            connector: self.connector.clone(),
665            pool: self.pool.clone(),
666        }
667    }
668}
669
670impl<C, B> fmt::Debug for Client<C, B> {
671    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
672        f.debug_struct("Client").finish()
673    }
674}
675
676// ===== impl ResponseFuture =====
677
678impl ResponseFuture {
679    fn new<F>(value: F) -> Self
680    where
681        F: Future<Output = Result<Response<hyper::body::Incoming>, Error>> + Send + 'static,
682    {
683        Self {
684            inner: SyncWrapper::new(Box::pin(value)),
685        }
686    }
687
688    fn error_version(ver: Version) -> Self {
689        warn!("Request has unsupported version \"{:?}\"", ver);
690        ResponseFuture::new(Box::pin(future::err(e!(UserUnsupportedVersion))))
691    }
692}
693
694impl fmt::Debug for ResponseFuture {
695    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
696        f.pad("Future<Response>")
697    }
698}
699
700impl Future for ResponseFuture {
701    type Output = Result<Response<hyper::body::Incoming>, Error>;
702
703    fn poll(mut self: Pin<&mut Self>, cx: &mut task::Context<'_>) -> Poll<Self::Output> {
704        self.inner.get_mut().as_mut().poll(cx)
705    }
706}
707
708// ===== impl PoolClient =====
709
710// FIXME: allow() required due to `impl Trait` leaking types to this lint
711#[allow(missing_debug_implementations)]
712struct PoolClient<B> {
713    conn_info: Connected,
714    tx: PoolTx<B>,
715}
716
717enum PoolTx<B> {
718    #[cfg(feature = "http1")]
719    Http1(hyper::client::conn::http1::SendRequest<B>),
720    #[cfg(feature = "http2")]
721    Http2(hyper::client::conn::http2::SendRequest<B>),
722}
723
724impl<B> PoolClient<B> {
725    fn poll_ready(
726        &mut self,
727        #[allow(unused_variables)] cx: &mut task::Context<'_>,
728    ) -> Poll<Result<(), Error>> {
729        match self.tx {
730            #[cfg(feature = "http1")]
731            PoolTx::Http1(ref mut tx) => tx.poll_ready(cx).map_err(Error::closed),
732            #[cfg(feature = "http2")]
733            PoolTx::Http2(_) => Poll::Ready(Ok(())),
734        }
735    }
736
737    fn is_http1(&self) -> bool {
738        !self.is_http2()
739    }
740
741    fn is_http2(&self) -> bool {
742        match self.tx {
743            #[cfg(feature = "http1")]
744            PoolTx::Http1(_) => false,
745            #[cfg(feature = "http2")]
746            PoolTx::Http2(_) => true,
747        }
748    }
749
750    fn is_poisoned(&self) -> bool {
751        self.conn_info.poisoned.poisoned()
752    }
753
754    fn is_ready(&self) -> bool {
755        match self.tx {
756            #[cfg(feature = "http1")]
757            PoolTx::Http1(ref tx) => tx.is_ready(),
758            #[cfg(feature = "http2")]
759            PoolTx::Http2(ref tx) => tx.is_ready(),
760        }
761    }
762}
763
764impl<B: Body + 'static> PoolClient<B> {
765    fn try_send_request(
766        &mut self,
767        req: Request<B>,
768    ) -> impl Future<Output = Result<Response<hyper::body::Incoming>, ConnTrySendError<Request<B>>>>
769    where
770        B: Send,
771    {
772        #[cfg(all(feature = "http1", feature = "http2"))]
773        return match self.tx {
774            #[cfg(feature = "http1")]
775            PoolTx::Http1(ref mut tx) => Either::Left(tx.try_send_request(req)),
776            #[cfg(feature = "http2")]
777            PoolTx::Http2(ref mut tx) => Either::Right(tx.try_send_request(req)),
778        };
779
780        #[cfg(feature = "http1")]
781        #[cfg(not(feature = "http2"))]
782        return match self.tx {
783            #[cfg(feature = "http1")]
784            PoolTx::Http1(ref mut tx) => tx.try_send_request(req),
785        };
786
787        #[cfg(not(feature = "http1"))]
788        #[cfg(feature = "http2")]
789        return match self.tx {
790            #[cfg(feature = "http2")]
791            PoolTx::Http2(ref mut tx) => tx.try_send_request(req),
792        };
793    }
794}
795
796impl<B> pool::Poolable for PoolClient<B>
797where
798    B: Send + 'static,
799{
800    fn is_open(&self) -> bool {
801        !self.is_poisoned() && self.is_ready()
802    }
803
804    fn reserve(self) -> pool::Reservation<Self> {
805        match self.tx {
806            #[cfg(feature = "http1")]
807            PoolTx::Http1(tx) => pool::Reservation::Unique(PoolClient {
808                conn_info: self.conn_info,
809                tx: PoolTx::Http1(tx),
810            }),
811            #[cfg(feature = "http2")]
812            PoolTx::Http2(tx) => {
813                let b = PoolClient {
814                    conn_info: self.conn_info.clone(),
815                    tx: PoolTx::Http2(tx.clone()),
816                };
817                let a = PoolClient {
818                    conn_info: self.conn_info,
819                    tx: PoolTx::Http2(tx),
820                };
821                pool::Reservation::Shared(a, b)
822            }
823        }
824    }
825
826    fn can_share(&self) -> bool {
827        self.is_http2()
828    }
829}
830
831enum ClientConnectError {
832    Normal(Error),
833    CheckoutIsClosed(pool::Error),
834}
835
836fn origin_form(uri: &mut Uri) {
837    let path = match uri.path_and_query() {
838        Some(path) if path.as_str() != "/" => {
839            let mut parts = ::http::uri::Parts::default();
840            parts.path_and_query = Some(path.clone());
841            Uri::from_parts(parts).expect("path is valid uri")
842        }
843        _none_or_just_slash => {
844            debug_assert!(Uri::default() == "/");
845            Uri::default()
846        }
847    };
848    *uri = path
849}
850
851fn absolute_form(uri: &mut Uri) {
852    debug_assert!(uri.scheme().is_some(), "absolute_form needs a scheme");
853    debug_assert!(
854        uri.authority().is_some(),
855        "absolute_form needs an authority"
856    );
857    // If the URI is to HTTPS, and the connector claimed to be a proxy,
858    // then it *should* have tunneled, and so we don't want to send
859    // absolute-form in that case.
860    if uri.scheme() == Some(&Scheme::HTTPS) {
861        origin_form(uri);
862    }
863}
864
865fn authority_form(uri: &mut Uri) {
866    if let Some(path) = uri.path_and_query() {
867        // `https://hyper.rs` would parse with `/` path, don't
868        // annoy people about that...
869        if path != "/" {
870            warn!("HTTP/1.1 CONNECT request stripping path: {:?}", path);
871        }
872    }
873    *uri = match uri.authority() {
874        Some(auth) => {
875            let mut parts = ::http::uri::Parts::default();
876            parts.authority = Some(auth.clone());
877            Uri::from_parts(parts).expect("authority is valid")
878        }
879        None => {
880            unreachable!("authority_form with relative uri");
881        }
882    };
883}
884
885fn extract_domain(uri: &mut Uri, is_http_connect: bool) -> Result<PoolKey, Error> {
886    let uri_clone = uri.clone();
887    match (uri_clone.scheme(), uri_clone.authority()) {
888        (Some(scheme), Some(auth)) => Ok((scheme.clone(), auth.clone())),
889        (None, Some(auth)) if is_http_connect => {
890            let scheme = match auth.port_u16() {
891                Some(443) => {
892                    set_scheme(uri, Scheme::HTTPS);
893                    Scheme::HTTPS
894                }
895                _ => {
896                    set_scheme(uri, Scheme::HTTP);
897                    Scheme::HTTP
898                }
899            };
900            Ok((scheme, auth.clone()))
901        }
902        _ => {
903            debug!("Client requires absolute-form URIs, received: {:?}", uri);
904            Err(e!(UserAbsoluteUriRequired))
905        }
906    }
907}
908
909fn domain_as_uri((scheme, auth): PoolKey) -> Uri {
910    http::uri::Builder::new()
911        .scheme(scheme)
912        .authority(auth)
913        .path_and_query("/")
914        .build()
915        .expect("domain is valid Uri")
916}
917
918fn set_scheme(uri: &mut Uri, scheme: Scheme) {
919    debug_assert!(
920        uri.scheme().is_none(),
921        "set_scheme expects no existing scheme"
922    );
923    let old = std::mem::take(uri);
924    let mut parts: ::http::uri::Parts = old.into();
925    parts.scheme = Some(scheme);
926    parts.path_and_query = Some("/".parse().expect("slash is a valid path"));
927    *uri = Uri::from_parts(parts).expect("scheme is valid");
928}
929
930fn get_non_default_port(uri: &Uri) -> Option<http::uri::Port<&str>> {
931    match (uri.port().map(|p| p.as_u16()), is_schema_secure(uri)) {
932        (Some(443), true) => None,
933        (Some(80), false) => None,
934        _ => uri.port(),
935    }
936}
937
938fn is_schema_secure(uri: &Uri) -> bool {
939    uri.scheme_str()
940        .map(|scheme_str| matches!(scheme_str, "wss" | "https"))
941        .unwrap_or_default()
942}
943
944/// A builder to configure a new [`Client`](Client).
945///
946/// # Example
947///
948/// ```
949/// # #[cfg(feature = "tokio")]
950/// # fn run () {
951/// use std::time::Duration;
952/// use hyper_util::client::legacy::Client;
953/// use hyper_util::rt::TokioExecutor;
954///
955/// let client = Client::builder(TokioExecutor::new())
956///     .pool_idle_timeout(Duration::from_secs(30))
957///     .http2_only(true)
958///     .build_http();
959/// # let infer: Client<_, http_body_util::Full<bytes::Bytes>> = client;
960/// # drop(infer);
961/// # }
962/// # fn main() {}
963/// ```
964#[cfg_attr(docsrs, doc(cfg(any(feature = "http1", feature = "http2"))))]
965#[derive(Clone)]
966pub struct Builder {
967    client_config: Config,
968    exec: Exec,
969    #[cfg(feature = "http1")]
970    h1_builder: hyper::client::conn::http1::Builder,
971    #[cfg(feature = "http2")]
972    h2_builder: hyper::client::conn::http2::Builder<Exec>,
973    pool_config: pool::Config,
974    pool_timer: Option<timer::Timer>,
975}
976
977impl Builder {
978    /// Construct a new Builder.
979    pub fn new<E>(executor: E) -> Self
980    where
981        E: hyper::rt::Executor<BoxSendFuture> + Send + Sync + Clone + 'static,
982    {
983        let exec = Exec::new(executor);
984        Self {
985            client_config: Config {
986                retry_canceled_requests: true,
987                set_host: true,
988                ver: Ver::Auto,
989            },
990            exec: exec.clone(),
991            #[cfg(feature = "http1")]
992            h1_builder: hyper::client::conn::http1::Builder::new(),
993            #[cfg(feature = "http2")]
994            h2_builder: hyper::client::conn::http2::Builder::new(exec),
995            pool_config: pool::Config {
996                idle_timeout: Some(Duration::from_secs(90)),
997                max_idle_per_host: usize::MAX,
998            },
999            pool_timer: None,
1000        }
1001    }
1002    /// Set an optional timeout for idle sockets being kept-alive.
1003    /// A `Timer` is required for this to take effect. See `Builder::pool_timer`
1004    ///
1005    /// Pass `None` to disable timeout.
1006    ///
1007    /// Default is 90 seconds.
1008    ///
1009    /// # Example
1010    ///
1011    /// ```
1012    /// # #[cfg(feature = "tokio")]
1013    /// # fn run () {
1014    /// use std::time::Duration;
1015    /// use hyper_util::client::legacy::Client;
1016    /// use hyper_util::rt::{TokioExecutor, TokioTimer};
1017    ///
1018    /// let client = Client::builder(TokioExecutor::new())
1019    ///     .pool_idle_timeout(Duration::from_secs(30))
1020    ///     .pool_timer(TokioTimer::new())
1021    ///     .build_http();
1022    ///
1023    /// # let infer: Client<_, http_body_util::Full<bytes::Bytes>> = client;
1024    /// # }
1025    /// # fn main() {}
1026    /// ```
1027    pub fn pool_idle_timeout<D>(&mut self, val: D) -> &mut Self
1028    where
1029        D: Into<Option<Duration>>,
1030    {
1031        self.pool_config.idle_timeout = val.into();
1032        self
1033    }
1034
1035    #[doc(hidden)]
1036    #[deprecated(note = "renamed to `pool_max_idle_per_host`")]
1037    pub fn max_idle_per_host(&mut self, max_idle: usize) -> &mut Self {
1038        self.pool_config.max_idle_per_host = max_idle;
1039        self
1040    }
1041
1042    /// Sets the maximum idle connection per host allowed in the pool.
1043    ///
1044    /// Default is `usize::MAX` (no limit).
1045    pub fn pool_max_idle_per_host(&mut self, max_idle: usize) -> &mut Self {
1046        self.pool_config.max_idle_per_host = max_idle;
1047        self
1048    }
1049
1050    // HTTP/1 options
1051
1052    /// Sets the exact size of the read buffer to *always* use.
1053    ///
1054    /// Note that setting this option unsets the `http1_max_buf_size` option.
1055    ///
1056    /// Default is an adaptive read buffer.
1057    #[cfg(feature = "http1")]
1058    #[cfg_attr(docsrs, doc(cfg(feature = "http1")))]
1059    pub fn http1_read_buf_exact_size(&mut self, sz: usize) -> &mut Self {
1060        self.h1_builder.read_buf_exact_size(Some(sz));
1061        self
1062    }
1063
1064    /// Set the maximum buffer size for the connection.
1065    ///
1066    /// Default is ~400kb.
1067    ///
1068    /// Note that setting this option unsets the `http1_read_exact_buf_size` option.
1069    ///
1070    /// # Panics
1071    ///
1072    /// The minimum value allowed is 8192. This method panics if the passed `max` is less than the minimum.
1073    #[cfg(feature = "http1")]
1074    #[cfg_attr(docsrs, doc(cfg(feature = "http1")))]
1075    pub fn http1_max_buf_size(&mut self, max: usize) -> &mut Self {
1076        self.h1_builder.max_buf_size(max);
1077        self
1078    }
1079
1080    /// Set whether HTTP/1 connections will accept spaces between header names
1081    /// and the colon that follow them in responses.
1082    ///
1083    /// Newline codepoints (`\r` and `\n`) will be transformed to spaces when
1084    /// parsing.
1085    ///
1086    /// You probably don't need this, here is what [RFC 7230 Section 3.2.4.] has
1087    /// to say about it:
1088    ///
1089    /// > No whitespace is allowed between the header field-name and colon. In
1090    /// > the past, differences in the handling of such whitespace have led to
1091    /// > security vulnerabilities in request routing and response handling. A
1092    /// > server MUST reject any received request message that contains
1093    /// > whitespace between a header field-name and colon with a response code
1094    /// > of 400 (Bad Request). A proxy MUST remove any such whitespace from a
1095    /// > response message before forwarding the message downstream.
1096    ///
1097    /// Note that this setting does not affect HTTP/2.
1098    ///
1099    /// Default is false.
1100    ///
1101    /// [RFC 7230 Section 3.2.4.]: https://tools.ietf.org/html/rfc7230#section-3.2.4
1102    #[cfg(feature = "http1")]
1103    #[cfg_attr(docsrs, doc(cfg(feature = "http1")))]
1104    pub fn http1_allow_spaces_after_header_name_in_responses(&mut self, val: bool) -> &mut Self {
1105        self.h1_builder
1106            .allow_spaces_after_header_name_in_responses(val);
1107        self
1108    }
1109
1110    /// Set whether HTTP/1 connections will accept obsolete line folding for
1111    /// header values.
1112    ///
1113    /// You probably don't need this, here is what [RFC 7230 Section 3.2.4.] has
1114    /// to say about it:
1115    ///
1116    /// > A server that receives an obs-fold in a request message that is not
1117    /// > within a message/http container MUST either reject the message by
1118    /// > sending a 400 (Bad Request), preferably with a representation
1119    /// > explaining that obsolete line folding is unacceptable, or replace
1120    /// > each received obs-fold with one or more SP octets prior to
1121    /// > interpreting the field value or forwarding the message downstream.
1122    ///
1123    /// > A proxy or gateway that receives an obs-fold in a response message
1124    /// > that is not within a message/http container MUST either discard the
1125    /// > message and replace it with a 502 (Bad Gateway) response, preferably
1126    /// > with a representation explaining that unacceptable line folding was
1127    /// > received, or replace each received obs-fold with one or more SP
1128    /// > octets prior to interpreting the field value or forwarding the
1129    /// > message downstream.
1130    ///
1131    /// > A user agent that receives an obs-fold in a response message that is
1132    /// > not within a message/http container MUST replace each received
1133    /// > obs-fold with one or more SP octets prior to interpreting the field
1134    /// > value.
1135    ///
1136    /// Note that this setting does not affect HTTP/2.
1137    ///
1138    /// Default is false.
1139    ///
1140    /// [RFC 7230 Section 3.2.4.]: https://tools.ietf.org/html/rfc7230#section-3.2.4
1141    #[cfg(feature = "http1")]
1142    #[cfg_attr(docsrs, doc(cfg(feature = "http1")))]
1143    pub fn http1_allow_obsolete_multiline_headers_in_responses(&mut self, val: bool) -> &mut Self {
1144        self.h1_builder
1145            .allow_obsolete_multiline_headers_in_responses(val);
1146        self
1147    }
1148
1149    /// Sets whether invalid header lines should be silently ignored in HTTP/1 responses.
1150    ///
1151    /// This mimics the behaviour of major browsers. You probably don't want this.
1152    /// You should only want this if you are implementing a proxy whose main
1153    /// purpose is to sit in front of browsers whose users access arbitrary content
1154    /// which may be malformed, and they expect everything that works without
1155    /// the proxy to keep working with the proxy.
1156    ///
1157    /// This option will prevent Hyper's client from returning an error encountered
1158    /// when parsing a header, except if the error was caused by the character NUL
1159    /// (ASCII code 0), as Chrome specifically always reject those.
1160    ///
1161    /// The ignorable errors are:
1162    /// * empty header names;
1163    /// * characters that are not allowed in header names, except for `\0` and `\r`;
1164    /// * when `allow_spaces_after_header_name_in_responses` is not enabled,
1165    ///   spaces and tabs between the header name and the colon;
1166    /// * missing colon between header name and colon;
1167    /// * characters that are not allowed in header values except for `\0` and `\r`.
1168    ///
1169    /// If an ignorable error is encountered, the parser tries to find the next
1170    /// line in the input to resume parsing the rest of the headers. An error
1171    /// will be emitted nonetheless if it finds `\0` or a lone `\r` while
1172    /// looking for the next line.
1173    #[cfg(feature = "http1")]
1174    #[cfg_attr(docsrs, doc(cfg(feature = "http1")))]
1175    pub fn http1_ignore_invalid_headers_in_responses(&mut self, val: bool) -> &mut Builder {
1176        self.h1_builder.ignore_invalid_headers_in_responses(val);
1177        self
1178    }
1179
1180    /// Set whether HTTP/1 connections should try to use vectored writes,
1181    /// or always flatten into a single buffer.
1182    ///
1183    /// Note that setting this to false may mean more copies of body data,
1184    /// but may also improve performance when an IO transport doesn't
1185    /// support vectored writes well, such as most TLS implementations.
1186    ///
1187    /// Setting this to true will force hyper to use queued strategy
1188    /// which may eliminate unnecessary cloning on some TLS backends
1189    ///
1190    /// Default is `auto`. In this mode hyper will try to guess which
1191    /// mode to use
1192    #[cfg(feature = "http1")]
1193    #[cfg_attr(docsrs, doc(cfg(feature = "http1")))]
1194    pub fn http1_writev(&mut self, enabled: bool) -> &mut Builder {
1195        self.h1_builder.writev(enabled);
1196        self
1197    }
1198
1199    /// Set whether HTTP/1 connections will write header names as title case at
1200    /// the socket level.
1201    ///
1202    /// Note that this setting does not affect HTTP/2.
1203    ///
1204    /// Default is false.
1205    #[cfg(feature = "http1")]
1206    #[cfg_attr(docsrs, doc(cfg(feature = "http1")))]
1207    pub fn http1_title_case_headers(&mut self, val: bool) -> &mut Self {
1208        self.h1_builder.title_case_headers(val);
1209        self
1210    }
1211
1212    /// Set whether to support preserving original header cases.
1213    ///
1214    /// Currently, this will record the original cases received, and store them
1215    /// in a private extension on the `Response`. It will also look for and use
1216    /// such an extension in any provided `Request`.
1217    ///
1218    /// Since the relevant extension is still private, there is no way to
1219    /// interact with the original cases. The only effect this can have now is
1220    /// to forward the cases in a proxy-like fashion.
1221    ///
1222    /// Note that this setting does not affect HTTP/2.
1223    ///
1224    /// Default is false.
1225    #[cfg(feature = "http1")]
1226    #[cfg_attr(docsrs, doc(cfg(feature = "http1")))]
1227    pub fn http1_preserve_header_case(&mut self, val: bool) -> &mut Self {
1228        self.h1_builder.preserve_header_case(val);
1229        self
1230    }
1231
1232    /// Set the maximum number of headers.
1233    ///
1234    /// When a response is received, the parser will reserve a buffer to store headers for optimal
1235    /// performance.
1236    ///
1237    /// If client receives more headers than the buffer size, the error "message header too large"
1238    /// is returned.
1239    ///
1240    /// The headers is allocated on the stack by default, which has higher performance. After
1241    /// setting this value, headers will be allocated in heap memory, that is, heap memory
1242    /// allocation will occur for each response, and there will be a performance drop of about 5%.
1243    ///
1244    /// Note that this setting does not affect HTTP/2.
1245    ///
1246    /// Default is 100.
1247    #[cfg(feature = "http1")]
1248    #[cfg_attr(docsrs, doc(cfg(feature = "http1")))]
1249    pub fn http1_max_headers(&mut self, val: usize) -> &mut Self {
1250        self.h1_builder.max_headers(val);
1251        self
1252    }
1253
1254    /// Set whether HTTP/0.9 responses should be tolerated.
1255    ///
1256    /// Default is false.
1257    #[cfg(feature = "http1")]
1258    #[cfg_attr(docsrs, doc(cfg(feature = "http1")))]
1259    pub fn http09_responses(&mut self, val: bool) -> &mut Self {
1260        self.h1_builder.http09_responses(val);
1261        self
1262    }
1263
1264    /// Set whether the connection **must** use HTTP/2.
1265    ///
1266    /// The destination must either allow HTTP2 Prior Knowledge, or the
1267    /// `Connect` should be configured to do use ALPN to upgrade to `h2`
1268    /// as part of the connection process. This will not make the `Client`
1269    /// utilize ALPN by itself.
1270    ///
1271    /// Note that setting this to true prevents HTTP/1 from being allowed.
1272    ///
1273    /// Default is false.
1274    #[cfg(feature = "http2")]
1275    #[cfg_attr(docsrs, doc(cfg(feature = "http2")))]
1276    pub fn http2_only(&mut self, val: bool) -> &mut Self {
1277        self.client_config.ver = if val { Ver::Http2 } else { Ver::Auto };
1278        self
1279    }
1280
1281    /// Configures the maximum number of pending reset streams allowed before a GOAWAY will be sent.
1282    ///
1283    /// This will default to the default value set by the [`h2` crate](https://crates.io/crates/h2).
1284    /// As of v0.4.0, it is 20.
1285    ///
1286    /// See <https://github.com/hyperium/hyper/issues/2877> for more information.
1287    #[cfg(feature = "http2")]
1288    #[cfg_attr(docsrs, doc(cfg(feature = "http2")))]
1289    pub fn http2_max_pending_accept_reset_streams(
1290        &mut self,
1291        max: impl Into<Option<usize>>,
1292    ) -> &mut Self {
1293        self.h2_builder.max_pending_accept_reset_streams(max.into());
1294        self
1295    }
1296
1297    /// Sets the [`SETTINGS_INITIAL_WINDOW_SIZE`][spec] option for HTTP2
1298    /// stream-level flow control.
1299    ///
1300    /// Passing `None` will do nothing.
1301    ///
1302    /// If not set, hyper will use a default.
1303    ///
1304    /// [spec]: https://http2.github.io/http2-spec/#SETTINGS_INITIAL_WINDOW_SIZE
1305    #[cfg(feature = "http2")]
1306    #[cfg_attr(docsrs, doc(cfg(feature = "http2")))]
1307    pub fn http2_initial_stream_window_size(&mut self, sz: impl Into<Option<u32>>) -> &mut Self {
1308        self.h2_builder.initial_stream_window_size(sz.into());
1309        self
1310    }
1311
1312    /// Sets the max connection-level flow control for HTTP2
1313    ///
1314    /// Passing `None` will do nothing.
1315    ///
1316    /// If not set, hyper will use a default.
1317    #[cfg(feature = "http2")]
1318    #[cfg_attr(docsrs, doc(cfg(feature = "http2")))]
1319    pub fn http2_initial_connection_window_size(
1320        &mut self,
1321        sz: impl Into<Option<u32>>,
1322    ) -> &mut Self {
1323        self.h2_builder.initial_connection_window_size(sz.into());
1324        self
1325    }
1326
1327    /// Sets the initial maximum of locally initiated (send) streams.
1328    ///
1329    /// This value will be overwritten by the value included in the initial
1330    /// SETTINGS frame received from the peer as part of a [connection preface].
1331    ///
1332    /// Passing `None` will do nothing.
1333    ///
1334    /// If not set, hyper will use a default.
1335    ///
1336    /// [connection preface]: https://httpwg.org/specs/rfc9113.html#preface
1337    #[cfg(feature = "http2")]
1338    #[cfg_attr(docsrs, doc(cfg(feature = "http2")))]
1339    pub fn http2_initial_max_send_streams(
1340        &mut self,
1341        initial: impl Into<Option<usize>>,
1342    ) -> &mut Self {
1343        self.h2_builder.initial_max_send_streams(initial);
1344        self
1345    }
1346
1347    /// Sets whether to use an adaptive flow control.
1348    ///
1349    /// Enabling this will override the limits set in
1350    /// `http2_initial_stream_window_size` and
1351    /// `http2_initial_connection_window_size`.
1352    #[cfg(feature = "http2")]
1353    #[cfg_attr(docsrs, doc(cfg(feature = "http2")))]
1354    pub fn http2_adaptive_window(&mut self, enabled: bool) -> &mut Self {
1355        self.h2_builder.adaptive_window(enabled);
1356        self
1357    }
1358
1359    /// Sets the maximum frame size to use for HTTP2.
1360    ///
1361    /// Passing `None` will do nothing.
1362    ///
1363    /// If not set, hyper will use a default.
1364    #[cfg(feature = "http2")]
1365    #[cfg_attr(docsrs, doc(cfg(feature = "http2")))]
1366    pub fn http2_max_frame_size(&mut self, sz: impl Into<Option<u32>>) -> &mut Self {
1367        self.h2_builder.max_frame_size(sz);
1368        self
1369    }
1370
1371    /// Sets the max size of received header frames for HTTP2.
1372    ///
1373    /// Default is currently 16KB, but can change.
1374    #[cfg(feature = "http2")]
1375    #[cfg_attr(docsrs, doc(cfg(feature = "http2")))]
1376    pub fn http2_max_header_list_size(&mut self, max: u32) -> &mut Self {
1377        self.h2_builder.max_header_list_size(max);
1378        self
1379    }
1380
1381    /// Sets an interval for HTTP2 Ping frames should be sent to keep a
1382    /// connection alive.
1383    ///
1384    /// Pass `None` to disable HTTP2 keep-alive.
1385    ///
1386    /// Default is currently disabled.
1387    ///
1388    /// # Cargo Feature
1389    ///
1390    /// Requires the `tokio` cargo feature to be enabled.
1391    #[cfg(feature = "tokio")]
1392    #[cfg(feature = "http2")]
1393    #[cfg_attr(docsrs, doc(cfg(feature = "http2")))]
1394    pub fn http2_keep_alive_interval(
1395        &mut self,
1396        interval: impl Into<Option<Duration>>,
1397    ) -> &mut Self {
1398        self.h2_builder.keep_alive_interval(interval);
1399        self
1400    }
1401
1402    /// Sets a timeout for receiving an acknowledgement of the keep-alive ping.
1403    ///
1404    /// If the ping is not acknowledged within the timeout, the connection will
1405    /// be closed. Does nothing if `http2_keep_alive_interval` is disabled.
1406    ///
1407    /// Default is 20 seconds.
1408    ///
1409    /// # Cargo Feature
1410    ///
1411    /// Requires the `tokio` cargo feature to be enabled.
1412    #[cfg(feature = "tokio")]
1413    #[cfg(feature = "http2")]
1414    #[cfg_attr(docsrs, doc(cfg(feature = "http2")))]
1415    pub fn http2_keep_alive_timeout(&mut self, timeout: Duration) -> &mut Self {
1416        self.h2_builder.keep_alive_timeout(timeout);
1417        self
1418    }
1419
1420    /// Sets whether HTTP2 keep-alive should apply while the connection is idle.
1421    ///
1422    /// If disabled, keep-alive pings are only sent while there are open
1423    /// request/responses streams. If enabled, pings are also sent when no
1424    /// streams are active. Does nothing if `http2_keep_alive_interval` is
1425    /// disabled.
1426    ///
1427    /// Default is `false`.
1428    ///
1429    /// # Cargo Feature
1430    ///
1431    /// Requires the `tokio` cargo feature to be enabled.
1432    #[cfg(feature = "tokio")]
1433    #[cfg(feature = "http2")]
1434    #[cfg_attr(docsrs, doc(cfg(feature = "http2")))]
1435    pub fn http2_keep_alive_while_idle(&mut self, enabled: bool) -> &mut Self {
1436        self.h2_builder.keep_alive_while_idle(enabled);
1437        self
1438    }
1439
1440    /// Sets the maximum number of HTTP2 concurrent locally reset streams.
1441    ///
1442    /// See the documentation of [`h2::client::Builder::max_concurrent_reset_streams`] for more
1443    /// details.
1444    ///
1445    /// The default value is determined by the `h2` crate.
1446    ///
1447    /// [`h2::client::Builder::max_concurrent_reset_streams`]: https://docs.rs/h2/client/struct.Builder.html#method.max_concurrent_reset_streams
1448    #[cfg(feature = "http2")]
1449    #[cfg_attr(docsrs, doc(cfg(feature = "http2")))]
1450    pub fn http2_max_concurrent_reset_streams(&mut self, max: usize) -> &mut Self {
1451        self.h2_builder.max_concurrent_reset_streams(max);
1452        self
1453    }
1454
1455    /// Provide a timer to be used for h2
1456    ///
1457    /// See the documentation of [`h2::client::Builder::timer`] for more
1458    /// details.
1459    ///
1460    /// [`h2::client::Builder::timer`]: https://docs.rs/h2/client/struct.Builder.html#method.timer
1461    pub fn timer<M>(&mut self, timer: M) -> &mut Self
1462    where
1463        M: Timer + Send + Sync + 'static,
1464    {
1465        #[cfg(feature = "http2")]
1466        self.h2_builder.timer(timer);
1467        self
1468    }
1469
1470    /// Provide a timer to be used for timeouts and intervals in connection pools.
1471    pub fn pool_timer<M>(&mut self, timer: M) -> &mut Self
1472    where
1473        M: Timer + Clone + Send + Sync + 'static,
1474    {
1475        self.pool_timer = Some(timer::Timer::new(timer.clone()));
1476        self
1477    }
1478
1479    /// Set the maximum write buffer size for each HTTP/2 stream.
1480    ///
1481    /// Default is currently 1MB, but may change.
1482    ///
1483    /// # Panics
1484    ///
1485    /// The value must be no larger than `u32::MAX`.
1486    #[cfg(feature = "http2")]
1487    #[cfg_attr(docsrs, doc(cfg(feature = "http2")))]
1488    pub fn http2_max_send_buf_size(&mut self, max: usize) -> &mut Self {
1489        self.h2_builder.max_send_buf_size(max);
1490        self
1491    }
1492
1493    /// Set whether to retry requests that get disrupted before ever starting
1494    /// to write.
1495    ///
1496    /// This means a request that is queued, and gets given an idle, reused
1497    /// connection, and then encounters an error immediately as the idle
1498    /// connection was found to be unusable.
1499    ///
1500    /// When this is set to `false`, the related `ResponseFuture` would instead
1501    /// resolve to an `Error::Cancel`.
1502    ///
1503    /// Default is `true`.
1504    #[inline]
1505    pub fn retry_canceled_requests(&mut self, val: bool) -> &mut Self {
1506        self.client_config.retry_canceled_requests = val;
1507        self
1508    }
1509
1510    /// Set whether to automatically add the `Host` header to requests.
1511    ///
1512    /// If true, and a request does not include a `Host` header, one will be
1513    /// added automatically, derived from the authority of the `Uri`.
1514    ///
1515    /// Default is `true`.
1516    #[inline]
1517    pub fn set_host(&mut self, val: bool) -> &mut Self {
1518        self.client_config.set_host = val;
1519        self
1520    }
1521
1522    /// Build a client with this configuration and the default `HttpConnector`.
1523    #[cfg(feature = "tokio")]
1524    pub fn build_http<B>(&self) -> Client<HttpConnector, B>
1525    where
1526        B: Body + Send,
1527        B::Data: Send,
1528    {
1529        let mut connector = HttpConnector::new();
1530        if self.pool_config.is_enabled() {
1531            connector.set_keepalive(self.pool_config.idle_timeout);
1532        }
1533        self.build(connector)
1534    }
1535
1536    /// Combine the configuration of this builder with a connector to create a `Client`.
1537    pub fn build<C, B>(&self, connector: C) -> Client<C, B>
1538    where
1539        C: Connect + Clone,
1540        B: Body + Send,
1541        B::Data: Send,
1542    {
1543        let exec = self.exec.clone();
1544        let timer = self.pool_timer.clone();
1545        Client {
1546            config: self.client_config,
1547            exec: exec.clone(),
1548            #[cfg(feature = "http1")]
1549            h1_builder: self.h1_builder.clone(),
1550            #[cfg(feature = "http2")]
1551            h2_builder: self.h2_builder.clone(),
1552            connector,
1553            pool: pool::Pool::new(self.pool_config, exec, timer),
1554        }
1555    }
1556}
1557
1558impl fmt::Debug for Builder {
1559    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1560        f.debug_struct("Builder")
1561            .field("client_config", &self.client_config)
1562            .field("pool_config", &self.pool_config)
1563            .finish()
1564    }
1565}
1566
1567// ==== impl Error ====
1568
1569impl fmt::Debug for Error {
1570    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1571        let mut f = f.debug_tuple("hyper_util::client::legacy::Error");
1572        f.field(&self.kind);
1573        if let Some(ref cause) = self.source {
1574            f.field(cause);
1575        }
1576        f.finish()
1577    }
1578}
1579
1580impl fmt::Display for Error {
1581    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1582        write!(f, "client error ({:?})", self.kind)
1583    }
1584}
1585
1586impl StdError for Error {
1587    fn source(&self) -> Option<&(dyn StdError + 'static)> {
1588        self.source.as_ref().map(|e| &**e as _)
1589    }
1590}
1591
1592impl Error {
1593    /// Returns true if this was an error from `Connect`.
1594    pub fn is_connect(&self) -> bool {
1595        matches!(self.kind, ErrorKind::Connect)
1596    }
1597
1598    /// Returns the info of the client connection on which this error occurred.
1599    #[cfg(any(feature = "http1", feature = "http2"))]
1600    pub fn connect_info(&self) -> Option<&Connected> {
1601        self.connect_info.as_ref()
1602    }
1603
1604    #[cfg(any(feature = "http1", feature = "http2"))]
1605    fn with_connect_info(self, connect_info: Connected) -> Self {
1606        Self {
1607            connect_info: Some(connect_info),
1608            ..self
1609        }
1610    }
1611    fn is_canceled(&self) -> bool {
1612        matches!(self.kind, ErrorKind::Canceled)
1613    }
1614
1615    fn tx(src: hyper::Error) -> Self {
1616        e!(SendRequest, src)
1617    }
1618
1619    fn closed(src: hyper::Error) -> Self {
1620        e!(ChannelClosed, src)
1621    }
1622}