Skip to main content

camel_core/lifecycle/adapters/step_compilers/
mod.rs

1//! StepCompiler registry pattern — extract from step_resolution.rs
2//!
3//! Each compiler group is responsible for matching specific `BuilderStep` variants.
4//! The registry dispatches each step to compilers in registration order; the first
5//! compiler that returns `Matched` wins. Compilers that don't handle a variant
6//! return `NotHandled(step)` to pass it to the next compiler.
7
8use std::sync::Arc;
9
10use camel_api::{
11    BodyType, BoxProcessor, CamelError, FunctionInvoker, ProducerContext, SpanKindHint,
12    StepLifecycle,
13};
14use camel_component_api::{ComponentContext, RuntimeObservability};
15use camel_endpoint::parse_uri;
16
17use crate::intercept::InterceptRules;
18use crate::lifecycle::adapters::route_controller::SharedLanguageRegistry;
19use crate::lifecycle::adapters::step_resolution::FunctionStagingMode;
20use crate::lifecycle::application::route_definition::BuilderStep;
21use crate::{CacheRegistry, ClaimCheckRegistry, IdempotentRegistry};
22use camel_bean::BeanRegistry;
23
24mod control_flow;
25mod core;
26mod endpoints;
27mod error_handling;
28mod middleware;
29mod routing;
30mod splitting;
31mod transforms;
32
33/// A compiled pipeline step.
34///
35/// `Process` is the normal case: a boxed processor plus its optional body
36/// contract. `Stop` (added in Task 3b) is the Stop EIP marker — `run_steps`
37/// recognises it and produces `PipelineOutcome::Stopped` without invoking a
38/// Tower service. `Segment` (added in Task 3) wraps an `OutcomeSegment` for
39/// structural EIPs with outcome-aware sub-pipelines.
40///
41/// **Boundary:** `CompiledStep` is the compile-time representation. At runtime,
42/// `run_steps` consumes a `Vec<CompiledStep>` (Stop variants included) and
43/// produces a `PipelineOutcome`; the wrapping `Service<Exchange>` impl
44/// translates `PipelineOutcome` back to `Result<Exchange, CamelError>`. See
45/// ADR-0024.
46#[derive(Debug, Clone)]
47pub enum CompiledStep {
48    Process {
49        processor: BoxProcessor,
50        body_contract: Option<BodyType>,
51        /// Lifecycle handle for this processor, if it is stateful.
52        /// `None` for stateless processors (the common case).
53        lifecycle: Option<Arc<dyn StepLifecycle>>,
54        /// Stable span name (e.g. `to:direct`, `split`), stamped by
55        /// `StepCompilerRegistry::compile_step` from
56        /// `BuilderStep::span_label`. `None` for anonymous steps — spans
57        /// fall back to the positional `step-{index}` name. Read by
58        /// `compose_traced_pipeline` / `segment_span` in route_compiler.rs.
59        label: Option<Arc<str>>,
60        /// Span kind for this step's step span, stamped by
61        /// `StepCompilerRegistry::compile_step` from
62        /// `BuilderStep::span_kind_hint`. `Internal` for steps built
63        /// outside the registry. Read by `compose_traced_pipeline` in
64        /// route_compiler.rs.
65        kind_hint: SpanKindHint,
66        /// Declared send URI for `To` steps — the raw authored text,
67        /// stamped by `StepCompilerRegistry::compile_step` from
68        /// `BuilderStep::to_uri_metadata` BEFORE endpoint resolution and
69        /// interception (a `SkipTo` substitution or `DivertCopyTo`
70        /// diversion never rewrites it). `None` for every non-To step.
71        /// Stored as shared immutable text; read by the tracing
72        /// pipeline (steplatency task 2.1) in route_compiler.rs.
73        to_uri: Option<Arc<str>>,
74    },
75    /// Stop EIP marker. `run_steps` produces `PipelineOutcome::Stopped(ex)`
76    /// without invoking a Tower service. Replaces `StopService` (Task 7).
77    Stop,
78    /// Outcome-aware structural EIP segment. `run_steps` invokes
79    /// `segment.run(ex)` and matches on the returned `PipelineOutcome`.
80    /// See ADR-0025.
81    Segment {
82        segment: camel_api::OutcomeSegment,
83        body_contract: Option<BodyType>,
84        /// Lifecycle handles from children nested inside this segment.
85        /// `Option<Vec<...>>` (not `Option<Arc<...>>`) because multiple stateful
86        /// children (e.g. Idempotent+Resequencer inside Filter) each
87        /// register independently.
88        lifecycle: Option<Vec<Arc<dyn StepLifecycle>>>,
89        /// Stable span name, same contract as [`CompiledStep::Process`]'s
90        /// `label` field.
91        label: Option<Arc<str>>,
92    },
93}
94
95impl CompiledStep {
96    /// Overwrite the span label of a `Process`/`Segment` step; no-op on `Stop`
97    /// (the marker produces no step span, so it carries no label).
98    pub(crate) fn set_label(&mut self, label: Option<String>) {
99        let label = label.map(Arc::from);
100        match self {
101            CompiledStep::Process { label: slot, .. }
102            | CompiledStep::Segment { label: slot, .. } => {
103                *slot = label;
104            }
105            CompiledStep::Stop => {}
106        }
107    }
108
109    /// Overwrite the span kind hint of a `Process` step; no-op on `Stop` and
110    /// `Segment` (neither produces an individual step span, so neither
111    /// carries a kind hint).
112    pub(crate) fn set_kind_hint(&mut self, hint: SpanKindHint) {
113        match self {
114            CompiledStep::Process {
115                kind_hint: slot, ..
116            } => *slot = hint,
117            CompiledStep::Stop | CompiledStep::Segment { .. } => {}
118        }
119    }
120
121    /// Overwrite the declared send URI of a `Process` step; no-op on `Stop`
122    /// and `Segment` (neither is a send step, so neither carries declared
123    /// URI metadata).
124    pub(crate) fn set_to_uri(&mut self, to_uri: Option<Arc<str>>) {
125        match self {
126            CompiledStep::Process { to_uri: slot, .. } => *slot = to_uri,
127            CompiledStep::Stop | CompiledStep::Segment { .. } => {}
128        }
129    }
130}
131
132/// Result from a compiler: either it handled the step, or it did not recognize
133/// the variant and returns the step for the next compiler.
134///
135/// `Result` is intentionally outside this enum (returned by `StepCompiler::compile`)
136/// so that compiler arms can use the `?` operator for propagated errors instead of
137/// wrapping every `Err` in `Matched(Err(e))`.
138pub(crate) enum CompileOutcome {
139    Matched(CompiledStep),
140    NotHandled(BuilderStep),
141}
142
143/// A compiler that can handle one or more `BuilderStep` variants.
144///
145/// The `compile` method receives ownership of the step. If the compiler recognizes
146/// the variant it returns `Ok(CompileOutcome::Matched(...))`. Otherwise it returns
147/// `Ok(CompileOutcome::NotHandled(step))` to pass the step to the next compiler.
148/// Compilation errors are returned as `Err(CamelError)`.
149pub(crate) trait StepCompiler: Send + Sync {
150    fn compile(
151        &self,
152        step: BuilderStep,
153        step_index: usize,
154        ctx: &CompilationContext,
155        registry: &StepCompilerRegistry,
156    ) -> Result<CompileOutcome, CamelError>;
157}
158
159/// Shared context passed to every compiler invocation.
160pub(crate) struct CompilationContext<'a> {
161    pub producer_ctx: &'a ProducerContext,
162    pub rt: Arc<dyn RuntimeObservability>,
163    pub languages: &'a SharedLanguageRegistry,
164    pub beans: &'a Arc<std::sync::Mutex<BeanRegistry>>,
165    pub function_invoker: Option<Arc<dyn FunctionInvoker>>,
166    pub component_ctx: Arc<dyn ComponentContext>,
167    pub route_id: Option<&'a str>,
168    pub staging_mode: &'a FunctionStagingMode,
169    /// Idempotent repository registry. Used by the `IdempotentConsumer`
170    /// compiler arm to resolve repository names into `Arc<dyn IdempotentRepository>`.
171    pub idempotent_repositories: &'a IdempotentRegistry,
172    /// Claim check repository registry. Used by the `ClaimCheck` compiler arm
173    /// to resolve repository names into `Arc<dyn ClaimCheckRepository>`.
174    pub claim_check_repositories: &'a ClaimCheckRegistry,
175    /// Cache repository registry. Used by the `Cache`, `CacheInvalidate`, and
176    /// `CachePeekStale` compiler arms to resolve repository names into
177    /// `Arc<dyn CacheRepository>`.
178    pub cache_repositories: &'a CacheRegistry,
179    /// Route send-point interception rules captured at compile time.
180    /// Consulted by send-step compilation (Task 4/5).
181    pub intercept: InterceptRules,
182}
183
184impl<'a> CompilationContext<'a> {
185    /// Recursively compile child steps. Used by compilers that have sub-pipelines
186    /// (Filter, Choice, Split, Loop, etc.).
187    pub fn compile_children(
188        &self,
189        steps: Vec<BuilderStep>,
190        registry: &StepCompilerRegistry,
191    ) -> Result<Vec<CompiledStep>, CamelError> {
192        registry.compile_steps(steps, self)
193    }
194
195    /// Recursively compile child steps and map them into outcome-aware segments.
196    ///
197    /// Each `CompiledStep` variant is converted to a `Box<dyn OutcomePipeline>`:
198    /// - `Process` → `BoxProcessorSegment`, optionally wrapped in `BodyCoercingSegment`
199    /// - `Stop` → `StopSegment` (produces `PipelineOutcome::Stopped(ex)`)
200    /// - `Segment` → its inner `OutcomeSegment` (which now implements OutcomePipeline)
201    ///
202    /// This replaces the 22-line duplicated closure in Filter/DeclarativeFilter
203    /// (and will prevent 14+ more duplicates in T9–T16).
204    #[allow(clippy::type_complexity)]
205    pub fn compile_children_segments(
206        &self,
207        steps: Vec<BuilderStep>,
208        registry: &StepCompilerRegistry,
209    ) -> Result<
210        (
211            Vec<Box<dyn camel_api::OutcomePipeline>>,
212            Vec<Arc<dyn camel_api::StepLifecycle>>,
213        ),
214        CamelError,
215    > {
216        let pairs = self.compile_children(steps, registry)?;
217        let mut lifecycle_handles: Vec<Arc<dyn camel_api::StepLifecycle>> = Vec::new();
218        let segments: Vec<Box<dyn camel_api::OutcomePipeline>> = pairs
219            .into_iter()
220            .map(|c| match c {
221                CompiledStep::Process {
222                    processor,
223                    body_contract,
224                    lifecycle,
225                    label: _,
226                    kind_hint: _,
227                    to_uri: _,
228                } => {
229                    if let Some(lc) = lifecycle {
230                        lifecycle_handles.push(lc);
231                    }
232                    let inner: Box<dyn camel_api::OutcomePipeline> = Box::new(
233                        crate::lifecycle::adapters::route_compiler::BoxProcessorSegment::new(
234                            processor,
235                        ),
236                    );
237                    match body_contract {
238                        Some(contract) => Box::new(
239                            crate::lifecycle::adapters::route_compiler::BodyCoercingSegment::new(
240                                inner, contract,
241                            ),
242                        ),
243                        None => inner,
244                    }
245                }
246                CompiledStep::Stop => {
247                    Box::new(crate::lifecycle::adapters::route_compiler::StopSegment)
248                        as Box<dyn camel_api::OutcomePipeline>
249                }
250                CompiledStep::Segment {
251                    segment,
252                    body_contract: _,
253                    lifecycle,
254                    label: _,
255                } => {
256                    if let Some(lcs) = lifecycle {
257                        lifecycle_handles.extend(lcs);
258                    }
259                    Box::new(segment)
260                }
261            })
262            .collect();
263        Ok((segments, lifecycle_handles))
264    }
265}
266
267/// Registry of step compilers. Steps are dispatched to compilers in registration
268/// order. The first matching compiler handles the step.
269pub(crate) struct StepCompilerRegistry {
270    compilers: Vec<Box<dyn StepCompiler>>,
271}
272
273impl StepCompilerRegistry {
274    pub fn new() -> Self {
275        Self {
276            compilers: Vec::new(),
277        }
278    }
279
280    pub fn register(&mut self, compiler: Box<dyn StepCompiler>) {
281        self.compilers.push(compiler);
282    }
283
284    /// Try each compiler in order. The first to return `Matched` wins.
285    /// If all return `NotHandled`, returns `Ok(None)`. Compilation errors
286    /// short-circuit and return `Err(CamelError)`.
287    pub fn compile_step(
288        &self,
289        step: BuilderStep,
290        step_index: usize,
291        ctx: &CompilationContext,
292    ) -> Result<Option<CompiledStep>, CamelError> {
293        // Capture the span label, kind hint, and declared To URI BEFORE the
294        // dispatch loop moves the step. The URI is the authored text, so a
295        // `SkipTo`/`DivertCopyTo` interception inside a compiler never
296        // rewrites the retained metadata.
297        let label = step.span_label();
298        let kind_hint = step.span_kind_hint();
299        let to_uri = step.to_uri_metadata();
300        let mut step = step;
301        for compiler in &self.compilers {
302            match compiler.compile(step, step_index, ctx, self)? {
303                CompileOutcome::Matched(mut s) => {
304                    s.set_label(label);
305                    s.set_kind_hint(kind_hint);
306                    s.set_to_uri(to_uri);
307                    return Ok(Some(s));
308                }
309                CompileOutcome::NotHandled(s) => step = s,
310            }
311        }
312        Ok(None)
313    }
314
315    /// Compile all steps in a vector.
316    pub fn compile_steps(
317        &self,
318        steps: Vec<BuilderStep>,
319        ctx: &CompilationContext,
320    ) -> Result<Vec<CompiledStep>, CamelError> {
321        let mut out = Vec::with_capacity(steps.len());
322        for (i, step) in steps.into_iter().enumerate() {
323            match self.compile_step(step, i, ctx)? {
324                Some(c) => out.push(c),
325                None => {
326                    return Err(CamelError::RouteError(
327                        "no compiler registered for step variant".into(),
328                    ));
329                }
330            }
331        }
332        Ok(out)
333    }
334}
335
336/// A resolved send target: the pieces the un-intercepted `To` path produces
337/// for one URI.
338pub(super) struct ResolvedSend {
339    pub producer: BoxProcessor,
340    pub body_contract: Option<BodyType>,
341    pub lifecycle: Option<Arc<dyn StepLifecycle>>,
342}
343
344/// Resolve a send URI into producer/body-contract/lifecycle, exactly as the
345/// un-intercepted `To` path does. Canonical resolution path for send steps;
346/// [`resolve_producer_with_lifecycle`] and [`resolve_producer`] are thin
347/// wrappers over this.
348pub(super) fn resolve_send(
349    ctx: &CompilationContext,
350    uri: &str,
351) -> Result<ResolvedSend, CamelError> {
352    let parsed = parse_uri(uri)?;
353    let component = ctx
354        .component_ctx
355        .resolve_component(&parsed.scheme)
356        .ok_or_else(|| CamelError::ComponentNotFound(parsed.scheme.clone()))?;
357    let endpoint = component.create_endpoint(uri, ctx.component_ctx.as_ref())?;
358    let body_contract = endpoint.body_contract();
359    let producer = endpoint.create_producer(Arc::clone(&ctx.rt), ctx.producer_ctx)?;
360    // Capture the endpoint's lifecycle handle so the route controller can
361    // start/shut it down in route order (ADR-0022). Default is `None` for
362    // stateless endpoints — see `Endpoint::lifecycle` in camel-component-api.
363    let lifecycle: Option<Arc<dyn StepLifecycle>> = endpoint.lifecycle();
364    Ok(ResolvedSend {
365        producer,
366        body_contract,
367        lifecycle,
368    })
369}
370
371/// Parse a URI and create a producer, also returning the endpoint's
372/// [`StepLifecycle`] handle (if any). Thin wrapper over [`resolve_send`] that
373/// discards the body contract. Use directly when the lifecycle is needed
374/// (e.g. `WireTap` propagation).
375pub(crate) fn resolve_producer_with_lifecycle(
376    ctx: &CompilationContext,
377    uri: &str,
378) -> Result<(BoxProcessor, Option<Arc<dyn StepLifecycle>>), CamelError> {
379    let resolved = resolve_send(ctx, uri)?;
380    Ok((resolved.producer, resolved.lifecycle))
381}
382
383/// Parse a URI and create a producer, reusing `component_ctx`, `rt`, and `producer_ctx`
384/// from the compilation context.
385///
386/// Thin wrapper over [`resolve_producer_with_lifecycle`] that discards the
387/// endpoint's [`StepLifecycle`] handle.
388pub(crate) fn resolve_producer(
389    ctx: &CompilationContext,
390    uri: &str,
391) -> Result<BoxProcessor, CamelError> {
392    Ok(resolve_producer_with_lifecycle(ctx, uri)?.0)
393}
394
395/// Pack a lifecycle Vec into `None` when empty, `Some` when non-empty.
396/// Preserves the invariant that `Some` always implies ≥1 handle.
397pub(super) fn pack_lifecycles(
398    lifecycles: Vec<Arc<dyn StepLifecycle>>,
399) -> Option<Vec<Arc<dyn StepLifecycle>>> {
400    if lifecycles.is_empty() {
401        None
402    } else {
403        Some(lifecycles)
404    }
405}
406
407/// Build the full registry with all compiler groups.
408pub(crate) fn build_registry() -> StepCompilerRegistry {
409    let mut reg = StepCompilerRegistry::new();
410    reg.register(Box::new(core::CoreCompiler));
411    reg.register(Box::new(endpoints::EndpointsCompiler));
412    reg.register(Box::new(transforms::TransformsCompiler));
413    reg.register(Box::new(routing::RoutingCompiler));
414    reg.register(Box::new(control_flow::ControlFlowCompiler));
415    reg.register(Box::new(middleware::MiddlewareCompiler));
416    reg.register(Box::new(splitting::SplittingCompiler));
417    reg.register(Box::new(error_handling::ErrorHandlingCompiler));
418    reg
419}
420
421#[cfg(test)]
422mod segment_tests {
423    use super::*;
424    use camel_api::{Exchange, OutcomePipeline, PipelineOutcome};
425    use std::future::Future;
426    use std::pin::Pin;
427
428    #[derive(Clone)]
429    struct EchoSegment;
430
431    impl OutcomePipeline for EchoSegment {
432        fn clone_box(&self) -> Box<dyn OutcomePipeline> {
433            Box::new(EchoSegment)
434        }
435        fn run<'a>(
436            &'a mut self,
437            exchange: Exchange,
438        ) -> Pin<Box<dyn Future<Output = PipelineOutcome> + Send + 'a>> {
439            Box::pin(async move { PipelineOutcome::Completed(exchange) })
440        }
441    }
442
443    #[test]
444    fn compiled_step_segment_clone_compiles() {
445        let seg = camel_api::OutcomeSegment::new(Box::new(EchoSegment));
446        let step = CompiledStep::Segment {
447            segment: seg,
448            body_contract: None,
449            lifecycle: None,
450            label: None,
451        };
452        let _cloned = step.clone();
453        if let CompiledStep::Segment { .. } = _cloned {
454            // ok
455        } else {
456            panic!("clone should preserve variant");
457        }
458    }
459
460    #[test]
461    fn compiled_step_segment_debug_renders() {
462        let seg = camel_api::OutcomeSegment::new(Box::new(EchoSegment));
463        let step = CompiledStep::Segment {
464            segment: seg,
465            body_contract: None,
466            lifecycle: None,
467            label: None,
468        };
469        let s = format!("{:?}", step);
470        assert!(
471            s.contains("Segment"),
472            "debug should mention Segment variant: {s}"
473        );
474    }
475
476    #[test]
477    fn outcome_segment_satisfies_clone_send_static() {
478        fn assert_traits<T: Clone + Send + 'static>() {}
479        assert_traits::<camel_api::OutcomeSegment>();
480    }
481
482    #[tokio::test]
483    #[allow(clippy::arc_with_non_send_sync)]
484    async fn outcome_segment_survives_arcswap_swap() {
485        use arc_swap::ArcSwap;
486        use camel_api::{Exchange, Message, OutcomePipeline, PipelineOutcome};
487        use std::sync::Arc;
488
489        #[derive(Clone)]
490        struct EchoSegment;
491        impl OutcomePipeline for EchoSegment {
492            fn clone_box(&self) -> Box<dyn OutcomePipeline> {
493                Box::new(EchoSegment)
494            }
495            fn run<'a>(
496                &'a mut self,
497                ex: Exchange,
498            ) -> std::pin::Pin<Box<dyn std::future::Future<Output = PipelineOutcome> + Send + 'a>>
499            {
500                Box::pin(async move { PipelineOutcome::Completed(ex) })
501            }
502        }
503
504        let seg = camel_api::OutcomeSegment::new(Box::new(EchoSegment));
505        let slot: ArcSwap<Option<camel_api::OutcomeSegment>> = ArcSwap::from_pointee(None);
506        slot.store(Arc::new(Some(seg.clone())));
507        slot.store(Arc::new(Some(seg)));
508
509        let mut borrowed = slot.load().as_ref().clone().unwrap();
510        let outcome = borrowed.run(Exchange::new(Message::new("ping"))).await;
511        assert!(matches!(outcome, PipelineOutcome::Completed(_)));
512    }
513
514    /// Test lifecycle handle used by compile_children_segments_bubbles_child_lifecycle.
515    #[derive(Debug)]
516    struct TestLifecycle;
517
518    #[async_trait::async_trait]
519    impl camel_api::StepLifecycle for TestLifecycle {
520        fn name(&self) -> &'static str {
521            "test-lifecycle"
522        }
523        async fn shutdown(
524            &self,
525            _reason: camel_api::StepShutdownReason,
526        ) -> Result<(), camel_api::CamelError> {
527            Ok(())
528        }
529    }
530
531    /// Custom compiler that injects a lifecycle handle into every
532    /// `BuilderStep::Processor` it compiles.
533    struct LifecycleInjectorCompiler {
534        handle: Arc<dyn camel_api::StepLifecycle>,
535    }
536
537    impl StepCompiler for LifecycleInjectorCompiler {
538        fn compile(
539            &self,
540            step: BuilderStep,
541            _step_index: usize,
542            _ctx: &CompilationContext,
543            _registry: &StepCompilerRegistry,
544        ) -> Result<CompileOutcome, CamelError> {
545            match step {
546                BuilderStep::Processor(op) => Ok(CompileOutcome::Matched(CompiledStep::Process {
547                    processor: op.0,
548                    body_contract: None,
549                    lifecycle: Some(self.handle.clone()),
550                    label: None,
551                    kind_hint: SpanKindHint::Internal,
552                    to_uri: None,
553                })),
554                other => Ok(CompileOutcome::NotHandled(other)),
555            }
556        }
557    }
558
559    #[tokio::test]
560    async fn compile_children_segments_bubbles_child_lifecycle() {
561        use std::collections::HashMap;
562        use std::sync::Mutex;
563
564        use camel_api::{
565            BoxProcessor, BoxProcessorExt, FilterPredicate, OpaqueProcessor, StepLifecycle,
566        };
567        use camel_bean::BeanRegistry;
568        use camel_component_api::{
569            ComponentContext, NoOpComponentContext, RuntimeObservability,
570            test_support::NoopRuntimeObservability,
571        };
572
573        use crate::lifecycle::adapters::step_resolution::FunctionStagingMode;
574
575        let handle: Arc<dyn StepLifecycle> = Arc::new(TestLifecycle);
576
577        // Register lifecycle injector + real control-flow compiler so
578        // compile_children_segments runs through a structural EIP path.
579        let mut reg = StepCompilerRegistry::new();
580        reg.register(Box::new(LifecycleInjectorCompiler {
581            handle: handle.clone(),
582        }));
583        reg.register(Box::new(super::control_flow::ControlFlowCompiler));
584
585        let pc = ProducerContext::default();
586        let rt: Arc<dyn RuntimeObservability> = Arc::new(NoopRuntimeObservability);
587        let languages: SharedLanguageRegistry = Arc::new(Mutex::new(HashMap::new()));
588        let beans: Arc<Mutex<BeanRegistry>> = Arc::new(Mutex::new(BeanRegistry::new()));
589        let component_ctx: Arc<dyn ComponentContext> = Arc::new(NoOpComponentContext);
590        let staging = FunctionStagingMode::DirectAdd;
591        let idempotent_repositories = crate::IdempotentRegistry::new();
592        let claim_check_repositories = crate::ClaimCheckRegistry::new();
593        let cache_repositories = crate::CacheRegistry::new();
594
595        let ctx = CompilationContext {
596            producer_ctx: &pc,
597            rt,
598            languages: &languages,
599            beans: &beans,
600            function_invoker: None,
601            component_ctx,
602            route_id: None,
603            staging_mode: &staging,
604            idempotent_repositories: &idempotent_repositories,
605            claim_check_repositories: &claim_check_repositories,
606            cache_repositories: &cache_repositories,
607            intercept: InterceptRules::default(),
608        };
609
610        // Compile a Filter with a child Processor step.
611        let filter_step = BuilderStep::Filter {
612            predicate: FilterPredicate::new(|_| true),
613            steps: vec![BuilderStep::Processor(OpaqueProcessor(
614                BoxProcessor::from_fn(|ex| Box::pin(async move { Ok(ex) })),
615            ))],
616        };
617
618        let result = reg.compile_step(filter_step, 0, &ctx);
619        let compiled = result
620            .expect("compilation should succeed")
621            .expect("should match");
622
623        match compiled {
624            CompiledStep::Segment {
625                lifecycle,
626                body_contract,
627                ..
628            } => {
629                assert_eq!(body_contract, None, "body_contract should be None");
630                let handles = lifecycle.expect("Segment should have lifecycle handles");
631                assert_eq!(handles.len(), 1, "expected 1 lifecycle handle");
632                assert_eq!(handles[0].name(), "test-lifecycle", "handle name mismatch");
633            }
634            other => panic!("Expected CompiledStep::Segment, got {other:?}"),
635        }
636    }
637
638    /// A lifecycle handle with a configurable name for multi-handle tests.
639    #[derive(Debug)]
640    struct NamedLifecycle(&'static str);
641
642    #[async_trait::async_trait]
643    impl camel_api::StepLifecycle for NamedLifecycle {
644        fn name(&self) -> &'static str {
645            self.0
646        }
647        async fn shutdown(
648            &self,
649            _reason: camel_api::StepShutdownReason,
650        ) -> Result<(), camel_api::CamelError> {
651            Ok(())
652        }
653    }
654
655    /// Test A: Multiple stateful children in one Segment → Vec length 2.
656    #[tokio::test]
657    async fn compile_children_segments_multiple_stateful_children() {
658        use std::collections::HashMap;
659        use std::sync::Mutex;
660
661        use crate::lifecycle::adapters::step_resolution::FunctionStagingMode;
662        use camel_api::{
663            BoxProcessor, BoxProcessorExt, FilterPredicate, OpaqueProcessor, StepLifecycle,
664        };
665        use camel_bean::BeanRegistry;
666        use camel_component_api::{
667            ComponentContext, NoOpComponentContext, RuntimeObservability,
668            test_support::NoopRuntimeObservability,
669        };
670
671        let handle: Arc<dyn StepLifecycle> = Arc::new(NamedLifecycle("multi"));
672
673        let mut reg = StepCompilerRegistry::new();
674        reg.register(Box::new(LifecycleInjectorCompiler {
675            handle: handle.clone(),
676        }));
677        reg.register(Box::new(super::control_flow::ControlFlowCompiler));
678
679        let pc = ProducerContext::default();
680        let rt: Arc<dyn RuntimeObservability> = Arc::new(NoopRuntimeObservability);
681        let languages: SharedLanguageRegistry = Arc::new(Mutex::new(HashMap::new()));
682        let beans: Arc<Mutex<BeanRegistry>> = Arc::new(Mutex::new(BeanRegistry::new()));
683        let component_ctx: Arc<dyn ComponentContext> = Arc::new(NoOpComponentContext);
684        let staging = FunctionStagingMode::DirectAdd;
685        let idempotent_repositories = crate::IdempotentRegistry::new();
686        let claim_check_repositories = crate::ClaimCheckRegistry::new();
687        let cache_repositories = crate::CacheRegistry::new();
688
689        let ctx = CompilationContext {
690            producer_ctx: &pc,
691            rt,
692            languages: &languages,
693            beans: &beans,
694            function_invoker: None,
695            component_ctx,
696            route_id: None,
697            staging_mode: &staging,
698            idempotent_repositories: &idempotent_repositories,
699            claim_check_repositories: &claim_check_repositories,
700            cache_repositories: &cache_repositories,
701            intercept: InterceptRules::default(),
702        };
703
704        // Filter with TWO child Processors → both get the same lifecycle handle.
705        let filter_step = BuilderStep::Filter {
706            predicate: FilterPredicate::new(|_| true),
707            steps: vec![
708                BuilderStep::Processor(OpaqueProcessor(BoxProcessor::from_fn(|ex| {
709                    Box::pin(async move { Ok(ex) })
710                }))),
711                BuilderStep::Processor(OpaqueProcessor(BoxProcessor::from_fn(|ex| {
712                    Box::pin(async move { Ok(ex) })
713                }))),
714            ],
715        };
716
717        let result = reg.compile_step(filter_step, 0, &ctx);
718        let compiled = result
719            .expect("compilation should succeed")
720            .expect("should match");
721
722        match compiled {
723            CompiledStep::Segment { lifecycle, .. } => {
724                let handles = lifecycle.expect("Segment should have lifecycle handles");
725                assert_eq!(
726                    handles.len(),
727                    2,
728                    "expected 2 lifecycle handles for 2 children"
729                );
730                for h in &handles {
731                    assert_eq!(h.name(), "multi", "all handles should be 'multi'");
732                }
733            }
734            other => panic!("Expected CompiledStep::Segment, got {other:?}"),
735        }
736    }
737
738    /// Test B: Multi-branch accumulation across Choice when-clauses.
739    #[tokio::test]
740    async fn compile_children_segments_multi_branch_accumulation() {
741        use std::collections::HashMap;
742        use std::sync::Mutex;
743
744        use crate::lifecycle::adapters::step_resolution::FunctionStagingMode;
745        use crate::lifecycle::application::route_definition::WhenStep;
746        use camel_api::{
747            BoxProcessor, BoxProcessorExt, FilterPredicate, OpaqueProcessor, StepLifecycle,
748        };
749        use camel_bean::BeanRegistry;
750        use camel_component_api::{
751            ComponentContext, NoOpComponentContext, RuntimeObservability,
752            test_support::NoopRuntimeObservability,
753        };
754
755        let handle: Arc<dyn StepLifecycle> = Arc::new(NamedLifecycle("branch"));
756
757        let mut reg = StepCompilerRegistry::new();
758        reg.register(Box::new(LifecycleInjectorCompiler {
759            handle: handle.clone(),
760        }));
761        reg.register(Box::new(super::control_flow::ControlFlowCompiler));
762
763        let pc = ProducerContext::default();
764        let rt: Arc<dyn RuntimeObservability> = Arc::new(NoopRuntimeObservability);
765        let languages: SharedLanguageRegistry = Arc::new(Mutex::new(HashMap::new()));
766        let beans: Arc<Mutex<BeanRegistry>> = Arc::new(Mutex::new(BeanRegistry::new()));
767        let component_ctx: Arc<dyn ComponentContext> = Arc::new(NoOpComponentContext);
768        let staging = FunctionStagingMode::DirectAdd;
769        let idempotent_repositories = crate::IdempotentRegistry::new();
770        let claim_check_repositories = crate::ClaimCheckRegistry::new();
771        let cache_repositories = crate::CacheRegistry::new();
772
773        let ctx = CompilationContext {
774            producer_ctx: &pc,
775            rt,
776            languages: &languages,
777            beans: &beans,
778            function_invoker: None,
779            component_ctx,
780            route_id: None,
781            staging_mode: &staging,
782            idempotent_repositories: &idempotent_repositories,
783            claim_check_repositories: &claim_check_repositories,
784            cache_repositories: &cache_repositories,
785            intercept: InterceptRules::default(),
786        };
787
788        // Choice with 2 when branches, each containing 1 stateful child.
789        let choice_step = BuilderStep::Choice {
790            whens: vec![
791                WhenStep {
792                    predicate: FilterPredicate::new(|_| true),
793                    steps: vec![BuilderStep::Processor(OpaqueProcessor(
794                        BoxProcessor::from_fn(|ex| Box::pin(async move { Ok(ex) })),
795                    ))],
796                },
797                WhenStep {
798                    predicate: FilterPredicate::new(|_| false),
799                    steps: vec![BuilderStep::Processor(OpaqueProcessor(
800                        BoxProcessor::from_fn(|ex| Box::pin(async move { Ok(ex) })),
801                    ))],
802                },
803            ],
804            otherwise: None,
805        };
806
807        let result = reg.compile_step(choice_step, 0, &ctx);
808        let compiled = result
809            .expect("compilation should succeed")
810            .expect("should match");
811
812        match compiled {
813            CompiledStep::Segment { lifecycle, .. } => {
814                let handles = lifecycle.expect("Segment should have lifecycle handles");
815                assert_eq!(
816                    handles.len(),
817                    2,
818                    "expected 2 lifecycle handles from 2 branches"
819                );
820                for h in &handles {
821                    assert_eq!(h.name(), "branch", "all handles should be 'branch'");
822                }
823            }
824            other => panic!("Expected CompiledStep::Segment, got {other:?}"),
825        }
826    }
827
828    /// Test C: Nested Segment-in-Segment flattening — outer Segment contains
829    /// innermost lifecycle handle from a grandchild Processor.
830    #[tokio::test]
831    async fn compile_children_segments_nested_segment_flattening() {
832        use std::collections::HashMap;
833        use std::sync::Mutex;
834
835        use crate::lifecycle::adapters::step_resolution::FunctionStagingMode;
836        use camel_api::{
837            BoxProcessor, BoxProcessorExt, FilterPredicate, OpaqueProcessor, StepLifecycle,
838        };
839        use camel_bean::BeanRegistry;
840        use camel_component_api::{
841            ComponentContext, NoOpComponentContext, RuntimeObservability,
842            test_support::NoopRuntimeObservability,
843        };
844
845        let inner_handle: Arc<dyn StepLifecycle> = Arc::new(NamedLifecycle("deep"));
846
847        let mut reg = StepCompilerRegistry::new();
848        reg.register(Box::new(LifecycleInjectorCompiler {
849            handle: inner_handle.clone(),
850        }));
851        reg.register(Box::new(super::control_flow::ControlFlowCompiler));
852
853        let pc = ProducerContext::default();
854        let rt: Arc<dyn RuntimeObservability> = Arc::new(NoopRuntimeObservability);
855        let languages: SharedLanguageRegistry = Arc::new(Mutex::new(HashMap::new()));
856        let beans: Arc<Mutex<BeanRegistry>> = Arc::new(Mutex::new(BeanRegistry::new()));
857        let component_ctx: Arc<dyn ComponentContext> = Arc::new(NoOpComponentContext);
858        let staging = FunctionStagingMode::DirectAdd;
859        let idempotent_repositories = crate::IdempotentRegistry::new();
860        let claim_check_repositories = crate::ClaimCheckRegistry::new();
861        let cache_repositories = crate::CacheRegistry::new();
862
863        let ctx = CompilationContext {
864            producer_ctx: &pc,
865            rt,
866            languages: &languages,
867            beans: &beans,
868            function_invoker: None,
869            component_ctx,
870            route_id: None,
871            staging_mode: &staging,
872            idempotent_repositories: &idempotent_repositories,
873            claim_check_repositories: &claim_check_repositories,
874            cache_repositories: &cache_repositories,
875            intercept: InterceptRules::default(),
876        };
877
878        // Outer Filter containing an inner Filter that has a stateful Processor.
879        // The outer Segment's lifecycle should contain the innermost handle
880        // (proves recursive flattening through compile_children_segments).
881        let inner_filter = BuilderStep::Filter {
882            predicate: FilterPredicate::new(|_| true),
883            steps: vec![BuilderStep::Processor(OpaqueProcessor(
884                BoxProcessor::from_fn(|ex| Box::pin(async move { Ok(ex) })),
885            ))],
886        };
887
888        let outer_filter = BuilderStep::Filter {
889            predicate: FilterPredicate::new(|_| true),
890            steps: vec![inner_filter],
891        };
892
893        let result = reg.compile_step(outer_filter, 0, &ctx);
894        let compiled = result
895            .expect("compilation should succeed")
896            .expect("should match");
897
898        match compiled {
899            CompiledStep::Segment { lifecycle, .. } => {
900                let handles = lifecycle.expect("outer Segment should have lifecycle handles");
901                assert_eq!(handles.len(), 1, "expected 1 innermost lifecycle handle");
902                assert_eq!(
903                    handles[0].name(),
904                    "deep",
905                    "handle should be from innermost child"
906                );
907            }
908            other => panic!("Expected CompiledStep::Segment, got {other:?}"),
909        }
910    }
911}
912
913#[cfg(test)]
914mod dispatch_tests {
915    use super::*;
916    use crate::lifecycle::adapters::step_resolution::FunctionStagingMode;
917    use camel_api::{BoxProcessor, BoxProcessorExt};
918    use camel_bean::BeanRegistry;
919    use camel_component_api::{
920        ComponentContext, NoOpComponentContext, RuntimeObservability,
921        test_support::NoopRuntimeObservability,
922    };
923    use std::collections::HashMap;
924    use std::sync::Mutex;
925
926    /// Compiler that handles `BuilderStep::To` → `CompiledStep::Stop`.
927    struct ToStopCompiler;
928
929    impl StepCompiler for ToStopCompiler {
930        fn compile(
931            &self,
932            step: BuilderStep,
933            _step_index: usize,
934            _ctx: &CompilationContext,
935            _registry: &StepCompilerRegistry,
936        ) -> Result<CompileOutcome, CamelError> {
937            match step {
938                BuilderStep::To(_) => Ok(CompileOutcome::Matched(CompiledStep::Stop)),
939                other => Ok(CompileOutcome::NotHandled(other)),
940            }
941        }
942    }
943
944    /// Compiler that handles `BuilderStep::To` → `CompiledStep::Process`.
945    struct ToProcessCompiler;
946
947    impl StepCompiler for ToProcessCompiler {
948        fn compile(
949            &self,
950            step: BuilderStep,
951            _step_index: usize,
952            _ctx: &CompilationContext,
953            _registry: &StepCompilerRegistry,
954        ) -> Result<CompileOutcome, CamelError> {
955            match step {
956                BuilderStep::To(_) => Ok(CompileOutcome::Matched(CompiledStep::Process {
957                    processor: BoxProcessor::from_fn(|ex| Box::pin(async move { Ok(ex) })),
958                    body_contract: None,
959                    lifecycle: None,
960                    label: None,
961                    kind_hint: SpanKindHint::Internal,
962                    to_uri: None,
963                })),
964                other => Ok(CompileOutcome::NotHandled(other)),
965            }
966        }
967    }
968
969    /// Minimal outcome pipeline for building `Segment` fixtures in tests.
970    #[derive(Clone)]
971    struct NoopPipeline;
972
973    impl camel_api::OutcomePipeline for NoopPipeline {
974        fn clone_box(&self) -> Box<dyn camel_api::OutcomePipeline> {
975            Box::new(NoopPipeline)
976        }
977
978        fn run<'a>(
979            &'a mut self,
980            exchange: camel_api::Exchange,
981        ) -> std::pin::Pin<
982            Box<dyn std::future::Future<Output = camel_api::PipelineOutcome> + Send + 'a>,
983        > {
984            Box::pin(async move { camel_api::PipelineOutcome::Completed(exchange) })
985        }
986    }
987
988    /// Compiler that passes all steps through (never handles any variant).
989    /// Returns `NotHandled(step)` for every input, proving by-value pass-through.
990    struct PassThroughCompiler;
991
992    impl StepCompiler for PassThroughCompiler {
993        fn compile(
994            &self,
995            step: BuilderStep,
996            _step_index: usize,
997            _ctx: &CompilationContext,
998            _registry: &StepCompilerRegistry,
999        ) -> Result<CompileOutcome, CamelError> {
1000            Ok(CompileOutcome::NotHandled(step))
1001        }
1002    }
1003
1004    /// Shared context builder — avoids repeating the 15-line setup in every test.
1005    #[allow(clippy::too_many_arguments)]
1006    fn ctx<'a>(
1007        pc: &'a ProducerContext,
1008        rt: Arc<dyn RuntimeObservability>,
1009        languages: &'a SharedLanguageRegistry,
1010        beans: &'a Arc<Mutex<BeanRegistry>>,
1011        component_ctx: Arc<dyn ComponentContext>,
1012        staging: &'a FunctionStagingMode,
1013        idempotent_repositories: &'a crate::IdempotentRegistry,
1014        claim_check_repositories: &'a crate::ClaimCheckRegistry,
1015        cache_repositories: &'a crate::CacheRegistry,
1016    ) -> CompilationContext<'a> {
1017        CompilationContext {
1018            producer_ctx: pc,
1019            rt,
1020            languages,
1021            beans,
1022            function_invoker: None,
1023            component_ctx,
1024            route_id: None,
1025            staging_mode: staging,
1026            idempotent_repositories,
1027            claim_check_repositories,
1028            cache_repositories,
1029            intercept: InterceptRules::default(),
1030        }
1031    }
1032
1033    /// Test that the dispatcher respects registration order: the first matching
1034    /// compiler wins even when a later compiler also matches.
1035    #[test]
1036    fn compile_step_preserves_registry_order() {
1037        let pc = ProducerContext::default();
1038        let rt: Arc<dyn RuntimeObservability> = Arc::new(NoopRuntimeObservability);
1039        let languages: SharedLanguageRegistry = Arc::new(Mutex::new(HashMap::new()));
1040        let beans: Arc<Mutex<BeanRegistry>> = Arc::new(Mutex::new(BeanRegistry::new()));
1041        let component_ctx: Arc<dyn ComponentContext> = Arc::new(NoOpComponentContext);
1042        let staging = FunctionStagingMode::DirectAdd;
1043        let idempotent_repositories = crate::IdempotentRegistry::new();
1044        let claim_check_repositories = crate::ClaimCheckRegistry::new();
1045        let cache_repositories = crate::CacheRegistry::new();
1046
1047        let context = ctx(
1048            &pc,
1049            rt,
1050            &languages,
1051            &beans,
1052            component_ctx,
1053            &staging,
1054            &idempotent_repositories,
1055            &claim_check_repositories,
1056            &cache_repositories,
1057        );
1058
1059        // Register ToStopCompiler FIRST, ToProcessCompiler SECOND.
1060        // Both match BuilderStep::To. The first-registered should win.
1061        let mut reg = StepCompilerRegistry::new();
1062        reg.register(Box::new(ToStopCompiler));
1063        reg.register(Box::new(ToProcessCompiler));
1064
1065        let result = reg
1066            .compile_step(BuilderStep::To("test".into()), 0, &context)
1067            .expect("compilation should succeed")
1068            .expect("should match");
1069
1070        assert!(
1071            matches!(result, CompiledStep::Stop),
1072            "expected ToStopCompiler (first registered) to win, got {result:?}"
1073        );
1074    }
1075
1076    /// Task 1.2 (span-name-enrichment): `set_label` is a no-op on `Stop`.
1077    #[test]
1078    fn set_label_noop_on_stop() {
1079        let mut step = CompiledStep::Stop;
1080        step.set_label(Some("x".into()));
1081        assert!(
1082            matches!(step, CompiledStep::Stop),
1083            "set_label must not change a Stop step, got {step:?}"
1084        );
1085    }
1086
1087    /// Task 1.2 (span-name-enrichment): `compile_step` stamps the outcome with
1088    /// the step's `span_label` (here `to:direct` from `BuilderStep::To`).
1089    #[test]
1090    fn compile_step_stamps_label() {
1091        let pc = ProducerContext::default();
1092        let rt: Arc<dyn RuntimeObservability> = Arc::new(NoopRuntimeObservability);
1093        let languages: SharedLanguageRegistry = Arc::new(Mutex::new(HashMap::new()));
1094        let beans: Arc<Mutex<BeanRegistry>> = Arc::new(Mutex::new(BeanRegistry::new()));
1095        let component_ctx: Arc<dyn ComponentContext> = Arc::new(NoOpComponentContext);
1096        let staging = FunctionStagingMode::DirectAdd;
1097        let idempotent_repositories = crate::IdempotentRegistry::new();
1098        let claim_check_repositories = crate::ClaimCheckRegistry::new();
1099        let cache_repositories = crate::CacheRegistry::new();
1100
1101        let context = ctx(
1102            &pc,
1103            rt,
1104            &languages,
1105            &beans,
1106            component_ctx,
1107            &staging,
1108            &idempotent_repositories,
1109            &claim_check_repositories,
1110            &cache_repositories,
1111        );
1112
1113        let mut reg = StepCompilerRegistry::new();
1114        reg.register(Box::new(ToProcessCompiler));
1115
1116        let result = reg
1117            .compile_step(BuilderStep::To("direct:x".into()), 0, &context)
1118            .expect("compilation should succeed")
1119            .expect("should match");
1120
1121        match result {
1122            CompiledStep::Process { label, .. } => {
1123                assert_eq!(label.as_deref(), Some("to:direct"));
1124            }
1125            other => panic!("expected Process, got {other:?}"),
1126        }
1127    }
1128
1129    /// Task 1.2 (span-kind-hint): `set_kind_hint` is a no-op on `Stop` and
1130    /// `Segment` — only `Process` carries a kind hint, and a Segment's label
1131    /// must survive the call untouched.
1132    #[test]
1133    fn set_kind_hint_noop_on_stop_and_segment() {
1134        use camel_api::SpanKindHint;
1135
1136        // Stop: the marker produces no step span, so it carries no kind.
1137        let mut step = CompiledStep::Stop;
1138        step.set_kind_hint(SpanKindHint::Client);
1139        assert!(
1140            matches!(step, CompiledStep::Stop),
1141            "set_kind_hint must not change a Stop step, got {step:?}"
1142        );
1143
1144        // Segment: no kind_hint field; its label is unchanged.
1145        let mut step = CompiledStep::Segment {
1146            segment: camel_api::OutcomeSegment::new(Box::new(NoopPipeline)),
1147            body_contract: None,
1148            lifecycle: None,
1149            label: Some("seg".into()),
1150        };
1151        step.set_kind_hint(SpanKindHint::Client);
1152        match step {
1153            CompiledStep::Segment { label, .. } => {
1154                assert_eq!(label.as_deref(), Some("seg"));
1155            }
1156            other => panic!("expected Segment to stay a Segment, got {other:?}"),
1157        }
1158    }
1159
1160    /// Task 1.2 (span-kind-hint): `compile_step` stamps the outcome with the
1161    /// step's `span_kind_hint` (here `kafka` → Producer) alongside the label.
1162    #[test]
1163    fn compile_step_stamps_kind_hint() {
1164        use camel_api::SpanKindHint;
1165
1166        let pc = ProducerContext::default();
1167        let rt: Arc<dyn RuntimeObservability> = Arc::new(NoopRuntimeObservability);
1168        let languages: SharedLanguageRegistry = Arc::new(Mutex::new(HashMap::new()));
1169        let beans: Arc<Mutex<BeanRegistry>> = Arc::new(Mutex::new(BeanRegistry::new()));
1170        let component_ctx: Arc<dyn ComponentContext> = Arc::new(NoOpComponentContext);
1171        let staging = FunctionStagingMode::DirectAdd;
1172        let idempotent_repositories = crate::IdempotentRegistry::new();
1173        let claim_check_repositories = crate::ClaimCheckRegistry::new();
1174        let cache_repositories = crate::CacheRegistry::new();
1175
1176        let context = ctx(
1177            &pc,
1178            rt,
1179            &languages,
1180            &beans,
1181            component_ctx,
1182            &staging,
1183            &idempotent_repositories,
1184            &claim_check_repositories,
1185            &cache_repositories,
1186        );
1187
1188        let mut reg = StepCompilerRegistry::new();
1189        reg.register(Box::new(ToProcessCompiler));
1190
1191        let result = reg
1192            .compile_step(BuilderStep::To("kafka:orders".into()), 0, &context)
1193            .expect("compilation should succeed")
1194            .expect("should match");
1195
1196        match result {
1197            CompiledStep::Process {
1198                kind_hint, label, ..
1199            } => {
1200                assert_eq!(kind_hint, SpanKindHint::Producer);
1201                assert_eq!(label.as_deref(), Some("to:kafka"));
1202            }
1203            other => panic!("expected Process, got {other:?}"),
1204        }
1205    }
1206
1207    /// Task 1.1 (steplatency): `compile_step` retains the declared To URI —
1208    /// the raw authored text, captured before endpoint resolution and
1209    /// interception — as shared immutable string metadata on the compiled
1210    /// `Process` step.
1211    #[test]
1212    fn compiled_to_step_retains_declared_uri() {
1213        let pc = ProducerContext::default();
1214        let rt: Arc<dyn RuntimeObservability> = Arc::new(NoopRuntimeObservability);
1215        let languages: SharedLanguageRegistry = Arc::new(Mutex::new(HashMap::new()));
1216        let beans: Arc<Mutex<BeanRegistry>> = Arc::new(Mutex::new(BeanRegistry::new()));
1217        let component_ctx: Arc<dyn ComponentContext> = Arc::new(NoOpComponentContext);
1218        let staging = FunctionStagingMode::DirectAdd;
1219        let idempotent_repositories = crate::IdempotentRegistry::new();
1220        let claim_check_repositories = crate::ClaimCheckRegistry::new();
1221        let cache_repositories = crate::CacheRegistry::new();
1222
1223        let context = ctx(
1224            &pc,
1225            rt,
1226            &languages,
1227            &beans,
1228            component_ctx,
1229            &staging,
1230            &idempotent_repositories,
1231            &claim_check_repositories,
1232            &cache_repositories,
1233        );
1234
1235        let mut reg = StepCompilerRegistry::new();
1236        reg.register(Box::new(ToProcessCompiler));
1237
1238        let result = reg
1239            .compile_step(BuilderStep::To("direct:orders".into()), 0, &context)
1240            .expect("compilation should succeed")
1241            .expect("should match");
1242
1243        match result {
1244            CompiledStep::Process { to_uri, .. } => {
1245                assert_eq!(to_uri, Some(Arc::from("direct:orders")));
1246            }
1247            other => panic!("expected Process, got {other:?}"),
1248        }
1249    }
1250
1251    /// Task 1.1 (steplatency): a non-To process step carries no declared URI.
1252    #[test]
1253    fn compiled_processor_step_has_no_declared_uri() {
1254        use camel_api::OpaqueProcessor;
1255
1256        let pc = ProducerContext::default();
1257        let rt: Arc<dyn RuntimeObservability> = Arc::new(NoopRuntimeObservability);
1258        let languages: SharedLanguageRegistry = Arc::new(Mutex::new(HashMap::new()));
1259        let beans: Arc<Mutex<BeanRegistry>> = Arc::new(Mutex::new(BeanRegistry::new()));
1260        let component_ctx: Arc<dyn ComponentContext> = Arc::new(NoOpComponentContext);
1261        let staging = FunctionStagingMode::DirectAdd;
1262        let idempotent_repositories = crate::IdempotentRegistry::new();
1263        let claim_check_repositories = crate::ClaimCheckRegistry::new();
1264        let cache_repositories = crate::CacheRegistry::new();
1265
1266        let context = ctx(
1267            &pc,
1268            rt,
1269            &languages,
1270            &beans,
1271            component_ctx,
1272            &staging,
1273            &idempotent_repositories,
1274            &claim_check_repositories,
1275            &cache_repositories,
1276        );
1277
1278        let mut reg = StepCompilerRegistry::new();
1279        reg.register(Box::new(super::core::CoreCompiler));
1280
1281        let result = reg
1282            .compile_step(
1283                BuilderStep::Processor(OpaqueProcessor(BoxProcessor::from_fn(|ex| {
1284                    Box::pin(async move { Ok(ex) })
1285                }))),
1286                0,
1287                &context,
1288            )
1289            .expect("compilation should succeed")
1290            .expect("should match");
1291
1292        match result {
1293            CompiledStep::Process { to_uri, .. } => {
1294                assert_eq!(to_uri, None);
1295            }
1296            other => panic!("expected Process, got {other:?}"),
1297        }
1298    }
1299
1300    /// Test that when no compiler handles a variant, the dispatcher returns
1301    /// `Ok(None)` rather than an error.
1302    #[test]
1303    fn compile_step_unhandled_returns_ok_none() {
1304        let pc = ProducerContext::default();
1305        let rt: Arc<dyn RuntimeObservability> = Arc::new(NoopRuntimeObservability);
1306        let languages: SharedLanguageRegistry = Arc::new(Mutex::new(HashMap::new()));
1307        let beans: Arc<Mutex<BeanRegistry>> = Arc::new(Mutex::new(BeanRegistry::new()));
1308        let component_ctx: Arc<dyn ComponentContext> = Arc::new(NoOpComponentContext);
1309        let staging = FunctionStagingMode::DirectAdd;
1310        let idempotent_repositories = crate::IdempotentRegistry::new();
1311        let claim_check_repositories = crate::ClaimCheckRegistry::new();
1312        let cache_repositories = crate::CacheRegistry::new();
1313
1314        let context = ctx(
1315            &pc,
1316            rt,
1317            &languages,
1318            &beans,
1319            component_ctx,
1320            &staging,
1321            &idempotent_repositories,
1322            &claim_check_repositories,
1323            &cache_repositories,
1324        );
1325
1326        // Register a compiler that only handles BuilderStep::To.
1327        let mut reg = StepCompilerRegistry::new();
1328        reg.register(Box::new(ToStopCompiler));
1329
1330        // Send a BuilderStep::Log variant — ToStopCompiler does not match it.
1331        let result = reg.compile_step(
1332            BuilderStep::Log {
1333                level: camel_processor::LogLevel::Info,
1334                message: "unhandled".into(),
1335            },
1336            0,
1337            &context,
1338        );
1339
1340        assert!(
1341            matches!(result, Ok(None)),
1342            "expected Ok(None), got {result:?}"
1343        );
1344    }
1345
1346    /// Test that `NotHandled(step)` passes the step by-value to the next
1347    /// compiler. Compiler N returns `NotHandled(step)` for a variant that
1348    /// compiler N+1 handles — proving the step is not dropped or replaced.
1349    #[test]
1350    fn compile_step_nothandled_passes_step_intact_to_next_compiler() {
1351        let pc = ProducerContext::default();
1352        let rt: Arc<dyn RuntimeObservability> = Arc::new(NoopRuntimeObservability);
1353        let languages: SharedLanguageRegistry = Arc::new(Mutex::new(HashMap::new()));
1354        let beans: Arc<Mutex<BeanRegistry>> = Arc::new(Mutex::new(BeanRegistry::new()));
1355        let component_ctx: Arc<dyn ComponentContext> = Arc::new(NoOpComponentContext);
1356        let staging = FunctionStagingMode::DirectAdd;
1357        let idempotent_repositories = crate::IdempotentRegistry::new();
1358        let claim_check_repositories = crate::ClaimCheckRegistry::new();
1359        let cache_repositories = crate::CacheRegistry::new();
1360
1361        let context = ctx(
1362            &pc,
1363            rt,
1364            &languages,
1365            &beans,
1366            component_ctx,
1367            &staging,
1368            &idempotent_repositories,
1369            &claim_check_repositories,
1370            &cache_repositories,
1371        );
1372
1373        // Register PassThroughCompiler FIRST (never handles anything),
1374        // ToStopCompiler SECOND (handles BuilderStep::To).
1375        let mut reg = StepCompilerRegistry::new();
1376        reg.register(Box::new(PassThroughCompiler));
1377        reg.register(Box::new(ToStopCompiler));
1378
1379        let result = reg
1380            .compile_step(BuilderStep::To("passthrough".into()), 0, &context)
1381            .expect("compilation should succeed")
1382            .expect("should match");
1383
1384        assert!(
1385            matches!(result, CompiledStep::Stop),
1386            "expected ToStopCompiler (N+1) to win after pass-through, got {result:?}"
1387        );
1388    }
1389
1390    // ── BuilderStep::DoTry → DoTrySegment ──
1391
1392    fn dotry_registry() -> StepCompilerRegistry {
1393        let mut reg = StepCompilerRegistry::new();
1394        reg.register(Box::new(super::core::CoreCompiler));
1395        reg.register(Box::new(super::control_flow::ControlFlowCompiler));
1396        reg
1397    }
1398
1399    #[tokio::test]
1400    async fn do_try_compiles_to_segment() {
1401        use std::sync::atomic::{AtomicU32, Ordering};
1402
1403        use camel_api::error_handler::ExceptionDisposition;
1404        use camel_api::{OpaqueProcessor, PipelineOutcome};
1405        use camel_processor::CatchMatcher;
1406
1407        use crate::lifecycle::application::route_definition::DoTryCatchClause;
1408
1409        let catch_calls = Arc::new(AtomicU32::new(0));
1410        let catch_calls_child = Arc::clone(&catch_calls);
1411
1412        let step = BuilderStep::DoTry {
1413            try_steps: vec![BuilderStep::Processor(OpaqueProcessor(
1414                BoxProcessor::from_fn(|_ex| {
1415                    Box::pin(async move { Err(CamelError::ProcessorError("boom".into())) })
1416                }),
1417            ))],
1418            catches: vec![DoTryCatchClause {
1419                matcher: CatchMatcher::ByVariant(vec!["ProcessorError".into()]),
1420                on_when: None,
1421                disposition: ExceptionDisposition::Handled,
1422                steps: vec![BuilderStep::Processor(OpaqueProcessor(
1423                    BoxProcessor::from_fn(move |ex| {
1424                        catch_calls_child.fetch_add(1, Ordering::SeqCst);
1425                        Box::pin(async move { Ok(ex) })
1426                    }),
1427                ))],
1428            }],
1429            finally: None,
1430        };
1431
1432        let pc = ProducerContext::default();
1433        let rt: Arc<dyn RuntimeObservability> = Arc::new(NoopRuntimeObservability);
1434        let languages: SharedLanguageRegistry = Arc::new(Mutex::new(HashMap::new()));
1435        let beans: Arc<Mutex<BeanRegistry>> = Arc::new(Mutex::new(BeanRegistry::new()));
1436        let component_ctx: Arc<dyn ComponentContext> = Arc::new(NoOpComponentContext);
1437        let staging = FunctionStagingMode::DirectAdd;
1438        let idempotent_repositories = crate::IdempotentRegistry::new();
1439        let claim_check_repositories = crate::ClaimCheckRegistry::new();
1440        let cache_repositories = crate::CacheRegistry::new();
1441        let context = ctx(
1442            &pc,
1443            rt,
1444            &languages,
1445            &beans,
1446            component_ctx,
1447            &staging,
1448            &idempotent_repositories,
1449            &claim_check_repositories,
1450            &cache_repositories,
1451        );
1452
1453        let reg = dotry_registry();
1454        let compiled = reg
1455            .compile_step(step, 0, &context)
1456            .expect("compilation should succeed")
1457            .expect("DoTry should match");
1458
1459        let mut segment = match compiled {
1460            CompiledStep::Segment { segment, .. } => segment,
1461            other => panic!("expected CompiledStep::Segment, got {other:?}"),
1462        };
1463        let outcome = segment.run(camel_api::Exchange::default()).await;
1464        assert!(
1465            matches!(outcome, PipelineOutcome::Completed(_)),
1466            "handled catch should complete, got {outcome:?}"
1467        );
1468        assert_eq!(
1469            catch_calls.load(Ordering::SeqCst),
1470            1,
1471            "catch body must run once"
1472        );
1473    }
1474
1475    #[tokio::test]
1476    async fn stop_inside_try_skips_remaining_try_steps() {
1477        use std::sync::atomic::{AtomicU32, Ordering};
1478
1479        use camel_api::error_handler::ExceptionDisposition;
1480        use camel_api::{CAMEL_STOP, OpaqueProcessor, PipelineOutcome, Value};
1481        use camel_processor::CatchMatcher;
1482
1483        use crate::lifecycle::application::route_definition::{
1484            DoTryCatchClause, DoTryFinallyClause,
1485        };
1486
1487        let after_stop_calls = Arc::new(AtomicU32::new(0));
1488        let after_stop_calls_child = Arc::clone(&after_stop_calls);
1489        let catch_calls = Arc::new(AtomicU32::new(0));
1490        let catch_calls_child = Arc::clone(&catch_calls);
1491        let finally_calls = Arc::new(AtomicU32::new(0));
1492        let finally_calls_child = Arc::clone(&finally_calls);
1493
1494        let step = BuilderStep::DoTry {
1495            try_steps: vec![
1496                BuilderStep::Processor(OpaqueProcessor(BoxProcessor::from_fn(|ex| {
1497                    Box::pin(async move {
1498                        let mut ex = ex;
1499                        ex.set_property(CAMEL_STOP, Value::Bool(true));
1500                        Ok(ex)
1501                    })
1502                }))),
1503                BuilderStep::Processor(OpaqueProcessor(BoxProcessor::from_fn(move |ex| {
1504                    after_stop_calls_child.fetch_add(1, Ordering::SeqCst);
1505                    Box::pin(async move { Ok(ex) })
1506                }))),
1507            ],
1508            catches: vec![DoTryCatchClause {
1509                matcher: CatchMatcher::ByVariant(vec!["*".into()]),
1510                on_when: None,
1511                disposition: ExceptionDisposition::Handled,
1512                steps: vec![BuilderStep::Processor(OpaqueProcessor(
1513                    BoxProcessor::from_fn(move |ex| {
1514                        catch_calls_child.fetch_add(1, Ordering::SeqCst);
1515                        Box::pin(async move { Ok(ex) })
1516                    }),
1517                ))],
1518            }],
1519            finally: Some(DoTryFinallyClause {
1520                on_when: None,
1521                steps: vec![BuilderStep::Processor(OpaqueProcessor(
1522                    BoxProcessor::from_fn(move |ex| {
1523                        finally_calls_child.fetch_add(1, Ordering::SeqCst);
1524                        Box::pin(async move { Ok(ex) })
1525                    }),
1526                ))],
1527            }),
1528        };
1529
1530        let pc = ProducerContext::default();
1531        let rt: Arc<dyn RuntimeObservability> = Arc::new(NoopRuntimeObservability);
1532        let languages: SharedLanguageRegistry = Arc::new(Mutex::new(HashMap::new()));
1533        let beans: Arc<Mutex<BeanRegistry>> = Arc::new(Mutex::new(BeanRegistry::new()));
1534        let component_ctx: Arc<dyn ComponentContext> = Arc::new(NoOpComponentContext);
1535        let staging = FunctionStagingMode::DirectAdd;
1536        let idempotent_repositories = crate::IdempotentRegistry::new();
1537        let claim_check_repositories = crate::ClaimCheckRegistry::new();
1538        let cache_repositories = crate::CacheRegistry::new();
1539        let context = ctx(
1540            &pc,
1541            rt,
1542            &languages,
1543            &beans,
1544            component_ctx,
1545            &staging,
1546            &idempotent_repositories,
1547            &claim_check_repositories,
1548            &cache_repositories,
1549        );
1550
1551        let reg = dotry_registry();
1552        let compiled = reg
1553            .compile_step(step, 0, &context)
1554            .expect("compilation should succeed")
1555            .expect("DoTry should match");
1556
1557        let mut segment = match compiled {
1558            CompiledStep::Segment { segment, .. } => segment,
1559            other => panic!("expected CompiledStep::Segment, got {other:?}"),
1560        };
1561        let outcome = segment.run(camel_api::Exchange::default()).await;
1562        assert!(
1563            matches!(outcome, PipelineOutcome::Stopped(_)),
1564            "CamelStop marker inside try must propagate Stopped, got {outcome:?}"
1565        );
1566        assert_eq!(
1567            after_stop_calls.load(Ordering::SeqCst),
1568            0,
1569            "remaining try steps must not run after CamelStop marker"
1570        );
1571        assert_eq!(
1572            catch_calls.load(Ordering::SeqCst),
1573            0,
1574            "catch must not run when try stops"
1575        );
1576        assert_eq!(
1577            finally_calls.load(Ordering::SeqCst),
1578            0,
1579            "finally must not run when try stops"
1580        );
1581    }
1582}