use std::{
collections::VecDeque,
future::Future,
sync::{Arc, Mutex, PoisonError},
};
use agent_client_protocol::{v2::schema as v2, Error as AcpError, RequestCancellation};
use rho_sdk::CancellationToken;
use tokio::sync::{watch, MutexGuard};
use super::retry::{self, Keys, Retries, Retry};
use crate::app::acp::sessions::{Busy, Live};
pub(in crate::app::acp) struct Holds {
line: watch::Sender<Line>,
keys: Mutex<Keys>,
}
impl Default for Holds {
fn default() -> Self {
Self {
line: watch::channel(Line::default()).0,
keys: Mutex::default(),
}
}
}
impl Holds {
pub(in crate::app::acp) fn cancel(&self) {
self.line.send_modify(|line| line.cancels += 1);
}
pub(super) fn keys(&self) -> std::sync::MutexGuard<'_, Keys> {
self.keys.lock().unwrap_or_else(PoisonError::into_inner)
}
}
#[derive(Default)]
struct Line {
waiting: VecDeque<u64>,
next: u64,
cancels: u64,
}
pub(in crate::app::acp) struct Place {
live: Arc<Live>,
ticket: u64,
cancels: u64,
cancellation: RequestCancellation,
withdrawn: CancellationToken,
key: Option<v2::IdempotencyKey>,
}
pub(in crate::app::acp) enum Entry {
Held {
place: Place,
retries: Option<Retries>,
},
Retry(Retry),
}
impl Place {
pub(in crate::app::acp) fn new(live: Arc<Live>, cancellation: RequestCancellation) -> Self {
let (mut ticket, mut cancels) = (0, 0);
live.held.line.send_modify(|line| {
ticket = line.next;
line.next += 1;
line.waiting.push_back(ticket);
cancels = line.cancels;
});
Self {
live,
ticket,
cancels,
cancellation,
withdrawn: CancellationToken::new(),
key: None,
}
}
pub(in crate::app::acp) fn keyed(mut self, key: Option<v2::IdempotencyKey>) -> Entry {
let Some(key) = key else {
return Entry::Held {
place: self,
retries: None,
};
};
let claimed = retry::claim(
&mut self.live.held.keys(),
&key,
self.cancels,
&self.withdrawn,
);
match claimed {
Ok(prompt) => {
let retries = Retries::new(Arc::clone(&self.live), key.clone(), prompt);
self.key = Some(key);
Entry::Held {
place: self,
retries: Some(retries),
}
}
Err(followed) => Entry::Retry(Retry {
followed,
cancellation: self.cancellation.clone(),
}),
}
}
pub(in crate::app::acp) fn key(&self) -> Option<&v2::IdempotencyKey> {
self.key.as_ref()
}
pub(in crate::app::acp) fn live(&self) -> &Arc<Live> {
&self.live
}
pub(in crate::app::acp) async fn take_turn(&self) -> Result<MutexGuard<'_, ()>, AcpError> {
let first_free = async {
let mut line = self.live.held.line.subscribe();
let _ = line
.wait_for(|line| self.dropped(line) || line.waiting.front() == Some(&self.ticket))
.await;
self.live.prompt.lock().await
};
let turn = self.unless_dropped(first_free).await?;
self.leave();
Ok(turn)
}
pub(in crate::app::acp) async fn until_free(&self, busy: Busy) -> Result<(), AcpError> {
self.unless_dropped(busy.ended()).await
}
pub(in crate::app::acp) fn check(&self) -> Result<(), AcpError> {
if self.session_cancelled() {
return Err(cancelled());
}
if self.cancellation.is_cancelled() || self.withdrawn.is_cancelled() {
return Err(AcpError::request_cancelled());
}
Ok(())
}
pub(in crate::app::acp) fn session_cancelled(&self) -> bool {
self.dropped(&self.live.held.line.borrow())
}
fn dropped(&self, line: &Line) -> bool {
line.cancels != self.cancels
}
pub(in crate::app::acp) async fn unless_dropped<T>(
&self,
work: impl Future<Output = T>,
) -> Result<T, AcpError> {
let mut line = self.live.held.line.subscribe();
let session_cancelled = async {
let _ = line.wait_for(|line| self.dropped(line)).await;
};
tokio::select! {
biased;
() = session_cancelled => Err(cancelled()),
() = self.cancellation.cancelled() => Err(AcpError::request_cancelled()),
() = self.withdrawn.cancelled() => Err(AcpError::request_cancelled()),
value = work => Ok(value),
}
}
fn leave(&self) {
self.live.held.line.send_if_modified(|line| {
let before = line.waiting.len();
line.waiting.retain(|ticket| *ticket != self.ticket);
line.waiting.len() != before
});
}
}
impl Drop for Place {
fn drop(&mut self) {
self.leave();
}
}
fn cancelled() -> AcpError {
AcpError::request_cancelled().data("the session was cancelled before the prompt was inserted")
}