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_IMPL_CODEGEN_CALLBACK_COMMON_H
20 #define GRPCPP_IMPL_CODEGEN_CALLBACK_COMMON_H
21
22 #include <functional>
23
24 #include <grpc/impl/codegen/grpc_types.h>
25 #include <grpcpp/impl/codegen/call.h>
26 #include <grpcpp/impl/codegen/channel_interface.h>
27 #include <grpcpp/impl/codegen/completion_queue_tag.h>
28 #include <grpcpp/impl/codegen/config.h>
29 #include <grpcpp/impl/codegen/core_codegen_interface.h>
30 #include <grpcpp/impl/codegen/status.h>
31
32 namespace grpc {
33 namespace internal {
34
35 /// An exception-safe way of invoking a user-specified callback function
36 // TODO(vjpai): decide whether it is better for this to take a const lvalue
37 // parameter or an rvalue parameter, or if it even matters
38 template <class Func, class... Args>
CatchingCallback(Func && func,Args &&...args)39 void CatchingCallback(Func&& func, Args&&... args) {
40 #if GRPC_ALLOW_EXCEPTIONS
41 try {
42 func(std::forward<Args>(args)...);
43 } catch (...) {
44 // nothing to return or change here, just don't crash the library
45 }
46 #else // GRPC_ALLOW_EXCEPTIONS
47 func(std::forward<Args>(args)...);
48 #endif // GRPC_ALLOW_EXCEPTIONS
49 }
50
51 template <class Reactor, class Func, class... Args>
CatchingReactorGetter(Func && func,Args &&...args)52 Reactor* CatchingReactorGetter(Func&& func, Args&&... args) {
53 #if GRPC_ALLOW_EXCEPTIONS
54 try {
55 return func(std::forward<Args>(args)...);
56 } catch (...) {
57 // fail the RPC, don't crash the library
58 return nullptr;
59 }
60 #else // GRPC_ALLOW_EXCEPTIONS
61 return func(std::forward<Args>(args)...);
62 #endif // GRPC_ALLOW_EXCEPTIONS
63 }
64
65 // The contract on these tags is that they are single-shot. They must be
66 // constructed and then fired at exactly one point. There is no expectation
67 // that they can be reused without reconstruction.
68
69 class CallbackWithStatusTag
70 : public grpc_experimental_completion_queue_functor {
71 public:
72 // always allocated against a call arena, no memory free required
delete(void *,std::size_t size)73 static void operator delete(void* /*ptr*/, std::size_t size) {
74 GPR_CODEGEN_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.
delete(void *,void *)82 static void operator delete(void*, void*) { GPR_CODEGEN_ASSERT(false); }
83
CallbackWithStatusTag(grpc_call * call,std::function<void (Status)> f,CompletionQueueTag * ops)84 CallbackWithStatusTag(grpc_call* call, std::function<void(Status)> f,
85 CompletionQueueTag* ops)
86 : call_(call), func_(std::move(f)), ops_(ops) {
87 g_core_codegen_interface->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 }
~CallbackWithStatusTag()94 ~CallbackWithStatusTag() {}
status_ptr()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.
force_run(Status s)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
StaticRun(grpc_experimental_completion_queue_functor * cb,int ok)111 static void StaticRun(grpc_experimental_completion_queue_functor* cb,
112 int ok) {
113 static_cast<CallbackWithStatusTag*>(cb)->Run(static_cast<bool>(ok));
114 }
Run(bool ok)115 void Run(bool ok) {
116 void* ignored = ops_;
117
118 if (!ops_->FinalizeResult(&ignored, &ok)) {
119 // The tag was swallowed
120 return;
121 }
122 GPR_CODEGEN_ASSERT(ignored == ops_);
123
124 // Last use of func_ or status_, so ok to move them out
125 auto func = std::move(func_);
126 auto status = std::move(status_);
127 func_ = nullptr; // reset to clear this out for sure
128 status_ = Status(); // reset to clear this out for sure
129 CatchingCallback(std::move(func), std::move(status));
130 g_core_codegen_interface->grpc_call_unref(call_);
131 }
132 };
133
134 /// CallbackWithSuccessTag can be reused multiple times, and will be used in
135 /// this fashion for streaming operations. As a result, it shouldn't clear
136 /// anything up until its destructor
137 class CallbackWithSuccessTag
138 : public grpc_experimental_completion_queue_functor {
139 public:
140 // always allocated against a call arena, no memory free required
delete(void *,std::size_t size)141 static void operator delete(void* /*ptr*/, std::size_t size) {
142 GPR_CODEGEN_ASSERT(size == sizeof(CallbackWithSuccessTag));
143 }
144
145 // This operator should never be called as the memory should be freed as part
146 // of the arena destruction. It only exists to provide a matching operator
147 // delete to the operator new so that some compilers will not complain (see
148 // https://github.com/grpc/grpc/issues/11301) Note at the time of adding this
149 // there are no tests catching the compiler warning.
delete(void *,void *)150 static void operator delete(void*, void*) { GPR_CODEGEN_ASSERT(false); }
151
CallbackWithSuccessTag()152 CallbackWithSuccessTag() : call_(nullptr) {}
153
154 CallbackWithSuccessTag(const CallbackWithSuccessTag&) = delete;
155 CallbackWithSuccessTag& operator=(const CallbackWithSuccessTag&) = delete;
156
~CallbackWithSuccessTag()157 ~CallbackWithSuccessTag() { Clear(); }
158
159 // Set can only be called on a default-constructed or Clear'ed tag.
160 // It should never be called on a tag that was constructed with arguments
161 // or on a tag that has been Set before unless the tag has been cleared.
162 // can_inline indicates that this particular callback can be executed inline
163 // (without needing a thread hop) and is only used for library-provided server
164 // callbacks.
Set(grpc_call * call,std::function<void (bool)> f,CompletionQueueTag * ops,bool can_inline)165 void Set(grpc_call* call, std::function<void(bool)> f,
166 CompletionQueueTag* ops, bool can_inline) {
167 GPR_CODEGEN_ASSERT(call_ == nullptr);
168 g_core_codegen_interface->grpc_call_ref(call);
169 call_ = call;
170 func_ = std::move(f);
171 ops_ = ops;
172 functor_run = &CallbackWithSuccessTag::StaticRun;
173 inlineable = can_inline;
174 }
175
Clear()176 void Clear() {
177 if (call_ != nullptr) {
178 grpc_call* call = call_;
179 call_ = nullptr;
180 func_ = nullptr;
181 g_core_codegen_interface->grpc_call_unref(call);
182 }
183 }
184
ops()185 CompletionQueueTag* ops() { return ops_; }
186
187 // force_run can not be performed on a tag if operations using this tag
188 // have been sent to PerformOpsOnCall. It is intended for error conditions
189 // that are detected before the operations are internally processed.
force_run(bool ok)190 void force_run(bool ok) { Run(ok); }
191
192 /// check if this tag is currently set
193 /* NOLINTNEXTLINE(google-explicit-constructor) */
194 operator bool() const { return call_ != nullptr; }
195
196 private:
197 grpc_call* call_;
198 std::function<void(bool)> func_;
199 CompletionQueueTag* ops_;
200
StaticRun(grpc_experimental_completion_queue_functor * cb,int ok)201 static void StaticRun(grpc_experimental_completion_queue_functor* cb,
202 int ok) {
203 static_cast<CallbackWithSuccessTag*>(cb)->Run(static_cast<bool>(ok));
204 }
Run(bool ok)205 void Run(bool ok) {
206 void* ignored = ops_;
207 // Allow a "false" return value from FinalizeResult to silence the
208 // callback, just as it silences a CQ tag in the async cases
209 #ifndef NDEBUG
210 auto* ops = ops_;
211 #endif
212 bool do_callback = ops_->FinalizeResult(&ignored, &ok);
213 GPR_CODEGEN_DEBUG_ASSERT(ignored == ops);
214
215 if (do_callback) {
216 CatchingCallback(func_, ok);
217 }
218 }
219 };
220
221 } // namespace internal
222 } // namespace grpc
223
224 #endif // GRPCPP_IMPL_CODEGEN_CALLBACK_COMMON_H
225