use std::time::Duration;
use proptest::{prelude::*, test_runner::TestCaseError};
use tokio::{
runtime::{Builder, Runtime},
time,
};
use super::super::PushQueues;
use crate::push::{PushError, PushPolicy, PushPriority};
#[tokio::test]
async fn try_push_shares_the_rate_limit_with_awaited_pushes() {
time::pause();
let (mut queues, handle) = PushQueues::<u8>::builder()
.high_capacity(4)
.low_capacity(4)
.rate(Some(1))
.build()
.expect("queue builds");
let clone = handle.clone();
handle
.push_high_priority(1)
.await
.expect("the first push consumes the only permit");
assert_eq!(
clone.try_push(2, PushPriority::High, PushPolicy::DropIfFull),
Err(PushError::RateLimited),
"a clone must see the permit the awaited path consumed"
);
time::advance(Duration::from_secs(1)).await;
clone
.try_push(3, PushPriority::High, PushPolicy::DropIfFull)
.expect("a replenished permit admits the non-blocking push");
let (_, first) = queues.recv().await.expect("the awaited push is queued");
let (_, second) = queues.recv().await.expect("the admitted push is queued");
assert_eq!(
(first, second),
(1, 3),
"the refused frame must not be queued"
);
}
#[tokio::test]
async fn an_awaited_push_waits_for_a_permit_a_try_push_spent() {
time::pause();
let (mut queues, handle) = PushQueues::<u8>::builder()
.high_capacity(4)
.low_capacity(1)
.rate(Some(1))
.build()
.expect("queue builds");
let non_blocking = handle.clone();
let awaited = handle.clone();
non_blocking
.try_push(1, PushPriority::High, PushPolicy::ReturnErrorIfFull)
.expect("the first push consumes the only permit");
let push = awaited.push_low_priority(2);
tokio::pin!(push);
assert!(
futures::poll!(push.as_mut()).is_pending(),
"the awaited push must wait for the next window"
);
assert_eq!(
handle.try_push(3, PushPriority::Low, PushPolicy::ReturnErrorIfFull),
Err(PushError::QueueFull),
"the waiting push must hold its lane slot until its permit arrives"
);
time::advance(Duration::from_secs(1)).await;
push.await
.expect("the refilled permit admits the awaited push");
let (_, first) = queues
.recv()
.await
.expect("the non-blocking push is queued");
let (priority, second) = queues.recv().await.expect("the awaited push is queued");
assert_eq!((first, second), (1, 2), "both frames are delivered once");
assert_eq!(
priority,
PushPriority::Low,
"the awaited push keeps its lane"
);
}
#[tokio::test]
async fn try_push_refused_for_capacity_does_not_spend_a_rate_permit() {
time::pause();
let (mut queues, handle) = PushQueues::<u8>::builder()
.high_capacity(1)
.low_capacity(1)
.rate(Some(2))
.build()
.expect("queue builds");
handle
.push_high_priority(1)
.await
.expect("the first push spends one permit and fills the high lane");
assert_eq!(
handle.try_push(2, PushPriority::High, PushPolicy::ReturnErrorIfFull),
Err(PushError::QueueFull),
"a full high lane must refuse the frame without spending the last permit"
);
handle
.try_push(3, PushPriority::Low, PushPolicy::ReturnErrorIfFull)
.expect("the low lane has room and the refusal spent no permit");
let delivered = [queues.recv().await, queues.recv().await];
assert_eq!(
delivered,
[Some((PushPriority::High, 1)), Some((PushPriority::Low, 3)),],
"only the admitted frames are queued, in delivery order"
);
}
#[tokio::test]
async fn try_push_reports_a_closed_connection_before_an_exhausted_rate_limit() {
time::pause();
let (queues, handle) = PushQueues::<u8>::builder()
.high_capacity(1)
.low_capacity(1)
.rate(Some(1))
.build()
.expect("queue builds");
handle
.push_high_priority(1)
.await
.expect("the first push consumes the only permit");
drop(queues);
assert_eq!(
handle.try_push(2, PushPriority::High, PushPolicy::ReturnErrorIfFull),
Err(PushError::Closed),
"a closed connection is permanent, so it must outrank the rate limit"
);
}
#[tokio::test]
async fn awaited_push_reports_closed_without_waiting_for_a_rate_token() {
time::pause();
let (queues, handle) = PushQueues::<u8>::builder()
.high_capacity(1)
.low_capacity(1)
.rate(Some(1))
.build()
.expect("queue builds");
handle
.push_high_priority(1)
.await
.expect("the first push consumes the only permit");
drop(queues);
let outcome = time::timeout(Duration::ZERO, handle.push_high_priority(2))
.await
.expect("a closed connection must be reported without waiting for a refill");
assert_eq!(outcome, Err(PushError::Closed));
}
#[tokio::test]
async fn producers_parked_on_a_full_queue_do_not_burst_after_it_drains() {
time::pause();
let (mut queues, handle) = PushQueues::<u8>::builder()
.high_capacity(1)
.low_capacity(1)
.rate(Some(1))
.build()
.expect("queue builds");
handle
.push_high_priority(1)
.await
.expect("the first push consumes the window's permit and fills the queue");
let parked = tokio::spawn({
let producer = handle.clone();
async move {
futures::join!(
producer.push_high_priority(2),
producer.push_high_priority(3),
producer.push_high_priority(4),
)
}
});
tokio::task::yield_now().await;
time::advance(Duration::from_secs(3)).await;
assert_eq!(
queues.recv().await,
Some((PushPriority::High, 1)),
"the queued frame is drained first"
);
assert_eq!(
queues.recv().await,
Some((PushPriority::High, 2)),
"the permit accumulated while parked admits the next frame"
);
assert!(
time::timeout(Duration::ZERO, queues.recv()).await.is_err(),
"the third frame must wait for the next refill, not leave with the second"
);
time::advance(Duration::from_secs(1)).await;
assert_eq!(queues.recv().await, Some((PushPriority::High, 3)));
assert!(
time::timeout(Duration::ZERO, queues.recv()).await.is_err(),
"the fourth frame must also wait for a refill"
);
time::advance(Duration::from_secs(1)).await;
assert_eq!(queues.recv().await, Some((PushPriority::High, 4)));
assert_eq!(
parked.await.expect("the producer task must not panic"),
(Ok(()), Ok(()), Ok(())),
"every parked frame is eventually admitted"
);
}
fn paused_runtime() -> Result<Runtime, TestCaseError> {
Builder::new_current_thread()
.enable_time()
.start_paused(true)
.build()
.map_err(|error| TestCaseError::fail(format!("a paused runtime must build: {error}")))
}
fn ticketed_queues(
budget: u8,
) -> Result<(PushQueues<u8>, crate::push::PushHandle<u8>), TestCaseError> {
PushQueues::<u8>::builder()
.high_capacity(64)
.low_capacity(64)
.rate(Some(usize::from(budget)))
.build()
.map_err(|error| TestCaseError::fail(format!("the queues must build: {error}")))
}
proptest! {
#![proptest_config(ProptestConfig { cases: 48, ..ProptestConfig::default() })]
#[test]
fn a_window_never_admits_more_pushes_than_its_budget(
budget in 1u8..=8,
lanes in proptest::collection::vec(any::<bool>(), 1..=32),
) {
let runtime = paused_runtime()?;
let (attempts, admitted) = runtime.block_on(async move {
let (_queues, handle) = ticketed_queues(budget)?;
let clone = handle.clone();
let attempts = lanes.len();
let mut admitted = 0usize;
for is_high in lanes {
let priority = if is_high {
PushPriority::High
} else {
PushPriority::Low
};
if clone
.try_push(1, priority, PushPolicy::ReturnErrorIfFull)
.is_ok()
{
admitted += 1;
}
}
Ok::<_, TestCaseError>((attempts, admitted))
})?;
let allowance = usize::from(budget);
prop_assert!(
admitted <= allowance,
"{admitted} pushes were admitted in one window with a budget of {allowance}"
);
prop_assert_eq!(
admitted,
attempts.min(allowance),
"every attempt a fresh window can admit must be admitted"
);
}
}
proptest! {
#[test]
fn a_closed_connection_outranks_an_exhausted_window(
budget in 1u8..=8,
is_high in any::<bool>(),
) {
let runtime = paused_runtime()?;
let error = runtime.block_on(async move {
let (queues, handle) = ticketed_queues(budget)?;
for _ in 0..budget {
handle
.try_push(1, PushPriority::High, PushPolicy::ReturnErrorIfFull)
.map_err(|error| TestCaseError::fail(format!("the budget must admit the frame: {error}")))?;
}
drop(queues);
let priority = if is_high {
PushPriority::High
} else {
PushPriority::Low
};
Ok::<_, TestCaseError>(handle.try_push(2, priority, PushPolicy::ReturnErrorIfFull))
})?;
prop_assert_eq!(error, Err(PushError::Closed));
}
}