service_descriptor.h
1 // Copyright 2018, Beeri 15. All rights reserved.
2 // Author: Roman Gershman (romange@gmail.com)
3 //
4 #pragma once
5 
6 #include <functional>
7 
8 #include <google/protobuf/message.h>
9 
10 #include "absl/strings/string_view.h"
11 #include "util/status.h"
12 
13 namespace util {
14 
15 // RPC-Server side part.
16 
17 namespace rpc {
18 
20  public:
21  struct MethodOptions {
22  // Must be power of 2. If not - will be quietly rounded up to power of 2.
23  uint32_t async_level = 0;
24  };
25 
26  using Message = ::google::protobuf::Message;
27  using StreamItemWriter = std::function<void(const Message*)>;
28  using RpcMethodCb = std::function<util::Status(const Message&, Message* msg) noexcept>;
29  using RpcStreamMethodCb = std::function<util::Status(const Message&, StreamItemWriter) noexcept>;
30 
32 
33  virtual ~ServiceDescriptor();
34 
35  virtual size_t GetMethodByHash(absl::string_view method) const = 0;
36 
37  size_t size() const {
38  return methods_.size();
39  }
40 
41  void SetOptions(size_t index, const MethodOptions& opts);
42 
43  // Must be in header file due to size() accessor.
44  // Must be public because RpcBridge needs to access it.
45  // Static descriptor helping rpc framework to reroute generic on-wire envelopes to
46  // specific rpc methods.
47  struct Method {
48  ::std::string name;
49  MethodOptions options;
50 
51  // Only one of those defined.
52  RpcMethodCb single_rpc_method;
53  RpcStreamMethodCb stream_rpc_method;
54 
55  // Factory req/resp creators.
56  const Message* default_req = nullptr;
57  const Message* default_resp = nullptr;
58 
59  // Simple RPC
60  Method(std::string n, RpcMethodCb c, const Message& dreq, const Message& dresp)
61  : name(std::move(n)),
62  single_rpc_method(std::move(c)),
63  default_req(&dreq),
64  default_resp(&dresp) {
65  }
66 
67  // Streaming RPC.
68  Method(std::string n, RpcStreamMethodCb c, const Message& dreq)
69  : name(std::move(n)), stream_rpc_method(std::move(c)), default_req(&dreq) {
70  }
71  };
72 
73  const Method& method(size_t i) const {
74  return methods_[i];
75  }
76 
77  protected:
78  std::vector<Method> methods_; // Generated classes derive from this class and fill this field.
79 };
80 
81 } // namespace rpc
82 } // namespace util