1 use std::error::Error as StdError;
2 #[cfg(feature = "runtime")]
3 use std::time::Duration;
4
5 use bytes::Bytes;
6 use futures_channel::{mpsc, oneshot};
7 use futures_util::future::{self, Either, FutureExt as _, TryFutureExt as _};
8 use futures_util::stream::StreamExt as _;
9 use h2::client::{Builder, SendRequest};
10 use http::{Method, StatusCode};
11 use tokio::io::{AsyncRead, AsyncWrite};
12
13 use super::{ping, H2Upgraded, PipeToSendStream, SendBuf};
14 use crate::body::HttpBody;
15 use crate::common::{exec::Exec, task, Future, Never, Pin, Poll};
16 use crate::headers;
17 use crate::proto::h2::UpgradedSendStream;
18 use crate::proto::Dispatched;
19 use crate::upgrade::Upgraded;
20 use crate::{Body, Request, Response};
21
22 type ClientRx<B> = crate::client::dispatch::Receiver<Request<B>, Response<Body>>;
23
24 ///// An mpsc channel is used to help notify the `Connection` task when *all*
25 ///// other handles to it have been dropped, so that it can shutdown.
26 type ConnDropRef = mpsc::Sender<Never>;
27
28 ///// A oneshot channel watches the `Connection` task, and when it completes,
29 ///// the "dispatch" task will be notified and can shutdown sooner.
30 type ConnEof = oneshot::Receiver<Never>;
31
32 // Our defaults are chosen for the "majority" case, which usually are not
33 // resource constrained, and so the spec default of 64kb can be too limiting
34 // for performance.
35 const DEFAULT_CONN_WINDOW: u32 = 1024 * 1024 * 5; // 5mb
36 const DEFAULT_STREAM_WINDOW: u32 = 1024 * 1024 * 2; // 2mb
37 const DEFAULT_MAX_FRAME_SIZE: u32 = 1024 * 16; // 16kb
38
39 #[derive(Clone, Debug)]
40 pub(crate) struct Config {
41 pub(crate) adaptive_window: bool,
42 pub(crate) initial_conn_window_size: u32,
43 pub(crate) initial_stream_window_size: u32,
44 pub(crate) max_frame_size: u32,
45 #[cfg(feature = "runtime")]
46 pub(crate) keep_alive_interval: Option<Duration>,
47 #[cfg(feature = "runtime")]
48 pub(crate) keep_alive_timeout: Duration,
49 #[cfg(feature = "runtime")]
50 pub(crate) keep_alive_while_idle: bool,
51 pub(crate) max_concurrent_reset_streams: Option<usize>,
52 }
53
54 impl Default for Config {
default() -> Config55 fn default() -> Config {
56 Config {
57 adaptive_window: false,
58 initial_conn_window_size: DEFAULT_CONN_WINDOW,
59 initial_stream_window_size: DEFAULT_STREAM_WINDOW,
60 max_frame_size: DEFAULT_MAX_FRAME_SIZE,
61 #[cfg(feature = "runtime")]
62 keep_alive_interval: None,
63 #[cfg(feature = "runtime")]
64 keep_alive_timeout: Duration::from_secs(20),
65 #[cfg(feature = "runtime")]
66 keep_alive_while_idle: false,
67 max_concurrent_reset_streams: None,
68 }
69 }
70 }
71
new_builder(config: &Config) -> Builder72 fn new_builder(config: &Config) -> Builder {
73 let mut builder = Builder::default();
74 builder
75 .initial_window_size(config.initial_stream_window_size)
76 .initial_connection_window_size(config.initial_conn_window_size)
77 .max_frame_size(config.max_frame_size)
78 .enable_push(false);
79 if let Some(max) = config.max_concurrent_reset_streams {
80 builder.max_concurrent_reset_streams(max);
81 }
82 builder
83 }
84
new_ping_config(config: &Config) -> ping::Config85 fn new_ping_config(config: &Config) -> ping::Config {
86 ping::Config {
87 bdp_initial_window: if config.adaptive_window {
88 Some(config.initial_stream_window_size)
89 } else {
90 None
91 },
92 #[cfg(feature = "runtime")]
93 keep_alive_interval: config.keep_alive_interval,
94 #[cfg(feature = "runtime")]
95 keep_alive_timeout: config.keep_alive_timeout,
96 #[cfg(feature = "runtime")]
97 keep_alive_while_idle: config.keep_alive_while_idle,
98 }
99 }
100
handshake<T, B>( io: T, req_rx: ClientRx<B>, config: &Config, exec: Exec, ) -> crate::Result<ClientTask<B>> where T: AsyncRead + AsyncWrite + Send + Unpin + 'static, B: HttpBody, B::Data: Send + 'static,101 pub(crate) async fn handshake<T, B>(
102 io: T,
103 req_rx: ClientRx<B>,
104 config: &Config,
105 exec: Exec,
106 ) -> crate::Result<ClientTask<B>>
107 where
108 T: AsyncRead + AsyncWrite + Send + Unpin + 'static,
109 B: HttpBody,
110 B::Data: Send + 'static,
111 {
112 let (h2_tx, mut conn) = new_builder(config)
113 .handshake::<_, SendBuf<B::Data>>(io)
114 .await
115 .map_err(crate::Error::new_h2)?;
116
117 // An mpsc channel is used entirely to detect when the
118 // 'Client' has been dropped. This is to get around a bug
119 // in h2 where dropping all SendRequests won't notify a
120 // parked Connection.
121 let (conn_drop_ref, rx) = mpsc::channel(1);
122 let (cancel_tx, conn_eof) = oneshot::channel();
123
124 let conn_drop_rx = rx.into_future().map(|(item, _rx)| {
125 if let Some(never) = item {
126 match never {}
127 }
128 });
129
130 let ping_config = new_ping_config(&config);
131
132 let (conn, ping) = if ping_config.is_enabled() {
133 let pp = conn.ping_pong().expect("conn.ping_pong");
134 let (recorder, mut ponger) = ping::channel(pp, ping_config);
135
136 let conn = future::poll_fn(move |cx| {
137 match ponger.poll(cx) {
138 Poll::Ready(ping::Ponged::SizeUpdate(wnd)) => {
139 conn.set_target_window_size(wnd);
140 conn.set_initial_window_size(wnd)?;
141 }
142 #[cfg(feature = "runtime")]
143 Poll::Ready(ping::Ponged::KeepAliveTimedOut) => {
144 debug!("connection keep-alive timed out");
145 return Poll::Ready(Ok(()));
146 }
147 Poll::Pending => {}
148 }
149
150 Pin::new(&mut conn).poll(cx)
151 });
152 (Either::Left(conn), recorder)
153 } else {
154 (Either::Right(conn), ping::disabled())
155 };
156 let conn = conn.map_err(|e| debug!("connection error: {}", e));
157
158 exec.execute(conn_task(conn, conn_drop_rx, cancel_tx));
159
160 Ok(ClientTask {
161 ping,
162 conn_drop_ref,
163 conn_eof,
164 executor: exec,
165 h2_tx,
166 req_rx,
167 })
168 }
169
conn_task<C, D>(conn: C, drop_rx: D, cancel_tx: oneshot::Sender<Never>) where C: Future + Unpin, D: Future<Output = ()> + Unpin,170 async fn conn_task<C, D>(conn: C, drop_rx: D, cancel_tx: oneshot::Sender<Never>)
171 where
172 C: Future + Unpin,
173 D: Future<Output = ()> + Unpin,
174 {
175 match future::select(conn, drop_rx).await {
176 Either::Left(_) => {
177 // ok or err, the `conn` has finished
178 }
179 Either::Right(((), conn)) => {
180 // mpsc has been dropped, hopefully polling
181 // the connection some more should start shutdown
182 // and then close
183 trace!("send_request dropped, starting conn shutdown");
184 drop(cancel_tx);
185 let _ = conn.await;
186 }
187 }
188 }
189
190 pub(crate) struct ClientTask<B>
191 where
192 B: HttpBody,
193 {
194 ping: ping::Recorder,
195 conn_drop_ref: ConnDropRef,
196 conn_eof: ConnEof,
197 executor: Exec,
198 h2_tx: SendRequest<SendBuf<B::Data>>,
199 req_rx: ClientRx<B>,
200 }
201
202 impl<B> Future for ClientTask<B>
203 where
204 B: HttpBody + Send + 'static,
205 B::Data: Send,
206 B::Error: Into<Box<dyn StdError + Send + Sync>>,
207 {
208 type Output = crate::Result<Dispatched>;
209
poll(mut self: Pin<&mut Self>, cx: &mut task::Context<'_>) -> Poll<Self::Output>210 fn poll(mut self: Pin<&mut Self>, cx: &mut task::Context<'_>) -> Poll<Self::Output> {
211 loop {
212 match ready!(self.h2_tx.poll_ready(cx)) {
213 Ok(()) => (),
214 Err(err) => {
215 self.ping.ensure_not_timed_out()?;
216 return if err.reason() == Some(::h2::Reason::NO_ERROR) {
217 trace!("connection gracefully shutdown");
218 Poll::Ready(Ok(Dispatched::Shutdown))
219 } else {
220 Poll::Ready(Err(crate::Error::new_h2(err)))
221 };
222 }
223 };
224
225 match self.req_rx.poll_recv(cx) {
226 Poll::Ready(Some((req, cb))) => {
227 // check that future hasn't been canceled already
228 if cb.is_canceled() {
229 trace!("request callback is canceled");
230 continue;
231 }
232 let (head, body) = req.into_parts();
233 let mut req = ::http::Request::from_parts(head, ());
234 super::strip_connection_headers(req.headers_mut(), true);
235 if let Some(len) = body.size_hint().exact() {
236 if len != 0 || headers::method_has_defined_payload_semantics(req.method()) {
237 headers::set_content_length_if_missing(req.headers_mut(), len);
238 }
239 }
240
241 let is_connect = req.method() == Method::CONNECT;
242 let eos = body.is_end_stream();
243 let ping = self.ping.clone();
244
245 if is_connect {
246 if headers::content_length_parse_all(req.headers())
247 .map_or(false, |len| len != 0)
248 {
249 warn!("h2 connect request with non-zero body not supported");
250 cb.send(Err((
251 crate::Error::new_h2(h2::Reason::INTERNAL_ERROR.into()),
252 None,
253 )));
254 continue;
255 }
256 }
257
258 let (fut, body_tx) = match self.h2_tx.send_request(req, !is_connect && eos) {
259 Ok(ok) => ok,
260 Err(err) => {
261 debug!("client send request error: {}", err);
262 cb.send(Err((crate::Error::new_h2(err), None)));
263 continue;
264 }
265 };
266
267 let send_stream = if !is_connect {
268 if !eos {
269 let mut pipe =
270 Box::pin(PipeToSendStream::new(body, body_tx)).map(|res| {
271 if let Err(e) = res {
272 debug!("client request body error: {}", e);
273 }
274 });
275
276 // eagerly see if the body pipe is ready and
277 // can thus skip allocating in the executor
278 match Pin::new(&mut pipe).poll(cx) {
279 Poll::Ready(_) => (),
280 Poll::Pending => {
281 let conn_drop_ref = self.conn_drop_ref.clone();
282 // keep the ping recorder's knowledge of an
283 // "open stream" alive while this body is
284 // still sending...
285 let ping = ping.clone();
286 let pipe = pipe.map(move |x| {
287 drop(conn_drop_ref);
288 drop(ping);
289 x
290 });
291 self.executor.execute(pipe);
292 }
293 }
294 }
295
296 None
297 } else {
298 Some(body_tx)
299 };
300
301 let fut = fut.map(move |result| match result {
302 Ok(res) => {
303 // record that we got the response headers
304 ping.record_non_data();
305
306 let content_length = headers::content_length_parse_all(res.headers());
307 if let (Some(mut send_stream), StatusCode::OK) =
308 (send_stream, res.status())
309 {
310 if content_length.map_or(false, |len| len != 0) {
311 warn!("h2 connect response with non-zero body not supported");
312
313 send_stream.send_reset(h2::Reason::INTERNAL_ERROR);
314 return Err((
315 crate::Error::new_h2(h2::Reason::INTERNAL_ERROR.into()),
316 None,
317 ));
318 }
319 let (parts, recv_stream) = res.into_parts();
320 let mut res = Response::from_parts(parts, Body::empty());
321
322 let (pending, on_upgrade) = crate::upgrade::pending();
323 let io = H2Upgraded {
324 ping,
325 send_stream: unsafe { UpgradedSendStream::new(send_stream) },
326 recv_stream,
327 buf: Bytes::new(),
328 };
329 let upgraded = Upgraded::new(io, Bytes::new());
330
331 pending.fulfill(upgraded);
332 res.extensions_mut().insert(on_upgrade);
333
334 Ok(res)
335 } else {
336 let res = res.map(|stream| {
337 let ping = ping.for_stream(&stream);
338 crate::Body::h2(stream, content_length.into(), ping)
339 });
340 Ok(res)
341 }
342 }
343 Err(err) => {
344 ping.ensure_not_timed_out().map_err(|e| (e, None))?;
345
346 debug!("client response error: {}", err);
347 Err((crate::Error::new_h2(err), None))
348 }
349 });
350 self.executor.execute(cb.send_when(fut));
351 continue;
352 }
353
354 Poll::Ready(None) => {
355 trace!("client::dispatch::Sender dropped");
356 return Poll::Ready(Ok(Dispatched::Shutdown));
357 }
358
359 Poll::Pending => match ready!(Pin::new(&mut self.conn_eof).poll(cx)) {
360 Ok(never) => match never {},
361 Err(_conn_is_eof) => {
362 trace!("connection task is closed, closing dispatch task");
363 return Poll::Ready(Ok(Dispatched::Shutdown));
364 }
365 },
366 }
367 }
368 }
369 }
370