p2panda-stream 0.6.0

Event stream processing for p2p data-types
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
// SPDX-License-Identifier: MIT OR Apache-2.0

use std::cell::RefCell;
use std::convert::Infallible;
use std::marker::PhantomData;
use std::sync::atomic::AtomicU64;
use std::task::Poll;
use std::time::Duration;

use futures_util::{StreamExt, stream};
use tokio::{task, time};
use tokio_stream::wrappers::UnboundedReceiverStream;

use crate::processors::buffered::Buffer;
use crate::test_utils::{AsyncBuffer, assert_poll_eq};

use super::*;

/// Processor turning all strings into UPPERCASE.
#[derive(Default)]
struct UppercaseProcessor {
    outputs: RefCell<AsyncBuffer<String>>,
}

impl Processor<String> for UppercaseProcessor {
    type Output = String;

    type Error = Infallible;

    async fn process(&self, input: String) -> Result<(), Self::Error> {
        self.outputs.borrow_mut().push(input.to_uppercase());
        Ok(())
    }

    async fn next(&self) -> Result<Self::Output, Self::Error> {
        Ok(self.outputs.borrow_mut().pop().await)
    }
}

/// Processor adding a counter to any item.
struct CounterProcessor<T> {
    outputs: RefCell<AsyncBuffer<WithCounter<T>>>,
    counter: AtomicU64,
}

impl<T> CounterProcessor<T> {
    pub fn new() -> Self {
        Self {
            outputs: RefCell::new(AsyncBuffer::new()),
            counter: AtomicU64::new(0),
        }
    }
}

#[derive(Clone, Debug, PartialEq, Eq)]
struct WithCounter<T> {
    item: T,
    counter: u64,
}

impl<T> ToString for WithCounter<T>
where
    T: ToString,
{
    fn to_string(&self) -> String {
        format!("{}_{}", self.item.to_string(), self.counter)
    }
}

impl<T> Processor<T> for CounterProcessor<T> {
    type Output = WithCounter<T>;

    type Error = String;

    async fn process(&self, item: T) -> Result<(), Self::Error> {
        let counter = self
            .counter
            .fetch_add(1, std::sync::atomic::Ordering::Relaxed);

        self.outputs
            .borrow_mut()
            .push(WithCounter { item, counter });

        Ok(())
    }

    async fn next(&self) -> Result<Self::Output, Self::Error> {
        Ok(self.outputs.borrow_mut().pop().await)
    }
}

/// Test layer simulating "expensive" async operations when calling "next" or "process".
struct SlowProcessor<T> {
    process_delay: Duration,
    next_delay: Duration,
    output_queue: RefCell<AsyncBuffer<String>>,
    should_error: bool,
    _marker: PhantomData<T>,
}

impl<T> SlowProcessor<T>
where
    T: ToString,
{
    fn new() -> Self {
        Self {
            process_delay: Duration::from_millis(0),
            next_delay: Duration::from_millis(0),
            output_queue: RefCell::new(AsyncBuffer::new()),
            should_error: false,
            _marker: PhantomData,
        }
    }

    fn with_process_delay(mut self, process_delay: Duration) -> Self {
        self.process_delay = process_delay;
        self
    }

    fn with_next_delay(mut self, next_delay: Duration) -> Self {
        self.next_delay = next_delay;
        self
    }

    fn with_error_mode(mut self) -> Self {
        self.should_error = true;
        self
    }
}

impl<T> Processor<T> for SlowProcessor<T>
where
    T: ToString,
{
    type Output = String;

    type Error = String;

    async fn process(&self, input: T) -> Result<(), Self::Error> {
        time::sleep(self.process_delay).await;

        if self.should_error {
            return Err(format!("error in process method: {}", input.to_string()));
        }

        self.output_queue
            .borrow_mut()
            .push(format!("processed_{}", input.to_string()));

        Ok(())
    }

    async fn next(&self) -> Result<Self::Output, Self::Error> {
        time::sleep(self.next_delay).await;

        if self.should_error {
            return Err("error in next method".to_string());
        }

        Ok(self.output_queue.borrow_mut().pop().await)
    }
}

#[tokio::test]
async fn awaiting_on_next() {
    // Processors do not terminate and will rather await at "next" whenever there's no work.
    let uppercase = UppercaseProcessor::default();
    uppercase.process("Hello".to_string()).await.unwrap();
    assert_eq!(uppercase.next().await, Ok("HELLO".to_string()));
    assert_poll_eq(uppercase.next(), Poll::Pending);

    // Continue doing new work ..
    uppercase.process("World".to_string()).await.unwrap();
    assert_eq!(uppercase.next().await, Ok("WORLD".to_string()));
    assert_poll_eq(uppercase.next(), Poll::Pending);
}

#[tokio::test]
async fn chaining_processors() {
    let uppercase = UppercaseProcessor::default();
    let counter = CounterProcessor::<String>::new();

    let pipeline = PipelineBuilder::new()
        .layer(uppercase)
        .layer(counter)
        .build();

    pipeline.process("im".to_string()).await.unwrap();
    pipeline.process("very".to_string()).await.unwrap();
    pipeline.process("silent".to_string()).await.unwrap();

    assert_eq!(
        pipeline.next().await,
        Ok(WithCounter {
            item: "IM".to_string(),
            counter: 0,
        }),
    );

    assert_eq!(
        pipeline.next().await,
        Ok(WithCounter {
            item: "VERY".to_string(),
            counter: 1,
        }),
    );

    assert_eq!(
        pipeline.next().await,
        Ok(WithCounter {
            item: "SILENT".to_string(),
            counter: 2,
        }),
    );
}

#[tokio::test]
async fn expensive_async_processing() {
    let local = task::LocalSet::new();

    local
        .run_until(async move {
            // Have a "slow" processing layer which will not return a result instantly (first
            // poll will _not_ yield Poll::Ready(T)).
            let slow = SlowProcessor::new()
                .with_process_delay(Duration::from_millis(25))
                .with_next_delay(Duration::from_millis(50));
            assert_poll_eq(slow.process(0), Poll::Pending);
            assert_poll_eq(slow.next(), Poll::Pending);

            // .. eventually the result will arrive.
            slow.process(1).await.unwrap();
            let result = slow.next().await;
            assert_eq!(result, Ok("processed_1".to_string()));
        })
        .await;
}

#[tokio::test]
async fn expensive_async_processors_chaining() {
    let local = task::LocalSet::new();

    local
        .run_until(async move {
            let handle_1 = task::spawn_local(async {
                let slow_1 = SlowProcessor::new().with_next_delay(Duration::from_millis(10));
                let uppercase = UppercaseProcessor::default();
                let slow_2 = SlowProcessor::new().with_next_delay(Duration::from_millis(10));

                let pipeline = PipelineBuilder::new()
                    .layer(slow_1)
                    .layer(uppercase)
                    .layer(slow_2)
                    .build();

                pipeline.process(1).await.unwrap();
                pipeline.process(2).await.unwrap();
                pipeline.process(3).await.unwrap();

                assert_eq!(pipeline.next().await, Ok("processed_PROCESSED_1".into()));
                pipeline.process(4).await.unwrap();
                assert_eq!(pipeline.next().await, Ok("processed_PROCESSED_2".into()));
                assert_eq!(pipeline.next().await, Ok("processed_PROCESSED_3".into()));
                assert_eq!(pipeline.next().await, Ok("processed_PROCESSED_4".into()));
            });

            let handle_2 = task::spawn_local(async {
                let slow_1 = SlowProcessor::new()
                    .with_process_delay(Duration::from_millis(25))
                    .with_next_delay(Duration::from_millis(15));
                let uppercase = UppercaseProcessor::default();
                let slow_2 = SlowProcessor::new().with_next_delay(Duration::from_millis(10));

                let pipeline = PipelineBuilder::new()
                    .layer(slow_1)
                    .layer(uppercase)
                    .layer(slow_2)
                    .build();

                pipeline.process(1).await.unwrap();
                assert_eq!(pipeline.next().await, Ok("processed_PROCESSED_1".into()));
                pipeline.process(2).await.unwrap();
                pipeline.process(3).await.unwrap();
                assert_eq!(pipeline.next().await, Ok("processed_PROCESSED_2".into()));
                assert_eq!(pipeline.next().await, Ok("processed_PROCESSED_3".into()));
            });

            let (result_1, result_2) = futures_util::future::join(handle_1, handle_2).await;
            assert!(result_1.is_ok());
            assert!(result_2.is_ok());
        })
        .await;
}

#[tokio::test]
async fn error_handling() {
    let local = task::LocalSet::new();

    local
        .run_until(async move {
            let slow = SlowProcessor::new().with_error_mode();
            assert!(slow.process(1).await.is_err());
            assert!(slow.next().await.is_err());
        })
        .await;
}

#[tokio::test]
async fn buffered_processor() {
    let local = task::LocalSet::new();

    local
        .run_until(async move {
            let uppercase = UppercaseProcessor::default();
            let (_buffered, tx, rx) = Buffer::new(uppercase);

            tx.send("i scream".to_string()).unwrap();
            tx.send("you scream".to_string()).unwrap();
            tx.send("we all scream".to_string()).unwrap();
            tx.send("for icecream".to_string()).unwrap();

            let rx = UnboundedReceiverStream::new(rx);

            let result = rx
                .take(4) // Processor does not terminate by itself
                .filter_map(|item| async {
                    match item {
                        Ok(item) => Some(item),
                        Err(err) => panic!("{}", err),
                    }
                })
                .collect::<Vec<String>>()
                .await;

            assert_eq!(
                result,
                vec![
                    "I SCREAM".to_string(),
                    "YOU SCREAM".to_string(),
                    "WE ALL SCREAM".to_string(),
                    "FOR ICECREAM".to_string(),
                ]
            );
        })
        .await;
}

#[tokio::test]
async fn into_stream() {
    let local = task::LocalSet::new();

    local
        .run_until(async move {
            let slow = SlowProcessor::new()
                .with_process_delay(Duration::from_millis(25))
                .with_next_delay(Duration::from_millis(15));
            let uppercase = UppercaseProcessor::default();
            let counter = CounterProcessor::new();

            let pipeline = stream::iter([62, 23, 11, 74])
                .layer(counter)
                .filter_map(|item| async { item.ok() })
                .layer(slow)
                .filter_map(|item| async { item.ok() })
                .layer(uppercase)
                .filter_map(|item| async { item.ok() });

            assert_eq!(
                pipeline.take(4).collect::<Vec<String>>().await,
                vec![
                    "PROCESSED_62_0".to_string(),
                    "PROCESSED_23_1".to_string(),
                    "PROCESSED_11_2".to_string(),
                    "PROCESSED_74_3".to_string(),
                ],
            );
        })
        .await;
}

#[tokio::test]
async fn processor_stream_polling() {
    let local = task::LocalSet::new();

    local
        .run_until(async move {
            // Input stream and processor output stream are properly polled independently, so new
            // input doesn't get blocked when processor is still working.

            let input_stream = stream::iter(vec![
                "hey".to_string(),
                "ho".to_string(),
                "lets go".to_string(),
            ]);

            // Create a processor with delay on processing (_not_ on next).
            let slow_processor = SlowProcessor::new().with_process_delay(Duration::from_millis(50));
            let stream = slow_processor.into_stream(input_stream);

            // Collect all results - this should work without getting stuck even though the
            // processor has delays.
            let results: Vec<_> = stream
                .take(3)
                .filter_map(|item| async { item.ok() })
                .collect()
                .await;

            assert_eq!(results.len(), 3);
            assert!(results.iter().all(|s| s.starts_with("processed_")));
        })
        .await;
}