use std::future::Future;
use std::sync::{Arc, Mutex, PoisonError};
use std::time::{Duration, Instant};
use rig_core::wasm_compat::WasmBoxedFuture;
use tokio::sync::oneshot;
use crate::node::{Node, NodeError, NodeIo, NodeOutput};
pub struct Question {
from: String,
question: String,
context: String,
reply: oneshot::Sender<String>,
_paused: Vec<Pause>,
}
impl std::fmt::Debug for Question {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
f.debug_struct("Question")
.field("from", &self.from)
.field("question", &self.question)
.field("context", &self.context)
.finish_non_exhaustive()
}
}
impl Question {
pub(crate) fn new(
from: impl Into<String>,
question: impl Into<String>,
context: impl Into<String>,
) -> (Self, oneshot::Receiver<String>) {
let (reply, answer) = oneshot::channel();
let question = Self {
from: from.into(),
question: question.into(),
context: context.into(),
reply,
_paused: Vec::new(),
};
(question, answer)
}
pub fn from(&self) -> &str {
&self.from
}
pub fn question(&self) -> &str {
&self.question
}
pub fn context(&self) -> &str {
&self.context
}
pub fn answer(self, answer: impl Into<String>) {
let _ = self.reply.send(answer.into());
}
pub(crate) fn pausing(mut self, clock: &Clock) -> Self {
self._paused.push(clock.pause());
self
}
pub(crate) fn via(mut self, node: &str) -> Self {
self.from = format!("{node}/{}", self.from);
self
}
}
pub(crate) async fn answer(answer: oneshot::Receiver<String>) -> Result<String, NodeError> {
answer
.await
.map_err(|_| "the question was dismissed without an answer".into())
}
pub struct HumanNode {
question: String,
}
pub fn human(question: impl Into<String>) -> HumanNode {
HumanNode {
question: question.into(),
}
}
impl Node for HumanNode {
fn run<'a>(
&'a self,
input: String,
io: &'a NodeIo<'a>,
) -> WasmBoxedFuture<'a, Result<NodeOutput, NodeError>> {
Box::pin(async move { Ok(NodeOutput::new(io.ask(&self.question, input).await?)) })
}
}
#[derive(Clone)]
pub(crate) struct Clock(Arc<Mutex<ClockState>>);
struct ClockState {
offset: Duration,
started: Instant,
paused_total: Duration,
paused_since: Option<Instant>,
pauses: usize,
}
impl Clock {
pub(crate) fn resumed(offset: Duration) -> Self {
Self(Arc::new(Mutex::new(ClockState {
offset,
started: Instant::now(),
paused_total: Duration::ZERO,
paused_since: None,
pauses: 0,
})))
}
fn state(&self) -> std::sync::MutexGuard<'_, ClockState> {
self.0.lock().unwrap_or_else(PoisonError::into_inner)
}
pub(crate) fn active(&self) -> Duration {
let state = self.state();
let now = Instant::now();
let paused = state.paused_total
+ state
.paused_since
.map_or(Duration::ZERO, |since| now - since);
state.offset + (now - state.started).saturating_sub(paused)
}
fn is_paused(&self) -> bool {
self.state().pauses > 0
}
fn pause(&self) -> Pause {
let mut state = self.state();
state.pauses += 1;
if state.pauses == 1 {
state.paused_since = Some(Instant::now());
}
Pause(self.clone())
}
pub(crate) async fn within<F: Future>(&self, budget: Duration, future: F) -> Option<F::Output> {
let start = self.active();
let mut future = std::pin::pin!(future);
loop {
let left = budget.saturating_sub(self.active().saturating_sub(start));
let paused = self.is_paused();
if left.is_zero() && !paused {
return None;
}
let wait = if paused {
left.max(Duration::from_secs(1))
} else {
left
};
tokio::select! {
output = &mut future => return Some(output),
() = tokio::time::sleep(wait) => {}
}
}
}
}
pub(crate) struct Pause(Clock);
impl Drop for Pause {
fn drop(&mut self) {
let mut state = self.0.state();
state.pauses -= 1;
if state.pauses == 0
&& let Some(since) = state.paused_since.take()
{
state.paused_total += since.elapsed();
}
}
}