Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
use std::os::raw::c_void;
use std::ptr;
use std::{
  marker::PhantomData,
  sync::{
    atomic::{AtomicBool, Ordering},
    Arc, Mutex, RwLock, Weak,
  },
};

#[cfg(feature = "deferred_trace")]
use crate::{bindgen_runtime::JsObjectValue, JsValue};
use crate::{
  bindgen_runtime::{Object, ToNapiValue},
  check_status, sys, Env, Error, Result,
};

#[cfg(feature = "deferred_trace")]
/// A javascript error which keeps a stack trace
/// to the original caller in an asynchronous context.
/// This is required as the stack trace is lost when
/// an error is created in a different thread.
///
/// See this issue for more details:
/// https://github.com/nodejs/node-addon-api/issues/595
#[repr(transparent)]
#[derive(Clone)]
struct DeferredTrace(sys::napi_ref);

#[cfg(feature = "deferred_trace")]
impl DeferredTrace {
  fn new(raw_env: sys::napi_env) -> Result<Self> {
    let env = Env::from_raw(raw_env);
    let reason = env.create_string("none")?;

    let mut js_error = ptr::null_mut();
    check_status!(
      unsafe { sys::napi_create_error(raw_env, ptr::null_mut(), reason.raw(), &mut js_error) },
      "Create error in DeferredTrace failed"
    )?;

    let mut result = ptr::null_mut();
    check_status!(
      unsafe { sys::napi_create_reference(raw_env, js_error, 1, &mut result) },
      "Create reference in DeferredTrace failed"
    )?;

    Ok(Self(result))
  }

  fn into_rejected(self, raw_env: sys::napi_env, err: Error) -> Result<sys::napi_value> {
    let env = Env::from_raw(raw_env);
    let mut raw = ptr::null_mut();
    check_status!(
      unsafe { sys::napi_get_reference_value(raw_env, self.0, &mut raw) },
      "Failed to get referenced value in DeferredTrace"
    )?;

    let mut obj = Object::from_raw(raw_env, raw);
    // Reuse the original JS error object when it is safe to read on this thread;
    // the shared `napi_ref` is released when `err` drops at the end of the call.
    let err_value = if let Some(err_raw_value) = unsafe { err.referenced_value(raw_env) } {
      let err_obj = Object::from_raw(raw_env, err_raw_value);
      if err_obj.has_named_property("message")? {
        // The error was already created inside the JS engine, just return it
        Ok(err_obj.raw())
      } else {
        obj.set_named_property("message", "")?;
        obj.set_named_property("code", "")?;
        Ok(raw)
      }
    } else {
      obj.set_named_property("message", &err.reason)?;
      obj.set_named_property(
        "code",
        env.create_string_from_std(format!("{}", err.status))?,
      )?;
      Ok(raw)
    };
    check_status!(
      unsafe { sys::napi_delete_reference(raw_env, self.0) },
      "Failed to get referenced value in DeferredTrace"
    )?;
    err_value
  }
}

type FinalizeCallback = Arc<RwLock<Option<Box<dyn FnOnce(sys::napi_env)>>>>;

struct DeferredData<Data: ToNapiValue, Resolver: FnOnce(Env) -> Result<Data>> {
  resolver: Result<Resolver>,
  #[cfg(feature = "deferred_trace")]
  trace: DeferredTrace,
  tsfn: sys::napi_threadsafe_function,
  finalize_callback: FinalizeCallback,
}

/// Shared between the deferred (and its clones) and the threadsafe function's env teardown hook
/// and finalize callback. Owns the pending threadsafe function: a settle takes it (moving the
/// release duty into the queued `DeferredData`), the env teardown hook abort-releases it,
/// whichever locks first. The lock is held across those calls so env teardown cannot finalize
/// the threadsafe function while a settle on a foreign thread is inside it.
struct DeferredHandle {
  pending_tsfn: Mutex<Option<sys::napi_threadsafe_function>>,
}

/// Shared by the env teardown hook and the threadsafe function's finalize callback; boxed, and
/// freed exactly once, by the finalize callback (which during an env teardown runs after the
/// LIFO-ordered cleanup hooks).
struct DeferredHookData {
  handle: Weak<DeferredHandle>,
  /// Whether the env cleanup hook is currently registered: set once registration succeeds,
  /// cleared when the teardown hook runs (Node's teardown drain consumes hooks as it runs them).
  /// The finalize callback only unregisters the hook while this is set — Node-API requires the
  /// removed pair to still be registered, otherwise the process may abort (Bun ≤ 1.2.20 aborts via
  /// `NAPI_PERISH`; fixed in 1.2.21 to match Node's silent no-op).
  hook_registered: AtomicBool,
}

// The raw threadsafe-function pointer makes the handle neither `Send` nor `Sync`, but calling a
// threadsafe function from any thread is its documented purpose, and the mutex hands it to
// exactly one consumer.
unsafe impl Send for DeferredHandle {}
unsafe impl Sync for DeferredHandle {}

pub struct JsDeferred<Data: ToNapiValue, Resolver: FnOnce(Env) -> Result<Data>> {
  handle: Arc<DeferredHandle>,
  #[cfg(feature = "deferred_trace")]
  trace: DeferredTrace,
  finalize_callback: FinalizeCallback,
  _data: PhantomData<Data>,
  _resolver: PhantomData<Resolver>,
}

// A trick to send the resolver into the `panic` handler
// Do not use clone in the other place besides the `fn execute_tokio_future`
impl<Data: ToNapiValue, Resolver: FnOnce(Env) -> Result<Data>> Clone
  for JsDeferred<Data, Resolver>
{
  fn clone(&self) -> Self {
    Self {
      handle: self.handle.clone(),
      #[cfg(feature = "deferred_trace")]
      trace: self.trace.clone(),
      finalize_callback: self.finalize_callback.clone(),
      _data: PhantomData,
      _resolver: PhantomData,
    }
  }
}

unsafe impl<Data: ToNapiValue, Resolver: FnOnce(Env) -> Result<Data>> Send
  for JsDeferred<Data, Resolver>
{
}

impl<Data: ToNapiValue, Resolver: FnOnce(Env) -> Result<Data>> JsDeferred<Data, Resolver> {
  pub(crate) fn new(env: &Env) -> Result<(Self, Object<'_>)> {
    let handle = Arc::new(DeferredHandle {
      pending_tsfn: Mutex::new(None),
    });
    let hook_data_ptr = Box::into_raw(Box::new(DeferredHookData {
      handle: Arc::downgrade(&handle),
      hook_registered: AtomicBool::new(false),
    }));

    let (tsfn, promise) = match js_deferred_new_raw(
      env,
      Some(napi_resolve_deferred::<Data, Resolver>),
      hook_data_ptr.cast(),
    ) {
      Ok(created) => created,
      Err(err) => {
        drop(unsafe { Box::from_raw(hook_data_ptr) });
        return Err(err);
      }
    };
    *handle
      .pending_tsfn
      .lock()
      .expect("JsDeferred pending lock failed") = Some(tsfn);

    // Pre-abort the threadsafe function when the environment tears down, before Node finalizes
    // it: a deferred settled from a foreign thread after (or while) its env tears down (e.g. a
    // future resolving after a worker thread terminated, see napi-rs#2460) would otherwise call
    // into a freed threadsafe function. Node registers the threadsafe function's own teardown as
    // a cleanup hook at creation, and hooks run in reverse registration order, so this hook runs
    // before Node finalizes the threadsafe function.
    #[cfg(not(target_family = "wasm"))]
    {
      if let Err(err) = check_status!(
        unsafe {
          sys::napi_add_env_cleanup_hook(
            env.0,
            Some(deferred_env_teardown_cb),
            hook_data_ptr.cast(),
          )
        },
        "Register env cleanup hook in JsDeferred failed"
      ) {
        // The tsfn exists but no teardown hook guards it yet. Release it so it cannot keep the loop
        // alive; its finalize callback owns the boxed `DeferredHookData`, frees it, and — seeing
        // `hook_registered == false` — skips the unregister. Do NOT free the box here: that would
        // double-free against the finalize callback.
        if let Some(tsfn) = handle
          .pending_tsfn
          .lock()
          .expect("JsDeferred pending lock failed")
          .take()
        {
          unsafe {
            sys::napi_release_threadsafe_function(tsfn, sys::ThreadsafeFunctionReleaseMode::abort)
          };
        }
        return Err(err);
      }
      unsafe { &*hook_data_ptr }
        .hook_registered
        .store(true, Ordering::Release);
    }

    // Create the trace ref LAST, after every fallible step. `DeferredTrace` has no `Drop` (its
    // `napi_ref` is deleted by hand when the promise settles), so building it before a step that can
    // still fail would leak that ref on the error path. On its own failure there is no trace ref yet
    // to leak, and we release the still-`Some` tsfn so it cannot strand the loop either — its
    // finalize still frees the boxed `DeferredHookData`, so (as above) we must not free it here.
    #[cfg(feature = "deferred_trace")]
    let trace = match DeferredTrace::new(env.0) {
      Ok(trace) => trace,
      Err(err) => {
        if let Some(tsfn) = handle
          .pending_tsfn
          .lock()
          .expect("JsDeferred pending lock failed")
          .take()
        {
          unsafe {
            sys::napi_release_threadsafe_function(tsfn, sys::ThreadsafeFunctionReleaseMode::abort)
          };
        }
        return Err(err);
      }
    };

    let deferred = Self {
      handle,
      #[cfg(feature = "deferred_trace")]
      trace,
      finalize_callback: Default::default(),
      _data: PhantomData,
      _resolver: PhantomData,
    };

    Ok((deferred, promise))
  }

  /// Consumes the deferred, and resolves the promise. The provided function will be called
  /// from the JavaScript thread, and should return the resolved value.
  pub fn resolve(self, resolver: Resolver) {
    self.call_tsfn(Ok(resolver))
  }

  /// Consumes the deferred, and rejects the promise with the provided error.
  pub fn reject(self, error: Error) {
    self.call_tsfn(Err(error))
  }

  #[allow(clippy::arc_with_non_send_sync)]
  pub fn set_finalize_callback(
    &mut self,
    finalize_callback: Option<Box<dyn FnOnce(sys::napi_env)>>,
  ) {
    self.finalize_callback = Arc::new(RwLock::new(finalize_callback));
  }

  fn call_tsfn(self, result: Result<Resolver>) {
    let mut pending = self
      .handle
      .pending_tsfn
      .lock()
      .expect("JsDeferred pending lock failed");
    let Some(tsfn) = pending.take() else {
      // The environment tore down (or another clone already settled the promise): the promise no
      // longer exists and the threadsafe function is gone. Drop the resolver instead of calling
      // into freed memory.
      return;
    };

    let data = DeferredData {
      resolver: result,
      #[cfg(feature = "deferred_trace")]
      trace: self.trace,
      tsfn,
      finalize_callback: self.finalize_callback.clone(),
    };

    // Call back into the JS thread via a threadsafe function. This results in napi_resolve_deferred being called.
    let status = unsafe {
      sys::napi_call_threadsafe_function(
        tsfn,
        Box::into_raw(Box::from(data)).cast(),
        sys::ThreadsafeFunctionCallMode::blocking,
      )
    };
    debug_assert!(
      status == sys::Status::napi_ok,
      "Call threadsafe function in JsDeferred failed"
    );
  }
}

/// Aborts the deferred's threadsafe function when its environment starts tearing down, before
/// Node finalizes it. Runs on the environment's thread; the `pending_tsfn` lock serializes it
/// against settles on foreign threads.
#[cfg(not(target_family = "wasm"))]
unsafe extern "C" fn deferred_env_teardown_cb(data: *mut c_void) {
  let hook_data = unsafe { &*data.cast::<DeferredHookData>() };
  // The teardown drain consumes this hook as it runs it; the threadsafe function's finalize
  // callback, which runs later in the teardown, must not unregister it a second time.
  hook_data.hook_registered.store(false, Ordering::Release);
  let Some(handle) = hook_data.handle.upgrade() else {
    return;
  };

  let mut pending = handle
    .pending_tsfn
    .lock()
    .expect("JsDeferred pending lock failed");
  if let Some(tsfn) = pending.take() {
    let status = unsafe {
      sys::napi_release_threadsafe_function(tsfn, sys::ThreadsafeFunctionReleaseMode::abort)
    };
    debug_assert!(
      status == sys::Status::napi_ok,
      "Abort deferred threadsafe function on env teardown failed"
    );
  }
}

/// Finalize callback of the deferred's threadsafe function: unregisters the teardown hook (when
/// it is still registered — during an env teardown the drain already consumed it) and frees the
/// shared hook data exactly once.
unsafe extern "C" fn deferred_finalize_cb(
  env: sys::napi_env,
  finalize_data: *mut c_void,
  _finalize_hint: *mut c_void,
) {
  let hook_registered = unsafe { &*finalize_data.cast::<DeferredHookData>() }
    .hook_registered
    .load(Ordering::Acquire);
  #[cfg(not(target_family = "wasm"))]
  if !env.is_null() && hook_registered {
    unsafe {
      sys::napi_remove_env_cleanup_hook(env, Some(deferred_env_teardown_cb), finalize_data)
    };
  }
  #[cfg(target_family = "wasm")]
  {
    let _ = env;
    let _ = hook_registered;
  }

  let hook_data = unsafe { Box::from_raw(finalize_data.cast::<DeferredHookData>()) };
  if let Some(handle) = hook_data.handle.upgrade() {
    handle
      .pending_tsfn
      .lock()
      .expect("JsDeferred pending lock failed")
      .take();
  }
}

fn js_deferred_new_raw(
  env: &Env,
  resolve_deferred: sys::napi_threadsafe_function_call_js,
  finalize_data: *mut c_void,
) -> Result<(sys::napi_threadsafe_function, Object<'_>)> {
  let mut raw_promise = ptr::null_mut();
  let mut raw_deferred = ptr::null_mut();
  check_status!(
    unsafe { sys::napi_create_promise(env.0, &mut raw_deferred, &mut raw_promise) },
    "Create promise in JsDeferred failed"
  )?;

  // Create a threadsafe function so we can call back into the JS thread when we are done.
  let mut async_resource_name = ptr::null_mut();
  check_status!(
    unsafe {
      sys::napi_create_string_utf8(
        env.0,
        c"napi_resolve_deferred".as_ptr().cast(),
        22,
        &mut async_resource_name,
      )
    },
    "Create async resource name in JsDeferred failed"
  )?;

  let mut tsfn = ptr::null_mut();
  check_status!(
    unsafe {
      sys::napi_create_threadsafe_function(
        env.0,
        ptr::null_mut(),
        ptr::null_mut(),
        async_resource_name,
        0,
        1,
        finalize_data,
        Some(deferred_finalize_cb),
        raw_deferred.cast(),
        resolve_deferred,
        &mut tsfn,
      )
    },
    "Create threadsafe function in JsDeferred failed"
  )?;

  let promise = Object::from_raw(env.0, raw_promise);

  Ok((tsfn, promise))
}

extern "C" fn napi_resolve_deferred<Data: ToNapiValue, Resolver: FnOnce(Env) -> Result<Data>>(
  env: sys::napi_env,
  _js_callback: sys::napi_value,
  context: *mut c_void,
  data: *mut c_void,
) {
  let deferred_data: Box<DeferredData<Data, Resolver>> = unsafe { Box::from_raw(data.cast()) };

  // A leftover queue item is drained with a null env while the threadsafe function closes during env
  // teardown. There is no promise left to settle, but this item still owns the release of the
  // threadsafe function's thread count (moved here by the settle in `call_tsfn`). Recent Node (its
  // `MaybeDelete` only frees the threadsafe function once the count reaches zero) and emnapi will
  // otherwise leak the threadsafe function, so we must release it here too instead of only on the
  // settle path below. This is safe during the teardown drain: `EmptyQueue` runs this callback
  // without holding the tsfn lock, and while it is closing the release only drops the count — the
  // object is deleted exactly once by the finalize that immediately follows.
  if env.is_null() {
    unsafe {
      sys::napi_release_threadsafe_function(
        deferred_data.tsfn,
        sys::ThreadsafeFunctionReleaseMode::release,
      )
    };
    return;
  }

  let deferred = context.cast();
  let tsfn: *mut napi_sys::napi_threadsafe_function__ = deferred_data.tsfn;
  let finalize_callback = RwLock::write(&deferred_data.finalize_callback)
    .expect("RwLock Poison")
    .take();
  let result = deferred_data
    .resolver
    .and_then(|resolver| resolver(Env::from_raw(env)))
    .and_then(|res| unsafe { ToNapiValue::to_napi_value(env, res) });

  let release_tsfn_result = check_status!(
    unsafe {
      sys::napi_release_threadsafe_function(tsfn, sys::ThreadsafeFunctionReleaseMode::release)
    },
    "Release threadsafe function in JsDeferred failed"
  );

  if let Err(e) = release_tsfn_result.and(result).and_then(|res| {
    check_status!(
      unsafe { sys::napi_resolve_deferred(env, deferred, res) },
      "Resolve deferred value failed"
    )
    .map(|_| {
      #[cfg(feature = "deferred_trace")]
      {
        let _status = unsafe { sys::napi_delete_reference(env, deferred_data.trace.0) };
        if _status != sys::Status::napi_ok && cfg!(debug_assertions) {
          eprintln!(
            "Failed to delete reference in deferred {}",
            crate::Status::from(_status)
          );
        }
      }
    })
  }) {
    #[cfg(feature = "deferred_trace")]
    let error = deferred_data.trace.into_rejected(env, e);
    #[cfg(not(feature = "deferred_trace"))]
    let error = Ok::<sys::napi_value, Error>(unsafe { crate::JsError::from(e).into_value(env) });

    match error {
      Ok(error) => {
        unsafe { sys::napi_reject_deferred(env, deferred, error) };
        if let Some(finalize_callback) = finalize_callback {
          finalize_callback(env);
        }
      }
      Err(err) => {
        if let Some(finalize_callback) = finalize_callback {
          finalize_callback(env);
        }
        if cfg!(debug_assertions) {
          eprintln!("Failed to reject deferred: {err:?}");
          let mut err = ptr::null_mut();
          let mut err_msg = ptr::null_mut();
          unsafe {
            sys::napi_create_string_utf8(env, c"Rejection failed".as_ptr().cast(), 0, &mut err_msg);
            sys::napi_create_error(env, ptr::null_mut(), err_msg, &mut err);
            sys::napi_reject_deferred(env, deferred, err);
          }
        }
      }
    }
  } else if let Some(finalize_callback) = finalize_callback {
    finalize_callback(env);
  }
}