camel-core 0.24.0

Core engine for rust-camel
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
//! StepCompiler registry pattern — extract from step_resolution.rs
//!
//! Each compiler group is responsible for matching specific `BuilderStep` variants.
//! The registry dispatches each step to compilers in registration order; the first
//! compiler that returns `Matched` wins. Compilers that don't handle a variant
//! return `NotHandled(step)` to pass it to the next compiler.

use std::sync::Arc;

use camel_api::{
    BodyType, BoxProcessor, CamelError, FunctionInvoker, ProducerContext, StepLifecycle,
};
use camel_component_api::{ComponentContext, RuntimeObservability};
use camel_endpoint::parse_uri;

use crate::lifecycle::adapters::route_controller::SharedLanguageRegistry;
use crate::lifecycle::adapters::step_resolution::FunctionStagingMode;
use crate::lifecycle::application::route_definition::BuilderStep;
use crate::{ClaimCheckRegistry, IdempotentRegistry};
use camel_bean::BeanRegistry;

mod control_flow;
mod core;
mod endpoints;
mod error_handling;
mod routing;
mod splitting;
mod transforms;

/// A compiled pipeline step.
///
/// `Process` is the normal case: a boxed processor plus its optional body
/// contract. `Stop` (added in Task 3b) is the Stop EIP marker — `run_steps`
/// recognises it and produces `PipelineOutcome::Stopped` without invoking a
/// Tower service. `Segment` (added in Task 3) wraps an `OutcomeSegment` for
/// structural EIPs with outcome-aware sub-pipelines.
///
/// **Boundary:** `CompiledStep` is the compile-time representation. At runtime,
/// `run_steps` consumes a `Vec<CompiledStep>` (Stop variants included) and
/// produces a `PipelineOutcome`; the wrapping `Service<Exchange>` impl
/// translates `PipelineOutcome` back to `Result<Exchange, CamelError>`. See
/// ADR-0024.
#[derive(Debug, Clone)]
pub enum CompiledStep {
    Process {
        processor: BoxProcessor,
        body_contract: Option<BodyType>,
        /// Lifecycle handle for this processor, if it is stateful.
        /// `None` for stateless processors (the common case).
        lifecycle: Option<Arc<dyn StepLifecycle>>,
    },
    /// Stop EIP marker. `run_steps` produces `PipelineOutcome::Stopped(ex)`
    /// without invoking a Tower service. Replaces `StopService` (Task 7).
    Stop,
    /// Outcome-aware structural EIP segment. `run_steps` invokes
    /// `segment.run(ex)` and matches on the returned `PipelineOutcome`.
    /// See ADR-0025.
    Segment {
        segment: camel_api::OutcomeSegment,
        body_contract: Option<BodyType>,
        /// Lifecycle handles from children nested inside this segment.
        /// `Option<Vec<...>>` (not `Option<Arc<...>>`) so multiple stateful
        /// children (e.g. Idempotent+Resequencer inside Filter) each
        /// register independently.
        lifecycle: Option<Vec<Arc<dyn StepLifecycle>>>,
    },
}

/// Result from a compiler: either it handled the step, or it did not recognize
/// the variant and returns the step for the next compiler.
///
/// `Result` is intentionally outside this enum (returned by `StepCompiler::compile`)
/// so that compiler arms can use the `?` operator for propagated errors instead of
/// wrapping every `Err` in `Matched(Err(e))`.
pub(crate) enum CompileOutcome {
    Matched(CompiledStep),
    NotHandled(BuilderStep),
}

/// A compiler that can handle one or more `BuilderStep` variants.
///
/// The `compile` method receives ownership of the step. If the compiler recognizes
/// the variant it returns `Ok(CompileOutcome::Matched(...))`. Otherwise it returns
/// `Ok(CompileOutcome::NotHandled(step))` to pass the step to the next compiler.
/// Compilation errors are returned as `Err(CamelError)`.
pub(crate) trait StepCompiler: Send + Sync {
    fn compile(
        &self,
        step: BuilderStep,
        step_index: usize,
        ctx: &CompilationContext,
        registry: &StepCompilerRegistry,
    ) -> Result<CompileOutcome, CamelError>;
}

/// Shared context passed to every compiler invocation.
pub(crate) struct CompilationContext<'a> {
    pub producer_ctx: &'a ProducerContext,
    pub rt: Arc<dyn RuntimeObservability>,
    pub languages: &'a SharedLanguageRegistry,
    pub beans: &'a Arc<std::sync::Mutex<BeanRegistry>>,
    pub function_invoker: Option<Arc<dyn FunctionInvoker>>,
    pub component_ctx: Arc<dyn ComponentContext>,
    pub route_id: Option<&'a str>,
    pub staging_mode: &'a FunctionStagingMode,
    /// Idempotent repository registry. Used by the `IdempotentConsumer`
    /// compiler arm to resolve repository names into `Arc<dyn IdempotentRepository>`.
    pub idempotent_repositories: &'a IdempotentRegistry,
    /// Claim check repository registry. Used by the `ClaimCheck` compiler arm
    /// to resolve repository names into `Arc<dyn ClaimCheckRepository>`.
    pub claim_check_repositories: &'a ClaimCheckRegistry,
}

impl<'a> CompilationContext<'a> {
    /// Recursively compile child steps. Used by compilers that have sub-pipelines
    /// (Filter, Choice, Split, Loop, etc.).
    pub fn compile_children(
        &self,
        steps: Vec<BuilderStep>,
        registry: &StepCompilerRegistry,
    ) -> Result<Vec<CompiledStep>, CamelError> {
        registry.compile_steps(steps, self)
    }

    /// Recursively compile child steps and map them into outcome-aware segments.
    ///
    /// Each `CompiledStep` variant is converted to a `Box<dyn OutcomePipeline>`:
    /// - `Process` → `BoxProcessorSegment`, optionally wrapped in `BodyCoercingSegment`
    /// - `Stop` → `StopSegment` (produces `PipelineOutcome::Stopped(ex)`)
    /// - `Segment` → its inner `OutcomeSegment` (which now implements OutcomePipeline)
    ///
    /// This replaces the 22-line duplicated closure in Filter/DeclarativeFilter
    /// (and will prevent 14+ more duplicates in T9–T16).
    #[allow(clippy::type_complexity)]
    pub fn compile_children_segments(
        &self,
        steps: Vec<BuilderStep>,
        registry: &StepCompilerRegistry,
    ) -> Result<
        (
            Vec<Box<dyn camel_api::OutcomePipeline>>,
            Vec<Arc<dyn camel_api::StepLifecycle>>,
        ),
        CamelError,
    > {
        let pairs = self.compile_children(steps, registry)?;
        let mut lifecycle_handles: Vec<Arc<dyn camel_api::StepLifecycle>> = Vec::new();
        let segments: Vec<Box<dyn camel_api::OutcomePipeline>> = pairs
            .into_iter()
            .map(|c| match c {
                CompiledStep::Process {
                    processor,
                    body_contract,
                    lifecycle,
                } => {
                    if let Some(lc) = lifecycle {
                        lifecycle_handles.push(lc);
                    }
                    let inner: Box<dyn camel_api::OutcomePipeline> = Box::new(
                        crate::lifecycle::adapters::route_compiler::BoxProcessorSegment::new(
                            processor,
                        ),
                    );
                    match body_contract {
                        Some(contract) => Box::new(
                            crate::lifecycle::adapters::route_compiler::BodyCoercingSegment::new(
                                inner, contract,
                            ),
                        ),
                        None => inner,
                    }
                }
                CompiledStep::Stop => {
                    Box::new(crate::lifecycle::adapters::route_compiler::StopSegment)
                        as Box<dyn camel_api::OutcomePipeline>
                }
                CompiledStep::Segment {
                    segment,
                    body_contract: _,
                    lifecycle,
                } => {
                    if let Some(lcs) = lifecycle {
                        lifecycle_handles.extend(lcs);
                    }
                    Box::new(segment)
                }
            })
            .collect();
        Ok((segments, lifecycle_handles))
    }
}

/// Registry of step compilers. Steps are dispatched to compilers in registration
/// order. The first matching compiler handles the step.
pub(crate) struct StepCompilerRegistry {
    compilers: Vec<Box<dyn StepCompiler>>,
}

impl StepCompilerRegistry {
    pub fn new() -> Self {
        Self {
            compilers: Vec::new(),
        }
    }

    pub fn register(&mut self, compiler: Box<dyn StepCompiler>) {
        self.compilers.push(compiler);
    }

    /// Try each compiler in order. The first to return `Matched` wins.
    /// If all return `NotHandled`, returns `Ok(None)`. Compilation errors
    /// short-circuit and return `Err(CamelError)`.
    pub fn compile_step(
        &self,
        step: BuilderStep,
        step_index: usize,
        ctx: &CompilationContext,
    ) -> Result<Option<CompiledStep>, CamelError> {
        let mut step = step;
        for compiler in &self.compilers {
            match compiler.compile(step, step_index, ctx, self)? {
                CompileOutcome::Matched(s) => return Ok(Some(s)),
                CompileOutcome::NotHandled(s) => step = s,
            }
        }
        Ok(None)
    }

    /// Compile all steps in a vector.
    pub fn compile_steps(
        &self,
        steps: Vec<BuilderStep>,
        ctx: &CompilationContext,
    ) -> Result<Vec<CompiledStep>, CamelError> {
        let mut out = Vec::with_capacity(steps.len());
        for (i, step) in steps.into_iter().enumerate() {
            match self.compile_step(step, i, ctx)? {
                Some(c) => out.push(c),
                None => {
                    return Err(CamelError::RouteError(
                        "no compiler registered for step variant".into(),
                    ));
                }
            }
        }
        Ok(out)
    }
}

/// Parse a URI and create a producer, reusing `component_ctx`, `rt`, and `producer_ctx`
/// from the compilation context.
pub(crate) fn resolve_producer(
    ctx: &CompilationContext,
    uri: &str,
) -> Result<BoxProcessor, CamelError> {
    let parsed = parse_uri(uri)?;
    let component = ctx
        .component_ctx
        .resolve_component(&parsed.scheme)
        .ok_or_else(|| CamelError::ComponentNotFound(parsed.scheme.clone()))?;
    let endpoint = component.create_endpoint(uri, ctx.component_ctx.as_ref())?;
    endpoint.create_producer(Arc::clone(&ctx.rt), ctx.producer_ctx)
}

/// Pack a lifecycle Vec into `None` when empty, `Some` when non-empty.
/// Preserves the invariant that `Some` always implies ≥1 handle.
pub(super) fn pack_lifecycles(
    lifecycles: Vec<Arc<dyn StepLifecycle>>,
) -> Option<Vec<Arc<dyn StepLifecycle>>> {
    if lifecycles.is_empty() {
        None
    } else {
        Some(lifecycles)
    }
}

/// Build the full registry with all compiler groups.
pub(crate) fn build_registry() -> StepCompilerRegistry {
    let mut reg = StepCompilerRegistry::new();
    reg.register(Box::new(core::CoreCompiler));
    reg.register(Box::new(endpoints::EndpointsCompiler));
    reg.register(Box::new(transforms::TransformsCompiler));
    reg.register(Box::new(routing::RoutingCompiler));
    reg.register(Box::new(control_flow::ControlFlowCompiler));
    reg.register(Box::new(splitting::SplittingCompiler));
    reg.register(Box::new(error_handling::ErrorHandlingCompiler));
    reg
}

#[cfg(test)]
mod segment_tests {
    use super::*;
    use camel_api::{Exchange, OutcomePipeline, PipelineOutcome};
    use std::future::Future;
    use std::pin::Pin;

    #[derive(Clone)]
    struct EchoSegment;

    impl OutcomePipeline for EchoSegment {
        fn clone_box(&self) -> Box<dyn OutcomePipeline> {
            Box::new(EchoSegment)
        }
        fn run<'a>(
            &'a mut self,
            exchange: Exchange,
        ) -> Pin<Box<dyn Future<Output = PipelineOutcome> + Send + 'a>> {
            Box::pin(async move { PipelineOutcome::Completed(exchange) })
        }
    }

    #[test]
    fn compiled_step_segment_clone_compiles() {
        let seg = camel_api::OutcomeSegment::new(Box::new(EchoSegment));
        let step = CompiledStep::Segment {
            segment: seg,
            body_contract: None,
            lifecycle: None,
        };
        let _cloned = step.clone();
        if let CompiledStep::Segment { segment: _, .. } = _cloned {
            // ok
        } else {
            panic!("clone should preserve variant");
        }
    }

    #[test]
    fn compiled_step_segment_debug_renders() {
        let seg = camel_api::OutcomeSegment::new(Box::new(EchoSegment));
        let step = CompiledStep::Segment {
            segment: seg,
            body_contract: None,
            lifecycle: None,
        };
        let s = format!("{:?}", step);
        assert!(
            s.contains("Segment"),
            "debug should mention Segment variant: {s}"
        );
    }

    #[test]
    fn outcome_segment_satisfies_clone_send_static() {
        fn assert_traits<T: Clone + Send + 'static>() {}
        assert_traits::<camel_api::OutcomeSegment>();
    }

    #[tokio::test]
    #[allow(clippy::arc_with_non_send_sync)]
    async fn outcome_segment_survives_arcswap_swap() {
        use arc_swap::ArcSwap;
        use camel_api::{Exchange, Message, OutcomePipeline, PipelineOutcome};
        use std::sync::Arc;

        #[derive(Clone)]
        struct EchoSegment;
        impl OutcomePipeline for EchoSegment {
            fn clone_box(&self) -> Box<dyn OutcomePipeline> {
                Box::new(EchoSegment)
            }
            fn run<'a>(
                &'a mut self,
                ex: Exchange,
            ) -> std::pin::Pin<Box<dyn std::future::Future<Output = PipelineOutcome> + Send + 'a>>
            {
                Box::pin(async move { PipelineOutcome::Completed(ex) })
            }
        }

        let seg = camel_api::OutcomeSegment::new(Box::new(EchoSegment));
        let slot: ArcSwap<Option<camel_api::OutcomeSegment>> = ArcSwap::from_pointee(None);
        slot.store(Arc::new(Some(seg.clone())));
        slot.store(Arc::new(Some(seg)));

        let mut borrowed = slot.load().as_ref().clone().unwrap();
        let outcome = borrowed.run(Exchange::new(Message::new("ping"))).await;
        assert!(matches!(outcome, PipelineOutcome::Completed(_)));
    }

    /// Test lifecycle handle used by compile_children_segments_bubbles_child_lifecycle.
    #[derive(Debug)]
    struct TestLifecycle;

    #[async_trait::async_trait]
    impl camel_api::StepLifecycle for TestLifecycle {
        fn name(&self) -> &'static str {
            "test-lifecycle"
        }
        async fn shutdown(
            &self,
            _reason: camel_api::StepShutdownReason,
        ) -> Result<(), camel_api::CamelError> {
            Ok(())
        }
    }

    /// Custom compiler that injects a lifecycle handle into every
    /// `BuilderStep::Processor` it compiles.
    struct LifecycleInjectorCompiler {
        handle: Arc<dyn camel_api::StepLifecycle>,
    }

    impl StepCompiler for LifecycleInjectorCompiler {
        fn compile(
            &self,
            step: BuilderStep,
            _step_index: usize,
            _ctx: &CompilationContext,
            _registry: &StepCompilerRegistry,
        ) -> Result<CompileOutcome, CamelError> {
            match step {
                BuilderStep::Processor(op) => Ok(CompileOutcome::Matched(CompiledStep::Process {
                    processor: op.0,
                    body_contract: None,
                    lifecycle: Some(self.handle.clone()),
                })),
                other => Ok(CompileOutcome::NotHandled(other)),
            }
        }
    }

    #[tokio::test]
    async fn compile_children_segments_bubbles_child_lifecycle() {
        use std::collections::HashMap;
        use std::sync::Mutex;

        use camel_api::{
            BoxProcessor, BoxProcessorExt, FilterPredicate, OpaqueProcessor, StepLifecycle,
        };
        use camel_bean::BeanRegistry;
        use camel_component_api::{
            ComponentContext, NoOpComponentContext, RuntimeObservability,
            test_support::NoopRuntimeObservability,
        };

        use crate::lifecycle::adapters::step_resolution::FunctionStagingMode;

        let handle: Arc<dyn StepLifecycle> = Arc::new(TestLifecycle);

        // Register lifecycle injector + real control-flow compiler so
        // compile_children_segments runs through a structural EIP path.
        let mut reg = StepCompilerRegistry::new();
        reg.register(Box::new(LifecycleInjectorCompiler {
            handle: handle.clone(),
        }));
        reg.register(Box::new(super::control_flow::ControlFlowCompiler));

        let pc = ProducerContext::default();
        let rt: Arc<dyn RuntimeObservability> = Arc::new(NoopRuntimeObservability);
        let languages: SharedLanguageRegistry = Arc::new(Mutex::new(HashMap::new()));
        let beans: Arc<Mutex<BeanRegistry>> = Arc::new(Mutex::new(BeanRegistry::new()));
        let component_ctx: Arc<dyn ComponentContext> = Arc::new(NoOpComponentContext);
        let staging = FunctionStagingMode::DirectAdd;
        let idempotent_repositories = crate::IdempotentRegistry::new();
        let claim_check_repositories = crate::ClaimCheckRegistry::new();

        let ctx = CompilationContext {
            producer_ctx: &pc,
            rt,
            languages: &languages,
            beans: &beans,
            function_invoker: None,
            component_ctx,
            route_id: None,
            staging_mode: &staging,
            idempotent_repositories: &idempotent_repositories,
            claim_check_repositories: &claim_check_repositories,
        };

        // Compile a Filter with a child Processor step.
        let filter_step = BuilderStep::Filter {
            predicate: FilterPredicate::new(|_| true),
            steps: vec![BuilderStep::Processor(OpaqueProcessor(
                BoxProcessor::from_fn(|ex| Box::pin(async move { Ok(ex) })),
            ))],
        };

        let result = reg.compile_step(filter_step, 0, &ctx);
        let compiled = result
            .expect("compilation should succeed")
            .expect("should match");

        match compiled {
            CompiledStep::Segment {
                lifecycle,
                body_contract,
                ..
            } => {
                assert_eq!(body_contract, None, "body_contract should be None");
                let handles = lifecycle.expect("Segment should have lifecycle handles");
                assert_eq!(handles.len(), 1, "expected 1 lifecycle handle");
                assert_eq!(handles[0].name(), "test-lifecycle", "handle name mismatch");
            }
            other => panic!("Expected CompiledStep::Segment, got {other:?}"),
        }
    }

    /// A lifecycle handle with a configurable name for multi-handle tests.
    #[derive(Debug)]
    struct NamedLifecycle(&'static str);

    #[async_trait::async_trait]
    impl camel_api::StepLifecycle for NamedLifecycle {
        fn name(&self) -> &'static str {
            self.0
        }
        async fn shutdown(
            &self,
            _reason: camel_api::StepShutdownReason,
        ) -> Result<(), camel_api::CamelError> {
            Ok(())
        }
    }

    /// Test A: Multiple stateful children in one Segment → Vec length 2.
    #[tokio::test]
    async fn compile_children_segments_multiple_stateful_children() {
        use std::collections::HashMap;
        use std::sync::Mutex;

        use crate::lifecycle::adapters::step_resolution::FunctionStagingMode;
        use camel_api::{
            BoxProcessor, BoxProcessorExt, FilterPredicate, OpaqueProcessor, StepLifecycle,
        };
        use camel_bean::BeanRegistry;
        use camel_component_api::{
            ComponentContext, NoOpComponentContext, RuntimeObservability,
            test_support::NoopRuntimeObservability,
        };

        let handle: Arc<dyn StepLifecycle> = Arc::new(NamedLifecycle("multi"));

        let mut reg = StepCompilerRegistry::new();
        reg.register(Box::new(LifecycleInjectorCompiler {
            handle: handle.clone(),
        }));
        reg.register(Box::new(super::control_flow::ControlFlowCompiler));

        let pc = ProducerContext::default();
        let rt: Arc<dyn RuntimeObservability> = Arc::new(NoopRuntimeObservability);
        let languages: SharedLanguageRegistry = Arc::new(Mutex::new(HashMap::new()));
        let beans: Arc<Mutex<BeanRegistry>> = Arc::new(Mutex::new(BeanRegistry::new()));
        let component_ctx: Arc<dyn ComponentContext> = Arc::new(NoOpComponentContext);
        let staging = FunctionStagingMode::DirectAdd;
        let idempotent_repositories = crate::IdempotentRegistry::new();
        let claim_check_repositories = crate::ClaimCheckRegistry::new();

        let ctx = CompilationContext {
            producer_ctx: &pc,
            rt,
            languages: &languages,
            beans: &beans,
            function_invoker: None,
            component_ctx,
            route_id: None,
            staging_mode: &staging,
            idempotent_repositories: &idempotent_repositories,
            claim_check_repositories: &claim_check_repositories,
        };

        // Filter with TWO child Processors → both get the same lifecycle handle.
        let filter_step = BuilderStep::Filter {
            predicate: FilterPredicate::new(|_| true),
            steps: vec![
                BuilderStep::Processor(OpaqueProcessor(BoxProcessor::from_fn(|ex| {
                    Box::pin(async move { Ok(ex) })
                }))),
                BuilderStep::Processor(OpaqueProcessor(BoxProcessor::from_fn(|ex| {
                    Box::pin(async move { Ok(ex) })
                }))),
            ],
        };

        let result = reg.compile_step(filter_step, 0, &ctx);
        let compiled = result
            .expect("compilation should succeed")
            .expect("should match");

        match compiled {
            CompiledStep::Segment { lifecycle, .. } => {
                let handles = lifecycle.expect("Segment should have lifecycle handles");
                assert_eq!(
                    handles.len(),
                    2,
                    "expected 2 lifecycle handles for 2 children"
                );
                for h in &handles {
                    assert_eq!(h.name(), "multi", "all handles should be 'multi'");
                }
            }
            other => panic!("Expected CompiledStep::Segment, got {other:?}"),
        }
    }

    /// Test B: Multi-branch accumulation across Choice when-clauses.
    #[tokio::test]
    async fn compile_children_segments_multi_branch_accumulation() {
        use std::collections::HashMap;
        use std::sync::Mutex;

        use crate::lifecycle::adapters::step_resolution::FunctionStagingMode;
        use crate::lifecycle::application::route_definition::WhenStep;
        use camel_api::{
            BoxProcessor, BoxProcessorExt, FilterPredicate, OpaqueProcessor, StepLifecycle,
        };
        use camel_bean::BeanRegistry;
        use camel_component_api::{
            ComponentContext, NoOpComponentContext, RuntimeObservability,
            test_support::NoopRuntimeObservability,
        };

        let handle: Arc<dyn StepLifecycle> = Arc::new(NamedLifecycle("branch"));

        let mut reg = StepCompilerRegistry::new();
        reg.register(Box::new(LifecycleInjectorCompiler {
            handle: handle.clone(),
        }));
        reg.register(Box::new(super::control_flow::ControlFlowCompiler));

        let pc = ProducerContext::default();
        let rt: Arc<dyn RuntimeObservability> = Arc::new(NoopRuntimeObservability);
        let languages: SharedLanguageRegistry = Arc::new(Mutex::new(HashMap::new()));
        let beans: Arc<Mutex<BeanRegistry>> = Arc::new(Mutex::new(BeanRegistry::new()));
        let component_ctx: Arc<dyn ComponentContext> = Arc::new(NoOpComponentContext);
        let staging = FunctionStagingMode::DirectAdd;
        let idempotent_repositories = crate::IdempotentRegistry::new();
        let claim_check_repositories = crate::ClaimCheckRegistry::new();

        let ctx = CompilationContext {
            producer_ctx: &pc,
            rt,
            languages: &languages,
            beans: &beans,
            function_invoker: None,
            component_ctx,
            route_id: None,
            staging_mode: &staging,
            idempotent_repositories: &idempotent_repositories,
            claim_check_repositories: &claim_check_repositories,
        };

        // Choice with 2 when branches, each containing 1 stateful child.
        let choice_step = BuilderStep::Choice {
            whens: vec![
                WhenStep {
                    predicate: FilterPredicate::new(|_| true),
                    steps: vec![BuilderStep::Processor(OpaqueProcessor(
                        BoxProcessor::from_fn(|ex| Box::pin(async move { Ok(ex) })),
                    ))],
                },
                WhenStep {
                    predicate: FilterPredicate::new(|_| false),
                    steps: vec![BuilderStep::Processor(OpaqueProcessor(
                        BoxProcessor::from_fn(|ex| Box::pin(async move { Ok(ex) })),
                    ))],
                },
            ],
            otherwise: None,
        };

        let result = reg.compile_step(choice_step, 0, &ctx);
        let compiled = result
            .expect("compilation should succeed")
            .expect("should match");

        match compiled {
            CompiledStep::Segment { lifecycle, .. } => {
                let handles = lifecycle.expect("Segment should have lifecycle handles");
                assert_eq!(
                    handles.len(),
                    2,
                    "expected 2 lifecycle handles from 2 branches"
                );
                for h in &handles {
                    assert_eq!(h.name(), "branch", "all handles should be 'branch'");
                }
            }
            other => panic!("Expected CompiledStep::Segment, got {other:?}"),
        }
    }

    /// Test C: Nested Segment-in-Segment flattening — outer Segment contains
    /// innermost lifecycle handle from a grandchild Processor.
    #[tokio::test]
    async fn compile_children_segments_nested_segment_flattening() {
        use std::collections::HashMap;
        use std::sync::Mutex;

        use crate::lifecycle::adapters::step_resolution::FunctionStagingMode;
        use camel_api::{
            BoxProcessor, BoxProcessorExt, FilterPredicate, OpaqueProcessor, StepLifecycle,
        };
        use camel_bean::BeanRegistry;
        use camel_component_api::{
            ComponentContext, NoOpComponentContext, RuntimeObservability,
            test_support::NoopRuntimeObservability,
        };

        let inner_handle: Arc<dyn StepLifecycle> = Arc::new(NamedLifecycle("deep"));

        let mut reg = StepCompilerRegistry::new();
        reg.register(Box::new(LifecycleInjectorCompiler {
            handle: inner_handle.clone(),
        }));
        reg.register(Box::new(super::control_flow::ControlFlowCompiler));

        let pc = ProducerContext::default();
        let rt: Arc<dyn RuntimeObservability> = Arc::new(NoopRuntimeObservability);
        let languages: SharedLanguageRegistry = Arc::new(Mutex::new(HashMap::new()));
        let beans: Arc<Mutex<BeanRegistry>> = Arc::new(Mutex::new(BeanRegistry::new()));
        let component_ctx: Arc<dyn ComponentContext> = Arc::new(NoOpComponentContext);
        let staging = FunctionStagingMode::DirectAdd;
        let idempotent_repositories = crate::IdempotentRegistry::new();
        let claim_check_repositories = crate::ClaimCheckRegistry::new();

        let ctx = CompilationContext {
            producer_ctx: &pc,
            rt,
            languages: &languages,
            beans: &beans,
            function_invoker: None,
            component_ctx,
            route_id: None,
            staging_mode: &staging,
            idempotent_repositories: &idempotent_repositories,
            claim_check_repositories: &claim_check_repositories,
        };

        // Outer Filter containing an inner Filter that has a stateful Processor.
        // The outer Segment's lifecycle should contain the innermost handle
        // (proves recursive flattening through compile_children_segments).
        let inner_filter = BuilderStep::Filter {
            predicate: FilterPredicate::new(|_| true),
            steps: vec![BuilderStep::Processor(OpaqueProcessor(
                BoxProcessor::from_fn(|ex| Box::pin(async move { Ok(ex) })),
            ))],
        };

        let outer_filter = BuilderStep::Filter {
            predicate: FilterPredicate::new(|_| true),
            steps: vec![inner_filter],
        };

        let result = reg.compile_step(outer_filter, 0, &ctx);
        let compiled = result
            .expect("compilation should succeed")
            .expect("should match");

        match compiled {
            CompiledStep::Segment { lifecycle, .. } => {
                let handles = lifecycle.expect("outer Segment should have lifecycle handles");
                assert_eq!(handles.len(), 1, "expected 1 innermost lifecycle handle");
                assert_eq!(
                    handles[0].name(),
                    "deep",
                    "handle should be from innermost child"
                );
            }
            other => panic!("Expected CompiledStep::Segment, got {other:?}"),
        }
    }
}

#[cfg(test)]
mod dispatch_tests {
    use super::*;
    use crate::lifecycle::adapters::step_resolution::FunctionStagingMode;
    use camel_api::{BoxProcessor, BoxProcessorExt};
    use camel_bean::BeanRegistry;
    use camel_component_api::{
        ComponentContext, NoOpComponentContext, RuntimeObservability,
        test_support::NoopRuntimeObservability,
    };
    use std::collections::HashMap;
    use std::sync::Mutex;

    /// Compiler that handles `BuilderStep::To` → `CompiledStep::Stop`.
    struct ToStopCompiler;

    impl StepCompiler for ToStopCompiler {
        fn compile(
            &self,
            step: BuilderStep,
            _step_index: usize,
            _ctx: &CompilationContext,
            _registry: &StepCompilerRegistry,
        ) -> Result<CompileOutcome, CamelError> {
            match step {
                BuilderStep::To(_) => Ok(CompileOutcome::Matched(CompiledStep::Stop)),
                other => Ok(CompileOutcome::NotHandled(other)),
            }
        }
    }

    /// Compiler that handles `BuilderStep::To` → `CompiledStep::Process`.
    struct ToProcessCompiler;

    impl StepCompiler for ToProcessCompiler {
        fn compile(
            &self,
            step: BuilderStep,
            _step_index: usize,
            _ctx: &CompilationContext,
            _registry: &StepCompilerRegistry,
        ) -> Result<CompileOutcome, CamelError> {
            match step {
                BuilderStep::To(_) => Ok(CompileOutcome::Matched(CompiledStep::Process {
                    processor: BoxProcessor::from_fn(|ex| Box::pin(async move { Ok(ex) })),
                    body_contract: None,
                    lifecycle: None,
                })),
                other => Ok(CompileOutcome::NotHandled(other)),
            }
        }
    }

    /// Compiler that passes all steps through (never handles any variant).
    /// Returns `NotHandled(step)` for every input, proving by-value pass-through.
    struct PassThroughCompiler;

    impl StepCompiler for PassThroughCompiler {
        fn compile(
            &self,
            step: BuilderStep,
            _step_index: usize,
            _ctx: &CompilationContext,
            _registry: &StepCompilerRegistry,
        ) -> Result<CompileOutcome, CamelError> {
            Ok(CompileOutcome::NotHandled(step))
        }
    }

    /// Shared context builder — avoids repeating the 15-line setup in every test.
    #[allow(clippy::too_many_arguments)]
    fn ctx<'a>(
        pc: &'a ProducerContext,
        rt: Arc<dyn RuntimeObservability>,
        languages: &'a SharedLanguageRegistry,
        beans: &'a Arc<Mutex<BeanRegistry>>,
        component_ctx: Arc<dyn ComponentContext>,
        staging: &'a FunctionStagingMode,
        idempotent_repositories: &'a crate::IdempotentRegistry,
        claim_check_repositories: &'a crate::ClaimCheckRegistry,
    ) -> CompilationContext<'a> {
        CompilationContext {
            producer_ctx: pc,
            rt,
            languages,
            beans,
            function_invoker: None,
            component_ctx,
            route_id: None,
            staging_mode: staging,
            idempotent_repositories,
            claim_check_repositories,
        }
    }

    /// Test that the dispatcher respects registration order: the first matching
    /// compiler wins even when a later compiler also matches.
    #[test]
    fn compile_step_preserves_registry_order() {
        let pc = ProducerContext::default();
        let rt: Arc<dyn RuntimeObservability> = Arc::new(NoopRuntimeObservability);
        let languages: SharedLanguageRegistry = Arc::new(Mutex::new(HashMap::new()));
        let beans: Arc<Mutex<BeanRegistry>> = Arc::new(Mutex::new(BeanRegistry::new()));
        let component_ctx: Arc<dyn ComponentContext> = Arc::new(NoOpComponentContext);
        let staging = FunctionStagingMode::DirectAdd;
        let idempotent_repositories = crate::IdempotentRegistry::new();
        let claim_check_repositories = crate::ClaimCheckRegistry::new();

        let context = ctx(
            &pc,
            rt,
            &languages,
            &beans,
            component_ctx,
            &staging,
            &idempotent_repositories,
            &claim_check_repositories,
        );

        // Register ToStopCompiler FIRST, ToProcessCompiler SECOND.
        // Both match BuilderStep::To. The first-registered should win.
        let mut reg = StepCompilerRegistry::new();
        reg.register(Box::new(ToStopCompiler));
        reg.register(Box::new(ToProcessCompiler));

        let result = reg
            .compile_step(BuilderStep::To("test".into()), 0, &context)
            .expect("compilation should succeed")
            .expect("should match");

        assert!(
            matches!(result, CompiledStep::Stop),
            "expected ToStopCompiler (first registered) to win, got {result:?}"
        );
    }

    /// Test that when no compiler handles a variant, the dispatcher returns
    /// `Ok(None)` rather than an error.
    #[test]
    fn compile_step_unhandled_returns_ok_none() {
        let pc = ProducerContext::default();
        let rt: Arc<dyn RuntimeObservability> = Arc::new(NoopRuntimeObservability);
        let languages: SharedLanguageRegistry = Arc::new(Mutex::new(HashMap::new()));
        let beans: Arc<Mutex<BeanRegistry>> = Arc::new(Mutex::new(BeanRegistry::new()));
        let component_ctx: Arc<dyn ComponentContext> = Arc::new(NoOpComponentContext);
        let staging = FunctionStagingMode::DirectAdd;
        let idempotent_repositories = crate::IdempotentRegistry::new();
        let claim_check_repositories = crate::ClaimCheckRegistry::new();

        let context = ctx(
            &pc,
            rt,
            &languages,
            &beans,
            component_ctx,
            &staging,
            &idempotent_repositories,
            &claim_check_repositories,
        );

        // Register a compiler that only handles BuilderStep::To.
        let mut reg = StepCompilerRegistry::new();
        reg.register(Box::new(ToStopCompiler));

        // Send a BuilderStep::Log variant — ToStopCompiler does not match it.
        let result = reg.compile_step(
            BuilderStep::Log {
                level: camel_processor::LogLevel::Info,
                message: "unhandled".into(),
            },
            0,
            &context,
        );

        assert!(
            matches!(result, Ok(None)),
            "expected Ok(None), got {result:?}"
        );
    }

    /// Test that `NotHandled(step)` passes the step by-value to the next
    /// compiler. Compiler N returns `NotHandled(step)` for a variant that
    /// compiler N+1 handles — proving the step is not dropped or replaced.
    #[test]
    fn compile_step_nothandled_passes_step_intact_to_next_compiler() {
        let pc = ProducerContext::default();
        let rt: Arc<dyn RuntimeObservability> = Arc::new(NoopRuntimeObservability);
        let languages: SharedLanguageRegistry = Arc::new(Mutex::new(HashMap::new()));
        let beans: Arc<Mutex<BeanRegistry>> = Arc::new(Mutex::new(BeanRegistry::new()));
        let component_ctx: Arc<dyn ComponentContext> = Arc::new(NoOpComponentContext);
        let staging = FunctionStagingMode::DirectAdd;
        let idempotent_repositories = crate::IdempotentRegistry::new();
        let claim_check_repositories = crate::ClaimCheckRegistry::new();

        let context = ctx(
            &pc,
            rt,
            &languages,
            &beans,
            component_ctx,
            &staging,
            &idempotent_repositories,
            &claim_check_repositories,
        );

        // Register PassThroughCompiler FIRST (never handles anything),
        // ToStopCompiler SECOND (handles BuilderStep::To).
        let mut reg = StepCompilerRegistry::new();
        reg.register(Box::new(PassThroughCompiler));
        reg.register(Box::new(ToStopCompiler));

        let result = reg
            .compile_step(BuilderStep::To("passthrough".into()), 0, &context)
            .expect("compilation should succeed")
            .expect("should match");

        assert!(
            matches!(result, CompiledStep::Stop),
            "expected ToStopCompiler (N+1) to win after pass-through, got {result:?}"
        );
    }
}