You can not select more than 25 topics Topics must start with a chinese character,a letter or number, can include dashes ('-') and can be up to 35 characters long.

callback_common.h 10 kB

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