Skip to main content

common_cache/
batch.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
15//! Request-local batching of cache initializers.
16
17use std::future::Future;
18use std::pin::pin;
19use std::task::Poll;
20
21use futures::channel::{mpsc, oneshot};
22use futures::future::{self, Either};
23use futures::stream::{FuturesUnordered, StreamExt};
24
25/// Submits backend requests from the initializers elected by the cache.
26/// Only the active initializer calls [`Self::request`]. A waiter enqueues
27/// nothing until it takes over a cancelled initializer.
28pub struct BatchSender<K, V> {
29    requests: mpsc::UnboundedSender<(K, oneshot::Sender<V>)>,
30}
31
32impl<K, V> Clone for BatchSender<K, V> {
33    fn clone(&self) -> Self {
34        Self {
35            requests: self.requests.clone(),
36        }
37    }
38}
39
40impl<K, V> BatchSender<K, V> {
41    /// Enqueues one request and waits for its reply. Returns `None` if the batch closes.
42    pub async fn request(&self, key: K) -> Option<V> {
43        let (reply, receive) = oneshot::channel();
44        self.requests.unbounded_send((key, reply)).ok()?;
45        receive.await.ok()
46    }
47}
48
49/// Drives one caller's per-key loads and batches requests from their active initializers.
50/// Each dispatch receives ready keys and their corresponding reply senders in the same order.
51/// Completed loads are delivered to `on_loaded` in completion order. An error or cancellation
52/// drops the remaining loads and any in-progress dispatch.
53pub async fn load<K, V, T, E, I, D>(
54    make_loads: impl FnOnce(BatchSender<K, V>) -> I,
55    mut dispatch: impl FnMut(Vec<K>, Vec<oneshot::Sender<V>>) -> D,
56    mut on_loaded: impl FnMut(T),
57) -> Result<(), E>
58where
59    I: ExactSizeIterator,
60    I::Item: Future<Output = Result<T, E>>,
61    D: Future<Output = ()>,
62{
63    let (requests, receiver) = mpsc::unbounded();
64    let loads = make_loads(BatchSender { requests });
65    let batch_size = loads.len();
66    if batch_size == 0 {
67        return Ok(());
68    }
69
70    let reads = async move {
71        let mut pending = FuturesUnordered::new();
72        // Poll every key before dispatch so stream fairness does not split ready misses.
73        for load in loads {
74            let mut load = Box::pin(load);
75            match futures::poll!(&mut load) {
76                Poll::Ready(value) => on_loaded(value?),
77                Poll::Pending => pending.push(load),
78            }
79        }
80        while let Some(value) = pending.next().await {
81            on_loaded(value?);
82        }
83        Ok(())
84    };
85    let batches = async move {
86        let mut batches = receiver.ready_chunks(batch_size);
87        while let Some(batch) = batches.next().await {
88            let (keys, replies) = batch.into_iter().unzip();
89            dispatch(keys, replies).await;
90        }
91    };
92    match future::select(pin!(reads), pin!(batches)).await {
93        Either::Left((result, _)) => result,
94        Either::Right(((), reads)) => reads.await,
95    }
96}
97
98#[cfg(test)]
99mod tests {
100    use futures::future;
101
102    use super::*;
103
104    #[tokio::test]
105    async fn test_empty_loads_skip_dispatch() {
106        let result = load(
107            |_: BatchSender<(), ()>| std::iter::empty::<future::Ready<Result<(), ()>>>(),
108            |_, _| async { panic!("unexpected dispatch") },
109            |_| panic!("unexpected load"),
110        )
111        .await;
112        assert_eq!(result, Ok(()));
113    }
114
115    #[tokio::test]
116    async fn test_delivers_replies_in_completion_order() {
117        let (send_batch, mut batches) = mpsc::unbounded();
118        let (send_value, mut values) = mpsc::unbounded();
119        let mut read = Box::pin(load(
120            |requests: BatchSender<u32, u32>| {
121                [1, 2].into_iter().map(move |key| {
122                    let requests = requests.clone();
123                    async move {
124                        requests
125                            .request(key)
126                            .await
127                            .map(|value| (key, value))
128                            .ok_or(())
129                    }
130                })
131            },
132            move |keys, replies| {
133                send_batch.unbounded_send((keys, replies)).unwrap();
134                future::ready(())
135            },
136            move |value| send_value.unbounded_send(value).unwrap(),
137        ));
138        assert!(futures::poll!(&mut read).is_pending());
139        let (keys, replies) = batches.try_recv().unwrap();
140        assert_eq!(keys, [1, 2]);
141        let [first, second]: [_; 2] = replies.try_into().unwrap();
142        second.send(20).unwrap();
143        assert!(futures::poll!(&mut read).is_pending());
144        assert_eq!(values.try_recv().unwrap(), (2, 20));
145        first.send(10).unwrap();
146        read.await.unwrap();
147        assert_eq!(values.try_recv().unwrap(), (1, 10));
148    }
149
150    #[tokio::test]
151    async fn test_dropped_reply_cancels_pending_dispatch() {
152        let (release, gate) = oneshot::channel();
153        let mut gate = Some(gate);
154        let read = load(
155            |requests: BatchSender<(), ()>| {
156                std::iter::once(async move { requests.request(()).await.ok_or("reply dropped") })
157            },
158            |_, replies| {
159                let gate = gate.take().unwrap();
160                async move {
161                    drop(replies);
162                    gate.await.unwrap();
163                }
164            },
165            |_| panic!("unexpected successful load"),
166        );
167        let result = tokio::time::timeout(std::time::Duration::from_secs(5), read)
168            .await
169            .unwrap();
170        assert_eq!(result, Err("reply dropped"));
171        assert!(release.send(()).is_err());
172    }
173
174    #[tokio::test]
175    async fn test_waits_for_load_after_queue_closes() {
176        let (release, gate) = oneshot::channel();
177        let mut value = None;
178        let mut read = Box::pin(load(
179            |_: BatchSender<(), ()>| std::iter::once(gate),
180            |_, _| async { panic!("unexpected dispatch") },
181            |v| value = Some(v),
182        ));
183        assert!(futures::poll!(&mut read).is_pending());
184        release.send(42).unwrap();
185        read.await.unwrap();
186        assert_eq!(value, Some(42));
187    }
188}