chore: clippy lints (#467)

* chore: clippy lints
This commit is contained in:
Juan Alvarez
2020-09-29 14:38:49 -05:00
committed by GitHub
parent 9ea4a64a6c
commit 0c69c378fd
27 changed files with 69 additions and 88 deletions
+5 -1
View File
@@ -1,6 +1,10 @@
fn main() { 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/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/echo/echo.proto").unwrap();
tonic_build::compile_protos("proto/google/pubsub/pubsub.proto").unwrap(); tonic_build::compile_protos("proto/google/pubsub/pubsub.proto").unwrap();
} }
+2 -3
View File
@@ -18,9 +18,8 @@ async fn main() -> Result<(), Box<dyn std::error::Error>> {
})?; })?;
let project = std::env::args() let project = std::env::args()
.skip(1) .nth(1)
.next() .ok_or_else(|| "Expected a project name as the first argument.".to_string())?;
.ok_or("Expected a project name as the first argument.".to_string())?;
let bearer_token = format!("Bearer {}", token); let bearer_token = format!("Bearer {}", token);
let header_value = MetadataValue::from_str(&bearer_token)?; let header_value = MetadataValue::from_str(&bearer_token)?;
+1 -2
View File
@@ -48,12 +48,11 @@ async fn main() -> Result<(), Box<dyn std::error::Error>> {
println!("GreeterServer listening on {}", addr); println!("GreeterServer listening on {}", addr);
let tonic = GreeterServer::new(greeter); 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) Server::bind(&addr)
.serve(make_service_fn(move |_| { .serve(make_service_fn(move |_| {
let mut tonic = tonic.clone(); let mut tonic = tonic.clone();
let mut warp = warp.clone();
future::ok::<_, Infallible>(tower::service_fn( future::ok::<_, Infallible>(tower::service_fn(
move |req: hyper::Request<hyper::Body>| match req.version() { move |req: hyper::Request<hyper::Body>| match req.version() {
Version::HTTP_11 | Version::HTTP_10 => Either::Left( Version::HTTP_11 | Version::HTTP_10 => Either::Left(
+1 -4
View File
@@ -96,9 +96,7 @@ impl Echo for MyEcho {
async fn main() -> Result<(), Box<dyn std::error::Error>> { async fn main() -> Result<(), Box<dyn std::error::Error>> {
let addr = "[::1]:50051".parse().unwrap(); let addr = "[::1]:50051".parse().unwrap();
//println!("GreeterServer listening on {}", addr); let mut warp = warp::service(warp::path("hello").map(|| "hello, world!"));
let warp = warp::service(warp::path("hello").map(|| "hello, world!"));
Server::bind(&addr) Server::bind(&addr)
.serve(make_service_fn(move |_| { .serve(make_service_fn(move |_| {
@@ -110,7 +108,6 @@ async fn main() -> Result<(), Box<dyn std::error::Error>> {
.add_service(echo) .add_service(echo)
.into_service(); .into_service();
let mut warp = warp.clone();
future::ok::<_, Infallible>(tower::service_fn( future::ok::<_, Infallible>(tower::service_fn(
move |req: hyper::Request<hyper::Body>| match req.version() { move |req: hyper::Request<hyper::Body>| match req.version() {
Version::HTTP_11 | Version::HTTP_10 => Either::Left( Version::HTTP_11 | Version::HTTP_10 => Either::Left(
-12
View File
@@ -1,5 +1,4 @@
use std::collections::HashMap; use std::collections::HashMap;
use std::hash::{Hash, Hasher};
use std::pin::Pin; use std::pin::Pin;
use std::sync::Arc; use std::sync::Arc;
use std::time::Instant; use std::time::Instant;
@@ -150,17 +149,6 @@ async fn main() -> Result<(), Box<dyn std::error::Error>> {
Ok(()) Ok(())
} }
// Implement hash for Point
impl Hash for Point {
fn hash<H>(&self, state: &mut H)
where
H: Hasher,
{
self.latitude.hash(state);
self.longitude.hash(state);
}
}
impl Eq for Point {} impl Eq for Point {}
fn in_range(point: &Point, rect: &Rectangle) -> bool { fn in_range(point: &Point, rect: &Rectangle) -> bool {
-3
View File
@@ -251,7 +251,6 @@ pub async fn status_code_and_message(client: &mut TestClient, assertions: &mut V
response_status: Some(EchoStatus { response_status: Some(EchoStatus {
code: 2, code: 2,
message: TEST_STATUS_MESSAGE.to_string(), message: TEST_STATUS_MESSAGE.to_string(),
..Default::default()
}), }),
..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 { response_status: Some(EchoStatus {
code: 2, code: 2,
message: TEST_STATUS_MESSAGE.to_string(), message: TEST_STATUS_MESSAGE.to_string(),
..Default::default()
}), }),
..Default::default() ..Default::default()
}; };
@@ -286,7 +284,6 @@ pub async fn special_status_message(client: &mut TestClient, assertions: &mut Ve
response_status: Some(EchoStatus { response_status: Some(EchoStatus {
code: 2, code: 2,
message: SPECIAL_TEST_STATUS_MESSAGE.to_string(), message: SPECIAL_TEST_STATUS_MESSAGE.to_string(),
..Default::default()
}), }),
..Default::default() ..Default::default()
}; };
+1 -1
View File
@@ -50,7 +50,7 @@ fn response_length(response: &pb::StreamingOutputCallResponse) -> i32 {
} }
} }
fn response_lengths(responses: &Vec<pb::StreamingOutputCallResponse>) -> Vec<i32> { fn response_lengths(responses: &[pb::StreamingOutputCallResponse]) -> Vec<i32> {
responses.iter().map(&response_length).collect() responses.iter().map(&response_length).collect()
} }
+2 -3
View File
@@ -21,6 +21,7 @@ type Streaming<T> = Request<tonic::Streaming<T>>;
type Stream<T> = Pin< type Stream<T> = Pin<
Box<dyn futures_core::Stream<Item = std::result::Result<T, Status>> + Send + Sync + 'static>, Box<dyn futures_core::Stream<Item = std::result::Result<T, Status>> + Send + Sync + 'static>,
>; >;
type BoxFuture<T, E> = Pin<Box<dyn Future<Output = std::result::Result<T, E>> + Send + 'static>>;
#[tonic::async_trait] #[tonic::async_trait]
impl pb::test_service_server::TestService for TestService { impl pb::test_service_server::TestService for TestService {
@@ -187,9 +188,7 @@ where
{ {
type Response = S::Response; type Response = S::Response;
type Error = S::Error; type Error = S::Error;
type Future = Pin< type Future = BoxFuture<Self::Response, Self::Error>;
Box<dyn Future<Output = std::result::Result<Self::Response, Self::Error>> + Send + 'static>,
>;
fn poll_ready(&mut self, _cx: &mut Context<'_>) -> Poll<std::result::Result<(), Self::Error>> { fn poll_ready(&mut self, _cx: &mut Context<'_>) -> Poll<std::result::Result<(), Self::Error>> {
Ok(()).into() Ok(()).into()
+1 -1
View File
@@ -39,7 +39,7 @@ pub fn compile_protos(proto: impl AsRef<Path>) -> io::Result<()> {
Ok(()) Ok(())
} }
const PROST_CODEC_PATH: &'static str = "tonic::codec::ProstCodec"; const PROST_CODEC_PATH: &str = "tonic::codec::ProstCodec";
impl crate::Service for Service { impl crate::Service for Service {
const CODEC_PATH: &'static str = PROST_CODEC_PATH; const CODEC_PATH: &'static str = PROST_CODEC_PATH;
+6 -8
View File
@@ -134,7 +134,7 @@ impl<T> Streaming<T> {
} }
// To fetch the trailers we must clear the body and drop it. // 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 // Since we call poll_trailers internally on poll_next we need to
// check if it got cached again. // check if it got cached again.
@@ -219,9 +219,8 @@ impl<T> Stream for Streaming<T> {
// FIXME: implement the ability to poll trailers when we _know_ that // FIXME: implement the ability to poll trailers when we _know_ that
// the consumer of this stream will only poll for the first message. // the consumer of this stream will only poll for the first message.
// This means we skip the poll_trailers step. // This means we skip the poll_trailers step.
match self.decode_chunk()? { if let Some(item) = self.decode_chunk()? {
Some(item) => return Poll::Ready(Some(Ok(item))), return Poll::Ready(Some(Ok(item)));
None => (),
} }
let chunk = match ready!(Pin::new(&mut self.body).poll_data(cx)) { let chunk = match ready!(Pin::new(&mut self.body).poll_data(cx)) {
@@ -230,8 +229,7 @@ impl<T> Stream for Streaming<T> {
let err: crate::Error = e.into(); let err: crate::Error = e.into();
debug!("decoder inner stream error: {:?}", err); debug!("decoder inner stream error: {:?}", err);
let status = Status::from_error(&*err); let status = Status::from_error(&*err);
Err(status)?; return Poll::Ready(Some(Err(status)));
break;
} }
None => None, None => None,
}; };
@@ -252,10 +250,10 @@ impl<T> Stream for Streaming<T> {
// FIXME: improve buf usage. // FIXME: improve buf usage.
if self.buf.has_remaining() { if self.buf.has_remaining() {
trace!("unexpected EOF decoding stream"); trace!("unexpected EOF decoding stream");
Err(Status::new( return Poll::Ready(Some(Err(Status::new(
Code::Internal, Code::Internal,
"Unexpected EOF decoding stream.".to_string(), "Unexpected EOF decoding stream.".to_string(),
))?; ))));
} else { } else {
break; break;
} }
+1 -1
View File
@@ -35,7 +35,7 @@ where
T::Item: Send + Sync, T::Item: Send + Sync,
U: Stream<Item = T::Item> + Send + Sync + 'static, U: Stream<Item = T::Item> + 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) EncodeBody::new_client(stream)
} }
+4 -1
View File
@@ -1,6 +1,9 @@
use crate::{Request, Status}; use crate::{Request, Status};
use std::{fmt, sync::Arc}; use std::{fmt, sync::Arc};
type InterceptorFn =
Arc<dyn Fn(Request<()>) -> Result<Request<()>, Status> + Send + Sync + 'static>;
/// Represents a gRPC interceptor. /// Represents a gRPC interceptor.
/// ///
/// gRPC interceptors are similar to middleware but have much less /// 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. /// features to the body of the request, going through the `tower` abstraction is recommended.
#[derive(Clone)] #[derive(Clone)]
pub struct Interceptor { pub struct Interceptor {
f: Arc<dyn Fn(Request<()>) -> Result<Request<()>, Status> + Send + Sync + 'static>, f: InterceptorFn,
} }
impl Interceptor { impl Interceptor {
+3 -2
View File
@@ -505,11 +505,12 @@ impl Status {
Status { Status {
code, code,
message: message.into(), message: message.into(),
details: details, details,
metadata: metadata, metadata,
} }
} }
#[allow(clippy::wrong_self_convention)]
/// Build an `http::Response` from the given `Status`. /// Build an `http::Response` from the given `Status`.
pub fn to_http(self) -> http::Response<BoxBody> { pub fn to_http(self) -> http::Response<BoxBody> {
let (mut parts, _body) = http::Response::new(()).into_parts(); let (mut parts, _body) = http::Response::new(()).into_parts();
+1 -1
View File
@@ -192,7 +192,7 @@ impl Endpoint {
tls: Some( tls: Some(
tls_config tls_config
.tls_connector(self.uri.clone()) .tls_connector(self.uri.clone())
.map_err(|e| Error::from_source(e))?, .map_err(Error::from_source)?,
), ),
..self ..self
}) })
+2 -2
View File
@@ -183,7 +183,7 @@ impl GrpcService<BoxBody> for Channel {
type Future = ResponseFuture; type Future = ResponseFuture;
fn poll_ready(&mut self, cx: &mut Context<'_>) -> Poll<Result<(), Self::Error>> { fn poll_ready(&mut self, cx: &mut Context<'_>) -> Poll<Result<(), Self::Error>> {
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<BoxBody>) -> Self::Future { fn call(&mut self, request: Request<BoxBody>) -> Self::Future {
@@ -197,7 +197,7 @@ impl Future for ResponseFuture {
fn poll(mut self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<Self::Output> { fn poll(mut self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<Self::Output> {
let val = futures_util::ready!(Pin::new(&mut self.inner).poll(cx)) 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() Ok(val).into()
} }
} }
+2 -2
View File
@@ -9,7 +9,7 @@ use std::fmt;
/// Configures TLS settings for endpoints. /// Configures TLS settings for endpoints.
#[cfg(feature = "tls")] #[cfg(feature = "tls")]
#[cfg_attr(docsrs, doc(cfg(feature = "tls")))] #[cfg_attr(docsrs, doc(cfg(feature = "tls")))]
#[derive(Clone)] #[derive(Clone, Default)]
pub struct ClientTlsConfig { pub struct ClientTlsConfig {
domain: Option<String>, domain: Option<String>,
cert: Option<Certificate>, cert: Option<Certificate>,
@@ -80,7 +80,7 @@ impl ClientTlsConfig {
pub(crate) fn tls_connector(&self, uri: Uri) -> Result<TlsConnector, crate::Error> { pub(crate) fn tls_connector(&self, uri: Uri) -> Result<TlsConnector, crate::Error> {
let domain = match &self.domain { 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(), Some(domain) => domain.clone(),
}; };
match &self.rustls_raw { match &self.rustls_raw {
+3
View File
@@ -107,3 +107,6 @@ pub use self::channel::ClientTlsConfig;
#[cfg(feature = "tls")] #[cfg(feature = "tls")]
#[cfg_attr(docsrs, doc(cfg(feature = "tls")))] #[cfg_attr(docsrs, doc(cfg(feature = "tls")))]
pub use self::server::ServerTlsConfig; pub use self::server::ServerTlsConfig;
type BoxFuture<T, E> =
std::pin::Pin<Box<dyn std::future::Future<Output = Result<T, E>> + Send + 'static>>;
+13 -12
View File
@@ -21,7 +21,10 @@ pub(crate) use incoming::TlsStream;
#[cfg(feature = "tls")] #[cfg(feature = "tls")]
use crate::transport::Error; 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 crate::{body::BoxBody, request::ConnectionInfo};
use futures_core::Stream; use futures_core::Stream;
use futures_util::{ use futures_util::{
@@ -34,7 +37,6 @@ use std::{
fmt, fmt,
future::Future, future::Future,
net::SocketAddr, net::SocketAddr,
pin::Pin,
sync::Arc, sync::Arc,
task::{Context, Poll}, task::{Context, Poll},
time::Duration, time::Duration,
@@ -98,11 +100,13 @@ where
B::Error: Into<crate::Error> + Send, B::Error: Into<crate::Error> + Send,
{ {
type Response = Response<BoxBody>; type Response = Response<BoxBody>;
type Error = crate::Error;
#[allow(clippy::type_complexity)]
type Future = FutureEither< type Future = FutureEither<
MapErr<A::Future, fn(A::Error) -> crate::Error>, MapErr<A::Future, fn(A::Error) -> crate::Error>,
MapErr<B::Future, fn(B::Error) -> crate::Error>, MapErr<B::Future, fn(B::Error) -> crate::Error>,
>; >;
type Error = crate::Error;
fn poll_ready(&mut self, _: &mut Context<'_>) -> Poll<Result<(), Self::Error>> { fn poll_ready(&mut self, _: &mut Context<'_>) -> Poll<Result<(), Self::Error>> {
Poll::Ready(Ok(())) Poll::Ready(Ok(()))
@@ -143,11 +147,7 @@ impl Server {
#[cfg_attr(docsrs, doc(cfg(feature = "tls")))] #[cfg_attr(docsrs, doc(cfg(feature = "tls")))]
pub fn tls_config(self, tls_config: ServerTlsConfig) -> Result<Self, Error> { pub fn tls_config(self, tls_config: ServerTlsConfig) -> Result<Self, Error> {
Ok(Server { Ok(Server {
tls: Some( tls: Some(tls_config.tls_acceptor().map_err(Error::from_source)?),
tls_config
.tls_acceptor()
.map_err(|e| Error::from_source(e))?,
),
..self ..self
}) })
} }
@@ -320,7 +320,7 @@ impl Server {
let init_connection_window_size = self.init_connection_window_size; let init_connection_window_size = self.init_connection_window_size;
let init_stream_window_size = self.init_stream_window_size; let init_stream_window_size = self.init_stream_window_size;
let max_concurrent_streams = self.max_concurrent_streams; 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 tcp = incoming::tcp_incoming(incoming, self);
let incoming = accept::from_stream::<_, _, crate::Error>(tcp); let incoming = accept::from_stream::<_, _, crate::Error>(tcp);
@@ -538,6 +538,8 @@ where
{ {
type Response = Response<BoxBody>; type Response = Response<BoxBody>;
type Error = crate::Error; type Error = crate::Error;
#[allow(clippy::type_complexity)]
type Future = MapErr<Instrumented<S::Future>, fn(S::Error) -> crate::Error>; type Future = MapErr<Instrumented<S::Future>, fn(S::Error) -> crate::Error>;
fn poll_ready(&mut self, cx: &mut Context<'_>) -> Poll<Result<(), Self::Error>> { fn poll_ready(&mut self, cx: &mut Context<'_>) -> Poll<Result<(), Self::Error>> {
@@ -578,8 +580,7 @@ where
{ {
type Response = BoxService; type Response = BoxService;
type Error = crate::Error; type Error = crate::Error;
type Future = type Future = BoxFuture<Self::Response, Self::Error>;
Pin<Box<dyn Future<Output = Result<Self::Response, Self::Error>> + Send + 'static>>;
fn poll_ready(&mut self, _cx: &mut Context<'_>) -> Poll<Result<(), Self::Error>> { fn poll_ready(&mut self, _cx: &mut Context<'_>) -> Poll<Result<(), Self::Error>> {
Ok(()).into() Ok(()).into()
@@ -593,7 +594,7 @@ where
let svc = self.inner.clone(); let svc = self.inner.clone();
let concurrency_limit = self.concurrency_limit; let concurrency_limit = self.concurrency_limit;
let timeout = self.timeout.clone(); let timeout = self.timeout;
let span = self.span.clone(); let span = self.span.clone();
Box::pin(async move { Box::pin(async move {
+1 -1
View File
@@ -7,7 +7,7 @@ use std::fmt;
/// Configures TLS settings for servers. /// Configures TLS settings for servers.
#[cfg(feature = "tls")] #[cfg(feature = "tls")]
#[cfg_attr(docsrs, doc(cfg(feature = "tls")))] #[cfg_attr(docsrs, doc(cfg(feature = "tls")))]
#[derive(Clone)] #[derive(Clone, Default)]
pub struct ServerTlsConfig { pub struct ServerTlsConfig {
identity: Option<Identity>, identity: Option<Identity>,
client_ca_root: Option<Certificate>, client_ca_root: Option<Certificate>,
+2 -2
View File
@@ -35,8 +35,8 @@ where
let set_uri = self.origin.clone().into_parts(); let set_uri = self.origin.clone().into_parts();
// Update the URI parts, setting hte scheme and authority // Update the URI parts, setting hte scheme and authority
uri.scheme = Some(set_uri.scheme.expect("expected scheme").clone()); uri.scheme = Some(set_uri.scheme.expect("expected scheme"));
uri.authority = Some(set_uri.authority.expect("expected authority").clone()); uri.authority = Some(set_uri.authority.expect("expected authority"));
// Update the the request URI // Update the the request URI
head.uri = http::Uri::from_parts(uri).expect("valid uri"); head.uri = http::Uri::from_parts(uri).expect("valid uri");
+2 -7
View File
@@ -1,3 +1,4 @@
use super::super::BoxFuture;
use super::{layer::ServiceBuilderExt, reconnect::Reconnect, AddOrigin, UserAgent}; use super::{layer::ServiceBuilderExt, reconnect::Reconnect, AddOrigin, UserAgent};
use crate::{body::BoxBody, transport::Endpoint}; use crate::{body::BoxBody, transport::Endpoint};
use http::Uri; use http::Uri;
@@ -6,8 +7,6 @@ use hyper::client::connect::Connection as HyperConnection;
use hyper::client::service::Connect as HyperConnect; use hyper::client::service::Connect as HyperConnect;
use std::{ use std::{
fmt, fmt,
future::Future,
pin::Pin,
task::{Context, Poll}, task::{Context, Poll},
}; };
use tokio::io::{AsyncRead, AsyncWrite}; use tokio::io::{AsyncRead, AsyncWrite};
@@ -51,8 +50,6 @@ impl Connection {
settings.http2_keep_alive_while_idle(val); settings.http2_keep_alive_while_idle(val);
} }
let settings = settings.clone();
let stack = ServiceBuilder::new() let stack = ServiceBuilder::new()
.layer_fn(|s| AddOrigin::new(s, endpoint.uri.clone())) .layer_fn(|s| AddOrigin::new(s, endpoint.uri.clone()))
.layer_fn(|s| UserAgent::new(s, endpoint.user_agent.clone())) .layer_fn(|s| UserAgent::new(s, endpoint.user_agent.clone()))
@@ -95,9 +92,7 @@ impl Connection {
impl Service<Request> for Connection { impl Service<Request> for Connection {
type Response = Response; type Response = Response;
type Error = crate::Error; type Error = crate::Error;
type Future = BoxFuture<Self::Response, Self::Error>;
type Future =
Pin<Box<dyn Future<Output = Result<Self::Response, Self::Error>> + Send + 'static>>;
fn poll_ready(&mut self, cx: &mut Context<'_>) -> Poll<Result<(), Self::Error>> { fn poll_ready(&mut self, cx: &mut Context<'_>) -> Poll<Result<(), Self::Error>> {
Service::poll_ready(&mut self.inner, cx).map_err(Into::into) Service::poll_ready(&mut self.inner, cx).map_err(Into::into)
+2 -5
View File
@@ -1,9 +1,8 @@
use super::super::BoxFuture;
use super::io::BoxedIo; use super::io::BoxedIo;
#[cfg(feature = "tls")] #[cfg(feature = "tls")]
use super::tls::TlsConnector; use super::tls::TlsConnector;
use http::Uri; use http::Uri;
use std::future::Future;
use std::pin::Pin;
use std::task::{Context, Poll}; use std::task::{Context, Poll};
use tower_make::MakeConnection; use tower_make::MakeConnection;
use tower_service::Service; use tower_service::Service;
@@ -48,9 +47,7 @@ where
{ {
type Response = BoxedIo; type Response = BoxedIo;
type Error = crate::Error; type Error = crate::Error;
type Future = BoxFuture<Self::Response, Self::Error>;
type Future =
Pin<Box<dyn Future<Output = Result<Self::Response, Self::Error>> + Send + 'static>>;
fn poll_ready(&mut self, cx: &mut Context<'_>) -> Poll<Result<(), Self::Error>> { fn poll_ready(&mut self, cx: &mut Context<'_>) -> Poll<Result<(), Self::Error>> {
MakeConnection::poll_ready(&mut self.inner, cx).map_err(Into::into) MakeConnection::poll_ready(&mut self.inner, cx).map_err(Into::into)
+5 -6
View File
@@ -1,4 +1,4 @@
use super::super::service; use super::super::{service, BoxFuture};
use super::connection::Connection; use super::connection::Connection;
use crate::transport::Endpoint; use crate::transport::Endpoint;
@@ -12,12 +12,11 @@ use tokio::{stream::Stream, sync::mpsc::Receiver};
use tower::discover::{Change, Discover}; use tower::discover::{Change, Discover};
type DiscoverResult<K, S, E> = Result<Change<K, S>, E>;
pub(crate) struct DynamicServiceStream<K: Hash + Eq + Clone> { pub(crate) struct DynamicServiceStream<K: Hash + Eq + Clone> {
changes: Receiver<Change<K, Endpoint>>, changes: Receiver<Change<K, Endpoint>>,
connecting: Option<( connecting: Option<(K, BoxFuture<Connection, crate::Error>)>,
K,
Pin<Box<dyn Future<Output = Result<Connection, crate::Error>> + Send + 'static>>,
)>,
} }
impl<K: Hash + Eq + Clone> DynamicServiceStream<K> { impl<K: Hash + Eq + Clone> DynamicServiceStream<K> {
@@ -37,7 +36,7 @@ impl<K: Hash + Eq + Clone> Discover for DynamicServiceStream<K> {
fn poll_discover( fn poll_discover(
mut self: Pin<&mut Self>, mut self: Pin<&mut Self>,
cx: &mut Context<'_>, cx: &mut Context<'_>,
) -> Poll<Result<Change<Self::Key, Self::Service>, Self::Error>> { ) -> Poll<DiscoverResult<Self::Key, Self::Service, Self::Error>> {
loop { loop {
if let Some((key, connecting)) = &mut self.connecting { if let Some((key, connecting)) = &mut self.connecting {
let svc = futures_core::ready!(Pin::new(connecting).poll(cx))?; let svc = futures_core::ready!(Pin::new(connecting).poll(cx))?;
+1 -1
View File
@@ -94,7 +94,7 @@ where
if !(self.has_been_connected || self.is_lazy) { if !(self.has_been_connected || self.is_lazy) {
return Poll::Ready(Err(e.into())); return Poll::Ready(Err(e.into()));
} else { } else {
self.error = Some(e.into()); self.error = Some(e);
break; break;
} }
} }
+2
View File
@@ -94,6 +94,8 @@ where
{ {
type Response = A::Response; type Response = A::Response;
type Error = crate::Error; type Error = crate::Error;
#[allow(clippy::type_complexity)]
type Future = Either< type Future = Either<
MapErr<A::Future, fn(A::Error) -> crate::Error>, MapErr<A::Future, fn(A::Error) -> crate::Error>,
MapErr<B::Future, fn(B::Error) -> crate::Error>, MapErr<B::Future, fn(B::Error) -> crate::Error>,
+5 -6
View File
@@ -133,10 +133,9 @@ impl TlsAcceptor {
let mut cert = std::io::Cursor::new(&cert.pem[..]); let mut cert = std::io::Cursor::new(&cert.pem[..]);
let mut client_root_cert_store = tokio_rustls::rustls::RootCertStore::empty(); let mut client_root_cert_store = tokio_rustls::rustls::RootCertStore::empty();
match client_root_cert_store.add_pem_file(&mut cert) { if client_root_cert_store.add_pem_file(&mut cert).is_err() {
Err(_) => return Err(Box::new(TlsError::CertificateParseError)), return Err(Box::new(TlsError::CertificateParseError));
_ => (), }
};
let client_auth = let client_auth =
tokio_rustls::rustls::AllowAnyAuthenticatedClient::new(client_root_cert_store); tokio_rustls::rustls::AllowAnyAuthenticatedClient::new(client_root_cert_store);
@@ -204,7 +203,7 @@ mod rustls_keys {
) -> Result<PrivateKey, crate::Error> { ) -> Result<PrivateKey, crate::Error> {
// First attempt to load the private key assuming it is PKCS8-encoded // First attempt to load the private key assuming it is PKCS8-encoded
if let Ok(mut keys) = pemfile::pkcs8_private_keys(&mut cursor) { if let Ok(mut keys) = pemfile::pkcs8_private_keys(&mut cursor) {
if keys.len() > 0 { if !keys.is_empty() {
return Ok(keys.remove(0)); return Ok(keys.remove(0));
} }
} }
@@ -212,7 +211,7 @@ mod rustls_keys {
// If it not, try loading the private key as an RSA key // If it not, try loading the private key as an RSA key
cursor.set_position(0); cursor.set_position(0);
if let Ok(mut keys) = pemfile::rsa_private_keys(&mut cursor) { if let Ok(mut keys) = pemfile::rsa_private_keys(&mut cursor) {
if keys.len() > 0 { if !keys.is_empty() {
return Ok(keys.remove(0)); return Ok(keys.remove(0));
} }
} }
+1 -1
View File
@@ -20,7 +20,7 @@ impl<T> UserAgent<T> {
buf.extend(TONIC_USER_AGENT.as_bytes()); buf.extend(TONIC_USER_AGENT.as_bytes());
HeaderValue::from_bytes(&buf).expect("user-agent should be valid") 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 } Self { inner, user_agent }
} }