Skip to main content

hyprstream_decision_stub/
wire.rs

1//! The jev-1 wire envelope: `POST /v1/systemone` request → validated IR.
2//!
3//! The request body is `{state, model, questions}`. Parsing goes through
4//! [`hyprstream_decision::entry::Entry`] so insertion order survives (option order is
5//! canonical, D6) and validation is delegated to the P0.1a authoring layer — the facade
6//! enforces exactly the profile rules, nothing parallel.
7//!
8//! Error bodies mirror the FastAPI detail shape (S6a §6.1): 422 carries
9//! `{"detail": [{"loc": [...], "msg", "type"}]}`; other error statuses carry
10//! `{"detail": "<message>"}` (A10 — non-422 shapes are unspecified upstream).
11
12use hyprstream_decision::author;
13use hyprstream_decision::entry::Entry;
14use hyprstream_decision::error::SpecError;
15use hyprstream_decision::spec::QuestionSet;
16use serde::Serialize;
17
18/// A parsed, validated `SystemOneRequest`.
19#[derive(Debug, Clone)]
20pub struct WireRequest {
21    /// The shared state (required, non-null on the wire).
22    pub state: Entry,
23    /// The requested model string (alias or versioned id). Resolution happens at answer
24    /// time — the response echoes the resolved id.
25    pub model: String,
26    /// The validated question set (state included, questions in canonical order).
27    pub set: QuestionSet,
28}
29
30/// One FastAPI-style 422 detail item.
31#[derive(Debug, Clone, PartialEq, Serialize)]
32pub struct DetailItem {
33    /// Location of the offending element: `["body", <json-pointer>]`.
34    pub loc: Vec<String>,
35    /// Human-readable rule violation.
36    pub msg: String,
37    /// Machine-readable category (the P0.1a `SpecErrorKind` code, or `value_error`).
38    #[serde(rename = "type")]
39    pub error_type: String,
40}
41
42/// A facade error: an HTTP status plus a body that matches the documented error shapes.
43#[derive(Debug, Clone, PartialEq)]
44pub struct WireError {
45    /// HTTP status code (401, 422, …).
46    pub status: u16,
47    /// Serialized body. For 422 this is `{"detail": [DetailItem, …]}`; for anything else
48    /// `{"detail": "<msg>"}` (the FastAPI non-validation shape).
49    pub body: String,
50}
51
52impl WireError {
53    /// A FastAPI-style validation error (HTTP 422).
54    pub fn unprocessable(items: Vec<DetailItem>) -> Self {
55        #[derive(Serialize)]
56        struct DetailBody {
57            detail: Vec<DetailItem>,
58        }
59        let body = serde_json::to_string(&DetailBody { detail: items })
60            .unwrap_or_else(|_| r#"{"detail":[]}"#.to_owned());
61        Self { status: 422, body }
62    }
63
64    /// A non-validation error with the `{"detail": "<msg>"}` shape.
65    pub fn simple(status: u16, message: impl Into<String>) -> Self {
66        #[derive(Serialize)]
67        struct SimpleBody {
68            detail: String,
69        }
70        let body = serde_json::to_string(&SimpleBody {
71            detail: message.into(),
72        })
73        .unwrap_or_else(|_| r#"{"detail":"internal error"}"#.to_owned());
74        Self { status, body }
75    }
76
77    /// One-item 422 at a body-level location.
78    pub fn invalid(loc: Vec<String>, msg: impl Into<String>, error_type: &str) -> Self {
79        Self::unprocessable(vec![DetailItem {
80            loc,
81            msg: msg.into(),
82            error_type: error_type.to_owned(),
83        }])
84    }
85}
86
87fn body_loc(pointer: &str) -> Vec<String> {
88    vec!["body".to_owned(), pointer.to_owned()]
89}
90
91impl From<SpecError> for WireError {
92    fn from(error: SpecError) -> Self {
93        WireError::invalid(
94            body_loc(&error.path.to_string()),
95            error.message.clone(),
96            error.kind.code(),
97        )
98    }
99}
100
101/// Parse and validate a `POST /v1/systemone` request body.
102///
103/// Field rules: exactly `state` (required, non-null), `model` (required string),
104/// `questions` (required map, ≥ 1 entry); unknown fields are rejected (parity with the
105/// stock SDKs' `extra=forbid`). Question-level rules (D1–D6 cardinalities, reserved v2
106/// types, duplicate keys) come from the P0.1a authoring layer. Bare booleans/numbers in
107/// entry positions are accepted — see the crate docs for that profile decision.
108pub fn parse_request(body: &[u8]) -> Result<WireRequest, WireError> {
109    let root: Entry = serde_json::from_slice(body).map_err(|error| {
110        WireError::invalid(
111            vec!["body".to_owned()],
112            format!("request body is not valid JSON: {error}"),
113            "json_invalid",
114        )
115    })?;
116    let Entry::Map(fields) = &root else {
117        return Err(WireError::invalid(
118            vec!["body".to_owned()],
119            "request body must be a JSON object with `state`, `model`, and `questions`",
120            "structure",
121        ));
122    };
123    for (index, (key, _)) in fields.iter().enumerate() {
124        if fields[..index].iter().any(|(earlier, _)| earlier == key) {
125            return Err(WireError::invalid(
126                body_loc(&format!("/{key}")),
127                format!("duplicate key `{key}`"),
128                "duplicate_key",
129            ));
130        }
131    }
132
133    let mut state = None;
134    let mut model = None;
135    let mut questions = None;
136    for (key, value) in fields {
137        match key.as_str() {
138            "state" => state = Some(value),
139            "model" => model = Some(value),
140            "questions" => questions = Some(value),
141            other => {
142                return Err(WireError::invalid(
143                    body_loc(&format!("/{other}")),
144                    format!("unknown field `{other}`; the envelope accepts only `state`, `model`, and `questions`"),
145                    "unknown_field",
146                ));
147            }
148        }
149    }
150
151    let state = match state {
152        None => {
153            return Err(WireError::invalid(
154                body_loc("/state"),
155                "`state` is required",
156                "missing_field",
157            ));
158        }
159        Some(Entry::Null) => {
160            return Err(WireError::invalid(
161                body_loc("/state"),
162                "`state` must not be null",
163                "structure",
164            ));
165        }
166        Some(entry) => entry.clone(),
167    };
168    let model = match model {
169        Some(Entry::Str(name)) if !name.is_empty() => name.clone(),
170        Some(_) => {
171            return Err(WireError::invalid(
172                body_loc("/model"),
173                "`model` must be a non-empty string (alias or versioned id)",
174                "structure",
175            ));
176        }
177        None => {
178            return Err(WireError::invalid(
179                body_loc("/model"),
180                "`model` is required",
181                "missing_field",
182            ));
183        }
184    };
185    let questions = match questions {
186        Some(entry @ Entry::Map(_)) => entry.clone(),
187        Some(_) => {
188            return Err(WireError::invalid(
189                body_loc("/questions"),
190                "`questions` must be a mapping of question id to spec",
191                "structure",
192            ));
193        }
194        None => {
195            return Err(WireError::invalid(
196                body_loc("/questions"),
197                "`questions` is required",
198                "missing_field",
199            ));
200        }
201    };
202
203    // Delegate every question-level rule to the P0.1a authoring layer by re-serializing
204    // the (state, questions) pair as an authoring document. `Entry::canonical_text` of a
205    // map is compact JSON, and the re-parse preserves insertion order exactly.
206    let document = Entry::Map(vec![
207        ("state".to_owned(), state.clone()),
208        ("questions".to_owned(), questions),
209    ]);
210    let set = author::parse_json(&document.canonical_text())?;
211
212    Ok(WireRequest { state, model, set })
213}
214
215#[cfg(test)]
216#[allow(clippy::unwrap_used, clippy::expect_used)] // panicking is correct in unit tests
217mod tests {
218    use super::*;
219
220    #[test]
221    fn golden_request_parses() {
222        let body = br#"{
223            "state": "The refund arrived two weeks late and the box was crushed.",
224            "model": "jev-latest",
225            "questions": {
226                "is_refund": {"type": "noul", "instructions": "The customer wants money back."},
227                "tone": {"type": "choice", "criteria": {"angry": "Hostile message", "calm": null}},
228                "severity": {"type": "score", "criteria": ["cosmetic", "unusable"]}
229            }
230        }"#;
231        let request =
232            parse_request(body).unwrap_or_else(|error| panic!("golden request parses: {error:?}"));
233        assert_eq!(request.model, "jev-latest");
234        assert_eq!(request.set.questions.len(), 3);
235        assert_eq!(request.set.questions[1].id, "tone");
236        assert_eq!(request.set.questions[1].labels(), vec!["angry", "calm"]);
237    }
238
239    #[test]
240    fn bare_bool_and_number_entries_are_accepted() {
241        // The P0.7 profile decision (crate docs): superset scalars pass through as IR
242        // values, not strings, not errors.
243        let body = br#"{
244            "state": {"ticket": {"priority": 3, "paid": true}},
245            "model": "jev-latest",
246            "questions": {
247                "q": {"type": "noul", "instructions": {"threshold": 0.75, "strict": false}}
248            }
249        }"#;
250        let request =
251            parse_request(body).unwrap_or_else(|error| panic!("superset scalars parse: {error:?}"));
252        let question = &request.set.questions[0];
253        assert_eq!(
254            question
255                .instructions
256                .as_ref()
257                .map(hyprstream_decision::Entry::canonical_text),
258            Some(r#"{"threshold":0.75,"strict":false}"#.to_owned()),
259            "scalars stay scalars through the IR (no stringification)"
260        );
261    }
262
263    #[test]
264    fn unknown_top_level_field_is_422() {
265        let error = parse_request(
266            br#"{"state": "x", "model": "m", "questions": {"q": {"type": "noul"}}, "extra": 1}"#,
267        )
268        .unwrap_err();
269        assert_eq!(error.status, 422);
270        assert!(error.body.contains("unknown_field"), "{}", error.body);
271    }
272
273    #[test]
274    fn reserved_and_unknown_types_are_422() {
275        for (tag, code) in [
276            ("span", "reserved_question_type"),
277            ("bogus", "unknown_question_type"),
278        ] {
279            let body = format!(
280                r#"{{"state": "x", "model": "m", "questions": {{"q": {{"type": "{tag}"}}}}}}"#
281            );
282            let error = parse_request(body.as_bytes()).unwrap_err();
283            assert_eq!(error.status, 422);
284            assert!(error.body.contains(code), "{tag}: {}", error.body);
285        }
286    }
287
288    #[test]
289    fn profile_cardinalities_enforced() {
290        // 256 options exceeds the pinned 255 limit (D2/A4).
291        let options = (0..256)
292            .map(|i| format!(r#""opt{i}": null"#))
293            .collect::<Vec<_>>()
294            .join(",");
295        let body = format!(
296            r#"{{"state": "x", "model": "m", "questions": {{"q": {{"type": "choice", "criteria": {{{options}}}}}}}}}"#
297        );
298        let error = parse_request(body.as_bytes()).unwrap_err();
299        assert_eq!(error.status, 422);
300        assert!(error.body.contains("cardinality"), "{}", error.body);
301    }
302}