use serde::{Deserialize, Serialize};
use super::{persist, JobRecord, JobRegistry};
use crate::app::{daemon_host::jobs::JobId, self_questions::QuestionId};
#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)]
pub(in crate::app::daemon_host) struct SavedQuestion {
pub(in crate::app::daemon_host) id: QuestionId,
pub(in crate::app::daemon_host) arguments: serde_json::Value,
pub(in crate::app::daemon_host) ask: String,
#[serde(flatten)]
pub(in crate::app::daemon_host) state: QuestionState,
}
#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)]
#[serde(tag = "state", rename_all = "snake_case")]
pub(in crate::app::daemon_host) enum QuestionState {
Open {
#[serde(default, skip_serializing_if = "Option::is_none")]
held_by: Option<HeldBy>,
},
Answered { answer: String },
}
#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)]
pub(in crate::app::daemon_host) struct HeldBy {
pub(in crate::app::daemon_host) session: rho_sdk::SessionId,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub(in crate::app::daemon_host) passed_by: Option<rho_sdk::SessionId>,
}
impl JobRegistry {
pub(in crate::app::daemon_host) fn ask_question(&self, id: &JobId, question: SavedQuestion) {
self.change_questions(id, |questions| {
questions.push(question);
true
});
}
pub(in crate::app::daemon_host) fn hold_question(
&self,
id: &JobId,
question: &QuestionId,
held_by: Option<HeldBy>,
) {
self.change_questions(id, |questions| {
let Some(QuestionState::Open { held_by: saved }) =
find(questions, question).map(|saved| &mut saved.state)
else {
return false;
};
let changed = *saved != held_by;
*saved = held_by;
changed
});
}
pub(in crate::app::daemon_host) fn answer_saved_question(
&self,
id: &JobId,
question: &QuestionId,
answer: String,
) {
self.change_questions(id, |questions| {
find(questions, question).is_some_and(|saved| {
saved.state = QuestionState::Answered { answer };
true
})
});
}
pub(in crate::app::daemon_host) fn close_question(&self, id: &JobId, question: &QuestionId) {
self.change_questions(id, |questions| {
let before = questions.len();
questions.retain(|saved| saved.id != *question);
questions.len() != before
});
}
pub(in crate::app::daemon_host) fn questions_of(&self, id: &JobId) -> Vec<SavedQuestion> {
self.lock()
.get(id)
.map(|record| record.questions.clone())
.unwrap_or_default()
}
fn change_questions(&self, id: &JobId, change: impl FnOnce(&mut Vec<SavedQuestion>) -> bool) {
let mut jobs = self.lock();
if let Some(record) = jobs.get_mut(id) {
if change(&mut record.questions) {
persist(&self.store, record);
}
}
}
}
pub(super) fn waits_on(record: &JobRecord) -> Option<String> {
record
.questions
.iter()
.find(|saved| matches!(saved.state, QuestionState::Open { .. }))
.map(|saved| saved.ask.clone())
}
fn find<'a>(questions: &'a mut [SavedQuestion], id: &QuestionId) -> Option<&'a mut SavedQuestion> {
questions.iter_mut().find(|saved| saved.id == *id)
}
#[cfg(test)]
#[path = "registry_questions_tests.rs"]
mod tests;