salamandr-plugin-sdk 0.3.0

Write Salamandr helpdesk extensions in Rust: safe typed wrappers for every host capability, the fetch_context wire contract, and an in-process mock host for testing.
Documentation
//! Low-level wire primitives: guest-owned allocation, pointer packing and
//! the `{ok,data,error,code}` envelope every value crossing the boundary
//! is wrapped in. Mirrors backend/internal/extwasm/abi.go and
//! hostfuncs.go's `envelope` type field for field.
//!
//! Everything here is `pub(crate)` except [`sdk_alloc`]/[`sdk_dealloc`],
//! which the `plugin!` macro's generated exports have to reach. A plugin
//! author never calls anything in this module directly — that is the
//! whole point of the crate.

use serde::Serialize;
#[cfg(target_arch = "wasm32")]
use std::alloc::{alloc as sys_alloc, dealloc as sys_dealloc, Layout};

/// The guest-side allocator every host_* function and `handle` call use
/// to move bytes across the boundary — see abi.go's doc comment for why
/// the guest, not the host, always owns allocation.
///
/// A zero-size request answers 1 rather than 0: 0 is the "allocation
/// failed" signal on the Go side, and a legitimately empty payload must
/// not look like a failure.
#[cfg(target_arch = "wasm32")]
#[doc(hidden)]
pub fn sdk_alloc(size: u32) -> u32 {
    if size == 0 {
        return 1;
    }
    unsafe {
        let layout = Layout::from_size_align(size as usize, 1).unwrap();
        sys_alloc(layout) as u32
    }
}

#[cfg(target_arch = "wasm32")]
#[doc(hidden)]
pub fn sdk_dealloc(ptr: u32, size: u32) {
    if ptr == 0 || size == 0 {
        return;
    }
    unsafe {
        let layout = Layout::from_size_align(size as usize, 1).unwrap();
        sys_dealloc(ptr as *mut u8, layout);
    }
}

#[cfg(target_arch = "wasm32")]
pub(crate) fn read_bytes(ptr: u32, len: u32) -> &'static [u8] {
    if ptr == 0 || len == 0 {
        return &[];
    }
    unsafe { std::slice::from_raw_parts(ptr as *const u8, len as usize) }
}

#[cfg(target_arch = "wasm32")]
pub(crate) fn write_bytes(data: &[u8]) -> (u32, u32) {
    let ptr = sdk_alloc(data.len() as u32);
    if !data.is_empty() {
        unsafe {
            let dst = std::slice::from_raw_parts_mut(ptr as *mut u8, data.len());
            dst.copy_from_slice(data);
        }
    }
    (ptr, data.len() as u32)
}

// ---------------------------------------------------------------------
// Native (test) builds.
//
// A wasm "pointer" is a 32-bit offset into the guest's own linear memory,
// which is exactly what makes `sys_alloc(...) as u32` correct there and
// catastrophic on a 64-bit host: truncating a real address to 32 bits
// yields something that reads as memory the process doesn't own. So on
// non-wasm targets the u32 is a *handle* into a per-thread table of leaked
// buffers rather than an address, and crate::testing's mock host speaks
// the same handles. Nothing here is compiled into a shipped .wasm.
// ---------------------------------------------------------------------

#[cfg(not(target_arch = "wasm32"))]
mod native_mem {
    use std::cell::RefCell;
    use std::collections::HashMap;

    thread_local! {
        static SLAB: RefCell<(u32, HashMap<u32, &'static mut [u8]>)> =
            RefCell::new((1, HashMap::new()));
    }

    pub(super) fn alloc(size: u32) -> u32 {
        SLAB.with(|slab| {
            let mut slab = slab.borrow_mut();
            let id = slab.0;
            // Never hand back 0 — it is the host's "allocation failed"
            // signal, same as on the wasm path.
            slab.0 = slab.0.checked_add(1).unwrap_or(1);
            let buf: &'static mut [u8] = vec![0u8; size as usize].leak();
            slab.1.insert(id, buf);
            id
        })
    }

    pub(super) fn write(id: u32, data: &[u8]) {
        SLAB.with(|slab| {
            if let Some(buf) = slab.borrow_mut().1.get_mut(&id) {
                buf[..data.len()].copy_from_slice(data);
            }
        });
    }

    pub(super) fn read(id: u32, len: u32) -> &'static [u8] {
        SLAB.with(|slab| match slab.borrow().1.get(&id) {
            // SAFETY: buffers are leaked and this path never frees one
            // (see dealloc below), so the slice genuinely outlives the
            // map borrow being released here.
            Some(buf) => unsafe { std::slice::from_raw_parts(buf.as_ptr(), (len as usize).min(buf.len())) },
            None => &[],
        })
    }
}

#[cfg(not(target_arch = "wasm32"))]
#[doc(hidden)]
pub fn sdk_alloc(size: u32) -> u32 {
    native_mem::alloc(size)
}

/// Deliberately a no-op natively: a test process is short-lived, and
/// freeing here would make [`read_bytes`]' `'static` a lie the moment a
/// caller held onto a slice.
#[cfg(not(target_arch = "wasm32"))]
#[doc(hidden)]
pub fn sdk_dealloc(_ptr: u32, _size: u32) {}

#[cfg(not(target_arch = "wasm32"))]
pub(crate) fn read_bytes(ptr: u32, len: u32) -> &'static [u8] {
    if ptr == 0 || len == 0 {
        return &[];
    }
    native_mem::read(ptr, len)
}

#[cfg(not(target_arch = "wasm32"))]
pub(crate) fn write_bytes(data: &[u8]) -> (u32, u32) {
    let ptr = sdk_alloc(data.len() as u32);
    native_mem::write(ptr, data);
    (ptr, data.len() as u32)
}

pub(crate) fn pack(ptr: u32, len: u32) -> u64 {
    ((ptr as u64) << 32) | (len as u64)
}

pub(crate) fn unpack(packed: u64) -> (u32, u32) {
    ((packed >> 32) as u32, packed as u32)
}

/// Envelope is the shape hostfuncs.go uses for every host_* response and
/// this SDK uses for `handle`/`describe`'s own responses.
#[derive(Serialize, serde::Deserialize)]
pub(crate) struct Envelope<T> {
    pub(crate) ok: bool,
    #[serde(skip_serializing_if = "Option::is_none")]
    pub(crate) data: Option<T>,
    #[serde(default)]
    pub(crate) error: String,
    #[serde(default)]
    pub(crate) code: String,
    /// retry_after accompanies `code == "rate_limited"`: the interval the
    /// vendor itself named, so the host waits what it was told to rather
    /// than a fixed guess. See extwasm's own envelope.RetryAfter.
    #[serde(default, skip_serializing_if = "String::is_empty")]
    pub(crate) retry_after: String,
}

/// respond_ok encodes a successful envelope into guest memory and returns
/// the packed pointer/length `handle` hands back to the host.
pub(crate) fn respond_ok<T: Serialize>(data: &T) -> u64 {
    let body = serde_json::to_vec(&Envelope {
        ok: true,
        data: Some(data),
        error: String::new(),
        code: String::new(),
        retry_after: String::new(),
    })
    .unwrap_or_else(|_| br#"{"ok":false,"error":"failed to encode response"}"#.to_vec());
    let (ptr, len) = write_bytes(&body);
    pack(ptr, len)
}

pub(crate) fn respond_err(msg: &str) -> u64 {
    respond_err_code(msg, "")
}

pub(crate) fn respond_err_code(msg: &str, code: &str) -> u64 {
    respond_err_retry(msg, code, "")
}

/// respond_err_retry is respond_err_code carrying the interval the vendor
/// named — only meaningful with the "rate_limited" code.
pub(crate) fn respond_err_retry(msg: &str, code: &str, retry_after: &str) -> u64 {
    let body = serde_json::to_vec(&Envelope::<()> {
        ok: false,
        data: None,
        error: msg.to_string(),
        code: code.to_string(),
        retry_after: retry_after.to_string(),
    })
    .unwrap_or_else(|_| br#"{"ok":false,"error":"failed to encode error response"}"#.to_vec());
    let (ptr, len) = write_bytes(&body);
    pack(ptr, len)
}