Skip to main content

camel_api/
aggregator.rs

1use std::sync::Arc;
2use std::time::Duration;
3
4use crate::error::{CamelError, ConfigValidationError};
5use crate::exchange::Exchange;
6
7/// Aggregation function — left-fold binary: (accumulated, next) -> merged.
8///
9/// ```compile_fail
10/// use std::sync::Arc;
11/// use camel_api::aggregator::AggregationFn;
12/// use camel_api::{Exchange, CamelError};
13/// // A strategy that attempts to signal failure via Result does NOT type-check
14/// // as AggregationFn (whose Fn returns Exchange, not Result<Exchange, CamelError>).
15/// let _: AggregationFn = Arc::new(
16///     |_old: Exchange, _new: Exchange| -> Result<Exchange, CamelError> { unreachable!() }
17/// );
18/// ```
19pub type AggregationFn = Arc<dyn Fn(Exchange, Exchange) -> Exchange + Send + Sync>;
20
21/// Strategy for correlating exchanges into aggregation buckets.
22#[non_exhaustive]
23pub enum CorrelationStrategy {
24    /// Correlate by the value of a named header.
25    HeaderName(String),
26    /// Correlate by evaluating an expression using a language registry.
27    Expression { expr: String, language: String },
28    /// Correlate using a custom function.
29    #[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/// How to combine collected exchanges into one.
61#[derive(Clone)]
62#[non_exhaustive]
63pub enum AggregationStrategy {
64    /// Collects all bodies into Body::Json([body1, body2, ...]).
65    CollectAll,
66    /// Left-fold: f(f(ex1, ex2), ex3), ...
67    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/// When the bucket is considered complete and should be emitted.
80#[derive(Clone)]
81#[non_exhaustive]
82pub enum CompletionCondition {
83    /// Emit when bucket reaches exactly N exchanges.
84    Size(usize),
85    /// Emit when predicate returns true for current bucket.
86    #[allow(clippy::type_complexity)]
87    Predicate(Arc<dyn Fn(&[Exchange]) -> bool + Send + Sync>),
88    /// Configuration-time counterpart to `Predicate`: carries a serialized
89    /// language expression (`expr` + `language`) resolvable via the language
90    /// registry at runtime. Unlike `Predicate` (a closure), this variant is
91    /// declarable from YAML/DSL. The serializable wire representation lives
92    /// on `CanonicalAggregateSpec.completion_predicate`.
93    PredicateExpr { expr: String, language: String },
94    /// Emit when the bucket has been inactive for the given duration.
95    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/// Determines how a bucket's completion is evaluated.
114/// `Single` wraps one condition; `Any` completes when the first condition triggers.
115#[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/// Configuration for the Aggregator EIP.
152#[derive(Clone)]
153pub struct AggregatorConfig {
154    /// Name of the header used as correlation key.
155    pub header_name: String,
156    /// When to emit the aggregated exchange.
157    pub completion: CompletionMode,
158    /// Strategy for determining correlation keys.
159    pub correlation: CorrelationStrategy,
160    /// How to combine the bucket into one exchange.
161    pub strategy: AggregationStrategy,
162    /// Maximum number of correlation key buckets (memory protection).
163    /// When limit is reached, new correlation keys are rejected.
164    pub max_buckets: Option<usize>,
165    /// Time-to-live for inactive buckets (memory protection).
166    /// Buckets not updated for this duration are evicted.
167    pub bucket_ttl: Option<Duration>,
168    /// Force-complete all pending buckets when the route is stopped.
169    pub force_completion_on_stop: bool,
170    /// Discard bucket contents on timeout instead of emitting.
171    pub discard_on_timeout: bool,
172    /// Maximum number of concurrently-live per-bucket timeout tasks (DoS cap, R3-M3).
173    /// When the cap is reached, new buckets skip the dedicated timeout spawn and
174    /// rely on `bucket_ttl` eviction (graceful degradation under a key flood).
175    /// Default 1024.
176    pub max_timeout_tasks: usize,
177}
178
179impl std::fmt::Debug for AggregatorConfig {
180    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
181        f.debug_struct("AggregatorConfig")
182            .field("header_name", &self.header_name)
183            .field("completion", &self.completion)
184            .field("correlation", &self.correlation)
185            .field("strategy", &self.strategy)
186            .field("max_buckets", &self.max_buckets)
187            .field("bucket_ttl", &self.bucket_ttl)
188            .field("force_completion_on_stop", &self.force_completion_on_stop)
189            .field("discard_on_timeout", &self.discard_on_timeout)
190            .field("max_timeout_tasks", &self.max_timeout_tasks)
191            .finish()
192    }
193}
194
195impl AggregatorConfig {
196    /// Start building config with correlation key extracted from the named header.
197    pub fn correlate_by(header: impl Into<String>) -> AggregatorConfigBuilder {
198        let header_name = header.into();
199        AggregatorConfigBuilder {
200            header_name: header_name.clone(),
201            completion: None,
202            correlation: CorrelationStrategy::HeaderName(header_name),
203            strategy: AggregationStrategy::CollectAll,
204            // R3-C1 Batch 1: bounded defaults — the correlation map MUST NOT
205            // grow without a cap. A flood of unique correlation keys is the
206            // remote-OOM vector; the default cap (10_000) is a sane production
207            // ceiling the operator may still override. The TTL (5 minutes) is
208            // the inline-retain + background-sweep eviction window.
209            max_buckets: Some(10_000),
210            bucket_ttl: Some(Duration::from_secs(300)),
211            force_completion_on_stop: false,
212            discard_on_timeout: false,
213            // R3-M3: cap concurrently-live per-bucket timeout tasks.
214            max_timeout_tasks: 1024,
215        }
216    }
217
218    /// Validate that at least one memory-release bound is configured (R3-M2).
219    ///
220    /// At least one of `max_buckets`, a `Timeout` completion condition, or
221    /// `bucket_ttl` MUST be set, otherwise a flood of unique correlation keys
222    /// grows the bucket map without limit (remote-OOM vector).
223    ///
224    /// Additionally, when a `Timeout` completion condition is present,
225    /// `bucket_ttl` MUST also be set. The R3-M3 timeout-task cap may skip
226    /// spawning a dedicated timeout task under flood; without `bucket_ttl`
227    /// there is no fallback eviction path and the bucket leaks until shutdown.
228    /// Requiring `bucket_ttl` whenever Timeout is present makes the cap-skip
229    /// degradation safe by construction.
230    pub fn validate(&self) -> Result<(), CamelError> {
231        let has_timeout = match &self.completion {
232            CompletionMode::Single(CompletionCondition::Timeout(_)) => true,
233            CompletionMode::Any(conds) => conds
234                .iter()
235                .any(|c| matches!(c, CompletionCondition::Timeout(_))),
236            _ => false,
237        };
238        let has_bound = self.max_buckets.is_some() || has_timeout || self.bucket_ttl.is_some();
239        if !has_bound {
240            return Err(CamelError::from(
241                ConfigValidationError::AggregatorMissingMemoryBound,
242            ));
243        }
244        // R3-M3: Timeout completion requires bucket_ttl so the cap-skip
245        // degradation always has an eviction path.
246        if has_timeout && self.bucket_ttl.is_none() {
247            return Err(CamelError::from(
248                ConfigValidationError::AggregatorTimeoutRequiresTtl,
249            ));
250        }
251        Ok(())
252    }
253}
254
255/// Builder for `AggregatorConfig`.
256pub struct AggregatorConfigBuilder {
257    header_name: String,
258    completion: Option<CompletionMode>,
259    correlation: CorrelationStrategy,
260    strategy: AggregationStrategy,
261    max_buckets: Option<usize>,
262    bucket_ttl: Option<Duration>,
263    force_completion_on_stop: bool,
264    discard_on_timeout: bool,
265    max_timeout_tasks: usize,
266}
267
268impl AggregatorConfigBuilder {
269    /// Emit when bucket has N exchanges.
270    pub fn complete_when_size(mut self, n: usize) -> Self {
271        self.completion = Some(CompletionMode::Single(CompletionCondition::Size(n)));
272        self
273    }
274
275    /// Emit when predicate returns true for the current bucket.
276    pub fn complete_when<F>(mut self, predicate: F) -> Self
277    where
278        F: Fn(&[Exchange]) -> bool + Send + Sync + 'static,
279    {
280        self.completion = Some(CompletionMode::Single(CompletionCondition::Predicate(
281            Arc::new(predicate),
282        )));
283        self
284    }
285
286    /// Emit when the bucket has been inactive for the given duration.
287    pub fn complete_on_timeout(mut self, duration: Duration) -> Self {
288        self.completion = Some(CompletionMode::Single(CompletionCondition::Timeout(
289            duration,
290        )));
291        self
292    }
293
294    /// Emit when the bucket reaches `size` OR has been inactive for `timeout`.
295    pub fn complete_on_size_or_timeout(mut self, size: usize, timeout: Duration) -> Self {
296        self.completion = Some(CompletionMode::Any(vec![
297            CompletionCondition::Size(size),
298            CompletionCondition::Timeout(timeout),
299        ]));
300        self
301    }
302
303    /// Enable force-completion of pending buckets when the route is stopped.
304    pub fn force_completion_on_stop(mut self, enabled: bool) -> Self {
305        self.force_completion_on_stop = enabled;
306        self
307    }
308
309    /// Discard bucket contents on timeout instead of emitting the aggregated exchange.
310    pub fn discard_on_timeout(mut self, enabled: bool) -> Self {
311        self.discard_on_timeout = enabled;
312        self
313    }
314
315    /// Override the correlation strategy with a header-based key.
316    pub fn correlate_by(mut self, header: impl Into<String>) -> Self {
317        let header = header.into();
318        self.header_name = header.clone();
319        self.correlation = CorrelationStrategy::HeaderName(header);
320        self
321    }
322
323    /// Override the default `CollectAll` aggregation strategy.
324    pub fn strategy(mut self, strategy: AggregationStrategy) -> Self {
325        self.strategy = strategy;
326        self
327    }
328
329    /// Set the maximum number of correlation key buckets.
330    /// When the limit is reached, new correlation keys are rejected with an error.
331    pub fn max_buckets(mut self, max: usize) -> Self {
332        self.max_buckets = Some(max);
333        self
334    }
335
336    /// Set the time-to-live for inactive buckets.
337    /// Buckets that haven't been updated for this duration will be evicted.
338    pub fn bucket_ttl(mut self, ttl: Duration) -> Self {
339        self.bucket_ttl = Some(ttl);
340        self
341    }
342
343    /// Override the maximum number of concurrently-live per-bucket timeout tasks.
344    pub fn max_timeout_tasks(mut self, max: usize) -> Self {
345        self.max_timeout_tasks = max;
346        self
347    }
348
349    pub fn try_build(self) -> Result<AggregatorConfig, CamelError> {
350        // R3-C1 Batch 1: a completion-bound is mandatory. A config with no
351        // completion bound lets a bucket live forever — combined with a
352        // unique-key flood, that is the remote-OOM vector. Typed
353        // ConfigValidationError (ADR-0033) — operators can match on the
354        // `AggregatorMissingCompletionBound` variant.
355        let completion = self.completion.ok_or_else(|| {
356            CamelError::from(ConfigValidationError::AggregatorMissingCompletionBound)
357        })?;
358        Ok(AggregatorConfig {
359            header_name: self.header_name,
360            completion,
361            correlation: self.correlation,
362            strategy: self.strategy,
363            max_buckets: self.max_buckets,
364            bucket_ttl: self.bucket_ttl,
365            force_completion_on_stop: self.force_completion_on_stop,
366            discard_on_timeout: self.discard_on_timeout,
367            max_timeout_tasks: self.max_timeout_tasks,
368        })
369    }
370
371    /// Build the config. Returns an error if no completion condition was set.
372    pub fn build(self) -> Result<AggregatorConfig, CamelError> {
373        self.try_build()
374    }
375}
376
377#[cfg(test)]
378mod tests {
379    use super::*;
380
381    #[test]
382    fn test_aggregator_config_complete_when_size() {
383        let config = AggregatorConfig::correlate_by("orderId")
384            .complete_when_size(3)
385            .build()
386            .unwrap();
387        assert_eq!(config.header_name, "orderId");
388        assert!(matches!(
389            config.completion,
390            CompletionMode::Single(CompletionCondition::Size(3))
391        ));
392        assert!(matches!(config.strategy, AggregationStrategy::CollectAll));
393    }
394
395    #[test]
396    fn test_aggregator_config_complete_when_predicate() {
397        let config = AggregatorConfig::correlate_by("key")
398            .complete_when(|bucket| bucket.len() >= 2)
399            .build()
400            .unwrap();
401        assert!(matches!(
402            config.completion,
403            CompletionMode::Single(CompletionCondition::Predicate(_))
404        ));
405    }
406
407    #[test]
408    fn test_aggregator_config_custom_strategy() {
409        use std::sync::Arc;
410        let f: AggregationFn = Arc::new(|acc, _next| acc);
411        let config = AggregatorConfig::correlate_by("key")
412            .complete_when_size(1)
413            .strategy(AggregationStrategy::Custom(f))
414            .build()
415            .unwrap();
416        assert!(matches!(config.strategy, AggregationStrategy::Custom(_)));
417    }
418
419    #[test]
420    fn test_aggregator_config_missing_completion_returns_err() {
421        let result = AggregatorConfig::correlate_by("key").build();
422        let err = match result {
423            Err(e) => e,
424            Ok(_) => panic!("expected error, got Ok"),
425        };
426        assert!(
427            err.to_string().contains("completion"),
428            "error message should mention 'completion': {err}"
429        );
430    }
431
432    #[test]
433    fn test_complete_on_size_or_timeout() {
434        let config = AggregatorConfig::correlate_by("key")
435            .complete_on_size_or_timeout(3, Duration::from_secs(5))
436            .build()
437            .unwrap();
438        assert!(matches!(config.completion, CompletionMode::Any(v) if v.len() == 2));
439    }
440
441    #[test]
442    fn test_force_completion_on_stop_default() {
443        let config = AggregatorConfig::correlate_by("key")
444            .complete_when_size(1)
445            .build()
446            .unwrap();
447        assert!(!config.force_completion_on_stop);
448        assert!(!config.discard_on_timeout);
449    }
450
451    #[test]
452    fn test_builder_sets_timeout_and_flags_and_limits() {
453        let config = AggregatorConfig::correlate_by("key")
454            .complete_on_timeout(Duration::from_secs(2))
455            .max_buckets(7)
456            .bucket_ttl(Duration::from_secs(10))
457            .force_completion_on_stop(true)
458            .discard_on_timeout(true)
459            .build()
460            .unwrap();
461
462        assert!(matches!(
463            config.completion,
464            CompletionMode::Single(CompletionCondition::Timeout(d)) if d == Duration::from_secs(2)
465        ));
466        assert_eq!(config.max_buckets, Some(7));
467        assert_eq!(config.bucket_ttl, Some(Duration::from_secs(10)));
468        assert!(config.force_completion_on_stop);
469        assert!(config.discard_on_timeout);
470    }
471
472    #[test]
473    fn test_builder_correlate_by_overrides_header_and_strategy() {
474        let config = AggregatorConfig::correlate_by("original")
475            .correlate_by("override")
476            .complete_when_size(1)
477            .build()
478            .unwrap();
479
480        assert_eq!(config.header_name, "override");
481        assert!(matches!(
482            config.correlation,
483            CorrelationStrategy::HeaderName(ref h) if h == "override"
484        ));
485    }
486
487    #[test]
488    fn test_completion_reason_as_str_all_variants() {
489        assert_eq!(CompletionReason::Size.as_str(), "size");
490        assert_eq!(CompletionReason::Predicate.as_str(), "predicate");
491        assert_eq!(CompletionReason::Timeout.as_str(), "timeout");
492        assert_eq!(CompletionReason::Stop.as_str(), "stop");
493    }
494
495    #[test]
496    fn test_correlation_strategy_clone_and_debug() {
497        let strategy = CorrelationStrategy::Expression {
498            expr: "${header.orderId}".to_string(),
499            language: "simple".to_string(),
500        };
501        let cloned = strategy.clone();
502        assert!(matches!(
503            cloned,
504            CorrelationStrategy::Expression { ref expr, ref language }
505                if expr == "${header.orderId}" && language == "simple"
506        ));
507
508        let f = CorrelationStrategy::Fn(Arc::new(|_| Some("k".to_string())));
509        assert_eq!(format!("{:?}", f), "Fn(..)");
510    }
511
512    #[test]
513    fn completion_condition_predicate_expr_debug_and_clone() {
514        let c = CompletionCondition::PredicateExpr {
515            expr: "${body} == 'DONE'".to_string(),
516            language: "simple".to_string(),
517        };
518        let debugged = format!("{:?}", c);
519        assert!(debugged.contains("PredicateExpr"), "debug: {}", debugged);
520        assert!(debugged.contains("DONE"), "debug: {}", debugged);
521        // Clone must compile (the enum derives Clone).
522        let _cloned = c.clone();
523    }
524
525    #[test]
526    fn test_complete_on_size_or_timeout_contains_both_conditions() {
527        let config = AggregatorConfig::correlate_by("k")
528            .complete_on_size_or_timeout(4, Duration::from_millis(250))
529            .build()
530            .unwrap();
531
532        match config.completion {
533            CompletionMode::Any(conditions) => {
534                assert!(matches!(conditions[0], CompletionCondition::Size(4)));
535                assert!(matches!(
536                    conditions[1],
537                    CompletionCondition::Timeout(d) if d == Duration::from_millis(250)
538                ));
539            }
540            _ => panic!("expected CompletionMode::Any"),
541        }
542    }
543
544    #[test]
545    #[allow(clippy::type_complexity)]
546    fn test_correlation_strategy_fn_clone_shares_same_arc() {
547        let f: Arc<dyn Fn(&Exchange) -> Option<String> + Send + Sync> =
548            Arc::new(|_| Some("shared".to_string()));
549        let strategy = CorrelationStrategy::Fn(f.clone());
550        let cloned = strategy.clone();
551
552        match cloned {
553            CorrelationStrategy::Fn(cloned_fn) => assert!(Arc::ptr_eq(&f, &cloned_fn)),
554            _ => panic!("expected fn strategy"),
555        }
556    }
557
558    #[test]
559    fn test_builder_correlate_by_overrides_previous() {
560        let config = AggregatorConfig::correlate_by("first")
561            .correlate_by("second")
562            .complete_when_size(2)
563            .build()
564            .unwrap();
565
566        assert_eq!(config.header_name, "second");
567        assert!(
568            matches!(config.correlation, CorrelationStrategy::HeaderName(ref h) if h == "second")
569        );
570    }
571
572    #[test]
573    fn test_aggregator_try_build_missing_completion_returns_error() {
574        let result = AggregatorConfig::correlate_by("key").try_build();
575        assert!(result.is_err());
576    }
577
578    // ── R3-C1 Batch 1: DoS caps + completion-bound validation ────────
579
580    /// The builder default for `max_buckets` is `Some(10_000)`. The spec fixes
581    /// this as the bounded default; the operator may still override.
582    #[test]
583    fn test_default_max_buckets_is_10000() {
584        let cfg = AggregatorConfig::correlate_by("k")
585            .complete_when_size(1)
586            .build()
587            .unwrap();
588        assert_eq!(cfg.max_buckets, Some(10_000));
589    }
590
591    /// The builder default for `bucket_ttl` is `Some(Duration::from_secs(300))`.
592    /// Inline retain + background sweep both use this TTL.
593    #[test]
594    fn test_default_bucket_ttl_is_300s() {
595        let cfg = AggregatorConfig::correlate_by("k")
596            .complete_when_size(1)
597            .build()
598            .unwrap();
599        assert_eq!(cfg.bucket_ttl, Some(Duration::from_secs(300)));
600    }
601
602    /// Configs that override `max_buckets(0)` still build (the operator chose it).
603    /// The cap may be set to 1 by the operator; the bound itself is not validated.
604    /// The completion-bound check below is what Batch 1 enforces.
605    #[test]
606    fn test_explicit_max_buckets_zero_is_accepted_at_build() {
607        let cfg = AggregatorConfig::correlate_by("k")
608            .complete_when_size(1)
609            .max_buckets(0)
610            .build()
611            .unwrap();
612        assert_eq!(cfg.max_buckets, Some(0));
613    }
614
615    /// A config with no completion bound — neither size, nor timeout, nor predicate —
616    /// is rejected at `try_build` with `AggregatorMissingCompletionBound`. Spec §11
617    /// RESOLVED: at least one completion bound is mandatory.
618    #[test]
619    fn test_aggregator_rejects_no_completion_bound() {
620        // Builder has no `complete_*` call → try_build returns Err.
621        // Use match (not unwrap_err) because AggregatorConfig is not Debug.
622        let err = match AggregatorConfig::correlate_by("k").try_build() {
623            Err(e) => e,
624            Ok(_) => panic!("expected error, got Ok"),
625        };
626        assert!(
627            matches!(
628                err,
629                CamelError::ConfigValidation(
630                    ConfigValidationError::AggregatorMissingCompletionBound
631                )
632            ),
633            "expected ConfigValidation(AggregatorMissingCompletionBound), got: {err}"
634        );
635    }
636
637    // ── R3-M2: memory-bound validation ────────────────────────────────
638
639    #[test]
640    fn test_aggregator_config_rejects_no_memory_bound() {
641        // Direct construction bypassing the builder defaults — simulate a config
642        // with no max_buckets, no timeout, no ttl.
643        let config = AggregatorConfig {
644            header_name: "k".into(),
645            completion: CompletionMode::Single(CompletionCondition::Size(2)),
646            correlation: CorrelationStrategy::HeaderName("k".into()),
647            strategy: AggregationStrategy::CollectAll,
648            max_buckets: None,
649            bucket_ttl: None,
650            force_completion_on_stop: false,
651            discard_on_timeout: false,
652            max_timeout_tasks: 1024,
653        };
654        let err = config.validate().unwrap_err();
655        assert!(
656            err.to_string().contains("max_buckets")
657                || err.to_string().contains("completionTimeout")
658                || err.to_string().contains("bucket_ttl"),
659            "error should explain the required bound: {err}"
660        );
661    }
662
663    /// D-A5: typed-variant pin — the exact `AggregatorMissingMemoryBound`
664    /// variant, not a substring match. ADR-0033 contract: operators may match
665    /// on the typed variant for structured error handling.
666    #[test]
667    fn test_da5_validate_returns_typed_missing_memory_bound_variant() {
668        let config = AggregatorConfig {
669            header_name: "k".into(),
670            completion: CompletionMode::Single(CompletionCondition::Size(2)),
671            correlation: CorrelationStrategy::HeaderName("k".into()),
672            strategy: AggregationStrategy::CollectAll,
673            max_buckets: None,
674            bucket_ttl: None,
675            force_completion_on_stop: false,
676            discard_on_timeout: false,
677            max_timeout_tasks: 1024,
678        };
679        let err = config.validate().unwrap_err();
680        assert!(
681            matches!(
682                err,
683                CamelError::ConfigValidation(ConfigValidationError::AggregatorMissingMemoryBound)
684            ),
685            "expected ConfigValidation(AggregatorMissingMemoryBound), got: {err}"
686        );
687    }
688
689    #[test]
690    fn test_aggregator_config_accepts_size_only_with_max_buckets() {
691        // Builder path defaults max_buckets + bucket_ttl — must validate OK.
692        let config = AggregatorConfig::correlate_by("k")
693            .complete_when_size(2)
694            .build()
695            .unwrap();
696        assert!(config.validate().is_ok());
697    }
698
699    /// R3-M3: Timeout completion requires bucket_ttl so the cap-skip
700    /// degradation always has an eviction path. A config with Timeout but
701    /// no bucket_ttl is rejected by validate().
702    #[test]
703    fn test_aggregator_timeout_requires_bucket_ttl() {
704        let config = AggregatorConfig {
705            header_name: "k".into(),
706            completion: CompletionMode::Single(CompletionCondition::Timeout(Duration::from_secs(
707                5,
708            ))),
709            correlation: CorrelationStrategy::HeaderName("k".into()),
710            strategy: AggregationStrategy::CollectAll,
711            max_buckets: Some(100),
712            bucket_ttl: None, // <-- missing ttl fallback
713            force_completion_on_stop: false,
714            discard_on_timeout: false,
715            max_timeout_tasks: 1024,
716        };
717        let err = config.validate().unwrap_err();
718        assert!(
719            err.to_string().contains("bucket_ttl") || err.to_string().contains("Timeout"),
720            "error should explain the timeout-requires-ttl invariant: {err}"
721        );
722    }
723}