1use 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
25pub 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 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
49pub 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 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}