Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

node-api: use c-based api for libnode embedding #54660

Draft
wants to merge 23 commits into
base: main
Choose a base branch
from
Draft
Changes from 17 commits
Commits
Show all changes
23 commits
Select commit Hold shift + click to select a range
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
1,087 changes: 1,081 additions & 6 deletions doc/api/embedding.md

Large diffs are not rendered by default.

2 changes: 1 addition & 1 deletion doc/api/index.md
Original file line number Diff line number Diff line change
@@ -16,7 +16,7 @@
* [Buffer](buffer.md)
* [C++ addons](addons.md)
* [C/C++ addons with Node-API](n-api.md)
* [C++ embedder API](embedding.md)
* [C/C++ embedder API](embedding.md)
* [Child processes](child_process.md)
* [Cluster](cluster.md)
* [Command-line options](cli.md)
10 changes: 10 additions & 0 deletions node.gyp
Original file line number Diff line number Diff line change
@@ -110,6 +110,7 @@
'src/node_debug.cc',
'src/node_dir.cc',
'src/node_dotenv.cc',
'src/node_embedding_api.cc',
'src/node_env_var.cc',
'src/node_errors.cc',
'src/node_external_reference.cc',
@@ -223,6 +224,7 @@
'src/module_wrap.h',
'src/node.h',
'src/node_api.h',
'src/node_api_internals.h',
'src/node_api_types.h',
'src/node_binding.h',
'src/node_blob.h',
@@ -234,6 +236,7 @@
'src/node_debug.h',
'src/node_dir.h',
'src/node_dotenv.h',
'src/node_embedding_api.h',
'src/node_errors.h',
'src/node_exit_code.h',
'src/node_external_reference.h',
@@ -1284,6 +1287,13 @@
'sources': [
'src/node_snapshot_stub.cc',
'test/embedding/embedtest.cc',
'test/embedding/embedtest_main.cc',
'test/embedding/embedtest_modules_node_api.cc',
'test/embedding/embedtest_node_api.cc',
'test/embedding/embedtest_node_api.h',
'test/embedding/embedtest_nodejs_main_node_api.cc',
'test/embedding/embedtest_preload_node_api.cc',
'test/embedding/embedtest_threading_node_api.cc',
],

'conditions': [
148 changes: 100 additions & 48 deletions src/api/embed_helpers.cc
Original file line number Diff line number Diff line change
@@ -19,7 +19,24 @@ using v8::TryCatch;

namespace node {

Maybe<ExitCode> SpinEventLoopInternal(Environment* env) {
enum class SpinEventLoopCleanupMode {
kNormal,
kNoCleanup,
};

/**
* Spin the event loop with the provided run_mode.
* For the UV_RUN_DEFAULT it will spin it until there are no pending callbacks
* and then shutdown the environment. Returns a reference to the exit value or
* an empty reference on unexpected exit. If the cleanup_mode is kNoCleanup,
* then the environment will not be cleaned up.
* For the UV_RUN_ONCE and UV_RUN_NOWAIT modes, the cleanup_mode is ignored and
* the environment is not cleaned up.
*/
template <
uv_run_mode run_mode = UV_RUN_DEFAULT,
SpinEventLoopCleanupMode cleanup_mode = SpinEventLoopCleanupMode::kNormal>
Maybe<ExitCode> SpinEventLoopInternalImpl(Environment* env) {
CHECK_NOT_NULL(env);
MultiIsolatePlatform* platform = GetMultiIsolatePlatform(env);
CHECK_NOT_NULL(platform);
@@ -31,62 +48,105 @@ Maybe<ExitCode> SpinEventLoopInternal(Environment* env) {

if (env->is_stopping()) return Nothing<ExitCode>();

env->set_trace_sync_io(env->options()->trace_sync_io);
{
bool more;
env->set_trace_sync_io(env->options()->trace_sync_io);
auto clear_set_trace_sync_io =
OnScopeLeave([env] { env->set_trace_sync_io(false); });

env->performance_state()->Mark(
node::performance::NODE_PERFORMANCE_MILESTONE_LOOP_START);
auto mark_loop_exit = OnScopeLeave([env] {
env->performance_state()->Mark(
node::performance::NODE_PERFORMANCE_MILESTONE_LOOP_EXIT);
});

bool more;
do {
if (env->is_stopping()) break;
uv_run(env->event_loop(), UV_RUN_DEFAULT);
uv_run(env->event_loop(), run_mode);
if (env->is_stopping()) break;

if constexpr (run_mode != UV_RUN_DEFAULT) {
break;
}

platform->DrainTasks(isolate);

more = uv_loop_alive(env->event_loop());
if (more && !env->is_stopping()) continue;
if constexpr (cleanup_mode == SpinEventLoopCleanupMode::kNormal) {
if (more && !env->is_stopping()) continue;

if (EmitProcessBeforeExit(env).IsNothing())
break;
if (EmitProcessBeforeExit(env).IsNothing()) break;

{
HandleScope handle_scope(isolate);
if (env->RunSnapshotSerializeCallback().IsEmpty()) {
break;
{
HandleScope handle_scope(isolate);
if (env->RunSnapshotSerializeCallback().IsEmpty()) {
break;
}
}
}

// Emit `beforeExit` if the loop became alive either after emitting
// event, or after running some callbacks.
more = uv_loop_alive(env->event_loop());
// Emit `beforeExit` again if the loop became alive either after
// emitting event, or after running some callbacks.
more = uv_loop_alive(env->event_loop());
}
} while (more == true && !env->is_stopping());
env->performance_state()->Mark(
node::performance::NODE_PERFORMANCE_MILESTONE_LOOP_EXIT);
}
if (env->is_stopping()) return Nothing<ExitCode>();

env->set_trace_sync_io(false);
// Clear the serialize callback even though the JS-land queue should
// be empty this point so that the deserialized instance won't
// attempt to call into JS again.
env->set_snapshot_serialize_callback(Local<Function>());

env->PrintInfoForSnapshotIfDebug();
env->ForEachRealm([](Realm* realm) { realm->VerifyNoStrongBaseObjects(); });
Maybe<ExitCode> exit_code = EmitProcessExitInternal(env);
if (exit_code.FromMaybe(ExitCode::kGenericUserError) !=
ExitCode::kNoFailure) {
return exit_code;
if constexpr (run_mode == UV_RUN_DEFAULT &&
cleanup_mode == SpinEventLoopCleanupMode::kNormal) {
// Clear the serialize callback even though the JS-land queue should
// be empty this point so that the deserialized instance won't
// attempt to call into JS again.
env->set_snapshot_serialize_callback(Local<Function>());

env->PrintInfoForSnapshotIfDebug();
env->ForEachRealm([](Realm* realm) { realm->VerifyNoStrongBaseObjects(); });
Maybe<ExitCode> exit_code = EmitProcessExitInternal(env);
if (exit_code.FromMaybe(ExitCode::kGenericUserError) !=
ExitCode::kNoFailure) {
return exit_code;
}

auto unsettled_tla = env->CheckUnsettledTopLevelAwait();
if (unsettled_tla.IsNothing()) {
return Nothing<ExitCode>();
}
if (!unsettled_tla.FromJust()) {
return Just(ExitCode::kUnsettledTopLevelAwait);
}
}
return Just(ExitCode::kNoFailure);
}

v8::Maybe<ExitCode> SpinEventLoopInternal(Environment* env) {
return SpinEventLoopInternalImpl(env);
}

auto unsettled_tla = env->CheckUnsettledTopLevelAwait();
if (unsettled_tla.IsNothing()) {
Maybe<int> ExitCodeToInt(Maybe<ExitCode> value) {
if (value.IsNothing()) return Nothing<int>();
return Just(static_cast<int>(value.FromJust()));
}

Maybe<int> SpinEventLoop(Environment* env) {
return ExitCodeToInt(SpinEventLoopInternalImpl(env));
}

v8::Maybe<ExitCode> SpinEventLoopWithoutCleanup(Environment* env,
uv_run_mode run_mode) {
if (run_mode == UV_RUN_DEFAULT) {
return SpinEventLoopInternalImpl<UV_RUN_DEFAULT,
SpinEventLoopCleanupMode::kNoCleanup>(env);
} else if (run_mode == UV_RUN_ONCE) {
return SpinEventLoopInternalImpl<UV_RUN_ONCE,
SpinEventLoopCleanupMode::kNoCleanup>(env);
} else if (run_mode == UV_RUN_NOWAIT) {
return SpinEventLoopInternalImpl<UV_RUN_NOWAIT,
SpinEventLoopCleanupMode::kNoCleanup>(env);
} else {
CHECK(false && "Invalid run_mode");
return Nothing<ExitCode>();
}
if (!unsettled_tla.FromJust()) {
return Just(ExitCode::kUnsettledTopLevelAwait);
}
return Just(ExitCode::kNoFailure);
}

struct CommonEnvironmentSetup::Impl {
@@ -229,18 +289,18 @@ CommonEnvironmentSetup::~CommonEnvironmentSetup() {
}

bool platform_finished = false;
impl_->platform->AddIsolateFinishedCallback(isolate, [](void* data) {
*static_cast<bool*>(data) = true;
}, &platform_finished);
impl_->platform->AddIsolateFinishedCallback(
isolate,
[](void* data) { *static_cast<bool*>(data) = true; },
&platform_finished);
impl_->platform->UnregisterIsolate(isolate);
if (impl_->snapshot_creator.has_value())
impl_->snapshot_creator.reset();
else
isolate->Dispose();

// Wait until the platform has cleaned up all relevant resources.
while (!platform_finished)
uv_run(&impl_->loop, UV_RUN_ONCE);
while (!platform_finished) uv_run(&impl_->loop, UV_RUN_ONCE);
}

if (impl_->isolate || impl_->loop.data != nullptr)
@@ -261,14 +321,6 @@ EmbedderSnapshotData::Pointer CommonEnvironmentSetup::CreateSnapshot() {
return result;
}

Maybe<int> SpinEventLoop(Environment* env) {
Maybe<ExitCode> result = SpinEventLoopInternal(env);
if (result.IsNothing()) {
return Nothing<int>();
}
return Just(static_cast<int>(result.FromJust()));
}

uv_loop_t* CommonEnvironmentSetup::event_loop() const {
return &impl_->loop;
}
2 changes: 1 addition & 1 deletion src/js_native_api.h
Original file line number Diff line number Diff line change
@@ -13,7 +13,7 @@
#else
// The baseline version for N-API.
// The NAPI_VERSION controls which version will be used by default when
// compilling a native addon. If the addon developer specifically wants to use
// compiling a native addon. If the addon developer specifically wants to use
// functions available in a new version of N-API that is not yet ported in all
// LTS versions, they can set NAPI_VERSION knowing that they have specifically
// depended on that version.
10 changes: 7 additions & 3 deletions src/node_api.cc
Original file line number Diff line number Diff line change
@@ -164,9 +164,11 @@ void ThrowNodeApiVersionError(node::Environment* node_env,
node_env->ThrowError(error_message.c_str());
}

inline napi_env NewEnv(v8::Local<v8::Context> context,
const std::string& module_filename,
int32_t module_api_version) {
} // namespace

napi_env NewEnv(v8::Local<v8::Context> context,
const std::string& module_filename,
int32_t module_api_version) {
node_napi_env result;

// Validate module_api_version.
@@ -196,6 +198,8 @@ inline napi_env NewEnv(v8::Local<v8::Context> context,
return result;
}

namespace {

class ThreadSafeFunction : public node::AsyncResource {
public:
ThreadSafeFunction(v8::Local<v8::Function> func,
Loading