1 // Copyright 2024 gRPC authors. 2 // 3 // Licensed under the Apache License, Version 2.0 (the "License"); 4 // you may not use this file except in compliance with the License. 5 // You may obtain a copy of the License at 6 // 7 // http://www.apache.org/licenses/LICENSE-2.0 8 // 9 // Unless required by applicable law or agreed to in writing, software 10 // distributed under the License is distributed on an "AS IS" BASIS, 11 // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 12 // See the License for the specific language governing permissions and 13 // limitations under the License. 14 15 #ifndef GRPCPP_SUPPORT_GLOBAL_CALLBACK_HOOK_H 16 #define GRPCPP_SUPPORT_GLOBAL_CALLBACK_HOOK_H 17 18 #include "absl/functional/function_ref.h" 19 20 struct grpc_call; 21 22 namespace grpc { 23 24 class GlobalCallbackHook { 25 public: 26 virtual ~GlobalCallbackHook() = default; 27 virtual void RunCallback(grpc_call* call, 28 absl::FunctionRef<void()> callback) = 0; 29 30 protected: 31 // An exception-safe way of invoking a user-specified callback function. 32 template <class Func, class... Args> CatchingCallback(Func && func,Args &&...args)33 void CatchingCallback(Func&& func, Args&&... args) { 34 #if GRPC_ALLOW_EXCEPTIONS 35 try { 36 func(std::forward<Args>(args)...); 37 } catch (...) { 38 // nothing to return or change here, just don't crash the library 39 } 40 #else // GRPC_ALLOW_EXCEPTIONS 41 func(std::forward<Args>(args)...); 42 #endif // GRPC_ALLOW_EXCEPTIONS 43 } 44 }; 45 46 class DefaultGlobalCallbackHook final : public GlobalCallbackHook { 47 public: RunCallback(grpc_call * call,absl::FunctionRef<void ()> callback)48 void RunCallback(grpc_call* call, 49 absl::FunctionRef<void()> callback) override { 50 CatchingCallback(callback); 51 } 52 }; 53 54 std::shared_ptr<GlobalCallbackHook> GetGlobalCallbackHook(); 55 void SetGlobalCallbackHook(GlobalCallbackHook* hook); 56 } // namespace grpc 57 58 #endif // GRPCPP_SUPPORT_GLOBAL_CALLBACK_HOOK_H 59