node-app-sdk-rust 7.7.16

Rust SDK for building Node-App native plugins (cdylib) — Lightning-powered marketplace nodes
Documentation
//! Threads an app starts, charged to the app (ADR-314).
//!
//! A built-in app runs inside the host process, so every thread it starts
//! burns host CPU and allocates host memory that nothing attributes to it on
//! its own: the host can only count such a thread as *unattributed*, landing
//! its cost on "the node". The host therefore exports two hooks that
//! register the calling thread with the app for the thread's whole life
//! (ADR-314 §4):
//!
//! ```c
//! int  node_host_thread_bind_v1(const void *host_data);   /* 0 = bound */
//! void node_host_thread_unbind_v1(const void *host_data);
//! ```
//!
//! [`spawn`] and [`Builder`] resolve both symbols once with
//! `dlsym(RTLD_DEFAULT, …)` and cache them: a host that predates ADR-314 does
//! not export them, and then the helpers still run your closure and bind
//! nothing. The app does not have to know which host it was loaded into.
//!
//! Start every thread through [`spawn`] or [`Builder`] — for a tokio runtime,
//! through the `tokio`-gated `runtime::Builder` — or its CPU and its jemalloc
//! allocations stay outside the app's figures and count as the node's
//! unattributed threads (ADR-314 §3).

use std::ffi::c_void;
use std::io;
use std::sync::atomic::Ordering;
use std::sync::OnceLock;
use std::thread::JoinHandle;

use crate::APP_CONTEXT;

/// Signature of the host's `node_host_thread_bind_v1` (contract C1).
///
/// Returns `0` when the thread is now bound to the app.
type BindHook = unsafe extern "C" fn(host_data: *const c_void) -> i32;

/// Signature of the host's `node_host_thread_unbind_v1` (contract C1).
type UnbindHook = unsafe extern "C" fn(host_data: *const c_void);

/// The contract C1 hooks, resolved once for the lifetime of the process.
struct HostThreadHooks {
    bind: Option<BindHook>,
    unbind: Option<UnbindHook>,
}

static HOST_THREAD_HOOKS: OnceLock<HostThreadHooks> = OnceLock::new();

fn hooks() -> &'static HostThreadHooks {
    HOST_THREAD_HOOKS.get_or_init(resolve_host_thread_hooks)
}

#[cfg(unix)]
fn resolve_host_thread_hooks() -> HostThreadHooks {
    HostThreadHooks {
        bind: resolve_address(b"node_host_thread_bind_v1\0").map(|address| {
            // SAFETY: the address is what `dlsym` found under the C1 name,
            // and `BindHook` is that hook's declared signature.
            unsafe { std::mem::transmute::<*mut c_void, BindHook>(address) }
        }),
        unbind: resolve_address(b"node_host_thread_unbind_v1\0").map(|address| {
            // SAFETY: same, for the unbind half of contract C1.
            unsafe { std::mem::transmute::<*mut c_void, UnbindHook>(address) }
        }),
    }
}

/// Look one hook up in the process's global symbol scope.
///
/// Returns `None` when the host does not export it (an older host), which is
/// the normal case on a node that predates ADR-314.
#[cfg(unix)]
fn resolve_address(name: &'static [u8]) -> Option<*mut c_void> {
    // SAFETY: `name` is a NUL-terminated byte string, which is exactly what
    // `dlsym` asks for, and a null answer is only an answer.
    unsafe {
        let symbol = libc::dlsym(libc::RTLD_DEFAULT, name.as_ptr().cast::<std::ffi::c_char>());
        if symbol.is_null() {
            None
        } else {
            Some(symbol)
        }
    }
}

/// No hook lookup off unix: the host exports contract C1 on the unix hosts
/// that ship this SDK, so elsewhere every helper binds nothing and just runs.
#[cfg(not(unix))]
fn resolve_host_thread_hooks() -> HostThreadHooks {
    HostThreadHooks {
        bind: None,
        unbind: None,
    }
}

/// The `host_data` pointer the host passed in `init`, read the same way
/// every other SDK helper reads it: `None` before init is a null pointer,
/// and the host answers a bind with `2 = unknown host_data`.
fn current_host_data() -> *const c_void {
    let context = APP_CONTEXT.load(Ordering::Acquire);
    if context.is_null() {
        return std::ptr::null();
    }
    // SAFETY: `APP_CONTEXT` is null or a live `NodeAppContext` for as long as
    // the host keeps this app instance alive — the invariant every SDK helper
    // that calls into the host already relies on.
    unsafe { (*context).host_data }
}

/// One thread's registration with the host, released when it drops.
///
/// `bound` is false when the host did not take the binding: no hooks
/// exported at all (an older host, or a non-unix target), only one half of
/// contract C1, or the hook answered `1 = not supported`,
/// `2 = unknown host_data` or `3 = already bound`. Releasing a binding that
/// was never made is a no-op, so a thread that is offered a binding twice is
/// never unbound twice.
pub(crate) struct ThreadBinding {
    host_data: *const c_void,
    bound: bool,
}

impl ThreadBinding {
    /// Bind the calling thread to this app.
    pub(crate) fn bind() -> Self {
        let host_data = current_host_data();
        let resolved = hooks();
        // Bind only when the host offers the whole contract: a build that
        // exports one half alone would register the tid and never see it
        // released, and an unbound tid is exactly what keeps a reused tid
        // from being charged to the wrong app (ADR-314 §3).
        let bound = match (resolved.bind, resolved.unbind) {
            (Some(bind), Some(_)) => unsafe { bind(host_data) == 0 },
            _ => false,
        };
        Self { host_data, bound }
    }

    /// Release the binding, if this thread is the one that made it.
    fn release(&mut self) {
        if self.bound {
            self.bound = false;
            if let Some(unbind) = hooks().unbind {
                // SAFETY: `host_data` came from `current_host_data` at bind
                // time and the host keeps it alive for the whole app
                // instance; `unbind` is idempotent (contract C1).
                unsafe { unbind(self.host_data) };
            }
        }
    }
}

impl Drop for ThreadBinding {
    fn drop(&mut self) {
        self.release();
    }
}

/// Thread factory mirroring [`std::thread::Builder`], with app binding (ADR-314).
///
/// Same knobs as the std builder — [`Builder::name`] and [`Builder::stack_size`]
/// — plus the host bind/unbind around the closure. Use this when an app needs
/// a named long-lived thread or a smaller stack (for example 512 KiB on a Pi
/// Zero 2 W); use [`spawn`] when the defaults are enough.
///
/// # Examples
///
/// ```
/// use node_app_sdk_rust::thread::Builder;
///
/// let handle = Builder::new()
///     .name("worker".into())
///     .stack_size(512 * 1024)
///     .spawn(|| 6 * 7)
///     .unwrap();
/// assert_eq!(handle.join().unwrap(), 42);
/// ```
pub struct Builder {
    inner: std::thread::Builder,
}

impl Builder {
    /// Same defaults as [`std::thread::Builder::new`].
    pub fn new() -> Self {
        Self {
            inner: std::thread::Builder::new(),
        }
    }

    /// Sets the name of the thread for debugging and panic messages.
    pub fn name(self, name: String) -> Self {
        Self {
            inner: self.inner.name(name),
        }
    }

    /// Sets the size of the stack (in bytes) for the new thread.
    pub fn stack_size(self, size: usize) -> Self {
        Self {
            inner: self.inner.stack_size(size),
        }
    }

    /// Spawns an OS thread that is bound to this app (ADR-314).
    ///
    /// Everything [`std::thread::Builder::spawn`] does, plus the binding: the
    /// host charges the new thread's CPU and the memory it allocates to this
    /// app from the moment it starts until it exits. The binding is released
    /// when the closure returns — including when it panics, and including when
    /// the OS refuses to start the thread (then there is nothing to release).
    ///
    /// A host that predates ADR-314 exports no hooks: the closure still runs
    /// and nothing else happens.
    ///
    /// # Errors
    ///
    /// The OS could not create a thread; the closure never runs.
    pub fn spawn<F, T>(self, f: F) -> io::Result<JoinHandle<T>>
    where
        F: FnOnce() -> T + Send + 'static,
        T: Send + 'static,
    {
        self.inner.spawn(|| {
            let _binding = ThreadBinding::bind();
            f()
        })
    }
}

impl Default for Builder {
    fn default() -> Self {
        Self::new()
    }
}

/// Spawn an OS thread that is bound to this app (ADR-314).
///
/// Thin wrapper around [`Builder::new().spawn`](Builder::spawn): same binding
/// semantics, default name and stack size. Prefer [`Builder`] when you need a
/// name or a custom stack.
///
/// # Errors
///
/// The OS could not create a thread; the closure never runs.
///
/// # Examples
///
/// ```
/// let handle = node_app_sdk_rust::thread::spawn(|| 6 * 7).unwrap();
/// assert_eq!(handle.join().unwrap(), 42);
/// ```
pub fn spawn<F, T>(f: F) -> io::Result<JoinHandle<T>>
where
    F: FnOnce() -> T + Send + 'static,
    T: Send + 'static,
{
    Builder::new().spawn(f)
}

#[cfg(test)]
mod tests {
    use super::*;
    use std::sync::{Arc, Mutex};

    /// 512 KiB — the stack size apps use for long-lived threads on Pi Zero 2 W.
    const SMALL_STACK: usize = 512 * 1024;

    /// The absence half of ADR-314's contract C1 tests: this test binary
    /// exports no `node_host_thread_*` symbol, so a host-less build of the
    /// helpers must find nothing to bind with.
    #[cfg(unix)]
    #[test]
    fn host_thread_hooks_are_absent_here() {
        // SAFETY: `dlsym` gets NUL-terminated byte strings and its null
        // answer is the answer under test.
        unsafe {
            assert!(libc::dlsym(
                libc::RTLD_DEFAULT,
                b"node_host_thread_bind_v1\0"
                    .as_ptr()
                    .cast::<std::ffi::c_char>()
            )
            .is_null());
            assert!(libc::dlsym(
                libc::RTLD_DEFAULT,
                b"node_host_thread_unbind_v1\0"
                    .as_ptr()
                    .cast::<std::ffi::c_char>()
            )
            .is_null());
        }
        assert!(hooks().bind.is_none());
        assert!(hooks().unbind.is_none());
    }

    /// With the hooks absent, `spawn` runs the closure and does nothing else.
    #[test]
    fn spawn_runs_the_closure_without_a_host() {
        let handle = spawn(|| 40 + 2).unwrap();
        assert_eq!(handle.join().unwrap(), 42);
    }

    /// Nothing is bound, so nothing is released on the way out — not even
    /// with no host context stored at all.
    #[test]
    fn binding_without_hooks_is_a_silent_no_op() {
        let binding = ThreadBinding::bind();
        assert!(!binding.bound);
        drop(binding);
        assert!(hooks().bind.is_none());
    }

    /// [`Builder::name`] reaches the OS thread: the closure sees it on
    /// [`std::thread::current`].
    #[test]
    fn builder_applies_thread_name() {
        let handle = Builder::new()
            .name("sdk-thread-builder".into())
            .spawn(|| {
                std::thread::current()
                    .name()
                    .map(str::to_owned)
                    .expect("thread name set by Builder")
            })
            .unwrap();
        assert_eq!(handle.thread().name(), Some("sdk-thread-builder"));
        assert_eq!(handle.join().unwrap(), "sdk-thread-builder");
    }

    /// [`Builder::stack_size`] is forwarded to the OS; a 512 KiB stack still
    /// runs the closure (the size apps keep for long-lived Pi Zero 2 W threads).
    #[test]
    fn builder_applies_stack_size() {
        let handle = Builder::new()
            .stack_size(SMALL_STACK)
            .spawn(|| 21 * 2)
            .unwrap();
        assert_eq!(handle.join().unwrap(), 42);
    }

    /// Name and stack size can be set together; both still apply.
    #[test]
    fn builder_applies_name_and_stack_size_together() {
        let handle = Builder::new()
            .name("sdk-named-stack".into())
            .stack_size(SMALL_STACK)
            .spawn(|| {
                std::thread::current()
                    .name()
                    .map(str::to_owned)
                    .expect("thread name set by Builder")
            })
            .unwrap();
        assert_eq!(handle.join().unwrap(), "sdk-named-stack");
    }

    /// With hooks absent, a panicking closure still exits cleanly: Drop of
    /// the (unbound) guard is a no-op and `join` reports the panic.
    #[test]
    fn spawn_reports_panic_without_a_host() {
        let handle = spawn(|| panic!("expected test panic")).unwrap();
        assert!(handle.join().unwrap_err().downcast_ref::<&str>().is_some());
    }

    /// Same panic path through [`Builder`]: unbind (a no-op here) still runs
    /// via Drop before the panic is delivered to `join`.
    #[test]
    fn builder_unbinds_on_panic_without_a_host() {
        let saw_bind_drop = Arc::new(Mutex::new(false));
        let flag = Arc::clone(&saw_bind_drop);
        let handle = Builder::new()
            .name("sdk-panic".into())
            .stack_size(SMALL_STACK)
            .spawn(move || {
                // Observe that we entered the thread; Drop of ThreadBinding
                // runs on the way out of the panic unwind.
                *flag.lock().unwrap() = true;
                panic!("expected builder panic");
            })
            .unwrap();
        assert!(handle.join().is_err());
        assert!(*saw_bind_drop.lock().unwrap());
    }
}