use std::sync::{Arc, Mutex, MutexGuard, PoisonError};
use futures_util::FutureExt;
use rho_sdk::{ModelRequestGate, ModelRequestGateFuture, ModelRequestPermit, SessionId};
use rho_tools::cancellation::RunCancellation;
use tokio::sync::watch;
use super::{AgentConcurrency, QueueWatch, RuntimePermits};
pub(crate) struct RunSlot {
state: Mutex<SlotState>,
concurrency: AgentConcurrency,
queue: QueueWatch,
wait: watch::Sender<SlotWait>,
}
enum SlotState {
Holding { _permits: RuntimePermits },
Lent { open: usize },
Ended,
}
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
pub(crate) enum SlotWait {
#[default]
NotWaiting,
InLine,
}
impl RunSlot {
pub(crate) fn new(
permits: RuntimePermits,
concurrency: &AgentConcurrency,
queue: QueueWatch,
) -> Self {
Self {
state: Mutex::new(SlotState::Holding { _permits: permits }),
concurrency: concurrency.clone(),
queue,
wait: watch::Sender::default(),
}
}
pub(crate) fn asking(self: &Arc<Self>) -> Asking {
let mut state = self.state();
match &mut *state {
SlotState::Holding { .. } => *state = SlotState::Lent { open: 1 },
SlotState::Lent { open } => *open += 1,
SlotState::Ended => {}
}
Asking(Arc::clone(self))
}
pub(crate) fn wait(&self) -> watch::Receiver<SlotWait> {
self.wait.subscribe()
}
pub(crate) fn release(&self) {
*self.state() = SlotState::Ended;
}
fn state(&self) -> MutexGuard<'_, SlotState> {
self.state.lock().unwrap_or_else(PoisonError::into_inner)
}
}
pub(crate) struct Asking(Arc<RunSlot>);
impl Drop for Asking {
fn drop(&mut self) {
match &mut *self.0.state() {
SlotState::Lent { open } => *open -= 1,
SlotState::Holding { .. } | SlotState::Ended => {}
}
}
}
impl ModelRequestGate for RunSlot {
fn admit<'a>(&'a self, _session_id: &'a SessionId) -> ModelRequestGateFuture<'a> {
Box::pin(async move {
match &*self.state() {
SlotState::Holding { .. } | SlotState::Ended => return ModelRequestPermit::free(),
SlotState::Lent { .. } => {}
}
let never = RunCancellation::new();
let acquire = self.concurrency.rejoin(&self.queue).acquire(&never);
tokio::pin!(acquire);
let permits = match acquire.as_mut().now_or_never() {
Some(permits) => permits,
None => {
let _in_line = InLine::shown(&self.wait);
acquire.await
}
};
let Some(permits) = permits else {
tracing::error!(
"an uncancelled wait for a slot ended without one; the request goes unbudgeted"
);
return ModelRequestPermit::free();
};
let mut state = self.state();
match &*state {
SlotState::Lent { open: 0 } => {
*state = SlotState::Holding { _permits: permits };
ModelRequestPermit::free()
}
SlotState::Lent { .. } | SlotState::Holding { .. } | SlotState::Ended => {
ModelRequestPermit::holding(permits)
}
}
})
}
}
struct InLine<'a>(&'a watch::Sender<SlotWait>);
impl<'a> InLine<'a> {
fn shown(wait: &'a watch::Sender<SlotWait>) -> Self {
wait.send_replace(SlotWait::InLine);
Self(wait)
}
}
impl Drop for InLine<'_> {
fn drop(&mut self) {
self.0.send_replace(SlotWait::NotWaiting);
}
}
#[cfg(test)]
pub(crate) fn holding_the_only_slot() -> (AgentConcurrency, Arc<RunSlot>, QueueWatch) {
let pool = AgentConcurrency::new(super::ConcurrencyLimits {
total: 1,
claude_requested: 1,
});
let permits = pool
.join(super::CapacityClass::Rho)
.acquire(&RunCancellation::new())
.now_or_never()
.flatten()
.expect("a free slot");
let queue = QueueWatch::default();
let slot = Arc::new(RunSlot::new(permits, &pool, queue.clone()));
(pool, slot, queue)
}
#[cfg(test)]
#[path = "run_slot_tests.rs"]
mod tests;