1 /** 2 * Copyright (c) 2024 Huawei Device Co., Ltd. 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 16 #ifndef PANDA_PLUGINS_ETS_RUNTIME_INTEROP_JS_EVENT_LOOP_MODULE_H 17 #define PANDA_PLUGINS_ETS_RUNTIME_INTEROP_JS_EVENT_LOOP_MODULE_H 18 19 #include <uv.h> 20 #include <node_api.h> 21 #include <queue> 22 23 #include "runtime/include/external_callback_poster.h" 24 #include "libpandabase/os/mutex.h" 25 26 namespace ark::ets::interop::js { 27 28 class EventLoopCallbackPoster : public CallbackPoster { 29 class ThreadSafeCallbackQueue { 30 using CallbackQueue = std::queue<WrappedCallback>; 31 32 public: 33 ThreadSafeCallbackQueue() = default; 34 NO_COPY_SEMANTIC(ThreadSafeCallbackQueue); 35 NO_MOVE_SEMANTIC(ThreadSafeCallbackQueue); 36 ~ThreadSafeCallbackQueue() = default; 37 38 void PushCallback(WrappedCallback &&callback, uv_async_t *async); 39 void ExecuteAllCallbacks(); 40 41 private: 42 os::memory::RecursiveMutex lock_; 43 CallbackQueue callbackQueue_ GUARDED_BY(lock_); 44 }; 45 46 public: 47 static_assert(PANDA_ETS_INTEROP_JS); 48 EventLoopCallbackPoster(); 49 ~EventLoopCallbackPoster() override; 50 NO_COPY_SEMANTIC(EventLoopCallbackPoster); 51 NO_MOVE_SEMANTIC(EventLoopCallbackPoster); 52 53 static uv_loop_t *GetEventLoop(); 54 55 private: 56 void PostImpl(WrappedCallback &&callback) override; 57 58 void PostToEventLoop(WrappedCallback &&callback); 59 60 static void AsyncEventToExecuteCallbacks(uv_async_t *async); 61 62 uv_async_t *async_ = nullptr; 63 ThreadSafeCallbackQueue *callbackQueue_; 64 }; 65 66 class EventLoopCallbackPosterFactoryImpl : public CallbackPosterFactoryIface { 67 public: 68 EventLoopCallbackPosterFactoryImpl() = default; 69 ~EventLoopCallbackPosterFactoryImpl() override = default; 70 NO_COPY_SEMANTIC(EventLoopCallbackPosterFactoryImpl); 71 NO_MOVE_SEMANTIC(EventLoopCallbackPosterFactoryImpl); 72 73 /// @brief Method should create a unique instance of CallbackPoster with inputted strategy of posting 74 PandaUniquePtr<CallbackPoster> CreatePoster() override; 75 }; 76 77 } // namespace ark::ets::interop::js 78 79 #endif // PANDA_PLUGINS_ETS_RUNTIME_INTEROP_JS_EVENT_LOOP_MODULE_H 80