GRPC C++  1.81.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  grpc_call_run_cq_cb(call_, [this, ok]() { Proceed(ok); });
120  }
121  void Proceed(bool ok) {
122  void* ignored = ops_;
123 
124  if (!ops_->FinalizeResult(&ignored, &ok)) {
125  // The tag was swallowed
126  return;
127  }
128  ABSL_CHECK(ignored == ops_);
129 
130  // Last use of func_ or status_, so ok to move them out
131  auto func = std::move(func_);
132  auto status = std::move(status_);
133  func_ = nullptr; // reset to clear this out for sure
134  status_ = Status(); // reset to clear this out for sure
135  GetGlobalCallbackHook()->RunCallback(call_, [func, status]() {
136 #if GRPC_ALLOW_EXCEPTIONS
137  try {
138  func(status);
139  } catch (...) {
140  // nothing to return or change here, just don't crash the library
141  }
142 #else // GRPC_ALLOW_EXCEPTIONS
143  func(status);
144 #endif // GRPC_ALLOW_EXCEPTIONS
145  });
146  grpc_call_unref(call_);
147  }
148 };
149 
154  public:
155  // always allocated against a call arena, no memory free required
156  static void operator delete(void* /*ptr*/, std::size_t size) {
157  ABSL_CHECK_EQ(size, sizeof(CallbackWithSuccessTag));
158  }
159 
160  // This operator should never be called as the memory should be freed as part
161  // of the arena destruction. It only exists to provide a matching operator
162  // delete to the operator new so that some compilers will not complain (see
163  // https://github.com/grpc/grpc/issues/11301) Note at the time of adding this
164  // there are no tests catching the compiler warning.
165  static void operator delete(void*, void*) { ABSL_CHECK(false); }
166 
167  CallbackWithSuccessTag() : call_(nullptr) {}
168 
171 
173 
174  // Set can only be called on a default-constructed or Clear'ed tag.
175  // It should never be called on a tag that was constructed with arguments
176  // or on a tag that has been Set before unless the tag has been cleared.
177  // can_inline indicates that this particular callback can be executed inline
178  // (without needing a thread hop) and is only used for library-provided server
179  // callbacks.
180  void Set(grpc_call* call, std::function<void(bool)> f,
181  CompletionQueueTag* ops, bool can_inline) {
182  ABSL_CHECK_EQ(call_, nullptr);
183  grpc_call_ref(call);
184  call_ = call;
185  func_ = std::move(f);
186  ops_ = ops;
187  functor_run = &CallbackWithSuccessTag::StaticRun;
188  inlineable = can_inline;
189  }
190 
191  void Clear() {
192  if (call_ != nullptr) {
193  grpc_call* call = call_;
194  call_ = nullptr;
195  func_ = nullptr;
196  grpc_call_unref(call);
197  }
198  }
199 
200  CompletionQueueTag* ops() { return ops_; }
201 
202  // force_run can not be performed on a tag if operations using this tag
203  // have been sent to PerformOpsOnCall. It is intended for error conditions
204  // that are detected before the operations are internally processed.
205  void force_run(bool ok) { Run(ok); }
206 
208  // NOLINTNEXTLINE(google-explicit-constructor)
209  operator bool() const { return call_ != nullptr; }
210 
211  private:
212  grpc_call* call_;
213  std::function<void(bool)> func_;
214  CompletionQueueTag* ops_;
215 
216  static void StaticRun(grpc_completion_queue_functor* cb, int ok) {
217  static_cast<CallbackWithSuccessTag*>(cb)->Run(static_cast<bool>(ok));
218  }
219  void Run(bool ok) {
220  grpc_call_run_cq_cb(call_, [this, ok]() { Proceed(ok); });
221  }
222  void Proceed(bool ok) {
223  void* ignored = ops_;
224  // Allow a "false" return value from FinalizeResult to silence the
225  // callback, just as it silences a CQ tag in the async cases
226 #ifndef NDEBUG
227  auto* ops = ops_;
228 #endif
229  bool do_callback = ops_->FinalizeResult(&ignored, &ok);
230 #ifndef NDEBUG
231  ABSL_DCHECK(ignored == ops);
232 #endif
233 
234  if (do_callback) {
235  auto func = func_;
236 
237  // TODO(aananthv): Determine if call_ can be null here. It is
238  // theoretically possible? But I am not sure if the call can be deleted
239  // before this callback is invoked.
240  GetGlobalCallbackHook()->RunCallback(call_, [func, ok]() {
241 #if GRPC_ALLOW_EXCEPTIONS
242  try {
243  func(ok);
244  } catch (...) {
245  // nothing to return or change here, just don't crash the library
246  }
247 #else // GRPC_ALLOW_EXCEPTIONS
248  func(ok);
249 #endif // GRPC_ALLOW_EXCEPTIONS
250  });
251  }
252  }
253 };
254 
255 } // namespace internal
256 } // namespace grpc
257 
258 #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:153
grpc::internal::CallbackWithSuccessTag::~CallbackWithSuccessTag
~CallbackWithSuccessTag()
Definition: callback_common.h:172
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:205
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:191
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:180
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:167
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:200
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