node-app-sdk-rust 7.7.8

Rust SDK for building Node-App native plugins (cdylib) — Lightning-powered marketplace nodes
Documentation
//! A tokio runtime whose threads are bound to this app (ADR-314).
//!
//! [`Builder`] wraps [`tokio::runtime::Builder`] and wires its
//! `on_thread_start` / `on_thread_stop` callbacks to the host's thread hooks
//! (contract C1): every worker thread and every blocking-pool thread binds
//! itself to the app when it starts and releases the binding when it exits.
//! Without that, a tokio runtime inside a built-in app is exactly the case
//! ADR-314 calls unattributed — its CPU and its allocations count as the
//! node's.
//!
//! Available behind the `tokio` cargo feature. Configure and build it the
//! same way as tokio's own builder:
//!
//! ```
//! # fn main() -> std::io::Result<()> {
//! use node_app_sdk_rust::runtime::Builder;
//!
//! let runtime = Builder::new_multi_thread()
//!     .worker_threads(4)
//!     .thread_name("my-app")
//!     .enable_all()
//!     .build()?;
//! assert_eq!(runtime.block_on(async { 6 * 7 }), 42);
//! # Ok(())
//! # }
//! ```
//!
//! Your own [`on_thread_start`](Builder::on_thread_start) /
//! [`on_thread_stop`](Builder::on_thread_stop) callbacks are kept: they run
//! after the bind and before the unbind, so the work they do is still
//! charged to the app.
//!
//! A host that predates ADR-314 exports no hooks; the runtime then behaves
//! like tokio's, with the callbacks doing nothing else.

use std::cell::RefCell;
use std::io;
use std::sync::Arc;

use crate::thread::ThreadBinding;

pub use tokio::runtime::Runtime;

/// A user callback installed on the wrapped builder.
type ThreadCallback = Arc<dyn Fn() + Send + Sync>;

thread_local! {
    /// The binding this thread holds while it runs inside the runtime, if
    /// the host accepted one. `on_thread_start` puts it there and
    /// `on_thread_stop` takes it, because the two callbacks run on opposite
    /// sides of the thread's whole life — an RAII guard created in the first
    /// would drop at the end of that callback.
    static BINDING: RefCell<Option<ThreadBinding>> = const { RefCell::new(None) };
}

/// A [`tokio::runtime::Builder`] that binds its threads to the app.
///
/// See the [module documentation](self) for the attribution rules; the
/// methods mirror tokio's builder, plus the two callbacks.
pub struct Builder {
    inner: tokio::runtime::Builder,
    on_thread_start: Option<ThreadCallback>,
    on_thread_stop: Option<ThreadCallback>,
}

impl Builder {
    fn new(inner: tokio::runtime::Builder) -> Self {
        Self {
            inner,
            on_thread_start: None,
            on_thread_stop: None,
        }
    }

    /// A multithreaded scheduler with one worker thread per CPU.
    pub fn new_multi_thread() -> Self {
        Self::new(tokio::runtime::Builder::new_multi_thread())
    }

    /// A single-threaded scheduler: all tasks run on the thread that calls
    /// [`Runtime::block_on`]; blocking work still runs on runtime threads,
    /// which bind like any other.
    pub fn new_current_thread() -> Self {
        Self::new(tokio::runtime::Builder::new_current_thread())
    }

    /// Number of worker threads in a multithreaded runtime.
    pub fn worker_threads(&mut self, threads: usize) -> &mut Self {
        self.inner.worker_threads(threads);
        self
    }

    /// Upper bound on the runtime's blocking threads.
    pub fn max_blocking_threads(&mut self, limit: usize) -> &mut Self {
        self.inner.max_blocking_threads(limit);
        self
    }

    /// Names the runtime's threads (`tokio` shows the name in panics and in
    /// `/proc`/`ps`).
    pub fn thread_name(&mut self, name: impl Into<String>) -> &mut Self {
        self.inner.thread_name(name);
        self
    }

    /// Stack size of each runtime thread.
    pub fn thread_stack_size(&mut self, bytes: usize) -> &mut Self {
        self.inner.thread_stack_size(bytes);
        self
    }

    /// Enables the I/O and time drivers (`tokio::runtime::Builder::enable_all`).
    pub fn enable_all(&mut self) -> &mut Self {
        self.inner.enable_all();
        self
    }

    /// Runs `callback` on each runtime thread right after it binds to the app.
    pub fn on_thread_start<F>(&mut self, callback: F) -> &mut Self
    where
        F: Fn() + Send + Sync + 'static,
    {
        self.on_thread_start = Some(Arc::new(callback));
        self
    }

    /// Runs `callback` on each runtime thread just before it releases its
    /// binding to the app.
    pub fn on_thread_stop<F>(&mut self, callback: F) -> &mut Self
    where
        F: Fn() + Send + Sync + 'static,
    {
        self.on_thread_stop = Some(Arc::new(callback));
        self
    }

    /// Builds the runtime with the app binding installed on every thread it
    /// starts.
    ///
    /// # Errors
    ///
    /// The same errors as [`tokio::runtime::Builder::build`] — typically an
    /// I/O or timer driver that could not start. No thread is left bound
    /// when this fails.
    pub fn build(&mut self) -> io::Result<Runtime> {
        let started = self.on_thread_start.clone();
        let stopping = self.on_thread_stop.clone();

        self.inner.on_thread_start(move || {
            // Bind first, so the user's own start callback already runs
            // charged to the app.
            BINDING.with(|binding| *binding.borrow_mut() = Some(ThreadBinding::bind()));
            if let Some(callback) = started.as_ref() {
                callback();
            }
        });
        self.inner.on_thread_stop(move || {
            // Unbind last, for the same reason in reverse.
            if let Some(callback) = stopping.as_ref() {
                callback();
            }
            BINDING.with(|binding| {
                let released = binding.borrow_mut().take();
                drop(released);
            });
        });

        self.inner.build()
    }
}

#[cfg(test)]
mod tests {
    use std::sync::{Arc, Mutex};
    use std::time::{Duration, Instant};

    use super::*;

    /// This test binary exports no `node_host_thread_*` symbols, so the
    /// binding installed by [`Builder::build`] has nothing to call: the
    /// runtime must still be a plain, working tokio runtime.
    #[test]
    fn runs_tasks_when_the_host_hooks_are_absent() {
        let runtime = Builder::new_multi_thread()
            .worker_threads(2)
            .thread_name("sdk-absent-hooks")
            .build()
            .unwrap();
        assert_eq!(runtime.block_on(async { 6 * 7 }), 42);
        drop(runtime);
    }

    /// The callbacks a caller installs keep running, and run once per runtime
    /// thread even with nothing bound: start when the thread comes up, stop
    /// when it goes down.
    #[test]
    fn user_callbacks_still_run_without_a_host() {
        let calls: Arc<Mutex<Vec<&'static str>>> = Arc::new(Mutex::new(Vec::new()));
        let started = calls.clone();
        let stopping = calls.clone();

        let runtime = Builder::new_multi_thread()
            .worker_threads(1)
            .on_thread_start(move || started.lock().unwrap().push("start"))
            .on_thread_stop(move || stopping.lock().unwrap().push("stop"))
            .build()
            .unwrap();

        assert_eq!(runtime.block_on(async { 42 }), 42);
        drop(runtime);

        let deadline = Instant::now() + Duration::from_secs(10);
        loop {
            let calls = calls.lock().unwrap();
            let starts = calls.iter().filter(|&&c| c == "start").count();
            let stops = calls.iter().filter(|&&c| c == "stop").count();
            if starts > 0 && starts == stops {
                break;
            }
            assert!(
                Instant::now() < deadline,
                "runtime threads never stopped: {calls:?}"
            );
            drop(calls);
            std::thread::sleep(Duration::from_millis(20));
        }
    }

    /// A current-thread runtime binds the threads its blocking work runs on
    /// through the same callbacks.
    #[test]
    fn current_thread_runtime_binds_its_blocking_threads() {
        let calls: Arc<Mutex<Vec<&'static str>>> = Arc::new(Mutex::new(Vec::new()));
        let started = calls.clone();
        let stopping = calls.clone();

        let runtime = Builder::new_current_thread()
            .thread_name("sdk-current-thread")
            .on_thread_start(move || started.lock().unwrap().push("start"))
            .on_thread_stop(move || stopping.lock().unwrap().push("stop"))
            .build()
            .unwrap();

        let value =
            runtime.block_on(async { tokio::task::spawn_blocking(|| 21 * 2).await.unwrap() });
        assert_eq!(value, 42);
        drop(runtime);

        let deadline = Instant::now() + Duration::from_secs(10);
        loop {
            let calls = calls.lock().unwrap();
            if calls.iter().filter(|&&c| c == "start").count() > 0
                && calls.iter().filter(|&&c| c == "stop").count() > 0
            {
                break;
            }
            assert!(
                Instant::now() < deadline,
                "blocking thread callbacks never fired: {calls:?}"
            );
            drop(calls);
            std::thread::sleep(Duration::from_millis(20));
        }
    }
}