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