node-app-sdk-rust 7.6.207

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`] resolves both symbols once with `dlsym(RTLD_DEFAULT, …)` and
//! caches 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`] — 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();
    }
}

/// Spawn an OS thread that is bound to this app (ADR-314).
///
/// Everything [`std::thread::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.
///
/// # 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,
{
    std::thread::Builder::new().spawn(|| {
        let _binding = ThreadBinding::bind();
        f()
    })
}

#[cfg(test)]
mod tests {
    use super::*;

    /// 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());
    }
}