Skip to content

Commit

Permalink
chore: Small refactoring (#1739)
Browse files Browse the repository at this point in the history
* chore: Refactor redundant pattern match

* chore: Refactor redundant closure style

* chore(examples): Remove redundant type converting

* chore(examples): Use rustls_pemfile::private_key to parse private key

* chore(examples): Remove redundant CertificateDer::to_owned call

* chore(examples): Create Routes directly
  • Loading branch information
tottoto authored Jun 20, 2024
1 parent 606cc71 commit 34b863b
Show file tree
Hide file tree
Showing 5 changed files with 17 additions and 43 deletions.
33 changes: 8 additions & 25 deletions examples/src/tls_rustls/server.rs
Original file line number Diff line number Diff line change
Expand Up @@ -9,52 +9,35 @@ use pb::{EchoRequest, EchoResponse};
use std::sync::Arc;
use tokio::net::TcpListener;
use tokio_rustls::{
rustls::{
pki_types::{CertificateDer, PrivatePkcs8KeyDer},
ServerConfig,
},
rustls::{pki_types::CertificateDer, ServerConfig},
TlsAcceptor,
};
use tonic::{body::BoxBody, transport::Server, Request, Response, Status};
use tonic::{body::BoxBody, service::Routes, Request, Response, Status};
use tower::{BoxError, ServiceExt};
use tower_http::ServiceBuilderExt;

#[tokio::main]
async fn main() -> Result<(), Box<dyn std::error::Error>> {
let data_dir = std::path::PathBuf::from_iter([std::env!("CARGO_MANIFEST_DIR"), "data"]);
let certs: Vec<CertificateDer<'static>> = {
let certs = {
let fd = std::fs::File::open(data_dir.join("tls/server.pem"))?;
let mut buf = std::io::BufReader::new(&fd);
rustls_pemfile::certs(&mut buf)
.into_iter()
.map(|res| res.map(|cert| cert.to_owned()))
.collect::<Result<Vec<_>, _>>()?
rustls_pemfile::certs(&mut buf).collect::<Result<Vec<_>, _>>()?
};
let key: PrivatePkcs8KeyDer<'static> = {
let key = {
let fd = std::fs::File::open(data_dir.join("tls/server.key"))?;
let mut buf = std::io::BufReader::new(&fd);
let key = rustls_pemfile::pkcs8_private_keys(&mut buf)
.into_iter()
.next()
.unwrap()?
.clone_key();

key

// let key = std::fs::read(data_dir.join("tls/server.key"))?;
// PrivateKey(key)
rustls_pemfile::private_key(&mut buf)?.unwrap()
};

let mut tls = ServerConfig::builder()
.with_no_client_auth()
.with_single_cert(certs, key.into())?;
.with_single_cert(certs, key)?;
tls.alpn_protocols = vec![b"h2".to_vec()];

let server = EchoServer::default();

let svc = Server::builder()
.add_service(pb::echo_server::EchoServer::new(server))
.into_service();
let svc = Routes::new(pb::echo_server::EchoServer::new(server));

let http = Builder::new(TokioExecutor::new());

Expand Down
12 changes: 5 additions & 7 deletions tonic/src/codec/decode.rs
Original file line number Diff line number Diff line change
Expand Up @@ -291,13 +291,11 @@ impl StreamingInner {

fn response(&mut self) -> Result<(), Status> {
if let Direction::Response(status) = self.direction {
if let Err(e) = crate::status::infer_grpc_status(self.trailers.as_ref(), status) {
if let Some(e) = e {
// If the trailers contain a grpc-status, then we should return that as the error
// and otherwise stop the stream (by taking the error state)
self.trailers.take();
return Err(e);
}
if let Err(Some(e)) = crate::status::infer_grpc_status(self.trailers.as_ref(), status) {
// If the trailers contain a grpc-status, then we should return that as the error
// and otherwise stop the stream (by taking the error state)
self.trailers.take();
return Err(e);
}
}
Ok(())
Expand Down
7 changes: 2 additions & 5 deletions tonic/src/service/router.rs
Original file line number Diff line number Diff line change
Expand Up @@ -168,10 +168,7 @@ where
}

fn call(&mut self, req: Request<axum::body::Body>) -> Self::Future {
let fut = self.service.call(req.map(|body| boxed(body)));
Box::pin(async move {
fut.await
.map(|res| res.map(|body| axum::body::Body::new(body)))
})
let fut = self.service.call(req.map(boxed));
Box::pin(async move { fut.await.map(|res| res.map(axum::body::Body::new)) })
}
}
6 changes: 1 addition & 5 deletions tonic/src/transport/channel/service/connection.rs
Original file line number Diff line number Diff line change
Expand Up @@ -147,11 +147,7 @@ impl tower::Service<http::Request<BoxBody>> for SendRequest {
fn call(&mut self, req: Request) -> Self::Future {
let fut = self.inner.send_request(req);

Box::pin(async move {
fut.await
.map_err(Into::into)
.map(|res| res.map(|body| boxed(body)))
})
Box::pin(async move { fut.await.map_err(Into::into).map(|res| res.map(boxed)) })
}
}

Expand Down
2 changes: 1 addition & 1 deletion tonic/src/transport/channel/service/connector.rs
Original file line number Diff line number Diff line change
Expand Up @@ -118,7 +118,7 @@ where
Ok::<_, crate::Error>(BoxedIo::new(io))
}
.await
.map_err(|err| ConnectError(From::from(err)))
.map_err(ConnectError)
})
}
}
Expand Down

0 comments on commit 34b863b

Please sign in to comment.