1use std::future::Future;
5use std::sync::{Arc, Mutex, PoisonError};
6use std::time::{Duration, Instant};
7
8use rig_core::wasm_compat::WasmBoxedFuture;
9use tokio::sync::oneshot;
10
11use crate::node::{Node, NodeError, NodeIo, NodeOutput};
12
13pub struct Question {
18 from: String,
19 question: String,
20 context: String,
21 reply: oneshot::Sender<String>,
22 _paused: Vec<Pause>,
25}
26
27impl std::fmt::Debug for Question {
28 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
29 f.debug_struct("Question")
30 .field("from", &self.from)
31 .field("question", &self.question)
32 .field("context", &self.context)
33 .finish_non_exhaustive()
34 }
35}
36
37impl Question {
38 pub(crate) fn new(
39 from: impl Into<String>,
40 question: impl Into<String>,
41 context: impl Into<String>,
42 ) -> (Self, oneshot::Receiver<String>) {
43 let (reply, answer) = oneshot::channel();
44 let question = Self {
45 from: from.into(),
46 question: question.into(),
47 context: context.into(),
48 reply,
49 _paused: Vec::new(),
50 };
51 (question, answer)
52 }
53
54 pub fn from(&self) -> &str {
57 &self.from
58 }
59
60 pub fn question(&self) -> &str {
62 &self.question
63 }
64
65 pub fn context(&self) -> &str {
68 &self.context
69 }
70
71 pub fn answer(self, answer: impl Into<String>) {
73 let _ = self.reply.send(answer.into());
75 }
76
77 pub(crate) fn pausing(mut self, clock: &Clock) -> Self {
79 self._paused.push(clock.pause());
80 self
81 }
82
83 pub(crate) fn via(mut self, node: &str) -> Self {
85 self.from = format!("{node}/{}", self.from);
86 self
87 }
88}
89
90pub(crate) async fn answer(answer: oneshot::Receiver<String>) -> Result<String, NodeError> {
92 answer
93 .await
94 .map_err(|_| "the question was dismissed without an answer".into())
95}
96
97pub struct HumanNode {
99 question: String,
100}
101
102pub fn human(question: impl Into<String>) -> HumanNode {
125 HumanNode {
126 question: question.into(),
127 }
128}
129
130impl Node for HumanNode {
131 fn run<'a>(
132 &'a self,
133 input: String,
134 io: &'a NodeIo<'a>,
135 ) -> WasmBoxedFuture<'a, Result<NodeOutput, NodeError>> {
136 Box::pin(async move { Ok(NodeOutput::new(io.ask(&self.question, input).await?)) })
137 }
138}
139
140#[derive(Clone)]
143pub(crate) struct Clock(Arc<Mutex<ClockState>>);
144
145struct ClockState {
146 offset: Duration,
148 started: Instant,
149 paused_total: Duration,
150 paused_since: Option<Instant>,
151 pauses: usize,
152}
153
154impl Clock {
155 pub(crate) fn resumed(offset: Duration) -> Self {
157 Self(Arc::new(Mutex::new(ClockState {
158 offset,
159 started: Instant::now(),
160 paused_total: Duration::ZERO,
161 paused_since: None,
162 pauses: 0,
163 })))
164 }
165
166 fn state(&self) -> std::sync::MutexGuard<'_, ClockState> {
167 self.0.lock().unwrap_or_else(PoisonError::into_inner)
168 }
169
170 pub(crate) fn active(&self) -> Duration {
172 let state = self.state();
173 let now = Instant::now();
174 let paused = state.paused_total
175 + state
176 .paused_since
177 .map_or(Duration::ZERO, |since| now - since);
178 state.offset + (now - state.started).saturating_sub(paused)
179 }
180
181 fn is_paused(&self) -> bool {
182 self.state().pauses > 0
183 }
184
185 fn pause(&self) -> Pause {
186 let mut state = self.state();
187 state.pauses += 1;
188 if state.pauses == 1 {
189 state.paused_since = Some(Instant::now());
190 }
191 Pause(self.clone())
192 }
193
194 pub(crate) async fn within<F: Future>(&self, budget: Duration, future: F) -> Option<F::Output> {
196 let start = self.active();
197 let mut future = std::pin::pin!(future);
198 loop {
199 let left = budget.saturating_sub(self.active().saturating_sub(start));
200 let paused = self.is_paused();
201 if left.is_zero() && !paused {
202 return None;
203 }
204 let wait = if paused {
206 left.max(Duration::from_secs(1))
207 } else {
208 left
209 };
210 tokio::select! {
211 output = &mut future => return Some(output),
212 () = tokio::time::sleep(wait) => {}
213 }
214 }
215 }
216}
217
218pub(crate) struct Pause(Clock);
221
222impl Drop for Pause {
223 fn drop(&mut self) {
224 let mut state = self.0.state();
225 state.pauses -= 1;
226 if state.pauses == 0
227 && let Some(since) = state.paused_since.take()
228 {
229 state.paused_total += since.elapsed();
230 }
231 }
232}