Skip to main content

camel_api/
splitter.rs

1use std::pin::Pin;
2use std::sync::Arc;
3
4use futures::Stream;
5
6use crate::body::{Body, body_type_name};
7use crate::error::CamelError;
8use crate::exchange::Exchange;
9use crate::message::Message;
10use crate::value::Value;
11
12/// A function that splits a single exchange into multiple fragment exchanges.
13///
14/// Built-in expressions return [`CamelError::TypeConversionFailed`] when the
15/// body type does not match their input contract; empty-content bodies yield
16/// `Ok(Vec::new())` (pass-through).
17pub type SplitExpression =
18    Arc<dyn Fn(&Exchange) -> Result<Vec<Exchange>, CamelError> + Send + Sync>;
19
20/// Fallible split source: a synchronous [`SplitExpression`] or a
21/// language-backed asynchronous expression.
22///
23/// The async arm evaluates to a [`Value`]; fragments are derived with the
24/// canonical split rules (string → non-empty line fragments, array → one
25/// fragment per element). Evaluation errors propagate before any fragment
26/// is materialized.
27#[derive(Clone)]
28#[non_exhaustive]
29pub enum SplitSource {
30    /// Programmatic synchronous splitter.
31    Sync(SplitExpression),
32    /// Language-backed asynchronous expression.
33    Async(Arc<dyn Fn(&Exchange) -> crate::filter::BoxValueFuture + Send + Sync>),
34}
35
36impl From<SplitExpression> for SplitSource {
37    fn from(f: SplitExpression) -> Self {
38        Self::Sync(f)
39    }
40}
41
42impl SplitSource {
43    /// Split `exchange` into fragments, propagating evaluation failures.
44    pub async fn split(&self, exchange: &Exchange) -> Result<Vec<Exchange>, CamelError> {
45        match self {
46            Self::Sync(f) => f(exchange),
47            Self::Async(f) => derive_fragments(exchange, f(exchange).await?),
48        }
49    }
50}
51
52/// Derive fragment exchanges from an evaluated language value.
53///
54/// Mirrors the rules previously inlined in camel-core `splitting.rs`
55/// (DeclarativeSplit): a string yields one fragment per non-empty line; an
56/// array yields one fragment per element (string elements become text
57/// bodies, everything else JSON); anything else is a type error.
58fn derive_fragments(exchange: &Exchange, value: Value) -> Result<Vec<Exchange>, CamelError> {
59    match value {
60        Value::String(s) => Ok(s
61            .lines()
62            .filter(|line| !line.is_empty())
63            .map(|line| {
64                let mut fragment = exchange.clone();
65                fragment.input.body = Body::from(line.to_string());
66                fragment
67            })
68            .collect()),
69        Value::Array(arr) => Ok(arr
70            .into_iter()
71            .map(|v| {
72                let mut fragment = exchange.clone();
73                fragment.input.body = match v {
74                    Value::String(s) => Body::Text(s),
75                    other => Body::Json(other),
76                };
77                fragment
78            })
79            .collect()),
80        other => Err(CamelError::TypeConversionFailed(format!(
81            "declarative split requires a text or array value, got {received}; add an unmarshal step before split",
82            received = crate::value_type_name(&other)
83        ))),
84    }
85}
86
87/// A function that lazily produces a stream of exchange fragments.
88///
89/// Used by `StreamingSplitterService` (camel-processor) for v1 sequential streaming split
90/// (e.g., ZIP entry extraction, CSV/JSON streaming in future work).
91///
92/// Each call returns a `Stream` that yields fragments one at a time.
93pub type StreamingSplitExpression = Arc<
94    dyn Fn(Exchange) -> Pin<Box<dyn Stream<Item = Result<Exchange, CamelError>> + Send>>
95        + Send
96        + Sync,
97>;
98
99/// Typed error returned when a streaming split receives a body that is not
100/// `Body::Stream`. Shared by the compiled production expression, the test
101/// mirrors, and examples so the message cannot drift between copies.
102pub fn streaming_split_type_error(body: &Body) -> CamelError {
103    CamelError::TypeConversionFailed(format!(
104        "streaming split requires body type stream, got {}; add an unmarshal step before split",
105        body_type_name(body)
106    ))
107}
108
109/// Strategy for aggregating fragment results back into a single exchange.
110#[derive(Clone, Default)]
111#[non_exhaustive]
112pub enum AggregationStrategy {
113    /// Result is the last fragment's exchange (default).
114    #[default]
115    LastWins,
116    /// Collects all fragment bodies into a JSON array.
117    CollectAll,
118    /// Returns the original exchange unchanged.
119    Original,
120    /// Custom aggregation function: `(accumulated, next) -> merged`.
121    Custom(Arc<dyn Fn(Exchange, Exchange) -> Exchange + Send + Sync>),
122}
123
124impl std::fmt::Debug for AggregationStrategy {
125    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
126        match self {
127            AggregationStrategy::LastWins => f.write_str("LastWins"),
128            AggregationStrategy::CollectAll => f.write_str("CollectAll"),
129            AggregationStrategy::Original => f.write_str("Original"),
130            AggregationStrategy::Custom(_) => f.write_str("Custom(..)"),
131        }
132    }
133}
134
135/// The streaming format to use when splitting a stream body.
136#[derive(
137    Clone,
138    Debug,
139    Default,
140    PartialEq,
141    Eq,
142    serde::Serialize,
143    serde::Deserialize,
144    schemars::JsonSchema,
145    ts_rs::TS,
146)]
147#[serde(rename_all = "snake_case")]
148#[ts(rename_all = "snake_case")]
149#[non_exhaustive]
150pub enum StreamSplitFormat {
151    /// Auto-detect the format from the body content.
152    #[default]
153    Auto,
154    /// Newline-delimited JSON — each line is a complete JSON value.
155    Ndjson,
156    /// Split by newlines, each line becomes a text fragment.
157    Lines,
158    /// Split into fixed-size byte chunks.
159    Chunks,
160    /// ZIP archive — materialized format, each entry becomes a fragment exchange.
161    Zip,
162    /// TAR archive — materialized format, each regular-file entry becomes a fragment exchange.
163    Tar,
164    /// GZIP-compressed TAR archive — materialized format, each regular-file entry becomes a fragment exchange.
165    #[serde(rename = "tar.gz")]
166    #[ts(rename = "tar.gz")]
167    TarGz,
168}
169
170/// Configuration for splitting a streaming body into fragments.
171///
172/// Controls how the stream splitter processes the body, including format
173/// detection, sizing limits, and metadata propagation.
174#[derive(
175    Clone,
176    Debug,
177    PartialEq,
178    Eq,
179    serde::Serialize,
180    serde::Deserialize,
181    schemars::JsonSchema,
182    ts_rs::TS,
183)]
184#[serde(rename_all = "snake_case")]
185#[ts(rename_all = "snake_case")]
186pub struct StreamSplitConfig {
187    /// The streaming format to use.
188    pub format: StreamSplitFormat,
189    /// Maximum size (in bytes) of a single record or chunk.
190    pub max_record_bytes: usize,
191    /// Number of records/chunks to collect into a single exchange batch.
192    pub batch_size: usize,
193    /// Explicit chunk size in bytes (required when format is [`Chunks`](StreamSplitFormat::Chunks)).
194    pub chunk_size: Option<usize>,
195    /// Whether to include origin metadata in each fragment.
196    pub include_origin: bool,
197}
198
199impl Default for StreamSplitConfig {
200    fn default() -> Self {
201        Self {
202            format: StreamSplitFormat::Auto,
203            max_record_bytes: 1024 * 1024,
204            batch_size: 1,
205            chunk_size: None,
206            include_origin: true,
207        }
208    }
209}
210
211impl StreamSplitConfig {
212    /// Validates the configuration.
213    ///
214    /// # Errors
215    ///
216    /// Returns [`CamelError::Config`] if:
217    /// - `batch_size` is `0`
218    /// - `max_record_bytes` is `0`
219    /// - `format` is [`Chunks`](StreamSplitFormat::Chunks) but `chunk_size` is `None`
220    /// - `format` is a materialized archive format ([`Zip`](StreamSplitFormat::Zip),
221    ///   [`Tar`](StreamSplitFormat::Tar), [`TarGz`](StreamSplitFormat::TarGz)) but
222    ///   `chunk_size` is `Some(...)`
223    /// - `chunk_size` is `Some(0)`
224    pub fn validate(&self) -> Result<(), CamelError> {
225        if self.batch_size == 0 {
226            return Err(CamelError::Config(
227                "stream split batch_size must be > 0".into(),
228            ));
229        }
230        if self.max_record_bytes == 0 {
231            return Err(CamelError::Config(
232                "stream split max_record_bytes must be > 0".into(),
233            ));
234        }
235        if self.format == StreamSplitFormat::Chunks && self.chunk_size.is_none() {
236            return Err(CamelError::Config(
237                "stream split format=Chunks requires chunk_size".into(),
238            ));
239        }
240        // Materialized archive formats split whole entries, not byte chunks,
241        // so chunk_size is meaningless. The Zip+chunk_size check must come
242        // before the generic chunk_size zero/exceeds checks so that
243        // `Zip + Some(0)` yields the more specific error.
244        if self.format == StreamSplitFormat::Zip && self.chunk_size.is_some() {
245            return Err(CamelError::Config(
246                "stream split format=Zip does not support chunk_size".into(),
247            ));
248        }
249        if matches!(
250            self.format,
251            StreamSplitFormat::Tar | StreamSplitFormat::TarGz
252        ) && self.chunk_size.is_some()
253        {
254            return Err(CamelError::Config(format!(
255                "stream split format={:?} is a materialized archive format and does not support chunk_size",
256                self.format
257            )));
258        }
259        if let Some(cs) = self.chunk_size
260            && cs == 0
261        {
262            return Err(CamelError::Config(
263                "stream split chunk_size must be > 0".into(),
264            ));
265        }
266        if self.format == StreamSplitFormat::Chunks
267            && let Some(cs) = self.chunk_size
268            && cs > self.max_record_bytes
269        {
270            return Err(CamelError::Config(
271                "stream split chunk_size must be <= max_record_bytes".into(),
272            ));
273        }
274        Ok(())
275    }
276}
277
278/// Default threshold above which split fragments start new traces (0 = off).
279pub const DEFAULT_TRACE_ITEM_THRESHOLD: usize = 100;
280
281/// Configuration for the Splitter EIP.
282#[derive(Clone)]
283pub struct SplitterConfig {
284    /// Expression that splits an exchange into fragments.
285    pub expression: SplitSource,
286    /// How to aggregate fragment results.
287    pub aggregation: AggregationStrategy,
288    /// Whether to process fragments in parallel.
289    pub parallel: bool,
290    /// Maximum number of parallel fragments (None = unlimited).
291    pub parallel_limit: Option<usize>,
292    /// Whether to stop processing on the first exception.
293    ///
294    /// In parallel mode this only affects aggregation (the first error is
295    /// propagated), **not** in-flight futures — `join_all` cannot cancel
296    /// already-spawned work.
297    pub stop_on_exception: bool,
298    /// Maximum number of fragments materialized by `expression` (DoS cap, R3-M4).
299    ///
300    /// The eager splitter materializes the whole `Vec<Exchange>` before
301    /// processing; this cap rejects a split that would explode memory.
302    /// Default 100_000. For unbounded/lazy input use `StreamingSplitter`.
303    pub max_fragments: usize,
304    /// Threshold above which split fragments start new traces (0 = off).
305    pub trace_item_threshold: usize,
306}
307
308impl std::fmt::Debug for SplitterConfig {
309    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
310        f.debug_struct("SplitterConfig")
311            .field("expression", &"<split-expression>")
312            .field("aggregation", &self.aggregation)
313            .field("parallel", &self.parallel)
314            .field("parallel_limit", &self.parallel_limit)
315            .field("stop_on_exception", &self.stop_on_exception)
316            .field("max_fragments", &self.max_fragments)
317            .field("trace_item_threshold", &self.trace_item_threshold)
318            .finish()
319    }
320}
321
322impl SplitterConfig {
323    /// Create a new splitter config with the given split expression.
324    pub fn new(expression: impl Into<SplitSource>) -> Self {
325        Self {
326            expression: expression.into(),
327            aggregation: AggregationStrategy::default(),
328            parallel: false,
329            parallel_limit: None,
330            stop_on_exception: true,
331            max_fragments: 100_000,
332            trace_item_threshold: DEFAULT_TRACE_ITEM_THRESHOLD,
333        }
334    }
335
336    /// Set the aggregation strategy for combining fragment results.
337    pub fn aggregation(mut self, strategy: AggregationStrategy) -> Self {
338        self.aggregation = strategy;
339        self
340    }
341
342    /// Enable or disable parallel fragment processing.
343    pub fn parallel(mut self, parallel: bool) -> Self {
344        self.parallel = parallel;
345        self
346    }
347
348    /// Set the maximum number of concurrent fragments in parallel mode.
349    pub fn parallel_limit(mut self, limit: usize) -> Self {
350        self.parallel_limit = Some(limit);
351        self
352    }
353
354    /// Control whether processing stops on the first fragment error.
355    ///
356    /// In parallel mode this only affects aggregation — see the field-level
357    /// doc comment for details.
358    pub fn stop_on_exception(mut self, stop: bool) -> Self {
359        self.stop_on_exception = stop;
360        self
361    }
362
363    /// Set the maximum number of fragments the eager splitter will materialize.
364    pub fn max_fragments(mut self, max: usize) -> Self {
365        self.max_fragments = max;
366        self
367    }
368
369    /// Set the threshold above which split fragments start new traces (0 = off).
370    pub fn trace_item_threshold(mut self, threshold: usize) -> Self {
371        self.trace_item_threshold = threshold;
372        self
373    }
374
375    /// Validates the configuration.
376    ///
377    /// Returns `Err(CamelError::Config)` if `parallel_limit` is set to 0,
378    /// which would cause a `Semaphore::new(0)` panic at runtime.
379    pub fn validate(&self) -> Result<(), CamelError> {
380        if self.parallel && self.parallel_limit == Some(0) {
381            return Err(CamelError::Config(
382                "splitter parallel_limit must be > 0".to_string(),
383            ));
384        }
385        if self.max_fragments == 0 {
386            return Err(CamelError::Config(
387                "splitter max_fragments must be > 0".to_string(),
388            ));
389        }
390        Ok(())
391    }
392}
393
394// ---------------------------------------------------------------------------
395// Helpers
396// ---------------------------------------------------------------------------
397
398/// Create a fragment exchange that inherits headers, properties, and OTel context
399/// from the parent, but with a new body.
400///
401/// # OpenTelemetry Trace Propagation
402///
403/// Each fragment inherits the live segment step span context: the splitter step's
404/// span, not the route root and not a previous fragment's span. A fragment-driven
405/// sub-route root therefore opens as a child of that segment span in the same trace,
406/// creating a natural fan-out relationship in the distributed trace:
407///
408/// ```text
409/// Segment step (span A)
410///   ├─ Fragment 1 sub-route root (span B, child of A)
411///   ├─ Fragment 2 sub-route root (span C, child of A)
412///   └─ Fragment N sub-route root (span N, child of A)
413/// ```
414///
415/// Restoring the entry context after the segment completes is the segment wrapper's
416/// job (`route_compiler::TracedSegmentStep` in `camel-core`), not
417/// `fragment_exchange`'s job.
418pub fn fragment_exchange(parent: &Exchange, body: Body) -> Exchange {
419    let mut msg = Message::new(body);
420    msg.headers = parent.input.headers.clone();
421    let mut ex = Exchange::new(msg);
422    ex.properties = parent.properties.clone();
423    ex.pattern = parent.pattern;
424    // Inherit OTel context so fragment spans are children of the parent span
425    ex.otel_context = parent.otel_context.clone();
426    // claimfamily: each fragment is a fanout branch exchange of the
427    // parent — split a sibling claim onto it so drain stays covered
428    // while the fragment is in flight.
429    ex.in_flight_claim = parent.in_flight_claim.as_ref().map(|claim| claim.split());
430    ex
431}
432
433/// Split the exchange body by newlines. Returns one fragment per line.
434///
435/// Empty bodies pass through with zero fragments. Wrong-type bodies return a
436/// [`CamelError::TypeConversionFailed`] naming the received body type and the
437/// expected `text` input.
438pub fn split_body_lines() -> SplitExpression {
439    Arc::new(|exchange: &Exchange| {
440        let text = match &exchange.input.body {
441            Body::Text(s) => s.as_str(),
442            Body::Empty => return Ok(Vec::new()),
443            _ => {
444                return Err(CamelError::TypeConversionFailed(format!(
445                    "split expression 'body_lines' requires body type text, got {received}; add an unmarshal step before split",
446                    received = body_type_name(&exchange.input.body)
447                )));
448            }
449        };
450        Ok(text
451            .lines()
452            .map(|line| fragment_exchange(exchange, Body::Text(line.to_string())))
453            .collect())
454    })
455}
456
457/// Split a JSON array body into one fragment per element.
458///
459/// Fragment typing is element-driven: string elements produce [`Body::Text`]
460/// fragments carrying the raw string (so `${body}` renders it unquoted);
461/// number, boolean, object, nested-array, and null elements produce
462/// [`Body::Json`] fragments.
463///
464/// Empty bodies and empty arrays pass through with zero fragments. Non-array
465/// JSON and wrong-type bodies return a [`CamelError::TypeConversionFailed`]
466/// naming the received body type and the expected `json (array)` input.
467pub fn split_body_json_array() -> SplitExpression {
468    Arc::new(|exchange: &Exchange| {
469        let arr = match &exchange.input.body {
470            Body::Json(serde_json::Value::Array(arr)) => arr,
471            Body::Empty => return Ok(Vec::new()),
472            Body::Json(_) => {
473                return Err(CamelError::TypeConversionFailed(
474                    "split expression 'body_json_array' requires body type json (array), got json (non-array); add an unmarshal step before split"
475                        .to_string(),
476                ))
477            }
478            _ => {
479                return Err(CamelError::TypeConversionFailed(format!(
480                    "split expression 'body_json_array' requires body type json (array), got {received}; add an unmarshal step before split",
481                    received = body_type_name(&exchange.input.body)
482                )))
483            }
484        };
485        Ok(arr
486            .iter()
487            .map(|val| match val {
488                serde_json::Value::String(s) => fragment_exchange(exchange, Body::Text(s.clone())),
489                other => fragment_exchange(exchange, Body::Json(other.clone())),
490            })
491            .collect())
492    })
493}
494
495/// Split the exchange body using a custom function that operates on the body.
496///
497/// Custom closures stay infallible: they own their body-type policy and an
498/// empty `Vec` keeps pass-through semantics.
499pub fn split_body<F>(f: F) -> SplitExpression
500where
501    F: Fn(&Body) -> Vec<Body> + Send + Sync + 'static,
502{
503    Arc::new(move |exchange: &Exchange| {
504        Ok(f(&exchange.input.body)
505            .into_iter()
506            .map(|body| fragment_exchange(exchange, body))
507            .collect())
508    })
509}
510
511#[cfg(test)]
512mod tests {
513    use super::*;
514    use crate::in_flight::{InFlightClaim, InFlightGauge};
515    use crate::value::Value;
516    use std::sync::Arc;
517
518    #[test]
519    fn test_split_body_lines() {
520        let mut ex = Exchange::new(Message::new("a\nb\nc"));
521        ex.input.set_header("source", Value::String("test".into()));
522        ex.set_property("trace", Value::Bool(true));
523
524        let fragments = split_body_lines()(&ex).unwrap();
525        assert_eq!(fragments.len(), 3);
526        assert_eq!(fragments[0].input.body.as_text(), Some("a"));
527        assert_eq!(fragments[1].input.body.as_text(), Some("b"));
528        assert_eq!(fragments[2].input.body.as_text(), Some("c"));
529
530        // Verify headers and properties inherited
531        for frag in &fragments {
532            assert_eq!(
533                frag.input.header("source"),
534                Some(&Value::String("test".into()))
535            );
536            assert_eq!(frag.property("trace"), Some(&Value::Bool(true)));
537        }
538    }
539
540    #[test]
541    fn test_split_body_lines_empty() {
542        let ex = Exchange::new(Message::default()); // Body::Empty
543        let fragments = split_body_lines()(&ex).unwrap();
544        assert!(fragments.is_empty());
545    }
546
547    #[test]
548    fn fragment_exchange_splits_parent_claim() {
549        let gauge = Arc::new(InFlightGauge::new());
550        let mut parent = Exchange::new(Message::new(Body::Text("a,b".into())));
551        parent.in_flight_claim = Some(InFlightClaim::attach(&gauge));
552
553        let frag = fragment_exchange(&parent, Body::Text("a".into()));
554        assert_eq!(gauge.total(), 2);
555        assert!(frag.in_flight_claim.is_some());
556        assert!(parent.in_flight_claim.is_some());
557
558        drop(frag);
559        assert_eq!(gauge.total(), 1);
560    }
561
562    #[test]
563    fn test_split_body_json_array() {
564        let arr = serde_json::json!([1, 2, 3]);
565        let ex = Exchange::new(Message::new(arr));
566
567        let fragments = split_body_json_array()(&ex).unwrap();
568        assert_eq!(fragments.len(), 3);
569        assert!(matches!(&fragments[0].input.body, Body::Json(v) if *v == serde_json::json!(1)));
570        assert!(matches!(&fragments[1].input.body, Body::Json(v) if *v == serde_json::json!(2)));
571        assert!(matches!(&fragments[2].input.body, Body::Json(v) if *v == serde_json::json!(3)));
572    }
573
574    #[test]
575    fn split_body_json_array_string_elements_become_text() {
576        // The leading empty-string element pins the accepted delta from
577        // mission 251 (bd rc-etf0q): an empty element yields an empty
578        // `Body::Text`, not a quoted `""` JSON string.
579        let ex = Exchange::new(Message::new(serde_json::json!(["", "a", "b"])));
580
581        let fragments = split_body_json_array()(&ex).unwrap();
582        assert_eq!(fragments.len(), 3);
583        assert!(
584            matches!(&fragments[0].input.body, Body::Text(s) if s.is_empty()),
585            "fragment 0 must be Body::Text(\"\"), got {:?}",
586            fragments[0].input.body
587        );
588        assert!(matches!(&fragments[1].input.body, Body::Text(s) if s == "a"));
589        assert!(matches!(&fragments[2].input.body, Body::Text(s) if s == "b"));
590        // No fragment body carries a literal quote character: string elements
591        // are raw text, so `${body}` renders them unquoted.
592        for frag in &fragments {
593            let text = match &frag.input.body {
594                Body::Text(s) => s.as_str(),
595                other => panic!("expected Body::Text fragment, got {other:?}"),
596            };
597            assert!(
598                !text.contains('"'),
599                "fragment body must not carry a quote character, got {text:?}"
600            );
601        }
602    }
603
604    #[test]
605    fn test_split_body_json_array_non_string_elements_stay_json() {
606        let ex = Exchange::new(Message::new(serde_json::json!([1, {"k": "v"}, null])));
607
608        let fragments = split_body_json_array()(&ex).unwrap();
609        assert_eq!(fragments.len(), 3);
610        assert!(matches!(&fragments[0].input.body, Body::Json(v) if *v == serde_json::json!(1)));
611        assert!(matches!(&fragments[1].input.body, Body::Json(v)
612                if *v == serde_json::json!({"k": "v"})));
613        assert!(matches!(&fragments[2].input.body, Body::Json(v) if v.is_null()));
614    }
615
616    #[test]
617    fn test_split_body_json_array_not_array() {
618        let obj = serde_json::json!({"not": "array"});
619        let ex = Exchange::new(Message::new(obj));
620
621        let err = split_body_json_array()(&ex).unwrap_err();
622        assert!(matches!(err, CamelError::TypeConversionFailed(_)));
623        assert!(err.to_string().contains("json (non-array)"));
624    }
625
626    #[test]
627    fn test_split_body_lines_wrong_type_json_errors() {
628        let ex = Exchange::new(Message::new(serde_json::json!({"a": 1})));
629
630        let err = split_body_lines()(&ex).unwrap_err();
631        let msg = err.to_string();
632        assert!(matches!(err, CamelError::TypeConversionFailed(_)));
633        for needle in [
634            "body_lines",
635            "json",
636            "text",
637            "add an unmarshal step before split",
638        ] {
639            assert!(msg.contains(needle), "message '{msg}' missing '{needle}'");
640        }
641    }
642
643    #[test]
644    fn test_split_body_json_array_wrong_type_text_errors() {
645        let ex = Exchange::new(Message::new("x"));
646
647        let err = split_body_json_array()(&ex).unwrap_err();
648        let msg = err.to_string();
649        assert!(matches!(err, CamelError::TypeConversionFailed(_)));
650        for needle in [
651            "body_json_array",
652            "text",
653            "json (array)",
654            "add an unmarshal step before split",
655        ] {
656            assert!(msg.contains(needle), "message '{msg}' missing '{needle}'");
657        }
658    }
659
660    #[test]
661    fn test_split_body_json_array_non_array_json_errors() {
662        let ex = Exchange::new(Message::new(serde_json::json!({"o": 1})));
663
664        let err = split_body_json_array()(&ex).unwrap_err();
665        let msg = err.to_string();
666        assert!(matches!(err, CamelError::TypeConversionFailed(_)));
667        assert!(msg.contains("json (non-array)"));
668    }
669
670    #[test]
671    fn test_split_body_lines_empty_body_ok() {
672        let ex = Exchange::new(Message::default()); // Body::Empty
673        let fragments = split_body_lines()(&ex).unwrap();
674        assert!(fragments.is_empty());
675    }
676
677    #[test]
678    fn test_split_body_json_array_empty_body_ok() {
679        let ex = Exchange::new(Message::default()); // Body::Empty
680        let fragments = split_body_json_array()(&ex).unwrap();
681        assert!(fragments.is_empty());
682    }
683
684    #[test]
685    fn test_split_body_json_array_empty_array_ok() {
686        let ex = Exchange::new(Message::new(serde_json::json!([])));
687        let fragments = split_body_json_array()(&ex).unwrap();
688        assert!(fragments.is_empty());
689    }
690
691    #[test]
692    fn test_split_body_lines_empty_text_ok() {
693        let ex = Exchange::new(Message::new(""));
694        let fragments = split_body_lines()(&ex).unwrap();
695        assert!(fragments.is_empty());
696    }
697
698    #[test]
699    fn test_split_error_omits_payload() {
700        let ex = Exchange::new(Message::new(serde_json::json!({
701            "secret": "SECRET-8f31a"
702        })));
703
704        let err = split_body_lines()(&ex).unwrap_err();
705        let msg = err.to_string();
706        assert!(matches!(err, CamelError::TypeConversionFailed(_)));
707        for needle in [
708            "body_lines",
709            "json",
710            "text",
711            "add an unmarshal step before split",
712        ] {
713            assert!(msg.contains(needle), "message '{msg}' missing '{needle}'");
714        }
715        assert!(
716            !msg.contains("SECRET-8f31a"),
717            "message '{msg}' leaks payload"
718        );
719    }
720
721    #[test]
722    fn test_split_body_custom() {
723        let splitter = split_body(|body: &Body| match body {
724            Body::Text(s) => s
725                .split(',')
726                .map(|part| Body::Text(part.trim().to_string()))
727                .collect(),
728            _ => Vec::new(),
729        });
730
731        let mut ex = Exchange::new(Message::new("x, y, z"));
732        ex.set_property("id", Value::from(42));
733
734        let fragments = splitter(&ex).unwrap();
735        assert_eq!(fragments.len(), 3);
736        assert_eq!(fragments[0].input.body.as_text(), Some("x"));
737        assert_eq!(fragments[1].input.body.as_text(), Some("y"));
738        assert_eq!(fragments[2].input.body.as_text(), Some("z"));
739
740        // Properties inherited
741        for frag in &fragments {
742            assert_eq!(frag.property("id"), Some(&Value::from(42)));
743        }
744    }
745
746    #[test]
747    fn test_splitter_config_defaults() {
748        let config = SplitterConfig::new(split_body_lines());
749        assert!(matches!(config.aggregation, AggregationStrategy::LastWins));
750        assert!(!config.parallel);
751        assert!(config.parallel_limit.is_none());
752        assert!(config.stop_on_exception);
753    }
754
755    #[test]
756    fn test_splitter_config_builder() {
757        let config = SplitterConfig::new(split_body_lines())
758            .aggregation(AggregationStrategy::CollectAll)
759            .parallel(true)
760            .parallel_limit(4)
761            .stop_on_exception(false);
762
763        assert!(matches!(
764            config.aggregation,
765            AggregationStrategy::CollectAll
766        ));
767        assert!(config.parallel);
768        assert_eq!(config.parallel_limit, Some(4));
769        assert!(!config.stop_on_exception);
770    }
771
772    #[test]
773    fn test_splitter_config_default_max_fragments() {
774        let cfg = SplitterConfig::new(Arc::new(|_: &Exchange| Ok(Vec::new())) as SplitExpression);
775        assert_eq!(cfg.max_fragments, 100_000);
776    }
777
778    #[test]
779    fn test_splitter_config_rejects_zero_max_fragments() {
780        let cfg = SplitterConfig::new(Arc::new(|_: &Exchange| Ok(Vec::new())) as SplitExpression)
781            .max_fragments(0);
782        assert!(cfg.validate().is_err());
783    }
784
785    #[test]
786    fn test_fragment_exchange_inherits_otel_context() {
787        use opentelemetry::Context;
788        use opentelemetry::trace::{SpanContext, SpanId, TraceContextExt, TraceFlags, TraceId};
789
790        // Create parent exchange with a valid span context
791        let mut parent = Exchange::new(Message::new("test"));
792        let trace_id = TraceId::from_bytes([0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 123]);
793        let span_id = SpanId::from_bytes([0, 0, 0, 0, 0, 0, 1, 200]);
794        let span_context = SpanContext::new(
795            trace_id,
796            span_id,
797            TraceFlags::SAMPLED,
798            true,
799            Default::default(),
800        );
801        let expected_trace_id = span_context.trace_id();
802        parent.otel_context = Context::current().with_remote_span_context(span_context);
803
804        // Create fragment via split_body_lines
805        let fragments = split_body_lines()(&parent).unwrap();
806        assert!(!fragments.is_empty(), "Should have at least one fragment");
807
808        // Verify each fragment has the same span context as parent
809        for fragment in &fragments {
810            let span = fragment.otel_context.span();
811            let frag_span_ctx = span.span_context();
812            assert!(
813                frag_span_ctx.is_valid(),
814                "Fragment should have valid span context"
815            );
816            assert_eq!(
817                frag_span_ctx.trace_id(),
818                expected_trace_id,
819                "Fragment should have same trace ID as parent"
820            );
821        }
822    }
823
824    #[test]
825    fn test_stream_split_config_defaults_valid() {
826        let config = StreamSplitConfig::default();
827        assert!(config.validate().is_ok());
828    }
829
830    #[test]
831    fn test_stream_split_config_batch_size_zero_rejected() {
832        let config = StreamSplitConfig {
833            batch_size: 0,
834            ..Default::default()
835        };
836        let err = config.validate().unwrap_err();
837        assert!(err.to_string().contains("batch_size"));
838    }
839
840    #[test]
841    fn test_stream_split_config_max_record_bytes_zero_rejected() {
842        let config = StreamSplitConfig {
843            max_record_bytes: 0,
844            ..Default::default()
845        };
846        let err = config.validate().unwrap_err();
847        assert!(err.to_string().contains("max_record_bytes"));
848    }
849
850    #[test]
851    fn test_stream_split_config_chunks_requires_chunk_size() {
852        let config = StreamSplitConfig {
853            format: StreamSplitFormat::Chunks,
854            chunk_size: None,
855            ..Default::default()
856        };
857        let err = config.validate().unwrap_err();
858        assert!(err.to_string().contains("Chunks requires chunk_size"));
859    }
860
861    #[test]
862    fn test_stream_split_config_chunk_size_zero_rejected() {
863        let config = StreamSplitConfig {
864            format: StreamSplitFormat::Chunks,
865            chunk_size: Some(0),
866            ..Default::default()
867        };
868        let err = config.validate().unwrap_err();
869        assert!(err.to_string().contains("chunk_size must be > 0"));
870    }
871
872    #[test]
873    fn test_stream_split_config_chunk_size_exceeds_max_record_bytes() {
874        let config = StreamSplitConfig {
875            format: StreamSplitFormat::Chunks,
876            chunk_size: Some(2000),
877            max_record_bytes: 1000,
878            ..Default::default()
879        };
880        let err = config.validate().unwrap_err();
881        assert!(
882            err.to_string()
883                .contains("chunk_size must be <= max_record_bytes")
884        );
885    }
886
887    #[test]
888    fn test_stream_split_config_zip_rejects_chunk_size() {
889        let config = StreamSplitConfig {
890            format: StreamSplitFormat::Zip,
891            chunk_size: Some(1024),
892            ..Default::default()
893        };
894        let err = config.validate().unwrap_err();
895        assert!(err.to_string().contains("Zip does not support chunk_size"));
896    }
897
898    #[test]
899    fn test_all_fragments_share_same_trace_context() {
900        use opentelemetry::Context;
901        use opentelemetry::trace::{SpanContext, SpanId, TraceContextExt, TraceFlags, TraceId};
902
903        // Create parent with a specific trace ID
904        let mut parent = Exchange::new(Message::new("line1\nline2\nline3"));
905        let trace_id =
906            TraceId::from_bytes([0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0x3B, 0x9A, 0xCA, 0x09]);
907        let span_id = SpanId::from_bytes([0, 0, 0, 0, 0, 0, 0, 111]);
908        let span_context = SpanContext::new(
909            trace_id,
910            span_id,
911            TraceFlags::SAMPLED,
912            true,
913            Default::default(),
914        );
915        parent.otel_context = Context::current().with_remote_span_context(span_context);
916
917        let fragments = split_body_lines()(&parent).unwrap();
918        assert_eq!(fragments.len(), 3);
919
920        // All fragments should share the same trace ID
921        let trace_ids: Vec<_> = fragments
922            .iter()
923            .map(|f| {
924                let span = f.otel_context.span();
925                span.span_context().trace_id()
926            })
927            .collect();
928
929        assert!(
930            trace_ids.iter().all(|&id| id == trace_id),
931            "All fragments should have the same trace ID"
932        );
933    }
934
935    #[test]
936    fn trace_item_threshold_defaults_to_100() {
937        let config = SplitterConfig::new(split_body_lines());
938        assert_eq!(config.trace_item_threshold, 100);
939    }
940
941    #[test]
942    fn trace_item_threshold_builder_sets_value() {
943        let config = SplitterConfig::new(split_body_lines()).trace_item_threshold(0);
944        assert_eq!(config.trace_item_threshold, 0);
945
946        let config = SplitterConfig::new(split_body_lines()).trace_item_threshold(7);
947        assert_eq!(config.trace_item_threshold, 7);
948    }
949
950    #[test]
951    fn canonical_split_spec_carries_trace_item_threshold() {
952        use crate::runtime::{CanonicalSplitAggregationSpec, CanonicalSplitExpressionSpec};
953
954        let with_threshold = crate::runtime::CanonicalStepSpec::Split {
955            expression: CanonicalSplitExpressionSpec::BodyLines,
956            aggregation: CanonicalSplitAggregationSpec::CollectAll,
957            parallel: false,
958            parallel_limit: None,
959            stop_on_exception: true,
960            trace_item_threshold: Some(5),
961            steps: Vec::new(),
962        };
963        let without_threshold = crate::runtime::CanonicalStepSpec::Split {
964            expression: CanonicalSplitExpressionSpec::BodyLines,
965            aggregation: CanonicalSplitAggregationSpec::CollectAll,
966            parallel: false,
967            parallel_limit: None,
968            stop_on_exception: true,
969            trace_item_threshold: None,
970            steps: Vec::new(),
971        };
972
973        // Mirror the derive(PartialEq)/destructure path `parallel_limit` uses.
974        let crate::runtime::CanonicalStepSpec::Split {
975            trace_item_threshold,
976            ..
977        } = &with_threshold
978        else {
979            unreachable!()
980        };
981        assert_eq!(trace_item_threshold, &Some(5));
982
983        let crate::runtime::CanonicalStepSpec::Split {
984            trace_item_threshold,
985            ..
986        } = &without_threshold
987        else {
988            unreachable!()
989        };
990        assert_eq!(trace_item_threshold, &None);
991
992        assert_ne!(with_threshold, without_threshold);
993    }
994}