use crate::napi::*;
use crate::value::{self, Result, Thrown};
type Settle = Box<dyn FnOnce(napi_env) -> Result<napi_value> + Send>;
enum Work {
Settle(Completion),
Deliver {
listeners: std::sync::Arc<std::sync::Mutex<Vec<std::sync::Arc<crate::object::Held>>>>,
value: Vec<u8>,
},
}
struct Completion {
settle: Settle,
deferred: napi_deferred,
rejected: bool,
}
unsafe impl Send for Completion {}
unsafe impl Send for Work {}
pub struct Runtime {
executor: crate::exec::Executor,
bridge: std::sync::Mutex<Option<&'static Bridge>>,
}
#[derive(Default)]
pub struct LoopHold(std::sync::atomic::AtomicUsize);
impl LoopHold {
pub fn acquire(&self) -> bool {
self.0.fetch_add(1, std::sync::atomic::Ordering::AcqRel) == 0
}
pub fn release(&self) -> bool {
self.0.fetch_sub(1, std::sync::atomic::Ordering::AcqRel) == 1
}
pub fn undo(&self) {
self.0.fetch_sub(1, std::sync::atomic::Ordering::AcqRel);
}
#[allow(dead_code)]
pub fn outstanding(&self) -> usize {
self.0.load(std::sync::atomic::Ordering::Acquire)
}
}
struct Bridge {
function: napi_threadsafe_function,
in_flight: LoopHold,
}
unsafe impl Send for Bridge {}
unsafe impl Sync for Bridge {}
impl Default for Runtime {
fn default() -> Self {
Self::new()
}
}
impl Runtime {
pub fn new() -> Self {
Self {
executor: crate::exec::Executor::new(),
bridge: std::sync::Mutex::new(None),
}
}
fn bridge(&self, env: napi_env) -> Result<&'static Bridge> {
let mut slot = self.bridge.lock().unwrap();
if slot.is_none() {
let name = value::string(env, "webbluetooth")?;
let mut function: napi_threadsafe_function = std::ptr::null_mut();
let bridge: &'static Bridge = Box::leak(Box::new(Bridge {
function: std::ptr::null_mut(),
in_flight: LoopHold::default(),
}));
let context = bridge as *const Bridge as *mut std::ffi::c_void;
value::ok(
unsafe {
napi_create_threadsafe_function(
env,
std::ptr::null_mut(),
std::ptr::null_mut(),
name,
0,
1,
std::ptr::null_mut(),
None,
context,
Some(deliver),
&mut function,
)
},
"napi_create_threadsafe_function",
)?;
value::ok(
unsafe { napi_unref_threadsafe_function(env, function) },
"napi_unref_threadsafe_function",
)?;
unsafe {
let slot = bridge as *const Bridge as *mut Bridge;
(*slot).function = function;
}
*slot = Some(bridge);
}
slot.ok_or_else(|| Thrown("the runtime bridge is missing".into()))
}
pub fn spawn(&self, future: impl std::future::Future<Output = ()> + Send + 'static) -> bool {
self.executor.spawn(future)
}
pub fn promise<T, F>(&self, env: napi_env, future: F) -> Result<napi_value>
where
T: IntoJs + Send + 'static,
F: std::future::Future<Output = std::result::Result<T, webbluetooth::Error>>
+ Send
+ 'static,
{
self.promise_with(env, future, |env, value: T| value.into_js(env))
}
pub fn promise_with<T, F, C>(&self, env: napi_env, future: F, into_js: C) -> Result<napi_value>
where
T: Send + 'static,
F: std::future::Future<Output = std::result::Result<T, webbluetooth::Error>>
+ Send
+ 'static,
C: FnOnce(napi_env, T) -> Result<napi_value> + Send + 'static,
{
let mut deferred: napi_deferred = std::ptr::null_mut();
let mut promise: napi_value = std::ptr::null_mut();
value::ok(
unsafe { napi_create_promise(env, &mut deferred, &mut promise) },
"napi_create_promise",
)?;
let bridge = self.bridge(env)?;
hold(env, bridge)?;
let deferred = SendDeferred(deferred);
let queued = self.executor.spawn(async move {
let deferred = deferred;
let outcome = future.await;
let completion = match outcome {
Ok(value) => Completion {
settle: Box::new(move |env| into_js(env, value)),
deferred: deferred.0,
rejected: false,
},
Err(error) => {
let message = error.to_string();
Completion {
settle: Box::new(move |env| js_error(env, &message)),
deferred: deferred.0,
rejected: true,
}
}
};
let boxed = Box::into_raw(Box::new(Work::Settle(completion))) as *mut std::ffi::c_void;
let status = unsafe {
napi_call_threadsafe_function(bridge.function, boxed, NAPI_TSFN_NONBLOCKING)
};
if status != NAPI_OK {
drop(unsafe { Box::from_raw(boxed as *mut Work) });
}
});
if !queued {
release(env, bridge);
return Err(Thrown("the executor thread has stopped".into()));
}
Ok(promise)
}
}
struct SendDeferred(napi_deferred);
unsafe impl Send for SendDeferred {}
unsafe extern "C" fn deliver(
env: napi_env,
_js_callback: napi_value,
context: *mut std::ffi::c_void,
data: *mut std::ffi::c_void,
) {
if data.is_null() {
return;
}
let work = unsafe { Box::from_raw(data as *mut Work) };
if env.is_null() {
return;
}
let completion = match *work {
Work::Settle(completion) => completion,
Work::Deliver { listeners, value } => {
let Ok(buffer) = value::array_buffer(env, &value) else {
return;
};
let current: Vec<_> = listeners.lock().unwrap().clone();
for listener in current {
let _ = unsafe { listener.call(env, buffer) };
}
return;
}
};
if !context.is_null() {
release(env, unsafe { &*(context as *const Bridge) });
}
let Completion {
settle,
deferred,
rejected,
} = completion;
let value = match settle(env) {
Ok(value) => value,
Err(Thrown(message)) => match js_error(env, &message) {
Ok(error) => {
unsafe { napi_reject_deferred(env, deferred, error) };
return;
}
Err(_) => return,
},
};
unsafe {
match rejected {
true => napi_reject_deferred(env, deferred, value),
false => napi_resolve_deferred(env, deferred, value),
}
};
}
fn hold(env: napi_env, bridge: &Bridge) -> Result<()> {
if !bridge.in_flight.acquire() {
return Ok(());
}
let status = unsafe { napi_ref_threadsafe_function(env, bridge.function) };
if let Err(e) = value::ok(status, "napi_ref_threadsafe_function") {
bridge.in_flight.undo();
return Err(e);
}
Ok(())
}
fn release(env: napi_env, bridge: &Bridge) {
if bridge.in_flight.release() {
unsafe { napi_unref_threadsafe_function(env, bridge.function) };
}
}
pub fn deliver_to(
bridge_of: &Runtime,
listeners: std::sync::Arc<std::sync::Mutex<Vec<std::sync::Arc<crate::object::Held>>>>,
value: Vec<u8>,
) {
let Some(bridge) = *bridge_of.bridge.lock().unwrap() else {
return; };
let boxed =
Box::into_raw(Box::new(Work::Deliver { listeners, value })) as *mut std::ffi::c_void;
let status =
unsafe { napi_call_threadsafe_function(bridge.function, boxed, NAPI_TSFN_NONBLOCKING) };
if status != NAPI_OK {
drop(unsafe { Box::from_raw(boxed as *mut Work) });
}
}
fn js_error(env: napi_env, message: &str) -> Result<napi_value> {
let text = value::string(env, message)?;
let mut error = std::ptr::null_mut();
value::ok(
unsafe { napi_create_error(env, std::ptr::null_mut(), text, &mut error) },
"napi_create_error",
)?;
Ok(error)
}
pub trait IntoJs {
fn into_js(self, env: napi_env) -> Result<napi_value>;
}
impl IntoJs for () {
fn into_js(self, env: napi_env) -> Result<napi_value> {
value::undefined(env)
}
}
impl IntoJs for bool {
fn into_js(self, env: napi_env) -> Result<napi_value> {
value::boolean(env, self)
}
}
impl IntoJs for String {
fn into_js(self, env: napi_env) -> Result<napi_value> {
value::string(env, &self)
}
}
impl IntoJs for i32 {
fn into_js(self, env: napi_env) -> Result<napi_value> {
value::number(env, self as f64)
}
}
impl IntoJs for u16 {
fn into_js(self, env: napi_env) -> Result<napi_value> {
value::number(env, self as f64)
}
}
impl IntoJs for Vec<u8> {
fn into_js(self, env: napi_env) -> Result<napi_value> {
value::array_buffer(env, &self)
}
}
impl<T: IntoJs> IntoJs for Option<T> {
fn into_js(self, env: napi_env) -> Result<napi_value> {
match self {
Some(value) => value.into_js(env),
None => value::null(env),
}
}
}
impl<T: IntoJs> IntoJs for Vec<T> {
fn into_js(self, env: napi_env) -> Result<napi_value> {
let items: Result<Vec<_>> = self.into_iter().map(|i| i.into_js(env)).collect();
value::array(env, &items?)
}
}
#[cfg(test)]
mod tests {
use super::*;
use std::sync::Arc;
#[test]
fn the_loop_is_released_only_by_the_last_holder() {
let held = LoopHold::default();
assert!(held.acquire(), "the first hold must reference the loop");
assert!(!held.acquire(), "the second must not reference it again");
assert!(!held.acquire());
assert_eq!(held.outstanding(), 3);
assert!(!held.release(), "two are still out");
assert!(!held.release(), "one is still out");
assert!(held.release(), "the last must release the loop");
assert_eq!(held.outstanding(), 0);
}
#[test]
fn an_undone_hold_leaves_the_count_where_it_started() {
let held = LoopHold::default();
assert!(held.acquire());
held.undo();
assert_eq!(held.outstanding(), 0);
assert!(held.acquire());
}
#[test]
fn concurrent_holds_net_out() {
let held = Arc::new(LoopHold::default());
assert!(held.acquire());
let threads: Vec<_> = (0..8)
.map(|_| {
let held = held.clone();
std::thread::spawn(move || {
for _ in 0..1000 {
assert!(!held.acquire(), "the kept hold means never first");
assert!(!held.release(), "nor ever last");
}
})
})
.collect();
for t in threads {
t.join().expect("no thread should have panicked");
}
assert_eq!(held.outstanding(), 1, "only the kept hold remains");
assert!(held.release());
}
#[test]
fn a_runtime_starts_and_accepts_work() {
let runtime = Runtime::new();
let done = Arc::new(std::sync::atomic::AtomicBool::new(false));
let flag = done.clone();
assert!(runtime.executor.spawn(async move {
flag.store(true, std::sync::atomic::Ordering::SeqCst);
}));
let deadline = std::time::Instant::now() + std::time::Duration::from_secs(5);
while std::time::Instant::now() < deadline
&& !done.load(std::sync::atomic::Ordering::SeqCst)
{
std::thread::yield_now();
}
assert!(done.load(std::sync::atomic::Ordering::SeqCst));
}
}