Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
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
141 changes: 100 additions & 41 deletions src/runtime/napi/napi_body.rs
Original file line number Diff line number Diff line change
Expand Up @@ -2707,12 +2707,31 @@ impl ThreadSafeFunction {

/// `Ok(true)`: a queued call ran (what it threw has been reported), keep
/// draining. `Err`: the VM is stopping.
///
/// This can run several times in one tick of the event loop, so the
/// microtasks one call queued are drained before the next call
/// (https://github.com/nodejs/node/pull/38506), but not before the first.
pub(crate) fn dispatch_one(&mut self, is_first: bool) -> Result<bool, bun_jsc::Stopped> {
let mut queue_finalizer_after_call = false;
let task = 'brk: {
// `MutexGuard` holds the lock by raw pointer, so it does not borrow
// `*self` across the `&mut self` calls below.
let _g = self.lock.lock_guard();
if self.is_closing() {
// Closing (napi_tsfn_abort, or the last call already ran):
// nothing still queued runs any more, as in Node's DispatchOne.
// An abort's leftovers go back to the addon, with no lock held
// since that re-enters it; the function finalizes once the last
// thread reference is gone.
let leftovers = self.take_queue();
drop(_g);
self.hand_back(leftovers);
let _g = self.lock.lock_guard();
if self.thread_count.load(Ordering::SeqCst) == 0 {
self.maybe_queue_finalizer();
}
return Ok(false);
}
let was_blocked = self.queue.is_blocked();
let Some(t) = self.queue.data.read_item() else {
// When there are no tasks and the number of threads that have
Expand Down Expand Up @@ -2743,7 +2762,11 @@ impl ThreadSafeFunction {
break 'brk t;
};

let called = self.call(task, is_first);
let called = match self.loop_mut() {
Some(loop_) if !is_first => loop_.drain_microtasks(),
_ => Ok(()),
}
.and_then(|()| self.call(task));

// The last queued call finalizes even when the VM is stopping.
if queue_finalizer_after_call {
Expand All @@ -2756,28 +2779,29 @@ impl ThreadSafeFunction {
Ok(true)
}

/// This function can be called multiple times in one tick of the event loop.
/// See: https://github.com/nodejs/node/pull/38506
/// In that case, we need to drain microtasks.
/// One queued call: a JS entry of its own, so what it leaves pending is
/// folded here. `Err`: the VM is stopping.
fn call(&mut self, task: *mut c_void, is_first: bool) -> Result<(), bun_jsc::Stopped> {
/// One queued call from the drain, which is its landing frame: what it
/// left pending is folded here. `Err`: the VM is stopping.
fn call(&mut self, task: *mut c_void) -> Result<(), bun_jsc::Stopped> {
let Some(env) = self.env.as_ref().map(NapiEnvRef::get) else {
// env torn down; nothing to call into.
return Ok(());
};
// SAFETY: env is valid while the TSF is live.
let global_object = unsafe { &*env }.to_js();
if !is_first {
let Some(loop_) = self.loop_mut() else {
return Ok(());
};
loop_.drain_microtasks()?;
let env = unsafe { &*env };
match self.deliver(env, task) {
Ok(()) => Ok(()),
Err(err) => bun_jsc::task::report_error_or_terminate(env.to_js(), err),
}
}

/// One queued call: a JS entry of its own, so what it leaves pending is
/// the `Err`, for the caller's landing frame to fold. `env` is this
/// function's own, which `self.env` still holds.
fn deliver(&mut self, env: &NapiEnv, task: *mut c_void) -> JsResult<()> {
let global_object = env.to_js();
let _dispatch = self.tracker.dispatch(global_object);

let called = match &self.callback {
match &self.callback {
TsfnCallback::Js(strong) => {
let js: JSValue = strong.get().unwrap_or(JSValue::UNDEFINED);
if js.is_empty_or_undefined_or_null() {
Expand All @@ -2790,21 +2814,45 @@ impl ThreadSafeFunction {
js: cb_js,
napi_threadsafe_function_call_js,
} => {
// SAFETY: `env` is held alive by `self.env` (`NapiEnvRef`) for the TSF's lifetime.
let env_ref = unsafe { &*env };
let _hs = NapiHandleScope::open_scoped(env_ref);
let _hs = NapiHandleScope::open_scoped(env);
// No func at creation => null js_callback (Node), not encoded undefined.
let js = match cb_js.get() {
Some(v) => napi_value::create(env_ref, v),
Some(v) => napi_value::create(env, v),
None => napi_value(0),
};
napi_threadsafe_function_call_js(env, js, self.ctx, task);
env_ref.surface_exception(global_object)
napi_threadsafe_function_call_js(env.as_mut_ptr(), js, self.ctx, task);
env.surface_exception(global_object)
}
}
}

/// Caller holds `lock`. Empties the queue; the items are the caller's to
/// give back to the addon once the lock is dropped.
fn take_queue(&mut self) -> Vec<*mut c_void> {
let mut items = Vec::new();
while let Some(item) = self.queue.data.read_item() {
items.push(item);
}
self.queue.count.store(0, Ordering::SeqCst);
items
}

/// What a closing function does with items it will never run: each goes
/// back to the addon's call_js_cb with a null env and js_callback, which is
/// the signal napi_threadsafe_function_call_js documents for "free this,
/// JS is no longer reachable" (Node's ThreadSafeFunction::EmptyQueue). A
/// function created without a call_js_cb has nothing to give back.
fn hand_back(&self, items: Vec<*mut c_void>) {
let TsfnCallback::C {
napi_threadsafe_function_call_js,
..
} = &self.callback
else {
return;
};
match called {
Ok(()) => Ok(()),
Err(err) => bun_jsc::task::report_error_or_terminate(global_object, err),
let call_js = *napi_threadsafe_function_call_js;
for item in items {
call_js(ptr::null_mut(), napi_value(0), self.ctx, item);
}
}

Expand Down Expand Up @@ -2954,10 +3002,11 @@ impl ThreadSafeFunction {
// Phase 1: publish "the loop is going away". From here no other thread
// schedules onto it, but none may free us either -- the JS resources
// below are still live and only this thread may touch them.
let drained: Vec<*mut c_void> = {
let (was_closing, queued) = {
let _g = self.lock.lock_guard();
self.env_dead.store(true, Ordering::SeqCst);
if self.closing.load(Ordering::SeqCst) == ClosingState::NotClosing as u8 {
let was_closing = self.is_closing();
if !was_closing {
self.closing
.store(ClosingState::Closing as u8, Ordering::SeqCst);
}
Expand All @@ -2966,25 +3015,35 @@ impl ThreadSafeFunction {
// is_closing and release.
self.blocking_condvar.broadcast();
}
let mut drained = Vec::new();
while let Some(item) = self.queue.data.read_item() {
drained.push(item);
}
self.queue.count.store(0, Ordering::SeqCst);
drained
(was_closing, self.take_queue())
};

// Phase 2: addon callbacks, so no lock is held. Node hands queued items
// back with a null env (ThreadSafeFunction::EmptyQueue) so the addon can
// free them, then runs the finalizer.
if let TsfnCallback::C {
napi_threadsafe_function_call_js,
..
} = &self.callback
// Phase 2: addon callbacks, so no lock is held.
//
// What is still queued goes back to the addon only when a worker's env
// dies under it. On the main thread this is process exit, where Node
// runs nothing of a threadsafe function; most call_js_cbs cannot take
// the null env a hand-back would give them (they abort), and a
// process.exit() from inside one of them would re-enter it. The queue
// dies with the process. In a worker the items arrive as Node's last
// turn of the loop (CleanupHandles) delivers them: the normal call,
// live env and js_callback, with script refused if the worker was
// stopped. A function already closing (napi_tsfn_abort) keeps the
// abort contract. The finalizer runs either way.
//
// SAFETY: `env` is live; phase 3 below is what drops our reference.
let env = self.env.as_ref().map(|env| unsafe { &*env.get() });
if let Some(env) = env
&& env.to_js().bun_vm().worker_ref().is_some()
{
let call_js = *napi_threadsafe_function_call_js;
for item in drained {
call_js(ptr::null_mut(), napi_value(0), self.ctx, item);
if was_closing {
self.hand_back(queued);
} else if matches!(self.callback, TsfnCallback::C { .. }) {
for item in queued {
// The env's cleanup hook is each delivery's landing frame,
// as it is the finalizer's below.
crate::dispatch::fold(self.deliver(env, item));
}
}
}
let finalizer = self
Expand Down
97 changes: 97 additions & 0 deletions test/napi/napi-app/async_tests.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,8 @@
#include <atomic>
#include <cassert>
#include <chrono>
#include <cstdint>
#include <cstdio>
#include <mutex>
#include <thread>
#include <vector>
Expand Down Expand Up @@ -555,7 +557,102 @@ napi_value late_finalizer_run_count(const Napi::CallbackInfo &info) {
return Napi::Number::New(info.Env(), late_finalizer_runs.load());
}

// What happens to the items still queued on a threadsafe function when it
// stops being dispatched: process exit, the creating worker's exit or
// termination, or napi_tsfn_abort. Everything is printed from here (not from
// JS: a worker's console.log reaches stdout asynchronously) and compared with
// node's output. `data` carries the item number.
static napi_threadsafe_function queued_items_tsfn = nullptr;
static bool queued_items_tsfn_print_finalize = false;
static bool queued_items_tsfn_finalized = false;

static void queued_items_call_js(napi_env env, napi_value js_callback,
void *context, void *data) {
int item = static_cast<int>(reinterpret_cast<intptr_t>(data));
if (env == nullptr) {
// The napi_threadsafe_function_call_js contract for an item that will
// never run: free it. js_callback is null along with env.
printf("call_js: item %d, env null, js_callback %s\n", item,
js_callback == nullptr ? "null" : "set");
fflush(stdout);
return;
}
printf("call_js: item %d, env live, js_callback %s\n", item,
js_callback == nullptr ? "null" : "set");
fflush(stdout);
if (js_callback == nullptr) {
return;
}
napi_value undefined;
if (napi_get_undefined(env, &undefined) != napi_ok) {
printf("call_js: item %d, napi_get_undefined failed\n", item);
fflush(stdout);
return;
}
// Refused (napi_cannot_run_js, 23, for this addon's Node-API version) once
// the env is being torn down. In one test the JS callback exits the process,
// and this does not return.
napi_status status =
napi_call_function(env, undefined, js_callback, 0, nullptr, nullptr);
printf("call_js: item %d, call_function %d\n", item,
static_cast<int>(status));
fflush(stdout);
}

static void queued_items_finalize(napi_env env, void *data, void *hint) {
queued_items_tsfn_finalized = true;
if (queued_items_tsfn_print_finalize) {
printf("finalize: env %s\n", env == nullptr ? "null" : "live");
fflush(stdout);
}
}

// queue_threadsafe_function_items(js_callback, count, print_finalize): creates
// the function (one thread reference, which is never released) and queues
// `count` items from this thread. They sit in the queue until the caller
// returns to the event loop. Node runs no finalizer on process.exit() and bun
// does, so the tests that exit the process do not print it.
napi_value queue_threadsafe_function_items(const Napi::CallbackInfo &info) {
napi_env env = info.Env();
int count = info[1].As<Napi::Number>().Int32Value();
queued_items_tsfn_print_finalize = info[2].As<Napi::Boolean>().Value();
queued_items_tsfn_finalized = false;
napi_value name;
NODE_API_CALL(env, napi_create_string_utf8(env, "napitests::queued_items",
NAPI_AUTO_LENGTH, &name));
NODE_API_CALL(env, napi_create_threadsafe_function(
env, info[0], nullptr, name,
/* max_queue_size (unlimited) */ 0,
/* initial_thread_count */ 1,
/* thread_finalize_data */ nullptr,
queued_items_finalize, /* context */ nullptr,
queued_items_call_js, &queued_items_tsfn));
for (intptr_t item = 1; item <= count; item++) {
NODE_API_CALL(env, napi_call_threadsafe_function(
queued_items_tsfn, reinterpret_cast<void *>(item),
napi_tsfn_nonblocking));
}
return info.Env().Undefined();
}

napi_value
abort_threadsafe_function_with_queued_items(const Napi::CallbackInfo &info) {
napi_status status =
napi_release_threadsafe_function(queued_items_tsfn, napi_tsfn_abort);
queued_items_tsfn = nullptr;
return Napi::Number::New(info.Env(), static_cast<double>(status));
}

napi_value threadsafe_function_with_queued_items_finalized(
const Napi::CallbackInfo &info) {
return Napi::Boolean::New(info.Env(), queued_items_tsfn_finalized);
}

void register_async_tests(Napi::Env env, Napi::Object exports) {
REGISTER_FUNCTION(env, exports, queue_threadsafe_function_items);
REGISTER_FUNCTION(env, exports, abort_threadsafe_function_with_queued_items);
REGISTER_FUNCTION(env, exports,
threadsafe_function_with_queued_items_finalized);
REGISTER_FUNCTION(env, exports, create_object_whose_finalizer_creates_external_buffer);
REGISTER_FUNCTION(env, exports, late_finalizer_run_count);
REGISTER_FUNCTION(env, exports, create_promise);
Expand Down
58 changes: 58 additions & 0 deletions test/napi/napi-app/module.js
Original file line number Diff line number Diff line change
Expand Up @@ -1586,6 +1586,64 @@ nativeTests.test_threadsafe_function_orphan_leak = async () => {
}
};

// Items still queued on a threadsafe function when the process exits are
// dropped: node's process.exit() never gets back to the function, and an
// addon's call_js usually cannot take a null env.
nativeTests.test_threadsafe_function_queued_items_at_process_exit = () => {
nativeTests.queue_threadsafe_function_items(() => {}, 3, /* print_finalize */ false);
require("node:fs").writeSync(1, "exiting with 3 items queued\n");
process.exit(0);
};

// The same from inside the function's own callback: the items behind the one
// that is running must not be delivered into the callback's frame.
nativeTests.test_threadsafe_function_process_exit_inside_callback = () => {
nativeTests.queue_threadsafe_function_items(() => process.exit(0), 3, /* print_finalize */ false);
// Returning a pending promise keeps main.js quiet; the first item's callback
// exits the process.
return new Promise(() => {});
};

// A worker that exits (process.exit()) or is terminated with items queued: the
// addon gets each item through call_js with the live env (calling into JS is
// refused), then the finalizer, as when node's env cleanup turns the loop.
async function runQueuedItemsWorker(how) {
const { Worker } = require("node:worker_threads");
const path = require("node:path");
const worker = new Worker(path.join(__dirname, "tsfn-queued-items-worker.js"), { workerData: { how } });
const code = await new Promise((resolve, reject) => {
worker.on("error", reject);
worker.on("exit", resolve);
if (how === "terminate") {
worker.on("message", () => worker.terminate());
}
});
console.log("worker exited with", code);
}

nativeTests.test_threadsafe_function_queued_items_at_worker_exit = () => runQueuedItemsWorker("exit");
nativeTests.test_threadsafe_function_queued_items_at_worker_terminate = () => runQueuedItemsWorker("terminate");

// napi_tsfn_abort with items queued: none of them runs; each goes back to
// call_js with a null env and js_callback so the addon can free it, and then
// the function finalizes.
nativeTests.test_threadsafe_function_abort_hands_queued_items_back = async () => {
// writeSync: these interleave with the addon's printf lines, so they must
// reach stdout synchronously.
const { writeSync } = require("node:fs");
nativeTests.queue_threadsafe_function_items(
() => writeSync(1, "js callback ran after abort\n"),
3,
/* print_finalize */ true,
);
writeSync(1, `abort: ${nativeTests.abort_threadsafe_function_with_queued_items()}\n`);
for (let i = 0; i < 1000; i++) {
if (nativeTests.threadsafe_function_with_queued_items_finalized()) break;
await new Promise(resolve => setImmediate(resolve));
}
writeSync(1, `finalized: ${nativeTests.threadsafe_function_with_queued_items_finalized()}\n`);
};

// When napi_create_threadsafe_function is given no JS func, the call_js
// callback receives a null js_callback (addons test `if (js_callback != NULL)`).
nativeTests.test_tsfn_null_js_callback_driver = async () => {
Expand Down
Loading
Loading