use async_trait::async_trait;
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 std::fmt::Debug for WasmTransform {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
f.debug_struct("WasmTransform")
.field("name", &self.name)
.finish_non_exhaustive()
}
}
#[async_trait]
impl Transform for WasmTransform {
async fn apply(&self, event: &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),
}
}
fn name(&self) -> &str {
&self.name
}
}