Skip to main content

node_app_sdk_rust/
thread.rs

1//! Threads an app starts, charged to the app (ADR-314).
2//!
3//! A built-in app runs inside the host process, so every thread it starts
4//! burns host CPU and allocates host memory that nothing attributes to it on
5//! its own: the host can only count such a thread as *unattributed*, landing
6//! its cost on "the node". The host therefore exports two hooks that
7//! register the calling thread with the app for the thread's whole life
8//! (ADR-314 §4):
9//!
10//! ```c
11//! int  node_host_thread_bind_v1(const void *host_data);   /* 0 = bound */
12//! void node_host_thread_unbind_v1(const void *host_data);
13//! ```
14//!
15//! [`spawn`] resolves both symbols once with `dlsym(RTLD_DEFAULT, …)` and
16//! caches them: a host that predates ADR-314 does not export them, and then
17//! the helpers still run your closure and bind nothing. The app does not
18//! have to know which host it was loaded into.
19//!
20//! Start every thread through [`spawn`] — for a tokio runtime, through the
21//! `tokio`-gated `runtime::Builder` — or its CPU and its jemalloc
22//! allocations stay outside the app's figures and count as the node's
23//! unattributed threads (ADR-314 §3).
24
25use std::ffi::c_void;
26use std::io;
27use std::sync::atomic::Ordering;
28use std::sync::OnceLock;
29use std::thread::JoinHandle;
30
31use crate::APP_CONTEXT;
32
33/// Signature of the host's `node_host_thread_bind_v1` (contract C1).
34///
35/// Returns `0` when the thread is now bound to the app.
36type BindHook = unsafe extern "C" fn(host_data: *const c_void) -> i32;
37
38/// Signature of the host's `node_host_thread_unbind_v1` (contract C1).
39type UnbindHook = unsafe extern "C" fn(host_data: *const c_void);
40
41/// The contract C1 hooks, resolved once for the lifetime of the process.
42struct HostThreadHooks {
43    bind: Option<BindHook>,
44    unbind: Option<UnbindHook>,
45}
46
47static HOST_THREAD_HOOKS: OnceLock<HostThreadHooks> = OnceLock::new();
48
49fn hooks() -> &'static HostThreadHooks {
50    HOST_THREAD_HOOKS.get_or_init(resolve_host_thread_hooks)
51}
52
53#[cfg(unix)]
54fn resolve_host_thread_hooks() -> HostThreadHooks {
55    HostThreadHooks {
56        bind: resolve_address(b"node_host_thread_bind_v1\0").map(|address| {
57            // SAFETY: the address is what `dlsym` found under the C1 name,
58            // and `BindHook` is that hook's declared signature.
59            unsafe { std::mem::transmute::<*mut c_void, BindHook>(address) }
60        }),
61        unbind: resolve_address(b"node_host_thread_unbind_v1\0").map(|address| {
62            // SAFETY: same, for the unbind half of contract C1.
63            unsafe { std::mem::transmute::<*mut c_void, UnbindHook>(address) }
64        }),
65    }
66}
67
68/// Look one hook up in the process's global symbol scope.
69///
70/// Returns `None` when the host does not export it (an older host), which is
71/// the normal case on a node that predates ADR-314.
72#[cfg(unix)]
73fn resolve_address(name: &'static [u8]) -> Option<*mut c_void> {
74    // SAFETY: `name` is a NUL-terminated byte string, which is exactly what
75    // `dlsym` asks for, and a null answer is only an answer.
76    unsafe {
77        let symbol = libc::dlsym(libc::RTLD_DEFAULT, name.as_ptr().cast::<std::ffi::c_char>());
78        if symbol.is_null() {
79            None
80        } else {
81            Some(symbol)
82        }
83    }
84}
85
86/// No hook lookup off unix: the host exports contract C1 on the unix hosts
87/// that ship this SDK, so elsewhere every helper binds nothing and just runs.
88#[cfg(not(unix))]
89fn resolve_host_thread_hooks() -> HostThreadHooks {
90    HostThreadHooks {
91        bind: None,
92        unbind: None,
93    }
94}
95
96/// The `host_data` pointer the host passed in `init`, read the same way
97/// every other SDK helper reads it: `None` before init is a null pointer,
98/// and the host answers a bind with `2 = unknown host_data`.
99fn current_host_data() -> *const c_void {
100    let context = APP_CONTEXT.load(Ordering::Acquire);
101    if context.is_null() {
102        return std::ptr::null();
103    }
104    // SAFETY: `APP_CONTEXT` is null or a live `NodeAppContext` for as long as
105    // the host keeps this app instance alive — the invariant every SDK helper
106    // that calls into the host already relies on.
107    unsafe { (*context).host_data }
108}
109
110/// One thread's registration with the host, released when it drops.
111///
112/// `bound` is false when the host did not take the binding: no hooks
113/// exported at all (an older host, or a non-unix target), only one half of
114/// contract C1, or the hook answered `1 = not supported`,
115/// `2 = unknown host_data` or `3 = already bound`. Releasing a binding that
116/// was never made is a no-op, so a thread that is offered a binding twice is
117/// never unbound twice.
118pub(crate) struct ThreadBinding {
119    host_data: *const c_void,
120    bound: bool,
121}
122
123impl ThreadBinding {
124    /// Bind the calling thread to this app.
125    pub(crate) fn bind() -> Self {
126        let host_data = current_host_data();
127        let resolved = hooks();
128        // Bind only when the host offers the whole contract: a build that
129        // exports one half alone would register the tid and never see it
130        // released, and an unbound tid is exactly what keeps a reused tid
131        // from being charged to the wrong app (ADR-314 §3).
132        let bound = match (resolved.bind, resolved.unbind) {
133            (Some(bind), Some(_)) => unsafe { bind(host_data) == 0 },
134            _ => false,
135        };
136        Self { host_data, bound }
137    }
138
139    /// Release the binding, if this thread is the one that made it.
140    fn release(&mut self) {
141        if self.bound {
142            self.bound = false;
143            if let Some(unbind) = hooks().unbind {
144                // SAFETY: `host_data` came from `current_host_data` at bind
145                // time and the host keeps it alive for the whole app
146                // instance; `unbind` is idempotent (contract C1).
147                unsafe { unbind(self.host_data) };
148            }
149        }
150    }
151}
152
153impl Drop for ThreadBinding {
154    fn drop(&mut self) {
155        self.release();
156    }
157}
158
159/// Spawn an OS thread that is bound to this app (ADR-314).
160///
161/// Everything [`std::thread::spawn`] does, plus the binding: the host
162/// charges the new thread's CPU and the memory it allocates to this app from
163/// the moment it starts until it exits. The binding is released when the
164/// closure returns — including when it panics, and including when the OS
165/// refuses to start the thread (then there is nothing to release).
166///
167/// A host that predates ADR-314 exports no hooks: the closure still runs and
168/// nothing else happens.
169///
170/// # Errors
171///
172/// The OS could not create a thread; the closure never runs.
173///
174/// # Examples
175///
176/// ```
177/// let handle = node_app_sdk_rust::thread::spawn(|| 6 * 7).unwrap();
178/// assert_eq!(handle.join().unwrap(), 42);
179/// ```
180pub fn spawn<F, T>(f: F) -> io::Result<JoinHandle<T>>
181where
182    F: FnOnce() -> T + Send + 'static,
183    T: Send + 'static,
184{
185    std::thread::Builder::new().spawn(|| {
186        let _binding = ThreadBinding::bind();
187        f()
188    })
189}
190
191#[cfg(test)]
192mod tests {
193    use super::*;
194
195    /// The absence half of ADR-314's contract C1 tests: this test binary
196    /// exports no `node_host_thread_*` symbol, so a host-less build of the
197    /// helpers must find nothing to bind with.
198    #[cfg(unix)]
199    #[test]
200    fn host_thread_hooks_are_absent_here() {
201        // SAFETY: `dlsym` gets NUL-terminated byte strings and its null
202        // answer is the answer under test.
203        unsafe {
204            assert!(libc::dlsym(
205                libc::RTLD_DEFAULT,
206                b"node_host_thread_bind_v1\0"
207                    .as_ptr()
208                    .cast::<std::ffi::c_char>()
209            )
210            .is_null());
211            assert!(libc::dlsym(
212                libc::RTLD_DEFAULT,
213                b"node_host_thread_unbind_v1\0"
214                    .as_ptr()
215                    .cast::<std::ffi::c_char>()
216            )
217            .is_null());
218        }
219        assert!(hooks().bind.is_none());
220        assert!(hooks().unbind.is_none());
221    }
222
223    /// With the hooks absent, `spawn` runs the closure and does nothing else.
224    #[test]
225    fn spawn_runs_the_closure_without_a_host() {
226        let handle = spawn(|| 40 + 2).unwrap();
227        assert_eq!(handle.join().unwrap(), 42);
228    }
229
230    /// Nothing is bound, so nothing is released on the way out — not even
231    /// with no host context stored at all.
232    #[test]
233    fn binding_without_hooks_is_a_silent_no_op() {
234        let binding = ThreadBinding::bind();
235        assert!(!binding.bound);
236        drop(binding);
237        assert!(hooks().bind.is_none());
238    }
239}