use std::{collections::HashMap, sync::Arc};
use agent_client_protocol::{v2::schema as v2, Error as AcpError, RequestCancellation};
use rho_sdk::CancellationToken;
use tokio::sync::watch;
use crate::app::acp::sessions::Live;
pub(super) type Keys = HashMap<v2::IdempotencyKey, Keyed>;
#[derive(Clone)]
pub(super) enum Keyed {
Pending(Arc<KeyedPrompt>),
Inserted(v2::MessageId),
}
type Outcome = Result<v2::MessageId, AcpError>;
pub(super) struct KeyedPrompt {
outcome: watch::Sender<Option<Outcome>>,
withdrawn: CancellationToken,
cancels: u64,
}
pub(super) fn claim(
keys: &mut Keys,
key: &v2::IdempotencyKey,
cancels: u64,
withdrawn: &CancellationToken,
) -> Result<Arc<KeyedPrompt>, Keyed> {
match keys.get(key) {
Some(earlier @ Keyed::Inserted(_)) => return Err(earlier.clone()),
Some(earlier @ Keyed::Pending(prompt)) if prompt.cancels == cancels => {
return Err(earlier.clone());
}
Some(Keyed::Pending(_)) | None => {}
}
let prompt = Arc::new(KeyedPrompt {
outcome: watch::channel(None).0,
withdrawn: withdrawn.clone(),
cancels,
});
keys.insert(key.clone(), Keyed::Pending(Arc::clone(&prompt)));
Ok(prompt)
}
pub(in crate::app::acp) struct Retry {
pub(super) followed: Keyed,
pub(super) cancellation: RequestCancellation,
}
impl Retry {
pub(in crate::app::acp) async fn outcome(self) -> Outcome {
let prompt = match self.followed {
Keyed::Inserted(message) => return Ok(message),
Keyed::Pending(prompt) => prompt,
};
let mut outcome = prompt.outcome.subscribe();
let told = async {
match outcome.wait_for(Option::is_some).await {
Ok(told) => told.clone().unwrap_or_else(|| Err(lost())),
Err(_) => Err(lost()),
}
};
tokio::pin!(told);
tokio::select! {
biased;
outcome = &mut told => return outcome,
() = self.cancellation.cancelled() => prompt.withdrawn.cancel(),
}
told.await
}
}
pub(in crate::app::acp) struct Retries {
live: Arc<Live>,
key: v2::IdempotencyKey,
prompt: Arc<KeyedPrompt>,
told: bool,
}
impl Retries {
pub(super) fn new(live: Arc<Live>, key: v2::IdempotencyKey, prompt: Arc<KeyedPrompt>) -> Self {
Self {
live,
key,
prompt,
told: false,
}
}
pub(in crate::app::acp) fn tell(mut self, outcome: Outcome) {
self.told = true;
self.settle(outcome);
}
fn settle(&self, outcome: Outcome) {
{
let mut keys = self.live.held.keys();
let owned = matches!(
keys.get(&self.key),
Some(Keyed::Pending(prompt)) if Arc::ptr_eq(prompt, &self.prompt)
);
if owned {
match &outcome {
Ok(message) => {
keys.insert(self.key.clone(), Keyed::Inserted(message.clone()));
}
Err(_) => {
keys.remove(&self.key);
}
}
}
}
self.prompt.outcome.send_replace(Some(outcome));
}
}
impl Drop for Retries {
fn drop(&mut self) {
if !self.told {
self.settle(Err(lost()));
}
}
}
fn lost() -> AcpError {
AcpError::internal_error().data("the prompt this retries stopped without an answer")
}