1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
//! The questions a session that reports to its starter asks (see
//! `app::starter_report`), asked without waiting and answered in a later
//! turn.
//!
//! Such a session works on its own, its starter, or the session its
//! question was passed up to, answering when it can: nothing below the top
//! of a tree holds a turn open waiting on a person. So its `questionnaire`
//! call hands the form to its host ([`SelfQuestions::ask`]) and returns at
//! once, and its turn ends. The host opens the question as the session's
//! own request, which outlives the turn, and saves it with the session's
//! job, so a restart keeps it (see `daemon_host::sessions::self_questions`).
//! The answer arrives in the session's [`AnswerInbox`], whose answers a
//! turn boundary delivers as a background result: the host wakes the idle
//! session for it, as for a finished process.
//!
//! An answer stays saved until a turn took it ([`Receipt`]), so a restart
//! before then delivers it again.
use std::{
future::Future,
sync::{Arc, Mutex, MutexGuard, PoisonError},
};
use serde::{Deserialize, Serialize};
use tokio::sync::{mpsc, Notify};
use super::peer_sessions::Receipt;
/// Names one question a session asked of itself, across daemons.
#[derive(Clone, Debug, PartialEq, Eq, Hash, Serialize, Deserialize)]
#[serde(transparent)]
pub(crate) struct QuestionId(String);
impl QuestionId {
fn generate() -> Self {
Self(uuid::Uuid::new_v4().to_string())
}
}
/// A form a session asks: the `questionnaire` call's arguments, which open
/// it again after a restart, the request they make, and what it asks in a
/// line. Parsed once, where the call comes in.
#[derive(Clone, Debug, PartialEq)]
pub(crate) struct Form {
pub(crate) arguments: serde_json::Value,
pub(crate) request: rho_sdk::HostInputRequest,
pub(crate) ask: String,
}
/// A question the session asked, which its host opens as a request.
#[derive(Clone, Debug, PartialEq)]
pub(crate) struct Asked {
pub(crate) id: QuestionId,
pub(crate) form: Form,
}
/// Where a session that reports to its starter asks, and its answers
/// arrive. Cheap to clone; clones share the queue and the inbox.
#[derive(Clone)]
pub(crate) struct SelfQuestions {
asks: mpsc::UnboundedSender<Asked>,
/// The queue's far end, until the host takes it.
asked: Arc<Mutex<Option<mpsc::UnboundedReceiver<Asked>>>>,
answers: AnswerInbox,
}
impl SelfQuestions {
pub(crate) fn new() -> Self {
let (asks, asked) = mpsc::unbounded_channel();
Self {
asks,
asked: Arc::new(Mutex::new(Some(asked))),
answers: AnswerInbox::default(),
}
}
/// The queue the session's questions arrive on, for its host to take
/// once; `None` after.
pub(crate) fn take_asked(&self) -> Option<mpsc::UnboundedReceiver<Asked>> {
self.asked
.lock()
.unwrap_or_else(PoisonError::into_inner)
.take()
}
/// Asks the session's host `form`; its answer arrives in
/// [`Self::answers`]. `None` once the host stopped taking questions.
/// The question counts as open from before its host can see it, so the
/// session never settles as if nothing could wake it, and an answer
/// never comes before its question counts.
pub(crate) fn ask(&self, form: Form) -> Option<QuestionId> {
let id = QuestionId::generate();
self.answers.opened();
let asked = Asked {
id: id.clone(),
form,
};
if self.asks.send(asked).is_err() {
self.answers.state().open -= 1;
return None;
}
Some(id)
}
pub(crate) fn answers(&self) -> &AnswerInbox {
&self.answers
}
}
impl std::fmt::Debug for SelfQuestions {
fn fmt(&self, formatter: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
formatter.write_str("SelfQuestions")
}
}
/// The answers to a session's own questions, until a turn takes them.
/// Cheap to clone; clones share the answers.
#[derive(Clone, Default)]
pub(crate) struct AnswerInbox {
shared: Arc<Shared>,
}
#[derive(Default)]
struct Shared {
state: Mutex<State>,
/// Told when an answer arrives or is put back.
arrived: Arc<Notify>,
}
#[derive(Default)]
struct State {
/// Each answer waiting, with what runs once it is delivered.
answers: Vec<(Answer, Receipt)>,
/// How many questions are open, their answers still to come.
open: usize,
}
/// One answer, as the model reads it.
#[derive(Clone, Debug, PartialEq, Eq)]
pub(crate) struct Answer {
/// The question's title.
pub(crate) title: String,
/// The answer, as the `questionnaire` tool reads one back.
pub(crate) content: String,
}
impl AnswerInbox {
fn state(&self) -> MutexGuard<'_, State> {
// Each change is one push, take, or count.
self.shared
.state
.lock()
.unwrap_or_else(PoisonError::into_inner)
}
/// A question opened, whose answer is to come.
pub(crate) fn opened(&self) {
self.state().open += 1;
}
/// An open question was answered with `answer`; `receipt` runs once a
/// turn took it.
pub(crate) fn answered(&self, answer: Answer, receipt: Receipt) {
{
let mut state = self.state();
state.open = state.open.saturating_sub(1);
state.answers.push((answer, receipt));
}
self.shared.arrived.notify_waiters();
}
/// An answer a turn has yet to take, as a restart found it saved;
/// `receipt` runs once a turn took it.
pub(crate) fn restore_answer(&self, answer: Answer, receipt: Receipt) {
self.state().open += 1;
self.answered(answer, receipt);
}
/// Whether an answer waits.
pub(crate) fn has_answers(&self) -> bool {
!self.state().answers.is_empty()
}
/// Whether a question is open, its answer still to come.
pub(crate) fn expecting(&self) -> bool {
self.state().open > 0
}
/// Completes when an answer arrives or is put back. Subscribe before
/// checking [`Self::has_answers`], so an answer in between is not
/// missed.
pub(crate) fn arrived_owned(&self) -> impl Future<Output = ()> + Send + 'static {
Arc::clone(&self.shared.arrived).notified_owned()
}
/// Takes every answer that waits, oldest first.
pub(crate) fn take(&self) -> AnswerBatch {
AnswerBatch(std::mem::take(&mut self.state().answers))
}
/// Puts back, ahead of the rest, answers a turn took and did not
/// deliver.
pub(crate) fn restore(&self, batch: &mut AnswerBatch) {
if batch.is_empty() {
return;
}
self.state().answers.splice(0..0, batch.0.drain(..));
self.shared.arrived.notify_waiters();
}
}
/// The answers one turn boundary took, oldest first, each with what runs
/// once it is delivered.
#[derive(Default)]
pub(crate) struct AnswerBatch(Vec<(Answer, Receipt)>);
impl AnswerBatch {
pub(crate) fn is_empty(&self) -> bool {
self.0.is_empty()
}
/// The run applied the batch: its answers are delivered.
pub(crate) fn commit(&mut self) {
for (_, receipt) in std::mem::take(&mut self.0) {
receipt.run();
}
}
/// What the model reads of the answers.
pub(crate) fn prompt(&self) -> String {
self.answers()
.map(|Answer { title, content }| {
format!("The answer to the question you asked, \"{title}\":\n\n{content}")
})
.collect::<Vec<_>>()
.join("\n\n")
}
/// The answers, oldest first.
pub(crate) fn answers(&self) -> impl Iterator<Item = &Answer> {
self.0.iter().map(|(answer, _)| answer)
}
}
#[cfg(test)]
#[path = "self_questions_tests.rs"]
mod tests;