Skip to main content

jev/
answer.rs

1//! `Answer`, `Answers`, and the checked accessors that turn a wire map into either a
2//! typed value or a named [`Error`].
3
4use indexmap::IndexMap;
5use serde::{
6    Deserialize, Serialize,
7    de::{self, Deserializer, MapAccess, Visitor},
8};
9use serde_json::Value;
10
11// `Answer` intentionally has no `Serialize` impl: its `Other` variant carries
12// arbitrary raw JSON under an unrecognized `type`, which a derived, internally
13// tagged `Serialize` cannot round-trip. Callers who need to re-emit an answer as
14// JSON should serialize the original response body instead.
15use crate::error::Error;
16use crate::guidance::Guidance;
17
18/// One answered question.
19///
20/// Deserialization dispatches on the wire `type` field. A `type` this SDK version
21/// does not recognize becomes [`Answer::Other`] instead of failing the whole
22/// response, so a new server-side primitive never breaks existing callers using the
23/// dynamic path (typed callers see [`Error::AnswerType`] if a field expects a known
24/// primitive and gets `Other`).
25#[derive(Debug, Clone, PartialEq)]
26pub enum Answer {
27    /// Answer to a `noul` question.
28    Noul(NoulAnswer),
29    /// Answer to a `choice` question.
30    Choice(ChoiceAnswer),
31    /// Answer to a `score` question.
32    Score(ScoreAnswer),
33    /// A primitive this SDK version does not know about.
34    Other {
35        /// The unrecognized wire `type` value.
36        r#type: String,
37        /// The raw JSON payload, preserved verbatim.
38        raw: Value,
39    },
40}
41
42impl Answer {
43    /// The wire name of this answer's primitive.
44    #[must_use]
45    pub fn kind(&self) -> String {
46        match self {
47            Answer::Noul(_) => "noul".to_string(),
48            Answer::Choice(_) => "choice".to_string(),
49            Answer::Score(_) => "score".to_string(),
50            Answer::Other { r#type, .. } => format!("other({type})"),
51        }
52    }
53}
54
55/// A `noul` answer: `P(yes)`.
56#[derive(Debug, Clone, Copy, PartialEq, Serialize)]
57pub struct NoulAnswer {
58    /// `P(yes)`, always finite and within `0.0..=1.0`.
59    pub noul: f64,
60}
61
62/// A `choice` answer.
63#[derive(Debug, Clone, PartialEq, Serialize)]
64pub struct ChoiceAnswer {
65    /// The option key the model selected.
66    pub choice: String,
67    /// Confidence in `choice`, when the server reports it.
68    pub confidence: Option<f64>,
69    /// Per-option probabilities. Empty, not absent, when the server omits them.
70    pub probabilities: IndexMap<String, f64>,
71}
72
73/// A `score` answer.
74#[derive(Debug, Clone, PartialEq, Serialize)]
75pub struct ScoreAnswer {
76    /// The continuous score, always finite and non-negative.
77    pub score: f64,
78    /// Confidence in `score`, when the server reports it.
79    pub confidence: Option<f64>,
80    /// Per-level probabilities. Empty, not absent, when the server omits them.
81    pub probabilities: IndexMap<String, f64>,
82    /// Per-level legend text, when the server echoes it back.
83    pub legend: IndexMap<String, Guidance>,
84}
85
86/// Validates that `v` is finite and within `0.0..=1.0`.
87fn validate_probability(field: &str, v: f64) -> Result<f64, Error> {
88    if !v.is_finite() || !(0.0..=1.0).contains(&v) {
89        return Err(Error::Parse(format!(
90            "`{field}` must be finite and within 0.0..=1.0, got {v}"
91        )));
92    }
93    Ok(v)
94}
95
96/// Validates that `v` is finite and non-negative.
97fn validate_score(v: f64) -> Result<f64, Error> {
98    if !v.is_finite() || v < 0.0 {
99        return Err(Error::Parse(format!(
100            "`score` must be finite and non-negative, got {v}"
101        )));
102    }
103    Ok(v)
104}
105
106/// Parses an optional confidence field, validating it as a probability when present.
107fn parse_confidence(obj: &serde_json::Map<String, Value>) -> Result<Option<f64>, Error> {
108    match obj.get("confidence") {
109        None | Some(Value::Null) => Ok(None),
110        Some(v) => {
111            let f = v
112                .as_f64()
113                .ok_or_else(|| Error::Parse("`confidence` must be a number".to_string()))?;
114            Ok(Some(validate_probability("confidence", f)?))
115        }
116    }
117}
118
119/// Parses a `probabilities` object into an ordered, range-checked map.
120fn parse_probabilities(
121    obj: &serde_json::Map<String, Value>,
122) -> Result<IndexMap<String, f64>, Error> {
123    match obj.get("probabilities") {
124        None | Some(Value::Null) => Ok(IndexMap::new()),
125        Some(Value::Object(map)) => {
126            let mut out = IndexMap::with_capacity(map.len());
127            for (k, v) in map {
128                let f = v
129                    .as_f64()
130                    .ok_or_else(|| Error::Parse(format!("`probabilities.{k}` must be a number")))?;
131                out.insert(
132                    k.clone(),
133                    validate_probability(&format!("probabilities.{k}"), f)?,
134                );
135            }
136            Ok(out)
137        }
138        Some(_) => Err(Error::Parse(
139            "`probabilities` must be an object".to_string(),
140        )),
141    }
142}
143
144/// Parses a `legend` object into an ordered map of [`Guidance`].
145fn parse_legend(obj: &serde_json::Map<String, Value>) -> Result<IndexMap<String, Guidance>, Error> {
146    match obj.get("legend") {
147        None | Some(Value::Null) => Ok(IndexMap::new()),
148        Some(Value::Object(map)) => Ok(map
149            .iter()
150            .map(|(k, v)| (k.clone(), Guidance::from(v.clone())))
151            .collect()),
152        Some(_) => Err(Error::Parse("`legend` must be an object".to_string())),
153    }
154}
155
156/// Parses one JSON object into a typed [`Answer`], dispatching on `type`.
157fn answer_from_value(value: Value) -> Result<Answer, Error> {
158    let Value::Object(obj) = value else {
159        return Err(Error::Parse("answer must be a JSON object".to_string()));
160    };
161    let r#type = obj
162        .get("type")
163        .and_then(Value::as_str)
164        .ok_or_else(|| Error::Parse("answer is missing a string `type` field".to_string()))?
165        .to_string();
166
167    match r#type.as_str() {
168        "noul" => {
169            let noul = obj.get("noul").and_then(Value::as_f64).ok_or_else(|| {
170                Error::Parse("`noul` answer is missing a numeric `noul` field".to_string())
171            })?;
172            Ok(Answer::Noul(NoulAnswer {
173                noul: validate_probability("noul", noul)?,
174            }))
175        }
176        "choice" => {
177            let choice = obj
178                .get("choice")
179                .and_then(Value::as_str)
180                .ok_or_else(|| {
181                    Error::Parse("`choice` answer is missing a string `choice` field".to_string())
182                })?
183                .to_string();
184            Ok(Answer::Choice(ChoiceAnswer {
185                choice,
186                confidence: parse_confidence(&obj)?,
187                probabilities: parse_probabilities(&obj)?,
188            }))
189        }
190        "score" => {
191            let score = obj.get("score").and_then(Value::as_f64).ok_or_else(|| {
192                Error::Parse("`score` answer is missing a numeric `score` field".to_string())
193            })?;
194            Ok(Answer::Score(ScoreAnswer {
195                score: validate_score(score)?,
196                confidence: parse_confidence(&obj)?,
197                probabilities: parse_probabilities(&obj)?,
198                legend: parse_legend(&obj)?,
199            }))
200        }
201        other => Ok(Answer::Other {
202            r#type: other.to_string(),
203            raw: Value::Object(obj),
204        }),
205    }
206}
207
208impl<'de> Deserialize<'de> for Answer {
209    fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
210    where
211        D: Deserializer<'de>,
212    {
213        let value = Value::deserialize(deserializer)?;
214        answer_from_value(value).map_err(de::Error::custom)
215    }
216}
217
218/// The full set of answers for one request: an ordered map of question key to
219/// [`Answer`].
220///
221/// # Examples
222///
223/// ```
224/// # fn main() -> Result<(), jev::Error> {
225/// let body = r#"{"refund": {"type": "noul", "noul": 0.87}}"#;
226/// let answers: jev::Answers = serde_json::from_str(body).unwrap();
227/// assert!(answers.noul("refund")? > 0.5);
228/// # Ok(())
229/// # }
230/// ```
231#[derive(Debug, Clone, PartialEq, Default)]
232pub struct Answers(IndexMap<String, Answer>);
233
234impl Answers {
235    /// Looks up an answer by key, without checking its primitive type.
236    #[must_use]
237    pub fn get(&self, key: &str) -> Option<&Answer> {
238        self.0.get(key)
239    }
240
241    /// The number of answers.
242    #[must_use]
243    pub fn len(&self) -> usize {
244        self.0.len()
245    }
246
247    /// Whether there are no answers.
248    #[must_use]
249    pub fn is_empty(&self) -> bool {
250        self.0.is_empty()
251    }
252
253    /// Iterates answers in the order the server returned them.
254    #[must_use]
255    pub fn iter(&self) -> indexmap::map::Iter<'_, String, Answer> {
256        self.0.iter()
257    }
258
259    /// Reads `key` as a `noul` answer's `P(yes)`.
260    ///
261    /// # Errors
262    ///
263    /// [`Error::MissingAnswer`] if `key` is absent; [`Error::AnswerType`] if present
264    /// but not a `noul` answer.
265    pub fn noul(&self, key: &str) -> Result<f64, Error> {
266        match self.get(key) {
267            None => Err(Error::MissingAnswer {
268                key: key.to_string(),
269            }),
270            Some(Answer::Noul(a)) => Ok(a.noul),
271            Some(other) => Err(Error::AnswerType {
272                key: key.to_string(),
273                expected: "noul",
274                actual: other.kind(),
275            }),
276        }
277    }
278
279    /// Reads `key` as a `choice` answer.
280    ///
281    /// # Errors
282    ///
283    /// [`Error::MissingAnswer`] if `key` is absent; [`Error::AnswerType`] if present
284    /// but not a `choice` answer.
285    pub fn choice(&self, key: &str) -> Result<&ChoiceAnswer, Error> {
286        match self.get(key) {
287            None => Err(Error::MissingAnswer {
288                key: key.to_string(),
289            }),
290            Some(Answer::Choice(a)) => Ok(a),
291            Some(other) => Err(Error::AnswerType {
292                key: key.to_string(),
293                expected: "choice",
294                actual: other.kind(),
295            }),
296        }
297    }
298
299    /// Reads `key` as a `score` answer.
300    ///
301    /// # Errors
302    ///
303    /// [`Error::MissingAnswer`] if `key` is absent; [`Error::AnswerType`] if present
304    /// but not a `score` answer.
305    pub fn score(&self, key: &str) -> Result<&ScoreAnswer, Error> {
306        match self.get(key) {
307            None => Err(Error::MissingAnswer {
308                key: key.to_string(),
309            }),
310            Some(Answer::Score(a)) => Ok(a),
311            Some(other) => Err(Error::AnswerType {
312                key: key.to_string(),
313                expected: "score",
314                actual: other.kind(),
315            }),
316        }
317    }
318}
319
320impl<'de> Deserialize<'de> for Answers {
321    fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
322    where
323        D: Deserializer<'de>,
324    {
325        struct AnswersVisitor;
326
327        impl<'de> Visitor<'de> for AnswersVisitor {
328            type Value = Answers;
329
330            fn expecting(&self, formatter: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
331                formatter.write_str("a map of question key to answer")
332            }
333
334            fn visit_map<M>(self, mut map: M) -> Result<Self::Value, M::Error>
335            where
336                M: MapAccess<'de>,
337            {
338                let mut out = IndexMap::with_capacity(map.size_hint().unwrap_or(0));
339                while let Some((key, answer)) = map.next_entry::<String, Answer>()? {
340                    out.insert(key, answer);
341                }
342                Ok(Answers(out))
343            }
344        }
345
346        deserializer.deserialize_map(AnswersVisitor)
347    }
348}
349
350impl<'a> IntoIterator for &'a Answers {
351    type Item = (&'a String, &'a Answer);
352    type IntoIter = indexmap::map::Iter<'a, String, Answer>;
353
354    fn into_iter(self) -> Self::IntoIter {
355        self.0.iter()
356    }
357}
358
359#[cfg(test)]
360mod tests {
361    use serde_json::json;
362
363    use super::*;
364
365    #[test]
366    fn test_should_deserialize_noul_answer() {
367        let answers: Answers = serde_json::from_value(json!({
368            "refund": {"type": "noul", "noul": 0.87}
369        }))
370        .unwrap();
371        assert_eq!(answers.noul("refund").unwrap(), 0.87);
372    }
373
374    #[test]
375    fn test_should_deserialize_choice_answer_with_probabilities() {
376        let answers: Answers = serde_json::from_value(json!({
377            "team": {
378                "type": "choice",
379                "choice": "payments",
380                "confidence": 0.9,
381                "probabilities": {"payments": 0.9, "frontend": 0.1}
382            }
383        }))
384        .unwrap();
385        let choice = answers.choice("team").unwrap();
386        assert_eq!(choice.choice, "payments");
387        assert_eq!(choice.confidence, Some(0.9));
388        assert_eq!(choice.probabilities.get("payments"), Some(&0.9));
389    }
390
391    #[test]
392    fn test_should_deserialize_score_answer_with_legend() {
393        let answers: Answers = serde_json::from_value(json!({
394            "urgency": {
395                "type": "score",
396                "score": 1.7,
397                "legend": {"0": "Low", "1": "High"}
398            }
399        }))
400        .unwrap();
401        let score = answers.score("urgency").unwrap();
402        assert_eq!(score.score, 1.7);
403        assert_eq!(
404            score.legend.get("1").and_then(Guidance::as_str),
405            Some("High")
406        );
407    }
408
409    #[test]
410    fn test_should_default_probabilities_and_legend_to_empty_map_not_option() {
411        let answers: Answers =
412            serde_json::from_value(json!({"team": {"type": "choice", "choice": "x"}})).unwrap();
413        let choice = answers.choice("team").unwrap();
414        assert!(choice.probabilities.is_empty());
415    }
416
417    #[test]
418    fn test_should_map_unknown_type_to_other_instead_of_failing() {
419        let answers: Answers = serde_json::from_value(json!({
420            "future": {"type": "vibe", "vibe": "great"}
421        }))
422        .unwrap();
423        match answers.get("future").unwrap() {
424            Answer::Other { r#type, raw } => {
425                assert_eq!(r#type, "vibe");
426                assert_eq!(raw["vibe"], "great");
427            }
428            other => panic!("expected Other, got {other:?}"),
429        }
430    }
431
432    #[test]
433    fn test_should_reject_nan_noul_probability() {
434        let result: Result<Answers, _> =
435            serde_json::from_value(json!({"refund": {"type": "noul", "noul": f64::NAN}}));
436        assert!(result.is_err());
437    }
438
439    #[test]
440    fn test_should_reject_out_of_range_probability() {
441        let result: Result<Answers, _> =
442            serde_json::from_value(json!({"refund": {"type": "noul", "noul": 1.5}}));
443        assert!(result.is_err());
444
445        let result: Result<Answers, _> =
446            serde_json::from_value(json!({"refund": {"type": "noul", "noul": -0.1}}));
447        assert!(result.is_err());
448    }
449
450    #[test]
451    fn test_should_reject_negative_score() {
452        let result: Result<Answers, _> =
453            serde_json::from_value(json!({"urgency": {"type": "score", "score": -1.0}}));
454        assert!(result.is_err());
455    }
456
457    #[test]
458    fn test_should_reject_out_of_range_choice_probability() {
459        let result: Result<Answers, _> = serde_json::from_value(json!({
460            "team": {"type": "choice", "choice": "x", "probabilities": {"x": 2.0}}
461        }));
462        assert!(result.is_err());
463    }
464
465    #[test]
466    fn test_should_return_missing_answer_error_for_absent_key() {
467        let answers = Answers::default();
468        assert!(matches!(
469            answers.noul("missing"),
470            Err(Error::MissingAnswer { .. })
471        ));
472    }
473
474    #[test]
475    fn test_should_return_answer_type_error_for_type_mismatch() {
476        let answers: Answers =
477            serde_json::from_value(json!({"team": {"type": "choice", "choice": "x"}})).unwrap();
478        match answers.noul("team") {
479            Err(Error::AnswerType {
480                expected, actual, ..
481            }) => {
482                assert_eq!(expected, "noul");
483                assert_eq!(actual, "choice");
484            }
485            other => panic!("expected AnswerType error, got {other:?}"),
486        }
487    }
488}