1use 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_util::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
23pub 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#[must_use = "futures do nothing unless polled"]
43pub struct Connection<T, B, E>
44where
45 T: Read + Write + Unpin,
46 B: Body + 'static,
47 E: Http2ClientConnExec<B, T> + Unpin,
48 B::Error: Into<Box<dyn Error + Send + Sync>>,
49{
50 inner: (PhantomData<T>, proto::h2::ClientTask<B, E, T>),
51}
52
53#[derive(Clone, Debug)]
60pub struct Builder<Ex> {
61 pub(super) exec: Ex,
62 pub(super) timer: Time,
63 h2_builder: proto::h2::client::Config,
64}
65
66pub async fn handshake<E, T, B>(
71 exec: E,
72 io: T,
73) -> crate::Result<(SendRequest<B>, Connection<T, B, E>)>
74where
75 T: Read + Write + Unpin,
76 B: Body + 'static,
77 B::Data: Send,
78 B::Error: Into<Box<dyn Error + Send + Sync>>,
79 E: Http2ClientConnExec<B, T> + Unpin + Clone,
80{
81 Builder::new(exec).handshake(io).await
82}
83
84impl<B> SendRequest<B> {
87 pub fn poll_ready(&mut self, _cx: &mut Context<'_>) -> Poll<crate::Result<()>> {
91 if self.is_closed() {
92 Poll::Ready(Err(crate::Error::new_closed()))
93 } else {
94 Poll::Ready(Ok(()))
95 }
96 }
97
98 pub async fn ready(&mut self) -> crate::Result<()> {
102 futures_util::future::poll_fn(|cx| self.poll_ready(cx)).await
103 }
104
105 pub fn is_ready(&self) -> bool {
113 self.dispatch.is_ready()
114 }
115
116 pub fn is_closed(&self) -> bool {
118 self.dispatch.is_closed()
119 }
120}
121
122impl<B> SendRequest<B>
123where
124 B: Body + 'static,
125{
126 pub fn send_request(
135 &mut self,
136 req: Request<B>,
137 ) -> impl Future<Output = crate::Result<Response<IncomingBody>>> {
138 let sent = self.dispatch.send(req);
139
140 async move {
141 match sent {
142 Ok(rx) => match rx.await {
143 Ok(Ok(resp)) => Ok(resp),
144 Ok(Err(err)) => Err(err),
145 Err(_canceled) => panic!("dispatch dropped without returning error"),
147 },
148 Err(_req) => {
149 debug!("connection was not ready");
150
151 Err(crate::Error::new_canceled().with("connection was not ready"))
152 }
153 }
154 }
155 }
156
157 pub fn try_send_request(
166 &mut self,
167 req: Request<B>,
168 ) -> impl Future<Output = Result<Response<IncomingBody>, TrySendError<Request<B>>>> {
169 let sent = self.dispatch.try_send(req);
170 async move {
171 match sent {
172 Ok(rx) => match rx.await {
173 Ok(Ok(res)) => Ok(res),
174 Ok(Err(err)) => Err(err),
175 Err(_) => panic!("dispatch dropped without returning error"),
177 },
178 Err(req) => {
179 debug!("connection was not ready");
180 let error = crate::Error::new_canceled().with("connection was not ready");
181 Err(TrySendError {
182 error,
183 message: Some(req),
184 })
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
197impl<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 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> + 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
253impl<Ex> Builder<Ex>
256where
257 Ex: Clone,
258{
259 #[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 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 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 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 pub fn initial_max_send_streams(&mut self, initial: impl Into<Option<usize>>) -> &mut Self {
318 if let Some(initial) = initial.into() {
319 self.h2_builder.initial_max_send_streams = initial;
320 }
321 self
322 }
323
324 pub fn adaptive_window(&mut self, enabled: bool) -> &mut Self {
330 use proto::h2::SPEC_WINDOW_SIZE;
331
332 self.h2_builder.adaptive_window = enabled;
333 if enabled {
334 self.h2_builder.initial_conn_window_size = SPEC_WINDOW_SIZE;
335 self.h2_builder.initial_stream_window_size = SPEC_WINDOW_SIZE;
336 }
337 self
338 }
339
340 pub fn max_frame_size(&mut self, sz: impl Into<Option<u32>>) -> &mut Self {
344 self.h2_builder.max_frame_size = sz.into();
345 self
346 }
347
348 pub fn max_header_list_size(&mut self, max: u32) -> &mut Self {
352 self.h2_builder.max_header_list_size = max;
353 self
354 }
355
356 pub fn header_table_size(&mut self, size: impl Into<Option<u32>>) -> &mut Self {
364 self.h2_builder.header_table_size = size.into();
365 self
366 }
367
368 pub fn max_concurrent_streams(&mut self, max: impl Into<Option<u32>>) -> &mut Self {
392 self.h2_builder.max_concurrent_streams = max.into();
393 self
394 }
395
396 pub fn keep_alive_interval(&mut self, interval: impl Into<Option<Duration>>) -> &mut Self {
403 self.h2_builder.keep_alive_interval = interval.into();
404 self
405 }
406
407 pub fn keep_alive_timeout(&mut self, timeout: Duration) -> &mut Self {
414 self.h2_builder.keep_alive_timeout = timeout;
415 self
416 }
417
418 pub fn keep_alive_while_idle(&mut self, enabled: bool) -> &mut Self {
427 self.h2_builder.keep_alive_while_idle = enabled;
428 self
429 }
430
431 pub fn max_concurrent_reset_streams(&mut self, max: usize) -> &mut Self {
440 self.h2_builder.max_concurrent_reset_streams = Some(max);
441 self
442 }
443
444 pub fn max_send_buf_size(&mut self, max: usize) -> &mut Self {
452 assert!(max <= u32::MAX as usize);
453 self.h2_builder.max_send_buffer_size = max;
454 self
455 }
456
457 pub fn max_pending_accept_reset_streams(&mut self, max: impl Into<Option<usize>>) -> &mut Self {
464 self.h2_builder.max_pending_accept_reset_streams = max.into();
465 self
466 }
467
468 pub fn enable_push(&mut self, enabled: bool) -> &mut Self {
480 self.h2_builder.enable_push = enabled;
481 self
482 }
483
484 pub fn headers_frame_pseudo_order(
490 &mut self,
491 order: impl Into<Option<&'static [crate::ext::PseudoType; 4]>>,
492 ) -> &mut Self {
493 self.h2_builder.headers_frame_pseudo_order = order.into();
494 self
495 }
496
497 pub fn headers_frame_priority(
499 &mut self,
500 priority: impl Into<Option<crate::ext::FrameStreamDependency>>,
501 ) -> &mut Self {
502 self.h2_builder.headers_frame_priority = priority.into();
503 self
504 }
505
506 pub fn virtual_streams_priorities(
508 &mut self,
509 priorities: impl Into<Option<&'static [crate::ext::FramePriority]>>,
510 ) -> &mut Self {
511 self.h2_builder.virtual_streams_priorities = priorities.into();
512 self
513 }
514
515 pub fn handshake<T, B>(
521 &self,
522 io: T,
523 ) -> impl Future<Output = crate::Result<(SendRequest<B>, Connection<T, B, Ex>)>>
524 where
525 T: Read + Write + Unpin,
526 B: Body + 'static,
527 B::Data: Send,
528 B::Error: Into<Box<dyn Error + Send + Sync>>,
529 Ex: Http2ClientConnExec<B, T> + Unpin,
530 {
531 let opts = self.clone();
532
533 async move {
534 trace!("client handshake HTTP/2");
535
536 let (tx, rx) = dispatch::channel();
537 let h2 = proto::h2::client::handshake(io, rx, &opts.h2_builder, opts.exec, opts.timer)
538 .await?;
539 Ok((
540 SendRequest {
541 dispatch: tx.unbound(),
542 },
543 Connection {
544 inner: (PhantomData, h2),
545 },
546 ))
547 }
548 }
549}
550
551#[cfg(test)]
552mod tests {
553
554 #[tokio::test]
555 #[ignore] async fn send_sync_executor_of_non_send_futures() {
557 #[derive(Clone)]
558 struct LocalTokioExecutor;
559
560 impl<F> crate::rt::Executor<F> for LocalTokioExecutor
561 where
562 F: std::future::Future + 'static, {
564 fn execute(&self, fut: F) {
565 tokio::task::spawn_local(fut);
567 }
568 }
569
570 #[allow(unused)]
571 async fn run(io: impl crate::rt::Read + crate::rt::Write + Unpin + 'static) {
572 let (_sender, conn) = crate::client::conn::http2::handshake::<
573 _,
574 _,
575 http_body_util::Empty<bytes::Bytes>,
576 >(LocalTokioExecutor, io)
577 .await
578 .unwrap();
579
580 tokio::task::spawn_local(async move {
581 conn.await.unwrap();
582 });
583 }
584 }
585
586 #[tokio::test]
587 #[ignore] async fn not_send_not_sync_executor_of_not_send_futures() {
589 #[derive(Clone)]
590 struct LocalTokioExecutor {
591 _x: std::marker::PhantomData<std::rc::Rc<()>>,
592 }
593
594 impl<F> crate::rt::Executor<F> for LocalTokioExecutor
595 where
596 F: std::future::Future + 'static, {
598 fn execute(&self, fut: F) {
599 tokio::task::spawn_local(fut);
601 }
602 }
603
604 #[allow(unused)]
605 async fn run(io: impl crate::rt::Read + crate::rt::Write + Unpin + 'static) {
606 let (_sender, conn) =
607 crate::client::conn::http2::handshake::<_, _, http_body_util::Empty<bytes::Bytes>>(
608 LocalTokioExecutor {
609 _x: Default::default(),
610 },
611 io,
612 )
613 .await
614 .unwrap();
615
616 tokio::task::spawn_local(async move {
617 conn.await.unwrap();
618 });
619 }
620 }
621
622 #[tokio::test]
623 #[ignore] async fn send_not_sync_executor_of_not_send_futures() {
625 #[derive(Clone)]
626 struct LocalTokioExecutor {
627 _x: std::marker::PhantomData<std::cell::Cell<()>>,
628 }
629
630 impl<F> crate::rt::Executor<F> for LocalTokioExecutor
631 where
632 F: std::future::Future + 'static, {
634 fn execute(&self, fut: F) {
635 tokio::task::spawn_local(fut);
637 }
638 }
639
640 #[allow(unused)]
641 async fn run(io: impl crate::rt::Read + crate::rt::Write + Unpin + 'static) {
642 let (_sender, conn) =
643 crate::client::conn::http2::handshake::<_, _, http_body_util::Empty<bytes::Bytes>>(
644 LocalTokioExecutor {
645 _x: Default::default(),
646 },
647 io,
648 )
649 .await
650 .unwrap();
651
652 tokio::task::spawn_local(async move {
653 conn.await.unwrap();
654 });
655 }
656 }
657
658 #[tokio::test]
659 #[ignore] async fn send_sync_executor_of_send_futures() {
661 #[derive(Clone)]
662 struct TokioExecutor;
663
664 impl<F> crate::rt::Executor<F> for TokioExecutor
665 where
666 F: std::future::Future + 'static + Send,
667 F::Output: Send + 'static,
668 {
669 fn execute(&self, fut: F) {
670 tokio::task::spawn(fut);
671 }
672 }
673
674 #[allow(unused)]
675 async fn run(io: impl crate::rt::Read + crate::rt::Write + Send + Unpin + 'static) {
676 let (_sender, conn) = crate::client::conn::http2::handshake::<
677 _,
678 _,
679 http_body_util::Empty<bytes::Bytes>,
680 >(TokioExecutor, io)
681 .await
682 .unwrap();
683
684 tokio::task::spawn(async move {
685 conn.await.unwrap();
686 });
687 }
688 }
689
690 #[tokio::test]
691 #[ignore] async fn not_send_not_sync_executor_of_send_futures() {
693 #[derive(Clone)]
694 struct TokioExecutor {
695 _x: std::marker::PhantomData<std::rc::Rc<()>>,
697 }
698
699 impl<F> crate::rt::Executor<F> for TokioExecutor
700 where
701 F: std::future::Future + 'static + Send,
702 F::Output: Send + 'static,
703 {
704 fn execute(&self, fut: F) {
705 tokio::task::spawn(fut);
706 }
707 }
708
709 #[allow(unused)]
710 async fn run(io: impl crate::rt::Read + crate::rt::Write + Send + Unpin + 'static) {
711 let (_sender, conn) =
712 crate::client::conn::http2::handshake::<_, _, http_body_util::Empty<bytes::Bytes>>(
713 TokioExecutor {
714 _x: Default::default(),
715 },
716 io,
717 )
718 .await
719 .unwrap();
720
721 tokio::task::spawn_local(async move {
722 conn.await.unwrap();
724 });
725 }
726 }
727
728 #[tokio::test]
729 #[ignore] async fn send_not_sync_executor_of_send_futures() {
731 #[derive(Clone)]
732 struct TokioExecutor {
733 _x: std::marker::PhantomData<std::cell::Cell<()>>,
735 }
736
737 impl<F> crate::rt::Executor<F> for TokioExecutor
738 where
739 F: std::future::Future + 'static + Send,
740 F::Output: Send + 'static,
741 {
742 fn execute(&self, fut: F) {
743 tokio::task::spawn(fut);
744 }
745 }
746
747 #[allow(unused)]
748 async fn run(io: impl crate::rt::Read + crate::rt::Write + Send + Unpin + 'static) {
749 let (_sender, conn) =
750 crate::client::conn::http2::handshake::<_, _, http_body_util::Empty<bytes::Bytes>>(
751 TokioExecutor {
752 _x: Default::default(),
753 },
754 io,
755 )
756 .await
757 .unwrap();
758
759 tokio::task::spawn_local(async move {
760 conn.await.unwrap();
762 });
763 }
764 }
765}