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: {}", call->status.error_message());
41  }
42  if (call->on_response) {
43  call->on_response(call->status, call->reply);
44  }
45  delete call;
46  }
47  }
48 
50  cq_.Shutdown();
51  if (thread_.joinable()) {
52  thread_.join();
53  }
54  }
55 
56  grpc::CompletionQueue cq_;
57  std::thread thread_;
58 
62  struct AsyncClientCall {
63  Response reply;
64 
65  grpc::ClientContext context;
66 
68 
69  std::unique_ptr<grpc::ClientAsyncResponseReaderInterface<Response>>
71 
72  std::function<void(grpc::Status &, Response &)> on_response;
73  };
74 
80  template <typename F>
81  void Call(
82  F &&lambda,
83  std::function<void(grpc::Status &, Response &)> on_response = {}) {
84  auto call = new AsyncClientCall;
85  call->on_response = std::move(on_response);
86  call->response_reader = lambda(&call->context, &cq_);
87  call->response_reader->Finish(&call->reply, &call->status, call);
88  }
89 
90  private:
91  logger::LoggerPtr log_;
92  };
93  } // namespace network
94 } // namespace iroha
95 
96 #endif // IROHA_ASYNC_GRPC_CLIENT_HPP
grpc::ClientContext context
Definition: async_grpc_client.hpp:65
AsyncGrpcClient(logger::LoggerPtr log)
Definition: async_grpc_client.hpp:27
Definition: async_grpc_client.hpp:62
Response reply
Definition: async_grpc_client.hpp:63
std::unique_ptr< grpc::ClientAsyncResponseReaderInterface< Response > > response_reader
Definition: async_grpc_client.hpp:70
std::function< void(grpc::Status &, Response &)> on_response
Definition: async_grpc_client.hpp:72
Definition: peer.hpp:48
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:67
Definition: block_query.hpp:15
std::thread thread_
Definition: async_grpc_client.hpp:57
Definition: on_demand_ordering_init.hpp:44
Status
Definition: status.hpp:12
~AsyncGrpcClient()
Definition: async_grpc_client.hpp:49
void Call(F &&lambda, std::function< void(grpc::Status &, Response &)> on_response={})
Definition: async_grpc_client.hpp:81
grpc::CompletionQueue cq_
Definition: async_grpc_client.hpp:56