forgeFRENParcourir les dépôts

roneocratesroneo-plugin-sdksrclib.rs

0518da6beb3fd562b82c5b5c2798b72e0d1591b2

At commit 0518da6

192 lines · 6.4 KiBRustRaw
  1. //! Lightweight SDK for writing standalone WebAssembly (`.wasm`) plugins for Roneo.
  2. //!
  3. //! Compile any plugin crate with:
  4. //! ```sh
  5. //! cargo build --release --target wasm32-unknown-unknown
  6. //! ```
  7. //! and load the resulting `.wasm` file via `roneo copy --plugin my_plugin.wasm ...`
  8. //! or `_roneo_plugins: [path/to/my_plugin.wasm]` in `copier.yml` / `roneo.yml`.
  9. use indexmap::IndexMap;
  10. use serde::{Deserialize, Serialize};
  11. use serde_json::{Map as JsonMap, Value as JsonValue};
  12. /// Manifest describing the capabilities a WASM plugin exports to Roneo.
  13. #[derive(Debug, Clone, Default, Serialize, Deserialize)]
  14. pub struct PluginManifest {
  15. pub name: String,
  16. #[serde(default)]
  17. pub strict_undefined: bool,
  18. #[serde(default)]
  19. pub globals: IndexMap<String, JsonValue>,
  20. #[serde(default)]
  21. pub filters: Vec<String>,
  22. #[serde(default)]
  23. pub functions: Vec<String>,
  24. #[serde(default)]
  25. pub tests: Vec<String>,
  26. #[serde(default)]
  27. pub has_context_hook: bool,
  28. /// Optional context keys forwarded on filter/function/test calls.
  29. #[serde(default)]
  30. pub context_keys: Vec<String>,
  31. /// Optional template files read by the host and passed to `init()` (zero FS access in WASM).
  32. #[serde(default)]
  33. pub template_files: Vec<String>,
  34. }
  35. /// Host initialization payload delivered to `RoneoPlugin::init`.
  36. #[derive(Debug, Clone, Default, Deserialize)]
  37. pub struct InitPayload {
  38. #[serde(default)]
  39. pub template_files: IndexMap<String, String>,
  40. #[serde(default)]
  41. pub recorded_answers: JsonValue,
  42. #[serde(default)]
  43. pub dst_path: String,
  44. #[serde(default)]
  45. pub template_root: String,
  46. }
  47. /// Request delivered to `RoneoPlugin::call`.
  48. #[derive(Debug, Clone, Deserialize)]
  49. pub struct CallRequest {
  50. pub kind: String,
  51. pub name: String,
  52. #[serde(default)]
  53. pub args: Vec<JsonValue>,
  54. #[serde(default)]
  55. pub kwargs: JsonMap<String, JsonValue>,
  56. #[serde(default)]
  57. pub context: JsonMap<String, JsonValue>,
  58. #[serde(default)]
  59. pub phase: String,
  60. }
  61. #[derive(Debug, Serialize)]
  62. #[serde(rename_all = "lowercase")]
  63. pub enum CallResponse {
  64. Ok(JsonValue),
  65. Err(String),
  66. }
  67. /// Trait implemented by external WASM plugins.
  68. pub trait RoneoPlugin: Default + Send + 'static {
  69. fn manifest(&self) -> PluginManifest;
  70. fn init(&mut self, _payload: InitPayload) -> Result<(), String> {
  71. Ok(())
  72. }
  73. fn call(&self, req: CallRequest) -> Result<JsonValue, String>;
  74. }
  75. #[doc(hidden)]
  76. pub mod abi {
  77. use super::{CallRequest, CallResponse, InitPayload, RoneoPlugin};
  78. use serde_json::Value as JsonValue;
  79. pub fn pack_bytes(bytes: Vec<u8>) -> u64 {
  80. let boxed = bytes.into_boxed_slice();
  81. let len = boxed.len() as u64;
  82. let ptr = Box::into_raw(boxed).cast::<u8>() as usize as u64;
  83. (ptr << 32) | len
  84. }
  85. /// # Safety
  86. /// Caller (the WASM host) must pass a valid pointer/length pair allocated via `roneo_alloc`.
  87. pub unsafe fn read_slice(ptr: u32, len: u32) -> &'static [u8] {
  88. unsafe { std::slice::from_raw_parts(ptr as usize as *const u8, len as usize) }
  89. }
  90. #[allow(clippy::cast_possible_truncation)]
  91. pub fn alloc(size: u32) -> u32 {
  92. let mut buf = Vec::<u8>::with_capacity(size as usize);
  93. let ptr = buf.as_mut_ptr() as usize as u32;
  94. std::mem::forget(buf);
  95. ptr
  96. }
  97. #[allow(clippy::same_length_and_capacity)]
  98. pub fn dealloc(ptr: u32, size: u32) {
  99. if ptr == 0 || size == 0 {
  100. return;
  101. }
  102. unsafe {
  103. let _ = Vec::from_raw_parts(ptr as usize as *mut u8, size as usize, size as usize);
  104. }
  105. }
  106. pub fn dispatch_manifest<P: RoneoPlugin>(plugin: &P) -> u64 {
  107. let bytes = serde_json::to_vec(&plugin.manifest()).unwrap_or_default();
  108. pack_bytes(bytes)
  109. }
  110. /// # Safety
  111. /// `ptr` and `len` must reference valid guest memory.
  112. pub unsafe fn dispatch_init<P: RoneoPlugin>(plugin: &mut P, ptr: u32, len: u32) -> u64 {
  113. let slice = unsafe { read_slice(ptr, len) };
  114. let resp = match serde_json::from_slice::<InitPayload>(slice) {
  115. Ok(payload) => match plugin.init(payload) {
  116. Ok(()) => CallResponse::Ok(JsonValue::Null),
  117. Err(msg) => CallResponse::Err(msg),
  118. },
  119. Err(e) => CallResponse::Err(format!("Invalid init payload: {e}")),
  120. };
  121. pack_bytes(serde_json::to_vec(&resp).unwrap_or_default())
  122. }
  123. /// # Safety
  124. /// `ptr` and `len` must reference valid guest memory.
  125. pub unsafe fn dispatch_call<P: RoneoPlugin>(plugin: &P, ptr: u32, len: u32) -> u64 {
  126. let slice = unsafe { read_slice(ptr, len) };
  127. let resp = match serde_json::from_slice::<CallRequest>(slice) {
  128. Ok(req) => match plugin.call(req) {
  129. Ok(val) => CallResponse::Ok(val),
  130. Err(msg) => CallResponse::Err(msg),
  131. },
  132. Err(e) => CallResponse::Err(format!("Invalid call payload: {e}")),
  133. };
  134. pack_bytes(serde_json::to_vec(&resp).unwrap_or_default())
  135. }
  136. }
  137. /// Export all required Roneo WASM ABI entry points for a `RoneoPlugin` implementation.
  138. #[macro_export]
  139. macro_rules! export_plugin {
  140. ($plugin_ty:ty) => {
  141. fn __roneo_plugin_cell() -> &'static ::std::sync::Mutex<$plugin_ty> {
  142. static CELL: ::std::sync::OnceLock<::std::sync::Mutex<$plugin_ty>> =
  143. ::std::sync::OnceLock::new();
  144. CELL.get_or_init(|| ::std::sync::Mutex::new(<$plugin_ty as Default>::default()))
  145. }
  146. #[unsafe(no_mangle)]
  147. pub extern "C" fn roneo_alloc(size: u32) -> u32 {
  148. $crate::abi::alloc(size)
  149. }
  150. #[unsafe(no_mangle)]
  151. pub extern "C" fn roneo_dealloc(ptr: u32, size: u32) {
  152. $crate::abi::dealloc(ptr, size);
  153. }
  154. #[unsafe(no_mangle)]
  155. pub extern "C" fn roneo_manifest() -> u64 {
  156. let guard = __roneo_plugin_cell().lock().expect("plugin lock");
  157. $crate::abi::dispatch_manifest(&*guard)
  158. }
  159. #[unsafe(no_mangle)]
  160. pub extern "C" fn roneo_init(ptr: u32, len: u32) -> u64 {
  161. let mut guard = __roneo_plugin_cell().lock().expect("plugin lock");
  162. unsafe { $crate::abi::dispatch_init(&mut *guard, ptr, len) }
  163. }
  164. #[unsafe(no_mangle)]
  165. pub extern "C" fn roneo_call(ptr: u32, len: u32) -> u64 {
  166. let guard = __roneo_plugin_cell().lock().expect("plugin lock");
  167. unsafe { $crate::abi::dispatch_call(&*guard, ptr, len) }
  168. }
  169. };
  170. }