diff --git a/examples/build.rs b/examples/build.rs index 97ab2d0..4a1c07c 100644 --- a/examples/build.rs +++ b/examples/build.rs @@ -1,6 +1,10 @@ fn main() { + tonic_build::configure() + .type_attribute("routeguide.Point", "#[derive(Hash)]") + .compile(&["proto/routeguide/route_guide.proto"], &["proto"]) + .unwrap(); + tonic_build::compile_protos("proto/helloworld/helloworld.proto").unwrap(); - tonic_build::compile_protos("proto/routeguide/route_guide.proto").unwrap(); tonic_build::compile_protos("proto/echo/echo.proto").unwrap(); tonic_build::compile_protos("proto/google/pubsub/pubsub.proto").unwrap(); } diff --git a/examples/src/gcp/client.rs b/examples/src/gcp/client.rs index 1cf30fc..b434ed1 100644 --- a/examples/src/gcp/client.rs +++ b/examples/src/gcp/client.rs @@ -18,9 +18,8 @@ async fn main() -> Result<(), Box> { })?; let project = std::env::args() - .skip(1) - .next() - .ok_or("Expected a project name as the first argument.".to_string())?; + .nth(1) + .ok_or_else(|| "Expected a project name as the first argument.".to_string())?; let bearer_token = format!("Bearer {}", token); let header_value = MetadataValue::from_str(&bearer_token)?; diff --git a/examples/src/hyper_warp/server.rs b/examples/src/hyper_warp/server.rs index 7c54b1e..a49da38 100644 --- a/examples/src/hyper_warp/server.rs +++ b/examples/src/hyper_warp/server.rs @@ -48,12 +48,11 @@ async fn main() -> Result<(), Box> { println!("GreeterServer listening on {}", addr); let tonic = GreeterServer::new(greeter); - let warp = warp::service(warp::path("hello").map(|| "hello, world!")); + let mut warp = warp::service(warp::path("hello").map(|| "hello, world!")); Server::bind(&addr) .serve(make_service_fn(move |_| { let mut tonic = tonic.clone(); - let mut warp = warp.clone(); future::ok::<_, Infallible>(tower::service_fn( move |req: hyper::Request| match req.version() { Version::HTTP_11 | Version::HTTP_10 => Either::Left( diff --git a/examples/src/hyper_warp_multiplex/server.rs b/examples/src/hyper_warp_multiplex/server.rs index cbcccc9..1e251c4 100644 --- a/examples/src/hyper_warp_multiplex/server.rs +++ b/examples/src/hyper_warp_multiplex/server.rs @@ -96,9 +96,7 @@ impl Echo for MyEcho { async fn main() -> Result<(), Box> { let addr = "[::1]:50051".parse().unwrap(); - //println!("GreeterServer listening on {}", addr); - - let warp = warp::service(warp::path("hello").map(|| "hello, world!")); + let mut warp = warp::service(warp::path("hello").map(|| "hello, world!")); Server::bind(&addr) .serve(make_service_fn(move |_| { @@ -110,7 +108,6 @@ async fn main() -> Result<(), Box> { .add_service(echo) .into_service(); - let mut warp = warp.clone(); future::ok::<_, Infallible>(tower::service_fn( move |req: hyper::Request| match req.version() { Version::HTTP_11 | Version::HTTP_10 => Either::Left( diff --git a/examples/src/routeguide/server.rs b/examples/src/routeguide/server.rs index 4597174..2f1c50e 100644 --- a/examples/src/routeguide/server.rs +++ b/examples/src/routeguide/server.rs @@ -1,5 +1,4 @@ use std::collections::HashMap; -use std::hash::{Hash, Hasher}; use std::pin::Pin; use std::sync::Arc; use std::time::Instant; @@ -150,17 +149,6 @@ async fn main() -> Result<(), Box> { Ok(()) } -// Implement hash for Point -impl Hash for Point { - fn hash(&self, state: &mut H) - where - H: Hasher, - { - self.latitude.hash(state); - self.longitude.hash(state); - } -} - impl Eq for Point {} fn in_range(point: &Point, rect: &Rectangle) -> bool { diff --git a/interop/src/client.rs b/interop/src/client.rs index ce6e6e6..e79b041 100644 --- a/interop/src/client.rs +++ b/interop/src/client.rs @@ -251,7 +251,6 @@ pub async fn status_code_and_message(client: &mut TestClient, assertions: &mut V response_status: Some(EchoStatus { code: 2, message: TEST_STATUS_MESSAGE.to_string(), - ..Default::default() }), ..Default::default() }; @@ -260,7 +259,6 @@ pub async fn status_code_and_message(client: &mut TestClient, assertions: &mut V response_status: Some(EchoStatus { code: 2, message: TEST_STATUS_MESSAGE.to_string(), - ..Default::default() }), ..Default::default() }; @@ -286,7 +284,6 @@ pub async fn special_status_message(client: &mut TestClient, assertions: &mut Ve response_status: Some(EchoStatus { code: 2, message: SPECIAL_TEST_STATUS_MESSAGE.to_string(), - ..Default::default() }), ..Default::default() }; diff --git a/interop/src/lib.rs b/interop/src/lib.rs index 6239a1b..1a2c77a 100644 --- a/interop/src/lib.rs +++ b/interop/src/lib.rs @@ -50,7 +50,7 @@ fn response_length(response: &pb::StreamingOutputCallResponse) -> i32 { } } -fn response_lengths(responses: &Vec) -> Vec { +fn response_lengths(responses: &[pb::StreamingOutputCallResponse]) -> Vec { responses.iter().map(&response_length).collect() } diff --git a/interop/src/server.rs b/interop/src/server.rs index f815832..154ed50 100644 --- a/interop/src/server.rs +++ b/interop/src/server.rs @@ -21,6 +21,7 @@ type Streaming = Request>; type Stream = Pin< Box> + Send + Sync + 'static>, >; +type BoxFuture = Pin> + Send + 'static>>; #[tonic::async_trait] impl pb::test_service_server::TestService for TestService { @@ -187,9 +188,7 @@ where { type Response = S::Response; type Error = S::Error; - type Future = Pin< - Box> + Send + 'static>, - >; + type Future = BoxFuture; fn poll_ready(&mut self, _cx: &mut Context<'_>) -> Poll> { Ok(()).into() diff --git a/tonic-build/src/prost.rs b/tonic-build/src/prost.rs index 1351bdb..f8284d4 100644 --- a/tonic-build/src/prost.rs +++ b/tonic-build/src/prost.rs @@ -39,7 +39,7 @@ pub fn compile_protos(proto: impl AsRef) -> io::Result<()> { Ok(()) } -const PROST_CODEC_PATH: &'static str = "tonic::codec::ProstCodec"; +const PROST_CODEC_PATH: &str = "tonic::codec::ProstCodec"; impl crate::Service for Service { const CODEC_PATH: &'static str = PROST_CODEC_PATH; diff --git a/tonic/src/codec/decode.rs b/tonic/src/codec/decode.rs index 88545df..157a270 100644 --- a/tonic/src/codec/decode.rs +++ b/tonic/src/codec/decode.rs @@ -134,7 +134,7 @@ impl Streaming { } // To fetch the trailers we must clear the body and drop it. - while let Some(_) = self.message().await? {} + while self.message().await?.is_some() {} // Since we call poll_trailers internally on poll_next we need to // check if it got cached again. @@ -219,9 +219,8 @@ impl Stream for Streaming { // FIXME: implement the ability to poll trailers when we _know_ that // the consumer of this stream will only poll for the first message. // This means we skip the poll_trailers step. - match self.decode_chunk()? { - Some(item) => return Poll::Ready(Some(Ok(item))), - None => (), + if let Some(item) = self.decode_chunk()? { + return Poll::Ready(Some(Ok(item))); } let chunk = match ready!(Pin::new(&mut self.body).poll_data(cx)) { @@ -230,8 +229,7 @@ impl Stream for Streaming { let err: crate::Error = e.into(); debug!("decoder inner stream error: {:?}", err); let status = Status::from_error(&*err); - Err(status)?; - break; + return Poll::Ready(Some(Err(status))); } None => None, }; @@ -252,10 +250,10 @@ impl Stream for Streaming { // FIXME: improve buf usage. if self.buf.has_remaining() { trace!("unexpected EOF decoding stream"); - Err(Status::new( + return Poll::Ready(Some(Err(Status::new( Code::Internal, "Unexpected EOF decoding stream.".to_string(), - ))?; + )))); } else { break; } diff --git a/tonic/src/codec/encode.rs b/tonic/src/codec/encode.rs index ce65f8a..58f4f99 100644 --- a/tonic/src/codec/encode.rs +++ b/tonic/src/codec/encode.rs @@ -35,7 +35,7 @@ where T::Item: Send + Sync, U: Stream + Send + Sync + 'static, { - let stream = encode(encoder, source.map(|x| Ok(x))).into_stream(); + let stream = encode(encoder, source.map(Ok)).into_stream(); EncodeBody::new_client(stream) } diff --git a/tonic/src/interceptor.rs b/tonic/src/interceptor.rs index 51dcd6e..3ad0ac6 100644 --- a/tonic/src/interceptor.rs +++ b/tonic/src/interceptor.rs @@ -1,6 +1,9 @@ use crate::{Request, Status}; use std::{fmt, sync::Arc}; +type InterceptorFn = + Arc) -> Result, Status> + Send + Sync + 'static>; + /// Represents a gRPC interceptor. /// /// gRPC interceptors are similar to middleware but have much less @@ -16,7 +19,7 @@ use std::{fmt, sync::Arc}; /// features to the body of the request, going through the `tower` abstraction is recommended. #[derive(Clone)] pub struct Interceptor { - f: Arc) -> Result, Status> + Send + Sync + 'static>, + f: InterceptorFn, } impl Interceptor { diff --git a/tonic/src/status.rs b/tonic/src/status.rs index c54dca9..13ede75 100644 --- a/tonic/src/status.rs +++ b/tonic/src/status.rs @@ -505,11 +505,12 @@ impl Status { Status { code, message: message.into(), - details: details, - metadata: metadata, + details, + metadata, } } + #[allow(clippy::wrong_self_convention)] /// Build an `http::Response` from the given `Status`. pub fn to_http(self) -> http::Response { let (mut parts, _body) = http::Response::new(()).into_parts(); diff --git a/tonic/src/transport/channel/endpoint.rs b/tonic/src/transport/channel/endpoint.rs index c558ff5..788fa2e 100644 --- a/tonic/src/transport/channel/endpoint.rs +++ b/tonic/src/transport/channel/endpoint.rs @@ -192,7 +192,7 @@ impl Endpoint { tls: Some( tls_config .tls_connector(self.uri.clone()) - .map_err(|e| Error::from_source(e))?, + .map_err(Error::from_source)?, ), ..self }) diff --git a/tonic/src/transport/channel/mod.rs b/tonic/src/transport/channel/mod.rs index 63b3080..be2c122 100644 --- a/tonic/src/transport/channel/mod.rs +++ b/tonic/src/transport/channel/mod.rs @@ -183,7 +183,7 @@ impl GrpcService for Channel { type Future = ResponseFuture; fn poll_ready(&mut self, cx: &mut Context<'_>) -> Poll> { - GrpcService::poll_ready(&mut self.svc, cx).map_err(|e| super::Error::from_source(e)) + GrpcService::poll_ready(&mut self.svc, cx).map_err(super::Error::from_source) } fn call(&mut self, request: Request) -> Self::Future { @@ -197,7 +197,7 @@ impl Future for ResponseFuture { fn poll(mut self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll { let val = futures_util::ready!(Pin::new(&mut self.inner).poll(cx)) - .map_err(|e| super::Error::from_source(e))?; + .map_err(super::Error::from_source)?; Ok(val).into() } } diff --git a/tonic/src/transport/channel/tls.rs b/tonic/src/transport/channel/tls.rs index 37888b8..00e640f 100644 --- a/tonic/src/transport/channel/tls.rs +++ b/tonic/src/transport/channel/tls.rs @@ -9,7 +9,7 @@ use std::fmt; /// Configures TLS settings for endpoints. #[cfg(feature = "tls")] #[cfg_attr(docsrs, doc(cfg(feature = "tls")))] -#[derive(Clone)] +#[derive(Clone, Default)] pub struct ClientTlsConfig { domain: Option, cert: Option, @@ -80,7 +80,7 @@ impl ClientTlsConfig { pub(crate) fn tls_connector(&self, uri: Uri) -> Result { let domain = match &self.domain { - None => uri.host().ok_or(Error::new_invalid_uri())?.to_string(), + None => uri.host().ok_or_else(Error::new_invalid_uri)?.to_string(), Some(domain) => domain.clone(), }; match &self.rustls_raw { diff --git a/tonic/src/transport/mod.rs b/tonic/src/transport/mod.rs index 40bd7b1..b91767a 100644 --- a/tonic/src/transport/mod.rs +++ b/tonic/src/transport/mod.rs @@ -107,3 +107,6 @@ pub use self::channel::ClientTlsConfig; #[cfg(feature = "tls")] #[cfg_attr(docsrs, doc(cfg(feature = "tls")))] pub use self::server::ServerTlsConfig; + +type BoxFuture = + std::pin::Pin> + Send + 'static>>; diff --git a/tonic/src/transport/server/mod.rs b/tonic/src/transport/server/mod.rs index e83ff07..490654f 100644 --- a/tonic/src/transport/server/mod.rs +++ b/tonic/src/transport/server/mod.rs @@ -21,7 +21,10 @@ pub(crate) use incoming::TlsStream; #[cfg(feature = "tls")] use crate::transport::Error; -use super::service::{Or, Routes, ServerIo, ServiceBuilderExt}; +use super::{ + service::{Or, Routes, ServerIo, ServiceBuilderExt}, + BoxFuture, +}; use crate::{body::BoxBody, request::ConnectionInfo}; use futures_core::Stream; use futures_util::{ @@ -34,7 +37,6 @@ use std::{ fmt, future::Future, net::SocketAddr, - pin::Pin, sync::Arc, task::{Context, Poll}, time::Duration, @@ -98,11 +100,13 @@ where B::Error: Into + Send, { type Response = Response; + type Error = crate::Error; + + #[allow(clippy::type_complexity)] type Future = FutureEither< MapErr crate::Error>, MapErr crate::Error>, >; - type Error = crate::Error; fn poll_ready(&mut self, _: &mut Context<'_>) -> Poll> { Poll::Ready(Ok(())) @@ -143,11 +147,7 @@ impl Server { #[cfg_attr(docsrs, doc(cfg(feature = "tls")))] pub fn tls_config(self, tls_config: ServerTlsConfig) -> Result { Ok(Server { - tls: Some( - tls_config - .tls_acceptor() - .map_err(|e| Error::from_source(e))?, - ), + tls: Some(tls_config.tls_acceptor().map_err(Error::from_source)?), ..self }) } @@ -320,7 +320,7 @@ impl Server { let init_connection_window_size = self.init_connection_window_size; let init_stream_window_size = self.init_stream_window_size; let max_concurrent_streams = self.max_concurrent_streams; - let timeout = self.timeout.clone(); + let timeout = self.timeout; let tcp = incoming::tcp_incoming(incoming, self); let incoming = accept::from_stream::<_, _, crate::Error>(tcp); @@ -538,6 +538,8 @@ where { type Response = Response; type Error = crate::Error; + + #[allow(clippy::type_complexity)] type Future = MapErr, fn(S::Error) -> crate::Error>; fn poll_ready(&mut self, cx: &mut Context<'_>) -> Poll> { @@ -578,8 +580,7 @@ where { type Response = BoxService; type Error = crate::Error; - type Future = - Pin> + Send + 'static>>; + type Future = BoxFuture; fn poll_ready(&mut self, _cx: &mut Context<'_>) -> Poll> { Ok(()).into() @@ -593,7 +594,7 @@ where let svc = self.inner.clone(); let concurrency_limit = self.concurrency_limit; - let timeout = self.timeout.clone(); + let timeout = self.timeout; let span = self.span.clone(); Box::pin(async move { diff --git a/tonic/src/transport/server/tls.rs b/tonic/src/transport/server/tls.rs index 42facbb..999ec30 100644 --- a/tonic/src/transport/server/tls.rs +++ b/tonic/src/transport/server/tls.rs @@ -7,7 +7,7 @@ use std::fmt; /// Configures TLS settings for servers. #[cfg(feature = "tls")] #[cfg_attr(docsrs, doc(cfg(feature = "tls")))] -#[derive(Clone)] +#[derive(Clone, Default)] pub struct ServerTlsConfig { identity: Option, client_ca_root: Option, diff --git a/tonic/src/transport/service/add_origin.rs b/tonic/src/transport/service/add_origin.rs index 7c7df74..a1d7cd2 100644 --- a/tonic/src/transport/service/add_origin.rs +++ b/tonic/src/transport/service/add_origin.rs @@ -35,8 +35,8 @@ where let set_uri = self.origin.clone().into_parts(); // Update the URI parts, setting hte scheme and authority - uri.scheme = Some(set_uri.scheme.expect("expected scheme").clone()); - uri.authority = Some(set_uri.authority.expect("expected authority").clone()); + uri.scheme = Some(set_uri.scheme.expect("expected scheme")); + uri.authority = Some(set_uri.authority.expect("expected authority")); // Update the the request URI head.uri = http::Uri::from_parts(uri).expect("valid uri"); diff --git a/tonic/src/transport/service/connection.rs b/tonic/src/transport/service/connection.rs index 1875a14..52e82ab 100644 --- a/tonic/src/transport/service/connection.rs +++ b/tonic/src/transport/service/connection.rs @@ -1,3 +1,4 @@ +use super::super::BoxFuture; use super::{layer::ServiceBuilderExt, reconnect::Reconnect, AddOrigin, UserAgent}; use crate::{body::BoxBody, transport::Endpoint}; use http::Uri; @@ -6,8 +7,6 @@ use hyper::client::connect::Connection as HyperConnection; use hyper::client::service::Connect as HyperConnect; use std::{ fmt, - future::Future, - pin::Pin, task::{Context, Poll}, }; use tokio::io::{AsyncRead, AsyncWrite}; @@ -51,8 +50,6 @@ impl Connection { settings.http2_keep_alive_while_idle(val); } - let settings = settings.clone(); - let stack = ServiceBuilder::new() .layer_fn(|s| AddOrigin::new(s, endpoint.uri.clone())) .layer_fn(|s| UserAgent::new(s, endpoint.user_agent.clone())) @@ -95,9 +92,7 @@ impl Connection { impl Service for Connection { type Response = Response; type Error = crate::Error; - - type Future = - Pin> + Send + 'static>>; + type Future = BoxFuture; fn poll_ready(&mut self, cx: &mut Context<'_>) -> Poll> { Service::poll_ready(&mut self.inner, cx).map_err(Into::into) diff --git a/tonic/src/transport/service/connector.rs b/tonic/src/transport/service/connector.rs index 6f1177d..25d6a19 100644 --- a/tonic/src/transport/service/connector.rs +++ b/tonic/src/transport/service/connector.rs @@ -1,9 +1,8 @@ +use super::super::BoxFuture; use super::io::BoxedIo; #[cfg(feature = "tls")] use super::tls::TlsConnector; use http::Uri; -use std::future::Future; -use std::pin::Pin; use std::task::{Context, Poll}; use tower_make::MakeConnection; use tower_service::Service; @@ -48,9 +47,7 @@ where { type Response = BoxedIo; type Error = crate::Error; - - type Future = - Pin> + Send + 'static>>; + type Future = BoxFuture; fn poll_ready(&mut self, cx: &mut Context<'_>) -> Poll> { MakeConnection::poll_ready(&mut self.inner, cx).map_err(Into::into) diff --git a/tonic/src/transport/service/discover.rs b/tonic/src/transport/service/discover.rs index 55a98cd..925525c 100644 --- a/tonic/src/transport/service/discover.rs +++ b/tonic/src/transport/service/discover.rs @@ -1,4 +1,4 @@ -use super::super::service; +use super::super::{service, BoxFuture}; use super::connection::Connection; use crate::transport::Endpoint; @@ -12,12 +12,11 @@ use tokio::{stream::Stream, sync::mpsc::Receiver}; use tower::discover::{Change, Discover}; +type DiscoverResult = Result, E>; + pub(crate) struct DynamicServiceStream { changes: Receiver>, - connecting: Option<( - K, - Pin> + Send + 'static>>, - )>, + connecting: Option<(K, BoxFuture)>, } impl DynamicServiceStream { @@ -37,7 +36,7 @@ impl Discover for DynamicServiceStream { fn poll_discover( mut self: Pin<&mut Self>, cx: &mut Context<'_>, - ) -> Poll, Self::Error>> { + ) -> Poll> { loop { if let Some((key, connecting)) = &mut self.connecting { let svc = futures_core::ready!(Pin::new(connecting).poll(cx))?; diff --git a/tonic/src/transport/service/reconnect.rs b/tonic/src/transport/service/reconnect.rs index e01074b..c123d96 100644 --- a/tonic/src/transport/service/reconnect.rs +++ b/tonic/src/transport/service/reconnect.rs @@ -94,7 +94,7 @@ where if !(self.has_been_connected || self.is_lazy) { return Poll::Ready(Err(e.into())); } else { - self.error = Some(e.into()); + self.error = Some(e); break; } } diff --git a/tonic/src/transport/service/router.rs b/tonic/src/transport/service/router.rs index 490c588..76f0d0c 100644 --- a/tonic/src/transport/service/router.rs +++ b/tonic/src/transport/service/router.rs @@ -94,6 +94,8 @@ where { type Response = A::Response; type Error = crate::Error; + + #[allow(clippy::type_complexity)] type Future = Either< MapErr crate::Error>, MapErr crate::Error>, diff --git a/tonic/src/transport/service/tls.rs b/tonic/src/transport/service/tls.rs index eef0f9a..f292da7 100644 --- a/tonic/src/transport/service/tls.rs +++ b/tonic/src/transport/service/tls.rs @@ -133,10 +133,9 @@ impl TlsAcceptor { let mut cert = std::io::Cursor::new(&cert.pem[..]); let mut client_root_cert_store = tokio_rustls::rustls::RootCertStore::empty(); - match client_root_cert_store.add_pem_file(&mut cert) { - Err(_) => return Err(Box::new(TlsError::CertificateParseError)), - _ => (), - }; + if client_root_cert_store.add_pem_file(&mut cert).is_err() { + return Err(Box::new(TlsError::CertificateParseError)); + } let client_auth = tokio_rustls::rustls::AllowAnyAuthenticatedClient::new(client_root_cert_store); @@ -204,7 +203,7 @@ mod rustls_keys { ) -> Result { // First attempt to load the private key assuming it is PKCS8-encoded if let Ok(mut keys) = pemfile::pkcs8_private_keys(&mut cursor) { - if keys.len() > 0 { + if !keys.is_empty() { return Ok(keys.remove(0)); } } @@ -212,7 +211,7 @@ mod rustls_keys { // If it not, try loading the private key as an RSA key cursor.set_position(0); if let Ok(mut keys) = pemfile::rsa_private_keys(&mut cursor) { - if keys.len() > 0 { + if !keys.is_empty() { return Ok(keys.remove(0)); } } diff --git a/tonic/src/transport/service/user_agent.rs b/tonic/src/transport/service/user_agent.rs index 6ceaea6..7f59e90 100644 --- a/tonic/src/transport/service/user_agent.rs +++ b/tonic/src/transport/service/user_agent.rs @@ -20,7 +20,7 @@ impl UserAgent { buf.extend(TONIC_USER_AGENT.as_bytes()); HeaderValue::from_bytes(&buf).expect("user-agent should be valid") }) - .unwrap_or(HeaderValue::from_static(TONIC_USER_AGENT)); + .unwrap_or_else(|| HeaderValue::from_static(TONIC_USER_AGENT)); Self { inner, user_agent } }