Skip to main content

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