hyperledger/iroha
Iroha - A simple, decentralized ledger http://iroha.tech
async_grpc_client.hpp
Go to the documentation of this file.
1 
6 #ifndef IROHA_ASYNC_GRPC_CLIENT_HPP
7 #define IROHA_ASYNC_GRPC_CLIENT_HPP
8 
9 #include <ciso646>
10 #include <thread>
11 
12 #include <google/protobuf/empty.pb.h>
13 #include <grpc++/grpc++.h>
14 #include <grpcpp/impl/codegen/async_unary_call.h>
15 #include "logger/logger.hpp"
16 
17 namespace iroha {
18  namespace network {
19 
24  template <typename Response>
25  class AsyncGrpcClient {
26  public:
29  log_(std::move(log)) {}
30 
35  void *got_tag;
36  auto ok = false;
37  while (cq_.Next(&got_tag, &ok)) {
38  auto call = static_cast<AsyncClientCall *>(got_tag);
39  if (not call->status.ok()) {
40  log_->warn("RPC failed: {} {}",
41  call->context.peer(),
42  call->status.error_message());
43  }
44  if (call->on_response) {
45  call->on_response(call->status, call->reply);
46  }
47  delete call;
48  }
49  }
50 
52  cq_.Shutdown();
53  if (thread_.joinable()) {
54  thread_.join();
55  }
56  }
57 
58  grpc::CompletionQueue cq_;
59  std::thread thread_;
60 
64  struct AsyncClientCall {
65  Response reply;
66 
67  grpc::ClientContext context;
68 
70 
71  std::unique_ptr<grpc::ClientAsyncResponseReaderInterface<Response>>
73 
74  std::function<void(grpc::Status &, Response &)> on_response;
75  };
76 
82  template <typename F>
83  void Call(
84  F &&lambda,
85  std::function<void(grpc::Status &, Response &)> on_response = {}) {
86  auto call = new AsyncClientCall;
87  call->on_response = std::move(on_response);
88  call->response_reader = lambda(&call->context, &cq_);
89  call->response_reader->Finish(&call->reply, &call->status, call);
90  }
91 
92  private:
93  logger::LoggerPtr log_;
94  };
95  } // namespace network
96 } // namespace iroha
97 
98 #endif // IROHA_ASYNC_GRPC_CLIENT_HPP
grpc::ClientContext context
Definition: async_grpc_client.hpp:67
AsyncGrpcClient(logger::LoggerPtr log)
Definition: async_grpc_client.hpp:27
Definition: async_grpc_client.hpp:64
Response reply
Definition: async_grpc_client.hpp:65
std::unique_ptr< grpc::ClientAsyncResponseReaderInterface< Response > > response_reader
Definition: async_grpc_client.hpp:72
std::function< void(grpc::Status &, Response &)> on_response
Definition: async_grpc_client.hpp:74
Definition: round.cpp:51
void asyncCompleteRpc()
Definition: async_grpc_client.hpp:34
std::shared_ptr< Logger > LoggerPtr
Definition: logger_fwd.hpp:22
grpc::Status status
Definition: async_grpc_client.hpp:69
Definition: block_query.hpp:15
std::thread thread_
Definition: async_grpc_client.hpp:59
Definition: application.hpp:53
Status
Definition: status.hpp:12
~AsyncGrpcClient()
Definition: async_grpc_client.hpp:51
void Call(F &&lambda, std::function< void(grpc::Status &, Response &)> on_response={})
Definition: async_grpc_client.hpp:83
grpc::CompletionQueue cq_
Definition: async_grpc_client.hpp:58