Skip to main content

camel_processor/
do_try_segment.rs

1//! ## Stop semantics (ADR-0025)
2//!
3//! This segment implements `OutcomePipeline` and propagates `PipelineOutcome::Stopped(ex)`
4//! with the exchange state intact. See ADR-0025 §3.
5
6use crate::do_try::CatchMatcher;
7use crate::do_try::chain_predicate_error;
8use crate::error_handler::record_span_error;
9use camel_api::error_handler::ExceptionDisposition;
10use camel_api::exchange::PROPERTY_EXCEPTION_HANDLED;
11use camel_api::outcome_pipeline::OutcomePipeline;
12use camel_api::pipeline_outcome::PipelineOutcome;
13use camel_api::{CamelError, Exchange, PredicateSource};
14use std::future::Future;
15use std::pin::Pin;
16
17/// - `Handled`: the exchange continues through finally and downstream.
18/// - `Propagate`: the catch body runs for side effects, finally runs with the
19///   catch body's exchange, and the original try-error re-throws as `Failed`.
20#[derive(Clone)]
21pub struct CatchClauseSegment {
22    pub matcher: CatchMatcher,
23    pub on_when: Option<PredicateSource>,
24    pub body: camel_api::OutcomeSegment,
25    pub disposition: ExceptionDisposition,
26}
27
28/// Compilable segment for a `doFinally` clause within a `DoTrySegment`.
29#[derive(Clone)]
30pub struct FinallyClauseSegment {
31    pub on_when: Option<PredicateSource>,
32    pub body: camel_api::OutcomeSegment,
33}
34
35/// Outcome-aware structural EIP segment for the doTry/doCatch/doFinally pattern.
36///
37/// Operates at the `PipelineOutcome` layer so that `Stopped(ex)` from a
38/// sub-step (e.g. Stop EIP) is preserved with the exchange including all
39/// mutations. See ADR-0025 §5.1 for full semantics.
40pub struct DoTrySegment {
41    pub try_body: camel_api::OutcomeSegment,
42    pub catches: Vec<CatchClauseSegment>,
43    pub finally: Option<FinallyClauseSegment>,
44}
45
46impl Clone for DoTrySegment {
47    fn clone(&self) -> Self {
48        Self {
49            try_body: self.try_body.clone(),
50            catches: self.catches.clone(),
51            finally: self.finally.clone(),
52        }
53    }
54}
55
56/// Narrow outcome type for `run_finally_body` so the compiler enforces
57/// exhaustiveness at the two call sites instead of `unreachable!()`.
58/// This is a private, transient type; the `Stopped` exchange is boxed to keep
59/// the `Err` variant of `run_finally_body` small (clippy::result_large_err).
60enum FinallyOutcome {
61    Stopped(Box<Exchange>),
62    Failed(CamelError),
63    /// The finally `on_when` predicate itself failed; the typed error fails
64    /// the segment.
65    PredicateFailed(CamelError),
66}
67
68/// Run the finally body if present and on_when permits.
69/// Free function (not a method) to avoid borrow conflict with
70/// `self.catches.iter_mut()` inside the catch loop.
71/// The `FinallyOutcome` variants move the `Exchange` (the catch loop needs
72/// its state); boxing would rewrite the segment call chain for a lint
73/// threshold.
74#[allow(clippy::result_large_err)]
75async fn run_finally_body(
76    finally: &mut Option<FinallyClauseSegment>,
77    ex: Exchange,
78) -> Result<Exchange, FinallyOutcome> {
79    let Some(f) = finally.as_mut() else {
80        return Ok(ex);
81    };
82    if let Some(on_when) = &f.on_when {
83        match on_when.matches(&ex).await {
84            Ok(true) => {}
85            Ok(false) => return Ok(ex),
86            Err(err) => return Err(FinallyOutcome::PredicateFailed(err)),
87        }
88    }
89    match f.body.run(ex).await {
90        PipelineOutcome::Completed(e) => Ok(e),
91        PipelineOutcome::Stopped(e) => Err(FinallyOutcome::Stopped(Box::new(e))),
92        PipelineOutcome::Failed(e) => Err(FinallyOutcome::Failed(e)),
93    }
94}
95
96/// Surface `failure` after running finally.
97///
98/// Used for a failed catch predicate (the predicate error surfaced as the
99/// main failure), the no-catch-matched path, the Propagate / fail-closed
100/// path (the original try error), and the catch-body-failure path (the catch
101/// error is the surfaced failure).
102/// `failure` becomes the main failure (Camel parity: a throwing finally body
103/// restores it; Stop in finally still stops the outer route; a failed finally
104/// `on_when` predicate supersedes it).
105async fn fail_after_finally(
106    finally: &mut Option<FinallyClauseSegment>,
107    ex: Exchange,
108    failure: CamelError,
109) -> PipelineOutcome {
110    match run_finally_body(finally, ex).await {
111        Ok(_) => PipelineOutcome::Failed(failure),
112        Err(FinallyOutcome::Stopped(e)) => PipelineOutcome::Stopped(*e),
113        Err(FinallyOutcome::Failed(_finally_err)) => {
114            tracing::warn!(
115                error = %failure,
116                "doFinally threw; restoring previous error (Camel parity)"
117            );
118            PipelineOutcome::Failed(failure)
119        }
120        Err(FinallyOutcome::PredicateFailed(pred_err)) => PipelineOutcome::Failed(pred_err),
121    }
122}
123
124impl OutcomePipeline for DoTrySegment {
125    fn clone_box(&self) -> Box<dyn OutcomePipeline> {
126        Box::new(self.clone())
127    }
128
129    fn run<'a>(
130        &'a mut self,
131        mut exchange: Exchange,
132    ) -> Pin<Box<dyn Future<Output = PipelineOutcome> + Send + 'a>> {
133        Box::pin(async move {
134            // Stale handled-marker protocol inherited from the deleted
135            // `DoTryService` (clear-on-entry; `Exchange::clear_error` does not
136            // touch HANDLED).
137            exchange.properties.remove(PROPERTY_EXCEPTION_HANDLED);
138            // Pre-clone for the "no catch matched" path; `exchange` itself is
139            // consumed by `try_body.run(...)` below.
140            let exchange_for_unmatched = exchange.branch_clone();
141
142            // 1. Run try_body. If Stopped, return immediately (skip catch AND finally).
143            let try_outcome = self.try_body.run(exchange).await;
144            let returned_ex = match try_outcome {
145                PipelineOutcome::Stopped(ex) => return PipelineOutcome::Stopped(ex),
146                PipelineOutcome::Completed(ex) => ex,
147                PipelineOutcome::Failed(err) => {
148                    // 2. try failed — try each catch in order. Walk the catch
149                    // chain starting from the failed try-exchange. On the first
150                    // matching catch whose `on_when` is true (or unset), run it.
151                    // A failed catch `when`/`on_when` predicate replaces the
152                    // original error (preserved as `cause`) and fails the scope.
153                    let mut current_ex = exchange_for_unmatched;
154                    current_ex.set_error(err.clone());
155                    // Distinguishes "a catch handled the error" (loop breaks
156                    // with `current_ex` = catch output) from "the loop
157                    // exhausted with no match" (must propagate the original).
158                    let mut catch_matched = false;
159                    for catch in self.catches.iter_mut() {
160                        let matched = match catch.matcher.matches(&err, &current_ex).await {
161                            Ok(m) => m,
162                            Err(pred_err) => {
163                                let chained = chain_predicate_error(pred_err, err);
164                                return fail_after_finally(&mut self.finally, current_ex, chained)
165                                    .await;
166                            }
167                        };
168                        if !matched {
169                            continue;
170                        }
171                        if let Some(on_when) = &catch.on_when {
172                            match on_when.matches(&current_ex).await {
173                                Ok(true) => {}
174                                Ok(false) => continue,
175                                Err(pred_err) => {
176                                    let chained = chain_predicate_error(pred_err, err);
177                                    return fail_after_finally(
178                                        &mut self.finally,
179                                        current_ex,
180                                        chained,
181                                    )
182                                    .await;
183                                }
184                            }
185                        }
186                        // Pre-clone for the catch-body-failure path:
187                        // `PipelineOutcome::Failed` drops the exchange, so the
188                        // finally body still needs a pre-catch snapshot (same
189                        // pattern as `exchange_for_unmatched` above).
190                        let catch_input_ex = current_ex.branch_clone();
191                        match catch.body.run(current_ex).await {
192                            // Stop in catch: skip finally AND outer route halts.
193                            PipelineOutcome::Stopped(stopped_ex) => {
194                                return PipelineOutcome::Stopped(stopped_ex);
195                            }
196                            // Catch handled — exit catch chain with this exchange.
197                            PipelineOutcome::Completed(mut next) => {
198                                match catch.disposition {
199                                    ExceptionDisposition::Handled => {
200                                        next.handle_error();
201                                        current_ex = next;
202                                        catch_matched = true;
203                                        break;
204                                    }
205                                    ExceptionDisposition::Continued => {
206                                        next.clear_error();
207                                        current_ex = next;
208                                        catch_matched = true;
209                                        break;
210                                    }
211                                    // Propagate and any future variant run finally then
212                                    // surface the original error (fail-closed).
213                                    _ => {
214                                        return fail_after_finally(&mut self.finally, next, err)
215                                            .await;
216                                    }
217                                }
218                            }
219                            // Catch-body Failed: Java try/catch/finally
220                            // parity (JLS §14.20.2) — the finally body runs
221                            // exactly once even when the catch body fails,
222                            // and the catch error remains the surfaced
223                            // failure. No catch-of-catch: the doTry island
224                            // invariant (ADR-0025 #4) is unchanged, so the
225                            // catch chain is NOT re-entered.
226                            PipelineOutcome::Failed(catch_err) => {
227                                // Sealed failure envelope: the catch error
228                                // stays the main error (returned below);
229                                // the original try error is surfaced
230                                // through the unconditional warn record
231                                // and, when a span is active, the span
232                                // error record. No new span is created.
233                                tracing::warn!(
234                                    original_error = %err,
235                                    catch_error = %catch_err,
236                                    "do_try catch block failed; catch error supersedes original"
237                                );
238                                record_span_error(&catch_err);
239                                return fail_after_finally(
240                                    &mut self.finally,
241                                    catch_input_ex,
242                                    catch_err,
243                                )
244                                .await;
245                            }
246                        }
247                    }
248                    if catch_matched {
249                        // A catch handled the error: continue to the shared
250                        // finally path and return its exchange as Completed.
251                        current_ex
252                    } else {
253                        // No catch matched: run finally, then propagate the
254                        // original try error as `Failed`. Falling through to the
255                        // shared finally path would return `Completed` and
256                        // swallow the error, letting the route continue past
257                        // the scope (the segment is the only doTry runtime).
258                        return fail_after_finally(&mut self.finally, current_ex, err).await;
259                    }
260                }
261            };
262            // 3. Run finally if present (skip if try/catch returned Stopped —
263            // already returned above; catch-body failures flow through
264            // `fail_after_finally` and return there).
265            match run_finally_body(&mut self.finally, returned_ex).await {
266                Ok(ex) => PipelineOutcome::Completed(ex),
267                Err(FinallyOutcome::Stopped(e)) => PipelineOutcome::Stopped(*e),
268                Err(FinallyOutcome::Failed(finally_err)) => {
269                    tracing::warn!(
270                        error = %finally_err,
271                        "doFinally threw during/after catch; surfacing finally error"
272                    );
273                    PipelineOutcome::Failed(finally_err)
274                }
275                // Failed finally `on_when` predicate: the typed error fails
276                // the segment.
277                Err(FinallyOutcome::PredicateFailed(pred_err)) => PipelineOutcome::Failed(pred_err),
278            }
279        })
280    }
281}
282
283#[cfg(test)]
284mod tests {
285    use super::*;
286    use crate::do_try::CatchMatcher;
287    use crate::test_log_capture::{capture_debugs_with_span_records, captured_field, record_field};
288    use camel_api::Value;
289    use camel_api::exchange::{PROPERTY_EXCEPTION_CAUGHT, PROPERTY_EXCEPTION_MESSAGE};
290    use camel_api::pipeline_outcome::PipelineOutcome;
291    use std::sync::Arc;
292    use std::sync::atomic::{AtomicU32, Ordering};
293
294    // ── Helpers for DoTrySegment tests ──
295
296    struct CompleteSegment;
297
298    impl OutcomePipeline for CompleteSegment {
299        fn clone_box(&self) -> Box<dyn OutcomePipeline> {
300            Box::new(CompleteSegment)
301        }
302        fn run<'a>(
303            &'a mut self,
304            exchange: Exchange,
305        ) -> Pin<Box<dyn Future<Output = PipelineOutcome> + Send + 'a>> {
306            Box::pin(async move { PipelineOutcome::Completed(exchange) })
307        }
308    }
309
310    fn seg_complete() -> camel_api::OutcomeSegment {
311        camel_api::OutcomeSegment::new(Box::new(CompleteSegment))
312    }
313
314    struct FailSegment(CamelError);
315
316    impl OutcomePipeline for FailSegment {
317        fn clone_box(&self) -> Box<dyn OutcomePipeline> {
318            Box::new(FailSegment(self.0.clone()))
319        }
320        fn run<'a>(
321            &'a mut self,
322            _exchange: Exchange,
323        ) -> Pin<Box<dyn Future<Output = PipelineOutcome> + Send + 'a>> {
324            let e = self.0.clone();
325            Box::pin(async move { PipelineOutcome::Failed(e) })
326        }
327    }
328
329    fn seg_fail(err: CamelError) -> camel_api::OutcomeSegment {
330        camel_api::OutcomeSegment::new(Box::new(FailSegment(err)))
331    }
332
333    struct MutateThenStop {
334        mutator: Arc<dyn Fn(&mut Exchange) + Send + Sync>,
335    }
336
337    impl OutcomePipeline for MutateThenStop {
338        fn clone_box(&self) -> Box<dyn OutcomePipeline> {
339            Box::new(MutateThenStop {
340                mutator: Arc::clone(&self.mutator),
341            })
342        }
343        fn run<'a>(
344            &'a mut self,
345            mut exchange: Exchange,
346        ) -> Pin<Box<dyn Future<Output = PipelineOutcome> + Send + 'a>> {
347            let m = Arc::clone(&self.mutator);
348            Box::pin(async move {
349                m(&mut exchange);
350                PipelineOutcome::Stopped(exchange)
351            })
352        }
353    }
354
355    fn seg_stop_with(
356        mutator: impl Fn(&mut Exchange) + Send + Sync + 'static,
357    ) -> camel_api::OutcomeSegment {
358        camel_api::OutcomeSegment::new(Box::new(MutateThenStop {
359            mutator: Arc::new(mutator),
360        }))
361    }
362
363    struct CheckThenComplete {
364        check: Arc<dyn Fn(&Exchange) + Send + Sync>,
365    }
366
367    impl OutcomePipeline for CheckThenComplete {
368        fn clone_box(&self) -> Box<dyn OutcomePipeline> {
369            Box::new(CheckThenComplete {
370                check: Arc::clone(&self.check),
371            })
372        }
373        fn run<'a>(
374            &'a mut self,
375            exchange: Exchange,
376        ) -> Pin<Box<dyn Future<Output = PipelineOutcome> + Send + 'a>> {
377            let check = Arc::clone(&self.check);
378            Box::pin(async move {
379                check(&exchange);
380                PipelineOutcome::Completed(exchange)
381            })
382        }
383    }
384
385    fn seg_check_then_complete(
386        check: impl Fn(&Exchange) + Send + Sync + 'static,
387    ) -> camel_api::OutcomeSegment {
388        camel_api::OutcomeSegment::new(Box::new(CheckThenComplete {
389            check: Arc::new(check),
390        }))
391    }
392
393    struct RecordCall {
394        counter: Arc<AtomicU32>,
395    }
396
397    impl OutcomePipeline for RecordCall {
398        fn clone_box(&self) -> Box<dyn OutcomePipeline> {
399            Box::new(RecordCall {
400                counter: Arc::clone(&self.counter),
401            })
402        }
403        fn run<'a>(
404            &'a mut self,
405            exchange: Exchange,
406        ) -> Pin<Box<dyn Future<Output = PipelineOutcome> + Send + 'a>> {
407            let c = Arc::clone(&self.counter);
408            Box::pin(async move {
409                c.fetch_add(1, Ordering::SeqCst);
410                PipelineOutcome::Completed(exchange)
411            })
412        }
413    }
414
415    fn seg_record(counter: Arc<AtomicU32>) -> camel_api::OutcomeSegment {
416        camel_api::OutcomeSegment::new(Box::new(RecordCall { counter }))
417    }
418
419    struct CountThenFail {
420        counter: Arc<AtomicU32>,
421        err: CamelError,
422    }
423
424    impl OutcomePipeline for CountThenFail {
425        fn clone_box(&self) -> Box<dyn OutcomePipeline> {
426            Box::new(CountThenFail {
427                counter: Arc::clone(&self.counter),
428                err: self.err.clone(),
429            })
430        }
431        fn run<'a>(
432            &'a mut self,
433            _exchange: Exchange,
434        ) -> Pin<Box<dyn Future<Output = PipelineOutcome> + Send + 'a>> {
435            let c = Arc::clone(&self.counter);
436            let e = self.err.clone();
437            Box::pin(async move {
438                c.fetch_add(1, Ordering::SeqCst);
439                PipelineOutcome::Failed(e)
440            })
441        }
442    }
443
444    fn seg_count_then_fail(counter: Arc<AtomicU32>, err: CamelError) -> camel_api::OutcomeSegment {
445        camel_api::OutcomeSegment::new(Box::new(CountThenFail { counter, err }))
446    }
447
448    struct CountThenStop {
449        counter: Arc<AtomicU32>,
450        mutator: Arc<dyn Fn(&mut Exchange) + Send + Sync>,
451    }
452
453    impl OutcomePipeline for CountThenStop {
454        fn clone_box(&self) -> Box<dyn OutcomePipeline> {
455            Box::new(CountThenStop {
456                counter: Arc::clone(&self.counter),
457                mutator: Arc::clone(&self.mutator),
458            })
459        }
460        fn run<'a>(
461            &'a mut self,
462            mut exchange: Exchange,
463        ) -> Pin<Box<dyn Future<Output = PipelineOutcome> + Send + 'a>> {
464            let c = Arc::clone(&self.counter);
465            let m = Arc::clone(&self.mutator);
466            Box::pin(async move {
467                c.fetch_add(1, Ordering::SeqCst);
468                m(&mut exchange);
469                PipelineOutcome::Stopped(exchange)
470            })
471        }
472    }
473
474    fn seg_count_then_stop(
475        counter: Arc<AtomicU32>,
476        mutator: impl Fn(&mut Exchange) + Send + Sync + 'static,
477    ) -> camel_api::OutcomeSegment {
478        camel_api::OutcomeSegment::new(Box::new(CountThenStop {
479            counter,
480            mutator: Arc::new(mutator),
481        }))
482    }
483
484    // ── 5 New tests for DoTrySegment (ADR-0025) ──
485
486    #[tokio::test]
487    async fn stop_inside_try_skips_catch_and_finally() {
488        let catch_call = Arc::new(AtomicU32::new(0));
489        let finally_call = Arc::new(AtomicU32::new(0));
490
491        let mut seg = DoTrySegment {
492            try_body: seg_stop_with(|ex| {
493                ex.set_property("mutated", camel_api::Value::Bool(true));
494            }),
495            catches: vec![CatchClauseSegment {
496                matcher: CatchMatcher::ByVariant(vec!["*".into()]),
497                on_when: None,
498                body: seg_record(catch_call.clone()),
499                disposition: ExceptionDisposition::Handled,
500            }],
501            finally: Some(FinallyClauseSegment {
502                on_when: None,
503                body: seg_record(finally_call.clone()),
504            }),
505        };
506
507        let result = seg.run(Exchange::default()).await;
508        match result {
509            PipelineOutcome::Stopped(ex) => {
510                assert_eq!(
511                    ex.properties.get("mutated"),
512                    Some(&camel_api::Value::Bool(true)),
513                    "try body mutation must be preserved in Stopped exchange"
514                );
515            }
516            other => panic!("expected Stopped, got {:?}", other),
517        }
518        assert_eq!(
519            catch_call.load(Ordering::SeqCst),
520            0,
521            "catch must NOT run when try stops"
522        );
523        assert_eq!(
524            finally_call.load(Ordering::SeqCst),
525            0,
526            "finally must NOT run when try stops"
527        );
528    }
529
530    #[tokio::test]
531    async fn stop_inside_catch_skips_finally() {
532        let finally_call = Arc::new(AtomicU32::new(0));
533
534        let mut seg = DoTrySegment {
535            try_body: seg_fail(CamelError::ProcessorError("boom".into())),
536            catches: vec![CatchClauseSegment {
537                matcher: CatchMatcher::ByVariant(vec!["ProcessorError".into()]),
538                on_when: None,
539                body: seg_stop_with(|ex| {
540                    ex.set_property("catch_mutated", camel_api::Value::Bool(true));
541                }),
542                disposition: ExceptionDisposition::Handled,
543            }],
544            finally: Some(FinallyClauseSegment {
545                on_when: None,
546                body: seg_record(finally_call.clone()),
547            }),
548        };
549
550        let result = seg.run(Exchange::default()).await;
551        match result {
552            PipelineOutcome::Stopped(ex) => {
553                assert_eq!(
554                    ex.properties.get("catch_mutated"),
555                    Some(&camel_api::Value::Bool(true)),
556                    "catch body mutation must be preserved in Stopped exchange"
557                );
558            }
559            other => panic!("expected Stopped, got {:?}", other),
560        }
561        assert_eq!(
562            finally_call.load(Ordering::SeqCst),
563            0,
564            "finally must NOT run when catch stops"
565        );
566    }
567
568    #[tokio::test]
569    async fn stop_inside_finally_stops_outer_route() {
570        let mut seg = DoTrySegment {
571            try_body: seg_complete(),
572            catches: vec![],
573            finally: Some(FinallyClauseSegment {
574                on_when: None,
575                body: seg_stop_with(|ex| {
576                    ex.set_property("finally_mutated", camel_api::Value::Bool(true));
577                }),
578            }),
579        };
580
581        let result = seg.run(Exchange::default()).await;
582        match result {
583            PipelineOutcome::Stopped(ex) => {
584                assert_eq!(
585                    ex.properties.get("finally_mutated"),
586                    Some(&camel_api::Value::Bool(true)),
587                    "finally body mutation must be preserved in Stopped exchange"
588                );
589            }
590            other => panic!("expected Stopped, got {:?}", other),
591        }
592    }
593
594    #[tokio::test]
595    async fn catch_on_when_false_falls_through_to_next_catch() {
596        let first_call = Arc::new(AtomicU32::new(0));
597        let second_call = Arc::new(AtomicU32::new(0));
598
599        let mut seg = DoTrySegment {
600            try_body: seg_fail(CamelError::Io("disk err".into())),
601            catches: vec![
602                CatchClauseSegment {
603                    matcher: CatchMatcher::ByVariant(vec!["Io".into()]),
604                    on_when: Some(PredicateSource::Sync(FilterPredicate::new(|_ex| false))),
605                    body: seg_record(first_call.clone()),
606                    disposition: ExceptionDisposition::Handled,
607                },
608                CatchClauseSegment {
609                    matcher: CatchMatcher::ByVariant(vec!["*".into()]),
610                    on_when: None,
611                    body: seg_record(second_call.clone()),
612                    disposition: ExceptionDisposition::Handled,
613                },
614            ],
615            finally: None,
616        };
617
618        let result = seg.run(Exchange::default()).await;
619        assert!(
620            matches!(result, PipelineOutcome::Completed(_)),
621            "expected Completed after second catch"
622        );
623        assert_eq!(
624            first_call.load(Ordering::SeqCst),
625            0,
626            "first catch must NOT fire (on_when=false)"
627        );
628        assert_eq!(
629            second_call.load(Ordering::SeqCst),
630            1,
631            "second catch must fire"
632        );
633    }
634
635    #[tokio::test]
636    async fn finally_on_when_false_skips_finally_entirely() {
637        let finally_call = Arc::new(AtomicU32::new(0));
638        let mut ex = Exchange::default();
639        ex.set_property("try_set", camel_api::Value::Bool(true));
640
641        let mut seg = DoTrySegment {
642            try_body: seg_complete(),
643            catches: vec![],
644            finally: Some(FinallyClauseSegment {
645                on_when: Some(PredicateSource::Sync(FilterPredicate::new(|_ex| false))),
646                body: seg_record(finally_call.clone()),
647            }),
648        };
649
650        let result = seg.run(ex).await;
651        match result {
652            PipelineOutcome::Completed(ex) => {
653                assert_eq!(
654                    ex.properties.get("try_set"),
655                    Some(&camel_api::Value::Bool(true)),
656                    "exchange state from try must be preserved"
657                );
658            }
659            other => panic!("expected Completed, got {:?}", other),
660        }
661        assert_eq!(
662            finally_call.load(Ordering::SeqCst),
663            0,
664            "finally must NOT run when on_when=false"
665        );
666    }
667
668    // ── Catch disposition clears error (mission 479) ──
669
670    #[tokio::test]
671    async fn handled_catch_clears_error_and_marks_handled() {
672        let mut seg = DoTrySegment {
673            try_body: seg_fail(CamelError::ProcessorError("boom".into())),
674            catches: vec![CatchClauseSegment {
675                matcher: CatchMatcher::ByVariant(vec!["ProcessorError".into()]),
676                on_when: None,
677                body: seg_check_then_complete(|ex| {
678                    assert!(ex.has_error(), "catch body must see the try error");
679                    assert!(
680                        matches!(ex.properties.get(PROPERTY_EXCEPTION_MESSAGE), Some(Value::String(s)) if s.contains("boom")),
681                        "catch body must see the derived exception message, got {:?}",
682                        ex.properties.get(PROPERTY_EXCEPTION_MESSAGE)
683                    );
684                }),
685                disposition: ExceptionDisposition::Handled,
686            }],
687            finally: None,
688        };
689
690        let result = seg.run(Exchange::default()).await;
691        match result {
692            PipelineOutcome::Completed(ex) => {
693                assert!(
694                    !ex.has_error(),
695                    "handled catch must clear the exchange error"
696                );
697                assert_eq!(
698                    ex.properties.get(PROPERTY_EXCEPTION_HANDLED),
699                    Some(&Value::Bool(true)),
700                    "handled catch must set CamelExceptionHandled"
701                );
702                assert!(
703                    !ex.properties.contains_key(PROPERTY_EXCEPTION_MESSAGE),
704                    "handled catch must clear the derived exception message"
705                );
706            }
707            other => panic!("expected Completed, got {other:?}"),
708        }
709    }
710
711    #[tokio::test]
712    async fn continued_catch_clears_error_without_handled_marker() {
713        let mut ex = Exchange::default();
714        ex.set_property(PROPERTY_EXCEPTION_HANDLED, Value::Bool(true));
715
716        let mut seg = DoTrySegment {
717            try_body: seg_fail(CamelError::ProcessorError("boom".into())),
718            catches: vec![CatchClauseSegment {
719                matcher: CatchMatcher::ByVariant(vec!["ProcessorError".into()]),
720                on_when: None,
721                body: seg_check_then_complete(|ex| {
722                    assert!(ex.has_error(), "catch body must see the try error");
723                    assert!(
724                        matches!(ex.properties.get(PROPERTY_EXCEPTION_MESSAGE), Some(Value::String(s)) if s.contains("boom")),
725                        "catch body must see the derived exception message, got {:?}",
726                        ex.properties.get(PROPERTY_EXCEPTION_MESSAGE)
727                    );
728                }),
729                disposition: ExceptionDisposition::Continued,
730            }],
731            finally: None,
732        };
733
734        let result = seg.run(ex).await;
735        match result {
736            PipelineOutcome::Completed(ex) => {
737                assert!(
738                    !ex.has_error(),
739                    "continued catch must clear the exchange error"
740                );
741                assert!(
742                    !ex.properties.contains_key(PROPERTY_EXCEPTION_HANDLED),
743                    "Continued must not leave the handled marker"
744                );
745                assert!(
746                    !ex.properties.contains_key(PROPERTY_EXCEPTION_MESSAGE),
747                    "continued catch must clear the derived exception message"
748                );
749            }
750            other => panic!("expected Completed, got {other:?}"),
751        }
752    }
753
754    #[tokio::test]
755    async fn finally_after_handled_catch_sees_no_error() {
756        let finally_calls = Arc::new(AtomicU32::new(0));
757        let calls = Arc::clone(&finally_calls);
758        let mut seg = DoTrySegment {
759            try_body: seg_fail(CamelError::ProcessorError("boom".into())),
760            catches: vec![CatchClauseSegment {
761                matcher: CatchMatcher::ByVariant(vec!["ProcessorError".into()]),
762                on_when: None,
763                body: seg_complete(),
764                disposition: ExceptionDisposition::Handled,
765            }],
766            finally: Some(FinallyClauseSegment {
767                on_when: None,
768                body: seg_check_then_complete(move |ex| {
769                    calls.fetch_add(1, Ordering::SeqCst);
770                    assert!(
771                        !ex.has_error(),
772                        "finally must observe a clean exchange after a handled catch"
773                    );
774                    assert!(
775                        !ex.properties.contains_key(PROPERTY_EXCEPTION_MESSAGE),
776                        "derived exception properties must be cleared"
777                    );
778                }),
779            }),
780        };
781
782        let result = seg.run(Exchange::default()).await;
783        match result {
784            PipelineOutcome::Completed(ex) => {
785                assert!(!ex.has_error(), "handled catch must leave a clean exchange");
786            }
787            other => panic!("expected Completed, got {other:?}"),
788        }
789        assert_eq!(
790            finally_calls.load(Ordering::SeqCst),
791            1,
792            "finally must run exactly once"
793        );
794    }
795
796    // ── Catch-body failure envelope (compiled-segment path) ──
797
798    fn catch_fails_segment() -> DoTrySegment {
799        DoTrySegment {
800            try_body: seg_fail(CamelError::ProcessorError("orig".into())),
801            catches: vec![CatchClauseSegment {
802                matcher: CatchMatcher::ByVariant(vec!["ProcessorError".into()]),
803                on_when: None,
804                body: seg_fail(CamelError::Io("catch-fail".into())),
805                disposition: ExceptionDisposition::Handled,
806            }],
807            finally: None,
808        }
809    }
810
811    #[test]
812    fn catch_body_failure_returns_catch_err_and_marks_span() {
813        let mut seg = catch_fails_segment();
814        let (result, captured, span_records) = capture_debugs_with_span_records(|| {
815            // Declared `error` field so record_span_error's record lands.
816            let span = tracing::info_span!("dotry_seg_test", error = tracing::field::Empty);
817            let _guard = span.enter();
818            tokio::runtime::Builder::new_current_thread()
819                .enable_all()
820                .build()
821                .expect("current-thread runtime")
822                .block_on(async { seg.run(Exchange::default()).await })
823        });
824
825        assert!(
826            matches!(result, PipelineOutcome::Failed(CamelError::Io(_))),
827            "catch failure must surface the catch error as Failed(Io), got: {result:?}"
828        );
829        // The span recorded the `error` field with the CATCH error.
830        // Structured field lookup: substring `error=` would also match
831        // `original_error=` suffixes.
832        assert!(
833            span_records.iter().any(|line| {
834                captured_field(line, "error").is_some_and(|v| v.contains("catch-fail"))
835            }),
836            "expected span error record carrying the catch error, span records: {span_records:?}"
837        );
838        let original = record_field(&captured, "do_try catch block failed", "original_error")
839            .unwrap_or_else(|| {
840                panic!(
841                    "envelope record missing original_error field under active span, captured: {captured:?}"
842                )
843            });
844        assert!(
845            original.contains("orig"),
846            "original_error must carry the original error under an active span, got: {original}"
847        );
848    }
849
850    #[test]
851    fn catch_body_failure_emits_envelope_log() {
852        let mut seg = catch_fails_segment();
853        let (result, captured, _span_records) = capture_debugs_with_span_records(|| {
854            tokio::runtime::Builder::new_current_thread()
855                .enable_all()
856                .build()
857                .expect("current-thread runtime")
858                .block_on(async { seg.run(Exchange::default()).await })
859        });
860
861        assert!(
862            matches!(result, PipelineOutcome::Failed(CamelError::Io(_))),
863            "catch failure must surface the catch error as Failed(Io), got: {result:?}"
864        );
865        // Structured field lookup on the envelope record, not message
866        // formatting.
867        let original = record_field(&captured, "do_try catch block failed", "original_error")
868            .unwrap_or_else(|| {
869                panic!("envelope record missing original_error field, captured: {captured:?}")
870            });
871        let catch = record_field(&captured, "do_try catch block failed", "catch_error")
872            .unwrap_or_else(|| {
873                panic!("envelope record missing catch_error field, captured: {captured:?}")
874            });
875        assert!(
876            original.contains("orig"),
877            "original_error must carry the original error, got: {original}"
878        );
879        assert!(
880            catch.contains("catch-fail"),
881            "catch_error must carry the catch error, got: {catch}"
882        );
883    }
884
885    // ── Fallible predicate path (language-value-boundary task 1.4) ──
886
887    use camel_api::{ExpressionErrorClass, FilterPredicate, PredicateSource};
888
889    fn expression_failed() -> CamelError {
890        CamelError::ExpressionFailed {
891            language: "rhai".to_string(),
892            route_id: "r1".to_string(),
893            step_id: "step#0".to_string(),
894            verb: "on_when".to_string(),
895            class: ExpressionErrorClass::Runtime,
896            position: None,
897            conversion: None,
898            cause: None,
899        }
900    }
901
902    fn async_err_predicate(err: CamelError) -> PredicateSource {
903        PredicateSource::Async(Arc::new(move |_: &Exchange| {
904            let err = err.clone();
905            Box::pin(async move { Err(err) }) as camel_api::BoxBoolFuture
906        }))
907    }
908
909    #[tokio::test]
910    async fn finally_on_when_predicate_error_fails_segment() {
911        let finally_call = Arc::new(AtomicU32::new(0));
912        let mut seg = DoTrySegment {
913            try_body: seg_complete(),
914            catches: vec![],
915            finally: Some(FinallyClauseSegment {
916                on_when: Some(async_err_predicate(expression_failed())),
917                body: seg_record(finally_call.clone()),
918            }),
919        };
920
921        let result = seg.run(Exchange::default()).await;
922        match result {
923            PipelineOutcome::Failed(CamelError::ExpressionFailed { .. }) => {}
924            other => panic!("expected Failed(ExpressionFailed), got {other:?}"),
925        }
926        assert_eq!(
927            finally_call.load(Ordering::SeqCst),
928            0,
929            "finally body must not run when its on_when predicate errors"
930        );
931    }
932
933    // ── No-catch-matched path (mission 353) ──
934
935    /// doTry with no matching catch must run finally and propagate the
936    /// original try error as `Failed` (the segment is the only doTry runtime).
937    /// Guards against regressing back to `Completed(bugged_swallow)`.
938    #[tokio::test]
939    async fn no_clause_matches_runs_finally_and_propagates_original() {
940        let catch_call = Arc::new(AtomicU32::new(0));
941        let finally_call = Arc::new(AtomicU32::new(0));
942
943        let mut seg = DoTrySegment {
944            try_body: seg_fail(CamelError::EndpointCreationFailed(
945                "direct endpoint 'direct:does-not-exist' not registered".into(),
946            )),
947            catches: vec![CatchClauseSegment {
948                matcher: CatchMatcher::ByVariant(vec!["Io".into()]),
949                on_when: None,
950                body: seg_record(catch_call.clone()),
951                disposition: ExceptionDisposition::Handled,
952            }],
953            finally: Some(FinallyClauseSegment {
954                on_when: None,
955                body: seg_record(finally_call.clone()),
956            }),
957        };
958
959        let result = seg.run(Exchange::default()).await;
960        match result {
961            PipelineOutcome::Failed(CamelError::EndpointCreationFailed(msg)) => {
962                assert!(
963                    msg.contains("does-not-exist"),
964                    "propagated error must be the original try error, got: {msg}"
965                );
966            }
967            other => {
968                panic!("no catch matched: expected Failed(EndpointCreationFailed), got {other:?}")
969            }
970        }
971        assert_eq!(
972            finally_call.load(Ordering::SeqCst),
973            1,
974            "finally must run exactly once when no catch matches"
975        );
976        assert_eq!(
977            catch_call.load(Ordering::SeqCst),
978            0,
979            "the unmatched catch body must not run"
980        );
981    }
982    // ── Ported from the deleted Tower doTry service (no coverage loss) ──
983
984    use camel_language_api::{EvalMeta, LanguageError, to_expression_failed};
985
986    fn catch_variant(names: &[&str], body: camel_api::OutcomeSegment) -> CatchClauseSegment {
987        catch_variant_with(names, body, ExceptionDisposition::Handled)
988    }
989
990    fn catch_variant_with(
991        names: &[&str],
992        body: camel_api::OutcomeSegment,
993        disposition: ExceptionDisposition,
994    ) -> CatchClauseSegment {
995        CatchClauseSegment {
996            matcher: CatchMatcher::ByVariant(names.iter().map(|n| (*n).to_string()).collect()),
997            on_when: None,
998            body,
999            disposition,
1000        }
1001    }
1002
1003    fn finally_seg(body: camel_api::OutcomeSegment) -> FinallyClauseSegment {
1004        FinallyClauseSegment {
1005            on_when: None,
1006            body,
1007        }
1008    }
1009
1010    #[tokio::test]
1011    async fn happy_path_try_succeeds_finally_runs() {
1012        let finally_flag = Arc::new(AtomicU32::new(0));
1013        let mut seg = DoTrySegment {
1014            try_body: seg_complete(),
1015            catches: vec![],
1016            finally: Some(finally_seg(seg_record(finally_flag.clone()))),
1017        };
1018
1019        let result = seg.run(Exchange::default()).await;
1020        assert!(
1021            matches!(result, PipelineOutcome::Completed(_)),
1022            "try success must complete, got {result:?}"
1023        );
1024        assert_eq!(finally_flag.load(Ordering::SeqCst), 1);
1025    }
1026
1027    #[tokio::test]
1028    async fn catch_by_variant_handled_returns_ok() {
1029        let mut seg = DoTrySegment {
1030            try_body: seg_fail(CamelError::ProcessorError("boom".into())),
1031            catches: vec![catch_variant(&["ProcessorError"], seg_complete())],
1032            finally: None,
1033        };
1034
1035        let result = seg.run(Exchange::default()).await;
1036        match result {
1037            PipelineOutcome::Completed(ex) => {
1038                assert!(!ex.has_error(), "Handled must clear the exchange error");
1039                assert_eq!(
1040                    ex.properties.get(PROPERTY_EXCEPTION_HANDLED),
1041                    Some(&Value::Bool(true)),
1042                    "Handled must set CamelExceptionHandled"
1043                );
1044            }
1045            other => panic!("Handled must return Completed, got {other:?}"),
1046        }
1047    }
1048
1049    #[tokio::test]
1050    async fn catch_by_variant_propagate_runs_side_effects_and_rethrows() {
1051        let side_effect = Arc::new(AtomicU32::new(0));
1052        let mut seg = DoTrySegment {
1053            try_body: seg_fail(CamelError::ProcessorError("boom".into())),
1054            catches: vec![catch_variant_with(
1055                &["ProcessorError"],
1056                seg_record(side_effect.clone()),
1057                ExceptionDisposition::Propagate,
1058            )],
1059            finally: None,
1060        };
1061
1062        let result = seg.run(Exchange::default()).await;
1063        assert!(
1064            matches!(
1065                result,
1066                PipelineOutcome::Failed(CamelError::ProcessorError(_))
1067            ),
1068            "Propagate must rethrow the original error, got {result:?}"
1069        );
1070        assert_eq!(
1071            side_effect.load(Ordering::SeqCst),
1072            1,
1073            "catch branch must have run for side-effects"
1074        );
1075    }
1076
1077    #[tokio::test]
1078    async fn catch_by_predicate_matches_via_exception_kind() {
1079        let predicate = FilterPredicate::new(|ex: &Exchange| {
1080            ex.properties
1081                .get(camel_api::exchange::PROPERTY_EXCEPTION_KIND)
1082                .map(|v| matches!(v, camel_api::Value::String(s) if s == "io"))
1083                .unwrap_or(false)
1084        });
1085        let mut seg = DoTrySegment {
1086            try_body: seg_fail(CamelError::Io("disk full".into())),
1087            catches: vec![CatchClauseSegment {
1088                matcher: CatchMatcher::Predicate(PredicateSource::Sync(predicate)),
1089                on_when: None,
1090                body: seg_complete(),
1091                disposition: ExceptionDisposition::Handled,
1092            }],
1093            finally: None,
1094        };
1095
1096        let result = seg.run(Exchange::default()).await;
1097        assert!(
1098            matches!(result, PipelineOutcome::Completed(_)),
1099            "Predicate matcher must catch the error and Handled must return Completed, got {result:?}"
1100        );
1101    }
1102
1103    #[tokio::test]
1104    async fn first_match_wins_subsequent_clauses_not_evaluated() {
1105        let first_call = Arc::new(AtomicU32::new(0));
1106        let second_call = Arc::new(AtomicU32::new(0));
1107        let mut seg = DoTrySegment {
1108            try_body: seg_fail(CamelError::Io("err".into())),
1109            catches: vec![
1110                catch_variant(&["Io"], seg_record(first_call.clone())),
1111                catch_variant(&["*"], seg_record(second_call.clone())),
1112            ],
1113            finally: None,
1114        };
1115
1116        let _ = seg.run(Exchange::default()).await;
1117        assert_eq!(first_call.load(Ordering::SeqCst), 1);
1118        assert_eq!(second_call.load(Ordering::SeqCst), 0);
1119    }
1120
1121    #[tokio::test]
1122    async fn catch_branch_throws_new_error_wins() {
1123        let mut seg = DoTrySegment {
1124            try_body: seg_fail(CamelError::ProcessorError("orig".into())),
1125            catches: vec![catch_variant(
1126                &["ProcessorError"],
1127                seg_fail(CamelError::Io("catch-fail".into())),
1128            )],
1129            finally: None,
1130        };
1131
1132        let result = seg.run(Exchange::default()).await;
1133        assert!(
1134            matches!(result, PipelineOutcome::Failed(CamelError::Io(_))),
1135            "catch error must win over the try error, got {result:?}"
1136        );
1137    }
1138
1139    #[tokio::test]
1140    async fn finally_throws_with_no_previous_error_propagates_finally_error() {
1141        let mut seg = DoTrySegment {
1142            try_body: seg_complete(),
1143            catches: vec![],
1144            finally: Some(finally_seg(seg_fail(CamelError::Config("fin".into())))),
1145        };
1146
1147        let result = seg.run(Exchange::default()).await;
1148        assert!(
1149            matches!(result, PipelineOutcome::Failed(CamelError::Config(_))),
1150            "finally error must propagate when no previous error exists, got {result:?}"
1151        );
1152    }
1153
1154    #[tokio::test]
1155    async fn finally_throws_with_previous_error_restores_previous() {
1156        let mut seg = DoTrySegment {
1157            try_body: seg_fail(CamelError::ProcessorError("orig".into())),
1158            catches: vec![],
1159            finally: Some(finally_seg(seg_fail(CamelError::Config("fin".into())))),
1160        };
1161
1162        let result = seg.run(Exchange::default()).await;
1163        assert!(
1164            matches!(
1165                result,
1166                PipelineOutcome::Failed(CamelError::ProcessorError(_))
1167            ),
1168            "previous error must be restored when finally throws (Camel parity), got {result:?}"
1169        );
1170    }
1171
1172    #[tokio::test]
1173    async fn stale_handled_marker_cleared_on_entry() {
1174        let mut ex = Exchange::default();
1175        ex.set_property(
1176            camel_api::exchange::PROPERTY_EXCEPTION_HANDLED,
1177            camel_api::Value::Bool(true),
1178        );
1179        ex.set_error(CamelError::ProcessorError("stale".into()));
1180        let mut seg = DoTrySegment {
1181            try_body: seg_complete(),
1182            catches: vec![],
1183            finally: None,
1184        };
1185
1186        let result = seg.run(ex).await;
1187        match result {
1188            PipelineOutcome::Completed(ex) => assert!(
1189                !ex.properties
1190                    .contains_key(camel_api::exchange::PROPERTY_EXCEPTION_HANDLED),
1191                "stale CamelExceptionHandled must be cleared on entry"
1192            ),
1193            other => panic!("expected Completed, got {other:?}"),
1194        }
1195    }
1196
1197    #[tokio::test]
1198    async fn nested_do_try_inner_catch_does_not_leak_to_outer() {
1199        let inner = DoTrySegment {
1200            try_body: seg_fail(CamelError::Io("inner".into())),
1201            catches: vec![catch_variant(&["Io"], seg_complete())],
1202            finally: None,
1203        };
1204        let mut outer = DoTrySegment {
1205            try_body: camel_api::OutcomeSegment::new(Box::new(inner)),
1206            catches: vec![catch_variant(&["Io"], seg_complete())],
1207            finally: None,
1208        };
1209
1210        let result = outer.run(Exchange::default()).await;
1211        match result {
1212            PipelineOutcome::Completed(ex) => {
1213                assert!(
1214                    !ex.has_error(),
1215                    "inner handled error must not leak to the outer exchange"
1216                );
1217            }
1218            other => panic!(
1219                "outer must see Completed because inner handled its own error, got {other:?}"
1220            ),
1221        }
1222    }
1223
1224    #[tokio::test]
1225    async fn catch_all_only_fires_when_no_specific_clause_matches() {
1226        let processor_call = Arc::new(AtomicU32::new(0));
1227        let catch_all_call = Arc::new(AtomicU32::new(0));
1228        let mut seg = DoTrySegment {
1229            try_body: seg_fail(CamelError::Io("err".into())),
1230            catches: vec![
1231                catch_variant(&["ProcessorError"], seg_record(processor_call.clone())),
1232                catch_variant(&["*"], seg_record(catch_all_call.clone())),
1233            ],
1234            finally: None,
1235        };
1236
1237        let _ = seg.run(Exchange::default()).await;
1238        assert_eq!(
1239            processor_call.load(Ordering::SeqCst),
1240            0,
1241            "specific ProcessorError clause must not fire on Io error"
1242        );
1243        assert_eq!(
1244            catch_all_call.load(Ordering::SeqCst),
1245            1,
1246            "catch-all clause must fire when no specific clause matches"
1247        );
1248    }
1249
1250    /// Java try/catch/finally parity (JLS §14.20.2): a failing catch body
1251    /// does not skip finally, and the catch error remains the surfaced
1252    /// failure. This rebuilds the catch-and-finally coverage lost with the
1253    /// deleted builder-only `DoTryService`.
1254    #[tokio::test]
1255    async fn catch_body_failure_runs_finally_once_then_returns_catch_err() {
1256        let finally_flag = Arc::new(AtomicU32::new(0));
1257        let mut seg = DoTrySegment {
1258            try_body: seg_fail(CamelError::ProcessorError("orig".into())),
1259            catches: vec![catch_variant(
1260                &["ProcessorError"],
1261                seg_fail(CamelError::Io("catch-fail".into())),
1262            )],
1263            finally: Some(finally_seg(seg_record(finally_flag.clone()))),
1264        };
1265
1266        let result = seg.run(Exchange::default()).await;
1267        assert!(
1268            matches!(result, PipelineOutcome::Failed(CamelError::Io(_))),
1269            "catch_err must propagate (not original ProcessorError), got {result:?}"
1270        );
1271        assert_eq!(
1272            finally_flag.load(Ordering::SeqCst),
1273            1,
1274            "finally must run exactly once even when the catch body fails (Java try/catch/finally parity)"
1275        );
1276    }
1277
1278    /// Real exercise of the finally/catch parity rule: the finally body runs
1279    /// (and throws) even when the catch body fails, and the catch error still
1280    /// wins over the finally error (Camel parity: a throwing finally restores
1281    /// the previous error). Before the catch-body-failure path ran finally,
1282    /// this test passed vacuously.
1283    #[tokio::test]
1284    async fn catch_throws_and_throwing_finally_still_returns_catch_err() {
1285        let finally_flag = Arc::new(AtomicU32::new(0));
1286        let mut seg = DoTrySegment {
1287            try_body: seg_fail(CamelError::ProcessorError("orig".into())),
1288            catches: vec![catch_variant(
1289                &["ProcessorError"],
1290                seg_fail(CamelError::Io("catch-fail".into())),
1291            )],
1292            finally: Some(finally_seg(seg_count_then_fail(
1293                finally_flag.clone(),
1294                CamelError::Config("fin-fail".into()),
1295            ))),
1296        };
1297
1298        let result = seg.run(Exchange::default()).await;
1299        assert!(
1300            matches!(result, PipelineOutcome::Failed(CamelError::Io(_))),
1301            "catch_err (Io) must be returned over finally_err (Config), got {result:?}"
1302        );
1303        assert_eq!(
1304            finally_flag.load(Ordering::SeqCst),
1305            1,
1306            "finally must run exactly once even when its own body fails"
1307        );
1308    }
1309
1310    /// Stop in finally takes precedence over the pending catch failure: the
1311    /// outer route stops with the finally exchange (mutation preserved), and
1312    /// the finally body still ran exactly once. Pins the `Stopped` arm of
1313    /// `fail_after_finally` on the catch-body-failure path.
1314    #[tokio::test]
1315    async fn catch_body_failure_then_finally_stops_stops_outer_route() {
1316        let finally_flag = Arc::new(AtomicU32::new(0));
1317        let mut seg = DoTrySegment {
1318            try_body: seg_fail(CamelError::ProcessorError("orig".into())),
1319            catches: vec![catch_variant(
1320                &["ProcessorError"],
1321                seg_fail(CamelError::Io("catch-fail".into())),
1322            )],
1323            finally: Some(finally_seg(seg_count_then_stop(
1324                finally_flag.clone(),
1325                |ex| {
1326                    ex.set_property("finally_stopped_marker", camel_api::Value::Bool(true));
1327                },
1328            ))),
1329        };
1330
1331        let result = seg.run(Exchange::default()).await;
1332        match result {
1333            PipelineOutcome::Stopped(ex) => {
1334                assert_eq!(
1335                    ex.properties.get("finally_stopped_marker"),
1336                    Some(&camel_api::Value::Bool(true)),
1337                    "finally exchange mutation must be preserved in Stopped"
1338                );
1339            }
1340            other => panic!("expected Stopped, got {other:?}"),
1341        }
1342        assert_eq!(
1343            finally_flag.load(Ordering::SeqCst),
1344            1,
1345            "finally must run exactly once before the outer route stops"
1346        );
1347    }
1348
1349    #[tokio::test]
1350    async fn finally_on_when_false_with_previous_error_still_propagates_original() {
1351        let finally_flag = Arc::new(AtomicU32::new(0));
1352        let mut seg = DoTrySegment {
1353            try_body: seg_fail(CamelError::ProcessorError("orig".into())),
1354            catches: vec![],
1355            finally: Some(FinallyClauseSegment {
1356                on_when: Some(PredicateSource::Sync(FilterPredicate::new(|_ex| false))),
1357                body: seg_record(finally_flag.clone()),
1358            }),
1359        };
1360
1361        let result = seg.run(Exchange::default()).await;
1362        assert!(
1363            matches!(
1364                result,
1365                PipelineOutcome::Failed(CamelError::ProcessorError(_))
1366            ),
1367            "original error must propagate even when finally_on_when skips finally, got {result:?}"
1368        );
1369        assert_eq!(
1370            finally_flag.load(Ordering::SeqCst),
1371            0,
1372            "doFinally must NOT run when on_when returns false"
1373        );
1374    }
1375
1376    #[tokio::test]
1377    async fn catch_throws_under_propagate_disposition_returns_catch_err() {
1378        let mut seg = DoTrySegment {
1379            try_body: seg_fail(CamelError::ProcessorError("orig".into())),
1380            catches: vec![catch_variant_with(
1381                &["ProcessorError"],
1382                seg_fail(CamelError::Io("catch-fail".into())),
1383                ExceptionDisposition::Propagate,
1384            )],
1385            finally: None,
1386        };
1387
1388        let result = seg.run(Exchange::default()).await;
1389        assert!(
1390            matches!(result, PipelineOutcome::Failed(CamelError::Io(_))),
1391            "Propagate-disposition catch failure must surface the catch error, got {result:?}"
1392        );
1393    }
1394
1395    #[tokio::test]
1396    async fn catch_when_predicate_error_chains_original() {
1397        let mut seg = DoTrySegment {
1398            try_body: seg_fail(CamelError::ProcessorError("boom".into())),
1399            catches: vec![CatchClauseSegment {
1400                matcher: CatchMatcher::Predicate(async_err_predicate(expression_failed())),
1401                on_when: None,
1402                body: seg_complete(),
1403                disposition: ExceptionDisposition::Handled,
1404            }],
1405            finally: None,
1406        };
1407
1408        let result = seg.run(Exchange::default()).await;
1409        match result {
1410            PipelineOutcome::Failed(CamelError::ExpressionFailed {
1411                cause: Some(cause), ..
1412            }) => {
1413                assert!(
1414                    cause.to_string().contains("boom"),
1415                    "cause must carry the original error, got: {cause}"
1416                );
1417            }
1418            other => panic!("expected Failed(ExpressionFailed) with chained cause, got {other:?}"),
1419        }
1420    }
1421
1422    #[tokio::test]
1423    async fn catch_on_when_predicate_error_chains_original() {
1424        let mut seg = DoTrySegment {
1425            try_body: seg_fail(CamelError::ProcessorError("boom".into())),
1426            catches: vec![CatchClauseSegment {
1427                matcher: CatchMatcher::ByVariant(vec!["*".into()]),
1428                on_when: Some(async_err_predicate(expression_failed())),
1429                body: seg_complete(),
1430                disposition: ExceptionDisposition::Handled,
1431            }],
1432            finally: None,
1433        };
1434
1435        let result = seg.run(Exchange::default()).await;
1436        match result {
1437            PipelineOutcome::Failed(CamelError::ExpressionFailed {
1438                cause: Some(cause), ..
1439            }) => {
1440                assert!(
1441                    cause.to_string().contains("boom"),
1442                    "cause must carry the original error, got: {cause}"
1443                );
1444            }
1445            other => panic!("expected Failed(ExpressionFailed) with chained cause, got {other:?}"),
1446        }
1447    }
1448
1449    // ── Mapper-generated cause replacement (ported from do_try.rs) ──
1450
1451    fn caller_diagnostic_failed(cause: CamelError) -> CamelError {
1452        CamelError::ExpressionFailed {
1453            language: "rhai".to_string(),
1454            route_id: "r1".to_string(),
1455            step_id: "s1".to_string(),
1456            verb: "when".to_string(),
1457            class: ExpressionErrorClass::Runtime,
1458            position: None,
1459            conversion: None,
1460            cause: Some(Box::new(cause)),
1461        }
1462    }
1463
1464    #[test]
1465    fn chain_replaces_mapper_generated_cause() {
1466        let meta = EvalMeta {
1467            language: "xpath".into(),
1468            route_id: "r1".into(),
1469            step_id: "s1".into(),
1470            verb: "when".into(),
1471            target: None,
1472        };
1473        let mapper_err = to_expression_failed(
1474            LanguageError::EvalFailure {
1475                class: ExpressionErrorClass::Parse,
1476                position: None,
1477                detail: Some("body is not valid XML".into()),
1478            },
1479            &meta,
1480        );
1481
1482        let result = chain_predicate_error(mapper_err, CamelError::ProcessorError("boom".into()));
1483
1484        match result {
1485            CamelError::ExpressionFailed {
1486                cause: Some(cause), ..
1487            } => {
1488                assert!(
1489                    cause.to_string().contains("boom"),
1490                    "mapper diagnostic cause must be replaced by the original, got: {cause}"
1491                );
1492            }
1493            other => panic!("expected ExpressionFailed with chained cause, got {other:?}"),
1494        }
1495    }
1496
1497    #[test]
1498    fn chain_preserves_caller_cause() {
1499        let predicate_err =
1500            caller_diagnostic_failed(CamelError::ProcessorError("caller diagnostic".into()));
1501
1502        let result =
1503            chain_predicate_error(predicate_err, CamelError::ProcessorError("boom".into()));
1504
1505        match result {
1506            CamelError::ExpressionFailed {
1507                cause: Some(cause), ..
1508            } => {
1509                let rendered = cause.to_string();
1510                assert!(
1511                    rendered.contains("caller diagnostic"),
1512                    "caller cause must pass through untouched, got: {rendered}"
1513                );
1514                assert!(
1515                    !rendered.contains("boom"),
1516                    "caller cause must not be replaced, got: {rendered}"
1517                );
1518            }
1519            other => panic!("expected ExpressionFailed with caller cause, got {other:?}"),
1520        }
1521    }
1522
1523    #[test]
1524    fn chain_preserves_caller_source_bearing_cause() {
1525        let predicate_err = caller_diagnostic_failed(CamelError::ProcessorErrorWithSource(
1526            "caller diagnostic".into(),
1527            Arc::new(std::io::Error::other("caller source")),
1528        ));
1529
1530        let result =
1531            chain_predicate_error(predicate_err, CamelError::ProcessorError("boom".into()));
1532
1533        match result {
1534            CamelError::ExpressionFailed {
1535                cause: Some(cause), ..
1536            } => {
1537                let rendered = cause.to_string();
1538                assert!(
1539                    rendered.contains("caller diagnostic"),
1540                    "caller cause must pass through untouched, got: {rendered}"
1541                );
1542                let source = std::error::Error::source(cause.as_ref())
1543                    .unwrap_or_else(|| panic!("caller source must survive, cause: {cause:?}"));
1544                assert!(
1545                    source.to_string().contains("caller source"),
1546                    "caller source must survive untouched, got: {source}"
1547                );
1548            }
1549            other => panic!("expected ExpressionFailed with caller cause, got {other:?}"),
1550        }
1551    }
1552
1553    // ── Handled-marker / caught-property lifetime tests ──
1554
1555    struct MarkThenFail;
1556
1557    impl OutcomePipeline for MarkThenFail {
1558        fn clone_box(&self) -> Box<dyn OutcomePipeline> {
1559            Box::new(MarkThenFail)
1560        }
1561        fn run<'a>(
1562            &'a mut self,
1563            mut exchange: Exchange,
1564        ) -> Pin<Box<dyn Future<Output = PipelineOutcome> + Send + 'a>> {
1565            Box::pin(async move {
1566                exchange.set_property(PROPERTY_EXCEPTION_HANDLED, Value::Bool(true));
1567                PipelineOutcome::Failed(CamelError::ProcessorError("try".into()))
1568            })
1569        }
1570    }
1571
1572    #[tokio::test]
1573    async fn nested_handled_marker_survives_outer_continued() {
1574        let inner = DoTrySegment {
1575            try_body: seg_fail(CamelError::Io("inner".into())),
1576            catches: vec![catch_variant(&["Io"], seg_complete())],
1577            finally: None,
1578        };
1579        let mut outer = DoTrySegment {
1580            try_body: seg_fail(CamelError::ProcessorError("outer".into())),
1581            catches: vec![catch_variant_with(
1582                &["ProcessorError"],
1583                camel_api::OutcomeSegment::new(Box::new(inner)),
1584                ExceptionDisposition::Continued,
1585            )],
1586            finally: None,
1587        };
1588
1589        let result = outer.run(Exchange::default()).await;
1590        match result {
1591            PipelineOutcome::Completed(ex) => {
1592                assert!(
1593                    !ex.has_error(),
1594                    "continued catch must leave a clean exchange"
1595                );
1596                assert_eq!(
1597                    ex.properties.get(PROPERTY_EXCEPTION_HANDLED),
1598                    Some(&Value::Bool(true)),
1599                    "inner Handled marker must survive the outer Continued exit"
1600                );
1601                assert!(
1602                    !ex.properties.contains_key(PROPERTY_EXCEPTION_CAUGHT),
1603                    "continued exit must clear CamelExceptionCaught"
1604                );
1605            }
1606            other => panic!("expected Completed, got {other:?}"),
1607        }
1608    }
1609
1610    #[tokio::test]
1611    async fn failing_try_body_marker_does_not_reach_catch_chain() {
1612        let mut outer = DoTrySegment {
1613            try_body: camel_api::OutcomeSegment::new(Box::new(MarkThenFail)),
1614            catches: vec![catch_variant_with(
1615                &["ProcessorError"],
1616                seg_complete(),
1617                ExceptionDisposition::Continued,
1618            )],
1619            finally: None,
1620        };
1621
1622        let result = outer.run(Exchange::default()).await;
1623        match result {
1624            PipelineOutcome::Completed(ex) => {
1625                assert!(
1626                    !ex.has_error(),
1627                    "continued catch must leave a clean exchange"
1628                );
1629                assert!(
1630                    !ex.properties.contains_key(PROPERTY_EXCEPTION_HANDLED),
1631                    "a marker set by a failing try body must not reach the catch chain"
1632                );
1633            }
1634            other => panic!("expected Completed, got {other:?}"),
1635        }
1636    }
1637
1638    #[tokio::test]
1639    async fn caught_property_absent_after_handled_and_continued_exit() {
1640        for disposition in [
1641            ExceptionDisposition::Handled,
1642            ExceptionDisposition::Continued,
1643        ] {
1644            let mut seg = DoTrySegment {
1645                try_body: seg_fail(CamelError::ProcessorError("boom".into())),
1646                catches: vec![catch_variant_with(
1647                    &["ProcessorError"],
1648                    seg_check_then_complete(|ex| {
1649                        assert!(
1650                            ex.properties.contains_key(PROPERTY_EXCEPTION_CAUGHT),
1651                            "catch body must see CamelExceptionCaught"
1652                        );
1653                    }),
1654                    disposition,
1655                )],
1656                finally: None,
1657            };
1658
1659            let result = seg.run(Exchange::default()).await;
1660            match result {
1661                PipelineOutcome::Completed(ex) => {
1662                    assert!(
1663                        !ex.has_error(),
1664                        "{disposition:?} must clear the exchange error"
1665                    );
1666                    assert!(
1667                        !ex.properties.contains_key(PROPERTY_EXCEPTION_CAUGHT),
1668                        "{disposition:?} exit must clear CamelExceptionCaught"
1669                    );
1670                    if disposition == ExceptionDisposition::Handled {
1671                        assert_eq!(
1672                            ex.properties.get(PROPERTY_EXCEPTION_HANDLED),
1673                            Some(&Value::Bool(true)),
1674                            "Handled exit must keep the handled marker"
1675                        );
1676                    } else {
1677                        assert!(
1678                            !ex.properties.contains_key(PROPERTY_EXCEPTION_HANDLED),
1679                            "Continued exit must not leave the handled marker"
1680                        );
1681                    }
1682                }
1683                other => panic!("expected Completed, got {other:?}"),
1684            }
1685        }
1686    }
1687}