use tokio::sync::Mutex;
use crate::{
core::{Event, Result},
transform::Transform,
wasm::{TransformResult, WasmConfig, WasmRuntime},
};
pub struct WasmTransform {
runtime: Mutex<WasmRuntime>,
name: String,
}
impl WasmTransform {
pub async fn new(config: WasmConfig) -> Result<Self> {
let name = config
.module_path
.file_name()
.and_then(|n| n.to_str())
.unwrap_or("wasm")
.to_string();
let mut rt = WasmRuntime::new_with_config(config)?;
rt.init().await?;
Ok(Self {
runtime: Mutex::new(rt),
name,
})
}
}
impl Transform for WasmTransform {
async fn apply<'a>(&'a self, event: &'a mut Event) -> Result<bool> {
let mut guard = self.runtime.lock().await;
match guard.transform(event).await? {
TransformResult::Ok(transformed) => {
*event = *transformed;
Ok(true)
}
TransformResult::Filtered => Ok(false),
TransformResult::Err(reason) => Err(crate::core::Error::SourceError(format!(
"WASM transform returned error: {reason}"
))),
}
}
fn name(&self) -> &str {
&self.name
}
}