rama_hyper/server/conn/
http2.rs

1//! HTTP/2 Server Connections
2
3use std::error::Error as StdError;
4use std::fmt;
5use std::future::Future;
6use std::marker::Unpin;
7use std::pin::Pin;
8use std::sync::Arc;
9use std::task::{Context, Poll};
10use std::time::Duration;
11
12use crate::rt::{Read, Write};
13use pin_project_lite::pin_project;
14
15use crate::body::{Body, Incoming as IncomingBody};
16use crate::proto;
17use crate::rt::bounds::Http2ServerConnExec;
18use crate::service::HttpService;
19use crate::{common::time::Time, rt::Timer};
20
21pin_project! {
22    /// A [`Future`](core::future::Future) representing an HTTP/2 connection, bound to a
23    /// [`Service`](crate::service::Service), returned from
24    /// [`Builder::serve_connection`](struct.Builder.html#method.serve_connection).
25    ///
26    /// To drive HTTP on this connection this future **must be polled**, typically with
27    /// `.await`. If it isn't polled, no progress will be made on this connection.
28    #[must_use = "futures do nothing unless polled"]
29    pub struct Connection<T, S, E>
30    where
31        S: HttpService<IncomingBody>,
32    {
33        conn: proto::h2::Server<T, S, S::ResBody, E>,
34    }
35}
36
37/// A configuration builder for HTTP/2 server connections.
38///
39/// **Note**: The default values of options are *not considered stable*. They
40/// are subject to change at any time.
41#[derive(Clone, Debug)]
42pub struct Builder<E> {
43    exec: E,
44    timer: Time,
45    h2_builder: proto::h2::server::Config,
46}
47
48// ===== impl Connection =====
49
50impl<I, S, E> fmt::Debug for Connection<I, S, E>
51where
52    S: HttpService<IncomingBody>,
53{
54    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
55        f.debug_struct("Connection").finish()
56    }
57}
58
59impl<I, B, S, E> Connection<I, S, E>
60where
61    S: HttpService<IncomingBody, ResBody = B>,
62    S::Error: Into<Box<dyn StdError + Send + Sync>>,
63    I: Read + Write + Unpin,
64    B: Body + 'static,
65    B::Error: Into<Box<dyn StdError + Send + Sync>>,
66    E: Http2ServerConnExec<S::Future, B>,
67{
68    /// Start a graceful shutdown process for this connection.
69    ///
70    /// This `Connection` should continue to be polled until shutdown
71    /// can finish.
72    ///
73    /// # Note
74    ///
75    /// This should only be called while the `Connection` future is still
76    /// pending. If called after `Connection::poll` has resolved, this does
77    /// nothing.
78    pub fn graceful_shutdown(mut self: Pin<&mut Self>) {
79        self.conn.graceful_shutdown();
80    }
81}
82
83impl<I, B, S, E> Future for Connection<I, S, E>
84where
85    S: HttpService<IncomingBody, ResBody = B>,
86    S::Error: Into<Box<dyn StdError + Send + Sync>>,
87    I: Read + Write + Unpin + 'static,
88    B: Body + 'static,
89    B::Error: Into<Box<dyn StdError + Send + Sync>>,
90    E: Http2ServerConnExec<S::Future, B>,
91{
92    type Output = crate::Result<()>;
93
94    fn poll(mut self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<Self::Output> {
95        match ready!(Pin::new(&mut self.conn).poll(cx)) {
96            Ok(_done) => {
97                //TODO: the proto::h2::Server no longer needs to return
98                //the Dispatched enum
99                Poll::Ready(Ok(()))
100            }
101            Err(e) => Poll::Ready(Err(e)),
102        }
103    }
104}
105
106// ===== impl Builder =====
107
108impl<E> Builder<E> {
109    /// Create a new connection builder.
110    ///
111    /// This starts with the default options, and an executor which is a type
112    /// that implements [`Http2ServerConnExec`] trait.
113    ///
114    /// [`Http2ServerConnExec`]: crate::rt::bounds::Http2ServerConnExec
115    pub fn new(exec: E) -> Self {
116        Self {
117            exec,
118            timer: Time::Empty,
119            h2_builder: Default::default(),
120        }
121    }
122
123    /// Sets the [`SETTINGS_INITIAL_WINDOW_SIZE`][spec] option for HTTP2
124    /// stream-level flow control.
125    ///
126    /// Passing `None` will do nothing.
127    ///
128    /// If not set, hyper will use a default.
129    ///
130    /// [spec]: https://httpwg.org/specs/rfc9113.html#SETTINGS_INITIAL_WINDOW_SIZE
131    pub fn initial_stream_window_size(&mut self, sz: impl Into<Option<u32>>) -> &mut Self {
132        if let Some(sz) = sz.into() {
133            self.h2_builder.adaptive_window = false;
134            self.h2_builder.initial_stream_window_size = sz;
135        }
136        self
137    }
138
139    /// Sets the max connection-level flow control for HTTP2.
140    ///
141    /// Passing `None` will do nothing.
142    ///
143    /// If not set, hyper will use a default.
144    pub fn initial_connection_window_size(&mut self, sz: impl Into<Option<u32>>) -> &mut Self {
145        if let Some(sz) = sz.into() {
146            self.h2_builder.adaptive_window = false;
147            self.h2_builder.initial_conn_window_size = sz;
148        }
149        self
150    }
151
152    /// Sets whether to use an adaptive flow control.
153    ///
154    /// Enabling this will override the limits set in
155    /// `initial_stream_window_size` and
156    /// `initial_connection_window_size`.
157    pub fn adaptive_window(&mut self, enabled: bool) -> &mut Self {
158        use proto::h2::SPEC_WINDOW_SIZE;
159
160        self.h2_builder.adaptive_window = enabled;
161        if enabled {
162            self.h2_builder.initial_conn_window_size = SPEC_WINDOW_SIZE;
163            self.h2_builder.initial_stream_window_size = SPEC_WINDOW_SIZE;
164        }
165        self
166    }
167
168    /// Sets the maximum frame size to use for HTTP2.
169    ///
170    /// Passing `None` will do nothing.
171    ///
172    /// If not set, hyper will use a default.
173    pub fn max_frame_size(&mut self, sz: impl Into<Option<u32>>) -> &mut Self {
174        if let Some(sz) = sz.into() {
175            self.h2_builder.max_frame_size = sz;
176        }
177        self
178    }
179
180    /// Sets the [`SETTINGS_MAX_CONCURRENT_STREAMS`][spec] option for HTTP2
181    /// connections.
182    ///
183    /// Default is 200, but not part of the stability of hyper. It could change
184    /// in a future release. You are encouraged to set your own limit.
185    ///
186    /// Passing `None` will remove any limit.
187    ///
188    /// [spec]: https://httpwg.org/specs/rfc9113.html#SETTINGS_MAX_CONCURRENT_STREAMS
189    pub fn max_concurrent_streams(&mut self, max: impl Into<Option<u32>>) -> &mut Self {
190        self.h2_builder.max_concurrent_streams = max.into();
191        self
192    }
193
194    /// Sets an interval for HTTP2 Ping frames should be sent to keep a
195    /// connection alive.
196    ///
197    /// Pass `None` to disable HTTP2 keep-alive.
198    ///
199    /// Default is currently disabled.
200    pub fn keep_alive_interval(&mut self, interval: impl Into<Option<Duration>>) -> &mut Self {
201        self.h2_builder.keep_alive_interval = interval.into();
202        self
203    }
204
205    /// Sets a timeout for receiving an acknowledgement of the keep-alive ping.
206    ///
207    /// If the ping is not acknowledged within the timeout, the connection will
208    /// be closed. Does nothing if `keep_alive_interval` is disabled.
209    ///
210    /// Default is 20 seconds.
211    pub fn keep_alive_timeout(&mut self, timeout: Duration) -> &mut Self {
212        self.h2_builder.keep_alive_timeout = timeout;
213        self
214    }
215
216    /// Set the maximum write buffer size for each HTTP/2 stream.
217    ///
218    /// Default is currently ~400KB, but may change.
219    ///
220    /// # Panics
221    ///
222    /// The value must be no larger than `u32::MAX`.
223    pub fn max_send_buf_size(&mut self, max: usize) -> &mut Self {
224        assert!(max <= std::u32::MAX as usize);
225        self.h2_builder.max_send_buffer_size = max;
226        self
227    }
228
229    /// Enables the [extended CONNECT protocol].
230    ///
231    /// [extended CONNECT protocol]: https://datatracker.ietf.org/doc/html/rfc8441#section-4
232    pub fn enable_connect_protocol(&mut self) -> &mut Self {
233        self.h2_builder.enable_connect_protocol = true;
234        self
235    }
236
237    /// Sets the max size of received header frames.
238    ///
239    /// Default is currently ~16MB, but may change.
240    pub fn max_header_list_size(&mut self, max: u32) -> &mut Self {
241        self.h2_builder.max_header_list_size = max;
242        self
243    }
244
245    /// Set the timer used in background tasks.
246    pub fn timer<M>(&mut self, timer: M) -> &mut Self
247    where
248        M: Timer + Send + Sync + 'static,
249    {
250        self.timer = Time::Timer(Arc::new(timer));
251        self
252    }
253
254    /// Bind a connection together with a [`Service`](crate::service::Service).
255    ///
256    /// This returns a Future that must be polled in order for HTTP to be
257    /// driven on the connection.
258    pub fn serve_connection<S, I, Bd>(&self, io: I, service: S) -> Connection<I, S, E>
259    where
260        S: HttpService<IncomingBody, ResBody = Bd>,
261        S::Error: Into<Box<dyn StdError + Send + Sync>>,
262        Bd: Body + 'static,
263        Bd::Error: Into<Box<dyn StdError + Send + Sync>>,
264        I: Read + Write + Unpin,
265        E: Http2ServerConnExec<S::Future, Bd>,
266    {
267        let proto = proto::h2::Server::new(
268            io,
269            service,
270            &self.h2_builder,
271            self.exec.clone(),
272            self.timer.clone(),
273        );
274        Connection { conn: proto }
275    }
276}