node_app_sdk_rust/lib.rs
1//! # Node-App SDK for Rust
2//!
3//! Build native [Node-App] plugins as shared libraries (`cdylib`) with a
4//! safe, ergonomic Rust API. The SDK targets the **Node Host API v1**
5//! (the canonical C header is `core/host-abi-v1/include/node-host-api-v1.h`
6//! in the host repository).
7//!
8//! [Node-App]: https://github.com/econ-v1/node-app-distribution
9//!
10//! ## What this crate provides
11//!
12//! - The [`NodeApp`] trait — implement it on your plugin type to get HTTP,
13//! event, and capability handling.
14//! - The [`declare_node_app!`] macro — generates all FFI boilerplate
15//! (vtable, panic guards, JSON serialization) from your trait impl.
16//! - Helpers for talking to the host: [`log`], [`invoke_capability`],
17//! [`publish_event`], [`get_config`], [`get_storage`], [`set_storage`].
18//! - Distributed-trace propagation across capability invocations
19//! (thread-local span context — see [`CurrentTrace`]).
20//! - Threads attributed to your app: [`thread::spawn`], and with the
21//! `tokio` feature a `runtime::Builder`, so the CPU your threads burn and
22//! the memory they allocate are reported as yours instead of the node's
23//! (ADR-314).
24//! - Hard limits matching the host: [`MAX_CAPABILITY_RESPONSE_SIZE`]
25//! (16 MiB), [`MAX_EVENT_NAME_LEN`] (256 B), [`MAX_EVENT_DATA_LEN`]
26//! (64 KiB).
27//!
28//! ## Stability
29//!
30//! This crate is published as **`1.0.1-experimental`**. The trait surface
31//! and the underlying C ABI are FROZEN for the v1 series, but breaking
32//! changes between `1.0.x-experimental` releases are possible until at
33//! least two first-party packages have proven the surface in production.
34//! Pin to an exact version in `Cargo.toml`.
35//!
36//! ## Quick start
37//!
38//! ```toml
39//! # Cargo.toml
40//! [lib]
41//! crate-type = ["cdylib"]
42//!
43//! [dependencies]
44//! node-app-sdk-rust = "1.0.1-experimental"
45//! serde_json = "1.0"
46//! ```
47//!
48//! ```rust,ignore
49//! use node_app_sdk_rust::*;
50//!
51//! #[derive(Default)]
52//! pub struct MyApp;
53//!
54//! impl NodeApp for MyApp {
55//! fn metadata() -> NodeAppInfo {
56//! NodeAppInfo {
57//! name: "my-app".into(),
58//! version: "0.1.0".into(),
59//! author: "Me".into(),
60//! description: "Hello-world Node-App".into(),
61//! capabilities: vec!["http_handler".into()],
62//! }
63//! }
64//!
65//! fn handle_request(&self, _req: AppRequest) -> Result<AppResponse, NodeAppError> {
66//! Ok(AppResponse {
67//! status: 200,
68//! headers: Default::default(),
69//! body: serde_json::json!({ "hello": "world" }),
70//! })
71//! }
72//! }
73//!
74//! declare_node_app!(MyApp);
75//! ```
76//!
77//! Build with `cargo build --release`; the resulting shared library plus a
78//! `manifest.json` is installed into the host's app directory.
79//!
80//! ## Calling host capabilities
81//!
82//! Use [`invoke_capability`] to call any capability registered with the
83//! host's capability router (e.g. `core.storage.get`,
84//! `core.lightning.payment.send`):
85//!
86//! ```rust,ignore
87//! use node_app_sdk_rust::{invoke_capability, CapabilityRequest};
88//!
89//! let response = invoke_capability(&CapabilityRequest {
90//! id: "req-1".into(),
91//! capability: "core.storage.get".into(),
92//! payload: serde_json::json!({ "key": "user_pref" }),
93//! caller_node_id: None,
94//! trace_id: None,
95//! span_id: None,
96//! parent_span_id: None,
97//! trace_depth: None,
98//! })?;
99//! # Ok::<(), node_app_sdk_rust::NodeAppError>(())
100//! ```
101//!
102//! Trace context (`trace_id`, `span_id`, `trace_depth`) is propagated
103//! automatically when invoking from inside `handle_capability` — you do
104//! not need to thread it manually.
105//!
106//! ## Publishing events
107//!
108//! ```rust,ignore
109//! use node_app_sdk_rust::publish_event;
110//!
111//! publish_event(
112//! "my-app.something_happened",
113//! &serde_json::json!({ "user_id": 42 }),
114//! )?;
115//! # Ok::<(), node_app_sdk_rust::NodeAppError>(())
116//! ```
117//!
118//! Event names **must** be namespaced with the app name (`my-app.*`); the
119//! host rejects un-namespaced events.
120
121#![warn(missing_docs)]
122#![warn(rustdoc::broken_intra_doc_links)]
123
124pub use node_app_api::types::{
125 AppEvent, AppRequest, AppResponse, Capabilities, CapabilityExample, CapabilityRequest,
126 CapabilityResponse, NodeAppInfo, ProvidedCapability,
127};
128pub use node_app_api::context::NodeAppContext;
129pub use node_app_api::ffi::{FfiResult, NodeAppMetadata, NodeAppVTable};
130pub use node_app_api::API_VERSION;
131
132use std::cell::RefCell;
133use std::ffi::CString;
134use std::sync::atomic::{AtomicPtr, Ordering};
135use std::sync::{Condvar, Mutex, MutexGuard, PoisonError};
136use std::time::Duration;
137
138/// Maximum response size for capability handlers (16 MiB).
139///
140/// The host enforces this limit on every capability response. Apps that
141/// produce a larger response will see [`FfiResult::error`] returned with
142/// error code `-6`. Use streaming or pagination for larger payloads.
143pub const MAX_CAPABILITY_RESPONSE_SIZE: usize = 16 * 1024 * 1024;
144
145/// Trace fields for the currently-executing capability span (per-thread).
146///
147/// Set at the start of `handle_capability` by the [`declare_node_app!`]
148/// macro and cleared on return. Allows [`invoke_capability`] to propagate
149/// distributed trace context automatically without the caller having to
150/// thread `trace_id` / `span_id` through every call site.
151#[doc(hidden)]
152#[derive(Clone)]
153pub struct CurrentTrace {
154 /// Trace ID inherited from the inbound capability request.
155 pub trace_id: String,
156 /// Span ID of the current execution — becomes `parent_span_id` for
157 /// sub-invocations made from this thread.
158 pub span_id: String,
159 /// Depth of the current span in the trace tree (root = 0).
160 pub depth: u8,
161}
162
163thread_local! {
164 /// Current trace context for the executing capability (set by
165 /// [`declare_node_app!`]).
166 #[doc(hidden)]
167 pub static CURRENT_TRACE: RefCell<Option<CurrentTrace>> = const { RefCell::new(None) };
168 #[doc(hidden)]
169 pub static CURRENT_INVOCATION_CONTEXT: RefCell<Option<String>> = const { RefCell::new(None) };
170}
171
172#[doc(hidden)]
173pub struct CurrentInvocationContextGuard(Option<String>);
174
175impl CurrentInvocationContextGuard {
176 #[doc(hidden)]
177 pub fn enter(invocation_context_id: Option<String>) -> Self {
178 let previous = CURRENT_INVOCATION_CONTEXT.with(|current| {
179 std::mem::replace(&mut *current.borrow_mut(), invocation_context_id)
180 });
181 Self(previous)
182 }
183}
184
185impl Drop for CurrentInvocationContextGuard {
186 fn drop(&mut self) {
187 let previous = self.0.take();
188 CURRENT_INVOCATION_CONTEXT.with(|current| {
189 *current.borrow_mut() = previous;
190 });
191 }
192}
193
194/// Global storage for the host context pointer.
195///
196/// Uses `AtomicPtr` instead of `OnceLock` so that the pointer can be
197/// **updated on every init call**. On macOS, `dlclose` does not actually
198/// unload user libraries (`man dlclose`: "Mac OS X does not support
199/// dynamic unloading"), so the same library instance is reused across
200/// hot-reloads. With a `OnceLock` the first-load context pointer would
201/// be retained permanently; after the first-load `HostData` is dropped
202/// that pointer becomes dangling, causing a SIGSEGV on the next reload
203/// when any SDK function (e.g. `log`) tries to read it.
204///
205/// `AtomicPtr` allows `__store_context` to atomically replace the pointer
206/// on each init, ensuring it always points to the current live `HostData`.
207///
208/// Safety invariant: the pointer is set to a valid `NodeAppContext` during
209/// `__node_app_init` and is only read while the app is alive. The host
210/// (NativeLoader) keeps `HostData` + `NodeAppContext` alive for the entire
211/// lifetime of the loaded app instance.
212static APP_CONTEXT: AtomicPtr<NodeAppContext> = AtomicPtr::new(std::ptr::null_mut());
213
214/// Error code a call gets when it arrives after the app's shutdown started.
215///
216/// From the moment the host calls the app's shutdown entry, the
217/// [`declare_node_app!`] wrappers refuse new `handle_request`,
218/// `handle_event` and `handle_capability` calls with this code instead of
219/// running them. The next `init` accepts calls again. See ADR-083.
220pub const ERROR_SHUTTING_DOWN: i32 = -11;
221
222/// How long the shutdown entry waits for in-flight calls before it logs a
223/// warning that names how many are still running.
224///
225/// The entry keeps waiting after this. It must not return while a call is
226/// still running inside the library: the host releases the library owner
227/// when the shutdown entry returns, and it calls the app without holding
228/// that owner. The host's own shutdown budget bounds the whole wait. See
229/// ADR-083.
230pub const SHUTDOWN_DRAIN_WARN_AFTER: Duration = Duration::from_secs(2);
231
232/// Admission gate for calls into the app (generated by [`declare_node_app!`]).
233///
234/// Counts the calls that run inside the app and refuses new ones after
235/// [`CallGate::close`], so the shutdown entry can tell the app to stop at
236/// once and take the write lock only after the in-flight calls return.
237#[doc(hidden)]
238pub struct CallGate {
239 state: Mutex<CallGateState>,
240 drained: Condvar,
241}
242
243struct CallGateState {
244 closed: bool,
245 in_flight: usize,
246}
247
248impl CallGate {
249 #[doc(hidden)]
250 pub const fn new() -> Self {
251 Self {
252 state: Mutex::new(CallGateState {
253 closed: false,
254 in_flight: 0,
255 }),
256 drained: Condvar::new(),
257 }
258 }
259
260 fn lock(&self) -> MutexGuard<'_, CallGateState> {
261 // No code panics while it holds this mutex, so poison carries no
262 // information; recover the state rather than wedge every call.
263 self.state.lock().unwrap_or_else(PoisonError::into_inner)
264 }
265
266 /// Admit one call, or `None` once the gate is closed. The call counts
267 /// as in flight until the returned permit drops.
268 #[doc(hidden)]
269 pub fn enter(&self) -> Option<CallPermit<'_>> {
270 let mut state = self.lock();
271 if state.closed {
272 return None;
273 }
274 state.in_flight += 1;
275 Some(CallPermit(self))
276 }
277
278 /// Accept calls again (the app is being initialized).
279 #[doc(hidden)]
280 pub fn open(&self) {
281 self.lock().closed = false;
282 }
283
284 /// Refuse every call from now on.
285 #[doc(hidden)]
286 pub fn close(&self) {
287 self.lock().closed = true;
288 }
289
290 /// Wait until no call is in flight, or until `timeout` passes when it is
291 /// `Some`. Returns the number of calls still in flight.
292 #[doc(hidden)]
293 pub fn wait_drained(&self, timeout: Option<Duration>) -> usize {
294 let state = self.lock();
295 let state = match timeout {
296 Some(timeout) => {
297 self.drained
298 .wait_timeout_while(state, timeout, |state| state.in_flight > 0)
299 .unwrap_or_else(PoisonError::into_inner)
300 .0
301 }
302 None => self
303 .drained
304 .wait_while(state, |state| state.in_flight > 0)
305 .unwrap_or_else(PoisonError::into_inner),
306 };
307 state.in_flight
308 }
309}
310
311impl Default for CallGate {
312 fn default() -> Self {
313 Self::new()
314 }
315}
316
317/// One admitted call; see [`CallGate::enter`].
318#[doc(hidden)]
319pub struct CallPermit<'a>(&'a CallGate);
320
321impl Drop for CallPermit<'_> {
322 fn drop(&mut self) {
323 let mut state = self.0.lock();
324 state.in_flight -= 1;
325 if state.in_flight == 0 {
326 self.0.drained.notify_all();
327 }
328 }
329}
330
331// ── Public api-store LLM SDK (feature 472) ──────────────────────────────────
332//
333// Type-safe surface for the host's `/api/v2/public/api_store/llm/{call,stream}`
334// endpoints. Lives in its own submodule so plugins that don't talk to the
335// public LLM endpoint never see these symbols in their import surface.
336pub mod llm;
337
338/// In-process pipes to another native app (`core.pipe.*`, ADR-300).
339#[cfg(unix)]
340pub mod pipe;
341
342/// Threads an app starts, bound to the app for CPU and memory attribution
343/// (ADR-314, contract C1).
344pub mod thread;
345
346/// A tokio runtime that binds every one of its threads to the app
347/// (ADR-314). Enabled by the `tokio` cargo feature.
348#[cfg(feature = "tokio")]
349pub mod runtime;
350
351/// Log levels accepted by the [`log`] function.
352///
353/// Use these constants instead of magic numbers when calling
354/// [`log`] directly. The convenience macros ([`log_info!`], etc.)
355/// take care of this for you.
356pub mod log_level {
357 /// Most verbose level — use for fine-grained tracing.
358 pub const TRACE: u32 = 0;
359 /// Debug-level diagnostics, typically not shown in production.
360 pub const DEBUG: u32 = 1;
361 /// Informational messages indicating normal operation.
362 pub const INFO: u32 = 2;
363 /// Warnings — recoverable issues or unusual conditions.
364 pub const WARN: u32 = 3;
365 /// Errors — operations that failed and require attention.
366 pub const ERROR: u32 = 4;
367}
368
369/// Log a message to the host using the stored context.
370///
371/// Logs are written to the host's per-app log file
372/// (`{log_dir}/{app_name}.log`) and forwarded to the host's tracing
373/// subscriber, so they appear in the daemon's main log output too.
374///
375/// This function is a no-op if the context was not provided during init
376/// or if the message contains invalid UTF-8.
377///
378/// # Arguments
379/// * `level` - Log level (0=trace, 1=debug, 2=info, 3=warn, 4=error). Use the [`log_level`] constants.
380/// * `message` - The log message (must not contain interior NUL bytes).
381///
382/// # Example
383/// ```ignore
384/// use node_app_sdk_rust::{log, log_level};
385///
386/// log(log_level::INFO, "App initialized successfully");
387/// log(log_level::ERROR, "Something went wrong!");
388/// ```
389///
390/// Most callers should use the convenience macros ([`log_info!`],
391/// [`log_error!`], etc.) which accept `format!`-style arguments.
392pub fn log(level: u32, message: &str) {
393 let ctx_ptr = APP_CONTEXT.load(Ordering::Acquire);
394 if ctx_ptr.is_null() {
395 return;
396 }
397
398 let c_message = match CString::new(message) {
399 Ok(s) => s,
400 Err(_) => return, // Invalid message (contains null byte)
401 };
402
403 // Safety: ctx_ptr is valid for the app's lifetime, and host_log is a valid function pointer
404 unsafe {
405 let ctx = &*ctx_ptr;
406 (ctx.host_log)(ctx.host_data, level, c_message.as_ptr());
407 }
408}
409
410/// Invoke a capability on the host via the capability router.
411///
412/// This is the primary mechanism for app-to-app communication. The host
413/// resolves the capability name to the providing app, dispatches the
414/// request, and returns the response. The provider may itself be a
415/// different app, the host kernel, or a remote node (transparent to the
416/// caller).
417///
418/// Trace context is propagated automatically: if this call happens
419/// inside `handle_capability` and the inbound request carried a
420/// `trace_id`, the same trace ID is injected on outbound calls. Callers
421/// may override this by setting `trace_id` explicitly on the request.
422///
423/// # Errors
424///
425/// Returns [`NodeAppError::CapabilityError`] when:
426/// - The host context is not available (called before init).
427/// - The host's invoke callback is not wired up.
428/// - The capability is not registered, the provider rejects the call,
429/// or the response cannot be deserialized.
430pub fn invoke_capability(request: &CapabilityRequest) -> Result<CapabilityResponse, NodeAppError> {
431 let ctx_ptr = APP_CONTEXT.load(Ordering::Acquire);
432 if ctx_ptr.is_null() {
433 return Err(NodeAppError::CapabilityError(
434 "Host context not available".into(),
435 ));
436 }
437
438 // Propagate distributed trace context if a parent span is active on this thread.
439 // Only inject when the caller hasn't already set trace fields.
440 let active_invocation_context =
441 CURRENT_INVOCATION_CONTEXT.with(|current| current.borrow().clone());
442 let active_trace = if request.trace_id.is_none() {
443 CURRENT_TRACE.with(|current| current.borrow().clone())
444 } else {
445 None
446 };
447 let effective_request: std::borrow::Cow<CapabilityRequest> =
448 if active_trace.is_some() || active_invocation_context.is_some() {
449 let mut injected = request.clone();
450 if let Some(trace) = active_trace {
451 injected.trace_id = Some(trace.trace_id);
452 injected.span_id = Some(trace.span_id);
453 injected.parent_span_id = None;
454 injected.trace_depth = Some(trace.depth);
455 }
456 if let Some(context_id) = active_invocation_context {
457 injected.invocation_context_id = Some(context_id);
458 }
459 std::borrow::Cow::Owned(injected)
460 } else {
461 std::borrow::Cow::Borrowed(request)
462 };
463
464 // Serialize the request to JSON
465 let request_json = serde_json::to_vec(effective_request.as_ref())?;
466
467 // Safety: ctx_ptr is valid for the app's lifetime
468 unsafe {
469 let ctx = &*ctx_ptr;
470
471 // Check if the callback is available
472 if ctx.host_invoke_capability as usize == 0 {
473 return Err(NodeAppError::CapabilityError(
474 "host_invoke_capability callback not available".into(),
475 ));
476 }
477
478 let result = (ctx.host_invoke_capability)(
479 ctx.host_data,
480 request_json.as_ptr(),
481 request_json.len(),
482 );
483
484 if result.success && !result.data.is_null() && result.data_len > 0 {
485 let response_slice = std::slice::from_raw_parts(result.data, result.data_len);
486 let response: CapabilityResponse = serde_json::from_slice(response_slice)
487 .map_err(|e| NodeAppError::CapabilityError(format!("Response deserialization error: {}", e)))?;
488 // Free the host-allocated data
489 // Note: The host is responsible for freeing this memory via its own allocator
490 Ok(response)
491 } else if !result.success {
492 Err(NodeAppError::CapabilityError(format!(
493 "Host capability invocation failed with error code {}",
494 result.error_code
495 )))
496 } else {
497 Err(NodeAppError::CapabilityError(
498 "Empty response from host".into(),
499 ))
500 }
501 }
502}
503
504/// Maximum event name length in bytes (256).
505///
506/// Names that exceed this limit are rejected by [`publish_event`] with
507/// [`NodeAppError::EventFailed`]. The host enforces the same limit on
508/// the receiving side.
509pub const MAX_EVENT_NAME_LEN: usize = 256;
510
511/// Maximum event data length in bytes (64 KiB).
512///
513/// Payloads that exceed this limit are rejected by [`publish_event`]
514/// with [`NodeAppError::EventFailed`]. For larger artifacts, store them
515/// (e.g. via `core.storage.insert`) and emit an event referencing the
516/// storage key instead.
517pub const MAX_EVENT_DATA_LEN: usize = 64 * 1024;
518
519/// Publish a domain event to the host event bus.
520///
521/// The event is queued asynchronously (fire-and-forget). The event
522/// name **must** be namespaced with the app name prefix
523/// (e.g. `lightning.payment_received`, `my-app.user_created`); the host
524/// rejects events whose name does not start with `{app_name}.`.
525///
526/// # Errors
527///
528/// Returns [`NodeAppError::EventFailed`] if the host context is not
529/// available, the event name or data exceeds size limits
530/// ([`MAX_EVENT_NAME_LEN`] / [`MAX_EVENT_DATA_LEN`]), or the host
531/// rejects the event.
532pub fn publish_event(name: &str, data: &serde_json::Value) -> Result<(), NodeAppError> {
533 let ctx_ptr = APP_CONTEXT.load(Ordering::Acquire);
534 if ctx_ptr.is_null() {
535 return Err(NodeAppError::EventFailed(
536 "Host context not available".into(),
537 ));
538 }
539
540 let name_bytes = name.as_bytes();
541 if name_bytes.len() > MAX_EVENT_NAME_LEN {
542 return Err(NodeAppError::EventFailed(format!(
543 "Event name exceeds {} byte limit (got {})",
544 MAX_EVENT_NAME_LEN,
545 name_bytes.len()
546 )));
547 }
548
549 let data_json = serde_json::to_vec(data)?;
550 if data_json.len() > MAX_EVENT_DATA_LEN {
551 return Err(NodeAppError::EventFailed(format!(
552 "Event data exceeds {} byte limit (got {})",
553 MAX_EVENT_DATA_LEN,
554 data_json.len()
555 )));
556 }
557
558 unsafe {
559 let ctx = &*ctx_ptr;
560
561 if ctx.host_publish_event as usize == 0 {
562 return Err(NodeAppError::EventFailed(
563 "host_publish_event callback not available".into(),
564 ));
565 }
566
567 let result = (ctx.host_publish_event)(
568 ctx.host_data,
569 name_bytes.as_ptr(),
570 name_bytes.len(),
571 data_json.as_ptr(),
572 data_json.len(),
573 );
574
575 if result == 0 {
576 Ok(())
577 } else {
578 Err(NodeAppError::EventFailed(format!(
579 "host_publish_event returned error code {}",
580 result
581 )))
582 }
583 }
584}
585
586/// Log a TRACE-level message using `format!`-style arguments.
587///
588/// No-op when the host context has not been wired up yet. See [`log`]
589/// for details about delivery semantics.
590#[macro_export]
591macro_rules! log_trace {
592 ($($arg:tt)*) => {
593 $crate::log($crate::log_level::TRACE, &format!($($arg)*))
594 };
595}
596
597/// Log a DEBUG-level message using `format!`-style arguments.
598#[macro_export]
599macro_rules! log_debug {
600 ($($arg:tt)*) => {
601 $crate::log($crate::log_level::DEBUG, &format!($($arg)*))
602 };
603}
604
605/// Log an INFO-level message using `format!`-style arguments.
606#[macro_export]
607macro_rules! log_info {
608 ($($arg:tt)*) => {
609 $crate::log($crate::log_level::INFO, &format!($($arg)*))
610 };
611}
612
613/// Log a WARN-level message using `format!`-style arguments.
614#[macro_export]
615macro_rules! log_warn {
616 ($($arg:tt)*) => {
617 $crate::log($crate::log_level::WARN, &format!($($arg)*))
618 };
619}
620
621/// Log an ERROR-level message using `format!`-style arguments.
622#[macro_export]
623macro_rules! log_error {
624 ($($arg:tt)*) => {
625 $crate::log($crate::log_level::ERROR, &format!($($arg)*))
626 };
627}
628
629/// Store the context pointer for use by host helper functions.
630///
631/// Called automatically by [`declare_node_app!`] during init. App code
632/// must not call this directly.
633///
634/// Uses `AtomicPtr::store` so the pointer is replaced on every init —
635/// required on macOS where `dlclose` never unloads user libraries and the
636/// same app instance is reused across hot-reloads.
637#[doc(hidden)]
638pub fn __store_context(ctx: *const NodeAppContext) {
639 APP_CONTEXT.store(ctx as *mut NodeAppContext, Ordering::Release);
640}
641
642/// Get a configuration value from the host by key.
643///
644/// Common keys include `data_dir`, `host_port`, `app_name`, and
645/// `app_id`. The full set of available keys is determined by the host
646/// at app-init time.
647///
648/// Returns `None` if the key is not registered or the context is not
649/// available (called before init).
650pub fn get_config(key: &str) -> Option<String> {
651 let ctx_ptr = APP_CONTEXT.load(Ordering::Acquire);
652 if ctx_ptr.is_null() {
653 return None;
654 }
655 let c_key = CString::new(key).ok()?;
656 unsafe {
657 let ctx = &*ctx_ptr;
658 let result = (ctx.host_get_config)(ctx.host_data, c_key.as_ptr());
659 if result.is_null() {
660 return None;
661 }
662 Some(std::ffi::CStr::from_ptr(result).to_string_lossy().into_owned())
663 }
664}
665
666/// Set a storage value scoped to this app.
667///
668/// Storage is persisted by the host across app restarts and is isolated
669/// per-app: other apps cannot read or write keys you set here. Useful
670/// for small bits of configuration or state; for larger or relational
671/// data, prefer the `core.storage.*` capabilities.
672///
673/// No-op when the host context is not available or `key`/`value`
674/// contain interior NUL bytes.
675pub fn set_storage(key: &str, value: &str) {
676 let ctx_ptr = APP_CONTEXT.load(Ordering::Acquire);
677 if ctx_ptr.is_null() {
678 return;
679 }
680 let c_key = match CString::new(key) {
681 Ok(s) => s,
682 Err(_) => return,
683 };
684 let c_value = match CString::new(value) {
685 Ok(s) => s,
686 Err(_) => return,
687 };
688 unsafe {
689 let ctx = &*ctx_ptr;
690 (ctx.host_set_storage)(ctx.host_data, c_key.as_ptr(), c_value.as_ptr());
691 }
692}
693
694/// Get a storage value by key, scoped to this app.
695///
696/// See [`set_storage`] for scoping semantics. Returns `None` if the key
697/// is not found or the context is not available.
698pub fn get_storage(key: &str) -> Option<String> {
699 let ctx_ptr = APP_CONTEXT.load(Ordering::Acquire);
700 if ctx_ptr.is_null() {
701 return None;
702 }
703 let c_key = CString::new(key).ok()?;
704 unsafe {
705 let ctx = &*ctx_ptr;
706 let result = (ctx.host_get_storage)(ctx.host_data, c_key.as_ptr());
707 if result.is_null() {
708 return None;
709 }
710 Some(std::ffi::CStr::from_ptr(result).to_string_lossy().into_owned())
711 }
712}
713
714/// Error type returned by app operations.
715///
716/// Variants surface specific failure modes from each lifecycle hook plus
717/// transport-level errors (serialization, capability dispatch). The
718/// `#[from] serde_json::Error` impl on [`NodeAppError::SerializationError`]
719/// allows the `?` operator to propagate JSON errors directly.
720#[derive(Debug, thiserror::Error)]
721pub enum NodeAppError {
722 /// Returned from [`NodeApp::init`] when initialization failed.
723 #[error("Initialization failed: {0}")]
724 InitFailed(String),
725 /// Returned from [`NodeApp::handle_request`] when handling failed.
726 #[error("Request handling failed: {0}")]
727 RequestFailed(String),
728 /// Returned from [`NodeApp::handle_event`] or [`publish_event`].
729 #[error("Event handling failed: {0}")]
730 EventFailed(String),
731 /// Returned from [`NodeApp::shutdown`] when graceful shutdown failed.
732 #[error("Shutdown failed: {0}")]
733 ShutdownFailed(String),
734 /// JSON (de)serialization error — auto-converted from
735 /// [`serde_json::Error`] via the `?` operator.
736 #[error("Serialization error: {0}")]
737 SerializationError(#[from] serde_json::Error),
738 /// Returned from [`NodeApp::handle_capability`] or [`invoke_capability`].
739 #[error("Capability error: {0}")]
740 CapabilityError(String),
741}
742
743/// Trait implemented by node-app plugins.
744///
745/// Pair this with [`declare_node_app!`] to generate all the FFI
746/// boilerplate. Implementors must be `Default + Send + Sync + 'static`
747/// because the macro stores the singleton instance behind a static
748/// `OnceLock<Mutex<T>>`.
749///
750/// All trait methods have sensible default implementations; override
751/// only the hooks the app uses. Apps that opt into a hook must also
752/// declare the matching capability in their manifest, e.g.
753/// `"http_handler"` for HTTP request routing.
754pub trait NodeApp: Default + Send + Sync + 'static {
755 /// Return app metadata (name, version, author, description, capabilities).
756 ///
757 /// Called once when the host loads the shared library. The values
758 /// are cached for the lifetime of the process.
759 fn metadata() -> NodeAppInfo;
760
761 /// Initialize the app with the host context.
762 ///
763 /// Called once after loading. The default impl is a no-op — override
764 /// to set up state (DB connections, caches, etc.). The context may
765 /// be `None` if the host has not wired up callbacks yet (very early
766 /// in bootstrap or in unit tests).
767 fn init(&mut self, _ctx: Option<&NodeAppContext>) -> Result<(), NodeAppError> {
768 Ok(())
769 }
770
771 /// Start shutting down: called at once when the host stops the app,
772 /// while earlier calls may still be running.
773 ///
774 /// Runs under a shared borrow and does not wait for in-flight calls.
775 /// From this point the SDK refuses new calls with
776 /// [`ERROR_SHUTTING_DOWN`]. Override it to make in-flight work return
777 /// soon: cancel a token, set a flag, close a channel. Keep it short and
778 /// do not block in it. [`NodeApp::shutdown`] runs after it, once every
779 /// in-flight call has returned. Default is a no-op. See ADR-083.
780 fn begin_shutdown(&self) {}
781
782 /// Shut down the app gracefully.
783 ///
784 /// Called before unloading, after [`NodeApp::begin_shutdown`] and after
785 /// every in-flight call has returned, so it has exclusive access.
786 /// Default is a no-op. Override to flush pending writes, close
787 /// connections, etc.
788 fn shutdown(&mut self) -> Result<(), NodeAppError> {
789 Ok(())
790 }
791
792 /// Handle an incoming HTTP request proxied from the host.
793 ///
794 /// Only invoked if the app declared the `http_handler` capability.
795 /// Default returns `501 Not Implemented`.
796 fn handle_request(&self, _request: AppRequest) -> Result<AppResponse, NodeAppError> {
797 Ok(AppResponse {
798 status: 501,
799 headers: Default::default(),
800 body: serde_json::json!({"error": "Not implemented"}),
801 })
802 }
803
804 /// Handle a domain event from the host event bus.
805 ///
806 /// Only invoked if the app declared the `event_listener` capability
807 /// and subscribed to the event's namespace via the manifest.
808 fn handle_event(&self, _event: AppEvent) -> Result<(), NodeAppError> {
809 Ok(())
810 }
811
812 /// Return the list of service capabilities this app provides.
813 ///
814 /// Override to declare capabilities for the host's capability
815 /// registry. Default returns an empty list (no capabilities
816 /// provided). Each entry must use the namespace `{app_name}.{domain}.{action}`
817 /// — the `core.*` namespace is reserved for first-party apps.
818 fn provided_capabilities() -> Vec<ProvidedCapability> {
819 Vec::new()
820 }
821
822 /// Handle a capability invocation from another app via the
823 /// capability router.
824 ///
825 /// Override to implement capability handling logic. The default
826 /// returns [`NodeAppError::CapabilityError`] indicating the
827 /// capability is not implemented.
828 ///
829 /// Trace context is automatically captured into thread-local state
830 /// for the duration of this call so [`invoke_capability`] can
831 /// propagate it on outbound calls without explicit threading.
832 fn handle_capability(
833 &self,
834 _request: CapabilityRequest,
835 ) -> Result<CapabilityResponse, NodeAppError> {
836 Err(NodeAppError::CapabilityError(
837 "Capability handling not implemented".into(),
838 ))
839 }
840}
841
842/// Generate all FFI boilerplate for a [`NodeApp`] implementation.
843///
844/// This macro creates:
845/// - A `OnceLock<RwLock<T>>` instance for the app (sound concurrent access).
846/// - A call gate: the shutdown entry calls [`NodeApp::begin_shutdown`] at
847/// once, refuses new calls with [`ERROR_SHUTTING_DOWN`], and takes the
848/// write lock for [`NodeApp::shutdown`] only after in-flight calls return.
849/// - The `_node_app_entry` export symbol returning a [`NodeAppVTable`].
850/// - FFI wrapper functions for `init`, `shutdown`, `handle_request`,
851/// `handle_event`, `handle_capability`, and `free`.
852/// - `catch_unwind` guards on every FFI boundary to prevent UB from
853/// panics crossing the Rust/C ABI.
854/// - Thread-local trace span management around `handle_capability`.
855///
856/// Invoke once at the crate root after defining the app type:
857///
858/// ```ignore
859/// declare_node_app!(MyApp);
860/// ```
861#[macro_export]
862macro_rules! declare_node_app {
863 ($app_type:ty) => {
864 // Feature 463 B5 fix — RwLock instead of Mutex so capability calls
865 // can run CONCURRENTLY (read-locked). The previous Mutex serialized
866 // every call, causing a deadlock when one capability (e.g. agent.prompt)
867 // invokes another capability on the SAME app re-entrantly through the
868 // graph engine (agent.prompt → graph.engine.send_event → graph node →
869 // graph.tasks.storage.* → core.agent_storage.* → BACK to agent app).
870 // init still takes the write lock. Shutdown takes it only after the
871 // call gate has drained, so begin_shutdown runs at once (ADR-083).
872 static APP_INSTANCE: std::sync::OnceLock<std::sync::RwLock<$app_type>> =
873 std::sync::OnceLock::new();
874 static CALL_GATE: $crate::CallGate = $crate::CallGate::new();
875 static VTABLE: std::sync::OnceLock<$crate::NodeAppVTable> =
876 std::sync::OnceLock::new();
877
878 // OnceLock-backed CStrings for metadata (valid for process lifetime)
879 static META_NAME: std::sync::OnceLock<std::ffi::CString> = std::sync::OnceLock::new();
880 static META_VERSION: std::sync::OnceLock<std::ffi::CString> = std::sync::OnceLock::new();
881 static META_AUTHOR: std::sync::OnceLock<std::ffi::CString> = std::sync::OnceLock::new();
882 static META_DESCRIPTION: std::sync::OnceLock<std::ffi::CString> =
883 std::sync::OnceLock::new();
884
885 unsafe extern "C" fn __node_app_init(
886 ctx: *const std::os::raw::c_void,
887 ) -> $crate::FfiResult {
888 match std::panic::catch_unwind(std::panic::AssertUnwindSafe(|| {
889 let ctx_opt = if ctx.is_null() {
890 None
891 } else {
892 // Store context pointer for use by log() helper
893 let ctx_typed = ctx as *const $crate::NodeAppContext;
894 $crate::__store_context(ctx_typed);
895 Some(unsafe { &*ctx_typed })
896 };
897 let app = APP_INSTANCE.get_or_init(|| {
898 std::sync::RwLock::new(<$app_type>::default())
899 });
900 let mut guard = match app.write() {
901 Ok(g) => g,
902 Err(e) => {
903 eprintln!("[node-app] rwlock poisoned in init: {}", e);
904 return $crate::FfiResult::error(-10);
905 }
906 };
907 // A cached library is initialized again after a shutdown
908 // (reload), so accept calls again.
909 CALL_GATE.open();
910 match guard.init(ctx_opt) {
911 Ok(()) => $crate::FfiResult::ok(),
912 Err(e) => {
913 let msg = format!("init error: {}", e);
914 $crate::log($crate::log_level::ERROR, &msg);
915 eprintln!("[node-app] {}", msg);
916 $crate::FfiResult::error(-1)
917 }
918 }
919 })) {
920 Ok(result) => result,
921 Err(_) => {
922 eprintln!("[node-app] panic in init");
923 $crate::FfiResult::error(-99)
924 }
925 }
926 }
927
928 unsafe extern "C" fn __node_app_shutdown() -> $crate::FfiResult {
929 match std::panic::catch_unwind(std::panic::AssertUnwindSafe(|| {
930 if let Some(app) = APP_INSTANCE.get() {
931 // ADR-083: refuse new calls, tell the app at once, then
932 // take the write lock only after in-flight calls return.
933 // Never return before they do: the host may unload the
934 // library when this entry returns.
935 CALL_GATE.close();
936 let hook = match app.read() {
937 Ok(app) => std::panic::catch_unwind(std::panic::AssertUnwindSafe(|| {
938 <$app_type as $crate::NodeApp>::begin_shutdown(&app)
939 })),
940 Err(e) => {
941 eprintln!("[node-app] rwlock poisoned in shutdown: {}", e);
942 return $crate::FfiResult::error(-10);
943 }
944 };
945 // A panicking hook must not skip the drain below.
946 if hook.is_err() {
947 let msg = "panic in begin_shutdown; still waiting for in-flight calls";
948 $crate::log($crate::log_level::ERROR, msg);
949 eprintln!("[node-app] {}", msg);
950 }
951 let in_flight =
952 CALL_GATE.wait_drained(Some($crate::SHUTDOWN_DRAIN_WARN_AFTER));
953 if in_flight > 0 {
954 let msg = format!(
955 "shutdown: {} call(s) still in flight after {} ms; waiting for them to return",
956 in_flight,
957 $crate::SHUTDOWN_DRAIN_WARN_AFTER.as_millis()
958 );
959 $crate::log($crate::log_level::WARN, &msg);
960 eprintln!("[node-app] {}", msg);
961 CALL_GATE.wait_drained(None);
962 }
963 let mut guard = match app.write() {
964 Ok(g) => g,
965 Err(e) => {
966 eprintln!("[node-app] rwlock poisoned in shutdown: {}", e);
967 return $crate::FfiResult::error(-10);
968 }
969 };
970 match guard.shutdown() {
971 Ok(()) => $crate::FfiResult::ok(),
972 Err(e) => {
973 let msg = format!("shutdown error: {}", e);
974 $crate::log($crate::log_level::ERROR, &msg);
975 eprintln!("[node-app] {}", msg);
976 $crate::FfiResult::error(-1)
977 }
978 }
979 } else {
980 $crate::FfiResult::ok()
981 }
982 })) {
983 Ok(result) => result,
984 Err(_) => {
985 eprintln!("[node-app] panic in shutdown");
986 $crate::FfiResult::error(-99)
987 }
988 }
989 }
990
991 unsafe extern "C" fn __node_app_handle_request(
992 request_json: *const u8,
993 request_len: usize,
994 ) -> $crate::FfiResult {
995 match std::panic::catch_unwind(std::panic::AssertUnwindSafe(|| {
996 let json_slice =
997 unsafe { std::slice::from_raw_parts(request_json, request_len) };
998 let request: $crate::AppRequest = match serde_json::from_slice(json_slice) {
999 Ok(r) => r,
1000 Err(e) => {
1001 eprintln!("[node-app] request deserialization error: {}", e);
1002 return $crate::FfiResult::error(-2);
1003 }
1004 };
1005
1006 let app = match APP_INSTANCE.get() {
1007 Some(a) => a,
1008 None => return $crate::FfiResult::error(-3),
1009 };
1010 // ADR-083 — refused once shutdown starts; counted in flight
1011 // until this permit drops (after the read guard below).
1012 let _call = match CALL_GATE.enter() {
1013 Some(call) => call,
1014 None => return $crate::FfiResult::error($crate::ERROR_SHUTTING_DOWN),
1015 };
1016 // Feature 463 B5 — read-lock allows concurrent calls
1017 let guard = match app.read() {
1018 Ok(g) => g,
1019 Err(e) => {
1020 eprintln!("[node-app] rwlock poisoned in handle_request: {}", e);
1021 return $crate::FfiResult::error(-10);
1022 }
1023 };
1024
1025 match guard.handle_request(request) {
1026 Ok(response) => match serde_json::to_vec(&response) {
1027 Ok(bytes) => {
1028 let len = bytes.len();
1029 let boxed = bytes.into_boxed_slice();
1030 let ptr = Box::into_raw(boxed) as *mut u8;
1031 $crate::FfiResult {
1032 success: true,
1033 error_code: 0,
1034 data: ptr,
1035 data_len: len,
1036 }
1037 }
1038 Err(e) => {
1039 eprintln!("[node-app] response serialization error: {}", e);
1040 $crate::FfiResult::error(-4)
1041 }
1042 },
1043 Err(e) => {
1044 eprintln!("[node-app] handle_request error: {}", e);
1045 $crate::FfiResult::error(-5)
1046 }
1047 }
1048 })) {
1049 Ok(result) => result,
1050 Err(_) => {
1051 eprintln!("[node-app] panic in handle_request");
1052 $crate::FfiResult::error(-99)
1053 }
1054 }
1055 }
1056
1057 unsafe extern "C" fn __node_app_handle_event(
1058 event_json: *const u8,
1059 event_len: usize,
1060 ) -> $crate::FfiResult {
1061 match std::panic::catch_unwind(std::panic::AssertUnwindSafe(|| {
1062 let json_slice =
1063 unsafe { std::slice::from_raw_parts(event_json, event_len) };
1064 let event: $crate::AppEvent = match serde_json::from_slice(json_slice) {
1065 Ok(e) => e,
1066 Err(e) => {
1067 eprintln!("[node-app] event deserialization error: {}", e);
1068 return $crate::FfiResult::error(-2);
1069 }
1070 };
1071
1072 let app = match APP_INSTANCE.get() {
1073 Some(a) => a,
1074 None => return $crate::FfiResult::error(-3),
1075 };
1076 // ADR-083 — refused once shutdown starts; declared before the
1077 // read guard so the guard drops first.
1078 let _call = match CALL_GATE.enter() {
1079 Some(call) => call,
1080 None => return $crate::FfiResult::error($crate::ERROR_SHUTTING_DOWN),
1081 };
1082 // Feature 463 B5 — read-lock allows concurrent calls
1083 let guard = match app.read() {
1084 Ok(g) => g,
1085 Err(e) => {
1086 eprintln!("[node-app] rwlock poisoned in handle_event: {}", e);
1087 return $crate::FfiResult::error(-10);
1088 }
1089 };
1090
1091 match guard.handle_event(event) {
1092 Ok(()) => $crate::FfiResult::ok(),
1093 Err(e) => {
1094 eprintln!("[node-app] handle_event error: {}", e);
1095 $crate::FfiResult::error(-5)
1096 }
1097 }
1098 })) {
1099 Ok(result) => result,
1100 Err(_) => {
1101 eprintln!("[node-app] panic in handle_event");
1102 $crate::FfiResult::error(-99)
1103 }
1104 }
1105 }
1106
1107 unsafe extern "C" fn __node_app_handle_capability(
1108 request_json: *const u8,
1109 request_len: usize,
1110 ) -> $crate::FfiResult {
1111 match std::panic::catch_unwind(std::panic::AssertUnwindSafe(|| {
1112 let json_slice =
1113 unsafe { std::slice::from_raw_parts(request_json, request_len) };
1114 let request: $crate::CapabilityRequest = match serde_json::from_slice(json_slice) {
1115 Ok(r) => r,
1116 Err(e) => {
1117 eprintln!("[node-app] capability request deserialization error: {}", e);
1118 return $crate::FfiResult::error(-2);
1119 }
1120 };
1121
1122 let app = match APP_INSTANCE.get() {
1123 Some(a) => a,
1124 None => return $crate::FfiResult::error(-3),
1125 };
1126 // ADR-083 — refused once shutdown starts; declared before the
1127 // read guard so the guard drops first.
1128 let _call = match CALL_GATE.enter() {
1129 Some(call) => call,
1130 None => return $crate::FfiResult::error($crate::ERROR_SHUTTING_DOWN),
1131 };
1132 // Feature 463 B5 — read-lock allows the SAME app to handle
1133 // re-entrant capability calls (e.g. agent.prompt outer call
1134 // and an inner core.agent_storage.write from a graph node)
1135 // concurrently. handle_capability is &self so this is sound.
1136 let guard = match app.read() {
1137 Ok(g) => g,
1138 Err(e) => {
1139 eprintln!("[node-app] rwlock poisoned in handle_capability: {}", e);
1140 return $crate::FfiResult::error(-10);
1141 }
1142 };
1143
1144 // Set thread-local trace context for duration of this capability call.
1145 // This allows invoke_capability() to propagate trace automatically.
1146 $crate::CURRENT_TRACE.with(|tl| {
1147 *tl.borrow_mut() = if let Some(ref trace_id) = request.trace_id {
1148 Some($crate::CurrentTrace {
1149 trace_id: trace_id.clone(),
1150 span_id: request.span_id.clone().unwrap_or_default(),
1151 depth: request.trace_depth.unwrap_or(0),
1152 })
1153 } else {
1154 None
1155 };
1156 });
1157
1158 let _invocation_context_guard =
1159 $crate::CurrentInvocationContextGuard::enter(
1160 request.invocation_context_id.clone(),
1161 );
1162
1163 let cap_result = guard.handle_capability(request);
1164
1165 // Clear trace context after call completes.
1166 $crate::CURRENT_TRACE.with(|tl| {
1167 *tl.borrow_mut() = None;
1168 });
1169
1170 match cap_result {
1171 Ok(response) => match serde_json::to_vec(&response) {
1172 Ok(bytes) => {
1173 // Enforce 16MB response limit
1174 if bytes.len() > $crate::MAX_CAPABILITY_RESPONSE_SIZE {
1175 eprintln!(
1176 "[node-app] capability response exceeds 16MB limit ({} bytes)",
1177 bytes.len()
1178 );
1179 return $crate::FfiResult::error(-6);
1180 }
1181 let len = bytes.len();
1182 let boxed = bytes.into_boxed_slice();
1183 let ptr = Box::into_raw(boxed) as *mut u8;
1184 $crate::FfiResult {
1185 success: true,
1186 error_code: 0,
1187 data: ptr,
1188 data_len: len,
1189 }
1190 }
1191 Err(e) => {
1192 eprintln!("[node-app] capability response serialization error: {}", e);
1193 $crate::FfiResult::error(-4)
1194 }
1195 },
1196 Err(e) => {
1197 eprintln!("[node-app] handle_capability error: {}", e);
1198 $crate::FfiResult::error(-5)
1199 }
1200 }
1201 })) {
1202 Ok(result) => result,
1203 Err(_) => {
1204 eprintln!("[node-app] panic in handle_capability");
1205 $crate::FfiResult::error(-99)
1206 }
1207 }
1208 }
1209
1210 unsafe extern "C" fn __node_app_free(ptr: *mut u8, len: usize) {
1211 if !ptr.is_null() && len > 0 {
1212 let _ = unsafe { Box::from_raw(std::slice::from_raw_parts_mut(ptr, len)) };
1213 }
1214 }
1215
1216 #[no_mangle]
1217 pub unsafe extern "C" fn _node_app_entry(
1218 _ctx: *const std::os::raw::c_void,
1219 ) -> *const $crate::NodeAppVTable {
1220 match std::panic::catch_unwind(std::panic::AssertUnwindSafe(|| {
1221 let info = <$app_type as $crate::NodeApp>::metadata();
1222 let caps = info.capability_flags();
1223
1224 let name = META_NAME
1225 .get_or_init(|| std::ffi::CString::new(info.name).unwrap_or_default());
1226 let version = META_VERSION
1227 .get_or_init(|| std::ffi::CString::new(info.version).unwrap_or_default());
1228 let author = META_AUTHOR
1229 .get_or_init(|| std::ffi::CString::new(info.author).unwrap_or_default());
1230 let description = META_DESCRIPTION
1231 .get_or_init(|| std::ffi::CString::new(info.description).unwrap_or_default());
1232
1233 let metadata = $crate::NodeAppMetadata {
1234 api_version: $crate::API_VERSION,
1235 name: name.as_ptr(),
1236 version: version.as_ptr(),
1237 author: author.as_ptr(),
1238 description: description.as_ptr(),
1239 capabilities: caps.bits(),
1240 };
1241
1242 VTABLE.get_or_init(|| $crate::NodeAppVTable {
1243 metadata,
1244 init: __node_app_init,
1245 shutdown: __node_app_shutdown,
1246 handle_request: __node_app_handle_request,
1247 handle_event: __node_app_handle_event,
1248 handle_capability: __node_app_handle_capability,
1249 free: __node_app_free,
1250 }) as *const $crate::NodeAppVTable
1251 })) {
1252 Ok(ptr) => ptr,
1253 Err(_) => {
1254 eprintln!("[node-app] panic in _node_app_entry");
1255 std::ptr::null()
1256 }
1257 }
1258 }
1259 };
1260}
1261
1262#[cfg(test)]
1263mod invocation_context_tests {
1264 use std::ffi::{c_char, c_void};
1265 use std::sync::Mutex;
1266
1267 use super::*;
1268
1269 pub(super) static TEST_LOCK: Mutex<()> = Mutex::new(());
1270
1271 unsafe extern "C" fn noop_log(_: *const c_void, _: u32, _: *const c_char) {}
1272 unsafe extern "C" fn no_config(_: *const c_void, _: *const c_char) -> *const c_char {
1273 std::ptr::null()
1274 }
1275 unsafe extern "C" fn noop_storage(_: *const c_void, _: *const c_char, _: *const c_char) {}
1276 unsafe extern "C" fn no_storage(_: *const c_void, _: *const c_char) -> *const c_char {
1277 std::ptr::null()
1278 }
1279 unsafe extern "C" fn noop_publish(
1280 _: *const c_void,
1281 _: *const u8,
1282 _: usize,
1283 _: *const u8,
1284 _: usize,
1285 ) -> i32 {
1286 0
1287 }
1288 unsafe extern "C" fn capture_invoke(
1289 host_data: *const c_void,
1290 request_json: *const u8,
1291 request_len: usize,
1292 ) -> FfiResult {
1293 let requests = &*(host_data as *const Mutex<Vec<CapabilityRequest>>);
1294 let bytes = std::slice::from_raw_parts(request_json, request_len);
1295 requests
1296 .lock()
1297 .unwrap()
1298 .push(serde_json::from_slice(bytes).unwrap());
1299 let response = CapabilityResponse {
1300 id: "nested-1".into(),
1301 success: true,
1302 payload: serde_json::json!({"ok": true}),
1303 };
1304 let bytes = serde_json::to_vec(&response).unwrap().into_boxed_slice();
1305 let len = bytes.len();
1306 let data = Box::into_raw(bytes) as *mut u8;
1307 FfiResult {
1308 success: true,
1309 error_code: 0,
1310 data,
1311 data_len: len,
1312 }
1313 }
1314
1315 #[test]
1316 fn nested_invocation_propagates_opaque_context() {
1317 let _serial = TEST_LOCK.lock().unwrap();
1318 let captured = Mutex::new(Vec::<CapabilityRequest>::new());
1319 let context = NodeAppContext {
1320 host_data: &captured as *const _ as *const c_void,
1321 host_log: noop_log,
1322 host_get_config: no_config,
1323 host_set_storage: noop_storage,
1324 host_get_storage: no_storage,
1325 host_invoke_capability: capture_invoke,
1326 host_publish_event: noop_publish,
1327 };
1328 __store_context(&context);
1329 CURRENT_TRACE.with(|current| {
1330 *current.borrow_mut() = Some(CurrentTrace {
1331 trace_id: "trace-1".into(),
1332 span_id: "span-1".into(),
1333 depth: 4,
1334 });
1335 });
1336 let _invocation =
1337 CurrentInvocationContextGuard::enter(Some("opaque-context-1".into()));
1338
1339 invoke_capability(&CapabilityRequest {
1340 id: "nested-1".into(),
1341 capability: "example.nested".into(),
1342 payload: serde_json::json!({}),
1343 ..Default::default()
1344 })
1345 .unwrap();
1346
1347 let requests = captured.lock().unwrap();
1348 assert_eq!(requests.len(), 1);
1349 assert_eq!(
1350 requests[0].invocation_context_id.as_deref(),
1351 Some("opaque-context-1")
1352 );
1353 assert_eq!(requests[0].trace_id.as_deref(), Some("trace-1"));
1354 assert_eq!(requests[0].span_id.as_deref(), Some("span-1"));
1355 drop(requests);
1356 CURRENT_TRACE.with(|current| *current.borrow_mut() = None);
1357 __store_context(std::ptr::null());
1358 }
1359}
1360
1361#[cfg(test)]
1362mod shutdown_gate_tests {
1363 use std::sync::atomic::AtomicBool;
1364 use std::sync::{Condvar, Mutex, PoisonError};
1365 use std::time::Duration;
1366
1367 use super::*;
1368
1369 struct Signal {
1370 set: Mutex<bool>,
1371 changed: Condvar,
1372 }
1373
1374 impl Signal {
1375 const fn new() -> Self {
1376 Self {
1377 set: Mutex::new(false),
1378 changed: Condvar::new(),
1379 }
1380 }
1381
1382 fn set(&self) {
1383 *self.set.lock().unwrap() = true;
1384 self.changed.notify_all();
1385 }
1386
1387 fn reset(&self) {
1388 *self.set.lock().unwrap() = false;
1389 }
1390
1391 fn is_set(&self) -> bool {
1392 *self.set.lock().unwrap()
1393 }
1394
1395 fn wait(&self, timeout: Duration) -> bool {
1396 let set = self.set.lock().unwrap();
1397 *self
1398 .changed
1399 .wait_timeout_while(set, timeout, |set| !*set)
1400 .unwrap()
1401 .0
1402 }
1403 }
1404
1405 // Tests that use the app reset these first and hold TEST_LOCK: the macro
1406 // allows one app per binary, so they share it.
1407 static CALL_ENTERED: Signal = Signal::new();
1408 static RELEASE_CALL: Signal = Signal::new();
1409 static HOOK_RAN: Signal = Signal::new();
1410 static SHUTDOWN_RAN: Signal = Signal::new();
1411 static PANIC_IN_HOOK: AtomicBool = AtomicBool::new(false);
1412
1413 #[derive(Default)]
1414 struct SlowApp;
1415
1416 impl NodeApp for SlowApp {
1417 fn metadata() -> NodeAppInfo {
1418 NodeAppInfo {
1419 name: "slow".into(),
1420 version: "0.0.0".into(),
1421 author: "test".into(),
1422 description: "holds a capability call open".into(),
1423 capabilities: Vec::new(),
1424 }
1425 }
1426
1427 fn begin_shutdown(&self) {
1428 HOOK_RAN.set();
1429 if PANIC_IN_HOOK.load(Ordering::SeqCst) {
1430 panic!("begin_shutdown test panic");
1431 }
1432 }
1433
1434 fn shutdown(&mut self) -> Result<(), NodeAppError> {
1435 SHUTDOWN_RAN.set();
1436 Ok(())
1437 }
1438
1439 fn handle_capability(
1440 &self,
1441 request: CapabilityRequest,
1442 ) -> Result<CapabilityResponse, NodeAppError> {
1443 CALL_ENTERED.set();
1444 // Holds the app's read lock until the test lets go. The bound only
1445 // keeps a failing test from hanging.
1446 if !RELEASE_CALL.wait(Duration::from_secs(10)) {
1447 return Err(NodeAppError::CapabilityError("never released".into()));
1448 }
1449 Ok(CapabilityResponse {
1450 id: request.id,
1451 success: true,
1452 payload: serde_json::json!({}),
1453 })
1454 }
1455 }
1456
1457 crate::declare_node_app!(SlowApp);
1458
1459 /// 0 on success, else the wrapper's error code. Frees any response.
1460 fn code(result: FfiResult) -> i32 {
1461 if !result.success {
1462 return result.error_code;
1463 }
1464 if !result.data.is_null() {
1465 unsafe { __node_app_free(result.data, result.data_len) };
1466 }
1467 0
1468 }
1469
1470 fn call() -> i32 {
1471 let request = serde_json::to_vec(&CapabilityRequest {
1472 id: "call-1".into(),
1473 capability: "slow.wait".into(),
1474 payload: serde_json::json!({}),
1475 ..Default::default()
1476 })
1477 .unwrap();
1478 code(unsafe { __node_app_handle_capability(request.as_ptr(), request.len()) })
1479 }
1480
1481 fn request() -> i32 {
1482 let request = serde_json::to_vec(&AppRequest {
1483 id: "request-1".into(),
1484 method: "GET".into(),
1485 path: "/".into(),
1486 headers: Default::default(),
1487 body: serde_json::Value::Null,
1488 caller: None,
1489 })
1490 .unwrap();
1491 code(unsafe { __node_app_handle_request(request.as_ptr(), request.len()) })
1492 }
1493
1494 fn event() -> i32 {
1495 let event = serde_json::to_vec(&AppEvent {
1496 name: "slow.tick".into(),
1497 data: serde_json::Value::Null,
1498 })
1499 .unwrap();
1500 code(unsafe { __node_app_handle_event(event.as_ptr(), event.len()) })
1501 }
1502
1503 /// Stop the app while a capability call holds its read lock.
1504 fn stop_while_a_call_is_in_flight(panic_in_hook: bool) {
1505 for signal in [&CALL_ENTERED, &RELEASE_CALL, &HOOK_RAN, &SHUTDOWN_RAN] {
1506 signal.reset();
1507 }
1508 PANIC_IN_HOOK.store(panic_in_hook, Ordering::SeqCst);
1509 assert!(unsafe { __node_app_init(std::ptr::null()) }.success);
1510
1511 let in_flight = std::thread::spawn(call);
1512 assert!(
1513 CALL_ENTERED.wait(Duration::from_secs(5)),
1514 "call never started"
1515 );
1516
1517 let shutdown = std::thread::spawn(|| unsafe { __node_app_shutdown() }.success);
1518 // The in-flight call cannot return before RELEASE_CALL, so the hook
1519 // runs while that call still holds the read lock.
1520 assert!(
1521 HOOK_RAN.wait(Duration::from_secs(1)),
1522 "begin_shutdown waited behind the in-flight call"
1523 );
1524 assert_eq!(call(), ERROR_SHUTTING_DOWN, "capability call not refused");
1525 assert_eq!(request(), ERROR_SHUTTING_DOWN, "request not refused");
1526 assert_eq!(event(), ERROR_SHUTTING_DOWN, "event not refused");
1527 assert!(
1528 !SHUTDOWN_RAN.is_set(),
1529 "shutdown(&mut self) ran while a call was in flight"
1530 );
1531
1532 RELEASE_CALL.set();
1533 assert_eq!(in_flight.join().unwrap(), 0, "in-flight call failed");
1534 assert!(shutdown.join().unwrap(), "shutdown entry failed");
1535 assert!(SHUTDOWN_RAN.is_set());
1536 }
1537
1538 #[test]
1539 fn shutdown_hook_runs_while_a_call_is_in_flight() {
1540 let _serial = super::invocation_context_tests::TEST_LOCK
1541 .lock()
1542 .unwrap_or_else(PoisonError::into_inner);
1543 stop_while_a_call_is_in_flight(false);
1544
1545 // A cached library is initialized again on reload; it takes calls again.
1546 assert!(unsafe { __node_app_init(std::ptr::null()) }.success);
1547 assert_eq!(call(), 0, "capability call refused after init");
1548 assert_eq!(request(), 0, "request refused after init");
1549 assert_eq!(event(), 0, "event refused after init");
1550 }
1551
1552 #[test]
1553 fn panicking_shutdown_hook_still_waits_for_in_flight_calls() {
1554 let _serial = super::invocation_context_tests::TEST_LOCK
1555 .lock()
1556 .unwrap_or_else(PoisonError::into_inner);
1557 stop_while_a_call_is_in_flight(true);
1558 }
1559
1560 #[test]
1561 fn call_gate_counts_each_call_until_its_permit_drops() {
1562 let gate = CallGate::new();
1563 let first = gate.enter().expect("open gate admits");
1564 let second = gate.enter().expect("open gate admits");
1565 gate.close();
1566 assert!(gate.enter().is_none(), "closed gate admitted a call");
1567 assert_eq!(gate.wait_drained(Some(Duration::from_millis(10))), 2);
1568 drop(first);
1569 assert_eq!(gate.wait_drained(Some(Duration::from_millis(10))), 1);
1570 drop(second);
1571 assert_eq!(gate.wait_drained(None), 0);
1572 gate.open();
1573 assert!(gate.enter().is_some(), "reopened gate refused a call");
1574 }
1575}