use std::ffi::{c_char, c_void};
use std::sync::Mutex;
use node_app_sdk_rust::thread::Builder;
use node_app_sdk_rust::{FfiResult, NodeAppContext};
static HOST_DATA: u8 = 0;
const SMALL_STACK: usize = 512 * 1024;
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
enum Hook {
Bind,
Unbind,
}
#[derive(Debug, Clone, PartialEq, Eq)]
struct Call {
thread: usize,
hook: Hook,
host_data: usize,
}
static CALLS: Mutex<Vec<Call>> = Mutex::new(Vec::new());
static TEST_LOCK: Mutex<()> = Mutex::new(());
fn record(hook: Hook, host_data: *const c_void) {
let thread = unsafe { libc::pthread_self() } as usize;
CALLS.lock().unwrap().push(Call {
thread,
hook,
host_data: host_data as usize,
});
}
fn clear_calls() {
CALLS
.lock()
.unwrap_or_else(|poisoned| poisoned.into_inner())
.clear();
}
fn lock_suite() -> std::sync::MutexGuard<'static, ()> {
TEST_LOCK
.lock()
.unwrap_or_else(|poisoned| poisoned.into_inner())
}
#[no_mangle]
pub extern "C" fn node_host_thread_bind_v1(host_data: *const c_void) -> i32 {
record(Hook::Bind, host_data);
0
}
#[no_mangle]
pub extern "C" fn node_host_thread_unbind_v1(host_data: *const c_void) {
record(Hook::Unbind, host_data);
}
unsafe extern "C" fn noop_log(_host_data: *const c_void, _level: u32, _message: *const c_char) {}
unsafe extern "C" fn no_config(_host_data: *const c_void, _key: *const c_char) -> *const c_char {
std::ptr::null()
}
unsafe extern "C" fn noop_set_storage(
_host_data: *const c_void,
_key: *const c_char,
_value: *const c_char,
) {
}
unsafe extern "C" fn no_get_storage(
_host_data: *const c_void,
_key: *const c_char,
) -> *const c_char {
std::ptr::null()
}
unsafe extern "C" fn no_invoke(
_host_data: *const c_void,
_request_json: *const u8,
_request_len: usize,
) -> FfiResult {
FfiResult {
success: false,
error_code: -1,
data: std::ptr::null_mut(),
data_len: 0,
}
}
unsafe extern "C" fn noop_publish(
_host_data: *const c_void,
_event_name: *const u8,
_event_name_len: usize,
_event_data: *const u8,
_event_data_len: usize,
) -> i32 {
0
}
fn hooks_are_exported() -> bool {
unsafe {
!libc::dlsym(
libc::RTLD_DEFAULT,
b"node_host_thread_bind_v1\0".as_ptr().cast::<c_char>(),
)
.is_null()
&& !libc::dlsym(
libc::RTLD_DEFAULT,
b"node_host_thread_unbind_v1\0".as_ptr().cast::<c_char>(),
)
.is_null()
}
}
fn test_context(host_data: *const c_void) -> NodeAppContext {
NodeAppContext {
host_data,
host_log: noop_log,
host_get_config: no_config,
host_set_storage: noop_set_storage,
host_get_storage: no_get_storage,
host_invoke_capability: no_invoke,
host_publish_event: noop_publish,
}
}
fn assert_bind_unbind_once_per_thread(host_data: *const c_void, expected_threads: usize) {
let calls = CALLS.lock().unwrap().clone();
assert_eq!(
calls.len(),
expected_threads * 2,
"one bind and one unbind per thread: {calls:?}"
);
assert!(
calls.iter().all(|c| c.host_data == host_data as usize),
"every call must carry the app's host_data: {calls:?}"
);
let mut threads: Vec<usize> = calls.iter().map(|c| c.thread).collect();
threads.sort_unstable();
threads.dedup();
assert_eq!(
threads.len(),
expected_threads,
"one entry per spawned thread: {calls:?}"
);
for thread in threads {
let sequence: Vec<(Hook, usize)> = calls
.iter()
.filter(|c| c.thread == thread)
.map(|c| (c.hook, c.host_data))
.collect();
assert_eq!(
sequence,
vec![
(Hook::Bind, host_data as usize),
(Hook::Unbind, host_data as usize)
],
"bind first, unbind last, exactly once (thread {thread})"
);
}
}
#[test]
fn bind_and_unbind_run_once_per_thread_in_order() {
let _guard = lock_suite();
assert!(hooks_are_exported());
clear_calls();
let host_data = &HOST_DATA as *const _ as *const c_void;
let context = test_context(host_data);
node_app_sdk_rust::__store_context(&context);
let handles: Vec<_> = (0..3)
.map(|i| node_app_sdk_rust::thread::spawn(move || i * 2).unwrap())
.collect();
let mut results: Vec<i32> = handles.into_iter().map(|h| h.join().unwrap()).collect();
results.sort_unstable();
assert_eq!(results, vec![0, 2, 4]);
assert_bind_unbind_once_per_thread(host_data, 3);
node_app_sdk_rust::__store_context(std::ptr::null());
}
#[test]
fn builder_applies_name_and_stack_size_with_hooks() {
let _guard = lock_suite();
assert!(hooks_are_exported());
clear_calls();
let host_data = &HOST_DATA as *const _ as *const c_void;
let context = test_context(host_data);
node_app_sdk_rust::__store_context(&context);
let handle = Builder::new()
.name("sdk-hook-named".into())
.stack_size(SMALL_STACK)
.spawn(|| {
std::thread::current()
.name()
.map(str::to_owned)
.expect("thread name set by Builder")
})
.unwrap();
assert_eq!(handle.thread().name(), Some("sdk-hook-named"));
assert_eq!(handle.join().unwrap(), "sdk-hook-named");
assert_bind_unbind_once_per_thread(host_data, 1);
node_app_sdk_rust::__store_context(std::ptr::null());
}
#[test]
fn builder_unbinds_once_when_closure_panics() {
let _guard = lock_suite();
assert!(hooks_are_exported());
clear_calls();
let host_data = &HOST_DATA as *const _ as *const c_void;
let context = test_context(host_data);
node_app_sdk_rust::__store_context(&context);
let handle = Builder::new()
.name("sdk-hook-panic".into())
.stack_size(SMALL_STACK)
.spawn(|| panic!("expected hook-present panic"))
.unwrap();
assert!(handle.join().is_err());
assert_bind_unbind_once_per_thread(host_data, 1);
node_app_sdk_rust::__store_context(std::ptr::null());
}