Skip to main content

saluki_common/sync/
work_queue.rs

1//! A self-balancing work queue.
2//!
3//! A work queue distributes items from one or more producers across a fixed set of workers. Each worker has its own
4//! bounded queue, so workers never contend with each other on a shared receiver.
5//!
6//! Items keep going to the same worker until it has a backlog of a few queued items. A moderately loaded queue therefore
7//! keeps as few workers busy as it can, which avoids waking up idle workers for every item. Once that worker falls
8//! behind, items go to whichever worker has the fewest queued items, so no worker sits idle while another has a backlog.
9//!
10//! Each sender balances independently, based on how many items are currently queued for each worker. Items already
11//! queued for a worker stay with that worker, so a worker that stops making progress holds on to its backlog. Workers
12//! that have stopped, by dropping their receiver, are skipped, and items queued for them are dropped.
13
14use std::{
15    fmt,
16    future::{poll_fn, Future as _},
17    num::NonZeroUsize,
18    sync::Arc,
19    task::Poll,
20};
21
22use tokio::sync::mpsc;
23
24/// Number of queued items at which a sender moves on from its current worker.
25const BACKLOG_THRESHOLD: usize = 4;
26
27/// Creates a bounded work queue with `workers` workers.
28///
29/// Returns a sender, which can be cloned to create additional producers, along with one receiver per worker.
30/// `capacity` is the total number of items that can be queued, and is split evenly across the workers, with each worker
31/// able to queue at least one item.
32pub fn bounded<T>(workers: NonZeroUsize, capacity: usize) -> (WorkQueueSender<T>, Vec<WorkQueueReceiver<T>>) {
33    let per_worker_capacity = (capacity / workers.get()).max(1);
34    let (senders, receivers): (Vec<_>, Vec<_>) = (0..workers.get())
35        .map(|_| {
36            let (tx, rx) = mpsc::channel(per_worker_capacity);
37            (tx, WorkQueueReceiver { inner: rx })
38        })
39        .unzip();
40
41    let sender = WorkQueueSender {
42        senders: senders.into(),
43        current: 0,
44    };
45    (sender, receivers)
46}
47
48/// The sending side of a work queue.
49///
50/// Cloning a sender creates another producer for the same work queue. Each clone balances independently.
51pub struct WorkQueueSender<T> {
52    senders: Arc<[mpsc::Sender<T>]>,
53    current: usize,
54}
55
56impl<T> WorkQueueSender<T> {
57    /// Sends an item to one of the workers.
58    ///
59    /// Workers that have stopped are skipped. If every running worker's queue is full, waits until any running worker
60    /// has room.
61    ///
62    /// # Errors
63    ///
64    /// If every worker has stopped, an error is returned with the item.
65    pub async fn send(&mut self, mut item: T) -> Result<(), SendError<T>> {
66        if self.is_stopped(self.current) || self.queued(self.current) >= BACKLOG_THRESHOLD {
67            self.current = self.least_loaded();
68        }
69
70        let workers = self.senders.len();
71        for offset in 0..workers {
72            let index = (self.current + offset) % workers;
73            match self.senders[index].try_send(item) {
74                Ok(()) => return Ok(()),
75                Err(mpsc::error::TrySendError::Full(returned) | mpsc::error::TrySendError::Closed(returned)) => {
76                    item = returned
77                }
78            }
79        }
80
81        // Every running worker's queue is full, so wait for room in whichever worker frees up first. Waiting on a single
82        // worker could leave this send blocked behind a slow worker while another worker sits idle.
83        let senders = Arc::clone(&self.senders);
84        let mut reservations: Vec<_> = (0..workers)
85            .map(|offset| (self.current + offset) % workers)
86            .map(|index| (index, Box::pin(senders[index].reserve())))
87            .collect();
88        let reserved = poll_fn(|cx| {
89            let mut i = 0;
90            while i < reservations.len() {
91                match reservations[i].1.as_mut().poll(cx) {
92                    Poll::Ready(Ok(permit)) => return Poll::Ready(Some((reservations[i].0, permit))),
93                    // The worker stopped while waiting, so stop waiting on it.
94                    Poll::Ready(Err(_)) => {
95                        drop(reservations.remove(i));
96                    }
97                    Poll::Pending => i += 1,
98                }
99            }
100
101            if reservations.is_empty() {
102                Poll::Ready(None)
103            } else {
104                Poll::Pending
105            }
106        })
107        .await;
108
109        match reserved {
110            Some((index, permit)) => {
111                permit.send(item);
112                self.current = index;
113                Ok(())
114            }
115            None => Err(SendError(item)),
116        }
117    }
118
119    /// Returns `true` if the given worker has stopped.
120    fn is_stopped(&self, index: usize) -> bool {
121        self.senders[index].is_closed()
122    }
123
124    /// Returns the number of items queued for the given worker.
125    fn queued(&self, index: usize) -> usize {
126        let sender = &self.senders[index];
127        sender.max_capacity() - sender.capacity()
128    }
129
130    /// Returns the running worker with the fewest queued items, preferring the workers after the current one on ties.
131    ///
132    /// If every worker has stopped, returns the current worker.
133    fn least_loaded(&self) -> usize {
134        let workers = self.senders.len();
135        (1..=workers)
136            .map(|offset| (self.current + offset) % workers)
137            .filter(|&index| !self.is_stopped(index))
138            .min_by_key(|&index| self.queued(index))
139            .unwrap_or(self.current)
140    }
141}
142
143impl<T> Clone for WorkQueueSender<T> {
144    fn clone(&self) -> Self {
145        Self {
146            senders: Arc::clone(&self.senders),
147            current: self.current,
148        }
149    }
150}
151
152impl<T> fmt::Debug for WorkQueueSender<T> {
153    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
154        f.debug_struct("WorkQueueSender")
155            .field("workers", &self.senders.len())
156            .field("current", &self.current)
157            .finish()
158    }
159}
160
161/// The receiving side of a work queue, for a single worker.
162#[derive(Debug)]
163pub struct WorkQueueReceiver<T> {
164    inner: mpsc::Receiver<T>,
165}
166
167impl<T> WorkQueueReceiver<T> {
168    /// Receives the next item queued for this worker.
169    ///
170    /// Returns `None` once every sender has been dropped and no items remain queued for this worker.
171    ///
172    /// This method is cancel safe: if it's used in `select!` and another branch completes first, no item is lost.
173    pub async fn recv(&mut self) -> Option<T> {
174        self.inner.recv().await
175    }
176
177    /// Receives the next item queued for this worker, if one is available, without waiting.
178    pub fn try_recv(&mut self) -> Option<T> {
179        self.inner.try_recv().ok()
180    }
181
182    /// Returns the number of items queued for this worker.
183    pub fn len(&self) -> usize {
184        self.inner.len()
185    }
186
187    /// Returns `true` if no items are queued for this worker.
188    pub fn is_empty(&self) -> bool {
189        self.inner.is_empty()
190    }
191}
192
193/// An error returned when sending to a work queue whose workers have all stopped.
194///
195/// The item that couldn't be sent is returned in the error.
196pub struct SendError<T>(pub T);
197
198impl<T> fmt::Debug for SendError<T> {
199    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
200        f.write_str("SendError(..)")
201    }
202}
203
204impl<T> fmt::Display for SendError<T> {
205    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
206        f.write_str("all workers in the work queue have stopped")
207    }
208}
209
210impl<T> std::error::Error for SendError<T> {}
211
212#[cfg(test)]
213mod tests {
214    use std::time::Duration;
215
216    use tokio::time::timeout;
217
218    use super::*;
219
220    fn workers(n: usize) -> NonZeroUsize {
221        NonZeroUsize::new(n).unwrap()
222    }
223
224    fn drain<T>(receiver: &mut WorkQueueReceiver<T>) -> Vec<T> {
225        std::iter::from_fn(|| receiver.try_recv()).collect()
226    }
227
228    #[tokio::test]
229    async fn stays_on_a_worker_that_keeps_up() {
230        let (mut sender, mut receivers) = bounded(workers(2), 4);
231
232        // The worker drains each item before the next arrives, so every item goes to the same worker.
233        for item in 0..3 {
234            sender.send(item).await.unwrap();
235            assert_eq!(receivers[0].recv().await, Some(item));
236        }
237        assert!(receivers[1].try_recv().is_none());
238    }
239
240    #[tokio::test]
241    async fn spreads_items_across_workers_that_fall_behind() {
242        let worker_count = 3;
243        let (mut sender, mut receivers) = bounded(workers(worker_count), 64);
244
245        // Nothing is draining, so each worker takes items until it has a backlog, and then the next one does.
246        for item in 0..worker_count * BACKLOG_THRESHOLD {
247            sender.send(item).await.unwrap();
248        }
249        assert!(receivers.iter().all(|receiver| receiver.len() == BACKLOG_THRESHOLD));
250        for (worker, receiver) in receivers.iter_mut().enumerate() {
251            let start = worker * BACKLOG_THRESHOLD;
252            assert_eq!(drain(receiver), (start..start + BACKLOG_THRESHOLD).collect::<Vec<_>>());
253        }
254    }
255
256    #[tokio::test]
257    async fn moves_to_the_least_loaded_worker() {
258        let (mut sender, mut receivers) = bounded(workers(3), 64);
259
260        // Give every worker a backlog, which leaves the sender on the third worker.
261        for item in 0..BACKLOG_THRESHOLD * 3 {
262            sender.send(item).await.unwrap();
263        }
264
265        // Partly drain the first worker and fully drain the second, so the second is the least loaded even though the
266        // first comes next in order.
267        for _ in 0..BACKLOG_THRESHOLD / 2 {
268            receivers[0].recv().await.unwrap();
269        }
270        drain(&mut receivers[1]);
271
272        sender.send(100).await.unwrap();
273        assert_eq!(drain(&mut receivers[1]), vec![100]);
274    }
275
276    #[tokio::test]
277    async fn skips_full_worker_queues() {
278        let (mut sender, mut receivers) = bounded(workers(2), 2);
279
280        // Fill the first worker's queue. The next item has to go to the second worker.
281        sender.send(1).await.unwrap();
282        timeout(Duration::from_secs(1), sender.send(2))
283            .await
284            .expect("send should not wait while another worker has room")
285            .unwrap();
286        assert_eq!(receivers[0].recv().await, Some(1));
287        assert_eq!(receivers[1].recv().await, Some(2));
288    }
289
290    #[tokio::test]
291    async fn waits_for_room_when_every_queue_is_full() {
292        let (mut sender, mut receivers) = bounded(workers(2), 2);
293        sender.send(1).await.unwrap();
294        sender.send(2).await.unwrap();
295
296        let blocked = tokio::spawn(async move { sender.send(3).await });
297        tokio::task::yield_now().await;
298        assert!(!blocked.is_finished(), "send should wait while every queue is full");
299
300        // Freeing room in either queue lets the send complete.
301        let first = receivers[0].recv().await;
302        let second = receivers[1].recv().await;
303        blocked.await.unwrap().unwrap();
304        assert_eq!((first, second), (Some(1), Some(2)));
305        let rest: Vec<_> = receivers.iter_mut().flat_map(drain).collect();
306        assert_eq!(rest, vec![3]);
307    }
308
309    #[tokio::test]
310    async fn waits_for_a_running_worker_when_the_current_worker_has_stopped() {
311        let (mut sender, mut receivers) = bounded(workers(2), 2);
312
313        // Stop the first worker, which is the sender's current worker, and fill the second worker's queue.
314        drop(receivers.remove(0));
315        sender.send(1).await.unwrap();
316
317        // Every running worker's queue is full, so the send waits rather than failing on the stopped worker.
318        let blocked = tokio::spawn(async move { sender.send(2).await });
319        tokio::task::yield_now().await;
320        assert!(!blocked.is_finished(), "send should wait for the running worker");
321
322        assert_eq!(receivers[0].recv().await, Some(1));
323        blocked.await.unwrap().unwrap();
324        assert_eq!(receivers[0].recv().await, Some(2));
325    }
326
327    #[tokio::test]
328    async fn sends_to_whichever_worker_frees_up_first() {
329        let (mut sender, mut receivers) = bounded(workers(2), 2);
330        sender.send(1).await.unwrap();
331        sender.send(2).await.unwrap();
332
333        // Both queues are full, and the current worker is the first one.
334        let blocked = tokio::spawn(async move { sender.send(3).await });
335        tokio::task::yield_now().await;
336        assert!(!blocked.is_finished(), "send should wait while every queue is full");
337
338        // Only the second worker frees up, so the send goes there rather than waiting on the first worker.
339        assert_eq!(receivers[1].recv().await, Some(2));
340        blocked.await.unwrap().unwrap();
341        assert_eq!(receivers[1].recv().await, Some(3));
342        assert_eq!(receivers[0].recv().await, Some(1));
343        assert!(receivers[0].try_recv().is_none());
344    }
345
346    #[tokio::test]
347    async fn moves_on_when_a_worker_stops_while_waiting_for_it() {
348        let (mut sender, mut receivers) = bounded(workers(2), 2);
349        sender.send(1).await.unwrap();
350        sender.send(2).await.unwrap();
351
352        // Both queues are full, so the send waits on the current worker.
353        let blocked = tokio::spawn(async move { sender.send(3).await });
354        tokio::task::yield_now().await;
355        assert!(!blocked.is_finished(), "send should wait while every queue is full");
356
357        // Stopping that worker moves the send on to the other worker, which it waits on until there's room.
358        drop(receivers.remove(0));
359        tokio::task::yield_now().await;
360        assert!(!blocked.is_finished(), "send should wait for the remaining worker");
361
362        assert_eq!(receivers[0].recv().await, Some(2));
363        blocked.await.unwrap().unwrap();
364        assert_eq!(receivers[0].recv().await, Some(3));
365    }
366
367    #[tokio::test]
368    async fn errors_with_the_item_once_every_worker_stops() {
369        let (mut sender, receivers) = bounded::<u32>(workers(2), 2);
370        drop(receivers);
371
372        let SendError(item) = sender.send(7).await.unwrap_err();
373        assert_eq!(item, 7);
374    }
375
376    #[tokio::test]
377    async fn receivers_finish_once_every_sender_drops() {
378        let (mut sender, mut receivers) = bounded(workers(1), 4);
379        let mut clone = sender.clone();
380        sender.send(1).await.unwrap();
381        clone.send(2).await.unwrap();
382        drop(sender);
383        drop(clone);
384
385        assert_eq!(receivers[0].recv().await, Some(1));
386        assert_eq!(receivers[0].recv().await, Some(2));
387        assert_eq!(receivers[0].recv().await, None);
388    }
389}