fix(transport): Update builders to move self (#132)

This commit is contained in:
Juan Alvarez
2019-11-11 15:27:40 +01:00
committed by Lucio Franco
parent 4490812ab4
commit 85ef18f8b7
9 changed files with 144 additions and 112 deletions
+2 -3
View File
@@ -29,14 +29,13 @@ async fn main() -> Result<(), Box<dyn std::error::Error>> {
let tls_config = ClientTlsConfig::with_rustls() let tls_config = ClientTlsConfig::with_rustls()
.ca_certificate(Certificate::from_pem(certs.as_slice())) .ca_certificate(Certificate::from_pem(certs.as_slice()))
.domain_name("pubsub.googleapis.com") .domain_name("pubsub.googleapis.com");
.clone();
let channel = Channel::from_static(ENDPOINT) let channel = Channel::from_static(ENDPOINT)
.intercept_headers(move |headers| { .intercept_headers(move |headers| {
headers.insert("authorization", header_value.clone()); headers.insert("authorization", header_value.clone());
}) })
.tls_config(&tls_config) .tls_config(tls_config)
.connect() .connect()
.await?; .await?;
+2 -3
View File
@@ -12,11 +12,10 @@ async fn main() -> Result<(), Box<dyn std::error::Error>> {
let tls = ClientTlsConfig::with_rustls() let tls = ClientTlsConfig::with_rustls()
.ca_certificate(ca) .ca_certificate(ca)
.domain_name("example.com") .domain_name("example.com");
.clone();
let channel = Channel::from_static("http://[::1]:50051") let channel = Channel::from_static("http://[::1]:50051")
.tls_config(&tls) .tls_config(tls)
.connect() .connect()
.await?; .await?;
-1
View File
@@ -60,7 +60,6 @@ async fn main() -> Result<(), Box<dyn std::error::Error>> {
Server::builder() Server::builder()
.tls_config(ServerTlsConfig::with_rustls().identity(identity)) .tls_config(ServerTlsConfig::with_rustls().identity(identity))
.clone()
.add_service(pb::server::EchoServer::new(server)) .add_service(pb::server::EchoServer::new(server))
.serve(addr) .serve(addr)
.await?; .await?;
+2 -3
View File
@@ -16,11 +16,10 @@ async fn main() -> Result<(), Box<dyn std::error::Error>> {
let tls = ClientTlsConfig::with_rustls() let tls = ClientTlsConfig::with_rustls()
.domain_name("localhost") .domain_name("localhost")
.ca_certificate(server_root_ca_cert) .ca_certificate(server_root_ca_cert)
.identity(client_identity) .identity(client_identity);
.clone();
let channel = Channel::from_static("http://[::1]:50051") let channel = Channel::from_static("http://[::1]:50051")
.tls_config(&tls) .tls_config(tls)
.connect() .connect()
.await?; .await?;
+2 -3
View File
@@ -39,11 +39,10 @@ async fn main() -> Result<(), Box<dyn std::error::Error>> {
let tls = ServerTlsConfig::with_rustls() let tls = ServerTlsConfig::with_rustls()
.identity(server_identity) .identity(server_identity)
.client_ca_root(client_ca_cert) .client_ca_root(client_ca_cert);
.clone();
Server::builder() Server::builder()
.tls_config(&tls) .tls_config(tls)
.add_service(pb::server::EchoServer::new(server)) .add_service(pb::server::EchoServer::new(server))
.serve(addr) .serve(addr)
.await?; .await?;
+4 -5
View File
@@ -30,20 +30,19 @@ async fn main() -> Result<(), Box<dyn std::error::Error>> {
#[allow(unused_mut)] #[allow(unused_mut)]
let mut endpoint = Endpoint::from_static("http://localhost:10000") let mut endpoint = Endpoint::from_static("http://localhost:10000")
.timeout(Duration::from_secs(5)) .timeout(Duration::from_secs(5))
.concurrency_limit(30) .concurrency_limit(30);
.clone();
if matches.use_tls { if matches.use_tls {
#[cfg(not(any(feature = "tls_rustls", feature = "tls_openssl")))] #[cfg(not(any(feature = "tls_rustls", feature = "tls_openssl")))]
{ {
panic!("No TLS libary feature selected"); panic!("No TLS library feature selected");
} }
#[cfg(feature = "tls_rustls")] #[cfg(feature = "tls_rustls")]
{ {
let pem = tokio::fs::read("tonic-interop/data/ca.pem").await?; let pem = tokio::fs::read("tonic-interop/data/ca.pem").await?;
let ca = Certificate::from_pem(pem); let ca = Certificate::from_pem(pem);
endpoint.tls_config( endpoint = endpoint.tls_config(
ClientTlsConfig::with_rustls() ClientTlsConfig::with_rustls()
.ca_certificate(ca) .ca_certificate(ca)
.domain_name("foo.test.google.fr"), .domain_name("foo.test.google.fr"),
@@ -54,7 +53,7 @@ async fn main() -> Result<(), Box<dyn std::error::Error>> {
{ {
let pem = tokio::fs::read("tonic-interop/data/ca.pem").await?; let pem = tokio::fs::read("tonic-interop/data/ca.pem").await?;
let ca = Certificate::from_pem(pem); let ca = Certificate::from_pem(pem);
endpoint.tls_config( endpoint = endpoint.tls_config(
ClientTlsConfig::with_openssl() ClientTlsConfig::with_openssl()
.ca_certificate(ca) .ca_certificate(ca)
.domain_name("foo.test.google.fr"), .domain_name("foo.test.google.fr"),
+26 -28
View File
@@ -21,34 +21,7 @@ async fn main() -> std::result::Result<(), Box<dyn std::error::Error>> {
let addr = "127.0.0.1:10000".parse().unwrap(); let addr = "127.0.0.1:10000".parse().unwrap();
let mut builder = Server::builder(); let mut builder = Server::builder().interceptor_fn(|svc, req| {
if matches.use_tls {
#[cfg(not(any(feature = "tls_rustls", feature = "tls_openssl")))]
{
panic!("No TLS libary feature selected");
}
#[cfg(feature = "tls_rustls")]
{
let cert = tokio::fs::read("tonic-interop/data/server1.pem").await?;
let key = tokio::fs::read("tonic-interop/data/server1.key").await?;
let identity = Identity::from_pem(cert, key);
builder.tls_config(ServerTlsConfig::with_rustls().identity(identity));
}
#[cfg(feature = "tls_openssl")]
{
let cert = tokio::fs::read("tonic-interop/data/server1.pem").await?;
let key = tokio::fs::read("tonic-interop/data/server1.key").await?;
let identity = Identity::from_pem(cert, key);
builder.tls_config(ServerTlsConfig::with_openssl().identity(identity));
}
}
builder.interceptor_fn(|svc, req| {
let echo_header = req let echo_header = req
.headers() .headers()
.get("x-grpc-test-echo-initial") .get("x-grpc-test-echo-initial")
@@ -76,6 +49,31 @@ async fn main() -> std::result::Result<(), Box<dyn std::error::Error>> {
} }
}); });
if matches.use_tls {
#[cfg(not(any(feature = "tls_rustls", feature = "tls_openssl")))]
{
panic!("No TLS library feature selected");
}
#[cfg(feature = "tls_rustls")]
{
let cert = tokio::fs::read("tonic-interop/data/server1.pem").await?;
let key = tokio::fs::read("tonic-interop/data/server1.key").await?;
let identity = Identity::from_pem(cert, key);
builder = builder.tls_config(ServerTlsConfig::with_rustls().identity(identity));
}
#[cfg(feature = "tls_openssl")]
{
let cert = tokio::fs::read("tonic-interop/data/server1.pem").await?;
let key = tokio::fs::read("tonic-interop/data/server1.key").await?;
let identity = Identity::from_pem(cert, key);
builder = builder.tls_config(ServerTlsConfig::with_openssl().identity(identity));
}
}
let test_service = server::TestServiceServer::new(server::TestService::default()); let test_service = server::TestServiceServer::new(server::TestService::default());
let unimplemented_service = let unimplemented_service =
server::UnimplementedServiceServer::new(server::UnimplementedService::default()); server::UnimplementedServiceServer::new(server::UnimplementedService::default());
+60 -39
View File
@@ -76,9 +76,11 @@ impl Endpoint {
/// # let mut builder = Endpoint::from_static("https://example.com"); /// # let mut builder = Endpoint::from_static("https://example.com");
/// builder.timeout(Duration::from_secs(5)); /// builder.timeout(Duration::from_secs(5));
/// ``` /// ```
pub fn timeout(&mut self, dur: Duration) -> &mut Self { pub fn timeout(self, dur: Duration) -> Self {
self.timeout = Some(dur); Endpoint {
self timeout: Some(dur),
..self
}
} }
/// Apply a concurrency limit to each request. /// Apply a concurrency limit to each request.
@@ -88,9 +90,11 @@ impl Endpoint {
/// # let mut builder = Endpoint::from_static("https://example.com"); /// # let mut builder = Endpoint::from_static("https://example.com");
/// builder.concurrency_limit(256); /// builder.concurrency_limit(256);
/// ``` /// ```
pub fn concurrency_limit(&mut self, limit: usize) -> &mut Self { pub fn concurrency_limit(self, limit: usize) -> Self {
self.concurrency_limit = Some(limit); Endpoint {
self concurrency_limit: Some(limit),
..self
}
} }
/// Apply a rate limit to each request. /// Apply a rate limit to each request.
@@ -101,9 +105,11 @@ impl Endpoint {
/// # let mut builder = Endpoint::from_static("https://example.com"); /// # let mut builder = Endpoint::from_static("https://example.com");
/// builder.rate_limit(32, Duration::from_secs(1)); /// builder.rate_limit(32, Duration::from_secs(1));
/// ``` /// ```
pub fn rate_limit(&mut self, limit: u64, duration: Duration) -> &mut Self { pub fn rate_limit(self, limit: u64, duration: Duration) -> Self {
self.rate_limit = Some((limit, duration)); Endpoint {
self rate_limit: Some((limit, duration)),
..self
}
} }
/// Sets the [`SETTINGS_INITIAL_WINDOW_SIZE`][spec] option for HTTP2 /// Sets the [`SETTINGS_INITIAL_WINDOW_SIZE`][spec] option for HTTP2
@@ -112,33 +118,41 @@ impl Endpoint {
/// Default is 65,535 /// Default is 65,535
/// ///
/// [spec]: https://http2.github.io/http2-spec/#SETTINGS_INITIAL_WINDOW_SIZE /// [spec]: https://http2.github.io/http2-spec/#SETTINGS_INITIAL_WINDOW_SIZE
pub fn initial_stream_window_size(&mut self, sz: impl Into<Option<u32>>) -> &mut Self { pub fn initial_stream_window_size(self, sz: impl Into<Option<u32>>) -> Self {
self.init_stream_window_size = sz.into(); Endpoint {
self init_stream_window_size: sz.into(),
..self
}
} }
/// Sets the max connection-level flow control for HTTP2 /// Sets the max connection-level flow control for HTTP2
/// ///
/// Default is 65,535 /// Default is 65,535
pub fn initial_connection_window_size(&mut self, sz: impl Into<Option<u32>>) -> &mut Self { pub fn initial_connection_window_size(self, sz: impl Into<Option<u32>>) -> Self {
self.init_connection_window_size = sz.into(); Endpoint {
self init_connection_window_size: sz.into(),
..self
}
} }
/// Intercept outbound HTTP Request headers; /// Intercept outbound HTTP Request headers;
pub fn intercept_headers<F>(&mut self, f: F) -> &mut Self pub fn intercept_headers<F>(self, f: F) -> Self
where where
F: Fn(&mut http::HeaderMap) + Send + Sync + 'static, F: Fn(&mut http::HeaderMap) + Send + Sync + 'static,
{ {
self.interceptor_headers = Some(Arc::new(f)); Endpoint {
self interceptor_headers: Some(Arc::new(f)),
..self
}
} }
/// Configures TLS for the endpoint. /// Configures TLS for the endpoint.
#[cfg(feature = "tls")] #[cfg(feature = "tls")]
pub fn tls_config(&mut self, tls_config: &ClientTlsConfig) -> &mut Self { pub fn tls_config(self, tls_config: ClientTlsConfig) -> Self {
self.tls = Some(tls_config.tls_connector(self.uri.clone()).unwrap()); Endpoint {
self tls: Some(tls_config.tls_connector(self.uri.clone()).unwrap()),
..self
}
} }
/// Create a channel from this config. /// Create a channel from this config.
@@ -262,48 +276,55 @@ impl ClientTlsConfig {
/// ///
/// This has no effect if `rustls_client_config` or `openssl_connector` is used to configure /// This has no effect if `rustls_client_config` or `openssl_connector` is used to configure
/// Rustls or OpenSSL respectively. /// Rustls or OpenSSL respectively.
pub fn domain_name(&mut self, domain_name: impl Into<String>) -> &mut Self { pub fn domain_name(self, domain_name: impl Into<String>) -> Self {
self.domain = Some(domain_name.into()); ClientTlsConfig {
self domain: Some(domain_name.into()),
..self
}
} }
/// Sets the CA Certificate against which to verify the server's TLS certificate. /// Sets the CA Certificate against which to verify the server's TLS certificate.
/// ///
/// This has no effect if `rustls_client_config` or `openssl_connector` is used to configure /// This has no effect if `rustls_client_config` or `openssl_connector` is used to configure
/// Rustls or OpenSSL respectively. /// Rustls or OpenSSL respectively.
pub fn ca_certificate(&mut self, ca_certificate: Certificate) -> &mut Self { pub fn ca_certificate(self, ca_certificate: Certificate) -> Self {
self.cert = Some(ca_certificate); ClientTlsConfig {
self cert: Some(ca_certificate),
..self
}
} }
/// Sets the client identity to present to the server. /// Sets the client identity to present to the server.
/// ///
/// This has no effect if `rustls_client_config` or `openssl_connector` is used to configure /// This has no effect if `rustls_client_config` or `openssl_connector` is used to configure
/// Rustls or OpenSSL respectively. /// Rustls or OpenSSL respectively.
pub fn identity(&mut self, identity: Identity) -> &mut Self { pub fn identity(self, identity: Identity) -> Self {
self.identity = Some(identity); ClientTlsConfig {
self identity: Some(identity),
..self
}
} }
/// Use options specified by the given `SslConnector` to configure TLS. /// Use options specified by the given `SslConnector` to configure TLS.
/// ///
/// This overrides all other TLS options set via other means. /// This overrides all other TLS options set via other means.
#[cfg(feature = "openssl")] #[cfg(feature = "openssl")]
pub fn openssl_connector(&mut self, connector: openssl1::ssl::SslConnector) -> &mut Self { pub fn openssl_connector(self, connector: openssl1::ssl::SslConnector) -> Self {
self.openssl_raw = Some(connector); ClientTlsConfig {
self openssl_raw: Some(connector),
..self
}
} }
/// Use options specified by the given `ClientConfig` to configure TLS. /// Use options specified by the given `ClientConfig` to configure TLS.
/// ///
/// This overrides all other TLS options set via other means. /// This overrides all other TLS options set via other means.
#[cfg(feature = "rustls")] #[cfg(feature = "rustls")]
pub fn rustls_client_config( pub fn rustls_client_config(self, config: tokio_rustls::rustls::ClientConfig) -> Self {
&mut self, ClientTlsConfig {
config: tokio_rustls::rustls::ClientConfig, rustls_raw: Some(config),
) -> &mut Self { ..self
self.rustls_raw = Some(config); }
self
} }
fn tls_connector(&self, uri: Uri) -> Result<TlsConnector, crate::Error> { fn tls_connector(&self, uri: Uri) -> Result<TlsConnector, crate::Error> {
+46 -27
View File
@@ -83,9 +83,11 @@ impl Server {
impl Server { impl Server {
/// Configure TLS for this server. /// Configure TLS for this server.
#[cfg(feature = "tls")] #[cfg(feature = "tls")]
pub fn tls_config(&mut self, tls_config: &ServerTlsConfig) -> &mut Self { pub fn tls_config(self, tls_config: ServerTlsConfig) -> Self {
self.tls = Some(tls_config.tls_acceptor().unwrap()); Server {
self tls: Some(tls_config.tls_acceptor().unwrap()),
..self
}
} }
/// Set the concurrency limit applied to on requests inbound per connection. /// Set the concurrency limit applied to on requests inbound per connection.
@@ -96,9 +98,11 @@ impl Server {
/// # let mut builder = Server::builder(); /// # let mut builder = Server::builder();
/// builder.concurrency_limit_per_connection(32); /// builder.concurrency_limit_per_connection(32);
/// ``` /// ```
pub fn concurrency_limit_per_connection(&mut self, limit: usize) -> &mut Self { pub fn concurrency_limit_per_connection(self, limit: usize) -> Self {
self.concurrency_limit = Some(limit); Server {
self concurrency_limit: Some(limit),
..self
}
} }
// FIXME: tower-timeout currentlly uses `From` instead of `Into` for the error // FIXME: tower-timeout currentlly uses `From` instead of `Into` for the error
@@ -114,17 +118,21 @@ impl Server {
/// Default is 65,535 /// Default is 65,535
/// ///
/// [spec]: https://http2.github.io/http2-spec/#SETTINGS_INITIAL_WINDOW_SIZE /// [spec]: https://http2.github.io/http2-spec/#SETTINGS_INITIAL_WINDOW_SIZE
pub fn initial_stream_window_size(&mut self, sz: impl Into<Option<u32>>) -> &mut Self { pub fn initial_stream_window_size(self, sz: impl Into<Option<u32>>) -> Self {
self.init_stream_window_size = sz.into(); Server {
self init_stream_window_size: sz.into(),
..self
}
} }
/// Sets the max connection-level flow control for HTTP2 /// Sets the max connection-level flow control for HTTP2
/// ///
/// Default is 65,535 /// Default is 65,535
pub fn initial_connection_window_size(&mut self, sz: impl Into<Option<u32>>) -> &mut Self { pub fn initial_connection_window_size(self, sz: impl Into<Option<u32>>) -> Self {
self.init_connection_window_size = sz.into(); Server {
self init_connection_window_size: sz.into(),
..self
}
} }
/// Sets the [`SETTINGS_MAX_CONCURRENT_STREAMS`][spec] option for HTTP2 /// Sets the [`SETTINGS_MAX_CONCURRENT_STREAMS`][spec] option for HTTP2
@@ -133,9 +141,11 @@ impl Server {
/// Default is no limit (`None`). /// Default is no limit (`None`).
/// ///
/// [spec]: https://http2.github.io/http2-spec/#SETTINGS_MAX_CONCURRENT_STREAMS /// [spec]: https://http2.github.io/http2-spec/#SETTINGS_MAX_CONCURRENT_STREAMS
pub fn max_concurrent_streams(&mut self, max: impl Into<Option<u32>>) -> &mut Self { pub fn max_concurrent_streams(self, max: impl Into<Option<u32>>) -> Self {
self.max_concurrent_streams = max.into(); Server {
self max_concurrent_streams: max.into(),
..self
}
} }
/// Intercept the execution of gRPC methods. /// Intercept the execution of gRPC methods.
@@ -149,7 +159,7 @@ impl Server {
/// svc.call(req) /// svc.call(req)
/// }); /// });
/// ``` /// ```
pub fn interceptor_fn<F, Out>(&mut self, f: F) -> &mut Self pub fn interceptor_fn<F, Out>(self, f: F) -> Self
where where
F: Fn(&mut BoxService, Request<Body>) -> Out + Send + Sync + 'static, F: Fn(&mut BoxService, Request<Body>) -> Out + Send + Sync + 'static,
Out: Future<Output = Result<Response<BoxBody>, crate::Error>> + Send + 'static, Out: Future<Output = Result<Response<BoxBody>, crate::Error>> + Send + 'static,
@@ -160,8 +170,11 @@ impl Server {
tower::service_fn(move |req| f(&mut s, req)) tower::service_fn(move |req| f(&mut s, req))
}); });
let layer = Stack::new(interceptor, layer_fn(BoxService::new)); let layer = Stack::new(interceptor, layer_fn(BoxService::new));
self.interceptor = Some(Arc::new(layer));
self Server {
interceptor: Some(Arc::new(layer)),
..self
}
} }
/// Create a router with the `S` typed service as the first service. /// Create a router with the `S` typed service as the first service.
@@ -366,24 +379,30 @@ impl ServerTlsConfig {
} }
/// Sets the [`Identity`] of the server. /// Sets the [`Identity`] of the server.
pub fn identity(&mut self, identity: Identity) -> &mut Self { pub fn identity(self, identity: Identity) -> Self {
self.identity = Some(identity); ServerTlsConfig {
self identity: Some(identity),
..self
}
} }
/// Sets a certificate against which to validate client TLS certificates. /// Sets a certificate against which to validate client TLS certificates.
pub fn client_ca_root(&mut self, cert: Certificate) -> &mut Self { pub fn client_ca_root(self, cert: Certificate) -> Self {
self.client_ca_root = Some(cert); ServerTlsConfig {
self client_ca_root: Some(cert),
..self
}
} }
/// Use options specified by the given `SslAcceptor` to configure TLS. /// Use options specified by the given `SslAcceptor` to configure TLS.
/// ///
/// This overrides all other TLS options set via other means. /// This overrides all other TLS options set via other means.
#[cfg(feature = "openssl")] #[cfg(feature = "openssl")]
pub fn openssl_connector(&mut self, acceptor: openssl1::ssl::SslAcceptor) -> &mut Self { pub fn openssl_connector(self, acceptor: openssl1::ssl::SslAcceptor) -> Self {
self.openssl_raw = Some(acceptor); ServerTlsConfig {
self openssl_raw: Some(acceptor),
..self
}
} }
/// Use options specified by the given `ServerConfig` to configure TLS. /// Use options specified by the given `ServerConfig` to configure TLS.