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
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
//! Windowing primitives: [`Clock`], [`SystemClock`], [`WindowPolicy`],
//! and [`Window<T>`].
//!
//! Windowing groups items by wall-clock time. Three policies are
//! supported:
//!
//! * [`WindowPolicy::Tumbling`] - fixed, non-overlapping windows of
//!   duration `size`.
//! * [`WindowPolicy::Sliding`] - overlapping windows of width `size`
//!   that advance by `slide` each tick. Each item belongs to multiple
//!   active windows, so `T: Clone` is required.
//! * [`WindowPolicy::Session`] - adaptive windows that close after
//!   `idle` of no activity.
//!
//! Windows close on the *next* item arriving after the close condition
//! is satisfied (or at end-of-stream via [`crate::Stage::flush`]). With
//! pure synchronous execution there is no background timer that fires
//! while items are not flowing; if a session window is `idle` and no
//! further items arrive, it closes only when [`crate::Pipeline::run`]
//! reaches end-of-stream and flushes.
//!
//! # Example
//!
//! ```
//! use core::time::Duration;
//! use pipe_io::WindowPolicy;
//!
//! let p = WindowPolicy::Tumbling { size: Duration::from_secs(5) };
//! assert!(matches!(p, WindowPolicy::Tumbling { .. }));
//! ```

use alloc::collections::VecDeque;
use alloc::vec::Vec;
use core::time::Duration;
use std::time::Instant;

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

/// Source of wall-clock time used by [`crate::PipelineBuilder::window`].
///
/// The default impl is [`SystemClock`], which wraps
/// [`std::time::Instant::now`]. Custom impls let tests advance time
/// deterministically.
pub trait Clock: Send {
    /// Return the current instant.
    fn now(&self) -> Instant;
}

/// Default [`Clock`] using [`std::time::Instant::now`].
#[derive(Debug, Default, Clone, Copy)]
pub struct SystemClock;

impl Clock for SystemClock {
    fn now(&self) -> Instant {
        Instant::now()
    }
}

/// Window emission strategy.
///
/// Pass to [`crate::PipelineBuilder::window`] to install a windowing
/// stage. The carrier type changes from `T` to [`Window<T>`] after
/// the call.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum WindowPolicy {
    /// Fixed-width, non-overlapping windows. The first window starts
    /// when the first item arrives; subsequent windows are anchored
    /// at multiples of `size` from that point.
    Tumbling {
        /// Width of each window.
        size: Duration,
    },
    /// Overlapping windows of width `size`. A new window starts every
    /// `slide` interval. Each item is duplicated into every active
    /// window, so the item type must be `Clone`.
    Sliding {
        /// Width of each window.
        size: Duration,
        /// Time between successive window starts.
        slide: Duration,
    },
    /// Adaptive window that stays open as long as new items arrive
    /// within `idle`. Closes (and emits) on the next item arriving
    /// after `idle` has elapsed since the last item, or at
    /// end-of-stream.
    Session {
        /// Idle gap after which the window closes.
        idle: Duration,
    },
}

/// A closed window of items with a start and end instant.
///
/// `start <= end` always holds. For tumbling and sliding windows
/// `end - start == size` (modulo end-of-stream flushes). For session
/// windows `end` is the instant of the last item that arrived inside
/// the session.
#[derive(Debug, Clone)]
pub struct Window<T> {
    items: Vec<T>,
    start: Instant,
    end: Instant,
}

impl<T> Window<T> {
    /// Construct a window directly from parts. Primarily for tests
    /// and custom Stage implementations.
    #[must_use]
    pub fn new(items: Vec<T>, start: Instant, end: Instant) -> Self {
        Self { items, start, end }
    }

    /// Items in this window, in arrival order.
    #[must_use]
    pub fn items(&self) -> &[T] {
        &self.items
    }

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

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

    /// Window start instant.
    #[must_use]
    pub fn start(&self) -> Instant {
        self.start
    }

    /// Window end instant. For tumbling/sliding, this is `start + size`.
    /// For session, this is the timestamp of the last item.
    #[must_use]
    pub fn end(&self) -> Instant {
        self.end
    }

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

impl<T> IntoIterator for Window<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 Window<T> {
    type Item = &'a T;
    type IntoIter = core::slice::Iter<'a, T>;
    fn into_iter(self) -> Self::IntoIter {
        self.items.iter()
    }
}

// ---------------------------------------------------------------------
// Internal stage implementation. Used by PipelineBuilder::window.
// Requires T: Clone universally because sliding windows duplicate
// items across overlapping windows. Tumbling/session do not strictly
// need Clone, but keeping a unified stage type simplifies the builder.
// Consumers with non-Clone item types can use `.batch()` with a
// `max_age` trigger as a substitute for tumbling windows.
// ---------------------------------------------------------------------

struct PendingWindow<T> {
    start: Instant,
    end: Instant,
    items: Vec<T>,
}

pub(crate) struct WindowStage<T: Clone, C: Clock> {
    policy: WindowPolicy,
    clock: C,
    state: WindowState<T>,
}

enum WindowState<T> {
    Tumbling {
        start: Option<Instant>,
        items: Vec<T>,
    },
    Sliding {
        windows: VecDeque<PendingWindow<T>>,
        next_window_start: Option<Instant>,
    },
    Session {
        start: Option<Instant>,
        last_seen: Option<Instant>,
        items: Vec<T>,
    },
}

impl<T: Clone, C: Clock> WindowStage<T, C> {
    pub(crate) fn new(policy: WindowPolicy, clock: C) -> Self {
        let state = match policy {
            WindowPolicy::Tumbling { .. } => WindowState::Tumbling {
                start: None,
                items: Vec::new(),
            },
            WindowPolicy::Sliding { .. } => WindowState::Sliding {
                windows: VecDeque::new(),
                next_window_start: None,
            },
            WindowPolicy::Session { .. } => WindowState::Session {
                start: None,
                last_seen: None,
                items: Vec::new(),
            },
        };
        Self {
            policy,
            clock,
            state,
        }
    }
}

impl<T, C> Stage for WindowStage<T, C>
where
    T: Clone + Send + 'static,
    C: Clock + 'static,
{
    type Input = T;
    type Output = Window<T>;
    type Error = Infallible;

    fn process(
        &mut self,
        item: Self::Input,
        out: &mut dyn Emit<Item = Self::Output>,
    ) -> Result<(), Self::Error> {
        let now = self.clock.now();
        match (&self.policy, &mut self.state) {
            (WindowPolicy::Tumbling { size }, WindowState::Tumbling { start, items }) => {
                if start.is_none() {
                    *start = Some(now);
                }
                // Advance window boundaries past any elapsed sizes.
                while let Some(s) = *start {
                    if now.saturating_duration_since(s) >= *size {
                        let window_items = core::mem::take(items);
                        let _ = out.emit(Window::new(window_items, s, s + *size));
                        *start = Some(s + *size);
                    } else {
                        break;
                    }
                }
                items.push(item);
            }
            (
                WindowPolicy::Session { idle },
                WindowState::Session {
                    start,
                    last_seen,
                    items,
                },
            ) => {
                if let Some(ls) = *last_seen {
                    if now.saturating_duration_since(ls) > *idle {
                        if let Some(s) = *start {
                            let window_items = core::mem::take(items);
                            let _ = out.emit(Window::new(window_items, s, ls));
                        }
                        *start = Some(now);
                    }
                } else {
                    *start = Some(now);
                }
                *last_seen = Some(now);
                items.push(item);
            }
            (
                WindowPolicy::Sliding { size, slide },
                WindowState::Sliding {
                    windows,
                    next_window_start,
                },
            ) => {
                if next_window_start.is_none() {
                    *next_window_start = Some(now);
                }
                // Spawn new windows whose start is at or before now.
                while let Some(s) = *next_window_start {
                    if s <= now {
                        windows.push_back(PendingWindow {
                            start: s,
                            end: s + *size,
                            items: Vec::new(),
                        });
                        *next_window_start = Some(s + *slide);
                    } else {
                        break;
                    }
                }
                // Emit windows that have already ended.
                while let Some(w) = windows.front() {
                    if w.end <= now {
                        let w = windows.pop_front().expect("front exists");
                        let _ = out.emit(Window::new(w.items, w.start, w.end));
                    } else {
                        break;
                    }
                }
                // Add the new item to all currently-active windows.
                for w in windows.iter_mut() {
                    if w.start <= now && now < w.end {
                        w.items.push(item.clone());
                    }
                }
            }
            _ => unreachable!(
                "policy/state mismatch is impossible by construction; \
                 WindowStage::new enforces alignment"
            ),
        }
        Ok(())
    }

    fn flush(&mut self, out: &mut dyn Emit<Item = Self::Output>) -> Result<(), Self::Error> {
        let now = self.clock.now();
        match &mut self.state {
            WindowState::Tumbling { start, items } => {
                if !items.is_empty() {
                    let s = start.unwrap_or(now);
                    let window_items = core::mem::take(items);
                    let _ = out.emit(Window::new(window_items, s, now));
                }
            }
            WindowState::Session {
                start,
                last_seen,
                items,
            } => {
                if !items.is_empty() {
                    let s = start.unwrap_or(now);
                    let e = last_seen.unwrap_or(now);
                    let window_items = core::mem::take(items);
                    let _ = out.emit(Window::new(window_items, s, e));
                }
            }
            WindowState::Sliding { windows, .. } => {
                while let Some(w) = windows.pop_front() {
                    if !w.items.is_empty() {
                        let _ = out.emit(Window::new(w.items, w.start, w.end));
                    }
                }
            }
        }
        Ok(())
    }
}

#[cfg(test)]
mod tests {
    use super::*;
    use crate::emit::EmitError;
    use std::sync::{Arc, Mutex};

    // A deterministic Clock for tests. Each call to `now()` returns the
    // current set time. Tests advance time explicitly.
    #[derive(Clone)]
    struct FakeClock {
        inner: Arc<Mutex<Instant>>,
    }

    impl FakeClock {
        fn new(start: Instant) -> Self {
            Self {
                inner: Arc::new(Mutex::new(start)),
            }
        }

        fn advance(&self, by: Duration) {
            let mut g = self.inner.lock().unwrap();
            *g += by;
        }
    }

    impl Clock for FakeClock {
        fn now(&self) -> Instant {
            *self.inner.lock().unwrap()
        }
    }

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

    #[test]
    fn tumbling_emits_on_boundary() {
        let t0 = Instant::now();
        let clock = FakeClock::new(t0);
        let mut stage = WindowStage::<u32, _>::new(
            WindowPolicy::Tumbling {
                size: Duration::from_secs(10),
            },
            clock.clone(),
        );
        let mut emit = Collect::<u32> { out: Vec::new() };

        // t=0: item 1
        stage.process(1, &mut emit).unwrap();
        assert!(emit.out.is_empty());

        // t=5: item 2 (still inside first window)
        clock.advance(Duration::from_secs(5));
        stage.process(2, &mut emit).unwrap();
        assert!(emit.out.is_empty());

        // t=10: item 3 (boundary; emit window [0, 10) with items 1, 2)
        clock.advance(Duration::from_secs(5));
        stage.process(3, &mut emit).unwrap();
        assert_eq!(emit.out.len(), 1);
        assert_eq!(emit.out[0].items(), &[1, 2]);

        // t=20: item 4 (emit window [10, 20) with item 3)
        clock.advance(Duration::from_secs(10));
        stage.process(4, &mut emit).unwrap();
        assert_eq!(emit.out.len(), 2);
        assert_eq!(emit.out[1].items(), &[3]);

        // Flush emits the remaining window with item 4.
        stage.flush(&mut emit).unwrap();
        assert_eq!(emit.out.len(), 3);
        assert_eq!(emit.out[2].items(), &[4]);
    }

    #[test]
    fn session_closes_after_idle() {
        let t0 = Instant::now();
        let clock = FakeClock::new(t0);
        let mut stage = WindowStage::<u32, _>::new(
            WindowPolicy::Session {
                idle: Duration::from_secs(5),
            },
            clock.clone(),
        );
        let mut emit = Collect::<u32> { out: Vec::new() };

        // t=0: 1
        stage.process(1, &mut emit).unwrap();
        // t=2: 2 (within session)
        clock.advance(Duration::from_secs(2));
        stage.process(2, &mut emit).unwrap();
        // t=4: 3 (within session)
        clock.advance(Duration::from_secs(2));
        stage.process(3, &mut emit).unwrap();
        assert!(emit.out.is_empty());

        // t=20: 4 (>5s gap, closes prior session, starts new one)
        clock.advance(Duration::from_secs(16));
        stage.process(4, &mut emit).unwrap();
        assert_eq!(emit.out.len(), 1);
        assert_eq!(emit.out[0].items(), &[1, 2, 3]);

        // Flush closes the second session.
        stage.flush(&mut emit).unwrap();
        assert_eq!(emit.out.len(), 2);
        assert_eq!(emit.out[1].items(), &[4]);
    }

    #[test]
    fn sliding_overlapping_windows() {
        let t0 = Instant::now();
        let clock = FakeClock::new(t0);
        // size=10s, slide=5s: windows [0,10), [5,15), [10,20), ...
        let mut stage = WindowStage::<u32, _>::new(
            WindowPolicy::Sliding {
                size: Duration::from_secs(10),
                slide: Duration::from_secs(5),
            },
            clock.clone(),
        );
        let mut emit = Collect::<u32> { out: Vec::new() };

        // t=0: item 1. Spawns window [0,10). Item belongs.
        stage.process(1, &mut emit).unwrap();
        // t=3: item 2. Still only window [0,10) active.
        clock.advance(Duration::from_secs(3));
        stage.process(2, &mut emit).unwrap();
        // t=5: item 3. Spawns window [5,15). Item belongs to both [0,10) and [5,15).
        clock.advance(Duration::from_secs(2));
        stage.process(3, &mut emit).unwrap();
        // t=10: item 4. Window [0,10) ends -> emit. Spawn [10,20). Item belongs to [5,15) and [10,20).
        clock.advance(Duration::from_secs(5));
        stage.process(4, &mut emit).unwrap();
        assert_eq!(emit.out.len(), 1);
        assert_eq!(emit.out[0].items(), &[1, 2, 3]);

        // Flush emits remaining windows: [5,15) with {3,4}, [10,20) with {4}.
        stage.flush(&mut emit).unwrap();
        assert_eq!(emit.out.len(), 3);
        assert_eq!(emit.out[1].items(), &[3, 4]);
        assert_eq!(emit.out[2].items(), &[4]);
    }

    #[test]
    fn tumbling_flush_emits_partial() {
        let t0 = Instant::now();
        let clock = FakeClock::new(t0);
        let mut stage = WindowStage::<u32, _>::new(
            WindowPolicy::Tumbling {
                size: Duration::from_secs(10),
            },
            clock.clone(),
        );
        let mut emit = Collect::<u32> { out: Vec::new() };

        stage.process(1, &mut emit).unwrap();
        stage.process(2, &mut emit).unwrap();
        stage.flush(&mut emit).unwrap();
        assert_eq!(emit.out.len(), 1);
        assert_eq!(emit.out[0].items(), &[1, 2]);
    }

    #[test]
    fn window_into_inner_returns_items() {
        let t = Instant::now();
        let w = Window::new(alloc::vec![10u32, 20, 30], t, t);
        assert_eq!(w.len(), 3);
        assert!(!w.is_empty());
        assert_eq!(w.into_inner(), alloc::vec![10, 20, 30]);
    }
}