Skip to main content

camel_processor/
choice.rs

1use std::future::Future;
2use std::pin::Pin;
3use std::sync::Arc;
4
5use camel_api::{BoxProcessor, CamelError, PredicateSource};
6
7/// A single when-clause: a fallible predicate + the sub-pipeline to execute
8/// when it matches.
9pub struct WhenClause {
10    pub predicate: PredicateSource,
11    pub pipeline: BoxProcessor,
12}
13
14impl Clone for WhenClause {
15    fn clone(&self) -> Self {
16        Self {
17            predicate: self.predicate.clone(),
18            pipeline: self.pipeline.clone(),
19        }
20    }
21}
22
23// ── ChoiceSegment + WhenClauseSegment (ADR-0025 OutcomePipeline) ──────────
24
25/// Outcome-aware structural EIP segment for a single when clause.
26pub struct WhenClauseSegment {
27    pub predicate: camel_api::PredicateSource,
28    pub body: camel_api::OutcomeSegment,
29}
30
31impl Clone for WhenClauseSegment {
32    fn clone(&self) -> Self {
33        Self {
34            predicate: self.predicate.clone(),
35            body: self.body.clone(),
36        }
37    }
38}
39
40/// Outcome-aware structural EIP segment for the Choice pattern.
41///
42/// Evaluates `when` clauses in order. The first matching predicate runs its
43/// `body` (which can return `Completed`, `Stopped`, or `Failed`). If no
44/// predicate matches, the `otherwise` segment runs (if present); otherwise
45/// returns `Completed(original_exchange)`. A failed predicate evaluation
46/// yields `Failed(err)` instead of falling through to `otherwise`.
47///
48/// The segment operates at the `PipelineOutcome` layer and preserves the
49/// exchange at the Stop point including all mutations.
50pub struct ChoiceSegment {
51    pub clauses: Vec<WhenClauseSegment>,
52    pub otherwise: Option<camel_api::OutcomeSegment>,
53}
54
55impl Clone for ChoiceSegment {
56    fn clone(&self) -> Self {
57        Self {
58            clauses: self
59                .clauses
60                .iter()
61                .map(|c| WhenClauseSegment {
62                    predicate: c.predicate.clone(),
63                    body: c.body.clone(),
64                })
65                .collect(),
66            otherwise: self.otherwise.clone(),
67        }
68    }
69}
70
71impl camel_api::OutcomePipeline for ChoiceSegment {
72    fn clone_box(&self) -> Box<dyn camel_api::OutcomePipeline> {
73        Box::new(self.clone())
74    }
75
76    fn run<'a>(
77        &'a mut self,
78        exchange: camel_api::Exchange,
79    ) -> Pin<Box<dyn Future<Output = camel_api::PipelineOutcome> + Send + 'a>> {
80        Box::pin(async move {
81            for clause in self.clauses.iter_mut() {
82                match clause.predicate.matches(&exchange).await {
83                    Ok(true) => return clause.body.run(exchange).await,
84                    Ok(false) => continue,
85                    Err(err) => return camel_api::PipelineOutcome::Failed(err),
86                }
87            }
88            if let Some(otherwise) = self.otherwise.as_mut() {
89                otherwise.run(exchange).await
90            } else {
91                camel_api::PipelineOutcome::Completed(exchange)
92            }
93        })
94    }
95}
96
97// ── ChoiceGroupSegment (grouped when clauses) ─────────────────────────────
98
99/// Outcome-aware structural EIP segment for grouped `when` clauses that share
100/// one language.
101///
102/// Grouped evaluation of same-language `when` clauses — one group evaluation
103/// per message replaces per-clause `PredicateSource::matches`. Clause order,
104/// first-match, and error semantics are identical to [`ChoiceSegment`].
105pub struct ChoiceGroupSegment {
106    /// The shared-language predicate group evaluated once per message.
107    pub group: Arc<dyn camel_language_api::PredicateGroup>,
108    /// Per-clause evaluation metadata, parallel to `bodies`.
109    pub metas: Vec<camel_language_api::EvalMeta>,
110    /// Sub-pipeline for each clause, parallel to `metas`.
111    pub bodies: Vec<camel_api::OutcomeSegment>,
112    /// Pipeline to run when no clause matches.
113    pub otherwise: Option<camel_api::OutcomeSegment>,
114}
115
116impl Clone for ChoiceGroupSegment {
117    fn clone(&self) -> Self {
118        Self {
119            group: Arc::clone(&self.group),
120            metas: self.metas.clone(),
121            bodies: self.bodies.clone(),
122            otherwise: self.otherwise.clone(),
123        }
124    }
125}
126
127impl ChoiceGroupSegment {
128    /// Build a grouped choice segment.
129    ///
130    /// `metas` and `bodies` are parallel: `metas[i]` attributes an error from
131    /// clause `i` and `bodies[i]` is the pipeline to run when clause `i` is the
132    /// first match. Empty groups are rejected because the compiler falls back
133    /// to the sequential path for 0/1 clauses.
134    pub fn new(
135        group: Arc<dyn camel_language_api::PredicateGroup>,
136        metas: Vec<camel_language_api::EvalMeta>,
137        bodies: Vec<camel_api::OutcomeSegment>,
138        otherwise: Option<camel_api::OutcomeSegment>,
139    ) -> Result<Self, CamelError> {
140        if bodies.is_empty() {
141            return Err(CamelError::Config(
142                "ChoiceGroupSegment requires at least one clause".to_string(),
143            ));
144        }
145        if metas.len() != bodies.len() {
146            return Err(CamelError::Config(format!(
147                "ChoiceGroupSegment metas ({}) and bodies ({}) must have equal length",
148                metas.len(),
149                bodies.len()
150            )));
151        }
152        Ok(Self {
153            group,
154            metas,
155            bodies,
156            otherwise,
157        })
158    }
159}
160
161impl camel_api::OutcomePipeline for ChoiceGroupSegment {
162    fn clone_box(&self) -> Box<dyn camel_api::OutcomePipeline> {
163        Box::new(self.clone())
164    }
165
166    fn run<'a>(
167        &'a mut self,
168        exchange: camel_api::Exchange,
169    ) -> Pin<Box<dyn Future<Output = camel_api::PipelineOutcome> + Send + 'a>> {
170        Box::pin(async move {
171            match self.group.first_match(&exchange).await {
172                Ok(Some(index)) => self.bodies[index].run(exchange).await,
173                Ok(None) => {
174                    if let Some(otherwise) = self.otherwise.as_mut() {
175                        otherwise.run(exchange).await
176                    } else {
177                        camel_api::PipelineOutcome::Completed(exchange)
178                    }
179                }
180                Err(indexed) => camel_api::PipelineOutcome::Failed(
181                    camel_language_api::eval::to_expression_failed(
182                        indexed.error,
183                        &self.metas[indexed.index],
184                    ),
185                ),
186            }
187        })
188    }
189}
190
191#[cfg(test)]
192mod tests {
193    use super::*;
194    use crate::test_processor_segment::processor_segment;
195    use camel_api::{
196        Body, BoxProcessorExt, CamelError, Exchange, FilterPredicate, Message, OutcomePipeline,
197        PipelineOutcome, Value,
198    };
199
200    fn append_body(suffix: &'static str) -> BoxProcessor {
201        BoxProcessor::from_fn(move |mut ex: Exchange| {
202            Box::pin(async move {
203                if let Body::Text(s) = &ex.input.body {
204                    ex.input.body = Body::Text(format!("{s}{suffix}"));
205                }
206                Ok(ex)
207            })
208        })
209    }
210
211    fn failing() -> BoxProcessor {
212        BoxProcessor::from_fn(|_ex| {
213            Box::pin(async { Err(CamelError::ProcessorError("boom".into())) })
214        })
215    }
216
217    fn pred_header(name: &'static str) -> PredicateSource {
218        PredicateSource::Sync(FilterPredicate::new(move |ex: &Exchange| {
219            ex.input.header(name).is_some()
220        }))
221    }
222
223    fn clause(predicate: PredicateSource, body: BoxProcessor) -> WhenClauseSegment {
224        WhenClauseSegment {
225            predicate,
226            body: processor_segment(body),
227        }
228    }
229
230    fn completed_exchange(outcome: PipelineOutcome) -> Exchange {
231        match outcome {
232            PipelineOutcome::Completed(ex) => ex,
233            other => panic!("expected PipelineOutcome::Completed, got {other:?}"),
234        }
235    }
236
237    // 1. First matching when executes its body.
238    #[tokio::test]
239    async fn choice_segment_first_when_matches() {
240        let mut seg = ChoiceSegment {
241            clauses: vec![
242                clause(pred_header("a"), append_body("-A")),
243                clause(pred_header("b"), append_body("-B")),
244            ],
245            otherwise: None,
246        };
247        let mut ex = Exchange::new(Message::new("x"));
248        ex.input.set_header("a", Value::Bool(true));
249        let result = completed_exchange(seg.run(ex).await);
250        assert_eq!(result.input.body.as_text(), Some("x-A"));
251    }
252
253    // 2. Second when executes when first does not match.
254    #[tokio::test]
255    async fn choice_segment_second_when_matches() {
256        let mut seg = ChoiceSegment {
257            clauses: vec![
258                clause(pred_header("a"), append_body("-A")),
259                clause(pred_header("b"), append_body("-B")),
260            ],
261            otherwise: None,
262        };
263        let mut ex = Exchange::new(Message::new("x"));
264        ex.input.set_header("b", Value::Bool(true));
265        let result = completed_exchange(seg.run(ex).await);
266        assert_eq!(result.input.body.as_text(), Some("x-B"));
267    }
268
269    // 3. Only the FIRST matching when fires (short-circuit — both a and b present).
270    #[tokio::test]
271    async fn choice_segment_short_circuits_at_first_match() {
272        let mut seg = ChoiceSegment {
273            clauses: vec![
274                clause(pred_header("a"), append_body("-A")),
275                clause(pred_header("b"), append_body("-B")),
276            ],
277            otherwise: None,
278        };
279        let mut ex = Exchange::new(Message::new("x"));
280        ex.input.set_header("a", Value::Bool(true));
281        ex.input.set_header("b", Value::Bool(true));
282        let result = completed_exchange(seg.run(ex).await);
283        assert_eq!(result.input.body.as_text(), Some("x-A"));
284    }
285
286    // 4. Otherwise executes when no when matches.
287    #[tokio::test]
288    async fn choice_segment_otherwise_fires_when_no_when_matches() {
289        let mut seg = ChoiceSegment {
290            clauses: vec![clause(pred_header("a"), append_body("-A"))],
291            otherwise: Some(processor_segment(append_body("-else"))),
292        };
293        let ex = Exchange::new(Message::new("x"));
294        let result = completed_exchange(seg.run(ex).await);
295        assert_eq!(result.input.body.as_text(), Some("x-else"));
296    }
297
298    // 5. No match and no otherwise → exchange passes unchanged.
299    #[tokio::test]
300    async fn choice_segment_no_match_no_otherwise_passthrough() {
301        let mut seg = ChoiceSegment {
302            clauses: vec![clause(pred_header("a"), append_body("-A"))],
303            otherwise: None,
304        };
305        let ex = Exchange::new(Message::new("untouched"));
306        let result = completed_exchange(seg.run(ex).await);
307        assert_eq!(result.input.body.as_text(), Some("untouched"));
308    }
309
310    // 6. Errors in a matching when's body surface as Failed.
311    #[tokio::test]
312    async fn choice_segment_error_in_when_propagates() {
313        let mut seg = ChoiceSegment {
314            clauses: vec![clause(pred_header("a"), failing())],
315            otherwise: None,
316        };
317        let mut ex = Exchange::new(Message::new("x"));
318        ex.input.set_header("a", Value::Bool(true));
319        match seg.run(ex).await {
320            PipelineOutcome::Failed(err) => {
321                assert!(err.to_string().contains("boom"), "unexpected error: {err}");
322            }
323            other => panic!("expected PipelineOutcome::Failed, got {other:?}"),
324        }
325    }
326
327    // 7. Errors in otherwise surface as Failed.
328    #[tokio::test]
329    async fn choice_segment_error_in_otherwise_propagates() {
330        let mut seg = ChoiceSegment {
331            clauses: vec![],
332            otherwise: Some(processor_segment(failing())),
333        };
334        let ex = Exchange::new(Message::new("x"));
335        assert!(matches!(seg.run(ex).await, PipelineOutcome::Failed(_)));
336    }
337
338    // ── Fallible predicate path (language-value-boundary task 1.4) ──
339
340    use std::sync::Arc;
341    use std::sync::atomic::{AtomicU32, Ordering};
342
343    use camel_api::ExpressionErrorClass;
344
345    fn expression_failed() -> CamelError {
346        CamelError::ExpressionFailed {
347            language: "rhai".to_string(),
348            route_id: "r1".to_string(),
349            step_id: "step#0".to_string(),
350            verb: "choice".to_string(),
351            class: ExpressionErrorClass::Runtime,
352            position: None,
353            conversion: None,
354            cause: None,
355        }
356    }
357
358    fn async_err_predicate(err: CamelError) -> PredicateSource {
359        PredicateSource::Async(Arc::new(move |_: &Exchange| {
360            let err = err.clone();
361            Box::pin(async move { Err(err) }) as camel_api::BoxBoolFuture
362        }))
363    }
364
365    struct RecordRun(Arc<AtomicU32>);
366
367    impl camel_api::OutcomePipeline for RecordRun {
368        fn clone_box(&self) -> Box<dyn camel_api::OutcomePipeline> {
369            Box::new(RecordRun(Arc::clone(&self.0)))
370        }
371        fn run<'a>(
372            &'a mut self,
373            exchange: Exchange,
374        ) -> Pin<Box<dyn Future<Output = PipelineOutcome> + Send + 'a>> {
375            let c = Arc::clone(&self.0);
376            Box::pin(async move {
377                c.fetch_add(1, Ordering::SeqCst);
378                PipelineOutcome::Completed(exchange)
379            })
380        }
381    }
382
383    #[tokio::test]
384    async fn choice_when_predicate_error_fails_step() {
385        let body_calls = Arc::new(AtomicU32::new(0));
386        let otherwise_calls = Arc::new(AtomicU32::new(0));
387        let mut seg = ChoiceSegment {
388            clauses: vec![WhenClauseSegment {
389                predicate: async_err_predicate(expression_failed()),
390                body: camel_api::OutcomeSegment::new(Box::new(RecordRun(Arc::clone(&body_calls)))),
391            }],
392            otherwise: Some(camel_api::OutcomeSegment::new(Box::new(RecordRun(
393                Arc::clone(&otherwise_calls),
394            )))),
395        };
396        let outcome = seg.run(Exchange::default()).await;
397        match outcome {
398            PipelineOutcome::Failed(err) => {
399                assert!(
400                    matches!(err, CamelError::ExpressionFailed { .. }),
401                    "expected ExpressionFailed, got {err:?}"
402                );
403            }
404            other => panic!("expected PipelineOutcome::Failed, got {other:?}"),
405        }
406        assert_eq!(
407            body_calls.load(Ordering::SeqCst),
408            0,
409            "when body must not run when its predicate errors"
410        );
411        assert_eq!(
412            otherwise_calls.load(Ordering::SeqCst),
413            0,
414            "otherwise must never execute when a when-predicate errors"
415        );
416    }
417
418    // ── ChoiceGroupSegment (grouped when clauses) ────────────────────────
419
420    use camel_language_api::{EvalMeta, IndexedPredicateError, LanguageError, PredicateGroup};
421
422    enum GroupOutcome {
423        Match(usize),
424        NoMatch,
425        Error { index: usize },
426    }
427
428    struct MockGroup {
429        outcome: GroupOutcome,
430        calls: Arc<AtomicU32>,
431    }
432
433    impl MockGroup {
434        fn mock(outcome: GroupOutcome, calls: Arc<AtomicU32>) -> Arc<dyn PredicateGroup> {
435            Arc::new(Self { outcome, calls })
436        }
437    }
438
439    #[camel_language_api::async_trait]
440    impl PredicateGroup for MockGroup {
441        async fn first_match(
442            &self,
443            _exchange: &Exchange,
444        ) -> Result<Option<usize>, IndexedPredicateError> {
445            self.calls.fetch_add(1, Ordering::SeqCst);
446            match &self.outcome {
447                GroupOutcome::Match(i) => Ok(Some(*i)),
448                GroupOutcome::NoMatch => Ok(None),
449                GroupOutcome::Error { index } => Err(IndexedPredicateError {
450                    index: *index,
451                    error: LanguageError::NotSupported {
452                        feature: "predicate_group".to_string(),
453                        language: "rhai".to_string(),
454                    },
455                }),
456            }
457        }
458    }
459
460    fn group_meta(index: usize) -> EvalMeta {
461        EvalMeta {
462            language: "rhai".to_string(),
463            route_id: "r1".to_string(),
464            step_id: format!("step#{index}"),
465            verb: format!("choice/when[{index}]"),
466            target: None,
467        }
468    }
469
470    fn group_segment(
471        group: Arc<dyn PredicateGroup>,
472        metas: Vec<EvalMeta>,
473        bodies: Vec<camel_api::OutcomeSegment>,
474        otherwise: Option<camel_api::OutcomeSegment>,
475    ) -> ChoiceGroupSegment {
476        ChoiceGroupSegment::new(group, metas, bodies, otherwise).expect("valid group segment")
477    }
478
479    fn body_segments(suffixes: &[&'static str]) -> Vec<camel_api::OutcomeSegment> {
480        suffixes
481            .iter()
482            .map(|s| processor_segment(append_body(s)))
483            .collect()
484    }
485
486    // 1. First matching clause runs its body.
487    #[tokio::test]
488    async fn choice_group_first_when_matches() {
489        let calls = Arc::new(AtomicU32::new(0));
490        let group = MockGroup::mock(GroupOutcome::Match(0), Arc::clone(&calls));
491        let mut seg = group_segment(
492            group,
493            vec![group_meta(0), group_meta(1)],
494            body_segments(&["-A", "-B"]),
495            None,
496        );
497        let ex = Exchange::new(Message::new("x"));
498        let result = completed_exchange(seg.run(ex).await);
499        assert_eq!(result.input.body.as_text(), Some("x-A"));
500        assert_eq!(calls.load(Ordering::SeqCst), 1, "exactly one first_match");
501    }
502
503    // 2. No match runs otherwise.
504    #[tokio::test]
505    async fn choice_group_no_match_runs_otherwise() {
506        let calls = Arc::new(AtomicU32::new(0));
507        let group = MockGroup::mock(GroupOutcome::NoMatch, Arc::clone(&calls));
508        let mut seg = group_segment(
509            group,
510            vec![group_meta(0)],
511            body_segments(&["-A"]),
512            Some(processor_segment(append_body("-else"))),
513        );
514        let ex = Exchange::new(Message::new("x"));
515        let result = completed_exchange(seg.run(ex).await);
516        assert_eq!(result.input.body.as_text(), Some("x-else"));
517    }
518
519    // 3. No match and no otherwise → passthrough.
520    #[tokio::test]
521    async fn choice_group_no_match_passthrough_without_otherwise() {
522        let calls = Arc::new(AtomicU32::new(0));
523        let group = MockGroup::mock(GroupOutcome::NoMatch, Arc::clone(&calls));
524        let mut seg = group_segment(group, vec![group_meta(0)], body_segments(&["-A"]), None);
525        let ex = Exchange::new(Message::new("untouched"));
526        let result = completed_exchange(seg.run(ex).await);
527        assert_eq!(result.input.body.as_text(), Some("untouched"));
528    }
529
530    // 4. Group errors are attributed to the offending clause's metadata.
531    #[tokio::test]
532    async fn choice_group_error_maps_through_offending_clause_meta() {
533        let calls = Arc::new(AtomicU32::new(0));
534        let group = MockGroup::mock(GroupOutcome::Error { index: 2 }, Arc::clone(&calls));
535        let mut seg = group_segment(
536            group,
537            vec![group_meta(0), group_meta(1), group_meta(2)],
538            body_segments(&["-A", "-B", "-C"]),
539            None,
540        );
541        match seg.run(Exchange::default()).await {
542            PipelineOutcome::Failed(err) => match err {
543                CamelError::ExpressionFailed { step_id, verb, .. } => {
544                    assert_eq!(verb, "choice/when[2]", "clause attribution");
545                    assert_eq!(step_id, "step#2");
546                }
547                other => panic!("expected ExpressionFailed, got {other:?}"),
548            },
549            other => panic!("expected PipelineOutcome::Failed, got {other:?}"),
550        }
551        assert_eq!(calls.load(Ordering::SeqCst), 1, "exactly one first_match");
552    }
553
554    // 5. Only the selected clause's body runs.
555    #[tokio::test]
556    async fn choice_group_runs_body_of_selected_clause_only() {
557        let calls = Arc::new(AtomicU32::new(0));
558        let group = MockGroup::mock(GroupOutcome::Match(1), Arc::clone(&calls));
559        let mut seg = group_segment(
560            group,
561            vec![group_meta(0), group_meta(1), group_meta(2)],
562            body_segments(&["-A", "-B", "-C"]),
563            None,
564        );
565        let ex = Exchange::new(Message::new("x"));
566        let result = completed_exchange(seg.run(ex).await);
567        assert_eq!(result.input.body.as_text(), Some("x-B"));
568    }
569
570    // 6. Constructor rejects mismatched metas/bodies and empty groups.
571    #[test]
572    fn choice_group_new_rejects_metas_body_mismatch() {
573        let calls = Arc::new(AtomicU32::new(0));
574        let group = MockGroup::mock(GroupOutcome::NoMatch, Arc::clone(&calls));
575        assert!(
576            ChoiceGroupSegment::new(
577                Arc::clone(&group),
578                vec![group_meta(0), group_meta(1)],
579                body_segments(&["-A"]),
580                None,
581            )
582            .is_err(),
583            "metas.len() != bodies.len() must be rejected"
584        );
585        assert!(
586            ChoiceGroupSegment::new(group, vec![], vec![], None).is_err(),
587            "empty groups must be rejected"
588        );
589    }
590}