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        // Dark slice: route ADDITION is still gated here. A `transacted` block
294        // can now pass load validation (boot registers one manager per catalog
295        // datasource), but the executor wiring that lowers the block into a
296        // running `TransactedSegment` is the family's NEXT slice: there is no
297        // block session to join yet, so a block that reaches lowering fails
298        // closed with the frozen typed join error naming the block datasource.
299        // Never silently skip the block, never panic.
300        if let BuilderStep::Transacted { datasource, .. } = &step {
301            return Err(CamelError::Transaction(
302                camel_api::TransactionError::JoinSessionMissing {
303                    datasource: datasource.clone(),
304                },
305            ));
306        }
307        // Capture the span label, kind hint, and declared To URI BEFORE the
308        // dispatch loop moves the step. The URI is the authored text, so a
309        // `SkipTo`/`DivertCopyTo` interception inside a compiler never
310        // rewrites the retained metadata.
311        let label = step.span_label();
312        let kind_hint = step.span_kind_hint();
313        let to_uri = step.to_uri_metadata();
314        let mut step = step;
315        for compiler in &self.compilers {
316            match compiler.compile(step, step_index, ctx, self)? {
317                CompileOutcome::Matched(mut s) => {
318                    s.set_label(label);
319                    s.set_kind_hint(kind_hint);
320                    s.set_to_uri(to_uri);
321                    return Ok(Some(s));
322                }
323                CompileOutcome::NotHandled(s) => step = s,
324            }
325        }
326        Ok(None)
327    }
328
329    /// Compile all steps in a vector.
330    pub fn compile_steps(
331        &self,
332        steps: Vec<BuilderStep>,
333        ctx: &CompilationContext,
334    ) -> Result<Vec<CompiledStep>, CamelError> {
335        let mut out = Vec::with_capacity(steps.len());
336        for (i, step) in steps.into_iter().enumerate() {
337            match self.compile_step(step, i, ctx)? {
338                Some(c) => out.push(c),
339                None => {
340                    return Err(CamelError::RouteError(
341                        "no compiler registered for step variant".into(),
342                    ));
343                }
344            }
345        }
346        Ok(out)
347    }
348}
349
350/// A resolved send target: the pieces the un-intercepted `To` path produces
351/// for one URI.
352pub(super) struct ResolvedSend {
353    pub producer: BoxProcessor,
354    pub body_contract: Option<BodyType>,
355    pub lifecycle: Option<Arc<dyn StepLifecycle>>,
356}
357
358/// Resolve a send URI into producer/body-contract/lifecycle, exactly as the
359/// un-intercepted `To` path does. Canonical resolution path for send steps;
360/// [`resolve_producer_with_lifecycle`] and [`resolve_producer`] are thin
361/// wrappers over this.
362pub(super) fn resolve_send(
363    ctx: &CompilationContext,
364    uri: &str,
365) -> Result<ResolvedSend, CamelError> {
366    let parsed = parse_uri(uri)?;
367    let component = ctx
368        .component_ctx
369        .resolve_component(&parsed.scheme)
370        .ok_or_else(|| CamelError::ComponentNotFound(parsed.scheme.clone()))?;
371    let endpoint = component.create_endpoint(uri, ctx.component_ctx.as_ref())?;
372    let body_contract = endpoint.body_contract();
373    let producer = endpoint.create_producer(Arc::clone(&ctx.rt), ctx.producer_ctx)?;
374    // Capture the endpoint's lifecycle handle so the route controller can
375    // start/shut it down in route order (ADR-0022). Default is `None` for
376    // stateless endpoints — see `Endpoint::lifecycle` in camel-component-api.
377    let lifecycle: Option<Arc<dyn StepLifecycle>> = endpoint.lifecycle();
378    Ok(ResolvedSend {
379        producer,
380        body_contract,
381        lifecycle,
382    })
383}
384
385/// Parse a URI and create a producer, also returning the endpoint's
386/// [`StepLifecycle`] handle (if any). Thin wrapper over [`resolve_send`] that
387/// discards the body contract. Use directly when the lifecycle is needed
388/// (e.g. `WireTap` propagation).
389pub(crate) fn resolve_producer_with_lifecycle(
390    ctx: &CompilationContext,
391    uri: &str,
392) -> Result<(BoxProcessor, Option<Arc<dyn StepLifecycle>>), CamelError> {
393    let resolved = resolve_send(ctx, uri)?;
394    Ok((resolved.producer, resolved.lifecycle))
395}
396
397/// Parse a URI and create a producer, reusing `component_ctx`, `rt`, and `producer_ctx`
398/// from the compilation context.
399///
400/// Thin wrapper over [`resolve_producer_with_lifecycle`] that discards the
401/// endpoint's [`StepLifecycle`] handle.
402pub(crate) fn resolve_producer(
403    ctx: &CompilationContext,
404    uri: &str,
405) -> Result<BoxProcessor, CamelError> {
406    Ok(resolve_producer_with_lifecycle(ctx, uri)?.0)
407}
408
409/// Pack a lifecycle Vec into `None` when empty, `Some` when non-empty.
410/// Preserves the invariant that `Some` always implies ≥1 handle.
411pub(super) fn pack_lifecycles(
412    lifecycles: Vec<Arc<dyn StepLifecycle>>,
413) -> Option<Vec<Arc<dyn StepLifecycle>>> {
414    if lifecycles.is_empty() {
415        None
416    } else {
417        Some(lifecycles)
418    }
419}
420
421/// Build the full registry with all compiler groups.
422pub(crate) fn build_registry() -> StepCompilerRegistry {
423    let mut reg = StepCompilerRegistry::new();
424    reg.register(Box::new(core::CoreCompiler));
425    reg.register(Box::new(endpoints::EndpointsCompiler));
426    reg.register(Box::new(transforms::TransformsCompiler));
427    reg.register(Box::new(routing::RoutingCompiler));
428    reg.register(Box::new(control_flow::ControlFlowCompiler));
429    reg.register(Box::new(middleware::MiddlewareCompiler));
430    reg.register(Box::new(splitting::SplittingCompiler));
431    reg.register(Box::new(error_handling::ErrorHandlingCompiler));
432    reg
433}
434
435#[cfg(test)]
436mod segment_tests {
437    use super::*;
438    use camel_api::{Exchange, OutcomePipeline, PipelineOutcome};
439    use std::future::Future;
440    use std::pin::Pin;
441
442    #[derive(Clone)]
443    struct EchoSegment;
444
445    impl OutcomePipeline for EchoSegment {
446        fn clone_box(&self) -> Box<dyn OutcomePipeline> {
447            Box::new(EchoSegment)
448        }
449        fn run<'a>(
450            &'a mut self,
451            exchange: Exchange,
452        ) -> Pin<Box<dyn Future<Output = PipelineOutcome> + Send + 'a>> {
453            Box::pin(async move { PipelineOutcome::Completed(exchange) })
454        }
455    }
456
457    #[test]
458    fn compiled_step_segment_clone_compiles() {
459        let seg = camel_api::OutcomeSegment::new(Box::new(EchoSegment));
460        let step = CompiledStep::Segment {
461            segment: seg,
462            body_contract: None,
463            lifecycle: None,
464            label: None,
465        };
466        let _cloned = step.clone();
467        if let CompiledStep::Segment { .. } = _cloned {
468            // ok
469        } else {
470            panic!("clone should preserve variant");
471        }
472    }
473
474    #[test]
475    fn compiled_step_segment_debug_renders() {
476        let seg = camel_api::OutcomeSegment::new(Box::new(EchoSegment));
477        let step = CompiledStep::Segment {
478            segment: seg,
479            body_contract: None,
480            lifecycle: None,
481            label: None,
482        };
483        let s = format!("{:?}", step);
484        assert!(
485            s.contains("Segment"),
486            "debug should mention Segment variant: {s}"
487        );
488    }
489
490    #[test]
491    fn outcome_segment_satisfies_clone_send_static() {
492        fn assert_traits<T: Clone + Send + 'static>() {}
493        assert_traits::<camel_api::OutcomeSegment>();
494    }
495
496    #[tokio::test]
497    #[allow(clippy::arc_with_non_send_sync)]
498    async fn outcome_segment_survives_arcswap_swap() {
499        use arc_swap::ArcSwap;
500        use camel_api::{Exchange, Message, OutcomePipeline, PipelineOutcome};
501        use std::sync::Arc;
502
503        #[derive(Clone)]
504        struct EchoSegment;
505        impl OutcomePipeline for EchoSegment {
506            fn clone_box(&self) -> Box<dyn OutcomePipeline> {
507                Box::new(EchoSegment)
508            }
509            fn run<'a>(
510                &'a mut self,
511                ex: Exchange,
512            ) -> std::pin::Pin<Box<dyn std::future::Future<Output = PipelineOutcome> + Send + 'a>>
513            {
514                Box::pin(async move { PipelineOutcome::Completed(ex) })
515            }
516        }
517
518        let seg = camel_api::OutcomeSegment::new(Box::new(EchoSegment));
519        let slot: ArcSwap<Option<camel_api::OutcomeSegment>> = ArcSwap::from_pointee(None);
520        slot.store(Arc::new(Some(seg.clone())));
521        slot.store(Arc::new(Some(seg)));
522
523        let mut borrowed = slot.load().as_ref().clone().unwrap();
524        let outcome = borrowed.run(Exchange::new(Message::new("ping"))).await;
525        assert!(matches!(outcome, PipelineOutcome::Completed(_)));
526    }
527
528    /// Test lifecycle handle used by compile_children_segments_bubbles_child_lifecycle.
529    #[derive(Debug)]
530    struct TestLifecycle;
531
532    #[async_trait::async_trait]
533    impl camel_api::StepLifecycle for TestLifecycle {
534        fn name(&self) -> &'static str {
535            "test-lifecycle"
536        }
537        async fn shutdown(
538            &self,
539            _reason: camel_api::StepShutdownReason,
540        ) -> Result<(), camel_api::CamelError> {
541            Ok(())
542        }
543    }
544
545    /// Custom compiler that injects a lifecycle handle into every
546    /// `BuilderStep::Processor` it compiles.
547    struct LifecycleInjectorCompiler {
548        handle: Arc<dyn camel_api::StepLifecycle>,
549    }
550
551    impl StepCompiler for LifecycleInjectorCompiler {
552        fn compile(
553            &self,
554            step: BuilderStep,
555            _step_index: usize,
556            _ctx: &CompilationContext,
557            _registry: &StepCompilerRegistry,
558        ) -> Result<CompileOutcome, CamelError> {
559            match step {
560                BuilderStep::Processor(op) => Ok(CompileOutcome::Matched(CompiledStep::Process {
561                    processor: op.0,
562                    body_contract: None,
563                    lifecycle: Some(self.handle.clone()),
564                    label: None,
565                    kind_hint: SpanKindHint::Internal,
566                    to_uri: None,
567                })),
568                other => Ok(CompileOutcome::NotHandled(other)),
569            }
570        }
571    }
572
573    #[tokio::test]
574    async fn compile_children_segments_bubbles_child_lifecycle() {
575        use std::collections::HashMap;
576        use std::sync::Mutex;
577
578        use camel_api::{
579            BoxProcessor, BoxProcessorExt, FilterPredicate, OpaqueProcessor, StepLifecycle,
580        };
581        use camel_bean::BeanRegistry;
582        use camel_component_api::{
583            ComponentContext, NoOpComponentContext, RuntimeObservability,
584            test_support::NoopRuntimeObservability,
585        };
586
587        use crate::lifecycle::adapters::step_resolution::FunctionStagingMode;
588
589        let handle: Arc<dyn StepLifecycle> = Arc::new(TestLifecycle);
590
591        // Register lifecycle injector + real control-flow compiler so
592        // compile_children_segments runs through a structural EIP path.
593        let mut reg = StepCompilerRegistry::new();
594        reg.register(Box::new(LifecycleInjectorCompiler {
595            handle: handle.clone(),
596        }));
597        reg.register(Box::new(super::control_flow::ControlFlowCompiler));
598
599        let pc = ProducerContext::default();
600        let rt: Arc<dyn RuntimeObservability> = Arc::new(NoopRuntimeObservability);
601        let languages: SharedLanguageRegistry = Arc::new(Mutex::new(HashMap::new()));
602        let beans: Arc<Mutex<BeanRegistry>> = Arc::new(Mutex::new(BeanRegistry::new()));
603        let component_ctx: Arc<dyn ComponentContext> = Arc::new(NoOpComponentContext);
604        let staging = FunctionStagingMode::DirectAdd;
605        let idempotent_repositories = crate::IdempotentRegistry::new();
606        let claim_check_repositories = crate::ClaimCheckRegistry::new();
607        let cache_repositories = crate::CacheRegistry::new();
608
609        let ctx = CompilationContext {
610            producer_ctx: &pc,
611            rt,
612            languages: &languages,
613            beans: &beans,
614            function_invoker: None,
615            component_ctx,
616            route_id: None,
617            staging_mode: &staging,
618            idempotent_repositories: &idempotent_repositories,
619            claim_check_repositories: &claim_check_repositories,
620            cache_repositories: &cache_repositories,
621            intercept: InterceptRules::default(),
622        };
623
624        // Compile a Filter with a child Processor step.
625        let filter_step = BuilderStep::Filter {
626            predicate: FilterPredicate::new(|_| true),
627            steps: vec![BuilderStep::Processor(OpaqueProcessor(
628                BoxProcessor::from_fn(|ex| Box::pin(async move { Ok(ex) })),
629            ))],
630        };
631
632        let result = reg.compile_step(filter_step, 0, &ctx);
633        let compiled = result
634            .expect("compilation should succeed")
635            .expect("should match");
636
637        match compiled {
638            CompiledStep::Segment {
639                lifecycle,
640                body_contract,
641                ..
642            } => {
643                assert_eq!(body_contract, None, "body_contract should be None");
644                let handles = lifecycle.expect("Segment should have lifecycle handles");
645                assert_eq!(handles.len(), 1, "expected 1 lifecycle handle");
646                assert_eq!(handles[0].name(), "test-lifecycle", "handle name mismatch");
647            }
648            other => panic!("Expected CompiledStep::Segment, got {other:?}"),
649        }
650    }
651
652    /// A lifecycle handle with a configurable name for multi-handle tests.
653    #[derive(Debug)]
654    struct NamedLifecycle(&'static str);
655
656    #[async_trait::async_trait]
657    impl camel_api::StepLifecycle for NamedLifecycle {
658        fn name(&self) -> &'static str {
659            self.0
660        }
661        async fn shutdown(
662            &self,
663            _reason: camel_api::StepShutdownReason,
664        ) -> Result<(), camel_api::CamelError> {
665            Ok(())
666        }
667    }
668
669    /// Test A: Multiple stateful children in one Segment → Vec length 2.
670    #[tokio::test]
671    async fn compile_children_segments_multiple_stateful_children() {
672        use std::collections::HashMap;
673        use std::sync::Mutex;
674
675        use crate::lifecycle::adapters::step_resolution::FunctionStagingMode;
676        use camel_api::{
677            BoxProcessor, BoxProcessorExt, FilterPredicate, OpaqueProcessor, StepLifecycle,
678        };
679        use camel_bean::BeanRegistry;
680        use camel_component_api::{
681            ComponentContext, NoOpComponentContext, RuntimeObservability,
682            test_support::NoopRuntimeObservability,
683        };
684
685        let handle: Arc<dyn StepLifecycle> = Arc::new(NamedLifecycle("multi"));
686
687        let mut reg = StepCompilerRegistry::new();
688        reg.register(Box::new(LifecycleInjectorCompiler {
689            handle: handle.clone(),
690        }));
691        reg.register(Box::new(super::control_flow::ControlFlowCompiler));
692
693        let pc = ProducerContext::default();
694        let rt: Arc<dyn RuntimeObservability> = Arc::new(NoopRuntimeObservability);
695        let languages: SharedLanguageRegistry = Arc::new(Mutex::new(HashMap::new()));
696        let beans: Arc<Mutex<BeanRegistry>> = Arc::new(Mutex::new(BeanRegistry::new()));
697        let component_ctx: Arc<dyn ComponentContext> = Arc::new(NoOpComponentContext);
698        let staging = FunctionStagingMode::DirectAdd;
699        let idempotent_repositories = crate::IdempotentRegistry::new();
700        let claim_check_repositories = crate::ClaimCheckRegistry::new();
701        let cache_repositories = crate::CacheRegistry::new();
702
703        let ctx = CompilationContext {
704            producer_ctx: &pc,
705            rt,
706            languages: &languages,
707            beans: &beans,
708            function_invoker: None,
709            component_ctx,
710            route_id: None,
711            staging_mode: &staging,
712            idempotent_repositories: &idempotent_repositories,
713            claim_check_repositories: &claim_check_repositories,
714            cache_repositories: &cache_repositories,
715            intercept: InterceptRules::default(),
716        };
717
718        // Filter with TWO child Processors → both get the same lifecycle handle.
719        let filter_step = BuilderStep::Filter {
720            predicate: FilterPredicate::new(|_| true),
721            steps: vec![
722                BuilderStep::Processor(OpaqueProcessor(BoxProcessor::from_fn(|ex| {
723                    Box::pin(async move { Ok(ex) })
724                }))),
725                BuilderStep::Processor(OpaqueProcessor(BoxProcessor::from_fn(|ex| {
726                    Box::pin(async move { Ok(ex) })
727                }))),
728            ],
729        };
730
731        let result = reg.compile_step(filter_step, 0, &ctx);
732        let compiled = result
733            .expect("compilation should succeed")
734            .expect("should match");
735
736        match compiled {
737            CompiledStep::Segment { lifecycle, .. } => {
738                let handles = lifecycle.expect("Segment should have lifecycle handles");
739                assert_eq!(
740                    handles.len(),
741                    2,
742                    "expected 2 lifecycle handles for 2 children"
743                );
744                for h in &handles {
745                    assert_eq!(h.name(), "multi", "all handles should be 'multi'");
746                }
747            }
748            other => panic!("Expected CompiledStep::Segment, got {other:?}"),
749        }
750    }
751
752    /// Test B: Multi-branch accumulation across Choice when-clauses.
753    #[tokio::test]
754    async fn compile_children_segments_multi_branch_accumulation() {
755        use std::collections::HashMap;
756        use std::sync::Mutex;
757
758        use crate::lifecycle::adapters::step_resolution::FunctionStagingMode;
759        use crate::lifecycle::application::route_definition::WhenStep;
760        use camel_api::{
761            BoxProcessor, BoxProcessorExt, FilterPredicate, OpaqueProcessor, StepLifecycle,
762        };
763        use camel_bean::BeanRegistry;
764        use camel_component_api::{
765            ComponentContext, NoOpComponentContext, RuntimeObservability,
766            test_support::NoopRuntimeObservability,
767        };
768
769        let handle: Arc<dyn StepLifecycle> = Arc::new(NamedLifecycle("branch"));
770
771        let mut reg = StepCompilerRegistry::new();
772        reg.register(Box::new(LifecycleInjectorCompiler {
773            handle: handle.clone(),
774        }));
775        reg.register(Box::new(super::control_flow::ControlFlowCompiler));
776
777        let pc = ProducerContext::default();
778        let rt: Arc<dyn RuntimeObservability> = Arc::new(NoopRuntimeObservability);
779        let languages: SharedLanguageRegistry = Arc::new(Mutex::new(HashMap::new()));
780        let beans: Arc<Mutex<BeanRegistry>> = Arc::new(Mutex::new(BeanRegistry::new()));
781        let component_ctx: Arc<dyn ComponentContext> = Arc::new(NoOpComponentContext);
782        let staging = FunctionStagingMode::DirectAdd;
783        let idempotent_repositories = crate::IdempotentRegistry::new();
784        let claim_check_repositories = crate::ClaimCheckRegistry::new();
785        let cache_repositories = crate::CacheRegistry::new();
786
787        let ctx = CompilationContext {
788            producer_ctx: &pc,
789            rt,
790            languages: &languages,
791            beans: &beans,
792            function_invoker: None,
793            component_ctx,
794            route_id: None,
795            staging_mode: &staging,
796            idempotent_repositories: &idempotent_repositories,
797            claim_check_repositories: &claim_check_repositories,
798            cache_repositories: &cache_repositories,
799            intercept: InterceptRules::default(),
800        };
801
802        // Choice with 2 when branches, each containing 1 stateful child.
803        let choice_step = BuilderStep::Choice {
804            whens: vec![
805                WhenStep {
806                    predicate: FilterPredicate::new(|_| true),
807                    steps: vec![BuilderStep::Processor(OpaqueProcessor(
808                        BoxProcessor::from_fn(|ex| Box::pin(async move { Ok(ex) })),
809                    ))],
810                },
811                WhenStep {
812                    predicate: FilterPredicate::new(|_| false),
813                    steps: vec![BuilderStep::Processor(OpaqueProcessor(
814                        BoxProcessor::from_fn(|ex| Box::pin(async move { Ok(ex) })),
815                    ))],
816                },
817            ],
818            otherwise: None,
819        };
820
821        let result = reg.compile_step(choice_step, 0, &ctx);
822        let compiled = result
823            .expect("compilation should succeed")
824            .expect("should match");
825
826        match compiled {
827            CompiledStep::Segment { lifecycle, .. } => {
828                let handles = lifecycle.expect("Segment should have lifecycle handles");
829                assert_eq!(
830                    handles.len(),
831                    2,
832                    "expected 2 lifecycle handles from 2 branches"
833                );
834                for h in &handles {
835                    assert_eq!(h.name(), "branch", "all handles should be 'branch'");
836                }
837            }
838            other => panic!("Expected CompiledStep::Segment, got {other:?}"),
839        }
840    }
841
842    /// Test C: Nested Segment-in-Segment flattening — outer Segment contains
843    /// innermost lifecycle handle from a grandchild Processor.
844    #[tokio::test]
845    async fn compile_children_segments_nested_segment_flattening() {
846        use std::collections::HashMap;
847        use std::sync::Mutex;
848
849        use crate::lifecycle::adapters::step_resolution::FunctionStagingMode;
850        use camel_api::{
851            BoxProcessor, BoxProcessorExt, FilterPredicate, OpaqueProcessor, StepLifecycle,
852        };
853        use camel_bean::BeanRegistry;
854        use camel_component_api::{
855            ComponentContext, NoOpComponentContext, RuntimeObservability,
856            test_support::NoopRuntimeObservability,
857        };
858
859        let inner_handle: Arc<dyn StepLifecycle> = Arc::new(NamedLifecycle("deep"));
860
861        let mut reg = StepCompilerRegistry::new();
862        reg.register(Box::new(LifecycleInjectorCompiler {
863            handle: inner_handle.clone(),
864        }));
865        reg.register(Box::new(super::control_flow::ControlFlowCompiler));
866
867        let pc = ProducerContext::default();
868        let rt: Arc<dyn RuntimeObservability> = Arc::new(NoopRuntimeObservability);
869        let languages: SharedLanguageRegistry = Arc::new(Mutex::new(HashMap::new()));
870        let beans: Arc<Mutex<BeanRegistry>> = Arc::new(Mutex::new(BeanRegistry::new()));
871        let component_ctx: Arc<dyn ComponentContext> = Arc::new(NoOpComponentContext);
872        let staging = FunctionStagingMode::DirectAdd;
873        let idempotent_repositories = crate::IdempotentRegistry::new();
874        let claim_check_repositories = crate::ClaimCheckRegistry::new();
875        let cache_repositories = crate::CacheRegistry::new();
876
877        let ctx = CompilationContext {
878            producer_ctx: &pc,
879            rt,
880            languages: &languages,
881            beans: &beans,
882            function_invoker: None,
883            component_ctx,
884            route_id: None,
885            staging_mode: &staging,
886            idempotent_repositories: &idempotent_repositories,
887            claim_check_repositories: &claim_check_repositories,
888            cache_repositories: &cache_repositories,
889            intercept: InterceptRules::default(),
890        };
891
892        // Outer Filter containing an inner Filter that has a stateful Processor.
893        // The outer Segment's lifecycle should contain the innermost handle
894        // (proves recursive flattening through compile_children_segments).
895        let inner_filter = BuilderStep::Filter {
896            predicate: FilterPredicate::new(|_| true),
897            steps: vec![BuilderStep::Processor(OpaqueProcessor(
898                BoxProcessor::from_fn(|ex| Box::pin(async move { Ok(ex) })),
899            ))],
900        };
901
902        let outer_filter = BuilderStep::Filter {
903            predicate: FilterPredicate::new(|_| true),
904            steps: vec![inner_filter],
905        };
906
907        let result = reg.compile_step(outer_filter, 0, &ctx);
908        let compiled = result
909            .expect("compilation should succeed")
910            .expect("should match");
911
912        match compiled {
913            CompiledStep::Segment { lifecycle, .. } => {
914                let handles = lifecycle.expect("outer Segment should have lifecycle handles");
915                assert_eq!(handles.len(), 1, "expected 1 innermost lifecycle handle");
916                assert_eq!(
917                    handles[0].name(),
918                    "deep",
919                    "handle should be from innermost child"
920                );
921            }
922            other => panic!("Expected CompiledStep::Segment, got {other:?}"),
923        }
924    }
925}
926
927#[cfg(test)]
928mod dispatch_tests {
929    use super::*;
930    use crate::lifecycle::adapters::step_resolution::FunctionStagingMode;
931    use camel_api::{BoxProcessor, BoxProcessorExt};
932    use camel_bean::BeanRegistry;
933    use camel_component_api::{
934        ComponentContext, NoOpComponentContext, RuntimeObservability,
935        test_support::NoopRuntimeObservability,
936    };
937    use std::collections::HashMap;
938    use std::sync::Mutex;
939
940    /// Compiler that handles `BuilderStep::To` → `CompiledStep::Stop`.
941    struct ToStopCompiler;
942
943    impl StepCompiler for ToStopCompiler {
944        fn compile(
945            &self,
946            step: BuilderStep,
947            _step_index: usize,
948            _ctx: &CompilationContext,
949            _registry: &StepCompilerRegistry,
950        ) -> Result<CompileOutcome, CamelError> {
951            match step {
952                BuilderStep::To(_) => Ok(CompileOutcome::Matched(CompiledStep::Stop)),
953                other => Ok(CompileOutcome::NotHandled(other)),
954            }
955        }
956    }
957
958    /// Compiler that handles `BuilderStep::To` → `CompiledStep::Process`.
959    struct ToProcessCompiler;
960
961    impl StepCompiler for ToProcessCompiler {
962        fn compile(
963            &self,
964            step: BuilderStep,
965            _step_index: usize,
966            _ctx: &CompilationContext,
967            _registry: &StepCompilerRegistry,
968        ) -> Result<CompileOutcome, CamelError> {
969            match step {
970                BuilderStep::To(_) => Ok(CompileOutcome::Matched(CompiledStep::Process {
971                    processor: BoxProcessor::from_fn(|ex| Box::pin(async move { Ok(ex) })),
972                    body_contract: None,
973                    lifecycle: None,
974                    label: None,
975                    kind_hint: SpanKindHint::Internal,
976                    to_uri: None,
977                })),
978                other => Ok(CompileOutcome::NotHandled(other)),
979            }
980        }
981    }
982
983    /// Minimal outcome pipeline for building `Segment` fixtures in tests.
984    #[derive(Clone)]
985    struct NoopPipeline;
986
987    impl camel_api::OutcomePipeline for NoopPipeline {
988        fn clone_box(&self) -> Box<dyn camel_api::OutcomePipeline> {
989            Box::new(NoopPipeline)
990        }
991
992        fn run<'a>(
993            &'a mut self,
994            exchange: camel_api::Exchange,
995        ) -> std::pin::Pin<
996            Box<dyn std::future::Future<Output = camel_api::PipelineOutcome> + Send + 'a>,
997        > {
998            Box::pin(async move { camel_api::PipelineOutcome::Completed(exchange) })
999        }
1000    }
1001
1002    /// Compiler that passes all steps through (never handles any variant).
1003    /// Returns `NotHandled(step)` for every input, proving by-value pass-through.
1004    struct PassThroughCompiler;
1005
1006    impl StepCompiler for PassThroughCompiler {
1007        fn compile(
1008            &self,
1009            step: BuilderStep,
1010            _step_index: usize,
1011            _ctx: &CompilationContext,
1012            _registry: &StepCompilerRegistry,
1013        ) -> Result<CompileOutcome, CamelError> {
1014            Ok(CompileOutcome::NotHandled(step))
1015        }
1016    }
1017
1018    /// Shared context builder — avoids repeating the 15-line setup in every test.
1019    #[allow(clippy::too_many_arguments)]
1020    fn ctx<'a>(
1021        pc: &'a ProducerContext,
1022        rt: Arc<dyn RuntimeObservability>,
1023        languages: &'a SharedLanguageRegistry,
1024        beans: &'a Arc<Mutex<BeanRegistry>>,
1025        component_ctx: Arc<dyn ComponentContext>,
1026        staging: &'a FunctionStagingMode,
1027        idempotent_repositories: &'a crate::IdempotentRegistry,
1028        claim_check_repositories: &'a crate::ClaimCheckRegistry,
1029        cache_repositories: &'a crate::CacheRegistry,
1030    ) -> CompilationContext<'a> {
1031        CompilationContext {
1032            producer_ctx: pc,
1033            rt,
1034            languages,
1035            beans,
1036            function_invoker: None,
1037            component_ctx,
1038            route_id: None,
1039            staging_mode: staging,
1040            idempotent_repositories,
1041            claim_check_repositories,
1042            cache_repositories,
1043            intercept: InterceptRules::default(),
1044        }
1045    }
1046
1047    /// Test that the dispatcher respects registration order: the first matching
1048    /// compiler wins even when a later compiler also matches.
1049    #[test]
1050    fn compile_step_preserves_registry_order() {
1051        let pc = ProducerContext::default();
1052        let rt: Arc<dyn RuntimeObservability> = Arc::new(NoopRuntimeObservability);
1053        let languages: SharedLanguageRegistry = Arc::new(Mutex::new(HashMap::new()));
1054        let beans: Arc<Mutex<BeanRegistry>> = Arc::new(Mutex::new(BeanRegistry::new()));
1055        let component_ctx: Arc<dyn ComponentContext> = Arc::new(NoOpComponentContext);
1056        let staging = FunctionStagingMode::DirectAdd;
1057        let idempotent_repositories = crate::IdempotentRegistry::new();
1058        let claim_check_repositories = crate::ClaimCheckRegistry::new();
1059        let cache_repositories = crate::CacheRegistry::new();
1060
1061        let context = ctx(
1062            &pc,
1063            rt,
1064            &languages,
1065            &beans,
1066            component_ctx,
1067            &staging,
1068            &idempotent_repositories,
1069            &claim_check_repositories,
1070            &cache_repositories,
1071        );
1072
1073        // Register ToStopCompiler FIRST, ToProcessCompiler SECOND.
1074        // Both match BuilderStep::To. The first-registered should win.
1075        let mut reg = StepCompilerRegistry::new();
1076        reg.register(Box::new(ToStopCompiler));
1077        reg.register(Box::new(ToProcessCompiler));
1078
1079        let result = reg
1080            .compile_step(BuilderStep::To("test".into()), 0, &context)
1081            .expect("compilation should succeed")
1082            .expect("should match");
1083
1084        assert!(
1085            matches!(result, CompiledStep::Stop),
1086            "expected ToStopCompiler (first registered) to win, got {result:?}"
1087        );
1088    }
1089
1090    /// Task 1.2 (span-name-enrichment): `set_label` is a no-op on `Stop`.
1091    #[test]
1092    fn set_label_noop_on_stop() {
1093        let mut step = CompiledStep::Stop;
1094        step.set_label(Some("x".into()));
1095        assert!(
1096            matches!(step, CompiledStep::Stop),
1097            "set_label must not change a Stop step, got {step:?}"
1098        );
1099    }
1100
1101    /// Task 1.2 (span-name-enrichment): `compile_step` stamps the outcome with
1102    /// the step's `span_label` (here `to:direct` from `BuilderStep::To`).
1103    #[test]
1104    fn compile_step_stamps_label() {
1105        let pc = ProducerContext::default();
1106        let rt: Arc<dyn RuntimeObservability> = Arc::new(NoopRuntimeObservability);
1107        let languages: SharedLanguageRegistry = Arc::new(Mutex::new(HashMap::new()));
1108        let beans: Arc<Mutex<BeanRegistry>> = Arc::new(Mutex::new(BeanRegistry::new()));
1109        let component_ctx: Arc<dyn ComponentContext> = Arc::new(NoOpComponentContext);
1110        let staging = FunctionStagingMode::DirectAdd;
1111        let idempotent_repositories = crate::IdempotentRegistry::new();
1112        let claim_check_repositories = crate::ClaimCheckRegistry::new();
1113        let cache_repositories = crate::CacheRegistry::new();
1114
1115        let context = ctx(
1116            &pc,
1117            rt,
1118            &languages,
1119            &beans,
1120            component_ctx,
1121            &staging,
1122            &idempotent_repositories,
1123            &claim_check_repositories,
1124            &cache_repositories,
1125        );
1126
1127        let mut reg = StepCompilerRegistry::new();
1128        reg.register(Box::new(ToProcessCompiler));
1129
1130        let result = reg
1131            .compile_step(BuilderStep::To("direct:x".into()), 0, &context)
1132            .expect("compilation should succeed")
1133            .expect("should match");
1134
1135        match result {
1136            CompiledStep::Process { label, .. } => {
1137                assert_eq!(label.as_deref(), Some("to:direct"));
1138            }
1139            other => panic!("expected Process, got {other:?}"),
1140        }
1141    }
1142
1143    /// Task 1.2 (span-kind-hint): `set_kind_hint` is a no-op on `Stop` and
1144    /// `Segment` — only `Process` carries a kind hint, and a Segment's label
1145    /// must survive the call untouched.
1146    #[test]
1147    fn set_kind_hint_noop_on_stop_and_segment() {
1148        use camel_api::SpanKindHint;
1149
1150        // Stop: the marker produces no step span, so it carries no kind.
1151        let mut step = CompiledStep::Stop;
1152        step.set_kind_hint(SpanKindHint::Client);
1153        assert!(
1154            matches!(step, CompiledStep::Stop),
1155            "set_kind_hint must not change a Stop step, got {step:?}"
1156        );
1157
1158        // Segment: no kind_hint field; its label is unchanged.
1159        let mut step = CompiledStep::Segment {
1160            segment: camel_api::OutcomeSegment::new(Box::new(NoopPipeline)),
1161            body_contract: None,
1162            lifecycle: None,
1163            label: Some("seg".into()),
1164        };
1165        step.set_kind_hint(SpanKindHint::Client);
1166        match step {
1167            CompiledStep::Segment { label, .. } => {
1168                assert_eq!(label.as_deref(), Some("seg"));
1169            }
1170            other => panic!("expected Segment to stay a Segment, got {other:?}"),
1171        }
1172    }
1173
1174    /// Task 1.2 (span-kind-hint): `compile_step` stamps the outcome with the
1175    /// step's `span_kind_hint` (here `kafka` → Producer) alongside the label.
1176    #[test]
1177    fn compile_step_stamps_kind_hint() {
1178        use camel_api::SpanKindHint;
1179
1180        let pc = ProducerContext::default();
1181        let rt: Arc<dyn RuntimeObservability> = Arc::new(NoopRuntimeObservability);
1182        let languages: SharedLanguageRegistry = Arc::new(Mutex::new(HashMap::new()));
1183        let beans: Arc<Mutex<BeanRegistry>> = Arc::new(Mutex::new(BeanRegistry::new()));
1184        let component_ctx: Arc<dyn ComponentContext> = Arc::new(NoOpComponentContext);
1185        let staging = FunctionStagingMode::DirectAdd;
1186        let idempotent_repositories = crate::IdempotentRegistry::new();
1187        let claim_check_repositories = crate::ClaimCheckRegistry::new();
1188        let cache_repositories = crate::CacheRegistry::new();
1189
1190        let context = ctx(
1191            &pc,
1192            rt,
1193            &languages,
1194            &beans,
1195            component_ctx,
1196            &staging,
1197            &idempotent_repositories,
1198            &claim_check_repositories,
1199            &cache_repositories,
1200        );
1201
1202        let mut reg = StepCompilerRegistry::new();
1203        reg.register(Box::new(ToProcessCompiler));
1204
1205        let result = reg
1206            .compile_step(BuilderStep::To("kafka:orders".into()), 0, &context)
1207            .expect("compilation should succeed")
1208            .expect("should match");
1209
1210        match result {
1211            CompiledStep::Process {
1212                kind_hint, label, ..
1213            } => {
1214                assert_eq!(kind_hint, SpanKindHint::Producer);
1215                assert_eq!(label.as_deref(), Some("to:kafka"));
1216            }
1217            other => panic!("expected Process, got {other:?}"),
1218        }
1219    }
1220
1221    /// Task 1.1 (steplatency): `compile_step` retains the declared To URI —
1222    /// the raw authored text, captured before endpoint resolution and
1223    /// interception — as shared immutable string metadata on the compiled
1224    /// `Process` step.
1225    #[test]
1226    fn compiled_to_step_retains_declared_uri() {
1227        let pc = ProducerContext::default();
1228        let rt: Arc<dyn RuntimeObservability> = Arc::new(NoopRuntimeObservability);
1229        let languages: SharedLanguageRegistry = Arc::new(Mutex::new(HashMap::new()));
1230        let beans: Arc<Mutex<BeanRegistry>> = Arc::new(Mutex::new(BeanRegistry::new()));
1231        let component_ctx: Arc<dyn ComponentContext> = Arc::new(NoOpComponentContext);
1232        let staging = FunctionStagingMode::DirectAdd;
1233        let idempotent_repositories = crate::IdempotentRegistry::new();
1234        let claim_check_repositories = crate::ClaimCheckRegistry::new();
1235        let cache_repositories = crate::CacheRegistry::new();
1236
1237        let context = ctx(
1238            &pc,
1239            rt,
1240            &languages,
1241            &beans,
1242            component_ctx,
1243            &staging,
1244            &idempotent_repositories,
1245            &claim_check_repositories,
1246            &cache_repositories,
1247        );
1248
1249        let mut reg = StepCompilerRegistry::new();
1250        reg.register(Box::new(ToProcessCompiler));
1251
1252        let result = reg
1253            .compile_step(BuilderStep::To("direct:orders".into()), 0, &context)
1254            .expect("compilation should succeed")
1255            .expect("should match");
1256
1257        match result {
1258            CompiledStep::Process { to_uri, .. } => {
1259                assert_eq!(to_uri, Some(Arc::from("direct:orders")));
1260            }
1261            other => panic!("expected Process, got {other:?}"),
1262        }
1263    }
1264
1265    /// Task 1.1 (steplatency): a non-To process step carries no declared URI.
1266    #[test]
1267    fn compiled_processor_step_has_no_declared_uri() {
1268        use camel_api::OpaqueProcessor;
1269
1270        let pc = ProducerContext::default();
1271        let rt: Arc<dyn RuntimeObservability> = Arc::new(NoopRuntimeObservability);
1272        let languages: SharedLanguageRegistry = Arc::new(Mutex::new(HashMap::new()));
1273        let beans: Arc<Mutex<BeanRegistry>> = Arc::new(Mutex::new(BeanRegistry::new()));
1274        let component_ctx: Arc<dyn ComponentContext> = Arc::new(NoOpComponentContext);
1275        let staging = FunctionStagingMode::DirectAdd;
1276        let idempotent_repositories = crate::IdempotentRegistry::new();
1277        let claim_check_repositories = crate::ClaimCheckRegistry::new();
1278        let cache_repositories = crate::CacheRegistry::new();
1279
1280        let context = ctx(
1281            &pc,
1282            rt,
1283            &languages,
1284            &beans,
1285            component_ctx,
1286            &staging,
1287            &idempotent_repositories,
1288            &claim_check_repositories,
1289            &cache_repositories,
1290        );
1291
1292        let mut reg = StepCompilerRegistry::new();
1293        reg.register(Box::new(super::core::CoreCompiler));
1294
1295        let result = reg
1296            .compile_step(
1297                BuilderStep::Processor(OpaqueProcessor(BoxProcessor::from_fn(|ex| {
1298                    Box::pin(async move { Ok(ex) })
1299                }))),
1300                0,
1301                &context,
1302            )
1303            .expect("compilation should succeed")
1304            .expect("should match");
1305
1306        match result {
1307            CompiledStep::Process { to_uri, .. } => {
1308                assert_eq!(to_uri, None);
1309            }
1310            other => panic!("expected Process, got {other:?}"),
1311        }
1312    }
1313
1314    /// Test that when no compiler handles a variant, the dispatcher returns
1315    /// `Ok(None)` rather than an error.
1316    #[test]
1317    fn compile_step_unhandled_returns_ok_none() {
1318        let pc = ProducerContext::default();
1319        let rt: Arc<dyn RuntimeObservability> = Arc::new(NoopRuntimeObservability);
1320        let languages: SharedLanguageRegistry = Arc::new(Mutex::new(HashMap::new()));
1321        let beans: Arc<Mutex<BeanRegistry>> = Arc::new(Mutex::new(BeanRegistry::new()));
1322        let component_ctx: Arc<dyn ComponentContext> = Arc::new(NoOpComponentContext);
1323        let staging = FunctionStagingMode::DirectAdd;
1324        let idempotent_repositories = crate::IdempotentRegistry::new();
1325        let claim_check_repositories = crate::ClaimCheckRegistry::new();
1326        let cache_repositories = crate::CacheRegistry::new();
1327
1328        let context = ctx(
1329            &pc,
1330            rt,
1331            &languages,
1332            &beans,
1333            component_ctx,
1334            &staging,
1335            &idempotent_repositories,
1336            &claim_check_repositories,
1337            &cache_repositories,
1338        );
1339
1340        // Register a compiler that only handles BuilderStep::To.
1341        let mut reg = StepCompilerRegistry::new();
1342        reg.register(Box::new(ToStopCompiler));
1343
1344        // Send a BuilderStep::Log variant — ToStopCompiler does not match it.
1345        let result = reg.compile_step(
1346            BuilderStep::Log {
1347                level: camel_processor::LogLevel::Info,
1348                message: "unhandled".into(),
1349            },
1350            0,
1351            &context,
1352        );
1353
1354        assert!(
1355            matches!(result, Ok(None)),
1356            "expected Ok(None), got {result:?}"
1357        );
1358    }
1359
1360    /// Test that `NotHandled(step)` passes the step by-value to the next
1361    /// compiler. Compiler N returns `NotHandled(step)` for a variant that
1362    /// compiler N+1 handles — proving the step is not dropped or replaced.
1363    #[test]
1364    fn compile_step_nothandled_passes_step_intact_to_next_compiler() {
1365        let pc = ProducerContext::default();
1366        let rt: Arc<dyn RuntimeObservability> = Arc::new(NoopRuntimeObservability);
1367        let languages: SharedLanguageRegistry = Arc::new(Mutex::new(HashMap::new()));
1368        let beans: Arc<Mutex<BeanRegistry>> = Arc::new(Mutex::new(BeanRegistry::new()));
1369        let component_ctx: Arc<dyn ComponentContext> = Arc::new(NoOpComponentContext);
1370        let staging = FunctionStagingMode::DirectAdd;
1371        let idempotent_repositories = crate::IdempotentRegistry::new();
1372        let claim_check_repositories = crate::ClaimCheckRegistry::new();
1373        let cache_repositories = crate::CacheRegistry::new();
1374
1375        let context = ctx(
1376            &pc,
1377            rt,
1378            &languages,
1379            &beans,
1380            component_ctx,
1381            &staging,
1382            &idempotent_repositories,
1383            &claim_check_repositories,
1384            &cache_repositories,
1385        );
1386
1387        // Register PassThroughCompiler FIRST (never handles anything),
1388        // ToStopCompiler SECOND (handles BuilderStep::To).
1389        let mut reg = StepCompilerRegistry::new();
1390        reg.register(Box::new(PassThroughCompiler));
1391        reg.register(Box::new(ToStopCompiler));
1392
1393        let result = reg
1394            .compile_step(BuilderStep::To("passthrough".into()), 0, &context)
1395            .expect("compilation should succeed")
1396            .expect("should match");
1397
1398        assert!(
1399            matches!(result, CompiledStep::Stop),
1400            "expected ToStopCompiler (N+1) to win after pass-through, got {result:?}"
1401        );
1402    }
1403
1404    // ── BuilderStep::DoTry → DoTrySegment ──
1405
1406    fn dotry_registry() -> StepCompilerRegistry {
1407        let mut reg = StepCompilerRegistry::new();
1408        reg.register(Box::new(super::core::CoreCompiler));
1409        reg.register(Box::new(super::control_flow::ControlFlowCompiler));
1410        reg
1411    }
1412
1413    #[tokio::test]
1414    async fn do_try_compiles_to_segment() {
1415        use std::sync::atomic::{AtomicU32, Ordering};
1416
1417        use camel_api::error_handler::ExceptionDisposition;
1418        use camel_api::{OpaqueProcessor, PipelineOutcome};
1419        use camel_processor::CatchMatcher;
1420
1421        use crate::lifecycle::application::route_definition::DoTryCatchClause;
1422
1423        let catch_calls = Arc::new(AtomicU32::new(0));
1424        let catch_calls_child = Arc::clone(&catch_calls);
1425
1426        let step = BuilderStep::DoTry {
1427            try_steps: vec![BuilderStep::Processor(OpaqueProcessor(
1428                BoxProcessor::from_fn(|_ex| {
1429                    Box::pin(async move { Err(CamelError::ProcessorError("boom".into())) })
1430                }),
1431            ))],
1432            catches: vec![DoTryCatchClause {
1433                matcher: CatchMatcher::ByVariant(vec!["ProcessorError".into()]),
1434                on_when: None,
1435                disposition: ExceptionDisposition::Handled,
1436                steps: vec![BuilderStep::Processor(OpaqueProcessor(
1437                    BoxProcessor::from_fn(move |ex| {
1438                        catch_calls_child.fetch_add(1, Ordering::SeqCst);
1439                        Box::pin(async move { Ok(ex) })
1440                    }),
1441                ))],
1442            }],
1443            finally: None,
1444        };
1445
1446        let pc = ProducerContext::default();
1447        let rt: Arc<dyn RuntimeObservability> = Arc::new(NoopRuntimeObservability);
1448        let languages: SharedLanguageRegistry = Arc::new(Mutex::new(HashMap::new()));
1449        let beans: Arc<Mutex<BeanRegistry>> = Arc::new(Mutex::new(BeanRegistry::new()));
1450        let component_ctx: Arc<dyn ComponentContext> = Arc::new(NoOpComponentContext);
1451        let staging = FunctionStagingMode::DirectAdd;
1452        let idempotent_repositories = crate::IdempotentRegistry::new();
1453        let claim_check_repositories = crate::ClaimCheckRegistry::new();
1454        let cache_repositories = crate::CacheRegistry::new();
1455        let context = ctx(
1456            &pc,
1457            rt,
1458            &languages,
1459            &beans,
1460            component_ctx,
1461            &staging,
1462            &idempotent_repositories,
1463            &claim_check_repositories,
1464            &cache_repositories,
1465        );
1466
1467        let reg = dotry_registry();
1468        let compiled = reg
1469            .compile_step(step, 0, &context)
1470            .expect("compilation should succeed")
1471            .expect("DoTry should match");
1472
1473        let mut segment = match compiled {
1474            CompiledStep::Segment { segment, .. } => segment,
1475            other => panic!("expected CompiledStep::Segment, got {other:?}"),
1476        };
1477        let outcome = segment.run(camel_api::Exchange::default()).await;
1478        assert!(
1479            matches!(outcome, PipelineOutcome::Completed(_)),
1480            "handled catch should complete, got {outcome:?}"
1481        );
1482        assert_eq!(
1483            catch_calls.load(Ordering::SeqCst),
1484            1,
1485            "catch body must run once"
1486        );
1487    }
1488
1489    #[tokio::test]
1490    async fn stop_inside_try_skips_remaining_try_steps() {
1491        use std::sync::atomic::{AtomicU32, Ordering};
1492
1493        use camel_api::error_handler::ExceptionDisposition;
1494        use camel_api::{CAMEL_STOP, OpaqueProcessor, PipelineOutcome, Value};
1495        use camel_processor::CatchMatcher;
1496
1497        use crate::lifecycle::application::route_definition::{
1498            DoTryCatchClause, DoTryFinallyClause,
1499        };
1500
1501        let after_stop_calls = Arc::new(AtomicU32::new(0));
1502        let after_stop_calls_child = Arc::clone(&after_stop_calls);
1503        let catch_calls = Arc::new(AtomicU32::new(0));
1504        let catch_calls_child = Arc::clone(&catch_calls);
1505        let finally_calls = Arc::new(AtomicU32::new(0));
1506        let finally_calls_child = Arc::clone(&finally_calls);
1507
1508        let step = BuilderStep::DoTry {
1509            try_steps: vec![
1510                BuilderStep::Processor(OpaqueProcessor(BoxProcessor::from_fn(|ex| {
1511                    Box::pin(async move {
1512                        let mut ex = ex;
1513                        ex.set_property(CAMEL_STOP, Value::Bool(true));
1514                        Ok(ex)
1515                    })
1516                }))),
1517                BuilderStep::Processor(OpaqueProcessor(BoxProcessor::from_fn(move |ex| {
1518                    after_stop_calls_child.fetch_add(1, Ordering::SeqCst);
1519                    Box::pin(async move { Ok(ex) })
1520                }))),
1521            ],
1522            catches: vec![DoTryCatchClause {
1523                matcher: CatchMatcher::ByVariant(vec!["*".into()]),
1524                on_when: None,
1525                disposition: ExceptionDisposition::Handled,
1526                steps: vec![BuilderStep::Processor(OpaqueProcessor(
1527                    BoxProcessor::from_fn(move |ex| {
1528                        catch_calls_child.fetch_add(1, Ordering::SeqCst);
1529                        Box::pin(async move { Ok(ex) })
1530                    }),
1531                ))],
1532            }],
1533            finally: Some(DoTryFinallyClause {
1534                on_when: None,
1535                steps: vec![BuilderStep::Processor(OpaqueProcessor(
1536                    BoxProcessor::from_fn(move |ex| {
1537                        finally_calls_child.fetch_add(1, Ordering::SeqCst);
1538                        Box::pin(async move { Ok(ex) })
1539                    }),
1540                ))],
1541            }),
1542        };
1543
1544        let pc = ProducerContext::default();
1545        let rt: Arc<dyn RuntimeObservability> = Arc::new(NoopRuntimeObservability);
1546        let languages: SharedLanguageRegistry = Arc::new(Mutex::new(HashMap::new()));
1547        let beans: Arc<Mutex<BeanRegistry>> = Arc::new(Mutex::new(BeanRegistry::new()));
1548        let component_ctx: Arc<dyn ComponentContext> = Arc::new(NoOpComponentContext);
1549        let staging = FunctionStagingMode::DirectAdd;
1550        let idempotent_repositories = crate::IdempotentRegistry::new();
1551        let claim_check_repositories = crate::ClaimCheckRegistry::new();
1552        let cache_repositories = crate::CacheRegistry::new();
1553        let context = ctx(
1554            &pc,
1555            rt,
1556            &languages,
1557            &beans,
1558            component_ctx,
1559            &staging,
1560            &idempotent_repositories,
1561            &claim_check_repositories,
1562            &cache_repositories,
1563        );
1564
1565        let reg = dotry_registry();
1566        let compiled = reg
1567            .compile_step(step, 0, &context)
1568            .expect("compilation should succeed")
1569            .expect("DoTry should match");
1570
1571        let mut segment = match compiled {
1572            CompiledStep::Segment { segment, .. } => segment,
1573            other => panic!("expected CompiledStep::Segment, got {other:?}"),
1574        };
1575        let outcome = segment.run(camel_api::Exchange::default()).await;
1576        assert!(
1577            matches!(outcome, PipelineOutcome::Stopped(_)),
1578            "CamelStop marker inside try must propagate Stopped, got {outcome:?}"
1579        );
1580        assert_eq!(
1581            after_stop_calls.load(Ordering::SeqCst),
1582            0,
1583            "remaining try steps must not run after CamelStop marker"
1584        );
1585        assert_eq!(
1586            catch_calls.load(Ordering::SeqCst),
1587            0,
1588            "catch must not run when try stops"
1589        );
1590        assert_eq!(
1591            finally_calls.load(Ordering::SeqCst),
1592            0,
1593            "finally must not run when try stops"
1594        );
1595    }
1596}
1597
1598#[cfg(test)]
1599mod transacted_lowering_tests {
1600    use std::collections::HashMap;
1601    use std::sync::Mutex;
1602
1603    use camel_bean::BeanRegistry;
1604    use camel_component_api::NoOpComponentContext;
1605    use camel_component_api::test_support::NoopRuntimeObservability;
1606
1607    use super::*;
1608    use crate::lifecycle::adapters::route_controller::SharedLanguageRegistry;
1609    use crate::lifecycle::adapters::step_resolution::FunctionStagingMode;
1610
1611    fn dummy_context<'a>(
1612        producer_ctx: &'a ProducerContext,
1613        languages: &'a SharedLanguageRegistry,
1614        beans: &'a Arc<std::sync::Mutex<BeanRegistry>>,
1615        staging: &'a FunctionStagingMode,
1616        idempotent: &'a crate::IdempotentRegistry,
1617        claim_check: &'a crate::ClaimCheckRegistry,
1618        cache: &'a crate::CacheRegistry,
1619    ) -> CompilationContext<'a> {
1620        CompilationContext {
1621            producer_ctx,
1622            rt: Arc::new(NoopRuntimeObservability),
1623            languages,
1624            beans,
1625            function_invoker: None,
1626            component_ctx: Arc::new(NoOpComponentContext),
1627            route_id: None,
1628            staging_mode: staging,
1629            idempotent_repositories: idempotent,
1630            claim_check_repositories: claim_check,
1631            cache_repositories: cache,
1632            intercept: crate::intercept::InterceptRules::default(),
1633        }
1634    }
1635
1636    /// Dark slice: a `Transacted` block with a REGISTERED manager still has no
1637    /// block session at lowering, so the route-add backstop fails closed with
1638    /// the frozen typed join error naming the block datasource — never skip
1639    /// the block and never panic. (The load walk resolves the manager; the
1640    /// session is the executor slice's job.)
1641    #[test]
1642    fn registered_manager_dark_gate_no_block_compiles() {
1643        let producer_ctx = ProducerContext::default();
1644        let languages: SharedLanguageRegistry = Arc::new(Mutex::new(HashMap::new()));
1645        let beans = Arc::new(Mutex::new(BeanRegistry::new()));
1646        let staging = FunctionStagingMode::DirectAdd;
1647        let idempotent = crate::IdempotentRegistry::new();
1648        let claim_check = crate::ClaimCheckRegistry::new();
1649        let cache = crate::CacheRegistry::new();
1650        let ctx = dummy_context(
1651            &producer_ctx,
1652            &languages,
1653            &beans,
1654            &staging,
1655            &idempotent,
1656            &claim_check,
1657            &cache,
1658        );
1659
1660        let err = build_registry()
1661            .compile_step(
1662                BuilderStep::Transacted {
1663                    datasource: "pg".into(),
1664                    steps: vec![BuilderStep::To("sql:select 1?datasource=pg".into())],
1665                },
1666                0,
1667                &ctx,
1668            )
1669            .expect_err("a transacted block must not compile without a block session");
1670
1671        match err {
1672            CamelError::Transaction(camel_api::TransactionError::JoinSessionMissing {
1673                datasource,
1674            }) => {
1675                assert_eq!(datasource, "pg");
1676            }
1677            other => panic!("expected Transaction::JoinSessionMissing, got {other:?}"),
1678        }
1679    }
1680}