Skip to main content

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 futures_core::ready;
14use http::{Request, Response};
15
16use super::super::dispatch::{self, TrySendError};
17use crate::body::{Body, Incoming as IncomingBody};
18use crate::common::time::Time;
19use crate::proto;
20use crate::rt::bounds::Http2ClientConnExec;
21use crate::rt::Timer;
22
23/// The sender side of an established connection.
24pub struct SendRequest<B> {
25    dispatch: dispatch::UnboundedSender<Request<B>, Response<IncomingBody>>,
26}
27
28impl<B> Clone for SendRequest<B> {
29    fn clone(&self) -> SendRequest<B> {
30        SendRequest {
31            dispatch: self.dispatch.clone(),
32        }
33    }
34}
35
36/// A future that processes all HTTP state for the IO object.
37///
38/// In most cases, this should just be spawned into an executor, so that it
39/// can process incoming and outgoing messages, notice hangups, and the like.
40///
41/// Instances of this type are typically created via the [`handshake`] function.
42///
43/// # Drop behavior
44///
45/// Dropping the `Connection` will close the underlying IO resource.
46/// Any in-flight requests that have not received a response will be
47/// interrupted. If graceful shutdown is desired, poll the connection
48/// until it completes instead of dropping.
49#[must_use = "futures do nothing unless polled"]
50pub struct Connection<T, B, E>
51where
52    T: Read + Write + Unpin,
53    B: Body + 'static,
54    E: Http2ClientConnExec<B, T> + Unpin,
55    B::Error: Into<Box<dyn Error + Send + Sync>>,
56{
57    inner: (PhantomData<T>, proto::h2::ClientTask<B, E, T>),
58}
59
60/// A builder to configure an HTTP connection.
61///
62/// After setting options, the builder is used to create a handshake future.
63///
64/// **Note**: The default values of options are *not considered stable*. They
65/// are subject to change at any time.
66#[derive(Clone, Debug)]
67pub struct Builder<Ex> {
68    pub(super) exec: Ex,
69    pub(super) timer: Time,
70    h2_builder: proto::h2::client::Config,
71}
72
73/// Returns a handshake future over some IO.
74///
75/// This is a shortcut for `Builder::new(exec).handshake(io)`.
76/// See [`client::conn`](crate::client::conn) for more.
77///
78/// # Errors
79///
80/// Returns an error if the HTTP/2 connection handshake fails.
81pub async fn handshake<E, T, B>(
82    exec: E,
83    io: T,
84) -> crate::Result<(SendRequest<B>, Connection<T, B, E>)>
85where
86    T: Read + Write + Unpin,
87    B: Body + 'static,
88    B::Data: Send,
89    B::Error: Into<Box<dyn Error + Send + Sync>>,
90    E: Http2ClientConnExec<B, T> + Unpin + Clone,
91{
92    Builder::new(exec).handshake(io).await
93}
94
95// ===== impl SendRequest
96
97impl<B> SendRequest<B> {
98    /// Polls to determine whether this sender can be used yet for a request.
99    ///
100    /// If the associated connection is closed, this returns an Error.
101    pub fn poll_ready(&mut self, _cx: &mut Context<'_>) -> Poll<crate::Result<()>> {
102        if self.is_closed() {
103            Poll::Ready(Err(crate::Error::new_closed()))
104        } else {
105            Poll::Ready(Ok(()))
106        }
107    }
108
109    /// Waits until the dispatcher is ready.
110    ///
111    /// # Errors
112    ///
113    /// If the associated connection is closed, this returns an Error.
114    pub async fn ready(&mut self) -> crate::Result<()> {
115        crate::common::future::poll_fn(|cx| self.poll_ready(cx)).await
116    }
117
118    /// Checks if the connection is currently ready to send a request.
119    ///
120    /// # Note
121    ///
122    /// This is mostly a hint. Due to inherent latency of networks, it is
123    /// possible that even after checking this is ready, sending a request
124    /// may still fail because the connection was closed in the meantime.
125    pub fn is_ready(&self) -> bool {
126        self.dispatch.is_ready()
127    }
128
129    /// Checks if the connection side has been closed.
130    pub fn is_closed(&self) -> bool {
131        self.dispatch.is_closed()
132    }
133}
134
135impl<B> SendRequest<B>
136where
137    B: Body + 'static,
138{
139    /// Sends a `Request` on the associated connection.
140    ///
141    /// Returns a future that if successful, yields the `Response`.
142    ///
143    /// `req` must have a `Host` header.
144    ///
145    /// Absolute-form `Uri`s are not required. If received, they will be serialized
146    /// as-is.
147    ///
148    /// # Cancel safety
149    ///
150    /// Dropping the returned future is the supported way to cancel an
151    /// in-flight HTTP/2 request. The stream is reset with `RST_STREAM`
152    /// (`CANCEL` error code); the shared connection remains usable for
153    /// other in-flight and future requests. The peer is notified
154    /// immediately rather than continuing to send a response body that
155    /// would be discarded.
156    ///
157    /// # Errors
158    ///
159    /// Returns an error if the connection is not ready or if an error occurs while
160    /// processing the request.
161    pub fn send_request(
162        &mut self,
163        req: Request<B>,
164    ) -> impl Future<Output = crate::Result<Response<IncomingBody>>> {
165        let sent = self.dispatch.send(req);
166
167        async move {
168            match sent {
169                Ok(rx) => match rx.await {
170                    Ok(Ok(resp)) => Ok(resp),
171                    Ok(Err(err)) => Err(err),
172                    // this is definite bug if it happens, but it shouldn't happen!
173                    Err(_canceled) => panic!("dispatch dropped without returning error"),
174                },
175                Err(_req) => {
176                    debug!("connection was not ready");
177
178                    Err(crate::Error::new_canceled().with("connection was not ready"))
179                }
180            }
181        }
182    }
183
184    /// Sends a `Request` on the associated connection.
185    ///
186    /// Returns a future that if successful, yields the `Response`.
187    ///
188    /// # Errors
189    ///
190    /// If there was an error before trying to serialize the request to the
191    /// connection, the message will be returned as part of this error.
192    #[allow(clippy::result_large_err)]
193    pub fn try_send_request(
194        &mut self,
195        req: Request<B>,
196    ) -> impl Future<Output = Result<Response<IncomingBody>, TrySendError<Request<B>>>> {
197        let sent = self.dispatch.try_send(req);
198        async move {
199            match sent {
200                Ok(rx) => match rx.await {
201                    Ok(Ok(res)) => Ok(res),
202                    Ok(Err(err)) => Err(err),
203                    // this is definite bug if it happens, but it shouldn't happen!
204                    Err(_) => panic!("dispatch dropped without returning error"),
205                },
206                Err(req) => {
207                    debug!("connection was not ready");
208                    let error = crate::Error::new_canceled().with("connection was not ready");
209                    Err(TrySendError {
210                        error,
211                        message: Some(req),
212                    })
213                }
214            }
215        }
216    }
217}
218
219impl<B> fmt::Debug for SendRequest<B> {
220    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
221        f.debug_struct("SendRequest").finish()
222    }
223}
224
225// ===== impl Connection
226
227impl<T, B, E> Connection<T, B, E>
228where
229    T: Read + Write + Unpin + 'static,
230    B: Body + Unpin + 'static,
231    B::Data: Send,
232    B::Error: Into<Box<dyn Error + Send + Sync>>,
233    E: Http2ClientConnExec<B, T> + Unpin,
234{
235    /// Returns whether the [extended CONNECT protocol][1] is enabled or not.
236    ///
237    /// This setting is configured by the server peer by sending the
238    /// [`SETTINGS_ENABLE_CONNECT_PROTOCOL` parameter][2] in a `SETTINGS` frame.
239    /// This method returns the currently acknowledged value received from the
240    /// remote.
241    ///
242    /// [1]: https://datatracker.ietf.org/doc/html/rfc8441#section-4
243    /// [2]: https://datatracker.ietf.org/doc/html/rfc8441#section-3
244    pub fn is_extended_connect_protocol_enabled(&self) -> bool {
245        self.inner.1.is_extended_connect_protocol_enabled()
246    }
247
248    /// Returns the current maximum send stream count.
249    ///
250    /// This setting is configured in a [`SETTINGS_MAX_CONCURRENT_STREAMS` parameter][1] in a `SETTINGS` frame,
251    /// and may change throughout the connection lifetime.
252    ///
253    /// [1]: https://datatracker.ietf.org/doc/html/rfc7540#section-5.1.2
254    pub fn current_max_send_streams(&self) -> usize {
255        self.inner.1.current_max_send_streams()
256    }
257
258    /// Returns the current maximum receive stream count.
259    ///
260    /// This setting is configured in a [`SETTINGS_MAX_CONCURRENT_STREAMS` parameter][1] in a `SETTINGS` frame,
261    /// and may change throughout the connection lifetime.
262    ///
263    /// [1]: https://datatracker.ietf.org/doc/html/rfc7540#section-5.1.2
264    pub fn current_max_recv_streams(&self) -> usize {
265        self.inner.1.current_max_recv_streams()
266    }
267}
268
269impl<T, B, E> fmt::Debug for Connection<T, B, E>
270where
271    T: Read + Write + fmt::Debug + 'static + Unpin,
272    B: Body + 'static,
273    E: Http2ClientConnExec<B, T> + Unpin,
274    B::Error: Into<Box<dyn Error + Send + Sync>>,
275{
276    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
277        f.debug_struct("Connection").finish()
278    }
279}
280
281impl<T, B, E> Future for Connection<T, B, E>
282where
283    T: Read + Write + Unpin + 'static,
284    B: Body + 'static + Unpin,
285    B::Data: Send,
286    E: Unpin,
287    B::Error: Into<Box<dyn Error + Send + Sync>>,
288    E: Http2ClientConnExec<B, T> + Unpin,
289{
290    type Output = crate::Result<()>;
291
292    fn poll(mut self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<Self::Output> {
293        match ready!(Pin::new(&mut self.inner.1).poll(cx))? {
294            proto::Dispatched::Shutdown => Poll::Ready(Ok(())),
295            #[cfg(feature = "http1")]
296            proto::Dispatched::Upgrade(_pending) => unreachable!("http2 cannot upgrade"),
297        }
298    }
299}
300
301// ===== impl Builder
302
303impl<Ex> Builder<Ex>
304where
305    Ex: Clone,
306{
307    /// Creates a new connection builder.
308    #[inline]
309    pub fn new(exec: Ex) -> Builder<Ex> {
310        Builder {
311            exec,
312            timer: Time::Empty,
313            h2_builder: proto::h2::client::Config::default(),
314        }
315    }
316
317    /// Provide a timer to execute background HTTP2 tasks.
318    pub fn timer<M>(&mut self, timer: M) -> &mut Builder<Ex>
319    where
320        M: Timer + Send + Sync + 'static,
321    {
322        self.timer = Time::Timer(Arc::new(timer));
323        self
324    }
325
326    /// Sets the [`SETTINGS_INITIAL_WINDOW_SIZE`][spec] option for HTTP2
327    /// stream-level flow control.
328    ///
329    /// Passing `None` will do nothing.
330    ///
331    /// If not set, hyper will use a default.
332    ///
333    /// [spec]: https://httpwg.org/specs/rfc9113.html#SETTINGS_INITIAL_WINDOW_SIZE
334    pub fn initial_stream_window_size(&mut self, sz: impl Into<Option<u32>>) -> &mut Self {
335        if let Some(sz) = sz.into() {
336            self.h2_builder.adaptive_window = false;
337            self.h2_builder.initial_stream_window_size = sz;
338        }
339        self
340    }
341
342    /// Sets the max connection-level flow control for HTTP2.
343    ///
344    /// Passing `None` will do nothing.
345    ///
346    /// If not set, hyper will use a default.
347    pub fn initial_connection_window_size(&mut self, sz: impl Into<Option<u32>>) -> &mut Self {
348        if let Some(sz) = sz.into() {
349            self.h2_builder.adaptive_window = false;
350            self.h2_builder.initial_conn_window_size = sz;
351        }
352        self
353    }
354
355    /// Sets the initial maximum of locally initiated (send) streams.
356    ///
357    /// This value will be overwritten by the value included in the initial
358    /// SETTINGS frame received from the peer as part of a [connection preface].
359    ///
360    /// Passing `None` will do nothing.
361    ///
362    /// If not set, hyper will use a default.
363    ///
364    /// [connection preface]: https://httpwg.org/specs/rfc9113.html#preface
365    pub fn initial_max_send_streams(&mut self, initial: impl Into<Option<usize>>) -> &mut Self {
366        if let Some(initial) = initial.into() {
367            self.h2_builder.initial_max_send_streams = initial;
368        }
369        self
370    }
371
372    /// Sets whether to use an adaptive flow control.
373    ///
374    /// Enabling this will override the limits set in
375    /// `initial_stream_window_size` and
376    /// `initial_connection_window_size`.
377    pub fn adaptive_window(&mut self, enabled: bool) -> &mut Self {
378        use proto::h2::SPEC_WINDOW_SIZE;
379
380        self.h2_builder.adaptive_window = enabled;
381        if enabled {
382            self.h2_builder.initial_conn_window_size = SPEC_WINDOW_SIZE;
383            self.h2_builder.initial_stream_window_size = SPEC_WINDOW_SIZE;
384        }
385        self
386    }
387
388    /// Sets the maximum frame size to use for HTTP2.
389    ///
390    /// Default is currently 16KB, but can change.
391    pub fn max_frame_size(&mut self, sz: impl Into<Option<u32>>) -> &mut Self {
392        self.h2_builder.max_frame_size = sz.into();
393        self
394    }
395
396    /// Sets the max size of received header frames.
397    ///
398    /// Default is currently 16KB, but can change.
399    pub fn max_header_list_size(&mut self, max: u32) -> &mut Self {
400        self.h2_builder.max_header_list_size = max;
401        self
402    }
403
404    /// Sets the header table size.
405    ///
406    /// This setting informs the peer of the maximum size of the header compression
407    /// table used to encode header blocks, in octets. The encoder may select any value
408    /// equal to or less than the header table size specified by the sender.
409    ///
410    /// The default value of crate `h2` is 4,096.
411    pub fn header_table_size(&mut self, size: impl Into<Option<u32>>) -> &mut Self {
412        self.h2_builder.header_table_size = size.into();
413        self
414    }
415
416    /// Sets the maximum number of concurrent streams.
417    ///
418    /// The maximum concurrent streams setting only controls the maximum number
419    /// of streams that can be initiated by the remote peer. In other words,
420    /// when this setting is set to 100, this does not limit the number of
421    /// concurrent streams that can be created by the caller.
422    ///
423    /// It is recommended that this value be no smaller than 100, so as to not
424    /// unnecessarily limit parallelism. However, any value is legal, including
425    /// 0. If `max` is set to 0, then the remote will not be permitted to
426    /// initiate streams.
427    ///
428    /// Note that streams in the reserved state, i.e., push promises that have
429    /// been reserved but the stream has not started, do not count against this
430    /// setting.
431    ///
432    /// Also note that if the remote *does* exceed the value set here, it is not
433    /// a protocol level error. Instead, the `h2` library will immediately reset
434    /// the stream.
435    ///
436    /// See [Section 5.1.2] in the HTTP/2 spec for more details.
437    ///
438    /// [Section 5.1.2]: https://httpwg.org/specs/rfc7540.html#rfc.section.5.1.2
439    pub fn max_concurrent_streams(&mut self, max: impl Into<Option<u32>>) -> &mut Self {
440        self.h2_builder.max_concurrent_streams = max.into();
441        self
442    }
443
444    /// Sets an interval for HTTP2 Ping frames should be sent to keep a
445    /// connection alive.
446    ///
447    /// Pass `None` to disable HTTP2 keep-alive.
448    ///
449    /// Default is currently disabled.
450    pub fn keep_alive_interval(&mut self, interval: impl Into<Option<Duration>>) -> &mut Self {
451        self.h2_builder.keep_alive_interval = interval.into();
452        self
453    }
454
455    /// Sets a timeout for receiving an acknowledgement of the keep-alive ping.
456    ///
457    /// If the ping is not acknowledged within the timeout, the connection will
458    /// be closed. Does nothing if `keep_alive_interval` is disabled.
459    ///
460    /// Default is 20 seconds.
461    pub fn keep_alive_timeout(&mut self, timeout: Duration) -> &mut Self {
462        self.h2_builder.keep_alive_timeout = timeout;
463        self
464    }
465
466    /// Sets whether HTTP2 keep-alive should apply while the connection is idle.
467    ///
468    /// If disabled, keep-alive pings are only sent while there are open
469    /// request/responses streams. If enabled, pings are also sent when no
470    /// streams are active. Does nothing if `keep_alive_interval` is
471    /// disabled.
472    ///
473    /// Default is `false`.
474    pub fn keep_alive_while_idle(&mut self, enabled: bool) -> &mut Self {
475        self.h2_builder.keep_alive_while_idle = enabled;
476        self
477    }
478
479    /// Sets the maximum number of HTTP2 concurrent locally reset streams.
480    ///
481    /// See the documentation of [`h2::client::Builder::max_concurrent_reset_streams`] for more
482    /// details.
483    ///
484    /// The default value is determined by the `h2` crate.
485    ///
486    /// [`h2::client::Builder::max_concurrent_reset_streams`]: https://docs.rs/h2/client/struct.Builder.html#method.max_concurrent_reset_streams
487    pub fn max_concurrent_reset_streams(&mut self, max: usize) -> &mut Self {
488        self.h2_builder.max_concurrent_reset_streams = Some(max);
489        self
490    }
491
492    /// Set the maximum write buffer size for each HTTP/2 stream.
493    ///
494    /// Default is currently 1MB, but may change.
495    ///
496    /// # Panics
497    ///
498    /// The value must be no larger than `u32::MAX`.
499    pub fn max_send_buf_size(&mut self, max: usize) -> &mut Self {
500        assert!(max <= u32::MAX as usize);
501        self.h2_builder.max_send_buffer_size = max;
502        self
503    }
504
505    /// Configures the maximum number of pending reset streams allowed before a GOAWAY will be sent.
506    ///
507    /// This will default to the default value set by the [`h2` crate](https://crates.io/crates/h2).
508    /// As of v0.4.0, it is 20.
509    ///
510    /// See <https://github.com/hyperium/hyper/issues/2877> for more information.
511    pub fn max_pending_accept_reset_streams(&mut self, max: impl Into<Option<usize>>) -> &mut Self {
512        self.h2_builder.max_pending_accept_reset_streams = max.into();
513        self
514    }
515
516    /// Configures the maximum number of local resets due to protocol errors made by the remote end.
517    ///
518    /// See the documentation of [`h2::client::Builder::max_local_error_reset_streams`] for more
519    /// details.
520    ///
521    /// The default value is 1024.
522    pub fn max_local_error_reset_streams(&mut self, max: impl Into<Option<usize>>) -> &mut Self {
523        self.h2_builder.max_local_error_reset_streams = max.into();
524        self
525    }
526
527    /// Sets the duration to remember locally reset streams.
528    ///
529    /// When a stream is explicitly reset by either the client or the server,
530    /// the HTTP/2 specification requires that any further frames received for
531    /// that stream must be ignored for "some time".
532    ///
533    /// In order to satisfy the specification, internal state must be maintained
534    /// to implement the behavior. This state grows linearly with the number of
535    /// streams that are locally reset.
536    ///
537    /// The `reset_stream_duration` setting configures the max amount of time
538    /// this state will be maintained in memory. Once the duration elapses, the
539    /// stream state is purged from memory.
540    ///
541    /// Once the stream has been fully purged from memory, any additional frames
542    /// received for that stream will result in a connection level protocol
543    /// error, forcing the connection to terminate.
544    ///
545    /// The default value is determined by the `h2` crate, and is currently
546    /// 1 second.
547    ///
548    /// See the documentation of [`h2::client::Builder::reset_stream_duration`] for more
549    /// details.
550    ///
551    /// [`h2::client::Builder::reset_stream_duration`]: https://docs.rs/h2/client/struct.Builder.html#method.reset_stream_duration
552    pub fn reset_stream_duration(&mut self, dur: Duration) -> &mut Self {
553        self.h2_builder.reset_stream_duration = Some(dur);
554        self
555    }
556
557    /// Constructs a connection with the configured options and IO.
558    /// See [`client::conn`](crate::client::conn) for more.
559    ///
560    /// Note, if [`Connection`] is not `await`-ed, [`SendRequest`] will
561    /// do nothing.
562    ///
563    /// # Errors
564    ///
565    /// Returns an error if the HTTP/2 connection handshake fails.
566    pub fn handshake<T, B>(
567        &self,
568        io: T,
569    ) -> impl Future<Output = crate::Result<(SendRequest<B>, Connection<T, B, Ex>)>>
570    where
571        T: Read + Write + Unpin,
572        B: Body + 'static,
573        B::Data: Send,
574        B::Error: Into<Box<dyn Error + Send + Sync>>,
575        Ex: Http2ClientConnExec<B, T> + Unpin,
576    {
577        let opts = self.clone();
578
579        async move {
580            trace!("client handshake HTTP/2");
581
582            let (tx, rx) = dispatch::channel();
583            let h2 = proto::h2::client::handshake(io, rx, &opts.h2_builder, opts.exec, opts.timer)
584                .await?;
585            Ok((
586                SendRequest {
587                    dispatch: tx.unbound(),
588                },
589                Connection {
590                    inner: (PhantomData, h2),
591                },
592            ))
593        }
594    }
595}
596
597#[cfg(test)]
598mod tests {
599
600    #[tokio::test]
601    #[ignore] // only compilation is checked
602    async fn send_sync_executor_of_non_send_futures() {
603        #[derive(Clone)]
604        struct LocalTokioExecutor;
605
606        impl<F> crate::rt::Executor<F> for LocalTokioExecutor
607        where
608            F: std::future::Future + 'static, // not requiring `Send`
609        {
610            fn execute(&self, fut: F) {
611                // This will spawn into the currently running `LocalSet`.
612                tokio::task::spawn_local(fut);
613            }
614        }
615
616        #[allow(unused)]
617        async fn run(io: impl crate::rt::Read + crate::rt::Write + Unpin + 'static) {
618            let (_sender, conn) = crate::client::conn::http2::handshake::<
619                _,
620                _,
621                http_body_util::Empty<bytes::Bytes>,
622            >(LocalTokioExecutor, io)
623            .await
624            .unwrap();
625
626            tokio::task::spawn_local(async move {
627                conn.await.unwrap();
628            });
629        }
630    }
631
632    #[tokio::test]
633    #[ignore] // only compilation is checked
634    async fn not_send_not_sync_executor_of_not_send_futures() {
635        #[derive(Clone)]
636        struct LocalTokioExecutor {
637            _x: std::marker::PhantomData<std::rc::Rc<()>>,
638        }
639
640        impl<F> crate::rt::Executor<F> for LocalTokioExecutor
641        where
642            F: std::future::Future + 'static, // not requiring `Send`
643        {
644            fn execute(&self, fut: F) {
645                // This will spawn into the currently running `LocalSet`.
646                tokio::task::spawn_local(fut);
647            }
648        }
649
650        #[allow(unused)]
651        async fn run(io: impl crate::rt::Read + crate::rt::Write + Unpin + 'static) {
652            let (_sender, conn) =
653                crate::client::conn::http2::handshake::<_, _, http_body_util::Empty<bytes::Bytes>>(
654                    LocalTokioExecutor {
655                        _x: Default::default(),
656                    },
657                    io,
658                )
659                .await
660                .unwrap();
661
662            tokio::task::spawn_local(async move {
663                conn.await.unwrap();
664            });
665        }
666    }
667
668    #[tokio::test]
669    #[ignore] // only compilation is checked
670    async fn send_not_sync_executor_of_not_send_futures() {
671        #[derive(Clone)]
672        struct LocalTokioExecutor {
673            _x: std::marker::PhantomData<std::cell::Cell<()>>,
674        }
675
676        impl<F> crate::rt::Executor<F> for LocalTokioExecutor
677        where
678            F: std::future::Future + 'static, // not requiring `Send`
679        {
680            fn execute(&self, fut: F) {
681                // This will spawn into the currently running `LocalSet`.
682                tokio::task::spawn_local(fut);
683            }
684        }
685
686        #[allow(unused)]
687        async fn run(io: impl crate::rt::Read + crate::rt::Write + Unpin + 'static) {
688            let (_sender, conn) =
689                crate::client::conn::http2::handshake::<_, _, http_body_util::Empty<bytes::Bytes>>(
690                    LocalTokioExecutor {
691                        _x: Default::default(),
692                    },
693                    io,
694                )
695                .await
696                .unwrap();
697
698            tokio::task::spawn_local(async move {
699                conn.await.unwrap();
700            });
701        }
702    }
703
704    #[tokio::test]
705    #[ignore] // only compilation is checked
706    async fn send_sync_executor_of_send_futures() {
707        #[derive(Clone)]
708        struct TokioExecutor;
709
710        impl<F> crate::rt::Executor<F> for TokioExecutor
711        where
712            F: std::future::Future + 'static + Send,
713            F::Output: Send + 'static,
714        {
715            fn execute(&self, fut: F) {
716                tokio::task::spawn(fut);
717            }
718        }
719
720        #[allow(unused)]
721        async fn run(io: impl crate::rt::Read + crate::rt::Write + Send + Unpin + 'static) {
722            let (_sender, conn) = crate::client::conn::http2::handshake::<
723                _,
724                _,
725                http_body_util::Empty<bytes::Bytes>,
726            >(TokioExecutor, io)
727            .await
728            .unwrap();
729
730            tokio::task::spawn(async move {
731                conn.await.unwrap();
732            });
733        }
734    }
735
736    #[tokio::test]
737    #[ignore] // only compilation is checked
738    async fn send_not_sync_executor_of_send_futures() {
739        #[derive(Clone)]
740        struct TokioExecutor {
741            // !Sync
742            _x: std::marker::PhantomData<std::cell::Cell<()>>,
743        }
744
745        impl<F> crate::rt::Executor<F> for TokioExecutor
746        where
747            F: std::future::Future + 'static + Send,
748            F::Output: Send + 'static,
749        {
750            fn execute(&self, fut: F) {
751                tokio::task::spawn(fut);
752            }
753        }
754
755        #[allow(unused)]
756        async fn run(io: impl crate::rt::Read + crate::rt::Write + Send + Unpin + 'static) {
757            let (_sender, conn) =
758                crate::client::conn::http2::handshake::<_, _, http_body_util::Empty<bytes::Bytes>>(
759                    TokioExecutor {
760                        _x: Default::default(),
761                    },
762                    io,
763                )
764                .await
765                .unwrap();
766
767            tokio::task::spawn_local(async move {
768                // can't use spawn here because when executor is !Send
769                conn.await.unwrap();
770            });
771        }
772    }
773}