1use 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#[derive(Debug, Clone)]
47pub enum CompiledStep {
48 Process {
49 processor: BoxProcessor,
50 body_contract: Option<BodyType>,
51 lifecycle: Option<Arc<dyn StepLifecycle>>,
54 label: Option<Arc<str>>,
60 kind_hint: SpanKindHint,
66 to_uri: Option<Arc<str>>,
74 },
75 Stop,
78 Segment {
82 segment: camel_api::OutcomeSegment,
83 body_contract: Option<BodyType>,
84 lifecycle: Option<Vec<Arc<dyn StepLifecycle>>>,
89 label: Option<Arc<str>>,
92 },
93}
94
95impl CompiledStep {
96 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 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 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
132pub(crate) enum CompileOutcome {
139 Matched(CompiledStep),
140 NotHandled(BuilderStep),
141}
142
143pub(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
159pub(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 pub idempotent_repositories: &'a IdempotentRegistry,
172 pub claim_check_repositories: &'a ClaimCheckRegistry,
175 pub cache_repositories: &'a CacheRegistry,
179 pub intercept: InterceptRules,
182}
183
184impl<'a> CompilationContext<'a> {
185 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 #[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
267pub(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 pub fn compile_step(
288 &self,
289 step: BuilderStep,
290 step_index: usize,
291 ctx: &CompilationContext,
292 ) -> Result<Option<CompiledStep>, CamelError> {
293 if let BuilderStep::Transacted { datasource, .. } = &step {
301 return Err(CamelError::Transaction(
302 camel_api::TransactionError::JoinSessionMissing {
303 datasource: datasource.clone(),
304 },
305 ));
306 }
307 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 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
350pub(super) struct ResolvedSend {
353 pub producer: BoxProcessor,
354 pub body_contract: Option<BodyType>,
355 pub lifecycle: Option<Arc<dyn StepLifecycle>>,
356}
357
358pub(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 let lifecycle: Option<Arc<dyn StepLifecycle>> = endpoint.lifecycle();
378 Ok(ResolvedSend {
379 producer,
380 body_contract,
381 lifecycle,
382 })
383}
384
385pub(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
397pub(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
409pub(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
421pub(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 } 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 #[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 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 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 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 #[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 #[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 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 #[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 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 #[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 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 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 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 #[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 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 #[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]
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 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 #[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 #[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 #[test]
1147 fn set_kind_hint_noop_on_stop_and_segment() {
1148 use camel_api::SpanKindHint;
1149
1150 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 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 #[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 #[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 #[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]
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 let mut reg = StepCompilerRegistry::new();
1342 reg.register(Box::new(ToStopCompiler));
1343
1344 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]
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 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 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 #[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}