rama_hyper/client/conn/
http2.rs

1//! HTTP/2 client connections
2
3use std::error::Error;
4use std::fmt;
5use std::future::Future;
6use std::marker::PhantomData;
7use std::pin::Pin;
8use std::sync::Arc;
9use std::task::{Context, Poll};
10use std::time::Duration;
11
12use crate::rt::{Read, Write};
13use http::{Request, Response};
14
15use super::super::dispatch;
16use crate::body::{Body, Incoming as IncomingBody};
17use crate::common::time::Time;
18use crate::proto;
19use crate::rt::bounds::Http2ClientConnExec;
20use crate::rt::Timer;
21
22/// The sender side of an established connection.
23pub struct SendRequest<B> {
24    dispatch: dispatch::UnboundedSender<Request<B>, Response<IncomingBody>>,
25}
26
27impl<B> Clone for SendRequest<B> {
28    fn clone(&self) -> SendRequest<B> {
29        SendRequest {
30            dispatch: self.dispatch.clone(),
31        }
32    }
33}
34
35/// A future that processes all HTTP state for the IO object.
36///
37/// In most cases, this should just be spawned into an executor, so that it
38/// can process incoming and outgoing messages, notice hangups, and the like.
39#[must_use = "futures do nothing unless polled"]
40pub struct Connection<T, B, E>
41where
42    T: Read + Write + 'static + Unpin,
43    B: Body + 'static,
44    E: Http2ClientConnExec<B, T> + Unpin,
45    B::Error: Into<Box<dyn Error + Send + Sync>>,
46{
47    inner: (PhantomData<T>, proto::h2::ClientTask<B, E, T>),
48}
49
50/// A builder to configure an HTTP connection.
51///
52/// After setting options, the builder is used to create a handshake future.
53///
54/// **Note**: The default values of options are *not considered stable*. They
55/// are subject to change at any time.
56#[derive(Clone, Debug)]
57pub struct Builder<Ex> {
58    pub(super) exec: Ex,
59    pub(super) timer: Time,
60    h2_builder: proto::h2::client::Config,
61}
62
63/// Returns a handshake future over some IO.
64///
65/// This is a shortcut for `Builder::new().handshake(io)`.
66/// See [`client::conn`](crate::client::conn) for more.
67pub async fn handshake<E, T, B>(
68    exec: E,
69    io: T,
70) -> crate::Result<(SendRequest<B>, Connection<T, B, E>)>
71where
72    T: Read + Write + Unpin + 'static,
73    B: Body + 'static,
74    B::Data: Send,
75    B::Error: Into<Box<dyn Error + Send + Sync>>,
76    E: Http2ClientConnExec<B, T> + Unpin + Clone,
77{
78    Builder::new(exec).handshake(io).await
79}
80
81// ===== impl SendRequest
82
83impl<B> SendRequest<B> {
84    /// Polls to determine whether this sender can be used yet for a request.
85    ///
86    /// If the associated connection is closed, this returns an Error.
87    pub fn poll_ready(&mut self, _cx: &mut Context<'_>) -> Poll<crate::Result<()>> {
88        if self.is_closed() {
89            Poll::Ready(Err(crate::Error::new_closed()))
90        } else {
91            Poll::Ready(Ok(()))
92        }
93    }
94
95    /// Waits until the dispatcher is ready
96    ///
97    /// If the associated connection is closed, this returns an Error.
98    pub async fn ready(&mut self) -> crate::Result<()> {
99        futures_util::future::poll_fn(|cx| self.poll_ready(cx)).await
100    }
101
102    /// Checks if the connection is currently ready to send a request.
103    ///
104    /// # Note
105    ///
106    /// This is mostly a hint. Due to inherent latency of networks, it is
107    /// possible that even after checking this is ready, sending a request
108    /// may still fail because the connection was closed in the meantime.
109    pub fn is_ready(&self) -> bool {
110        self.dispatch.is_ready()
111    }
112
113    /// Checks if the connection side has been closed.
114    pub fn is_closed(&self) -> bool {
115        self.dispatch.is_closed()
116    }
117}
118
119impl<B> SendRequest<B>
120where
121    B: Body + 'static,
122{
123    /// Sends a `Request` on the associated connection.
124    ///
125    /// Returns a future that if successful, yields the `Response`.
126    ///
127    /// # Note
128    ///
129    /// There are some key differences in what automatic things the `Client`
130    /// does for you that will not be done here:
131    ///
132    /// - `Client` requires absolute-form `Uri`s, since the scheme and
133    ///   authority are needed to connect. They aren't required here.
134    /// - Since the `Client` requires absolute-form `Uri`s, it can add
135    ///   the `Host` header based on it. You must add a `Host` header yourself
136    ///   before calling this method.
137    /// - Since absolute-form `Uri`s are not required, if received, they will
138    ///   be serialized as-is.
139    pub fn send_request(
140        &mut self,
141        req: Request<B>,
142    ) -> impl Future<Output = crate::Result<Response<IncomingBody>>> {
143        let sent = self.dispatch.send(req);
144
145        async move {
146            match sent {
147                Ok(rx) => match rx.await {
148                    Ok(Ok(resp)) => Ok(resp),
149                    Ok(Err(err)) => Err(err),
150                    // this is definite bug if it happens, but it shouldn't happen!
151                    Err(_canceled) => panic!("dispatch dropped without returning error"),
152                },
153                Err(_req) => {
154                    debug!("connection was not ready");
155
156                    Err(crate::Error::new_canceled().with("connection was not ready"))
157                }
158            }
159        }
160    }
161
162    /*
163    pub(super) fn send_request_retryable(
164        &mut self,
165        req: Request<B>,
166    ) -> impl Future<Output = Result<Response<Body>, (crate::Error, Option<Request<B>>)>> + Unpin
167    where
168        B: Send,
169    {
170        match self.dispatch.try_send(req) {
171            Ok(rx) => {
172                Either::Left(rx.then(move |res| {
173                    match res {
174                        Ok(Ok(res)) => future::ok(res),
175                        Ok(Err(err)) => future::err(err),
176                        // this is definite bug if it happens, but it shouldn't happen!
177                        Err(_) => panic!("dispatch dropped without returning error"),
178                    }
179                }))
180            }
181            Err(req) => {
182                debug!("connection was not ready");
183                let err = crate::Error::new_canceled().with("connection was not ready");
184                Either::Right(future::err((err, Some(req))))
185            }
186        }
187    }
188    */
189}
190
191impl<B> fmt::Debug for SendRequest<B> {
192    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
193        f.debug_struct("SendRequest").finish()
194    }
195}
196
197// ===== impl Connection
198
199impl<T, B, E> Connection<T, B, E>
200where
201    T: Read + Write + Unpin + 'static,
202    B: Body + Unpin + 'static,
203    B::Data: Send,
204    B::Error: Into<Box<dyn Error + Send + Sync>>,
205    E: Http2ClientConnExec<B, T> + Unpin,
206{
207    /// Returns whether the [extended CONNECT protocol][1] is enabled or not.
208    ///
209    /// This setting is configured by the server peer by sending the
210    /// [`SETTINGS_ENABLE_CONNECT_PROTOCOL` parameter][2] in a `SETTINGS` frame.
211    /// This method returns the currently acknowledged value received from the
212    /// remote.
213    ///
214    /// [1]: https://datatracker.ietf.org/doc/html/rfc8441#section-4
215    /// [2]: https://datatracker.ietf.org/doc/html/rfc8441#section-3
216    pub fn is_extended_connect_protocol_enabled(&self) -> bool {
217        self.inner.1.is_extended_connect_protocol_enabled()
218    }
219}
220
221impl<T, B, E> fmt::Debug for Connection<T, B, E>
222where
223    T: Read + Write + fmt::Debug + 'static + Unpin,
224    B: Body + 'static,
225    E: Http2ClientConnExec<B, T> + Unpin,
226    B::Error: Into<Box<dyn Error + Send + Sync>>,
227{
228    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
229        f.debug_struct("Connection").finish()
230    }
231}
232
233impl<T, B, E> Future for Connection<T, B, E>
234where
235    T: Read + Write + Unpin + 'static,
236    B: Body + 'static + Unpin,
237    B::Data: Send,
238    E: Unpin,
239    B::Error: Into<Box<dyn Error + Send + Sync>>,
240    E: Http2ClientConnExec<B, T> + 'static + Send + Sync + Unpin,
241{
242    type Output = crate::Result<()>;
243
244    fn poll(mut self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<Self::Output> {
245        match ready!(Pin::new(&mut self.inner.1).poll(cx))? {
246            proto::Dispatched::Shutdown => Poll::Ready(Ok(())),
247            #[cfg(feature = "http1")]
248            proto::Dispatched::Upgrade(_pending) => unreachable!("http2 cannot upgrade"),
249        }
250    }
251}
252
253// ===== impl Builder
254
255impl<Ex> Builder<Ex>
256where
257    Ex: Clone,
258{
259    /// Creates a new connection builder.
260    #[inline]
261    pub fn new(exec: Ex) -> Builder<Ex> {
262        Builder {
263            exec,
264            timer: Time::Empty,
265            h2_builder: Default::default(),
266        }
267    }
268
269    /// Provide a timer to execute background HTTP2 tasks.
270    pub fn timer<M>(&mut self, timer: M) -> &mut Builder<Ex>
271    where
272        M: Timer + Send + Sync + 'static,
273    {
274        self.timer = Time::Timer(Arc::new(timer));
275        self
276    }
277
278    /// Sets the [`SETTINGS_INITIAL_WINDOW_SIZE`][spec] option for HTTP2
279    /// stream-level flow control.
280    ///
281    /// Passing `None` will do nothing.
282    ///
283    /// If not set, hyper will use a default.
284    ///
285    /// [spec]: https://httpwg.org/specs/rfc9113.html#SETTINGS_INITIAL_WINDOW_SIZE
286    pub fn initial_stream_window_size(&mut self, sz: impl Into<Option<u32>>) -> &mut Self {
287        if let Some(sz) = sz.into() {
288            self.h2_builder.adaptive_window = false;
289            self.h2_builder.initial_stream_window_size = sz;
290        }
291        self
292    }
293
294    /// Sets the max connection-level flow control for HTTP2
295    ///
296    /// Passing `None` will do nothing.
297    ///
298    /// If not set, hyper will use a default.
299    pub fn initial_connection_window_size(&mut self, sz: impl Into<Option<u32>>) -> &mut Self {
300        if let Some(sz) = sz.into() {
301            self.h2_builder.adaptive_window = false;
302            self.h2_builder.initial_conn_window_size = sz;
303        }
304        self
305    }
306
307    /// Sets whether to use an adaptive flow control.
308    ///
309    /// Enabling this will override the limits set in
310    /// `initial_stream_window_size` and
311    /// `initial_connection_window_size`.
312    pub fn adaptive_window(&mut self, enabled: bool) -> &mut Self {
313        use proto::h2::SPEC_WINDOW_SIZE;
314
315        self.h2_builder.adaptive_window = enabled;
316        if enabled {
317            self.h2_builder.initial_conn_window_size = SPEC_WINDOW_SIZE;
318            self.h2_builder.initial_stream_window_size = SPEC_WINDOW_SIZE;
319        }
320        self
321    }
322
323    /// Sets the maximum frame size to use for HTTP2.
324    ///
325    /// Passing `None` will do nothing.
326    ///
327    /// If not set, hyper will use a default.
328    pub fn max_frame_size(&mut self, sz: impl Into<Option<u32>>) -> &mut Self {
329        if let Some(sz) = sz.into() {
330            self.h2_builder.max_frame_size = sz;
331        }
332        self
333    }
334
335    /// Sets an interval for HTTP2 Ping frames should be sent to keep a
336    /// connection alive.
337    ///
338    /// Pass `None` to disable HTTP2 keep-alive.
339    ///
340    /// Default is currently disabled.
341    pub fn keep_alive_interval(&mut self, interval: impl Into<Option<Duration>>) -> &mut Self {
342        self.h2_builder.keep_alive_interval = interval.into();
343        self
344    }
345
346    /// Sets a timeout for receiving an acknowledgement of the keep-alive ping.
347    ///
348    /// If the ping is not acknowledged within the timeout, the connection will
349    /// be closed. Does nothing if `keep_alive_interval` is disabled.
350    ///
351    /// Default is 20 seconds.
352    pub fn keep_alive_timeout(&mut self, timeout: Duration) -> &mut Self {
353        self.h2_builder.keep_alive_timeout = timeout;
354        self
355    }
356
357    /// Sets whether HTTP2 keep-alive should apply while the connection is idle.
358    ///
359    /// If disabled, keep-alive pings are only sent while there are open
360    /// request/responses streams. If enabled, pings are also sent when no
361    /// streams are active. Does nothing if `keep_alive_interval` is
362    /// disabled.
363    ///
364    /// Default is `false`.
365    pub fn keep_alive_while_idle(&mut self, enabled: bool) -> &mut Self {
366        self.h2_builder.keep_alive_while_idle = enabled;
367        self
368    }
369
370    /// Sets the maximum number of HTTP2 concurrent locally reset streams.
371    ///
372    /// See the documentation of [`h2::client::Builder::max_concurrent_reset_streams`] for more
373    /// details.
374    ///
375    /// The default value is determined by the `h2` crate.
376    ///
377    /// [`h2::client::Builder::max_concurrent_reset_streams`]: https://docs.rs/h2/client/struct.Builder.html#method.max_concurrent_reset_streams
378    pub fn max_concurrent_reset_streams(&mut self, max: usize) -> &mut Self {
379        self.h2_builder.max_concurrent_reset_streams = Some(max);
380        self
381    }
382
383    /// Set the maximum write buffer size for each HTTP/2 stream.
384    ///
385    /// Default is currently 1MB, but may change.
386    ///
387    /// # Panics
388    ///
389    /// The value must be no larger than `u32::MAX`.
390    pub fn max_send_buf_size(&mut self, max: usize) -> &mut Self {
391        assert!(max <= std::u32::MAX as usize);
392        self.h2_builder.max_send_buffer_size = max;
393        self
394    }
395
396    /// Constructs a connection with the configured options and IO.
397    /// See [`client::conn`](crate::client::conn) for more.
398    ///
399    /// Note, if [`Connection`] is not `await`-ed, [`SendRequest`] will
400    /// do nothing.
401    pub fn handshake<T, B>(
402        &self,
403        io: T,
404    ) -> impl Future<Output = crate::Result<(SendRequest<B>, Connection<T, B, Ex>)>>
405    where
406        T: Read + Write + Unpin + 'static,
407        B: Body + 'static,
408        B::Data: Send,
409        B::Error: Into<Box<dyn Error + Send + Sync>>,
410        Ex: Http2ClientConnExec<B, T> + Unpin,
411    {
412        let opts = self.clone();
413
414        async move {
415            trace!("client handshake HTTP/1");
416
417            let (tx, rx) = dispatch::channel();
418            let h2 = proto::h2::client::handshake(io, rx, &opts.h2_builder, opts.exec, opts.timer)
419                .await?;
420            Ok((
421                SendRequest {
422                    dispatch: tx.unbound(),
423                },
424                Connection {
425                    inner: (PhantomData, h2),
426                },
427            ))
428        }
429    }
430}