coreon-eip 0.1.0

Enterprise Integration Pattern processors for camel-rs.
Documentation
//! Choice — evaluate predicates in order; run the first matching branch,
//! or the `otherwise` branch if none match. If no otherwise is set, the
//! exchange passes through unchanged.

use async_trait::async_trait;
use coreon_core::{processor::Predicate, Exchange, Processor, Result};
use std::sync::Arc;

pub struct WhenClause {
    predicate: Arc<dyn Predicate>,
    then: Arc<dyn Processor>,
}

impl WhenClause {
    pub fn new(predicate: Arc<dyn Predicate>, then: Arc<dyn Processor>) -> Self {
        Self { predicate, then }
    }
}

pub struct Choice {
    clauses: Vec<WhenClause>,
    otherwise: Option<Arc<dyn Processor>>,
}

impl Choice {
    pub fn new(clauses: Vec<WhenClause>, otherwise: Option<Arc<dyn Processor>>) -> Arc<Self> {
        Arc::new(Self { clauses, otherwise })
    }
}

#[async_trait]
impl Processor for Choice {
    async fn process(&self, exchange: &mut Exchange) -> Result<()> {
        for clause in &self.clauses {
            if clause.predicate.matches(exchange) {
                return clause.then.process(exchange).await;
            }
        }
        if let Some(o) = &self.otherwise {
            return o.process(exchange).await;
        }
        Ok(())
    }
}