1use serde_json::Value;
34use std::collections::HashMap;
35
36use crate::state::{State, StateSchema};
37
38use super::error::FunctionalError;
39
40#[derive(Debug, Clone, Copy, PartialEq, Eq)]
45pub enum ExpectedType {
46 Null,
48 Boolean,
50 Number,
52 String,
54 Array,
56 Object,
58}
59
60impl ExpectedType {
61 pub fn matches(&self, value: &Value) -> bool {
63 match self {
64 ExpectedType::Null => value.is_null(),
65 ExpectedType::Boolean => value.is_boolean(),
66 ExpectedType::Number => value.is_number(),
67 ExpectedType::String => value.is_string(),
68 ExpectedType::Array => value.is_array(),
69 ExpectedType::Object => value.is_object(),
70 }
71 }
72
73 pub fn type_name(&self) -> &'static str {
75 match self {
76 ExpectedType::Null => "null",
77 ExpectedType::Boolean => "boolean",
78 ExpectedType::Number => "number",
79 ExpectedType::String => "string",
80 ExpectedType::Array => "array",
81 ExpectedType::Object => "object",
82 }
83 }
84}
85
86impl std::fmt::Display for ExpectedType {
87 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
88 write!(f, "{}", self.type_name())
89 }
90}
91
92fn value_type_name(value: &Value) -> &'static str {
94 match value {
95 Value::Null => "null",
96 Value::Bool(_) => "boolean",
97 Value::Number(_) => "number",
98 Value::String(_) => "string",
99 Value::Array(_) => "array",
100 Value::Object(_) => "object",
101 }
102}
103
104#[derive(Clone)]
126pub struct StateSchemaValidator {
127 schema: StateSchema,
129 type_expectations: HashMap<String, ExpectedType>,
131 required_fields: Vec<String>,
133}
134
135impl std::fmt::Debug for StateSchemaValidator {
136 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
137 f.debug_struct("StateSchemaValidator")
138 .field("type_expectations", &self.type_expectations)
139 .field("required_fields", &self.required_fields)
140 .finish_non_exhaustive()
141 }
142}
143
144impl StateSchemaValidator {
145 pub fn new(schema: StateSchema) -> Self {
147 Self { schema, type_expectations: HashMap::new(), required_fields: Vec::new() }
148 }
149
150 pub fn expect_type(mut self, field: &str, expected: ExpectedType) -> Self {
155 self.type_expectations.insert(field.to_string(), expected);
156 self
157 }
158
159 pub fn require_field(mut self, field: &str) -> Self {
164 if !self.required_fields.contains(&field.to_string()) {
165 self.required_fields.push(field.to_string());
166 }
167 self
168 }
169
170 pub fn schema(&self) -> &StateSchema {
172 &self.schema
173 }
174
175 pub fn validate_state(&self, state: &State) -> Result<(), FunctionalError> {
185 for field in &self.required_fields {
187 if !state.contains_key(field) {
188 return Err(FunctionalError::SchemaValidation {
189 field: field.clone(),
190 expected: "present".to_string(),
191 actual: "missing".to_string(),
192 });
193 }
194 }
195
196 for (field, expected_type) in &self.type_expectations {
198 if let Some(value) = state.get(field)
199 && !expected_type.matches(value)
200 {
201 return Err(FunctionalError::SchemaValidation {
202 field: field.clone(),
203 expected: expected_type.type_name().to_string(),
204 actual: value_type_name(value).to_string(),
205 });
206 }
207 }
208
209 Ok(())
210 }
211
212 pub fn validate_task_output(&self, output: &State) -> Result<(), FunctionalError> {
227 for (field, value) in output {
228 if let Some(expected_type) = self.type_expectations.get(field)
229 && !expected_type.matches(value)
230 {
231 return Err(FunctionalError::SchemaValidation {
232 field: field.clone(),
233 expected: expected_type.type_name().to_string(),
234 actual: value_type_name(value).to_string(),
235 });
236 }
237 }
238
239 Ok(())
240 }
241
242 pub fn apply_update(&self, state: &mut State, key: &str, value: Value) {
246 self.schema.apply_update(state, key, value);
247 }
248}
249
250impl Default for StateSchemaValidator {
251 fn default() -> Self {
252 Self::new(StateSchema::default())
253 }
254}
255
256#[cfg(test)]
257mod tests {
258 use super::*;
259 use serde_json::json;
260
261 #[test]
262 fn test_validate_state_passes_with_correct_types() {
263 let schema = StateSchema::builder().channel("name").counter_channel("count").build();
264
265 let validator = StateSchemaValidator::new(schema)
266 .expect_type("name", ExpectedType::String)
267 .expect_type("count", ExpectedType::Number)
268 .require_field("name");
269
270 let mut state = State::new();
271 state.insert("name".to_string(), json!("workflow_1"));
272 state.insert("count".to_string(), json!(0));
273
274 assert!(validator.validate_state(&state).is_ok());
275 }
276
277 #[test]
278 fn test_validate_state_fails_on_missing_required_field() {
279 let validator =
280 StateSchemaValidator::new(StateSchema::default()).require_field("required_field");
281
282 let state = State::new();
283
284 let err = validator.validate_state(&state).unwrap_err();
285 match err {
286 FunctionalError::SchemaValidation { field, expected, actual } => {
287 assert_eq!(field, "required_field");
288 assert_eq!(expected, "present");
289 assert_eq!(actual, "missing");
290 }
291 _ => panic!("unexpected error variant"),
292 }
293 }
294
295 #[test]
296 fn test_validate_state_fails_on_type_mismatch() {
297 let validator = StateSchemaValidator::new(StateSchema::default())
298 .expect_type("count", ExpectedType::Number);
299
300 let mut state = State::new();
301 state.insert("count".to_string(), json!("not_a_number"));
302
303 let err = validator.validate_state(&state).unwrap_err();
304 match err {
305 FunctionalError::SchemaValidation { field, expected, actual } => {
306 assert_eq!(field, "count");
307 assert_eq!(expected, "number");
308 assert_eq!(actual, "string");
309 }
310 _ => panic!("unexpected error variant"),
311 }
312 }
313
314 #[test]
315 fn test_validate_task_output_passes_with_correct_types() {
316 let validator = StateSchemaValidator::new(StateSchema::default())
317 .expect_type("result", ExpectedType::Object)
318 .expect_type("score", ExpectedType::Number);
319
320 let mut output = State::new();
321 output.insert("result".to_string(), json!({"key": "value"}));
322 output.insert("score".to_string(), json!(95));
323
324 assert!(validator.validate_task_output(&output).is_ok());
325 }
326
327 #[test]
328 fn test_validate_task_output_fails_on_type_mismatch() {
329 let validator = StateSchemaValidator::new(StateSchema::default())
330 .expect_type("items", ExpectedType::Array);
331
332 let mut output = State::new();
333 output.insert("items".to_string(), json!("not_an_array"));
334
335 let err = validator.validate_task_output(&output).unwrap_err();
336 match err {
337 FunctionalError::SchemaValidation { field, expected, actual } => {
338 assert_eq!(field, "items");
339 assert_eq!(expected, "array");
340 assert_eq!(actual, "string");
341 }
342 _ => panic!("unexpected error variant"),
343 }
344 }
345
346 #[test]
347 fn test_validate_state_skips_absent_optional_fields() {
348 let validator = StateSchemaValidator::new(StateSchema::default())
349 .expect_type("optional_field", ExpectedType::String);
350
351 let state = State::new();
353 assert!(validator.validate_state(&state).is_ok());
354 }
355
356 #[test]
357 fn test_validate_task_output_ignores_unknown_fields() {
358 let validator = StateSchemaValidator::new(StateSchema::default())
359 .expect_type("known", ExpectedType::Number);
360
361 let mut output = State::new();
362 output.insert("known".to_string(), json!(42));
363 output.insert("unknown".to_string(), json!("anything"));
364
365 assert!(validator.validate_task_output(&output).is_ok());
367 }
368
369 #[test]
370 fn test_expected_type_matches() {
371 assert!(ExpectedType::Null.matches(&json!(null)));
372 assert!(ExpectedType::Boolean.matches(&json!(true)));
373 assert!(ExpectedType::Number.matches(&json!(42)));
374 assert!(ExpectedType::Number.matches(&json!(1.5)));
375 assert!(ExpectedType::String.matches(&json!("hello")));
376 assert!(ExpectedType::Array.matches(&json!([1, 2, 3])));
377 assert!(ExpectedType::Object.matches(&json!({"key": "value"})));
378
379 assert!(!ExpectedType::Number.matches(&json!("42")));
380 assert!(!ExpectedType::String.matches(&json!(42)));
381 assert!(!ExpectedType::Array.matches(&json!({})));
382 }
383}