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
Show file tree
Hide file tree
Changes from all 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,260 changes: 1,258 additions & 2 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
Expand Up @@ -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)
Expand Down
12 changes: 12 additions & 0 deletions node.gyp
Original file line number Diff line number Diff line change
Expand Up @@ -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',
Expand Down Expand Up @@ -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',
Expand All @@ -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',
Expand Down Expand Up @@ -1273,6 +1276,15 @@
'sources': [
'src/node_snapshot_stub.cc',
'test/embedding/embedtest.cc',
'test/embedding/embedtest_c_api.cc',
'test/embedding/embedtest_c_api_common.cc',
'test/embedding/embedtest_c_api_common.h',
'test/embedding/embedtest_c_api_env.cc',
'test/embedding/embedtest_c_api_modules.cc',
'test/embedding/embedtest_c_api_preload.cc',
'test/embedding/embedtest_c_api_run_main.cc',
'test/embedding/embedtest_c_api_threading.cc',
'test/embedding/embedtest_main.cc',
],

'conditions': [
Expand Down
148 changes: 100 additions & 48 deletions src/api/embed_helpers.cc
Original file line number Diff line number Diff line change
Expand Up @@ -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);
Expand All @@ -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 {
Expand Down Expand Up @@ -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)
Expand All @@ -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;
}
Expand Down
2 changes: 1 addition & 1 deletion src/js_native_api.h
Original file line number Diff line number Diff line change
Expand Up @@ -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.
Expand Down
31 changes: 24 additions & 7 deletions src/js_native_api_v8.h
Original file line number Diff line number Diff line change
Expand Up @@ -85,14 +85,31 @@ struct napi_env__ {
// v8 uses a special exception to indicate termination, the
// `handle_exception` callback should identify such case using
// terminatedOrTerminating() before actually handle the exception
template <typename T, typename U = decltype(HandleThrow)>
inline void CallIntoModule(T&& call, U&& handle_exception = HandleThrow) {
int open_handle_scopes_before = open_handle_scopes;
int open_callback_scopes_before = open_callback_scopes;
napi_clear_last_error(this);
template <typename Call, typename JSExceptionHandler = decltype(HandleThrow)>
inline void CallIntoModule(
Call&& call, JSExceptionHandler&& handle_exception = HandleThrow) {
CallModuleScopeData scope_data = OpenCallModuleScope();
auto onModuleScopeLeave = node::OnScopeLeave(
[&] { CloseCallModuleScope(scope_data, handle_exception); });
call(this);
CHECK_EQ(open_handle_scopes, open_handle_scopes_before);
CHECK_EQ(open_callback_scopes, open_callback_scopes_before);
}

struct CallModuleScopeData {
int open_handle_scopes_before;
int open_callback_scopes_before;
};

inline CallModuleScopeData OpenCallModuleScope() {
napi_clear_last_error(this);
return {open_handle_scopes, open_callback_scopes};
}

template <typename JSExceptionHandler = decltype(HandleThrow)>
inline void CloseCallModuleScope(
const CallModuleScopeData& scope_data,
JSExceptionHandler&& handle_exception = HandleThrow) {
CHECK_EQ(open_handle_scopes, scope_data.open_handle_scopes_before);
CHECK_EQ(open_callback_scopes, scope_data.open_callback_scopes_before);
if (!last_exception.IsEmpty()) {
handle_exception(this, last_exception.Get(this->isolate));
last_exception.Reset();
Expand Down
10 changes: 7 additions & 3 deletions src/node_api.cc
Original file line number Diff line number Diff line change
Expand Up @@ -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.
Expand Down Expand Up @@ -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,
Expand Down
Loading