Skip to main content

ostrya_fetch/
gate.rs

1//! A priority admission gate that bounds concurrent work.
2//!
3//! A [`Gate`] holds a fixed number of permits. [`Gate::acquire`] returns an
4//! [`Acquire`] future, which resolves to a [`Permit`].
5//! [`Fetcher`](crate::Fetcher) uses a gate to bound the requests in flight.
6//! Other code can use a gate to bound other work, for example the content
7//! writes that run at once.
8//!
9//! If no permit is free, the waiter joins a queue. The queue serves the highest
10//! [`Priority`] first, and the waiters of one priority in arrival order. A
11//! released permit goes directly to the first waiter and does not raise the
12//! free count, so a new waiter cannot take it.
13//!
14//! The order across priorities is strict. If higher-priority waiters arrive
15//! without a pause, a lower-priority waiter stays in the queue. The mix of
16//! priorities that the callers use sets the limit of that wait.
17
18use std::cmp::Reverse;
19use std::collections::{BTreeMap, BTreeSet};
20use std::future::Future;
21use std::pin::Pin;
22use std::sync::{Arc, Mutex};
23use std::task::{Context, Poll, Waker};
24
25use super::Priority;
26
27/// The place of a waiter in the queue: highest priority first, then arrival.
28#[derive(Clone, Copy, Debug, Eq, Ord, PartialEq, PartialOrd)]
29struct WaitKey {
30    rank: Reverse<Priority>,
31    seq: u64,
32}
33
34/// The queue and the count of free permits.
35struct State {
36    free: usize,
37    next_seq: u64,
38    /// The waiters that have no permit, each with the waker to wake.
39    waiting: BTreeMap<WaitKey, Option<Waker>>,
40    /// The waiters that got a permit, which the next poll of each takes.
41    granted: BTreeSet<WaitKey>,
42}
43
44impl State {
45    /// Releases one permit. If a waiter is in the queue, the first waiter gets
46    /// the permit. If not, the free count increases. Returns the waker that the
47    /// caller must wake after it releases the lock.
48    fn hand_off(&mut self) -> Option<Waker> {
49        match self.waiting.keys().next().copied() {
50            Some(key) => {
51                let waker = self.waiting.remove(&key).flatten();
52                self.granted.insert(key);
53                waker
54            }
55            None => {
56                self.free += 1;
57                None
58            }
59        }
60    }
61}
62
63/// A priority admission gate with a fixed number of permits.
64pub struct Gate {
65    state: Mutex<State>,
66}
67
68impl Gate {
69    /// Creates a gate with `limit` permits.
70    ///
71    /// If `limit` is 0, no [`Acquire`] future resolves.
72    pub fn new(limit: usize) -> Gate {
73        Gate {
74            state: Mutex::new(State {
75                free: limit,
76                next_seq: 0,
77                waiting: BTreeMap::new(),
78                granted: BTreeSet::new(),
79            }),
80        }
81    }
82
83    /// Returns a future that waits for a permit at `priority`.
84    ///
85    /// The future resolves to a [`Permit`]. The [`gate`](crate::gate) module
86    /// states the queue order.
87    pub fn acquire(self: &Arc<Gate>, priority: Priority) -> Acquire {
88        Acquire {
89            gate: self.clone(),
90            priority,
91            key: None,
92        }
93    }
94
95    /// Releases one permit and wakes the waiter that gets it.
96    fn release(&self) {
97        let waker = self.state.lock().expect("fetch gate mutex").hand_off();
98        // The wake runs outside the lock, so an executor that polls the woken
99        // future inline does not lock the mutex a second time.
100        if let Some(waker) = waker {
101            waker.wake();
102        }
103    }
104}
105
106/// The future that [`Gate::acquire`] returns.
107///
108/// If a caller drops the future before it resolves, the future leaves the
109/// queue. If the gate gave it a permit already, the permit goes to the next
110/// waiter.
111pub struct Acquire {
112    gate: Arc<Gate>,
113    priority: Priority,
114    /// The place of this waiter in the queue, after it joins the queue.
115    key: Option<WaitKey>,
116}
117
118impl Future for Acquire {
119    type Output = Permit;
120
121    fn poll(self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<Permit> {
122        let me = self.get_mut();
123        // The mutex is poisoned only if a holder panics under the lock. No
124        // caller input can cause that.
125        let mut state = me.gate.state.lock().expect("fetch gate mutex");
126        match me.key {
127            None => {
128                if state.free > 0 {
129                    state.free -= 1;
130                    drop(state);
131                    return Poll::Ready(Permit {
132                        gate: me.gate.clone(),
133                    });
134                }
135                let seq = state.next_seq;
136                state.next_seq += 1;
137                let key = WaitKey {
138                    rank: Reverse(me.priority),
139                    seq,
140                };
141                state.waiting.insert(key, Some(cx.waker().clone()));
142                me.key = Some(key);
143                Poll::Pending
144            }
145            Some(key) => {
146                if state.granted.remove(&key) {
147                    me.key = None;
148                    drop(state);
149                    return Poll::Ready(Permit {
150                        gate: me.gate.clone(),
151                    });
152                }
153                if let Some(slot) = state.waiting.get_mut(&key) {
154                    *slot = Some(cx.waker().clone());
155                }
156                Poll::Pending
157            }
158        }
159    }
160}
161
162impl Drop for Acquire {
163    fn drop(&mut self) {
164        let Some(key) = self.key else { return };
165        let waker = {
166            let mut state = self.gate.state.lock().expect("fetch gate mutex");
167            state.waiting.remove(&key);
168            // If the gate gave this waiter a permit, the permit goes to
169            // the next waiter.
170            if state.granted.remove(&key) {
171                state.hand_off()
172            } else {
173                None
174            }
175        };
176        if let Some(waker) = waker {
177            waker.wake();
178        }
179    }
180}
181
182/// A permit of a [`Gate`], which returns to the gate on drop.
183pub struct Permit {
184    gate: Arc<Gate>,
185}
186
187impl Drop for Permit {
188    fn drop(&mut self) {
189        self.gate.release();
190    }
191}
192
193#[cfg(test)]
194mod tests {
195    use super::*;
196    use futures_lite::future::poll_once;
197    use ostrya_rt::block_on;
198
199    #[test]
200    fn permits_up_to_the_limit_are_granted_at_once() {
201        block_on(async {
202            let gate = Arc::new(Gate::new(2));
203            let first = gate.acquire(Priority::Normal).await;
204            let second = gate.acquire(Priority::Normal).await;
205            // The third waits until one is released.
206            let mut third = Box::pin(gate.acquire(Priority::Normal));
207            assert!(poll_once(&mut third).await.is_none());
208            drop(first);
209            assert!(poll_once(&mut third).await.is_some());
210            drop(second);
211        });
212    }
213
214    #[test]
215    fn a_released_permit_goes_to_the_highest_priority_waiter() {
216        block_on(async {
217            let gate = Arc::new(Gate::new(1));
218            let held = gate.acquire(Priority::Normal).await;
219            let mut low = Box::pin(gate.acquire(Priority::Low));
220            let mut high = Box::pin(gate.acquire(Priority::High));
221            // Queue low first, then high. The later arrival gets the permit,
222            // because priority comes first.
223            assert!(poll_once(&mut low).await.is_none());
224            assert!(poll_once(&mut high).await.is_none());
225            drop(held);
226            assert!(poll_once(&mut low).await.is_none());
227            let permit = poll_once(&mut high).await;
228            assert!(permit.is_some());
229            // After the high-priority holder releases its permit, the low
230            // waiter gets it.
231            drop(permit);
232            assert!(poll_once(&mut low).await.is_some());
233        });
234    }
235
236    #[test]
237    fn equal_priority_waiters_are_served_in_arrival_order() {
238        block_on(async {
239            let gate = Arc::new(Gate::new(1));
240            let held = gate.acquire(Priority::Normal).await;
241            let mut first = Box::pin(gate.acquire(Priority::Normal));
242            let mut second = Box::pin(gate.acquire(Priority::Normal));
243            assert!(poll_once(&mut first).await.is_none());
244            assert!(poll_once(&mut second).await.is_none());
245            drop(held);
246            assert!(poll_once(&mut second).await.is_none());
247            assert!(poll_once(&mut first).await.is_some());
248        });
249    }
250
251    #[test]
252    fn abandoning_a_granted_waiter_passes_the_permit_on() {
253        block_on(async {
254            let gate = Arc::new(Gate::new(1));
255            let held = gate.acquire(Priority::Normal).await;
256            let mut leaving = Box::pin(gate.acquire(Priority::High));
257            let mut staying = Box::pin(gate.acquire(Priority::Normal));
258            assert!(poll_once(&mut leaving).await.is_none());
259            assert!(poll_once(&mut staying).await.is_none());
260            // The gate gives the permit to the high-priority waiter. The test
261            // then drops that waiter before it polls again.
262            drop(held);
263            drop(leaving);
264            assert!(poll_once(&mut staying).await.is_some());
265        });
266    }
267
268    #[test]
269    fn a_dropped_queued_waiter_leaves_no_trace() {
270        block_on(async {
271            let gate = Arc::new(Gate::new(1));
272            let held = gate.acquire(Priority::Normal).await;
273            {
274                let mut abandoned = Box::pin(gate.acquire(Priority::High));
275                assert!(poll_once(&mut abandoned).await.is_none());
276            }
277            drop(held);
278            let state = gate.state.lock().unwrap();
279            assert!(state.waiting.is_empty());
280            assert!(state.granted.is_empty());
281            assert_eq!(state.free, 1);
282        });
283    }
284}