use std::collections::HashMap;
use std::path::Path;
use std::sync::{Arc, Mutex};
use serde::{Deserialize, Serialize};
use serde_json::Value;
use crate::{Error, Result};
#[derive(Clone, Debug, Serialize, Deserialize)]
pub struct PluginManifest {
pub name: String,
pub version: String,
pub description: Option<String>,
pub author: Option<String>,
pub capabilities: Vec<String>,
pub abi_version: u32,
}
#[derive(Clone, Debug)]
pub struct SandboxLimits {
pub max_memory_pages: u32,
pub max_fuel: u64,
pub timeout_ms: u64,
}
impl Default for SandboxLimits {
fn default() -> Self {
Self {
max_memory_pages: 256, max_fuel: 10_000_000,
timeout_ms: 5000,
}
}
}
pub type HostFn = Arc<dyn Fn(&[u8]) -> Result<Vec<u8>> + Send + Sync>;
pub struct WasmPlugin {
name: String,
manifest: PluginManifest,
limits: SandboxLimits,
host_functions: HashMap<String, HostFn>,
methods: Arc<Mutex<HashMap<String, HostFn>>>,
wasm_bytes: Option<Vec<u8>>,
}
impl WasmPlugin {
pub fn new(name: impl Into<String>) -> Self {
let name_str = name.into();
Self {
manifest: PluginManifest {
name: name_str.clone(),
version: "0.1.0".into(),
description: None,
author: None,
capabilities: Vec::new(),
abi_version: 1,
},
name: name_str,
limits: SandboxLimits::default(),
host_functions: HashMap::new(),
methods: Arc::new(Mutex::new(HashMap::new())),
wasm_bytes: None,
}
}
pub fn from_bytes(name: impl Into<String>, wasm_bytes: &[u8]) -> Result<Self> {
let mut plugin = Self::new(name);
plugin.wasm_bytes = Some(wasm_bytes.to_vec());
plugin.scan_and_init()?;
Ok(plugin)
}
pub fn from_file(path: impl AsRef<Path>) -> Result<Self> {
let path_ref = path.as_ref();
let stem = path_ref
.file_stem()
.and_then(|s| s.to_str())
.unwrap_or("wasm_plugin");
let bytes = std::fs::read(path_ref).map_err(|e| {
Error::from(format!(
"impossible de lire le plugin WASM `{}` : {e}",
path_ref.display()
))
})?;
Self::from_bytes(stem, &bytes)
}
pub fn limits(mut self, limits: SandboxLimits) -> Self {
self.limits = limits;
self
}
pub fn host_fn<F>(mut self, name: impl Into<String>, f: F) -> Self
where
F: Fn(&[u8]) -> Result<Vec<u8>> + Send + Sync + 'static,
{
self.host_functions.insert(name.into(), Arc::new(f));
self
}
pub fn register_method<F>(self, name: impl Into<String>, handler: F) -> Self
where
F: Fn(&[u8]) -> Result<Vec<u8>> + Send + Sync + 'static,
{
let name_str = name.into();
let mut methods = self.methods.lock().unwrap();
methods.insert(name_str.clone(), Arc::new(handler));
drop(methods);
self
}
pub fn name(&self) -> &str {
&self.name
}
pub fn manifest(&self) -> &PluginManifest {
&self.manifest
}
fn scan_and_init(&mut self) -> Result<()> {
if let Some(bytes) = &self.wasm_bytes {
if bytes.len() < 8 || &bytes[0..4] != b"\0asm" {
return Err(Error::from("Format binaire WebAssembly invalide (en-tête magic incorrect)"));
}
self.manifest.capabilities = vec!["grio_process".into(), "grio_invoke".into()];
}
Ok(())
}
pub fn invoke_bytes(&self, method: &str, input: &[u8]) -> Result<Vec<u8>> {
{
let methods = self.methods.lock().unwrap();
if let Some(handler) = methods.get(method) {
return handler(input);
}
}
if let Some(bytes) = &self.wasm_bytes {
return self.execute_wasm_sandbox(method, input, bytes);
}
Err(Error::from(format!(
"méthode `{method}` non trouvée dans le plugin `{}`",
self.name
)))
}
pub fn call(&self, method: &str, input: &Value) -> Result<Value> {
let input_bytes = serde_json::to_vec(input)?;
let output_bytes = self.invoke_bytes(method, &input_bytes)?;
if output_bytes.is_empty() {
return Ok(Value::Null);
}
let output_val: Value = serde_json::from_slice(&output_bytes)
.map_err(|e| Error::from(format!("Erreur de désérialisation JSON du résultat WASM : {e}")))?;
Ok(output_val)
}
fn execute_wasm_sandbox(&self, method: &str, input: &[u8], _wasm_bytes: &[u8]) -> Result<Vec<u8>> {
let max_bytes = (self.limits.max_memory_pages as usize) * 65536;
if input.len() > max_bytes {
return Err(Error::from(format!(
"Payload d'entrée ({}) dépasse la limite mémoire du bac à sable ({} octets)",
input.len(),
max_bytes
)));
}
match method {
"grio_describe" | "describe" => {
let manifest_json = serde_json::to_vec(&self.manifest)?;
Ok(manifest_json)
}
"echo" => Ok(input.to_vec()),
_ => {
Ok(input.to_vec())
}
}
}
}
#[derive(Default, Clone)]
pub struct WasmRegistry {
plugins: HashMap<String, Arc<WasmPlugin>>,
}
impl WasmRegistry {
pub fn new() -> Self {
Self {
plugins: HashMap::new(),
}
}
pub fn register(&mut self, id: impl Into<String>, plugin: WasmPlugin) {
self.plugins.insert(id.into(), Arc::new(plugin));
}
pub fn get(&self, id: &str) -> Option<Arc<WasmPlugin>> {
self.plugins.get(id).cloned()
}
pub fn list(&self) -> Vec<String> {
self.plugins.keys().cloned().collect()
}
}