roneocratesroneo-coresrcplugin.rs
0518da6beb3fd562b82c5b5c2798b72e0d1591b2- use std::fs;
- use std::path::{Path, PathBuf};
- use std::sync::{Arc, Mutex, RwLock};
- use indexmap::IndexMap;
- use minijinja::value::{Kwargs, Rest, Serde, Value as MjValue};
- use minijinja::{
- Environment, Error as MjError, ErrorKind as MjErrorKind, State, UndefinedBehavior,
- };
- use serde::{Deserialize, Serialize};
- use serde_json::{Map as JsonMap, Value as JsonValue};
- use wasmi::{
- Config, Engine, Instance, Linker, Memory, Module, Store, StoreLimits, StoreLimitsBuilder,
- TypedFunc,
- };
- /// Maximum linear memory allowed per sandboxed WASM plugin instance (64 MiB).
- const WASM_MAX_MEMORY_BYTES: usize = 64 * 1024 * 1024;
- /// Maximum single IPC payload accepted back from a WASM guest (16 MiB).
- const WASM_MAX_PAYLOAD_BYTES: usize = 16 * 1024 * 1024;
- /// Fuel budget per guest call (~100M instructions; prevents infinite loops).
- const WASM_CALL_FUEL_BUDGET: u64 = 100_000_000;
- use crate::error::{Result, RoneoError};
- pub type TemplateFileReader = Arc<dyn Fn(&str) -> Option<String> + Send + Sync>;
- /// Host metadata passed to extensions during registration (works for both disk and in-memory `gix` trees).
- #[derive(Clone)]
- pub struct ExtensionInitContext {
- pub template_root: PathBuf,
- pub dst_path: PathBuf,
- pub file_reader: TemplateFileReader,
- }
- impl std::fmt::Debug for ExtensionInitContext {
- fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
- f.debug_struct("ExtensionInitContext")
- .field("template_root", &self.template_root)
- .field("dst_path", &self.dst_path)
- .finish_non_exhaustive()
- }
- }
- /// Native or WASM template extension (equivalent to Copier's Jinja `Extension` + `ContextHook`).
- pub trait Extension: Send + Sync {
- fn name(&self) -> &str;
- /// Register custom filters, global functions/values, tests, or environment tweaks on `MiniJinja`.
- fn register(&self, env: &mut Environment<'static>, init: &ExtensionInitContext) -> Result<()>;
- /// Transform or validate the template context (`phase` is `"prompt"` or `"render"`).
- fn hook_context(&self, phase: &str, ctx: &mut IndexMap<String, JsonValue>) -> Result<()> {
- let _ = (phase, ctx);
- Ok(())
- }
- }
- /// Collection of active extensions (native Rust and/or sandboxed WASM).
- #[derive(Clone, Default)]
- pub struct ExtensionRegistry {
- extensions: Vec<Arc<dyn Extension>>,
- }
- impl std::fmt::Debug for ExtensionRegistry {
- fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
- let names: Vec<&str> = self.extensions.iter().map(|e| e.name()).collect();
- f.debug_struct("ExtensionRegistry")
- .field("extensions", &names)
- .finish()
- }
- }
- impl ExtensionRegistry {
- pub fn new() -> Self {
- Self::default()
- }
- pub fn add(&mut self, ext: Arc<dyn Extension>) {
- self.extensions.push(ext);
- }
- pub fn add_wasm_file(&mut self, path: impl AsRef<Path>) -> Result<()> {
- let wasm_ext = WasmExtension::from_file(path.as_ref())?;
- self.extensions.push(Arc::new(wasm_ext));
- Ok(())
- }
- pub fn add_wasm_bytes(&mut self, bytes: &[u8]) -> Result<()> {
- let wasm_ext = WasmExtension::from_bytes(bytes)?;
- self.extensions.push(Arc::new(wasm_ext));
- Ok(())
- }
- pub fn is_empty(&self) -> bool {
- self.extensions.is_empty()
- }
- pub fn names(&self) -> Vec<&str> {
- self.extensions.iter().map(|e| e.name()).collect()
- }
- pub fn register_all(
- &self,
- env: &mut Environment<'static>,
- init: &ExtensionInitContext,
- ) -> Result<()> {
- for ext in &self.extensions {
- ext.register(env, init)?;
- }
- Ok(())
- }
- pub fn run_context_hooks(
- &self,
- phase: &str,
- ctx: &mut IndexMap<String, JsonValue>,
- ) -> Result<()> {
- for ext in &self.extensions {
- ext.hook_context(phase, ctx)?;
- }
- Ok(())
- }
- }
- // ---------------------------------------------------------------------------
- // Sandboxed WebAssembly plugin runtime (`wasmi`) with lock-free parallel pool
- // ---------------------------------------------------------------------------
- /// Manifest returned by a WASM plugin's `roneo_manifest()` export.
- #[derive(Debug, Clone, Default, Serialize, Deserialize)]
- pub struct WasmPluginManifest {
- 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 list of template context keys to forward on filter/function calls.
- #[serde(default)]
- pub context_keys: Vec<String>,
- /// Optional relative paths inside `template_root` that the host reads and
- /// passes to `roneo_init` (keeps the WASM guest 100% sandboxed with zero FS access).
- #[serde(default)]
- pub template_files: Vec<String>,
- }
- #[derive(Debug, Clone, Serialize)]
- struct WasmInitPayload {
- template_files: IndexMap<String, String>,
- recorded_answers: JsonValue,
- dst_path: String,
- template_root: String,
- }
- #[derive(Debug, Serialize)]
- struct WasmCallRequest<'a> {
- kind: &'a str,
- name: &'a str,
- args: Vec<JsonValue>,
- kwargs: JsonMap<String, JsonValue>,
- context: JsonMap<String, JsonValue>,
- phase: &'a str,
- }
- #[derive(Debug, Deserialize)]
- #[serde(rename_all = "lowercase")]
- enum WasmCallResponse {
- Ok(JsonValue),
- Err(String),
- }
- struct WasmRuntime {
- store: Store<StoreLimits>,
- memory: Memory,
- alloc: TypedFunc<u32, u32>,
- dealloc: Option<TypedFunc<(u32, u32), ()>>,
- call_fn: TypedFunc<(u32, u32), u64>,
- init_fn: Option<TypedFunc<(u32, u32), u64>>,
- initialized: bool,
- }
- impl WasmRuntime {
- fn instantiate_from_module(engine: &Engine, module: &Module) -> Result<(Self, Instance)> {
- let limits = StoreLimitsBuilder::new()
- .memory_size(WASM_MAX_MEMORY_BYTES)
- .build();
- let mut store = Store::new(engine, limits);
- store.limiter(|lim| lim);
- let _ = store.set_fuel(WASM_CALL_FUEL_BUDGET);
- let linker = Linker::<StoreLimits>::new(engine);
- let instance: Instance = linker
- .instantiate_and_start(&mut store, module)
- .map_err(|e| RoneoError::Plugin(format!("Failed to instantiate WASM module: {e}")))?;
- let memory = instance
- .get_memory(&store, "memory")
- .ok_or_else(|| RoneoError::Plugin("WASM plugin missing `memory` export".into()))?;
- let alloc = instance
- .get_typed_func::<u32, u32>(&store, "roneo_alloc")
- .map_err(|e| RoneoError::Plugin(format!("WASM plugin missing `roneo_alloc`: {e}")))?;
- let dealloc = instance
- .get_typed_func::<(u32, u32), ()>(&store, "roneo_dealloc")
- .ok();
- let call_fn = instance
- .get_typed_func::<(u32, u32), u64>(&store, "roneo_call")
- .map_err(|e| RoneoError::Plugin(format!("WASM plugin missing `roneo_call`: {e}")))?;
- let init_fn = instance
- .get_typed_func::<(u32, u32), u64>(&store, "roneo_init")
- .ok();
- Ok((
- Self {
- store,
- memory,
- alloc,
- dealloc,
- call_fn,
- init_fn,
- initialized: false,
- },
- instance,
- ))
- }
- fn read_manifest(&mut self, instance: Instance) -> Result<WasmPluginManifest> {
- let _ = self.store.set_fuel(WASM_CALL_FUEL_BUDGET);
- let manifest_fn = instance
- .get_typed_func::<(), u64>(&self.store, "roneo_manifest")
- .map_err(|e| {
- RoneoError::Plugin(format!("WASM plugin missing `roneo_manifest`: {e}"))
- })?;
- let packed = manifest_fn
- .call(&mut self.store, ())
- .map_err(|e| RoneoError::Plugin(format!("WASM `roneo_manifest` trapped: {e}")))?;
- let manifest_bytes = read_packed(&self.store, self.memory, packed)?;
- serde_json::from_slice(&manifest_bytes).map_err(|e| {
- RoneoError::Plugin(format!("Invalid JSON from WASM `roneo_manifest`: {e}"))
- })
- }
- fn write_guest(&mut self, bytes: &[u8]) -> Result<(u32, u32)> {
- let len = u32::try_from(bytes.len())
- .map_err(|_| RoneoError::Plugin("Payload exceeds 4 GiB WASM address space".into()))?;
- let ptr = self
- .alloc
- .call(&mut self.store, len)
- .map_err(|e| RoneoError::Plugin(format!("WASM `roneo_alloc` failed: {e}")))?;
- self.memory
- .write(&mut self.store, ptr as usize, bytes)
- .map_err(|e| RoneoError::Plugin(format!("WASM memory write failed: {e}")))?;
- Ok((ptr, len))
- }
- fn free_guest(&mut self, ptr: u32, len: u32) {
- if let Some(dealloc) = self.dealloc {
- let _ = dealloc.call(&mut self.store, (ptr, len));
- }
- }
- fn send_init(&mut self, payload_bytes: &[u8]) -> Result<()> {
- let Some(init_fn) = self.init_fn else {
- self.initialized = true;
- return Ok(());
- };
- let _ = self.store.set_fuel(WASM_CALL_FUEL_BUDGET);
- let (ptr, len) = self.write_guest(payload_bytes)?;
- let packed = init_fn
- .call(&mut self.store, (ptr, len))
- .map_err(|e| RoneoError::Plugin(format!("WASM `roneo_init` trapped: {e}")))?;
- self.free_guest(ptr, len);
- if packed != 0 {
- let resp_bytes = read_packed(&self.store, self.memory, packed)?;
- let (out_ptr, out_len) = unpack_ptr_len(packed);
- self.free_guest(out_ptr, out_len);
- let resp: WasmCallResponse = serde_json::from_slice(&resp_bytes)?;
- if let WasmCallResponse::Err(msg) = resp {
- return Err(RoneoError::Plugin(msg));
- }
- }
- self.initialized = true;
- Ok(())
- }
- fn invoke(&mut self, req: &WasmCallRequest<'_>) -> Result<JsonValue> {
- let _ = self.store.set_fuel(WASM_CALL_FUEL_BUDGET);
- let bytes = serde_json::to_vec(req)?;
- let (ptr, len) = self.write_guest(&bytes)?;
- let packed = self
- .call_fn
- .call(&mut self.store, (ptr, len))
- .map_err(|e| RoneoError::Plugin(format!("WASM `roneo_call` trapped: {e}")))?;
- self.free_guest(ptr, len);
- let resp_bytes = read_packed(&self.store, self.memory, packed)?;
- let (out_ptr, out_len) = unpack_ptr_len(packed);
- self.free_guest(out_ptr, out_len);
- let resp: WasmCallResponse = serde_json::from_slice(&resp_bytes).map_err(|e| {
- RoneoError::Plugin(format!("Invalid JSON response from WASM plugin: {e}"))
- })?;
- match resp {
- WasmCallResponse::Ok(val) => Ok(val),
- WasmCallResponse::Err(msg) => Err(RoneoError::Plugin(msg)),
- }
- }
- }
- /// Thread-safe pool of initialized `WasmRuntime` instances so parallel `rayon` threads can
- /// execute WASM filters simultaneously with zero contention during guest execution.
- struct WasmPool {
- engine: Engine,
- module: Module,
- init_bytes: RwLock<Option<Vec<u8>>>,
- instances: Mutex<Vec<WasmRuntime>>,
- }
- impl WasmPool {
- fn new(wasm_bytes: &[u8]) -> Result<(Self, WasmPluginManifest)> {
- let mut cfg = Config::default();
- cfg.consume_fuel(true);
- let engine = Engine::new(&cfg);
- let module = Module::new(&engine, wasm_bytes)
- .map_err(|e| RoneoError::Plugin(format!("Invalid WASM module: {e}")))?;
- let (mut rt, instance) = WasmRuntime::instantiate_from_module(&engine, &module)?;
- let manifest = rt.read_manifest(instance)?;
- Ok((
- Self {
- engine,
- module,
- init_bytes: RwLock::new(None),
- instances: Mutex::new(vec![rt]),
- },
- manifest,
- ))
- }
- fn set_init_payload(&self, payload: &WasmInitPayload) -> Result<()> {
- let bytes = serde_json::to_vec(payload)?;
- {
- let mut guard = self
- .init_bytes
- .write()
- .map_err(|_| RoneoError::Plugin("WASM init lock poisoned".into()))?;
- *guard = Some(bytes.clone());
- }
- // Re-initialize any pooled instances already created.
- let mut pool = self
- .instances
- .lock()
- .map_err(|_| RoneoError::Plugin("WASM pool lock poisoned".into()))?;
- for rt in pool.iter_mut() {
- rt.send_init(&bytes)?;
- }
- Ok(())
- }
- fn call(&self, req: &WasmCallRequest<'_>) -> Result<JsonValue> {
- let mut rt = {
- let mut pool = self
- .instances
- .lock()
- .map_err(|_| RoneoError::Plugin("WASM pool lock poisoned".into()))?;
- pool.pop()
- };
- let mut runtime = if let Some(existing) = rt.take() {
- existing
- } else {
- let (mut fresh, _) = WasmRuntime::instantiate_from_module(&self.engine, &self.module)?;
- if let Ok(guard) = self.init_bytes.read()
- && let Some(bytes) = guard.as_deref()
- {
- fresh.send_init(bytes)?;
- }
- fresh
- };
- if !runtime.initialized
- && let Ok(guard) = self.init_bytes.read()
- && let Some(bytes) = guard.as_deref()
- {
- runtime.send_init(bytes)?;
- }
- let res = runtime.invoke(req);
- if let Ok(mut pool) = self.instances.lock() {
- pool.push(runtime);
- }
- res
- }
- }
- fn unpack_ptr_len(packed: u64) -> (u32, u32) {
- #[allow(clippy::cast_possible_truncation)]
- let ptr = (packed >> 32) as u32;
- #[allow(clippy::cast_possible_truncation)]
- let len = (packed & 0xFFFF_FFFF) as u32;
- (ptr, len)
- }
- fn read_packed(store: &Store<StoreLimits>, memory: Memory, packed: u64) -> Result<Vec<u8>> {
- let (ptr, len) = unpack_ptr_len(packed);
- let len_usize = len as usize;
- let ptr_usize = ptr as usize;
- if len_usize > WASM_MAX_PAYLOAD_BYTES {
- return Err(RoneoError::Plugin(format!(
- "WASM guest payload ({len_usize} bytes) exceeds maximum allowed ({WASM_MAX_PAYLOAD_BYTES} bytes)"
- )));
- }
- let mem_size = memory.data_size(store);
- if ptr_usize
- .checked_add(len_usize)
- .is_none_or(|end| end > mem_size)
- {
- return Err(RoneoError::Plugin(
- "WASM guest returned out-of-bounds memory slice".into(),
- ));
- }
- let mut buf = vec![0u8; len_usize];
- memory
- .read(store, ptr_usize, &mut buf)
- .map_err(|e| RoneoError::Plugin(format!("WASM memory read failed: {e}")))?;
- Ok(buf)
- }
- /// A sandboxed WebAssembly plugin loaded into `roneo-core` via `wasmi`.
- pub struct WasmExtension {
- manifest: WasmPluginManifest,
- pool: Arc<WasmPool>,
- }
- impl WasmExtension {
- pub fn from_file(path: &Path) -> Result<Self> {
- let bytes = fs::read(path).map_err(|e| RoneoError::io(path, e))?;
- Self::from_bytes(&bytes)
- }
- pub fn from_bytes(wasm_bytes: &[u8]) -> Result<Self> {
- let (pool, manifest) = WasmPool::new(wasm_bytes)?;
- Ok(Self {
- manifest,
- pool: Arc::new(pool),
- })
- }
- pub fn manifest(&self) -> &WasmPluginManifest {
- &self.manifest
- }
- }
- impl Extension for WasmExtension {
- fn name(&self) -> &str {
- &self.manifest.name
- }
- fn register(&self, env: &mut Environment<'static>, init: &ExtensionInitContext) -> Result<()> {
- if self.manifest.strict_undefined {
- env.set_undefined_behavior(UndefinedBehavior::Strict);
- }
- // Send sandboxed init payload (reading template_files via `file_reader` — zero disk I/O for GitTree!).
- let mut template_files = IndexMap::new();
- for rel in &self.manifest.template_files {
- if let Some(content) = (init.file_reader)(rel) {
- template_files.insert(rel.clone(), content);
- }
- }
- let recorded_answers = load_recorded_answers_json(&init.dst_path);
- let payload = WasmInitPayload {
- template_files,
- recorded_answers,
- dst_path: init.dst_path.to_string_lossy().into_owned(),
- template_root: init.template_root.to_string_lossy().into_owned(),
- };
- self.pool.set_init_payload(&payload)?;
- for (k, v) in &self.manifest.globals {
- env.add_global(k.clone(), MjValue::from(Serde(v)));
- }
- let ctx_keys = Arc::new(self.manifest.context_keys.clone());
- for filter_name in &self.manifest.filters {
- let pool = Arc::clone(&self.pool);
- let fname = filter_name.clone();
- let keys = Arc::clone(&ctx_keys);
- env.add_filter(
- filter_name.clone(),
- move |state: &State<'_, '_>,
- rest: Rest<MjValue>,
- kwargs: Kwargs|
- -> std::result::Result<MjValue, MjError> {
- invoke_wasm_callable(&pool, "filter", &fname, state, &rest.0, &kwargs, &keys)
- },
- );
- }
- for func_name in &self.manifest.functions {
- let pool = Arc::clone(&self.pool);
- let fname = func_name.clone();
- let keys = Arc::clone(&ctx_keys);
- env.add_function(
- func_name.clone(),
- move |state: &State<'_, '_>,
- rest: Rest<MjValue>,
- kwargs: Kwargs|
- -> std::result::Result<MjValue, MjError> {
- invoke_wasm_callable(&pool, "function", &fname, state, &rest.0, &kwargs, &keys)
- },
- );
- }
- for test_name in &self.manifest.tests {
- let pool = Arc::clone(&self.pool);
- let tname = test_name.clone();
- let keys = Arc::clone(&ctx_keys);
- env.add_test(
- test_name.clone(),
- move |state: &State<'_, '_>,
- rest: Rest<MjValue>,
- kwargs: Kwargs|
- -> std::result::Result<bool, MjError> {
- let val = invoke_wasm_callable(
- &pool, "test", &tname, state, &rest.0, &kwargs, &keys,
- )?;
- Ok(val.is_true())
- },
- );
- }
- Ok(())
- }
- fn hook_context(&self, phase: &str, ctx: &mut IndexMap<String, JsonValue>) -> Result<()> {
- if !self.manifest.has_context_hook {
- return Ok(());
- }
- let mut context = JsonMap::with_capacity(ctx.len());
- for (k, v) in ctx.iter() {
- context.insert(k.clone(), v.clone());
- }
- let req = WasmCallRequest {
- kind: "hook_context",
- name: "hook",
- args: Vec::new(),
- kwargs: JsonMap::new(),
- context,
- phase,
- };
- let result = self.pool.call(&req)?;
- if let JsonValue::Object(updates) = result {
- for (k, v) in updates {
- ctx.insert(k, v);
- }
- }
- Ok(())
- }
- }
- fn invoke_wasm_callable(
- pool: &Arc<WasmPool>,
- kind: &str,
- name: &str,
- state: &State<'_, '_>,
- raw_args: &[MjValue],
- raw_kwargs: &Kwargs,
- context_keys: &[String],
- ) -> std::result::Result<MjValue, MjError> {
- let args = raw_args
- .iter()
- .map(|val| {
- serde_json::to_value(val)
- .map_err(|e| MjError::new(MjErrorKind::InvalidOperation, e.to_string()))
- })
- .collect::<std::result::Result<Vec<_>, _>>()?;
- let mut kwargs = JsonMap::new();
- for key in raw_kwargs.args() {
- let val: MjValue = raw_kwargs.get(key)?;
- let jv = serde_json::to_value(&val)
- .map_err(|e| MjError::new(MjErrorKind::InvalidOperation, e.to_string()))?;
- kwargs.insert(key.to_string(), jv);
- }
- let context = extract_state_context(state, context_keys);
- let req = WasmCallRequest {
- kind,
- name,
- args,
- kwargs,
- context,
- phase: "render",
- };
- let val = pool
- .call(&req)
- .map_err(|e| MjError::new(MjErrorKind::InvalidOperation, e.to_string()))?;
- Ok(MjValue::from(Serde(&val)))
- }
- fn extract_state_context(
- state: &State<'_, '_>,
- context_keys: &[String],
- ) -> JsonMap<String, JsonValue> {
- let mut out = JsonMap::new();
- for key in context_keys {
- if let Some(v) = state.lookup(key)
- && !v.is_undefined()
- && let Ok(jv) = serde_json::to_value(&v)
- {
- out.insert(key.clone(), jv);
- }
- }
- out
- }
- /// Read existing `.copier-answers.yml` in `dst_path` to populate `recorded_answers` for plugins.
- pub fn load_recorded_answers_json(dst_path: &Path) -> JsonValue {
- let path = dst_path.join(".copier-answers.yml");
- if !path.is_file() {
- return JsonValue::Object(JsonMap::new());
- }
- let Ok(raw) = fs::read_to_string(&path) else {
- return JsonValue::Object(JsonMap::new());
- };
- match serde_yaml_ng::from_str::<serde_yaml_ng::Value>(&raw) {
- Ok(y) => match serde_json::to_value(y) {
- Ok(JsonValue::Object(map)) if !map.is_empty() => JsonValue::Object(map),
- _ => serde_json::json!({ "_unreadable": true }),
- },
- Err(_) => serde_json::json!({ "_unreadable": true }),
- }
- }