roneocratesroneo-plugin-sdksrclib.rs
0518da6beb3fd562b82c5b5c2798b72e0d1591b2- //! Lightweight SDK for writing standalone WebAssembly (`.wasm`) plugins for Roneo.
- //!
- //! Compile any plugin crate with:
- //! ```sh
- //! cargo build --release --target wasm32-unknown-unknown
- //! ```
- //! and load the resulting `.wasm` file via `roneo copy --plugin my_plugin.wasm ...`
- //! or `_roneo_plugins: [path/to/my_plugin.wasm]` in `copier.yml` / `roneo.yml`.
- use indexmap::IndexMap;
- use serde::{Deserialize, Serialize};
- use serde_json::{Map as JsonMap, Value as JsonValue};
- /// Manifest describing the capabilities a WASM plugin exports to Roneo.
- #[derive(Debug, Clone, Default, Serialize, Deserialize)]
- pub struct PluginManifest {
- pub name: String,
- #[serde(default)]
- pub strict_undefined: bool,
- #[serde(default)]
- pub globals: IndexMap<String, JsonValue>,
- #[serde(default)]
- pub filters: Vec<String>,
- #[serde(default)]
- pub functions: Vec<String>,
- #[serde(default)]
- pub tests: Vec<String>,
- #[serde(default)]
- pub has_context_hook: bool,
- /// Optional context keys forwarded on filter/function/test calls.
- #[serde(default)]
- pub context_keys: Vec<String>,
- /// Optional template files read by the host and passed to `init()` (zero FS access in WASM).
- #[serde(default)]
- pub template_files: Vec<String>,
- }
- /// Host initialization payload delivered to `RoneoPlugin::init`.
- #[derive(Debug, Clone, Default, Deserialize)]
- pub struct InitPayload {
- #[serde(default)]
- pub template_files: IndexMap<String, String>,
- #[serde(default)]
- pub recorded_answers: JsonValue,
- #[serde(default)]
- pub dst_path: String,
- #[serde(default)]
- pub template_root: String,
- }
- /// Request delivered to `RoneoPlugin::call`.
- #[derive(Debug, Clone, Deserialize)]
- pub struct CallRequest {
- pub kind: String,
- pub name: String,
- #[serde(default)]
- pub args: Vec<JsonValue>,
- #[serde(default)]
- pub kwargs: JsonMap<String, JsonValue>,
- #[serde(default)]
- pub context: JsonMap<String, JsonValue>,
- #[serde(default)]
- pub phase: String,
- }
- #[derive(Debug, Serialize)]
- #[serde(rename_all = "lowercase")]
- pub enum CallResponse {
- Ok(JsonValue),
- Err(String),
- }
- /// Trait implemented by external WASM plugins.
- pub trait RoneoPlugin: Default + Send + 'static {
- fn manifest(&self) -> PluginManifest;
- fn init(&mut self, _payload: InitPayload) -> Result<(), String> {
- Ok(())
- }
- fn call(&self, req: CallRequest) -> Result<JsonValue, String>;
- }
- #[doc(hidden)]
- pub mod abi {
- use super::{CallRequest, CallResponse, InitPayload, RoneoPlugin};
- use serde_json::Value as JsonValue;
- pub fn pack_bytes(bytes: Vec<u8>) -> u64 {
- let boxed = bytes.into_boxed_slice();
- let len = boxed.len() as u64;
- let ptr = Box::into_raw(boxed).cast::<u8>() as usize as u64;
- (ptr << 32) | len
- }
- /// # Safety
- /// Caller (the WASM host) must pass a valid pointer/length pair allocated via `roneo_alloc`.
- pub unsafe fn read_slice(ptr: u32, len: u32) -> &'static [u8] {
- unsafe { std::slice::from_raw_parts(ptr as usize as *const u8, len as usize) }
- }
- #[allow(clippy::cast_possible_truncation)]
- pub fn alloc(size: u32) -> u32 {
- let mut buf = Vec::<u8>::with_capacity(size as usize);
- let ptr = buf.as_mut_ptr() as usize as u32;
- std::mem::forget(buf);
- ptr
- }
- #[allow(clippy::same_length_and_capacity)]
- pub fn dealloc(ptr: u32, size: u32) {
- if ptr == 0 || size == 0 {
- return;
- }
- unsafe {
- let _ = Vec::from_raw_parts(ptr as usize as *mut u8, size as usize, size as usize);
- }
- }
- pub fn dispatch_manifest<P: RoneoPlugin>(plugin: &P) -> u64 {
- let bytes = serde_json::to_vec(&plugin.manifest()).unwrap_or_default();
- pack_bytes(bytes)
- }
- /// # Safety
- /// `ptr` and `len` must reference valid guest memory.
- pub unsafe fn dispatch_init<P: RoneoPlugin>(plugin: &mut P, ptr: u32, len: u32) -> u64 {
- let slice = unsafe { read_slice(ptr, len) };
- let resp = match serde_json::from_slice::<InitPayload>(slice) {
- Ok(payload) => match plugin.init(payload) {
- Ok(()) => CallResponse::Ok(JsonValue::Null),
- Err(msg) => CallResponse::Err(msg),
- },
- Err(e) => CallResponse::Err(format!("Invalid init payload: {e}")),
- };
- pack_bytes(serde_json::to_vec(&resp).unwrap_or_default())
- }
- /// # Safety
- /// `ptr` and `len` must reference valid guest memory.
- pub unsafe fn dispatch_call<P: RoneoPlugin>(plugin: &P, ptr: u32, len: u32) -> u64 {
- let slice = unsafe { read_slice(ptr, len) };
- let resp = match serde_json::from_slice::<CallRequest>(slice) {
- Ok(req) => match plugin.call(req) {
- Ok(val) => CallResponse::Ok(val),
- Err(msg) => CallResponse::Err(msg),
- },
- Err(e) => CallResponse::Err(format!("Invalid call payload: {e}")),
- };
- pack_bytes(serde_json::to_vec(&resp).unwrap_or_default())
- }
- }
- /// Export all required Roneo WASM ABI entry points for a `RoneoPlugin` implementation.
- #[macro_export]
- macro_rules! export_plugin {
- ($plugin_ty:ty) => {
- fn __roneo_plugin_cell() -> &'static ::std::sync::Mutex<$plugin_ty> {
- static CELL: ::std::sync::OnceLock<::std::sync::Mutex<$plugin_ty>> =
- ::std::sync::OnceLock::new();
- CELL.get_or_init(|| ::std::sync::Mutex::new(<$plugin_ty as Default>::default()))
- }
- #[unsafe(no_mangle)]
- pub extern "C" fn roneo_alloc(size: u32) -> u32 {
- $crate::abi::alloc(size)
- }
- #[unsafe(no_mangle)]
- pub extern "C" fn roneo_dealloc(ptr: u32, size: u32) {
- $crate::abi::dealloc(ptr, size);
- }
- #[unsafe(no_mangle)]
- pub extern "C" fn roneo_manifest() -> u64 {
- let guard = __roneo_plugin_cell().lock().expect("plugin lock");
- $crate::abi::dispatch_manifest(&*guard)
- }
- #[unsafe(no_mangle)]
- pub extern "C" fn roneo_init(ptr: u32, len: u32) -> u64 {
- let mut guard = __roneo_plugin_cell().lock().expect("plugin lock");
- unsafe { $crate::abi::dispatch_init(&mut *guard, ptr, len) }
- }
- #[unsafe(no_mangle)]
- pub extern "C" fn roneo_call(ptr: u32, len: u32) -> u64 {
- let guard = __roneo_plugin_cell().lock().expect("plugin lock");
- unsafe { $crate::abi::dispatch_call(&*guard, ptr, len) }
- }
- };
- }