1d9a481baSLucio Franco use tokio::runtime::{Builder, Runtime};
2d9a481baSLucio Franco
3d9a481baSLucio Franco pub mod hello_world {
4d9a481baSLucio Franco tonic::include_proto!("helloworld");
5d9a481baSLucio Franco }
6d9a481baSLucio Franco
7d9a481baSLucio Franco use hello_world::{greeter_client::GreeterClient, HelloReply, HelloRequest};
8d9a481baSLucio Franco
9d9a481baSLucio Franco type StdError = Box<dyn std::error::Error + Send + Sync + 'static>;
10d9a481baSLucio Franco type Result<T, E = StdError> = ::std::result::Result<T, E>;
11d9a481baSLucio Franco
12b7860cc7SSpencer Judge // The order of the fields in this struct is important. They must be ordered
13b7860cc7SSpencer Judge // such that when `BlockingClient` is dropped the client is dropped
14d9a481baSLucio Franco // before the runtime. Not doing this will result in a deadlock when dropped.
15b7860cc7SSpencer Judge // Rust drops struct fields in declaration order.
16d9a481baSLucio Franco struct BlockingClient {
17d9a481baSLucio Franco client: GreeterClient<tonic::transport::Channel>,
18b7860cc7SSpencer Judge rt: Runtime,
19d9a481baSLucio Franco }
20d9a481baSLucio Franco
21d9a481baSLucio Franco impl BlockingClient {
connect<D>(dst: D) -> Result<Self, tonic::transport::Error> where D: TryInto<tonic::transport::Endpoint>, D::Error: Into<StdError>,22d9a481baSLucio Franco pub fn connect<D>(dst: D) -> Result<Self, tonic::transport::Error>
23d9a481baSLucio Franco where
24*bf22a740Stottoto D: TryInto<tonic::transport::Endpoint>,
25d9a481baSLucio Franco D::Error: Into<StdError>,
26d9a481baSLucio Franco {
27fdda5ae2SQuentin Perez let rt = Builder::new_multi_thread().enable_all().build().unwrap();
28d9a481baSLucio Franco let client = rt.block_on(GreeterClient::connect(dst))?;
29d9a481baSLucio Franco
304b0ece6dSDavid Pedersen Ok(Self { client, rt })
31d9a481baSLucio Franco }
32d9a481baSLucio Franco
say_hello( &mut self, request: impl tonic::IntoRequest<HelloRequest>, ) -> Result<tonic::Response<HelloReply>, tonic::Status>33d9a481baSLucio Franco pub fn say_hello(
34d9a481baSLucio Franco &mut self,
35d9a481baSLucio Franco request: impl tonic::IntoRequest<HelloRequest>,
36d9a481baSLucio Franco ) -> Result<tonic::Response<HelloReply>, tonic::Status> {
37d9a481baSLucio Franco self.rt.block_on(self.client.say_hello(request))
38d9a481baSLucio Franco }
39d9a481baSLucio Franco }
40d9a481baSLucio Franco
main() -> Result<()>41d9a481baSLucio Franco fn main() -> Result<()> {
42d9a481baSLucio Franco let mut client = BlockingClient::connect("http://[::1]:50051")?;
43d9a481baSLucio Franco
44d9a481baSLucio Franco let request = tonic::Request::new(HelloRequest {
45d9a481baSLucio Franco name: "Tonic".into(),
46d9a481baSLucio Franco });
47d9a481baSLucio Franco
48d9a481baSLucio Franco let response = client.say_hello(request)?;
49d9a481baSLucio Franco
50d9a481baSLucio Franco println!("RESPONSE={:?}", response);
51d9a481baSLucio Franco
52d9a481baSLucio Franco Ok(())
53d9a481baSLucio Franco }
54