|
| 1 | +use std::{ |
| 2 | + fmt::{Debug, Display}, |
| 3 | + path::Path, |
| 4 | + sync::{Arc, RwLock}, |
| 5 | +}; |
| 6 | + |
| 7 | +use anyhow::Context; |
| 8 | +use liquid_core::{Filter, ParseFilter, Runtime, ValueView}; |
| 9 | +use wasmtime::{Engine, Linker, Module, Store}; |
| 10 | +use wasmtime_wasi::{WasiCtx, WasiCtxBuilder}; |
| 11 | + |
| 12 | +wit_bindgen_wasmtime::import!({paths: ["./wit/custom-filter.wit"]}); |
| 13 | + |
| 14 | +struct CustomFilterContext { |
| 15 | + wasi: WasiCtx, |
| 16 | + data: custom_filter::CustomFilterData, |
| 17 | +} |
| 18 | + |
| 19 | +impl CustomFilterContext { |
| 20 | + fn new() -> Self { |
| 21 | + Self { |
| 22 | + wasi: WasiCtxBuilder::new().build(), |
| 23 | + data: custom_filter::CustomFilterData {}, |
| 24 | + } |
| 25 | + } |
| 26 | +} |
| 27 | + |
| 28 | +#[derive(Clone)] |
| 29 | +pub(crate) struct CustomFilterParser { |
| 30 | + name: String, |
| 31 | + wasm_store: Arc<RwLock<Store<CustomFilterContext>>>, |
| 32 | + exec: Arc<custom_filter::CustomFilter<CustomFilterContext>>, |
| 33 | +} |
| 34 | + |
| 35 | +impl CustomFilterParser { |
| 36 | + pub(crate) fn load(name: &str, wasm_path: &Path) -> anyhow::Result<Self> { |
| 37 | + let wasm = std::fs::read(&wasm_path).with_context(|| { |
| 38 | + format!("Failed loading custom filter from {}", wasm_path.display()) |
| 39 | + })?; |
| 40 | + |
| 41 | + let ctx = CustomFilterContext::new(); |
| 42 | + let engine = Engine::default(); |
| 43 | + let mut store = Store::new(&engine, ctx); |
| 44 | + let mut linker = Linker::new(&engine); |
| 45 | + wasmtime_wasi::add_to_linker(&mut linker, |ctx: &mut CustomFilterContext| &mut ctx.wasi) |
| 46 | + .with_context(|| format!("Setting up WASI for custom filter {}", name))?; |
| 47 | + let module = Module::new(&engine, &wasm) |
| 48 | + .with_context(|| format!("Creating Wasm module for custom filter {}", name))?; |
| 49 | + let instance = linker |
| 50 | + .instantiate(&mut store, &module) |
| 51 | + .with_context(|| format!("Instantiating Wasm module for custom filter {}", name))?; |
| 52 | + let filter_exec = |
| 53 | + custom_filter::CustomFilter::new(&mut store, &instance, |ctx| &mut ctx.data) |
| 54 | + .with_context(|| format!("Loading Wasm executor for custom filer {}", name))?; |
| 55 | + |
| 56 | + Ok(Self { |
| 57 | + name: name.to_owned(), |
| 58 | + wasm_store: Arc::new(RwLock::new(store)), |
| 59 | + exec: Arc::new(filter_exec), |
| 60 | + }) |
| 61 | + } |
| 62 | +} |
| 63 | + |
| 64 | +impl Debug for CustomFilterParser { |
| 65 | + fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { |
| 66 | + f.debug_struct("CustomFilterParser") |
| 67 | + .field("name", &self.name) |
| 68 | + .finish() |
| 69 | + } |
| 70 | +} |
| 71 | + |
| 72 | +impl ParseFilter for CustomFilterParser { |
| 73 | + fn parse( |
| 74 | + &self, |
| 75 | + _arguments: liquid_core::parser::FilterArguments, |
| 76 | + ) -> liquid_core::Result<Box<dyn Filter>> { |
| 77 | + Ok(Box::new(CustomFilter { |
| 78 | + name: self.name.to_owned(), |
| 79 | + wasm_store: self.wasm_store.clone(), |
| 80 | + exec: self.exec.clone(), |
| 81 | + })) |
| 82 | + } |
| 83 | + |
| 84 | + fn reflection(&self) -> &dyn liquid_core::FilterReflection { |
| 85 | + self |
| 86 | + } |
| 87 | +} |
| 88 | + |
| 89 | +const EMPTY: [liquid_core::parser::ParameterReflection; 0] = []; |
| 90 | + |
| 91 | +impl liquid_core::FilterReflection for CustomFilterParser { |
| 92 | + fn name(&self) -> &str { |
| 93 | + &self.name |
| 94 | + } |
| 95 | + |
| 96 | + fn description(&self) -> &str { |
| 97 | + "" |
| 98 | + } |
| 99 | + |
| 100 | + fn positional_parameters(&self) -> &'static [liquid_core::parser::ParameterReflection] { |
| 101 | + &EMPTY |
| 102 | + } |
| 103 | + |
| 104 | + fn keyword_parameters(&self) -> &'static [liquid_core::parser::ParameterReflection] { |
| 105 | + &EMPTY |
| 106 | + } |
| 107 | +} |
| 108 | + |
| 109 | +struct CustomFilter { |
| 110 | + name: String, |
| 111 | + wasm_store: Arc<RwLock<Store<CustomFilterContext>>>, |
| 112 | + exec: Arc<custom_filter::CustomFilter<CustomFilterContext>>, |
| 113 | +} |
| 114 | + |
| 115 | +impl Debug for CustomFilter { |
| 116 | + fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { |
| 117 | + f.debug_struct("CustomFilter") |
| 118 | + .field("name", &self.name) |
| 119 | + .finish() |
| 120 | + } |
| 121 | +} |
| 122 | + |
| 123 | +impl Display for CustomFilter { |
| 124 | + fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { |
| 125 | + f.write_str(&self.name) |
| 126 | + } |
| 127 | +} |
| 128 | + |
| 129 | +impl Filter for CustomFilter { |
| 130 | + fn evaluate( |
| 131 | + &self, |
| 132 | + input: &dyn ValueView, |
| 133 | + _runtime: &dyn Runtime, |
| 134 | + ) -> Result<liquid::model::Value, liquid_core::error::Error> { |
| 135 | + let mut store = self |
| 136 | + .wasm_store |
| 137 | + .write() |
| 138 | + .map_err(|e| liquid_err(format!("Failed to get custom filter Wasm store: {}", e)))?; |
| 139 | + let input_str = self.liquid_value_as_string(input)?; |
| 140 | + match self.exec.exec(&mut *store, &input_str) { |
| 141 | + Ok(Ok(text)) => Ok(to_liquid_value(text)), |
| 142 | + Ok(Err(s)) => Err(liquid_err(s)), |
| 143 | + Err(trap) => Err(liquid_err(format!("{:?}", trap))), |
| 144 | + } |
| 145 | + } |
| 146 | +} |
| 147 | + |
| 148 | +impl CustomFilter { |
| 149 | + fn liquid_value_as_string(&self, input: &dyn ValueView) -> Result<String, liquid::Error> { |
| 150 | + let str = input.as_scalar().map(|s| s.into_cow_str()).ok_or_else(|| { |
| 151 | + liquid_err(format!( |
| 152 | + "Filter '{}': no input or input is not a string", |
| 153 | + self.name |
| 154 | + )) |
| 155 | + })?; |
| 156 | + Ok(str.to_string()) |
| 157 | + } |
| 158 | +} |
| 159 | + |
| 160 | +fn to_liquid_value(value: String) -> liquid::model::Value { |
| 161 | + liquid::model::Value::Scalar(liquid::model::Scalar::from(value)) |
| 162 | +} |
| 163 | + |
| 164 | +fn liquid_err(text: String) -> liquid_core::error::Error { |
| 165 | + liquid_core::error::Error::with_msg(text) |
| 166 | +} |
0 commit comments