1use std::future::Future;
16
17use futures::{Stream, StreamExt};
18
19pub(crate) struct BatchScanner {
21 batch_size: usize,
22 max_in_flight: usize,
23}
24
25impl BatchScanner {
26 pub(crate) const METADATA: Self = Self {
28 batch_size: 128,
29 max_in_flight: 8,
30 };
31
32 pub(crate) fn scan<T, U, E, F, Fut>(
34 &self,
35 input: impl Stream<Item = Result<T, E>>,
36 mut load: F,
37 ) -> impl Stream<Item = Result<U, E>>
38 where
39 F: FnMut(Vec<T>) -> Fut,
40 Fut: Future<Output = Result<U, E>>,
41 {
42 input
43 .ready_chunks(self.batch_size)
44 .map(move |items| {
45 let batch = items
46 .into_iter()
47 .collect::<Result<Vec<_>, _>>()
48 .map(&mut load);
49 async move { batch?.await }
50 })
51 .buffered(self.max_in_flight)
52 }
53}
54
55#[cfg(test)]
56mod tests {
57 use std::collections::VecDeque;
58
59 use futures::channel::oneshot;
60 use futures::{StreamExt, TryStreamExt, future, stream};
61
62 use super::*;
63
64 #[tokio::test]
65 async fn test_in_flight_limit_order_and_cancellation() {
66 let scanner = BatchScanner {
67 batch_size: 1,
68 max_in_flight: 2,
69 };
70 let (mut sends, mut replies): (VecDeque<_>, VecDeque<_>) =
71 (0..4).map(|_| oneshot::channel::<()>()).unzip();
72 let started = std::cell::Cell::new(0);
73 let input = stream::iter((0..4).map(Ok::<_, ()>));
74 let mut output = Box::pin(scanner.scan(input, |batch| {
75 started.set(started.get() + 1);
76 let reply = replies.pop_front().unwrap();
77 async move {
78 reply.await.unwrap();
79 Ok(batch)
80 }
81 }));
82 assert!(futures::poll!(output.next()).is_pending());
83 assert_eq!(started.get(), 2);
84 sends.remove(1).unwrap().send(()).unwrap();
85 assert!(futures::poll!(output.next()).is_pending());
86 sends.pop_front().unwrap().send(()).unwrap();
87 assert_eq!(output.try_next().await.unwrap(), Some(vec![0]));
88 assert_eq!(output.try_next().await.unwrap(), Some(vec![1]));
89 drop(output);
90 assert!(sends.pop_front().unwrap().send(()).is_err());
91 assert_eq!(started.get(), 3);
92 }
93
94 #[tokio::test]
95 async fn test_partial_batch_does_not_wait_for_full_input() {
96 let input = stream::iter([Ok::<_, ()>(1)]).chain(stream::pending());
97 let mut output =
98 Box::pin(BatchScanner::METADATA.scan(input, |batch| future::ready(Ok(batch))));
99 assert_eq!(output.try_next().await.unwrap(), Some(vec![1]));
100 }
101}