use std::path::PathBuf;
use hyper_util::rt::TokioIo;
use tonic::transport::{Certificate, Channel, ClientTlsConfig, Endpoint, Error, Identity, Uri};
use tower::service_fn;
#[derive(Debug, Clone)]
pub struct Tls {
pub ca: PathBuf,
pub cert: PathBuf,
pub key: PathBuf,
}
pub async fn connect_tls(
addr: &str,
tls: &Tls,
) -> Result<Channel, Box<dyn std::error::Error + Send + Sync>> {
connect_tls_pinging(addr, tls, None).await
}
fn pinging(endpoint: Endpoint, every: Option<std::time::Duration>) -> Endpoint {
match every {
Some(every) => endpoint
.http2_keep_alive_interval(every)
.keep_alive_timeout(every)
.keep_alive_while_idle(true)
.connect_timeout(every.max(std::time::Duration::from_secs(1)) * 2),
None => endpoint,
}
}
pub async fn connect_tls_pinging(
addr: &str,
tls: &Tls,
every: Option<std::time::Duration>,
) -> Result<Channel, Box<dyn std::error::Error + Send + Sync>> {
let config = ClientTlsConfig::new()
.ca_certificate(Certificate::from_pem(std::fs::read(&tls.ca)?))
.identity(Identity::from_pem(
std::fs::read(&tls.cert)?,
std::fs::read(&tls.key)?,
));
Ok(pinging(
Endpoint::from_shared(format!("https://{}", tcp_addr(addr)))?.tls_config(config)?,
every,
)
.connect()
.await?)
}
pub async fn connect_https_pinging(
addr: &str,
ca: Option<&std::path::Path>,
identity: Option<(&std::path::Path, &std::path::Path)>,
every: Option<std::time::Duration>,
) -> Result<Channel, Box<dyn std::error::Error + Send + Sync>> {
let mut config = ClientTlsConfig::new().with_webpki_roots();
if let Some(ca) = ca {
config = config.ca_certificate(Certificate::from_pem(std::fs::read(ca)?));
}
if let Some((cert, key)) = identity {
config = config.identity(Identity::from_pem(
std::fs::read(cert)?,
std::fs::read(key)?,
));
}
Ok(pinging(
Endpoint::from_shared(format!("https://{}", tcp_addr(addr)))?.tls_config(config)?,
every,
)
.connect()
.await?)
}
pub async fn connect(addr: &str) -> Result<Channel, Error> {
connect_pinging(addr, None).await
}
pub async fn connect_pinging(
addr: &str,
every: Option<std::time::Duration>,
) -> Result<Channel, Error> {
match unix_path(addr) {
#[cfg(unix)]
Some(path) => {
let path = path.to_owned();
pinging(Endpoint::from_static("http://kernable"), every)
.connect_with_connector(service_fn(move |_: Uri| {
let path = path.clone();
async move {
let stream = tokio::net::UnixStream::connect(path).await?;
Ok::<_, std::io::Error>(TokioIo::new(stream))
}
}))
.await
}
#[cfg(not(unix))]
Some(_) => {
Endpoint::from_shared("unix sockets need Unix")?
.connect()
.await
}
None => {
pinging(
Endpoint::from_shared(format!("http://{}", tcp_addr(addr)))?,
every,
)
.connect()
.await
}
}
}
pub const PAIR_PING: std::time::Duration = std::time::Duration::from_secs(2);
fn sdk_endpoint(endpoint: Endpoint, several: bool) -> Endpoint {
let (every, answer, connect) = if several {
(PAIR_PING, PAIR_PING, PAIR_PING * 2)
} else {
(
std::time::Duration::from_secs(30),
std::time::Duration::from_secs(10),
std::time::Duration::from_secs(10),
)
};
endpoint
.http2_keep_alive_interval(every)
.keep_alive_timeout(answer)
.keep_alive_while_idle(true)
.connect_timeout(connect)
}
pub fn connect_lazy(
addr: &str,
tls: Option<&Tls>,
) -> Result<Channel, Box<dyn std::error::Error + Send + Sync>> {
connect_lazy_among(addr, tls, false)
}
pub fn connect_lazy_among(
addr: &str,
tls: Option<&Tls>,
several: bool,
) -> Result<Channel, Box<dyn std::error::Error + Send + Sync>> {
if let Some(tls) = tls {
let config = ClientTlsConfig::new()
.ca_certificate(Certificate::from_pem(std::fs::read(&tls.ca)?))
.identity(Identity::from_pem(
std::fs::read(&tls.cert)?,
std::fs::read(&tls.key)?,
));
return Ok(sdk_endpoint(
Endpoint::from_shared(format!("https://{}", tcp_addr(addr)))?,
several,
)
.tls_config(config)?
.connect_lazy());
}
match unix_path(addr) {
#[cfg(unix)]
Some(path) => {
let path = path.to_owned();
Ok(
sdk_endpoint(Endpoint::from_static("http://kernable"), several)
.connect_with_connector_lazy(service_fn(move |_: Uri| {
let path = path.clone();
async move {
let stream = tokio::net::UnixStream::connect(path).await?;
Ok::<_, std::io::Error>(TokioIo::new(stream))
}
})),
)
}
#[cfg(not(unix))]
Some(_) => Err("unix sockets need Unix".into()),
None => Ok(sdk_endpoint(
Endpoint::from_shared(format!("http://{}", tcp_addr(addr)))?,
several,
)
.connect_lazy()),
}
}
pub fn tcp_addr(addr: &str) -> &str {
let addr = addr
.strip_prefix("http://")
.or_else(|| addr.strip_prefix("https://"))
.unwrap_or(addr);
addr.strip_suffix('/').unwrap_or(addr)
}
pub fn unix_path(addr: &str) -> Option<&str> {
addr.strip_prefix("unix:")
.map(|p| p.strip_prefix("//").unwrap_or(p))
}