use std::pin::pin;
use std::sync::{Arc, Mutex};
use std::task::{Context, Poll, Waker};
use super::{Gate, Priority};
fn poll_once<F: Future>(future: std::pin::Pin<&mut F>) -> Poll<F::Output> {
future.poll(&mut Context::from_waker(Waker::noop()))
}
async fn queued(gate: &Gate, count: usize) {
while gate.waiting() != count {
tokio::task::yield_now().await;
}
}
#[tokio::test]
async fn high_priority_waiters_go_first() {
let gate = Arc::new(Gate::default());
let holder = gate.acquire(Priority::Normal).await;
let order = Arc::new(Mutex::new(Vec::new()));
let arrivals = [
("normal-1", Priority::Normal),
("normal-2", Priority::Normal),
("normal-3", Priority::Normal),
("high-1", Priority::High),
("high-2", Priority::High),
];
let mut waiters = Vec::new();
for (index, (name, priority)) in arrivals.into_iter().enumerate() {
let (gate_ref, order_ref) = (Arc::clone(&gate), Arc::clone(&order));
waiters.push(tokio::spawn(async move {
let permit = gate_ref.acquire(priority).await;
order_ref.lock().expect("order").push(name);
drop(permit);
}));
queued(&gate, index + 1).await;
}
drop(holder);
for waiter in waiters {
waiter.await.expect("waiter");
}
assert_eq!(
*order.lock().expect("order"),
["high-1", "high-2", "normal-1", "normal-2", "normal-3"]
);
}
#[tokio::test]
async fn dropped_waiter_leaves_the_queue() {
let gate = Arc::new(Gate::default());
let holder = gate.acquire(Priority::Normal).await;
let waiter = tokio::spawn({
let gate = Arc::clone(&gate);
async move { drop(gate.acquire(Priority::High).await) }
});
queued(&gate, 1).await;
waiter.abort();
let cancelled = waiter.await.is_err_and(|error| error.is_cancelled());
let waiting = gate.waiting();
drop(holder);
assert_eq!((cancelled, waiting, gate.is_held()), (true, 0, false));
}
#[test]
fn waiter_granted_then_dropped_passes_the_gate_on() {
let gate = Arc::new(Gate::default());
let Poll::Ready(holder) = poll_once(pin!(gate.acquire(Priority::Normal))) else {
panic!("a free gate admits at once");
};
let mut waiter = Box::pin(gate.acquire(Priority::Normal));
let queued = poll_once(waiter.as_mut()).is_pending();
drop(holder);
drop(waiter);
assert_eq!((queued, gate.waiting(), gate.is_held()), (true, 0, false));
}