pipe-io 1.0.0

Typed source-transform-sink pipelines with backpressure, batching, windowing, and per-stage error isolation. A lightweight runtime-agnostic stream processor for in-process workloads. The missing middle ground between raw iterators and full distributed stream processing.
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
//! Batching primitives: [`BatchPolicy`], [`Batch`], and [`ByteSize`].
//!
//! Batching is inserted into a pipeline via
//! [`crate::PipelineBuilder::batch`]. The carrier type changes from `T`
//! to `Batch<T>` after the call.

use alloc::vec::Vec;
use core::ops::Deref;
use core::slice;

use crate::emit::Emit;
use crate::source::Infallible;
use crate::stage::Stage;

#[cfg(feature = "std")]
use core::time::Duration;
#[cfg(feature = "std")]
use std::time::Instant;

/// Trigger configuration for a batching stage.
///
/// All configured triggers OR together: the batch is flushed as soon
/// as any one of them is satisfied. At least one of `max_items`,
/// `max_bytes`, or `max_age` must be set for the builder to accept
/// the policy.
///
/// # Example
///
/// ```
/// use pipe_io::BatchPolicy;
/// let p = BatchPolicy::new().max_items(1_000);
/// assert_eq!(p.items_limit(), Some(1_000));
/// ```
#[derive(Debug, Clone, Copy, Default)]
pub struct BatchPolicy {
    max_items: Option<usize>,
    max_bytes: Option<usize>,
    #[cfg(feature = "std")]
    max_age: Option<Duration>,
}

impl BatchPolicy {
    /// Construct a new empty policy. At least one trigger must be set
    /// before the policy is used by the builder.
    #[must_use]
    pub const fn new() -> Self {
        Self {
            max_items: None,
            max_bytes: None,
            #[cfg(feature = "std")]
            max_age: None,
        }
    }

    /// Set the maximum number of items per batch.
    #[must_use]
    pub const fn max_items(mut self, n: usize) -> Self {
        self.max_items = Some(n);
        self
    }

    /// Set the maximum byte size per batch. Requires the item type to
    /// implement [`ByteSize`].
    #[must_use]
    pub const fn max_bytes(mut self, n: usize) -> Self {
        self.max_bytes = Some(n);
        self
    }

    /// Set the maximum age of a batch (time between first push and
    /// flush). Requires the `std` feature.
    #[cfg(feature = "std")]
    #[cfg_attr(docsrs, doc(cfg(feature = "std")))]
    #[must_use]
    pub const fn max_age(mut self, age: Duration) -> Self {
        self.max_age = Some(age);
        self
    }

    /// Current items trigger.
    #[must_use]
    pub const fn items_limit(&self) -> Option<usize> {
        self.max_items
    }

    /// Current byte trigger.
    #[must_use]
    pub const fn bytes_limit(&self) -> Option<usize> {
        self.max_bytes
    }

    /// Current age trigger.
    #[cfg(feature = "std")]
    #[cfg_attr(docsrs, doc(cfg(feature = "std")))]
    #[must_use]
    pub const fn age_limit(&self) -> Option<Duration> {
        self.max_age
    }

    /// True if at least one trigger is configured.
    #[must_use]
    pub const fn has_trigger(&self) -> bool {
        if self.max_items.is_some() || self.max_bytes.is_some() {
            return true;
        }
        #[cfg(feature = "std")]
        {
            if self.max_age.is_some() {
                return true;
            }
        }
        false
    }
}

/// Opt-in trait for items that contribute a measurable byte size to a
/// batch. Required when [`BatchPolicy::max_bytes`] is set.
pub trait ByteSize {
    /// Number of bytes this item contributes to the batch.
    fn byte_size(&self) -> usize;
}

impl ByteSize for &str {
    fn byte_size(&self) -> usize {
        self.len()
    }
}

impl ByteSize for alloc::string::String {
    fn byte_size(&self) -> usize {
        self.len()
    }
}

impl ByteSize for Vec<u8> {
    fn byte_size(&self) -> usize {
        self.len()
    }
}

impl ByteSize for &[u8] {
    fn byte_size(&self) -> usize {
        self.len()
    }
}

/// A flushed group of items produced by the batching stage.
///
/// Deref's to `[T]`, so all slice methods are available. Owned items
/// are exposed via [`Batch::into_inner`].
#[derive(Debug, Clone)]
pub struct Batch<T> {
    items: Vec<T>,
}

impl<T> Batch<T> {
    /// Construct a batch wrapping an existing `Vec`.
    #[must_use]
    pub const fn new(items: Vec<T>) -> Self {
        Self { items }
    }

    /// Number of items in this batch.
    #[must_use]
    pub fn len(&self) -> usize {
        self.items.len()
    }

    /// True if the batch holds no items.
    #[must_use]
    pub fn is_empty(&self) -> bool {
        self.items.is_empty()
    }

    /// Slice iterator over the items.
    pub fn iter(&self) -> slice::Iter<'_, T> {
        self.items.iter()
    }

    /// Unwrap and return the inner `Vec`.
    #[must_use]
    pub fn into_inner(self) -> Vec<T> {
        self.items
    }
}

impl<T> Deref for Batch<T> {
    type Target = [T];

    fn deref(&self) -> &Self::Target {
        &self.items
    }
}

impl<T> IntoIterator for Batch<T> {
    type Item = T;
    type IntoIter = alloc::vec::IntoIter<T>;
    fn into_iter(self) -> Self::IntoIter {
        self.items.into_iter()
    }
}

impl<'a, T> IntoIterator for &'a Batch<T> {
    type Item = &'a T;
    type IntoIter = slice::Iter<'a, T>;
    fn into_iter(self) -> Self::IntoIter {
        self.items.iter()
    }
}

// ---------------------------------------------------------------------
// BatchStage: count-and-age trigger Stage<Input = T, Output = Batch<T>>.
// The builder picks BatchStage when policy has no bytes trigger, and
// BatchStageBytes when it does (which requires T: ByteSize).
// ---------------------------------------------------------------------

#[derive(Debug)]
pub(crate) struct BatchStage<T> {
    policy: BatchPolicy,
    items: Vec<T>,
    #[cfg(feature = "std")]
    started_at: Option<Instant>,
}

impl<T> BatchStage<T> {
    pub(crate) fn new(policy: BatchPolicy) -> Self {
        let cap = policy.max_items.unwrap_or(64);
        Self {
            policy,
            items: Vec::with_capacity(cap),
            #[cfg(feature = "std")]
            started_at: None,
        }
    }

    fn should_flush(&self) -> bool {
        if let Some(limit) = self.policy.max_items {
            if self.items.len() >= limit {
                return true;
            }
        }
        #[cfg(feature = "std")]
        {
            if let (Some(age), Some(start)) = (self.policy.max_age, self.started_at) {
                if start.elapsed() >= age {
                    return true;
                }
            }
        }
        false
    }

    fn drain(&mut self) -> Batch<T> {
        let cap = self.policy.max_items.unwrap_or(self.items.capacity());
        let items = core::mem::replace(&mut self.items, Vec::with_capacity(cap));
        #[cfg(feature = "std")]
        {
            self.started_at = None;
        }
        Batch::new(items)
    }
}

impl<T> Stage for BatchStage<T>
where
    T: 'static,
{
    type Input = T;
    type Output = Batch<T>;
    type Error = Infallible;

    fn process(
        &mut self,
        item: Self::Input,
        out: &mut dyn Emit<Item = Self::Output>,
    ) -> Result<(), Self::Error> {
        #[cfg(feature = "std")]
        {
            if self.started_at.is_none() {
                self.started_at = Some(Instant::now());
            }
        }
        self.items.push(item);
        if self.should_flush() {
            let batch = self.drain();
            let _ = out.emit(batch);
        }
        Ok(())
    }

    fn flush(&mut self, out: &mut dyn Emit<Item = Self::Output>) -> Result<(), Self::Error> {
        if !self.items.is_empty() {
            let batch = self.drain();
            let _ = out.emit(batch);
        }
        Ok(())
    }
}

// ---------------------------------------------------------------------
// Byte-aware variant. Used when policy.max_bytes is set.
// ---------------------------------------------------------------------

#[derive(Debug)]
pub(crate) struct BatchStageBytes<T: ByteSize> {
    policy: BatchPolicy,
    items: Vec<T>,
    bytes: usize,
    #[cfg(feature = "std")]
    started_at: Option<Instant>,
}

impl<T: ByteSize> BatchStageBytes<T> {
    pub(crate) fn new(policy: BatchPolicy) -> Self {
        let cap = policy.max_items.unwrap_or(64);
        Self {
            policy,
            items: Vec::with_capacity(cap),
            bytes: 0,
            #[cfg(feature = "std")]
            started_at: None,
        }
    }

    fn should_flush(&self) -> bool {
        if let Some(limit) = self.policy.max_items {
            if self.items.len() >= limit {
                return true;
            }
        }
        if let Some(limit) = self.policy.max_bytes {
            if self.bytes >= limit {
                return true;
            }
        }
        #[cfg(feature = "std")]
        {
            if let (Some(age), Some(start)) = (self.policy.max_age, self.started_at) {
                if start.elapsed() >= age {
                    return true;
                }
            }
        }
        false
    }

    fn drain(&mut self) -> Batch<T> {
        let cap = self.policy.max_items.unwrap_or(self.items.capacity());
        let items = core::mem::replace(&mut self.items, Vec::with_capacity(cap));
        self.bytes = 0;
        #[cfg(feature = "std")]
        {
            self.started_at = None;
        }
        Batch::new(items)
    }
}

impl<T> Stage for BatchStageBytes<T>
where
    T: ByteSize + 'static,
{
    type Input = T;
    type Output = Batch<T>;
    type Error = Infallible;

    fn process(
        &mut self,
        item: Self::Input,
        out: &mut dyn Emit<Item = Self::Output>,
    ) -> Result<(), Self::Error> {
        #[cfg(feature = "std")]
        {
            if self.started_at.is_none() {
                self.started_at = Some(Instant::now());
            }
        }
        self.bytes += item.byte_size();
        self.items.push(item);
        if self.should_flush() {
            let batch = self.drain();
            let _ = out.emit(batch);
        }
        Ok(())
    }

    fn flush(&mut self, out: &mut dyn Emit<Item = Self::Output>) -> Result<(), Self::Error> {
        if !self.items.is_empty() {
            let batch = self.drain();
            let _ = out.emit(batch);
        }
        Ok(())
    }
}

#[cfg(test)]
mod tests {
    use super::*;
    use crate::emit::EmitError;
    use alloc::vec;

    struct Collect<'a, T> {
        out: &'a mut Vec<Batch<T>>,
    }
    impl<'a, T> Emit for Collect<'a, T> {
        type Item = Batch<T>;
        fn emit(&mut self, b: Batch<T>) -> Result<(), EmitError> {
            self.out.push(b);
            Ok(())
        }
    }

    #[test]
    fn policy_builder_records_triggers() {
        let p = BatchPolicy::new().max_items(10).max_bytes(1024);
        assert_eq!(p.items_limit(), Some(10));
        assert_eq!(p.bytes_limit(), Some(1024));
        assert!(p.has_trigger());
    }

    #[test]
    fn empty_policy_has_no_trigger() {
        let p = BatchPolicy::new();
        assert!(!p.has_trigger());
    }

    #[test]
    fn batch_stage_emits_on_count() {
        let mut stage = BatchStage::<i32>::new(BatchPolicy::new().max_items(3));
        let mut got: Vec<Batch<i32>> = Vec::new();
        let mut emit = Collect { out: &mut got };
        for i in 1..=7 {
            stage.process(i, &mut emit).unwrap();
        }
        stage.flush(&mut emit).unwrap();
        let lens: Vec<_> = got.iter().map(Batch::len).collect();
        assert_eq!(lens, vec![3, 3, 1]);
        let all: Vec<i32> = got.into_iter().flat_map(Batch::into_inner).collect();
        assert_eq!(all, vec![1, 2, 3, 4, 5, 6, 7]);
    }

    #[test]
    fn byte_size_blanket_impls() {
        let s: &str = "abc";
        assert_eq!(s.byte_size(), 3);
        let owned: alloc::string::String = "abcd".into();
        assert_eq!(owned.byte_size(), 4);
        let v: Vec<u8> = vec![1, 2, 3, 4, 5];
        assert_eq!(v.byte_size(), 5);
        let sl: &[u8] = &[1, 2];
        assert_eq!(sl.byte_size(), 2);
    }

    #[test]
    fn batch_stage_bytes_emits_on_bytes() {
        let policy = BatchPolicy::new().max_bytes(8);
        let mut stage = BatchStageBytes::<alloc::string::String>::new(policy);
        let mut got: Vec<Batch<alloc::string::String>> = Vec::new();
        let mut emit = Collect { out: &mut got };
        stage.process("aa".into(), &mut emit).unwrap();
        stage.process("bb".into(), &mut emit).unwrap();
        stage.process("cccc".into(), &mut emit).unwrap();
        stage.process("dd".into(), &mut emit).unwrap();
        stage.flush(&mut emit).unwrap();
        let lens: Vec<_> = got.iter().map(Batch::len).collect();
        assert_eq!(lens, vec![3, 1]);
    }
}