Skip to main content

catalog/
batch_scan.rs

1// Copyright 2023 Greptime Team
2//
3// Licensed under the Apache License, Version 2.0 (the "License");
4// you may not use this file except in compliance with the License.
5// You may obtain a copy of the License at
6//
7//     http://www.apache.org/licenses/LICENSE-2.0
8//
9// Unless required by applicable law or agreed to in writing, software
10// distributed under the License is distributed on an "AS IS" BASIS,
11// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12// See the License for the specific language governing permissions and
13// limitations under the License.
14
15use std::future::Future;
16
17use futures::{Stream, StreamExt};
18
19/// Bounds both the number of keys per metadata read and concurrent reads per scan.
20pub(crate) struct BatchScanner {
21    batch_size: usize,
22    max_in_flight: usize,
23}
24
25impl BatchScanner {
26    /// At most 128 ready keys per batch and eight concurrent loads per scan.
27    pub(crate) const METADATA: Self = Self {
28        batch_size: 128,
29        max_in_flight: 8,
30    };
31
32    /// Emits loaded batches in input order. A partial batch can start as soon as input is pending.
33    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}