1use jsonschema::error::{TypeKind, ValidationErrorKind};
10use jsonschema::{Draft, Validator};
11use schedr_config::masked::{mask_text, names_secret_in_words};
12use schedr_model::Params;
13use schedr_model::params::{MAX_PARAMS_BYTES, duration_micros, to_stored};
14use serde_json::{Map, Value};
15
16#[cfg(test)]
17mod tests;
18
19const CHECKED: &[&str] = &[
22 "type",
23 "enum",
24 "const",
25 "multipleOf",
26 "maximum",
27 "exclusiveMaximum",
28 "minimum",
29 "exclusiveMinimum",
30 "maxLength",
31 "minLength",
32 "pattern",
33 "maxItems",
34 "minItems",
35 "uniqueItems",
36 "maxContains",
37 "minContains",
38 "maxProperties",
39 "minProperties",
40 "required",
41 "dependentRequired",
42 "allOf",
43 "anyOf",
44 "oneOf",
45 "not",
46 "if",
47 "then",
48 "else",
49 "dependentSchemas",
50 "prefixItems",
51 "items",
52 "contains",
53 "properties",
54 "patternProperties",
55 "additionalProperties",
56 "propertyNames",
57 "unevaluatedItems",
58 "unevaluatedProperties",
59 "format",
60 "$ref",
61 "$defs",
62 "definitions",
63];
64
65const ANNOTATIONS: &[&str] = &[
68 "$schema",
69 "$comment",
70 "title",
71 "description",
72 "default",
73 "examples",
74 "deprecated",
75 "readOnly",
76 "writeOnly",
77 "discriminator",
78];
79
80const FORMATS: &[&str] = &[
82 "date",
83 "date-time",
84 "time",
85 "duration",
86 "email",
87 "hostname",
88 "ipv4",
89 "ipv6",
90 "uri",
91 "uri-reference",
92 "iri",
93 "iri-reference",
94 "uri-template",
95 "uuid",
96 "json-pointer",
97 "relative-json-pointer",
98 "regex",
99];
100
101const ONE_SCHEMA: &[&str] = &[
103 "not",
104 "if",
105 "then",
106 "else",
107 "items",
108 "contains",
109 "additionalProperties",
110 "propertyNames",
111 "unevaluatedItems",
112 "unevaluatedProperties",
113];
114
115const SCHEMA_LIST: &[&str] = &["allOf", "anyOf", "oneOf", "prefixItems"];
117
118const SCHEMA_MAP: &[&str] = &[
120 "properties",
121 "patternProperties",
122 "dependentSchemas",
123 "$defs",
124 "definitions",
125];
126
127#[must_use]
130pub fn problems(params: &Params, scheduled: bool) -> Vec<String> {
131 let mut problems = Vec::new();
132 if !params.schema.is_object() {
133 return vec!["params: the schema isn't an object".to_owned()];
134 }
135 keyword_problems(¶ms.schema, "", &mut problems);
136 if !problems.is_empty() {
137 return problems;
138 }
139 if !matches!(
140 params.ty,
141 schedr_model::TypeDesc::Dataclass { .. } | schedr_model::TypeDesc::Model { .. }
142 ) {
143 problems.push("params: must be a dataclass or a Pydantic model".to_owned());
144 }
145 if scheduled
146 && let Some(missing) = required(¶ms.schema)
147 .into_iter()
148 .find(|name| !params.defaults.contains_key(*name))
149 {
150 problems.push(format!(
151 "params: `{missing}` has no default, but the DAG has a schedule (its runs use the \
152 defaults)"
153 ));
154 }
155 if let Err(why) = defaults_checked(params) {
156 problems.push(format!("params: the defaults: {why}"));
157 }
158 problems
159}
160
161fn required(schema: &Value) -> Vec<&str> {
163 fields_schema(schema)
164 .get("required")
165 .and_then(Value::as_array)
166 .map(|names| names.iter().filter_map(Value::as_str).collect())
167 .unwrap_or_default()
168}
169
170fn defaults_checked(params: &Params) -> Result<(), String> {
171 validator(¶ms.schema)?;
172 let size = Value::Object(params.defaults.clone()).to_string().len();
173 if size > MAX_PARAMS_BYTES {
174 return Err(over_limit(size));
175 }
176 for (name, value) in ¶ms.defaults {
179 let property = properties(¶ms.schema)
180 .and_then(|p| p.get(name))
181 .ok_or_else(|| format!("`{name}` isn't a field"))?;
182 let mut one = Map::new();
183 for defs in ["$defs", "definitions"] {
184 if let Some(found) = params.schema.get(defs) {
185 one.insert(defs.to_owned(), found.clone());
186 }
187 }
188 one.insert("properties".to_owned(), json_object(name, property.clone()));
189 check(
190 &validator(&Value::Object(one))?,
191 &json_object(name, value.clone()),
192 )?;
193 }
194 Ok(())
195}
196
197fn json_object(name: &str, value: Value) -> Value {
198 let mut map = Map::new();
199 map.insert(name.to_owned(), value);
200 Value::Object(map)
201}
202
203pub fn run_params(
211 params: Option<&Params>,
212 given: Option<&Map<String, Value>>,
213) -> Result<Value, String> {
214 let given = given.filter(|g| !g.is_empty());
215 let Some(params) = params else {
216 return match given {
217 Some(_) => Err("the DAG takes no parameters (it declares no `params=`)".to_owned()),
218 None => Ok(Value::Object(Map::new())),
219 };
220 };
221 let mut values = params.defaults.clone();
222 if let Some(given) = given {
223 let known = properties(¶ms.schema);
224 for (name, value) in given {
225 if !known.is_some_and(|k| k.contains_key(name)) {
226 let names = known
227 .map(|k| {
228 k.keys()
229 .map(|n| format!("`{n}`"))
230 .collect::<Vec<_>>()
231 .join(", ")
232 })
233 .unwrap_or_default();
234 return Err(format!(
236 "unknown parameter `{}` (the DAG takes {names})",
237 mask_text(name)
238 ));
239 }
240 values.insert(name.clone(), value.clone());
241 }
242 }
243 let values = Value::Object(values);
244 let size = values.to_string().len();
245 if size > MAX_PARAMS_BYTES {
246 return Err(over_limit(size));
247 }
248 check(&validator(¶ms.schema)?, &values)?;
249 to_stored(&values, ¶ms.ty).map_err(|misfit| {
251 if misfit.fields().any(names_secret_in_words) {
252 format!(
253 "`{}`: doesn't fit its type (the value isn't shown)",
254 mask_text(&misfit.at())
255 )
256 } else {
257 mask_text(&misfit.to_string())
259 }
260 })
261}
262
263fn fields_schema(schema: &Value) -> &Value {
266 schema
267 .get("$ref")
268 .and_then(Value::as_str)
269 .and_then(|r| r.strip_prefix('#'))
270 .and_then(|pointer| schema.pointer(pointer))
271 .unwrap_or(schema)
272}
273
274fn properties(schema: &Value) -> Option<&Map<String, Value>> {
276 fields_schema(schema)
277 .get("properties")
278 .and_then(Value::as_object)
279}
280
281fn over_limit(size: usize) -> String {
282 format!(
283 "the parameters are {size} bytes as JSON, over the limit of {} KiB",
284 MAX_PARAMS_BYTES / 1024
285 )
286}
287
288fn validator(schema: &Value) -> Result<Validator, String> {
289 jsonschema::options()
290 .with_draft(Draft::Draft202012)
291 .should_validate_formats(true)
292 .with_format("duration", is_duration)
295 .build(schema)
296 .map_err(|e| format!("the schema is invalid: {e}"))
297}
298
299fn check(validator: &Validator, values: &Value) -> Result<(), String> {
304 let reasons: Vec<String> = validator
305 .iter_errors(values)
306 .map(|e| {
307 let path = pointer_steps(&e.instance_path().to_string());
308 let at = path
309 .iter()
310 .map(|step| mask_text(step))
311 .collect::<Vec<_>>()
312 .join("/");
313 let reason = if path.iter().any(|step| names_secret_in_words(step)) {
314 "doesn't fit its schema (the value isn't shown)".to_owned()
315 } else {
316 reason(e.kind())
317 };
318 if at.is_empty() {
319 reason
320 } else {
321 format!("`{at}`: {reason}")
322 }
323 })
324 .collect();
325 if reasons.is_empty() {
326 Ok(())
327 } else {
328 Err(reasons.join("; "))
329 }
330}
331
332fn reason(kind: &ValidationErrorKind) -> String {
335 let names = |names: &[String]| {
336 names
337 .iter()
338 .map(|n| format!("`{}`", mask_text(n)))
339 .collect::<Vec<_>>()
340 .join(", ")
341 };
342 match kind {
343 ValidationErrorKind::Required { property } => match property.as_str() {
344 Some(name) => format!("`{}` is required", mask_text(name)),
345 None => "a required field is missing".to_owned(),
346 },
347 ValidationErrorKind::Type {
348 kind: TypeKind::Single(ty),
349 } => format!("not of type `{ty}`"),
350 ValidationErrorKind::Type { .. } => "not of any of its types".to_owned(),
351 ValidationErrorKind::Format { format } => format!("not of the format `{format}`"),
352 ValidationErrorKind::AdditionalProperties { unexpected }
353 | ValidationErrorKind::UnevaluatedProperties { unexpected } => {
354 format!("unknown fields {}", names(unexpected))
355 }
356 other => format!("doesn't fit the schema's `{}`", other.keyword()),
357 }
358}
359
360fn pointer_steps(pointer: &str) -> Vec<String> {
362 pointer
363 .split('/')
364 .skip(1)
365 .map(|step| step.replace("~1", "/").replace("~0", "~"))
366 .collect()
367}
368
369fn keyword_problems(schema: &Value, at: &str, problems: &mut Vec<String>) {
372 let Value::Object(object) = schema else {
373 if !schema.is_boolean() {
374 problems.push(format!(
375 "params: the schema at `{}` isn't a schema",
376 shown(at)
377 ));
378 }
379 return;
380 };
381 for (keyword, value) in object {
382 let here = format!("{at}/{keyword}");
383 if !CHECKED.contains(&keyword.as_str()) && !ANNOTATIONS.contains(&keyword.as_str()) {
384 problems.push(format!(
385 "params: the schema's keyword `{keyword}` (at `{}`) isn't one the master checks; \
386 remove it, or check it in the task",
387 shown(at)
388 ));
389 continue;
390 }
391 match keyword.as_str() {
392 "format" => {
393 if let Some(format) = value.as_str()
394 && !FORMATS.contains(&format)
395 {
396 problems.push(format!(
397 "params: the format `{format}` (at `{}`) isn't one the master checks \
398 ({}); use another type, or check it in the task",
399 shown(at),
400 FORMATS.join(", ")
401 ));
402 }
403 }
404 "$ref" => {
405 if !value.as_str().is_some_and(|r| r.starts_with('#')) {
406 problems.push(format!(
407 "params: `$ref` {value} (at `{}`) isn't within the schema; the master \
408 fetches nothing",
409 shown(at)
410 ));
411 }
412 }
413 "$schema" => {
414 if value.as_str().is_some_and(|s| !s.contains("2020-12")) {
415 problems.push(format!(
416 "params: `$schema` {value}: the master checks JSON Schema 2020-12"
417 ));
418 }
419 }
420 k if ONE_SCHEMA.contains(&k) => keyword_problems(value, &here, problems),
421 k if SCHEMA_LIST.contains(&k) => {
422 for (i, item) in value.as_array().into_iter().flatten().enumerate() {
423 keyword_problems(item, &format!("{here}/{i}"), problems);
424 }
425 }
426 k if SCHEMA_MAP.contains(&k) => {
427 for (name, item) in value.as_object().into_iter().flatten() {
428 keyword_problems(item, &format!("{here}/{name}"), problems);
429 }
430 }
431 _ => {}
432 }
433 }
434}
435
436fn is_duration(text: &str) -> bool {
439 duration_micros(text).is_ok()
440}
441
442fn shown(at: &str) -> &str {
443 if at.is_empty() { "/" } else { at }
444}