node-app-sdk-rust 7.6.209

Rust SDK for building Node-App native plugins (cdylib) — Lightning-powered marketplace nodes
Documentation
//! Contract C1 with the hooks **present**: this test binary exports stub
//! `node_host_thread_*` symbols, so `thread::spawn` must call each one once
//! per thread — bind before the closure runs, unbind after it — with the
//! `host_data` the SDK stored at init.

use std::ffi::{c_char, c_void};
use std::sync::Mutex;

use node_app_sdk_rust::{FfiResult, NodeAppContext};

/// `host_data` handed to the stubs, so the test can check which app
/// registered each thread.
static HOST_DATA: u8 = 0;

#[derive(Debug, Clone, Copy, PartialEq, Eq)]
enum Hook {
    Bind,
    Unbind,
}

#[derive(Debug, PartialEq, Eq)]
struct Call {
    thread: usize,
    hook: Hook,
    host_data: usize,
}

static CALLS: Mutex<Vec<Call>> = Mutex::new(Vec::new());

fn record(hook: Hook, host_data: *const c_void) {
    // SAFETY: `pthread_self` belongs to the calling thread and the mutex has
    // no poisoned state this test cannot recover from.
    let thread = unsafe { libc::pthread_self() } as usize;
    CALLS.lock().unwrap().push(Call {
        thread,
        hook,
        host_data: host_data as usize,
    });
}

/// Stub of the host export (contract C1): "0 = bound".
#[no_mangle]
pub extern "C" fn node_host_thread_bind_v1(host_data: *const c_void) -> i32 {
    record(Hook::Bind, host_data);
    0
}

/// Stub of the host export (contract C1): idempotent.
#[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
}

/// Resolves both C1 symbols from this process — the proof that the stubs
/// above are really what `dlsym` hands the SDK.
fn hooks_are_exported() -> bool {
    // SAFETY: NUL-terminated byte strings in, only a null-check on the way
    // out.
    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()
    }
}

#[test]
fn bind_and_unbind_run_once_per_thread_in_order() {
    assert!(hooks_are_exported());

    let host_data = &HOST_DATA as *const _ as *const c_void;
    let context = 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,
    };
    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]);

    let calls = CALLS.lock().unwrap();
    assert_eq!(
        calls.len(),
        6,
        "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(), 3, "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})"
        );
    }

    drop(calls);
    node_app_sdk_rust::__store_context(std::ptr::null());
}