1use hyper_util::rt::TokioIo;
9use rustls::pki_types::ServerName;
10use tokio::net::TcpStream;
11use tokio_rustls::TlsConnector;
12use tonic::transport::{Channel, Endpoint, Uri};
13
14use crate::reload::Tls;
15
16#[cfg(test)]
17mod tests;
18
19const HTTPS_PORT: u16 = 443;
21
22pub async fn channel(url: &str, tls: Option<&Tls>) -> Result<Channel, String> {
28 let endpoint = Endpoint::from_shared(url.to_owned()).map_err(|e| e.to_string())?;
29 let Some(tls) = tls else {
30 return endpoint.connect().await.map_err(|e| error_text(&e));
31 };
32 let tls = tls.clone();
33 let connector = tower::service_fn(move |uri: Uri| {
34 let tls = tls.clone();
35 async move {
36 let host = uri.host().unwrap_or_default();
38 let host = host
39 .trim_start_matches('[')
40 .trim_end_matches(']')
41 .to_owned();
42 let port = uri.port_u16().unwrap_or(HTTPS_PORT);
43 let name = ServerName::try_from(host.clone())
44 .map_err(|e| std::io::Error::new(std::io::ErrorKind::InvalidInput, e))?;
45 let tcp = TcpStream::connect((host, port)).await?;
46 let _ = tcp.set_nodelay(true);
47 let handshake = TlsConnector::from(tls.grpc_client()).connect(name, tcp);
48 let stream = tokio::time::timeout(tls.handshake_timeout(), handshake)
49 .await
50 .map_err(|_| {
51 std::io::Error::new(
52 std::io::ErrorKind::TimedOut,
53 "the master didn't complete the TLS handshake",
54 )
55 })??;
56 Ok::<_, std::io::Error>(TokioIo::new(stream))
57 }
58 });
59 endpoint
60 .connect_with_connector(connector)
61 .await
62 .map_err(|e| error_text(&e))
63}
64
65#[must_use]
67pub fn error_text(error: &dyn std::error::Error) -> String {
68 let mut text = error.to_string();
69 let mut source = error.source();
70 while let Some(cause) = source {
71 text.push_str(": ");
72 text.push_str(&cause.to_string());
73 source = cause.source();
74 }
75 text
76}