use futures_util::FutureExt;
use pretty_assertions::assert_eq;
use rho_sdk::{ModelRequestGate, SessionId};
use rho_tools::cancellation::RunCancellation;
use super::{holding_the_only_slot, SlotWait};
use crate::app::{
agent_binding::CapacityClass,
agent_concurrency::{Budget, QueuePlace},
};
#[tokio::test]
async fn an_asking_run_gives_its_slot_back_and_waits_first_in_line_for_it_after() {
let (pool, slot, queue) = holding_the_only_slot();
let asking = slot.asking();
let cancellation = RunCancellation::new();
let other = pool
.join(CapacityClass::Rho)
.acquire(&cancellation)
.now_or_never()
.flatten()
.expect("the slot the asking run gave back");
let unstarted = pool.join(CapacityClass::Rho).acquire(&cancellation);
tokio::pin!(unstarted);
let unstarted_waits = unstarted.as_mut().now_or_never().is_none();
drop(asking);
let mut wait = slot.wait();
let session = SessionId::new();
let admit = slot.admit(&session);
tokio::pin!(admit);
let admit_waits = admit.as_mut().now_or_never().is_none();
let in_line = (queue.place(), *wait.borrow_and_update());
drop(other);
let admitted = admit.now_or_never().is_some();
assert_eq!(
(
unstarted_waits,
admit_waits,
in_line,
admitted,
*wait.borrow(),
unstarted.now_or_never().is_none(),
),
(
true,
true,
(
Some(QueuePlace {
budget: Budget::AgentConcurrency,
limit: 1,
position: 1,
}),
SlotWait::InLine,
),
true,
SlotWait::NotWaiting,
true,
)
);
}
#[tokio::test]
async fn a_request_while_a_question_is_open_holds_the_slot_for_itself_only() {
let (pool, slot, _queue) = holding_the_only_slot();
let _asking = slot.asking();
let permit = slot.admit(&SessionId::new()).await;
let during = pool.available_total();
drop(permit);
assert_eq!((during, pool.available_total()), (0, 1));
}
#[tokio::test]
async fn a_dropped_wait_leaves_the_line_without_a_slot() {
let (pool, slot, queue) = holding_the_only_slot();
drop(slot.asking());
let other = pool
.join(CapacityClass::Rho)
.acquire(&RunCancellation::new())
.now_or_never()
.flatten()
.expect("the slot the run gave back");
let session = SessionId::new();
let mut admit = slot.admit(&session);
let waited = (&mut admit).now_or_never().is_none();
drop(admit);
drop(other);
assert_eq!(
(
waited,
queue.place(),
*slot.wait().borrow(),
pool.available_total()
),
(true, None, SlotWait::NotWaiting, 1)
);
}