reqwest/blocking/client.rs
1#[cfg(any(feature = "native-tls", feature = "__rustls",))]
2use std::any::Any;
3use std::convert::TryInto;
4use std::fmt;
5use std::future::Future;
6use std::net::IpAddr;
7use std::net::SocketAddr;
8use std::sync::Arc;
9use std::task::ready;
10use std::thread;
11use std::time::Duration;
12
13use http::header::HeaderValue;
14use log::{error, trace};
15use tokio::sync::{mpsc, oneshot};
16use tower::Layer;
17use tower::Service;
18
19use super::request::{Request, RequestBuilder};
20use super::response::Response;
21use super::wait;
22use crate::connect::sealed::{Conn, Unnameable};
23use crate::connect::BoxedConnectorService;
24use crate::dns::Resolve;
25use crate::error::BoxError;
26#[cfg(feature = "__tls")]
27use crate::tls;
28#[cfg(feature = "__rustls")]
29use crate::tls::CertificateRevocationList;
30#[cfg(feature = "__tls")]
31use crate::Certificate;
32#[cfg(any(feature = "native-tls", feature = "__rustls"))]
33use crate::Identity;
34use crate::{async_impl, header, redirect, IntoUrl, Method, Proxy};
35
36/// A `Client` to make Requests with.
37///
38/// The Client has various configuration values to tweak, but the defaults
39/// are set to what is usually the most commonly desired value. To configure a
40/// `Client`, use `Client::builder()`.
41///
42/// The `Client` holds a connection pool internally, so it is advised that
43/// you create one and **reuse** it.
44///
45/// # Examples
46///
47/// ```rust
48/// use reqwest::blocking::Client;
49/// #
50/// # fn run() -> Result<(), reqwest::Error> {
51/// let client = Client::new();
52/// let resp = client.get("http://httpbin.org/").send()?;
53/// # drop(resp);
54/// # Ok(())
55/// # }
56///
57/// ```
58#[derive(Clone)]
59pub struct Client {
60 inner: ClientHandle,
61}
62
63/// A `ClientBuilder` can be used to create a `Client` with custom configuration.
64///
65/// # Example
66///
67/// ```
68/// # fn run() -> Result<(), reqwest::Error> {
69/// use std::time::Duration;
70///
71/// let client = reqwest::blocking::Client::builder()
72/// .timeout(Duration::from_secs(10))
73/// .build()?;
74/// # Ok(())
75/// # }
76/// ```
77#[must_use]
78pub struct ClientBuilder {
79 inner: async_impl::ClientBuilder,
80 timeout: Timeout,
81}
82
83impl Default for ClientBuilder {
84 fn default() -> Self {
85 Self::new()
86 }
87}
88
89impl ClientBuilder {
90 /// Constructs a new `ClientBuilder`.
91 ///
92 /// This is the same as `Client::builder()`.
93 pub fn new() -> Self {
94 ClientBuilder {
95 inner: async_impl::ClientBuilder::new(),
96 timeout: Timeout::default(),
97 }
98 }
99}
100
101impl ClientBuilder {
102 /// Returns a `Client` that uses this `ClientBuilder` configuration.
103 ///
104 /// # Errors
105 ///
106 /// This method fails if TLS backend cannot be initialized, or the resolver
107 /// cannot load the system configuration.
108 ///
109 /// # Panics
110 ///
111 /// This method panics if called from within an async runtime. See docs on
112 /// [`reqwest::blocking`][crate::blocking] for details.
113 pub fn build(self) -> crate::Result<Client> {
114 ClientHandle::new(self).map(|handle| Client { inner: handle })
115 }
116
117 // Higher-level options
118
119 /// Sets the `User-Agent` header to be used by this client.
120 ///
121 /// # Example
122 ///
123 /// ```rust
124 /// # fn doc() -> Result<(), reqwest::Error> {
125 /// // Name your user agent after your app?
126 /// static APP_USER_AGENT: &str = concat!(
127 /// env!("CARGO_PKG_NAME"),
128 /// "/",
129 /// env!("CARGO_PKG_VERSION"),
130 /// );
131 ///
132 /// let client = reqwest::blocking::Client::builder()
133 /// .user_agent(APP_USER_AGENT)
134 /// .build()?;
135 /// let res = client.get("https://www.rust-lang.org").send()?;
136 /// # Ok(())
137 /// # }
138 /// ```
139 pub fn user_agent<V>(self, value: V) -> ClientBuilder
140 where
141 V: TryInto<HeaderValue>,
142 V::Error: Into<http::Error>,
143 {
144 self.with_inner(move |inner| inner.user_agent(value))
145 }
146
147 /// Sets the default headers for every request.
148 ///
149 /// # Example
150 ///
151 /// ```rust
152 /// use reqwest::header;
153 /// # fn build_client() -> Result<(), reqwest::Error> {
154 /// let mut headers = header::HeaderMap::new();
155 /// headers.insert("X-MY-HEADER", header::HeaderValue::from_static("value"));
156 /// headers.insert(header::AUTHORIZATION, header::HeaderValue::from_static("secret"));
157 ///
158 /// // Consider marking security-sensitive headers with `set_sensitive`.
159 /// let mut auth_value = header::HeaderValue::from_static("secret");
160 /// auth_value.set_sensitive(true);
161 /// headers.insert(header::AUTHORIZATION, auth_value);
162 ///
163 /// // get a client builder
164 /// let client = reqwest::blocking::Client::builder()
165 /// .default_headers(headers)
166 /// .build()?;
167 /// let res = client.get("https://www.rust-lang.org").send()?;
168 /// # Ok(())
169 /// # }
170 /// ```
171 pub fn default_headers(self, headers: header::HeaderMap) -> ClientBuilder {
172 self.with_inner(move |inner| inner.default_headers(headers))
173 }
174
175 /// Enable a persistent cookie store for the client.
176 ///
177 /// Cookies received in responses will be preserved and included in
178 /// additional requests.
179 ///
180 /// By default, no cookie store is used.
181 ///
182 /// # Optional
183 ///
184 /// This requires the optional `cookies` feature to be enabled.
185 #[cfg(feature = "cookies")]
186 #[cfg_attr(docsrs, doc(cfg(feature = "cookies")))]
187 pub fn cookie_store(self, enable: bool) -> ClientBuilder {
188 self.with_inner(|inner| inner.cookie_store(enable))
189 }
190
191 /// Set the persistent cookie store for the client.
192 ///
193 /// Cookies received in responses will be passed to this store, and
194 /// additional requests will query this store for cookies.
195 ///
196 /// By default, no cookie store is used.
197 ///
198 /// # Optional
199 ///
200 /// This requires the optional `cookies` feature to be enabled.
201 #[cfg(feature = "cookies")]
202 #[cfg_attr(docsrs, doc(cfg(feature = "cookies")))]
203 pub fn cookie_provider<C: crate::cookie::CookieStore + 'static>(
204 self,
205 cookie_store: Arc<C>,
206 ) -> ClientBuilder {
207 self.with_inner(|inner| inner.cookie_provider(cookie_store))
208 }
209
210 /// Enable auto gzip decompression by checking the `Content-Encoding` response header.
211 ///
212 /// If auto gzip decompression is turned on:
213 ///
214 /// - When sending a request and if the request's headers do not already contain
215 /// an `Accept-Encoding` **and** `Range` values, the `Accept-Encoding` header is set to `gzip`.
216 /// The request body is **not** automatically compressed.
217 /// - When receiving a response, if it's headers contain a `Content-Encoding` value that
218 /// equals to `gzip`, both values `Content-Encoding` and `Content-Length` are removed from the
219 /// headers' set. The response body is automatically decompressed.
220 ///
221 /// If the `gzip` feature is turned on, the default option is enabled.
222 ///
223 /// # Optional
224 ///
225 /// This requires the optional `gzip` feature to be enabled
226 #[cfg(feature = "gzip")]
227 #[cfg_attr(docsrs, doc(cfg(feature = "gzip")))]
228 pub fn gzip(self, enable: bool) -> ClientBuilder {
229 self.with_inner(|inner| inner.gzip(enable))
230 }
231
232 /// Enable auto brotli decompression by checking the `Content-Encoding` response header.
233 ///
234 /// If auto brotli decompression is turned on:
235 ///
236 /// - When sending a request and if the request's headers do not already contain
237 /// an `Accept-Encoding` **and** `Range` values, the `Accept-Encoding` header is set to `br`.
238 /// The request body is **not** automatically compressed.
239 /// - When receiving a response, if it's headers contain a `Content-Encoding` value that
240 /// equals to `br`, both values `Content-Encoding` and `Content-Length` are removed from the
241 /// headers' set. The response body is automatically decompressed.
242 ///
243 /// If the `brotli` feature is turned on, the default option is enabled.
244 ///
245 /// # Optional
246 ///
247 /// This requires the optional `brotli` feature to be enabled
248 #[cfg(feature = "brotli")]
249 #[cfg_attr(docsrs, doc(cfg(feature = "brotli")))]
250 pub fn brotli(self, enable: bool) -> ClientBuilder {
251 self.with_inner(|inner| inner.brotli(enable))
252 }
253
254 /// Enable auto zstd decompression by checking the `Content-Encoding` response header.
255 ///
256 /// If auto zstd decompression is turned on:
257 ///
258 /// - When sending a request and if the request's headers do not already contain
259 /// an `Accept-Encoding` **and** `Range` values, the `Accept-Encoding` header is set to `zstd`.
260 /// The request body is **not** automatically compressed.
261 /// - When receiving a response, if its headers contain a `Content-Encoding` value of
262 /// `zstd`, both `Content-Encoding` and `Content-Length` are removed from the
263 /// headers' set. The response body is automatically decompressed.
264 ///
265 /// If the `zstd` feature is turned on, the default option is enabled.
266 ///
267 /// # Optional
268 ///
269 /// This requires the optional `zstd` feature to be enabled
270 #[cfg(feature = "zstd")]
271 #[cfg_attr(docsrs, doc(cfg(feature = "zstd")))]
272 pub fn zstd(self, enable: bool) -> ClientBuilder {
273 self.with_inner(|inner| inner.zstd(enable))
274 }
275
276 /// Enable auto deflate decompression by checking the `Content-Encoding` response header.
277 ///
278 /// If auto deflate decompression is turned on:
279 ///
280 /// - When sending a request and if the request's headers do not already contain
281 /// an `Accept-Encoding` **and** `Range` values, the `Accept-Encoding` header is set to `deflate`.
282 /// The request body is **not** automatically compressed.
283 /// - When receiving a response, if it's headers contain a `Content-Encoding` value that
284 /// equals to `deflate`, both values `Content-Encoding` and `Content-Length` are removed from the
285 /// headers' set. The response body is automatically decompressed.
286 ///
287 /// If the `deflate` feature is turned on, the default option is enabled.
288 ///
289 /// # Optional
290 ///
291 /// This requires the optional `deflate` feature to be enabled
292 #[cfg(feature = "deflate")]
293 #[cfg_attr(docsrs, doc(cfg(feature = "deflate")))]
294 pub fn deflate(self, enable: bool) -> ClientBuilder {
295 self.with_inner(|inner| inner.deflate(enable))
296 }
297
298 /// Disable auto response body gzip decompression.
299 ///
300 /// This method exists even if the optional `gzip` feature is not enabled.
301 /// This can be used to ensure a `Client` doesn't use gzip decompression
302 /// even if another dependency were to enable the optional `gzip` feature.
303 pub fn no_gzip(self) -> ClientBuilder {
304 self.with_inner(|inner| inner.no_gzip())
305 }
306
307 /// Disable auto response body brotli decompression.
308 ///
309 /// This method exists even if the optional `brotli` feature is not enabled.
310 /// This can be used to ensure a `Client` doesn't use brotli decompression
311 /// even if another dependency were to enable the optional `brotli` feature.
312 pub fn no_brotli(self) -> ClientBuilder {
313 self.with_inner(|inner| inner.no_brotli())
314 }
315
316 /// Disable auto response body zstd decompression.
317 ///
318 /// This method exists even if the optional `zstd` feature is not enabled.
319 /// This can be used to ensure a `Client` doesn't use zstd decompression
320 /// even if another dependency were to enable the optional `zstd` feature.
321 pub fn no_zstd(self) -> ClientBuilder {
322 self.with_inner(|inner| inner.no_zstd())
323 }
324
325 /// Disable auto response body deflate decompression.
326 ///
327 /// This method exists even if the optional `deflate` feature is not enabled.
328 /// This can be used to ensure a `Client` doesn't use deflate decompression
329 /// even if another dependency were to enable the optional `deflate` feature.
330 pub fn no_deflate(self) -> ClientBuilder {
331 self.with_inner(|inner| inner.no_deflate())
332 }
333
334 // Redirect options
335
336 /// Set a `redirect::Policy` for this client.
337 ///
338 /// Default will follow redirects up to a maximum of 10.
339 pub fn redirect(self, policy: redirect::Policy) -> ClientBuilder {
340 self.with_inner(move |inner| inner.redirect(policy))
341 }
342
343 /// Enable or disable automatic setting of the `Referer` header.
344 ///
345 /// Default is `true`.
346 pub fn referer(self, enable: bool) -> ClientBuilder {
347 self.with_inner(|inner| inner.referer(enable))
348 }
349
350 // Proxy options
351
352 /// Add a `Proxy` to the list of proxies the `Client` will use.
353 ///
354 /// # Note
355 ///
356 /// Adding a proxy will disable the automatic usage of the "system" proxy.
357 pub fn proxy(self, proxy: Proxy) -> ClientBuilder {
358 self.with_inner(move |inner| inner.proxy(proxy))
359 }
360
361 /// Clear all `Proxies`, so `Client` will use no proxy anymore.
362 ///
363 /// # Note
364 /// To add a proxy exclusion list, use [Proxy::no_proxy()]
365 /// on all desired proxies instead.
366 ///
367 /// This also disables the automatic usage of the "system" proxy.
368 pub fn no_proxy(self) -> ClientBuilder {
369 self.with_inner(move |inner| inner.no_proxy())
370 }
371
372 // Timeout options
373
374 /// Set a timeout for connect, read and write operations of a `Client`.
375 ///
376 /// Default is 30 seconds.
377 ///
378 /// Pass `None` to disable timeout.
379 pub fn timeout<T>(mut self, timeout: T) -> ClientBuilder
380 where
381 T: Into<Option<Duration>>,
382 {
383 self.timeout = Timeout(timeout.into());
384 self
385 }
386
387 /// Set a timeout for only the connect phase of a `Client`.
388 ///
389 /// Default is `None`.
390 pub fn connect_timeout<T>(self, timeout: T) -> ClientBuilder
391 where
392 T: Into<Option<Duration>>,
393 {
394 let timeout = timeout.into();
395 if let Some(dur) = timeout {
396 self.with_inner(|inner| inner.connect_timeout(dur))
397 } else {
398 self
399 }
400 }
401
402 /// Set whether connections should emit verbose logs.
403 ///
404 /// Enabling this option will emit [log][] messages at the `TRACE` level
405 /// for read and write operations on connections.
406 ///
407 /// [log]: https://crates.io/crates/log
408 pub fn connection_verbose(self, verbose: bool) -> ClientBuilder {
409 self.with_inner(move |inner| inner.connection_verbose(verbose))
410 }
411
412 // HTTP options
413
414 /// Set an optional timeout for idle sockets being kept-alive.
415 ///
416 /// Pass `None` to disable timeout.
417 ///
418 /// Default is 90 seconds.
419 pub fn pool_idle_timeout<D>(self, val: D) -> ClientBuilder
420 where
421 D: Into<Option<Duration>>,
422 {
423 self.with_inner(|inner| inner.pool_idle_timeout(val))
424 }
425
426 /// Sets the maximum idle connection per host allowed in the pool.
427 pub fn pool_max_idle_per_host(self, max: usize) -> ClientBuilder {
428 self.with_inner(move |inner| inner.pool_max_idle_per_host(max))
429 }
430
431 /// Send headers as title case instead of lowercase.
432 pub fn http1_title_case_headers(self) -> ClientBuilder {
433 self.with_inner(|inner| inner.http1_title_case_headers())
434 }
435
436 /// Set whether HTTP/1 connections will accept obsolete line folding for
437 /// header values.
438 ///
439 /// Newline codepoints (`\r` and `\n`) will be transformed to spaces when
440 /// parsing.
441 pub fn http1_allow_obsolete_multiline_headers_in_responses(self, value: bool) -> ClientBuilder {
442 self.with_inner(|inner| inner.http1_allow_obsolete_multiline_headers_in_responses(value))
443 }
444
445 /// Sets whether invalid header lines should be silently ignored in HTTP/1 responses.
446 pub fn http1_ignore_invalid_headers_in_responses(self, value: bool) -> ClientBuilder {
447 self.with_inner(|inner| inner.http1_ignore_invalid_headers_in_responses(value))
448 }
449
450 /// Set whether HTTP/1 connections will accept spaces between header
451 /// names and the colon that follow them in responses.
452 ///
453 /// Newline codepoints (\r and \n) will be transformed to spaces when
454 /// parsing.
455 pub fn http1_allow_spaces_after_header_name_in_responses(self, value: bool) -> ClientBuilder {
456 self.with_inner(|inner| inner.http1_allow_spaces_after_header_name_in_responses(value))
457 }
458
459 /// Only use HTTP/1.
460 pub fn http1_only(self) -> ClientBuilder {
461 self.with_inner(|inner| inner.http1_only())
462 }
463
464 /// Allow HTTP/0.9 responses
465 pub fn http09_responses(self) -> ClientBuilder {
466 self.with_inner(|inner| inner.http09_responses())
467 }
468
469 /// Only use HTTP/2.
470 #[cfg(feature = "http2")]
471 #[cfg_attr(docsrs, doc(cfg(feature = "http2")))]
472 pub fn http2_prior_knowledge(self) -> ClientBuilder {
473 self.with_inner(|inner| inner.http2_prior_knowledge())
474 }
475
476 /// Sets the `SETTINGS_INITIAL_WINDOW_SIZE` option for HTTP2 stream-level flow control.
477 ///
478 /// Default is currently 65,535 but may change internally to optimize for common uses.
479 #[cfg(feature = "http2")]
480 #[cfg_attr(docsrs, doc(cfg(feature = "http2")))]
481 pub fn http2_initial_stream_window_size(self, sz: impl Into<Option<u32>>) -> ClientBuilder {
482 self.with_inner(|inner| inner.http2_initial_stream_window_size(sz))
483 }
484
485 /// Sets the max connection-level flow control for HTTP2
486 ///
487 /// Default is currently 65,535 but may change internally to optimize for common uses.
488 #[cfg(feature = "http2")]
489 #[cfg_attr(docsrs, doc(cfg(feature = "http2")))]
490 pub fn http2_initial_connection_window_size(self, sz: impl Into<Option<u32>>) -> ClientBuilder {
491 self.with_inner(|inner| inner.http2_initial_connection_window_size(sz))
492 }
493
494 /// Sets whether to use an adaptive flow control.
495 ///
496 /// Enabling this will override the limits set in `http2_initial_stream_window_size` and
497 /// `http2_initial_connection_window_size`.
498 #[cfg(feature = "http2")]
499 #[cfg_attr(docsrs, doc(cfg(feature = "http2")))]
500 pub fn http2_adaptive_window(self, enabled: bool) -> ClientBuilder {
501 self.with_inner(|inner| inner.http2_adaptive_window(enabled))
502 }
503
504 /// Sets the maximum frame size to use for HTTP2.
505 ///
506 /// Default is currently 16,384 but may change internally to optimize for common uses.
507 #[cfg(feature = "http2")]
508 #[cfg_attr(docsrs, doc(cfg(feature = "http2")))]
509 pub fn http2_max_frame_size(self, sz: impl Into<Option<u32>>) -> ClientBuilder {
510 self.with_inner(|inner| inner.http2_max_frame_size(sz))
511 }
512
513 /// Sets the maximum size of received header frames for HTTP2.
514 ///
515 /// Default is currently 16KB, but can change.
516 #[cfg(feature = "http2")]
517 #[cfg_attr(docsrs, doc(cfg(feature = "http2")))]
518 pub fn http2_max_header_list_size(self, max_header_size_bytes: u32) -> ClientBuilder {
519 self.with_inner(|inner| inner.http2_max_header_list_size(max_header_size_bytes))
520 }
521
522 /// This requires the optional `http3` feature to be
523 /// enabled.
524 #[cfg(feature = "http3")]
525 #[cfg_attr(docsrs, doc(cfg(feature = "http3")))]
526 pub fn http3_prior_knowledge(self) -> ClientBuilder {
527 self.with_inner(|inner| inner.http3_prior_knowledge())
528 }
529
530 // TCP options
531
532 /// Set whether sockets have `TCP_NODELAY` enabled.
533 ///
534 /// Default is `true`.
535 pub fn tcp_nodelay(self, enabled: bool) -> ClientBuilder {
536 self.with_inner(move |inner| inner.tcp_nodelay(enabled))
537 }
538
539 /// Bind to a local IP Address.
540 ///
541 /// # Example
542 ///
543 /// ```
544 /// use std::net::IpAddr;
545 /// let local_addr = IpAddr::from([12, 4, 1, 8]);
546 /// let client = reqwest::blocking::Client::builder()
547 /// .local_address(local_addr)
548 /// .build().unwrap();
549 /// ```
550 pub fn local_address<T>(self, addr: T) -> ClientBuilder
551 where
552 T: Into<Option<IpAddr>>,
553 {
554 self.with_inner(move |inner| inner.local_address(addr))
555 }
556
557 /// Bind to an interface by `SO_BINDTODEVICE`.
558 ///
559 /// # Example
560 ///
561 /// ```
562 /// let interface = "lo";
563 /// let client = reqwest::blocking::Client::builder()
564 /// .interface(interface)
565 /// .build().unwrap();
566 /// ```
567 #[cfg(any(target_os = "android", target_os = "fuchsia", target_os = "linux"))]
568 pub fn interface(self, interface: &str) -> ClientBuilder {
569 self.with_inner(move |inner| inner.interface(interface))
570 }
571
572 /// Set that all sockets have `SO_KEEPALIVE` set with the supplied duration.
573 ///
574 /// If `None`, the option will not be set.
575 pub fn tcp_keepalive<D>(self, val: D) -> ClientBuilder
576 where
577 D: Into<Option<Duration>>,
578 {
579 self.with_inner(move |inner| inner.tcp_keepalive(val))
580 }
581
582 // TLS options
583
584 /// Add a custom root certificate.
585 ///
586 /// This allows connecting to a server that has a self-signed
587 /// certificate for example. This **does not** replace the existing
588 /// trusted store.
589 ///
590 /// # Example
591 ///
592 /// ```
593 /// # use std::fs::File;
594 /// # use std::io::Read;
595 /// # fn build_client() -> Result<(), Box<dyn std::error::Error>> {
596 /// // read a local binary DER encoded certificate
597 /// let der = std::fs::read("my-cert.der")?;
598 ///
599 /// // create a certificate
600 /// let cert = reqwest::Certificate::from_der(&der)?;
601 ///
602 /// // get a client builder
603 /// let client = reqwest::blocking::Client::builder()
604 /// .add_root_certificate(cert)
605 /// .build()?;
606 /// # drop(client);
607 /// # Ok(())
608 /// # }
609 /// ```
610 ///
611 /// # Optional
612 ///
613 /// This requires the optional `default-tls`, `native-tls`, or `rustls-tls(-...)`
614 /// feature to be enabled.
615 #[cfg(feature = "__tls")]
616 #[cfg_attr(
617 docsrs,
618 doc(cfg(any(
619 feature = "default-tls",
620 feature = "native-tls",
621 feature = "rustls-tls"
622 )))
623 )]
624 pub fn add_root_certificate(self, cert: Certificate) -> ClientBuilder {
625 self.with_inner(move |inner| inner.add_root_certificate(cert))
626 }
627
628 /// Add a certificate revocation list.
629 ///
630 ///
631 /// # Optional
632 ///
633 /// This requires the `rustls-tls(-...)` Cargo feature enabled.
634 #[cfg(feature = "__rustls")]
635 #[cfg_attr(docsrs, doc(cfg(feature = "rustls-tls")))]
636 pub fn add_crl(self, crl: CertificateRevocationList) -> ClientBuilder {
637 self.with_inner(move |inner| inner.add_crl(crl))
638 }
639
640 /// Add multiple certificate revocation lists.
641 ///
642 ///
643 /// # Optional
644 ///
645 /// This requires the `rustls-tls(-...)` Cargo feature enabled.
646 #[cfg(feature = "__rustls")]
647 #[cfg_attr(docsrs, doc(cfg(feature = "rustls-tls")))]
648 pub fn add_crls(
649 self,
650 crls: impl IntoIterator<Item = CertificateRevocationList>,
651 ) -> ClientBuilder {
652 self.with_inner(move |inner| inner.add_crls(crls))
653 }
654
655 /// Controls the use of built-in system certificates during certificate validation.
656 ///
657 /// Defaults to `true` -- built-in system certs will be used.
658 ///
659 /// # Optional
660 ///
661 /// This requires the optional `default-tls`, `native-tls`, or `rustls-tls(-...)`
662 /// feature to be enabled.
663 #[cfg(feature = "__tls")]
664 #[cfg_attr(
665 docsrs,
666 doc(cfg(any(
667 feature = "default-tls",
668 feature = "native-tls",
669 feature = "rustls-tls"
670 )))
671 )]
672 pub fn tls_built_in_root_certs(self, tls_built_in_root_certs: bool) -> ClientBuilder {
673 self.with_inner(move |inner| inner.tls_built_in_root_certs(tls_built_in_root_certs))
674 }
675
676 /// Sets whether to load webpki root certs with rustls.
677 ///
678 /// If the feature is enabled, this value is `true` by default.
679 #[cfg(feature = "rustls-tls-webpki-roots-no-provider")]
680 #[cfg_attr(docsrs, doc(cfg(feature = "rustls-tls-webpki-roots-no-provider")))]
681 pub fn tls_built_in_webpki_certs(self, enabled: bool) -> ClientBuilder {
682 self.with_inner(move |inner| inner.tls_built_in_webpki_certs(enabled))
683 }
684
685 /// Sets whether to load native root certs with rustls.
686 ///
687 /// If the feature is enabled, this value is `true` by default.
688 #[cfg(feature = "rustls-tls-native-roots-no-provider")]
689 #[cfg_attr(docsrs, doc(cfg(feature = "rustls-tls-native-roots-no-provider")))]
690 pub fn tls_built_in_native_certs(self, enabled: bool) -> ClientBuilder {
691 self.with_inner(move |inner| inner.tls_built_in_native_certs(enabled))
692 }
693
694 /// Sets the identity to be used for client certificate authentication.
695 ///
696 /// # Optional
697 ///
698 /// This requires the optional `native-tls` or `rustls-tls(-...)` feature to be
699 /// enabled.
700 #[cfg(any(feature = "native-tls", feature = "__rustls"))]
701 #[cfg_attr(docsrs, doc(cfg(any(feature = "native-tls", feature = "rustls-tls"))))]
702 pub fn identity(self, identity: Identity) -> ClientBuilder {
703 self.with_inner(move |inner| inner.identity(identity))
704 }
705
706 /// Controls the use of hostname verification.
707 ///
708 /// Defaults to `false`.
709 ///
710 /// # Warning
711 ///
712 /// You should think very carefully before you use this method. If
713 /// hostname verification is not used, any valid certificate for any
714 /// site will be trusted for use from any other. This introduces a
715 /// significant vulnerability to man-in-the-middle attacks.
716 ///
717 /// # Optional
718 ///
719 /// This requires the optional `default-tls`, `native-tls`, or `rustls-tls(-...)`
720 /// feature to be enabled.
721 #[cfg(feature = "__tls")]
722 #[cfg_attr(
723 docsrs,
724 doc(cfg(any(
725 feature = "default-tls",
726 feature = "native-tls",
727 feature = "rustls-tls"
728 )))
729 )]
730 pub fn danger_accept_invalid_hostnames(self, accept_invalid_hostname: bool) -> ClientBuilder {
731 self.with_inner(|inner| inner.danger_accept_invalid_hostnames(accept_invalid_hostname))
732 }
733
734 /// Controls the use of certificate validation.
735 ///
736 /// Defaults to `false`.
737 ///
738 /// # Warning
739 ///
740 /// You should think very carefully before using this method. If
741 /// invalid certificates are trusted, *any* certificate for *any* site
742 /// will be trusted for use. This includes expired certificates. This
743 /// introduces significant vulnerabilities, and should only be used
744 /// as a last resort.
745 #[cfg(feature = "__tls")]
746 #[cfg_attr(
747 docsrs,
748 doc(cfg(any(
749 feature = "default-tls",
750 feature = "native-tls",
751 feature = "rustls-tls"
752 )))
753 )]
754 pub fn danger_accept_invalid_certs(self, accept_invalid_certs: bool) -> ClientBuilder {
755 self.with_inner(|inner| inner.danger_accept_invalid_certs(accept_invalid_certs))
756 }
757
758 /// Controls the use of TLS server name indication.
759 ///
760 /// Defaults to `true`.
761 #[cfg(feature = "__tls")]
762 #[cfg_attr(
763 docsrs,
764 doc(cfg(any(
765 feature = "default-tls",
766 feature = "native-tls",
767 feature = "rustls-tls"
768 )))
769 )]
770 pub fn tls_sni(self, tls_sni: bool) -> ClientBuilder {
771 self.with_inner(|inner| inner.tls_sni(tls_sni))
772 }
773
774 /// Set the minimum required TLS version for connections.
775 ///
776 /// By default, the TLS backend's own default is used.
777 ///
778 /// # Errors
779 ///
780 /// A value of `tls::Version::TLS_1_3` will cause an error with the
781 /// `native-tls`/`default-tls` backend. This does not mean the version
782 /// isn't supported, just that it can't be set as a minimum due to
783 /// technical limitations.
784 ///
785 /// # Optional
786 ///
787 /// This requires the optional `default-tls`, `native-tls`, or `rustls-tls(-...)`
788 /// feature to be enabled.
789 #[cfg(feature = "__tls")]
790 #[cfg_attr(
791 docsrs,
792 doc(cfg(any(
793 feature = "default-tls",
794 feature = "native-tls",
795 feature = "rustls-tls"
796 )))
797 )]
798 pub fn min_tls_version(self, version: tls::Version) -> ClientBuilder {
799 self.with_inner(|inner| inner.min_tls_version(version))
800 }
801
802 /// Set the maximum allowed TLS version for connections.
803 ///
804 /// By default, there's no maximum.
805 ///
806 /// # Errors
807 ///
808 /// A value of `tls::Version::TLS_1_3` will cause an error with the
809 /// `native-tls`/`default-tls` backend. This does not mean the version
810 /// isn't supported, just that it can't be set as a maximum due to
811 /// technical limitations.
812 ///
813 /// # Optional
814 ///
815 /// This requires the optional `default-tls`, `native-tls`, or `rustls-tls(-...)`
816 /// feature to be enabled.
817 #[cfg(feature = "__tls")]
818 #[cfg_attr(
819 docsrs,
820 doc(cfg(any(
821 feature = "default-tls",
822 feature = "native-tls",
823 feature = "rustls-tls"
824 )))
825 )]
826 pub fn max_tls_version(self, version: tls::Version) -> ClientBuilder {
827 self.with_inner(|inner| inner.max_tls_version(version))
828 }
829
830 /// Force using the native TLS backend.
831 ///
832 /// Since multiple TLS backends can be optionally enabled, this option will
833 /// force the `native-tls` backend to be used for this `Client`.
834 ///
835 /// # Optional
836 ///
837 /// This requires the optional `native-tls` feature to be enabled.
838 #[cfg(feature = "native-tls")]
839 #[cfg_attr(docsrs, doc(cfg(feature = "native-tls")))]
840 pub fn use_native_tls(self) -> ClientBuilder {
841 self.with_inner(move |inner| inner.use_native_tls())
842 }
843
844 /// Force using the Rustls TLS backend.
845 ///
846 /// Since multiple TLS backends can be optionally enabled, this option will
847 /// force the `rustls` backend to be used for this `Client`.
848 ///
849 /// # Optional
850 ///
851 /// This requires the optional `rustls-tls(-...)` feature to be enabled.
852 #[cfg(feature = "__rustls")]
853 #[cfg_attr(docsrs, doc(cfg(feature = "rustls-tls")))]
854 pub fn use_rustls_tls(self) -> ClientBuilder {
855 self.with_inner(move |inner| inner.use_rustls_tls())
856 }
857
858 /// Add TLS information as `TlsInfo` extension to responses.
859 ///
860 /// # Optional
861 ///
862 /// This requires the optional `default-tls`, `native-tls`, or `rustls-tls(-...)`
863 /// feature to be enabled.
864 #[cfg(feature = "__tls")]
865 #[cfg_attr(
866 docsrs,
867 doc(cfg(any(
868 feature = "default-tls",
869 feature = "native-tls",
870 feature = "rustls-tls"
871 )))
872 )]
873 pub fn tls_info(self, tls_info: bool) -> ClientBuilder {
874 self.with_inner(|inner| inner.tls_info(tls_info))
875 }
876
877 /// Use a preconfigured TLS backend.
878 ///
879 /// If the passed `Any` argument is not a TLS backend that reqwest
880 /// understands, the `ClientBuilder` will error when calling `build`.
881 ///
882 /// # Advanced
883 ///
884 /// This is an advanced option, and can be somewhat brittle. Usage requires
885 /// keeping the preconfigured TLS argument version in sync with reqwest,
886 /// since version mismatches will result in an "unknown" TLS backend.
887 ///
888 /// If possible, it's preferable to use the methods on `ClientBuilder`
889 /// to configure reqwest's TLS.
890 ///
891 /// # Optional
892 ///
893 /// This requires one of the optional features `native-tls` or
894 /// `rustls-tls(-...)` to be enabled.
895 #[cfg(any(feature = "native-tls", feature = "__rustls",))]
896 #[cfg_attr(docsrs, doc(cfg(any(feature = "native-tls", feature = "rustls-tls"))))]
897 pub fn use_preconfigured_tls(self, tls: impl Any) -> ClientBuilder {
898 self.with_inner(move |inner| inner.use_preconfigured_tls(tls))
899 }
900
901 /// Enables the [hickory-dns](hickory_resolver) async resolver instead of a default threadpool using `getaddrinfo`.
902 ///
903 /// If the `hickory-dns` feature is turned on, the default option is enabled.
904 ///
905 /// # Optional
906 ///
907 /// This requires the optional `hickory-dns` feature to be enabled
908 #[cfg(feature = "hickory-dns")]
909 #[cfg_attr(docsrs, doc(cfg(feature = "hickory-dns")))]
910 #[deprecated(note = "use `hickory_dns` instead", since = "0.12.0")]
911 pub fn trust_dns(self, enable: bool) -> ClientBuilder {
912 self.with_inner(|inner| inner.hickory_dns(enable))
913 }
914
915 /// Enables the [hickory-dns](hickory_resolver) async resolver instead of a default threadpool using `getaddrinfo`.
916 ///
917 /// If the `hickory-dns` feature is turned on, the default option is enabled.
918 ///
919 /// # Optional
920 ///
921 /// This requires the optional `hickory-dns` feature to be enabled
922 #[cfg(feature = "hickory-dns")]
923 #[cfg_attr(docsrs, doc(cfg(feature = "hickory-dns")))]
924 pub fn hickory_dns(self, enable: bool) -> ClientBuilder {
925 self.with_inner(|inner| inner.hickory_dns(enable))
926 }
927
928 /// Disables the hickory-dns async resolver.
929 ///
930 /// This method exists even if the optional `hickory-dns` feature is not enabled.
931 /// This can be used to ensure a `Client` doesn't use the hickory-dns async resolver
932 /// even if another dependency were to enable the optional `hickory-dns` feature.
933 #[deprecated(note = "use `no_hickory_dns` instead", since = "0.12.0")]
934 pub fn no_trust_dns(self) -> ClientBuilder {
935 self.with_inner(|inner| inner.no_hickory_dns())
936 }
937
938 /// Disables the hickory-dns async resolver.
939 ///
940 /// This method exists even if the optional `hickory-dns` feature is not enabled.
941 /// This can be used to ensure a `Client` doesn't use the hickory-dns async resolver
942 /// even if another dependency were to enable the optional `hickory-dns` feature.
943 pub fn no_hickory_dns(self) -> ClientBuilder {
944 self.with_inner(|inner| inner.no_hickory_dns())
945 }
946
947 /// Restrict the Client to be used with HTTPS only requests.
948 ///
949 /// Defaults to false.
950 pub fn https_only(self, enabled: bool) -> ClientBuilder {
951 self.with_inner(|inner| inner.https_only(enabled))
952 }
953
954 /// Override DNS resolution for specific domains to a particular IP address.
955 ///
956 /// Set the port to `0` to use the conventional port for the given scheme (e.g. 80 for http).
957 /// Ports in the URL itself will always be used instead of the port in the overridden addr.
958 pub fn resolve(self, domain: &str, addr: SocketAddr) -> ClientBuilder {
959 self.resolve_to_addrs(domain, &[addr])
960 }
961
962 /// Override DNS resolution for specific domains to particular IP addresses.
963 ///
964 /// Set the port to `0` to use the conventional port for the given scheme (e.g. 80 for http).
965 /// Ports in the URL itself will always be used instead of the port in the overridden addr.
966 pub fn resolve_to_addrs(self, domain: &str, addrs: &[SocketAddr]) -> ClientBuilder {
967 self.with_inner(|inner| inner.resolve_to_addrs(domain, addrs))
968 }
969
970 /// Override the DNS resolver implementation.
971 ///
972 /// Pass an `Arc` wrapping a trait object implementing `Resolve`.
973 /// Overrides for specific names passed to `resolve` and `resolve_to_addrs` will
974 /// still be applied on top of this resolver.
975 pub fn dns_resolver<R: Resolve + 'static>(self, resolver: Arc<R>) -> ClientBuilder {
976 self.with_inner(|inner| inner.dns_resolver(resolver))
977 }
978
979 /// Adds a new Tower [`Layer`](https://docs.rs/tower/latest/tower/trait.Layer.html) to the
980 /// base connector [`Service`](https://docs.rs/tower/latest/tower/trait.Service.html) which
981 /// is responsible for connection establishment.
982 ///
983 /// Each subsequent invocation of this function will wrap previous layers.
984 ///
985 /// Example usage:
986 /// ```
987 /// use std::time::Duration;
988 ///
989 /// let client = reqwest::blocking::Client::builder()
990 /// // resolved to outermost layer, meaning while we are waiting on concurrency limit
991 /// .connect_timeout(Duration::from_millis(200))
992 /// // underneath the concurrency check, so only after concurrency limit lets us through
993 /// .connector_layer(tower::timeout::TimeoutLayer::new(Duration::from_millis(50)))
994 /// .connector_layer(tower::limit::concurrency::ConcurrencyLimitLayer::new(2))
995 /// .build()
996 /// .unwrap();
997 /// ```
998 pub fn connector_layer<L>(self, layer: L) -> ClientBuilder
999 where
1000 L: Layer<BoxedConnectorService> + Clone + Send + Sync + 'static,
1001 L::Service:
1002 Service<Unnameable, Response = Conn, Error = BoxError> + Clone + Send + Sync + 'static,
1003 <L::Service as Service<Unnameable>>::Future: Send + 'static,
1004 {
1005 self.with_inner(|inner| inner.connector_layer(layer))
1006 }
1007
1008 // private
1009
1010 fn with_inner<F>(mut self, func: F) -> ClientBuilder
1011 where
1012 F: FnOnce(async_impl::ClientBuilder) -> async_impl::ClientBuilder,
1013 {
1014 self.inner = func(self.inner);
1015 self
1016 }
1017}
1018
1019impl From<async_impl::ClientBuilder> for ClientBuilder {
1020 fn from(builder: async_impl::ClientBuilder) -> Self {
1021 Self {
1022 inner: builder,
1023 timeout: Timeout::default(),
1024 }
1025 }
1026}
1027
1028impl Default for Client {
1029 fn default() -> Self {
1030 Self::new()
1031 }
1032}
1033
1034impl Client {
1035 /// Constructs a new `Client`.
1036 ///
1037 /// # Panic
1038 ///
1039 /// This method panics if TLS backend cannot be initialized, or the resolver
1040 /// cannot load the system configuration.
1041 ///
1042 /// Use `Client::builder()` if you wish to handle the failure as an `Error`
1043 /// instead of panicking.
1044 ///
1045 /// This method also panics if called from within an async runtime. See docs
1046 /// on [`reqwest::blocking`][crate::blocking] for details.
1047 pub fn new() -> Client {
1048 ClientBuilder::new().build().expect("Client::new()")
1049 }
1050
1051 /// Creates a `ClientBuilder` to configure a `Client`.
1052 ///
1053 /// This is the same as `ClientBuilder::new()`.
1054 pub fn builder() -> ClientBuilder {
1055 ClientBuilder::new()
1056 }
1057
1058 /// Convenience method to make a `GET` request to a URL.
1059 ///
1060 /// # Errors
1061 ///
1062 /// This method fails whenever supplied `Url` cannot be parsed.
1063 pub fn get<U: IntoUrl>(&self, url: U) -> RequestBuilder {
1064 self.request(Method::GET, url)
1065 }
1066
1067 /// Convenience method to make a `POST` request to a URL.
1068 ///
1069 /// # Errors
1070 ///
1071 /// This method fails whenever supplied `Url` cannot be parsed.
1072 pub fn post<U: IntoUrl>(&self, url: U) -> RequestBuilder {
1073 self.request(Method::POST, url)
1074 }
1075
1076 /// Convenience method to make a `PUT` request to a URL.
1077 ///
1078 /// # Errors
1079 ///
1080 /// This method fails whenever supplied `Url` cannot be parsed.
1081 pub fn put<U: IntoUrl>(&self, url: U) -> RequestBuilder {
1082 self.request(Method::PUT, url)
1083 }
1084
1085 /// Convenience method to make a `PATCH` request to a URL.
1086 ///
1087 /// # Errors
1088 ///
1089 /// This method fails whenever supplied `Url` cannot be parsed.
1090 pub fn patch<U: IntoUrl>(&self, url: U) -> RequestBuilder {
1091 self.request(Method::PATCH, url)
1092 }
1093
1094 /// Convenience method to make a `DELETE` request to a URL.
1095 ///
1096 /// # Errors
1097 ///
1098 /// This method fails whenever supplied `Url` cannot be parsed.
1099 pub fn delete<U: IntoUrl>(&self, url: U) -> RequestBuilder {
1100 self.request(Method::DELETE, url)
1101 }
1102
1103 /// Convenience method to make a `HEAD` request to a URL.
1104 ///
1105 /// # Errors
1106 ///
1107 /// This method fails whenever supplied `Url` cannot be parsed.
1108 pub fn head<U: IntoUrl>(&self, url: U) -> RequestBuilder {
1109 self.request(Method::HEAD, url)
1110 }
1111
1112 /// Start building a `Request` with the `Method` and `Url`.
1113 ///
1114 /// Returns a `RequestBuilder`, which will allow setting headers and
1115 /// request body before sending.
1116 ///
1117 /// # Errors
1118 ///
1119 /// This method fails whenever supplied `Url` cannot be parsed.
1120 pub fn request<U: IntoUrl>(&self, method: Method, url: U) -> RequestBuilder {
1121 let req = url.into_url().map(move |url| Request::new(method, url));
1122 RequestBuilder::new(self.clone(), req)
1123 }
1124
1125 /// Executes a `Request`.
1126 ///
1127 /// A `Request` can be built manually with `Request::new()` or obtained
1128 /// from a RequestBuilder with `RequestBuilder::build()`.
1129 ///
1130 /// You should prefer to use the `RequestBuilder` and
1131 /// `RequestBuilder::send()`.
1132 ///
1133 /// # Errors
1134 ///
1135 /// This method fails if there was an error while sending request,
1136 /// or redirect limit was exhausted.
1137 pub fn execute(&self, request: Request) -> crate::Result<Response> {
1138 self.inner.execute_request(request)
1139 }
1140}
1141
1142impl fmt::Debug for Client {
1143 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
1144 f.debug_struct("Client")
1145 //.field("gzip", &self.inner.gzip)
1146 //.field("redirect_policy", &self.inner.redirect_policy)
1147 //.field("referer", &self.inner.referer)
1148 .finish()
1149 }
1150}
1151
1152impl fmt::Debug for ClientBuilder {
1153 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
1154 self.inner.fmt(f)
1155 }
1156}
1157
1158#[derive(Clone)]
1159struct ClientHandle {
1160 timeout: Timeout,
1161 inner: Arc<InnerClientHandle>,
1162}
1163
1164type OneshotResponse = oneshot::Sender<crate::Result<async_impl::Response>>;
1165type ThreadSender = mpsc::UnboundedSender<(async_impl::Request, OneshotResponse)>;
1166
1167struct InnerClientHandle {
1168 tx: Option<ThreadSender>,
1169 thread: Option<thread::JoinHandle<()>>,
1170}
1171
1172impl Drop for InnerClientHandle {
1173 fn drop(&mut self) {
1174 let id = self
1175 .thread
1176 .as_ref()
1177 .map(|h| h.thread().id())
1178 .expect("thread not dropped yet");
1179
1180 trace!("closing runtime thread ({id:?})");
1181 self.tx.take();
1182 trace!("signaled close for runtime thread ({id:?})");
1183 self.thread.take().map(|h| h.join());
1184 trace!("closed runtime thread ({id:?})");
1185 }
1186}
1187
1188impl ClientHandle {
1189 fn new(builder: ClientBuilder) -> crate::Result<ClientHandle> {
1190 let timeout = builder.timeout;
1191 let builder = builder.inner;
1192 let (tx, rx) = mpsc::unbounded_channel::<(async_impl::Request, OneshotResponse)>();
1193 let (spawn_tx, spawn_rx) = oneshot::channel::<crate::Result<()>>();
1194 let handle = thread::Builder::new()
1195 .name("reqwest-internal-sync-runtime".into())
1196 .spawn(move || {
1197 use tokio::runtime;
1198 let rt = match runtime::Builder::new_current_thread()
1199 .enable_all()
1200 .build()
1201 .map_err(crate::error::builder)
1202 {
1203 Err(e) => {
1204 if let Err(e) = spawn_tx.send(Err(e)) {
1205 error!("Failed to communicate runtime creation failure: {e:?}");
1206 }
1207 return;
1208 }
1209 Ok(v) => v,
1210 };
1211
1212 let f = async move {
1213 let client = match builder.build() {
1214 Err(e) => {
1215 if let Err(e) = spawn_tx.send(Err(e)) {
1216 error!("Failed to communicate client creation failure: {e:?}");
1217 }
1218 return;
1219 }
1220 Ok(v) => v,
1221 };
1222 if let Err(e) = spawn_tx.send(Ok(())) {
1223 error!("Failed to communicate successful startup: {e:?}");
1224 return;
1225 }
1226
1227 let mut rx = rx;
1228
1229 while let Some((req, req_tx)) = rx.recv().await {
1230 let req_fut = client.execute(req);
1231 tokio::spawn(forward(req_fut, req_tx));
1232 }
1233
1234 trace!("({:?}) Receiver is shutdown", thread::current().id());
1235 };
1236
1237 trace!("({:?}) start runtime::block_on", thread::current().id());
1238 rt.block_on(f);
1239 trace!("({:?}) end runtime::block_on", thread::current().id());
1240 drop(rt);
1241 trace!("({:?}) finished", thread::current().id());
1242 })
1243 .map_err(crate::error::builder)?;
1244
1245 // Wait for the runtime thread to start up...
1246 match wait::timeout(spawn_rx, None) {
1247 Ok(Ok(())) => (),
1248 Ok(Err(err)) => return Err(err),
1249 Err(_canceled) => event_loop_panicked(),
1250 }
1251
1252 let inner_handle = Arc::new(InnerClientHandle {
1253 tx: Some(tx),
1254 thread: Some(handle),
1255 });
1256
1257 Ok(ClientHandle {
1258 timeout,
1259 inner: inner_handle,
1260 })
1261 }
1262
1263 fn execute_request(&self, req: Request) -> crate::Result<Response> {
1264 let (tx, rx) = oneshot::channel();
1265 let (req, body) = req.into_async();
1266 let url = req.url().clone();
1267 let timeout = req.timeout().copied().or(self.timeout.0);
1268
1269 self.inner
1270 .tx
1271 .as_ref()
1272 .expect("core thread exited early")
1273 .send((req, tx))
1274 .expect("core thread panicked");
1275
1276 let result: Result<crate::Result<async_impl::Response>, wait::Waited<crate::Error>> =
1277 if let Some(body) = body {
1278 let f = async move {
1279 body.send().await?;
1280 rx.await.map_err(|_canceled| event_loop_panicked())
1281 };
1282 wait::timeout(f, timeout)
1283 } else {
1284 let f = async move { rx.await.map_err(|_canceled| event_loop_panicked()) };
1285 wait::timeout(f, timeout)
1286 };
1287
1288 match result {
1289 Ok(Err(err)) => Err(err.with_url(url)),
1290 Ok(Ok(res)) => Ok(Response::new(
1291 res,
1292 timeout,
1293 KeepCoreThreadAlive(Some(self.inner.clone())),
1294 )),
1295 Err(wait::Waited::TimedOut(e)) => Err(crate::error::request(e).with_url(url)),
1296 Err(wait::Waited::Inner(err)) => Err(err.with_url(url)),
1297 }
1298 }
1299}
1300
1301async fn forward<F>(fut: F, mut tx: OneshotResponse)
1302where
1303 F: Future<Output = crate::Result<async_impl::Response>>,
1304{
1305 use std::task::Poll;
1306
1307 futures_util::pin_mut!(fut);
1308
1309 // "select" on the sender being canceled, and the future completing
1310 let res = std::future::poll_fn(|cx| {
1311 match fut.as_mut().poll(cx) {
1312 Poll::Ready(val) => Poll::Ready(Some(val)),
1313 Poll::Pending => {
1314 // check if the callback is canceled
1315 ready!(tx.poll_closed(cx));
1316 Poll::Ready(None)
1317 }
1318 }
1319 })
1320 .await;
1321
1322 if let Some(res) = res {
1323 let _ = tx.send(res);
1324 }
1325 // else request is canceled
1326}
1327
1328#[derive(Clone, Copy)]
1329struct Timeout(Option<Duration>);
1330
1331impl Default for Timeout {
1332 fn default() -> Timeout {
1333 // default mentioned in ClientBuilder::timeout() doc comment
1334 Timeout(Some(Duration::from_secs(30)))
1335 }
1336}
1337
1338pub(crate) struct KeepCoreThreadAlive(#[allow(dead_code)] Option<Arc<InnerClientHandle>>);
1339
1340impl KeepCoreThreadAlive {
1341 pub(crate) fn empty() -> KeepCoreThreadAlive {
1342 KeepCoreThreadAlive(None)
1343 }
1344}
1345
1346#[cold]
1347#[inline(never)]
1348fn event_loop_panicked() -> ! {
1349 // The only possible reason there would be a Canceled error
1350 // is if the thread running the event loop panicked. We could return
1351 // an Err here, like a BrokenPipe, but the Client is not
1352 // recoverable. Additionally, the panic in the other thread
1353 // is not normal, and should likely be propagated.
1354 panic!("event loop thread panicked");
1355}