tonic/transport/channel/service/
connector.rs

1use super::BoxedIo;
2#[cfg(feature = "tls")]
3use super::TlsConnector;
4use crate::transport::channel::BoxFuture;
5use crate::ConnectError;
6use http::Uri;
7#[cfg(feature = "tls")]
8use std::fmt;
9use std::task::{Context, Poll};
10
11use hyper::rt;
12
13#[cfg(feature = "tls")]
14use hyper_util::rt::TokioIo;
15use tower_service::Service;
16
17pub(crate) struct Connector<C> {
18    inner: C,
19    #[cfg(feature = "tls")]
20    tls: Option<TlsConnector>,
21}
22
23impl<C> Connector<C> {
24    pub(crate) fn new(inner: C, #[cfg(feature = "tls")] tls: Option<TlsConnector>) -> Self {
25        Self {
26            inner,
27            #[cfg(feature = "tls")]
28            tls,
29        }
30    }
31}
32
33impl<C> Service<Uri> for Connector<C>
34where
35    C: Service<Uri>,
36    C::Response: rt::Read + rt::Write + Unpin + Send + 'static,
37    C::Future: Send + 'static,
38    crate::Error: From<C::Error> + Send + 'static,
39{
40    type Response = BoxedIo;
41    type Error = ConnectError;
42    type Future = BoxFuture<'static, Result<Self::Response, Self::Error>>;
43
44    fn poll_ready(&mut self, cx: &mut Context<'_>) -> Poll<Result<(), Self::Error>> {
45        self.inner
46            .poll_ready(cx)
47            .map_err(|err| ConnectError(From::from(err)))
48    }
49
50    fn call(&mut self, uri: Uri) -> Self::Future {
51        #[cfg(feature = "tls")]
52        let tls = self.tls.clone();
53
54        #[cfg(feature = "tls")]
55        let is_https = uri.scheme_str() == Some("https");
56        let connect = self.inner.call(uri);
57
58        Box::pin(async move {
59            async {
60                let io = connect.await?;
61
62                #[cfg(feature = "tls")]
63                if is_https {
64                    return if let Some(tls) = tls {
65                        let io = tls.connect(TokioIo::new(io)).await?;
66                        Ok(io)
67                    } else {
68                        Err(HttpsUriWithoutTlsSupport(()).into())
69                    };
70                }
71
72                Ok::<_, crate::Error>(BoxedIo::new(io))
73            }
74            .await
75            .map_err(ConnectError)
76        })
77    }
78}
79
80/// Error returned when trying to connect to an HTTPS endpoint without TLS enabled.
81#[cfg(feature = "tls")]
82#[derive(Debug)]
83pub(crate) struct HttpsUriWithoutTlsSupport(());
84
85#[cfg(feature = "tls")]
86impl fmt::Display for HttpsUriWithoutTlsSupport {
87    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
88        write!(f, "Connecting to HTTPS without TLS enabled")
89    }
90}
91
92// std::error::Error only requires a type to impl Debug and Display
93#[cfg(feature = "tls")]
94impl std::error::Error for HttpsUriWithoutTlsSupport {}