camel-processor 0.16.0

Message processors for rust-camel
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
use futures::{StreamExt, pin_mut};
use std::future::Future;
use std::pin::Pin;
use std::task::{Context, Poll};
use tokio_util::sync::CancellationToken;
use tower::Service;

use camel_api::{
    AggregationStrategy, Body, BoxProcessor, CamelError, Exchange, StreamingSplitExpression, Value,
};

pub const CAMEL_SPLIT_INDEX: &str = "CamelSplitIndex";
pub const CAMEL_SPLIT_COMPLETE: &str = "CamelSplitComplete";

#[derive(Clone)]
pub struct StreamingSplitterService {
    expression: StreamingSplitExpression,
    sub_pipeline: BoxProcessor,
    aggregation: AggregationStrategy,
    stop_on_exception: bool,
    cancel_token: CancellationToken,
}

impl StreamingSplitterService {
    pub fn new(
        expression: StreamingSplitExpression,
        sub_pipeline: BoxProcessor,
        aggregation: AggregationStrategy,
        stop_on_exception: bool,
    ) -> Self {
        Self {
            expression,
            sub_pipeline,
            aggregation,
            stop_on_exception,
            cancel_token: CancellationToken::new(),
        }
    }

    pub fn cancel(&self) {
        self.cancel_token.cancel();
    }

    pub fn is_cancelled(&self) -> bool {
        self.cancel_token.is_cancelled()
    }
}

impl Service<Exchange> for StreamingSplitterService {
    type Response = Exchange;
    type Error = CamelError;
    type Future = Pin<Box<dyn Future<Output = Result<Exchange, CamelError>> + Send>>;

    fn poll_ready(&mut self, cx: &mut Context<'_>) -> Poll<Result<(), Self::Error>> {
        self.sub_pipeline.poll_ready(cx)
    }

    fn call(&mut self, exchange: Exchange) -> Self::Future {
        let mut original = exchange.clone();
        if matches!(original.input.body, Body::Stream(_)) {
            original.input.body = Body::Empty;
        }
        let expression = self.expression.clone();
        let sub_pipeline = self.sub_pipeline.clone();
        let aggregation = self.aggregation.clone();
        let stop_on_exception = self.stop_on_exception;
        let cancel_token = self.cancel_token.clone();

        Box::pin(async move {
            let stream = expression(exchange);
            pin_mut!(stream);

            let mut acc: Option<Exchange> = None;
            let mut acc_bodies: Vec<Value> = Vec::new();
            let mut index: u64 = 0;

            // One-entry lookahead for CamelSplitComplete
            let mut current = stream.next().await;

            while let Some(fragment_result) = current.take() {
                if cancel_token.is_cancelled() {
                    return Err(CamelError::ProcessorError(
                        "StreamingSplitter cancelled".to_string(),
                    ));
                }

                let fragment = fragment_result?;

                // Peek next to know if this is the last entry
                let next = stream.next().await;
                let is_last = next.is_none();

                let mut fragment = fragment;
                fragment.set_property(CAMEL_SPLIT_INDEX, Value::from(index));
                fragment.set_property(CAMEL_SPLIT_COMPLETE, Value::Bool(is_last));

                let mut pipeline = sub_pipeline.clone();
                let ready = tower::ServiceExt::ready(&mut pipeline).await;
                let result = match ready {
                    Ok(svc) => svc.call(fragment).await,
                    Err(e) => Err(e),
                };

                match result {
                    Ok(processed) => {
                        match &aggregation {
                            AggregationStrategy::CollectAll => {
                                let v = match &processed.input.body {
                                    Body::Text(s) => Value::String(s.clone()),
                                    Body::Json(v) => v.clone(),
                                    Body::Xml(s) => Value::String(s.clone()),
                                    Body::Bytes(b) => {
                                        Value::String(String::from_utf8_lossy(b).into_owned())
                                    }
                                    Body::Empty => Value::Null,
                                    Body::Stream(_) => {
                                        return Err(CamelError::TypeConversionFailed(
                                            "StreamingSplitter CollectAll cannot aggregate Body::Stream — use 'stream_cache' or 'convert_body_to' before this step".to_string(),
                                        ));
                                    }
                                };
                                acc_bodies.push(v);
                            }
                            AggregationStrategy::Custom(fold_fn) => {
                                acc = Some(match acc {
                                    Some(prev) => fold_fn(prev, processed),
                                    None => processed,
                                });
                            }
                            _ => {
                                acc = Some(processed);
                            }
                        }
                        index += 1;
                    }
                    Err(e) => {
                        if stop_on_exception {
                            return Err(e);
                        }
                        index += 1;
                    }
                }

                current = next;
            }

            match &aggregation {
                AggregationStrategy::LastWins => Ok(acc.unwrap_or(original)),
                AggregationStrategy::Original => Ok(original),
                AggregationStrategy::CollectAll => {
                    let mut out = original;
                    out.input.body = Body::Json(Value::Array(acc_bodies));
                    Ok(out)
                }
                AggregationStrategy::Custom(_) => Ok(acc.unwrap_or(original)),
            }
        })
    }
}

#[cfg(test)]
mod tests {
    use super::*;
    use bytes::Bytes;
    use camel_api::{BoxProcessorExt, Message, StreamBody, StreamMetadata};
    use futures::stream;
    use std::sync::Arc;
    use tokio::sync::Mutex;
    use tower::ServiceExt;

    use crate::stream_codec::{StreamSplitInput, resolve_codec, resolve_format};

    fn passthrough_pipeline() -> BoxProcessor {
        BoxProcessor::from_fn(|ex| Box::pin(async move { Ok(ex) }))
    }

    fn uppercase_pipeline() -> BoxProcessor {
        BoxProcessor::from_fn(|mut ex: Exchange| {
            Box::pin(async move {
                if let Body::Text(s) = &ex.input.body {
                    ex.input.body = Body::Text(s.to_uppercase());
                }
                Ok(ex)
            })
        })
    }

    fn make_exchange(text: &str) -> Exchange {
        Exchange::new(Message::new(text))
    }

    fn test_expression(fragments: Vec<Exchange>) -> StreamingSplitExpression {
        Arc::new(move |_| {
            let frags = fragments.clone();
            Box::pin(stream::iter(frags.into_iter().map(Ok)))
        })
    }

    fn error_expression() -> StreamingSplitExpression {
        Arc::new(|_| {
            Box::pin(stream::iter(vec![Err(CamelError::ProcessorError(
                "stream error".to_string(),
            ))]))
        })
    }

    /// Build a `StreamingSplitExpression` that reads from `Body::Stream` and
    /// splits using the NdjsonCodec. Mirrors the resolution logic in
    /// `step_resolution.rs`.
    fn ndjson_stream_expression(config: camel_api::StreamSplitConfig) -> StreamingSplitExpression {
        Arc::new(move |exchange: Exchange| {
            let config = config.clone();
            let (stream_body, parent) = match &exchange.input.body {
                Body::Stream(sb) => (sb.clone(), {
                    let mut p = exchange.clone();
                    p.input.body = Body::Empty;
                    p
                }),
                _ => {
                    return Box::pin(futures::stream::once(async {
                        Err(CamelError::ProcessorError(
                            "streaming split requires Body::Stream".into(),
                        ))
                    }));
                }
            };

            let stream = match stream_body.stream.try_lock() {
                Ok(mut guard) => match guard.take() {
                    Some(s) => s,
                    None => {
                        return Box::pin(futures::stream::once(async {
                            Err(CamelError::ProcessorError(
                                "stream body already consumed".into(),
                            ))
                        }));
                    }
                },
                Err(_) => {
                    return Box::pin(futures::stream::once(async {
                        Err(CamelError::ProcessorError("stream body locked".into()))
                    }));
                }
            };

            let input = StreamSplitInput {
                parent,
                stream,
                metadata: stream_body.metadata,
            };

            match resolve_format(&config.format, &input.metadata) {
                Ok(f) => {
                    let codec = resolve_codec(&f);
                    codec.split(input, config)
                }
                Err(e) => Box::pin(futures::stream::once(async { Err(e) })),
            }
        })
    }

    // ---------------------------------------------------------------------------
    // Integration test: Body::Stream NDJSON → streaming split → Body::Json fragments
    // ---------------------------------------------------------------------------

    #[tokio::test]
    async fn test_ndjson_body_stream_streaming_split() {
        // ── Arrange ────────────────────────────────────────────────────────────
        // 3 lines of NDJSON as a byte stream
        let ndjson_lines: Vec<Result<Bytes, CamelError>> = vec![
            Ok(Bytes::from("{\"id\":1,\"name\":\"a\"}\n")),
            Ok(Bytes::from("{\"id\":2,\"name\":\"b\"}\n")),
            Ok(Bytes::from("{\"id\":3,\"name\":\"c\"}\n")),
        ];
        let byte_stream = futures::stream::iter(ndjson_lines);

        let stream_body = StreamBody {
            stream: Arc::new(Mutex::new(Some(Box::pin(byte_stream)))),
            metadata: StreamMetadata {
                content_type: Some("application/x-ndjson".into()),
                size_hint: None,
                origin: Some("test://ndjson".into()),
            },
        };

        let ex = Exchange::new(Message::new(Body::Stream(stream_body)));

        // Streaming split config — Ndjson format
        let split_config = camel_api::StreamSplitConfig {
            format: camel_api::StreamSplitFormat::Ndjson,
            ..Default::default()
        };

        // Recorder sub-pipeline: captures per-fragment body + properties
        let fragments: Arc<Mutex<Vec<(Option<serde_json::Value>, Option<Value>, Option<Value>)>>> =
            Arc::new(Mutex::new(Vec::new()));
        let fragments_clone = Arc::clone(&fragments);
        let recorder = BoxProcessor::from_fn(move |ex: Exchange| {
            let frags = Arc::clone(&fragments_clone);
            Box::pin(async move {
                let body_json = match &ex.input.body {
                    Body::Json(v) => Some(v.clone()),
                    _ => None,
                };
                let split_index = ex.property(CAMEL_SPLIT_INDEX).cloned();
                let split_complete = ex.property(CAMEL_SPLIT_COMPLETE).cloned();
                let mut guard = frags.lock().await;
                guard.push((body_json, split_index, split_complete));
                Ok(ex)
            })
        });

        let expression = ndjson_stream_expression(split_config);

        // ── Act ────────────────────────────────────────────────────────────────
        let mut splitter = StreamingSplitterService::new(
            expression,
            recorder,
            AggregationStrategy::CollectAll,
            true, // stop_on_exception
        );

        let result = splitter
            .ready()
            .await
            .expect("splitter ready")
            .call(ex)
            .await
            .expect("splitter call");

        // ── Assert ─────────────────────────────────────────────────────────────
        let guard = fragments.lock().await;

        // 1. Three fragments were produced
        assert_eq!(guard.len(), 3, "expected 3 NDJSON fragments");

        // 2. Each fragment has Body::Json
        for (i, (body_json, _idx, _complete)) in guard.iter().enumerate() {
            assert!(
                body_json.is_some(),
                "fragment {i}: expected Body::Json body, got non-Json"
            );
        }

        // 3. Each fragment has CamelSplitIndex property (0, 1, 2)
        for (i, (_body, idx, _complete)) in guard.iter().enumerate() {
            assert_eq!(
                *idx,
                Some(Value::Number(serde_json::Number::from(i as u64))),
                "fragment {i}: CamelSplitIndex mismatch"
            );
        }

        // 4. CamelSplitComplete: first two false, last one true
        assert_eq!(
            guard[0].2,
            Some(Value::Bool(false)),
            "first fragment: CamelSplitComplete should be false"
        );
        assert_eq!(
            guard[1].2,
            Some(Value::Bool(false)),
            "second fragment: CamelSplitComplete should be false"
        );
        assert_eq!(
            guard[2].2,
            Some(Value::Bool(true)),
            "last fragment: CamelSplitComplete should be true"
        );

        // 5. CollectAll aggregated into JSON array with correct values
        match &result.input.body {
            Body::Json(v) => {
                let arr = v.as_array().expect("CollectAll result should be array");
                assert_eq!(arr.len(), 3);
                assert_eq!(arr[0], serde_json::json!({"id":1,"name":"a"}));
                assert_eq!(arr[1], serde_json::json!({"id":2,"name":"b"}));
                assert_eq!(arr[2], serde_json::json!({"id":3,"name":"c"}));
            }
            other => panic!("expected Body::Json from CollectAll, got {other:?}"),
        }

        // 6. Original stream body sanitized (already Empty, becomes part of aggregate)
        //    The aggregate exchange's body is Json, not Stream
        assert!(
            matches!(result.input.body, Body::Json(_)),
            "aggregate body should be Json, not Stream"
        );
    }

    // ---------------------------------------------------------------------------
    // Integration test: Empty Body::Stream → aggregate result is empty
    // ---------------------------------------------------------------------------

    #[tokio::test]
    async fn test_ndjson_body_stream_empty_stream() {
        // ── Arrange ────────────────────────────────────────────────────────────
        // Empty byte stream
        let byte_stream = futures::stream::iter(Vec::<Result<Bytes, CamelError>>::new());

        let stream_body = StreamBody {
            stream: Arc::new(Mutex::new(Some(Box::pin(byte_stream)))),
            metadata: StreamMetadata {
                content_type: Some("application/x-ndjson".into()),
                size_hint: None,
                origin: None,
            },
        };

        let mut ex = Exchange::new(Message::new(Body::Stream(stream_body)));
        ex.set_property("trace_id", Value::String("empty-test".into()));

        let split_config = camel_api::StreamSplitConfig {
            format: camel_api::StreamSplitFormat::Ndjson,
            ..Default::default()
        };

        let expression = ndjson_stream_expression(split_config);

        // ── Act ────────────────────────────────────────────────────────────────
        let mut splitter = StreamingSplitterService::new(
            expression,
            passthrough_pipeline(),
            AggregationStrategy::CollectAll,
            true,
        );

        let result = splitter
            .ready()
            .await
            .expect("splitter ready")
            .call(ex)
            .await
            .expect("splitter call");

        // ── Assert ─────────────────────────────────────────────────────────────
        // Empty stream → CollectAll produces Body::Json([])
        match &result.input.body {
            Body::Json(v) => {
                let arr = v.as_array().expect("CollectAll result should be array");
                assert!(
                    arr.is_empty(),
                    "empty stream should produce empty array, got {arr:?}"
                );
            }
            other => {
                panic!("expected Body::Json([]) from CollectAll on empty stream, got {other:?}")
            }
        }

        // Properties preserved
        assert_eq!(
            result.property("trace_id"),
            Some(&Value::String("empty-test".into()))
        );
    }

    #[tokio::test]
    async fn test_streaming_sequential_last_wins() {
        let expr = test_expression(vec![
            make_exchange("a"),
            make_exchange("b"),
            make_exchange("c"),
        ]);
        let mut svc = StreamingSplitterService::new(
            expr,
            uppercase_pipeline(),
            AggregationStrategy::LastWins,
            true,
        );

        let result = svc
            .ready()
            .await
            .unwrap()
            .call(make_exchange("original"))
            .await
            .unwrap();
        assert_eq!(result.input.body.as_text(), Some("C"));
    }

    #[tokio::test]
    async fn test_streaming_sequential_original() {
        let expr = test_expression(vec![make_exchange("a"), make_exchange("b")]);
        let mut svc = StreamingSplitterService::new(
            expr,
            uppercase_pipeline(),
            AggregationStrategy::Original,
            true,
        );

        let result = svc
            .ready()
            .await
            .unwrap()
            .call(make_exchange("original"))
            .await
            .unwrap();
        assert_eq!(result.input.body.as_text(), Some("original"));
    }

    #[tokio::test]
    async fn test_streaming_stop_on_exception() {
        let expr = test_expression(vec![make_exchange("a"), make_exchange("b")]);
        let fail_pipeline = BoxProcessor::from_fn(|_| {
            Box::pin(async { Err(CamelError::ProcessorError("boom".into())) })
        });
        let mut svc =
            StreamingSplitterService::new(expr, fail_pipeline, AggregationStrategy::LastWins, true);

        let result = svc
            .ready()
            .await
            .unwrap()
            .call(make_exchange("original"))
            .await;
        assert!(result.is_err());
    }

    #[tokio::test]
    async fn test_streaming_empty_stream() {
        let expr: StreamingSplitExpression = Arc::new(|_| Box::pin(futures::stream::empty()));
        let mut svc = StreamingSplitterService::new(
            expr,
            passthrough_pipeline(),
            AggregationStrategy::LastWins,
            true,
        );

        let mut ex = make_exchange("original");
        ex.set_property("marker", Value::Bool(true));
        let result = svc.ready().await.unwrap().call(ex).await.unwrap();
        assert_eq!(result.input.body.as_text(), Some("original"));
        assert_eq!(result.property("marker"), Some(&Value::Bool(true)));
    }

    #[tokio::test]
    async fn test_streaming_error_in_expression() {
        let mut svc = StreamingSplitterService::new(
            error_expression(),
            passthrough_pipeline(),
            AggregationStrategy::LastWins,
            true,
        );

        let result = svc
            .ready()
            .await
            .unwrap()
            .call(make_exchange("original"))
            .await;
        assert!(result.is_err());
    }

    #[tokio::test]
    async fn test_streaming_cancellation() {
        let expr = test_expression(vec![make_exchange("a"), make_exchange("b")]);
        let slow_pipeline = BoxProcessor::from_fn(|ex| {
            Box::pin(async move {
                tokio::time::sleep(std::time::Duration::from_secs(60)).await;
                Ok(ex)
            })
        });
        let svc =
            StreamingSplitterService::new(expr, slow_pipeline, AggregationStrategy::LastWins, true);
        svc.cancel();

        let mut svc_clone = svc.clone();
        let result = svc_clone
            .ready()
            .await
            .unwrap()
            .call(make_exchange("original"))
            .await;
        assert!(result.is_err());
    }

    #[tokio::test]
    async fn test_streaming_sequential_collect_all() {
        let expr = test_expression(vec![
            make_exchange("a"),
            make_exchange("b"),
            make_exchange("c"),
        ]);
        let mut svc = StreamingSplitterService::new(
            expr,
            uppercase_pipeline(),
            AggregationStrategy::CollectAll,
            true,
        );

        let result = svc
            .ready()
            .await
            .unwrap()
            .call(make_exchange("original"))
            .await
            .unwrap();
        let expected = serde_json::json!(["A", "B", "C"]);
        match &result.input.body {
            Body::Json(v) => assert_eq!(*v, expected),
            other => panic!("expected JSON body, got {other:?}"),
        }
    }

    #[tokio::test]
    async fn test_streaming_sequential_custom_aggregation() {
        let joiner: Arc<dyn Fn(Exchange, Exchange) -> Exchange + Send + Sync> =
            Arc::new(|mut acc: Exchange, next: Exchange| {
                let acc_text = acc.input.body.as_text().unwrap_or("").to_string();
                let next_text = next.input.body.as_text().unwrap_or("").to_string();
                acc.input.body = Body::Text(format!("{acc_text}+{next_text}"));
                acc
            });

        let expr = test_expression(vec![
            make_exchange("a"),
            make_exchange("b"),
            make_exchange("c"),
        ]);
        let mut svc = StreamingSplitterService::new(
            expr,
            uppercase_pipeline(),
            AggregationStrategy::Custom(joiner),
            true,
        );

        let result = svc
            .ready()
            .await
            .unwrap()
            .call(make_exchange("original"))
            .await
            .unwrap();
        assert_eq!(result.input.body.as_text(), Some("A+B+C"));
    }

    #[tokio::test]
    async fn test_streaming_error_continue_on_exception() {
        let call_count = Arc::new(std::sync::atomic::AtomicUsize::new(0));
        let count_clone = call_count.clone();
        let fail_on_first = BoxProcessor::from_fn(move |ex: Exchange| {
            let count = count_clone.clone();
            Box::pin(async move {
                let n = count.fetch_add(1, std::sync::atomic::Ordering::SeqCst);
                if n == 0 {
                    Err(CamelError::ProcessorError("first fails".into()))
                } else {
                    Ok(ex)
                }
            })
        });

        let expr = test_expression(vec![make_exchange("a"), make_exchange("b")]);
        let mut svc = StreamingSplitterService::new(
            expr,
            fail_on_first,
            AggregationStrategy::LastWins,
            false,
        );

        let result = svc
            .ready()
            .await
            .unwrap()
            .call(make_exchange("original"))
            .await
            .unwrap();
        assert_eq!(result.input.body.as_text(), Some("b"));
        assert_eq!(call_count.load(std::sync::atomic::Ordering::SeqCst), 2);
    }

    #[tokio::test]
    async fn test_streaming_metadata_lookahead() {
        let recorder = BoxProcessor::from_fn(|ex: Exchange| {
            Box::pin(async move {
                let idx = ex.property(CAMEL_SPLIT_INDEX).cloned();
                let complete = ex.property(CAMEL_SPLIT_COMPLETE).cloned();
                let body = serde_json::json!({
                    "index": idx,
                    "complete": complete,
                });
                let mut out = ex;
                out.input.body = Body::Json(body);
                Ok(out)
            })
        });

        let expr = test_expression(vec![
            make_exchange("x"),
            make_exchange("y"),
            make_exchange("z"),
        ]);
        let mut svc =
            StreamingSplitterService::new(expr, recorder, AggregationStrategy::CollectAll, true);

        let result = svc
            .ready()
            .await
            .unwrap()
            .call(make_exchange("original"))
            .await
            .unwrap();
        let expected = serde_json::json!([
            {"index": 0, "complete": false},
            {"index": 1, "complete": false},
            {"index": 2, "complete": true},
        ]);
        match &result.input.body {
            Body::Json(v) => assert_eq!(*v, expected),
            other => panic!("expected JSON body, got {other:?}"),
        }
    }

    #[tokio::test]
    async fn test_streaming_split_sanitizes_stream_body_in_original() {
        let chunks = vec![Ok(Bytes::from("line1\n"))];
        let stream = futures::stream::iter(chunks);
        let sb = StreamBody {
            stream: Arc::new(Mutex::new(Some(Box::pin(stream)))),
            metadata: Default::default(),
        };
        let ex = Exchange::new(Message::new(Body::Stream(sb)));

        let expression =
            test_expression(vec![Exchange::new(Message::new(Body::Text("frag".into())))]);
        let sub_pipeline = passthrough_pipeline();
        let mut splitter = StreamingSplitterService::new(
            expression,
            sub_pipeline,
            AggregationStrategy::Original,
            true,
        );

        let result = splitter
            .ready()
            .await
            .expect("ready")
            .call(ex)
            .await
            .expect("call");
        assert!(
            matches!(result.input.body, Body::Empty),
            "original body should be sanitized to Empty"
        );
    }
}