node-app-sdk-rust 7.6.214

Rust SDK for building Node-App native plugins (cdylib) — Lightning-powered marketplace nodes
Documentation
//! In-process pipes to another native app (`core.pipe.*`, ADR-300).
//!
//! Two native apps in one host process can share a live two-way byte stream: the opener gets
//! one end of a host-made `AF_UNIX` socket pair and a token for the other; it passes the token
//! on in a capability call of its own; the receiver claims it. Each side then owns a plain Unix
//! stream socket and wraps it on its own runtime (`tokio::net::UnixStream::from_std` after
//! `set_nonblocking(true)`). A token nobody claims within its TTL closes, and the opener reads
//! EOF.
//!
//! ```ignore
//! // opener
//! let (ours, token) = node_app_sdk_rust::pipe::open("ln-bolt8", None)?;
//! invoke_capability(/* the other app's capability, carrying `token` */)?;
//! // receiver, inside that capability
//! let (theirs, _info) = node_app_sdk_rust::pipe::claim(&token)?;
//! ```

use std::os::fd::{FromRawFd, OwnedFd, RawFd};
use std::os::unix::net::UnixStream;

use crate::{invoke_capability, CapabilityRequest, NodeAppError};

/// Opens a pair.
pub const OPEN: &str = "core.pipe.open";
/// Claims a parked end.
pub const CLAIM: &str = "core.pipe.claim";

/// What the claimer learns about the pipe.
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct ClaimInfo {
    /// The opener's purpose.
    pub purpose: String,
    /// The app that opened the pair.
    pub opener: String,
}

fn call(capability: &str, payload: serde_json::Value) -> Result<serde_json::Value, NodeAppError> {
    let response = invoke_capability(&CapabilityRequest {
        id: format!("pipe-{}", std::process::id()),
        capability: capability.to_string(),
        payload,
        ..Default::default()
    })?;
    if response.success {
        Ok(response.payload)
    } else {
        let message = response
            .payload
            .get("message")
            .or_else(|| response.payload.get("error"))
            .and_then(serde_json::Value::as_str)
            .unwrap_or("pipe call failed")
            .to_string();
        Err(NodeAppError::CapabilityError(message))
    }
}

/// Takes ownership of the fd a pipe answer names, after checking it is an open socket.
fn adopt(answer: &serde_json::Value) -> Result<OwnedFd, NodeAppError> {
    let fd = answer
        .get("fd")
        .and_then(serde_json::Value::as_i64)
        .and_then(|fd| RawFd::try_from(fd).ok())
        .filter(|fd| *fd >= 0)
        .ok_or_else(|| NodeAppError::CapabilityError("pipe answer has no fd".into()))?;
    // SAFETY: `fstat` only writes into the zeroed struct we own.
    let mut stat: libc::stat = unsafe { std::mem::zeroed() };
    if unsafe { libc::fstat(fd, &mut stat) } != 0 || (stat.st_mode & libc::S_IFMT) != libc::S_IFSOCK {
        return Err(NodeAppError::CapabilityError(format!(
            "fd {} is not an open socket in this process",
            fd
        )));
    }
    // SAFETY: the host transferred ownership of this descriptor in its answer.
    Ok(unsafe { OwnedFd::from_raw_fd(fd) })
}

/// Opens a pair for `purpose` (1..=64 printable ASCII): this app's end, and the token of the
/// other end to pass on. `ttl_ms` bounds the wait for a claimer (host default 10 s, max 30 s).
pub fn open(purpose: &str, ttl_ms: Option<u64>) -> Result<(UnixStream, String), NodeAppError> {
    let mut payload = serde_json::json!({ "pid": std::process::id(), "purpose": purpose });
    if let Some(ttl_ms) = ttl_ms {
        payload["ttl_ms"] = ttl_ms.into();
    }
    let answer = call(OPEN, payload)?;
    let token = answer
        .get("peer_token")
        .and_then(serde_json::Value::as_str)
        .ok_or_else(|| NodeAppError::CapabilityError("pipe answer has no token".into()))?
        .to_string();
    Ok((UnixStream::from(adopt(&answer)?), token))
}

/// Claims the end parked under `token`.
pub fn claim(token: &str) -> Result<(UnixStream, ClaimInfo), NodeAppError> {
    let answer = call(CLAIM, serde_json::json!({ "pid": std::process::id(), "token": token }))?;
    let text = |key: &str| {
        answer.get(key).and_then(serde_json::Value::as_str).unwrap_or_default().to_string()
    };
    let info = ClaimInfo { purpose: text("purpose"), opener: text("opener") };
    Ok((UnixStream::from(adopt(&answer)?), info))
}