fetchlet_net/http/client.rs
1use std::error::Error as _;
2use std::sync::Arc;
3use std::time::Duration;
4
5use hyper_util::client::legacy::Client;
6use hyper_util::rt::{TokioExecutor, TokioTimer};
7use tokio_rustls::rustls::ClientConfig;
8
9use fetchlet::http::{HeaderValue, Method, Version, header};
10use fetchlet::{Body, Error, FetchTransport, Request, RequireHttp2, Response, TransportFuture};
11use http_body::Body as _;
12
13use super::connect::Connect;
14use super::decode::{ACCEPT_ENCODING, Decoded, codings};
15use crate::network::{Connector, runtime};
16
17/// How long an idle pooled connection stays open by default: hyper-util's
18/// own default, long enough to reuse a connection between the requests of
19/// one page and short enough not to hold servers' sockets for long.
20const DEFAULT_POOL_IDLE_TIMEOUT: Duration = Duration::from_secs(90);
21
22/// A [`FetchTransport`] that sends JavaScript's outbound `fetch` requests
23/// to HTTP servers, with TLS for `https:`.
24///
25/// Pair it with a `FetchPolicy` in a `FetchService`, or register it as the
26/// outbound transport of `HostServices`: the policy authorizes the origins
27/// JavaScript reaches, and this transport resolves their hosts and refuses
28/// any resolved address that is not public, such as loopback, private and
29/// link-local networks, unless
30/// [`allow_private_addresses`](Self::allow_private_addresses). A host that
31/// resolves to no allowed address fails with `PermissionDenied`.
32///
33/// Each call sends one request and returns its response as it arrives,
34/// with the body streaming; redirects return to the caller, which follows
35/// them under its policy, as the transport contract requires. hyper speaks
36/// HTTP/1.1, and HTTP/2 when a TLS server selects it by ALPN; connections
37/// to one origin are pooled and reused, and an idle one closes after
38/// [`pool_idle_timeout`](Self::pool_idle_timeout). A request marked
39/// [`RequireHttp2`], such as one whose body streams, uses only an HTTP/2
40/// connection and fails with `Transport` before sending on an HTTP/1.1 one,
41/// including every plain `http:` connection.
42///
43/// As a browser does, the client asks for `gzip, deflate, br` and undoes
44/// the codings the response's `Content-Encoding` lists, including stacked
45/// ones and raw deflate sent as `deflate`, as JavaScript reads the body; it
46/// then removes `Content-Encoding` and `Content-Length`, which describe the
47/// bytes on the wire, so a handler that returns the response sends what it
48/// read. A request that carries its own `Accept-Encoding`, a `HEAD`
49/// request, a response without a body and one with an unknown coding keep
50/// the body and headers as the server sent them. Decoded pieces are at most
51/// 64 KiB, and the invocation's `response_body_bytes` budget applies to the
52/// decoded bytes; invalid coded data fails the body when read.
53///
54/// Requests run on the Tokio runtime that
55/// polls the host pump; an App without one fails each request with
56/// `Configuration`. TLS verifies the server against the Mozilla roots in
57/// `webpki-roots`, or the configuration from
58/// [`with_tls_config`](Self::with_tls_config). Dropping the request's future
59/// or its response body closes that exchange.
60#[derive(Clone)]
61pub struct HttpClient {
62 connector: Connector,
63 pool_idle_timeout: Option<Duration>,
64 client: Client<Connect, Body>,
65}
66
67impl HttpClient {
68 /// Connect to public addresses, verifying `https:` servers against the
69 /// `webpki-roots` certificates.
70 pub fn new() -> Self {
71 Self::build(Connector::new(), Some(DEFAULT_POOL_IDLE_TIMEOUT))
72 }
73
74 /// Connect to public addresses, using `config` for `https:`, such as one
75 /// that trusts a private certificate authority. Unless `config` names
76 /// its own ALPN protocols, the client offers HTTP/2 and HTTP/1.1.
77 pub fn with_tls_config(config: Arc<ClientConfig>) -> Self {
78 Self::build(
79 Connector::with_tls_config(config),
80 Some(DEFAULT_POOL_IDLE_TIMEOUT),
81 )
82 }
83
84 /// Also connect to loopback, private and other non-public addresses,
85 /// for a host whose services run beside it.
86 pub fn allow_private_addresses(mut self) -> Self {
87 self.connector.allow_private_addresses();
88 Self::build(self.connector, self.pool_idle_timeout)
89 }
90
91 /// Close a pooled connection after it has been idle for `timeout`, or
92 /// never with `None`. The default is 90 seconds.
93 pub fn pool_idle_timeout(self, timeout: Option<Duration>) -> Self {
94 Self::build(self.connector, timeout)
95 }
96
97 fn build(connector: Connector, pool_idle_timeout: Option<Duration>) -> Self {
98 let connector = connector.with_alpn(&[b"h2", b"http/1.1"]);
99 let client = Client::builder(TokioExecutor::new())
100 .pool_timer(TokioTimer::new())
101 .pool_idle_timeout(pool_idle_timeout)
102 .build(Connect {
103 connector: connector.clone(),
104 });
105 Self {
106 connector,
107 pool_idle_timeout,
108 client,
109 }
110 }
111}
112
113impl Default for HttpClient {
114 fn default() -> Self {
115 Self::new()
116 }
117}
118
119impl std::fmt::Debug for HttpClient {
120 fn fmt(&self, formatter: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
121 formatter
122 .debug_struct("HttpClient")
123 .field(
124 "allow_private_addresses",
125 &self.connector.allows_private_addresses(),
126 )
127 .field("pool_idle_timeout", &self.pool_idle_timeout)
128 .finish_non_exhaustive()
129 }
130}
131
132impl FetchTransport for HttpClient {
133 fn send(&self, mut request: Request) -> TransportFuture {
134 let client = self.client.clone();
135 Box::pin(async move {
136 // hyper spawns its connections on the current runtime.
137 runtime("HttpClient")?;
138 match request.uri().scheme_str() {
139 Some("http" | "https") => {}
140 _ => return Err(Error::InvalidRequest("unsupported URL scheme".into())),
141 }
142 // hyper chooses HTTP/2 by the connection, not the request. A
143 // request that must not use HTTP/1.x asks for HTTP/2, which
144 // hyper refuses on an HTTP/1 connection before sending anything.
145 *request.version_mut() = if request.extensions().get::<RequireHttp2>().is_some() {
146 Version::HTTP_2
147 } else {
148 Version::HTTP_11
149 };
150 // A caller that names its own codings reads the body as sent.
151 let decode = !request.headers().contains_key(header::ACCEPT_ENCODING);
152 if decode {
153 request.headers_mut().insert(
154 header::ACCEPT_ENCODING,
155 HeaderValue::from_static(ACCEPT_ENCODING),
156 );
157 }
158 let head = request.method() == Method::HEAD;
159 let response = client.request(request).await.map_err(failed)?;
160 let codings = codings(response.headers()).unwrap_or_default();
161 if !decode || head || codings.is_empty() || response.body().is_end_stream() {
162 return Ok(response.map(Body::from_http_body));
163 }
164 // The headers describe the body JavaScript reads: decoded, of a
165 // length known only once it ends.
166 let (mut parts, body) = response.into_parts();
167 parts.headers.remove(header::CONTENT_ENCODING);
168 parts.headers.remove(header::CONTENT_LENGTH);
169 Ok(Response::from_parts(
170 parts,
171 Body::from_http_body(Decoded::new(body, &codings)),
172 ))
173 })
174 }
175}
176
177/// The error of a failed exchange: the connector's own error, such as a
178/// refused address, or a transport error with hyper's description.
179fn failed(error: hyper_util::client::legacy::Error) -> Error {
180 let mut source = error.source();
181 while let Some(cause) = source {
182 if let Some(cause) = cause.downcast_ref::<Error>() {
183 return match cause {
184 Error::PermissionDenied => Error::PermissionDenied,
185 Error::InvalidRequest(message) => Error::InvalidRequest(message.clone()),
186 Error::LimitExceeded(resource) => Error::LimitExceeded(resource),
187 Error::Transport(message) => Error::Transport(message.clone()),
188 other => Error::Transport(other.to_string()),
189 };
190 }
191 source = cause.source();
192 }
193 Error::Transport(format!("HTTP request failed: {error}"))
194}