use hyper_util::rt::TokioIo;
use tokio::net::UnixStream;
use tonic::transport::{Channel, Endpoint};
fn url_wants_wait_connect(url: &url::Url) -> bool {
url.query_pairs()
.filter(|(k, v)| k == "wait-connect" && v == "1")
.count()
> 0
}
pub async fn channel_from_url(url: &url::Url) -> Result<Channel, self::Error> {
match url.scheme() {
"grpc+unix" => {
if url.host_str().is_some() {
return Err(Error::HostSetForUnixSocket());
}
let connector = tower::service_fn({
let url = url.clone();
move |_: tonic::transport::Uri| {
let unix = UnixStream::connect(url.path().to_string().clone());
async move { Ok::<_, std::io::Error>(TokioIo::new(unix.await?)) }
}
});
let endpoint = Endpoint::from_static("http://[::]:50051");
if url_wants_wait_connect(url) {
Ok(endpoint.connect_with_connector(connector).await?)
} else {
Ok(endpoint.connect_with_connector_lazy(connector))
}
}
_ => {
if !url.path().is_empty() {
return Err(Error::PathMayNotBeSet());
}
let unprefixed_url_str = match url.to_string().strip_prefix("grpc+") {
None => return Err(Error::MissingGRPCPrefix()),
Some(url_str) => url_str.to_owned(),
};
let endpoint = Endpoint::try_from(unprefixed_url_str)?;
if url_wants_wait_connect(url) {
Ok(endpoint.connect().await?)
} else {
Ok(endpoint.connect_lazy())
}
}
}
}
#[derive(Debug, thiserror::Error)]
pub enum Error {
#[error("grpc+ prefix is missing from URL")]
MissingGRPCPrefix(),
#[error("host may not be set for unix domain sockets")]
HostSetForUnixSocket(),
#[error("path may not be set")]
PathMayNotBeSet(),
#[error("transport error: {0}")]
TransportError(tonic::transport::Error),
}
impl From<tonic::transport::Error> for Error {
fn from(value: tonic::transport::Error) -> Self {
Self::TransportError(value)
}
}
#[cfg(test)]
mod tests {
use super::channel_from_url;
use rstest::rstest;
use url::Url;
#[rstest]
#[case::valid_unix_socket("grpc+unix:///path/to/somewhere", true)]
#[case::valid_unix_socket_wait_connect_0("grpc+unix:///path/to/somewhere?wait-connect=0", true)]
#[case::valid_unix_socket_wait_connect_1(
"grpc+unix:///path/to/somewhere?wait-connect=1",
false
)]
#[case::invalid_unix_socket_and_host("grpc+unix://host.example/path/to/somewhere", false)]
#[case::valid_ipv6_localhost_port_12345("grpc+http://[::1]:12345", true)]
#[case::valid_http_host_without_port("grpc+http://localhost", true)]
#[case::valid_https_host_without_port("grpc+https://localhost", true)]
#[case::invalid_host_and_path("grpc+http://localhost/some-path", false)]
#[case::valid_host_wait_connect_0("grpc+http://localhost?wait-connect=0", true)]
#[case::valid_host_wait_connect_1_fails("grpc+http://nonexist.invalid?wait-connect=1", false)]
#[tokio::test]
async fn test_from_addr_tokio(#[case] uri_str: &str, #[case] is_ok: bool) {
let url = Url::parse(uri_str).expect("must parse");
assert_eq!(channel_from_url(&url).await.is_ok(), is_ok)
}
}