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