use rho_protocol::{
methods::{SessionAnswerQuestion, SessionAnswerQuestionByAgent},
ClientError, ErrorCode, InputRequestId, QuestionAnswer, QuestionAsk,
SessionAnswerQuestionByAgentParams, SessionAnswerQuestionParams, SessionId,
};
use super::{AnswerResult, Caller, ControlError, DaemonError, SessionControl};
use crate::app::question_choices::choice_value;
#[derive(Clone, Debug, PartialEq, Eq)]
pub(super) enum Answerer {
Session(SessionId),
Outside,
}
impl Answerer {
pub(super) fn of(caller: &Caller) -> Result<Self, ControlError> {
match (&caller.session, caller.depth) {
(Some(session), _) => Ok(Self::Session(session.clone())),
(None, 0) => Ok(Self::Outside),
(None, depth) => Err(ControlError::Invalid(format!(
"`answer` from a session at depth {depth} answers only the questions of sessions it started, through the `sessions` tool's `answer`"
))),
}
}
}
pub(super) fn by_choice_values(answer: QuestionAnswer, question: &QuestionAsk) -> QuestionAnswer {
let QuestionAnswer::Answers { answers } = answer else {
return answer;
};
let answers = answers
.into_iter()
.map(|(id, values)| {
let values = match question.questions.iter().find(|asked| asked.id == id) {
Some(asked) => values
.into_iter()
.map(|value| choice_value(asked, value))
.collect(),
None => values,
};
(id, values)
})
.collect();
QuestionAnswer::Answers { answers }
}
impl SessionControl {
pub(super) async fn answer(
&self,
session: SessionId,
request: InputRequestId,
answer: QuestionAnswer,
by: Answerer,
) -> Result<AnswerResult, ControlError> {
let answered = match by {
Answerer::Session(by) => self
.daemon
.request::<SessionAnswerQuestion>(&SessionAnswerQuestionParams {
session: session.clone(),
request,
answer,
by,
})
.await
.map(drop),
Answerer::Outside => {
self.daemon
.request::<SessionAnswerQuestionByAgent>(
&SessionAnswerQuestionByAgentParams::new(session.clone(), request, answer),
)
.await
.map(drop)
}
};
let code = match &answered {
Err(DaemonError::Request(ClientError::Rpc { error, .. })) => error.error_code(),
_ => None,
};
match (answered, code) {
(Ok(()), _) => Ok(AnswerResult { session }),
(Err(_), Some(ErrorCode::InputNotOpen)) => Err(not_open(&session, request)),
(Err(_), Some(ErrorCode::MethodNotFound)) => Err(ControlError::Invalid(
"the rho daemon on this machine predates answering a question here; upgrade rho and restart its daemon".into(),
)),
(Err(error), _) => Err(error.into()),
}
}
}
pub(super) fn not_open(session: &SessionId, request: InputRequestId) -> ControlError {
ControlError::Invalid(format!(
"input request {request} of session {session} is not open: it was already answered, it timed out, or its turn withdrew it"
))
}
#[cfg(test)]
#[path = "answer_tests.rs"]
mod tests;