node-app-sdk-rust 7.6.211

Rust SDK for building Node-App native plugins (cdylib) — Lightning-powered marketplace nodes
Documentation
//! Contract C1 through `runtime::Builder` with the hooks **present**: this
//! test binary exports stub `node_host_thread_*` symbols, and every runtime
//! thread must bind once on the way in and unbind once on the way out, with
//! the caller's own callbacks in between.

#![cfg(feature = "tokio")]

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

use node_app_sdk_rust::runtime::Builder;
use node_app_sdk_rust::{FfiResult, NodeAppContext};

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

#[derive(Debug, Clone, Copy, PartialEq, Eq)]
enum Hook {
    Bind,
    UserStart,
    UserStop,
    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: Option<*const c_void>) {
    // SAFETY: `pthread_self` belongs to the calling thread; the callbacks
    // carry no pointer, so only the hooks pass one.
    let thread = unsafe { libc::pthread_self() } as usize;
    CALLS.lock().unwrap().push(Call {
        thread,
        hook,
        host_data: host_data.map_or(0, |pointer| pointer 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, Some(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, Some(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
}

/// Waits for the runtime's threads to leave: a worker thread exits
/// asynchronously while the dropped runtime shuts down.
fn waits_for_leaving(condition: impl Fn() -> bool) -> bool {
    let deadline = Instant::now() + Duration::from_secs(10);
    loop {
        if condition() {
            return true;
        }
        if Instant::now() >= deadline {
            return false;
        }
        std::thread::sleep(Duration::from_millis(20));
    }
}

#[test]
fn runtime_threads_bind_and_unbind_once_in_order() {
    // SAFETY: NUL-terminated byte strings in, only a null-check on the way
    // out.
    assert!(
        unsafe {
            !libc::dlsym(
                libc::RTLD_DEFAULT,
                b"node_host_thread_bind_v1\0".as_ptr().cast::<c_char>(),
            )
            .is_null()
        },
        "the stubs must be exported for this test to mean anything"
    );

    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 mut builder = Builder::new_multi_thread();
    builder
        .worker_threads(2)
        .thread_name("sdk-hook-test")
        .on_thread_start(|| record(Hook::UserStart, None))
        .on_thread_stop(|| record(Hook::UserStop, None));
    let runtime = builder.build().unwrap();

    assert_eq!(
        runtime.block_on(async {
            tokio::task::yield_now().await;
            6 * 7
        }),
        42
    );
    drop(runtime);

    let bound = || {
        let calls = CALLS.lock().unwrap();
        let binds = calls.iter().filter(|c| c.hook == Hook::Bind).count();
        let unbinds = calls.iter().filter(|c| c.hook == Hook::Unbind).count();
        binds > 0 && binds == unbinds
    };
    assert!(
        waits_for_leaving(bound),
        "runtime threads never all left: {:?}",
        *CALLS.lock().unwrap()
    );

    let calls = CALLS.lock().unwrap();
    assert!(
        calls
            .iter()
            .filter(|c| matches!(c.hook, Hook::Bind | Hook::Unbind))
            .all(|c| c.host_data == host_data as usize),
        "every binding 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!(!threads.is_empty(), "no runtime thread ever started");

    for thread in threads {
        let sequence: Vec<Hook> = calls
            .iter()
            .filter(|c| c.thread == thread)
            .map(|c| c.hook)
            .collect();
        assert_eq!(
            sequence,
            vec![Hook::Bind, Hook::UserStart, Hook::UserStop, Hook::Unbind],
            "bind before the caller's start callback, unbind after its stop \
             callback, exactly once (thread {thread})"
        );
    }

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