1use std::sync::Arc;
2use std::time::Duration;
3
4use crate::error::{CamelError, ConfigValidationError};
5use crate::exchange::Exchange;
6
7pub type AggregationFn = Arc<dyn Fn(Exchange, Exchange) -> Exchange + Send + Sync>;
20
21#[non_exhaustive]
23pub enum CorrelationStrategy {
24 HeaderName(String),
26 Expression { expr: String, language: String },
28 #[allow(clippy::type_complexity)]
30 Fn(Arc<dyn Fn(&Exchange) -> Option<String> + Send + Sync>),
31}
32
33impl std::fmt::Debug for CorrelationStrategy {
34 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
35 match self {
36 CorrelationStrategy::HeaderName(h) => f.debug_tuple("HeaderName").field(h).finish(),
37 CorrelationStrategy::Expression { expr, language } => f
38 .debug_struct("Expression")
39 .field("expr", expr)
40 .field("language", language)
41 .finish(),
42 CorrelationStrategy::Fn(_) => f.write_str("Fn(..)"),
43 }
44 }
45}
46
47impl Clone for CorrelationStrategy {
48 fn clone(&self) -> Self {
49 match self {
50 CorrelationStrategy::HeaderName(h) => CorrelationStrategy::HeaderName(h.clone()),
51 CorrelationStrategy::Expression { expr, language } => CorrelationStrategy::Expression {
52 expr: expr.clone(),
53 language: language.clone(),
54 },
55 CorrelationStrategy::Fn(f) => CorrelationStrategy::Fn(Arc::clone(f)),
56 }
57 }
58}
59
60#[derive(Clone)]
62#[non_exhaustive]
63pub enum AggregationStrategy {
64 CollectAll,
66 Custom(AggregationFn),
68}
69
70impl std::fmt::Debug for AggregationStrategy {
71 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
72 match self {
73 AggregationStrategy::CollectAll => f.write_str("CollectAll"),
74 AggregationStrategy::Custom(_) => f.write_str("Custom(..)"),
75 }
76 }
77}
78
79#[derive(Clone)]
81#[non_exhaustive]
82pub enum CompletionCondition {
83 Size(usize),
85 #[allow(clippy::type_complexity)]
87 Predicate(Arc<dyn Fn(&[Exchange]) -> bool + Send + Sync>),
88 PredicateExpr { expr: String, language: String },
94 Timeout(Duration),
96}
97
98impl std::fmt::Debug for CompletionCondition {
99 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
100 match self {
101 CompletionCondition::Size(n) => f.debug_tuple("Size").field(n).finish(),
102 CompletionCondition::Predicate(_) => f.write_str("Predicate(..)"),
103 CompletionCondition::PredicateExpr { expr, language } => f
104 .debug_struct("PredicateExpr")
105 .field("expr", expr)
106 .field("language", language)
107 .finish(),
108 CompletionCondition::Timeout(d) => f.debug_tuple("Timeout").field(d).finish(),
109 }
110 }
111}
112
113#[derive(Clone)]
116#[non_exhaustive]
117pub enum CompletionMode {
118 Single(CompletionCondition),
119 Any(Vec<CompletionCondition>),
120}
121
122impl std::fmt::Debug for CompletionMode {
123 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
124 match self {
125 CompletionMode::Single(c) => f.debug_tuple("Single").field(c).finish(),
126 CompletionMode::Any(conds) => f.debug_tuple("Any").field(conds).finish(),
127 }
128 }
129}
130
131#[derive(Debug, Clone, PartialEq, Eq)]
132#[non_exhaustive]
133pub enum CompletionReason {
134 Size,
135 Predicate,
136 Timeout,
137 Stop,
138}
139
140impl CompletionReason {
141 pub fn as_str(&self) -> &'static str {
142 match self {
143 CompletionReason::Size => "size",
144 CompletionReason::Predicate => "predicate",
145 CompletionReason::Timeout => "timeout",
146 CompletionReason::Stop => "stop",
147 }
148 }
149}
150
151#[derive(Clone)]
153pub struct AggregatorConfig {
154 pub header_name: String,
156 pub completion: CompletionMode,
158 pub correlation: CorrelationStrategy,
160 pub strategy: AggregationStrategy,
162 pub max_buckets: Option<usize>,
165 pub max_bucket_size: Option<usize>,
173 pub bucket_ttl: Option<Duration>,
176 pub force_completion_on_stop: bool,
178 pub discard_on_timeout: bool,
180 pub max_timeout_tasks: usize,
185}
186
187impl std::fmt::Debug for AggregatorConfig {
188 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
189 f.debug_struct("AggregatorConfig")
190 .field("header_name", &self.header_name)
191 .field("completion", &self.completion)
192 .field("correlation", &self.correlation)
193 .field("strategy", &self.strategy)
194 .field("max_buckets", &self.max_buckets)
195 .field("max_bucket_size", &self.max_bucket_size)
196 .field("bucket_ttl", &self.bucket_ttl)
197 .field("force_completion_on_stop", &self.force_completion_on_stop)
198 .field("discard_on_timeout", &self.discard_on_timeout)
199 .field("max_timeout_tasks", &self.max_timeout_tasks)
200 .finish()
201 }
202}
203
204impl AggregatorConfig {
205 pub fn correlate_by(header: impl Into<String>) -> AggregatorConfigBuilder {
207 let header_name = header.into();
208 AggregatorConfigBuilder {
209 header_name: header_name.clone(),
210 completion: None,
211 correlation: CorrelationStrategy::HeaderName(header_name),
212 strategy: AggregationStrategy::CollectAll,
213 max_buckets: Some(10_000),
219 max_bucket_size: Some(10_000),
221 bucket_ttl: Some(Duration::from_secs(300)),
222 force_completion_on_stop: false,
223 discard_on_timeout: false,
224 max_timeout_tasks: 1024,
226 }
227 }
228
229 pub fn validate(&self) -> Result<(), CamelError> {
242 let has_timeout = match &self.completion {
243 CompletionMode::Single(CompletionCondition::Timeout(_)) => true,
244 CompletionMode::Any(conds) => conds
245 .iter()
246 .any(|c| matches!(c, CompletionCondition::Timeout(_))),
247 _ => false,
248 };
249 let has_bound = self.max_buckets.is_some() || has_timeout || self.bucket_ttl.is_some();
250 if !has_bound {
251 return Err(CamelError::from(
252 ConfigValidationError::AggregatorMissingMemoryBound,
253 ));
254 }
255 if has_timeout && self.bucket_ttl.is_none() {
258 return Err(CamelError::from(
259 ConfigValidationError::AggregatorTimeoutRequiresTtl,
260 ));
261 }
262 Ok(())
263 }
264}
265
266pub struct AggregatorConfigBuilder {
268 header_name: String,
269 completion: Option<CompletionMode>,
270 correlation: CorrelationStrategy,
271 strategy: AggregationStrategy,
272 max_buckets: Option<usize>,
273 max_bucket_size: Option<usize>,
274 bucket_ttl: Option<Duration>,
275 force_completion_on_stop: bool,
276 discard_on_timeout: bool,
277 max_timeout_tasks: usize,
278}
279
280impl AggregatorConfigBuilder {
281 pub fn complete_when_size(mut self, n: usize) -> Self {
283 self.completion = Some(CompletionMode::Single(CompletionCondition::Size(n)));
284 self
285 }
286
287 pub fn complete_when<F>(mut self, predicate: F) -> Self
289 where
290 F: Fn(&[Exchange]) -> bool + Send + Sync + 'static,
291 {
292 self.completion = Some(CompletionMode::Single(CompletionCondition::Predicate(
293 Arc::new(predicate),
294 )));
295 self
296 }
297
298 pub fn complete_on_timeout(mut self, duration: Duration) -> Self {
300 self.completion = Some(CompletionMode::Single(CompletionCondition::Timeout(
301 duration,
302 )));
303 self
304 }
305
306 pub fn complete_on_size_or_timeout(mut self, size: usize, timeout: Duration) -> Self {
308 self.completion = Some(CompletionMode::Any(vec![
309 CompletionCondition::Size(size),
310 CompletionCondition::Timeout(timeout),
311 ]));
312 self
313 }
314
315 pub fn force_completion_on_stop(mut self, enabled: bool) -> Self {
317 self.force_completion_on_stop = enabled;
318 self
319 }
320
321 pub fn discard_on_timeout(mut self, enabled: bool) -> Self {
323 self.discard_on_timeout = enabled;
324 self
325 }
326
327 pub fn correlate_by(mut self, header: impl Into<String>) -> Self {
329 let header = header.into();
330 self.header_name = header.clone();
331 self.correlation = CorrelationStrategy::HeaderName(header);
332 self
333 }
334
335 pub fn strategy(mut self, strategy: AggregationStrategy) -> Self {
337 self.strategy = strategy;
338 self
339 }
340
341 pub fn max_buckets(mut self, max: usize) -> Self {
344 self.max_buckets = Some(max);
345 self
346 }
347
348 pub fn max_bucket_size(mut self, max: usize) -> Self {
352 self.max_bucket_size = Some(max);
353 self
354 }
355
356 pub fn bucket_ttl(mut self, ttl: Duration) -> Self {
359 self.bucket_ttl = Some(ttl);
360 self
361 }
362
363 pub fn max_timeout_tasks(mut self, max: usize) -> Self {
365 self.max_timeout_tasks = max;
366 self
367 }
368
369 pub fn try_build(self) -> Result<AggregatorConfig, CamelError> {
370 let completion = self.completion.ok_or_else(|| {
376 CamelError::from(ConfigValidationError::AggregatorMissingCompletionBound)
377 })?;
378 Ok(AggregatorConfig {
379 header_name: self.header_name,
380 completion,
381 correlation: self.correlation,
382 strategy: self.strategy,
383 max_buckets: self.max_buckets,
384 max_bucket_size: self.max_bucket_size,
385 bucket_ttl: self.bucket_ttl,
386 force_completion_on_stop: self.force_completion_on_stop,
387 discard_on_timeout: self.discard_on_timeout,
388 max_timeout_tasks: self.max_timeout_tasks,
389 })
390 }
391
392 pub fn build(self) -> Result<AggregatorConfig, CamelError> {
394 self.try_build()
395 }
396}
397
398#[cfg(test)]
399mod tests {
400 use super::*;
401
402 #[test]
403 fn test_aggregator_config_complete_when_size() {
404 let config = AggregatorConfig::correlate_by("orderId")
405 .complete_when_size(3)
406 .build()
407 .unwrap();
408 assert_eq!(config.header_name, "orderId");
409 assert!(matches!(
410 config.completion,
411 CompletionMode::Single(CompletionCondition::Size(3))
412 ));
413 assert!(matches!(config.strategy, AggregationStrategy::CollectAll));
414 }
415
416 #[test]
417 fn test_aggregator_config_complete_when_predicate() {
418 let config = AggregatorConfig::correlate_by("key")
419 .complete_when(|bucket| bucket.len() >= 2)
420 .build()
421 .unwrap();
422 assert!(matches!(
423 config.completion,
424 CompletionMode::Single(CompletionCondition::Predicate(_))
425 ));
426 }
427
428 #[test]
429 fn test_aggregator_config_custom_strategy() {
430 use std::sync::Arc;
431 let f: AggregationFn = Arc::new(|acc, _next| acc);
432 let config = AggregatorConfig::correlate_by("key")
433 .complete_when_size(1)
434 .strategy(AggregationStrategy::Custom(f))
435 .build()
436 .unwrap();
437 assert!(matches!(config.strategy, AggregationStrategy::Custom(_)));
438 }
439
440 #[test]
441 fn test_aggregator_config_missing_completion_returns_err() {
442 let result = AggregatorConfig::correlate_by("key").build();
443 let err = match result {
444 Err(e) => e,
445 Ok(_) => panic!("expected error, got Ok"),
446 };
447 assert!(
448 err.to_string().contains("completion"),
449 "error message should mention 'completion': {err}"
450 );
451 }
452
453 #[test]
454 fn test_complete_on_size_or_timeout() {
455 let config = AggregatorConfig::correlate_by("key")
456 .complete_on_size_or_timeout(3, Duration::from_secs(5))
457 .build()
458 .unwrap();
459 assert!(matches!(config.completion, CompletionMode::Any(v) if v.len() == 2));
460 }
461
462 #[test]
463 fn test_force_completion_on_stop_default() {
464 let config = AggregatorConfig::correlate_by("key")
465 .complete_when_size(1)
466 .build()
467 .unwrap();
468 assert!(!config.force_completion_on_stop);
469 assert!(!config.discard_on_timeout);
470 }
471
472 #[test]
473 fn test_builder_sets_timeout_and_flags_and_limits() {
474 let config = AggregatorConfig::correlate_by("key")
475 .complete_on_timeout(Duration::from_secs(2))
476 .max_buckets(7)
477 .bucket_ttl(Duration::from_secs(10))
478 .force_completion_on_stop(true)
479 .discard_on_timeout(true)
480 .build()
481 .unwrap();
482
483 assert!(matches!(
484 config.completion,
485 CompletionMode::Single(CompletionCondition::Timeout(d)) if d == Duration::from_secs(2)
486 ));
487 assert_eq!(config.max_buckets, Some(7));
488 assert_eq!(config.bucket_ttl, Some(Duration::from_secs(10)));
489 assert!(config.force_completion_on_stop);
490 assert!(config.discard_on_timeout);
491 }
492
493 #[test]
494 fn test_builder_correlate_by_overrides_header_and_strategy() {
495 let config = AggregatorConfig::correlate_by("original")
496 .correlate_by("override")
497 .complete_when_size(1)
498 .build()
499 .unwrap();
500
501 assert_eq!(config.header_name, "override");
502 assert!(matches!(
503 config.correlation,
504 CorrelationStrategy::HeaderName(ref h) if h == "override"
505 ));
506 }
507
508 #[test]
509 fn test_completion_reason_as_str_all_variants() {
510 assert_eq!(CompletionReason::Size.as_str(), "size");
511 assert_eq!(CompletionReason::Predicate.as_str(), "predicate");
512 assert_eq!(CompletionReason::Timeout.as_str(), "timeout");
513 assert_eq!(CompletionReason::Stop.as_str(), "stop");
514 }
515
516 #[test]
517 fn test_correlation_strategy_clone_and_debug() {
518 let strategy = CorrelationStrategy::Expression {
519 expr: "${header.orderId}".to_string(),
520 language: "simple".to_string(),
521 };
522 let cloned = strategy.clone();
523 assert!(matches!(
524 cloned,
525 CorrelationStrategy::Expression { ref expr, ref language }
526 if expr == "${header.orderId}" && language == "simple"
527 ));
528
529 let f = CorrelationStrategy::Fn(Arc::new(|_| Some("k".to_string())));
530 assert_eq!(format!("{:?}", f), "Fn(..)");
531 }
532
533 #[test]
534 fn completion_condition_predicate_expr_debug_and_clone() {
535 let c = CompletionCondition::PredicateExpr {
536 expr: "${body} == 'DONE'".to_string(),
537 language: "simple".to_string(),
538 };
539 let debugged = format!("{:?}", c);
540 assert!(debugged.contains("PredicateExpr"), "debug: {}", debugged);
541 assert!(debugged.contains("DONE"), "debug: {}", debugged);
542 let _cloned = c.clone();
544 }
545
546 #[test]
547 fn test_complete_on_size_or_timeout_contains_both_conditions() {
548 let config = AggregatorConfig::correlate_by("k")
549 .complete_on_size_or_timeout(4, Duration::from_millis(250))
550 .build()
551 .unwrap();
552
553 match config.completion {
554 CompletionMode::Any(conditions) => {
555 assert!(matches!(conditions[0], CompletionCondition::Size(4)));
556 assert!(matches!(
557 conditions[1],
558 CompletionCondition::Timeout(d) if d == Duration::from_millis(250)
559 ));
560 }
561 _ => panic!("expected CompletionMode::Any"),
562 }
563 }
564
565 #[test]
566 #[allow(clippy::type_complexity)]
567 fn test_correlation_strategy_fn_clone_shares_same_arc() {
568 let f: Arc<dyn Fn(&Exchange) -> Option<String> + Send + Sync> =
569 Arc::new(|_| Some("shared".to_string()));
570 let strategy = CorrelationStrategy::Fn(f.clone());
571 let cloned = strategy.clone();
572
573 match cloned {
574 CorrelationStrategy::Fn(cloned_fn) => assert!(Arc::ptr_eq(&f, &cloned_fn)),
575 _ => panic!("expected fn strategy"),
576 }
577 }
578
579 #[test]
580 fn test_builder_correlate_by_overrides_previous() {
581 let config = AggregatorConfig::correlate_by("first")
582 .correlate_by("second")
583 .complete_when_size(2)
584 .build()
585 .unwrap();
586
587 assert_eq!(config.header_name, "second");
588 assert!(
589 matches!(config.correlation, CorrelationStrategy::HeaderName(ref h) if h == "second")
590 );
591 }
592
593 #[test]
594 fn test_aggregator_try_build_missing_completion_returns_error() {
595 let result = AggregatorConfig::correlate_by("key").try_build();
596 assert!(result.is_err());
597 }
598
599 #[test]
604 fn test_default_max_buckets_is_10000() {
605 let cfg = AggregatorConfig::correlate_by("k")
606 .complete_when_size(1)
607 .build()
608 .unwrap();
609 assert_eq!(cfg.max_buckets, Some(10_000));
610 }
611
612 #[test]
615 fn test_default_bucket_ttl_is_300s() {
616 let cfg = AggregatorConfig::correlate_by("k")
617 .complete_when_size(1)
618 .build()
619 .unwrap();
620 assert_eq!(cfg.bucket_ttl, Some(Duration::from_secs(300)));
621 }
622
623 #[test]
627 fn test_explicit_max_buckets_zero_is_accepted_at_build() {
628 let cfg = AggregatorConfig::correlate_by("k")
629 .complete_when_size(1)
630 .max_buckets(0)
631 .build()
632 .unwrap();
633 assert_eq!(cfg.max_buckets, Some(0));
634 }
635
636 #[test]
640 fn test_aggregator_rejects_no_completion_bound() {
641 let err = match AggregatorConfig::correlate_by("k").try_build() {
644 Err(e) => e,
645 Ok(_) => panic!("expected error, got Ok"),
646 };
647 assert!(
648 matches!(
649 err,
650 CamelError::ConfigValidation(
651 ConfigValidationError::AggregatorMissingCompletionBound
652 )
653 ),
654 "expected ConfigValidation(AggregatorMissingCompletionBound), got: {err}"
655 );
656 }
657
658 #[test]
661 fn test_aggregator_config_rejects_no_memory_bound() {
662 let config = AggregatorConfig {
665 header_name: "k".into(),
666 completion: CompletionMode::Single(CompletionCondition::Size(2)),
667 correlation: CorrelationStrategy::HeaderName("k".into()),
668 strategy: AggregationStrategy::CollectAll,
669 max_buckets: None,
670 max_bucket_size: None,
671 bucket_ttl: None,
672 force_completion_on_stop: false,
673 discard_on_timeout: false,
674 max_timeout_tasks: 1024,
675 };
676 let err = config.validate().unwrap_err();
677 assert!(
678 err.to_string().contains("max_buckets")
679 || err.to_string().contains("completionTimeout")
680 || err.to_string().contains("bucket_ttl"),
681 "error should explain the required bound: {err}"
682 );
683 }
684
685 #[test]
689 fn test_da5_validate_returns_typed_missing_memory_bound_variant() {
690 let config = AggregatorConfig {
691 header_name: "k".into(),
692 completion: CompletionMode::Single(CompletionCondition::Size(2)),
693 correlation: CorrelationStrategy::HeaderName("k".into()),
694 strategy: AggregationStrategy::CollectAll,
695 max_buckets: None,
696 max_bucket_size: None,
697 bucket_ttl: None,
698 force_completion_on_stop: false,
699 discard_on_timeout: false,
700 max_timeout_tasks: 1024,
701 };
702 let err = config.validate().unwrap_err();
703 assert!(
704 matches!(
705 err,
706 CamelError::ConfigValidation(ConfigValidationError::AggregatorMissingMemoryBound)
707 ),
708 "expected ConfigValidation(AggregatorMissingMemoryBound), got: {err}"
709 );
710 }
711
712 #[test]
713 fn test_aggregator_config_accepts_size_only_with_max_buckets() {
714 let config = AggregatorConfig::correlate_by("k")
716 .complete_when_size(2)
717 .build()
718 .unwrap();
719 assert!(config.validate().is_ok());
720 }
721
722 #[test]
726 fn test_aggregator_timeout_requires_bucket_ttl() {
727 let config = AggregatorConfig {
728 header_name: "k".into(),
729 completion: CompletionMode::Single(CompletionCondition::Timeout(Duration::from_secs(
730 5,
731 ))),
732 correlation: CorrelationStrategy::HeaderName("k".into()),
733 strategy: AggregationStrategy::CollectAll,
734 max_buckets: Some(100),
735 max_bucket_size: None,
736 bucket_ttl: None, force_completion_on_stop: false,
738 discard_on_timeout: false,
739 max_timeout_tasks: 1024,
740 };
741 let err = config.validate().unwrap_err();
742 assert!(
743 err.to_string().contains("bucket_ttl") || err.to_string().contains("Timeout"),
744 "error should explain the timeout-requires-ttl invariant: {err}"
745 );
746 }
747}