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`] and [`Builder`] resolve both symbols once with
16//! `dlsym(RTLD_DEFAULT, …)` and cache them: a host that predates ADR-314 does
17//! not export them, and then the helpers still run your closure and bind
18//! nothing. The app does not have to know which host it was loaded into.
19//!
20//! Start every thread through [`spawn`] or [`Builder`] — for a tokio runtime,
21//! through the `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/// Thread factory mirroring [`std::thread::Builder`], with app binding (ADR-314).
160///
161/// Same knobs as the std builder — [`Builder::name`] and [`Builder::stack_size`]
162/// — plus the host bind/unbind around the closure. Use this when an app needs
163/// a named long-lived thread or a smaller stack (for example 512 KiB on a Pi
164/// Zero 2 W); use [`spawn`] when the defaults are enough.
165///
166/// # Examples
167///
168/// ```
169/// use node_app_sdk_rust::thread::Builder;
170///
171/// let handle = Builder::new()
172///     .name("worker".into())
173///     .stack_size(512 * 1024)
174///     .spawn(|| 6 * 7)
175///     .unwrap();
176/// assert_eq!(handle.join().unwrap(), 42);
177/// ```
178pub struct Builder {
179    inner: std::thread::Builder,
180}
181
182impl Builder {
183    /// Same defaults as [`std::thread::Builder::new`].
184    pub fn new() -> Self {
185        Self {
186            inner: std::thread::Builder::new(),
187        }
188    }
189
190    /// Sets the name of the thread for debugging and panic messages.
191    pub fn name(self, name: String) -> Self {
192        Self {
193            inner: self.inner.name(name),
194        }
195    }
196
197    /// Sets the size of the stack (in bytes) for the new thread.
198    pub fn stack_size(self, size: usize) -> Self {
199        Self {
200            inner: self.inner.stack_size(size),
201        }
202    }
203
204    /// Spawns an OS thread that is bound to this app (ADR-314).
205    ///
206    /// Everything [`std::thread::Builder::spawn`] does, plus the binding: the
207    /// host charges the new thread's CPU and the memory it allocates to this
208    /// app from the moment it starts until it exits. The binding is released
209    /// when the closure returns — including when it panics, and including when
210    /// the OS refuses to start the thread (then there is nothing to release).
211    ///
212    /// A host that predates ADR-314 exports no hooks: the closure still runs
213    /// and nothing else happens.
214    ///
215    /// # Errors
216    ///
217    /// The OS could not create a thread; the closure never runs.
218    pub fn spawn<F, T>(self, f: F) -> io::Result<JoinHandle<T>>
219    where
220        F: FnOnce() -> T + Send + 'static,
221        T: Send + 'static,
222    {
223        self.inner.spawn(|| {
224            let _binding = ThreadBinding::bind();
225            f()
226        })
227    }
228}
229
230impl Default for Builder {
231    fn default() -> Self {
232        Self::new()
233    }
234}
235
236/// Spawn an OS thread that is bound to this app (ADR-314).
237///
238/// Thin wrapper around [`Builder::new().spawn`](Builder::spawn): same binding
239/// semantics, default name and stack size. Prefer [`Builder`] when you need a
240/// name or a custom stack.
241///
242/// # Errors
243///
244/// The OS could not create a thread; the closure never runs.
245///
246/// # Examples
247///
248/// ```
249/// let handle = node_app_sdk_rust::thread::spawn(|| 6 * 7).unwrap();
250/// assert_eq!(handle.join().unwrap(), 42);
251/// ```
252pub fn spawn<F, T>(f: F) -> io::Result<JoinHandle<T>>
253where
254    F: FnOnce() -> T + Send + 'static,
255    T: Send + 'static,
256{
257    Builder::new().spawn(f)
258}
259
260#[cfg(test)]
261mod tests {
262    use super::*;
263    use std::sync::{Arc, Mutex};
264
265    /// 512 KiB — the stack size apps use for long-lived threads on Pi Zero 2 W.
266    const SMALL_STACK: usize = 512 * 1024;
267
268    /// The absence half of ADR-314's contract C1 tests: this test binary
269    /// exports no `node_host_thread_*` symbol, so a host-less build of the
270    /// helpers must find nothing to bind with.
271    #[cfg(unix)]
272    #[test]
273    fn host_thread_hooks_are_absent_here() {
274        // SAFETY: `dlsym` gets NUL-terminated byte strings and its null
275        // answer is the answer under test.
276        unsafe {
277            assert!(libc::dlsym(
278                libc::RTLD_DEFAULT,
279                b"node_host_thread_bind_v1\0"
280                    .as_ptr()
281                    .cast::<std::ffi::c_char>()
282            )
283            .is_null());
284            assert!(libc::dlsym(
285                libc::RTLD_DEFAULT,
286                b"node_host_thread_unbind_v1\0"
287                    .as_ptr()
288                    .cast::<std::ffi::c_char>()
289            )
290            .is_null());
291        }
292        assert!(hooks().bind.is_none());
293        assert!(hooks().unbind.is_none());
294    }
295
296    /// With the hooks absent, `spawn` runs the closure and does nothing else.
297    #[test]
298    fn spawn_runs_the_closure_without_a_host() {
299        let handle = spawn(|| 40 + 2).unwrap();
300        assert_eq!(handle.join().unwrap(), 42);
301    }
302
303    /// Nothing is bound, so nothing is released on the way out — not even
304    /// with no host context stored at all.
305    #[test]
306    fn binding_without_hooks_is_a_silent_no_op() {
307        let binding = ThreadBinding::bind();
308        assert!(!binding.bound);
309        drop(binding);
310        assert!(hooks().bind.is_none());
311    }
312
313    /// [`Builder::name`] reaches the OS thread: the closure sees it on
314    /// [`std::thread::current`].
315    #[test]
316    fn builder_applies_thread_name() {
317        let handle = Builder::new()
318            .name("sdk-thread-builder".into())
319            .spawn(|| {
320                std::thread::current()
321                    .name()
322                    .map(str::to_owned)
323                    .expect("thread name set by Builder")
324            })
325            .unwrap();
326        assert_eq!(handle.thread().name(), Some("sdk-thread-builder"));
327        assert_eq!(handle.join().unwrap(), "sdk-thread-builder");
328    }
329
330    /// [`Builder::stack_size`] is forwarded to the OS; a 512 KiB stack still
331    /// runs the closure (the size apps keep for long-lived Pi Zero 2 W threads).
332    #[test]
333    fn builder_applies_stack_size() {
334        let handle = Builder::new()
335            .stack_size(SMALL_STACK)
336            .spawn(|| 21 * 2)
337            .unwrap();
338        assert_eq!(handle.join().unwrap(), 42);
339    }
340
341    /// Name and stack size can be set together; both still apply.
342    #[test]
343    fn builder_applies_name_and_stack_size_together() {
344        let handle = Builder::new()
345            .name("sdk-named-stack".into())
346            .stack_size(SMALL_STACK)
347            .spawn(|| {
348                std::thread::current()
349                    .name()
350                    .map(str::to_owned)
351                    .expect("thread name set by Builder")
352            })
353            .unwrap();
354        assert_eq!(handle.join().unwrap(), "sdk-named-stack");
355    }
356
357    /// With hooks absent, a panicking closure still exits cleanly: Drop of
358    /// the (unbound) guard is a no-op and `join` reports the panic.
359    #[test]
360    fn spawn_reports_panic_without_a_host() {
361        let handle = spawn(|| panic!("expected test panic")).unwrap();
362        assert!(handle.join().unwrap_err().downcast_ref::<&str>().is_some());
363    }
364
365    /// Same panic path through [`Builder`]: unbind (a no-op here) still runs
366    /// via Drop before the panic is delivered to `join`.
367    #[test]
368    fn builder_unbinds_on_panic_without_a_host() {
369        let saw_bind_drop = Arc::new(Mutex::new(false));
370        let flag = Arc::clone(&saw_bind_drop);
371        let handle = Builder::new()
372            .name("sdk-panic".into())
373            .stack_size(SMALL_STACK)
374            .spawn(move || {
375                // Observe that we entered the thread; Drop of ThreadBinding
376                // runs on the way out of the panic unwind.
377                *flag.lock().unwrap() = true;
378                panic!("expected builder panic");
379            })
380            .unwrap();
381        assert!(handle.join().is_err());
382        assert!(*saw_bind_drop.lock().unwrap());
383    }
384}