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}
441
442impl BuilderStep {
443 pub(crate) fn span_label(&self) -> Option<String> {
458 match self {
459 Self::Processor(_) | Self::Stop => None,
461
462 Self::To(uri) => uri.contains(':').then(|| {
463 let scheme = uri.split(':').next().unwrap_or_default();
464 format!("to:{scheme}")
465 }),
466
467 Self::LayeredTo { uri, .. } => uri.contains(':').then(|| {
469 let scheme = uri.split(':').next().unwrap_or_default();
470 format!("to:{scheme}")
471 }),
472
473 Self::Log { .. } | Self::DeclarativeLog { .. } => Some("log".into()),
474
475 Self::DeclarativeSetHeader { .. } => Some("set-header".into()),
476 Self::DeclarativeSetHeaderIfAbsent { .. } => Some("set-header-if-absent".into()),
477 Self::DeclarativeThrow { .. } => Some("throw".into()),
478 Self::DeclarativeRemoveHeader { .. } => Some("remove-header".into()),
479 Self::DeclarativeSetProperty { .. } => Some("set-property".into()),
480 Self::DeclarativeSetBody { .. } => Some("set-body".into()),
481
482 Self::DeclarativeFilter { .. } | Self::Filter { .. } => Some("filter".into()),
483 Self::DeclarativeChoice { .. } | Self::Choice { .. } => Some("choice".into()),
484 Self::DeclarativeScript { .. } | Self::Script { .. } => Some("script".into()),
485 Self::DeclarativeFunction { .. } => Some("function".into()),
486
487 Self::DeclarativeSplit { .. }
488 | Self::DeclarativeStreamSplit { .. }
489 | Self::StreamSplit { .. }
490 | Self::Split { .. } => Some("split".into()),
491
492 Self::DeclarativeDynamicRouter { .. } | Self::DynamicRouter { .. } => {
493 Some("dynamic-router".into())
494 }
495 Self::DeclarativeRoutingSlip { .. } | Self::RoutingSlip { .. } => {
496 Some("routing-slip".into())
497 }
498 Self::DeclarativeRecipientList { .. } | Self::RecipientList { .. } => {
499 Some("recipient-list".into())
500 }
501
502 Self::Aggregate { .. } => Some("aggregate".into()),
503 Self::WireTap { .. } => Some("wire-tap".into()),
504 Self::Multicast { .. } => Some("multicast".into()),
505 Self::Bean { .. } => Some("bean".into()),
506 Self::Throttle { .. } => Some("throttle".into()),
507 Self::LoadBalance { .. } => Some("load-balance".into()),
508 Self::Delay { .. } => Some("delay".into()),
509 Self::Loop { .. } | Self::DeclarativeLoop { .. } => Some("loop".into()),
510 Self::Enrich { .. } => Some("enrich".into()),
511 Self::PollEnrich { .. } => Some("poll-enrich".into()),
512 Self::Validate { .. } => Some("validate".into()),
513 Self::ClaimCheck { .. } => Some("claim-check".into()),
514 Self::Sampling { .. } => Some("sampling".into()),
515 Self::Sort { .. } => Some("sort".into()),
516 Self::IdempotentConsumer { .. } => Some("idempotent-consumer".into()),
517 Self::Cache { .. } => Some("cache".into()),
518 Self::CacheInvalidate { .. } => Some("cache-invalidate".into()),
519 Self::CacheClear { .. } => Some("cache-clear".into()),
520 Self::CacheStats { .. } => Some("cache-stats".into()),
521 Self::CachePeekStale { .. } => Some("cache-peek-stale".into()),
522 Self::DeclarativeDoTry { .. } | Self::DoTry { .. } => Some("do-try".into()),
523 Self::Resequence { .. } => Some("resequence".into()),
524 Self::Layered { .. } => Some("layered".into()),
525 }
526 }
527
528 pub(crate) fn to_uri_metadata(&self) -> Option<Arc<str>> {
540 match self {
541 Self::To(uri) => Some(Arc::from(uri.as_str())),
542 Self::LayeredTo { uri, .. } => Some(Arc::from(uri.as_str())),
543
544 Self::Processor(..)
548 | Self::Stop
549 | Self::Log { .. }
550 | Self::DeclarativeSetHeader { .. }
551 | Self::DeclarativeSetHeaderIfAbsent { .. }
552 | Self::DeclarativeThrow { .. }
553 | Self::DeclarativeRemoveHeader { .. }
554 | Self::DeclarativeSetProperty { .. }
555 | Self::DeclarativeSetBody { .. }
556 | Self::DeclarativeFilter { .. }
557 | Self::DeclarativeChoice { .. }
558 | Self::DeclarativeScript { .. }
559 | Self::DeclarativeFunction { .. }
560 | Self::DeclarativeSplit { .. }
561 | Self::DeclarativeStreamSplit { .. }
562 | Self::StreamSplit { .. }
563 | Self::DeclarativeDynamicRouter { .. }
564 | Self::DeclarativeRoutingSlip { .. }
565 | Self::Split { .. }
566 | Self::Aggregate { .. }
567 | Self::Filter { .. }
568 | Self::Choice { .. }
569 | Self::Multicast { .. }
570 | Self::DeclarativeLog { .. }
571 | Self::Bean { .. }
572 | Self::Script { .. }
573 | Self::Throttle { .. }
574 | Self::LoadBalance { .. }
575 | Self::DynamicRouter { .. }
576 | Self::RoutingSlip { .. }
577 | Self::RecipientList { .. }
578 | Self::DeclarativeRecipientList { .. }
579 | Self::Delay { .. }
580 | Self::Loop { .. }
581 | Self::DeclarativeLoop { .. }
582 | Self::Enrich { .. }
583 | Self::PollEnrich { .. }
584 | Self::WireTap { .. }
585 | Self::Validate { .. }
586 | Self::ClaimCheck { .. }
587 | Self::Sampling { .. }
588 | Self::Sort { .. }
589 | Self::IdempotentConsumer { .. }
590 | Self::Cache { .. }
591 | Self::CacheInvalidate { .. }
592 | Self::CacheClear { .. }
593 | Self::CacheStats { .. }
594 | Self::CachePeekStale { .. }
595 | Self::DeclarativeDoTry { .. }
596 | Self::DoTry { .. }
597 | Self::Layered { .. }
598 | Self::Resequence { .. } => None,
599 }
600 }
601
602 pub(crate) fn span_kind_hint(&self) -> SpanKindHint {
619 match self {
620 Self::To(uri)
622 | Self::LayeredTo { uri, .. }
623 | Self::Enrich { uri, .. }
624 | Self::PollEnrich { uri, .. }
625 | Self::WireTap { uri, .. } => uri_span_kind(uri),
626
627 Self::Processor(..)
631 | Self::Stop
632 | Self::Log { .. }
633 | Self::DeclarativeSetHeader { .. }
634 | Self::DeclarativeSetHeaderIfAbsent { .. }
635 | Self::DeclarativeThrow { .. }
636 | Self::DeclarativeRemoveHeader { .. }
637 | Self::DeclarativeSetProperty { .. }
638 | Self::DeclarativeSetBody { .. }
639 | Self::DeclarativeFilter { .. }
640 | Self::DeclarativeChoice { .. }
641 | Self::DeclarativeScript { .. }
642 | Self::DeclarativeFunction { .. }
643 | Self::DeclarativeSplit { .. }
644 | Self::DeclarativeStreamSplit { .. }
645 | Self::StreamSplit { .. }
646 | Self::DeclarativeDynamicRouter { .. }
647 | Self::DeclarativeRoutingSlip { .. }
648 | Self::Split { .. }
649 | Self::Aggregate { .. }
650 | Self::Filter { .. }
651 | Self::Choice { .. }
652 | Self::Multicast { .. }
653 | Self::DeclarativeLog { .. }
654 | Self::Bean { .. }
655 | Self::Script { .. }
656 | Self::Throttle { .. }
657 | Self::LoadBalance { .. }
658 | Self::DynamicRouter { .. }
659 | Self::RoutingSlip { .. }
660 | Self::RecipientList { .. }
661 | Self::DeclarativeRecipientList { .. }
662 | Self::Delay { .. }
663 | Self::Loop { .. }
664 | Self::DeclarativeLoop { .. }
665 | Self::Validate { .. }
666 | Self::ClaimCheck { .. }
667 | Self::Sampling { .. }
668 | Self::Sort { .. }
669 | Self::IdempotentConsumer { .. }
670 | Self::Cache { .. }
671 | Self::CacheInvalidate { .. }
672 | Self::CacheClear { .. }
673 | Self::CacheStats { .. }
674 | Self::CachePeekStale { .. }
675 | Self::DeclarativeDoTry { .. }
676 | Self::DoTry { .. }
677 | Self::Layered { .. }
678 | Self::Resequence { .. } => SpanKindHint::Internal,
679 }
680 }
681}
682
683fn uri_span_kind(uri: &str) -> SpanKindHint {
690 const PRODUCER_SCHEMES: [&str; 5] = ["kafka", "jms", "activemq", "artemis", "mqtt"];
692 const CLIENT_SCHEMES: [&str; 12] = [
694 "http",
695 "https",
696 "grpc",
697 "grpcs",
698 "ws",
699 "redis",
700 "opensearch",
701 "sql",
702 "surrealdb",
703 "cxf",
704 "llm",
705 "mcp",
706 ];
707
708 let scheme = uri.split(':').next().unwrap_or_default();
709 if PRODUCER_SCHEMES
710 .iter()
711 .any(|s| s.eq_ignore_ascii_case(scheme))
712 {
713 SpanKindHint::Producer
714 } else if CLIENT_SCHEMES
715 .iter()
716 .any(|s| s.eq_ignore_ascii_case(scheme))
717 {
718 SpanKindHint::Client
719 } else {
720 SpanKindHint::Internal
721 }
722}
723
724pub struct RouteDefinition {
726 pub(crate) from_uri: String,
727 pub(crate) steps: Vec<BuilderStep>,
728 pub(crate) error_handler: Option<ErrorHandlerConfig>,
730 pub(crate) circuit_breaker: Option<CircuitBreakerConfig>,
732 pub(crate) circuit_breaker_fallback: Vec<BuilderStep>,
740 pub(crate) security_policy: Option<SecurityPolicyConfig>,
741 pub(crate) security_authenticator: Option<Arc<dyn TokenAuthenticator>>,
743 pub(crate) provider_registry: Option<Arc<camel_auth::ProviderRegistry>>,
746 pub(crate) security_provider: Option<String>,
750 pub(crate) security_audiences: Option<Vec<String>>,
755 pub(crate) unit_of_work: Option<UnitOfWorkConfig>,
757 pub(crate) http_error_mapping: Option<camel_api::HttpErrorMapping>,
764 pub(crate) concurrency: Option<ConcurrencyModel>,
767 pub(crate) route_id: String,
769 pub(crate) auto_startup: bool,
771 pub(crate) startup_order: i32,
773 pub(crate) source_hash: Option<u64>,
774}
775
776impl RouteDefinition {
777 pub fn new(from_uri: impl Into<String>, steps: Vec<BuilderStep>) -> Self {
779 Self {
780 from_uri: from_uri.into(),
781 steps,
782 error_handler: None,
783 circuit_breaker: None,
784 circuit_breaker_fallback: Vec::new(),
785 security_policy: None,
786 security_authenticator: None,
787 provider_registry: None,
788 security_provider: None,
789 security_audiences: None,
790 unit_of_work: None,
791 http_error_mapping: None,
792 concurrency: None,
793 route_id: String::new(), auto_startup: true,
795 startup_order: 1000,
796 source_hash: None,
797 }
798 }
799
800 pub fn from_uri(&self) -> &str {
802 &self.from_uri
803 }
804
805 pub fn steps(&self) -> &[BuilderStep] {
807 &self.steps
808 }
809
810 pub fn circuit_breaker_fallback(&self) -> &[BuilderStep] {
811 &self.circuit_breaker_fallback
812 }
813
814 pub fn map_steps(mut self, f: impl FnOnce(Vec<BuilderStep>) -> Vec<BuilderStep>) -> Self {
819 self.steps = f(self.steps);
820 self
821 }
822
823 pub fn with_error_handler(mut self, config: ErrorHandlerConfig) -> Self {
825 self.error_handler = Some(config);
826 self
827 }
828
829 pub fn error_handler_config(&self) -> Option<&ErrorHandlerConfig> {
831 self.error_handler.as_ref()
832 }
833
834 pub fn with_circuit_breaker(mut self, config: CircuitBreakerConfig) -> Self {
836 self.circuit_breaker = Some(config);
837 self
838 }
839
840 pub fn with_circuit_breaker_fallback(mut self, steps: Vec<BuilderStep>) -> Self {
847 self.circuit_breaker_fallback = steps;
848 self
849 }
850
851 pub fn with_security_policy(mut self, config: SecurityPolicyConfig) -> Self {
853 self.security_policy = Some(config);
854 self
855 }
856
857 pub fn with_security_authenticator(
859 mut self,
860 authenticator: Arc<dyn TokenAuthenticator>,
861 ) -> Self {
862 self.security_authenticator = Some(authenticator);
863 self
864 }
865
866 pub fn with_provider_registry(mut self, registry: Arc<camel_auth::ProviderRegistry>) -> Self {
872 self.provider_registry = Some(registry);
873 self
874 }
875
876 pub fn with_security_provider(mut self, name: impl Into<String>) -> Self {
878 self.security_provider = Some(name.into());
879 self
880 }
881
882 pub fn with_security_audiences(mut self, audiences: Vec<String>) -> Self {
884 self.security_audiences = Some(audiences);
885 self
886 }
887
888 pub fn security_provider(&self) -> Option<&str> {
890 self.security_provider.as_deref()
891 }
892
893 pub fn security_audiences(&self) -> Option<&[String]> {
895 self.security_audiences.as_deref()
896 }
897
898 pub fn with_unit_of_work(mut self, config: UnitOfWorkConfig) -> Self {
900 self.unit_of_work = Some(config);
901 self
902 }
903
904 pub fn with_http_error_mapping(mut self, mapping: camel_api::HttpErrorMapping) -> Self {
909 self.http_error_mapping = Some(mapping);
910 self
911 }
912
913 pub fn http_error_mapping(&self) -> Option<&camel_api::HttpErrorMapping> {
915 self.http_error_mapping.as_ref()
916 }
917
918 pub fn unit_of_work_config(&self) -> Option<&UnitOfWorkConfig> {
920 self.unit_of_work.as_ref()
921 }
922
923 pub fn circuit_breaker_config(&self) -> Option<&CircuitBreakerConfig> {
925 self.circuit_breaker.as_ref()
926 }
927
928 pub fn security_policy_config(&self) -> Option<&SecurityPolicyConfig> {
929 self.security_policy.as_ref()
930 }
931
932 pub fn security_authenticator(&self) -> Option<&Arc<dyn TokenAuthenticator>> {
933 self.security_authenticator.as_ref()
934 }
935
936 pub fn concurrency_override(&self) -> Option<&ConcurrencyModel> {
938 self.concurrency.as_ref()
939 }
940
941 pub fn with_concurrency(mut self, model: ConcurrencyModel) -> Self {
943 self.concurrency = Some(model);
944 self
945 }
946
947 pub fn route_id(&self) -> &str {
949 &self.route_id
950 }
951
952 pub fn auto_startup(&self) -> bool {
954 self.auto_startup
955 }
956
957 pub fn startup_order(&self) -> i32 {
959 self.startup_order
960 }
961
962 pub fn with_route_id(mut self, id: impl Into<String>) -> Self {
964 self.route_id = id.into();
965 self
966 }
967
968 pub fn with_auto_startup(mut self, auto: bool) -> Self {
970 self.auto_startup = auto;
971 self
972 }
973
974 pub fn with_startup_order(mut self, order: i32) -> Self {
976 self.startup_order = order;
977 self
978 }
979
980 pub fn with_source_hash(mut self, hash: u64) -> Self {
981 self.source_hash = Some(hash);
982 self
983 }
984
985 pub fn source_hash(&self) -> Option<u64> {
986 self.source_hash
987 }
988
989 pub fn to_info(&self) -> RouteDefinitionInfo {
992 RouteDefinitionInfo {
993 route_id: self.route_id.clone(),
994 auto_startup: self.auto_startup,
995 startup_order: self.startup_order,
996 source_hash: self.source_hash,
997 }
998 }
999}
1000
1001#[derive(Clone)]
1007pub struct RouteDefinitionInfo {
1008 route_id: String,
1009 auto_startup: bool,
1010 startup_order: i32,
1011 pub(crate) source_hash: Option<u64>,
1012}
1013
1014impl RouteDefinitionInfo {
1015 pub fn route_id(&self) -> &str {
1017 &self.route_id
1018 }
1019
1020 pub fn auto_startup(&self) -> bool {
1022 self.auto_startup
1023 }
1024
1025 pub fn startup_order(&self) -> i32 {
1027 self.startup_order
1028 }
1029
1030 pub fn source_hash(&self) -> Option<u64> {
1031 self.source_hash
1032 }
1033}
1034
1035#[cfg(test)]
1036mod tests {
1037 use super::*;
1038 use camel_api::{RecipientSource, TargetSource};
1039
1040 #[test]
1047 fn builder_step_span_label_mapping() {
1048 use camel_api::declarative::LanguageExpressionDef;
1049 use camel_api::splitter::AggregationStrategy;
1050 use camel_api::{BoxProcessor, IdentityProcessor, OpaqueProcessor};
1051
1052 let expr = LanguageExpressionDef {
1053 language: "simple".into(),
1054 source: "${body}".into(),
1055 };
1056
1057 assert_eq!(
1059 BuilderStep::To("direct:tree-sub".into())
1060 .span_label()
1061 .as_deref(),
1062 Some("to:direct")
1063 );
1064 assert_eq!(
1065 BuilderStep::To("http://api.example/x".into())
1066 .span_label()
1067 .as_deref(),
1068 Some("to:http")
1069 );
1070 assert_eq!(BuilderStep::To("garbage".into()).span_label(), None);
1072
1073 assert_eq!(
1075 BuilderStep::Log {
1076 level: camel_processor::LogLevel::Info,
1077 message: "m".into(),
1078 }
1079 .span_label()
1080 .as_deref(),
1081 Some("log")
1082 );
1083 assert_eq!(
1084 BuilderStep::Split {
1085 config: camel_api::splitter::SplitterConfig::new(
1086 camel_api::splitter::split_body_lines()
1087 ),
1088 steps: vec![BuilderStep::Stop],
1089 }
1090 .span_label()
1091 .as_deref(),
1092 Some("split")
1093 );
1094 assert_eq!(
1095 BuilderStep::DeclarativeSplit {
1096 expression: expr.clone(),
1097 aggregation: AggregationStrategy::Original,
1098 parallel: false,
1099 parallel_limit: None,
1100 trace_item_threshold: None,
1101 stop_on_exception: true,
1102 steps: vec![BuilderStep::Stop],
1103 }
1104 .span_label()
1105 .as_deref(),
1106 Some("split")
1107 );
1108 assert_eq!(
1109 BuilderStep::DeclarativeStreamSplit {
1110 stream_config: camel_api::StreamSplitConfig::default(),
1111 aggregation: AggregationStrategy::Original,
1112 stop_on_exception: true,
1113 steps: vec![BuilderStep::Stop],
1114 }
1115 .span_label()
1116 .as_deref(),
1117 Some("split")
1118 );
1119 assert_eq!(BuilderStep::Stop.span_label(), None);
1120
1121 assert_eq!(
1123 BuilderStep::Processor(OpaqueProcessor(BoxProcessor::new(IdentityProcessor)))
1124 .span_label(),
1125 None
1126 );
1127 }
1128
1129 #[test]
1141 fn builder_step_span_kind_hint_mapping() {
1142 use camel_api::splitter::split_body_lines;
1143 use camel_api::{Exchange, FilterPredicate, SpanKindHint};
1144
1145 let kind = |uri: &str| BuilderStep::To(uri.into()).span_kind_hint();
1146
1147 assert_eq!(kind("kafka:orders"), SpanKindHint::Producer);
1149 assert_eq!(kind("jms:q"), SpanKindHint::Producer);
1150 assert_eq!(kind("activemq:q"), SpanKindHint::Producer);
1151 assert_eq!(kind("artemis:q"), SpanKindHint::Producer);
1152 assert_eq!(kind("mqtt:t"), SpanKindHint::Producer);
1153 assert_eq!(kind("KAFKA:orders"), SpanKindHint::Producer);
1155
1156 assert_eq!(kind("http://x"), SpanKindHint::Client);
1158 assert_eq!(kind("https://x"), SpanKindHint::Client);
1159 assert_eq!(kind("grpc://x"), SpanKindHint::Client);
1160 assert_eq!(kind("grpcs://x"), SpanKindHint::Client);
1161 assert_eq!(kind("ws://x"), SpanKindHint::Client);
1162 assert_eq!(kind("redis://x"), SpanKindHint::Client);
1163 assert_eq!(kind("opensearch://x"), SpanKindHint::Client);
1164 assert_eq!(kind("sql:db"), SpanKindHint::Client);
1165 assert_eq!(kind("surrealdb://x"), SpanKindHint::Client);
1166 assert_eq!(kind("cxf://x"), SpanKindHint::Client);
1167 assert_eq!(kind("llm://x"), SpanKindHint::Client);
1168 assert_eq!(kind("mcp://x"), SpanKindHint::Client);
1169
1170 assert_eq!(kind("direct:y"), SpanKindHint::Internal);
1172 assert_eq!(kind("timer:z"), SpanKindHint::Internal);
1173 assert_eq!(kind("garbage"), SpanKindHint::Internal);
1175
1176 assert_eq!(
1178 BuilderStep::Log {
1179 level: camel_processor::LogLevel::Info,
1180 message: "m".into(),
1181 }
1182 .span_kind_hint(),
1183 SpanKindHint::Internal
1184 );
1185 assert_eq!(
1186 BuilderStep::Filter {
1187 predicate: FilterPredicate::new(|_: &Exchange| true),
1188 steps: vec![BuilderStep::Stop],
1189 }
1190 .span_kind_hint(),
1191 SpanKindHint::Internal
1192 );
1193 assert_eq!(
1194 BuilderStep::Split {
1195 config: camel_api::splitter::SplitterConfig::new(split_body_lines()),
1196 steps: vec![BuilderStep::Stop],
1197 }
1198 .span_kind_hint(),
1199 SpanKindHint::Internal
1200 );
1201
1202 let enrich = |uri: &str| BuilderStep::Enrich {
1206 uri: uri.into(),
1207 strategy: None,
1208 timeout_ms: None,
1209 };
1210 let poll_enrich = |uri: &str| BuilderStep::PollEnrich {
1211 uri: uri.into(),
1212 strategy: None,
1213 timeout_ms: None,
1214 };
1215 let wire_tap = |uri: &str| BuilderStep::WireTap { uri: uri.into() };
1216
1217 assert_eq!(enrich("http://x").span_kind_hint(), SpanKindHint::Client);
1219 assert_eq!(
1220 poll_enrich("http://x").span_kind_hint(),
1221 SpanKindHint::Client
1222 );
1223 assert_eq!(wire_tap("http://x").span_kind_hint(), SpanKindHint::Client);
1224 assert_eq!(
1226 enrich("kafka:orders").span_kind_hint(),
1227 SpanKindHint::Producer
1228 );
1229 assert_eq!(
1230 poll_enrich("kafka:orders").span_kind_hint(),
1231 SpanKindHint::Producer
1232 );
1233 assert_eq!(
1234 wire_tap("kafka:orders").span_kind_hint(),
1235 SpanKindHint::Producer
1236 );
1237 assert_eq!(enrich("direct:y").span_kind_hint(), SpanKindHint::Internal);
1239 assert_eq!(
1240 poll_enrich("seda:q").span_kind_hint(),
1241 SpanKindHint::Internal
1242 );
1243 assert_eq!(
1244 wire_tap("direct:y").span_kind_hint(),
1245 SpanKindHint::Internal
1246 );
1247 }
1248
1249 #[test]
1254 fn golden_debug_output_all_variants() {
1255 use camel_api::declarative::LanguageExpressionDef;
1256 use camel_api::loop_eip::LoopMode;
1257 use camel_api::recipient_list::RecipientListConfig;
1258 use camel_api::splitter::{AggregationStrategy, StreamSplitConfig, StreamSplitFormat};
1259 use camel_api::{
1260 BoxProcessor, DynamicRouterConfig, Exchange, FilterPredicate, FunctionDefinition,
1261 FunctionId, IdentityProcessor, MulticastConfig, OpaqueProcessor, RoutingSlipConfig,
1262 Value,
1263 };
1264 use std::sync::Arc;
1265
1266 let expr = LanguageExpressionDef {
1267 language: "simple".into(),
1268 source: "${body}".into(),
1269 };
1270
1271 assert_eq!(format!("{:?}", BuilderStep::Stop), "Stop");
1274 assert_eq!(
1275 format!(
1276 "{:?}",
1277 BuilderStep::Processor(OpaqueProcessor(BoxProcessor::new(IdentityProcessor)))
1278 ),
1279 "Processor(BoxProcessor(...))"
1280 );
1281 assert_eq!(
1282 format!("{:?}", BuilderStep::To("mock:out".into())),
1283 "To(\"mock:out\")"
1284 );
1285
1286 assert_eq!(
1289 format!(
1290 "{:?}",
1291 BuilderStep::Log {
1292 level: camel_processor::LogLevel::Info,
1293 message: "hello".into(),
1294 }
1295 ),
1296 "Log { level: Info, message: \"hello\" }"
1297 );
1298
1299 assert_eq!(
1300 format!(
1301 "{:?}",
1302 BuilderStep::DeclarativeSetHeader {
1303 key: "k".into(),
1304 value: ValueSourceDef::Literal(Value::String("v".into())),
1305 }
1306 ),
1307 "DeclarativeSetHeader { key: \"k\", value: Literal(String(\"v\")) }"
1308 );
1309
1310 assert_eq!(
1311 format!(
1312 "{:?}",
1313 BuilderStep::DeclarativeSetHeaderIfAbsent {
1314 key: "k".into(),
1315 value: ValueSourceDef::Literal(Value::String("v".into())),
1316 }
1317 ),
1318 "DeclarativeSetHeaderIfAbsent { key: \"k\", value: Literal(String(\"v\")) }"
1319 );
1320
1321 assert_eq!(
1322 format!(
1323 "{:?}",
1324 BuilderStep::DeclarativeSetBody {
1325 value: ValueSourceDef::Literal(Value::String("v".into())),
1326 }
1327 ),
1328 "DeclarativeSetBody { value: Literal(String(\"v\")) }"
1329 );
1330
1331 assert_eq!(
1332 format!(
1333 "{:?}",
1334 BuilderStep::DeclarativeSetProperty {
1335 key: "prop".into(),
1336 value_source: ValueSourceDef::Literal(Value::String("v".into())),
1337 }
1338 ),
1339 "DeclarativeSetProperty { key: \"prop\", value_source: Literal(String(\"v\")) }"
1340 );
1341
1342 assert_eq!(
1343 format!(
1344 "{:?}",
1345 BuilderStep::DeclarativeScript {
1346 expression: expr.clone(),
1347 }
1348 ),
1349 "DeclarativeScript { expression: LanguageExpressionDef { language: \"simple\", source: \"${body}\" } }"
1350 );
1351
1352 let func_def = FunctionDefinition {
1354 id: FunctionId("test-id".into()),
1355 runtime: "my_runtime".into(),
1356 source: "${body}".into(),
1357 timeout_ms: 5000,
1358 route_id: None,
1359 step_index: None,
1360 };
1361 assert_eq!(
1362 format!(
1363 "{:?}",
1364 BuilderStep::DeclarativeFunction {
1365 definition: func_def,
1366 }
1367 ),
1368 "DeclarativeFunction { definition: FunctionDefinition { id: FunctionId(\"test-id\"), runtime: \"my_runtime\", source: \"${body}\", timeout_ms: 5000, route_id: None, step_index: None } }"
1369 );
1370
1371 assert_eq!(
1372 format!(
1373 "{:?}",
1374 BuilderStep::WireTap {
1375 uri: "mock:tap".into(),
1376 }
1377 ),
1378 "WireTap { uri: \"mock:tap\" }"
1379 );
1380
1381 assert_eq!(
1382 format!(
1383 "{:?}",
1384 BuilderStep::DeclarativeLog {
1385 level: camel_processor::LogLevel::Info,
1386 message: ValueSourceDef::Expression(expr.clone()),
1387 }
1388 ),
1389 "DeclarativeLog { level: Info, message: Expression(LanguageExpressionDef { language: \"simple\", source: \"${body}\" }) }"
1390 );
1391
1392 assert_eq!(
1393 format!(
1394 "{:?}",
1395 BuilderStep::Bean {
1396 name: "myBean".into(),
1397 method: "process".into(),
1398 }
1399 ),
1400 "Bean { name: \"myBean\", method: \"process\" }"
1401 );
1402
1403 assert_eq!(
1404 format!(
1405 "{:?}",
1406 BuilderStep::Script {
1407 language: "js".into(),
1408 script: "body".into(),
1409 }
1410 ),
1411 "Script { language: \"js\", script: \"body\" }"
1412 );
1413
1414 assert_eq!(
1415 format!(
1416 "{:?}",
1417 BuilderStep::Aggregate {
1418 config: camel_api::AggregatorConfig::correlate_by("id")
1419 .complete_when_size(1)
1420 .build()
1421 .unwrap(),
1422 }
1423 ),
1424 "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 } }"
1425 );
1426
1427 assert_eq!(
1428 format!(
1429 "{:?}",
1430 BuilderStep::DynamicRouter {
1431 config: DynamicRouterConfig::new(TargetSource::Sync(Arc::new(
1432 |_: &Exchange| Some("mock:dr".into())
1433 ))),
1434 }
1435 ),
1436 "DynamicRouter { config: DynamicRouterConfig { uri_delimiter: \",\", cache_size: 1000, ignore_invalid_endpoints: false, max_iterations: 1000, timeout: Some(60s) } }"
1437 );
1438
1439 assert_eq!(
1440 format!(
1441 "{:?}",
1442 BuilderStep::RoutingSlip {
1443 config: RoutingSlipConfig::new(TargetSource::Sync(Arc::new(|_: &Exchange| {
1444 Some("mock:rs".into())
1445 }))),
1446 }
1447 ),
1448 "RoutingSlip { config: RoutingSlipConfig { uri_delimiter: \",\", cache_size: 1000, ignore_invalid_endpoints: false } }"
1449 );
1450
1451 assert_eq!(
1452 format!(
1453 "{:?}",
1454 BuilderStep::RecipientList {
1455 config: RecipientListConfig::new(RecipientSource::Sync(Arc::new(
1456 |_: &Exchange| String::new()
1457 ))),
1458 }
1459 ),
1460 "RecipientList { config: RecipientListConfig { delimiter: \",\", parallel: false, parallel_limit: None, stop_on_exception: false, max_recipients: 1000 } }"
1461 );
1462
1463 assert_eq!(
1464 format!(
1465 "{:?}",
1466 BuilderStep::Enrich {
1467 uri: "mock:enrich".into(),
1468 strategy: Some("agg".into()),
1469 timeout_ms: Some(1000),
1470 }
1471 ),
1472 "Enrich { uri: \"mock:enrich\", strategy: Some(\"agg\"), timeout_ms: Some(1000) }"
1473 );
1474
1475 assert_eq!(
1476 format!(
1477 "{:?}",
1478 BuilderStep::PollEnrich {
1479 uri: "mock:poll".into(),
1480 strategy: None,
1481 timeout_ms: None,
1482 }
1483 ),
1484 "PollEnrich { uri: \"mock:poll\", strategy: None, timeout_ms: None }"
1485 );
1486
1487 assert_eq!(
1488 format!(
1489 "{:?}",
1490 BuilderStep::Validate {
1491 predicate: expr.clone(),
1492 }
1493 ),
1494 "Validate { predicate: LanguageExpressionDef { language: \"simple\", source: \"${body}\" } }"
1495 );
1496
1497 assert_eq!(
1498 format!("{:?}", BuilderStep::Sampling { period: 100 }),
1499 "Sampling { period: 100 }"
1500 );
1501
1502 assert_eq!(
1503 format!(
1504 "{:?}",
1505 BuilderStep::Resequence {
1506 policy_config: Default::default(),
1507 }
1508 ),
1509 "Resequence { policy_config: ResequencePolicyConfig { mode: Batch { correlation: \"header.id\", sort: \"header.id\", completion: SizeOrTimeout(100, 30000) } } }"
1510 );
1511
1512 assert_eq!(
1514 format!(
1515 "{:?}",
1516 BuilderStep::DeclarativeFilter {
1517 predicate: expr.clone(),
1518 steps: vec![BuilderStep::Stop],
1519 }
1520 ),
1521 "DeclarativeFilter { predicate: LanguageExpressionDef { language: \"simple\", source: \"${body}\" }, steps: [Stop] }"
1522 );
1523
1524 assert_eq!(
1525 format!(
1526 "{:?}",
1527 BuilderStep::DeclarativeSplit {
1528 expression: expr.clone(),
1529 aggregation: AggregationStrategy::Original,
1530 parallel: false,
1531 parallel_limit: Some(2),
1532 trace_item_threshold: None,
1533 stop_on_exception: true,
1534 steps: vec![BuilderStep::Stop],
1535 }
1536 ),
1537 "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] }"
1538 );
1539
1540 assert_eq!(
1541 format!(
1542 "{:?}",
1543 BuilderStep::Split {
1544 config: camel_api::splitter::SplitterConfig::new(
1545 camel_api::splitter::split_body_lines()
1546 ),
1547 steps: vec![BuilderStep::Stop],
1548 }
1549 ),
1550 "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] }"
1551 );
1552
1553 assert_eq!(
1554 format!(
1555 "{:?}",
1556 BuilderStep::Filter {
1557 predicate: FilterPredicate::new(|_: &Exchange| true),
1558 steps: vec![BuilderStep::Stop],
1559 }
1560 ),
1561 "Filter { predicate: FilterPredicate(..), steps: [Stop] }"
1562 );
1563
1564 assert_eq!(
1565 format!(
1566 "{:?}",
1567 BuilderStep::Throttle {
1568 config: camel_api::ThrottlerConfig::new(
1569 10,
1570 std::time::Duration::from_millis(10)
1571 ),
1572 steps: vec![BuilderStep::Stop],
1573 }
1574 ),
1575 "Throttle { config: ThrottlerConfig { max_requests: 10, period: 10ms, strategy: Delay }, steps: [Stop] }"
1576 );
1577
1578 assert_eq!(
1579 format!(
1580 "{:?}",
1581 BuilderStep::LoadBalance {
1582 config: camel_api::LoadBalancerConfig::round_robin(),
1583 steps: vec![BuilderStep::To("mock:l1".into())],
1584 }
1585 ),
1586 "LoadBalance { config: LoadBalancerConfig { strategy: RoundRobin }, steps: [To(\"mock:l1\")] }"
1587 );
1588
1589 assert_eq!(
1590 format!(
1591 "{:?}",
1592 BuilderStep::Delay {
1593 config: camel_api::DelayConfig::new(500),
1594 }
1595 ),
1596 "Delay { config: DelayConfig { delay_ms: 500, dynamic_header: None, max_delay_ms: 3600000 } }"
1597 );
1598
1599 assert_eq!(
1603 format!(
1604 "{:?}",
1605 BuilderStep::Choice {
1606 whens: vec![WhenStep {
1607 predicate: FilterPredicate::new(|_: &Exchange| true),
1608 steps: vec![BuilderStep::To("mock:a".into())],
1609 }],
1610 otherwise: None,
1611 }
1612 ),
1613 "Choice { whens: [WhenStep { predicate: FilterPredicate(..), steps: [To(\"mock:a\")] }], otherwise: None }"
1614 );
1615
1616 assert_eq!(
1617 format!(
1618 "{:?}",
1619 BuilderStep::DeclarativeChoice {
1620 whens: vec![DeclarativeWhenStep {
1621 predicate: expr.clone(),
1622 steps: vec![BuilderStep::Stop],
1623 }],
1624 otherwise: Some(vec![BuilderStep::Stop]),
1625 }
1626 ),
1627 "DeclarativeChoice { whens: [DeclarativeWhenStep { predicate: LanguageExpressionDef { language: \"simple\", source: \"${body}\" }, steps: [Stop] }], otherwise: Some([Stop]) }"
1628 );
1629
1630 assert_eq!(
1632 format!(
1633 "{:?}",
1634 BuilderStep::Multicast {
1635 steps: vec![BuilderStep::To("direct:a".into())],
1636 config: MulticastConfig::new(),
1637 }
1638 ),
1639 "Multicast { steps: [To(\"direct:a\")], config: MulticastConfig { parallel: false, parallel_limit: None, stop_on_exception: false, timeout: None, aggregation: LastWins } }"
1640 );
1641
1642 assert_eq!(
1644 format!(
1645 "{:?}",
1646 BuilderStep::DeclarativeDynamicRouter {
1647 expression: expr.clone(),
1648 uri_delimiter: ",".into(),
1649 cache_size: 1000,
1650 ignore_invalid_endpoints: false,
1651 max_iterations: 1000,
1652 }
1653 ),
1654 "DeclarativeDynamicRouter { expression: LanguageExpressionDef { language: \"simple\", source: \"${body}\" }, uri_delimiter: \",\", cache_size: 1000, ignore_invalid_endpoints: false, max_iterations: 1000 }"
1655 );
1656
1657 assert_eq!(
1658 format!(
1659 "{:?}",
1660 BuilderStep::DeclarativeRoutingSlip {
1661 expression: expr.clone(),
1662 uri_delimiter: ",".into(),
1663 cache_size: 1000,
1664 ignore_invalid_endpoints: false,
1665 }
1666 ),
1667 "DeclarativeRoutingSlip { expression: LanguageExpressionDef { language: \"simple\", source: \"${body}\" }, uri_delimiter: \",\", cache_size: 1000, ignore_invalid_endpoints: false }"
1668 );
1669
1670 assert_eq!(
1672 format!(
1673 "{:?}",
1674 BuilderStep::DeclarativeRecipientList {
1675 expression: expr.clone(),
1676 delimiter: ",".into(),
1677 parallel: false,
1678 parallel_limit: None,
1679 stop_on_exception: false,
1680 aggregation: "original".into(),
1681 }
1682 ),
1683 "DeclarativeRecipientList { expression: LanguageExpressionDef { language: \"simple\", source: \"${body}\" }, delimiter: \",\", parallel: false, parallel_limit: None, stop_on_exception: false, aggregation: \"original\" }"
1684 );
1685
1686 assert_eq!(
1688 format!(
1689 "{:?}",
1690 BuilderStep::Loop {
1691 config: camel_api::loop_eip::LoopConfig::new(LoopMode::Count(3)),
1692 steps: vec![],
1693 }
1694 ),
1695 "Loop { config: LoopConfig { mode: Count(3), max_iterations: 10000 }, steps: [] }"
1696 );
1697
1698 assert_eq!(
1699 format!(
1700 "{:?}",
1701 BuilderStep::DeclarativeLoop {
1702 count: Some(5),
1703 while_predicate: None,
1704 steps: vec![],
1705 max_iterations: Some(100),
1706 }
1707 ),
1708 "DeclarativeLoop { count: Some(5), while_predicate: None, steps: [], max_iterations: Some(100) }"
1709 );
1710
1711 assert_eq!(
1713 format!(
1714 "{:?}",
1715 BuilderStep::ClaimCheck {
1716 repository: "myRepo".into(),
1717 operation: "checkout".into(),
1718 key: expr.clone(),
1719 filter: None,
1720 }
1721 ),
1722 "ClaimCheck { repository: \"myRepo\", operation: \"checkout\", key: LanguageExpressionDef { language: \"simple\", source: \"${body}\" }, filter: None }"
1723 );
1724
1725 assert_eq!(
1727 format!(
1728 "{:?}",
1729 BuilderStep::Sort {
1730 expression: expr.clone(),
1731 reverse: false,
1732 }
1733 ),
1734 "Sort { expression: LanguageExpressionDef { language: \"simple\", source: \"${body}\" }, reverse: false }"
1735 );
1736
1737 assert_eq!(
1739 format!(
1740 "{:?}",
1741 BuilderStep::IdempotentConsumer {
1742 repository: "myRepo".into(),
1743 expression: expr.clone(),
1744 steps: vec![],
1745 eager: true,
1746 remove_on_failure: false,
1747 on_missing_key: camel_processor::OnMissingKey::Fail,
1748 }
1749 ),
1750 "IdempotentConsumer { repository: \"myRepo\", expression: LanguageExpressionDef { language: \"simple\", source: \"${body}\" }, steps: [], eager: true, remove_on_failure: false, on_missing_key: Fail }"
1751 );
1752
1753 assert_eq!(
1755 format!(
1756 "{:?}",
1757 BuilderStep::DeclarativeDoTry {
1758 try_steps: vec![BuilderStep::Stop],
1759 catch: vec![],
1760 finally: None,
1761 }
1762 ),
1763 "DeclarativeDoTry { try_steps: [Stop], catch: [], finally: None }"
1764 );
1765
1766 assert_eq!(
1768 format!(
1769 "{:?}",
1770 BuilderStep::DeclarativeStreamSplit {
1771 stream_config: StreamSplitConfig {
1772 format: StreamSplitFormat::Ndjson,
1773 max_record_bytes: 1024 * 1024,
1774 batch_size: 1,
1775 chunk_size: None,
1776 max_parts: None,
1777 max_part_size: None,
1778 content_types: None,
1779 include_origin: true,
1780 },
1781 aggregation: AggregationStrategy::Original,
1782 stop_on_exception: true,
1783 steps: vec![BuilderStep::Stop],
1784 }
1785 ),
1786 "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] }"
1787 );
1788 }
1789
1790 #[test]
1791 fn test_builder_step_multicast_variant() {
1792 use camel_api::MulticastConfig;
1793
1794 let step = BuilderStep::Multicast {
1795 steps: vec![BuilderStep::To("direct:a".into())],
1796 config: MulticastConfig::new(),
1797 };
1798
1799 assert!(matches!(step, BuilderStep::Multicast { .. }));
1800 }
1801
1802 #[test]
1803 fn test_route_definition_defaults() {
1804 let def = RouteDefinition::new("direct:test", vec![]).with_route_id("test-route");
1805 assert_eq!(def.route_id(), "test-route");
1806 assert!(def.auto_startup());
1807 assert_eq!(def.startup_order(), 1000);
1808 }
1809
1810 #[test]
1811 fn test_route_definition_builders() {
1812 let def = RouteDefinition::new("direct:test", vec![])
1813 .with_route_id("my-route")
1814 .with_auto_startup(false)
1815 .with_startup_order(50);
1816 assert_eq!(def.route_id(), "my-route");
1817 assert!(!def.auto_startup());
1818 assert_eq!(def.startup_order(), 50);
1819 }
1820
1821 #[test]
1822 fn test_route_definition_accessors_cover_core_fields() {
1823 let def = RouteDefinition::new("direct:in", vec![BuilderStep::To("mock:out".into())])
1824 .with_route_id("accessor-route");
1825
1826 assert_eq!(def.from_uri(), "direct:in");
1827 assert_eq!(def.steps().len(), 1);
1828 assert!(matches!(def.steps()[0], BuilderStep::To(_)));
1829 }
1830
1831 #[test]
1832 fn test_route_definition_error_handler_circuit_breaker_and_concurrency_accessors() {
1833 use camel_api::circuit_breaker::CircuitBreakerConfig;
1834 use camel_api::error_handler::ErrorHandlerConfig;
1835 use camel_component_api::ConcurrencyModel;
1836
1837 let def = RouteDefinition::new("direct:test", vec![])
1838 .with_route_id("eh-route")
1839 .with_error_handler(ErrorHandlerConfig::dead_letter_channel("log:dlc"))
1840 .with_circuit_breaker(CircuitBreakerConfig::new())
1841 .with_concurrency(ConcurrencyModel::Concurrent { max: Some(4) });
1842
1843 let eh = def
1844 .error_handler_config()
1845 .expect("error handler should be set");
1846 assert_eq!(eh.dlc_uri.as_deref(), Some("log:dlc"));
1847 assert!(def.circuit_breaker_config().is_some());
1848 assert!(matches!(
1849 def.concurrency_override(),
1850 Some(ConcurrencyModel::Concurrent { max: Some(4) })
1851 ));
1852 }
1853
1854 #[test]
1855 fn test_builder_step_debug_covers_many_variants() {
1856 use camel_api::splitter::{AggregationStrategy, SplitterConfig, split_body_lines};
1857 use camel_api::{
1858 BoxProcessor, DynamicRouterConfig, Exchange, FilterPredicate, IdentityProcessor,
1859 OpaqueProcessor, RoutingSlipConfig, Value,
1860 };
1861 use std::sync::Arc;
1862
1863 let expr = LanguageExpressionDef {
1864 language: "simple".into(),
1865 source: "${body}".into(),
1866 };
1867
1868 let steps = vec![
1869 BuilderStep::Processor(OpaqueProcessor(BoxProcessor::new(IdentityProcessor))),
1870 BuilderStep::To("mock:out".into()),
1871 BuilderStep::Stop,
1872 BuilderStep::Log {
1873 level: camel_processor::LogLevel::Info,
1874 message: "hello".into(),
1875 },
1876 BuilderStep::DeclarativeSetHeader {
1877 key: "k".into(),
1878 value: ValueSourceDef::Literal(Value::String("v".into())),
1879 },
1880 BuilderStep::DeclarativeSetBody {
1881 value: ValueSourceDef::Expression(expr.clone()),
1882 },
1883 BuilderStep::DeclarativeFilter {
1884 predicate: expr.clone(),
1885 steps: vec![BuilderStep::Stop],
1886 },
1887 BuilderStep::DeclarativeChoice {
1888 whens: vec![DeclarativeWhenStep {
1889 predicate: expr.clone(),
1890 steps: vec![BuilderStep::Stop],
1891 }],
1892 otherwise: Some(vec![BuilderStep::Stop]),
1893 },
1894 BuilderStep::DeclarativeScript {
1895 expression: expr.clone(),
1896 },
1897 BuilderStep::DeclarativeSplit {
1898 expression: expr.clone(),
1899 aggregation: AggregationStrategy::Original,
1900 parallel: false,
1901 parallel_limit: Some(2),
1902 trace_item_threshold: None,
1903 stop_on_exception: true,
1904 steps: vec![BuilderStep::Stop],
1905 },
1906 BuilderStep::Split {
1907 config: SplitterConfig::new(split_body_lines()),
1908 steps: vec![BuilderStep::Stop],
1909 },
1910 BuilderStep::Aggregate {
1911 config: camel_api::AggregatorConfig::correlate_by("id")
1912 .complete_when_size(1)
1913 .build()
1914 .unwrap(),
1915 },
1916 BuilderStep::Filter {
1917 predicate: FilterPredicate::new(|_: &Exchange| true),
1918 steps: vec![BuilderStep::Stop],
1919 },
1920 BuilderStep::WireTap {
1921 uri: "mock:tap".into(),
1922 },
1923 BuilderStep::DeclarativeLog {
1924 level: camel_processor::LogLevel::Info,
1925 message: ValueSourceDef::Expression(expr.clone()),
1926 },
1927 BuilderStep::Bean {
1928 name: "bean".into(),
1929 method: "call".into(),
1930 },
1931 BuilderStep::Script {
1932 language: "rhai".into(),
1933 script: "body".into(),
1934 },
1935 BuilderStep::Throttle {
1936 config: camel_api::ThrottlerConfig::new(10, std::time::Duration::from_millis(10)),
1937 steps: vec![BuilderStep::Stop],
1938 },
1939 BuilderStep::LoadBalance {
1940 config: camel_api::LoadBalancerConfig::round_robin(),
1941 steps: vec![BuilderStep::To("mock:l1".into())],
1942 },
1943 BuilderStep::DynamicRouter {
1944 config: DynamicRouterConfig::new(TargetSource::Sync(Arc::new(|_| {
1945 Some("mock:dr".into())
1946 }))),
1947 },
1948 BuilderStep::RoutingSlip {
1949 config: RoutingSlipConfig::new(TargetSource::Sync(Arc::new(|_| {
1950 Some("mock:rs".into())
1951 }))),
1952 },
1953 ];
1954
1955 for step in steps {
1956 let dbg = format!("{step:?}");
1957 assert!(!dbg.is_empty());
1958 }
1959 }
1960
1961 #[test]
1962 fn test_route_definition_to_info_preserves_metadata() {
1963 let info = RouteDefinition::new("direct:test", vec![])
1964 .with_route_id("meta-route")
1965 .with_auto_startup(false)
1966 .with_startup_order(7)
1967 .to_info();
1968
1969 assert_eq!(info.route_id(), "meta-route");
1970 assert!(!info.auto_startup());
1971 assert_eq!(info.startup_order(), 7);
1972 }
1973
1974 #[test]
1975 fn test_choice_builder_step_debug() {
1976 use camel_api::FilterPredicate;
1977
1978 fn always_true(_: &camel_api::Exchange) -> bool {
1979 true
1980 }
1981
1982 let step = BuilderStep::Choice {
1983 whens: vec![WhenStep {
1984 predicate: FilterPredicate::new(always_true),
1985 steps: vec![BuilderStep::To("mock:a".into())],
1986 }],
1987 otherwise: None,
1988 };
1989 let debug = format!("{step:?}");
1990 assert!(debug.contains("Choice"));
1991 }
1992
1993 #[test]
1994 fn test_route_definition_unit_of_work() {
1995 use camel_api::UnitOfWorkConfig;
1996 let config = UnitOfWorkConfig {
1997 on_complete: Some("log:complete".into()),
1998 on_failure: Some("log:failed".into()),
1999 };
2000 let def = RouteDefinition::new("direct:test", vec![])
2001 .with_route_id("uow-test")
2002 .with_unit_of_work(config.clone());
2003 assert_eq!(
2004 def.unit_of_work_config().unwrap().on_complete.as_deref(),
2005 Some("log:complete")
2006 );
2007 assert_eq!(
2008 def.unit_of_work_config().unwrap().on_failure.as_deref(),
2009 Some("log:failed")
2010 );
2011
2012 let def_no_uow = RouteDefinition::new("direct:test", vec![]).with_route_id("no-uow");
2013 assert!(def_no_uow.unit_of_work_config().is_none());
2014 }
2015
2016 #[test]
2017 fn test_route_definition_security_policy_accessor() {
2018 use async_trait::async_trait;
2019 use camel_api::CamelError;
2020 use camel_api::Exchange;
2021 use camel_api::security_policy::{
2022 AuthContext, AuthorizationDecision, Principal, SecurityPolicy, SecurityPolicyConfig,
2023 };
2024
2025 struct StubPolicy;
2026 #[async_trait]
2027 impl SecurityPolicy for StubPolicy {
2028 async fn evaluate(
2029 &self,
2030 _exchange: &mut Exchange,
2031 _auth: &AuthContext<'_>,
2032 ) -> Result<AuthorizationDecision, CamelError> {
2033 Ok(AuthorizationDecision::Granted {
2034 principal: Principal {
2035 subject: "test".into(),
2036 issuer: "test".into(),
2037 audience: vec![],
2038 scopes: vec![],
2039 roles: vec![],
2040 claims: serde_json::Value::Null,
2041 },
2042 })
2043 }
2044 }
2045
2046 let def_no_sp = RouteDefinition::new("direct:test", vec![]).with_route_id("no-sp");
2047 assert!(def_no_sp.security_policy_config().is_none());
2048
2049 let def = RouteDefinition::new("direct:test", vec![])
2050 .with_route_id("sp-test")
2051 .with_security_policy(SecurityPolicyConfig::new(StubPolicy));
2052 assert!(def.security_policy_config().is_some());
2053 }
2054
2055 #[test]
2056 fn test_route_definition_security_authenticator_accessor() {
2057 use camel_api::security_policy::Principal;
2058
2059 struct TestAuth;
2060 #[async_trait::async_trait]
2061 impl TokenAuthenticator for TestAuth {
2062 async fn authenticate_bearer(
2063 &self,
2064 _token: &str,
2065 ) -> Result<Principal, camel_api::CamelError> {
2066 Ok(Principal {
2067 subject: "test".into(),
2068 issuer: "test".into(),
2069 audience: vec![],
2070 scopes: vec![],
2071 roles: vec![],
2072 claims: serde_json::Value::Null,
2073 })
2074 }
2075 }
2076
2077 let def_no_auth = RouteDefinition::new("direct:test".to_string(), vec![]);
2078 assert!(def_no_auth.security_authenticator().is_none());
2079
2080 let auth = Arc::new(TestAuth);
2081 let def = RouteDefinition::new("direct:test".to_string(), vec![])
2082 .with_security_authenticator(auth);
2083 assert!(def.security_authenticator().is_some());
2084 }
2085
2086 #[test]
2087 fn test_map_steps_swaps_steps_and_preserves_other_fields() {
2088 let original = RouteDefinition::new(
2089 "direct:test".to_string(),
2090 vec![BuilderStep::To("mock:a".into()), BuilderStep::Stop],
2091 )
2092 .with_route_id("my-route");
2093
2094 let mapped = original.map_steps(|steps| {
2095 let mut out = Vec::with_capacity(steps.len() + 1);
2096 out.push(BuilderStep::To("mock:prefix".into()));
2097 out.extend(steps);
2098 out
2099 });
2100
2101 assert_eq!(mapped.steps().len(), 3);
2103 assert!(matches!(mapped.steps()[0], BuilderStep::To(ref s) if s == "mock:prefix"));
2104 assert!(matches!(mapped.steps()[1], BuilderStep::To(ref s) if s == "mock:a"));
2105 assert_eq!(mapped.route_id(), "my-route");
2107 }
2108
2109 #[test]
2110 fn circuit_breaker_fallback_accessor_returns_steps() {
2111 let def = RouteDefinition::new("direct:start", vec![])
2112 .with_circuit_breaker_fallback(vec![BuilderStep::To("mock:out".into())]);
2113 assert_eq!(def.circuit_breaker_fallback().len(), 1);
2114 }
2115
2116 #[test]
2122 fn builder_step_layered_to_metadata_parity() {
2123 let layered = BuilderStep::LayeredTo {
2124 uri: "kafka:topic".into(),
2125 factory: LayerFactory::new(tower::limit::ConcurrencyLimitLayer::new(2)),
2126 };
2127 let plain = BuilderStep::To("kafka:topic".into());
2128
2129 assert_eq!(layered.span_label(), Some("to:kafka".to_string()));
2130 assert_eq!(layered.to_uri_metadata(), Some(Arc::from("kafka:topic")));
2131 assert_eq!(layered.span_kind_hint(), SpanKindHint::Producer);
2132
2133 assert_eq!(layered.span_label(), plain.span_label());
2135 assert_eq!(layered.to_uri_metadata(), plain.to_uri_metadata());
2136 assert_eq!(layered.span_kind_hint(), plain.span_kind_hint());
2137 }
2138
2139 #[test]
2144 fn builder_step_layered_label_and_internal_hint() {
2145 let step = BuilderStep::Layered {
2146 factory: LayerFactory::new(tower::limit::ConcurrencyLimitLayer::new(2)),
2147 steps: vec![],
2148 };
2149
2150 assert_eq!(step.span_label(), Some("layered".to_string()));
2151 assert_eq!(step.to_uri_metadata(), None);
2152 assert_eq!(step.span_kind_hint(), SpanKindHint::Internal);
2153 }
2154}