GRPC C++  1.62.0
callback_common.h
Go to the documentation of this file.
1 //
2 //
3 // Copyright 2018 gRPC authors.
4 //
5 // Licensed under the Apache License, Version 2.0 (the "License");
6 // you may not use this file except in compliance with the License.
7 // You may obtain a copy of the License at
8 //
9 // http://www.apache.org/licenses/LICENSE-2.0
10 //
11 // Unless required by applicable law or agreed to in writing, software
12 // distributed under the License is distributed on an "AS IS" BASIS,
13 // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
14 // See the License for the specific language governing permissions and
15 // limitations under the License.
16 //
17 //
18 
19 #ifndef GRPCPP_SUPPORT_CALLBACK_COMMON_H
20 #define GRPCPP_SUPPORT_CALLBACK_COMMON_H
21 
22 #include <functional>
23 
24 #include <grpc/grpc.h>
25 #include <grpc/impl/grpc_types.h>
26 #include <grpc/support/log.h>
27 #include <grpcpp/impl/call.h>
30 #include <grpcpp/support/config.h>
31 #include <grpcpp/support/status.h>
32 
33 namespace grpc {
34 namespace internal {
35 
37 // TODO(vjpai): decide whether it is better for this to take a const lvalue
38 // parameter or an rvalue parameter, or if it even matters
39 template <class Func, class... Args>
40 void CatchingCallback(Func&& func, Args&&... args) {
41 #if GRPC_ALLOW_EXCEPTIONS
42  try {
43  func(std::forward<Args>(args)...);
44  } catch (...) {
45  // nothing to return or change here, just don't crash the library
46  }
47 #else // GRPC_ALLOW_EXCEPTIONS
48  func(std::forward<Args>(args)...);
49 #endif // GRPC_ALLOW_EXCEPTIONS
50 }
51 
52 template <class Reactor, class Func, class... Args>
53 Reactor* CatchingReactorGetter(Func&& func, Args&&... args) {
54 #if GRPC_ALLOW_EXCEPTIONS
55  try {
56  return func(std::forward<Args>(args)...);
57  } catch (...) {
58  // fail the RPC, don't crash the library
59  return nullptr;
60  }
61 #else // GRPC_ALLOW_EXCEPTIONS
62  return func(std::forward<Args>(args)...);
63 #endif // GRPC_ALLOW_EXCEPTIONS
64 }
65 
66 // The contract on these tags is that they are single-shot. They must be
67 // constructed and then fired at exactly one point. There is no expectation
68 // that they can be reused without reconstruction.
69 
71  public:
72  // always allocated against a call arena, no memory free required
73  static void operator delete(void* /*ptr*/, std::size_t size) {
74  GPR_ASSERT(size == sizeof(CallbackWithStatusTag));
75  }
76 
77  // This operator should never be called as the memory should be freed as part
78  // of the arena destruction. It only exists to provide a matching operator
79  // delete to the operator new so that some compilers will not complain (see
80  // https://github.com/grpc/grpc/issues/11301) Note at the time of adding this
81  // there are no tests catching the compiler warning.
82  static void operator delete(void*, void*) { GPR_ASSERT(false); }
83 
84  CallbackWithStatusTag(grpc_call* call, std::function<void(Status)> f,
85  CompletionQueueTag* ops)
86  : call_(call), func_(std::move(f)), ops_(ops) {
87  grpc_call_ref(call);
88  functor_run = &CallbackWithStatusTag::StaticRun;
89  // A client-side callback should never be run inline since they will always
90  // have work to do from the user application. So, set the parent's
91  // inlineable field to false
92  inlineable = false;
93  }
95  Status* status_ptr() { return &status_; }
96 
97  // force_run can not be performed on a tag if operations using this tag
98  // have been sent to PerformOpsOnCall. It is intended for error conditions
99  // that are detected before the operations are internally processed.
100  void force_run(Status s) {
101  status_ = std::move(s);
102  Run(true);
103  }
104 
105  private:
106  grpc_call* call_;
107  std::function<void(Status)> func_;
108  CompletionQueueTag* ops_;
109  Status status_;
110 
111  static void StaticRun(grpc_completion_queue_functor* cb, int ok) {
112  static_cast<CallbackWithStatusTag*>(cb)->Run(static_cast<bool>(ok));
113  }
114  void Run(bool ok) {
115  void* ignored = ops_;
116 
117  if (!ops_->FinalizeResult(&ignored, &ok)) {
118  // The tag was swallowed
119  return;
120  }
121  GPR_ASSERT(ignored == ops_);
122 
123  // Last use of func_ or status_, so ok to move them out
124  auto func = std::move(func_);
125  auto status = std::move(status_);
126  func_ = nullptr; // reset to clear this out for sure
127  status_ = Status(); // reset to clear this out for sure
128  CatchingCallback(std::move(func), std::move(status));
129  grpc_call_unref(call_);
130  }
131 };
132 
137  public:
138  // always allocated against a call arena, no memory free required
139  static void operator delete(void* /*ptr*/, std::size_t size) {
140  GPR_ASSERT(size == sizeof(CallbackWithSuccessTag));
141  }
142 
143  // This operator should never be called as the memory should be freed as part
144  // of the arena destruction. It only exists to provide a matching operator
145  // delete to the operator new so that some compilers will not complain (see
146  // https://github.com/grpc/grpc/issues/11301) Note at the time of adding this
147  // there are no tests catching the compiler warning.
148  static void operator delete(void*, void*) { GPR_ASSERT(false); }
149 
150  CallbackWithSuccessTag() : call_(nullptr) {}
151 
154 
156 
157  // Set can only be called on a default-constructed or Clear'ed tag.
158  // It should never be called on a tag that was constructed with arguments
159  // or on a tag that has been Set before unless the tag has been cleared.
160  // can_inline indicates that this particular callback can be executed inline
161  // (without needing a thread hop) and is only used for library-provided server
162  // callbacks.
163  void Set(grpc_call* call, std::function<void(bool)> f,
164  CompletionQueueTag* ops, bool can_inline) {
165  GPR_ASSERT(call_ == nullptr);
166  grpc_call_ref(call);
167  call_ = call;
168  func_ = std::move(f);
169  ops_ = ops;
170  functor_run = &CallbackWithSuccessTag::StaticRun;
171  inlineable = can_inline;
172  }
173 
174  void Clear() {
175  if (call_ != nullptr) {
176  grpc_call* call = call_;
177  call_ = nullptr;
178  func_ = nullptr;
179  grpc_call_unref(call);
180  }
181  }
182 
183  CompletionQueueTag* ops() { return ops_; }
184 
185  // force_run can not be performed on a tag if operations using this tag
186  // have been sent to PerformOpsOnCall. It is intended for error conditions
187  // that are detected before the operations are internally processed.
188  void force_run(bool ok) { Run(ok); }
189 
191  // NOLINTNEXTLINE(google-explicit-constructor)
192  operator bool() const { return call_ != nullptr; }
193 
194  private:
195  grpc_call* call_;
196  std::function<void(bool)> func_;
197  CompletionQueueTag* ops_;
198 
199  static void StaticRun(grpc_completion_queue_functor* cb, int ok) {
200  static_cast<CallbackWithSuccessTag*>(cb)->Run(static_cast<bool>(ok));
201  }
202  void Run(bool ok) {
203  void* ignored = ops_;
204  // Allow a "false" return value from FinalizeResult to silence the
205  // callback, just as it silences a CQ tag in the async cases
206 #ifndef NDEBUG
207  auto* ops = ops_;
208 #endif
209  bool do_callback = ops_->FinalizeResult(&ignored, &ok);
210  GPR_DEBUG_ASSERT(ignored == ops);
211 
212  if (do_callback) {
213  CatchingCallback(func_, ok);
214  }
215  }
216 };
217 
218 } // namespace internal
219 } // namespace grpc
220 
221 #endif // GRPCPP_SUPPORT_CALLBACK_COMMON_H
grpc::internal::CallbackWithSuccessTag
CallbackWithSuccessTag can be reused multiple times, and will be used in this fashion for streaming o...
Definition: callback_common.h:136
grpc::internal::CallbackWithSuccessTag::~CallbackWithSuccessTag
~CallbackWithSuccessTag()
Definition: callback_common.h:155
grpc
An Alarm posts the user-provided tag to its associated completion queue or invokes the user-provided ...
Definition: alarm.h:33
GPR_DEBUG_ASSERT
#define GPR_DEBUG_ASSERT(x)
Definition: log.h:103
grpc::internal::CallbackWithStatusTag::status_ptr
Status * status_ptr()
Definition: callback_common.h:95
GPR_ASSERT
#define GPR_ASSERT(x)
abort() the process if x is zero, having written a line to the log.
Definition: log.h:95
status.h
completion_queue_tag.h
grpc::internal::CallbackWithStatusTag
Definition: callback_common.h:70
grpc_call_ref
GRPCAPI void grpc_call_ref(grpc_call *call)
Ref a call.
grpc::internal::CallbackWithStatusTag::CallbackWithStatusTag
CallbackWithStatusTag(grpc_call *call, std::function< void(Status)> f, CompletionQueueTag *ops)
Definition: callback_common.h:84
grpc_types.h
grpc::Status
Did it work? If it didn't, why?
Definition: status.h:35
grpc::internal::CallbackWithSuccessTag::operator=
CallbackWithSuccessTag & operator=(const CallbackWithSuccessTag &)=delete
grpc_completion_queue_functor::functor_run
void(* functor_run)(struct grpc_completion_queue_functor *, int)
The run member specifies a function that will be called when this tag is extracted from the completio...
Definition: grpc_types.h:450
log.h
grpc_call_unref
GRPCAPI void grpc_call_unref(grpc_call *call)
Unref a call.
grpc::internal::CallbackWithSuccessTag::force_run
void force_run(bool ok)
Definition: callback_common.h:188
grpc.h
grpc_call
struct grpc_call grpc_call
A Call represents an RPC.
Definition: grpc_types.h:70
grpc::internal::CallbackWithStatusTag::force_run
void force_run(Status s)
Definition: callback_common.h:100
grpc::internal::CallbackWithSuccessTag::Clear
void Clear()
Definition: callback_common.h:174
grpc::internal::CompletionQueueTag
An interface allowing implementors to process and filter event tags.
Definition: completion_queue_tag.h:26
grpc::internal::CallbackWithSuccessTag::Set
void Set(grpc_call *call, std::function< void(bool)> f, CompletionQueueTag *ops, bool can_inline)
Definition: callback_common.h:163
channel_interface.h
config.h
grpc::internal::CatchingCallback
void CatchingCallback(Func &&func, Args &&... args)
An exception-safe way of invoking a user-specified callback function.
Definition: callback_common.h:40
grpc::internal::CallbackWithSuccessTag::CallbackWithSuccessTag
CallbackWithSuccessTag()
Definition: callback_common.h:150
std
Definition: async_unary_call.h:405
call.h
grpc::internal::CompletionQueueTag::FinalizeResult
virtual bool FinalizeResult(void **tag, bool *status)=0
FinalizeResult must be called before informing user code that the operation bound to the underlying c...
grpc_completion_queue_functor
Specifies an interface class to be used as a tag for callback-based completion queues.
Definition: grpc_types.h:445
grpc::internal::CatchingReactorGetter
Reactor * CatchingReactorGetter(Func &&func, Args &&... args)
Definition: callback_common.h:53
grpc::protobuf::util::Status
::absl::Status Status
Definition: config_protobuf.h:97
grpc::internal::CallbackWithSuccessTag::ops
CompletionQueueTag * ops()
Definition: callback_common.h:183
grpc::internal::CallbackWithStatusTag::~CallbackWithStatusTag
~CallbackWithStatusTag()
Definition: callback_common.h:94
grpc_completion_queue_functor::inlineable
int inlineable
The inlineable member specifies whether this functor can be run inline.
Definition: grpc_types.h:454