|
| 1 | +//! The runner API's conformance: each response the service writes for a |
| 2 | +//! request its clients decode with `@githubnext/projections-schemas/runner` |
| 3 | +//! matches that response's schema in the generated |
| 4 | +//! `packages/schemas/internal/runner-api.json`, so the Rust service and the |
| 5 | +//! TypeScript decoders can't drift apart. |
| 6 | +//! |
| 7 | +//! It is stricter than the clients: a property the schema doesn't declare |
| 8 | +//! fails it unless the schema allows `additionalProperties`, so a field the |
| 9 | +//! service adds is declared, and typed, in the TypeBox source first. It |
| 10 | +//! supports only the keywords the generator writes and refuses any other, so |
| 11 | +//! a schema can't silently go unchecked. |
| 12 | +
|
| 13 | +use serde_json::{Map, Value, json}; |
| 14 | + |
| 15 | +const SCHEMA: &str = include_str!("../../../schemas/internal/runner-api.json"); |
| 16 | + |
| 17 | +/// The keywords the check applies, and the annotations it ignores. |
| 18 | +const KEYWORDS: &[&str] = &[ |
| 19 | + "type", |
| 20 | + "required", |
| 21 | + "properties", |
| 22 | + "additionalProperties", |
| 23 | + "items", |
| 24 | + "anyOf", |
| 25 | + "enum", |
| 26 | + "const", |
| 27 | + "minimum", |
| 28 | + "maximum", |
| 29 | + "title", |
| 30 | + "description", |
| 31 | + "x-request", |
| 32 | +]; |
| 33 | + |
| 34 | +/// Asserts that `value` is a valid `name` response (`adopt`, `explore`, …). |
| 35 | +pub(super) fn conforms(name: &str, value: &Value) { |
| 36 | + let problems = problems(name, value); |
| 37 | + assert!( |
| 38 | + problems.is_empty(), |
| 39 | + "the {name} response doesn't match its schema in packages/schemas/internal/runner-api.json:\n{}\n{value:#}", |
| 40 | + problems.join("\n") |
| 41 | + ); |
| 42 | +} |
| 43 | + |
| 44 | +/// Where and why `value` isn't a valid `name` response. |
| 45 | +fn problems(name: &str, value: &Value) -> Vec<String> { |
| 46 | + let schema: Value = serde_json::from_str(SCHEMA).unwrap(); |
| 47 | + let definition = &schema["$defs"][name]; |
| 48 | + assert!(definition.is_object(), "runner-api.json has no {name} response"); |
| 49 | + let mut problems = Vec::new(); |
| 50 | + check(definition, value, "", &mut problems); |
| 51 | + problems |
| 52 | +} |
| 53 | + |
| 54 | +fn check(schema: &Value, value: &Value, pointer: &str, problems: &mut Vec<String>) { |
| 55 | + let schema = schema.as_object().expect("a schema is an object"); |
| 56 | + if let Some(keyword) = schema.keys().find(|keyword| !KEYWORDS.contains(&keyword.as_str())) { |
| 57 | + panic!("the conformance check doesn't support {keyword} (at {pointer})"); |
| 58 | + } |
| 59 | + assert!( |
| 60 | + schema.get("type") == Some(&json!("object")) |
| 61 | + || !["properties", "required", "additionalProperties"] |
| 62 | + .iter() |
| 63 | + .any(|keyword| schema.contains_key(*keyword)), |
| 64 | + "the conformance check applies object keywords only with type object (at {pointer})" |
| 65 | + ); |
| 66 | + let at = if pointer.is_empty() { "the root" } else { pointer }; |
| 67 | + if let Some(alternatives) = schema.get("anyOf").and_then(Value::as_array) |
| 68 | + && !alternatives.iter().any(|alternative| { |
| 69 | + let mut nested = Vec::new(); |
| 70 | + check(alternative, value, pointer, &mut nested); |
| 71 | + nested.is_empty() |
| 72 | + }) |
| 73 | + { |
| 74 | + problems.push(format!("{at}: matches none of {}", Value::Array(alternatives.clone()))); |
| 75 | + } |
| 76 | + if let Some(kind) = schema.get("type").and_then(Value::as_str) |
| 77 | + && !is(kind, value) |
| 78 | + { |
| 79 | + problems.push(format!("{at}: {value} is not {kind}")); |
| 80 | + return; |
| 81 | + } |
| 82 | + if let Some(constant) = schema.get("const") |
| 83 | + && value != constant |
| 84 | + { |
| 85 | + problems.push(format!("{at}: {value} is not {constant}")); |
| 86 | + } |
| 87 | + if let Some(values) = schema.get("enum").and_then(Value::as_array) |
| 88 | + && !values.contains(value) |
| 89 | + { |
| 90 | + problems.push(format!("{at}: {value} is not one of {}", Value::Array(values.clone()))); |
| 91 | + } |
| 92 | + if let (Some(minimum), Some(number)) = (schema.get("minimum").and_then(Value::as_f64), value.as_f64()) |
| 93 | + && number < minimum |
| 94 | + { |
| 95 | + problems.push(format!("{at}: {number} is less than {minimum}")); |
| 96 | + } |
| 97 | + if let (Some(maximum), Some(number)) = (schema.get("maximum").and_then(Value::as_f64), value.as_f64()) |
| 98 | + && number > maximum |
| 99 | + { |
| 100 | + problems.push(format!("{at}: {number} is more than {maximum}")); |
| 101 | + } |
| 102 | + if let Some(object) = value.as_object() |
| 103 | + && schema.get("type") == Some(&json!("object")) |
| 104 | + { |
| 105 | + object_problems(schema, object, pointer, problems); |
| 106 | + } |
| 107 | + if let (Some(items), Some(array)) = (schema.get("items"), value.as_array()) { |
| 108 | + for (index, item) in array.iter().enumerate() { |
| 109 | + check(items, item, &format!("{pointer}/{index}"), problems); |
| 110 | + } |
| 111 | + } |
| 112 | +} |
| 113 | + |
| 114 | +fn object_problems(schema: &Map<String, Value>, object: &Map<String, Value>, pointer: &str, problems: &mut Vec<String>) { |
| 115 | + let at = if pointer.is_empty() { "the root" } else { pointer }; |
| 116 | + for name in schema.get("required").and_then(Value::as_array).into_iter().flatten() { |
| 117 | + let name = name.as_str().unwrap(); |
| 118 | + if !object.contains_key(name) { |
| 119 | + problems.push(format!("{at}: {name} is missing")); |
| 120 | + } |
| 121 | + } |
| 122 | + let empty = Map::new(); |
| 123 | + let properties = schema.get("properties").and_then(Value::as_object).unwrap_or(&empty); |
| 124 | + for (name, item) in object { |
| 125 | + let path = format!("{pointer}/{}", name.replace('~', "~0").replace('/', "~1")); |
| 126 | + match (properties.get(name), schema.get("additionalProperties")) { |
| 127 | + (Some(property), _) => check(property, item, &path, problems), |
| 128 | + (None, Some(Value::Bool(true))) => {} |
| 129 | + (None, Some(additional @ Value::Object(_))) => check(additional, item, &path, problems), |
| 130 | + (None, _) => problems.push(format!("{path}: is not declared in the schema")), |
| 131 | + } |
| 132 | + } |
| 133 | +} |
| 134 | + |
| 135 | +fn is(kind: &str, value: &Value) -> bool { |
| 136 | + match kind { |
| 137 | + "object" => value.is_object(), |
| 138 | + "array" => value.is_array(), |
| 139 | + "string" => value.is_string(), |
| 140 | + "boolean" => value.is_boolean(), |
| 141 | + "null" => value.is_null(), |
| 142 | + "number" => value.is_number(), |
| 143 | + "integer" => value.is_i64() || value.is_u64() || value.as_f64().is_some_and(|number| number.fract() == 0.0), |
| 144 | + _ => panic!("the conformance check doesn't support type {kind}"), |
| 145 | + } |
| 146 | +} |
| 147 | + |
| 148 | +#[test] |
| 149 | +fn the_conformance_check_refuses_malformed_nested_entries_and_undeclared_fields() { |
| 150 | + let preview = json!({"files": [], "digest": "sha256:00", "written": false}); |
| 151 | + assert_eq!(problems("adopt", &preview), Vec::<String>::new()); |
| 152 | + let mut nested = preview.clone(); |
| 153 | + nested["files"] = json!([null]); |
| 154 | + assert_eq!(problems("adopt", &nested), ["/files/0: null is not object"]); |
| 155 | + let mut undeclared = preview.clone(); |
| 156 | + undeclared["extra"] = json!(1); |
| 157 | + assert_eq!(problems("adopt", &undeclared), ["/extra: is not declared in the schema"]); |
| 158 | + // An opaque document is checked only by its envelope. |
| 159 | + let document = json!({"document": {"format": "projections.extraction", "version": 0, "extraction": {}}}); |
| 160 | + assert_eq!(problems("document", &document), Vec::<String>::new()); |
| 161 | +} |
0 commit comments