From bc9357decfe9bb4a10465e8a921bcb602aef7e86 Mon Sep 17 00:00:00 2001 From: tottoto Date: Thu, 21 Dec 2023 00:27:35 +0900 Subject: [PATCH] feat(transport): Unify API for setting service to be via Routes instance --- examples/src/authentication/server.rs | 9 +- examples/src/autoreload/server.rs | 7 +- examples/src/blocking/server.rs | 9 +- examples/src/cancellation/server.rs | 11 ++- examples/src/compression/server.rs | 12 ++- examples/src/dynamic/server.rs | 47 ++++------ examples/src/dynamic_load_balance/server.rs | 13 ++- examples/src/grpc-web/server.rs | 9 +- examples/src/h2c/server.rs | 5 +- examples/src/health/server.rs | 13 +-- examples/src/helloworld/server.rs | 10 +- examples/src/hyper_warp_multiplex/server.rs | 7 +- examples/src/interceptor/server.rs | 4 +- examples/src/json-codec/server.rs | 14 +-- examples/src/load_balance/server.rs | 13 ++- examples/src/mock/mock.rs | 7 +- examples/src/multiplex/server.rs | 12 ++- examples/src/optional/server.rs | 14 ++- examples/src/reflection/server.rs | 12 ++- examples/src/richer-error/server.rs | 14 +-- examples/src/richer-error/server_vec.rs | 14 +-- examples/src/routeguide/server.rs | 4 +- examples/src/streaming/server.rs | 11 ++- examples/src/timeout/server.rs | 10 +- examples/src/tls/server.rs | 8 +- examples/src/tls_client_auth/server.rs | 7 +- examples/src/tls_rustls/server.rs | 10 +- examples/src/tower/server.rs | 10 +- examples/src/tracing/server.rs | 10 +- examples/src/uds/server.rs | 8 +- interop/src/bin/server.rs | 8 +- tests/compression/src/bidirectional_stream.rs | 5 +- tests/compression/src/client_stream.rs | 14 ++- tests/compression/src/compressing_request.rs | 14 ++- tests/compression/src/compressing_response.rs | 26 ++++-- tests/compression/src/server_stream.rs | 10 +- tests/default_stubs/src/test_defaults.rs | 9 +- tests/integration_tests/tests/client_layer.rs | 5 +- .../tests/complex_tower_middleware.rs | 8 +- tests/integration_tests/tests/connect_info.rs | 19 +++- tests/integration_tests/tests/connection.rs | 8 +- tests/integration_tests/tests/extensions.rs | 8 +- tests/integration_tests/tests/interceptor.rs | 5 +- .../tests/max_message_size.rs | 9 +- tests/integration_tests/tests/origin.rs | 5 +- .../integration_tests/tests/routes_builder.rs | 10 +- tests/integration_tests/tests/status.rs | 11 ++- tests/integration_tests/tests/streams.rs | 8 +- tests/integration_tests/tests/timeout.rs | 8 +- tests/integration_tests/tests/user_agent.rs | 5 +- tonic-reflection/tests/server.rs | 8 +- tonic-web/tests/integration/tests/grpc.rs | 8 +- tonic-web/tests/integration/tests/grpc_web.rs | 5 +- tonic/src/transport/server/incoming.rs | 5 +- tonic/src/transport/server/mod.rs | 91 +------------------ tonic/src/transport/service/router.rs | 82 +++++++---------- 56 files changed, 382 insertions(+), 346 deletions(-) diff --git a/examples/src/authentication/server.rs b/examples/src/authentication/server.rs index d0a59cbc1..fa1c54171 100644 --- a/examples/src/authentication/server.rs +++ b/examples/src/authentication/server.rs @@ -3,7 +3,11 @@ pub mod pb { } use pb::{EchoRequest, EchoResponse}; -use tonic::{metadata::MetadataValue, transport::Server, Request, Response, Status}; +use tonic::{ + metadata::MetadataValue, + transport::{server::Routes, Server}, + Request, Response, Status, +}; type EchoResult = Result, Status>; @@ -24,8 +28,9 @@ async fn main() -> Result<(), Box> { let server = EchoServer::default(); let svc = pb::echo_server::EchoServer::with_interceptor(server, check_auth); + let routes = Routes::builder().add_service(svc).build(); - Server::builder().add_service(svc).serve(addr).await?; + Server::builder().add_routes(routes).serve(addr).await?; Ok(()) } diff --git a/examples/src/autoreload/server.rs b/examples/src/autoreload/server.rs index a181f75ec..0e839544d 100644 --- a/examples/src/autoreload/server.rs +++ b/examples/src/autoreload/server.rs @@ -1,3 +1,4 @@ +use tonic::transport::server::Routes; use tonic::{transport::Server, Request, Response, Status}; use hello_world::greeter_server::{Greeter, GreeterServer}; @@ -28,11 +29,13 @@ impl Greeter for MyGreeter { #[tokio::main] async fn main() -> Result<(), Box> { let addr = "[::1]:50051".parse().unwrap(); - let greeter = MyGreeter::default(); + let routes = Routes::builder() + .add_service(GreeterServer::new(MyGreeter::default())) + .build(); println!("GreeterServer listening on {}", addr); - let server = Server::builder().add_service(GreeterServer::new(greeter)); + let server = Server::builder().add_routes(routes); match listenfd::ListenFd::from_env().take_tcp_listener(0)? { Some(listener) => { diff --git a/examples/src/blocking/server.rs b/examples/src/blocking/server.rs index d7ef6177b..0c3e949c4 100644 --- a/examples/src/blocking/server.rs +++ b/examples/src/blocking/server.rs @@ -1,3 +1,4 @@ +use tonic::transport::server::Routes; use tonic::{transport::Server, Request, Response, Status}; use hello_world::greeter_server::{Greeter, GreeterServer}; @@ -30,12 +31,12 @@ impl Greeter for MyGreeter { fn main() { let addr = "[::1]:50051".parse().unwrap(); - let greeter = MyGreeter::default(); + let routes = Routes::builder() + .add_service(GreeterServer::new(MyGreeter::default())) + .build(); let rt = Runtime::new().expect("failed to obtain a new RunTime object"); - let server_future = Server::builder() - .add_service(GreeterServer::new(greeter)) - .serve(addr); + let server_future = Server::builder().add_routes(routes).serve(addr); rt.block_on(server_future) .expect("failed to successfully run the future on RunTime"); } diff --git a/examples/src/cancellation/server.rs b/examples/src/cancellation/server.rs index 32d93e7d7..21b44b74c 100644 --- a/examples/src/cancellation/server.rs +++ b/examples/src/cancellation/server.rs @@ -1,6 +1,7 @@ use std::future::Future; use tokio_util::sync::CancellationToken; +use tonic::transport::server::Routes; use tonic::{transport::Server, Request, Response, Status}; use hello_world::greeter_server::{Greeter, GreeterServer}; @@ -72,14 +73,14 @@ where #[tokio::main] async fn main() -> Result<(), Box> { let addr = "[::1]:50051".parse().unwrap(); - let greeter = MyGreeter::default(); + + let routes = Routes::builder() + .add_service(GreeterServer::new(MyGreeter::default())) + .build(); println!("GreeterServer listening on {}", addr); - Server::builder() - .add_service(GreeterServer::new(greeter)) - .serve(addr) - .await?; + Server::builder().add_routes(routes).serve(addr).await?; Ok(()) } diff --git a/examples/src/compression/server.rs b/examples/src/compression/server.rs index fd035d218..7afa6a7b0 100644 --- a/examples/src/compression/server.rs +++ b/examples/src/compression/server.rs @@ -1,3 +1,4 @@ +use tonic::transport::server::Routes; use tonic::{transport::Server, Request, Response, Status}; use hello_world::greeter_server::{Greeter, GreeterServer}; @@ -29,15 +30,16 @@ impl Greeter for MyGreeter { #[tokio::main] async fn main() -> Result<(), Box> { let addr = "[::1]:50051".parse().unwrap(); - let greeter = MyGreeter::default(); - println!("GreeterServer listening on {}", addr); - - let service = GreeterServer::new(greeter) + let service = GreeterServer::new(MyGreeter::default()) .send_compressed(CompressionEncoding::Gzip) .accept_compressed(CompressionEncoding::Gzip); - Server::builder().add_service(service).serve(addr).await?; + let routes = Routes::builder().add_service(service).build(); + + println!("GreeterServer listening on {}", addr); + + Server::builder().add_routes(routes).serve(addr).await?; Ok(()) } diff --git a/examples/src/dynamic/server.rs b/examples/src/dynamic/server.rs index 300ec868c..46cbd293c 100644 --- a/examples/src/dynamic/server.rs +++ b/examples/src/dynamic/server.rs @@ -1,5 +1,5 @@ use std::env; -use tonic::{transport::server::RoutesBuilder, transport::Server, Request, Response, Status}; +use tonic::{transport::server::Routes, transport::Server, Request, Response, Status}; use hello_world::greeter_server::{Greeter, GreeterServer}; use hello_world::{HelloReply, HelloRequest}; @@ -31,15 +31,6 @@ impl Echo for MyEcho { } } -fn init_echo(args: &[String], builder: &mut RoutesBuilder) { - let enabled = args.iter().any(|arg| arg.as_str() == "echo"); - if enabled { - println!("Adding Echo service..."); - let svc = EchoServer::new(MyEcho::default()); - builder.add_service(svc); - } -} - #[derive(Default)] pub struct MyGreeter {} @@ -58,31 +49,33 @@ impl Greeter for MyGreeter { } } -fn init_greeter(args: &[String], builder: &mut RoutesBuilder) { - let enabled = args.iter().any(|arg| arg.as_str() == "greeter"); - - if enabled { - println!("Adding Greeter service..."); - let svc = GreeterServer::new(MyGreeter::default()); - builder.add_service(svc); - } -} - #[tokio::main] async fn main() -> Result<(), Box> { let args: Vec = env::args().collect(); - let mut routes_builder = RoutesBuilder::default(); - init_greeter(&args, &mut routes_builder); - init_echo(&args, &mut routes_builder); + + let routes_builder = Routes::builder(); + + let routes_builder = if args.iter().any(|arg| arg.as_str() == "greeter") { + println!("Adding Greeter service..."); + routes_builder.add_service(GreeterServer::new(MyGreeter::default())) + } else { + routes_builder + }; + + let routes_builder = if args.iter().any(|arg| arg.as_str() == "echo") { + println!("Adding Echo service..."); + routes_builder.add_service(EchoServer::new(MyEcho::default())) + } else { + routes_builder + }; + + let routes = routes_builder.build(); let addr = "[::1]:50051".parse().unwrap(); println!("Grpc server listening on {}", addr); - Server::builder() - .add_routes(routes_builder.routes()) - .serve(addr) - .await?; + Server::builder().add_routes(routes).serve(addr).await?; Ok(()) } diff --git a/examples/src/dynamic_load_balance/server.rs b/examples/src/dynamic_load_balance/server.rs index 7935e1cf5..9ed1b1819 100644 --- a/examples/src/dynamic_load_balance/server.rs +++ b/examples/src/dynamic_load_balance/server.rs @@ -4,7 +4,10 @@ pub mod pb { use std::net::SocketAddr; use tokio::sync::mpsc; -use tonic::{transport::Server, Request, Response, Status}; +use tonic::{ + transport::{server::Routes, Server}, + Request, Response, Status, +}; use pb::{EchoRequest, EchoResponse}; @@ -34,10 +37,10 @@ async fn main() -> Result<(), Box> { let addr = addr.parse()?; let tx = tx.clone(); - let server = EchoServer { addr }; - let serve = Server::builder() - .add_service(pb::echo_server::EchoServer::new(server)) - .serve(addr); + let routes = Routes::builder() + .add_service(pb::echo_server::EchoServer::new(EchoServer { addr })) + .build(); + let serve = Server::builder().add_routes(routes).serve(addr); tokio::spawn(async move { if let Err(e) = serve.await { diff --git a/examples/src/grpc-web/server.rs b/examples/src/grpc-web/server.rs index 7734a7663..318c63384 100644 --- a/examples/src/grpc-web/server.rs +++ b/examples/src/grpc-web/server.rs @@ -1,3 +1,4 @@ +use tonic::transport::server::Routes; use tonic::{transport::Server, Request, Response, Status}; use hello_world::greeter_server::{Greeter, GreeterServer}; @@ -30,16 +31,16 @@ async fn main() -> Result<(), Box> { tracing_subscriber::fmt::init(); let addr = "127.0.0.1:3000".parse().unwrap(); - - let greeter = MyGreeter::default(); - let greeter = GreeterServer::new(greeter); + let routes = Routes::builder() + .add_service(GreeterServer::new(MyGreeter::default())) + .build(); println!("GreeterServer listening on {}", addr); Server::builder() // GrpcWeb is over http1 so we must enable it. .accept_http1(true) - .add_service(tonic_web::enable(greeter)) + .add_routes(routes) .serve(addr) .await?; diff --git a/examples/src/h2c/server.rs b/examples/src/h2c/server.rs index 92d08a417..ef117135a 100644 --- a/examples/src/h2c/server.rs +++ b/examples/src/h2c/server.rs @@ -1,4 +1,4 @@ -use tonic::{transport::Server, Request, Response, Status}; +use tonic::{transport::server::Routes, Request, Response, Status}; use hello_world::greeter_server::{Greeter, GreeterServer}; use hello_world::{HelloReply, HelloRequest}; @@ -33,8 +33,9 @@ async fn main() -> Result<(), Box> { println!("GreeterServer listening on {}", addr); - let svc = Server::builder() + let svc = Routes::builder() .add_service(GreeterServer::new(greeter)) + .build() .into_router(); let h2c = h2c::H2c { s: svc }; diff --git a/examples/src/health/server.rs b/examples/src/health/server.rs index 7b12e8668..ea39f6ad0 100644 --- a/examples/src/health/server.rs +++ b/examples/src/health/server.rs @@ -1,3 +1,4 @@ +use tonic::transport::server::Routes; use tonic::{transport::Server, Request, Response, Status}; use hello_world::greeter_server::{Greeter, GreeterServer}; @@ -53,15 +54,15 @@ async fn main() -> Result<(), Box> { tokio::spawn(twiddle_service_status(health_reporter.clone())); let addr = "[::1]:50051".parse().unwrap(); - let greeter = MyGreeter::default(); + + let routes = Routes::builder() + .add_service(health_service) + .add_service(GreeterServer::new(MyGreeter::default())) + .build(); println!("HealthServer + GreeterServer listening on {}", addr); - Server::builder() - .add_service(health_service) - .add_service(GreeterServer::new(greeter)) - .serve(addr) - .await?; + Server::builder().add_routes(routes).serve(addr).await?; Ok(()) } diff --git a/examples/src/helloworld/server.rs b/examples/src/helloworld/server.rs index c6398bb61..f4eb9976d 100644 --- a/examples/src/helloworld/server.rs +++ b/examples/src/helloworld/server.rs @@ -1,3 +1,4 @@ +use tonic::transport::server::Routes; use tonic::{transport::Server, Request, Response, Status}; use hello_world::greeter_server::{Greeter, GreeterServer}; @@ -28,14 +29,13 @@ impl Greeter for MyGreeter { #[tokio::main] async fn main() -> Result<(), Box> { let addr = "[::1]:50051".parse().unwrap(); - let greeter = MyGreeter::default(); + let routes = Routes::builder() + .add_service(GreeterServer::new(MyGreeter::default())) + .build(); println!("GreeterServer listening on {}", addr); - Server::builder() - .add_service(GreeterServer::new(greeter)) - .serve(addr) - .await?; + Server::builder().add_routes(routes).serve(addr).await?; Ok(()) } diff --git a/examples/src/hyper_warp_multiplex/server.rs b/examples/src/hyper_warp_multiplex/server.rs index deea8bea5..8b37bb02a 100644 --- a/examples/src/hyper_warp_multiplex/server.rs +++ b/examples/src/hyper_warp_multiplex/server.rs @@ -11,7 +11,8 @@ use std::{ pin::Pin, task::{Context, Poll}, }; -use tonic::{transport::Server as TonicServer, Request, Response, Status}; +use tonic::transport::server::Routes; +use tonic::{Request, Response, Status}; use tower::Service; use warp::Filter; @@ -75,10 +76,10 @@ async fn main() -> Result<(), Box> { let greeter = GreeterServer::new(MyGreeter::default()); let echo = EchoServer::new(MyEcho::default()); - let mut tonic = TonicServer::builder() + let mut tonic = Routes::builder() .add_service(greeter) .add_service(echo) - .into_service(); + .build(); std::future::ready(Ok::<_, Infallible>(tower::service_fn( move |req: hyper::Request| match req.version() { diff --git a/examples/src/interceptor/server.rs b/examples/src/interceptor/server.rs index 263348a6d..2fa9988fc 100644 --- a/examples/src/interceptor/server.rs +++ b/examples/src/interceptor/server.rs @@ -1,3 +1,4 @@ +use tonic::transport::server::Routes; use tonic::{transport::Server, Request, Response, Status}; use hello_world::greeter_server::{Greeter, GreeterServer}; @@ -35,10 +36,11 @@ async fn main() -> Result<(), Box> { // named interceptor that can be returned from functions or stored in // structs. let svc = GreeterServer::with_interceptor(greeter, intercept); + let routes = Routes::builder().add_service(svc).build(); println!("GreeterServer listening on {}", addr); - Server::builder().add_service(svc).serve(addr).await?; + Server::builder().add_routes(routes).serve(addr).await?; Ok(()) } diff --git a/examples/src/json-codec/server.rs b/examples/src/json-codec/server.rs index 1029b0bf9..461520695 100644 --- a/examples/src/json-codec/server.rs +++ b/examples/src/json-codec/server.rs @@ -4,7 +4,10 @@ //! in the `examples/build.rs` file. As defined there, the generated code assumes that a module //! `crate::common` exists which defines `HelloRequest`, `HelloResponse`, and `JsonCodec`. -use tonic::{transport::Server, Request, Response, Status}; +use tonic::{ + transport::{server::Routes, Server}, + Request, Response, Status, +}; pub mod common; use common::{HelloRequest, HelloResponse}; @@ -35,14 +38,13 @@ impl Greeter for MyGreeter { #[tokio::main] async fn main() -> Result<(), Box> { let addr = "[::1]:50051".parse().unwrap(); - let greeter = MyGreeter::default(); + let routes = Routes::builder() + .add_service(GreeterServer::new(MyGreeter::default())) + .build(); println!("GreeterServer listening on {}", addr); - Server::builder() - .add_service(GreeterServer::new(greeter)) - .serve(addr) - .await?; + Server::builder().add_routes(routes).serve(addr).await?; Ok(()) } diff --git a/examples/src/load_balance/server.rs b/examples/src/load_balance/server.rs index 7935e1cf5..9ed1b1819 100644 --- a/examples/src/load_balance/server.rs +++ b/examples/src/load_balance/server.rs @@ -4,7 +4,10 @@ pub mod pb { use std::net::SocketAddr; use tokio::sync::mpsc; -use tonic::{transport::Server, Request, Response, Status}; +use tonic::{ + transport::{server::Routes, Server}, + Request, Response, Status, +}; use pb::{EchoRequest, EchoResponse}; @@ -34,10 +37,10 @@ async fn main() -> Result<(), Box> { let addr = addr.parse()?; let tx = tx.clone(); - let server = EchoServer { addr }; - let serve = Server::builder() - .add_service(pb::echo_server::EchoServer::new(server)) - .serve(addr); + let routes = Routes::builder() + .add_service(pb::echo_server::EchoServer::new(EchoServer { addr })) + .build(); + let serve = Server::builder().add_routes(routes).serve(addr); tokio::spawn(async move { if let Err(e) = serve.await { diff --git a/examples/src/mock/mock.rs b/examples/src/mock/mock.rs index 0d3754921..3b8b43d30 100644 --- a/examples/src/mock/mock.rs +++ b/examples/src/mock/mock.rs @@ -1,5 +1,5 @@ use tonic::{ - transport::{Endpoint, Server, Uri}, + transport::{server::Routes, Endpoint, Server, Uri}, Request, Response, Status, }; use tower::service_fn; @@ -21,8 +21,11 @@ async fn main() -> Result<(), Box> { let greeter = MyGreeter::default(); tokio::spawn(async move { - Server::builder() + let routes = Routes::builder() .add_service(GreeterServer::new(greeter)) + .build(); + Server::builder() + .add_routes(routes) .serve_with_incoming(tokio_stream::once(Ok::<_, std::io::Error>(server))) .await }); diff --git a/examples/src/multiplex/server.rs b/examples/src/multiplex/server.rs index 9b148c861..8abe563a8 100644 --- a/examples/src/multiplex/server.rs +++ b/examples/src/multiplex/server.rs @@ -1,4 +1,7 @@ -use tonic::{transport::Server, Request, Response, Status}; +use tonic::{ + transport::{server::Routes, Server}, + Request, Response, Status, +}; pub mod hello_world { tonic::include_proto!("helloworld"); @@ -25,11 +28,12 @@ async fn main() -> Result<(), Box> { let greeter = GreeterServer::new(MyGreeter::default()); let echo = EchoServer::new(MyEcho::default()); - Server::builder() + let routes = Routes::builder() .add_service(greeter) .add_service(echo) - .serve(addr) - .await?; + .build(); + + Server::builder().add_routes(routes).serve(addr).await?; Ok(()) } diff --git a/examples/src/optional/server.rs b/examples/src/optional/server.rs index f1d4fa685..7884c04a0 100644 --- a/examples/src/optional/server.rs +++ b/examples/src/optional/server.rs @@ -1,4 +1,5 @@ use std::env; +use tonic::transport::server::Routes; use tonic::{transport::Server, Request, Response, Status}; use hello_world::greeter_server::{Greeter, GreeterServer}; @@ -42,12 +43,17 @@ async fn main() -> Result<(), Box> { None }; + let routes_builder = Routes::builder(); + let routes_builder = if let Some(svc) = optional_service { + routes_builder.add_service(svc) + } else { + routes_builder + }; + let routes = routes_builder.build(); + println!("GreeterServer listening on {}", addr); - Server::builder() - .add_optional_service(optional_service) - .serve(addr) - .await?; + Server::builder().add_routes(routes).serve(addr).await?; Ok(()) } diff --git a/examples/src/reflection/server.rs b/examples/src/reflection/server.rs index 500141fbb..f957aa30e 100644 --- a/examples/src/reflection/server.rs +++ b/examples/src/reflection/server.rs @@ -1,3 +1,4 @@ +use tonic::transport::server::Routes; use tonic::transport::Server; use tonic::{Request, Response, Status}; @@ -34,13 +35,14 @@ async fn main() -> Result<(), Box> { .unwrap(); let addr = "[::1]:50052".parse().unwrap(); - let greeter = MyGreeter::default(); + let greeter = proto::greeter_server::GreeterServer::new(MyGreeter::default()); - Server::builder() + let routes = Routes::builder() .add_service(service) - .add_service(proto::greeter_server::GreeterServer::new(greeter)) - .serve(addr) - .await?; + .add_service(greeter) + .build(); + + Server::builder().add_routes(routes).serve(addr).await?; Ok(()) } diff --git a/examples/src/richer-error/server.rs b/examples/src/richer-error/server.rs index cb1e6cf38..25b1993b1 100644 --- a/examples/src/richer-error/server.rs +++ b/examples/src/richer-error/server.rs @@ -1,4 +1,7 @@ -use tonic::{transport::Server, Code, Request, Response, Status}; +use tonic::{ + transport::{server::Routes, Server}, + Code, Request, Response, Status, +}; use tonic_types::{ErrorDetails, StatusExt}; use hello_world::greeter_server::{Greeter, GreeterServer}; @@ -58,14 +61,13 @@ impl Greeter for MyGreeter { #[tokio::main] async fn main() -> Result<(), Box> { let addr = "[::1]:50051".parse().unwrap(); - let greeter = MyGreeter::default(); + let routes = Routes::builder() + .add_service(GreeterServer::new(MyGreeter::default())) + .build(); println!("GreeterServer listening on {}", addr); - Server::builder() - .add_service(GreeterServer::new(greeter)) - .serve(addr) - .await?; + Server::builder().add_routes(routes).serve(addr).await?; Ok(()) } diff --git a/examples/src/richer-error/server_vec.rs b/examples/src/richer-error/server_vec.rs index 8ecf2e45c..72aef5803 100644 --- a/examples/src/richer-error/server_vec.rs +++ b/examples/src/richer-error/server_vec.rs @@ -1,4 +1,7 @@ -use tonic::{transport::Server, Code, Request, Response, Status}; +use tonic::{ + transport::{server::Routes, Server}, + Code, Request, Response, Status, +}; use tonic_types::{BadRequest, Help, LocalizedMessage, StatusExt}; use hello_world::greeter_server::{Greeter, GreeterServer}; @@ -58,14 +61,13 @@ impl Greeter for MyGreeter { #[tokio::main] async fn main() -> Result<(), Box> { let addr = "[::1]:50051".parse().unwrap(); - let greeter = MyGreeter::default(); + let routes = Routes::builder() + .add_service(GreeterServer::new(MyGreeter::default())) + .build(); println!("GreeterServer listening on {}", addr); - Server::builder() - .add_service(GreeterServer::new(greeter)) - .serve(addr) - .await?; + Server::builder().add_routes(routes).serve(addr).await?; Ok(()) } diff --git a/examples/src/routeguide/server.rs b/examples/src/routeguide/server.rs index c3ec4b32b..21a148118 100644 --- a/examples/src/routeguide/server.rs +++ b/examples/src/routeguide/server.rs @@ -5,6 +5,7 @@ use std::time::Instant; use tokio::sync::mpsc; use tokio_stream::{wrappers::ReceiverStream, Stream, StreamExt}; +use tonic::transport::server::Routes; use tonic::transport::Server; use tonic::{Request, Response, Status}; @@ -142,8 +143,9 @@ async fn main() -> Result<(), Box> { }; let svc = RouteGuideServer::new(route_guide); + let routes = Routes::builder().add_service(svc).build(); - Server::builder().add_service(svc).serve(addr).await?; + Server::builder().add_routes(routes).serve(addr).await?; Ok(()) } diff --git a/examples/src/streaming/server.rs b/examples/src/streaming/server.rs index 34d03fa0c..9a926ad36 100644 --- a/examples/src/streaming/server.rs +++ b/examples/src/streaming/server.rs @@ -5,7 +5,10 @@ pub mod pb { use std::{error::Error, io::ErrorKind, net::ToSocketAddrs, pin::Pin, time::Duration}; use tokio::sync::mpsc; use tokio_stream::{wrappers::ReceiverStream, Stream, StreamExt}; -use tonic::{transport::Server, Request, Response, Status, Streaming}; +use tonic::{ + transport::{server::Routes, Server}, + Request, Response, Status, Streaming, +}; use pb::{EchoRequest, EchoResponse}; @@ -143,9 +146,11 @@ impl pb::echo_server::Echo for EchoServer { #[tokio::main] async fn main() -> Result<(), Box> { - let server = EchoServer {}; + let routes = Routes::builder() + .add_service(pb::echo_server::EchoServer::new(EchoServer {})) + .build(); Server::builder() - .add_service(pb::echo_server::EchoServer::new(server)) + .add_routes(routes) .serve("[::1]:50051".to_socket_addrs().unwrap().next().unwrap()) .await .unwrap(); diff --git a/examples/src/timeout/server.rs b/examples/src/timeout/server.rs index 2d5b1fa2e..f0540ee4d 100644 --- a/examples/src/timeout/server.rs +++ b/examples/src/timeout/server.rs @@ -1,5 +1,6 @@ use std::time::Duration; use tokio::time::sleep; +use tonic::transport::server::Routes; use tonic::{transport::Server, Request, Response, Status}; use hello_world::greeter_server::{Greeter, GreeterServer}; @@ -32,14 +33,13 @@ impl Greeter for MyGreeter { #[tokio::main] async fn main() -> Result<(), Box> { let addr = "[::1]:50051".parse().unwrap(); - let greeter = MyGreeter::default(); + let routes = Routes::builder() + .add_service(GreeterServer::new(MyGreeter::default())) + .build(); println!("GreeterServer listening on {}", addr); - Server::builder() - .add_service(GreeterServer::new(greeter)) - .serve(addr) - .await?; + Server::builder().add_routes(routes).serve(addr).await?; Ok(()) } diff --git a/examples/src/tls/server.rs b/examples/src/tls/server.rs index 08697b221..1b75be199 100644 --- a/examples/src/tls/server.rs +++ b/examples/src/tls/server.rs @@ -5,7 +5,7 @@ pub mod pb { use pb::{EchoRequest, EchoResponse}; use tonic::{ transport::{ - server::{TcpConnectInfo, TlsConnectInfo}, + server::{Routes, TcpConnectInfo, TlsConnectInfo}, Identity, Server, ServerTlsConfig, }, Request, Response, Status, @@ -43,11 +43,13 @@ async fn main() -> Result<(), Box> { let identity = Identity::from_pem(cert, key); let addr = "[::1]:50051".parse().unwrap(); - let server = EchoServer::default(); + let routes = Routes::builder() + .add_service(pb::echo_server::EchoServer::new(EchoServer::default())) + .build(); Server::builder() .tls_config(ServerTlsConfig::new().identity(identity))? - .add_service(pb::echo_server::EchoServer::new(server)) + .add_routes(routes) .serve(addr) .await?; diff --git a/examples/src/tls_client_auth/server.rs b/examples/src/tls_client_auth/server.rs index 840c70ac9..f887c71e0 100644 --- a/examples/src/tls_client_auth/server.rs +++ b/examples/src/tls_client_auth/server.rs @@ -3,6 +3,7 @@ pub mod pb { } use pb::{EchoRequest, EchoResponse}; +use tonic::transport::server::Routes; use tonic::transport::{Certificate, Identity, Server, ServerTlsConfig}; use tonic::{Request, Response, Status}; @@ -36,7 +37,9 @@ async fn main() -> Result<(), Box> { let client_ca_cert = Certificate::from_pem(client_ca_cert); let addr = "[::1]:50051".parse().unwrap(); - let server = EchoServer::default(); + let routes = Routes::builder() + .add_service(pb::echo_server::EchoServer::new(EchoServer::default())) + .build(); let tls = ServerTlsConfig::new() .identity(server_identity) @@ -44,7 +47,7 @@ async fn main() -> Result<(), Box> { Server::builder() .tls_config(tls)? - .add_service(pb::echo_server::EchoServer::new(server)) + .add_routes(routes) .serve(addr) .await?; diff --git a/examples/src/tls_rustls/server.rs b/examples/src/tls_rustls/server.rs index 82f009344..087a11775 100644 --- a/examples/src/tls_rustls/server.rs +++ b/examples/src/tls_rustls/server.rs @@ -10,7 +10,7 @@ use tokio_rustls::{ rustls::{Certificate, PrivateKey, ServerConfig}, TlsAcceptor, }; -use tonic::{transport::Server, Request, Response, Status}; +use tonic::{transport::server::Routes, Request, Response, Status}; use tower_http::ServiceBuilderExt; #[tokio::main] @@ -45,9 +45,9 @@ async fn main() -> Result<(), Box> { let server = EchoServer::default(); - let svc = Server::builder() + let routes = Routes::builder() .add_service(pb::echo_server::EchoServer::new(server)) - .into_service(); + .build(); let mut http = Http::new(); http.http2_only(true); @@ -66,7 +66,7 @@ async fn main() -> Result<(), Box> { let http = http.clone(); let tls_acceptor = tls_acceptor.clone(); - let svc = svc.clone(); + let routes = routes.clone(); tokio::spawn(async move { let mut certificates = Vec::new(); @@ -84,7 +84,7 @@ async fn main() -> Result<(), Box> { let svc = tower::ServiceBuilder::new() .add_extension(Arc::new(ConnInfo { addr, certificates })) - .service(svc); + .service(routes); http.serve_connection(conn, svc).await.unwrap(); }); diff --git a/examples/src/tower/server.rs b/examples/src/tower/server.rs index cc85d62e5..53cfc2e43 100644 --- a/examples/src/tower/server.rs +++ b/examples/src/tower/server.rs @@ -4,7 +4,11 @@ use std::{ task::{Context, Poll}, time::Duration, }; -use tonic::{body::BoxBody, transport::Server, Request, Response, Status}; +use tonic::{ + body::BoxBody, + transport::{server::Routes, Server}, + Request, Response, Status, +}; use tower::{Layer, Service}; use hello_world::greeter_server::{Greeter, GreeterServer}; @@ -51,10 +55,12 @@ async fn main() -> Result<(), Box> { .layer(tonic::service::interceptor(intercept)) .into_inner(); + let routes = Routes::builder().add_service(svc).build(); + Server::builder() // Wrap all services in the middleware stack .layer(layer) - .add_service(svc) + .add_routes(routes) .serve(addr) .await?; diff --git a/examples/src/tracing/server.rs b/examples/src/tracing/server.rs index a068219a8..49ada60c4 100644 --- a/examples/src/tracing/server.rs +++ b/examples/src/tracing/server.rs @@ -1,4 +1,7 @@ -use tonic::{transport::Server, Request, Response, Status}; +use tonic::{ + transport::{server::Routes, Server}, + Request, Response, Status, +}; pub mod hello_world { tonic::include_proto!("helloworld"); @@ -42,9 +45,12 @@ async fn main() -> Result<(), Box> { tracing::info!(message = "Starting server.", %addr); + let routes = Routes::builder() + .add_service(GreeterServer::new(greeter)) + .build(); Server::builder() .trace_fn(|_| tracing::info_span!("helloworld_server")) - .add_service(GreeterServer::new(greeter)) + .add_routes(routes) .serve(addr) .await?; diff --git a/examples/src/uds/server.rs b/examples/src/uds/server.rs index ccf9c91a8..59083c735 100644 --- a/examples/src/uds/server.rs +++ b/examples/src/uds/server.rs @@ -43,17 +43,21 @@ impl Greeter for MyGreeter { #[cfg(unix)] #[tokio::main] async fn main() -> Result<(), Box> { + use tonic::transport::server::Routes; + let path = "/tmp/tonic/helloworld"; std::fs::create_dir_all(Path::new(path).parent().unwrap())?; - let greeter = MyGreeter::default(); + let routes = Routes::builder() + .add_service(GreeterServer::new(MyGreeter::default())) + .build(); let uds = UnixListener::bind(path)?; let uds_stream = UnixListenerStream::new(uds); Server::builder() - .add_service(GreeterServer::new(greeter)) + .add_routes(routes) .serve_with_incoming(uds_stream) .await?; diff --git a/interop/src/bin/server.rs b/interop/src/bin/server.rs index bbc8f433f..709559df2 100644 --- a/interop/src/bin/server.rs +++ b/interop/src/bin/server.rs @@ -1,4 +1,5 @@ use interop::server; +use tonic::transport::server::Routes; use tonic::transport::Server; use tonic::transport::{Identity, ServerTlsConfig}; @@ -41,11 +42,12 @@ async fn main() -> std::result::Result<(), Box> { // Wrap this test_service with a service that will echo headers as trailers. let test_service_svc = server::EchoHeadersSvc::new(test_service); - builder + let routes = Routes::builder() .add_service(test_service_svc) .add_service(unimplemented_service) - .serve(addr) - .await?; + .build(); + + builder.add_routes(routes).serve(addr).await?; Ok(()) } diff --git a/tests/compression/src/bidirectional_stream.rs b/tests/compression/src/bidirectional_stream.rs index 898fe5b05..4088c3f67 100644 --- a/tests/compression/src/bidirectional_stream.rs +++ b/tests/compression/src/bidirectional_stream.rs @@ -1,6 +1,6 @@ use super::*; use http_body::Body; -use tonic::codec::CompressionEncoding; +use tonic::{codec::CompressionEncoding, transport::server::Routes}; util::parametrized_tests! { client_enabled_server_enabled, @@ -15,6 +15,7 @@ async fn client_enabled_server_enabled(encoding: CompressionEncoding) { let svc = test_server::TestServer::new(Svc::default()) .accept_compressed(encoding) .send_compressed(encoding); + let routes = Routes::builder().add_service(svc).build(); let request_bytes_counter = Arc::new(AtomicUsize::new(0)); let response_bytes_counter = Arc::new(AtomicUsize::new(0)); @@ -63,7 +64,7 @@ async fn client_enabled_server_enabled(encoding: CompressionEncoding) { })) .into_inner(), ) - .add_service(svc) + .add_routes(routes) .serve_with_incoming(tokio_stream::once(Ok::<_, std::io::Error>(server))) .await .unwrap(); diff --git a/tests/compression/src/client_stream.rs b/tests/compression/src/client_stream.rs index 9402c75f2..e5eeb2541 100644 --- a/tests/compression/src/client_stream.rs +++ b/tests/compression/src/client_stream.rs @@ -1,6 +1,6 @@ use super::*; use http_body::Body; -use tonic::codec::CompressionEncoding; +use tonic::{codec::CompressionEncoding, transport::server::Routes}; util::parametrized_tests! { client_enabled_server_enabled, @@ -13,6 +13,7 @@ async fn client_enabled_server_enabled(encoding: CompressionEncoding) { let (client, server) = tokio::io::duplex(UNCOMPRESSED_MIN_BODY_SIZE * 10); let svc = test_server::TestServer::new(Svc::default()).accept_compressed(encoding); + let routes = Routes::builder().add_service(svc).build(); let request_bytes_counter = Arc::new(AtomicUsize::new(0)); @@ -53,7 +54,7 @@ async fn client_enabled_server_enabled(encoding: CompressionEncoding) { )) .into_inner(), ) - .add_service(svc) + .add_routes(routes) .serve_with_incoming(tokio_stream::once(Ok::<_, std::io::Error>(server))) .await .unwrap(); @@ -84,6 +85,7 @@ async fn client_disabled_server_enabled(encoding: CompressionEncoding) { let (client, server) = tokio::io::duplex(UNCOMPRESSED_MIN_BODY_SIZE * 10); let svc = test_server::TestServer::new(Svc::default()).accept_compressed(encoding); + let routes = Routes::builder().add_service(svc).build(); let request_bytes_counter = Arc::new(AtomicUsize::new(0)); @@ -104,7 +106,7 @@ async fn client_disabled_server_enabled(encoding: CompressionEncoding) { )) .into_inner(), ) - .add_service(svc) + .add_routes(routes) .serve_with_incoming(tokio_stream::once(Ok::<_, std::io::Error>(server))) .await .unwrap(); @@ -134,10 +136,11 @@ async fn client_enabled_server_disabled(encoding: CompressionEncoding) { let (client, server) = tokio::io::duplex(UNCOMPRESSED_MIN_BODY_SIZE * 10); let svc = test_server::TestServer::new(Svc::default()); + let routes = Routes::builder().add_service(svc).build(); tokio::spawn(async move { Server::builder() - .add_service(svc) + .add_routes(routes) .serve_with_incoming(tokio_stream::once(Ok::<_, std::io::Error>(server))) .await .unwrap(); @@ -178,6 +181,7 @@ async fn compressing_response_from_client_stream(encoding: CompressionEncoding) let (client, server) = tokio::io::duplex(UNCOMPRESSED_MIN_BODY_SIZE * 10); let svc = test_server::TestServer::new(Svc::default()).send_compressed(encoding); + let routes = Routes::builder().add_service(svc).build(); let response_bytes_counter = Arc::new(AtomicUsize::new(0)); @@ -195,7 +199,7 @@ async fn compressing_response_from_client_stream(encoding: CompressionEncoding) })) .into_inner(), ) - .add_service(svc) + .add_routes(routes) .serve_with_incoming(tokio_stream::once(Ok::<_, std::io::Error>(server))) .await .unwrap(); diff --git a/tests/compression/src/compressing_request.rs b/tests/compression/src/compressing_request.rs index 87a02de64..c20054194 100644 --- a/tests/compression/src/compressing_request.rs +++ b/tests/compression/src/compressing_request.rs @@ -1,6 +1,6 @@ use super::*; use http_body::Body; -use tonic::codec::CompressionEncoding; +use tonic::{codec::CompressionEncoding, transport::server::Routes}; util::parametrized_tests! { client_enabled_server_enabled, @@ -13,6 +13,7 @@ async fn client_enabled_server_enabled(encoding: CompressionEncoding) { let (client, server) = tokio::io::duplex(UNCOMPRESSED_MIN_BODY_SIZE * 10); let svc = test_server::TestServer::new(Svc::default()).accept_compressed(encoding); + let routes = Routes::builder().add_service(svc).build(); let request_bytes_counter = Arc::new(AtomicUsize::new(0)); @@ -55,7 +56,7 @@ async fn client_enabled_server_enabled(encoding: CompressionEncoding) { ) .into_inner(), ) - .add_service(svc) + .add_routes(routes) .serve_with_incoming(tokio_stream::iter(vec![Ok::<_, std::io::Error>(server)])) .await .unwrap(); @@ -90,6 +91,7 @@ async fn client_enabled_server_enabled_multi_encoding(encoding: CompressionEncod let svc = test_server::TestServer::new(Svc::default()) .accept_compressed(CompressionEncoding::Gzip) .accept_compressed(CompressionEncoding::Zstd); + let routes = Routes::builder().add_service(svc).build(); let request_bytes_counter = Arc::new(AtomicUsize::new(0)); @@ -115,7 +117,7 @@ async fn client_enabled_server_enabled_multi_encoding(encoding: CompressionEncod ) .into_inner(), ) - .add_service(svc) + .add_routes(routes) .serve_with_incoming(tokio_stream::once(Ok::<_, std::io::Error>(server))) .await .unwrap(); @@ -148,10 +150,11 @@ async fn client_enabled_server_disabled(encoding: CompressionEncoding) { let (client, server) = tokio::io::duplex(UNCOMPRESSED_MIN_BODY_SIZE * 10); let svc = test_server::TestServer::new(Svc::default()); + let routes = Routes::builder().add_service(svc).build(); tokio::spawn(async move { Server::builder() - .add_service(svc) + .add_routes(routes) .serve_with_incoming(tokio_stream::once(Ok::<_, std::io::Error>(server))) .await .unwrap(); @@ -197,11 +200,12 @@ async fn client_mark_compressed_without_header_server_enabled(encoding: Compress let (client, server) = tokio::io::duplex(UNCOMPRESSED_MIN_BODY_SIZE * 10); let svc = test_server::TestServer::new(Svc::default()).accept_compressed(encoding); + let routes = Routes::builder().add_service(svc).build(); tokio::spawn({ async move { Server::builder() - .add_service(svc) + .add_routes(routes) .serve_with_incoming(tokio_stream::once(Ok::<_, std::io::Error>(server))) .await .unwrap(); diff --git a/tests/compression/src/compressing_response.rs b/tests/compression/src/compressing_response.rs index 86b0fa6cf..5ca9d8fe9 100644 --- a/tests/compression/src/compressing_response.rs +++ b/tests/compression/src/compressing_response.rs @@ -1,5 +1,5 @@ use super::*; -use tonic::codec::CompressionEncoding; +use tonic::{codec::CompressionEncoding, transport::server::Routes}; util::parametrized_tests! { client_enabled_server_enabled, @@ -51,6 +51,7 @@ async fn client_enabled_server_enabled(encoding: CompressionEncoding) { } let svc = test_server::TestServer::new(Svc::default()).send_compressed(encoding); + let routes = Routes::builder().add_service(svc).build(); let response_bytes_counter = Arc::new(AtomicUsize::new(0)); @@ -72,7 +73,7 @@ async fn client_enabled_server_enabled(encoding: CompressionEncoding) { })) .into_inner(), ) - .add_service(svc) + .add_routes(routes) .serve_with_incoming(tokio_stream::once(Ok::<_, std::io::Error>(server))) .await .unwrap(); @@ -107,6 +108,7 @@ async fn client_enabled_server_disabled(encoding: CompressionEncoding) { let (client, server) = tokio::io::duplex(UNCOMPRESSED_MIN_BODY_SIZE * 10); let svc = test_server::TestServer::new(Svc::default()); + let routes = Routes::builder().add_service(svc).build(); let response_bytes_counter = Arc::new(AtomicUsize::new(0)); @@ -125,7 +127,7 @@ async fn client_enabled_server_disabled(encoding: CompressionEncoding) { })) .into_inner(), ) - .add_service(svc) + .add_routes(routes) .serve_with_incoming(tokio_stream::iter(vec![Ok::<_, std::io::Error>(server)])) .await .unwrap(); @@ -148,6 +150,7 @@ async fn client_enabled_server_disabled_multi_encoding() { let (client, server) = tokio::io::duplex(UNCOMPRESSED_MIN_BODY_SIZE * 10); let svc = test_server::TestServer::new(Svc::default()); + let routes = Routes::builder().add_service(svc).build(); let response_bytes_counter = Arc::new(AtomicUsize::new(0)); @@ -166,7 +169,7 @@ async fn client_enabled_server_disabled_multi_encoding() { })) .into_inner(), ) - .add_service(svc) + .add_routes(routes) .serve_with_incoming(tokio_stream::once(Ok::<_, std::io::Error>(server))) .await .unwrap(); @@ -220,6 +223,7 @@ async fn client_disabled(encoding: CompressionEncoding) { } let svc = test_server::TestServer::new(Svc::default()).send_compressed(encoding); + let routes = Routes::builder().add_service(svc).build(); let response_bytes_counter = Arc::new(AtomicUsize::new(0)); @@ -238,7 +242,7 @@ async fn client_disabled(encoding: CompressionEncoding) { })) .into_inner(), ) - .add_service(svc) + .add_routes(routes) .serve_with_incoming(tokio_stream::once(Ok::<_, std::io::Error>(server))) .await .unwrap(); @@ -266,6 +270,7 @@ async fn server_replying_with_unsupported_encoding(encoding: CompressionEncoding let (client, server) = tokio::io::duplex(UNCOMPRESSED_MIN_BODY_SIZE * 10); let svc = test_server::TestServer::new(Svc::default()).send_compressed(encoding); + let routes = Routes::builder().add_service(svc).build(); fn add_weird_content_encoding(mut response: http::Response) -> http::Response { response @@ -281,7 +286,7 @@ async fn server_replying_with_unsupported_encoding(encoding: CompressionEncoding .map_response(add_weird_content_encoding) .into_inner(), ) - .add_service(svc) + .add_routes(routes) .serve_with_incoming(tokio_stream::once(Ok::<_, std::io::Error>(server))) .await .unwrap(); @@ -312,6 +317,7 @@ async fn disabling_compression_on_single_response(encoding: CompressionEncoding) disable_compressing_on_response: true, }) .send_compressed(encoding); + let routes = Routes::builder().add_service(svc).build(); let response_bytes_counter = Arc::new(AtomicUsize::new(0)); @@ -329,7 +335,7 @@ async fn disabling_compression_on_single_response(encoding: CompressionEncoding) })) .into_inner(), ) - .add_service(svc) + .add_routes(routes) .serve_with_incoming(tokio_stream::once(Ok::<_, std::io::Error>(server))) .await .unwrap(); @@ -368,6 +374,7 @@ async fn disabling_compression_on_response_but_keeping_compression_on_stream( disable_compressing_on_response: true, }) .send_compressed(encoding); + let routes = Routes::builder().add_service(svc).build(); let response_bytes_counter = Arc::new(AtomicUsize::new(0)); @@ -385,7 +392,7 @@ async fn disabling_compression_on_response_but_keeping_compression_on_stream( })) .into_inner(), ) - .add_service(svc) + .add_routes(routes) .serve_with_incoming(tokio_stream::once(Ok::<_, std::io::Error>(server))) .await .unwrap(); @@ -435,6 +442,7 @@ async fn disabling_compression_on_response_from_client_stream(encoding: Compress disable_compressing_on_response: true, }) .send_compressed(encoding); + let routes = Routes::builder().add_service(svc).build(); let response_bytes_counter = Arc::new(AtomicUsize::new(0)); @@ -452,7 +460,7 @@ async fn disabling_compression_on_response_from_client_stream(encoding: Compress })) .into_inner(), ) - .add_service(svc) + .add_routes(routes) .serve_with_incoming(tokio_stream::once(Ok::<_, std::io::Error>(server))) .await .unwrap(); diff --git a/tests/compression/src/server_stream.rs b/tests/compression/src/server_stream.rs index 9d0e4f390..205ca3952 100644 --- a/tests/compression/src/server_stream.rs +++ b/tests/compression/src/server_stream.rs @@ -1,5 +1,6 @@ use super::*; use tonic::codec::CompressionEncoding; +use tonic::transport::server::Routes; use tonic::Streaming; util::parametrized_tests! { @@ -13,6 +14,7 @@ async fn client_enabled_server_enabled(encoding: CompressionEncoding) { let (client, server) = tokio::io::duplex(UNCOMPRESSED_MIN_BODY_SIZE * 10); let svc = test_server::TestServer::new(Svc::default()).send_compressed(encoding); + let routes = Routes::builder().add_service(svc).build(); let response_bytes_counter = Arc::new(AtomicUsize::new(0)); @@ -30,7 +32,7 @@ async fn client_enabled_server_enabled(encoding: CompressionEncoding) { })) .into_inner(), ) - .add_service(svc) + .add_routes(routes) .serve_with_incoming(tokio_stream::once(Ok::<_, std::io::Error>(server))) .await .unwrap(); @@ -77,6 +79,7 @@ async fn client_disabled_server_enabled(encoding: CompressionEncoding) { let (client, server) = tokio::io::duplex(UNCOMPRESSED_MIN_BODY_SIZE * 10); let svc = test_server::TestServer::new(Svc::default()).send_compressed(encoding); + let routes = Routes::builder().add_service(svc).build(); let response_bytes_counter = Arc::new(AtomicUsize::new(0)); @@ -94,7 +97,7 @@ async fn client_disabled_server_enabled(encoding: CompressionEncoding) { })) .into_inner(), ) - .add_service(svc) + .add_routes(routes) .serve_with_incoming(tokio_stream::once(Ok::<_, std::io::Error>(server))) .await .unwrap(); @@ -128,6 +131,7 @@ async fn client_enabled_server_disabled(encoding: CompressionEncoding) { let (client, server) = tokio::io::duplex(UNCOMPRESSED_MIN_BODY_SIZE * 10); let svc = test_server::TestServer::new(Svc::default()); + let routes = Routes::builder().add_service(svc).build(); let response_bytes_counter = Arc::new(AtomicUsize::new(0)); @@ -145,7 +149,7 @@ async fn client_enabled_server_disabled(encoding: CompressionEncoding) { })) .into_inner(), ) - .add_service(svc) + .add_routes(routes) .serve_with_incoming(tokio_stream::once(Ok::<_, std::io::Error>(server))) .await .unwrap(); diff --git a/tests/default_stubs/src/test_defaults.rs b/tests/default_stubs/src/test_defaults.rs index 32bed1be1..17afb22d1 100644 --- a/tests/default_stubs/src/test_defaults.rs +++ b/tests/default_stubs/src/test_defaults.rs @@ -3,7 +3,7 @@ use crate::*; use std::net::SocketAddr; use tokio::net::TcpListener; -use tonic::transport::Server; +use tonic::transport::{server::Routes, Server}; #[cfg(test)] fn echo_requests_iter() -> impl Stream { @@ -82,7 +82,10 @@ async fn test_default_stubs() { #[cfg(test)] async fn run_services_in_background() -> (SocketAddr, SocketAddr) { let svc = test_server::TestServer::new(Svc {}); + let routes = Routes::builder().add_service(svc).build(); + let svc_default_stubs = test_default_server::TestDefaultServer::new(Svc {}); + let routes_default_stubs = Routes::builder().add_service(svc_default_stubs).build(); let listener = TcpListener::bind("127.0.0.1:0").await.unwrap(); let addr = listener.local_addr().unwrap(); @@ -92,7 +95,7 @@ async fn run_services_in_background() -> (SocketAddr, SocketAddr) { tokio::spawn(async move { Server::builder() - .add_service(svc) + .add_routes(routes) .serve_with_incoming(tokio_stream::wrappers::TcpListenerStream::new(listener)) .await .unwrap(); @@ -100,7 +103,7 @@ async fn run_services_in_background() -> (SocketAddr, SocketAddr) { tokio::spawn(async move { Server::builder() - .add_service(svc_default_stubs) + .add_routes(routes_default_stubs) .serve_with_incoming(tokio_stream::wrappers::TcpListenerStream::new( listener_default_stubs, )) diff --git a/tests/integration_tests/tests/client_layer.rs b/tests/integration_tests/tests/client_layer.rs index 01fa5c17f..9a456ec76 100644 --- a/tests/integration_tests/tests/client_layer.rs +++ b/tests/integration_tests/tests/client_layer.rs @@ -3,7 +3,7 @@ use integration_tests::pb::{test_client::TestClient, test_server, Input, Output} use std::time::Duration; use tokio::sync::oneshot; use tonic::{ - transport::{Endpoint, Server}, + transport::{server::Routes, Endpoint, Server}, Request, Response, Status, }; use tower::ServiceBuilder; @@ -25,11 +25,12 @@ async fn connect_supports_standard_tower_layers() { let (tx, rx) = oneshot::channel(); let svc = test_server::TestServer::new(Svc); + let routes = Routes::builder().add_service(svc).build(); // Start the server now, second call should succeed let jh = tokio::spawn(async move { Server::builder() - .add_service(svc) + .add_routes(routes) .serve_with_shutdown("127.0.0.1:1340".parse().unwrap(), async { drop(rx.await) }) .await .unwrap(); diff --git a/tests/integration_tests/tests/complex_tower_middleware.rs b/tests/integration_tests/tests/complex_tower_middleware.rs index 5d7690be3..05d0d645e 100644 --- a/tests/integration_tests/tests/complex_tower_middleware.rs +++ b/tests/integration_tests/tests/complex_tower_middleware.rs @@ -7,7 +7,10 @@ use std::{ pin::Pin, task::{Context, Poll}, }; -use tonic::{transport::Server, Request, Response, Status}; +use tonic::{ + transport::{server::Routes, Server}, + Request, Response, Status, +}; use tower::{layer::Layer, BoxError, Service}; // all we care about is that this compiles @@ -22,10 +25,11 @@ async fn complex_tower_layers_work() { } let svc = test_server::TestServer::new(Svc); + let routes = Routes::builder().add_service(svc).build(); Server::builder() .layer(MyServiceLayer::new()) - .add_service(svc) + .add_routes(routes) .serve("127.0.0.1:1322".parse().unwrap()) .await .unwrap(); diff --git a/tests/integration_tests/tests/connect_info.rs b/tests/integration_tests/tests/connect_info.rs index 94fac8221..76b529108 100644 --- a/tests/integration_tests/tests/connect_info.rs +++ b/tests/integration_tests/tests/connect_info.rs @@ -2,7 +2,10 @@ use integration_tests::pb::{test_client, test_server, Input, Output}; use std::time::Duration; use tokio::sync::oneshot; use tonic::{ - transport::{server::TcpConnectInfo, Endpoint, Server}, + transport::{ + server::{Routes, TcpConnectInfo}, + Endpoint, Server, + }, Request, Response, Status, }; @@ -22,12 +25,13 @@ async fn getting_connect_info() { } let svc = test_server::TestServer::new(Svc); + let routes = Routes::builder().add_service(svc).build(); let (tx, rx) = oneshot::channel::<()>(); let jh = tokio::spawn(async move { Server::builder() - .add_service(svc) + .add_routes(routes) .serve_with_shutdown("127.0.0.1:1400".parse().unwrap(), async { drop(rx.await) }) .await .unwrap(); @@ -57,7 +61,10 @@ pub mod unix { }; use tokio_stream::wrappers::UnixListenerStream; use tonic::{ - transport::{server::UdsConnectInfo, Endpoint, Server, Uri}, + transport::{ + server::{Routes, UdsConnectInfo}, + Endpoint, Server, Uri, + }, Request, Response, Status, }; use tower::service_fn; @@ -90,12 +97,14 @@ pub mod unix { let uds = UnixListener::bind(&unix_socket_path).unwrap(); let uds_stream = UnixListenerStream::new(uds); - let service = test_server::TestServer::new(Svc {}); + let svc = test_server::TestServer::new(Svc {}); + let routes = Routes::builder().add_service(svc).build(); + let (tx, rx) = oneshot::channel::<()>(); let jh = tokio::spawn(async move { Server::builder() - .add_service(service) + .add_routes(routes) .serve_with_incoming_shutdown(uds_stream, async { drop(rx.await) }) .await .unwrap(); diff --git a/tests/integration_tests/tests/connection.rs b/tests/integration_tests/tests/connection.rs index bb67adf55..a92fe5363 100644 --- a/tests/integration_tests/tests/connection.rs +++ b/tests/integration_tests/tests/connection.rs @@ -3,7 +3,7 @@ use std::sync::{Arc, Mutex}; use std::time::Duration; use tokio::sync::oneshot; use tonic::{ - transport::{Endpoint, Server}, + transport::{server::Routes, Endpoint, Server}, Code, Request, Response, Status, }; @@ -31,10 +31,11 @@ async fn connect_returns_err_via_call_after_connected() { let (tx, rx) = oneshot::channel(); let sender = Arc::new(Mutex::new(Some(tx))); let svc = test_server::TestServer::new(Svc(sender)); + let routes = Routes::builder().add_service(svc).build(); let jh = tokio::spawn(async move { Server::builder() - .add_service(svc) + .add_routes(routes) .serve_with_shutdown("127.0.0.1:1338".parse().unwrap(), async { drop(rx.await) }) .await .unwrap(); @@ -62,6 +63,7 @@ async fn connect_lazy_reconnects_after_first_failure() { let (tx, rx) = oneshot::channel(); let sender = Arc::new(Mutex::new(Some(tx))); let svc = test_server::TestServer::new(Svc(sender)); + let routes = Routes::builder().add_service(svc).build(); let channel = Endpoint::from_static("http://127.0.0.1:1339").connect_lazy(); @@ -73,7 +75,7 @@ async fn connect_lazy_reconnects_after_first_failure() { // Start the server now, second call should succeed let jh = tokio::spawn(async move { Server::builder() - .add_service(svc) + .add_routes(routes) .serve_with_shutdown("127.0.0.1:1339".parse().unwrap(), async { drop(rx.await) }) .await .unwrap(); diff --git a/tests/integration_tests/tests/extensions.rs b/tests/integration_tests/tests/extensions.rs index b112f8e66..406506ac6 100644 --- a/tests/integration_tests/tests/extensions.rs +++ b/tests/integration_tests/tests/extensions.rs @@ -11,7 +11,7 @@ use tokio::sync::oneshot; use tonic::{ body::BoxBody, server::NamedService, - transport::{Endpoint, Server}, + transport::{server::Routes, Endpoint, Server}, Request, Response, Status, }; use tower_service::Service; @@ -36,12 +36,13 @@ async fn setting_extension_from_interceptor() { req.extensions_mut().insert(ExtensionValue(42)); Ok(req) }); + let routes = Routes::builder().add_service(svc).build(); let (tx, rx) = oneshot::channel::<()>(); let jh = tokio::spawn(async move { Server::builder() - .add_service(svc) + .add_routes(routes) .serve_with_shutdown("127.0.0.1:1323".parse().unwrap(), async { drop(rx.await) }) .await .unwrap(); @@ -80,12 +81,13 @@ async fn setting_extension_from_tower() { let svc = InterceptedService { inner: test_server::TestServer::new(Svc), }; + let routes = Routes::builder().add_service(svc).build(); let (tx, rx) = oneshot::channel::<()>(); let jh = tokio::spawn(async move { Server::builder() - .add_service(svc) + .add_routes(routes) .serve_with_shutdown("127.0.0.1:1324".parse().unwrap(), async { drop(rx.await) }) .await .unwrap(); diff --git a/tests/integration_tests/tests/interceptor.rs b/tests/integration_tests/tests/interceptor.rs index 23f2f25cf..266300849 100644 --- a/tests/integration_tests/tests/interceptor.rs +++ b/tests/integration_tests/tests/interceptor.rs @@ -2,7 +2,7 @@ use integration_tests::pb::{test_client::TestClient, test_server, Input, Output} use std::time::Duration; use tokio::sync::oneshot; use tonic::{ - transport::{Endpoint, Server}, + transport::{server::Routes, Endpoint, Server}, GrpcMethod, Request, Response, Status, }; @@ -20,12 +20,13 @@ async fn interceptor_retrieves_grpc_method() { } let svc = test_server::TestServer::new(Svc); + let routes = Routes::builder().add_service(svc).build(); let (tx, rx) = oneshot::channel(); // Start the server now, second call should succeed let jh = tokio::spawn(async move { Server::builder() - .add_service(svc) + .add_routes(routes) .serve_with_shutdown("127.0.0.1:1340".parse().unwrap(), async { drop(rx.await) }) .await .unwrap(); diff --git a/tests/integration_tests/tests/max_message_size.rs b/tests/integration_tests/tests/max_message_size.rs index 9ae524dbc..5eee367f7 100644 --- a/tests/integration_tests/tests/max_message_size.rs +++ b/tests/integration_tests/tests/max_message_size.rs @@ -6,7 +6,7 @@ use integration_tests::{ }; use tokio_stream::Stream; use tonic::{ - transport::{Endpoint, Server}, + transport::{server::Routes, Endpoint, Server}, Code, Request, Response, Status, }; @@ -144,10 +144,11 @@ async fn response_stream_limit() { } let svc = test1_server::Test1Server::new(Svc); + let routes = Routes::builder().add_service(svc).build(); tokio::spawn(async move { Server::builder() - .add_service(svc) + .add_routes(routes) .serve_with_incoming(tokio_stream::once(Ok::<_, std::io::Error>(server))) .await .unwrap(); @@ -314,9 +315,11 @@ async fn max_message_run(case: &TestCase) -> Result<(), Status> { svc }; + let routes = Routes::builder().add_service(svc).build(); + tokio::spawn(async move { Server::builder() - .add_service(svc) + .add_routes(routes) .serve_with_incoming(tokio_stream::once(Ok::<_, std::io::Error>(server))) .await .unwrap(); diff --git a/tests/integration_tests/tests/origin.rs b/tests/integration_tests/tests/origin.rs index f149dc68d..a40d53bac 100644 --- a/tests/integration_tests/tests/origin.rs +++ b/tests/integration_tests/tests/origin.rs @@ -7,7 +7,7 @@ use std::time::Duration; use tokio::sync::oneshot; use tonic::codegen::http::Request; use tonic::{ - transport::{Endpoint, Server}, + transport::{server::Routes, Endpoint, Server}, Response, Status, }; use tower::Layer; @@ -28,13 +28,14 @@ async fn writes_origin_header() { } let svc = test_server::TestServer::new(Svc); + let routes = Routes::builder().add_service(svc).build(); let (tx, rx) = oneshot::channel::<()>(); let jh = tokio::spawn(async move { Server::builder() .layer(OriginLayer {}) - .add_service(svc) + .add_routes(routes) .serve_with_shutdown("127.0.0.1:1442".parse().unwrap(), async { drop(rx.await) }) .await .unwrap(); diff --git a/tests/integration_tests/tests/routes_builder.rs b/tests/integration_tests/tests/routes_builder.rs index 7bcbfad37..82c08a11f 100644 --- a/tests/integration_tests/tests/routes_builder.rs +++ b/tests/integration_tests/tests/routes_builder.rs @@ -7,7 +7,7 @@ use integration_tests::pb::{ test1_client, test1_server, test_client, test_server, Input, Input1, Output, Output1, }; use tonic::codegen::BoxStream; -use tonic::transport::server::RoutesBuilder; +use tonic::transport::server::Routes; use tonic::{ transport::{Endpoint, Server}, Request, Response, Status, @@ -53,12 +53,14 @@ async fn multiple_service_using_routes_builder() { let svc2 = test1_server::Test1Server::new(Svc2); let (tx, rx) = oneshot::channel::<()>(); - let mut routes_builder = RoutesBuilder::default(); - routes_builder.add_service(svc1).add_service(svc2); + let routes = Routes::builder() + .add_service(svc1) + .add_service(svc2) + .build(); let jh = tokio::spawn(async move { Server::builder() - .add_routes(routes_builder.routes()) + .add_routes(routes) .serve_with_shutdown("127.0.0.1:1400".parse().unwrap(), async { drop(rx.await) }) .await .unwrap(); diff --git a/tests/integration_tests/tests/status.rs b/tests/integration_tests/tests/status.rs index 3fdabcd36..6e10e610b 100644 --- a/tests/integration_tests/tests/status.rs +++ b/tests/integration_tests/tests/status.rs @@ -9,7 +9,7 @@ use std::error::Error; use std::time::Duration; use tokio::sync::oneshot; use tonic::metadata::{MetadataMap, MetadataValue}; -use tonic::transport::Endpoint; +use tonic::transport::{server::Routes, Endpoint}; use tonic::{transport::Server, Code, Request, Response, Status}; #[tokio::test] @@ -28,12 +28,13 @@ async fn status_with_details() { } let svc = test_server::TestServer::new(Svc); + let routes = Routes::builder().add_service(svc).build(); let (tx, rx) = oneshot::channel::<()>(); let jh = tokio::spawn(async move { Server::builder() - .add_service(svc) + .add_routes(routes) .serve_with_shutdown("127.0.0.1:1337".parse().unwrap(), async { drop(rx.await) }) .await .unwrap(); @@ -82,12 +83,13 @@ async fn status_with_metadata() { } let svc = test_server::TestServer::new(Svc); + let routes = Routes::builder().add_service(svc).build(); let (tx, rx) = oneshot::channel::<()>(); let jh = tokio::spawn(async move { Server::builder() - .add_service(svc) + .add_routes(routes) .serve_with_shutdown("127.0.0.1:1338".parse().unwrap(), async { drop(rx.await) }) .await .unwrap(); @@ -151,10 +153,11 @@ async fn status_from_server_stream() { } let svc = test_stream_server::TestStreamServer::new(Svc); + let routes = Routes::builder().add_service(svc).build(); tokio::spawn(async move { Server::builder() - .add_service(svc) + .add_routes(routes) .serve("127.0.0.1:1339".parse().unwrap()) .await .unwrap(); diff --git a/tests/integration_tests/tests/streams.rs b/tests/integration_tests/tests/streams.rs index 8ce2e93bf..604eb922f 100644 --- a/tests/integration_tests/tests/streams.rs +++ b/tests/integration_tests/tests/streams.rs @@ -1,6 +1,9 @@ use integration_tests::pb::{test_stream_server, InputStream, OutputStream}; use tokio::sync::oneshot; -use tonic::{transport::Server, Request, Response, Status}; +use tonic::{ + transport::{server::Routes, Server}, + Request, Response, Status, +}; type Stream = std::pin::Pin< Box> + Send + 'static>, @@ -25,12 +28,13 @@ async fn status_from_server_stream_with_source() { } let svc = test_stream_server::TestStreamServer::new(Svc); + let routes = Routes::builder().add_service(svc).build(); let (tx, rx) = oneshot::channel::<()>(); let jh = tokio::spawn(async move { Server::builder() - .add_service(svc) + .add_routes(routes) .serve_with_shutdown("127.0.0.1:1339".parse().unwrap(), async { drop(rx.await) }) .await .unwrap(); diff --git a/tests/integration_tests/tests/timeout.rs b/tests/integration_tests/tests/timeout.rs index 450a67d21..0d517d2b7 100644 --- a/tests/integration_tests/tests/timeout.rs +++ b/tests/integration_tests/tests/timeout.rs @@ -1,7 +1,10 @@ use integration_tests::pb::{test_client, test_server, Input, Output}; use std::{net::SocketAddr, time::Duration}; use tokio::net::TcpListener; -use tonic::{transport::Server, Code, Request, Response, Status}; +use tonic::{ + transport::{server::Routes, Server}, + Code, Request, Response, Status, +}; #[tokio::test] async fn cancelation_on_timeout() { @@ -75,6 +78,7 @@ async fn run_service_in_background(latency: Duration, server_timeout: Duration) } let svc = test_server::TestServer::new(Svc { latency }); + let routes = Routes::builder().add_service(svc).build(); let listener = TcpListener::bind("127.0.0.1:0").await.unwrap(); let addr = listener.local_addr().unwrap(); @@ -82,7 +86,7 @@ async fn run_service_in_background(latency: Duration, server_timeout: Duration) tokio::spawn(async move { Server::builder() .timeout(server_timeout) - .add_service(svc) + .add_routes(routes) .serve_with_incoming(tokio_stream::wrappers::TcpListenerStream::new(listener)) .await .unwrap(); diff --git a/tests/integration_tests/tests/user_agent.rs b/tests/integration_tests/tests/user_agent.rs index 46747c97a..d88375149 100644 --- a/tests/integration_tests/tests/user_agent.rs +++ b/tests/integration_tests/tests/user_agent.rs @@ -2,7 +2,7 @@ use integration_tests::pb::{test_client, test_server, Input, Output}; use std::time::Duration; use tokio::sync::oneshot; use tonic::{ - transport::{Endpoint, Server}, + transport::{server::Routes, Endpoint, Server}, Request, Response, Status, }; @@ -21,12 +21,13 @@ async fn writes_user_agent_header() { } let svc = test_server::TestServer::new(Svc); + let routes = Routes::builder().add_service(svc).build(); let (tx, rx) = oneshot::channel::<()>(); let jh = tokio::spawn(async move { Server::builder() - .add_service(svc) + .add_routes(routes) .serve_with_shutdown("127.0.0.1:1322".parse().unwrap(), async { drop(rx.await) }) .await .unwrap(); diff --git a/tonic-reflection/tests/server.rs b/tonic-reflection/tests/server.rs index ab210d5db..19700973f 100644 --- a/tonic-reflection/tests/server.rs +++ b/tonic-reflection/tests/server.rs @@ -2,7 +2,10 @@ use prost::Message; use std::net::SocketAddr; use tokio::sync::oneshot; use tokio_stream::{wrappers::TcpListenerStream, StreamExt}; -use tonic::{transport::Server, Request}; +use tonic::{ + transport::{server::Routes, Server}, + Request, +}; use tonic_reflection::{ pb::{ server_reflection_client::ServerReflectionClient, @@ -102,9 +105,10 @@ async fn make_test_reflection_request(request: ServerReflectionRequest) -> Messa .register_encoded_file_descriptor_set(FILE_DESCRIPTOR_SET) .build() .unwrap(); + let routes = Routes::builder().add_service(service).build(); Server::builder() - .add_service(service) + .add_routes(routes) .serve_with_incoming_shutdown(TcpListenerStream::new(listener), async { drop(shutdown_rx.await) }) diff --git a/tonic-web/tests/integration/tests/grpc.rs b/tonic-web/tests/integration/tests/grpc.rs index 98eca1f92..3de87f631 100644 --- a/tonic-web/tests/integration/tests/grpc.rs +++ b/tonic-web/tests/integration/tests/grpc.rs @@ -6,7 +6,7 @@ use tokio::time::Duration; use tokio::{join, try_join}; use tokio_stream::wrappers::TcpListenerStream; use tokio_stream::{self as stream, StreamExt}; -use tonic::transport::{Channel, Error, Server}; +use tonic::transport::{server::Routes, Channel, Error, Server}; use tonic::{Response, Streaming}; use integration::pb::{test_client::TestClient, test_server::TestServer, Input}; @@ -102,10 +102,11 @@ async fn bind() -> (TcpListener, String) { async fn grpc(accept_h1: bool) -> (impl Future>, String) { let (listener, url) = bind().await; + let routes = Routes::builder().add_service(TestServer::new(Svc)).build(); let fut = Server::builder() .accept_http1(accept_h1) - .add_service(TestServer::new(Svc)) + .add_routes(routes) .serve_with_incoming(TcpListenerStream::new(listener)); (fut, url) @@ -113,11 +114,12 @@ async fn grpc(accept_h1: bool) -> (impl Future>, Stri async fn grpc_web(accept_h1: bool) -> (impl Future>, String) { let (listener, url) = bind().await; + let routes = Routes::builder().add_service(TestServer::new(Svc)).build(); let fut = Server::builder() .accept_http1(accept_h1) .layer(GrpcWebLayer::new()) - .add_service(TestServer::new(Svc)) + .add_routes(routes) .serve_with_incoming(TcpListenerStream::new(listener)); (fut, url) diff --git a/tonic-web/tests/integration/tests/grpc_web.rs b/tonic-web/tests/integration/tests/grpc_web.rs index 3343d754c..c62208583 100644 --- a/tonic-web/tests/integration/tests/grpc_web.rs +++ b/tonic-web/tests/integration/tests/grpc_web.rs @@ -7,7 +7,7 @@ use hyper::{Body, Client, Method, Request, Uri}; use prost::Message; use tokio::net::TcpListener; use tokio_stream::wrappers::TcpListenerStream; -use tonic::transport::Server; +use tonic::transport::{server::Routes, Server}; use integration::pb::{test_server::TestServer, Input, Output}; use integration::Svc; @@ -64,12 +64,13 @@ async fn spawn() -> String { let listener = TcpListener::bind(addr).await.expect("listener"); let url = format!("http://{}", listener.local_addr().unwrap()); let listener_stream = TcpListenerStream::new(listener); + let routes = Routes::builder().add_service(TestServer::new(Svc)).build(); drop(tokio::spawn(async move { Server::builder() .accept_http1(true) .layer(GrpcWebLayer::new()) - .add_service(TestServer::new(Svc)) + .add_routes(routes) .serve_with_incoming(listener_stream) .await .unwrap() diff --git a/tonic/src/transport/server/incoming.rs b/tonic/src/transport/server/incoming.rs index 61aadc93d..dc49a7ed1 100644 --- a/tonic/src/transport/server/incoming.rs +++ b/tonic/src/transport/server/incoming.rs @@ -139,7 +139,7 @@ impl TcpIncoming { /// ```no_run /// # use tower_service::Service; /// # use http::{request::Request, response::Response}; - /// # use tonic::{body::BoxBody, server::NamedService, transport::{Body, Server, server::TcpIncoming}}; + /// # use tonic::{body::BoxBody, server::NamedService, transport::{Body, Server, server::{Routes, TcpIncoming}}}; /// # use core::convert::Infallible; /// # use std::error::Error; /// # fn main() { } // Cannot have type parameters, hence instead define: @@ -157,8 +157,9 @@ impl TcpIncoming { /// Err(_) => port += 1 /// } /// }; + /// let routes = Routes::builder().add_service(some_service).build(); /// Server::builder() - /// .add_service(some_service) + /// .add_routes(routes) /// .serve_with_incoming(tinc); /// # Ok(()) /// # } diff --git a/tonic/src/transport/server/mod.rs b/tonic/src/transport/server/mod.rs index 7f2ffde2b..998b80adc 100644 --- a/tonic/src/transport/server/mod.rs +++ b/tonic/src/transport/server/mod.rs @@ -35,7 +35,6 @@ use crate::transport::Error; use self::recover_error::RecoverError; use super::service::{GrpcTimeout, ServerIo}; -use crate::body::BoxBody; use crate::server::NamedService; use bytes::Bytes; use http::{Request, Response}; @@ -43,7 +42,6 @@ use http_body::Body as _; use hyper::{server::accept, Body}; use pin_project::pin_project; use std::{ - convert::Infallible, fmt, future::{self, Future}, marker::PhantomData, @@ -353,45 +351,6 @@ impl Server { } } - /// Create a router with the `S` typed service as the first service. - /// - /// This will clone the `Server` builder and create a router that will - /// route around different services. - pub fn add_service(&mut self, svc: S) -> Router - where - S: Service, Response = Response, Error = Infallible> - + NamedService - + Clone - + Send - + 'static, - S::Future: Send + 'static, - L: Clone, - { - Router::new(self.clone(), Routes::new(svc)) - } - - /// Create a router with the optional `S` typed service as the first service. - /// - /// This will clone the `Server` builder and create a router that will - /// route around different services. - /// - /// # Note - /// Even when the argument given is `None` this will capture *all* requests to this service name. - /// As a result, one cannot use this to toggle between two identically named implementations. - pub fn add_optional_service(&mut self, svc: Option) -> Router - where - S: Service, Response = Response, Error = Infallible> - + NamedService - + Clone - + Send - + 'static, - S::Future: Send + 'static, - L: Clone, - { - let routes = svc.map(Routes::new).unwrap_or_default(); - Router::new(self.clone(), routes) - } - /// Create a router with given [`Routes`]. /// /// This will clone the `Server` builder and create a router that will @@ -566,46 +525,6 @@ impl Router { } impl Router { - /// Add a new service to this router. - pub fn add_service(mut self, svc: S) -> Self - where - S: Service, Response = Response, Error = Infallible> - + NamedService - + Clone - + Send - + 'static, - S::Future: Send + 'static, - { - self.routes = self.routes.add_service(svc); - self - } - - /// Add a new optional service to this router. - /// - /// # Note - /// Even when the argument given is `None` this will capture *all* requests to this service name. - /// As a result, one cannot use this to toggle between two identically named implementations. - #[allow(clippy::type_complexity)] - pub fn add_optional_service(mut self, svc: Option) -> Self - where - S: Service, Response = Response, Error = Infallible> - + NamedService - + Clone - + Send - + 'static, - S::Future: Send + 'static, - { - if let Some(svc) = svc { - self.routes = self.routes.add_service(svc); - } - self - } - - /// Convert this tonic `Router` into an axum `Router` consuming the tonic one. - pub fn into_router(self) -> axum::Router { - self.routes.into_router() - } - /// Consume this [`Server`] creating a future that will execute the server /// on [tokio]'s default executor. /// @@ -624,7 +543,7 @@ impl Router { .map_err(super::Error::from_source)?; self.server .serve_with_shutdown::<_, _, future::Ready<()>, _, _, ResBody>( - self.routes.prepare(), + self.routes, incoming, None, ) @@ -653,7 +572,7 @@ impl Router { let incoming = TcpIncoming::new(addr, self.server.tcp_nodelay, self.server.tcp_keepalive) .map_err(super::Error::from_source)?; self.server - .serve_with_shutdown(self.routes.prepare(), incoming, Some(signal)) + .serve_with_shutdown(self.routes, incoming, Some(signal)) .await } @@ -681,7 +600,7 @@ impl Router { { self.server .serve_with_shutdown::<_, _, future::Ready<()>, _, _, ResBody>( - self.routes.prepare(), + self.routes, incoming, None, ) @@ -715,7 +634,7 @@ impl Router { ResBody::Error: Into, { self.server - .serve_with_shutdown(self.routes.prepare(), incoming, Some(signal)) + .serve_with_shutdown(self.routes, incoming, Some(signal)) .await } @@ -729,7 +648,7 @@ impl Router { ResBody: http_body::Body + Send + 'static, ResBody::Error: Into, { - self.server.service_builder.service(self.routes.prepare()) + self.server.service_builder.service(self.routes) } } diff --git a/tonic/src/transport/service/router.rs b/tonic/src/transport/service/router.rs index 85636c4d4..4c28abb11 100644 --- a/tonic/src/transport/service/router.rs +++ b/tonic/src/transport/service/router.rs @@ -16,57 +16,27 @@ use tower::ServiceExt; use tower_service::Service; /// A [`Service`] router. -#[derive(Debug, Default, Clone)] +#[derive(Debug, Clone)] pub struct Routes { router: axum::Router, } -#[derive(Debug, Default, Clone)] +#[derive(Debug, Clone)] /// Allows adding new services to routes by passing a mutable reference to this builder. pub struct RoutesBuilder { - routes: Option, + router: axum::Router, } -impl RoutesBuilder { - /// Add a new service. - pub fn add_service(&mut self, svc: S) -> &mut Self - where - S: Service, Response = Response, Error = Infallible> - + NamedService - + Clone - + Send - + 'static, - S::Future: Send + 'static, - S::Error: Into + Send, - { - let routes = self.routes.take().unwrap_or_default(); - self.routes.replace(routes.add_service(svc)); - self - } - - /// Returns the routes with added services or empty [`Routes`] if no service was added - pub fn routes(self) -> Routes { - self.routes.unwrap_or_default() - } -} -impl Routes { - /// Create a new routes with `svc` already added to it. - pub fn new(svc: S) -> Self - where - S: Service, Response = Response, Error = Infallible> - + NamedService - + Clone - + Send - + 'static, - S::Future: Send + 'static, - S::Error: Into + Send, - { +impl Default for RoutesBuilder { + fn default() -> Self { let router = axum::Router::new().fallback(unimplemented); - Self { router }.add_service(svc) + Self { router } } +} +impl RoutesBuilder { /// Add a new service. - pub fn add_service(mut self, svc: S) -> Self + pub fn add_service(self, svc: S) -> Self where S: Service, Response = Response, Error = Infallible> + NamedService @@ -77,18 +47,25 @@ impl Routes { S::Error: Into + Send, { let svc = svc.map_response(|res| res.map(axum::body::boxed)); - self.router = self + let router = self .router .route_service(&format!("/{}/*rest", S::NAME), svc); - self + Self { router } } - pub(crate) fn prepare(self) -> Self { - Self { - // this makes axum perform update some internals of the router that improves perf - // see https://docs.rs/axum/latest/axum/routing/struct.Router.html#a-note-about-performance - router: self.router.with_state(()), - } + /// Returns the routes with added services or empty [`Routes`] if no service was added + pub fn build(self) -> Routes { + // this makes axum perform update some internals of the router that improves perf + // see https://docs.rs/axum/latest/axum/routing/struct.Router.html#a-note-about-performance + let router = self.router.with_state(()); + Routes { router } + } +} + +impl Routes { + /// Create a new routes with `svc` already added to it. + pub fn builder() -> RoutesBuilder { + RoutesBuilder::default() } /// Convert this `Routes` into an [`axum::Router`]. @@ -97,10 +74,13 @@ impl Routes { } } -async fn unimplemented() -> impl axum::response::IntoResponse { - let status = http::StatusCode::OK; - let headers = [("grpc-status", "12"), ("content-type", "application/grpc")]; - (status, headers) +async fn unimplemented() -> Response { + Response::builder() + .status(http::StatusCode::OK) + .header("grpc-status", "12") + .header("content-type", "application/grpc") + .body(crate::body::empty_body()) + .unwrap() } impl Service> for Routes {