1use std::sync::Arc;
5
6use camel_api::UnitOfWorkConfig;
7use camel_api::circuit_breaker::CircuitBreakerConfig;
8use camel_api::error_handler::ErrorHandlerConfig;
9use camel_api::loop_eip::LoopConfig;
10use camel_api::security_policy::SecurityPolicyConfig;
11use camel_api::{
12 AggregatorConfig, FilterPredicate, LayerFactory, MulticastConfig, OpaqueProcessor,
13 ResequencePolicyConfig, SpanKindHint, SplitterConfig,
14};
15use camel_auth::TokenAuthenticator;
16use camel_component_api::ConcurrencyModel;
17
18#[derive(Clone)]
20pub struct WhenStep {
21 pub predicate: FilterPredicate,
22 pub steps: Vec<BuilderStep>,
23}
24
25impl std::fmt::Debug for WhenStep {
26 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
27 f.debug_struct("WhenStep")
28 .field("predicate", &self.predicate)
29 .field("steps", &self.steps)
30 .finish()
31 }
32}
33
34pub use camel_api::declarative::{LanguageExpressionDef, ValueSourceDef};
35
36#[derive(Debug, Clone)]
38pub struct DeclarativeWhenStep {
39 pub predicate: LanguageExpressionDef,
40 pub steps: Vec<BuilderStep>,
41}
42
43#[derive(Debug, Clone)]
45pub struct DoTryCatchClauseBuilder {
46 pub exception: Option<Vec<String>>,
47 pub when: Option<LanguageExpressionDef>,
48 pub code: Option<String>,
50 pub business_kind: Option<String>,
52 pub on_when: Option<LanguageExpressionDef>,
53 pub disposition: camel_api::error_handler::ExceptionDisposition,
54 pub steps: Vec<BuilderStep>,
55}
56
57#[derive(Debug, Clone)]
59pub struct DoTryFinallyBuilder {
60 pub on_when: Option<LanguageExpressionDef>,
61 pub steps: Vec<BuilderStep>,
62}
63
64#[derive(Clone)]
66pub struct DoTryCatchClause {
67 pub matcher: camel_processor::CatchMatcher,
68 pub on_when: Option<camel_api::PredicateSource>,
69 pub disposition: camel_api::error_handler::ExceptionDisposition,
70 pub steps: Vec<BuilderStep>,
71}
72
73impl std::fmt::Debug for DoTryCatchClause {
74 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
75 f.debug_struct("DoTryCatchClause")
76 .field("matcher", &"<compiled>")
77 .field("on_when", &self.on_when.is_some())
78 .field("disposition", &self.disposition)
79 .field("steps", &self.steps)
80 .finish()
81 }
82}
83
84#[derive(Clone)]
86pub struct DoTryFinallyClause {
87 pub on_when: Option<camel_api::PredicateSource>,
88 pub steps: Vec<BuilderStep>,
89}
90
91impl std::fmt::Debug for DoTryFinallyClause {
92 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
93 f.debug_struct("DoTryFinallyClause")
94 .field("on_when", &self.on_when.is_some())
95 .field("steps", &self.steps)
96 .finish()
97 }
98}
99
100#[derive(Clone)]
106pub struct StreamSplitExpression(pub camel_api::StreamingSplitExpression);
107
108impl std::fmt::Debug for StreamSplitExpression {
109 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
110 f.write_str("StreamingSplitExpression(...)")
111 }
112}
113
114impl From<camel_api::StreamingSplitExpression> for StreamSplitExpression {
115 fn from(expression: camel_api::StreamingSplitExpression) -> Self {
116 Self(expression)
117 }
118}
119
120#[derive(Debug, Clone)]
122pub enum BuilderStep {
123 Processor(OpaqueProcessor),
125 To(String),
127 Stop,
129 Log {
131 level: camel_processor::LogLevel,
132 message: String,
133 },
134 DeclarativeSetHeader {
136 key: String,
137 value: ValueSourceDef,
138 },
139 DeclarativeSetHeaderIfAbsent {
141 key: String,
142 value: ValueSourceDef,
143 },
144 DeclarativeThrow {
147 code: String,
149 kind: Option<String>,
151 message: Option<ValueSourceDef>,
153 data: Option<serde_json::Value>,
155 },
156 DeclarativeRemoveHeader {
158 key: String,
159 },
160 DeclarativeSetProperty {
161 key: String,
162 value_source: ValueSourceDef,
163 },
164 DeclarativeSetBody {
166 value: ValueSourceDef,
167 },
168 DeclarativeFilter {
170 predicate: LanguageExpressionDef,
171 steps: Vec<BuilderStep>,
172 },
173 DeclarativeChoice {
175 whens: Vec<DeclarativeWhenStep>,
176 otherwise: Option<Vec<BuilderStep>>,
177 },
178 DeclarativeScript {
181 expression: LanguageExpressionDef,
182 },
183 DeclarativeFunction {
184 definition: camel_api::FunctionDefinition,
185 },
186 DeclarativeSplit {
188 expression: LanguageExpressionDef,
189 aggregation: camel_api::splitter::AggregationStrategy,
190 parallel: bool,
191 parallel_limit: Option<usize>,
192 trace_item_threshold: Option<usize>,
195 stop_on_exception: bool,
196 steps: Vec<BuilderStep>,
197 },
198 DeclarativeStreamSplit {
200 stream_config: camel_api::StreamSplitConfig,
201 aggregation: camel_api::splitter::AggregationStrategy,
202 stop_on_exception: bool,
203 steps: Vec<BuilderStep>,
204 },
205 StreamSplit {
210 expression: StreamSplitExpression,
211 aggregation: camel_api::splitter::AggregationStrategy,
212 stop_on_exception: bool,
213 steps: Vec<BuilderStep>,
214 },
215 DeclarativeDynamicRouter {
216 expression: LanguageExpressionDef,
217 uri_delimiter: String,
218 cache_size: i32,
219 ignore_invalid_endpoints: bool,
220 max_iterations: usize,
221 },
222 DeclarativeRoutingSlip {
223 expression: LanguageExpressionDef,
224 uri_delimiter: String,
225 cache_size: i32,
226 ignore_invalid_endpoints: bool,
227 },
228 Split {
230 config: SplitterConfig,
231 steps: Vec<BuilderStep>,
232 },
233 Aggregate {
235 config: AggregatorConfig,
236 },
237 Filter {
239 predicate: FilterPredicate,
240 steps: Vec<BuilderStep>,
241 },
242 Choice {
245 whens: Vec<WhenStep>,
246 otherwise: Option<Vec<BuilderStep>>,
247 },
248 WireTap {
250 uri: String,
251 },
252 Multicast {
254 steps: Vec<BuilderStep>,
255 config: MulticastConfig,
256 },
257 DeclarativeLog {
259 level: camel_processor::LogLevel,
260 message: ValueSourceDef,
261 },
262 Bean {
264 name: String,
265 method: String,
266 },
267 Script {
270 language: String,
271 script: String,
272 },
273 Throttle {
275 config: camel_api::ThrottlerConfig,
276 steps: Vec<BuilderStep>,
277 },
278 LoadBalance {
280 config: camel_api::LoadBalancerConfig,
281 steps: Vec<BuilderStep>,
282 },
283 DynamicRouter {
285 config: camel_api::DynamicRouterConfig,
286 },
287 RoutingSlip {
288 config: camel_api::RoutingSlipConfig,
289 },
290 RecipientList {
291 config: camel_api::recipient_list::RecipientListConfig,
292 },
293 DeclarativeRecipientList {
294 expression: LanguageExpressionDef,
295 delimiter: String,
296 parallel: bool,
297 parallel_limit: Option<usize>,
298 stop_on_exception: bool,
299 aggregation: String,
300 },
301 Delay {
302 config: camel_api::DelayConfig,
303 },
304 Loop {
306 config: LoopConfig,
307 steps: Vec<BuilderStep>,
308 },
309 DeclarativeLoop {
311 count: Option<usize>,
312 while_predicate: Option<LanguageExpressionDef>,
313 steps: Vec<BuilderStep>,
314 max_iterations: Option<usize>,
315 },
316 Enrich {
318 uri: String,
319 strategy: Option<String>,
320 timeout_ms: Option<u64>,
321 },
322 PollEnrich {
324 uri: String,
325 strategy: Option<String>,
326 timeout_ms: Option<u64>,
327 },
328 Validate {
331 predicate: LanguageExpressionDef,
332 },
333 ClaimCheck {
337 repository: String,
338 operation: String,
339 key: LanguageExpressionDef,
340 filter: Option<String>,
341 },
342 Sampling {
346 period: usize,
347 },
348 Sort {
351 expression: LanguageExpressionDef,
352 reverse: bool,
353 },
354 IdempotentConsumer {
358 repository: String,
359 expression: LanguageExpressionDef,
360 steps: Vec<BuilderStep>,
361 eager: bool,
362 remove_on_failure: bool,
363 on_missing_key: camel_processor::OnMissingKey,
365 },
366 Cache {
370 repository: Option<String>,
371 key: LanguageExpressionDef,
372 ttl: Option<String>,
373 max_entry_bytes: Option<usize>,
374 coalesce_misses: bool,
376 on_miss: Vec<BuilderStep>,
377 },
378 CacheInvalidate {
383 repository: Option<String>,
384 key: Option<LanguageExpressionDef>,
385 key_prefix: Option<LanguageExpressionDef>,
386 },
387 CacheClear {
390 repository: Option<String>,
391 },
392 CacheStats {
395 repository: Option<String>,
396 },
397 CachePeekStale {
400 repository: Option<String>,
401 key: LanguageExpressionDef,
402 on_miss: camel_processor::PeekStaleMissPolicy,
403 },
404 DeclarativeDoTry {
406 try_steps: Vec<BuilderStep>,
407 catch: Vec<DoTryCatchClauseBuilder>,
408 finally: Option<DoTryFinallyBuilder>,
409 },
410 DoTry {
413 try_steps: Vec<BuilderStep>,
414 catches: Vec<DoTryCatchClause>,
415 finally: Option<DoTryFinallyClause>,
416 },
417 Resequence {
420 policy_config: ResequencePolicyConfig,
421 },
422 LayeredTo {
426 uri: String,
429 factory: LayerFactory,
431 },
432 Layered {
434 factory: LayerFactory,
436 steps: Vec<BuilderStep>,
439 },
440 Transacted {
453 datasource: String,
456 steps: Vec<BuilderStep>,
458 },
459}
460
461impl BuilderStep {
462 pub(crate) fn span_label(&self) -> Option<String> {
477 match self {
478 Self::Processor(_) | Self::Stop => None,
480
481 Self::To(uri) => uri.contains(':').then(|| {
482 let scheme = uri.split(':').next().unwrap_or_default();
483 format!("to:{scheme}")
484 }),
485
486 Self::LayeredTo { uri, .. } => uri.contains(':').then(|| {
488 let scheme = uri.split(':').next().unwrap_or_default();
489 format!("to:{scheme}")
490 }),
491
492 Self::Log { .. } | Self::DeclarativeLog { .. } => Some("log".into()),
493
494 Self::DeclarativeSetHeader { .. } => Some("set-header".into()),
495 Self::DeclarativeSetHeaderIfAbsent { .. } => Some("set-header-if-absent".into()),
496 Self::DeclarativeThrow { .. } => Some("throw".into()),
497 Self::DeclarativeRemoveHeader { .. } => Some("remove-header".into()),
498 Self::DeclarativeSetProperty { .. } => Some("set-property".into()),
499 Self::DeclarativeSetBody { .. } => Some("set-body".into()),
500
501 Self::DeclarativeFilter { .. } | Self::Filter { .. } => Some("filter".into()),
502 Self::DeclarativeChoice { .. } | Self::Choice { .. } => Some("choice".into()),
503 Self::DeclarativeScript { .. } | Self::Script { .. } => Some("script".into()),
504 Self::DeclarativeFunction { .. } => Some("function".into()),
505
506 Self::DeclarativeSplit { .. }
507 | Self::DeclarativeStreamSplit { .. }
508 | Self::StreamSplit { .. }
509 | Self::Split { .. } => Some("split".into()),
510
511 Self::DeclarativeDynamicRouter { .. } | Self::DynamicRouter { .. } => {
512 Some("dynamic-router".into())
513 }
514 Self::DeclarativeRoutingSlip { .. } | Self::RoutingSlip { .. } => {
515 Some("routing-slip".into())
516 }
517 Self::DeclarativeRecipientList { .. } | Self::RecipientList { .. } => {
518 Some("recipient-list".into())
519 }
520
521 Self::Aggregate { .. } => Some("aggregate".into()),
522 Self::WireTap { .. } => Some("wire-tap".into()),
523 Self::Multicast { .. } => Some("multicast".into()),
524 Self::Bean { .. } => Some("bean".into()),
525 Self::Throttle { .. } => Some("throttle".into()),
526 Self::LoadBalance { .. } => Some("load-balance".into()),
527 Self::Delay { .. } => Some("delay".into()),
528 Self::Loop { .. } | Self::DeclarativeLoop { .. } => Some("loop".into()),
529 Self::Enrich { .. } => Some("enrich".into()),
530 Self::PollEnrich { .. } => Some("poll-enrich".into()),
531 Self::Validate { .. } => Some("validate".into()),
532 Self::ClaimCheck { .. } => Some("claim-check".into()),
533 Self::Sampling { .. } => Some("sampling".into()),
534 Self::Sort { .. } => Some("sort".into()),
535 Self::IdempotentConsumer { .. } => Some("idempotent-consumer".into()),
536 Self::Cache { .. } => Some("cache".into()),
537 Self::CacheInvalidate { .. } => Some("cache-invalidate".into()),
538 Self::CacheClear { .. } => Some("cache-clear".into()),
539 Self::CacheStats { .. } => Some("cache-stats".into()),
540 Self::CachePeekStale { .. } => Some("cache-peek-stale".into()),
541 Self::DeclarativeDoTry { .. } | Self::DoTry { .. } => Some("do-try".into()),
542 Self::Resequence { .. } => Some("resequence".into()),
543 Self::Layered { .. } => Some("layered".into()),
544 Self::Transacted { .. } => Some("transacted".into()),
545 }
546 }
547
548 pub(crate) fn to_uri_metadata(&self) -> Option<Arc<str>> {
560 match self {
561 Self::To(uri) => Some(Arc::from(uri.as_str())),
562 Self::LayeredTo { uri, .. } => Some(Arc::from(uri.as_str())),
563
564 Self::Processor(..)
568 | Self::Stop
569 | Self::Log { .. }
570 | Self::DeclarativeSetHeader { .. }
571 | Self::DeclarativeSetHeaderIfAbsent { .. }
572 | Self::DeclarativeThrow { .. }
573 | Self::DeclarativeRemoveHeader { .. }
574 | Self::DeclarativeSetProperty { .. }
575 | Self::DeclarativeSetBody { .. }
576 | Self::DeclarativeFilter { .. }
577 | Self::DeclarativeChoice { .. }
578 | Self::DeclarativeScript { .. }
579 | Self::DeclarativeFunction { .. }
580 | Self::DeclarativeSplit { .. }
581 | Self::DeclarativeStreamSplit { .. }
582 | Self::StreamSplit { .. }
583 | Self::DeclarativeDynamicRouter { .. }
584 | Self::DeclarativeRoutingSlip { .. }
585 | Self::Split { .. }
586 | Self::Aggregate { .. }
587 | Self::Filter { .. }
588 | Self::Choice { .. }
589 | Self::Multicast { .. }
590 | Self::DeclarativeLog { .. }
591 | Self::Bean { .. }
592 | Self::Script { .. }
593 | Self::Throttle { .. }
594 | Self::LoadBalance { .. }
595 | Self::DynamicRouter { .. }
596 | Self::RoutingSlip { .. }
597 | Self::RecipientList { .. }
598 | Self::DeclarativeRecipientList { .. }
599 | Self::Delay { .. }
600 | Self::Loop { .. }
601 | Self::DeclarativeLoop { .. }
602 | Self::Enrich { .. }
603 | Self::PollEnrich { .. }
604 | Self::WireTap { .. }
605 | Self::Validate { .. }
606 | Self::ClaimCheck { .. }
607 | Self::Sampling { .. }
608 | Self::Sort { .. }
609 | Self::IdempotentConsumer { .. }
610 | Self::Cache { .. }
611 | Self::CacheInvalidate { .. }
612 | Self::CacheClear { .. }
613 | Self::CacheStats { .. }
614 | Self::CachePeekStale { .. }
615 | Self::DeclarativeDoTry { .. }
616 | Self::DoTry { .. }
617 | Self::Layered { .. }
618 | Self::Resequence { .. }
619 | Self::Transacted { .. } => None,
620 }
621 }
622
623 pub(crate) fn span_kind_hint(&self) -> SpanKindHint {
640 match self {
641 Self::To(uri)
643 | Self::LayeredTo { uri, .. }
644 | Self::Enrich { uri, .. }
645 | Self::PollEnrich { uri, .. }
646 | Self::WireTap { uri, .. } => uri_span_kind(uri),
647
648 Self::Processor(..)
652 | Self::Stop
653 | Self::Log { .. }
654 | Self::DeclarativeSetHeader { .. }
655 | Self::DeclarativeSetHeaderIfAbsent { .. }
656 | Self::DeclarativeThrow { .. }
657 | Self::DeclarativeRemoveHeader { .. }
658 | Self::DeclarativeSetProperty { .. }
659 | Self::DeclarativeSetBody { .. }
660 | Self::DeclarativeFilter { .. }
661 | Self::DeclarativeChoice { .. }
662 | Self::DeclarativeScript { .. }
663 | Self::DeclarativeFunction { .. }
664 | Self::DeclarativeSplit { .. }
665 | Self::DeclarativeStreamSplit { .. }
666 | Self::StreamSplit { .. }
667 | Self::DeclarativeDynamicRouter { .. }
668 | Self::DeclarativeRoutingSlip { .. }
669 | Self::Split { .. }
670 | Self::Aggregate { .. }
671 | Self::Filter { .. }
672 | Self::Choice { .. }
673 | Self::Multicast { .. }
674 | Self::DeclarativeLog { .. }
675 | Self::Bean { .. }
676 | Self::Script { .. }
677 | Self::Throttle { .. }
678 | Self::LoadBalance { .. }
679 | Self::DynamicRouter { .. }
680 | Self::RoutingSlip { .. }
681 | Self::RecipientList { .. }
682 | Self::DeclarativeRecipientList { .. }
683 | Self::Delay { .. }
684 | Self::Loop { .. }
685 | Self::DeclarativeLoop { .. }
686 | Self::Validate { .. }
687 | Self::ClaimCheck { .. }
688 | Self::Sampling { .. }
689 | Self::Sort { .. }
690 | Self::IdempotentConsumer { .. }
691 | Self::Cache { .. }
692 | Self::CacheInvalidate { .. }
693 | Self::CacheClear { .. }
694 | Self::CacheStats { .. }
695 | Self::CachePeekStale { .. }
696 | Self::DeclarativeDoTry { .. }
697 | Self::DoTry { .. }
698 | Self::Layered { .. }
699 | Self::Resequence { .. }
700 | Self::Transacted { .. } => SpanKindHint::Internal,
701 }
702 }
703}
704
705const PRODUCER_SCHEMES: [&str; 5] = ["kafka", "jms", "activemq", "artemis", "mqtt"];
711
712fn uri_span_kind(uri: &str) -> SpanKindHint {
719 const CLIENT_SCHEMES: [&str; 12] = [
721 "http",
722 "https",
723 "grpc",
724 "grpcs",
725 "ws",
726 "redis",
727 "opensearch",
728 "sql",
729 "surrealdb",
730 "cxf",
731 "llm",
732 "mcp",
733 ];
734
735 let scheme = uri.split(':').next().unwrap_or_default();
736 if is_async_producer_scheme(scheme) {
737 SpanKindHint::Producer
738 } else if CLIENT_SCHEMES
739 .iter()
740 .any(|s| s.eq_ignore_ascii_case(scheme))
741 {
742 SpanKindHint::Client
743 } else {
744 SpanKindHint::Internal
745 }
746}
747
748pub fn is_async_producer_scheme(scheme: &str) -> bool {
758 PRODUCER_SCHEMES
759 .iter()
760 .any(|s| s.eq_ignore_ascii_case(scheme))
761}
762
763pub struct RouteDefinition {
765 pub(crate) from_uri: String,
766 pub(crate) steps: Vec<BuilderStep>,
767 pub(crate) error_handler: Option<ErrorHandlerConfig>,
769 pub(crate) circuit_breaker: Option<CircuitBreakerConfig>,
771 pub(crate) circuit_breaker_fallback: Vec<BuilderStep>,
779 pub(crate) security_policy: Option<SecurityPolicyConfig>,
780 pub(crate) security_authenticator: Option<Arc<dyn TokenAuthenticator>>,
782 pub(crate) provider_registry: Option<Arc<camel_auth::ProviderRegistry>>,
785 pub(crate) security_provider: Option<String>,
789 pub(crate) security_audiences: Option<Vec<String>>,
794 pub(crate) unit_of_work: Option<UnitOfWorkConfig>,
796 pub(crate) http_error_mapping: Option<camel_api::HttpErrorMapping>,
803 pub(crate) concurrency: Option<ConcurrencyModel>,
806 pub(crate) route_id: String,
808 pub(crate) auto_startup: bool,
810 pub(crate) startup_order: i32,
812 pub(crate) source_hash: Option<u64>,
813}
814
815impl RouteDefinition {
816 pub fn new(from_uri: impl Into<String>, steps: Vec<BuilderStep>) -> Self {
818 Self {
819 from_uri: from_uri.into(),
820 steps,
821 error_handler: None,
822 circuit_breaker: None,
823 circuit_breaker_fallback: Vec::new(),
824 security_policy: None,
825 security_authenticator: None,
826 provider_registry: None,
827 security_provider: None,
828 security_audiences: None,
829 unit_of_work: None,
830 http_error_mapping: None,
831 concurrency: None,
832 route_id: String::new(), auto_startup: true,
834 startup_order: 1000,
835 source_hash: None,
836 }
837 }
838
839 pub fn from_uri(&self) -> &str {
841 &self.from_uri
842 }
843
844 pub fn steps(&self) -> &[BuilderStep] {
846 &self.steps
847 }
848
849 pub fn circuit_breaker_fallback(&self) -> &[BuilderStep] {
850 &self.circuit_breaker_fallback
851 }
852
853 pub fn map_steps(mut self, f: impl FnOnce(Vec<BuilderStep>) -> Vec<BuilderStep>) -> Self {
858 self.steps = f(self.steps);
859 self
860 }
861
862 pub fn with_error_handler(mut self, config: ErrorHandlerConfig) -> Self {
864 self.error_handler = Some(config);
865 self
866 }
867
868 pub fn error_handler_config(&self) -> Option<&ErrorHandlerConfig> {
870 self.error_handler.as_ref()
871 }
872
873 pub fn with_circuit_breaker(mut self, config: CircuitBreakerConfig) -> Self {
875 self.circuit_breaker = Some(config);
876 self
877 }
878
879 pub fn with_circuit_breaker_fallback(mut self, steps: Vec<BuilderStep>) -> Self {
886 self.circuit_breaker_fallback = steps;
887 self
888 }
889
890 pub fn with_security_policy(mut self, config: SecurityPolicyConfig) -> Self {
892 self.security_policy = Some(config);
893 self
894 }
895
896 pub fn with_security_authenticator(
898 mut self,
899 authenticator: Arc<dyn TokenAuthenticator>,
900 ) -> Self {
901 self.security_authenticator = Some(authenticator);
902 self
903 }
904
905 pub fn with_provider_registry(mut self, registry: Arc<camel_auth::ProviderRegistry>) -> Self {
911 self.provider_registry = Some(registry);
912 self
913 }
914
915 pub fn with_security_provider(mut self, name: impl Into<String>) -> Self {
917 self.security_provider = Some(name.into());
918 self
919 }
920
921 pub fn with_security_audiences(mut self, audiences: Vec<String>) -> Self {
923 self.security_audiences = Some(audiences);
924 self
925 }
926
927 pub fn security_provider(&self) -> Option<&str> {
929 self.security_provider.as_deref()
930 }
931
932 pub fn security_audiences(&self) -> Option<&[String]> {
934 self.security_audiences.as_deref()
935 }
936
937 pub fn with_unit_of_work(mut self, config: UnitOfWorkConfig) -> Self {
939 self.unit_of_work = Some(config);
940 self
941 }
942
943 pub fn with_http_error_mapping(mut self, mapping: camel_api::HttpErrorMapping) -> Self {
948 self.http_error_mapping = Some(mapping);
949 self
950 }
951
952 pub fn http_error_mapping(&self) -> Option<&camel_api::HttpErrorMapping> {
954 self.http_error_mapping.as_ref()
955 }
956
957 pub fn unit_of_work_config(&self) -> Option<&UnitOfWorkConfig> {
959 self.unit_of_work.as_ref()
960 }
961
962 pub fn circuit_breaker_config(&self) -> Option<&CircuitBreakerConfig> {
964 self.circuit_breaker.as_ref()
965 }
966
967 pub fn security_policy_config(&self) -> Option<&SecurityPolicyConfig> {
968 self.security_policy.as_ref()
969 }
970
971 pub fn security_authenticator(&self) -> Option<&Arc<dyn TokenAuthenticator>> {
972 self.security_authenticator.as_ref()
973 }
974
975 pub fn concurrency_override(&self) -> Option<&ConcurrencyModel> {
977 self.concurrency.as_ref()
978 }
979
980 pub fn with_concurrency(mut self, model: ConcurrencyModel) -> Self {
982 self.concurrency = Some(model);
983 self
984 }
985
986 pub fn route_id(&self) -> &str {
988 &self.route_id
989 }
990
991 pub fn auto_startup(&self) -> bool {
993 self.auto_startup
994 }
995
996 pub fn startup_order(&self) -> i32 {
998 self.startup_order
999 }
1000
1001 pub fn with_route_id(mut self, id: impl Into<String>) -> Self {
1003 self.route_id = id.into();
1004 self
1005 }
1006
1007 pub fn with_auto_startup(mut self, auto: bool) -> Self {
1009 self.auto_startup = auto;
1010 self
1011 }
1012
1013 pub fn with_startup_order(mut self, order: i32) -> Self {
1015 self.startup_order = order;
1016 self
1017 }
1018
1019 pub fn with_source_hash(mut self, hash: u64) -> Self {
1020 self.source_hash = Some(hash);
1021 self
1022 }
1023
1024 pub fn source_hash(&self) -> Option<u64> {
1025 self.source_hash
1026 }
1027
1028 pub fn to_info(&self) -> RouteDefinitionInfo {
1031 RouteDefinitionInfo {
1032 route_id: self.route_id.clone(),
1033 auto_startup: self.auto_startup,
1034 startup_order: self.startup_order,
1035 source_hash: self.source_hash,
1036 }
1037 }
1038}
1039
1040#[derive(Clone)]
1046pub struct RouteDefinitionInfo {
1047 route_id: String,
1048 auto_startup: bool,
1049 startup_order: i32,
1050 pub(crate) source_hash: Option<u64>,
1051}
1052
1053impl RouteDefinitionInfo {
1054 pub fn route_id(&self) -> &str {
1056 &self.route_id
1057 }
1058
1059 pub fn auto_startup(&self) -> bool {
1061 self.auto_startup
1062 }
1063
1064 pub fn startup_order(&self) -> i32 {
1066 self.startup_order
1067 }
1068
1069 pub fn source_hash(&self) -> Option<u64> {
1070 self.source_hash
1071 }
1072}
1073
1074#[cfg(test)]
1075mod tests {
1076 use super::*;
1077 use camel_api::{RecipientSource, TargetSource};
1078
1079 #[test]
1083 fn builder_step_transacted_constructs() {
1084 let step = BuilderStep::Transacted {
1085 datasource: "pg".into(),
1086 steps: vec![BuilderStep::To("sql:select 1?datasource=pg".into())],
1087 };
1088 let rendered = format!("{step:?}");
1089 assert!(
1090 rendered.contains("Transacted"),
1091 "debug must name the Transacted variant: {rendered}"
1092 );
1093 assert!(
1094 rendered.contains(r#"datasource: "pg""#),
1095 "derived Debug must render the block datasource field: {rendered}"
1096 );
1097 }
1098
1099 #[test]
1103 fn is_async_producer_scheme_table() {
1104 assert!(is_async_producer_scheme("kafka"));
1105 assert!(!is_async_producer_scheme("seda"));
1106 assert!(!is_async_producer_scheme("sql"));
1107 }
1108
1109 #[test]
1116 fn builder_step_span_label_mapping() {
1117 use camel_api::declarative::LanguageExpressionDef;
1118 use camel_api::splitter::AggregationStrategy;
1119 use camel_api::{BoxProcessor, IdentityProcessor, OpaqueProcessor};
1120
1121 let expr = LanguageExpressionDef {
1122 language: "simple".into(),
1123 source: "${body}".into(),
1124 };
1125
1126 assert_eq!(
1128 BuilderStep::To("direct:tree-sub".into())
1129 .span_label()
1130 .as_deref(),
1131 Some("to:direct")
1132 );
1133 assert_eq!(
1134 BuilderStep::To("http://api.example/x".into())
1135 .span_label()
1136 .as_deref(),
1137 Some("to:http")
1138 );
1139 assert_eq!(BuilderStep::To("garbage".into()).span_label(), None);
1141
1142 assert_eq!(
1144 BuilderStep::Log {
1145 level: camel_processor::LogLevel::Info,
1146 message: "m".into(),
1147 }
1148 .span_label()
1149 .as_deref(),
1150 Some("log")
1151 );
1152 assert_eq!(
1153 BuilderStep::Split {
1154 config: camel_api::splitter::SplitterConfig::new(
1155 camel_api::splitter::split_body_lines()
1156 ),
1157 steps: vec![BuilderStep::Stop],
1158 }
1159 .span_label()
1160 .as_deref(),
1161 Some("split")
1162 );
1163 assert_eq!(
1164 BuilderStep::DeclarativeSplit {
1165 expression: expr.clone(),
1166 aggregation: AggregationStrategy::Original,
1167 parallel: false,
1168 parallel_limit: None,
1169 trace_item_threshold: None,
1170 stop_on_exception: true,
1171 steps: vec![BuilderStep::Stop],
1172 }
1173 .span_label()
1174 .as_deref(),
1175 Some("split")
1176 );
1177 assert_eq!(
1178 BuilderStep::DeclarativeStreamSplit {
1179 stream_config: camel_api::StreamSplitConfig::default(),
1180 aggregation: AggregationStrategy::Original,
1181 stop_on_exception: true,
1182 steps: vec![BuilderStep::Stop],
1183 }
1184 .span_label()
1185 .as_deref(),
1186 Some("split")
1187 );
1188 assert_eq!(BuilderStep::Stop.span_label(), None);
1189
1190 assert_eq!(
1192 BuilderStep::Processor(OpaqueProcessor(BoxProcessor::new(IdentityProcessor)))
1193 .span_label(),
1194 None
1195 );
1196 }
1197
1198 #[test]
1210 fn builder_step_span_kind_hint_mapping() {
1211 use camel_api::splitter::split_body_lines;
1212 use camel_api::{Exchange, FilterPredicate, SpanKindHint};
1213
1214 let kind = |uri: &str| BuilderStep::To(uri.into()).span_kind_hint();
1215
1216 assert_eq!(kind("kafka:orders"), SpanKindHint::Producer);
1218 assert_eq!(kind("jms:q"), SpanKindHint::Producer);
1219 assert_eq!(kind("activemq:q"), SpanKindHint::Producer);
1220 assert_eq!(kind("artemis:q"), SpanKindHint::Producer);
1221 assert_eq!(kind("mqtt:t"), SpanKindHint::Producer);
1222 assert_eq!(kind("KAFKA:orders"), SpanKindHint::Producer);
1224
1225 assert_eq!(kind("http://x"), SpanKindHint::Client);
1227 assert_eq!(kind("https://x"), SpanKindHint::Client);
1228 assert_eq!(kind("grpc://x"), SpanKindHint::Client);
1229 assert_eq!(kind("grpcs://x"), SpanKindHint::Client);
1230 assert_eq!(kind("ws://x"), SpanKindHint::Client);
1231 assert_eq!(kind("redis://x"), SpanKindHint::Client);
1232 assert_eq!(kind("opensearch://x"), SpanKindHint::Client);
1233 assert_eq!(kind("sql:db"), SpanKindHint::Client);
1234 assert_eq!(kind("surrealdb://x"), SpanKindHint::Client);
1235 assert_eq!(kind("cxf://x"), SpanKindHint::Client);
1236 assert_eq!(kind("llm://x"), SpanKindHint::Client);
1237 assert_eq!(kind("mcp://x"), SpanKindHint::Client);
1238
1239 assert_eq!(kind("direct:y"), SpanKindHint::Internal);
1241 assert_eq!(kind("timer:z"), SpanKindHint::Internal);
1242 assert_eq!(kind("garbage"), SpanKindHint::Internal);
1244
1245 assert_eq!(
1247 BuilderStep::Log {
1248 level: camel_processor::LogLevel::Info,
1249 message: "m".into(),
1250 }
1251 .span_kind_hint(),
1252 SpanKindHint::Internal
1253 );
1254 assert_eq!(
1255 BuilderStep::Filter {
1256 predicate: FilterPredicate::new(|_: &Exchange| true),
1257 steps: vec![BuilderStep::Stop],
1258 }
1259 .span_kind_hint(),
1260 SpanKindHint::Internal
1261 );
1262 assert_eq!(
1263 BuilderStep::Split {
1264 config: camel_api::splitter::SplitterConfig::new(split_body_lines()),
1265 steps: vec![BuilderStep::Stop],
1266 }
1267 .span_kind_hint(),
1268 SpanKindHint::Internal
1269 );
1270
1271 let enrich = |uri: &str| BuilderStep::Enrich {
1275 uri: uri.into(),
1276 strategy: None,
1277 timeout_ms: None,
1278 };
1279 let poll_enrich = |uri: &str| BuilderStep::PollEnrich {
1280 uri: uri.into(),
1281 strategy: None,
1282 timeout_ms: None,
1283 };
1284 let wire_tap = |uri: &str| BuilderStep::WireTap { uri: uri.into() };
1285
1286 assert_eq!(enrich("http://x").span_kind_hint(), SpanKindHint::Client);
1288 assert_eq!(
1289 poll_enrich("http://x").span_kind_hint(),
1290 SpanKindHint::Client
1291 );
1292 assert_eq!(wire_tap("http://x").span_kind_hint(), SpanKindHint::Client);
1293 assert_eq!(
1295 enrich("kafka:orders").span_kind_hint(),
1296 SpanKindHint::Producer
1297 );
1298 assert_eq!(
1299 poll_enrich("kafka:orders").span_kind_hint(),
1300 SpanKindHint::Producer
1301 );
1302 assert_eq!(
1303 wire_tap("kafka:orders").span_kind_hint(),
1304 SpanKindHint::Producer
1305 );
1306 assert_eq!(enrich("direct:y").span_kind_hint(), SpanKindHint::Internal);
1308 assert_eq!(
1309 poll_enrich("seda:q").span_kind_hint(),
1310 SpanKindHint::Internal
1311 );
1312 assert_eq!(
1313 wire_tap("direct:y").span_kind_hint(),
1314 SpanKindHint::Internal
1315 );
1316 }
1317
1318 #[test]
1323 fn golden_debug_output_all_variants() {
1324 use camel_api::declarative::LanguageExpressionDef;
1325 use camel_api::loop_eip::LoopMode;
1326 use camel_api::recipient_list::RecipientListConfig;
1327 use camel_api::splitter::{AggregationStrategy, StreamSplitConfig, StreamSplitFormat};
1328 use camel_api::{
1329 BoxProcessor, DynamicRouterConfig, Exchange, FilterPredicate, FunctionDefinition,
1330 FunctionId, IdentityProcessor, MulticastConfig, OpaqueProcessor, RoutingSlipConfig,
1331 Value,
1332 };
1333 use std::sync::Arc;
1334
1335 let expr = LanguageExpressionDef {
1336 language: "simple".into(),
1337 source: "${body}".into(),
1338 };
1339
1340 assert_eq!(format!("{:?}", BuilderStep::Stop), "Stop");
1343 assert_eq!(
1344 format!(
1345 "{:?}",
1346 BuilderStep::Processor(OpaqueProcessor(BoxProcessor::new(IdentityProcessor)))
1347 ),
1348 "Processor(BoxProcessor(...))"
1349 );
1350 assert_eq!(
1351 format!("{:?}", BuilderStep::To("mock:out".into())),
1352 "To(\"mock:out\")"
1353 );
1354
1355 assert_eq!(
1358 format!(
1359 "{:?}",
1360 BuilderStep::Log {
1361 level: camel_processor::LogLevel::Info,
1362 message: "hello".into(),
1363 }
1364 ),
1365 "Log { level: Info, message: \"hello\" }"
1366 );
1367
1368 assert_eq!(
1369 format!(
1370 "{:?}",
1371 BuilderStep::DeclarativeSetHeader {
1372 key: "k".into(),
1373 value: ValueSourceDef::Literal(Value::String("v".into())),
1374 }
1375 ),
1376 "DeclarativeSetHeader { key: \"k\", value: Literal(String(\"v\")) }"
1377 );
1378
1379 assert_eq!(
1380 format!(
1381 "{:?}",
1382 BuilderStep::DeclarativeSetHeaderIfAbsent {
1383 key: "k".into(),
1384 value: ValueSourceDef::Literal(Value::String("v".into())),
1385 }
1386 ),
1387 "DeclarativeSetHeaderIfAbsent { key: \"k\", value: Literal(String(\"v\")) }"
1388 );
1389
1390 assert_eq!(
1391 format!(
1392 "{:?}",
1393 BuilderStep::DeclarativeSetBody {
1394 value: ValueSourceDef::Literal(Value::String("v".into())),
1395 }
1396 ),
1397 "DeclarativeSetBody { value: Literal(String(\"v\")) }"
1398 );
1399
1400 assert_eq!(
1401 format!(
1402 "{:?}",
1403 BuilderStep::DeclarativeSetProperty {
1404 key: "prop".into(),
1405 value_source: ValueSourceDef::Literal(Value::String("v".into())),
1406 }
1407 ),
1408 "DeclarativeSetProperty { key: \"prop\", value_source: Literal(String(\"v\")) }"
1409 );
1410
1411 assert_eq!(
1412 format!(
1413 "{:?}",
1414 BuilderStep::DeclarativeScript {
1415 expression: expr.clone(),
1416 }
1417 ),
1418 "DeclarativeScript { expression: LanguageExpressionDef { language: \"simple\", source: \"${body}\" } }"
1419 );
1420
1421 let func_def = FunctionDefinition {
1423 id: FunctionId("test-id".into()),
1424 runtime: "my_runtime".into(),
1425 source: "${body}".into(),
1426 timeout_ms: 5000,
1427 route_id: None,
1428 step_index: None,
1429 };
1430 assert_eq!(
1431 format!(
1432 "{:?}",
1433 BuilderStep::DeclarativeFunction {
1434 definition: func_def,
1435 }
1436 ),
1437 "DeclarativeFunction { definition: FunctionDefinition { id: FunctionId(\"test-id\"), runtime: \"my_runtime\", source: \"${body}\", timeout_ms: 5000, route_id: None, step_index: None } }"
1438 );
1439
1440 assert_eq!(
1441 format!(
1442 "{:?}",
1443 BuilderStep::WireTap {
1444 uri: "mock:tap".into(),
1445 }
1446 ),
1447 "WireTap { uri: \"mock:tap\" }"
1448 );
1449
1450 assert_eq!(
1451 format!(
1452 "{:?}",
1453 BuilderStep::DeclarativeLog {
1454 level: camel_processor::LogLevel::Info,
1455 message: ValueSourceDef::Expression(expr.clone()),
1456 }
1457 ),
1458 "DeclarativeLog { level: Info, message: Expression(LanguageExpressionDef { language: \"simple\", source: \"${body}\" }) }"
1459 );
1460
1461 assert_eq!(
1462 format!(
1463 "{:?}",
1464 BuilderStep::Bean {
1465 name: "myBean".into(),
1466 method: "process".into(),
1467 }
1468 ),
1469 "Bean { name: \"myBean\", method: \"process\" }"
1470 );
1471
1472 assert_eq!(
1473 format!(
1474 "{:?}",
1475 BuilderStep::Script {
1476 language: "js".into(),
1477 script: "body".into(),
1478 }
1479 ),
1480 "Script { language: \"js\", script: \"body\" }"
1481 );
1482
1483 assert_eq!(
1484 format!(
1485 "{:?}",
1486 BuilderStep::Aggregate {
1487 config: camel_api::AggregatorConfig::correlate_by("id")
1488 .complete_when_size(1)
1489 .build()
1490 .unwrap(),
1491 }
1492 ),
1493 "Aggregate { config: AggregatorConfig { header_name: \"id\", completion: Single(Size(1)), correlation: HeaderName(\"id\"), strategy: CollectAll, max_buckets: Some(10000), max_bucket_size: Some(10000), bucket_ttl: Some(300s), force_completion_on_stop: false, discard_on_timeout: false, max_timeout_tasks: 1024 } }"
1494 );
1495
1496 assert_eq!(
1497 format!(
1498 "{:?}",
1499 BuilderStep::DynamicRouter {
1500 config: DynamicRouterConfig::new(TargetSource::Sync(Arc::new(
1501 |_: &Exchange| Some("mock:dr".into())
1502 ))),
1503 }
1504 ),
1505 "DynamicRouter { config: DynamicRouterConfig { uri_delimiter: \",\", cache_size: 1000, ignore_invalid_endpoints: false, max_iterations: 1000, timeout: Some(60s) } }"
1506 );
1507
1508 assert_eq!(
1509 format!(
1510 "{:?}",
1511 BuilderStep::RoutingSlip {
1512 config: RoutingSlipConfig::new(TargetSource::Sync(Arc::new(|_: &Exchange| {
1513 Some("mock:rs".into())
1514 }))),
1515 }
1516 ),
1517 "RoutingSlip { config: RoutingSlipConfig { uri_delimiter: \",\", cache_size: 1000, ignore_invalid_endpoints: false } }"
1518 );
1519
1520 assert_eq!(
1521 format!(
1522 "{:?}",
1523 BuilderStep::RecipientList {
1524 config: RecipientListConfig::new(RecipientSource::Sync(Arc::new(
1525 |_: &Exchange| String::new()
1526 ))),
1527 }
1528 ),
1529 "RecipientList { config: RecipientListConfig { delimiter: \",\", parallel: false, parallel_limit: None, stop_on_exception: false, max_recipients: 1000 } }"
1530 );
1531
1532 assert_eq!(
1533 format!(
1534 "{:?}",
1535 BuilderStep::Enrich {
1536 uri: "mock:enrich".into(),
1537 strategy: Some("agg".into()),
1538 timeout_ms: Some(1000),
1539 }
1540 ),
1541 "Enrich { uri: \"mock:enrich\", strategy: Some(\"agg\"), timeout_ms: Some(1000) }"
1542 );
1543
1544 assert_eq!(
1545 format!(
1546 "{:?}",
1547 BuilderStep::PollEnrich {
1548 uri: "mock:poll".into(),
1549 strategy: None,
1550 timeout_ms: None,
1551 }
1552 ),
1553 "PollEnrich { uri: \"mock:poll\", strategy: None, timeout_ms: None }"
1554 );
1555
1556 assert_eq!(
1557 format!(
1558 "{:?}",
1559 BuilderStep::Validate {
1560 predicate: expr.clone(),
1561 }
1562 ),
1563 "Validate { predicate: LanguageExpressionDef { language: \"simple\", source: \"${body}\" } }"
1564 );
1565
1566 assert_eq!(
1567 format!("{:?}", BuilderStep::Sampling { period: 100 }),
1568 "Sampling { period: 100 }"
1569 );
1570
1571 assert_eq!(
1572 format!(
1573 "{:?}",
1574 BuilderStep::Resequence {
1575 policy_config: Default::default(),
1576 }
1577 ),
1578 "Resequence { policy_config: ResequencePolicyConfig { mode: Batch { correlation: \"header.id\", sort: \"header.id\", completion: SizeOrTimeout(100, 30000) } } }"
1579 );
1580
1581 assert_eq!(
1583 format!(
1584 "{:?}",
1585 BuilderStep::DeclarativeFilter {
1586 predicate: expr.clone(),
1587 steps: vec![BuilderStep::Stop],
1588 }
1589 ),
1590 "DeclarativeFilter { predicate: LanguageExpressionDef { language: \"simple\", source: \"${body}\" }, steps: [Stop] }"
1591 );
1592
1593 assert_eq!(
1594 format!(
1595 "{:?}",
1596 BuilderStep::DeclarativeSplit {
1597 expression: expr.clone(),
1598 aggregation: AggregationStrategy::Original,
1599 parallel: false,
1600 parallel_limit: Some(2),
1601 trace_item_threshold: None,
1602 stop_on_exception: true,
1603 steps: vec![BuilderStep::Stop],
1604 }
1605 ),
1606 "DeclarativeSplit { expression: LanguageExpressionDef { language: \"simple\", source: \"${body}\" }, aggregation: Original, parallel: false, parallel_limit: Some(2), trace_item_threshold: None, stop_on_exception: true, steps: [Stop] }"
1607 );
1608
1609 assert_eq!(
1610 format!(
1611 "{:?}",
1612 BuilderStep::Split {
1613 config: camel_api::splitter::SplitterConfig::new(
1614 camel_api::splitter::split_body_lines()
1615 ),
1616 steps: vec![BuilderStep::Stop],
1617 }
1618 ),
1619 "Split { config: SplitterConfig { expression: \"<split-expression>\", aggregation: LastWins, parallel: false, parallel_limit: None, stop_on_exception: true, max_fragments: 100000, trace_item_threshold: 100 }, steps: [Stop] }"
1620 );
1621
1622 assert_eq!(
1623 format!(
1624 "{:?}",
1625 BuilderStep::Filter {
1626 predicate: FilterPredicate::new(|_: &Exchange| true),
1627 steps: vec![BuilderStep::Stop],
1628 }
1629 ),
1630 "Filter { predicate: FilterPredicate(..), steps: [Stop] }"
1631 );
1632
1633 assert_eq!(
1634 format!(
1635 "{:?}",
1636 BuilderStep::Throttle {
1637 config: camel_api::ThrottlerConfig::new(
1638 10,
1639 std::time::Duration::from_millis(10)
1640 ),
1641 steps: vec![BuilderStep::Stop],
1642 }
1643 ),
1644 "Throttle { config: ThrottlerConfig { max_requests: 10, period: 10ms, strategy: Delay }, steps: [Stop] }"
1645 );
1646
1647 assert_eq!(
1648 format!(
1649 "{:?}",
1650 BuilderStep::LoadBalance {
1651 config: camel_api::LoadBalancerConfig::round_robin(),
1652 steps: vec![BuilderStep::To("mock:l1".into())],
1653 }
1654 ),
1655 "LoadBalance { config: LoadBalancerConfig { strategy: RoundRobin }, steps: [To(\"mock:l1\")] }"
1656 );
1657
1658 assert_eq!(
1659 format!(
1660 "{:?}",
1661 BuilderStep::Delay {
1662 config: camel_api::DelayConfig::new(500),
1663 }
1664 ),
1665 "Delay { config: DelayConfig { delay_ms: 500, dynamic_header: None, max_delay_ms: 3600000 } }"
1666 );
1667
1668 assert_eq!(
1672 format!(
1673 "{:?}",
1674 BuilderStep::Choice {
1675 whens: vec![WhenStep {
1676 predicate: FilterPredicate::new(|_: &Exchange| true),
1677 steps: vec![BuilderStep::To("mock:a".into())],
1678 }],
1679 otherwise: None,
1680 }
1681 ),
1682 "Choice { whens: [WhenStep { predicate: FilterPredicate(..), steps: [To(\"mock:a\")] }], otherwise: None }"
1683 );
1684
1685 assert_eq!(
1686 format!(
1687 "{:?}",
1688 BuilderStep::DeclarativeChoice {
1689 whens: vec![DeclarativeWhenStep {
1690 predicate: expr.clone(),
1691 steps: vec![BuilderStep::Stop],
1692 }],
1693 otherwise: Some(vec![BuilderStep::Stop]),
1694 }
1695 ),
1696 "DeclarativeChoice { whens: [DeclarativeWhenStep { predicate: LanguageExpressionDef { language: \"simple\", source: \"${body}\" }, steps: [Stop] }], otherwise: Some([Stop]) }"
1697 );
1698
1699 assert_eq!(
1701 format!(
1702 "{:?}",
1703 BuilderStep::Multicast {
1704 steps: vec![BuilderStep::To("direct:a".into())],
1705 config: MulticastConfig::new(),
1706 }
1707 ),
1708 "Multicast { steps: [To(\"direct:a\")], config: MulticastConfig { parallel: false, parallel_limit: None, stop_on_exception: false, timeout: None, aggregation: LastWins } }"
1709 );
1710
1711 assert_eq!(
1713 format!(
1714 "{:?}",
1715 BuilderStep::DeclarativeDynamicRouter {
1716 expression: expr.clone(),
1717 uri_delimiter: ",".into(),
1718 cache_size: 1000,
1719 ignore_invalid_endpoints: false,
1720 max_iterations: 1000,
1721 }
1722 ),
1723 "DeclarativeDynamicRouter { expression: LanguageExpressionDef { language: \"simple\", source: \"${body}\" }, uri_delimiter: \",\", cache_size: 1000, ignore_invalid_endpoints: false, max_iterations: 1000 }"
1724 );
1725
1726 assert_eq!(
1727 format!(
1728 "{:?}",
1729 BuilderStep::DeclarativeRoutingSlip {
1730 expression: expr.clone(),
1731 uri_delimiter: ",".into(),
1732 cache_size: 1000,
1733 ignore_invalid_endpoints: false,
1734 }
1735 ),
1736 "DeclarativeRoutingSlip { expression: LanguageExpressionDef { language: \"simple\", source: \"${body}\" }, uri_delimiter: \",\", cache_size: 1000, ignore_invalid_endpoints: false }"
1737 );
1738
1739 assert_eq!(
1741 format!(
1742 "{:?}",
1743 BuilderStep::DeclarativeRecipientList {
1744 expression: expr.clone(),
1745 delimiter: ",".into(),
1746 parallel: false,
1747 parallel_limit: None,
1748 stop_on_exception: false,
1749 aggregation: "original".into(),
1750 }
1751 ),
1752 "DeclarativeRecipientList { expression: LanguageExpressionDef { language: \"simple\", source: \"${body}\" }, delimiter: \",\", parallel: false, parallel_limit: None, stop_on_exception: false, aggregation: \"original\" }"
1753 );
1754
1755 assert_eq!(
1757 format!(
1758 "{:?}",
1759 BuilderStep::Loop {
1760 config: camel_api::loop_eip::LoopConfig::new(LoopMode::Count(3)),
1761 steps: vec![],
1762 }
1763 ),
1764 "Loop { config: LoopConfig { mode: Count(3), max_iterations: 10000 }, steps: [] }"
1765 );
1766
1767 assert_eq!(
1768 format!(
1769 "{:?}",
1770 BuilderStep::DeclarativeLoop {
1771 count: Some(5),
1772 while_predicate: None,
1773 steps: vec![],
1774 max_iterations: Some(100),
1775 }
1776 ),
1777 "DeclarativeLoop { count: Some(5), while_predicate: None, steps: [], max_iterations: Some(100) }"
1778 );
1779
1780 assert_eq!(
1782 format!(
1783 "{:?}",
1784 BuilderStep::ClaimCheck {
1785 repository: "myRepo".into(),
1786 operation: "checkout".into(),
1787 key: expr.clone(),
1788 filter: None,
1789 }
1790 ),
1791 "ClaimCheck { repository: \"myRepo\", operation: \"checkout\", key: LanguageExpressionDef { language: \"simple\", source: \"${body}\" }, filter: None }"
1792 );
1793
1794 assert_eq!(
1796 format!(
1797 "{:?}",
1798 BuilderStep::Sort {
1799 expression: expr.clone(),
1800 reverse: false,
1801 }
1802 ),
1803 "Sort { expression: LanguageExpressionDef { language: \"simple\", source: \"${body}\" }, reverse: false }"
1804 );
1805
1806 assert_eq!(
1808 format!(
1809 "{:?}",
1810 BuilderStep::IdempotentConsumer {
1811 repository: "myRepo".into(),
1812 expression: expr.clone(),
1813 steps: vec![],
1814 eager: true,
1815 remove_on_failure: false,
1816 on_missing_key: camel_processor::OnMissingKey::Fail,
1817 }
1818 ),
1819 "IdempotentConsumer { repository: \"myRepo\", expression: LanguageExpressionDef { language: \"simple\", source: \"${body}\" }, steps: [], eager: true, remove_on_failure: false, on_missing_key: Fail }"
1820 );
1821
1822 assert_eq!(
1824 format!(
1825 "{:?}",
1826 BuilderStep::DeclarativeDoTry {
1827 try_steps: vec![BuilderStep::Stop],
1828 catch: vec![],
1829 finally: None,
1830 }
1831 ),
1832 "DeclarativeDoTry { try_steps: [Stop], catch: [], finally: None }"
1833 );
1834
1835 assert_eq!(
1837 format!(
1838 "{:?}",
1839 BuilderStep::DeclarativeStreamSplit {
1840 stream_config: StreamSplitConfig {
1841 format: StreamSplitFormat::Ndjson,
1842 max_record_bytes: 1024 * 1024,
1843 batch_size: 1,
1844 chunk_size: None,
1845 max_parts: None,
1846 max_part_size: None,
1847 content_types: None,
1848 include_origin: true,
1849 },
1850 aggregation: AggregationStrategy::Original,
1851 stop_on_exception: true,
1852 steps: vec![BuilderStep::Stop],
1853 }
1854 ),
1855 "DeclarativeStreamSplit { stream_config: StreamSplitConfig { format: Ndjson, max_record_bytes: 1048576, batch_size: 1, chunk_size: None, max_parts: None, max_part_size: None, content_types: None, include_origin: true }, aggregation: Original, stop_on_exception: true, steps: [Stop] }"
1856 );
1857 }
1858
1859 #[test]
1860 fn test_builder_step_multicast_variant() {
1861 use camel_api::MulticastConfig;
1862
1863 let step = BuilderStep::Multicast {
1864 steps: vec![BuilderStep::To("direct:a".into())],
1865 config: MulticastConfig::new(),
1866 };
1867
1868 assert!(matches!(step, BuilderStep::Multicast { .. }));
1869 }
1870
1871 #[test]
1872 fn test_route_definition_defaults() {
1873 let def = RouteDefinition::new("direct:test", vec![]).with_route_id("test-route");
1874 assert_eq!(def.route_id(), "test-route");
1875 assert!(def.auto_startup());
1876 assert_eq!(def.startup_order(), 1000);
1877 }
1878
1879 #[test]
1880 fn test_route_definition_builders() {
1881 let def = RouteDefinition::new("direct:test", vec![])
1882 .with_route_id("my-route")
1883 .with_auto_startup(false)
1884 .with_startup_order(50);
1885 assert_eq!(def.route_id(), "my-route");
1886 assert!(!def.auto_startup());
1887 assert_eq!(def.startup_order(), 50);
1888 }
1889
1890 #[test]
1891 fn test_route_definition_accessors_cover_core_fields() {
1892 let def = RouteDefinition::new("direct:in", vec![BuilderStep::To("mock:out".into())])
1893 .with_route_id("accessor-route");
1894
1895 assert_eq!(def.from_uri(), "direct:in");
1896 assert_eq!(def.steps().len(), 1);
1897 assert!(matches!(def.steps()[0], BuilderStep::To(_)));
1898 }
1899
1900 #[test]
1901 fn test_route_definition_error_handler_circuit_breaker_and_concurrency_accessors() {
1902 use camel_api::circuit_breaker::CircuitBreakerConfig;
1903 use camel_api::error_handler::ErrorHandlerConfig;
1904 use camel_component_api::ConcurrencyModel;
1905
1906 let def = RouteDefinition::new("direct:test", vec![])
1907 .with_route_id("eh-route")
1908 .with_error_handler(ErrorHandlerConfig::dead_letter_channel("log:dlc"))
1909 .with_circuit_breaker(CircuitBreakerConfig::new())
1910 .with_concurrency(ConcurrencyModel::Concurrent { max: Some(4) });
1911
1912 let eh = def
1913 .error_handler_config()
1914 .expect("error handler should be set");
1915 assert_eq!(eh.dlc_uri.as_deref(), Some("log:dlc"));
1916 assert!(def.circuit_breaker_config().is_some());
1917 assert!(matches!(
1918 def.concurrency_override(),
1919 Some(ConcurrencyModel::Concurrent { max: Some(4) })
1920 ));
1921 }
1922
1923 #[test]
1924 fn test_builder_step_debug_covers_many_variants() {
1925 use camel_api::splitter::{AggregationStrategy, SplitterConfig, split_body_lines};
1926 use camel_api::{
1927 BoxProcessor, DynamicRouterConfig, Exchange, FilterPredicate, IdentityProcessor,
1928 OpaqueProcessor, RoutingSlipConfig, Value,
1929 };
1930 use std::sync::Arc;
1931
1932 let expr = LanguageExpressionDef {
1933 language: "simple".into(),
1934 source: "${body}".into(),
1935 };
1936
1937 let steps = vec![
1938 BuilderStep::Processor(OpaqueProcessor(BoxProcessor::new(IdentityProcessor))),
1939 BuilderStep::To("mock:out".into()),
1940 BuilderStep::Stop,
1941 BuilderStep::Log {
1942 level: camel_processor::LogLevel::Info,
1943 message: "hello".into(),
1944 },
1945 BuilderStep::DeclarativeSetHeader {
1946 key: "k".into(),
1947 value: ValueSourceDef::Literal(Value::String("v".into())),
1948 },
1949 BuilderStep::DeclarativeSetBody {
1950 value: ValueSourceDef::Expression(expr.clone()),
1951 },
1952 BuilderStep::DeclarativeFilter {
1953 predicate: expr.clone(),
1954 steps: vec![BuilderStep::Stop],
1955 },
1956 BuilderStep::DeclarativeChoice {
1957 whens: vec![DeclarativeWhenStep {
1958 predicate: expr.clone(),
1959 steps: vec![BuilderStep::Stop],
1960 }],
1961 otherwise: Some(vec![BuilderStep::Stop]),
1962 },
1963 BuilderStep::DeclarativeScript {
1964 expression: expr.clone(),
1965 },
1966 BuilderStep::DeclarativeSplit {
1967 expression: expr.clone(),
1968 aggregation: AggregationStrategy::Original,
1969 parallel: false,
1970 parallel_limit: Some(2),
1971 trace_item_threshold: None,
1972 stop_on_exception: true,
1973 steps: vec![BuilderStep::Stop],
1974 },
1975 BuilderStep::Split {
1976 config: SplitterConfig::new(split_body_lines()),
1977 steps: vec![BuilderStep::Stop],
1978 },
1979 BuilderStep::Aggregate {
1980 config: camel_api::AggregatorConfig::correlate_by("id")
1981 .complete_when_size(1)
1982 .build()
1983 .unwrap(),
1984 },
1985 BuilderStep::Filter {
1986 predicate: FilterPredicate::new(|_: &Exchange| true),
1987 steps: vec![BuilderStep::Stop],
1988 },
1989 BuilderStep::WireTap {
1990 uri: "mock:tap".into(),
1991 },
1992 BuilderStep::DeclarativeLog {
1993 level: camel_processor::LogLevel::Info,
1994 message: ValueSourceDef::Expression(expr.clone()),
1995 },
1996 BuilderStep::Bean {
1997 name: "bean".into(),
1998 method: "call".into(),
1999 },
2000 BuilderStep::Script {
2001 language: "rhai".into(),
2002 script: "body".into(),
2003 },
2004 BuilderStep::Throttle {
2005 config: camel_api::ThrottlerConfig::new(10, std::time::Duration::from_millis(10)),
2006 steps: vec![BuilderStep::Stop],
2007 },
2008 BuilderStep::LoadBalance {
2009 config: camel_api::LoadBalancerConfig::round_robin(),
2010 steps: vec![BuilderStep::To("mock:l1".into())],
2011 },
2012 BuilderStep::DynamicRouter {
2013 config: DynamicRouterConfig::new(TargetSource::Sync(Arc::new(|_| {
2014 Some("mock:dr".into())
2015 }))),
2016 },
2017 BuilderStep::RoutingSlip {
2018 config: RoutingSlipConfig::new(TargetSource::Sync(Arc::new(|_| {
2019 Some("mock:rs".into())
2020 }))),
2021 },
2022 ];
2023
2024 for step in steps {
2025 let dbg = format!("{step:?}");
2026 assert!(!dbg.is_empty());
2027 }
2028 }
2029
2030 #[test]
2031 fn test_route_definition_to_info_preserves_metadata() {
2032 let info = RouteDefinition::new("direct:test", vec![])
2033 .with_route_id("meta-route")
2034 .with_auto_startup(false)
2035 .with_startup_order(7)
2036 .to_info();
2037
2038 assert_eq!(info.route_id(), "meta-route");
2039 assert!(!info.auto_startup());
2040 assert_eq!(info.startup_order(), 7);
2041 }
2042
2043 #[test]
2044 fn test_choice_builder_step_debug() {
2045 use camel_api::FilterPredicate;
2046
2047 fn always_true(_: &camel_api::Exchange) -> bool {
2048 true
2049 }
2050
2051 let step = BuilderStep::Choice {
2052 whens: vec![WhenStep {
2053 predicate: FilterPredicate::new(always_true),
2054 steps: vec![BuilderStep::To("mock:a".into())],
2055 }],
2056 otherwise: None,
2057 };
2058 let debug = format!("{step:?}");
2059 assert!(debug.contains("Choice"));
2060 }
2061
2062 #[test]
2063 fn test_route_definition_unit_of_work() {
2064 use camel_api::UnitOfWorkConfig;
2065 let config = UnitOfWorkConfig {
2066 on_complete: Some("log:complete".into()),
2067 on_failure: Some("log:failed".into()),
2068 };
2069 let def = RouteDefinition::new("direct:test", vec![])
2070 .with_route_id("uow-test")
2071 .with_unit_of_work(config.clone());
2072 assert_eq!(
2073 def.unit_of_work_config().unwrap().on_complete.as_deref(),
2074 Some("log:complete")
2075 );
2076 assert_eq!(
2077 def.unit_of_work_config().unwrap().on_failure.as_deref(),
2078 Some("log:failed")
2079 );
2080
2081 let def_no_uow = RouteDefinition::new("direct:test", vec![]).with_route_id("no-uow");
2082 assert!(def_no_uow.unit_of_work_config().is_none());
2083 }
2084
2085 #[test]
2086 fn test_route_definition_security_policy_accessor() {
2087 use async_trait::async_trait;
2088 use camel_api::CamelError;
2089 use camel_api::Exchange;
2090 use camel_api::security_policy::{
2091 AuthContext, AuthorizationDecision, Principal, SecurityPolicy, SecurityPolicyConfig,
2092 };
2093
2094 struct StubPolicy;
2095 #[async_trait]
2096 impl SecurityPolicy for StubPolicy {
2097 async fn evaluate(
2098 &self,
2099 _exchange: &mut Exchange,
2100 _auth: &AuthContext<'_>,
2101 ) -> Result<AuthorizationDecision, CamelError> {
2102 Ok(AuthorizationDecision::Granted {
2103 principal: Principal {
2104 subject: "test".into(),
2105 issuer: "test".into(),
2106 audience: vec![],
2107 scopes: vec![],
2108 roles: vec![],
2109 claims: serde_json::Value::Null,
2110 },
2111 })
2112 }
2113 }
2114
2115 let def_no_sp = RouteDefinition::new("direct:test", vec![]).with_route_id("no-sp");
2116 assert!(def_no_sp.security_policy_config().is_none());
2117
2118 let def = RouteDefinition::new("direct:test", vec![])
2119 .with_route_id("sp-test")
2120 .with_security_policy(SecurityPolicyConfig::new(StubPolicy));
2121 assert!(def.security_policy_config().is_some());
2122 }
2123
2124 #[test]
2125 fn test_route_definition_security_authenticator_accessor() {
2126 use camel_api::security_policy::Principal;
2127
2128 struct TestAuth;
2129 #[async_trait::async_trait]
2130 impl TokenAuthenticator for TestAuth {
2131 async fn authenticate_bearer(
2132 &self,
2133 _token: &str,
2134 ) -> Result<Principal, camel_api::CamelError> {
2135 Ok(Principal {
2136 subject: "test".into(),
2137 issuer: "test".into(),
2138 audience: vec![],
2139 scopes: vec![],
2140 roles: vec![],
2141 claims: serde_json::Value::Null,
2142 })
2143 }
2144 }
2145
2146 let def_no_auth = RouteDefinition::new("direct:test".to_string(), vec![]);
2147 assert!(def_no_auth.security_authenticator().is_none());
2148
2149 let auth = Arc::new(TestAuth);
2150 let def = RouteDefinition::new("direct:test".to_string(), vec![])
2151 .with_security_authenticator(auth);
2152 assert!(def.security_authenticator().is_some());
2153 }
2154
2155 #[test]
2156 fn test_map_steps_swaps_steps_and_preserves_other_fields() {
2157 let original = RouteDefinition::new(
2158 "direct:test".to_string(),
2159 vec![BuilderStep::To("mock:a".into()), BuilderStep::Stop],
2160 )
2161 .with_route_id("my-route");
2162
2163 let mapped = original.map_steps(|steps| {
2164 let mut out = Vec::with_capacity(steps.len() + 1);
2165 out.push(BuilderStep::To("mock:prefix".into()));
2166 out.extend(steps);
2167 out
2168 });
2169
2170 assert_eq!(mapped.steps().len(), 3);
2172 assert!(matches!(mapped.steps()[0], BuilderStep::To(ref s) if s == "mock:prefix"));
2173 assert!(matches!(mapped.steps()[1], BuilderStep::To(ref s) if s == "mock:a"));
2174 assert_eq!(mapped.route_id(), "my-route");
2176 }
2177
2178 #[test]
2179 fn circuit_breaker_fallback_accessor_returns_steps() {
2180 let def = RouteDefinition::new("direct:start", vec![])
2181 .with_circuit_breaker_fallback(vec![BuilderStep::To("mock:out".into())]);
2182 assert_eq!(def.circuit_breaker_fallback().len(), 1);
2183 }
2184
2185 #[test]
2191 fn builder_step_layered_to_metadata_parity() {
2192 let layered = BuilderStep::LayeredTo {
2193 uri: "kafka:topic".into(),
2194 factory: LayerFactory::new(tower::limit::ConcurrencyLimitLayer::new(2)),
2195 };
2196 let plain = BuilderStep::To("kafka:topic".into());
2197
2198 assert_eq!(layered.span_label(), Some("to:kafka".to_string()));
2199 assert_eq!(layered.to_uri_metadata(), Some(Arc::from("kafka:topic")));
2200 assert_eq!(layered.span_kind_hint(), SpanKindHint::Producer);
2201
2202 assert_eq!(layered.span_label(), plain.span_label());
2204 assert_eq!(layered.to_uri_metadata(), plain.to_uri_metadata());
2205 assert_eq!(layered.span_kind_hint(), plain.span_kind_hint());
2206 }
2207
2208 #[test]
2213 fn builder_step_layered_label_and_internal_hint() {
2214 let step = BuilderStep::Layered {
2215 factory: LayerFactory::new(tower::limit::ConcurrencyLimitLayer::new(2)),
2216 steps: vec![],
2217 };
2218
2219 assert_eq!(step.span_label(), Some("layered".to_string()));
2220 assert_eq!(step.to_uri_metadata(), None);
2221 assert_eq!(step.span_kind_hint(), SpanKindHint::Internal);
2222 }
2223}