Skip to content

Commit

Permalink
feat(build): add constructor from_arc for gRPC servers (#875)
Browse files Browse the repository at this point in the history
  • Loading branch information
athre0z authored and djc committed Jan 13, 2022
1 parent 65eceb1 commit 18a4fef
Show file tree
Hide file tree
Showing 2 changed files with 28 additions and 1 deletion.
5 changes: 4 additions & 1 deletion tonic-build/src/server.rs
Expand Up @@ -93,7 +93,10 @@ pub fn generate<T: Service>(

impl<T: #server_trait> #server_service<T> {
pub fn new(inner: T) -> Self {
let inner = Arc::new(inner);
Self::from_arc(Arc::new(inner))
}

pub fn from_arc(inner: Arc<T>) -> Self {
let inner = _Inner(inner);
Self {
inner,
Expand Down
24 changes: 24 additions & 0 deletions tonic/src/transport/service/connector.rs
Expand Up @@ -5,6 +5,7 @@ use super::tls::TlsConnector;
use http::Uri;
#[cfg(feature = "tls-roots-common")]
use std::convert::TryInto;
use std::fmt;
use std::task::{Context, Poll};
use tower::make::MakeConnection;
use tower_service::Service;
Expand Down Expand Up @@ -78,20 +79,43 @@ where
#[cfg(feature = "tls-roots-common")]
let tls = self.tls_or_default(uri.scheme_str(), uri.host());

let is_https = uri.scheme_str() == Some("https");
let connect = self.inner.make_connection(uri);

Box::pin(async move {
#[cfg(not(feature = "tls"))]
{
if is_https {
return Err(NoTlsSupport(()).into());
}
}

let io = connect.await?;

#[cfg(feature = "tls")]
{
if let Some(tls) = tls {
let conn = tls.connect(io).await?;
return Ok(BoxedIo::new(conn));
} else if is_https {
return Err(NoTlsSupport(()).into());
}
}

Ok(BoxedIo::new(io))
})
}
}

/// Error returned when trying to connect to an HTTPS endpoint without TLS enabled.
#[derive(Debug)]
pub(crate) struct NoTlsSupport(());

impl fmt::Display for NoTlsSupport {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
write!(f, "Connecting to HTTPS without TLS enabled")
}
}

// std::error::Error only requires a type to impl Debug and Display
impl std::error::Error for NoTlsSupport {}

0 comments on commit 18a4fef

Please sign in to comment.