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
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
//! Takes the questions a session that reports to its starter asks without
//! waiting (see `app::self_questions`), and gives it their answers.
//!
//! The session's `questionnaire` call queues its form and returns, so the
//! session, not a turn, owns the question. One watcher per loaded session,
//! started as the session is added, saves each question on the session's
//! job and opens it as the session's own input request
//! ([`super::inputs::Asker::Session`]). Its starter is told of it and holds
//! it, as of any question a session it started asks (see
//! `LoadedSession::change_inputs`), and it moves on from there as a held
//! question does (see `held_questions`). The answer goes to the session's
//! answer inbox, which wakes the idle session for a turn that takes it, and
//! is saved on the job until that turn took it.
//!
//! Who holds each question is saved as it is given one, explicitly: as
//! its starter is told, or as a holder passes it on. A holder that unloads
//! gives its questions to the person in memory only, so a restart, which
//! unloads every holder, keeps who held each. As the session loads again,
//! its saved questions count as open, and each answer no turn took waits
//! for a turn, before anything reads whether it settled; then each opens
//! again, under the holder it had if that holder is loaded and may act on
//! sessions, else the person's.
use std::{
sync::{Arc, Weak},
time::SystemTime,
};
use rho_protocol as wire;
use rho_sdk::{hooks::HookDispatcher, CancellationToken, HostInputId, HostInputRefusal};
use tokio::sync::mpsc;
use super::{
super::jobs::{HeldBy, QuestionState, SavedQuestion},
held_questions::Kept,
peer_wake::ask_of,
LoadedSession, Sessions,
};
use crate::{
app::{
peer_sessions::{PassedUp, Receipt},
self_questions::{Answer, AnswerInbox, Asked, Form, QuestionId, SelfQuestions},
session_runtime::{SessionRuntime, TurnControl},
},
tools::questionnaire_tool::{answer_content, form},
};
/// A session's side of its watcher.
pub(super) struct OwnQuestions {
questions: SelfQuestions,
/// Tells the session's hooks a question waits (#1721).
hooks: HookDispatcher,
/// Cancelled when the session is dropped.
dropped: CancellationToken,
}
impl OwnQuestions {
/// The questions the session `runtime` runs asks without waiting, when
/// it reports to its starter.
pub(super) fn of(runtime: &SessionRuntime) -> Option<Self> {
Some(Self {
questions: runtime.self_questions()?.clone(),
hooks: runtime.hooks(),
dropped: CancellationToken::new(),
})
}
/// Whether an answer waits for a turn or is still to come: the session
/// stays loaded meanwhile, so its open questions stay answerable.
pub(super) fn outstanding(&self) -> bool {
let answers = self.questions.answers();
answers.expecting() || answers.has_answers()
}
}
impl Drop for OwnQuestions {
fn drop(&mut self) {
self.dropped.cancel();
}
}
/// The questions a session's job kept open across a restart, counted open
/// and still to be opened as requests (see [`Sessions::watch_self_questions`]).
#[derive(Default)]
pub(super) struct Reopening(Vec<(QuestionId, Form, Option<HeldBy>)>);
/// The session's questions open in this daemon: the id their requests'
/// answers name, the question, and what it asks.
#[derive(Default)]
struct Opened(Vec<(HostInputId, QuestionId, String)>);
impl Sessions {
/// Takes back the questions `session` asked without waiting that its
/// job keeps: hands it each answer no turn took, and counts the rest
/// open, so the session does not settle as if nothing could wake it.
/// Call as the session is added, before anything reads whether it
/// settled; [`Self::watch_self_questions`] opens the rest.
pub(super) fn reopen_self_questions(&self, session: &LoadedSession) -> Reopening {
let Some(own) = &session.own_questions else {
return Reopening::default();
};
let answers = own.questions.answers();
let mut reopening = Reopening::default();
for SavedQuestion {
id,
arguments,
ask,
state,
} in self.jobs.questions_of(&session.job)
{
match state {
QuestionState::Answered { answer } => {
let receipt = closes(session, id);
let answer = Answer {
title: ask,
content: answer,
};
answers.restore_answer(answer, receipt);
}
QuestionState::Open { held_by } => match form(arguments) {
Ok(form) => {
answers.opened();
reopening.0.push((id, form, held_by));
}
// Checked as it was asked; a later daemon may read
// forms differently. Nothing could answer it now.
Err(_) => {
tracing::warn!(session = %session.id, "dropped a saved question that no longer reads as a form");
self.jobs.close_question(&session.job, &id);
}
},
}
}
reopening
}
/// Opens `reopening`, the questions [`Self::reopen_self_questions`]
/// took back, each under the holder it had, and starts the watcher that
/// takes `session`'s questions from now on. Call once, as the session
/// is added, holding no lock: it reads the loaded sessions.
pub(super) fn watch_self_questions(&self, session: &Arc<LoadedSession>, reopening: Reopening) {
let Some(own) = &session.own_questions else {
return;
};
let Some(asked) = own.questions.take_asked() else {
return;
};
// Where the session's input requests send the answers to its
// questions, as a turn's go to the turn.
let (control, answers) = mpsc::unbounded_channel();
let mut opened = Opened::default();
for (id, form, held_by) in reopening.0 {
let request = open(session, &control, &mut opened, id, &form);
self.restore_holder(session, request, held_by);
}
let watcher = take_questions(
Arc::downgrade(session),
Questions {
asked,
answers,
control,
opened,
},
own.questions.answers().clone(),
own.hooks.clone(),
);
let dropped = own.dropped.clone();
tokio::spawn(async move {
tokio::select! {
() = dropped.cancelled() => {}
() = watcher => {}
}
});
}
/// Gives question `request` of `asking`, opened again, back to the
/// session that held it, `held_by`, when that session is loaded, takes
/// notices, and may act on sessions; the person holds it otherwise.
/// Tells the holder of it, as it was told before the restart.
fn restore_holder(
&self,
asking: &Arc<LoadedSession>,
request: wire::InputRequestId,
held_by: Option<HeldBy>,
) {
let Some(HeldBy { session, passed_by }) = held_by else {
return;
};
let holder = self.loaded().get(&session).cloned();
let Some((holder, inbox)) = holder
.filter(|holder| self.jobs.may_act_on_sessions(&holder.job).is_ok())
.and_then(|holder| {
let inbox = holder.peer_wake.inbox()?.clone();
Some((holder, inbox))
})
else {
return;
};
let to = holder.peer_wake.owner();
let from = asking.feed.holder_of(request);
if from.as_ref() == Some(to) {
return;
}
// The job already saves this holder.
let moved = asking.give_held(&[request], from.as_ref(), Some(to), Kept::InMemory);
for (request, question) in &moved {
let passed_up = passed_by.as_ref().map(|by| PassedUp {
by: by.to_string(),
note: None,
});
inbox.tell_held(
asking.id.as_str(),
asking.feed.name(),
*request,
ask_of(question),
passed_up,
);
}
holder
.peer_wake
.hold_questions(asking, moved.into_iter().map(|(request, _)| request));
}
}
/// Opens `form` as question `id` of `session`, noting it in `opened`; its
/// answers go to `control`. Returns the request's id.
fn open(
session: &Arc<LoadedSession>,
control: &mpsc::UnboundedSender<TurnControl>,
opened: &mut Opened,
id: QuestionId,
form: &Form,
) -> wire::InputRequestId {
opened
.0
.push((form.request.id().clone(), id.clone(), form.ask.clone()));
session.change_inputs(|inputs| {
inputs.open_own_question(id, control, &form.request, SystemTime::now())
})
}
/// What runs once a turn of `session` took the answer to its question
/// `id`: the job no longer keeps it.
fn closes(session: &LoadedSession, id: QuestionId) -> Receipt {
let jobs = Arc::downgrade(&session.jobs);
let job = session.job.clone();
Receipt::new(move || {
if let Some(jobs) = jobs.upgrade() {
jobs.close_question(&job, &id);
}
})
}
/// A watcher's channels: the questions the session asks, and the answers
/// its requests send, with the end those requests send them on.
struct Questions {
asked: mpsc::UnboundedReceiver<Asked>,
answers: mpsc::UnboundedReceiver<TurnControl>,
control: mpsc::UnboundedSender<TurnControl>,
opened: Opened,
}
/// Saves and opens each question the session asks, and hands each answer
/// to `inbox`, the session's, until the session is gone.
async fn take_questions(
session: Weak<LoadedSession>,
questions: Questions,
inbox: AnswerInbox,
hooks: HookDispatcher,
) {
let Questions {
mut asked,
mut answers,
control,
mut opened,
} = questions;
loop {
tokio::select! {
asked = asked.recv() => {
let (Some(Asked { id, form }), Some(session)) = (asked, session.upgrade()) else {
return;
};
session.jobs.ask_question(&session.job, SavedQuestion {
id: id.clone(),
arguments: form.arguments.clone(),
ask: form.ask.clone(),
state: QuestionState::Open { held_by: None },
});
open(&session, &control, &mut opened, id, &form);
hooks.question_requested(&session.id, &form.request);
}
answer = answers.recv() => {
let (Some(answer), Some(session)) = (answer, session.upgrade()) else {
return;
};
answered(&session, &inbox, &mut opened, answer);
}
}
}
}
/// Hands `answer`, if it answers one of `opened`, to `inbox`, `session`'s:
/// saved on its job until a turn took it.
fn answered(
session: &LoadedSession,
inbox: &AnswerInbox,
opened: &mut Opened,
answer: TurnControl,
) {
let (id, answer) = match answer {
TurnControl::AnswerQuestion { id, answer } => (id, answer),
// Only questions are opened on this channel.
TurnControl::RespondApproval { .. }
| TurnControl::AnswerPlan { .. }
| TurnControl::AnswerSecret { .. }
| TurnControl::HostFailed { .. } => return,
};
let Some(at) = opened.0.iter().position(|(open, ..)| *open == id) else {
return;
};
let (_, question, ask) = opened.0.remove(at);
let content = match answer {
Ok(response) => answer_content(&response),
Err(refusal) => refused(refusal).to_owned(),
};
session
.jobs
.answer_saved_question(&session.job, &question, content.clone());
inbox.answered(
Answer {
title: ask,
content,
},
closes(session, question),
);
}
/// What the model reads of a question nobody answered.
fn refused(refusal: HostInputRefusal) -> &'static str {
match refusal {
HostInputRefusal::Declined => {
"The question was declined. Go on without its answer, or report what you need."
}
// `Dismissed`, and any refusal a newer SDK adds.
_ => "The question was dismissed unanswered. Go on without its answer, or report what you need.",
}
}
#[cfg(test)]
#[path = "self_questions_tests.rs"]
mod tests;