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) => unreachable!("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(_) => unreachable!("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 /// Returns the executor this builder was created with.
318 pub fn executor(&self) -> &Ex {
319 &self.exec
320 }
321
322 /// Provide a timer to execute background HTTP2 tasks.
323 pub fn timer<M>(&mut self, timer: M) -> &mut Builder<Ex>
324 where
325 M: Timer + Send + Sync + 'static,
326 {
327 self.timer = Time::Timer(Arc::new(timer));
328 self
329 }
330
331 /// Sets the [`SETTINGS_INITIAL_WINDOW_SIZE`][spec] option for HTTP2
332 /// stream-level flow control.
333 ///
334 /// Passing `None` will do nothing.
335 ///
336 /// If not set, hyper will use a default.
337 ///
338 /// [spec]: https://httpwg.org/specs/rfc9113.html#SETTINGS_INITIAL_WINDOW_SIZE
339 pub fn initial_stream_window_size(&mut self, sz: impl Into<Option<u32>>) -> &mut Self {
340 if let Some(sz) = sz.into() {
341 self.h2_builder.adaptive_window = false;
342 self.h2_builder.initial_stream_window_size = sz;
343 }
344 self
345 }
346
347 /// Sets the max connection-level flow control for HTTP2.
348 ///
349 /// Passing `None` will do nothing.
350 ///
351 /// If not set, hyper will use a default.
352 pub fn initial_connection_window_size(&mut self, sz: impl Into<Option<u32>>) -> &mut Self {
353 if let Some(sz) = sz.into() {
354 self.h2_builder.adaptive_window = false;
355 self.h2_builder.initial_conn_window_size = sz;
356 }
357 self
358 }
359
360 /// Sets the initial maximum of locally initiated (send) streams.
361 ///
362 /// This value will be overwritten by the value included in the initial
363 /// SETTINGS frame received from the peer as part of a [connection preface].
364 ///
365 /// Passing `None` will do nothing.
366 ///
367 /// If not set, hyper will use a default.
368 ///
369 /// [connection preface]: https://httpwg.org/specs/rfc9113.html#preface
370 pub fn initial_max_send_streams(&mut self, initial: impl Into<Option<usize>>) -> &mut Self {
371 if let Some(initial) = initial.into() {
372 self.h2_builder.initial_max_send_streams = initial;
373 }
374 self
375 }
376
377 /// Sets whether to use an adaptive flow control.
378 ///
379 /// Enabling this will override the limits set in
380 /// `initial_stream_window_size` and
381 /// `initial_connection_window_size`.
382 pub fn adaptive_window(&mut self, enabled: bool) -> &mut Self {
383 use proto::h2::SPEC_WINDOW_SIZE;
384
385 self.h2_builder.adaptive_window = enabled;
386 if enabled {
387 self.h2_builder.initial_conn_window_size = SPEC_WINDOW_SIZE;
388 self.h2_builder.initial_stream_window_size = SPEC_WINDOW_SIZE;
389 }
390 self
391 }
392
393 /// Sets the maximum frame size to use for HTTP2.
394 ///
395 /// Default is currently 16KB, but can change.
396 pub fn max_frame_size(&mut self, sz: impl Into<Option<u32>>) -> &mut Self {
397 self.h2_builder.max_frame_size = sz.into();
398 self
399 }
400
401 /// Sets the max size of received header frames.
402 ///
403 /// Default is currently 16KB, but can change.
404 pub fn max_header_list_size(&mut self, max: u32) -> &mut Self {
405 self.h2_builder.max_header_list_size = max;
406 self
407 }
408
409 /// Sets the header table size.
410 ///
411 /// This setting informs the peer of the maximum size of the header compression
412 /// table used to encode header blocks, in octets. The encoder may select any value
413 /// equal to or less than the header table size specified by the sender.
414 ///
415 /// The default value of crate `h2` is 4,096.
416 pub fn header_table_size(&mut self, size: impl Into<Option<u32>>) -> &mut Self {
417 self.h2_builder.header_table_size = size.into();
418 self
419 }
420
421 /// Sets the maximum number of concurrent streams.
422 ///
423 /// The maximum concurrent streams setting only controls the maximum number
424 /// of streams that can be initiated by the remote peer. In other words,
425 /// when this setting is set to 100, this does not limit the number of
426 /// concurrent streams that can be created by the caller.
427 ///
428 /// It is recommended that this value be no smaller than 100, so as to not
429 /// unnecessarily limit parallelism. However, any value is legal, including
430 /// 0. If `max` is set to 0, then the remote will not be permitted to
431 /// initiate streams.
432 ///
433 /// Note that streams in the reserved state, i.e., push promises that have
434 /// been reserved but the stream has not started, do not count against this
435 /// setting.
436 ///
437 /// Also note that if the remote *does* exceed the value set here, it is not
438 /// a protocol level error. Instead, the `h2` library will immediately reset
439 /// the stream.
440 ///
441 /// See [Section 5.1.2] in the HTTP/2 spec for more details.
442 ///
443 /// [Section 5.1.2]: https://httpwg.org/specs/rfc7540.html#rfc.section.5.1.2
444 pub fn max_concurrent_streams(&mut self, max: impl Into<Option<u32>>) -> &mut Self {
445 self.h2_builder.max_concurrent_streams = max.into();
446 self
447 }
448
449 /// Sets an interval for HTTP2 Ping frames should be sent to keep a
450 /// connection alive.
451 ///
452 /// Pass `None` to disable HTTP2 keep-alive.
453 ///
454 /// Default is currently disabled.
455 pub fn keep_alive_interval(&mut self, interval: impl Into<Option<Duration>>) -> &mut Self {
456 self.h2_builder.keep_alive_interval = interval.into();
457 self
458 }
459
460 /// Sets a timeout for receiving an acknowledgement of the keep-alive ping.
461 ///
462 /// If the ping is not acknowledged within the timeout, the connection will
463 /// be closed. Does nothing if `keep_alive_interval` is disabled.
464 ///
465 /// Default is 20 seconds.
466 pub fn keep_alive_timeout(&mut self, timeout: Duration) -> &mut Self {
467 self.h2_builder.keep_alive_timeout = timeout;
468 self
469 }
470
471 /// Sets whether HTTP2 keep-alive should apply while the connection is idle.
472 ///
473 /// If disabled, keep-alive pings are only sent while there are open
474 /// request/responses streams. If enabled, pings are also sent when no
475 /// streams are active. Does nothing if `keep_alive_interval` is
476 /// disabled.
477 ///
478 /// Default is `false`.
479 pub fn keep_alive_while_idle(&mut self, enabled: bool) -> &mut Self {
480 self.h2_builder.keep_alive_while_idle = enabled;
481 self
482 }
483
484 /// Sets the maximum number of HTTP2 concurrent locally reset streams.
485 ///
486 /// See the documentation of [`h2::client::Builder::max_concurrent_reset_streams`] for more
487 /// details.
488 ///
489 /// The default value is determined by the `h2` crate.
490 ///
491 /// [`h2::client::Builder::max_concurrent_reset_streams`]: https://docs.rs/h2/client/struct.Builder.html#method.max_concurrent_reset_streams
492 pub fn max_concurrent_reset_streams(&mut self, max: usize) -> &mut Self {
493 self.h2_builder.max_concurrent_reset_streams = Some(max);
494 self
495 }
496
497 /// Set the maximum write buffer size for each HTTP/2 stream.
498 ///
499 /// Default is currently 1MB, but may change.
500 ///
501 /// # Panics
502 ///
503 /// The value must be no larger than `u32::MAX`.
504 pub fn max_send_buf_size(&mut self, max: usize) -> &mut Self {
505 assert!(max <= u32::MAX as usize);
506 self.h2_builder.max_send_buffer_size = max;
507 self
508 }
509
510 /// Configures the maximum number of pending reset streams allowed before a GOAWAY will be sent.
511 ///
512 /// This will default to the default value set by the [`h2` crate](https://crates.io/crates/h2).
513 /// As of v0.4.0, it is 20.
514 ///
515 /// See <https://github.com/hyperium/hyper/issues/2877> for more information.
516 pub fn max_pending_accept_reset_streams(&mut self, max: impl Into<Option<usize>>) -> &mut Self {
517 self.h2_builder.max_pending_accept_reset_streams = max.into();
518 self
519 }
520
521 /// Configures the maximum number of local resets due to protocol errors made by the remote end.
522 ///
523 /// See the documentation of [`h2::client::Builder::max_local_error_reset_streams`] for more
524 /// details.
525 ///
526 /// The default value is 1024.
527 pub fn max_local_error_reset_streams(&mut self, max: impl Into<Option<usize>>) -> &mut Self {
528 self.h2_builder.max_local_error_reset_streams = max.into();
529 self
530 }
531
532 /// Sets the duration to remember locally reset streams.
533 ///
534 /// When a stream is explicitly reset by either the client or the server,
535 /// the HTTP/2 specification requires that any further frames received for
536 /// that stream must be ignored for "some time".
537 ///
538 /// In order to satisfy the specification, internal state must be maintained
539 /// to implement the behavior. This state grows linearly with the number of
540 /// streams that are locally reset.
541 ///
542 /// The `reset_stream_duration` setting configures the max amount of time
543 /// this state will be maintained in memory. Once the duration elapses, the
544 /// stream state is purged from memory.
545 ///
546 /// Once the stream has been fully purged from memory, any additional frames
547 /// received for that stream will result in a connection level protocol
548 /// error, forcing the connection to terminate.
549 ///
550 /// The default value is determined by the `h2` crate, and is currently
551 /// 1 second.
552 ///
553 /// See the documentation of [`h2::client::Builder::reset_stream_duration`] for more
554 /// details.
555 ///
556 /// [`h2::client::Builder::reset_stream_duration`]: https://docs.rs/h2/client/struct.Builder.html#method.reset_stream_duration
557 pub fn reset_stream_duration(&mut self, dur: Duration) -> &mut Self {
558 self.h2_builder.reset_stream_duration = Some(dur);
559 self
560 }
561
562 /// Constructs a connection with the configured options and IO.
563 /// See [`client::conn`](crate::client::conn) for more.
564 ///
565 /// Note, if [`Connection`] is not `await`-ed, [`SendRequest`] will
566 /// do nothing.
567 ///
568 /// # Errors
569 ///
570 /// Returns an error if the HTTP/2 connection handshake fails.
571 pub fn handshake<T, B>(
572 &self,
573 io: T,
574 ) -> impl Future<Output = crate::Result<(SendRequest<B>, Connection<T, B, Ex>)>>
575 where
576 T: Read + Write + Unpin,
577 B: Body + 'static,
578 B::Data: Send,
579 B::Error: Into<Box<dyn Error + Send + Sync>>,
580 Ex: Http2ClientConnExec<B, T> + Unpin,
581 {
582 let opts = self.clone();
583
584 async move {
585 trace!("client handshake HTTP/2");
586
587 let (tx, rx) = dispatch::channel();
588 let h2 = proto::h2::client::handshake(io, rx, &opts.h2_builder, opts.exec, opts.timer)
589 .await?;
590 Ok((
591 SendRequest {
592 dispatch: tx.unbound(),
593 },
594 Connection {
595 inner: (PhantomData, h2),
596 },
597 ))
598 }
599 }
600}
601
602#[cfg(test)]
603mod tests {
604
605 #[tokio::test]
606 #[ignore] // only compilation is checked
607 async fn send_sync_executor_of_non_send_futures() {
608 #[derive(Clone)]
609 struct LocalTokioExecutor;
610
611 impl<F> crate::rt::Executor<F> for LocalTokioExecutor
612 where
613 F: std::future::Future + 'static, // not requiring `Send`
614 {
615 fn execute(&self, fut: F) {
616 // This will spawn into the currently running `LocalSet`.
617 tokio::task::spawn_local(fut);
618 }
619 }
620
621 #[allow(unused)]
622 async fn run(io: impl crate::rt::Read + crate::rt::Write + Unpin + 'static) {
623 let (_sender, conn) = crate::client::conn::http2::handshake::<
624 _,
625 _,
626 http_body_util::Empty<bytes::Bytes>,
627 >(LocalTokioExecutor, io)
628 .await
629 .unwrap();
630
631 tokio::task::spawn_local(async move {
632 conn.await.unwrap();
633 });
634 }
635 }
636
637 #[tokio::test]
638 #[ignore] // only compilation is checked
639 async fn not_send_not_sync_executor_of_not_send_futures() {
640 #[derive(Clone)]
641 struct LocalTokioExecutor {
642 _x: std::marker::PhantomData<std::rc::Rc<()>>,
643 }
644
645 impl<F> crate::rt::Executor<F> for LocalTokioExecutor
646 where
647 F: std::future::Future + 'static, // not requiring `Send`
648 {
649 fn execute(&self, fut: F) {
650 // This will spawn into the currently running `LocalSet`.
651 tokio::task::spawn_local(fut);
652 }
653 }
654
655 #[allow(unused)]
656 async fn run(io: impl crate::rt::Read + crate::rt::Write + Unpin + 'static) {
657 let (_sender, conn) =
658 crate::client::conn::http2::handshake::<_, _, http_body_util::Empty<bytes::Bytes>>(
659 LocalTokioExecutor {
660 _x: Default::default(),
661 },
662 io,
663 )
664 .await
665 .unwrap();
666
667 tokio::task::spawn_local(async move {
668 conn.await.unwrap();
669 });
670 }
671 }
672
673 #[tokio::test]
674 #[ignore] // only compilation is checked
675 async fn send_not_sync_executor_of_not_send_futures() {
676 #[derive(Clone)]
677 struct LocalTokioExecutor {
678 _x: std::marker::PhantomData<std::cell::Cell<()>>,
679 }
680
681 impl<F> crate::rt::Executor<F> for LocalTokioExecutor
682 where
683 F: std::future::Future + 'static, // not requiring `Send`
684 {
685 fn execute(&self, fut: F) {
686 // This will spawn into the currently running `LocalSet`.
687 tokio::task::spawn_local(fut);
688 }
689 }
690
691 #[allow(unused)]
692 async fn run(io: impl crate::rt::Read + crate::rt::Write + Unpin + 'static) {
693 let (_sender, conn) =
694 crate::client::conn::http2::handshake::<_, _, http_body_util::Empty<bytes::Bytes>>(
695 LocalTokioExecutor {
696 _x: Default::default(),
697 },
698 io,
699 )
700 .await
701 .unwrap();
702
703 tokio::task::spawn_local(async move {
704 conn.await.unwrap();
705 });
706 }
707 }
708
709 #[tokio::test]
710 #[ignore] // only compilation is checked
711 async fn send_sync_executor_of_send_futures() {
712 #[derive(Clone)]
713 struct TokioExecutor;
714
715 impl<F> crate::rt::Executor<F> for TokioExecutor
716 where
717 F: std::future::Future + 'static + Send,
718 F::Output: Send + 'static,
719 {
720 fn execute(&self, fut: F) {
721 tokio::task::spawn(fut);
722 }
723 }
724
725 #[allow(unused)]
726 async fn run(io: impl crate::rt::Read + crate::rt::Write + Send + Unpin + 'static) {
727 let (_sender, conn) = crate::client::conn::http2::handshake::<
728 _,
729 _,
730 http_body_util::Empty<bytes::Bytes>,
731 >(TokioExecutor, io)
732 .await
733 .unwrap();
734
735 tokio::task::spawn(async move {
736 conn.await.unwrap();
737 });
738 }
739 }
740
741 #[tokio::test]
742 #[ignore] // only compilation is checked
743 async fn send_not_sync_executor_of_send_futures() {
744 #[derive(Clone)]
745 struct TokioExecutor {
746 // !Sync
747 _x: std::marker::PhantomData<std::cell::Cell<()>>,
748 }
749
750 impl<F> crate::rt::Executor<F> for TokioExecutor
751 where
752 F: std::future::Future + 'static + Send,
753 F::Output: Send + 'static,
754 {
755 fn execute(&self, fut: F) {
756 tokio::task::spawn(fut);
757 }
758 }
759
760 #[allow(unused)]
761 async fn run(io: impl crate::rt::Read + crate::rt::Write + Send + Unpin + 'static) {
762 let (_sender, conn) =
763 crate::client::conn::http2::handshake::<_, _, http_body_util::Empty<bytes::Bytes>>(
764 TokioExecutor {
765 _x: Default::default(),
766 },
767 io,
768 )
769 .await
770 .unwrap();
771
772 tokio::task::spawn_local(async move {
773 // can't use spawn here because when executor is !Send
774 conn.await.unwrap();
775 });
776 }
777 }
778}