flyby 0.1.1

A high-performance Rust framework for composable data-ingestion pipelines.
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
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
//! Minimal concrete [`Pipeline`] implementation.
//!
//! [`SimplePipeline`] owns a batch-oriented raw source, a decoder, optional
//! preprocessor, placement, and a map of sinks. It is the composition path
//! used by demos and tests until the fluent builder grows full type-state
//! wiring.

use std::collections::HashMap;
use std::marker::PhantomData;

use crate::api::{
    Decoder, Error, ErrorKind, Lifecycle, Message, MetricsCollector, NullCollector, Pipeline,
    Placement, PreProcessor, Result, SchemaId, Sink, SinkId, StepOutcome,
};
use crate::runtime::{BackpressureStrategy, RuntimeConfig, RuntimeMetricKey};

/// Pulls framed raw bytes into a caller-supplied buffer.
///
/// Adapters wrap [`crate::net::NetworkSource`] / [`crate::storage::StorageSource`]
/// (or any custom source) behind this trait so the pipeline stays free of
/// backend crates.
pub trait RawBatchSource: Lifecycle {
    /// Fill `out` with the next frame(s). Returns the number of frames written
    /// as separate slices into `out` (appended). Zero means idle.
    fn poll_frames(&mut self, out: &mut Vec<Vec<u8>>) -> Result<usize>;

    /// `true` when a finite source will never produce more data.
    fn is_exhausted(&self) -> bool {
        false
    }
}

/// Identity preprocessor: passes every message through unchanged.
#[derive(Debug)]
pub struct IdentityPreProcessor<M>(std::marker::PhantomData<fn() -> M>);

impl<M> Default for IdentityPreProcessor<M> {
    fn default() -> Self {
        Self(std::marker::PhantomData)
    }
}

impl<M: Message> PreProcessor for IdentityPreProcessor<M> {
    type Message = M;

    fn process(&mut self, message: M) -> Result<Option<M>> {
        Ok(Some(message))
    }
}

/// Routes every message to a fixed [`SinkId`].
#[derive(Debug, Clone, Copy)]
pub struct FixedPlacement<M> {
    id: SinkId,
    _marker: std::marker::PhantomData<fn() -> M>,
}

impl<M: Message> FixedPlacement<M> {
    /// Create a placement that always returns `id` (must not be [`SinkId::NONE`]).
    pub fn new(id: SinkId) -> Result<Self> {
        if id.is_none() {
            return Err(Error::config(
                "FixedPlacement cannot use SinkId::NONE; use DropAllPlacement",
            ));
        }
        Ok(Self {
            id,
            _marker: std::marker::PhantomData,
        })
    }
}

impl<M: Message> Placement for FixedPlacement<M> {
    type Message = M;

    fn route(&mut self, _message: &M) -> Result<SinkId> {
        Ok(self.id)
    }
}

/// Drops every message (`SinkId::NONE`).
#[derive(Debug, Clone, Copy)]
pub struct DropAllPlacement<M>(std::marker::PhantomData<fn() -> M>);

impl<M> Default for DropAllPlacement<M> {
    fn default() -> Self {
        Self(std::marker::PhantomData)
    }
}

impl<M: Message> Placement for DropAllPlacement<M> {
    type Message = M;

    fn route(&mut self, _message: &M) -> Result<SinkId> {
        Ok(SinkId::NONE)
    }
}

/// Round-robin across a non-empty list of sinks.
#[derive(Debug, Clone)]
pub struct RoundRobinPlacement<M> {
    sinks: Vec<SinkId>,
    next: usize,
    _marker: PhantomData<fn() -> M>,
}

impl<M: Message> RoundRobinPlacement<M> {
    /// Create a round-robin placement. `sinks` must be non-empty and exclude [`SinkId::NONE`].
    pub fn new(sinks: Vec<SinkId>) -> Result<Self> {
        if sinks.is_empty() {
            return Err(Error::config(
                "RoundRobinPlacement requires at least one sink",
            ));
        }
        if sinks.iter().any(|s| s.is_none()) {
            return Err(Error::config(
                "RoundRobinPlacement cannot include SinkId::NONE",
            ));
        }
        Ok(Self {
            sinks,
            next: 0,
            _marker: PhantomData,
        })
    }
}

impl<M: Message> Placement for RoundRobinPlacement<M> {
    type Message = M;

    fn route(&mut self, _message: &M) -> Result<SinkId> {
        let id = self.sinks[self.next % self.sinks.len()];
        self.next = self.next.wrapping_add(1);
        Ok(id)
    }
}

/// Hash a key extracted from the message onto a sink list.
pub struct HashPlacement<M, F> {
    sinks: Vec<SinkId>,
    key_fn: F,
    _marker: PhantomData<fn() -> M>,
}

impl<M, F> HashPlacement<M, F>
where
    M: Message,
    F: FnMut(&M) -> u64 + Send + Sync,
{
    /// Create a hash placement. `sinks` must be non-empty.
    pub fn new(sinks: Vec<SinkId>, key_fn: F) -> Result<Self> {
        if sinks.is_empty() {
            return Err(Error::config("HashPlacement requires at least one sink"));
        }
        if sinks.iter().any(|s| s.is_none()) {
            return Err(Error::config("HashPlacement cannot include SinkId::NONE"));
        }
        Ok(Self {
            sinks,
            key_fn,
            _marker: PhantomData,
        })
    }
}

impl<M, F> Placement for HashPlacement<M, F>
where
    M: Message,
    F: FnMut(&M) -> u64 + Send + Sync,
{
    type Message = M;

    fn route(&mut self, message: &M) -> Result<SinkId> {
        let key = (self.key_fn)(message);
        let idx = (key as usize) % self.sinks.len();
        Ok(self.sinks[idx])
    }
}

/// Hash the message [`SchemaId`] onto sinks.
pub type SchemaHashPlacement<M> = HashPlacement<M, fn(&M) -> u64>;

/// Hash the message [`SchemaId`] onto sinks.
pub fn schema_hash_placement<M: Message>(sinks: Vec<SinkId>) -> Result<SchemaHashPlacement<M>> {
    HashPlacement::new(sinks, |m: &M| u64::from(m.schema_id().id()))
}

/// Callback-driven placement (custom business rules stay outside the runtime).
pub struct CallbackPlacement<M, F> {
    callback: F,
    _marker: PhantomData<fn() -> M>,
}

impl<M, F> CallbackPlacement<M, F>
where
    M: Message,
    F: FnMut(&M) -> Result<SinkId> + Send + Sync,
{
    /// Wrap a routing callback.
    pub fn new(callback: F) -> Self {
        Self {
            callback,
            _marker: PhantomData,
        }
    }
}

impl<M, F> Placement for CallbackPlacement<M, F>
where
    M: Message,
    F: FnMut(&M) -> Result<SinkId> + Send + Sync,
{
    type Message = M;

    fn route(&mut self, message: &M) -> Result<SinkId> {
        (self.callback)(message)
    }
}

/// A single-threaded pipeline: source → decode → preprocess → place → sink.
pub struct SimplePipeline<M, S, D, P, Pl>
where
    M: Message,
    S: RawBatchSource,
    D: Decoder<Output = M>,
    P: PreProcessor<Message = M>,
    Pl: Placement<Message = M>,
{
    source: S,
    decoder: D,
    preprocessor: P,
    placement: Pl,
    sinks: HashMap<u32, Box<dyn Sink<Message = M>>>,
    metrics: Box<dyn MetricsCollector>,
    runtime: RuntimeConfig,
    /// Pending frames from the last source poll, awaiting decode.
    pending: Vec<Vec<u8>>,
    pending_idx: usize,
    initialized: bool,
    messages_out: u64,
    messages_dropped: u64,
    backpressure_events: u64,
}

impl<M, S, D, P, Pl> SimplePipeline<M, S, D, P, Pl>
where
    M: Message,
    S: RawBatchSource,
    D: Decoder<Output = M>,
    P: PreProcessor<Message = M>,
    Pl: Placement<Message = M>,
{
    /// Build a pipeline from its stages. Register sinks before [`Lifecycle::init`].
    pub fn new(source: S, decoder: D, preprocessor: P, placement: Pl) -> Self {
        Self {
            source,
            decoder,
            preprocessor,
            placement,
            sinks: HashMap::new(),
            metrics: Box::new(NullCollector),
            runtime: RuntimeConfig::default(),
            pending: Vec::new(),
            pending_idx: 0,
            initialized: false,
            messages_out: 0,
            messages_dropped: 0,
            backpressure_events: 0,
        }
    }

    /// Attach a metrics collector (replaces the default null collector).
    pub fn with_metrics(mut self, metrics: impl MetricsCollector + 'static) -> Self {
        self.metrics = Box::new(metrics);
        self
    }

    /// Attach runtime configuration (back-pressure, batch hints, metrics toggle).
    pub fn with_runtime(mut self, runtime: RuntimeConfig) -> Self {
        self.runtime = runtime;
        self
    }

    /// Borrow runtime configuration.
    pub fn runtime_config(&self) -> &RuntimeConfig {
        &self.runtime
    }

    /// Messages successfully written to a sink since construction / last re-init.
    pub fn messages_out(&self) -> u64 {
        self.messages_out
    }

    /// Messages dropped by back-pressure policy.
    pub fn messages_dropped(&self) -> u64 {
        self.messages_dropped
    }

    /// Back-pressure events observed.
    pub fn backpressure_events(&self) -> u64 {
        self.backpressure_events
    }

    /// Borrow the source.
    pub fn source(&self) -> &S {
        &self.source
    }

    /// Mutably borrow the source.
    pub fn source_mut(&mut self) -> &mut S {
        &mut self.source
    }

    fn ensure_init(&self) -> Result<()> {
        if !self.initialized {
            return Err(Error::lifecycle(
                "SimplePipeline: call init() before step()",
            ));
        }
        Ok(())
    }

    fn record_metric(&self, key: RuntimeMetricKey, n: u64) {
        if self.runtime.metrics {
            self.metrics.record_counter(&key, n);
        }
    }

    fn refill_pending(&mut self) -> Result<bool> {
        self.pending.clear();
        self.pending_idx = 0;
        let n = self.source.poll_frames(&mut self.pending)?;
        // Honour runtime batch_size as an upper bound on pending work.
        if self.pending.len() > self.runtime.batch_size {
            self.pending.truncate(self.runtime.batch_size);
        }
        Ok(n > 0)
    }

    /// Decode → preprocess → place → write one frame, applying back-pressure policy.
    fn process_one_frame(&mut self, frame: &[u8]) -> Result<FrameResult> {
        let Some(msg) = self.decoder.decode(frame)? else {
            self.record_metric(RuntimeMetricKey::IdleSkips, 1);
            return Ok(FrameResult::Skipped);
        };
        let Some(msg) = self.preprocessor.process(msg)? else {
            self.record_metric(RuntimeMetricKey::IdleSkips, 1);
            return Ok(FrameResult::Skipped);
        };
        let sink_id = self.placement.route(&msg)?;
        if sink_id.is_none() {
            self.record_metric(RuntimeMetricKey::IdleSkips, 1);
            return Ok(FrameResult::Skipped);
        }
        self.write_with_backpressure(sink_id, &msg)
    }

    fn write_with_backpressure(&mut self, sink_id: SinkId, msg: &M) -> Result<FrameResult> {
        let mut retries = 0u32;
        let max_retries = self.runtime.backpressure_retries;
        loop {
            let write_result = {
                let sink = self.sinks.get_mut(&sink_id.as_u32()).ok_or_else(|| {
                    Error::placement(format!("no sink registered for id {}", sink_id.as_u32()))
                })?;
                sink.write(msg)
            };
            match write_result {
                Ok(()) => {
                    self.messages_out += 1;
                    self.record_metric(RuntimeMetricKey::MessagesOut, 1);
                    return Ok(FrameResult::Written);
                }
                Err(e) if e.kind() == ErrorKind::BackPressure => {
                    self.backpressure_events += 1;
                    self.record_metric(RuntimeMetricKey::BackpressureEvents, 1);
                    match self.runtime.backpressure {
                        BackpressureStrategy::DropNewest | BackpressureStrategy::DropOldest => {
                            self.messages_dropped += 1;
                            self.record_metric(RuntimeMetricKey::MessagesDropped, 1);
                            return Ok(FrameResult::Dropped);
                        }
                        BackpressureStrategy::Overflow => {
                            if let Some(oid) = self.runtime.overflow_sink {
                                let overflow = SinkId::try_new(oid)?;
                                if overflow != sink_id {
                                    let over_res = {
                                        let sink = self.sinks.get_mut(&overflow.as_u32());
                                        match sink {
                                            Some(s) => s.write(msg),
                                            None => Err(Error::placement(format!(
                                                "overflow sink {oid} not registered"
                                            ))),
                                        }
                                    };
                                    match over_res {
                                        Ok(()) => {
                                            self.messages_out += 1;
                                            self.record_metric(RuntimeMetricKey::MessagesOut, 1);
                                            return Ok(FrameResult::Written);
                                        }
                                        Err(e2) if e2.kind() == ErrorKind::BackPressure => {
                                            self.messages_dropped += 1;
                                            self.record_metric(
                                                RuntimeMetricKey::MessagesDropped,
                                                1,
                                            );
                                            return Ok(FrameResult::Dropped);
                                        }
                                        Err(e2) => return Err(e2),
                                    }
                                }
                            }
                            self.messages_dropped += 1;
                            self.record_metric(RuntimeMetricKey::MessagesDropped, 1);
                            return Ok(FrameResult::Dropped);
                        }
                        BackpressureStrategy::Block
                        | BackpressureStrategy::Spin
                        | BackpressureStrategy::AdaptiveBatching => {
                            retries += 1;
                            if let Some(max) = max_retries
                                && retries > max
                            {
                                return Ok(FrameResult::BackPressured);
                            }
                            let yield_d = self.runtime.backpressure_yield();
                            if yield_d.is_zero()
                                || matches!(self.runtime.backpressure, BackpressureStrategy::Spin)
                            {
                                std::thread::yield_now();
                            } else {
                                std::thread::sleep(yield_d);
                            }
                        }
                    }
                }
                Err(e) => return Err(e),
            }
        }
    }
}

/// Result of attempting to process one frame.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
enum FrameResult {
    Written,
    Skipped,
    Dropped,
    BackPressured,
}

impl<M, S, D, P, Pl> Lifecycle for SimplePipeline<M, S, D, P, Pl>
where
    M: Message,
    S: RawBatchSource,
    D: Decoder<Output = M>,
    P: PreProcessor<Message = M>,
    Pl: Placement<Message = M>,
{
    fn init(&mut self) -> Result<()> {
        if self.sinks.is_empty() {
            return Err(Error::config(
                "SimplePipeline: register at least one sink before init",
            ));
        }
        self.source.init()?;
        for sink in self.sinks.values_mut() {
            sink.init()?;
        }
        self.pending.clear();
        self.pending_idx = 0;
        self.messages_out = 0;
        self.messages_dropped = 0;
        self.backpressure_events = 0;
        self.initialized = true;
        Ok(())
    }

    fn shutdown(&mut self) -> Result<()> {
        let mut first_err = None;
        for sink in self.sinks.values_mut() {
            if let Err(e) = sink.flush().and_then(|_| sink.shutdown())
                && first_err.is_none()
            {
                first_err = Some(e);
            }
        }
        if let Err(e) = self.source.shutdown()
            && first_err.is_none()
        {
            first_err = Some(e);
        }
        self.initialized = false;
        self.pending.clear();
        first_err.map_or(Ok(()), Err)
    }

    fn run(&mut self) -> Result<()> {
        while !matches!(self.step_outcome()?, StepOutcome::Exhausted) {}
        Ok(())
    }
}

impl<M, S, D, P, Pl> Pipeline for SimplePipeline<M, S, D, P, Pl>
where
    M: Message,
    S: RawBatchSource,
    D: Decoder<Output = M>,
    P: PreProcessor<Message = M>,
    Pl: Placement<Message = M>,
{
    type Message = M;

    fn step(&mut self) -> Result<bool> {
        match self.step_outcome()? {
            StepOutcome::Progress => Ok(true),
            _ => Ok(false),
        }
    }

    fn step_outcome(&mut self) -> Result<StepOutcome> {
        self.ensure_init()?;

        // Drain pending frames first (batch-oriented: process until progress/BP).
        while self.pending_idx < self.pending.len() {
            let frame = self.pending[self.pending_idx].clone();
            match self.process_one_frame(&frame)? {
                FrameResult::Written | FrameResult::Dropped => {
                    self.pending_idx += 1;
                    return Ok(StepOutcome::Progress);
                }
                FrameResult::Skipped => {
                    self.pending_idx += 1;
                    continue;
                }
                FrameResult::BackPressured => {
                    // Do not advance pending_idx — retry same frame next step.
                    return Ok(StepOutcome::BackPressured);
                }
            }
        }

        if self.source.is_exhausted() {
            return Ok(StepOutcome::Exhausted);
        }

        let had_data = self.refill_pending()?;
        if !had_data {
            if self.source.is_exhausted() {
                return Ok(StepOutcome::Exhausted);
            }
            return Ok(StepOutcome::Idle);
        }

        while self.pending_idx < self.pending.len() {
            let frame = self.pending[self.pending_idx].clone();
            match self.process_one_frame(&frame)? {
                FrameResult::Written | FrameResult::Dropped => {
                    self.pending_idx += 1;
                    return Ok(StepOutcome::Progress);
                }
                FrameResult::Skipped => {
                    self.pending_idx += 1;
                    continue;
                }
                FrameResult::BackPressured => return Ok(StepOutcome::BackPressured),
            }
        }
        Ok(StepOutcome::Idle)
    }

    fn register_sink(
        &mut self,
        id: SinkId,
        sink: Box<dyn Sink<Message = Self::Message>>,
    ) -> Result<()> {
        if self.initialized {
            return Err(Error::lifecycle("cannot register_sink after init"));
        }
        if id.is_none() {
            return Err(Error::config("cannot register sink under SinkId::NONE"));
        }
        if self.sinks.contains_key(&id.as_u32()) {
            return Err(Error::config(format!(
                "sink id {} already registered",
                id.as_u32()
            )));
        }
        self.sinks.insert(id.as_u32(), sink);
        Ok(())
    }
}

// ---------------------------------------------------------------------------
// Backend adapters
// ---------------------------------------------------------------------------

/// Adapts a [`crate::net::NetworkSource`] into a [`RawBatchSource`].
pub struct NetworkBatchSource<N> {
    inner: N,
    batch: crate::net::RawBatch,
}

impl<N: crate::net::NetworkSource> NetworkBatchSource<N> {
    /// Create an adapter with the given batch capacity and max frame size.
    pub fn new(inner: N, capacity: usize, max_frame_size: usize) -> Self {
        Self {
            inner,
            batch: crate::net::RawBatch::new(capacity, max_frame_size),
        }
    }

    /// Borrow the inner network source.
    pub fn inner(&self) -> &N {
        &self.inner
    }

    /// Mutably borrow the inner network source.
    pub fn inner_mut(&mut self) -> &mut N {
        &mut self.inner
    }
}

impl<N: crate::net::NetworkSource> Lifecycle for NetworkBatchSource<N> {
    fn init(&mut self) -> Result<()> {
        self.inner.init()
    }

    fn shutdown(&mut self) -> Result<()> {
        self.inner.shutdown()
    }
}

impl<N: crate::net::NetworkSource> RawBatchSource for NetworkBatchSource<N> {
    fn poll_frames(&mut self, out: &mut Vec<Vec<u8>>) -> Result<usize> {
        self.batch.reset(self.batch.max_frame_size());
        let n = self.inner.poll_batch(&mut self.batch)?;
        for (data, _) in self.batch.packets() {
            out.push(data.to_vec());
        }
        Ok(n)
    }
}

/// Adapts a [`crate::storage::StorageSource`] into a [`RawBatchSource`].
pub struct StorageBatchSource<S> {
    inner: S,
    batch: crate::storage::RawRecordBatch,
}

impl<S: crate::storage::StorageSource> StorageBatchSource<S> {
    /// Create an adapter with the given batch capacity and max record size.
    pub fn new(inner: S, capacity: usize, max_record_size: usize) -> Self {
        Self {
            inner,
            batch: crate::storage::RawRecordBatch::new(capacity, max_record_size),
        }
    }

    /// Create from a [`crate::storage::FileConfig`]'s sizing fields.
    pub fn from_file_config(inner: S, cfg: &crate::storage::FileConfig) -> Self {
        Self::new(inner, cfg.batch_size.max(1), cfg.max_record_size.max(1))
    }

    /// Borrow the inner storage source.
    pub fn inner(&self) -> &S {
        &self.inner
    }

    /// Mutably borrow the inner storage source.
    pub fn inner_mut(&mut self) -> &mut S {
        &mut self.inner
    }
}

impl<S: crate::storage::StorageSource> Lifecycle for StorageBatchSource<S> {
    fn init(&mut self) -> Result<()> {
        self.inner.init()
    }

    fn shutdown(&mut self) -> Result<()> {
        self.inner.shutdown()
    }
}

impl<S: crate::storage::StorageSource> RawBatchSource for StorageBatchSource<S> {
    fn poll_frames(&mut self, out: &mut Vec<Vec<u8>>) -> Result<usize> {
        self.batch.reset();
        let n = self.inner.poll_batch(&mut self.batch)?;
        for (data, _) in self.batch.records() {
            out.push(data.to_vec());
        }
        Ok(n)
    }

    fn is_exhausted(&self) -> bool {
        self.inner.is_exhausted()
    }
}

#[cfg(test)]
mod tests {
    use super::*;
    use crate::api::{DefaultSchemaId, Encode, Metadata, Timestamp};

    #[derive(Debug, Clone, Copy, PartialEq, Eq)]
    struct Tick {
        seq: u64,
    }

    impl Message for Tick {
        type Schema = DefaultSchemaId;
        fn schema_id(&self) -> DefaultSchemaId {
            DefaultSchemaId(1)
        }
        fn timestamp(&self) -> Timestamp {
            Timestamp::from_nanos(0)
        }
        fn metadata(&self) -> Metadata {
            Metadata {
                sequence: self.seq,
                suspect: false,
            }
        }
    }

    impl Encode for Tick {
        fn encoded_len(&self) -> usize {
            8
        }
        fn encode_into(&self, dst: &mut [u8]) -> Result<usize> {
            dst[..8].copy_from_slice(&self.seq.to_be_bytes());
            Ok(8)
        }
    }

    struct TickDecoder;
    impl Decoder for TickDecoder {
        type Output = Tick;
        fn decode(&mut self, raw: &[u8]) -> Result<Option<Tick>> {
            if raw.len() < 8 {
                return Ok(None);
            }
            let seq = u64::from_be_bytes(raw[..8].try_into().unwrap());
            Ok(Some(Tick { seq }))
        }
    }

    struct VecSource {
        frames: Vec<Vec<u8>>,
        idx: usize,
        init: bool,
    }

    impl Lifecycle for VecSource {
        fn init(&mut self) -> Result<()> {
            self.init = true;
            self.idx = 0;
            Ok(())
        }
        fn shutdown(&mut self) -> Result<()> {
            self.init = false;
            Ok(())
        }
    }

    impl RawBatchSource for VecSource {
        fn poll_frames(&mut self, out: &mut Vec<Vec<u8>>) -> Result<usize> {
            if !self.init {
                return Err(Error::lifecycle("not init"));
            }
            if self.idx >= self.frames.len() {
                return Ok(0);
            }
            let f = self.frames[self.idx].clone();
            self.idx += 1;
            out.push(f);
            Ok(1)
        }
        fn is_exhausted(&self) -> bool {
            self.idx >= self.frames.len()
        }
    }

    struct CollectSink {
        out: Vec<Tick>,
    }

    impl Lifecycle for CollectSink {}
    impl Sink for CollectSink {
        type Message = Tick;
        fn write(&mut self, message: &Tick) -> Result<()> {
            self.out.push(*message);
            Ok(())
        }
    }

    #[test]
    fn end_to_end_vec_source() {
        let frames: Vec<Vec<u8>> = (0..5u64)
            .map(|s| {
                let mut b = vec![0u8; 8];
                Tick { seq: s }.encode_into(&mut b).unwrap();
                b
            })
            .collect();
        let src = VecSource {
            frames,
            idx: 0,
            init: false,
        };
        let sink_id = SinkId::new(1);
        let mut pipe = SimplePipeline::new(
            src,
            TickDecoder,
            IdentityPreProcessor::default(),
            FixedPlacement::new(sink_id).unwrap(),
        );
        let collector = CollectSink { out: Vec::new() };
        // We need to keep the sink accessible — register and run, then check
        // messages_out.
        pipe.register_sink(sink_id, Box::new(collector)).unwrap();
        pipe.init().unwrap();
        let mut progress = 0;
        for _ in 0..20 {
            match pipe.step_outcome().unwrap() {
                StepOutcome::Progress => progress += 1,
                StepOutcome::Exhausted => break,
                StepOutcome::Idle | StepOutcome::BackPressured => {}
            }
        }
        assert_eq!(progress, 5);
        assert_eq!(pipe.messages_out(), 5);
        pipe.shutdown().unwrap();
    }

    #[cfg(feature = "memory")]
    #[test]
    fn network_sim_to_memory() {
        use crate::memory::{SharedMemorySink, StubMessage};
        use crate::net::{SimNetConfig, SimulatedNetSource};

        // Decoder that accepts any frame ≥ 8 bytes as a StubMessage using
        // the sequence from the sim payload (offset after eth/ip/udp = 42).
        struct AnyFrameDecoder;
        impl Decoder for AnyFrameDecoder {
            type Output = StubMessage;
            fn decode(&mut self, raw: &[u8]) -> Result<Option<StubMessage>> {
                if raw.len() < 50 {
                    return Ok(None);
                }
                let seq = u64::from_be_bytes(raw[42..50].try_into().unwrap());
                Ok(Some(StubMessage { seq }))
            }
        }

        let src = SimulatedNetSource::new(SimNetConfig {
            batch_size: 4,
            payload_size: 16,
            ..SimNetConfig::default()
        });
        let adapted = NetworkBatchSource::new(src, 8, 2048);
        let sink_id = SinkId::new(1);
        let mut pipe = SimplePipeline::new(
            adapted,
            AnyFrameDecoder,
            IdentityPreProcessor::default(),
            FixedPlacement::new(sink_id).unwrap(),
        );
        let mem = SharedMemorySink::<StubMessage>::new(64, 64).unwrap();
        pipe.register_sink(sink_id, Box::new(mem)).unwrap();
        pipe.init().unwrap();
        let mut wrote = 0u64;
        for _ in 0..10 {
            if matches!(pipe.step_outcome().unwrap(), StepOutcome::Progress) {
                wrote += 1;
            }
        }
        assert!(wrote > 0, "expected some messages through the pipeline");
        pipe.shutdown().unwrap();
    }
}