rs2-stream 0.3.3

A high-performance, production-ready async streaming library for Rust.
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
use futures::StreamExt;
use rs2_stream::state::{CustomKeyExtractor, KeyExtractor, StateConfig, StatefulStreamExt};
use serde::{Deserialize, Serialize};
use std::time::Duration;
use tokio;
use tokio::sync::mpsc;
use tokio_stream::wrappers;

#[derive(Debug, Clone, Serialize, Deserialize)]
struct TestData {
    id: u32,
    value: String,
    count: u64,
    is_new_session: Option<bool>, // Optional to allow for events without session info
}

#[derive(Debug, Clone, Serialize, Deserialize, PartialEq)]
struct TestState {
    total_count: u64,
    last_value: String,
}

impl KeyExtractor<TestData> for fn(&TestData) -> String {
    fn extract_key(&self, item: &TestData) -> String {
        self(item)
    }
}

#[tokio::test]
async fn test_stateful_map_basic() {
    let config = StateConfig::new();
    let key_extractor: fn(&TestData) -> String = |data| data.id.to_string();
    let data = vec![
        TestData {
            id: 1,
            value: "hello".to_string(),
            count: 10,
            is_new_session: None,
        },
        TestData {
            id: 2,
            value: "world".to_string(),
            count: 20,
            is_new_session: None,
        },
    ];
    let stream = futures::stream::iter(data);
    let result_stream = stream.stateful_map_rs2(config, key_extractor, |item, state_access| {
        let fut = async move {
            let state_bytes = state_access.get().await.unwrap_or(Vec::new());
            let mut state: TestState = if state_bytes.is_empty() {
                TestState {
                    total_count: 0,
                    last_value: String::new(),
                }
            } else {
                serde_json::from_slice(&state_bytes).unwrap()
            };

            state.total_count += item.count;
            state.last_value = item.value.clone();

            let state_bytes = serde_json::to_vec(&state).unwrap();
            state_access.set(&state_bytes).await.unwrap();

            Ok(format!(
                "{}: count={}, total={}",
                item.value, item.count, state.total_count
            ))
        };
        Box::pin(fut)
    });

    let results: Vec<String> = result_stream
        .collect::<Vec<_>>()
        .await
        .into_iter()
        .map(|r| r.unwrap())
        .collect();

    assert_eq!(results.len(), 2);
    assert!(results
        .iter()
        .any(|r| r.contains("hello: count=10, total=10")));
    assert!(results
        .iter()
        .any(|r| r.contains("world: count=20, total=20")));
}

#[tokio::test]
async fn test_stateful_filter() {
    let config = StateConfig::new();
    let key_extractor: fn(&TestData) -> String = |data| data.id.to_string();
    let data = vec![
        TestData {
            id: 1,
            value: "small".to_string(),
            count: 5,
            is_new_session: None,
        },
        TestData {
            id: 2,
            value: "large".to_string(),
            count: 15,
            is_new_session: None,
        },
        TestData {
            id: 3,
            value: "medium".to_string(),
            count: 10,
            is_new_session: None,
        },
    ];
    let stream = futures::stream::iter(data);
    let result_stream = stream.stateful_filter_rs2(config, key_extractor, |item, state_access| {
        let item = item.clone();
        let state_access = state_access.clone();
        Box::pin(async move {
            let state_bytes = state_access.get().await.unwrap_or(Vec::new());
            let mut state: TestState = if state_bytes.is_empty() {
                TestState {
                    total_count: 0,
                    last_value: String::new(),
                }
            } else {
                serde_json::from_slice(&state_bytes).unwrap()
            };

            state.total_count += item.count;
            state.last_value = item.value.clone();

            let state_bytes = serde_json::to_vec(&state).unwrap();
            state_access.set(&state_bytes).await.unwrap();

            Ok(item.count >= 10)
        })
    });

    let results: Vec<TestData> = result_stream
        .collect::<Vec<_>>()
        .await
        .into_iter()
        .map(|r| r.unwrap())
        .collect();

    assert_eq!(results.len(), 2);
    assert_eq!(results[0].value, "large");
    assert_eq!(results[1].value, "medium");
}

#[tokio::test]
async fn test_stateful_fold() {
    let config = StateConfig::new();
    let key_extractor: fn(&TestData) -> String = |data| data.id.to_string();
    let data = vec![
        TestData {
            id: 1,
            value: "hello".to_string(),
            count: 10,
            is_new_session: None,
        },
        TestData {
            id: 1,
            value: "world".to_string(),
            count: 20,
            is_new_session: None,
        },
        TestData {
            id: 2,
            value: "test".to_string(),
            count: 30,
            is_new_session: None,
        },
    ];
    let stream = futures::stream::iter(data);
    let result_stream =
        stream.stateful_fold_rs2(config, key_extractor, 0u64, |acc, item, _state_access| {
            Box::pin(async move { Ok(acc + item.count as u64) })
        });
    let results: Vec<u64> = result_stream
        .collect::<Vec<_>>()
        .await
        .into_iter()
        .map(|r| r.unwrap())
        .collect();
    assert_eq!(results.len(), 3);
    assert_eq!(results[0], 10);
    assert_eq!(results[1], 30);
    assert_eq!(results[2], 30);
}

#[tokio::test]
async fn test_stateful_window() {
    let config = StateConfig::new();
    let key_extractor: fn(&TestData) -> String = |data| data.id.to_string();
    let data = vec![
        TestData {
            id: 1,
            value: "a".to_string(),
            count: 1,
            is_new_session: None,
        },
        TestData {
            id: 1,
            value: "b".to_string(),
            count: 2,
            is_new_session: None,
        },
        TestData {
            id: 1,
            value: "c".to_string(),
            count: 3,
            is_new_session: None,
        },
        TestData {
            id: 1,
            value: "d".to_string(),
            count: 4,
            is_new_session: None,
        },
    ];
    let stream = futures::stream::iter(data);
    let result_stream = stream.stateful_window_rs2(
        config,
        key_extractor,
        2, // window size
        |window, state_access| {
            let fut = async move {
                let state_bytes = state_access.get().await.unwrap_or(Vec::new());
                let mut state: TestState = if state_bytes.is_empty() {
                    TestState {
                        total_count: 0,
                        last_value: String::new(),
                    }
                } else {
                    serde_json::from_slice(&state_bytes).unwrap()
                };
                let window_sum: u64 = window.iter().map(|item| item.count).sum();
                state.total_count += window_sum;
                let state_bytes = serde_json::to_vec(&state).unwrap();
                state_access.set(&state_bytes).await.unwrap();
                Ok(format!(
                    "Window sum: {}, Total: {}",
                    window_sum, state.total_count
                ))
            };
            Box::pin(fut)
        },
    );
    let results: Vec<String> = result_stream
        .collect::<Vec<_>>()
        .await
        .into_iter()
        .map(|r| r.unwrap())
        .collect();
    assert_eq!(results.len(), 2); // Two complete windows of size 2
    assert!(results[0].contains("Window sum: 3")); // a+b
    assert!(results[1].contains("Window sum: 7")); // c+d
}

#[tokio::test]
async fn test_stateful_join() {
    let config = StateConfig::new();
    let key_extractor: fn(&TestData) -> String = |data| data.id.to_string();
    let other_key_extractor: fn(&TestData) -> String = |data| data.id.to_string();

    let left_data = vec![
        TestData {
            id: 1,
            value: "left1".to_string(),
            count: 10,
            is_new_session: None,
        },
        TestData {
            id: 2,
            value: "left2".to_string(),
            count: 20,
            is_new_session: None,
        },
    ];
    let right_data = vec![
        TestData {
            id: 1,
            value: "right1".to_string(),
            count: 30,
            is_new_session: None,
        },
        TestData {
            id: 2,
            value: "right2".to_string(),
            count: 40,
            is_new_session: None,
        },
    ];

    // Create interleaved streams to ensure deterministic behavior
    let (left_tx, left_rx) = mpsc::unbounded_channel();
    let (right_tx, right_rx) = mpsc::unbounded_channel();

    // Spawn a task to send items in an interleaved manner
    tokio::spawn(async move {
        let max_len = left_data.len().max(right_data.len());
        for i in 0..max_len {
            if i < left_data.len() {
                left_tx.send(left_data[i].clone()).unwrap();
            }
            if i < right_data.len() {
                right_tx.send(right_data[i].clone()).unwrap();
            }
            // Small yield to allow polling
            tokio::task::yield_now().await;
        }
    });

    let left_stream = wrappers::UnboundedReceiverStream::new(left_rx);
    let right_stream = wrappers::UnboundedReceiverStream::new(right_rx);

    let result_stream = left_stream.stateful_join_rs2(
        Box::pin(right_stream),
        config,
        key_extractor,
        other_key_extractor,
        Duration::from_secs(10), // Longer window for deterministic results
        |left, right, state_access| {
            let fut = async move {
                let state_bytes = state_access.get().await.unwrap_or(Vec::new());
                let mut state: TestState = if state_bytes.is_empty() {
                    TestState {
                        total_count: 0,
                        last_value: String::new(),
                    }
                } else {
                    serde_json::from_slice(&state_bytes).unwrap()
                };

                state.total_count += left.count + right.count;
                state.last_value = format!("{}+{}", left.value, right.value);

                let state_bytes = serde_json::to_vec(&state).unwrap();
                state_access.set(&state_bytes).await.unwrap();

                Ok(format!("{} + {}", left.value, right.value))
            };
            Box::pin(fut)
        },
    );

    let results: Vec<String> = result_stream
        .collect::<Vec<_>>()
        .await
        .into_iter()
        .map(|r| r.unwrap())
        .collect();

    println!("[JOIN_BASIC_DEBUG] Results: {:?}", results);

    // With interleaved streams, we should get consistent results
    assert!(!results.is_empty(), "Expected at least one join result");
    assert!(
        results.len() >= 2,
        "Expected at least 2 join results, got {}",
        results.len()
    );

    // Check that we get the expected join results
    let mut found_left1_right1 = false;
    let mut found_left2_right2 = false;

    for result in &results {
        if result.contains("left1 + right1") {
            found_left1_right1 = true;
        }
        if result.contains("left2 + right2") {
            found_left2_right2 = true;
        }
    }

    // We should have at least these specific joins
    assert!(found_left1_right1, "Expected 'left1 + right1' join result");
    assert!(found_left2_right2, "Expected 'left2 + right2' join result");

    // All results should contain both left and right items
    for result in &results {
        assert!(
            result.contains("left") && result.contains("right"),
            "All join results should contain both left and right items: {}",
            result
        );
    }
}

#[tokio::test]
async fn test_stateful_join_different_keys() {
    let config = StateConfig::new();
    let key_extractor: fn(&TestData) -> String = |data| data.id.to_string();
    let other_key_extractor: fn(&TestData) -> String = |data| (data.id + 1).to_string(); // Different key mapping

    let left_data = vec![TestData {
        id: 1,
        value: "left1".to_string(),
        count: 10,
        is_new_session: None,
    }];
    let right_data = vec![
        TestData {
            id: 0,
            value: "right0".to_string(),
            count: 30,
            is_new_session: None,
        }, // id=0 maps to key="1"
    ];

    // Create interleaved streams to ensure deterministic behavior
    let (left_tx, left_rx) = mpsc::unbounded_channel();
    let (right_tx, right_rx) = mpsc::unbounded_channel();

    // Spawn a task to send items in an interleaved manner
    tokio::spawn(async move {
        let max_len = left_data.len().max(right_data.len());
        for i in 0..max_len {
            if i < left_data.len() {
                left_tx.send(left_data[i].clone()).unwrap();
            }
            if i < right_data.len() {
                right_tx.send(right_data[i].clone()).unwrap();
            }
            // Small yield to allow polling
            tokio::task::yield_now().await;
        }
    });

    let left_stream = wrappers::UnboundedReceiverStream::new(left_rx);
    let right_stream = wrappers::UnboundedReceiverStream::new(right_rx);

    let result_stream = left_stream.stateful_join_rs2(
        Box::pin(right_stream),
        config,
        key_extractor,
        other_key_extractor,
        Duration::from_secs(10), // Longer window for deterministic results
        |left: TestData, right: TestData, _state_access| {
            let fut = async move { Ok(format!("{} + {}", left.value, right.value)) };
            Box::pin(fut)
        },
    );

    let results: Vec<String> = result_stream
        .collect::<Vec<_>>()
        .await
        .into_iter()
        .map(|r| r.unwrap())
        .collect();

    println!("[JOIN_DIFFERENT_KEYS_DEBUG] Results: {:?}", results);

    // With interleaved streams, we should get consistent results
    assert!(!results.is_empty(), "Expected at least one join result");
    assert_eq!(
        results.len(),
        1,
        "Expected exactly 1 join result, got {}",
        results.len()
    );
    assert!(
        results[0].contains("left1 + right0"),
        "Expected 'left1 + right0' join result, got: {}",
        results[0]
    );
}

#[tokio::test]
async fn test_stateful_operations_with_empty_stream() {
    let config = StateConfig::new();
    let key_extractor: fn(&TestData) -> String = |data| data.id.to_string();
    let empty_data: Vec<TestData> = vec![];

    let stream = futures::stream::iter(empty_data);
    let result_stream = stream.stateful_map_rs2(config, key_extractor, |item, state_access| {
        let fut = async move {
            let state_bytes = state_access.get().await.unwrap_or(Vec::new());
            let mut state: TestState = if state_bytes.is_empty() {
                TestState {
                    total_count: 0,
                    last_value: String::new(),
                }
            } else {
                serde_json::from_slice(&state_bytes).unwrap()
            };

            state.total_count += item.count;
            state.last_value = item.value.clone();

            let state_bytes = serde_json::to_vec(&state).unwrap();
            state_access.set(&state_bytes).await.unwrap();

            Ok(format!(
                "{}: count={}, total={}",
                item.value, item.count, state.total_count
            ))
        };
        Box::pin(fut)
    });

    let results: Vec<String> = result_stream
        .collect::<Vec<_>>()
        .await
        .into_iter()
        .map(|r| r.unwrap())
        .collect();
    assert_eq!(results.len(), 0);
}

#[tokio::test]
async fn test_stateful_operations_with_single_item() {
    let config = StateConfig::new();
    let key_extractor: fn(&TestData) -> String = |data| data.id.to_string();
    let data = vec![TestData {
        id: 1,
        value: "single".to_string(),
        count: 100,
        is_new_session: None,
    }];

    let stream = futures::stream::iter(data);
    let result_stream = stream.stateful_filter_rs2(config, key_extractor, |item, state_access| {
        let item = item.clone();
        let state_access = state_access.clone();
        Box::pin(async move {
            let state_bytes = state_access.get().await.unwrap_or(Vec::new());
            let mut state: TestState = if state_bytes.is_empty() {
                TestState {
                    total_count: 0,
                    last_value: String::new(),
                }
            } else {
                serde_json::from_slice(&state_bytes).unwrap()
            };

            state.total_count += item.count;
            state.last_value = item.value.clone();

            let state_bytes = serde_json::to_vec(&state).unwrap();
            state_access.set(&state_bytes).await.unwrap();

            Ok(item.count > 50) // Only pass items with count > 50
        })
    });

    let results: Vec<TestData> = result_stream
        .collect::<Vec<_>>()
        .await
        .into_iter()
        .map(|r| r.unwrap())
        .collect();
    assert_eq!(results.len(), 1);
    assert_eq!(results[0].value, "single");
}

#[tokio::test]
async fn test_stateful_operations_with_multiple_keys() {
    let config = StateConfig::new();
    let key_extractor: fn(&TestData) -> String = |data| data.id.to_string();
    let data = vec![
        TestData {
            id: 1,
            value: "key1_a".to_string(),
            count: 10,
            is_new_session: None,
        },
        TestData {
            id: 2,
            value: "key2_a".to_string(),
            count: 20,
            is_new_session: None,
        },
        TestData {
            id: 1,
            value: "key1_b".to_string(),
            count: 30,
            is_new_session: None,
        },
        TestData {
            id: 2,
            value: "key2_b".to_string(),
            count: 40,
            is_new_session: None,
        },
    ];

    let stream = futures::stream::iter(data);
    let result_stream =
        stream.stateful_fold_rs2(config, key_extractor, 0u64, |acc, item, _state_access| {
            Box::pin(async move { Ok(acc + item.count as u64) })
        });

    let results: Vec<u64> = result_stream
        .collect::<Vec<_>>()
        .await
        .into_iter()
        .map(|r| r.unwrap())
        .collect();
    assert_eq!(results.len(), 4);
    assert_eq!(results[0], 10); // key1: 10
    assert_eq!(results[1], 20); // key2: 20
    assert_eq!(results[2], 40); // key1: 10 + 30
    assert_eq!(results[3], 60); // key2: 20 + 40
}

#[tokio::test]
async fn test_stateful_operations_with_large_data() {
    let config = StateConfig::new();
    let key_extractor: fn(&TestData) -> String = |data| (data.id % 10).to_string(); // Group into 10 keys

    let mut data = Vec::new();
    for i in 0..100 {
        data.push(TestData {
            id: i,
            value: format!("item_{}", i),
            count: i as u64,
            is_new_session: None,
        });
    }

    let stream = futures::stream::iter(data);
    let result_stream = stream.stateful_window_rs2(
        config,
        key_extractor,
        5, // window size
        |window, state_access| {
            let fut = async move {
                let state_bytes = state_access.get().await.unwrap_or(Vec::new());
                let mut state: TestState = if state_bytes.is_empty() {
                    TestState {
                        total_count: 0,
                        last_value: String::new(),
                    }
                } else {
                    serde_json::from_slice(&state_bytes).unwrap()
                };

                let window_sum: u64 = window.iter().map(|item| item.count).sum();
                state.total_count += window_sum;

                let state_bytes = serde_json::to_vec(&state).unwrap();
                state_access.set(&state_bytes).await.unwrap();

                Ok(format!(
                    "Window: {} items, sum: {}, total: {}",
                    window.len(),
                    window_sum,
                    state.total_count
                ))
            };
            Box::pin(fut)
        },
    );

    let results: Vec<String> = result_stream
        .collect::<Vec<_>>()
        .await
        .into_iter()
        .map(|r| r.unwrap())
        .collect();
    assert_eq!(results.len(), 20); // 100 items / 5 items per window = 20 windows
}

#[tokio::test]
async fn test_stateful_operations_error_handling() {
    let config = StateConfig::new();
    let key_extractor: fn(&TestData) -> String = |data| data.id.to_string();
    let data = vec![TestData {
        id: 1,
        value: "test".to_string(),
        count: 10,
        is_new_session: None,
    }];

    let stream = futures::stream::iter(data);
    let result_stream = stream.stateful_map_rs2(config, key_extractor, |item, state_access| {
        let fut = async move {
            // Simulate state access error
            let _state_bytes = state_access.get().await;
            // Continue processing even if state access fails
            Ok(format!("{}: processed", item.value))
        };
        Box::pin(fut)
    });

    let results: Vec<String> = result_stream
        .collect::<Vec<_>>()
        .await
        .into_iter()
        .map(|r| r.unwrap())
        .collect();
    assert_eq!(results.len(), 1);
    assert!(results[0].contains("test: processed"));
}

#[tokio::test]
async fn test_stateful_operations_concurrent_access() {
    let config = StateConfig::new();
    let key_extractor: fn(&TestData) -> String = |data| data.id.to_string();
    let data = vec![
        TestData {
            id: 1,
            value: "concurrent1".to_string(),
            count: 10,
            is_new_session: None,
        },
        TestData {
            id: 1,
            value: "concurrent2".to_string(),
            count: 20,
            is_new_session: None,
        },
        TestData {
            id: 2,
            value: "concurrent3".to_string(),
            count: 30,
            is_new_session: None,
        },
    ];

    let stream = futures::stream::iter(data);
    let result_stream =
        stream.stateful_reduce_rs2(config, key_extractor, 0u64, |acc, item, _state_access| {
            Box::pin(async move { Ok(acc + item.count as u64) })
        });

    let results: Vec<u64> = result_stream
        .collect::<Vec<_>>()
        .await
        .into_iter()
        .map(|r| r.unwrap())
        .collect();
    assert_eq!(results.len(), 3);
    assert_eq!(results[0], 10); // key1: 10
    assert_eq!(results[1], 30); // key1: 10 + 20
    assert_eq!(results[2], 30); // key2: 30
}

#[tokio::test]
async fn test_stateful_operations_with_custom_key_extractor() {
    let config = StateConfig::new();
    let key_extractor =
        CustomKeyExtractor::new(|data: &TestData| format!("{}_{}", data.id, data.value.len()));

    let data = vec![
        TestData {
            id: 1,
            value: "short".to_string(),
            count: 10,
            is_new_session: None,
        },
        TestData {
            id: 1,
            value: "longer".to_string(),
            count: 20,
            is_new_session: None,
        },
        TestData {
            id: 2,
            value: "short".to_string(),
            count: 30,
            is_new_session: None,
        },
    ];

    let stream = futures::stream::iter(data);
    let result_stream = stream.stateful_map_rs2(config, key_extractor, |item, state_access| {
        let fut = async move {
            let state_bytes = state_access.get().await.unwrap_or(Vec::new());
            let mut state: TestState = if state_bytes.is_empty() {
                TestState {
                    total_count: 0,
                    last_value: String::new(),
                }
            } else {
                serde_json::from_slice(&state_bytes).unwrap()
            };

            state.total_count += item.count;
            state.last_value = item.value.clone();

            let state_bytes = serde_json::to_vec(&state).unwrap();
            state_access.set(&state_bytes).await.unwrap();

            Ok(format!("{} (total: {})", item.value, state.total_count))
        };
        Box::pin(fut)
    });

    let results: Vec<String> = result_stream
        .collect::<Vec<_>>()
        .await
        .into_iter()
        .map(|r| r.unwrap())
        .collect();

    assert_eq!(results.len(), 3);
    assert!(results[0].contains("short (total: 10)"));
    assert!(results[1].contains("longer (total: 20)")); // Different key due to different length
    assert!(results[2].contains("short (total: 30)")); // Different key due to different id
}