use async_trait::async_trait;
use coreon_core::{message::Body, Exchange, Processor, Result};
use std::sync::Arc;
pub type SplitFn = dyn Fn(&Exchange) -> Vec<Body> + Send + Sync;
pub struct Splitter {
split: Arc<SplitFn>,
sub: Arc<dyn Processor>,
}
impl Splitter {
pub fn new<F>(split: F, sub: Arc<dyn Processor>) -> Arc<Self>
where
F: Fn(&Exchange) -> Vec<Body> + Send + Sync + 'static,
{
Arc::new(Self {
split: Arc::new(split),
sub,
})
}
}
#[async_trait]
impl Processor for Splitter {
async fn process(&self, exchange: &mut Exchange) -> Result<()> {
let parts = (self.split)(exchange);
for body in parts {
let mut sub_ex = exchange.clone();
sub_ex.r#in.body = body;
sub_ex.out = None;
self.sub.process(&mut sub_ex).await?;
}
Ok(())
}
}