GRPC C++  1.80.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 <grpc/grpc.h>
23 #include <grpc/impl/call.h>
24 #include <grpc/impl/grpc_types.h>
25 #include <grpcpp/impl/call.h>
28 #include <grpcpp/support/config.h>
30 #include <grpcpp/support/status.h>
31 
32 #include <functional>
33 #include <utility>
34 
35 #include "absl/log/absl_check.h"
36 
37 namespace grpc {
38 namespace internal {
39 
41 // TODO(vjpai): decide whether it is better for this to take a const lvalue
42 // parameter or an rvalue parameter, or if it even matters
43 template <class Func, class... Args>
44 void CatchingCallback(Func&& func, Args&&... args) {
45 #if GRPC_ALLOW_EXCEPTIONS
46  try {
47  func(std::forward<Args>(args)...);
48  } catch (...) {
49  // nothing to return or change here, just don't crash the library
50  }
51 #else // GRPC_ALLOW_EXCEPTIONS
52  func(std::forward<Args>(args)...);
53 #endif // GRPC_ALLOW_EXCEPTIONS
54 }
55 
56 template <class Reactor, class Func, class... Args>
57 Reactor* CatchingReactorGetter(Func&& func, Args&&... args) {
58 #if GRPC_ALLOW_EXCEPTIONS
59  try {
60  return func(std::forward<Args>(args)...);
61  } catch (...) {
62  // fail the RPC, don't crash the library
63  return nullptr;
64  }
65 #else // GRPC_ALLOW_EXCEPTIONS
66  return func(std::forward<Args>(args)...);
67 #endif // GRPC_ALLOW_EXCEPTIONS
68 }
69 
70 // The contract on these tags is that they are single-shot. They must be
71 // constructed and then fired at exactly one point. There is no expectation
72 // that they can be reused without reconstruction.
73 
75  public:
76  // always allocated against a call arena, no memory free required
77  static void operator delete(void* /*ptr*/, std::size_t size) {
78  ABSL_CHECK_EQ(size, sizeof(CallbackWithStatusTag));
79  }
80 
81  // This operator should never be called as the memory should be freed as part
82  // of the arena destruction. It only exists to provide a matching operator
83  // delete to the operator new so that some compilers will not complain (see
84  // https://github.com/grpc/grpc/issues/11301) Note at the time of adding this
85  // there are no tests catching the compiler warning.
86  static void operator delete(void*, void*) { ABSL_CHECK(false); }
87 
88  CallbackWithStatusTag(grpc_call* call, std::function<void(Status)>&& f,
89  CompletionQueueTag* ops)
90  : call_(call), func_(std::move(f)), ops_(ops) {
91  grpc_call_ref(call);
92  functor_run = &CallbackWithStatusTag::StaticRun;
93  // A client-side callback should never be run inline since they will always
94  // have work to do from the user application. So, set the parent's
95  // inlineable field to false
96  inlineable = false;
97  }
99  Status* status_ptr() { return &status_; }
100 
101  // force_run can not be performed on a tag if operations using this tag
102  // have been sent to PerformOpsOnCall. It is intended for error conditions
103  // that are detected before the operations are internally processed.
104  void force_run(Status s) {
105  status_ = std::move(s);
106  Run(true);
107  }
108 
109  private:
110  grpc_call* call_;
111  std::function<void(Status)> func_;
112  CompletionQueueTag* ops_;
113  Status status_;
114 
115  static void StaticRun(grpc_completion_queue_functor* cb, int ok) {
116  static_cast<CallbackWithStatusTag*>(cb)->Run(static_cast<bool>(ok));
117  }
118  void Run(bool ok) {
119  void* ignored = ops_;
120 
121  if (!ops_->FinalizeResult(&ignored, &ok)) {
122  // The tag was swallowed
123  return;
124  }
125  ABSL_CHECK(ignored == ops_);
126 
127  // Last use of func_ or status_, so ok to move them out
128  auto func = std::move(func_);
129  auto status = std::move(status_);
130  func_ = nullptr; // reset to clear this out for sure
131  status_ = Status(); // reset to clear this out for sure
132  auto callback = [call = call_, func = std::move(func),
133  status = std::move(status)]() {
134  GetGlobalCallbackHook()->RunCallback(call, [func, status]() {
135 #if GRPC_ALLOW_EXCEPTIONS
136  try {
137  func(status);
138  } catch (...) {
139  // nothing to return or change here, just don't crash the library
140  }
141 #else // GRPC_ALLOW_EXCEPTIONS
142  func(status);
143 #endif // GRPC_ALLOW_EXCEPTIONS
144  });
145  grpc_call_unref(call);
146  };
147 
148  grpc_call_run_cq_cb(call_, std::move(callback));
149  }
150 };
151 
156  public:
157  // always allocated against a call arena, no memory free required
158  static void operator delete(void* /*ptr*/, std::size_t size) {
159  ABSL_CHECK_EQ(size, sizeof(CallbackWithSuccessTag));
160  }
161 
162  // This operator should never be called as the memory should be freed as part
163  // of the arena destruction. It only exists to provide a matching operator
164  // delete to the operator new so that some compilers will not complain (see
165  // https://github.com/grpc/grpc/issues/11301) Note at the time of adding this
166  // there are no tests catching the compiler warning.
167  static void operator delete(void*, void*) { ABSL_CHECK(false); }
168 
169  CallbackWithSuccessTag() : call_(nullptr) {}
170 
173 
175 
176  // Set can only be called on a default-constructed or Clear'ed tag.
177  // It should never be called on a tag that was constructed with arguments
178  // or on a tag that has been Set before unless the tag has been cleared.
179  // can_inline indicates that this particular callback can be executed inline
180  // (without needing a thread hop) and is only used for library-provided server
181  // callbacks.
182  void Set(grpc_call* call, std::function<void(bool)> f,
183  CompletionQueueTag* ops, bool can_inline) {
184  ABSL_CHECK_EQ(call_, nullptr);
185  grpc_call_ref(call);
186  call_ = call;
187  func_ = std::move(f);
188  ops_ = ops;
189  functor_run = &CallbackWithSuccessTag::StaticRun;
190  inlineable = can_inline;
191  }
192 
193  void Clear() {
194  if (call_ != nullptr) {
195  grpc_call* call = call_;
196  call_ = nullptr;
197  func_ = nullptr;
198  grpc_call_unref(call);
199  }
200  }
201 
202  CompletionQueueTag* ops() { return ops_; }
203 
204  // force_run can not be performed on a tag if operations using this tag
205  // have been sent to PerformOpsOnCall. It is intended for error conditions
206  // that are detected before the operations are internally processed.
207  void force_run(bool ok) { Run(ok); }
208 
210  // NOLINTNEXTLINE(google-explicit-constructor)
211  operator bool() const { return call_ != nullptr; }
212 
213  private:
214  grpc_call* call_;
215  std::function<void(bool)> func_;
216  CompletionQueueTag* ops_;
217 
218  static void StaticRun(grpc_completion_queue_functor* cb, int ok) {
219  static_cast<CallbackWithSuccessTag*>(cb)->Run(static_cast<bool>(ok));
220  }
221  void Run(bool ok) {
222  void* ignored = ops_;
223  // Allow a "false" return value from FinalizeResult to silence the
224  // callback, just as it silences a CQ tag in the async cases
225 #ifndef NDEBUG
226  auto* ops = ops_;
227 #endif
228  bool do_callback = ops_->FinalizeResult(&ignored, &ok);
229 #ifndef NDEBUG
230  ABSL_DCHECK(ignored == ops);
231 #endif
232 
233  if (do_callback) {
234  auto callback = [call = call_, func = func_, ok]() {
235  GetGlobalCallbackHook()->RunCallback(call, [func, ok]() {
236 #if GRPC_ALLOW_EXCEPTIONS
237  try {
238  func(ok);
239  } catch (...) {
240  // nothing to return or change here, just don't crash the library
241  }
242 #else // GRPC_ALLOW_EXCEPTIONS
243  func(ok);
244 #endif // GRPC_ALLOW_EXCEPTIONS
245  });
246  };
247 
248  grpc_call_run_cq_cb(call_, std::move(callback));
249  }
250  }
251 };
252 
253 } // namespace internal
254 } // namespace grpc
255 
256 #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:155
grpc::internal::CallbackWithSuccessTag::~CallbackWithSuccessTag
~CallbackWithSuccessTag()
Definition: callback_common.h:174
grpc
An Alarm posts the user-provided tag to its associated completion queue or invokes the user-provided ...
Definition: alarm.h:33
grpc::internal::CallbackWithStatusTag::status_ptr
Status * status_ptr()
Definition: callback_common.h:99
status.h
completion_queue_tag.h
grpc::internal::CallbackWithStatusTag
Definition: callback_common.h:74
grpc_call_ref
GRPCAPI void grpc_call_ref(grpc_call *call)
Ref a call.
grpc_types.h
grpc::Status
Did it work? If it didn't, why?
Definition: status.h:34
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:448
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:207
grpc.h
grpc_call
struct grpc_call grpc_call
A Call represents an RPC.
Definition: grpc_types.h:68
grpc_call_run_cq_cb
void grpc_call_run_cq_cb(const grpc_call *call, absl::AnyInvocable< void()> &&cb)
grpc::internal::CallbackWithStatusTag::force_run
void force_run(Status s)
Definition: callback_common.h:104
grpc::internal::CallbackWithSuccessTag::Clear
void Clear()
Definition: callback_common.h:193
grpc::internal::CallbackWithStatusTag::CallbackWithStatusTag
CallbackWithStatusTag(grpc_call *call, std::function< void(Status)> &&f, CompletionQueueTag *ops)
Definition: callback_common.h:88
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:182
channel_interface.h
config.h
call.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:44
grpc::internal::CallbackWithSuccessTag::CallbackWithSuccessTag
CallbackWithSuccessTag()
Definition: callback_common.h:169
std
Definition: async_unary_call.h:410
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:443
global_callback_hook.h
grpc::GetGlobalCallbackHook
std::shared_ptr< GlobalCallbackHook > GetGlobalCallbackHook()
grpc::internal::CatchingReactorGetter
Reactor * CatchingReactorGetter(Func &&func, Args &&... args)
Definition: callback_common.h:57
grpc::protobuf::util::Status
::absl::Status Status
Definition: config_protobuf.h:107
grpc::internal::CallbackWithSuccessTag::ops
CompletionQueueTag * ops()
Definition: callback_common.h:202
grpc::internal::CallbackWithStatusTag::~CallbackWithStatusTag
~CallbackWithStatusTag()
Definition: callback_common.h:98
grpc_completion_queue_functor::inlineable
int inlineable
The inlineable member specifies whether this functor can be run inline.
Definition: grpc_types.h:452