hyprstream_decision_stub/
wire.rs1use hyprstream_decision::author;
13use hyprstream_decision::entry::Entry;
14use hyprstream_decision::error::SpecError;
15use hyprstream_decision::spec::QuestionSet;
16use serde::Serialize;
17
18#[derive(Debug, Clone)]
20pub struct WireRequest {
21 pub state: Entry,
23 pub model: String,
26 pub set: QuestionSet,
28}
29
30#[derive(Debug, Clone, PartialEq, Serialize)]
32pub struct DetailItem {
33 pub loc: Vec<String>,
35 pub msg: String,
37 #[serde(rename = "type")]
39 pub error_type: String,
40}
41
42#[derive(Debug, Clone, PartialEq)]
44pub struct WireError {
45 pub status: u16,
47 pub body: String,
50}
51
52impl WireError {
53 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 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 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
101pub 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 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)] mod 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 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 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}