Skip to main content

camel_builder/
lib.rs

1//! Fluent builder API for constructing Camel routes programmatically with EIP patterns.
2//!
3//! Main types: `RouteBuilder`, `StepAccumulator`, `SplitBuilder`, `ChoiceBuilder`, `MulticastBuilder`,
4//! `ThrottleBuilder`, `LoopBuilder`, `LoadBalancerBuilder`, `OnExceptionBuilder`.
5
6use std::collections::BTreeMap;
7use std::sync::Arc;
8
9use camel_api::DelayConfig;
10use camel_api::aggregator::{
11    AggregationStrategy, AggregatorConfig, CompletionCondition, CompletionMode, CorrelationStrategy,
12};
13use camel_api::body::Body;
14use camel_api::body_converter::BodyType;
15use camel_api::circuit_breaker::CircuitBreakerConfig;
16use camel_api::dynamic_router::DynamicRouterConfig;
17use camel_api::error_handler::{ErrorHandlerConfig, RedeliveryPolicy};
18use camel_api::load_balancer::LoadBalancerConfig;
19use camel_api::loop_eip::{LoopConfig, LoopMode};
20use camel_api::multicast::{MulticastConfig, MulticastStrategy};
21use camel_api::recipient_list::RecipientListConfig;
22use camel_api::routing_slip::RoutingSlipConfig;
23use camel_api::splitter::SplitterConfig;
24use camel_api::throttler::{ThrottleStrategy, ThrottlerConfig};
25use camel_api::{
26    BoxProcessor, CamelError, CanonicalRouteSpec, EndpointUri, Exchange, FilterPredicate,
27    IdentityProcessor, LanguageExpressionDef, OpaqueProcessor, ProcessorFn, Value,
28    runtime::{
29        CanonicalAggregateSpec, CanonicalAggregateStrategySpec, CanonicalCircuitBreakerSpec,
30        CanonicalSplitAggregationSpec, CanonicalSplitExpressionSpec, CanonicalStepSpec,
31        CanonicalWhenSpec,
32    },
33};
34use camel_component_api::ConcurrencyModel;
35use camel_core::route::{
36    BuilderStep, DeclarativeWhenStep, RouteDefinition, StreamSplitExpression, WhenStep,
37};
38use camel_processor::{
39    ConvertBodyTo, DynamicSetHeader, LogLevel, MapBody, MarshalService, SetHeader,
40    StreamCacheService, UnmarshalService, builtin_data_format,
41};
42
43// ── Module declarations ─────────────────────────────────────────────────────
44pub mod do_try;
45pub use do_try::{DoCatchBuilder, DoFinallyBuilder, DoTryBuilder};
46
47/// Shared step-accumulation methods for all builder types.
48///
49/// Implementors provide `steps_mut()` and get step-adding methods for free.
50/// `filter()` and other branching methods are NOT included — they return
51/// different types per builder and stay as per-builder methods.
52pub trait StepAccumulator: Sized {
53    fn steps_mut(&mut self) -> &mut Vec<BuilderStep>;
54
55    fn to(mut self, endpoint: impl Into<String>) -> Self {
56        self.steps_mut().push(BuilderStep::To(endpoint.into()));
57        self
58    }
59
60    fn process<F, Fut>(mut self, f: F) -> Self
61    where
62        F: Fn(Exchange) -> Fut + Send + Sync + 'static,
63        Fut: std::future::Future<Output = Result<Exchange, CamelError>> + Send + 'static,
64    {
65        let svc = ProcessorFn::new(f);
66        self.steps_mut()
67            .push(BuilderStep::Processor(OpaqueProcessor(BoxProcessor::new(
68                svc,
69            ))));
70        self
71    }
72
73    fn process_fn(mut self, processor: BoxProcessor) -> Self {
74        self.steps_mut()
75            .push(BuilderStep::Processor(OpaqueProcessor(processor)));
76        self
77    }
78
79    fn set_header(mut self, key: impl Into<String>, value: impl Into<Value>) -> Self {
80        let svc = SetHeader::new(IdentityProcessor, key, value);
81        self.steps_mut()
82            .push(BuilderStep::Processor(OpaqueProcessor(BoxProcessor::new(
83                svc,
84            ))));
85        self
86    }
87
88    fn map_body<F>(mut self, mapper: F) -> Self
89    where
90        F: Fn(Body) -> Body + Clone + Send + Sync + 'static,
91    {
92        let svc = MapBody::new(IdentityProcessor, mapper);
93        self.steps_mut()
94            .push(BuilderStep::Processor(OpaqueProcessor(BoxProcessor::new(
95                svc,
96            ))));
97        self
98    }
99
100    fn set_body<B>(mut self, body: B) -> Self
101    where
102        B: Into<Body> + Clone + Send + Sync + 'static,
103    {
104        let body: Body = body.into();
105        // Static Body (may be Bytes/Stream/Xml): assign directly. The
106        // `SetBody` service is reserved for `Value`-shaped sources —
107        // arbitrary Body variants do not round-trip through `Value`.
108        let svc = ProcessorFn::new(move |mut ex: Exchange| {
109            let body = body.clone();
110            async move {
111                ex.input.body = body;
112                Ok(ex)
113            }
114        });
115        self.steps_mut()
116            .push(BuilderStep::Processor(OpaqueProcessor(BoxProcessor::new(
117                svc,
118            ))));
119        self
120    }
121
122    /// Apache Camel-compatible alias for [`set_body`](Self::set_body).
123    ///
124    /// Transforms the message body using the given value. Semantically identical
125    /// to `set_body` — provided for familiarity with Apache Camel route DSLs.
126    fn transform<B>(self, body: B) -> Self
127    where
128        B: Into<Body> + Clone + Send + Sync + 'static,
129    {
130        self.set_body(body)
131    }
132
133    fn set_body_fn<F>(mut self, expr: F) -> Self
134    where
135        F: Fn(&Exchange) -> Body + Clone + Send + Sync + 'static,
136    {
137        // Body-producing closure: assign directly (see `set_body` for why
138        // this no longer routes through the Value-shaped `SetBody`).
139        let svc = ProcessorFn::new(move |mut ex: Exchange| {
140            let body = expr(&ex);
141            async move {
142                ex.input.body = body;
143                Ok(ex)
144            }
145        });
146        self.steps_mut()
147            .push(BuilderStep::Processor(OpaqueProcessor(BoxProcessor::new(
148                svc,
149            ))));
150        self
151    }
152
153    fn set_header_fn<F>(mut self, key: impl Into<String>, expr: F) -> Self
154    where
155        F: Fn(&Exchange) -> Value + Clone + Send + Sync + 'static,
156    {
157        let svc = DynamicSetHeader::new(
158            IdentityProcessor,
159            key,
160            camel_api::ValueSource::Sync(Arc::new(expr)),
161        );
162        self.steps_mut()
163            .push(BuilderStep::Processor(OpaqueProcessor(BoxProcessor::new(
164                svc,
165            ))));
166        self
167    }
168
169    fn aggregate(mut self, config: AggregatorConfig) -> Self {
170        self.steps_mut().push(BuilderStep::Aggregate { config });
171        self
172    }
173
174    /// Stop processing this exchange immediately. No further steps in the
175    /// current pipeline will run.
176    ///
177    /// Can be used at any point in the route: directly on RouteBuilder,
178    /// inside `.filter()`, inside `.split()`, etc.
179    fn stop(mut self) -> Self {
180        self.steps_mut().push(BuilderStep::Stop);
181        self
182    }
183
184    fn delay(mut self, duration: std::time::Duration) -> Self {
185        self.steps_mut().push(BuilderStep::Delay {
186            config: DelayConfig::from_duration(duration),
187        });
188        self
189    }
190
191    fn delay_with_header(
192        mut self,
193        duration: std::time::Duration,
194        header: impl Into<String>,
195    ) -> Self {
196        self.steps_mut().push(BuilderStep::Delay {
197            config: DelayConfig::from_duration_with_header(duration, header),
198        });
199        self
200    }
201
202    /// Log a message at the specified level.
203    ///
204    /// The message will be logged when an exchange passes through this step.
205    fn log(mut self, message: impl Into<String>, level: LogLevel) -> Self {
206        self.steps_mut().push(BuilderStep::Log {
207            level,
208            message: message.into(),
209        });
210        self
211    }
212
213    /// Convert the message body to the target type.
214    ///
215    /// Supported: Text ↔ Json ↔ Bytes. `Body::Stream` always fails.
216    /// Returns `TypeConversionFailed` if conversion is not possible.
217    ///
218    /// # Example
219    /// ```ignore
220    /// route.set_body(Value::String(r#"{"x":1}"#.into()))
221    ///      .convert_body_to(BodyType::Json)
222    ///      .to("direct:next")
223    /// ```
224    fn convert_body_to(mut self, target: BodyType) -> Self {
225        let svc = ConvertBodyTo::new(IdentityProcessor, target);
226        self.steps_mut()
227            .push(BuilderStep::Processor(OpaqueProcessor(BoxProcessor::new(
228                svc,
229            ))));
230        self
231    }
232
233    fn stream_cache(mut self, threshold: usize) -> Self {
234        let config = camel_api::stream_cache::StreamCacheConfig::new(threshold);
235        let svc = StreamCacheService::new(IdentityProcessor, config);
236        self.steps_mut()
237            .push(BuilderStep::Processor(OpaqueProcessor(BoxProcessor::new(
238                svc,
239            ))));
240        self
241    }
242
243    /// Materialize `Body::Stream` into `Body::Bytes` using the default threshold (128 KB).
244    ///
245    /// Equivalent to `.stream_cache(camel_api::stream_cache::DEFAULT_STREAM_CACHE_THRESHOLD)`.
246    fn stream_cache_default(self) -> Self {
247        self.stream_cache(camel_api::stream_cache::DEFAULT_STREAM_CACHE_THRESHOLD)
248    }
249
250    /// Marshal the message body using the specified data format.
251    ///
252    /// Supported formats: `"json"`, `"xml"`, `"csv"`, `"zip"`, `"tar"`, `"gzip"`, `"tar.gz"`.
253    /// Returns `Err(CamelError::Config)` if the format name is unknown.
254    /// Converts a structured body (e.g., `Body::Json`) to a wire-format body (e.g., `Body::Text`).
255    ///
256    /// # Example
257    /// ```ignore
258    /// route.marshal("json")?.to("direct:next")
259    /// ```
260    fn marshal(mut self, format: impl Into<String>) -> Result<Self, CamelError> {
261        let name = format.into();
262        let df = builtin_data_format(&name)
263            .ok_or_else(|| CamelError::Config(format!("unknown data format: '{name}'")))?;
264        let svc = MarshalService::new(IdentityProcessor, df);
265        self.steps_mut()
266            .push(BuilderStep::Processor(OpaqueProcessor(BoxProcessor::new(
267                svc,
268            ))));
269        Ok(self)
270    }
271
272    /// Unmarshal the message body using the specified data format.
273    ///
274    /// Supported formats: `"json"`, `"xml"`, `"csv"`, `"zip"`, `"tar"`, `"gzip"`, `"tar.gz"`.
275    /// Returns `Err(CamelError::Config)` if the format name is unknown.
276    /// Converts a wire-format body (e.g., `Body::Text`) to a structured body (e.g., `Body::Json`).
277    ///
278    /// # Example
279    /// ```ignore
280    /// route.unmarshal("json")?.to("direct:next")
281    /// ```
282    fn unmarshal(mut self, format: impl Into<String>) -> Result<Self, CamelError> {
283        let name = format.into();
284        let df = builtin_data_format(&name)
285            .ok_or_else(|| CamelError::Config(format!("unknown data format: '{name}'")))?;
286        let svc = UnmarshalService::new(IdentityProcessor, df);
287        self.steps_mut()
288            .push(BuilderStep::Processor(OpaqueProcessor(BoxProcessor::new(
289                svc,
290            ))));
291        Ok(self)
292    }
293
294    /// Validate the exchange using a predicate expression.
295    ///
296    /// If the expression evaluates to `true`, the exchange continues.
297    /// If `false`, a `CamelError::ValidationError` is returned into the route error handler.
298    ///
299    /// # Example
300    /// ```ignore
301    /// route.validate("${body.size()} > 0").to("direct:out")
302    /// ```
303    fn validate(mut self, expression: impl Into<String>) -> Self {
304        let source = expression.into();
305        let expression = LanguageExpressionDef {
306            language: "simple".into(),
307            source,
308        };
309        self.steps_mut().push(BuilderStep::Validate {
310            predicate: expression,
311        });
312        self
313    }
314
315    /// Execute a script that can modify the exchange (headers, properties, body).
316    ///
317    /// The script has access to `headers`, `properties`, and `body` variables
318    /// and can modify them with assignment syntax: `headers["k"] = v`.
319    ///
320    /// # Example
321    /// ```ignore
322    /// // ignore: requires full CamelContext setup with registered language
323    /// route.script("rhai", r#"headers["tenant"] = "acme"; body = body + "_processed""#)
324    /// ```
325    fn script(mut self, language: impl Into<String>, script: impl Into<String>) -> Self {
326        self.steps_mut().push(BuilderStep::Script {
327            language: language.into(),
328            script: script.into(),
329        });
330        self
331    }
332
333    /// EIP-7 enrich: synchronous content enrichment via a resolved producer.
334    ///
335    /// Calls the given endpoint URI as a producer, then merges the response
336    /// back into the original exchange body using the default `UseEnrichedBody`
337    /// strategy (original headers/properties are preserved).
338    fn enrich(mut self, uri: impl Into<String>) -> Self {
339        self.steps_mut().push(BuilderStep::Enrich {
340            uri: uri.into(),
341            strategy: None,
342            timeout_ms: None,
343        });
344        self
345    }
346
347    /// EIP-7 pollEnrich: blocking poll of a PollingConsumer with timeout.
348    ///
349    /// Reads from a polling endpoint (e.g., file) and merges the result
350    /// into the exchange body using the default `UseEnrichedBody` strategy.
351    /// `timeout_ms` controls how long to wait for data.
352    fn poll_enrich(mut self, uri: impl Into<String>, timeout_ms: u64) -> Self {
353        self.steps_mut().push(BuilderStep::PollEnrich {
354            uri: uri.into(),
355            strategy: None,
356            timeout_ms: Some(timeout_ms),
357        });
358        self
359    }
360
361    fn bean(mut self, name: impl Into<String>, method: impl Into<String>) -> Self {
362        self.steps_mut().push(BuilderStep::Bean {
363            name: name.into(),
364            method: method.into(),
365        });
366        self
367    }
368}
369
370/// Identifies the endpoint slot a `.parameters()` call attaches to.
371#[derive(Debug, Clone, PartialEq, Eq)]
372enum EndpointSlot {
373    /// The route's `from` endpoint.
374    From,
375    /// A step in `RouteBuilder::steps`, by index.
376    Step(usize),
377}
378
379/// A fluent builder for constructing routes.
380///
381/// # Example
382///
383/// ```ignore
384/// let definition = RouteBuilder::from("timer:tick?period=1000")
385///     .set_header("source", Value::String("timer".into()))
386///     .filter(|ex| ex.input.body.as_text().is_some())
387///     .to("log:info?showHeaders=true")
388///     .build()?;
389/// ```
390/// `RouteBuilder` is `Clone`: a partially-built route can be cloned and reused as a
391/// template for multiple routes (mirrors Apache Camel's cloneable `RouteBuilder`).
392/// Clone is a deep copy of the step list; step closures live behind `Arc`/`BoxProcessor`
393/// so cloning shares the closure and duplicates only the light wrapper (rc-8m5o).
394#[derive(Clone)]
395pub struct RouteBuilder {
396    from_uri: String,
397    steps: Vec<BuilderStep>,
398    /// Pending `.parameters()` maps, each attached to a specific endpoint slot.
399    parameter_assignments: Vec<(EndpointSlot, BTreeMap<String, String>)>,
400    /// Misuse recorded at `.parameters()` call time and surfaced at `build()`.
401    parameter_misuse: Option<String>,
402    error_handler: Option<ErrorHandlerConfig>,
403    error_handler_mode: ErrorHandlerMode,
404    circuit_breaker_config: Option<CircuitBreakerConfig>,
405    security_policy_config: Option<camel_api::security_policy::SecurityPolicyConfig>,
406    security_authenticator: Option<std::sync::Arc<dyn camel_auth::TokenAuthenticator>>,
407    provider_registry: Option<std::sync::Arc<camel_auth::ProviderRegistry>>,
408    concurrency: Option<ConcurrencyModel>,
409    route_id: Option<String>,
410    auto_startup: Option<bool>,
411    startup_order: Option<i32>,
412}
413
414#[derive(Default, Clone)]
415enum ErrorHandlerMode {
416    #[default]
417    None,
418    ExplicitConfig,
419    Shorthand {
420        dlc_uri: Option<String>,
421        specs: Vec<OnExceptionSpec>,
422    },
423    Mixed,
424}
425
426#[derive(Clone)]
427struct OnExceptionSpec {
428    matches: std::sync::Arc<dyn Fn(&CamelError) -> bool + Send + Sync>,
429    retry: Option<RedeliveryPolicy>,
430    handled_by: Option<String>,
431}
432
433impl RouteBuilder {
434    /// Start building a route from the given source endpoint URI.
435    pub fn from(endpoint: &str) -> Self {
436        Self {
437            from_uri: endpoint.to_string(),
438            steps: Vec::new(),
439            parameter_assignments: Vec::new(),
440            parameter_misuse: None,
441            error_handler: None,
442            error_handler_mode: ErrorHandlerMode::None,
443            circuit_breaker_config: None,
444            security_policy_config: None,
445            security_authenticator: None,
446            provider_registry: None,
447            concurrency: None,
448            route_id: None,
449            auto_startup: None,
450            startup_order: None,
451        }
452    }
453
454    /// Open a filter scope. Only exchanges matching `predicate` will be processed
455    /// by the steps inside the scope. Non-matching exchanges skip the scope entirely
456    /// and continue to steps after `.end_filter()`.
457    pub fn filter<F>(self, predicate: F) -> FilterBuilder
458    where
459        F: Fn(&Exchange) -> bool + Send + Sync + 'static,
460    {
461        FilterBuilder {
462            parent: self,
463            predicate: camel_api::FilterPredicate::new(predicate),
464            steps: vec![],
465        }
466    }
467
468    /// Open a choice scope for content-based routing.
469    ///
470    /// Within the choice, you can define multiple `.when()` clauses and an
471    /// optional `.otherwise()` clause. The first matching `when` predicate
472    /// determines which sub-pipeline executes.
473    pub fn choice(self) -> ChoiceBuilder {
474        ChoiceBuilder {
475            parent: self,
476            whens: vec![],
477            _otherwise: None,
478        }
479    }
480
481    /// Add a WireTap step that sends a clone of the exchange to the given
482    /// endpoint URI (fire-and-forget). The original exchange continues
483    /// downstream unchanged.
484    pub fn wire_tap(mut self, endpoint: &str) -> Self {
485        self.steps.push(BuilderStep::WireTap {
486            uri: endpoint.to_string(),
487        });
488        self
489    }
490
491    /// Attach a `parameters:` map to the most recent endpoint slot — the `from`
492    /// endpoint when called before any step, otherwise the last added step.
493    ///
494    /// Parameters on different endpoints each persist independently; none
495    /// overwrites another. Misuse (a second `.parameters()` on the same slot,
496    /// or a call with no pending endpoint step) is deferred and surfaced as a
497    /// `CamelError::RouteError` at `build()` / `build_canonical()`, never a panic.
498    pub fn parameters(mut self, params: BTreeMap<String, String>) -> Self {
499        let slot = if self.steps.is_empty() {
500            EndpointSlot::From
501        } else {
502            EndpointSlot::Step(self.steps.len() - 1)
503        };
504
505        if self
506            .parameter_assignments
507            .iter()
508            .any(|(existing, _)| *existing == slot)
509        {
510            self.parameter_misuse =
511                Some("multiple .parameters() calls attached to the same endpoint".to_string());
512        } else if !endpoint_slot_bears_uri(&slot, &self.steps) {
513            self.parameter_misuse =
514                Some(".parameters() called with no pending endpoint step".to_string());
515        }
516
517        self.parameter_assignments.push((slot, params));
518        self
519    }
520
521    /// Set a per-route error handler. Overrides the global error handler on `CamelContext`.
522    pub fn error_handler(mut self, config: ErrorHandlerConfig) -> Self {
523        self.error_handler_mode = match self.error_handler_mode {
524            ErrorHandlerMode::None | ErrorHandlerMode::ExplicitConfig => {
525                ErrorHandlerMode::ExplicitConfig
526            }
527            ErrorHandlerMode::Shorthand { .. } | ErrorHandlerMode::Mixed => ErrorHandlerMode::Mixed,
528        };
529        self.error_handler = Some(config);
530        self
531    }
532
533    /// Set a dead letter channel URI for shorthand error handler mode.
534    pub fn dead_letter_channel(mut self, uri: impl Into<String>) -> Self {
535        let uri = uri.into();
536        self.error_handler_mode = match self.error_handler_mode {
537            ErrorHandlerMode::None => ErrorHandlerMode::Shorthand {
538                dlc_uri: Some(uri),
539                specs: Vec::new(),
540            },
541            ErrorHandlerMode::Shorthand { specs, .. } => ErrorHandlerMode::Shorthand {
542                dlc_uri: Some(uri),
543                specs,
544            },
545            ErrorHandlerMode::ExplicitConfig | ErrorHandlerMode::Mixed => ErrorHandlerMode::Mixed,
546        };
547        self
548    }
549
550    /// Add a shorthand exception policy scope. Call `.end_on_exception()` to return to route builder.
551    pub fn on_exception<F>(mut self, matches: F) -> OnExceptionBuilder
552    where
553        F: Fn(&CamelError) -> bool + Send + Sync + 'static,
554    {
555        self.error_handler_mode = match self.error_handler_mode {
556            ErrorHandlerMode::None => ErrorHandlerMode::Shorthand {
557                dlc_uri: None,
558                specs: Vec::new(),
559            },
560            ErrorHandlerMode::ExplicitConfig | ErrorHandlerMode::Mixed => ErrorHandlerMode::Mixed,
561            shorthand @ ErrorHandlerMode::Shorthand { .. } => shorthand,
562        };
563
564        OnExceptionBuilder {
565            parent: self,
566            policy: OnExceptionSpec {
567                matches: std::sync::Arc::new(matches),
568                retry: None,
569                handled_by: None,
570            },
571        }
572    }
573
574    /// Set a circuit breaker for this route.
575    pub fn circuit_breaker(mut self, config: CircuitBreakerConfig) -> Self {
576        self.circuit_breaker_config = Some(config);
577        self
578    }
579
580    pub fn security_policy(
581        mut self,
582        config: camel_api::security_policy::SecurityPolicyConfig,
583    ) -> Self {
584        self.security_policy_config = Some(config);
585        self
586    }
587
588    pub fn security_authenticator(
589        mut self,
590        auth: std::sync::Arc<dyn camel_auth::TokenAuthenticator>,
591    ) -> Self {
592        self.security_authenticator = Some(auth);
593        self
594    }
595
596    /// Named provider registry for security plan compilation (ADR-0061):
597    /// routes declaring security resolve their provider here; staging
598    /// aborts when the registry cannot satisfy the declaration.
599    pub fn provider_registry(
600        mut self,
601        registry: std::sync::Arc<camel_auth::ProviderRegistry>,
602    ) -> Self {
603        self.provider_registry = Some(registry);
604        self
605    }
606
607    /// Override the consumer's default concurrency model.
608    ///
609    /// When set, the pipeline spawns a task per exchange, processing them
610    /// concurrently. `max` limits the number of simultaneously active
611    /// pipeline executions (0 = unbounded, channel buffer is backpressure).
612    ///
613    /// # Example
614    /// ```ignore
615    /// RouteBuilder::from("http://0.0.0.0:8080/api")
616    ///     .concurrent(16)  // max 16 in-flight pipeline executions
617    ///     .process(handle_request)
618    ///     .build()
619    /// ```
620    pub fn concurrent(mut self, max: usize) -> Self {
621        let max = if max == 0 { None } else { Some(max) };
622        self.concurrency = Some(ConcurrencyModel::Concurrent { max });
623        self
624    }
625
626    /// Force sequential processing, overriding a concurrent-capable consumer.
627    ///
628    /// Useful for HTTP routes that mutate shared state and need ordering
629    /// guarantees.
630    pub fn sequential(mut self) -> Self {
631        self.concurrency = Some(ConcurrencyModel::Sequential);
632        self
633    }
634
635    /// Set the route ID for this route.
636    ///
637    /// If not set, the route will be assigned an auto-generated ID.
638    pub fn route_id(mut self, id: impl Into<String>) -> Self {
639        self.route_id = Some(id.into());
640        self
641    }
642
643    /// Set whether this route should automatically start when the context starts.
644    ///
645    /// Default is `true`.
646    pub fn auto_startup(mut self, auto: bool) -> Self {
647        self.auto_startup = Some(auto);
648        self
649    }
650
651    /// Set the startup order for this route.
652    ///
653    /// Routes with lower values start first. Default is 1000.
654    pub fn startup_order(mut self, order: i32) -> Self {
655        self.startup_order = Some(order);
656        self
657    }
658
659    /// Begin a Splitter sub-pipeline. Steps added after this call (until
660    /// `.end_split()`) will be executed per-fragment.
661    ///
662    /// Returns a `SplitBuilder` — you cannot call `.build()` until
663    /// `.end_split()` closes the split scope (enforced by the type system).
664    pub fn split(self, config: SplitterConfig) -> SplitBuilder {
665        SplitBuilder {
666            parent: self,
667            config,
668            steps: Vec::new(),
669        }
670    }
671
672    /// Begin a streaming-split sub-pipeline. The caller supplies the fragment
673    /// expression directly (e.g. built from `camel_processor::stream_codec` or
674    /// `zip_splitter`); steps added after this call (until `.end_stream_split()`)
675    /// run once per fragment. Defaults: aggregation `LastWins`,
676    /// `stop_on_exception` true.
677    ///
678    /// Returns a `StreamSplitBuilder` — you cannot call `.build()` until
679    /// `.end_stream_split()` closes the split scope (enforced by the type system).
680    pub fn stream_split(
681        self,
682        expression: camel_api::StreamingSplitExpression,
683    ) -> StreamSplitBuilder {
684        StreamSplitBuilder {
685            parent: self,
686            expression: expression.into(),
687            aggregation: camel_api::splitter::AggregationStrategy::LastWins,
688            stop_on_exception: true,
689            steps: Vec::new(),
690        }
691    }
692
693    /// Begin a Multicast sub-pipeline. Steps added after this call (until
694    /// `.end_multicast()`) will each receive a copy of the exchange.
695    ///
696    /// Returns a `MulticastBuilder` — you cannot call `.build()` until
697    /// `.end_multicast()` closes the multicast scope (enforced by the type system).
698    pub fn multicast(self) -> MulticastBuilder {
699        MulticastBuilder {
700            parent: self,
701            steps: Vec::new(),
702            config: MulticastConfig::new(),
703        }
704    }
705
706    /// Begin a Throttle sub-pipeline. Rate limits message processing to at most
707    /// `max_requests` per `period`. Steps inside the throttle scope are only
708    /// executed when the rate limit allows.
709    ///
710    /// Returns a `ThrottleBuilder` — you cannot call `.build()` until
711    /// `.end_throttle()` closes the throttle scope (enforced by the type system).
712    pub fn throttle(self, max_requests: usize, period: std::time::Duration) -> ThrottleBuilder {
713        ThrottleBuilder {
714            parent: self,
715            config: ThrottlerConfig::new(max_requests, period),
716            steps: Vec::new(),
717        }
718    }
719
720    /// Begin a Loop sub-pipeline that iterates a fixed number of times.
721    pub fn loop_count(self, count: usize) -> LoopBuilder {
722        LoopBuilder {
723            parent: self,
724            config: LoopConfig::new(LoopMode::Count(count)),
725            steps: vec![],
726        }
727    }
728
729    /// Begin a Loop sub-pipeline that iterates while a predicate is true.
730    pub fn loop_while<F>(self, predicate: F) -> LoopBuilder
731    where
732        F: Fn(&Exchange) -> bool + Send + Sync + 'static,
733    {
734        LoopBuilder {
735            parent: self,
736            config: LoopConfig::new(LoopMode::While(camel_api::PredicateSource::Sync(
737                camel_api::FilterPredicate::new(predicate),
738            ))),
739            steps: vec![],
740        }
741    }
742
743    /// Begin a LoadBalance sub-pipeline. Distributes exchanges across multiple
744    /// endpoints using a configurable strategy (round-robin, random, weighted, failover).
745    ///
746    /// Returns a `LoadBalancerBuilder` — you cannot call `.build()` until
747    /// `.end_load_balance()` closes the load balance scope (enforced by the type system).
748    pub fn load_balance(self) -> LoadBalancerBuilder {
749        LoadBalancerBuilder {
750            parent: self,
751            config: LoadBalancerConfig::round_robin(),
752            steps: Vec::new(),
753        }
754    }
755
756    /// Add a dynamic router step that routes exchanges dynamically based on
757    /// expression evaluation at runtime.
758    ///
759    /// The expression source resolves each exchange to `Some(uri)` to route
760    /// to the next endpoint, or `None` to stop routing. Language-backed
761    /// fallible sources are built with `TargetSource::Async`; evaluation
762    /// failures fail the step instead of silently stopping the route.
763    ///
764    /// # Example
765    /// ```ignore
766    /// RouteBuilder::from("timer:tick")
767    ///     .route_id("test-route")
768    ///     .dynamic_router(TargetSource::Sync(Arc::new(|ex| {
769    ///         ex.input.header("dest").and_then(|v| v.as_str().map(|s| s.to_string()))
770    ///     })))
771    ///     .build()
772    /// ```
773    pub fn dynamic_router(self, expression: impl Into<camel_api::TargetSource>) -> Self {
774        self.dynamic_router_with_config(DynamicRouterConfig::new(expression))
775    }
776
777    /// Add a dynamic router step with full configuration.
778    ///
779    /// Allows customization of URI delimiter, cache size, timeout, and other options.
780    pub fn dynamic_router_with_config(mut self, config: DynamicRouterConfig) -> Self {
781        self.steps.push(BuilderStep::DynamicRouter { config });
782        self
783    }
784
785    pub fn routing_slip(self, expression: impl Into<camel_api::TargetSource>) -> Self {
786        self.routing_slip_with_config(RoutingSlipConfig::new(expression))
787    }
788
789    pub fn routing_slip_with_config(mut self, config: RoutingSlipConfig) -> Self {
790        self.steps.push(BuilderStep::RoutingSlip { config });
791        self
792    }
793
794    pub fn recipient_list(self, expression: impl Into<camel_api::RecipientSource>) -> Self {
795        self.recipient_list_with_config(RecipientListConfig::new(expression))
796    }
797
798    pub fn recipient_list_with_config(mut self, config: RecipientListConfig) -> Self {
799        self.steps.push(BuilderStep::RecipientList { config });
800        self
801    }
802
803    /// Consume the builder and produce a [`RouteDefinition`].
804    // Duplicate route IDs are detected at `CamelContext::add_route_definition` time
805    // (RouteController rejects atomically with CamelError::RouteError).
806    pub fn build(mut self) -> Result<RouteDefinition, CamelError> {
807        validate_uri(&self.from_uri)?;
808        let route_id = self
809            .route_id
810            .filter(|s| !s.trim().is_empty())
811            .ok_or_else(|| {
812                CamelError::RouteError(
813                    "route must have a non-empty 'route_id' — call .route_id(\"name\") on the builder"
814                        .to_string(),
815                )
816            })?;
817        let resolved_error_handler = match self.error_handler_mode {
818            ErrorHandlerMode::None => self.error_handler,
819            ErrorHandlerMode::ExplicitConfig => self.error_handler,
820            ErrorHandlerMode::Mixed => {
821                return Err(CamelError::RouteError(
822                    "mixed error handler modes: cannot combine .error_handler(config) with shorthand methods".into(),
823                ));
824            }
825            ErrorHandlerMode::Shorthand { dlc_uri, specs } => {
826                let mut config = if let Some(uri) = dlc_uri {
827                    ErrorHandlerConfig::dead_letter_channel(uri)
828                } else {
829                    ErrorHandlerConfig::log_only()
830                };
831
832                for spec in specs {
833                    let matcher = spec.matches.clone();
834                    let mut builder = config.on_exception(move |e| matcher(e));
835
836                    if let Some(retry) = spec.retry {
837                        builder = builder.retry(retry.max_attempts).with_backoff(
838                            retry.initial_delay,
839                            retry.multiplier,
840                            retry.max_delay,
841                        );
842                        if retry.jitter_factor > 0.0 {
843                            builder = builder.with_jitter(retry.jitter_factor);
844                        }
845                    }
846
847                    if let Some(uri) = spec.handled_by {
848                        builder = builder.handled_by(uri);
849                    }
850
851                    config = builder.build();
852                }
853
854                Some(config)
855            }
856        };
857
858        // Deferred `.parameters()` validation and merge: misuse is a RouteError,
859        // URI merge failures surface as CamelError::EndpointUri via `?`.
860        apply_parameter_assignments(
861            &mut self.from_uri,
862            &mut self.steps,
863            std::mem::take(&mut self.parameter_assignments),
864            std::mem::take(&mut self.parameter_misuse),
865        )?;
866
867        let definition = RouteDefinition::new(self.from_uri, self.steps);
868        let definition = if let Some(eh) = resolved_error_handler {
869            definition.with_error_handler(eh)
870        } else {
871            definition
872        };
873        let definition = if let Some(cb) = self.circuit_breaker_config {
874            definition.with_circuit_breaker(cb)
875        } else {
876            definition
877        };
878        let definition = if let Some(sp) = self.security_policy_config {
879            definition.with_security_policy(sp)
880        } else {
881            definition
882        };
883        let definition = if let Some(auth) = self.security_authenticator {
884            definition.with_security_authenticator(auth)
885        } else {
886            definition
887        };
888        let definition = if let Some(registry) = self.provider_registry {
889            definition.with_provider_registry(registry)
890        } else {
891            definition
892        };
893        let definition = if let Some(concurrency) = self.concurrency {
894            definition.with_concurrency(concurrency)
895        } else {
896            definition
897        };
898        let definition = definition.with_route_id(route_id);
899        let definition = if let Some(auto) = self.auto_startup {
900            definition.with_auto_startup(auto)
901        } else {
902            definition
903        };
904        let definition = if let Some(order) = self.startup_order {
905            definition.with_startup_order(order)
906        } else {
907            definition
908        };
909        Ok(definition)
910    }
911
912    /// Compile this builder route into canonical spec.
913    pub fn build_canonical(mut self) -> Result<CanonicalRouteSpec, CamelError> {
914        validate_uri(&self.from_uri)?;
915        let route_id = self
916            .route_id
917            .filter(|s| !s.trim().is_empty())
918            .ok_or_else(|| {
919                CamelError::RouteError(
920                    "route must have a non-empty 'route_id' — call .route_id(\"name\") on the builder"
921                        .to_string(),
922                )
923            })?;
924
925        // Deferred `.parameters()` validation and merge (same path as `build()`).
926        apply_parameter_assignments(
927            &mut self.from_uri,
928            &mut self.steps,
929            std::mem::take(&mut self.parameter_assignments),
930            std::mem::take(&mut self.parameter_misuse),
931        )?;
932
933        let steps = canonicalize_steps(self.steps)?;
934        let circuit_breaker = self
935            .circuit_breaker_config
936            .map(canonicalize_circuit_breaker)
937            .transpose()?;
938
939        if self.security_policy_config.is_some() {
940            return Err(CamelError::RouteError(
941                "routes with security_policy cannot use the canonical/hot-reload path (not yet supported)"
942                    .into(),
943            ));
944        }
945
946        let spec = CanonicalRouteSpec {
947            route_id,
948            from: self.from_uri,
949            steps,
950            circuit_breaker,
951            auto_startup: None,
952            startup_order: None,
953            concurrency: None,
954            version: camel_api::CANONICAL_CONTRACT_VERSION,
955        };
956        spec.validate_contract()?;
957        Ok(spec)
958    }
959}
960
961pub struct OnExceptionBuilder {
962    parent: RouteBuilder,
963    policy: OnExceptionSpec,
964}
965
966impl OnExceptionBuilder {
967    pub fn retry(mut self, max_attempts: u32) -> Self {
968        self.policy.retry = Some(RedeliveryPolicy::new(max_attempts));
969        self
970    }
971
972    pub fn with_backoff(
973        mut self,
974        initial: std::time::Duration,
975        multiplier: f64,
976        max: std::time::Duration,
977    ) -> Self {
978        if let Some(ref mut retry) = self.policy.retry {
979            retry.initial_delay = initial;
980            retry.multiplier = multiplier;
981            retry.max_delay = max;
982        } else {
983            tracing::warn!("backoff/jitter configuration has no effect when retry_count is 0");
984        }
985        self
986    }
987
988    pub fn with_jitter(mut self, jitter_factor: f64) -> Self {
989        if let Some(ref mut retry) = self.policy.retry {
990            retry.jitter_factor = jitter_factor.clamp(0.0, 1.0);
991        } else {
992            tracing::warn!("backoff/jitter configuration has no effect when retry_count is 0");
993        }
994        self
995    }
996
997    pub fn handled_by(mut self, uri: impl Into<String>) -> Self {
998        self.policy.handled_by = Some(uri.into());
999        self
1000    }
1001
1002    pub fn end_on_exception(mut self) -> RouteBuilder {
1003        if let ErrorHandlerMode::Shorthand { ref mut specs, .. } = self.parent.error_handler_mode {
1004            specs.push(self.policy);
1005        }
1006        self.parent
1007    }
1008}
1009
1010/// True when `slot` names an endpoint-bearing position: the `from` endpoint, or
1011/// a step of one of the endpoint kinds (`To`, `WireTap`, `Enrich`, `PollEnrich`).
1012fn endpoint_slot_bears_uri(slot: &EndpointSlot, steps: &[BuilderStep]) -> bool {
1013    match slot {
1014        EndpointSlot::From => true,
1015        EndpointSlot::Step(i) => steps.get(*i).is_some_and(|step| {
1016            matches!(
1017                step,
1018                BuilderStep::To(_)
1019                    | BuilderStep::WireTap { .. }
1020                    | BuilderStep::Enrich { .. }
1021                    | BuilderStep::PollEnrich { .. }
1022            )
1023        }),
1024    }
1025}
1026
1027/// Merge each pending `.parameters()` assignment into its endpoint slot's URI.
1028///
1029/// A recorded misuse flag aborts first (builder misuse → `RouteError`). Each
1030/// endpoint slot is then verified endpoint-bearing and its URI re-rendered via
1031/// [`EndpointUri::try_from_uri_and_params`]; URI merge failures propagate as
1032/// `CamelError::EndpointUri` (never folded into `RouteError`). Empty parameter
1033/// maps are skipped entirely, preserving URI bytes (parity with the DSL
1034/// lowering); misuse for such calls is still surfaced via `misuse`.
1035fn apply_parameter_assignments(
1036    from_uri: &mut String,
1037    steps: &mut [BuilderStep],
1038    assignments: Vec<(EndpointSlot, BTreeMap<String, String>)>,
1039    misuse: Option<String>,
1040) -> Result<(), CamelError> {
1041    if let Some(reason) = misuse {
1042        return Err(CamelError::RouteError(reason));
1043    }
1044
1045    for (slot, params) in assignments {
1046        // Empty maps are no-ops: re-rendering would still route through
1047        // `EndpointUri` and could normalize URI bytes, diverging from the DSL
1048        // lowering which skips empty maps for byte-identity/passthrough.
1049        if params.is_empty() {
1050            continue;
1051        }
1052
1053        let uri = match slot {
1054            EndpointSlot::From => &mut *from_uri,
1055            EndpointSlot::Step(i) => match steps.get_mut(i) {
1056                Some(BuilderStep::To(uri)) => uri,
1057                Some(BuilderStep::WireTap { uri, .. }) => uri,
1058                Some(BuilderStep::Enrich { uri, .. }) => uri,
1059                Some(BuilderStep::PollEnrich { uri, .. }) => uri,
1060                Some(other) => {
1061                    return Err(CamelError::RouteError(format!(
1062                        ".parameters() attached to a non-endpoint step (`{}`)",
1063                        canonical_step_name(other)
1064                    )));
1065                }
1066                None => {
1067                    return Err(CamelError::RouteError(
1068                        ".parameters() attached to an out-of-range step index".to_string(),
1069                    ));
1070                }
1071            },
1072        };
1073        let merged = EndpointUri::try_from_uri_and_params(uri, params)?.to_canonical_string();
1074        *uri = merged;
1075    }
1076
1077    Ok(())
1078}
1079
1080/// Validate that a URI is non-empty and contains a scheme component.
1081fn validate_uri(uri: &str) -> Result<(), CamelError> {
1082    let trimmed = uri.trim();
1083    if trimmed.is_empty() {
1084        return Err(CamelError::RouteError(
1085            "route must have a 'from' URI".to_string(),
1086        ));
1087    }
1088    if !trimmed.contains(':') {
1089        return Err(CamelError::RouteError(
1090            "URI must have a scheme (e.g. 'timer:tick')".to_string(),
1091        ));
1092    }
1093    let scheme = trimmed.split(':').next().unwrap_or("");
1094    if scheme.trim().is_empty() {
1095        return Err(CamelError::RouteError(
1096            "URI scheme must not be empty".to_string(),
1097        ));
1098    }
1099    Ok(())
1100}
1101
1102fn canonicalize_steps(steps: Vec<BuilderStep>) -> Result<Vec<CanonicalStepSpec>, CamelError> {
1103    let mut canonical = Vec::with_capacity(steps.len());
1104    for step in steps {
1105        canonical.push(canonicalize_step(step)?);
1106    }
1107    Ok(canonical)
1108}
1109
1110fn canonicalize_step(step: BuilderStep) -> Result<CanonicalStepSpec, CamelError> {
1111    match step {
1112        BuilderStep::To(uri) => Ok(CanonicalStepSpec::To { uri }),
1113        BuilderStep::Log { message, .. } => Ok(CanonicalStepSpec::Log { message }),
1114        BuilderStep::Stop => Ok(CanonicalStepSpec::Stop),
1115        BuilderStep::WireTap { uri } => Ok(CanonicalStepSpec::WireTap { uri }),
1116        BuilderStep::Delay { config } => Ok(CanonicalStepSpec::Delay {
1117            delay_ms: config.delay_ms,
1118            dynamic_header: config.dynamic_header,
1119        }),
1120        BuilderStep::DeclarativeScript { expression } => {
1121            Ok(CanonicalStepSpec::Script { expression })
1122        }
1123        BuilderStep::DeclarativeFilter { predicate, steps } => Ok(CanonicalStepSpec::Filter {
1124            predicate,
1125            steps: canonicalize_steps(steps)?,
1126        }),
1127        BuilderStep::DeclarativeChoice { whens, otherwise } => {
1128            let mut canonical_whens = Vec::with_capacity(whens.len());
1129            for DeclarativeWhenStep { predicate, steps } in whens {
1130                canonical_whens.push(CanonicalWhenSpec {
1131                    predicate,
1132                    steps: canonicalize_steps(steps)?,
1133                });
1134            }
1135            let otherwise = match otherwise {
1136                Some(steps) => Some(canonicalize_steps(steps)?),
1137                None => None,
1138            };
1139            Ok(CanonicalStepSpec::Choice {
1140                whens: canonical_whens,
1141                otherwise,
1142            })
1143        }
1144        BuilderStep::DeclarativeSplit {
1145            expression,
1146            aggregation,
1147            parallel,
1148            parallel_limit,
1149            // The programmatic language-split builder has no knob source;
1150            // the default applies at wrap time (asymmetry deferred).
1151            trace_item_threshold: _,
1152            stop_on_exception,
1153            steps,
1154        } => Ok(CanonicalStepSpec::Split {
1155            expression: CanonicalSplitExpressionSpec::Language(expression),
1156            aggregation: canonicalize_split_aggregation(aggregation)?,
1157            parallel,
1158            parallel_limit,
1159            trace_item_threshold: None,
1160            stop_on_exception,
1161            steps: canonicalize_steps(steps)?,
1162        }),
1163        BuilderStep::Aggregate { config } => Ok(CanonicalStepSpec::Aggregate(
1164            canonicalize_aggregate(config)?,
1165        )),
1166        other => {
1167            let step_name = canonical_step_name(&other);
1168            let detail = camel_api::canonical_contract_rejection_reason(step_name)
1169                .unwrap_or("not included in canonical v2");
1170            Err(CamelError::RouteError(format!(
1171                "canonical v2 does not support step `{step_name}`: {detail}"
1172            )))
1173        }
1174    }
1175}
1176
1177fn canonicalize_split_aggregation(
1178    strategy: camel_api::splitter::AggregationStrategy,
1179) -> Result<CanonicalSplitAggregationSpec, CamelError> {
1180    match strategy {
1181        camel_api::splitter::AggregationStrategy::LastWins => {
1182            Ok(CanonicalSplitAggregationSpec::LastWins)
1183        }
1184        camel_api::splitter::AggregationStrategy::CollectAll => {
1185            Ok(CanonicalSplitAggregationSpec::CollectAll)
1186        }
1187        camel_api::splitter::AggregationStrategy::Custom(_) => Err(CamelError::RouteError(
1188            "canonical v2 does not support custom split aggregation".to_string(),
1189        )),
1190        camel_api::splitter::AggregationStrategy::Original => {
1191            Ok(CanonicalSplitAggregationSpec::Original)
1192        }
1193        _ => Err(CamelError::RouteError(
1194            "canonical v2 does not support this split aggregation strategy".to_string(),
1195        )),
1196    }
1197}
1198
1199fn extract_completion_fields(
1200    mode: &CompletionMode,
1201) -> Result<(Option<usize>, Option<u64>), CamelError> {
1202    match mode {
1203        CompletionMode::Single(cond) => match cond {
1204            CompletionCondition::Size(n) => Ok((Some(*n), None)),
1205            CompletionCondition::Timeout(d) => Ok((None, Some(d.as_millis() as u64))),
1206            CompletionCondition::Predicate(_) | CompletionCondition::PredicateExpr { .. } => {
1207                Err(CamelError::RouteError(
1208                    "aggregate PredicateExpr/Predicate completion cannot reverse-map to canonical \
1209                     (forward-only in rc-zit); build the canonical spec directly"
1210                        .to_string(),
1211                ))
1212            }
1213            _ => Err(CamelError::RouteError(
1214                "unsupported completion condition".to_string(),
1215            )),
1216        },
1217        CompletionMode::Any(conds) => {
1218            let mut size = None;
1219            let mut timeout_ms = None;
1220            for cond in conds {
1221                match cond {
1222                    CompletionCondition::Size(n) => size = Some(*n),
1223                    CompletionCondition::Timeout(d) => timeout_ms = Some(d.as_millis() as u64),
1224                    CompletionCondition::Predicate(_)
1225                    | CompletionCondition::PredicateExpr { .. } => {
1226                        return Err(CamelError::RouteError(
1227                            "aggregate PredicateExpr/Predicate completion cannot reverse-map to \
1228                             canonical (forward-only in rc-zit); build the canonical spec directly"
1229                                .to_string(),
1230                        ));
1231                    }
1232                    _ => {
1233                        return Err(CamelError::RouteError(
1234                            "unsupported completion condition".to_string(),
1235                        ));
1236                    }
1237                }
1238            }
1239            Ok((size, timeout_ms))
1240        }
1241        _ => Err(CamelError::RouteError(
1242            "unsupported completion mode".to_string(),
1243        )),
1244    }
1245}
1246
1247fn canonicalize_aggregate(config: AggregatorConfig) -> Result<CanonicalAggregateSpec, CamelError> {
1248    let (completion_size, completion_timeout_ms) = extract_completion_fields(&config.completion)?;
1249
1250    let header = match &config.correlation {
1251        CorrelationStrategy::HeaderName(h) => h.clone(),
1252        CorrelationStrategy::Expression { expr, .. } => expr.clone(),
1253        CorrelationStrategy::Fn(_) => {
1254            return Err(CamelError::RouteError(
1255                "canonical v2 does not support Fn correlation strategy".to_string(),
1256            ));
1257        }
1258        _ => {
1259            return Err(CamelError::RouteError(
1260                "canonical v2 does not support this correlation strategy".to_string(),
1261            ));
1262        }
1263    };
1264
1265    let correlation_key = match &config.correlation {
1266        CorrelationStrategy::HeaderName(_) => None,
1267        CorrelationStrategy::Expression { expr, .. } => Some(expr.clone()),
1268        // INVARIANT: every other correlation variant (Fn and any future
1269        // variant) is rejected by the `header` match above, which returns
1270        // early — so this branch is unreachable here.
1271        _ => unreachable!(),
1272    };
1273
1274    let strategy = match config.strategy {
1275        AggregationStrategy::CollectAll => CanonicalAggregateStrategySpec::CollectAll,
1276        AggregationStrategy::Custom(_) => {
1277            return Err(CamelError::RouteError(
1278                "canonical v2 does not support custom aggregate strategy".to_string(),
1279            ));
1280        }
1281        _ => {
1282            return Err(CamelError::RouteError(
1283                "canonical v2 does not support this aggregate strategy".to_string(),
1284            ));
1285        }
1286    };
1287    let bucket_ttl_ms = config
1288        .bucket_ttl
1289        .map(|ttl| u64::try_from(ttl.as_millis()).unwrap_or(u64::MAX));
1290
1291    Ok(CanonicalAggregateSpec {
1292        header,
1293        completion_size,
1294        completion_timeout_ms,
1295        correlation_key,
1296        force_completion_on_stop: if config.force_completion_on_stop {
1297            Some(true)
1298        } else {
1299            None
1300        },
1301        discard_on_timeout: if config.discard_on_timeout {
1302            Some(true)
1303        } else {
1304            None
1305        },
1306        strategy,
1307        max_buckets: config.max_buckets,
1308        max_bucket_size: config.max_bucket_size,
1309        bucket_ttl_ms,
1310        completion_predicate: None,
1311    })
1312}
1313
1314fn canonicalize_circuit_breaker(
1315    config: CircuitBreakerConfig,
1316) -> Result<CanonicalCircuitBreakerSpec, CamelError> {
1317    if config.fallback.is_some() {
1318        return Err(CamelError::RouteError(
1319            "canonical v2 does not support circuit breaker `fallback` (opaque BoxProcessor \
1320             cannot reverse-map to canonical steps); build the canonical spec directly"
1321                .to_string(),
1322        ));
1323    }
1324    Ok(CanonicalCircuitBreakerSpec {
1325        failure_threshold: config.failure_threshold,
1326        open_duration_ms: u64::try_from(config.open_duration.as_millis()).unwrap_or(u64::MAX),
1327        fallback: Vec::new(),
1328    })
1329}
1330
1331fn canonical_step_name(step: &BuilderStep) -> &'static str {
1332    match step {
1333        BuilderStep::Processor(_) => "processor",
1334        BuilderStep::To(_) => "to",
1335        BuilderStep::Stop => "stop",
1336        BuilderStep::Log { .. } => "log",
1337        BuilderStep::DeclarativeSetHeader { .. } => "set_header",
1338        BuilderStep::DeclarativeSetHeaderIfAbsent { .. } => "set_header_if_absent",
1339        BuilderStep::DeclarativeRemoveHeader { .. } => "remove_header",
1340        BuilderStep::DeclarativeSetBody { .. } => "set_body",
1341        BuilderStep::DeclarativeFilter { .. } => "filter",
1342        BuilderStep::DeclarativeChoice { .. } => "choice",
1343        BuilderStep::DeclarativeScript { .. } => "script",
1344        BuilderStep::DeclarativeFunction { .. } => "function",
1345        BuilderStep::DeclarativeSplit { .. } => "split",
1346        BuilderStep::Split { .. } => "split",
1347        BuilderStep::Loop { .. } | BuilderStep::DeclarativeLoop { .. } => "loop",
1348        BuilderStep::Aggregate { .. } => "aggregate",
1349        BuilderStep::Filter { .. } => "filter",
1350        BuilderStep::Choice { .. } => "choice",
1351        BuilderStep::WireTap { .. } => "wire_tap",
1352        BuilderStep::Delay { .. } => "delay",
1353        BuilderStep::Multicast { .. } => "multicast",
1354        BuilderStep::DeclarativeLog { .. } => "log",
1355        BuilderStep::Bean { .. } => "bean",
1356        BuilderStep::Script { .. } => "script",
1357        BuilderStep::Throttle { .. } => "throttle",
1358        BuilderStep::LoadBalance { .. } => "load_balancer",
1359        BuilderStep::DynamicRouter { .. } => "dynamic_router",
1360        BuilderStep::RoutingSlip { .. } => "routing_slip",
1361        BuilderStep::DeclarativeDynamicRouter { .. } => "declarative_dynamic_router",
1362        BuilderStep::DeclarativeRoutingSlip { .. } => "declarative_routing_slip",
1363        BuilderStep::RecipientList { .. } => "recipient_list",
1364        BuilderStep::DeclarativeRecipientList { .. } => "declarative_recipient_list",
1365        BuilderStep::DeclarativeSetProperty { .. } => "set_property",
1366        BuilderStep::DeclarativeStreamSplit { .. } | BuilderStep::StreamSplit { .. } => {
1367            "stream_split"
1368        }
1369        BuilderStep::Enrich { .. } => "enrich",
1370        BuilderStep::PollEnrich { .. } => "poll_enrich",
1371        BuilderStep::Validate { .. } => "validate",
1372        BuilderStep::IdempotentConsumer { .. } => "idempotent_consumer",
1373        BuilderStep::ClaimCheck { .. } => "claim_check",
1374        BuilderStep::Cache { .. } => "cache",
1375        BuilderStep::CacheInvalidate { .. } => "cache_invalidate",
1376        BuilderStep::CacheClear { .. } => "cache_clear",
1377        BuilderStep::CacheStats { .. } => "cache_stats",
1378        BuilderStep::CachePeekStale { .. } => "cache_peek_stale",
1379        BuilderStep::Sampling { .. } => "sampling",
1380        BuilderStep::Sort { .. } => "sort",
1381        BuilderStep::DeclarativeDoTry { .. } => "do_try",
1382        BuilderStep::DoTry { .. } => "do_try",
1383        BuilderStep::Resequence { .. } => "resequence",
1384    }
1385}
1386
1387impl StepAccumulator for RouteBuilder {
1388    fn steps_mut(&mut self) -> &mut Vec<BuilderStep> {
1389        &mut self.steps
1390    }
1391}
1392
1393/// Builder for the sub-pipeline within a `.split()` ... `.end_split()` block.
1394///
1395/// Exposes the same step methods as `RouteBuilder` (to, process, filter, etc.)
1396/// but NOT `.build()` and NOT `.split()` (no nested splits).
1397///
1398/// Calling `.end_split()` packages the sub-steps into a `BuilderStep::Split`
1399/// and returns the parent `RouteBuilder`.
1400pub struct SplitBuilder {
1401    parent: RouteBuilder,
1402    config: SplitterConfig,
1403    steps: Vec<BuilderStep>,
1404}
1405
1406impl SplitBuilder {
1407    /// Open a filter scope within the split sub-pipeline.
1408    pub fn filter<F>(self, predicate: F) -> FilterInSplitBuilder
1409    where
1410        F: Fn(&Exchange) -> bool + Send + Sync + 'static,
1411    {
1412        FilterInSplitBuilder {
1413            parent: self,
1414            predicate: camel_api::FilterPredicate::new(predicate),
1415            steps: vec![],
1416        }
1417    }
1418
1419    /// Close the split scope. Packages the accumulated sub-steps into a
1420    /// `BuilderStep::Split` and returns the parent `RouteBuilder`.
1421    pub fn end_split(mut self) -> RouteBuilder {
1422        let split_step = BuilderStep::Split {
1423            config: self.config,
1424            steps: self.steps,
1425        };
1426        self.parent.steps.push(split_step);
1427        self.parent
1428    }
1429}
1430
1431impl StepAccumulator for SplitBuilder {
1432    fn steps_mut(&mut self) -> &mut Vec<BuilderStep> {
1433        &mut self.steps
1434    }
1435}
1436
1437/// Builder for the sub-pipeline within a `.filter()` ... `.end_filter()` block.
1438pub struct FilterBuilder {
1439    parent: RouteBuilder,
1440    predicate: FilterPredicate,
1441    steps: Vec<BuilderStep>,
1442}
1443
1444impl FilterBuilder {
1445    /// Close the filter scope. Packages the accumulated sub-steps into a
1446    /// `BuilderStep::Filter` and returns the parent `RouteBuilder`.
1447    pub fn end_filter(mut self) -> RouteBuilder {
1448        let step = BuilderStep::Filter {
1449            predicate: self.predicate,
1450            steps: self.steps,
1451        };
1452        self.parent.steps.push(step);
1453        self.parent
1454    }
1455}
1456
1457impl StepAccumulator for FilterBuilder {
1458    fn steps_mut(&mut self) -> &mut Vec<BuilderStep> {
1459        &mut self.steps
1460    }
1461}
1462
1463/// Builder for a filter scope nested inside a `.split()` block.
1464pub struct FilterInSplitBuilder {
1465    parent: SplitBuilder,
1466    predicate: FilterPredicate,
1467    steps: Vec<BuilderStep>,
1468}
1469
1470impl FilterInSplitBuilder {
1471    /// Close the filter scope and return the parent `SplitBuilder`.
1472    pub fn end_filter(mut self) -> SplitBuilder {
1473        let step = BuilderStep::Filter {
1474            predicate: self.predicate,
1475            steps: self.steps,
1476        };
1477        self.parent.steps.push(step);
1478        self.parent
1479    }
1480}
1481
1482impl StepAccumulator for FilterInSplitBuilder {
1483    fn steps_mut(&mut self) -> &mut Vec<BuilderStep> {
1484        &mut self.steps
1485    }
1486}
1487
1488/// Builder for the sub-pipeline within a `.stream_split()` ... `.end_stream_split()`
1489/// block.
1490///
1491/// The caller supplies the streaming fragment expression directly; sub-steps
1492/// added here run once per fragment. Calling `.end_stream_split()` packages
1493/// the sub-steps into a `BuilderStep::StreamSplit` and returns the parent
1494/// `RouteBuilder`.
1495pub struct StreamSplitBuilder {
1496    parent: RouteBuilder,
1497    expression: StreamSplitExpression,
1498    aggregation: camel_api::splitter::AggregationStrategy,
1499    stop_on_exception: bool,
1500    steps: Vec<BuilderStep>,
1501}
1502
1503impl StreamSplitBuilder {
1504    /// Set the aggregation strategy applied to fragment results.
1505    pub fn aggregation(mut self, strategy: camel_api::splitter::AggregationStrategy) -> Self {
1506        self.aggregation = strategy;
1507        self
1508    }
1509
1510    /// Set whether the first fragment error stops the split. Defaults to `true`.
1511    pub fn stop_on_exception(mut self, stop: bool) -> Self {
1512        self.stop_on_exception = stop;
1513        self
1514    }
1515
1516    /// Close the stream-split scope. Packages the accumulated sub-steps into a
1517    /// `BuilderStep::StreamSplit` and returns the parent `RouteBuilder`.
1518    pub fn end_stream_split(mut self) -> RouteBuilder {
1519        let step = BuilderStep::StreamSplit {
1520            expression: self.expression,
1521            aggregation: self.aggregation,
1522            stop_on_exception: self.stop_on_exception,
1523            steps: self.steps,
1524        };
1525        self.parent.steps.push(step);
1526        self.parent
1527    }
1528}
1529
1530impl StepAccumulator for StreamSplitBuilder {
1531    fn steps_mut(&mut self) -> &mut Vec<BuilderStep> {
1532        &mut self.steps
1533    }
1534}
1535
1536// ── Choice/When/Otherwise builders ─────────────────────────────────────────
1537
1538/// Builder for a `.choice()` ... `.end_choice()` block.
1539///
1540/// Accumulates `when` clauses and an optional `otherwise` clause.
1541/// Cannot call `.build()` until `.end_choice()` is called.
1542pub struct ChoiceBuilder {
1543    parent: RouteBuilder,
1544    whens: Vec<WhenStep>,
1545    _otherwise: Option<Vec<BuilderStep>>,
1546}
1547
1548impl ChoiceBuilder {
1549    /// Open a `when` clause. Only exchanges matching `predicate` will be
1550    /// processed by the steps inside the `.when()` ... `.end_when()` scope.
1551    pub fn when<F>(self, predicate: F) -> WhenBuilder
1552    where
1553        F: Fn(&Exchange) -> bool + Send + Sync + 'static,
1554    {
1555        WhenBuilder {
1556            parent: self,
1557            predicate: camel_api::FilterPredicate::new(predicate),
1558            steps: vec![],
1559        }
1560    }
1561
1562    /// Open an `otherwise` clause. Executed when no `when` predicate matched.
1563    ///
1564    /// Only one `otherwise` is allowed per `choice`. Call this after all `.when()` clauses.
1565    pub fn otherwise(self) -> OtherwiseBuilder {
1566        OtherwiseBuilder {
1567            parent: self,
1568            steps: vec![],
1569        }
1570    }
1571
1572    /// Close the choice scope. Packages all accumulated `when` clauses and
1573    /// optional `otherwise` into a `BuilderStep::Choice` and returns the
1574    /// parent `RouteBuilder`.
1575    pub fn end_choice(mut self) -> RouteBuilder {
1576        let step = BuilderStep::Choice {
1577            whens: self.whens,
1578            otherwise: self._otherwise,
1579        };
1580        self.parent.steps.push(step);
1581        self.parent
1582    }
1583}
1584
1585/// Builder for the sub-pipeline within a `.when()` ... `.end_when()` block.
1586pub struct WhenBuilder {
1587    parent: ChoiceBuilder,
1588    predicate: camel_api::FilterPredicate,
1589    steps: Vec<BuilderStep>,
1590}
1591
1592impl WhenBuilder {
1593    /// Close the when scope. Packages the accumulated sub-steps into a
1594    /// `WhenStep` and returns the parent `ChoiceBuilder`.
1595    pub fn end_when(mut self) -> ChoiceBuilder {
1596        self.parent.whens.push(WhenStep {
1597            predicate: self.predicate,
1598            steps: self.steps,
1599        });
1600        self.parent
1601    }
1602}
1603
1604impl StepAccumulator for WhenBuilder {
1605    fn steps_mut(&mut self) -> &mut Vec<BuilderStep> {
1606        &mut self.steps
1607    }
1608}
1609
1610/// Builder for the sub-pipeline within an `.otherwise()` ... `.end_otherwise()` block.
1611pub struct OtherwiseBuilder {
1612    parent: ChoiceBuilder,
1613    steps: Vec<BuilderStep>,
1614}
1615
1616impl OtherwiseBuilder {
1617    /// Close the otherwise scope and return the parent `ChoiceBuilder`.
1618    pub fn end_otherwise(self) -> ChoiceBuilder {
1619        let OtherwiseBuilder { mut parent, steps } = self;
1620        parent._otherwise = Some(steps);
1621        parent
1622    }
1623}
1624
1625impl StepAccumulator for OtherwiseBuilder {
1626    fn steps_mut(&mut self) -> &mut Vec<BuilderStep> {
1627        &mut self.steps
1628    }
1629}
1630
1631/// Builder for the sub-pipeline within a `.multicast()` ... `.end_multicast()` block.
1632///
1633/// Exposes the same step methods as `RouteBuilder` (to, process, filter, etc.)
1634/// but NOT `.build()` and NOT `.multicast()` (no nested multicasts).
1635///
1636/// Calling `.end_multicast()` packages the sub-steps into a `BuilderStep::Multicast`
1637/// and returns the parent `RouteBuilder`.
1638pub struct MulticastBuilder {
1639    parent: RouteBuilder,
1640    steps: Vec<BuilderStep>,
1641    config: MulticastConfig,
1642}
1643
1644impl MulticastBuilder {
1645    pub fn parallel(mut self, parallel: bool) -> Self {
1646        self.config = self.config.parallel(parallel);
1647        self
1648    }
1649
1650    pub fn parallel_limit(mut self, limit: usize) -> Self {
1651        self.config = self.config.parallel_limit(limit);
1652        self
1653    }
1654
1655    pub fn stop_on_exception(mut self, stop: bool) -> Self {
1656        self.config = self.config.stop_on_exception(stop);
1657        self
1658    }
1659
1660    pub fn timeout(mut self, duration: std::time::Duration) -> Self {
1661        self.config = self.config.timeout(duration);
1662        self
1663    }
1664
1665    pub fn aggregation(mut self, strategy: MulticastStrategy) -> Self {
1666        self.config = self.config.aggregation(strategy);
1667        self
1668    }
1669
1670    pub fn end_multicast(mut self) -> RouteBuilder {
1671        let step = BuilderStep::Multicast {
1672            steps: self.steps,
1673            config: self.config,
1674        };
1675        self.parent.steps.push(step);
1676        self.parent
1677    }
1678}
1679
1680impl StepAccumulator for MulticastBuilder {
1681    fn steps_mut(&mut self) -> &mut Vec<BuilderStep> {
1682        &mut self.steps
1683    }
1684}
1685
1686/// Builder for the sub-pipeline within a `.throttle()` ... `.end_throttle()` block.
1687///
1688/// Exposes the same step methods as `RouteBuilder` (to, process, filter, etc.)
1689/// but NOT `.build()` and NOT `.throttle()` (no nested throttles).
1690///
1691/// Calling `.end_throttle()` packages the sub-steps into a `BuilderStep::Throttle`
1692/// and returns the parent `RouteBuilder`.
1693pub struct ThrottleBuilder {
1694    parent: RouteBuilder,
1695    config: ThrottlerConfig,
1696    steps: Vec<BuilderStep>,
1697}
1698
1699impl ThrottleBuilder {
1700    /// Set the throttle strategy. Default is `Delay`.
1701    ///
1702    /// - `Delay`: Queue messages until capacity available
1703    /// - `Reject`: Return error immediately when throttled
1704    /// - `Drop`: Silently discard excess messages
1705    pub fn strategy(mut self, strategy: ThrottleStrategy) -> Self {
1706        self.config = self.config.strategy(strategy);
1707        self
1708    }
1709
1710    /// Close the throttle scope. Packages the accumulated sub-steps into a
1711    /// `BuilderStep::Throttle` and returns the parent `RouteBuilder`.
1712    pub fn end_throttle(mut self) -> RouteBuilder {
1713        let step = BuilderStep::Throttle {
1714            config: self.config,
1715            steps: self.steps,
1716        };
1717        self.parent.steps.push(step);
1718        self.parent
1719    }
1720}
1721
1722impl StepAccumulator for ThrottleBuilder {
1723    fn steps_mut(&mut self) -> &mut Vec<BuilderStep> {
1724        &mut self.steps
1725    }
1726}
1727
1728/// Builder for the sub-pipeline within a `.loop_count()` / `.loop_while()` ... `.end_loop()` block.
1729pub struct LoopBuilder {
1730    parent: RouteBuilder,
1731    config: LoopConfig,
1732    steps: Vec<BuilderStep>,
1733}
1734
1735impl LoopBuilder {
1736    pub fn loop_count(self, count: usize) -> LoopInLoopBuilder {
1737        LoopInLoopBuilder {
1738            parent: self,
1739            config: LoopConfig::new(LoopMode::Count(count)),
1740            steps: vec![],
1741        }
1742    }
1743
1744    pub fn loop_while<F>(self, predicate: F) -> LoopInLoopBuilder
1745    where
1746        F: Fn(&Exchange) -> bool + Send + Sync + 'static,
1747    {
1748        LoopInLoopBuilder {
1749            parent: self,
1750            config: LoopConfig::new(LoopMode::While(camel_api::PredicateSource::Sync(
1751                camel_api::FilterPredicate::new(predicate),
1752            ))),
1753            steps: vec![],
1754        }
1755    }
1756
1757    pub fn end_loop(mut self) -> RouteBuilder {
1758        let step = BuilderStep::Loop {
1759            config: self.config,
1760            steps: self.steps,
1761        };
1762        self.parent.steps.push(step);
1763        self.parent
1764    }
1765}
1766
1767impl StepAccumulator for LoopBuilder {
1768    fn steps_mut(&mut self) -> &mut Vec<BuilderStep> {
1769        &mut self.steps
1770    }
1771}
1772
1773pub struct LoopInLoopBuilder {
1774    parent: LoopBuilder,
1775    config: LoopConfig,
1776    steps: Vec<BuilderStep>,
1777}
1778
1779impl LoopInLoopBuilder {
1780    pub fn end_loop(mut self) -> LoopBuilder {
1781        let step = BuilderStep::Loop {
1782            config: self.config,
1783            steps: self.steps,
1784        };
1785        self.parent.steps.push(step);
1786        self.parent
1787    }
1788}
1789
1790impl StepAccumulator for LoopInLoopBuilder {
1791    fn steps_mut(&mut self) -> &mut Vec<BuilderStep> {
1792        &mut self.steps
1793    }
1794}
1795
1796/// Builder for the sub-pipeline within a `.load_balance()` ... `.end_load_balance()` block.
1797///
1798/// Exposes the same step methods as `RouteBuilder` (to, process, filter, etc.)
1799/// but NOT `.build()` and NOT `.load_balance()` (no nested load balancers).
1800///
1801/// Calling `.end_load_balance()` packages the sub-steps into a `BuilderStep::LoadBalance`
1802/// and returns the parent `RouteBuilder`.
1803pub struct LoadBalancerBuilder {
1804    parent: RouteBuilder,
1805    config: LoadBalancerConfig,
1806    steps: Vec<BuilderStep>,
1807}
1808
1809impl LoadBalancerBuilder {
1810    /// Set the load balance strategy to round-robin (default).
1811    pub fn round_robin(mut self) -> Self {
1812        self.config = LoadBalancerConfig::round_robin();
1813        self
1814    }
1815
1816    /// Set the load balance strategy to random selection.
1817    pub fn random(mut self) -> Self {
1818        self.config = LoadBalancerConfig::random();
1819        self
1820    }
1821
1822    /// Set the load balance strategy to weighted selection.
1823    ///
1824    /// Each endpoint is assigned a weight that determines its probability
1825    /// of being selected.
1826    pub fn weighted(mut self, weights: Vec<(String, u32)>) -> Self {
1827        self.config = LoadBalancerConfig::weighted(weights);
1828        self
1829    }
1830
1831    /// Set the load balance strategy to failover.
1832    ///
1833    /// Exchanges are sent to the first endpoint; on failure, the next endpoint
1834    /// is tried.
1835    pub fn failover(mut self) -> Self {
1836        self.config = LoadBalancerConfig::failover();
1837        self
1838    }
1839
1840    /// Close the load balance scope. Packages the accumulated sub-steps into a
1841    /// `BuilderStep::LoadBalance` and returns the parent `RouteBuilder`.
1842    pub fn end_load_balance(mut self) -> RouteBuilder {
1843        let step = BuilderStep::LoadBalance {
1844            config: self.config,
1845            steps: self.steps,
1846        };
1847        self.parent.steps.push(step);
1848        self.parent
1849    }
1850}
1851
1852impl StepAccumulator for LoadBalancerBuilder {
1853    fn steps_mut(&mut self) -> &mut Vec<BuilderStep> {
1854        &mut self.steps
1855    }
1856}
1857
1858// ---------------------------------------------------------------------------
1859// Tests
1860// ---------------------------------------------------------------------------
1861
1862#[cfg(test)]
1863mod tests {
1864    use super::*;
1865    use camel_api::SpanKindHint;
1866    use camel_api::error_handler::ErrorHandlerConfig;
1867    use camel_api::load_balancer::LoadBalanceStrategy;
1868    use camel_api::{Exchange, Message};
1869    use camel_core::route::BuilderStep;
1870    use std::sync::Arc;
1871    use std::time::Duration;
1872    use tower::{Service, ServiceExt};
1873
1874    #[test]
1875    fn test_builder_from_creates_definition() {
1876        let definition = RouteBuilder::from("timer:tick")
1877            .route_id("test-route")
1878            .build()
1879            .unwrap();
1880        assert_eq!(definition.from_uri(), "timer:tick");
1881    }
1882
1883    #[test]
1884    fn test_builder_empty_from_uri_errors() {
1885        let result = RouteBuilder::from("").route_id("test-route").build();
1886        assert!(result.is_err());
1887    }
1888
1889    #[test]
1890    fn test_build_rejects_schemeless_uri() {
1891        let result = RouteBuilder::from("no-scheme-here")
1892            .route_id("test-route")
1893            .build();
1894        match result {
1895            Err(err) => {
1896                let err_msg = format!("{err}");
1897                assert!(
1898                    err_msg.contains("scheme"),
1899                    "expected scheme-related error, got: {err_msg}"
1900                );
1901            }
1902            Ok(_) => panic!("schemeless URI should fail"),
1903        }
1904    }
1905
1906    #[test]
1907    fn test_build_rejects_empty_scheme_uri() {
1908        let result = RouteBuilder::from(":missing-scheme")
1909            .route_id("test-route")
1910            .build();
1911        match result {
1912            Err(err) => {
1913                let err_msg = format!("{err}");
1914                assert!(
1915                    err_msg.contains("scheme"),
1916                    "expected scheme-related error, got: {err_msg}"
1917                );
1918            }
1919            Ok(_) => panic!("empty-scheme URI should fail"),
1920        }
1921    }
1922
1923    #[test]
1924    fn test_build_accepts_valid_uri() {
1925        let result = RouteBuilder::from("timer:tick")
1926            .route_id("test-route")
1927            .build();
1928        assert!(result.is_ok());
1929    }
1930
1931    #[test]
1932    fn test_build_canonical_rejects_schemeless_uri() {
1933        let result = RouteBuilder::from("no-scheme-here")
1934            .route_id("test-route")
1935            .build_canonical();
1936        assert!(result.is_err());
1937    }
1938
1939    #[test]
1940    fn test_builder_to_adds_step() {
1941        let definition = RouteBuilder::from("timer:tick")
1942            .route_id("test-route")
1943            .to("log:info")
1944            .build()
1945            .unwrap();
1946
1947        assert_eq!(definition.from_uri(), "timer:tick");
1948        // We can verify steps were added by checking the structure
1949        assert!(matches!(&definition.steps()[0], BuilderStep::To(uri) if uri == "log:info"));
1950    }
1951
1952    #[test]
1953    fn test_builder_filter_adds_filter_step() {
1954        let definition = RouteBuilder::from("timer:tick")
1955            .route_id("test-route")
1956            .filter(|_ex| true)
1957            .to("mock:result")
1958            .end_filter()
1959            .build()
1960            .unwrap();
1961
1962        assert!(matches!(&definition.steps()[0], BuilderStep::Filter { .. }));
1963    }
1964
1965    #[test]
1966    fn test_builder_set_header_adds_processor_step() {
1967        let definition = RouteBuilder::from("timer:tick")
1968            .route_id("test-route")
1969            .set_header("key", Value::String("value".into()))
1970            .build()
1971            .unwrap();
1972
1973        assert!(matches!(&definition.steps()[0], BuilderStep::Processor(_)));
1974    }
1975
1976    #[test]
1977    fn test_builder_map_body_adds_processor_step() {
1978        let definition = RouteBuilder::from("timer:tick")
1979            .route_id("test-route")
1980            .map_body(|body| body)
1981            .build()
1982            .unwrap();
1983
1984        assert!(matches!(&definition.steps()[0], BuilderStep::Processor(_)));
1985    }
1986
1987    #[test]
1988    fn test_builder_process_adds_processor_step() {
1989        let definition = RouteBuilder::from("timer:tick")
1990            .route_id("test-route")
1991            .process(|ex| async move { Ok(ex) })
1992            .build()
1993            .unwrap();
1994
1995        assert!(matches!(&definition.steps()[0], BuilderStep::Processor(_)));
1996    }
1997
1998    #[test]
1999    fn test_builder_chain_multiple_steps() {
2000        let definition = RouteBuilder::from("timer:tick")
2001            .route_id("test-route")
2002            .set_header("source", Value::String("timer".into()))
2003            .filter(|ex| ex.input.header("source").is_some())
2004            .to("log:info")
2005            .end_filter()
2006            .to("mock:result")
2007            .build()
2008            .unwrap();
2009
2010        assert_eq!(definition.steps().len(), 3); // set_header + Filter + To("mock:result")
2011        assert!(matches!(&definition.steps()[0], BuilderStep::Processor(_))); // set_header
2012        assert!(matches!(&definition.steps()[1], BuilderStep::Filter { .. })); // filter
2013        assert!(matches!(&definition.steps()[2], BuilderStep::To(uri) if uri == "mock:result"));
2014    }
2015
2016    #[test]
2017    fn test_loop_count_builder() {
2018        use camel_api::loop_eip::LoopMode;
2019
2020        let def = RouteBuilder::from("direct:start")
2021            .route_id("loop-test")
2022            .loop_count(3)
2023            .to("mock:inside")
2024            .end_loop()
2025            .to("mock:after")
2026            .build()
2027            .unwrap();
2028
2029        assert_eq!(def.steps().len(), 2);
2030        match &def.steps()[0] {
2031            BuilderStep::Loop { config, steps } => {
2032                assert!(matches!(config.mode, LoopMode::Count(3)));
2033                assert_eq!(steps.len(), 1);
2034            }
2035            other => panic!("Expected Loop, got {:?}", other),
2036        }
2037        assert!(matches!(def.steps()[1], BuilderStep::To(_)));
2038    }
2039
2040    #[test]
2041    fn test_loop_while_builder() {
2042        use camel_api::loop_eip::LoopMode;
2043
2044        let def = RouteBuilder::from("direct:start")
2045            .route_id("loop-while-test")
2046            .loop_while(|_ex| true)
2047            .to("mock:retry")
2048            .end_loop()
2049            .build()
2050            .unwrap();
2051
2052        assert_eq!(def.steps().len(), 1);
2053        match &def.steps()[0] {
2054            BuilderStep::Loop { config, steps } => {
2055                assert!(matches!(config.mode, LoopMode::While(_)));
2056                assert_eq!(steps.len(), 1);
2057            }
2058            other => panic!("Expected Loop, got {:?}", other),
2059        }
2060    }
2061
2062    #[test]
2063    fn test_nested_loop_builder() {
2064        use camel_api::loop_eip::LoopMode;
2065
2066        let def = RouteBuilder::from("direct:start")
2067            .route_id("nested-loop-test")
2068            .loop_count(2)
2069            .to("mock:outer")
2070            .loop_count(3)
2071            .to("mock:inner")
2072            .end_loop()
2073            .end_loop()
2074            .to("mock:after")
2075            .build()
2076            .unwrap();
2077
2078        assert_eq!(def.steps().len(), 2);
2079        match &def.steps()[0] {
2080            BuilderStep::Loop { steps, .. } => {
2081                assert_eq!(steps.len(), 2);
2082                match &steps[1] {
2083                    BuilderStep::Loop {
2084                        config,
2085                        steps: inner_steps,
2086                    } => {
2087                        assert!(matches!(config.mode, LoopMode::Count(3)));
2088                        assert_eq!(inner_steps.len(), 1);
2089                    }
2090                    other => panic!("Expected nested Loop, got {:?}", other),
2091                }
2092            }
2093            other => panic!("Expected outer Loop, got {:?}", other),
2094        }
2095    }
2096
2097    // -----------------------------------------------------------------------
2098    // Processor behavior tests — exercise the real Tower services directly
2099    // -----------------------------------------------------------------------
2100
2101    #[tokio::test]
2102    async fn test_set_header_processor_works() {
2103        let mut svc = SetHeader::new(IdentityProcessor, "greeting", Value::String("hello".into()));
2104        let exchange = Exchange::new(Message::new("test"));
2105        let result = svc.call(exchange).await.unwrap();
2106        assert_eq!(
2107            result.input.header("greeting"),
2108            Some(&Value::String("hello".into()))
2109        );
2110    }
2111
2112    #[derive(Clone)]
2113    struct CompletedBody;
2114
2115    impl camel_api::OutcomePipeline for CompletedBody {
2116        fn clone_box(&self) -> Box<dyn camel_api::OutcomePipeline> {
2117            Box::new(self.clone())
2118        }
2119        fn run<'a>(
2120            &'a mut self,
2121            exchange: Exchange,
2122        ) -> std::pin::Pin<
2123            Box<dyn std::future::Future<Output = camel_api::PipelineOutcome> + Send + 'a>,
2124        > {
2125            Box::pin(async move { camel_api::PipelineOutcome::Completed(exchange) })
2126        }
2127    }
2128
2129    #[derive(Clone)]
2130    struct FailedBody;
2131
2132    impl camel_api::OutcomePipeline for FailedBody {
2133        fn clone_box(&self) -> Box<dyn camel_api::OutcomePipeline> {
2134            Box::new(self.clone())
2135        }
2136        fn run<'a>(
2137            &'a mut self,
2138            _exchange: Exchange,
2139        ) -> std::pin::Pin<
2140            Box<dyn std::future::Future<Output = camel_api::PipelineOutcome> + Send + 'a>,
2141        > {
2142            Box::pin(async move {
2143                camel_api::PipelineOutcome::Failed(CamelError::ProcessorError(
2144                    "should not reach".into(),
2145                ))
2146            })
2147        }
2148    }
2149
2150    fn filter_segment(
2151        predicate: impl Fn(&Exchange) -> bool + Send + Sync + 'static,
2152        body: Box<dyn camel_api::OutcomePipeline>,
2153    ) -> camel_processor::FilterSegment {
2154        camel_processor::FilterSegment {
2155            predicate: camel_api::PredicateSource::Sync(camel_api::FilterPredicate::new(predicate)),
2156            body: camel_api::OutcomeSegment::new(body),
2157        }
2158    }
2159
2160    #[tokio::test]
2161    async fn test_filter_processor_passes() {
2162        use camel_api::OutcomePipeline;
2163
2164        let mut seg = filter_segment(
2165            |ex: &Exchange| ex.input.body.as_text() == Some("pass"),
2166            Box::new(CompletedBody),
2167        );
2168        let exchange = Exchange::new(Message::new("pass"));
2169        let result = seg.run(exchange).await;
2170        match result {
2171            camel_api::PipelineOutcome::Completed(ex) => {
2172                assert_eq!(ex.input.body.as_text(), Some("pass"));
2173            }
2174            other => panic!("expected Completed, got {other:?}"),
2175        }
2176    }
2177
2178    #[tokio::test]
2179    async fn test_filter_processor_blocks() {
2180        use camel_api::OutcomePipeline;
2181
2182        let mut seg = filter_segment(
2183            |ex: &Exchange| ex.input.body.as_text() == Some("pass"),
2184            Box::new(FailedBody),
2185        );
2186        let exchange = Exchange::new(Message::new("reject"));
2187        let result = seg.run(exchange).await;
2188        match result {
2189            camel_api::PipelineOutcome::Completed(ex) => {
2190                assert_eq!(ex.input.body.as_text(), Some("reject"));
2191            }
2192            other => panic!("expected Completed, got {other:?}"),
2193        }
2194    }
2195
2196    #[tokio::test]
2197    async fn test_map_body_processor_works() {
2198        let mapper = MapBody::new(IdentityProcessor, |body: Body| {
2199            if let Some(text) = body.as_text() {
2200                Body::Text(text.to_uppercase())
2201            } else {
2202                body
2203            }
2204        });
2205        let exchange = Exchange::new(Message::new("hello"));
2206        let result = mapper.oneshot(exchange).await.unwrap();
2207        assert_eq!(result.input.body.as_text(), Some("HELLO"));
2208    }
2209
2210    #[tokio::test]
2211    async fn test_process_custom_processor_works() {
2212        let processor = ProcessorFn::new(|mut ex: Exchange| async move {
2213            ex.set_property("custom", Value::Bool(true));
2214            Ok(ex)
2215        });
2216        let exchange = Exchange::new(Message::default());
2217        let result = processor.oneshot(exchange).await.unwrap();
2218        assert_eq!(result.property("custom"), Some(&Value::Bool(true)));
2219    }
2220
2221    // -----------------------------------------------------------------------
2222    // Sequential pipeline test
2223    // -----------------------------------------------------------------------
2224
2225    #[tokio::test]
2226    async fn test_compose_pipeline_runs_steps_in_order() {
2227        use camel_core::route::{CompiledStep, PipelineRuntimeCtx, compose_pipeline};
2228
2229        let processors = vec![
2230            CompiledStep::Process {
2231                kind_hint: SpanKindHint::Internal,
2232                processor: BoxProcessor::new(SetHeader::new(
2233                    IdentityProcessor,
2234                    "step",
2235                    Value::String("one".into()),
2236                )),
2237                body_contract: None,
2238                lifecycle: None,
2239                label: None,
2240                to_uri: None,
2241            },
2242            CompiledStep::Process {
2243                kind_hint: SpanKindHint::Internal,
2244                processor: BoxProcessor::new(MapBody::new(IdentityProcessor, |body: Body| {
2245                    if let Some(text) = body.as_text() {
2246                        Body::Text(format!("{}-processed", text))
2247                    } else {
2248                        body
2249                    }
2250                })),
2251                body_contract: None,
2252                lifecycle: None,
2253                label: None,
2254                to_uri: None,
2255            },
2256        ];
2257
2258        let pipeline = compose_pipeline(processors, PipelineRuntimeCtx::compile_time());
2259        let exchange = Exchange::new(Message::new("hello"));
2260        let result = pipeline.oneshot(exchange).await.unwrap();
2261
2262        assert_eq!(
2263            result.input.header("step"),
2264            Some(&Value::String("one".into()))
2265        );
2266        assert_eq!(result.input.body.as_text(), Some("hello-processed"));
2267    }
2268
2269    #[tokio::test]
2270    async fn test_compose_pipeline_empty_is_identity() {
2271        use camel_core::route::{PipelineRuntimeCtx, compose_pipeline};
2272
2273        let pipeline = compose_pipeline(vec![], PipelineRuntimeCtx::compile_time());
2274        let exchange = Exchange::new(Message::new("unchanged"));
2275        let result = pipeline.oneshot(exchange).await.unwrap();
2276        assert_eq!(result.input.body.as_text(), Some("unchanged"));
2277    }
2278
2279    // -----------------------------------------------------------------------
2280    // Circuit breaker builder tests
2281    // -----------------------------------------------------------------------
2282
2283    #[test]
2284    fn test_builder_circuit_breaker_sets_config() {
2285        use camel_api::circuit_breaker::CircuitBreakerConfig;
2286
2287        let config = CircuitBreakerConfig::new().failure_threshold(5);
2288        let definition = RouteBuilder::from("timer:tick")
2289            .route_id("test-route")
2290            .circuit_breaker(config)
2291            .build()
2292            .unwrap();
2293
2294        let cb = definition
2295            .circuit_breaker_config()
2296            .expect("circuit breaker should be set");
2297        assert_eq!(cb.failure_threshold, 5);
2298    }
2299
2300    #[test]
2301    fn test_builder_circuit_breaker_with_error_handler() {
2302        use camel_api::circuit_breaker::CircuitBreakerConfig;
2303        use camel_api::error_handler::ErrorHandlerConfig;
2304
2305        let cb_config = CircuitBreakerConfig::new().failure_threshold(3);
2306        let eh_config = ErrorHandlerConfig::log_only();
2307
2308        let definition = RouteBuilder::from("timer:tick")
2309            .route_id("test-route")
2310            .to("log:info")
2311            .circuit_breaker(cb_config)
2312            .error_handler(eh_config)
2313            .build()
2314            .unwrap();
2315
2316        assert!(
2317            definition.circuit_breaker_config().is_some(),
2318            "circuit breaker config should be set"
2319        );
2320        // Route definition was built successfully with both configs.
2321    }
2322
2323    #[test]
2324    fn test_builder_on_exception_shorthand_multiple_clauses_preserve_order() {
2325        let definition = RouteBuilder::from("direct:start")
2326            .route_id("test-route")
2327            .dead_letter_channel("log:dlc")
2328            .on_exception(|e| matches!(e, CamelError::Io(_)))
2329            .retry(3)
2330            .handled_by("log:io")
2331            .end_on_exception()
2332            .on_exception(|e| matches!(e, CamelError::ProcessorError(_)))
2333            .retry(1)
2334            .end_on_exception()
2335            .to("mock:out")
2336            .build()
2337            .expect("route should build");
2338
2339        let cfg = definition
2340            .error_handler_config()
2341            .expect("error handler should be set");
2342        assert_eq!(cfg.policies.len(), 2);
2343        assert_eq!(cfg.dlc_uri.as_deref(), Some("log:dlc"));
2344        assert_eq!(
2345            cfg.policies[0].retry.as_ref().map(|p| p.max_attempts),
2346            Some(3)
2347        );
2348        assert_eq!(cfg.policies[0].handled_by.as_deref(), Some("log:io"));
2349        assert_eq!(
2350            cfg.policies[1].retry.as_ref().map(|p| p.max_attempts),
2351            Some(1)
2352        );
2353    }
2354
2355    #[test]
2356    fn test_builder_on_exception_mixed_mode_rejected() {
2357        let result = RouteBuilder::from("direct:start")
2358            .route_id("test-route")
2359            .error_handler(ErrorHandlerConfig::log_only())
2360            .on_exception(|_e| true)
2361            .end_on_exception()
2362            .to("mock:out")
2363            .build();
2364
2365        let err = result.err().expect("mixed mode should fail with an error");
2366
2367        assert!(
2368            format!("{err}").contains("mixed error handler modes"),
2369            "unexpected error: {err}"
2370        );
2371    }
2372
2373    #[test]
2374    fn test_builder_on_exception_backoff_and_jitter_without_retry_noop() {
2375        let definition = RouteBuilder::from("direct:start")
2376            .route_id("test-route")
2377            .on_exception(|_e| true)
2378            .with_backoff(Duration::from_millis(5), 3.0, Duration::from_millis(100))
2379            .with_jitter(0.5)
2380            .end_on_exception()
2381            .to("mock:out")
2382            .build()
2383            .expect("route should build");
2384
2385        let cfg = definition
2386            .error_handler_config()
2387            .expect("error handler should be set");
2388        assert_eq!(cfg.policies.len(), 1);
2389        assert!(cfg.policies[0].retry.is_none());
2390    }
2391
2392    #[test]
2393    fn test_builder_dead_letter_channel_without_on_exception_sets_dlc() {
2394        let definition = RouteBuilder::from("direct:start")
2395            .route_id("test-route")
2396            .dead_letter_channel("log:dlc")
2397            .to("mock:out")
2398            .build()
2399            .expect("route should build");
2400
2401        let cfg = definition
2402            .error_handler_config()
2403            .expect("error handler should be set");
2404        assert_eq!(cfg.dlc_uri.as_deref(), Some("log:dlc"));
2405        assert!(cfg.policies.is_empty());
2406    }
2407
2408    #[test]
2409    fn test_builder_dead_letter_channel_called_twice_uses_latest_and_keeps_policies() {
2410        let definition = RouteBuilder::from("direct:start")
2411            .route_id("test-route")
2412            .dead_letter_channel("log:first")
2413            .on_exception(|e| matches!(e, CamelError::Io(_)))
2414            .retry(2)
2415            .end_on_exception()
2416            .dead_letter_channel("log:second")
2417            .to("mock:out")
2418            .build()
2419            .expect("route should build");
2420
2421        let cfg = definition
2422            .error_handler_config()
2423            .expect("error handler should be set");
2424        assert_eq!(cfg.dlc_uri.as_deref(), Some("log:second"));
2425        assert_eq!(cfg.policies.len(), 1);
2426        assert_eq!(
2427            cfg.policies[0].retry.as_ref().map(|p| p.max_attempts),
2428            Some(2)
2429        );
2430    }
2431
2432    #[test]
2433    fn test_builder_on_exception_without_dlc_defaults_to_log_only() {
2434        let definition = RouteBuilder::from("direct:start")
2435            .route_id("test-route")
2436            .on_exception(|e| matches!(e, CamelError::ProcessorError(_)))
2437            .retry(1)
2438            .end_on_exception()
2439            .to("mock:out")
2440            .build()
2441            .expect("route should build");
2442
2443        let cfg = definition
2444            .error_handler_config()
2445            .expect("error handler should be set");
2446        assert!(cfg.dlc_uri.is_none());
2447        assert_eq!(cfg.policies.len(), 1);
2448    }
2449
2450    #[test]
2451    fn test_builder_error_handler_explicit_overwrite_stays_explicit_mode() {
2452        let first = ErrorHandlerConfig::dead_letter_channel("log:first");
2453        let second = ErrorHandlerConfig::dead_letter_channel("log:second");
2454
2455        let definition = RouteBuilder::from("direct:start")
2456            .route_id("test-route")
2457            .error_handler(first)
2458            .error_handler(second)
2459            .to("mock:out")
2460            .build()
2461            .expect("route should build");
2462
2463        let cfg = definition
2464            .error_handler_config()
2465            .expect("error handler should be set");
2466        assert_eq!(cfg.dlc_uri.as_deref(), Some("log:second"));
2467    }
2468
2469    // --- Splitter builder tests ---
2470
2471    #[test]
2472    fn test_split_builder_typestate() {
2473        use camel_api::splitter::{SplitterConfig, split_body_lines};
2474
2475        // .split() returns SplitBuilder, .end_split() returns RouteBuilder
2476        let definition = RouteBuilder::from("timer:test?period=1000")
2477            .route_id("test-route")
2478            .split(SplitterConfig::new(split_body_lines()))
2479            .to("mock:per-fragment")
2480            .end_split()
2481            .to("mock:final")
2482            .build()
2483            .unwrap();
2484
2485        // Should have 2 top-level steps: Split + To("mock:final")
2486        assert_eq!(definition.steps().len(), 2);
2487    }
2488
2489    #[test]
2490    fn test_split_builder_steps_collected() {
2491        use camel_api::splitter::{SplitterConfig, split_body_lines};
2492
2493        let definition = RouteBuilder::from("timer:test?period=1000")
2494            .route_id("test-route")
2495            .split(SplitterConfig::new(split_body_lines()))
2496            .set_header("fragment", Value::String("yes".into()))
2497            .to("mock:per-fragment")
2498            .end_split()
2499            .build()
2500            .unwrap();
2501
2502        // Should have 1 top-level step: Split (containing 2 sub-steps)
2503        assert_eq!(definition.steps().len(), 1);
2504        match &definition.steps()[0] {
2505            BuilderStep::Split { steps, .. } => {
2506                assert_eq!(steps.len(), 2); // SetHeader + To
2507            }
2508            other => panic!("Expected Split, got {:?}", other),
2509        }
2510    }
2511
2512    #[test]
2513    fn test_split_builder_config_propagated() {
2514        use camel_api::splitter::{AggregationStrategy, SplitterConfig, split_body_lines};
2515
2516        let definition = RouteBuilder::from("timer:test?period=1000")
2517            .route_id("test-route")
2518            .split(
2519                SplitterConfig::new(split_body_lines())
2520                    .parallel(true)
2521                    .parallel_limit(4)
2522                    .aggregation(AggregationStrategy::CollectAll),
2523            )
2524            .to("mock:per-fragment")
2525            .end_split()
2526            .build()
2527            .unwrap();
2528
2529        match &definition.steps()[0] {
2530            BuilderStep::Split { config, .. } => {
2531                assert!(config.parallel);
2532                assert_eq!(config.parallel_limit, Some(4));
2533                assert!(matches!(
2534                    config.aggregation,
2535                    AggregationStrategy::CollectAll
2536                ));
2537            }
2538            other => panic!("Expected Split, got {:?}", other),
2539        }
2540    }
2541
2542    #[test]
2543    fn test_aggregate_builder_adds_step() {
2544        use camel_api::aggregator::AggregatorConfig;
2545        use camel_core::route::BuilderStep;
2546
2547        let definition = RouteBuilder::from("timer:tick")
2548            .route_id("test-route")
2549            .aggregate(
2550                AggregatorConfig::correlate_by("key")
2551                    .complete_when_size(2)
2552                    .build()
2553                    .unwrap(),
2554            )
2555            .build()
2556            .unwrap();
2557
2558        assert_eq!(definition.steps().len(), 1);
2559        assert!(matches!(
2560            definition.steps()[0],
2561            BuilderStep::Aggregate { .. }
2562        ));
2563    }
2564
2565    #[test]
2566    fn test_aggregate_in_split_builder() {
2567        use camel_api::aggregator::AggregatorConfig;
2568        use camel_api::splitter::{SplitterConfig, split_body_lines};
2569        use camel_core::route::BuilderStep;
2570
2571        let definition = RouteBuilder::from("timer:tick")
2572            .route_id("test-route")
2573            .split(SplitterConfig::new(split_body_lines()))
2574            .aggregate(
2575                AggregatorConfig::correlate_by("key")
2576                    .complete_when_size(1)
2577                    .build()
2578                    .unwrap(),
2579            )
2580            .end_split()
2581            .build()
2582            .unwrap();
2583
2584        assert_eq!(definition.steps().len(), 1);
2585        if let BuilderStep::Split { steps, .. } = &definition.steps()[0] {
2586            assert!(matches!(steps[0], BuilderStep::Aggregate { .. }));
2587        } else {
2588            panic!("expected Split step");
2589        }
2590    }
2591
2592    // ── set_body / set_body_fn / set_header_fn builder tests ────────────────────
2593
2594    #[test]
2595    fn test_builder_set_body_static_adds_processor() {
2596        let definition = RouteBuilder::from("timer:tick")
2597            .route_id("test-route")
2598            .set_body("fixed")
2599            .build()
2600            .unwrap();
2601        assert!(matches!(&definition.steps()[0], BuilderStep::Processor(_)));
2602    }
2603
2604    #[test]
2605    fn test_builder_set_body_fn_adds_processor() {
2606        let definition = RouteBuilder::from("timer:tick")
2607            .route_id("test-route")
2608            .set_body_fn(|_ex: &Exchange| Body::Text("dynamic".into()))
2609            .build()
2610            .unwrap();
2611        assert!(matches!(&definition.steps()[0], BuilderStep::Processor(_)));
2612    }
2613
2614    #[test]
2615    fn transform_alias_produces_same_as_set_body() {
2616        let route_transform = RouteBuilder::from("timer:tick")
2617            .route_id("test-route")
2618            .transform("hello")
2619            .build()
2620            .unwrap();
2621
2622        let route_set_body = RouteBuilder::from("timer:tick")
2623            .route_id("test-route")
2624            .set_body("hello")
2625            .build()
2626            .unwrap();
2627
2628        assert_eq!(route_transform.steps().len(), route_set_body.steps().len());
2629    }
2630
2631    #[test]
2632    fn test_builder_set_header_fn_adds_processor() {
2633        let definition = RouteBuilder::from("timer:tick")
2634            .route_id("test-route")
2635            .set_header_fn("k", |_ex: &Exchange| Value::String("v".into()))
2636            .build()
2637            .unwrap();
2638        assert!(matches!(&definition.steps()[0], BuilderStep::Processor(_)));
2639    }
2640
2641    #[tokio::test]
2642    async fn test_set_body_static_processor_works() {
2643        use camel_core::route::{CompiledStep, PipelineRuntimeCtx, compose_pipeline};
2644        let def = RouteBuilder::from("t:t")
2645            .route_id("test-route")
2646            .set_body("replaced")
2647            .build()
2648            .unwrap();
2649        let pipeline = compose_pipeline(
2650            def.steps()
2651                .iter()
2652                .filter_map(|s| {
2653                    if let BuilderStep::Processor(op) = s {
2654                        Some(op.0.clone())
2655                    } else {
2656                        None
2657                    }
2658                })
2659                .map(|p| CompiledStep::Process {
2660                    kind_hint: SpanKindHint::Internal,
2661                    processor: p,
2662                    body_contract: None,
2663                    lifecycle: None,
2664                    label: None,
2665                    to_uri: None,
2666                })
2667                .collect(),
2668            PipelineRuntimeCtx::compile_time(),
2669        );
2670        let exchange = Exchange::new(Message::new("original"));
2671        let result = pipeline.oneshot(exchange).await.unwrap();
2672        assert_eq!(result.input.body.as_text(), Some("replaced"));
2673    }
2674
2675    #[tokio::test]
2676    async fn test_set_body_fn_processor_works() {
2677        use camel_core::route::{CompiledStep, PipelineRuntimeCtx, compose_pipeline};
2678        let def = RouteBuilder::from("t:t")
2679            .route_id("test-route")
2680            .set_body_fn(|ex: &Exchange| {
2681                Body::Text(ex.input.body.as_text().unwrap_or("").to_uppercase())
2682            })
2683            .build()
2684            .unwrap();
2685        let pipeline = compose_pipeline(
2686            def.steps()
2687                .iter()
2688                .filter_map(|s| {
2689                    if let BuilderStep::Processor(op) = s {
2690                        Some(op.0.clone())
2691                    } else {
2692                        None
2693                    }
2694                })
2695                .map(|p| CompiledStep::Process {
2696                    kind_hint: SpanKindHint::Internal,
2697                    processor: p,
2698                    body_contract: None,
2699                    lifecycle: None,
2700                    label: None,
2701                    to_uri: None,
2702                })
2703                .collect(),
2704            PipelineRuntimeCtx::compile_time(),
2705        );
2706        let exchange = Exchange::new(Message::new("hello"));
2707        let result = pipeline.oneshot(exchange).await.unwrap();
2708        assert_eq!(result.input.body.as_text(), Some("HELLO"));
2709    }
2710
2711    #[tokio::test]
2712    async fn test_set_header_fn_processor_works() {
2713        use camel_core::route::{CompiledStep, PipelineRuntimeCtx, compose_pipeline};
2714        let def = RouteBuilder::from("t:t")
2715            .route_id("test-route")
2716            .set_header_fn("echo", |ex: &Exchange| {
2717                ex.input
2718                    .body
2719                    .as_text()
2720                    .map(|t| Value::String(t.into()))
2721                    .unwrap_or(Value::Null)
2722            })
2723            .build()
2724            .unwrap();
2725        let pipeline = compose_pipeline(
2726            def.steps()
2727                .iter()
2728                .filter_map(|s| {
2729                    if let BuilderStep::Processor(op) = s {
2730                        Some(op.0.clone())
2731                    } else {
2732                        None
2733                    }
2734                })
2735                .map(|p| CompiledStep::Process {
2736                    kind_hint: SpanKindHint::Internal,
2737                    processor: p,
2738                    body_contract: None,
2739                    lifecycle: None,
2740                    label: None,
2741                    to_uri: None,
2742                })
2743                .collect(),
2744            PipelineRuntimeCtx::compile_time(),
2745        );
2746        let exchange = Exchange::new(Message::new("ping"));
2747        let result = pipeline.oneshot(exchange).await.unwrap();
2748        assert_eq!(
2749            result.input.header("echo"),
2750            Some(&Value::String("ping".into()))
2751        );
2752    }
2753
2754    // ── FilterBuilder typestate tests ─────────────────────────────────────
2755
2756    #[test]
2757    fn test_filter_builder_typestate() {
2758        let result = RouteBuilder::from("timer:tick?period=50&repeatCount=1")
2759            .route_id("test-route")
2760            .filter(|_ex| true)
2761            .to("mock:inner")
2762            .end_filter()
2763            .to("mock:outer")
2764            .build();
2765        assert!(result.is_ok());
2766    }
2767
2768    #[test]
2769    fn test_filter_builder_steps_collected() {
2770        let definition = RouteBuilder::from("timer:tick?period=50&repeatCount=1")
2771            .route_id("test-route")
2772            .filter(|_ex| true)
2773            .to("mock:inner")
2774            .end_filter()
2775            .build()
2776            .unwrap();
2777
2778        assert_eq!(definition.steps().len(), 1);
2779        assert!(matches!(&definition.steps()[0], BuilderStep::Filter { .. }));
2780    }
2781
2782    #[test]
2783    fn test_wire_tap_builder_adds_step() {
2784        let definition = RouteBuilder::from("timer:tick")
2785            .route_id("test-route")
2786            .wire_tap("mock:tap")
2787            .to("mock:result")
2788            .build()
2789            .unwrap();
2790
2791        assert_eq!(definition.steps().len(), 2);
2792        assert!(
2793            matches!(&definition.steps()[0], BuilderStep::WireTap { uri } if uri == "mock:tap")
2794        );
2795        assert!(matches!(&definition.steps()[1], BuilderStep::To(uri) if uri == "mock:result"));
2796    }
2797
2798    // ── MulticastBuilder typestate tests ─────────────────────────────────────
2799
2800    #[test]
2801    fn test_multicast_builder_typestate() {
2802        let definition = RouteBuilder::from("timer:tick")
2803            .route_id("test-route")
2804            .multicast()
2805            .to("direct:a")
2806            .to("direct:b")
2807            .end_multicast()
2808            .to("mock:result")
2809            .build()
2810            .unwrap();
2811
2812        assert_eq!(definition.steps().len(), 2); // Multicast + To("mock:result")
2813    }
2814
2815    #[test]
2816    fn test_multicast_builder_steps_collected() {
2817        let definition = RouteBuilder::from("timer:tick")
2818            .route_id("test-route")
2819            .multicast()
2820            .to("direct:a")
2821            .to("direct:b")
2822            .end_multicast()
2823            .build()
2824            .unwrap();
2825
2826        match &definition.steps()[0] {
2827            BuilderStep::Multicast { steps, .. } => {
2828                assert_eq!(steps.len(), 2);
2829            }
2830            other => panic!("Expected Multicast, got {:?}", other),
2831        }
2832    }
2833
2834    // ── Concurrency builder tests ─────────────────────────────────────
2835
2836    #[test]
2837    fn test_builder_concurrent_sets_concurrency() {
2838        use camel_component_api::ConcurrencyModel;
2839
2840        let definition = RouteBuilder::from("http://0.0.0.0:8080/test")
2841            .route_id("test-route")
2842            .concurrent(16)
2843            .to("log:info")
2844            .build()
2845            .unwrap();
2846
2847        assert_eq!(
2848            definition.concurrency_override(),
2849            Some(&ConcurrencyModel::Concurrent { max: Some(16) })
2850        );
2851    }
2852
2853    #[test]
2854    fn test_builder_concurrent_zero_means_unbounded() {
2855        use camel_component_api::ConcurrencyModel;
2856
2857        let definition = RouteBuilder::from("http://0.0.0.0:8080/test")
2858            .route_id("test-route")
2859            .concurrent(0)
2860            .to("log:info")
2861            .build()
2862            .unwrap();
2863
2864        assert_eq!(
2865            definition.concurrency_override(),
2866            Some(&ConcurrencyModel::Concurrent { max: None })
2867        );
2868    }
2869
2870    #[test]
2871    fn test_builder_sequential_sets_concurrency() {
2872        use camel_component_api::ConcurrencyModel;
2873
2874        let definition = RouteBuilder::from("http://0.0.0.0:8080/test")
2875            .route_id("test-route")
2876            .sequential()
2877            .to("log:info")
2878            .build()
2879            .unwrap();
2880
2881        assert_eq!(
2882            definition.concurrency_override(),
2883            Some(&ConcurrencyModel::Sequential)
2884        );
2885    }
2886
2887    #[test]
2888    fn test_builder_default_concurrency_is_none() {
2889        let definition = RouteBuilder::from("timer:tick")
2890            .route_id("test-route")
2891            .to("log:info")
2892            .build()
2893            .unwrap();
2894
2895        assert_eq!(definition.concurrency_override(), None);
2896    }
2897
2898    // ── Route lifecycle builder tests ─────────────────────────────────────
2899
2900    #[test]
2901    fn test_builder_route_id_sets_id() {
2902        let definition = RouteBuilder::from("timer:tick")
2903            .route_id("my-route")
2904            .build()
2905            .unwrap();
2906
2907        assert_eq!(definition.route_id(), "my-route");
2908    }
2909
2910    #[test]
2911    fn test_build_without_route_id_fails() {
2912        let result = RouteBuilder::from("timer:tick?period=1000")
2913            .to("log:info")
2914            .build();
2915        let err = match result {
2916            Err(e) => e.to_string(),
2917            Ok(_) => panic!("build() should fail without route_id"),
2918        };
2919        assert!(
2920            err.contains("route_id"),
2921            "error should mention route_id, got: {}",
2922            err
2923        );
2924    }
2925
2926    #[test]
2927    fn test_builder_empty_route_id_rejected() {
2928        let result = RouteBuilder::from("timer:tick").route_id("").build();
2929        let err = result.err().expect("empty route_id should be rejected");
2930        assert!(matches!(err, CamelError::RouteError(_)));
2931    }
2932
2933    #[test]
2934    fn test_builder_whitespace_route_id_rejected() {
2935        let result = RouteBuilder::from("timer:tick").route_id("   ").build();
2936        assert!(result.is_err());
2937    }
2938
2939    #[test]
2940    fn test_builder_auto_startup_false() {
2941        let definition = RouteBuilder::from("timer:tick")
2942            .route_id("test-route")
2943            .auto_startup(false)
2944            .build()
2945            .unwrap();
2946
2947        assert!(!definition.auto_startup());
2948    }
2949
2950    #[test]
2951    fn test_builder_startup_order_custom() {
2952        let definition = RouteBuilder::from("timer:tick")
2953            .route_id("test-route")
2954            .startup_order(50)
2955            .build()
2956            .unwrap();
2957
2958        assert_eq!(definition.startup_order(), 50);
2959    }
2960
2961    #[test]
2962    fn test_builder_defaults() {
2963        let definition = RouteBuilder::from("timer:tick")
2964            .route_id("test-route")
2965            .build()
2966            .unwrap();
2967
2968        assert_eq!(definition.route_id(), "test-route");
2969        assert!(definition.auto_startup());
2970        assert_eq!(definition.startup_order(), 1000);
2971    }
2972
2973    // ── Choice typestate tests ──────────────────────────────────────────────────
2974
2975    #[test]
2976    fn test_choice_builder_single_when() {
2977        let definition = RouteBuilder::from("timer:tick")
2978            .route_id("test-route")
2979            .choice()
2980            .when(|ex: &Exchange| ex.input.header("type").is_some())
2981            .to("mock:typed")
2982            .end_when()
2983            .end_choice()
2984            .build()
2985            .unwrap();
2986        assert_eq!(definition.steps().len(), 1);
2987        assert!(
2988            matches!(&definition.steps()[0], BuilderStep::Choice { whens, otherwise }
2989            if whens.len() == 1 && otherwise.is_none())
2990        );
2991    }
2992
2993    #[test]
2994    fn test_choice_builder_when_otherwise() {
2995        let definition = RouteBuilder::from("timer:tick")
2996            .route_id("test-route")
2997            .choice()
2998            .when(|ex: &Exchange| ex.input.header("a").is_some())
2999            .to("mock:a")
3000            .end_when()
3001            .otherwise()
3002            .to("mock:fallback")
3003            .end_otherwise()
3004            .end_choice()
3005            .build()
3006            .unwrap();
3007        assert!(
3008            matches!(&definition.steps()[0], BuilderStep::Choice { whens, otherwise }
3009            if whens.len() == 1 && otherwise.is_some())
3010        );
3011    }
3012
3013    #[test]
3014    fn test_choice_builder_multiple_whens() {
3015        let definition = RouteBuilder::from("timer:tick")
3016            .route_id("test-route")
3017            .choice()
3018            .when(|ex: &Exchange| ex.input.header("a").is_some())
3019            .to("mock:a")
3020            .end_when()
3021            .when(|ex: &Exchange| ex.input.header("b").is_some())
3022            .to("mock:b")
3023            .end_when()
3024            .end_choice()
3025            .build()
3026            .unwrap();
3027        assert!(
3028            matches!(&definition.steps()[0], BuilderStep::Choice { whens, .. }
3029            if whens.len() == 2)
3030        );
3031    }
3032
3033    #[test]
3034    fn test_choice_step_after_choice() {
3035        // Steps after end_choice() are added to the outer pipeline, not inside choice.
3036        let definition = RouteBuilder::from("timer:tick")
3037            .route_id("test-route")
3038            .choice()
3039            .when(|_ex: &Exchange| true)
3040            .to("mock:inner")
3041            .end_when()
3042            .end_choice()
3043            .to("mock:outer") // must be step[1], not inside choice
3044            .build()
3045            .unwrap();
3046        assert_eq!(definition.steps().len(), 2);
3047        assert!(matches!(&definition.steps()[1], BuilderStep::To(uri) if uri == "mock:outer"));
3048    }
3049
3050    // ── Throttle typestate tests ──────────────────────────────────────────────────
3051
3052    #[test]
3053    fn test_throttle_builder_typestate() {
3054        let definition = RouteBuilder::from("timer:tick")
3055            .route_id("test-route")
3056            .throttle(10, std::time::Duration::from_secs(1))
3057            .to("mock:result")
3058            .end_throttle()
3059            .build()
3060            .unwrap();
3061
3062        assert_eq!(definition.steps().len(), 1);
3063        assert!(matches!(
3064            &definition.steps()[0],
3065            BuilderStep::Throttle { .. }
3066        ));
3067    }
3068
3069    #[test]
3070    fn test_throttle_builder_with_strategy() {
3071        let definition = RouteBuilder::from("timer:tick")
3072            .route_id("test-route")
3073            .throttle(10, std::time::Duration::from_secs(1))
3074            .strategy(ThrottleStrategy::Reject)
3075            .to("mock:result")
3076            .end_throttle()
3077            .build()
3078            .unwrap();
3079
3080        if let BuilderStep::Throttle { config, .. } = &definition.steps()[0] {
3081            assert_eq!(config.strategy, ThrottleStrategy::Reject);
3082        } else {
3083            panic!("Expected Throttle step");
3084        }
3085    }
3086
3087    #[test]
3088    fn test_throttle_builder_steps_collected() {
3089        let definition = RouteBuilder::from("timer:tick")
3090            .route_id("test-route")
3091            .throttle(5, std::time::Duration::from_secs(1))
3092            .set_header("throttled", Value::Bool(true))
3093            .to("mock:throttled")
3094            .end_throttle()
3095            .build()
3096            .unwrap();
3097
3098        match &definition.steps()[0] {
3099            BuilderStep::Throttle { steps, .. } => {
3100                assert_eq!(steps.len(), 2); // SetHeader + To
3101            }
3102            other => panic!("Expected Throttle, got {:?}", other),
3103        }
3104    }
3105
3106    #[test]
3107    fn test_throttle_step_after_throttle() {
3108        // Steps after end_throttle() are added to the outer pipeline, not inside throttle.
3109        let definition = RouteBuilder::from("timer:tick")
3110            .route_id("test-route")
3111            .throttle(10, std::time::Duration::from_secs(1))
3112            .to("mock:inner")
3113            .end_throttle()
3114            .to("mock:outer")
3115            .build()
3116            .unwrap();
3117
3118        assert_eq!(definition.steps().len(), 2);
3119        assert!(matches!(&definition.steps()[1], BuilderStep::To(uri) if uri == "mock:outer"));
3120    }
3121
3122    // ── LoadBalance typestate tests ──────────────────────────────────────────────────
3123
3124    #[test]
3125    fn test_load_balance_builder_typestate() {
3126        let definition = RouteBuilder::from("timer:tick")
3127            .route_id("test-route")
3128            .load_balance()
3129            .round_robin()
3130            .to("mock:a")
3131            .to("mock:b")
3132            .end_load_balance()
3133            .build()
3134            .unwrap();
3135
3136        assert_eq!(definition.steps().len(), 1);
3137        assert!(matches!(
3138            &definition.steps()[0],
3139            BuilderStep::LoadBalance { .. }
3140        ));
3141    }
3142
3143    #[test]
3144    fn test_load_balance_builder_with_strategy() {
3145        let definition = RouteBuilder::from("timer:tick")
3146            .route_id("test-route")
3147            .load_balance()
3148            .random()
3149            .to("mock:result")
3150            .end_load_balance()
3151            .build()
3152            .unwrap();
3153
3154        if let BuilderStep::LoadBalance { config, .. } = &definition.steps()[0] {
3155            assert_eq!(config.strategy, LoadBalanceStrategy::Random);
3156        } else {
3157            panic!("Expected LoadBalance step");
3158        }
3159    }
3160
3161    #[test]
3162    fn test_load_balance_builder_steps_collected() {
3163        let definition = RouteBuilder::from("timer:tick")
3164            .route_id("test-route")
3165            .load_balance()
3166            .set_header("lb", Value::Bool(true))
3167            .to("mock:a")
3168            .end_load_balance()
3169            .build()
3170            .unwrap();
3171
3172        match &definition.steps()[0] {
3173            BuilderStep::LoadBalance { steps, .. } => {
3174                assert_eq!(steps.len(), 2); // SetHeader + To
3175            }
3176            other => panic!("Expected LoadBalance, got {:?}", other),
3177        }
3178    }
3179
3180    #[test]
3181    fn test_load_balance_step_after_load_balance() {
3182        // Steps after end_load_balance() are added to the outer pipeline, not inside load_balance.
3183        let definition = RouteBuilder::from("timer:tick")
3184            .route_id("test-route")
3185            .load_balance()
3186            .to("mock:inner")
3187            .end_load_balance()
3188            .to("mock:outer")
3189            .build()
3190            .unwrap();
3191
3192        assert_eq!(definition.steps().len(), 2);
3193        assert!(matches!(&definition.steps()[1], BuilderStep::To(uri) if uri == "mock:outer"));
3194    }
3195
3196    // ── DynamicRouter typestate tests ──────────────────────────────────────────────────
3197
3198    #[test]
3199    fn test_dynamic_router_builder() {
3200        let definition = RouteBuilder::from("timer:tick")
3201            .route_id("test-route")
3202            .dynamic_router(camel_api::TargetSource::Sync(Arc::new(|_| {
3203                Some("mock:result".to_string())
3204            })))
3205            .build()
3206            .unwrap();
3207
3208        assert_eq!(definition.steps().len(), 1);
3209        assert!(matches!(
3210            &definition.steps()[0],
3211            BuilderStep::DynamicRouter { .. }
3212        ));
3213    }
3214
3215    #[test]
3216    fn test_dynamic_router_builder_with_config() {
3217        let config = DynamicRouterConfig::new(camel_api::TargetSource::Sync(Arc::new(|_| {
3218            Some("mock:a".to_string())
3219        })))
3220        .max_iterations(100)
3221        .cache_size(500);
3222
3223        let definition = RouteBuilder::from("timer:tick")
3224            .route_id("test-route")
3225            .dynamic_router_with_config(config)
3226            .build()
3227            .unwrap();
3228
3229        assert_eq!(definition.steps().len(), 1);
3230        if let BuilderStep::DynamicRouter { config } = &definition.steps()[0] {
3231            assert_eq!(config.max_iterations, 100);
3232            assert_eq!(config.cache_size, 500);
3233        } else {
3234            panic!("Expected DynamicRouter step");
3235        }
3236    }
3237
3238    #[test]
3239    fn test_dynamic_router_step_after_router() {
3240        // Steps after dynamic_router() are added to the outer pipeline.
3241        let definition = RouteBuilder::from("timer:tick")
3242            .route_id("test-route")
3243            .dynamic_router(camel_api::TargetSource::Sync(Arc::new(|_| {
3244                Some("mock:inner".to_string())
3245            })))
3246            .to("mock:outer")
3247            .build()
3248            .unwrap();
3249
3250        assert_eq!(definition.steps().len(), 2);
3251        assert!(matches!(
3252            &definition.steps()[0],
3253            BuilderStep::DynamicRouter { .. }
3254        ));
3255        assert!(matches!(&definition.steps()[1], BuilderStep::To(uri) if uri == "mock:outer"));
3256    }
3257
3258    #[test]
3259    fn routing_slip_builder_creates_step() {
3260        use camel_api::TargetSource;
3261
3262        let expression = TargetSource::Sync(Arc::new(|_| Some("direct:a,direct:b".to_string())));
3263
3264        let route = RouteBuilder::from("direct:start")
3265            .route_id("routing-slip-test")
3266            .routing_slip(expression)
3267            .build()
3268            .unwrap();
3269
3270        assert!(
3271            matches!(route.steps()[0], BuilderStep::RoutingSlip { .. }),
3272            "Expected RoutingSlip step"
3273        );
3274    }
3275
3276    #[test]
3277    fn routing_slip_with_config_builder_creates_step() {
3278        use camel_api::RoutingSlipConfig;
3279
3280        let config = RoutingSlipConfig::new(camel_api::TargetSource::Sync(Arc::new(|_| {
3281            Some("mock:a".to_string())
3282        })))
3283        .uri_delimiter("|")
3284        .cache_size(50)
3285        .ignore_invalid_endpoints(true);
3286
3287        let route = RouteBuilder::from("direct:start")
3288            .route_id("routing-slip-config-test")
3289            .routing_slip_with_config(config)
3290            .build()
3291            .unwrap();
3292
3293        if let BuilderStep::RoutingSlip { config } = &route.steps()[0] {
3294            assert_eq!(config.uri_delimiter, "|");
3295            assert_eq!(config.cache_size, 50);
3296            assert!(config.ignore_invalid_endpoints);
3297        } else {
3298            panic!("Expected RoutingSlip step");
3299        }
3300    }
3301
3302    #[test]
3303    fn test_builder_marshal_adds_processor_step() {
3304        let definition = RouteBuilder::from("timer:tick")
3305            .route_id("test-route")
3306            .marshal("json")
3307            .unwrap()
3308            .build()
3309            .unwrap();
3310        assert!(matches!(&definition.steps()[0], BuilderStep::Processor(_)));
3311    }
3312
3313    #[test]
3314    fn test_builder_unmarshal_adds_processor_step() {
3315        let definition = RouteBuilder::from("timer:tick")
3316            .route_id("test-route")
3317            .unmarshal("json")
3318            .unwrap()
3319            .build()
3320            .unwrap();
3321        assert!(matches!(&definition.steps()[0], BuilderStep::Processor(_)));
3322    }
3323
3324    #[test]
3325    fn test_builder_stream_cache_adds_processor_step() {
3326        let definition = RouteBuilder::from("timer:tick")
3327            .route_id("test-route")
3328            .stream_cache(1024)
3329            .build()
3330            .unwrap();
3331        assert!(matches!(&definition.steps()[0], BuilderStep::Processor(_)));
3332    }
3333
3334    #[test]
3335    fn validate_adds_validate_step() {
3336        let def = RouteBuilder::from("direct:in")
3337            .route_id("test")
3338            .validate("schemas/order.xsd")
3339            .build()
3340            .unwrap();
3341        let steps = def.steps();
3342        assert_eq!(steps.len(), 1);
3343        assert!(
3344            matches!(&steps[0], BuilderStep::Validate { predicate } if predicate.language == "simple" && predicate.source == "schemas/order.xsd"),
3345            "got: {:?}",
3346            steps[0]
3347        );
3348    }
3349
3350    #[test]
3351    fn test_builder_marshal_returns_err_for_unknown_format() {
3352        let result = RouteBuilder::from("timer:tick")
3353            .route_id("test-route")
3354            .marshal("protobuf");
3355        let err = match result {
3356            Err(e) => e,
3357            Ok(_) => panic!("marshal with unknown format should return Err"),
3358        };
3359        let msg = err.to_string();
3360        assert!(
3361            msg.contains("unknown data format"),
3362            "error should mention unknown format, got: {msg}"
3363        );
3364        assert!(
3365            msg.contains("protobuf"),
3366            "error should mention format name, got: {msg}"
3367        );
3368    }
3369
3370    #[test]
3371    fn test_builder_unmarshal_returns_err_for_unknown_format() {
3372        let result = RouteBuilder::from("timer:tick")
3373            .route_id("test-route")
3374            .unmarshal("protobuf");
3375        let err = match result {
3376            Err(e) => e,
3377            Ok(_) => panic!("unmarshal with unknown format should return Err"),
3378        };
3379        let msg = err.to_string();
3380        assert!(
3381            msg.contains("unknown data format"),
3382            "error should mention unknown format, got: {msg}"
3383        );
3384        assert!(
3385            msg.contains("protobuf"),
3386            "error should mention format name, got: {msg}"
3387        );
3388    }
3389
3390    #[test]
3391    fn test_builder_recipient_list_creates_step() {
3392        let route = RouteBuilder::from("direct:start")
3393            .route_id("recipient-list-test")
3394            .recipient_list(camel_api::RecipientSource::Sync(Arc::new(|_| {
3395                "direct:a,direct:b".to_string()
3396            })))
3397            .build()
3398            .unwrap();
3399
3400        assert!(matches!(
3401            &route.steps()[0],
3402            BuilderStep::RecipientList { .. }
3403        ));
3404    }
3405
3406    #[test]
3407    fn test_builder_recipient_list_with_config_creates_step() {
3408        let config = RecipientListConfig::new(camel_api::RecipientSource::Sync(Arc::new(|_| {
3409            "mock:a".to_string()
3410        })));
3411
3412        let route = RouteBuilder::from("direct:start")
3413            .route_id("recipient-list-config-test")
3414            .recipient_list_with_config(config)
3415            .build()
3416            .unwrap();
3417
3418        assert!(matches!(
3419            &route.steps()[0],
3420            BuilderStep::RecipientList { .. }
3421        ));
3422    }
3423
3424    #[test]
3425    fn test_builder_script_adds_script_step() {
3426        let route = RouteBuilder::from("direct:start")
3427            .route_id("script-test")
3428            .script("rhai", "headers[\"x\"] = \"y\"")
3429            .build()
3430            .unwrap();
3431
3432        assert!(matches!(
3433            &route.steps()[0],
3434            BuilderStep::Script { language, script }
3435            if language == "rhai" && script == "headers[\"x\"] = \"y\""
3436        ));
3437    }
3438
3439    #[test]
3440    fn test_builder_delay_and_delay_with_header_add_steps() {
3441        let route = RouteBuilder::from("direct:start")
3442            .route_id("delay-test")
3443            .delay(Duration::from_millis(250))
3444            .delay_with_header(Duration::from_millis(500), "x-delay")
3445            .build()
3446            .unwrap();
3447
3448        assert_eq!(route.steps().len(), 2);
3449        assert!(matches!(&route.steps()[0], BuilderStep::Delay { .. }));
3450        assert!(matches!(&route.steps()[1], BuilderStep::Delay { .. }));
3451    }
3452
3453    #[test]
3454    fn test_builder_log_and_stop_add_steps_in_order() {
3455        let route = RouteBuilder::from("direct:start")
3456            .route_id("log-stop-test")
3457            .log("hello", LogLevel::Info)
3458            .stop()
3459            .to("mock:after")
3460            .build()
3461            .unwrap();
3462
3463        assert_eq!(route.steps().len(), 3);
3464        assert!(matches!(
3465            &route.steps()[0],
3466            BuilderStep::Log { message, .. } if message == "hello"
3467        ));
3468        assert!(matches!(&route.steps()[1], BuilderStep::Stop));
3469        assert!(matches!(&route.steps()[2], BuilderStep::To(uri) if uri == "mock:after"));
3470    }
3471
3472    #[test]
3473    fn test_builder_stream_cache_default_adds_processor_step() {
3474        let route = RouteBuilder::from("direct:start")
3475            .route_id("stream-cache-default-test")
3476            .stream_cache_default()
3477            .build()
3478            .unwrap();
3479
3480        assert!(matches!(&route.steps()[0], BuilderStep::Processor(_)));
3481    }
3482
3483    #[test]
3484    fn test_validate_creates_validate_step_with_expression() {
3485        let route = RouteBuilder::from("direct:in")
3486            .route_id("validate-prefix-test")
3487            .validate("${body.size()} > 0")
3488            .build()
3489            .unwrap();
3490
3491        assert!(matches!(
3492            &route.steps()[0],
3493            BuilderStep::Validate { predicate } if predicate.language == "simple" && predicate.source == "${body.size()} > 0"
3494        ));
3495    }
3496
3497    #[test]
3498    fn test_load_balance_builder_weighted_failover_config() {
3499        let route = RouteBuilder::from("direct:start")
3500            .route_id("lb-weighted-failover")
3501            .load_balance()
3502            .weighted(vec![
3503                ("direct:a".to_string(), 3),
3504                ("direct:b".to_string(), 1),
3505            ])
3506            .failover()
3507            .to("mock:result")
3508            .end_load_balance()
3509            .build()
3510            .unwrap();
3511
3512        if let BuilderStep::LoadBalance { config, .. } = &route.steps()[0] {
3513            assert_eq!(config.strategy, LoadBalanceStrategy::Failover);
3514        } else {
3515            panic!("Expected LoadBalance step");
3516        }
3517    }
3518
3519    #[test]
3520    fn test_multicast_builder_all_config_setters() {
3521        let route = RouteBuilder::from("direct:start")
3522            .route_id("multicast-config-test")
3523            .multicast()
3524            .parallel(true)
3525            .parallel_limit(4)
3526            .stop_on_exception(true)
3527            .timeout(Duration::from_millis(300))
3528            .aggregation(MulticastStrategy::Original)
3529            .to("mock:a")
3530            .end_multicast()
3531            .build()
3532            .unwrap();
3533
3534        if let BuilderStep::Multicast { config, .. } = &route.steps()[0] {
3535            assert!(config.parallel);
3536            assert_eq!(config.parallel_limit, Some(4));
3537            assert!(config.stop_on_exception);
3538            assert_eq!(config.timeout, Some(Duration::from_millis(300)));
3539            assert!(matches!(config.aggregation, MulticastStrategy::Original));
3540        } else {
3541            panic!("Expected Multicast step");
3542        }
3543    }
3544
3545    #[test]
3546    fn test_build_canonical_rejects_unsupported_processor_step() {
3547        let err = RouteBuilder::from("direct:start")
3548            .route_id("canonical-reject")
3549            .set_header("k", Value::String("v".into()))
3550            .build_canonical()
3551            .unwrap_err();
3552
3553        assert!(format!("{err}").contains("does not support step `processor`"));
3554    }
3555
3556    // ── LoadBalance strategy-specific tests ─────────────────────────────────────
3557
3558    #[test]
3559    fn test_load_balance_builder_weighted_strategy() {
3560        let route = RouteBuilder::from("direct:start")
3561            .route_id("lb-weighted")
3562            .load_balance()
3563            .weighted(vec![
3564                ("direct:a".to_string(), 5),
3565                ("direct:b".to_string(), 2),
3566                ("direct:c".to_string(), 1),
3567            ])
3568            .to("mock:result")
3569            .end_load_balance()
3570            .build()
3571            .unwrap();
3572
3573        if let BuilderStep::LoadBalance { config, .. } = &route.steps()[0] {
3574            assert!(matches!(config.strategy, LoadBalanceStrategy::Weighted(_)));
3575        } else {
3576            panic!("Expected LoadBalance step");
3577        }
3578    }
3579
3580    #[test]
3581    fn test_load_balance_builder_failover_strategy() {
3582        let route = RouteBuilder::from("direct:start")
3583            .route_id("lb-failover")
3584            .load_balance()
3585            .failover()
3586            .to("mock:primary")
3587            .end_load_balance()
3588            .build()
3589            .unwrap();
3590
3591        if let BuilderStep::LoadBalance { config, .. } = &route.steps()[0] {
3592            assert_eq!(config.strategy, LoadBalanceStrategy::Failover);
3593        } else {
3594            panic!("Expected LoadBalance step");
3595        }
3596    }
3597
3598    // ── FilterInSplitBuilder tests ──────────────────────────────────────────────
3599
3600    #[test]
3601    fn test_filter_in_split_builder_typestate() {
3602        use camel_api::splitter::{SplitterConfig, split_body_lines};
3603
3604        let definition = RouteBuilder::from("timer:test")
3605            .route_id("filter-in-split")
3606            .split(SplitterConfig::new(split_body_lines()))
3607            .filter(|_ex| true)
3608            .to("mock:filtered")
3609            .end_filter()
3610            .end_split()
3611            .build()
3612            .unwrap();
3613
3614        assert_eq!(definition.steps().len(), 1);
3615        if let BuilderStep::Split { steps, .. } = &definition.steps()[0] {
3616            assert_eq!(steps.len(), 1);
3617            assert!(matches!(&steps[0], BuilderStep::Filter { .. }));
3618        } else {
3619            panic!("Expected Split step");
3620        }
3621    }
3622
3623    #[test]
3624    fn test_filter_in_split_builder_multiple_steps() {
3625        use camel_api::splitter::{SplitterConfig, split_body_lines};
3626
3627        let definition = RouteBuilder::from("timer:test")
3628            .route_id("filter-in-split-multi")
3629            .split(SplitterConfig::new(split_body_lines()))
3630            .to("mock:before-filter")
3631            .filter(|_ex| true)
3632            .to("mock:inside-filter")
3633            .end_filter()
3634            .to("mock:after-filter")
3635            .end_split()
3636            .build()
3637            .unwrap();
3638
3639        if let BuilderStep::Split { steps, .. } = &definition.steps()[0] {
3640            // To("before-filter") + Filter{...} + To("after-filter") = 3
3641            assert_eq!(steps.len(), 3);
3642        } else {
3643            panic!("Expected Split step");
3644        }
3645    }
3646
3647    // ── build_canonical tests ───────────────────────────────────────────────────
3648
3649    #[test]
3650    fn test_build_canonical_with_circuit_breaker() {
3651        use camel_api::circuit_breaker::CircuitBreakerConfig;
3652
3653        let spec = RouteBuilder::from("direct:start")
3654            .route_id("canonical-cb")
3655            .circuit_breaker(CircuitBreakerConfig::new().failure_threshold(10))
3656            .to("mock:result")
3657            .build_canonical()
3658            .unwrap();
3659
3660        let cb = spec.circuit_breaker.expect("circuit breaker should be set");
3661        assert_eq!(cb.failure_threshold, 10);
3662    }
3663
3664    #[test]
3665    fn test_build_canonical_rejects_custom_split_aggregation() {
3666        use camel_api::splitter::{SplitterConfig, split_body_lines};
3667
3668        let err = RouteBuilder::from("direct:start")
3669            .route_id("canonical-custom-split")
3670            .split(SplitterConfig::new(split_body_lines()).aggregation(
3671                camel_api::splitter::AggregationStrategy::Custom(Arc::new(|_, ex| ex)),
3672            ))
3673            .to("mock:frag")
3674            .end_split()
3675            .build_canonical()
3676            .unwrap_err();
3677
3678        // Split with closure-based expression is rejected in canonical v2.
3679        assert!(format!("{err}").contains("canonical v2 does not support step `split`"));
3680    }
3681
3682    #[test]
3683    fn test_build_canonical_rejects_custom_aggregate_strategy() {
3684        let err = RouteBuilder::from("direct:start")
3685            .route_id("canonical-custom-agg")
3686            .aggregate(
3687                AggregatorConfig::correlate_by("key")
3688                    .complete_when_size(2)
3689                    .strategy(AggregationStrategy::Custom(Arc::new(|_, ex| ex)))
3690                    .build()
3691                    .unwrap(),
3692            )
3693            .build_canonical()
3694            .unwrap_err();
3695
3696        assert!(format!("{err}").contains("custom aggregate strategy"));
3697    }
3698
3699    #[test]
3700    fn test_build_canonical_rejects_fn_correlation_strategy() {
3701        let err = RouteBuilder::from("direct:start")
3702            .route_id("canonical-fn-corr")
3703            .aggregate(AggregatorConfig {
3704                header_name: "key".to_string(),
3705                completion: CompletionMode::Single(CompletionCondition::Size(1)),
3706                correlation: CorrelationStrategy::Fn(Arc::new(|_| Some("key".to_string()))),
3707                strategy: AggregationStrategy::CollectAll,
3708                max_buckets: None,
3709                max_bucket_size: None,
3710                bucket_ttl: None,
3711                force_completion_on_stop: false,
3712                discard_on_timeout: false,
3713                max_timeout_tasks: 1024,
3714            })
3715            .build_canonical()
3716            .unwrap_err();
3717
3718        assert!(format!("{err}").contains("Fn correlation strategy"));
3719    }
3720
3721    #[test]
3722    fn test_build_canonical_rejects_predicate_completion() {
3723        let err = RouteBuilder::from("direct:start")
3724            .route_id("canonical-pred-completion")
3725            .aggregate(AggregatorConfig {
3726                header_name: "key".to_string(),
3727                completion: CompletionMode::Single(CompletionCondition::Predicate(Arc::new(
3728                    |_| false,
3729                ))),
3730                correlation: CorrelationStrategy::HeaderName("key".to_string()),
3731                strategy: AggregationStrategy::CollectAll,
3732                max_buckets: None,
3733                max_bucket_size: None,
3734                bucket_ttl: None,
3735                force_completion_on_stop: false,
3736                discard_on_timeout: false,
3737                max_timeout_tasks: 1024,
3738            })
3739            .build_canonical()
3740            .unwrap_err();
3741
3742        assert!(
3743            format!("{err}").contains("cannot reverse-map"),
3744            "reject message must explain forward-only: {}",
3745            err
3746        );
3747    }
3748
3749    #[test]
3750    fn extract_completion_fields_rejects_predicate_expr() {
3751        let mode = CompletionMode::Single(CompletionCondition::PredicateExpr {
3752            expr: "${body} == 'DONE'".to_string(),
3753            language: "simple".to_string(),
3754        });
3755        let result = extract_completion_fields(&mode);
3756        assert!(
3757            result.is_err(),
3758            "PredicateExpr must be rejected (forward-only)"
3759        );
3760        let msg = format!("{}", result.unwrap_err());
3761        assert!(
3762            msg.contains("cannot reverse-map"),
3763            "reject message must explain forward-only: {}",
3764            msg
3765        );
3766    }
3767
3768    #[test]
3769    fn extract_completion_fields_rejects_predicate_expr_any_mode() {
3770        let mode = CompletionMode::Any(vec![
3771            CompletionCondition::Size(5),
3772            CompletionCondition::PredicateExpr {
3773                expr: "${body} == 'DONE'".to_string(),
3774                language: "simple".to_string(),
3775            },
3776        ]);
3777        let result = extract_completion_fields(&mode);
3778        assert!(
3779            result.is_err(),
3780            "PredicateExpr in Any must be rejected (forward-only)"
3781        );
3782        let msg = format!("{}", result.unwrap_err());
3783        assert!(
3784            msg.contains("cannot reverse-map"),
3785            "reject message must explain forward-only: {}",
3786            msg
3787        );
3788    }
3789
3790    #[test]
3791    fn test_build_canonical_with_expression_correlation() {
3792        let spec = RouteBuilder::from("direct:start")
3793            .route_id("canonical-expr-corr")
3794            .aggregate(AggregatorConfig {
3795                header_name: "key".to_string(),
3796                completion: CompletionMode::Single(CompletionCondition::Size(1)),
3797                correlation: CorrelationStrategy::Expression {
3798                    expr: "header.key".to_string(),
3799                    language: "simple".to_string(),
3800                },
3801                strategy: AggregationStrategy::CollectAll,
3802                max_buckets: None,
3803                max_bucket_size: None,
3804                bucket_ttl: None,
3805                force_completion_on_stop: false,
3806                discard_on_timeout: false,
3807                max_timeout_tasks: 1024,
3808            })
3809            .build_canonical()
3810            .unwrap();
3811
3812        assert!(spec.steps.iter().any(|s| matches!(s, CanonicalStepSpec::Aggregate(a) if a.correlation_key == Some("header.key".to_string()))));
3813    }
3814
3815    #[test]
3816    fn test_build_canonical_split_rejected_with_closure_expression() {
3817        use camel_api::splitter::{AggregationStrategy, SplitterConfig, split_body_lines};
3818
3819        // Builder-based split uses closure expressions, which are not serializable.
3820        let err = RouteBuilder::from("direct:start")
3821            .route_id("canonical-split-last")
3822            .split(
3823                SplitterConfig::new(split_body_lines()).aggregation(AggregationStrategy::LastWins),
3824            )
3825            .to("mock:frag")
3826            .end_split()
3827            .build_canonical()
3828            .unwrap_err();
3829
3830        assert!(format!("{err}").contains("canonical v2 does not support step `split`"));
3831    }
3832
3833    // ── OnExceptionBuilder full chain tests ─────────────────────────────────────
3834
3835    #[test]
3836    fn test_on_exception_full_chain_retry_backoff_jitter_handled_by() {
3837        let definition = RouteBuilder::from("direct:start")
3838            .route_id("on-exception-full")
3839            .dead_letter_channel("log:dlc")
3840            .on_exception(|e| matches!(e, CamelError::Io(_)))
3841            .retry(5)
3842            .with_backoff(Duration::from_millis(10), 2.0, Duration::from_millis(500))
3843            .with_jitter(0.3)
3844            .handled_by("log:io-handler")
3845            .end_on_exception()
3846            .to("mock:out")
3847            .build()
3848            .unwrap();
3849
3850        let cfg = definition
3851            .error_handler_config()
3852            .expect("error handler should be set");
3853        assert_eq!(cfg.policies.len(), 1);
3854        let policy = &cfg.policies[0];
3855        let retry = policy.retry.as_ref().expect("retry should be set");
3856        assert_eq!(retry.max_attempts, 5);
3857        assert_eq!(retry.initial_delay, Duration::from_millis(10));
3858        assert_eq!(retry.multiplier, 2.0);
3859        assert_eq!(retry.max_delay, Duration::from_millis(500));
3860        assert!((retry.jitter_factor - 0.3).abs() < f64::EPSILON);
3861        assert_eq!(policy.handled_by.as_deref(), Some("log:io-handler"));
3862    }
3863
3864    #[test]
3865    fn test_on_exception_jitter_clamped_to_valid_range() {
3866        let definition = RouteBuilder::from("direct:start")
3867            .route_id("jitter-clamp")
3868            .on_exception(|_e| true)
3869            .retry(1)
3870            .with_jitter(5.0)
3871            .end_on_exception()
3872            .to("mock:out")
3873            .build()
3874            .unwrap();
3875
3876        let cfg = definition.error_handler_config().unwrap();
3877        let retry = cfg.policies[0].retry.as_ref().unwrap();
3878        assert!((retry.jitter_factor - 1.0).abs() < f64::EPSILON);
3879    }
3880
3881    // ── StepAccumulator: process_fn, convert_body_to, bean ──────────────────────
3882
3883    #[test]
3884    fn test_builder_process_fn_adds_processor_step() {
3885        use camel_api::BoxProcessorExt;
3886        let processor = BoxProcessor::from_fn(|ex| Box::pin(async move { Ok(ex) }));
3887        let definition = RouteBuilder::from("timer:tick")
3888            .route_id("process-fn-test")
3889            .process_fn(processor)
3890            .build()
3891            .unwrap();
3892
3893        assert!(matches!(&definition.steps()[0], BuilderStep::Processor(_)));
3894    }
3895
3896    #[test]
3897    fn test_builder_convert_body_to_adds_processor_step() {
3898        let definition = RouteBuilder::from("timer:tick")
3899            .route_id("convert-body-test")
3900            .convert_body_to(BodyType::Json)
3901            .build()
3902            .unwrap();
3903
3904        assert!(matches!(&definition.steps()[0], BuilderStep::Processor(_)));
3905    }
3906
3907    #[test]
3908    fn test_builder_bean_adds_bean_step() {
3909        let definition = RouteBuilder::from("timer:tick")
3910            .route_id("bean-test")
3911            .bean("myBean", "process")
3912            .build()
3913            .unwrap();
3914
3915        assert!(
3916            matches!(&definition.steps()[0], BuilderStep::Bean { name, method }
3917            if name == "myBean" && method == "process")
3918        );
3919    }
3920
3921    // ── Throttle strategy-specific tests ────────────────────────────────────────
3922
3923    #[test]
3924    fn test_throttle_builder_delay_strategy() {
3925        let definition = RouteBuilder::from("timer:tick")
3926            .route_id("throttle-delay")
3927            .throttle(10, Duration::from_secs(1))
3928            .strategy(ThrottleStrategy::Delay)
3929            .to("mock:result")
3930            .end_throttle()
3931            .build()
3932            .unwrap();
3933
3934        if let BuilderStep::Throttle { config, .. } = &definition.steps()[0] {
3935            assert_eq!(config.strategy, ThrottleStrategy::Delay);
3936        } else {
3937            panic!("Expected Throttle step");
3938        }
3939    }
3940
3941    #[test]
3942    fn test_throttle_builder_drop_strategy() {
3943        let definition = RouteBuilder::from("timer:tick")
3944            .route_id("throttle-drop")
3945            .throttle(10, Duration::from_secs(1))
3946            .strategy(ThrottleStrategy::Drop)
3947            .to("mock:result")
3948            .end_throttle()
3949            .build()
3950            .unwrap();
3951
3952        if let BuilderStep::Throttle { config, .. } = &definition.steps()[0] {
3953            assert_eq!(config.strategy, ThrottleStrategy::Drop);
3954        } else {
3955            panic!("Expected Throttle step");
3956        }
3957    }
3958
3959    // ── LoopInLoopBuilder with loop_while ───────────────────────────────────────
3960
3961    #[test]
3962    fn test_nested_loop_while_builder() {
3963        use camel_api::loop_eip::LoopMode;
3964
3965        let def = RouteBuilder::from("direct:start")
3966            .route_id("nested-loop-while")
3967            .loop_count(2)
3968            .to("mock:outer")
3969            .loop_while(|_ex| true)
3970            .to("mock:inner")
3971            .end_loop()
3972            .end_loop()
3973            .build()
3974            .unwrap();
3975
3976        assert_eq!(def.steps().len(), 1);
3977        if let BuilderStep::Loop { steps, .. } = &def.steps()[0] {
3978            assert_eq!(steps.len(), 2);
3979            if let BuilderStep::Loop { config, .. } = &steps[1] {
3980                assert!(matches!(config.mode, LoopMode::While(_)));
3981            } else {
3982                panic!("Expected inner Loop step");
3983            }
3984        } else {
3985            panic!("Expected outer Loop step");
3986        }
3987    }
3988
3989    // ── Choice with multiple whens + otherwise ──────────────────────────────────
3990
3991    #[test]
3992    fn test_choice_builder_multiple_whens_with_otherwise() {
3993        let definition = RouteBuilder::from("timer:tick")
3994            .route_id("choice-multi-otherwise")
3995            .choice()
3996            .when(|ex: &Exchange| ex.input.header("a").is_some())
3997            .to("mock:a")
3998            .end_when()
3999            .when(|ex: &Exchange| ex.input.header("b").is_some())
4000            .to("mock:b")
4001            .end_when()
4002            .when(|ex: &Exchange| ex.input.header("c").is_some())
4003            .to("mock:c")
4004            .end_when()
4005            .otherwise()
4006            .to("mock:fallback")
4007            .end_otherwise()
4008            .end_choice()
4009            .build()
4010            .unwrap();
4011
4012        if let BuilderStep::Choice { whens, otherwise } = &definition.steps()[0] {
4013            assert_eq!(whens.len(), 3);
4014            assert!(otherwise.is_some());
4015            assert_eq!(otherwise.as_ref().unwrap().len(), 1);
4016        } else {
4017            panic!("Expected Choice step");
4018        }
4019    }
4020
4021    // ── Multicast individual config tests ───────────────────────────────────────
4022
4023    #[test]
4024    fn test_multicast_builder_parallel_only() {
4025        let route = RouteBuilder::from("direct:start")
4026            .route_id("multicast-parallel")
4027            .multicast()
4028            .parallel(true)
4029            .to("mock:a")
4030            .end_multicast()
4031            .build()
4032            .unwrap();
4033
4034        if let BuilderStep::Multicast { config, .. } = &route.steps()[0] {
4035            assert!(config.parallel);
4036            assert_eq!(config.parallel_limit, None);
4037        } else {
4038            panic!("Expected Multicast step");
4039        }
4040    }
4041
4042    #[test]
4043    fn test_multicast_builder_timeout_only() {
4044        let route = RouteBuilder::from("direct:start")
4045            .route_id("multicast-timeout")
4046            .multicast()
4047            .timeout(Duration::from_secs(5))
4048            .to("mock:a")
4049            .end_multicast()
4050            .build()
4051            .unwrap();
4052
4053        if let BuilderStep::Multicast { config, .. } = &route.steps()[0] {
4054            assert_eq!(config.timeout, Some(Duration::from_secs(5)));
4055        } else {
4056            panic!("Expected Multicast step");
4057        }
4058    }
4059
4060    #[test]
4061    fn test_multicast_builder_aggregation_collect_all() {
4062        let route = RouteBuilder::from("direct:start")
4063            .route_id("multicast-collect")
4064            .multicast()
4065            .aggregation(MulticastStrategy::CollectAll)
4066            .to("mock:a")
4067            .end_multicast()
4068            .build()
4069            .unwrap();
4070
4071        if let BuilderStep::Multicast { config, .. } = &route.steps()[0] {
4072            assert!(matches!(config.aggregation, MulticastStrategy::CollectAll));
4073        } else {
4074            panic!("Expected Multicast step");
4075        }
4076    }
4077
4078    // ── extract_completion_fields: Any mode with multiple conditions ────────────
4079
4080    #[test]
4081    fn test_build_canonical_aggregate_any_completion_mode() {
4082        let spec = RouteBuilder::from("direct:start")
4083            .route_id("canonical-any-completion")
4084            .aggregate(
4085                AggregatorConfig::correlate_by("key")
4086                    .complete_on_size_or_timeout(10, Duration::from_secs(30))
4087                    .build()
4088                    .unwrap(),
4089            )
4090            .build_canonical()
4091            .unwrap();
4092
4093        if let CanonicalStepSpec::Aggregate(agg) = &spec.steps[0] {
4094            assert_eq!(agg.completion_size, Some(10));
4095            assert_eq!(agg.completion_timeout_ms, Some(30_000));
4096        } else {
4097            panic!("Expected Aggregate step");
4098        }
4099    }
4100
4101    #[test]
4102    fn test_build_canonical_aggregate_timeout_completion() {
4103        let spec = RouteBuilder::from("direct:start")
4104            .route_id("canonical-timeout-completion")
4105            .aggregate(
4106                AggregatorConfig::correlate_by("key")
4107                    .complete_on_timeout(Duration::from_millis(500))
4108                    .build()
4109                    .unwrap(),
4110            )
4111            .build_canonical()
4112            .unwrap();
4113
4114        if let CanonicalStepSpec::Aggregate(agg) = &spec.steps[0] {
4115            assert_eq!(agg.completion_size, None);
4116            assert_eq!(agg.completion_timeout_ms, Some(500));
4117        } else {
4118            panic!("Expected Aggregate step");
4119        }
4120    }
4121
4122    // ── canonicalize_aggregate: discard_on_timeout and force_completion_on_stop ─
4123
4124    #[test]
4125    fn test_build_canonical_aggregate_discard_on_timeout() {
4126        use camel_api::aggregator::AggregatorConfig;
4127
4128        let spec = RouteBuilder::from("direct:start")
4129            .route_id("canonical-discard-timeout")
4130            .aggregate(
4131                AggregatorConfig::correlate_by("key")
4132                    .complete_when_size(1)
4133                    .discard_on_timeout(true)
4134                    .build()
4135                    .unwrap(),
4136            )
4137            .build_canonical()
4138            .unwrap();
4139
4140        if let CanonicalStepSpec::Aggregate(agg) = &spec.steps[0] {
4141            assert_eq!(agg.discard_on_timeout, Some(true));
4142        } else {
4143            panic!("Expected Aggregate step");
4144        }
4145    }
4146
4147    #[test]
4148    fn test_build_canonical_aggregate_force_completion_on_stop() {
4149        use camel_api::aggregator::AggregatorConfig;
4150
4151        let spec = RouteBuilder::from("direct:start")
4152            .route_id("canonical-force-stop")
4153            .aggregate(
4154                AggregatorConfig::correlate_by("key")
4155                    .complete_when_size(1)
4156                    .force_completion_on_stop(true)
4157                    .build()
4158                    .unwrap(),
4159            )
4160            .build_canonical()
4161            .unwrap();
4162
4163        if let CanonicalStepSpec::Aggregate(agg) = &spec.steps[0] {
4164            assert_eq!(agg.force_completion_on_stop, Some(true));
4165        } else {
4166            panic!("Expected Aggregate step");
4167        }
4168    }
4169
4170    // ── build_canonical: max_buckets and bucket_ttl ─────────────────────────────
4171
4172    #[test]
4173    fn test_build_canonical_aggregate_max_buckets_and_ttl() {
4174        use camel_api::aggregator::AggregatorConfig;
4175
4176        let spec = RouteBuilder::from("direct:start")
4177            .route_id("canonical-buckets-ttl")
4178            .aggregate(
4179                AggregatorConfig::correlate_by("key")
4180                    .complete_when_size(1)
4181                    .max_buckets(100)
4182                    .bucket_ttl(Duration::from_secs(60))
4183                    .build()
4184                    .unwrap(),
4185            )
4186            .build_canonical()
4187            .unwrap();
4188
4189        if let CanonicalStepSpec::Aggregate(agg) = &spec.steps[0] {
4190            assert_eq!(agg.max_buckets, Some(100));
4191            assert_eq!(agg.bucket_ttl_ms, Some(60_000));
4192        } else {
4193            panic!("Expected Aggregate step");
4194        }
4195    }
4196
4197    // ── canonicalize_aggregate: correlation strategy → correlation_key mapping ──
4198    //
4199    // These tests pin the canonicalize half of the expression round-trip
4200    // scenario. The recompile half is
4201    // `canonical_recompile_of_canonicalized_expression_config_yields_expression`
4202    // in camel-dsl compile.rs (task 2.4) — camel-builder has no camel-dsl
4203    // dependency, so the two halves live in their own crates.
4204
4205    #[test]
4206    fn canonicalize_aggregate_expression_maps_correlation_key() {
4207        use camel_api::aggregator::AggregatorConfig;
4208
4209        let config = AggregatorConfig::correlate_by("seed")
4210            .correlate_by_expr("${header.orderId}", "simple")
4211            .complete_when_size(2)
4212            .build()
4213            .unwrap();
4214
4215        let spec = canonicalize_aggregate(config).unwrap();
4216
4217        assert_eq!(spec.correlation_key, Some("${header.orderId}".to_string()));
4218        assert_eq!(spec.header, "${header.orderId}");
4219    }
4220
4221    #[test]
4222    fn canonicalize_aggregate_header_only_maps_no_correlation_key() {
4223        use camel_api::aggregator::AggregatorConfig;
4224
4225        let config = AggregatorConfig::correlate_by("orderId")
4226            .complete_when_size(2)
4227            .build()
4228            .unwrap();
4229
4230        let spec = canonicalize_aggregate(config).unwrap();
4231
4232        assert_eq!(spec.correlation_key, None);
4233        assert_eq!(spec.header, "orderId");
4234    }
4235
4236    // ── SplitBuilder with filter inside ─────────────────────────────────────────
4237
4238    #[test]
4239    fn test_split_builder_with_filter_inside() {
4240        use camel_api::splitter::{SplitterConfig, split_body_lines};
4241
4242        let definition = RouteBuilder::from("timer:test")
4243            .route_id("split-with-filter")
4244            .split(SplitterConfig::new(split_body_lines()))
4245            .filter(|_ex| true)
4246            .to("mock:filtered-frag")
4247            .end_filter()
4248            .end_split()
4249            .build()
4250            .unwrap();
4251
4252        if let BuilderStep::Split { steps, .. } = &definition.steps()[0] {
4253            assert_eq!(steps.len(), 1);
4254            assert!(matches!(&steps[0], BuilderStep::Filter { .. }));
4255        } else {
4256            panic!("Expected Split step");
4257        }
4258    }
4259
4260    // ── WireTap additional tests ────────────────────────────────────────────────
4261
4262    #[test]
4263    fn test_wire_tap_multiple_taps() {
4264        let definition = RouteBuilder::from("timer:tick")
4265            .route_id("multi-wire-tap")
4266            .wire_tap("mock:tap1")
4267            .wire_tap("mock:tap2")
4268            .to("mock:result")
4269            .build()
4270            .unwrap();
4271
4272        assert_eq!(definition.steps().len(), 3);
4273        assert!(
4274            matches!(&definition.steps()[0], BuilderStep::WireTap { uri } if uri == "mock:tap1")
4275        );
4276        assert!(
4277            matches!(&definition.steps()[1], BuilderStep::WireTap { uri } if uri == "mock:tap2")
4278        );
4279    }
4280
4281    // ── Error handler: explicit config after shorthand → Mixed mode ─────────────
4282
4283    #[test]
4284    fn test_builder_shorthand_then_explicit_mixed_mode() {
4285        let result = RouteBuilder::from("direct:start")
4286            .route_id("mixed-mode-2")
4287            .dead_letter_channel("log:dlc")
4288            .error_handler(ErrorHandlerConfig::log_only())
4289            .to("mock:out")
4290            .build();
4291
4292        let err = result.err().expect("mixed mode should fail");
4293        assert!(format!("{err}").contains("mixed error handler modes"));
4294    }
4295
4296    // ── build_canonical: empty from_uri error ───────────────────────────────────
4297
4298    #[test]
4299    fn test_build_canonical_empty_from_uri_errors() {
4300        let result = RouteBuilder::from("").route_id("test").build_canonical();
4301        assert!(result.is_err());
4302    }
4303
4304    #[test]
4305    fn test_build_canonical_missing_route_id_errors() {
4306        let result = RouteBuilder::from("direct:start").build_canonical();
4307        assert!(result.is_err());
4308        let err = result.unwrap_err().to_string();
4309        assert!(err.contains("route_id"));
4310    }
4311
4312    // ── SplitBuilder: aggregate inside split ────────────────────────────────────
4313
4314    #[test]
4315    fn test_split_builder_with_aggregate_inside() {
4316        use camel_api::aggregator::AggregatorConfig;
4317        use camel_api::splitter::{SplitterConfig, split_body_lines};
4318
4319        let definition = RouteBuilder::from("timer:test")
4320            .route_id("split-agg")
4321            .split(SplitterConfig::new(split_body_lines()))
4322            .aggregate(
4323                AggregatorConfig::correlate_by("frag-key")
4324                    .complete_when_size(3)
4325                    .build()
4326                    .unwrap(),
4327            )
4328            .end_split()
4329            .build()
4330            .unwrap();
4331
4332        if let BuilderStep::Split { steps, .. } = &definition.steps()[0] {
4333            assert_eq!(steps.len(), 1);
4334            assert!(matches!(&steps[0], BuilderStep::Aggregate { .. }));
4335        } else {
4336            panic!("Expected Split step");
4337        }
4338    }
4339
4340    // ── Throttle: steps collected inside throttle scope ─────────────────────────
4341
4342    #[test]
4343    fn test_throttle_builder_with_steps_inside() {
4344        let definition = RouteBuilder::from("timer:tick")
4345            .route_id("throttle-steps")
4346            .throttle(10, Duration::from_secs(1))
4347            .set_header("throttled", Value::Bool(true))
4348            .to("mock:throttled")
4349            .end_throttle()
4350            .build()
4351            .unwrap();
4352
4353        if let BuilderStep::Throttle { steps, .. } = &definition.steps()[0] {
4354            assert_eq!(steps.len(), 2);
4355        } else {
4356            panic!("Expected Throttle step");
4357        }
4358    }
4359
4360    // ── LoadBalance: steps collected inside scope ───────────────────────────────
4361
4362    #[test]
4363    fn test_load_balance_builder_with_steps_inside() {
4364        let definition = RouteBuilder::from("timer:tick")
4365            .route_id("lb-steps")
4366            .load_balance()
4367            .round_robin()
4368            .set_header("lb", Value::Bool(true))
4369            .to("mock:lb")
4370            .end_load_balance()
4371            .build()
4372            .unwrap();
4373
4374        if let BuilderStep::LoadBalance { steps, .. } = &definition.steps()[0] {
4375            assert_eq!(steps.len(), 2);
4376        } else {
4377            panic!("Expected LoadBalance step");
4378        }
4379    }
4380
4381    // ── Multicast: steps collected inside scope ─────────────────────────────────
4382
4383    #[test]
4384    fn test_multicast_builder_with_steps_inside() {
4385        let definition = RouteBuilder::from("timer:tick")
4386            .route_id("multicast-steps")
4387            .multicast()
4388            .set_header("mc", Value::Bool(true))
4389            .to("mock:multicast")
4390            .end_multicast()
4391            .build()
4392            .unwrap();
4393
4394        if let BuilderStep::Multicast { steps, .. } = &definition.steps()[0] {
4395            assert_eq!(steps.len(), 2);
4396        } else {
4397            panic!("Expected Multicast step");
4398        }
4399    }
4400
4401    // ── LoopBuilder: steps collected inside loop scope ──────────────────────────
4402
4403    #[test]
4404    fn test_loop_builder_with_steps_inside() {
4405        let definition = RouteBuilder::from("timer:tick")
4406            .route_id("loop-steps")
4407            .loop_count(3)
4408            .set_header("loop", Value::Bool(true))
4409            .to("mock:loop")
4410            .end_loop()
4411            .build()
4412            .unwrap();
4413
4414        if let BuilderStep::Loop { steps, .. } = &definition.steps()[0] {
4415            assert_eq!(steps.len(), 2);
4416        } else {
4417            panic!("Expected Loop step");
4418        }
4419    }
4420
4421    // ── canonical_step_name coverage for remaining variants ─────────────────────
4422
4423    #[test]
4424    fn test_build_canonical_rejects_loop_step() {
4425        let err = RouteBuilder::from("direct:start")
4426            .route_id("canonical-loop")
4427            .loop_count(3)
4428            .to("mock:loop")
4429            .end_loop()
4430            .build_canonical()
4431            .unwrap_err();
4432
4433        assert!(format!("{err}").contains("does not support step `loop`"));
4434    }
4435
4436    #[test]
4437    fn test_build_canonical_rejects_multicast_step() {
4438        let err = RouteBuilder::from("direct:start")
4439            .route_id("canonical-multicast")
4440            .multicast()
4441            .to("mock:a")
4442            .end_multicast()
4443            .build_canonical()
4444            .unwrap_err();
4445
4446        assert!(format!("{err}").contains("does not support step `multicast`"));
4447    }
4448
4449    #[test]
4450    fn test_build_canonical_rejects_throttle_step() {
4451        let err = RouteBuilder::from("direct:start")
4452            .route_id("canonical-throttle")
4453            .throttle(10, Duration::from_secs(1))
4454            .to("mock:result")
4455            .end_throttle()
4456            .build_canonical()
4457            .unwrap_err();
4458
4459        assert!(format!("{err}").contains("does not support step `throttle`"));
4460    }
4461
4462    #[test]
4463    fn test_build_canonical_rejects_load_balancer_step() {
4464        let err = RouteBuilder::from("direct:start")
4465            .route_id("canonical-lb")
4466            .load_balance()
4467            .round_robin()
4468            .to("mock:result")
4469            .end_load_balance()
4470            .build_canonical()
4471            .unwrap_err();
4472
4473        assert!(format!("{err}").contains("does not support step `load_balancer`"));
4474    }
4475
4476    #[test]
4477    fn test_build_canonical_rejects_bean_step() {
4478        let err = RouteBuilder::from("direct:start")
4479            .route_id("canonical-bean")
4480            .bean("myBean", "process")
4481            .build_canonical()
4482            .unwrap_err();
4483
4484        assert!(format!("{err}").contains("does not support step `bean`"));
4485    }
4486
4487    #[test]
4488    fn test_build_canonical_rejects_script_step() {
4489        let err = RouteBuilder::from("direct:start")
4490            .route_id("canonical-script")
4491            .script("rhai", "x = 1")
4492            .build_canonical()
4493            .unwrap_err();
4494
4495        assert!(format!("{err}").contains("does not support step `script`"));
4496    }
4497
4498    #[test]
4499    fn test_build_canonical_accepts_delay_step() {
4500        let spec = RouteBuilder::from("direct:start")
4501            .route_id("canonical-delay")
4502            .delay(Duration::from_millis(100))
4503            .build_canonical()
4504            .unwrap();
4505
4506        assert!(
4507            spec.steps.iter().any(
4508                |s| matches!(s, CanonicalStepSpec::Delay { delay_ms, .. } if *delay_ms == 100)
4509            )
4510        );
4511    }
4512
4513    #[test]
4514    fn test_build_canonical_accepts_wire_tap_step() {
4515        let spec = RouteBuilder::from("direct:start")
4516            .route_id("canonical-wiretap")
4517            .wire_tap("mock:tap")
4518            .build_canonical()
4519            .unwrap();
4520
4521        assert!(
4522            spec.steps
4523                .iter()
4524                .any(|s| matches!(s, CanonicalStepSpec::WireTap { uri } if uri == "mock:tap"))
4525        );
4526    }
4527
4528    #[test]
4529    fn test_build_canonical_rejects_dynamic_router_step() {
4530        let err = RouteBuilder::from("direct:start")
4531            .route_id("canonical-dyn-router")
4532            .dynamic_router(camel_api::TargetSource::Sync(Arc::new(|_| {
4533                Some("mock:a".to_string())
4534            })))
4535            .build_canonical()
4536            .unwrap_err();
4537
4538        assert!(format!("{err}").contains("does not support step `dynamic_router`"));
4539    }
4540
4541    #[test]
4542    fn test_build_canonical_rejects_routing_slip_step() {
4543        let err = RouteBuilder::from("direct:start")
4544            .route_id("canonical-routing-slip")
4545            .routing_slip(camel_api::TargetSource::Sync(Arc::new(|_| {
4546                Some("mock:a".to_string())
4547            })))
4548            .build_canonical()
4549            .unwrap_err();
4550
4551        assert!(format!("{err}").contains("does not support step `routing_slip`"));
4552    }
4553
4554    #[test]
4555    fn test_build_canonical_rejects_recipient_list_step() {
4556        let err = RouteBuilder::from("direct:start")
4557            .route_id("canonical-recipient")
4558            .recipient_list(camel_api::RecipientSource::Sync(Arc::new(|_| {
4559                "mock:a".to_string()
4560            })))
4561            .build_canonical()
4562            .unwrap_err();
4563
4564        assert!(format!("{err}").contains("does not support step `recipient_list`"));
4565    }
4566
4567    // ── extract_completion_fields: Any mode with predicate → error ──────────────
4568
4569    #[test]
4570    fn test_build_canonical_rejects_any_mode_with_predicate() {
4571        let err = RouteBuilder::from("direct:start")
4572            .route_id("canonical-any-pred")
4573            .aggregate(AggregatorConfig {
4574                header_name: "key".to_string(),
4575                completion: CompletionMode::Any(vec![
4576                    CompletionCondition::Size(5),
4577                    CompletionCondition::Predicate(Arc::new(|_| false)),
4578                ]),
4579                correlation: CorrelationStrategy::HeaderName("key".to_string()),
4580                strategy: AggregationStrategy::CollectAll,
4581                max_buckets: None,
4582                max_bucket_size: None,
4583                bucket_ttl: None,
4584                force_completion_on_stop: false,
4585                discard_on_timeout: false,
4586                max_timeout_tasks: 1024,
4587            })
4588            .build_canonical()
4589            .unwrap_err();
4590
4591        assert!(
4592            format!("{err}").contains("cannot reverse-map"),
4593            "reject message must explain forward-only: {}",
4594            err
4595        );
4596    }
4597
4598    // ── BUILDER-004: Validation errors for missing required fields ────────────
4599
4600    #[test]
4601    fn test_builder_validation_missing_from_uri() {
4602        let result = RouteBuilder::from("")
4603            .route_id("missing-uri-route")
4604            .to("log:info")
4605            .build();
4606        assert!(result.is_err(), "empty from URI should fail validation");
4607        let err = result.err().unwrap().to_string();
4608        assert!(
4609            err.contains("'from'") || err.contains("URI"),
4610            "error should mention from/URI, got: {err}"
4611        );
4612    }
4613
4614    #[test]
4615    fn test_builder_validation_invalid_step_uri_scheme() {
4616        let result = RouteBuilder::from("timer:tick")
4617            .route_id("bad-step-route")
4618            .to("not-a-valid-uri") // no scheme
4619            .build();
4620        // The builder itself accepts any URI string; validation happens at
4621        // resolution time. Verify the build succeeds (step URI is deferred).
4622        assert!(
4623            result.is_ok(),
4624            "builder should accept opaque step URIs; resolution happens later"
4625        );
4626    }
4627
4628    // ── rc-p9vq: Duplicate route IDs ──────────────────────────────────────
4629
4630    #[test]
4631    fn test_builder_duplicate_route_ids_produce_identical_definitions() {
4632        // The builder itself doesn't check for duplicates (that's context-level).
4633        // Verify both builds succeed with the same ID — detection is TODO(rc-p9vq).
4634        let route1 = RouteBuilder::from("direct:a")
4635            .route_id("dup-route")
4636            .to("mock:out")
4637            .build();
4638        let route2 = RouteBuilder::from("direct:b")
4639            .route_id("dup-route")
4640            .to("mock:out")
4641            .build();
4642
4643        assert!(route1.is_ok());
4644        assert!(route2.is_ok());
4645        assert_eq!(route1.unwrap().route_id(), route2.unwrap().route_id());
4646    }
4647
4648    #[test]
4649    fn test_builder_clone_reuse_as_template() {
4650        // rc-8m5o: a partially-built RouteBuilder can be cloned and reused as a
4651        // template, then each clone varied independently before build().
4652        let template = RouteBuilder::from("direct:in")
4653            .set_header("stage", Value::String("shared".into()))
4654            .log("shared prefix", LogLevel::Info);
4655
4656        let route_a = template
4657            .clone()
4658            .route_id("route-a")
4659            .to("mock:a")
4660            .build()
4661            .expect("clone A builds");
4662        let route_b = template
4663            .route_id("route-b")
4664            .to("mock:b")
4665            .build()
4666            .expect("clone B builds");
4667
4668        assert_eq!(route_a.route_id(), "route-a");
4669        assert_eq!(route_b.route_id(), "route-b");
4670        // Shared template steps (set_header + log) are present in both, plus the
4671        // per-clone `to` step: the clone is a deep copy, not an alias.
4672        assert_eq!(route_a.steps().len(), route_b.steps().len());
4673        assert_eq!(route_a.from_uri(), route_b.from_uri());
4674    }
4675
4676    // ── stream_split builder tests ──────────────────────────────────────────
4677
4678    fn test_stream_split_expression() -> camel_api::StreamingSplitExpression {
4679        camel_processor::zip_splitter::zip_splitter(
4680            camel_processor::zip_splitter::ZipSplitConfig::default(),
4681        )
4682    }
4683
4684    #[test]
4685    fn stream_split_builder_emits_variant_with_defaults() {
4686        let definition = RouteBuilder::from("direct:start")
4687            .route_id("stream-split-defaults")
4688            .stream_split(test_stream_split_expression())
4689            .log("fragment", LogLevel::Info)
4690            .end_stream_split()
4691            .build()
4692            .expect("route should build");
4693
4694        let steps = definition.steps();
4695        assert_eq!(steps.len(), 1);
4696        match &steps[0] {
4697            BuilderStep::StreamSplit {
4698                aggregation,
4699                stop_on_exception,
4700                steps,
4701                ..
4702            } => {
4703                assert!(matches!(
4704                    aggregation,
4705                    camel_api::splitter::AggregationStrategy::LastWins
4706                ));
4707                assert!(*stop_on_exception);
4708                assert_eq!(steps.len(), 1);
4709            }
4710            other => panic!("expected StreamSplit step, got {other:?}"),
4711        }
4712    }
4713
4714    #[test]
4715    fn stream_split_builder_setters_override() {
4716        let definition = RouteBuilder::from("direct:start")
4717            .route_id("stream-split-overrides")
4718            .stream_split(test_stream_split_expression())
4719            .aggregation(camel_api::splitter::AggregationStrategy::CollectAll)
4720            .stop_on_exception(false)
4721            .log("fragment", LogLevel::Info)
4722            .end_stream_split()
4723            .build()
4724            .expect("route should build");
4725
4726        let steps = definition.steps();
4727        assert_eq!(steps.len(), 1);
4728        match &steps[0] {
4729            BuilderStep::StreamSplit {
4730                aggregation,
4731                stop_on_exception,
4732                steps,
4733                ..
4734            } => {
4735                assert!(matches!(
4736                    aggregation,
4737                    camel_api::splitter::AggregationStrategy::CollectAll
4738                ));
4739                assert!(!*stop_on_exception);
4740                assert_eq!(steps.len(), 1);
4741            }
4742            other => panic!("expected StreamSplit step, got {other:?}"),
4743        }
4744    }
4745}