xref: /tonic/examples/src/health/server.rs (revision fdda5ae2)
1 use tonic::{transport::Server, Request, Response, Status};
2 
3 use hello_world::greeter_server::{Greeter, GreeterServer};
4 use hello_world::{HelloReply, HelloRequest};
5 use std::time::Duration;
6 use tonic_health::server::HealthReporter;
7 
8 pub mod hello_world {
9     tonic::include_proto!("helloworld");
10 }
11 
12 #[derive(Default)]
13 pub struct MyGreeter {}
14 
15 #[tonic::async_trait]
16 impl Greeter for MyGreeter {
say_hello( &self, request: Request<HelloRequest>, ) -> Result<Response<HelloReply>, Status>17     async fn say_hello(
18         &self,
19         request: Request<HelloRequest>,
20     ) -> Result<Response<HelloReply>, Status> {
21         println!("Got a request from {:?}", request.remote_addr());
22 
23         let reply = hello_world::HelloReply {
24             message: format!("Hello {}!", request.into_inner().name),
25         };
26         Ok(Response::new(reply))
27     }
28 }
29 
30 /// This function (somewhat improbably) flips the status of a service every second, in order
31 /// that the effect of `tonic_health::HealthReporter::watch` can be easily observed.
twiddle_service_status(mut reporter: HealthReporter)32 async fn twiddle_service_status(mut reporter: HealthReporter) {
33     let mut iter = 0u64;
34     loop {
35         iter += 1;
36         tokio::time::sleep(Duration::from_secs(1)).await;
37 
38         if iter % 2 == 0 {
39             reporter.set_serving::<GreeterServer<MyGreeter>>().await;
40         } else {
41             reporter.set_not_serving::<GreeterServer<MyGreeter>>().await;
42         };
43     }
44 }
45 
46 #[tokio::main]
main() -> Result<(), Box<dyn std::error::Error>>47 async fn main() -> Result<(), Box<dyn std::error::Error>> {
48     let (mut health_reporter, health_service) = tonic_health::server::health_reporter();
49     health_reporter
50         .set_serving::<GreeterServer<MyGreeter>>()
51         .await;
52 
53     tokio::spawn(twiddle_service_status(health_reporter.clone()));
54 
55     let addr = "[::1]:50051".parse().unwrap();
56     let greeter = MyGreeter::default();
57 
58     println!("HealthServer + GreeterServer listening on {}", addr);
59 
60     Server::builder()
61         .add_service(health_service)
62         .add_service(GreeterServer::new(greeter))
63         .serve(addr)
64         .await?;
65 
66     Ok(())
67 }
68