diff --git a/examples/Cargo.toml b/examples/Cargo.toml index 4f72329..7f29b99 100644 --- a/examples/Cargo.toml +++ b/examples/Cargo.toml @@ -106,6 +106,10 @@ path = "src/hyper_warp/server.rs" name = "health-server" path = "src/health/server.rs" +[[bin]] +name = "autoreload-server" +path = "src/autoreload/server.rs" + [dependencies] tonic = { path = "../tonic", features = ["tls"] } prost = "0.6" @@ -132,6 +136,7 @@ http-body = "0.3" pin-project = "0.4" # Health example tonic-health = { path = "../tonic-health" } +listenfd = "0.3" [build-dependencies] tonic-build = { path = "../tonic-build", features = ["prost"] } diff --git a/examples/README.md b/examples/README.md index d1217c7..1783b4b 100644 --- a/examples/README.md +++ b/examples/README.md @@ -80,6 +80,13 @@ $ cargo run --bin tls-server $ cargo run --bin health-server ``` +## Autoreloading Server + +### Server +```bash +systemfd --no-pid -s http::[::1]:50051 -- cargo watch -x 'run --bin autoreload-server' +``` + ### Notes: If you are using the `codegen` feature, then the following dependencies are @@ -89,3 +96,7 @@ If you are using the `codegen` feature, then the following dependencies are * [prost](https://crates.io/crates/prost) * [prost-derive](https://crates.io/crates/prost-derive) +The autoload example requires the following crates installed globally: + +* [systemfd](https://crates.io/crates/systemfd) +* [cargo-watch](https://crates.io/crates/cargo-watch) diff --git a/examples/src/autoreload/server.rs b/examples/src/autoreload/server.rs new file mode 100644 index 0000000..a4b713a --- /dev/null +++ b/examples/src/autoreload/server.rs @@ -0,0 +1,49 @@ +use tonic::{transport::Server, Request, Response, Status}; + +use hello_world::greeter_server::{Greeter, GreeterServer}; +use hello_world::{HelloReply, HelloRequest}; + +pub mod hello_world { + tonic::include_proto!("helloworld"); +} + +#[derive(Default)] +pub struct MyGreeter {} + +#[tonic::async_trait] +impl Greeter for MyGreeter { + async fn say_hello( + &self, + request: Request, + ) -> Result, Status> { + println!("Got a request from {:?}", request.remote_addr()); + + let reply = hello_world::HelloReply { + message: format!("Hello {}!", request.into_inner().name), + }; + Ok(Response::new(reply)) + } +} + +#[tokio::main] +async fn main() -> Result<(), Box> { + let addr = "[::1]:50051".parse().unwrap(); + let greeter = MyGreeter::default(); + + println!("GreeterServer listening on {}", addr); + + let server = Server::builder().add_service(GreeterServer::new(greeter)); + + match listenfd::ListenFd::from_env().take_tcp_listener(0)? { + Some(listener) => { + let mut listener = tokio::net::TcpListener::from_std(listener)?; + + server.serve_with_incoming(listener.incoming()).await?; + } + None => { + server.serve(addr).await?; + } + } + + Ok(()) +}