2021-05-28 19:50:16 +09:00
|
|
|
#![allow(clippy::single_component_path_imports)]
|
|
|
|
|
2020-08-26 01:07:27 +09:00
|
|
|
use std::convert::Into;
|
2020-12-02 19:39:20 +09:00
|
|
|
use std::ffi::CString;
|
2020-10-04 18:10:52 +09:00
|
|
|
use std::marker::PhantomData;
|
2020-12-02 19:39:20 +09:00
|
|
|
use std::os::raw::c_void;
|
2020-06-21 20:10:06 +09:00
|
|
|
use std::ptr;
|
2021-03-31 22:31:37 +09:00
|
|
|
use std::sync::atomic::{AtomicBool, AtomicUsize, Ordering};
|
2020-11-11 13:16:19 +09:00
|
|
|
use std::sync::Arc;
|
2020-06-21 20:10:06 +09:00
|
|
|
|
2021-05-17 18:29:38 +09:00
|
|
|
use crate::{check_status, sys, Env, Error, JsError, JsFunction, NapiRaw, Result, Status};
|
2020-06-19 21:42:18 +09:00
|
|
|
|
|
|
|
use sys::napi_threadsafe_function_call_mode;
|
|
|
|
|
2020-11-11 13:16:19 +09:00
|
|
|
/// ThreadSafeFunction Context object
|
|
|
|
/// the `value` is the value passed to `call` method
|
2020-10-04 18:10:52 +09:00
|
|
|
pub struct ThreadSafeCallContext<T: 'static> {
|
|
|
|
pub env: Env,
|
|
|
|
pub value: T,
|
|
|
|
}
|
|
|
|
|
2020-08-26 01:07:27 +09:00
|
|
|
#[repr(u8)]
|
|
|
|
pub enum ThreadsafeFunctionCallMode {
|
|
|
|
NonBlocking,
|
|
|
|
Blocking,
|
|
|
|
}
|
|
|
|
|
2021-05-28 19:50:16 +09:00
|
|
|
impl From<ThreadsafeFunctionCallMode> for napi_threadsafe_function_call_mode {
|
|
|
|
fn from(value: ThreadsafeFunctionCallMode) -> Self {
|
|
|
|
match value {
|
2020-08-26 01:07:27 +09:00
|
|
|
ThreadsafeFunctionCallMode::Blocking => {
|
|
|
|
napi_threadsafe_function_call_mode::napi_tsfn_blocking
|
|
|
|
}
|
|
|
|
ThreadsafeFunctionCallMode::NonBlocking => {
|
|
|
|
napi_threadsafe_function_call_mode::napi_tsfn_nonblocking
|
|
|
|
}
|
|
|
|
}
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
2021-03-10 07:24:53 +09:00
|
|
|
type_level_enum! {
|
|
|
|
/// Type-level `enum` to express how to feed [`ThreadsafeFunction`] errors to
|
|
|
|
/// the inner [`JsFunction`].
|
|
|
|
///
|
|
|
|
/// ### Context
|
|
|
|
///
|
|
|
|
/// For callbacks that expect a `Result`-like kind of input, the convention is
|
|
|
|
/// to have the callback take an `error` parameter as its first parameter.
|
|
|
|
///
|
|
|
|
/// This way receiving a `Result<Args…>` can be modelled as follows:
|
|
|
|
///
|
|
|
|
/// - In case of `Err(error)`, feed that `error` entity as the first parameter
|
|
|
|
/// of the callback;
|
|
|
|
///
|
|
|
|
/// - Otherwise (in case of `Ok(_)`), feed `null` instead.
|
|
|
|
///
|
|
|
|
/// In pseudo-code:
|
|
|
|
///
|
|
|
|
/// ```rust,ignore
|
|
|
|
/// match result_args {
|
|
|
|
/// Ok(args) => {
|
|
|
|
/// let js_null = /* … */;
|
|
|
|
/// callback.call(
|
|
|
|
/// // this
|
|
|
|
/// None,
|
|
|
|
/// // args…
|
|
|
|
/// &iter::once(js_null).chain(args).collect::<Vec<_>>(),
|
|
|
|
/// )
|
|
|
|
/// },
|
|
|
|
/// Err(err) => callback.call(None, &[JsError::from(err)]),
|
|
|
|
/// }
|
|
|
|
/// ```
|
|
|
|
///
|
|
|
|
/// **Note that the `Err` case can stem from a failed conversion from native
|
|
|
|
/// values to js values when calling the callback!**
|
|
|
|
///
|
|
|
|
/// That's why:
|
|
|
|
///
|
|
|
|
/// > **[This][`ErrorStrategy::CalleeHandled`] is the default error strategy**.
|
|
|
|
///
|
|
|
|
/// In order to opt-out of it, [`ThreadsafeFunction`] has an optional second
|
|
|
|
/// generic parameter (of "kind" [`ErrorStrategy::T`]) that defines whether
|
|
|
|
/// this behavior ([`ErrorStrategy::CalleeHandled`]) or a non-`Result` one
|
|
|
|
/// ([`ErrorStrategy::Fatal`]) is desired.
|
|
|
|
pub enum ErrorStrategy {
|
|
|
|
/// Input errors (including conversion errors) are left for the callee to
|
|
|
|
/// handle:
|
|
|
|
///
|
|
|
|
/// The callee receives an extra `error` parameter (the first one), which is
|
|
|
|
/// `null` if no error occurred, and the error payload otherwise.
|
|
|
|
CalleeHandled,
|
|
|
|
|
|
|
|
/// Input errors (including conversion errors) are deemed fatal:
|
|
|
|
///
|
|
|
|
/// they can thus cause a `panic!` or abort the process.
|
|
|
|
///
|
|
|
|
/// The callee thus is not expected to have to deal with [that extra `error`
|
|
|
|
/// parameter][CalleeHandled], which is thus not added.
|
|
|
|
Fatal,
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
2020-06-19 21:42:18 +09:00
|
|
|
/// Communicate with the addon's main thread by invoking a JavaScript function from other threads.
|
|
|
|
///
|
|
|
|
/// ## Example
|
|
|
|
/// An example of using `ThreadsafeFunction`:
|
|
|
|
///
|
2020-12-03 18:17:40 +09:00
|
|
|
/// ```rust
|
2020-06-19 21:42:18 +09:00
|
|
|
/// #[macro_use]
|
2020-07-19 18:29:47 +09:00
|
|
|
/// extern crate napi_derive;
|
2020-06-19 21:42:18 +09:00
|
|
|
///
|
|
|
|
/// use std::thread;
|
2020-10-04 18:10:52 +09:00
|
|
|
///
|
2020-07-19 18:29:47 +09:00
|
|
|
/// use napi::{
|
2020-11-11 13:16:19 +09:00
|
|
|
/// threadsafe_function::{
|
|
|
|
/// ThreadSafeCallContext, ThreadsafeFunctionCallMode, ThreadsafeFunctionReleaseMode,
|
|
|
|
/// },
|
|
|
|
/// CallContext, Error, JsFunction, JsNumber, JsUndefined, Result, Status,
|
2020-06-19 21:42:18 +09:00
|
|
|
/// };
|
2020-12-03 18:17:40 +09:00
|
|
|
///
|
2020-06-19 21:42:18 +09:00
|
|
|
/// #[js_function(1)]
|
2020-10-04 18:10:52 +09:00
|
|
|
/// pub fn test_threadsafe_function(ctx: CallContext) -> Result<JsUndefined> {
|
2020-12-03 18:17:40 +09:00
|
|
|
/// let func = ctx.get::<JsFunction>(0)?;
|
|
|
|
///
|
|
|
|
/// let tsfn =
|
|
|
|
/// ctx
|
|
|
|
/// .env
|
|
|
|
/// .create_threadsafe_function(&func, 0, |ctx: ThreadSafeCallContext<Vec<u32>>| {
|
2020-11-11 13:16:19 +09:00
|
|
|
/// ctx.value
|
|
|
|
/// .iter()
|
2020-12-03 18:17:40 +09:00
|
|
|
/// .map(|v| ctx.env.create_uint32(*v))
|
2020-11-11 13:16:19 +09:00
|
|
|
/// .collect::<Result<Vec<JsNumber>>>()
|
2020-12-03 18:17:40 +09:00
|
|
|
/// })?;
|
|
|
|
///
|
2021-02-26 19:36:51 +09:00
|
|
|
/// let tsfn_cloned = tsfn.clone();
|
2020-12-03 18:17:40 +09:00
|
|
|
///
|
|
|
|
/// thread::spawn(move || {
|
|
|
|
/// let output: Vec<u32> = vec![0, 1, 2, 3];
|
|
|
|
/// // It's okay to call a threadsafe function multiple times.
|
|
|
|
/// tsfn.call(Ok(output.clone()), ThreadsafeFunctionCallMode::Blocking);
|
|
|
|
/// });
|
|
|
|
///
|
|
|
|
/// thread::spawn(move || {
|
|
|
|
/// let output: Vec<u32> = vec![3, 2, 1, 0];
|
|
|
|
/// // It's okay to call a threadsafe function multiple times.
|
|
|
|
/// tsfn_cloned.call(Ok(output.clone()), ThreadsafeFunctionCallMode::NonBlocking);
|
|
|
|
/// });
|
|
|
|
///
|
|
|
|
/// ctx.env.get_undefined()
|
2020-06-19 21:42:18 +09:00
|
|
|
/// }
|
|
|
|
/// ```
|
2021-03-10 07:24:53 +09:00
|
|
|
pub struct ThreadsafeFunction<T: 'static, ES: ErrorStrategy::T = ErrorStrategy::CalleeHandled> {
|
2020-10-04 18:10:52 +09:00
|
|
|
raw_tsfn: sys::napi_threadsafe_function,
|
2020-11-11 13:16:19 +09:00
|
|
|
aborted: Arc<AtomicBool>,
|
2021-03-31 22:31:37 +09:00
|
|
|
ref_count: Arc<AtomicUsize>,
|
2021-03-10 07:24:53 +09:00
|
|
|
_phantom: PhantomData<(T, ES)>,
|
2020-06-19 21:42:18 +09:00
|
|
|
}
|
|
|
|
|
2021-03-10 07:24:53 +09:00
|
|
|
impl<T: 'static, ES: ErrorStrategy::T> Clone for ThreadsafeFunction<T, ES> {
|
2021-02-26 19:36:51 +09:00
|
|
|
fn clone(&self) -> Self {
|
|
|
|
if !self.aborted.load(Ordering::Acquire) {
|
|
|
|
let acquire_status = unsafe { sys::napi_acquire_threadsafe_function(self.raw_tsfn) };
|
|
|
|
debug_assert!(
|
|
|
|
acquire_status == sys::Status::napi_ok,
|
|
|
|
"Acquire threadsafe function failed in clone"
|
|
|
|
);
|
|
|
|
}
|
|
|
|
|
|
|
|
Self {
|
|
|
|
raw_tsfn: self.raw_tsfn,
|
|
|
|
aborted: Arc::clone(&self.aborted),
|
2021-03-31 22:31:37 +09:00
|
|
|
ref_count: Arc::clone(&self.ref_count),
|
2021-02-26 19:36:51 +09:00
|
|
|
_phantom: PhantomData,
|
|
|
|
}
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
2021-03-10 07:24:53 +09:00
|
|
|
unsafe impl<T, ES: ErrorStrategy::T> Send for ThreadsafeFunction<T, ES> {}
|
|
|
|
unsafe impl<T, ES: ErrorStrategy::T> Sync for ThreadsafeFunction<T, ES> {}
|
2020-10-04 18:10:52 +09:00
|
|
|
|
2021-03-10 07:24:53 +09:00
|
|
|
impl<T: 'static, ES: ErrorStrategy::T> ThreadsafeFunction<T, ES> {
|
2020-06-19 21:42:18 +09:00
|
|
|
/// See [napi_create_threadsafe_function](https://nodejs.org/api/n-api.html#n_api_napi_create_threadsafe_function)
|
|
|
|
/// for more information.
|
2020-10-04 18:10:52 +09:00
|
|
|
pub fn create<
|
2021-05-17 18:29:38 +09:00
|
|
|
V: NapiRaw,
|
2020-10-04 18:10:52 +09:00
|
|
|
R: 'static + Send + FnMut(ThreadSafeCallContext<T>) -> Result<Vec<V>>,
|
|
|
|
>(
|
|
|
|
env: sys::napi_env,
|
2020-11-11 13:16:19 +09:00
|
|
|
func: &JsFunction,
|
2020-11-04 23:52:13 +09:00
|
|
|
max_queue_size: usize,
|
2020-10-04 18:10:52 +09:00
|
|
|
callback: R,
|
|
|
|
) -> Result<Self> {
|
2020-06-19 21:42:18 +09:00
|
|
|
let mut async_resource_name = ptr::null_mut();
|
|
|
|
let s = "napi_rs_threadsafe_function";
|
2020-12-02 19:39:20 +09:00
|
|
|
let len = s.len();
|
|
|
|
let s = CString::new(s)?;
|
2020-11-25 18:42:14 +09:00
|
|
|
check_status!(unsafe {
|
2020-12-02 19:39:20 +09:00
|
|
|
sys::napi_create_string_utf8(env, s.as_ptr(), len, &mut async_resource_name)
|
2020-10-04 17:02:04 +09:00
|
|
|
})?;
|
2020-06-19 21:42:18 +09:00
|
|
|
|
2020-12-02 19:39:20 +09:00
|
|
|
let initial_thread_count = 1usize;
|
2020-10-04 18:10:52 +09:00
|
|
|
let mut raw_tsfn = ptr::null_mut();
|
2021-06-22 00:09:13 +09:00
|
|
|
let ptr = Box::into_raw(Box::new(callback)) as *mut c_void;
|
2020-11-25 18:42:14 +09:00
|
|
|
check_status!(unsafe {
|
2020-06-19 21:42:18 +09:00
|
|
|
sys::napi_create_threadsafe_function(
|
2020-10-04 18:10:52 +09:00
|
|
|
env,
|
2020-06-21 20:10:06 +09:00
|
|
|
func.0.value,
|
2020-06-19 21:42:18 +09:00
|
|
|
ptr::null_mut(),
|
|
|
|
async_resource_name,
|
2020-12-02 19:39:20 +09:00
|
|
|
max_queue_size,
|
2020-06-19 21:42:18 +09:00
|
|
|
initial_thread_count,
|
|
|
|
ptr,
|
2021-03-10 07:24:53 +09:00
|
|
|
Some(thread_finalize_cb::<T, V, R>),
|
2020-06-19 21:42:18 +09:00
|
|
|
ptr,
|
2021-03-10 07:24:53 +09:00
|
|
|
Some(call_js_cb::<T, V, R, ES>),
|
2020-10-04 18:10:52 +09:00
|
|
|
&mut raw_tsfn,
|
2020-06-19 21:42:18 +09:00
|
|
|
)
|
2020-10-04 18:10:52 +09:00
|
|
|
})?;
|
2020-06-19 21:42:18 +09:00
|
|
|
|
|
|
|
Ok(ThreadsafeFunction {
|
2020-10-04 18:10:52 +09:00
|
|
|
raw_tsfn,
|
2020-11-11 13:16:19 +09:00
|
|
|
aborted: Arc::new(AtomicBool::new(false)),
|
2021-03-31 22:31:37 +09:00
|
|
|
ref_count: Arc::new(AtomicUsize::new(initial_thread_count)),
|
2020-10-04 18:10:52 +09:00
|
|
|
_phantom: PhantomData,
|
2020-06-19 21:42:18 +09:00
|
|
|
})
|
|
|
|
}
|
|
|
|
|
|
|
|
/// See [napi_ref_threadsafe_function](https://nodejs.org/api/n-api.html#n_api_napi_ref_threadsafe_function)
|
|
|
|
/// for more information.
|
|
|
|
///
|
|
|
|
/// "ref" is a keyword so that we use "refer" here.
|
2020-11-11 13:16:19 +09:00
|
|
|
pub fn refer(&mut self, env: &Env) -> Result<()> {
|
2020-11-12 11:47:33 +09:00
|
|
|
if self.aborted.load(Ordering::Acquire) {
|
|
|
|
return Err(Error::new(
|
|
|
|
Status::Closing,
|
2021-05-28 19:50:16 +09:00
|
|
|
"Can not ref, Thread safe function already aborted".to_string(),
|
2020-11-12 11:47:33 +09:00
|
|
|
));
|
|
|
|
}
|
2021-04-12 18:08:12 +09:00
|
|
|
self.ref_count.fetch_add(1, Ordering::AcqRel);
|
2020-11-25 18:42:14 +09:00
|
|
|
check_status!(unsafe { sys::napi_ref_threadsafe_function(env.0, self.raw_tsfn) })
|
2020-06-19 21:42:18 +09:00
|
|
|
}
|
|
|
|
|
|
|
|
/// See [napi_unref_threadsafe_function](https://nodejs.org/api/n-api.html#n_api_napi_unref_threadsafe_function)
|
|
|
|
/// for more information.
|
2020-11-11 13:16:19 +09:00
|
|
|
pub fn unref(&mut self, env: &Env) -> Result<()> {
|
2020-11-12 11:47:33 +09:00
|
|
|
if self.aborted.load(Ordering::Acquire) {
|
|
|
|
return Err(Error::new(
|
|
|
|
Status::Closing,
|
2021-05-28 19:50:16 +09:00
|
|
|
"Can not unref, Thread safe function already aborted".to_string(),
|
2020-11-12 11:47:33 +09:00
|
|
|
));
|
|
|
|
}
|
2021-04-12 18:08:12 +09:00
|
|
|
self.ref_count.fetch_sub(1, Ordering::AcqRel);
|
2020-11-25 18:42:14 +09:00
|
|
|
check_status!(unsafe { sys::napi_unref_threadsafe_function(env.0, self.raw_tsfn) })
|
2020-06-19 21:42:18 +09:00
|
|
|
}
|
2020-11-11 13:16:19 +09:00
|
|
|
|
|
|
|
pub fn aborted(&self) -> bool {
|
2021-04-12 18:08:12 +09:00
|
|
|
self.aborted.load(Ordering::Relaxed)
|
2020-11-11 13:16:19 +09:00
|
|
|
}
|
|
|
|
|
|
|
|
pub fn abort(self) -> Result<()> {
|
2020-11-25 18:42:14 +09:00
|
|
|
check_status!(unsafe {
|
2020-11-11 13:16:19 +09:00
|
|
|
sys::napi_release_threadsafe_function(
|
|
|
|
self.raw_tsfn,
|
|
|
|
sys::napi_threadsafe_function_release_mode::napi_tsfn_abort,
|
|
|
|
)
|
|
|
|
})?;
|
|
|
|
self.aborted.store(true, Ordering::Release);
|
|
|
|
Ok(())
|
|
|
|
}
|
|
|
|
|
|
|
|
/// Get the raw `ThreadSafeFunction` pointer
|
|
|
|
pub fn raw(&self) -> sys::napi_threadsafe_function {
|
|
|
|
self.raw_tsfn
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
2021-03-10 07:24:53 +09:00
|
|
|
impl<T: 'static> ThreadsafeFunction<T, ErrorStrategy::CalleeHandled> {
|
|
|
|
/// See [napi_call_threadsafe_function](https://nodejs.org/api/n-api.html#n_api_napi_call_threadsafe_function)
|
|
|
|
/// for more information.
|
|
|
|
pub fn call(&self, value: Result<T>, mode: ThreadsafeFunctionCallMode) -> Status {
|
|
|
|
if self.aborted.load(Ordering::Acquire) {
|
|
|
|
return Status::Closing;
|
|
|
|
}
|
|
|
|
unsafe {
|
|
|
|
sys::napi_call_threadsafe_function(
|
|
|
|
self.raw_tsfn,
|
|
|
|
Box::into_raw(Box::new(value)) as *mut _,
|
|
|
|
mode.into(),
|
|
|
|
)
|
|
|
|
}
|
|
|
|
.into()
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
impl<T: 'static> ThreadsafeFunction<T, ErrorStrategy::Fatal> {
|
|
|
|
/// See [napi_call_threadsafe_function](https://nodejs.org/api/n-api.html#n_api_napi_call_threadsafe_function)
|
|
|
|
/// for more information.
|
|
|
|
pub fn call(&self, value: T, mode: ThreadsafeFunctionCallMode) -> Status {
|
|
|
|
if self.aborted.load(Ordering::Acquire) {
|
|
|
|
return Status::Closing;
|
|
|
|
}
|
|
|
|
unsafe {
|
|
|
|
sys::napi_call_threadsafe_function(
|
|
|
|
self.raw_tsfn,
|
|
|
|
Box::into_raw(Box::new(value)) as *mut _,
|
|
|
|
mode.into(),
|
|
|
|
)
|
|
|
|
}
|
|
|
|
.into()
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
impl<T: 'static, ES: ErrorStrategy::T> Drop for ThreadsafeFunction<T, ES> {
|
2020-11-11 13:16:19 +09:00
|
|
|
fn drop(&mut self) {
|
2021-04-12 18:08:12 +09:00
|
|
|
if !self.aborted.load(Ordering::Acquire) && self.ref_count.load(Ordering::Acquire) > 0usize {
|
2020-11-11 13:16:19 +09:00
|
|
|
let release_status = unsafe {
|
|
|
|
sys::napi_release_threadsafe_function(
|
|
|
|
self.raw_tsfn,
|
|
|
|
sys::napi_threadsafe_function_release_mode::napi_tsfn_release,
|
|
|
|
)
|
|
|
|
};
|
|
|
|
assert!(
|
|
|
|
release_status == sys::Status::napi_ok,
|
|
|
|
"Threadsafe Function release failed"
|
|
|
|
);
|
|
|
|
}
|
|
|
|
}
|
2020-06-19 21:42:18 +09:00
|
|
|
}
|
|
|
|
|
2021-05-17 18:29:38 +09:00
|
|
|
unsafe extern "C" fn thread_finalize_cb<T: 'static, V: NapiRaw, R>(
|
2020-06-19 21:42:18 +09:00
|
|
|
_raw_env: sys::napi_env,
|
|
|
|
finalize_data: *mut c_void,
|
|
|
|
_finalize_hint: *mut c_void,
|
2021-03-10 07:24:53 +09:00
|
|
|
) where
|
|
|
|
R: 'static + Send + FnMut(ThreadSafeCallContext<T>) -> Result<Vec<V>>,
|
|
|
|
{
|
2020-06-19 21:42:18 +09:00
|
|
|
// cleanup
|
2021-03-10 07:24:53 +09:00
|
|
|
drop(Box::<R>::from_raw(finalize_data.cast()));
|
2020-06-19 21:42:18 +09:00
|
|
|
}
|
|
|
|
|
2021-05-17 18:29:38 +09:00
|
|
|
unsafe extern "C" fn call_js_cb<T: 'static, V: NapiRaw, R, ES>(
|
2020-06-19 21:42:18 +09:00
|
|
|
raw_env: sys::napi_env,
|
|
|
|
js_callback: sys::napi_value,
|
|
|
|
context: *mut c_void,
|
|
|
|
data: *mut c_void,
|
2021-03-10 07:24:53 +09:00
|
|
|
) where
|
|
|
|
R: 'static + Send + FnMut(ThreadSafeCallContext<T>) -> Result<Vec<V>>,
|
|
|
|
ES: ErrorStrategy::T,
|
|
|
|
{
|
|
|
|
let ctx: &mut R = &mut *context.cast::<R>();
|
|
|
|
let val: Result<T> = match ES::VALUE {
|
|
|
|
ErrorStrategy::CalleeHandled::VALUE => *Box::<Result<T>>::from_raw(data.cast()),
|
|
|
|
ErrorStrategy::Fatal::VALUE => Ok(*Box::<T>::from_raw(data.cast())),
|
|
|
|
};
|
|
|
|
|
2020-06-19 21:42:18 +09:00
|
|
|
let mut recv = ptr::null_mut();
|
|
|
|
sys::napi_get_undefined(raw_env, &mut recv);
|
|
|
|
|
2020-10-04 18:10:52 +09:00
|
|
|
let ret = val.and_then(|v| {
|
2021-03-10 07:24:53 +09:00
|
|
|
(ctx)(ThreadSafeCallContext {
|
2020-10-04 18:10:52 +09:00
|
|
|
env: Env::from_raw(raw_env),
|
|
|
|
value: v,
|
|
|
|
})
|
|
|
|
});
|
2020-06-19 21:42:18 +09:00
|
|
|
|
|
|
|
let status;
|
|
|
|
|
2020-07-26 17:56:42 +09:00
|
|
|
// Follow async callback conventions: https://nodejs.org/en/knowledge/errors/what-are-the-error-conventions/
|
|
|
|
// Check if the Result is okay, if so, pass a null as the first (error) argument automatically.
|
|
|
|
// If the Result is an error, pass that as the first argument.
|
2020-10-04 18:10:52 +09:00
|
|
|
match ret {
|
|
|
|
Ok(values) => {
|
2021-03-10 07:24:53 +09:00
|
|
|
let values = values.iter().map(|v| v.raw());
|
|
|
|
let args: Vec<sys::napi_value> = if ES::VALUE == ErrorStrategy::CalleeHandled::VALUE {
|
|
|
|
let mut js_null = ptr::null_mut();
|
|
|
|
sys::napi_get_null(raw_env, &mut js_null);
|
|
|
|
::core::iter::once(js_null).chain(values).collect()
|
|
|
|
} else {
|
|
|
|
values.collect()
|
|
|
|
};
|
2020-10-04 18:10:52 +09:00
|
|
|
status = sys::napi_call_function(
|
|
|
|
raw_env,
|
|
|
|
recv,
|
|
|
|
js_callback,
|
2021-03-10 07:24:53 +09:00
|
|
|
args.len(),
|
2020-10-04 18:10:52 +09:00
|
|
|
args.as_ptr(),
|
|
|
|
ptr::null_mut(),
|
|
|
|
);
|
|
|
|
}
|
2021-03-10 07:24:53 +09:00
|
|
|
Err(e) if ES::VALUE == ErrorStrategy::Fatal::VALUE => {
|
2021-06-22 00:09:13 +09:00
|
|
|
panic!("{}", e);
|
2021-03-10 07:24:53 +09:00
|
|
|
}
|
2020-10-04 18:10:52 +09:00
|
|
|
Err(e) => {
|
|
|
|
status = sys::napi_call_function(
|
|
|
|
raw_env,
|
|
|
|
recv,
|
|
|
|
js_callback,
|
|
|
|
1,
|
2020-12-02 15:10:48 +09:00
|
|
|
[JsError::from(e).into_value(raw_env)].as_mut_ptr(),
|
2020-10-04 18:10:52 +09:00
|
|
|
ptr::null_mut(),
|
|
|
|
);
|
2020-07-03 01:36:45 +09:00
|
|
|
}
|
2020-06-19 21:42:18 +09:00
|
|
|
}
|
2021-06-22 00:09:13 +09:00
|
|
|
if status == sys::Status::napi_ok {
|
|
|
|
return;
|
|
|
|
}
|
2021-01-25 12:46:58 +09:00
|
|
|
if status == sys::Status::napi_pending_exception {
|
|
|
|
let mut error_result = ptr::null_mut();
|
|
|
|
assert_eq!(
|
|
|
|
sys::napi_get_and_clear_last_exception(raw_env, &mut error_result),
|
|
|
|
sys::Status::napi_ok
|
|
|
|
);
|
|
|
|
assert_eq!(
|
|
|
|
sys::napi_fatal_exception(raw_env, error_result),
|
|
|
|
sys::Status::napi_ok
|
|
|
|
);
|
2021-06-22 00:09:13 +09:00
|
|
|
} else {
|
2021-01-25 12:46:58 +09:00
|
|
|
let error_code: Status = status.into();
|
|
|
|
let error_code_string = format!("{:?}", error_code);
|
|
|
|
let mut error_code_value = ptr::null_mut();
|
|
|
|
assert_eq!(
|
|
|
|
sys::napi_create_string_utf8(
|
|
|
|
raw_env,
|
|
|
|
error_code_string.as_ptr() as *const _,
|
|
|
|
error_code_string.len(),
|
|
|
|
&mut error_code_value
|
|
|
|
),
|
|
|
|
sys::Status::napi_ok,
|
|
|
|
);
|
|
|
|
let error_msg = "Call JavaScript callback failed in thread safe function";
|
|
|
|
let mut error_msg_value = ptr::null_mut();
|
|
|
|
assert_eq!(
|
|
|
|
sys::napi_create_string_utf8(
|
|
|
|
raw_env,
|
|
|
|
error_msg.as_ptr() as *const _,
|
|
|
|
error_msg.len(),
|
|
|
|
&mut error_msg_value,
|
|
|
|
),
|
|
|
|
sys::Status::napi_ok,
|
|
|
|
);
|
|
|
|
let mut error_value = ptr::null_mut();
|
|
|
|
assert_eq!(
|
|
|
|
sys::napi_create_error(raw_env, error_code_value, error_msg_value, &mut error_value),
|
|
|
|
sys::Status::napi_ok,
|
|
|
|
);
|
|
|
|
assert_eq!(
|
|
|
|
sys::napi_fatal_exception(raw_env, error_value),
|
|
|
|
sys::Status::napi_ok
|
|
|
|
);
|
|
|
|
}
|
2020-06-19 21:42:18 +09:00
|
|
|
}
|
2021-03-10 07:24:53 +09:00
|
|
|
|
|
|
|
/// Helper
|
|
|
|
macro_rules! type_level_enum {(
|
|
|
|
$( #[doc = $doc:tt] )*
|
|
|
|
$pub:vis
|
|
|
|
enum $EnumName:ident {
|
|
|
|
$(
|
|
|
|
$( #[doc = $doc_variant:tt] )*
|
|
|
|
$Variant:ident
|
|
|
|
),* $(,)?
|
|
|
|
}
|
|
|
|
) => (type_level_enum! { // This requires the macro to be in scope when called.
|
|
|
|
with_docs! {
|
|
|
|
$( #[doc = $doc] )*
|
|
|
|
///
|
|
|
|
/// ### Type-level `enum`
|
|
|
|
///
|
|
|
|
/// Until `const_generics` can handle custom `enum`s, this pattern must be
|
|
|
|
/// implemented at the type level.
|
|
|
|
///
|
|
|
|
/// We thus end up with:
|
|
|
|
///
|
|
|
|
/// ```rust,ignore
|
|
|
|
/// #[type_level_enum]
|
|
|
|
#[doc = ::core::concat!(
|
|
|
|
" enum ", ::core::stringify!($EnumName), " {",
|
|
|
|
)]
|
|
|
|
$(
|
|
|
|
#[doc = ::core::concat!(
|
|
|
|
" ", ::core::stringify!($Variant), ",",
|
|
|
|
)]
|
|
|
|
)*
|
|
|
|
#[doc = " }"]
|
|
|
|
/// ```
|
|
|
|
///
|
|
|
|
#[doc = ::core::concat!(
|
|
|
|
"With [`", ::core::stringify!($EnumName), "::T`](#reexports) \
|
|
|
|
being the type-level \"enum type\":",
|
|
|
|
)]
|
|
|
|
///
|
|
|
|
/// ```rust,ignore
|
|
|
|
#[doc = ::core::concat!(
|
|
|
|
"<Param: ", ::core::stringify!($EnumName), "::T>"
|
|
|
|
)]
|
|
|
|
/// ```
|
|
|
|
}
|
|
|
|
#[allow(warnings)]
|
|
|
|
$pub mod $EnumName {
|
|
|
|
#[doc(no_inline)]
|
|
|
|
pub use $EnumName as T;
|
|
|
|
|
|
|
|
super::type_level_enum! {
|
|
|
|
with_docs! {
|
|
|
|
#[doc = ::core::concat!(
|
|
|
|
"See [`", ::core::stringify!($EnumName), "`]\
|
|
|
|
[super::", ::core::stringify!($EnumName), "]"
|
|
|
|
)]
|
|
|
|
}
|
|
|
|
pub trait $EnumName : __sealed::$EnumName + ::core::marker::Sized + 'static {
|
|
|
|
const VALUE: __value::$EnumName;
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
mod __sealed { pub trait $EnumName {} }
|
|
|
|
|
|
|
|
mod __value {
|
|
|
|
#[derive(Debug, PartialEq, Eq)]
|
|
|
|
pub enum $EnumName { $( $Variant ),* }
|
|
|
|
}
|
|
|
|
|
|
|
|
$(
|
|
|
|
$( #[doc = $doc_variant] )*
|
|
|
|
pub enum $Variant {}
|
|
|
|
impl __sealed::$EnumName for $Variant {}
|
|
|
|
impl $EnumName for $Variant {
|
|
|
|
const VALUE: __value::$EnumName = __value::$EnumName::$Variant;
|
|
|
|
}
|
|
|
|
impl $Variant {
|
|
|
|
pub const VALUE: __value::$EnumName = __value::$EnumName::$Variant;
|
|
|
|
}
|
|
|
|
)*
|
|
|
|
}
|
|
|
|
});(
|
|
|
|
with_docs! {
|
|
|
|
$( #[doc = $doc:expr] )*
|
|
|
|
}
|
|
|
|
$item:item
|
|
|
|
) => (
|
|
|
|
$( #[doc = $doc] )*
|
|
|
|
$item
|
|
|
|
)}
|
2021-05-28 19:50:16 +09:00
|
|
|
|
2021-03-10 07:24:53 +09:00
|
|
|
use type_level_enum;
|