add worker core

Signed-off-by: wupengyong <wupengyong@huawei.com>
This commit is contained in:
wupengyong
2021-08-19 10:01:59 +08:00
parent ca8d31c28b
commit 9dfe2c186f
18 changed files with 2299 additions and 0 deletions
+177
View File
@@ -0,0 +1,177 @@
Apache License
Version 2.0, January 2004
http://www.apache.org/licenses/
TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
1. Definitions.
"License" shall mean the terms and conditions for use, reproduction,
and distribution as defined by Sections 1 through 9 of this document.
"Licensor" shall mean the copyright owner or entity authorized by
the copyright owner that is granting the License.
"Legal Entity" shall mean the union of the acting entity and all
other entities that control, are controlled by, or are under common
control with that entity. For the purposes of this definition,
"control" means (i) the power, direct or indirect, to cause the
direction or management of such entity, whether by contract or
otherwise, or (ii) ownership of fifty percent (50%) or more of the
outstanding shares, or (iii) beneficial ownership of such entity.
"You" (or "Your") shall mean an individual or Legal Entity
exercising permissions granted by this License.
"Source" form shall mean the preferred form for making modifications,
including but not limited to software source code, documentation
source, and configuration files.
"Object" form shall mean any form resulting from mechanical
transformation or translation of a Source form, including but
not limited to compiled object code, generated documentation,
and conversions to other media types.
"Work" shall mean the work of authorship, whether in Source or
Object form, made available under the License, as indicated by a
copyright notice that is included in or attached to the work
(an example is provided in the Appendix below).
"Derivative Works" shall mean any work, whether in Source or Object
form, that is based on (or derived from) the Work and for which the
editorial revisions, annotations, elaborations, or other modifications
represent, as a whole, an original work of authorship. For the purposes
of this License, Derivative Works shall not include works that remain
separable from, or merely link (or bind by name) to the interfaces of,
the Work and Derivative Works thereof.
"Contribution" shall mean any work of authorship, including
the original version of the Work and any modifications or additions
to that Work or Derivative Works thereof, that is intentionally
submitted to Licensor for inclusion in the Work by the copyright owner
or by an individual or Legal Entity authorized to submit on behalf of
the copyright owner. For the purposes of this definition, "submitted"
means any form of electronic, verbal, or written communication sent
to the Licensor or its representatives, including but not limited to
communication on electronic mailing lists, source code control systems,
and issue tracking systems that are managed by, or on behalf of, the
Licensor for the purpose of discussing and improving the Work, but
excluding communication that is conspicuously marked or otherwise
designated in writing by the copyright owner as "Not a Contribution."
"Contributor" shall mean Licensor and any individual or Legal Entity
on behalf of whom a Contribution has been received by Licensor and
subsequently incorporated within the Work.
2. Grant of Copyright License. Subject to the terms and conditions of
this License, each Contributor hereby grants to You a perpetual,
worldwide, non-exclusive, no-charge, royalty-free, irrevocable
copyright license to reproduce, prepare Derivative Works of,
publicly display, publicly perform, sublicense, and distribute the
Work and such Derivative Works in Source or Object form.
3. Grant of Patent License. Subject to the terms and conditions of
this License, each Contributor hereby grants to You a perpetual,
worldwide, non-exclusive, no-charge, royalty-free, irrevocable
(except as stated in this section) patent license to make, have made,
use, offer to sell, sell, import, and otherwise transfer the Work,
where such license applies only to those patent claims licensable
by such Contributor that are necessarily infringed by their
Contribution(s) alone or by combination of their Contribution(s)
with the Work to which such Contribution(s) was submitted. If You
institute patent litigation against any entity (including a
cross-claim or counterclaim in a lawsuit) alleging that the Work
or a Contribution incorporated within the Work constitutes direct
or contributory patent infringement, then any patent licenses
granted to You under this License for that Work shall terminate
as of the date such litigation is filed.
4. Redistribution. You may reproduce and distribute copies of the
Work or Derivative Works thereof in any medium, with or without
modifications, and in Source or Object form, provided that You
meet the following conditions:
(a) You must give any other recipients of the Work or
Derivative Works a copy of this License; and
(b) You must cause any modified files to carry prominent notices
stating that You changed the files; and
(c) You must retain, in the Source form of any Derivative Works
that You distribute, all copyright, patent, trademark, and
attribution notices from the Source form of the Work,
excluding those notices that do not pertain to any part of
the Derivative Works; and
(d) If the Work includes a "NOTICE" text file as part of its
distribution, then any Derivative Works that You distribute must
include a readable copy of the attribution notices contained
within such NOTICE file, excluding those notices that do not
pertain to any part of the Derivative Works, in at least one
of the following places: within a NOTICE text file distributed
as part of the Derivative Works; within the Source form or
documentation, if provided along with the Derivative Works; or,
within a display generated by the Derivative Works, if and
wherever such third-party notices normally appear. The contents
of the NOTICE file are for informational purposes only and
do not modify the License. You may add Your own attribution
notices within Derivative Works that You distribute, alongside
or as an addendum to the NOTICE text from the Work, provided
that such additional attribution notices cannot be construed
as modifying the License.
You may add Your own copyright statement to Your modifications and
may provide additional or different license terms and conditions
for use, reproduction, or distribution of Your modifications, or
for any such Derivative Works as a whole, provided Your use,
reproduction, and distribution of the Work otherwise complies with
the conditions stated in this License.
5. Submission of Contributions. Unless You explicitly state otherwise,
any Contribution intentionally submitted for inclusion in the Work
by You to the Licensor shall be under the terms and conditions of
this License, without any additional terms or conditions.
Notwithstanding the above, nothing herein shall supersede or modify
the terms of any separate license agreement you may have executed
with Licensor regarding such Contributions.
6. Trademarks. This License does not grant permission to use the trade
names, trademarks, service marks, or product names of the Licensor,
except as required for reasonable and customary use in describing the
origin of the Work and reproducing the content of the NOTICE file.
7. Disclaimer of Warranty. Unless required by applicable law or
agreed to in writing, Licensor provides the Work (and each
Contributor provides its Contributions) on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
implied, including, without limitation, any warranties or conditions
of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
PARTICULAR PURPOSE. You are solely responsible for determining the
appropriateness of using or redistributing the Work and assume any
risks associated with Your exercise of permissions under this License.
8. Limitation of Liability. In no event and under no legal theory,
whether in tort (including negligence), contract, or otherwise,
unless required by applicable law (such as deliberate and grossly
negligent acts) or agreed to in writing, shall any Contributor be
liable to You for damages, including any direct, indirect, special,
incidental, or consequential damages of any character arising as a
result of this License or out of the use or inability to use the
Work (including but not limited to damages for loss of goodwill,
work stoppage, computer failure or malfunction, or any and all
other commercial damages or losses), even if such Contributor
has been advised of the possibility of such damages.
9. Accepting Warranty or Additional Liability. While redistributing
the Work or Derivative Works thereof, You may choose to offer,
and charge a fee for, acceptance of support, warranty, indemnity,
or other liability obligations and/or rights consistent with this
License. However, in accepting such obligations, You may act only
on Your own behalf and on Your sole responsibility, not on behalf
of any other Contributor, and only if You agree to indemnify,
defend, and hold each Contributor harmless for any liability
incurred by, or claims asserted against, such Contributor by reason
of your accepting any such warranty or additional liability.
END OF TERMS AND CONDITIONS
+88
View File
@@ -0,0 +1,88 @@
<?xml version="1.0" encoding="UTF-8"?>
<!-- Copyright (c) 2021 Huawei Device Co., Ltd.
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
Notes:
This is project config file for OpenHarmony OSS Audit Tool, if you have any questions or concerns, please email chenyaxun.
-->
<!-- OAT(OSS Audit Tool) configuration guide:
basedir: Root dir, the basedir + project path is the real source file location.
licensefile:
1.If the project don't have "LICENSE" in root dir, please define all the license files in this project in , OAT will check license files according to this rule.
tasklist(only for batch mode):
1. task: Define oat check thread, each task will start a new thread.
2. task name: Only an name, no practical effect.
3. task policy: Default policy for projects under this task, this field is required and the specified policy must defined in policylist.
4. task filter: Default filefilter for projects under this task, this field is required and the specified filefilter must defined in filefilterlist.
5. task project: Projects to be checked, the path field define the source root dir of the project.
policyList:
1. policy: All policyitems will be merged to default OAT.xml rules, the name of policy doesn't affect OAT check process.
2. policyitem: The fields type, name, path, desc is required, and the fields rule, group, filefilter is optional,the default value is:
<policyitem type="" name="" path="" desc="" rule="may" group="defaultGroup" filefilter="defaultPolicyFilter"/>
3. policyitem type:
"compatibility" is used to check license compatibility in the specified path;
"license" is used to check source license header in the specified path;
"copyright" is used to check source copyright header in the specified path;
"import" is used to check source dependency in the specified path, such as import ... ,include ...
"filetype" is used to check file type in the specified path, supported file types: archive, binary
"filename" is used to check whether the specified file exists in the specified path(support projectroot in default OAT.xml), supported file names: LICENSE, README, README.OpenSource
4. policyitem name: This field is used for define the license, copyright, "*" means match all, the "!" prefix means could not match this value. For example, "!GPL" means can not use GPL license.
5. policyitem path: This field is used for define the source file scope to apply this policyitem, the "!" prefix means exclude the files. For example, "!.*/lib/.*" means files in lib dir will be exclude while process this policyitem.
6. policyitem rule and group: These two fields are used together to merge policy results. "may" policyitems in the same group means any one in this group passed, the result will be passed.
7. policyitem filefilter: Used to bind filefilter which define filter rules.
8. filefilter: Filter rules, the type filename is used to filter file name, the type filepath is used to filter file path.
Note:If the text contains special characters, please escape them according to the following rules:
" == &gt;
& == &gt;
' == &gt;
< == &gt;
> == &gt;
-->
<configuration>
<oatconfig>
<licensefile></licensefile>
<policylist>
<policy name="projectPolicy" desc="">
<!--policyitem type="compatibility" name="curl" path=".*" rule="may" group="defaultGroup" filefilter="defaultPolicyFilter" desc=""/-->
<!--policyitem type="compatibility" name="GPL-2.0+" path=".*" desc="不使用或者使用但是是独立进程,被X进程调用,自研进程不受GPL影响"/>
<policyitem type="license" name="LGPL" path=".*" desc="未使用,或者使用了,被X进程以动态链接方式调用"/>
<policyitem type="copyright" name="xxx" path=".*" rule="may" group="defaultGroup" filefilter="copyrightPolicyFilter" desc="xxxx开发代码"/-->
<policyitem type="license" name="BSD-3-Clause" path="adapter/LICENSE" desc="协议友好,且使用符合开源要求"/>
</policy>
</policylist>
<filefilterlist>
<filefilter name="defaultFilter" desc="Files not to check">
</filefilter>
<filefilter name="defaultPolicyFilter" desc="Filters for compatibilitylicense header policies">
</filefilter>
<filefilter name="copyrightPolicyFilter" desc="Filters for copyright header policies" >
</filefilter>
<filefilter name="licenseFileNamePolicyFilter" desc="Filters for LICENSE file policies" >
</filefilter>
<filefilter name="readmeFileNamePolicyFilter" desc="Filters for README file policies" >
</filefilter>
<filefilter name="readmeOpenSourcefileNamePolicyFilter" desc="Filters for README.OpenSource file policies" >
</filefilter>
<filefilter name="binaryFileTypePolicyFilter" desc="Filters for binary file policies" >
</filefilter>
</filefilterlist>
</oatconfig>
</configuration>
+51
View File
@@ -0,0 +1,51 @@
# Copyright (c) 2021 Huawei Device Co., Ltd.
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
import("//build/ohos.gni")
ohos_shared_library("worker") {
include_dirs = [
"//base/compileruntime/js_worker_module/jsapi/worker",
"//base/compileruntime/js_worker_module/jsapi/interfaces/innerkits/worker_core/include",
]
sources = [
"worker/message_queue.cpp",
"worker/native_module_worker.cpp",
"worker/thread.cpp",
"worker/worker.cpp",
"worker/worker_helper.cpp",
"worker/worker_runner.cpp",
]
deps = [
"//base/compileruntime/js_worker_module/jsapi/interfaces/innerkits/worker_core:worker_init",
"//foundation/ace/napi:ace_napi",
"//foundation/ace/napi:ace_napi_quickjs",
]
if (is_standard_system) {
external_deps = [ "hiviewdfx_hilog_native:libhilog" ]
} else {
external_deps = [ "hilog:libhilog" ]
}
subsystem_name = "ccruntime"
part_name = "jsapi_worker"
relative_install_dir = "module"
}
group("jsapi_packages") {
deps = [ ":worker" ]
}
@@ -0,0 +1,39 @@
# Copyright (c) 2021 Huawei Device Co., Ltd.
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
import("//build/ohos.gni")
config("worker_init_config") {
include_dirs = [ "//base/compileruntime/js_worker_module/jsapi/interfaces/innerkits/worker_core/include" ]
}
ohos_shared_library("worker_init") {
include_dirs = [ "//base/compileruntime/js_worker_module/jsapi/interfaces/innerkits/worker_core/include" ]
sources =
[ "//base/compileruntime/js_worker_module/jsapi/worker/worker_init.cpp" ]
deps = [
"//foundation/ace/napi:ace_napi",
"//foundation/ace/napi:ace_napi_quickjs",
]
public_configs = [ ":worker_init_config" ]
subsystem_name = "ccruntime"
part_name = "jsapi_worker"
}
group("jsapi_init_packages") {
deps = [ ":worker_init" ]
}
@@ -0,0 +1,40 @@
/*
* Copyright (c) 2021 Huawei Device Co., Ltd.
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
#ifndef FOUNDATION_CCRUNTIME_JSAPI_INTERFACES_INNERKITS_WORKER_CORE_INCLUDE_H
#define FOUNDATION_CCRUNTIME_JSAPI_INTERFACES_INNERKITS_WORKER_CORE_INCLUDE_H
#include <functional>
#include "native_engine/native_engine.h"
using InitWorkerFunc = std::function<void(NativeEngine*)>;
using GetAssetFunc = std::function<void(const std::string& uri, std::vector<uint8_t>&)>;
using OffWorkerFunc = std::function<void(NativeEngine*)>;
namespace OHOS::CCRuntime::Worker {
class WorkerCore {
public:
static InitWorkerFunc initWorkerFunc;
static void RegisterInitWorkerFunc(InitWorkerFunc func);
static GetAssetFunc getAssertFunc;
static void RegisterAssetFunc(GetAssetFunc func);
static OffWorkerFunc offWorkerFunc;
static void RegisterOffWorkerFunc(OffWorkerFunc func);
};
} // namespace OHOS::CCRuntime::Worker
#endif // FOUNDATION_CCRUNTIME_JSAPI_INTERFACES_INNERKITS_WORKER_CORE_INCLUDE_H
+55
View File
@@ -0,0 +1,55 @@
/*
* Copyright (c) 2021 Huawei Device Co., Ltd.
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
#include "message_queue.h"
namespace OHOS::CCRuntime::Worker {
void MessageQueue::EnQueue(MessageDataType data)
{
queueLock_.lock();
queue_.push(data);
queueLock_.unlock();
}
bool MessageQueue::DeQueue(MessageDataType *data)
{
queueLock_.lock();
if (queue_.empty()) {
queueLock_.unlock();
return false;
}
*data = queue_.front();
queue_.pop();
queueLock_.unlock();
return true;
}
bool MessageQueue::IsEmpty() const
{
return queue_.empty();
}
void MessageQueue::Clear(napi_env env)
{
queueLock_.lock();
size_t size = queue_.size();
for (size_t i = 0; i < size; i++) {
MessageDataType data = queue_.front();
napi_delete_serialization_data(env, data);
queue_.pop();
}
queueLock_.unlock();
}
} // namespace worker
+41
View File
@@ -0,0 +1,41 @@
/*
* Copyright (c) 2021 Huawei Device Co., Ltd.
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
#ifndef FOUNDATION_CCRUNTIME_JSAPI_WORKER_MESSAGE_QUEUE_H
#define FOUNDATION_CCRUNTIME_JSAPI_WORKER_MESSAGE_QUEUE_H
#include <mutex>
#include <queue>
#include "napi/native_api.h"
namespace OHOS::CCRuntime::Worker {
using MessageDataType = napi_value;
class MessageQueue final {
public:
void EnQueue(MessageDataType data);
bool DeQueue(MessageDataType *data);
bool IsEmpty() const;
void Clear(napi_env env);
size_t GetSize() const
{
return queue_.size();
}
private:
std::mutex queueLock_;
std::queue<MessageDataType> queue_;
};
} // namespace OHOS::CCRuntime::Worker
#endif // FOUNDATION_CCRUNTIME_JSAPI_WORKER_MESSAGE_QUEUE_H
+36
View File
@@ -0,0 +1,36 @@
/*
* Copyright (c) 2021 Huawei Device Co., Ltd.
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
#include "worker.h"
/*
* module define
*/
static napi_module g_workerModule = {
.nm_version = 1,
.nm_flags = 0,
.nm_filename = nullptr,
.nm_register_func = OHOS::CCRuntime::Worker::Worker::InitWorker,
.nm_modname = "worker",
.nm_priv = ((void*)0),
.reserved = { 0 },
};
/*
* module register
*/
extern "C" __attribute__((constructor)) void Register()
{
napi_module_register(&g_workerModule);
}
+29
View File
@@ -0,0 +1,29 @@
/*
* Copyright (c) 2021 Huawei Device Co., Ltd.
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
#include "thread.h"
namespace OHOS::CCRuntime::Worker {
Thread::Thread() : tId_() {}
bool Thread::Start()
{
int ret = uv_thread_create(&tId_, [](void* arg) {
Thread* thread = reinterpret_cast<Thread*>(arg);
thread->Run();
}, this);
return ret != 0;
}
} // namespace OHOS::CCRuntime::Worker
+39
View File
@@ -0,0 +1,39 @@
/*
* Copyright (c) 2021 Huawei Device Co., Ltd.
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
#ifndef FOUNDATION_CCRUNTIME_JSAPI_WORKER_THREAD_H
#define FOUNDATION_CCRUNTIME_JSAPI_WORKER_THREAD_H
#include <uv.h>
namespace OHOS::CCRuntime::Worker {
class Thread {
public:
Thread();
virtual ~Thread() = default;
bool Start();
virtual void Run() = 0;
uv_thread_t GetThreadId() const
{
return tId_;
}
private:
uv_thread_t tId_ {0};
};
} // namespace OHOS::CCRuntime::Worker
#endif // #define FOUNDATION_CCRUNTIME_JSAPI_WORKER_THREAD_H
File diff suppressed because it is too large Load Diff
+259
View File
@@ -0,0 +1,259 @@
/*
* Copyright (c) 2021 Huawei Device Co., Ltd.
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
#ifndef FOUNDATION_CCRUNTIME_JSAPI_WORKER_H
#define FOUNDATION_CCRUNTIME_JSAPI_WORKER_H
#include <list>
#include <map>
#include <mutex>
#include <uv.h>
#include "message_queue.h"
#include "napi/native_node_api.h"
#include "native_engine/native_engine.h"
#include "utils/log.h"
#include "worker_helper.h"
#include "worker_runner.h"
namespace OHOS::CCRuntime::Worker {
class Worker {
public:
static const int8_t WORKERPARAMNUM = 2;
enum RunnerState { STARTING, RUNNING, TERMINATEING, TERMINATED };
enum ListenerMode { ONCE, PERMANENT };
enum ScriptMode { CLASSIC, MODULE };
class WorkerListener {
public:
WorkerListener() : callback_(nullptr), worker_(nullptr), mode_(PERMANENT) {}
explicit WorkerListener(Worker* worker) : callback_(nullptr), worker_(worker), mode_(PERMANENT) {}
WorkerListener(Worker* worker, ListenerMode mode) : callback_(nullptr), worker_(worker), mode_(mode) {}
~WorkerListener()
{
callback_ = nullptr;
worker_ = nullptr;
}
bool NextIsAvailable() const
{
return mode_ != ONCE;
}
ListenerMode GetListenerMode() const
{
return mode_;
}
napi_ref GetCallback() const
{
return callback_;
}
void SetCallable(napi_env env, napi_value value)
{
napi_create_reference(env, value, 1, &callback_);
}
void SetMode(ListenerMode mode)
{
mode_ = mode;
}
bool operator==(const WorkerListener& listener) const;
private:
napi_ref callback_ {NULL};
Worker* worker_ {nullptr};
ListenerMode mode_ {PERMANENT};
};
struct FindWorkerListener {
FindWorkerListener(napi_env env, napi_ref ref) : env_(env), ref_(ref) {}
bool operator()(const WorkerListener* listener) const
{
napi_ref compareRef = listener->GetCallback();
napi_value compareObj = nullptr;
napi_get_reference_value(env_, compareRef, &compareObj);
napi_value obj = nullptr;
napi_get_reference_value(env_, ref_, &obj);
bool isEqual = false;
napi_strict_equals(env_, compareObj, obj, &isEqual);
return isEqual;
}
napi_env env_;
napi_ref ref_;
};
using FindWorkerListener = struct FindWorkerListener;
Worker(NativeEngine* env, napi_ref thisVar);
~Worker();
static void MainOnMessage(const uv_async_t* req);
static void MainOnError(const uv_async_t* req);
static void WorkerOnMessage(const uv_async_t* req);
static void ExecuteInThread(const void* data);
static void PrepareForWorkerInstance(const Worker* worker);
static napi_value PostMessage(napi_env env, napi_callback_info cbinfo);
static napi_value PostMessageToMain(napi_env env, napi_callback_info cbinfo);
static napi_value Terminate(napi_env env, napi_callback_info cbinfo);
static napi_value CloseWorker(napi_env env, napi_callback_info cbinfo);
static napi_value On(napi_env env, napi_callback_info cbinfo);
static napi_value Once(napi_env env, napi_callback_info cbinfo);
static napi_value Off(napi_env env, napi_callback_info cbinfo);
static napi_value AddEventListener(napi_env env, napi_callback_info cbinfo);
static napi_value DispatchEvent(napi_env env, napi_callback_info cbinfo);
static napi_value RemoveEventListener(napi_env env, napi_callback_info cbinfo);
static napi_value RemoveAllListener(napi_env env, napi_callback_info cbinfo);
static napi_value AddListener(napi_env env, napi_callback_info cbinfo, ListenerMode mode);
static napi_value RemoveListener(napi_env env, napi_callback_info cbinfo);
static napi_value WorkerConstructor(napi_env env, napi_callback_info cbinfo);
static napi_value InitWorker(napi_env env, napi_value exports);
void StartExecuteInThread(napi_env env, const char* script);
bool UpdateWorkerState(RunnerState runnerState);
bool IsRunning() const
{
return runnerState_.load(std::memory_order_acquire) == RUNNING;
}
bool IsTerminated() const
{
return runnerState_.load(std::memory_order_acquire) >= TERMINATED;
}
bool IsTerminating() const
{
return runnerState_.load(std::memory_order_acquire) == TERMINATEING;
}
void SetScriptMode(ScriptMode mode)
{
scriptMode_ = mode;
}
void AddListenerInner(napi_env env, const char* type, const WorkerListener* listener);
void RemoveListenerInner(napi_env env, const char* type, napi_ref callback);
void RemoveAllListenerInner();
uv_loop_t* GetWorkerLoop() const
{
if (workerEngine_ != nullptr) {
return workerEngine_->GetUVLoop();
}
return nullptr;
}
const NativeEngine* GetWorkerEngine() const
{
return workerEngine_;
}
void SetWorkerEngine(NativeEngine* engine)
{
workerEngine_ = engine;
}
const NativeEngine* GetMainEngine() const
{
return mainEngine_;
}
const char* GetScript() const
{
return script_;
}
const char* GetName() const
{
return name_;
}
uv_loop_t* GetMainLoop() const
{
if (mainEngine_ != nullptr) {
return mainEngine_->GetUVLoop();
}
return nullptr;
}
private:
void WorkerOnMessageInner(const NativeEngine* engine);
void MainOnMessageInner(const NativeEngine* engine);
void MainOnErrorInner(const NativeEngine* engine);
void MainOnMessageErrorInner(const NativeEngine* engine);
void WorkerOnMessageErrorInner(const NativeEngine* engine);
void WorkerOnErrorInner(const NativeEngine* engine, napi_value error);
void HandleException(const NativeEngine* engine);
bool CallWorkerFunction(const NativeEngine* engine, int argc, const napi_value* argv,
const char* methodName, bool tryCatch);
void CallMainFunction(const NativeEngine* engine, int argc, const napi_value* argv, const char* methodName) const;
void HandleEventListeners(napi_env env, napi_value recv, size_t argc, const napi_value* argv, const char* type);
void TerminateInner();
void PostMessageInner(MessageDataType data);
void PostMessageToMainInner(MessageDataType data);
void TerminateWorker();
void CloseInner();
void PublishWorkerOverSignal();
void CloseWorkerCallback();
void CloseMainCallback() const;
char* script_ {nullptr};
char* name_ {nullptr};
ScriptMode scriptMode_ {CLASSIC};
MessageQueue workerMessageQueue_;
MessageQueue mainMessageQueue_;
MessageQueue errorQueue_;
uv_async_t workerOnMessageSignal_;
uv_async_t mainOnMessageSignal_;
uv_async_t mainOnErrorSignal_;
std::atomic<RunnerState> runnerState_;
WorkerRunner* runner_ {nullptr};
NativeEngine* mainEngine_ {nullptr};
NativeEngine* workerEngine_ {nullptr};
napi_ref workerWrapper_ {nullptr};
napi_ref parentPort_ {nullptr};
std::map<std::string, std::list<WorkerListener*>> eventListeners_;
std::mutex workerAsyncMutex_;
friend class WorkerListener;
};
} // namespace OHOS::CCRuntime::Worker
#endif // FOUNDATION_CCRUNTIME_JSAPI_WORKER_H
+116
View File
@@ -0,0 +1,116 @@
/*
* Copyright (c) 2021 Huawei Device Co., Ltd.
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
#include "worker_helper.h"
#include "native_engine/native_value.h"
namespace OHOS::CCRuntime::Worker {
const static int32_t MAXCHARLENGTH = 200;
bool NapiValueHelp::IsString(napi_value value)
{
auto valNative = reinterpret_cast<NativeValue*>(value);
return valNative == nullptr ? false : valNative->TypeOf() == NATIVE_STRING;
}
bool NapiValueHelp::IsArray(napi_value value)
{
auto valNative = reinterpret_cast<NativeValue*>(value);
return valNative == nullptr ? false : valNative->IsArray();
}
bool NapiValueHelp::IsConstructor(napi_env env, napi_callback_info cbInfo)
{
napi_value* funcObj = nullptr;
napi_get_new_target(env, cbInfo, funcObj);
return funcObj != nullptr;
}
size_t NapiValueHelp::GetCallbackInfoArgc(napi_env env, napi_callback_info cbInfo)
{
size_t argc = 0;
napi_get_cb_info(env, cbInfo, &argc, nullptr, nullptr, nullptr);
return argc;
}
napi_value NapiValueHelp::GetNamePropertyInParentPort(napi_env env, napi_ref parentPort, const char* name)
{
napi_value obj = nullptr;
napi_get_reference_value(env, parentPort, &obj);
napi_value value = nullptr;
napi_get_named_property(env, obj, name, &value);
return value;
}
napi_value NapiValueHelp::GetUndefinedValue(napi_env env)
{
napi_value result = nullptr;
napi_get_undefined(env, &result);
return result;
}
bool NapiValueHelp::IsCallable(napi_env env, napi_value value)
{
bool result = false;
napi_is_callable(env, value, &result);
return result;
}
bool NapiValueHelp::IsCallable(napi_env env, napi_ref value)
{
napi_value obj = nullptr;
napi_get_reference_value(env, value, &obj);
if (obj == nullptr) {
return false;
}
return IsCallable(env, obj);
}
void NapiValueHelp::SetNamePropertyInGlobal(napi_env env, const char* name, napi_value value)
{
napi_value object = nullptr;
napi_get_global(env, &object);
napi_set_named_property(env, object, name, value);
}
bool NapiValueHelp::IsObject(napi_value value)
{
auto nativeValue = reinterpret_cast<NativeValue*>(value);
return nativeValue->TypeOf() == NATIVE_OBJECT;
}
char* NapiValueHelp::GetString(napi_env env, napi_value value)
{
size_t bufferSize = 0;
size_t strLength = 0;
napi_get_value_string_utf8(env, value, nullptr, 0, &bufferSize);
if (bufferSize > MAXCHARLENGTH) {
return nullptr;
}
char* buffer = new char[bufferSize + 1] { 0 };
napi_get_value_string_utf8(env, value, buffer, bufferSize + 1, &strLength);
return buffer;
}
napi_value NapiValueHelp::GetBooleanValue(napi_env env, bool value)
{
napi_value result = nullptr;
napi_get_boolean(env, value, &result);
return result;
}
} // namespace OHOS::CCRuntime::Worker
+90
View File
@@ -0,0 +1,90 @@
/*
* Copyright (c) 2021 Huawei Device Co., Ltd.
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
#ifndef FOUNDATION_CCRUNTIME_JSAPI_WORKER_HELP_H
#define FOUNDATION_CCRUNTIME_JSAPI_WORKER_HELP_H
#include "napi/native_api.h"
#include "napi/native_node_api.h"
namespace OHOS::CCRuntime::Worker {
class DereferenceHelp {
public:
template<typename Inner, typename Outer>
static Outer* DereferenceOf(const Inner Outer::*field, const Inner* pointer)
{
if (field != nullptr && pointer != nullptr) {
uintptr_t fieldOffset = (uintptr_t)&(static_cast<Outer*>(0)->*field);
Outer* outPointer = reinterpret_cast<Outer*>((uintptr_t)(pointer) - fieldOffset);
return outPointer;
}
return nullptr;
}
};
class NapiValueHelp {
public:
static bool IsString(napi_value value);
static bool IsArray(napi_value value);
static bool IsConstructor(napi_env env, napi_callback_info cbInfo);
static bool IsCallable(napi_env env, napi_value value);
static bool IsCallable(napi_env env, napi_ref value);
static size_t GetCallbackInfoArgc(napi_env env, napi_callback_info cbInfo);
static napi_value GetNamePropertyInParentPort(napi_env env, napi_ref parentPort, const char* name);
static void SetNamePropertyInGlobal(napi_env env, const char* name, napi_value value);
static napi_value GetUndefinedValue(napi_env env);
static bool IsObject(napi_value value);
static char* GetString(napi_env env, napi_value value);
static napi_value GetBooleanValue(napi_env env, bool value);
};
class CloseHelp {
public:
template<typename T>
static void DeletePointer(const T* value, bool isArray)
{
if (value == nullptr) {
return;
}
if (isArray) {
delete[] value;
} else {
delete value;
}
}
};
template<typename T>
class ObjectScope {
public:
ObjectScope(T* data, bool isArray) : data_(data), isArray_(isArray) {}
~ObjectScope()
{
if (data_ == nullptr) {
return;
}
if (isArray_) {
delete[] data_;
} else {
delete data_;
}
}
private:
T* data_;
bool isArray_;
};
} // namespace OHOS::CCRuntime::Worker
#endif // FOUNDATION_CCRUNTIME_JSAPI_NAPI_VALUE_HELP_H
+43
View File
@@ -0,0 +1,43 @@
/*
* Copyright (c) 2021 Huawei Device Co., Ltd.
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
#include "worker_init.h"
namespace OHOS::CCRuntime::Worker {
InitWorkerFunc WorkerCore::initWorkerFunc = NULL;
GetAssetFunc WorkerCore::getAssertFunc = NULL;
OffWorkerFunc WorkerCore::offWorkerFunc = NULL;
void WorkerCore::RegisterInitWorkerFunc(InitWorkerFunc func)
{
if (func != nullptr) {
WorkerCore::initWorkerFunc = func;
}
}
void WorkerCore::RegisterAssetFunc(GetAssetFunc func)
{
if (func != nullptr) {
WorkerCore::getAssertFunc = func;
}
}
void WorkerCore::RegisterOffWorkerFunc(OffWorkerFunc func)
{
if (func != nullptr) {
WorkerCore::offWorkerFunc = func;
}
}
} // namespace OHOS::CCRuntime::Worker
+51
View File
@@ -0,0 +1,51 @@
/*
* Copyright (c) 2021 Huawei Device Co., Ltd.
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
#include "worker_runner.h"
#include <list>
#include <mutex>
#include "worker_helper.h"
namespace OHOS::CCRuntime::Worker {
WorkerRunner::WorkerRunner(WorkerStartCallback callback) : callback_(callback), selfThreadId_(uv_thread_self()) {}
WorkerRunner::~WorkerRunner()
{
CloseHelp::DeletePointer(workerInnerRunner_, false);
}
void WorkerRunner::WorkerInnerRunner::Run()
{
if (runner_ != nullptr) {
runner_->Run();
}
}
WorkerRunner::WorkerInnerRunner::WorkerInnerRunner(const WorkerRunner* runner) : runner_(runner) {}
void WorkerRunner::Run() const
{
if (callback_.callback != nullptr) {
callback_.callback(callback_.data);
}
}
bool WorkerRunner::Execute()
{
workerInnerRunner_ = new WorkerInnerRunner(this);
return workerInnerRunner_->Start();
}
} // namespace OHOS::CCRuntime::Worker
+62
View File
@@ -0,0 +1,62 @@
/*
* Copyright (c) 2021 Huawei Device Co., Ltd.
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
#ifndef FOUNDATION_CCRUNTIME_JSAPI_WORK_RUNNER_H
#define FOUNDATION_CCRUNTIME_JSAPI_WORK_RUNNER_H
#include <functional>
#include "native_engine/native_engine.h"
#include "thread.h"
namespace OHOS::CCRuntime::Worker {
struct WorkerStartCallback {
using CallbackFunction = std::function<void(void*)>;
explicit WorkerStartCallback(CallbackFunction function = nullptr, void* dataArgs = nullptr)
: callback(function), data(dataArgs)
{}
CallbackFunction callback;
void* data;
};
class WorkerRunner {
public:
// real thread execute
class WorkerInnerRunner : public Thread {
public:
explicit WorkerInnerRunner(const WorkerRunner* runner);
~WorkerInnerRunner() = default;
void Run() override;
private:
const WorkerRunner* runner_;
};
explicit WorkerRunner(WorkerStartCallback callback);
~WorkerRunner();
bool Execute();
void Run() const;
void Stop();
private:
WorkerInnerRunner* workerInnerRunner_ {nullptr};
WorkerStartCallback callback_;
uv_thread_t selfThreadId_ {0};
};
} // namespace OHOS::CCRuntime::Worker
#endif // FOUNDATION_CCRUNTIME_JSAPI_WORK_RUNNER_H
Executable
+28
View File
@@ -0,0 +1,28 @@
{
"subsystem": "ccruntime",
"parts": {
"jsapi": {
"variants": [
"wearable",
"phone"
],
"module_list": [
"//base/compileruntime/js_worker_module/jsapi:jsapi_packages",
"//base/compileruntime/js_worker_module/jsapi/interfaces/innerkits/worker_core:jsapi_init_packages"
],
"inner_kits": [
{
"header": {
"header_base": "//base/compileruntime/js_worker_module/jsapi/interfaces/innerkits/worker_core/include",
"header_files": [
"worker_init.h"
]
},
"name": "//base/compileruntime/js_worker_module/jsapi/interfaces/innerkits/worker_core:worker_init"
}
],
"test_list": [
]
}
}
}