1use std::collections::{BTreeMap, BTreeSet};
10use std::path::{Component, Path};
11
12use schedr_model::runner::{ErrorSummary, ParsedFile};
13use schedr_model::task::{CleanupRun, Task, WaitSource};
14use schedr_model::value::DagCtxField;
15use schedr_model::{
16 CommandLine, Dag, DagId, EdgeKind, Expand, Reference, ResourceRole, SchedrVersion, SecretDecl,
17 SensorMode, TaskId, TaskKind, Template, TemplatePart, TypeDesc, Value,
18};
19
20use crate::fire_times::FireTimes;
21use crate::mapping;
22
23#[cfg(test)]
24mod tests;
25
26pub const INVALID_DAG_EXCEPTION: &str = schedr_model::runner::INVALID_DAG_EXCEPTION;
28
29pub const INVALID_PATH_EXCEPTION: &str = schedr_model::runner::INVALID_PATH_EXCEPTION;
31
32fn memory_problem(task: &schedr_model::Task) -> Option<String> {
36 use schedr_model::TaskKind;
37 let settings = &task.settings;
38 let own = matches!(
39 task.kind,
40 TaskKind::Python { .. } | TaskKind::Command { .. } | TaskKind::Script { .. }
41 );
42 if !own && (settings.memory_bytes.is_some() || settings.hard_memory_limit) {
43 return Some(
44 "only a task running its own process has a memory budget (a wait step shares its \
45 host's, `[watchers] memory_budget`)"
46 .to_owned(),
47 );
48 }
49 match settings.memory_bytes {
50 Some(bytes) if bytes < MIN_TASK_MEMORY => {
51 Some(format!("memory_bytes must be at least 16 MiB, got {bytes}"))
52 }
53 None if settings.hard_memory_limit => {
54 Some("hard_memory_limit needs memory_bytes, the cap".to_owned())
55 }
56 _ => None,
57 }
58}
59
60const MIN_TASK_MEMORY: u64 = 16 << 20;
62
63#[must_use]
65pub fn dag_problems(dag: &Dag, root: &str, path: &str, master: SchedrVersion) -> Vec<String> {
66 let mut problems = Vec::new();
67 if !master.can_read(dag.produced_by) {
68 problems.push(format!(
69 "produced by schedr {}, which this master (schedr {master}) can't read",
70 dag.produced_by
71 ));
72 }
73 if dag.location.root != root || dag.location.path != path {
74 problems.push(format!(
75 "located at {}:{} in its DAG JSON, but parsed from {root}:{path}",
76 dag.location.root, dag.location.path
77 ));
78 }
79 if let Err(error) = FireTimes::new(&dag.trigger) {
80 problems.push(format!("trigger: {error}"));
81 }
82 if dag.max_active_runs == Some(0) {
83 problems.push("max_active_runs must be at least 1".to_owned());
84 }
85 if dag.max_active_tasks == Some(0) {
86 problems.push("max_active_tasks must be at least 1".to_owned());
87 }
88 for task in &dag.tasks {
89 for (name, limit) in [
90 ("max_active", task.settings.max_active),
91 ("max_active_per_run", task.settings.max_active_per_run),
92 ] {
93 if limit == Some(0) {
94 problems.push(format!("task `{}`: {name} must be at least 1", task.id));
95 }
96 }
97 if let Some(problem) = memory_problem(task) {
98 problems.push(format!("task `{}`: {problem}", task.id));
99 }
100 }
101 if let (Some(start), Some(end)) = (dag.trigger.start(), dag.trigger.end())
102 && start > end
103 {
104 problems.push(format!("start ({start}) is after end ({end})"));
105 }
106 let mut seen = BTreeSet::new();
107 for task in &dag.tasks {
108 if !seen.insert(&task.id) {
109 problems.push(format!("task `{}` is defined more than once", task.id));
110 }
111 }
112 if let Some(params) = &dag.params {
113 let scheduled = !matches!(
115 dag.trigger,
116 schedr_model::Trigger::None | schedr_model::Trigger::Chained { .. }
117 );
118 problems.extend(crate::params::problems(params, scheduled));
119 }
120 group_problems(dag, &mut problems);
121 expand_problems(dag, &mut problems);
122 param_problems(dag, &mut problems);
123 shell_problems(dag, &mut problems);
124 secret_problems(dag, &mut problems);
125 event_problems(dag, &mut problems);
126 edge_problems(dag, &seen, &mut problems);
127 reference_problems(dag, &seen, &mut problems);
128 first_of_problems(dag, &mut problems);
129 resource_problems(dag, &seen, &mut problems);
130 role_problems(dag, &mut problems);
131 if let Some(cycle) = cycle(dag, &seen) {
132 let names: Vec<String> = cycle.iter().map(|id| format!("`{id}`")).collect();
133 problems.push(format!(
134 "the tasks {} depend on each other in a cycle",
135 names.join(", ")
136 ));
137 }
138 problems
139}
140
141fn run_of_trigger_problems(
144 dag: &Dag,
145 run_of: &schedr_model::task::RunOf,
146 problems: &mut Vec<String>,
147) {
148 if run_of.dag == dag.id {
149 problems.push(format!(
150 "DAG `{}`: its trigger is a run of itself, which would start it for ever",
151 dag.id
152 ));
153 }
154 if let Some(why) = lag_problem(run_of) {
155 problems.push(format!("DAG `{}`: {why}", dag.id));
156 }
157 if run_of.lag_ms.is_some_and(|lag| lag < 0) {
158 problems.push(format!(
159 "DAG `{}`: a RunOf trigger's `lag` can't be negative: a run can't be planned \
160 before the one starting it",
161 dag.id
162 ));
163 }
164}
165
166fn chained_trigger_problems(dag: &Dag, by: &[DagId], problems: &mut Vec<String>) {
169 if by.is_empty() {
170 problems.push(format!(
171 "DAG `{}`: `Chained(by=[])` names no DAG to start it; `Chained()` is any DAG",
172 dag.id
173 ));
174 }
175 if by.contains(&dag.id) {
176 problems.push(format!(
177 "DAG `{}`: `Chained(by=...)` names the DAG itself, which can't start its own runs",
178 dag.id
179 ));
180 }
181}
182
183fn lag_problem(run_of: &schedr_model::task::RunOf) -> Option<String> {
185 run_of
186 .lag_ms
187 .filter(|lag| lag.unsigned_abs() > schedr_model::task::MAX_LAG_MS.unsigned_abs())
188 .map(|lag| format!("RunOf's `lag` is at most 10 years either way, got {lag} ms"))
189}
190
191fn event_problems(dag: &Dag, problems: &mut Vec<String>) {
194 let schedr_model::Trigger::Event {
195 task,
196 restart_if_idle_ms,
197 run_retries,
198 ..
199 } = &dag.trigger
200 else {
201 if let schedr_model::Trigger::RunOf { run_of } = &dag.trigger {
202 run_of_trigger_problems(dag, run_of, problems);
203 return;
204 }
205 if let schedr_model::Trigger::Chained { by: Some(by) } = &dag.trigger {
206 chained_trigger_problems(dag, by, problems);
207 }
208 if let schedr_model::Trigger::EventNamed { event } = &dag.trigger {
209 if event.key.is_some() {
210 problems.push(format!(
211 "DAG `{}`: an EventNamed trigger takes no `key`: it starts a run per event \
212 of its name, each keyed by its own",
213 dag.id
214 ));
215 }
216 return;
217 }
218 for task in &dag.tasks {
219 let reads = task.references().into_iter().any(|reference| {
220 matches!(
221 reference,
222 Reference::DagCtx {
223 field: DagCtxField::EventKey
224 | DagCtxField::EventData
225 | DagCtxField::EventAt
226 }
227 )
228 });
229 if reads {
230 problems.push(format!(
231 "task `{}` uses dag_ctx.event, but no event trigger starts the DAG's runs",
232 task.id
233 ));
234 }
235 }
236 return;
237 };
238 let id = &task.id;
239 if !matches!(task.kind, TaskKind::Sensor { .. }) {
240 problems.push(format!("trigger `{id}`: its function must be a sensor's"));
241 }
242 if !task.references().is_empty() {
243 problems.push(format!(
244 "trigger `{id}`: its arguments must be literals, as no run exists yet"
245 ));
246 }
247 if dag.tasks.iter().any(|other| &other.id == id) {
248 problems.push(format!("trigger `{id}` has the name of a task of the DAG"));
249 }
250 if *restart_if_idle_ms == Some(0) {
251 problems.push(format!(
252 "trigger `{id}`: restart_if_idle must be more than zero"
253 ));
254 }
255 if let TaskKind::Sensor {
256 mode,
257 batch_ms: Some(batch),
258 ..
259 } = &task.kind
260 {
261 batch_problems(id, *mode, *batch, problems);
262 }
263 trigger_wait_for_problems(
264 dag,
265 task,
266 restart_if_idle_ms.is_some(),
267 *run_retries,
268 problems,
269 );
270 for declared in &task.secrets {
271 if let Err(error) = declared.check() {
272 problems.push(format!("trigger `{id}`: secrets=: {error}"));
273 }
274 }
275 for name in &task.connections {
276 if let Err(error) = TaskId::new(name) {
277 problems.push(format!("trigger `{id}`: connections=: `{name}`: {error}"));
278 }
279 }
280}
281
282fn shell_problems(dag: &Dag, problems: &mut Vec<String>) {
285 for task in &dag.tasks {
286 if let TaskKind::Command {
287 command: CommandLine::Shell(template),
288 ..
289 } = &task.kind
290 && template.0.iter().any(|p| matches!(p, TemplatePart::Ref(_)))
291 {
292 problems.push(format!(
293 "task `{}`: a shell command takes no placeholders (the shell would read a value \
294 as code): pass values as arguments or in `env`",
295 task.id
296 ));
297 }
298 }
299}
300
301fn cleanup_problem(task: &Task) -> Option<String> {
303 let id = &task.id;
304 let run = &task.cleanup.as_ref()?.run;
305 match (&task.kind, run) {
306 (TaskKind::Sensor { .. }, _) => Some(format!(
307 "task `{id}`: a wait step has no cleanup; use `finally` in its function"
308 )),
309 (TaskKind::Python { .. }, CleanupRun::Python)
310 | (TaskKind::Command { .. }, CleanupRun::Command(_))
311 | (TaskKind::Script { .. }, CleanupRun::Script { .. }) => None,
312 (TaskKind::Python { .. }, CleanupRun::Command(_) | CleanupRun::Script { .. }) => Some(
313 format!("task `{id}`: a Python task's cleanup is a function, not a command"),
314 ),
315 (TaskKind::Command { .. }, CleanupRun::Python | CleanupRun::Script { .. }) => Some(
316 format!("task `{id}`: a command task's cleanup is a command, not `python`"),
317 ),
318 (TaskKind::Empty, _) => Some(format!(
319 "task `{id}`: an empty task has nothing to clean up"
320 )),
321 (TaskKind::FirstOf { .. }, _) => {
322 Some(format!("task `{id}`: first_of has nothing to clean up"))
323 }
324 (TaskKind::WaitFor { .. } | TaskKind::WaitForEvent { .. }, _) => {
325 Some(format!("task `{id}`: wait_for has nothing to clean up"))
326 }
327 (TaskKind::TriggerDag { .. }, _) => Some(format!(
328 "task `{id}`: a TriggerDagOperator has nothing to clean up"
329 )),
330 (TaskKind::Script { .. }, _) => {
331 Some(format!("task `{id}`: a script's cleanup is a script"))
332 }
333 }
334}
335
336fn secret_problems(dag: &Dag, problems: &mut Vec<String>) {
340 for task in &dag.tasks {
341 let id = &task.id;
342 for name in task.secret_references() {
343 if let Err(error) = name.check() {
344 problems.push(format!("task `{id}`: {error}"));
345 }
346 }
347 problems.extend(cleanup_problem(task));
348 for declared in &task.secrets {
349 if let Err(error) = declared.check() {
350 problems.push(format!("task `{id}`: secrets=: {error}"));
351 }
352 }
353 for name in &task.connections {
354 if let Err(error) = TaskId::new(name) {
355 problems.push(format!("task `{id}`: connections=: `{name}`: {error}"));
356 }
357 }
358 problems.extend(batch_in_a_step(task));
359 if let TaskKind::TriggerDag { dag: target, .. } = &task.kind
360 && target == &dag.id
361 {
362 problems.push(format!(
363 "task `{id}`: a TriggerDagOperator can't start a run of its own DAG `{target}` (a \
364 cycle)"
365 ));
366 }
367 let mut in_text = kind_problems(task, problems);
368 let mapped: Vec<&Value> = match &task.expand {
369 Some(Expand::Product(over)) => over.iter().map(|m| &m.value).collect(),
370 Some(Expand::Kwargs(over)) => vec![over],
371 None => Vec::new(),
372 };
373 in_text.extend(mapped.iter().flat_map(|value| value_templates(value)));
375 for template in in_text {
376 for reference in template.references() {
377 if let Reference::Secret(name) = reference
378 && name.key.is_none()
379 {
380 problems.push(format!(
381 "task `{id}`: `{name}` is a whole secret (every key), which can't be \
382 written into text: name its key, `path#key`"
383 ));
384 }
385 }
386 }
387 if mapped
388 .iter()
389 .any(|v| matches!(v, Value::Ref(Reference::Secret(_))))
390 {
391 problems.push(format!(
392 "task `{id}` is mapped over a secret: the number of instances can't depend on it"
393 ));
394 }
395 }
396}
397
398fn kind_problems<'a>(task: &'a Task, problems: &mut Vec<String>) -> Vec<&'a Template> {
401 let id = &task.id;
402 let mut in_text: Vec<&Template> = Vec::new();
403 match &task.kind {
404 TaskKind::Command {
405 command,
406 env,
407 connection_env,
408 ..
409 } => {
410 for (prefix, name) in connection_env {
411 if let Err(error) = schedr_model::connection::check_prefix(prefix) {
412 problems.push(format!("task `{id}`: connections=: {error}"));
413 }
414 if !task.connections.contains(name) {
415 problems.push(format!(
416 "task `{id}`: connections=: `{prefix}` names `{name}`, which the \
417 task doesn't declare"
418 ));
419 }
420 }
421 let cleanup = task.cleanup_command().into_iter();
422 for template in command
423 .templates()
424 .into_iter()
425 .chain(cleanup.flat_map(CommandLine::templates))
426 {
427 for reference in template.references() {
428 if let Reference::Secret(name) = reference {
429 problems.push(format!(
430 "task `{id}`: `{name}` in the command line (anyone on the \
431 machine could read it in the process list): pass it in `env`, \
432 or declare it in `secrets=` and read it with `schedr task-ctx \
433 secret get`"
434 ));
435 }
436 }
437 }
438 in_text.extend(env.values());
439 }
440 TaskKind::Script { args, env, .. } => {
441 for reference in args
442 .iter()
443 .chain(task.cleanup_script_args())
444 .flat_map(Template::references)
445 {
446 if let Reference::Secret(name) = reference {
447 problems.push(format!(
448 "task `{id}`: `{name}` in the arguments (anyone on the machine could \
449 read it in the process list): pass it in `env`, or declare it in \
450 `secrets` and read it with `schedr task-ctx secret get`"
451 ));
452 }
453 }
454 in_text.extend(env.values());
455 }
456 TaskKind::Python { arguments, .. } => {
457 for value in arguments.values() {
458 in_text.extend(value_templates(value));
459 }
460 }
461 TaskKind::Sensor { arguments, .. } => {
462 for value in arguments.values() {
463 in_text.extend(value_templates(value));
464 }
465 sensor_problems(task, problems);
466 }
467 TaskKind::WaitFor {
468 max_wait_ms,
469 run_of,
470 } => wait_for_problems(task, run_of, *max_wait_ms, problems),
471 TaskKind::WaitForEvent { event, max_wait_ms } => {
472 wait_for_event_problems(task, event, *max_wait_ms, problems);
473 }
474 TaskKind::TriggerDag {
475 params,
476 max_wait_ms,
477 wait,
478 planned_for,
479 ..
480 } => trigger_dag_problems(
481 task,
482 (*max_wait_ms, *wait),
483 params,
484 planned_for.as_ref(),
485 problems,
486 ),
487 TaskKind::Empty | TaskKind::FirstOf { .. } => {}
488 }
489 in_text
490}
491
492fn sensor_wait_for_problems(
496 task: &Task,
497 mode: SensorMode,
498 arguments: &BTreeMap<String, Value>,
499 wait_for: &schedr_model::task::SensorWaitFor,
500 problems: &mut Vec<String>,
501) {
502 let id = &task.id;
503 if mode == SensorMode::Poke {
504 problems.push(format!(
505 "task `{id}`: a @sensor.poke can't take `wait_for=`: it is called once per matching \
506 run, never on a timer (a poke can read the run from the API itself)"
507 ));
508 }
509 if arguments.contains_key(&wait_for.param) {
510 problems.push(format!(
511 "task `{id}`: `{}` is given the run it waits for, so it takes no argument",
512 wait_for.param
513 ));
514 }
515 match wait_for.source() {
516 Some(WaitSource::RunOf(run_of)) => {
517 if let Some(why) = lag_problem(run_of) {
518 problems.push(format!("task `{id}`: {why}"));
519 }
520 }
521 Some(WaitSource::Event(event)) => {
522 if let Some(why) = event.key.as_ref().and_then(event_key_problem) {
523 problems.push(format!("task `{id}`: its event's key {why}"));
524 }
525 }
526 None => problems.push(format!(
527 "task `{id}`: `wait_for` is a RunOf or an EventNamed, one of them"
528 )),
529 }
530 if wait_for.timeout_ms == Some(0) {
531 problems.push(format!(
532 "task `{id}`: a call's `timeout` must be above zero"
533 ));
534 }
535 if mapping::is_mapped(task) {
536 problems.push(format!(
537 "task `{id}`: a @sensor with `wait_for=` can't be mapped"
538 ));
539 }
540}
541
542fn sensor_problems(task: &Task, problems: &mut Vec<String>) {
544 let TaskKind::Sensor {
545 arguments,
546 mode,
547 every_ms,
548 max_wait_ms,
549 wait_for,
550 ..
551 } = &task.kind
552 else {
553 return;
554 };
555 let id = &task.id;
556 if let Some(wait_for) = wait_for {
557 sensor_wait_for_problems(task, *mode, arguments, wait_for, problems);
558 }
559 match (mode, every_ms) {
560 (SensorMode::Poke, None | Some(0)) => {
561 problems.push(format!(
562 "task `{id}`: a @sensor.poke needs `every` above zero"
563 ));
564 }
565 (SensorMode::Loop, Some(_)) => {
566 problems.push(format!("task `{id}`: only a @sensor.poke has `every`"));
567 }
568 _ => {}
569 }
570 if *max_wait_ms == Some(0) {
571 problems.push(format!(
572 "task `{id}`: a wait step's `max_wait` must be above zero"
573 ));
574 }
575}
576
577fn batch_in_a_step(task: &Task) -> Option<String> {
579 matches!(
580 task.kind,
581 TaskKind::Sensor {
582 batch_ms: Some(_),
583 ..
584 }
585 )
586 .then(|| {
587 format!(
588 "task `{}`: `batch` is for an @trigger.poke, which starts runs: a wait step ends \
589 with one value",
590 task.id
591 )
592 })
593}
594
595fn batch_problems(id: &TaskId, mode: SensorMode, batch: u64, problems: &mut Vec<String>) {
598 if mode != SensorMode::Poke {
599 problems.push(format!(
600 "trigger `{id}`: `batch` is for an @trigger.poke: an @trigger batches by yielding \
601 one event holding the group"
602 ));
603 }
604 if batch == 0 {
605 problems.push(format!("trigger `{id}`: `batch` must be more than zero"));
606 }
607}
608
609fn trigger_wait_for_problems(
613 dag: &Dag,
614 task: &Task,
615 idle_restart: bool,
616 run_retries: Option<u32>,
617 problems: &mut Vec<String>,
618) {
619 let id = &task.id;
620 let TaskKind::Sensor {
621 mode,
622 arguments,
623 wait_for: Some(wait_for),
624 ..
625 } = &task.kind
626 else {
627 if run_retries.is_some() {
628 problems.push(format!(
629 "trigger `{id}`: `run_retries` is for a trigger with `wait_for=`"
630 ));
631 }
632 return;
633 };
634 if *mode != SensorMode::Loop {
635 problems.push(format!(
636 "trigger `{id}`: with `wait_for=` it is called once per run, never on a timer"
637 ));
638 }
639 if idle_restart {
640 problems.push(format!(
641 "trigger `{id}`: with `wait_for=` it is called once per run: nothing to restart \
642 when idle"
643 ));
644 }
645 if arguments.contains_key(&wait_for.param) {
646 problems.push(format!(
647 "trigger `{id}`: `{}` is given the run it waits for, so it takes no argument",
648 wait_for.param
649 ));
650 }
651 match wait_for.source() {
652 Some(WaitSource::RunOf(run_of)) => {
653 if run_of.dag == dag.id {
654 problems.push(format!(
655 "trigger `{id}`: it waits for runs of its own DAG, which would start it for \
656 ever"
657 ));
658 }
659 if let Some(why) = lag_problem(run_of) {
660 problems.push(format!("trigger `{id}`: {why}"));
661 }
662 if run_of.lag_ms.is_some_and(|lag| lag < 0) {
663 problems.push(format!(
664 "trigger `{id}`: its RunOf's `lag` can't be negative: a run can't be planned \
665 before the one starting it"
666 ));
667 }
668 }
669 Some(WaitSource::Event(event)) => {
670 if event.key.is_some() {
671 problems.push(format!(
672 "trigger `{id}`: an EventNamed it waits for takes no `key`: it is called for \
673 every event of its name"
674 ));
675 }
676 }
677 None => problems.push(format!(
678 "trigger `{id}`: `wait_for` is a RunOf or an EventNamed, one of them"
679 )),
680 }
681 if wait_for.timeout_ms == Some(0) {
682 problems.push(format!(
683 "trigger `{id}`: a call's `timeout` must be above zero"
684 ));
685 }
686}
687
688fn wait_for_problems(
690 task: &Task,
691 run_of: &schedr_model::task::RunOf,
692 max_wait_ms: Option<u64>,
693 problems: &mut Vec<String>,
694) {
695 let id = &task.id;
696 if let Some(why) = lag_problem(run_of) {
697 problems.push(format!("task `{id}`: {why}"));
698 }
699 if max_wait_ms == Some(0) {
700 problems.push(format!(
701 "task `{id}`: wait_for's `max_wait` must be above zero"
702 ));
703 }
704 if mapping::is_mapped(task) {
705 problems.push(format!("task `{id}`: wait_for can't be mapped"));
706 }
707}
708
709fn trigger_dag_problems(
714 task: &Task,
715 (max_wait_ms, wait): (Option<u64>, bool),
716 params: &BTreeMap<String, Value>,
717 planned_for: Option<&Value>,
718 problems: &mut Vec<String>,
719) {
720 let id = &task.id;
721 let named = params
722 .iter()
723 .map(|(key, value)| (format!("`params[{key:?}]`"), value))
724 .chain(planned_for.map(|value| ("`planned_for`".to_owned(), value)));
725 for (name, value) in named {
726 if let Some(what) = not_for_the_master(value) {
727 problems.push(format!(
728 "task `{id}`: {name} can't be {what}: the master starts the run and reads no \
729 secret and renders no template; pass the value from an upstream task"
730 ));
731 }
732 }
733 if max_wait_ms == Some(0) {
734 problems.push(format!("task `{id}`: `max_wait` must be above zero"));
735 }
736 if max_wait_ms.is_some() && !wait {
737 problems.push(format!(
738 "task `{id}`: `max_wait` is for `wait=True`; with `wait=False` it ends once the run \
739 is created"
740 ));
741 }
742 if let Some(Value::Literal(literal)) = planned_for
743 && literal
744 .get("$datetime")
745 .and_then(serde_json::Value::as_str)
746 .is_none_or(|text| text.parse::<jiff::Timestamp>().is_err())
747 {
748 problems.push(format!(
749 "task `{id}`: `planned_for` is a datetime with an offset or a reference, not \
750 {literal}"
751 ));
752 }
753}
754
755fn not_for_the_master(value: &Value) -> Option<&'static str> {
757 match value {
758 Value::Template(_) => Some("a text template"),
759 Value::Ref(schedr_model::value::Reference::Secret(_)) => Some("a secret"),
760 Value::List(items) => items.iter().find_map(not_for_the_master),
761 Value::Map(entries) => entries.values().find_map(not_for_the_master),
762 Value::Literal(_) | Value::Ref(_) => None,
763 }
764}
765
766fn wait_for_event_problems(
770 task: &Task,
771 event: &schedr_model::task::EventNamed,
772 max_wait_ms: Option<u64>,
773 problems: &mut Vec<String>,
774) {
775 let id = &task.id;
776 if max_wait_ms == Some(0) {
777 problems.push(format!(
778 "task `{id}`: wait_for's `max_wait` must be above zero"
779 ));
780 }
781 if mapping::is_mapped(task) {
782 problems.push(format!("task `{id}`: wait_for can't be mapped"));
783 }
784 if let Some(key) = &event.key
785 && let Some(why) = event_key_problem(key)
786 {
787 problems.push(format!("task `{id}`: EventNamed's `key` {why}"));
788 }
789}
790
791fn event_key_problem(key: &Value) -> Option<&'static str> {
794 use schedr_model::value::{DagCtxField, Reference};
795 match key {
796 Value::Literal(serde_json::Value::String(text)) if text.is_empty() => {
797 Some("can't be empty")
798 }
799 Value::Literal(serde_json::Value::String(_)) => None,
800 Value::Literal(_) => Some("is a string"),
801 Value::Ref(reference) => match reference {
802 Reference::Param { .. }
803 | Reference::Output { .. }
804 | Reference::DagCtx {
805 field: DagCtxField::RunId | DagCtxField::DagId | DagCtxField::EventKey,
806 } => None,
807 Reference::Secret(_) => Some("can't be a secret: it is stored and shown"),
808 Reference::Outcome { .. } | Reference::DagCtx { .. } => Some(
809 "is a literal string, the run's params, `dag_ctx.run.id`, `dag_ctx.dag_id`, \
810 `dag_ctx.event.key` or an upstream output",
811 ),
812 },
813 _ => Some(
814 "is a literal string, the run's params, `dag_ctx.run.id`, `dag_ctx.dag_id`, \
815 `dag_ctx.event.key` or an upstream output",
816 ),
817 }
818}
819
820fn value_templates(value: &Value) -> Vec<&Template> {
822 match value {
823 Value::Template(template) => vec![template],
824 Value::List(items) => items.iter().flat_map(value_templates).collect(),
825 Value::Map(entries) => entries.values().flat_map(value_templates).collect(),
826 Value::Literal(_) | Value::Ref(_) => Vec::new(),
827 }
828}
829
830#[must_use]
833pub fn storage_problems(dag: &Dag, storages: &BTreeSet<String>) -> Vec<String> {
834 let mut problems = Vec::new();
835 for task in &dag.tasks {
836 let named = task
837 .secret_references()
838 .into_iter()
839 .filter_map(|name| name.storage.as_deref())
840 .chain(task.secrets.iter().filter_map(SecretDecl::storage));
841 let mut seen = BTreeSet::new();
842 for storage in named {
843 if !storages.contains(storage) && seen.insert(storage) {
844 let known = if storages.is_empty() {
845 "none".to_owned()
846 } else {
847 storages
848 .iter()
849 .map(|s| format!("`{s}`"))
850 .collect::<Vec<_>>()
851 .join(", ")
852 };
853 problems.push(format!(
854 "task `{}`: no secret storage `{storage}` on the worker that parsed it \
855 (configured: {known}; `[secret_storage.{storage}]` in the workers' \
856 configuration)",
857 task.id
858 ));
859 }
860 }
861 }
862 problems
863}
864
865fn expand_problems(dag: &Dag, problems: &mut Vec<String>) {
868 for task in &dag.tasks {
869 let Some(expand) = &task.expand else {
870 continue;
871 };
872 if let TaskKind::TriggerDag {
873 params,
874 planned_for,
875 ..
876 } = &task.kind
877 {
878 let fixed = (!params.is_empty(), planned_for.is_some());
879 trigger_dag_expand_problems(task, expand, fixed, problems);
880 continue;
881 }
882 let TaskKind::Python {
883 arguments, branch, ..
884 } = &task.kind
885 else {
886 problems.push(format!(
888 "task `{}`: only a @task function or a TriggerDagOperator can be mapped \
889 (`.expand()`)",
890 task.id
891 ));
892 continue;
893 };
894 if *branch {
895 problems.push(format!(
896 "task `{}`: a @branch task can't be mapped (`.expand()`)",
897 task.id
898 ));
899 }
900 if let Expand::Kwargs(over) = expand {
901 let fixed: std::collections::BTreeSet<&str> = kwargs_names(over)
902 .into_iter()
903 .flatten()
904 .filter(|name| arguments.contains_key(*name))
905 .collect();
906 for name in fixed {
907 problems.push(format!(
908 "task `{}`: argument `{name}` is both fixed (`.partial()`) and mapped \
909 (`.expand_kwargs()`)",
910 task.id
911 ));
912 }
913 }
914 if let Expand::Product(over) = expand {
915 if over.is_empty() {
916 problems.push(format!("task `{}`: `.expand()` names no argument", task.id));
917 }
918 let mut seen = std::collections::BTreeSet::new();
919 for name in over.iter().map(|m| m.name.as_str()) {
920 if arguments.contains_key(name) {
921 problems.push(format!(
922 "task `{}`: argument `{name}` is both fixed (`.partial()`) and mapped \
923 (`.expand()`)",
924 task.id
925 ));
926 }
927 if !seen.insert(name) {
928 problems.push(format!(
929 "task `{}`: argument `{name}` is mapped twice (`.expand()`)",
930 task.id
931 ));
932 }
933 }
934 }
935 }
936}
937
938fn kwargs_names(over: &Value) -> Vec<Vec<&str>> {
941 match over {
942 Value::Literal(serde_json::Value::Array(items)) => items
943 .iter()
944 .filter_map(serde_json::Value::as_object)
945 .map(|item| item.keys().map(String::as_str).collect())
946 .collect(),
947 Value::List(items) => items
948 .iter()
949 .filter_map(|item| match item {
950 Value::Map(entries) => Some(entries.keys().map(String::as_str).collect()),
951 Value::Literal(serde_json::Value::Object(entries)) => {
952 Some(entries.keys().map(String::as_str).collect())
953 }
954 _ => None,
955 })
956 .collect(),
957 _ => Vec::new(),
958 }
959}
960
961fn trigger_dag_expand_problems(
965 task: &Task,
966 expand: &Expand,
967 (params_fixed, planned_fixed): (bool, bool),
968 problems: &mut Vec<String>,
969) {
970 let id = &task.id;
971 let (names, values, how): (Vec<&str>, Vec<&Value>, &str) = match expand {
972 Expand::Product(over) => {
973 if over.is_empty() {
974 problems.push(format!("task `{id}`: `.expand()` names no argument"));
975 }
976 let mut seen = std::collections::BTreeSet::new();
977 for name in over.iter().map(|m| m.name.as_str()) {
978 if !seen.insert(name) {
979 problems.push(format!(
980 "task `{id}`: argument `{name}` is mapped twice (`.expand()`)"
981 ));
982 }
983 }
984 (
985 over.iter().map(|m| m.name.as_str()).collect(),
986 over.iter().map(|m| &m.value).collect(),
987 "`.expand()`",
988 )
989 }
990 Expand::Kwargs(over) => {
991 let mut names: Vec<&str> = kwargs_names(over).into_iter().flatten().collect();
992 names.sort_unstable();
993 names.dedup();
994 (names, vec![over], "`.expand_kwargs()`")
995 }
996 };
997 for name in names {
998 let fixed = match name {
999 "params" => params_fixed,
1000 "planned_for" => planned_fixed,
1001 _ => {
1002 problems.push(format!(
1003 "task `{id}`: a TriggerDagOperator maps `params` or `planned_for`, not \
1004 `{name}` ({how})"
1005 ));
1006 continue;
1007 }
1008 };
1009 if fixed {
1010 problems.push(format!(
1011 "task `{id}`: argument `{name}` is both fixed (`.partial()`) and mapped ({how})"
1012 ));
1013 }
1014 }
1015 for value in values {
1016 if let Some(what) = not_for_the_master(value) {
1017 problems.push(format!(
1018 "task `{id}`: what it maps over can't hold {what}: the master starts the runs \
1019 and reads no secret and renders no template; pass the values from an upstream \
1020 task"
1021 ));
1022 }
1023 }
1024}
1025
1026fn param_problems(dag: &Dag, problems: &mut Vec<String>) {
1029 for task in &dag.tasks {
1030 for reference in task.references() {
1031 let Reference::Param { path } = reference else {
1032 continue;
1033 };
1034 let label = param_label(path);
1035 let Some(params) = &dag.params else {
1036 problems.push(format!(
1037 "task `{}` uses `{label}`, but the DAG declares no params (`Dag(params=...)`)",
1038 task.id
1039 ));
1040 continue;
1041 };
1042 let mut ty = Some(¶ms.ty);
1043 for step in path {
1044 ty = ty.and_then(|t| match step {
1045 schedr_model::PathElem::Field(name) => t.field(name),
1046 schedr_model::PathElem::Index(i) => t.element(*i),
1047 });
1048 }
1049 if ty.is_none() {
1050 problems.push(format!(
1051 "task `{}` uses `{label}`, which the DAG's params don't have",
1052 task.id
1053 ));
1054 }
1055 }
1056 let mapped: Vec<&Value> = match &task.expand {
1057 Some(Expand::Product(over)) => over.iter().map(|m| &m.value).collect(),
1058 Some(Expand::Kwargs(over)) => vec![over],
1059 None => Vec::new(),
1060 };
1061 if mapped
1062 .iter()
1063 .any(|v| matches!(v, Value::Ref(Reference::Param { .. })))
1064 {
1065 problems.push(format!(
1066 "task `{}` is mapped over the run's params: the number of instances can't \
1067 depend on them",
1068 task.id
1069 ));
1070 }
1071 }
1072}
1073
1074fn param_label(path: &[schedr_model::PathElem]) -> String {
1076 let mut label = "dag_ctx.params".to_owned();
1077 for step in path {
1078 match step {
1079 schedr_model::PathElem::Field(name) => {
1080 label.push('.');
1081 label.push_str(name);
1082 }
1083 schedr_model::PathElem::Index(i) => {
1084 label.push('[');
1085 label.push_str(&i.to_string());
1086 label.push(']');
1087 }
1088 }
1089 }
1090 label
1091}
1092
1093fn group_problems(dag: &Dag, problems: &mut Vec<String>) {
1096 let mut parents: BTreeMap<&str, Option<&str>> = BTreeMap::new();
1097 for group in &dag.groups {
1098 if parents
1099 .insert(group.id.as_str(), group.parent.as_deref())
1100 .is_some()
1101 {
1102 problems.push(format!("group `{}` is defined more than once", group.id));
1103 }
1104 }
1105 for group in &dag.groups {
1106 if let Some(parent) = &group.parent
1107 && !parents.contains_key(parent.as_str())
1108 {
1109 problems.push(format!(
1110 "group `{}`: its parent `{parent}` isn't a group of the DAG",
1111 group.id
1112 ));
1113 }
1114 let mut at = group.parent.as_deref();
1116 for _ in 0..parents.len() {
1117 match at {
1118 Some(id) if id == group.id => {
1119 problems.push(format!("group `{}` is nested inside itself", group.id));
1120 break;
1121 }
1122 Some(id) => at = parents.get(id).copied().flatten(),
1123 None => break,
1124 }
1125 }
1126 }
1127 for task in &dag.tasks {
1128 if let Some(group) = &task.group
1129 && !parents.contains_key(group.as_str())
1130 {
1131 problems.push(format!(
1132 "task `{}`: its group `{group}` isn't a group of the DAG",
1133 task.id
1134 ));
1135 }
1136 }
1137}
1138
1139fn edge_problems(dag: &Dag, tasks: &BTreeSet<&TaskId>, problems: &mut Vec<String>) {
1140 let branches: BTreeSet<&TaskId> = dag
1141 .tasks
1142 .iter()
1143 .filter(|task| matches!(task.kind, TaskKind::Python { branch: true, .. }))
1144 .map(|task| &task.id)
1145 .collect();
1146 let group_of = |id: &TaskId| dag.task(id).and_then(|t| t.group.as_deref());
1147 let out_of_its_group = |from: &TaskId, to: &TaskId| {
1150 group_of(from).is_some_and(|group| {
1151 group_of(to).is_none_or(|g| g != group && !g.starts_with(&format!("{group}.")))
1152 })
1153 };
1154 for edge in &dag.edges {
1155 for end in [&edge.from, &edge.to] {
1156 if !tasks.contains(end) {
1157 problems.push(format!(
1158 "edge `{}` -> `{}`: no task `{end}`",
1159 edge.from, edge.to
1160 ));
1161 }
1162 }
1163 if edge.from == edge.to {
1164 problems.push(format!("task `{}` depends on itself", edge.from));
1165 }
1166 let from_branch = branches.contains(&edge.from);
1167 if edge.kind == EdgeKind::Selection && !from_branch {
1168 problems.push(format!(
1169 "edge `{}` -> `{}`: a selection edge, but `{}` isn't a `@branch` task",
1170 edge.from, edge.to, edge.from
1171 ));
1172 } else if edge.kind != EdgeKind::Selection
1173 && from_branch
1174 && !(edge.kind == EdgeKind::Order && out_of_its_group(&edge.from, &edge.to))
1175 {
1176 problems.push(format!(
1177 "edge `{}` -> `{}`: of kind `{}`, but every edge from the `@branch` task `{}` must \
1178 be a selection edge (or an order edge out of its group, decision 94)",
1179 edge.from,
1180 edge.to,
1181 edge_kind_name(edge.kind),
1182 edge.from
1183 ));
1184 }
1185 }
1186}
1187
1188const fn edge_kind_name(kind: EdgeKind) -> &'static str {
1190 match kind {
1191 EdgeKind::Data => "data",
1192 EdgeKind::Order => "order",
1193 EdgeKind::Selection => "selection",
1194 EdgeKind::Requirement => "requirement",
1195 }
1196}
1197
1198fn resource_problems(dag: &Dag, tasks: &BTreeSet<&TaskId>, problems: &mut Vec<String>) {
1200 let mut parts = BTreeSet::new();
1201 for resource in &dag.resources {
1202 for part in [&resource.setup, &resource.cleanup] {
1203 if !parts.insert(part) {
1204 problems.push(format!("task `{part}` is a part of two resources"));
1205 }
1206 }
1207 for task in [&resource.setup, &resource.cleanup]
1208 .into_iter()
1209 .chain(&resource.users)
1210 {
1211 if !tasks.contains(task) {
1212 problems.push(format!(
1213 "resource `{}`: `{task}` isn't a task of the DAG",
1214 resource.setup
1215 ));
1216 }
1217 }
1218 if resource.users.contains(&resource.setup) || resource.users.contains(&resource.cleanup) {
1219 problems.push(format!(
1220 "resource `{}`: a part of it can't be its user",
1221 resource.setup
1222 ));
1223 }
1224 if !dag.edges.iter().any(|e| {
1225 e.from == resource.setup
1226 && e.to == resource.cleanup
1227 && matches!(e.kind, EdgeKind::Data | EdgeKind::Requirement)
1228 }) {
1229 problems.push(format!(
1230 "resource `{}`: no data or requirement edge to its cleanup `{}`",
1231 resource.setup, resource.cleanup
1232 ));
1233 }
1234 let joined: BTreeSet<&TaskId> = dag
1236 .edges
1237 .iter()
1238 .filter(|e| {
1239 e.from == resource.setup
1240 && e.to != resource.cleanup
1241 && matches!(e.kind, EdgeKind::Data | EdgeKind::Requirement)
1242 })
1243 .map(|e| &e.to)
1244 .collect();
1245 let listed: BTreeSet<&TaskId> = resource
1246 .users
1247 .iter()
1248 .filter(|user| **user != resource.setup && **user != resource.cleanup)
1249 .collect();
1250 for task in joined.symmetric_difference(&listed) {
1251 problems.push(format!(
1252 "resource `{}`: its users and the edges from it differ on `{task}`",
1253 resource.setup
1254 ));
1255 }
1256 if let Some(setup) = dag.task(&resource.setup)
1257 && let TaskKind::Command { resource: None, .. } = &setup.kind
1258 {
1259 problems.push(format!(
1260 "resource `{}`: a command setup must report its value (a `CommandResource`)",
1261 resource.setup
1262 ));
1263 }
1264 for part in [&resource.setup, &resource.cleanup] {
1265 if dag.task(part).is_some_and(|t| t.expand.is_some()) {
1266 problems.push(format!(
1267 "resource `{}`: `{part}` can't be mapped",
1268 resource.setup
1269 ));
1270 }
1271 }
1272 }
1273}
1274
1275fn role_problems(dag: &Dag, problems: &mut Vec<String>) {
1278 for task in &dag.tasks {
1279 let TaskKind::Command {
1280 resource: Some(role),
1281 ..
1282 } = &task.kind
1283 else {
1284 continue;
1285 };
1286 let id = &task.id;
1287 match role {
1288 ResourceRole::Setup => {
1289 if !dag.resources.iter().any(|r| &r.setup == id) {
1290 problems.push(format!(
1291 "task `{id}`: a resource setup, but no resource has it as its setup"
1292 ));
1293 }
1294 if task.output_type == TypeDesc::ProcessResult {
1295 problems.push(format!(
1296 "task `{id}`: a resource's value can't be a command's result"
1297 ));
1298 }
1299 }
1300 ResourceRole::Cleanup { setup } => {
1301 if !dag
1302 .resources
1303 .iter()
1304 .any(|r| &r.cleanup == id && &r.setup == setup)
1305 {
1306 problems.push(format!(
1307 "task `{id}`: the cleanup of `{setup}`, but it isn't that resource's \
1308 cleanup"
1309 ));
1310 }
1311 }
1312 }
1313 }
1314}
1315
1316fn first_of_problems(dag: &Dag, problems: &mut Vec<String>) {
1319 for task in &dag.tasks {
1320 let TaskKind::FirstOf { at_least } = task.kind else {
1321 continue;
1322 };
1323 let id = &task.id;
1324 let options: Vec<&TaskId> = dag
1325 .edges_into(id)
1326 .filter(|e| e.kind != EdgeKind::Requirement)
1327 .map(|e| &e.from)
1328 .collect();
1329 if dag.edges_into(id).any(|e| e.kind == EdgeKind::Order) {
1330 problems.push(format!(
1331 "task `{id}`: nothing can be ordered before first_of: what it waits for are the \
1332 tasks it was given"
1333 ));
1334 }
1335 let distinct: BTreeSet<&TaskId> = options.iter().copied().collect();
1336 if distinct.len() < 2 || distinct.len() != options.len() {
1337 problems.push(format!(
1338 "task `{id}`: first_of needs at least two different tasks to choose from"
1339 ));
1340 }
1341 for option in &distinct {
1342 if dag.task(option).is_some_and(mapping::is_mapped) {
1343 problems.push(format!(
1344 "task `{id}`: `{option}` is mapped, so it has no one value to choose"
1345 ));
1346 }
1347 }
1348 if at_least
1349 .is_some_and(|n| n == 0 || usize::try_from(n).unwrap_or(usize::MAX) > options.len())
1350 {
1351 problems.push(format!(
1352 "task `{id}`: at_least can't be reached with {} tasks to choose from",
1353 options.len()
1354 ));
1355 }
1356 if mapping::is_mapped(task) {
1357 problems.push(format!("task `{id}`: first_of can't be mapped"));
1358 }
1359 }
1360}
1361
1362fn reference_problems(dag: &Dag, tasks: &BTreeSet<&TaskId>, problems: &mut Vec<String>) {
1363 for task in &dag.tasks {
1364 let mut reported = BTreeSet::new();
1365 for reference in task.references() {
1366 let Reference::Output { task: upstream, .. } = reference else {
1367 continue;
1368 };
1369 if !reported.insert(upstream) {
1370 continue;
1371 }
1372 if !tasks.contains(upstream) {
1373 problems.push(format!(
1374 "task `{}` uses the output of `{upstream}`, which isn't a task of the DAG",
1375 task.id
1376 ));
1377 } else if !dag.edges.iter().any(|e| {
1378 matches!(e.kind, EdgeKind::Data | EdgeKind::Selection)
1380 && &e.from == upstream
1381 && e.to == task.id
1382 }) {
1383 problems.push(format!(
1384 "task `{}` uses the output of `{upstream}` without a data edge from it",
1385 task.id
1386 ));
1387 }
1388 }
1389 }
1390}
1391
1392fn cycle<'a>(dag: &'a Dag, tasks: &BTreeSet<&'a TaskId>) -> Option<Vec<&'a TaskId>> {
1394 let mut incoming: BTreeMap<&TaskId, usize> = tasks.iter().map(|id| (*id, 0)).collect();
1395 let waits = dag
1397 .resources
1398 .iter()
1399 .flat_map(|r| r.users.iter().map(move |user| (user, &r.cleanup)));
1400 let edges: BTreeSet<(&TaskId, &TaskId)> = dag
1401 .edges
1402 .iter()
1403 .map(|e| (&e.from, &e.to))
1404 .chain(waits)
1405 .filter(|(from, to)| tasks.contains(from) && tasks.contains(to))
1406 .collect();
1407 for (_, to) in &edges {
1408 *incoming.entry(to).or_default() += 1;
1409 }
1410 let mut ready: Vec<&TaskId> = incoming
1411 .iter()
1412 .filter(|(_, n)| **n == 0)
1413 .map(|(id, _)| *id)
1414 .collect();
1415 while let Some(id) = ready.pop() {
1416 incoming.remove(id);
1417 for (_, to) in edges.iter().filter(|(from, _)| *from == id) {
1418 if let Some(n) = incoming.get_mut(to) {
1419 *n -= 1;
1420 if *n == 0 {
1421 ready.push(to);
1422 }
1423 }
1424 }
1425 }
1426 (!incoming.is_empty()).then(|| incoming.into_keys().collect())
1427}
1428
1429#[derive(Debug, Clone, Copy)]
1431pub struct Checks<'a> {
1432 pub master: SchedrVersion,
1434 pub max_message_size: usize,
1436 pub secret_storages: Option<&'a BTreeSet<String>>,
1439 pub notifications: Option<&'a crate::notifications::Notifications>,
1442}
1443
1444impl Checks<'_> {
1445 #[must_use]
1447 pub const fn new(master: SchedrVersion, max_message_size: usize) -> Self {
1448 Self {
1449 master,
1450 max_message_size,
1451 secret_storages: None,
1452 notifications: None,
1453 }
1454 }
1455}
1456
1457#[must_use]
1460pub fn validate_files(root: &str, files: Vec<ParsedFile>, checks: &Checks<'_>) -> Vec<ParsedFile> {
1461 files
1462 .into_iter()
1463 .map(|file| validate_file(root, file, checks))
1464 .collect()
1465}
1466
1467#[must_use]
1471pub fn connection_problems(files: Vec<ParsedFile>) -> Vec<ParsedFile> {
1472 let registry = schedr_model::connection::Registry::of(&files);
1473 files
1474 .into_iter()
1475 .map(|mut file| {
1476 let problems: Vec<String> = file
1477 .dags
1478 .iter()
1479 .flat_map(|dag| {
1480 registry
1481 .problems(dag)
1482 .into_iter()
1483 .map(|p| format!("DAG `{}`: {p}", dag.id))
1484 })
1485 .collect();
1486 if !problems.is_empty() {
1487 file.dags.clear();
1488 file.error = Some(ErrorSummary {
1489 exception: INVALID_DAG_EXCEPTION.to_owned(),
1490 message: problems.join("\n"),
1491 traceback: String::new(),
1492 });
1493 }
1494 file
1495 })
1496 .collect()
1497}
1498
1499#[must_use]
1506pub fn target_problems(files: Vec<ParsedFile>) -> Vec<ParsedFile> {
1507 let triggers: BTreeMap<DagId, schedr_model::Trigger> = files
1508 .iter()
1509 .flat_map(|f| f.dags.iter().map(|d| (d.id.clone(), d.trigger.clone())))
1510 .collect();
1511 files
1512 .into_iter()
1513 .map(|mut file| {
1514 let mut problems = Vec::new();
1515 for dag in &file.dags {
1516 for task in &dag.tasks {
1517 let TaskKind::TriggerDag { dag: target, .. } = &task.kind else {
1518 continue;
1519 };
1520 let at = format!("DAG `{}`, task `{}`", dag.id, task.id);
1521 match triggers.get(target) {
1522 None => file.warnings.push(format!(
1523 "{at}: no DAG `{target}` in this root; if it is in another, it runs \
1524 once that root is parsed, else the task fails"
1525 )),
1526 Some(trigger) if !trigger.chained_from(&dag.id) => problems.push(format!(
1527 "{at}: DAG `{target}` isn't started by this DAG: a TriggerDagOperator \
1528 starts only a DAG with `trigger=Chained()` (or `Chained(by=[...])` \
1529 naming `{}`)",
1530 dag.id
1531 )),
1532 Some(_) => {}
1533 }
1534 }
1535 }
1536 if !problems.is_empty() {
1537 file.dags.clear();
1538 file.error = Some(ErrorSummary {
1539 exception: INVALID_DAG_EXCEPTION.to_owned(),
1540 message: problems.join("\n"),
1541 traceback: String::new(),
1542 });
1543 }
1544 file
1545 })
1546 .collect()
1547}
1548
1549const RESULT_OVERHEAD: u64 = 64 * 1024;
1551
1552#[must_use]
1556pub fn output_problems(dag: &Dag, max_message_size: usize) -> Vec<String> {
1557 let limit = u64::try_from(max_message_size).unwrap_or(u64::MAX);
1558 let trigger = match &dag.trigger {
1560 schedr_model::Trigger::Event { task, .. } => Some(task.as_ref()),
1561 _ => None,
1562 };
1563 dag.tasks
1564 .iter()
1565 .chain(trigger)
1566 .filter_map(|task| {
1567 let streams = match task.kind {
1568 TaskKind::Empty
1569 | TaskKind::FirstOf { .. }
1570 | TaskKind::WaitFor { .. }
1571 | TaskKind::WaitForEvent { .. }
1572 | TaskKind::TriggerDag { .. } => {
1573 return None;
1574 }
1575 TaskKind::Command { .. } | TaskKind::Script { .. } => 2,
1576 TaskKind::Python { .. } | TaskKind::Sensor { .. } => 1,
1577 };
1578 let size = task.settings.max_output_size;
1579 let needed = size.saturating_mul(streams).saturating_add(RESULT_OVERHEAD);
1580 (needed > limit).then(|| {
1581 let each = if streams == 2 {
1582 " (stdout and stderr each)"
1583 } else {
1584 ""
1585 };
1586 format!(
1587 "task `{}`: max_output_size {}{each} can't reach the master, which accepts \
1588 results up to {} ([grpc] max_message_size, less 64 KiB for the \
1589 rest of the result): lower max_output_size, or raise the setting",
1590 task.id,
1591 shown_size(size),
1592 shown_size(limit.saturating_sub(RESULT_OVERHEAD) / streams),
1593 )
1594 })
1595 })
1596 .collect()
1597}
1598
1599fn shown_size(bytes: u64) -> String {
1601 const KIB: u64 = 1024;
1602 const MIB: u64 = 1024 * 1024;
1603 if bytes >= MIB && bytes.is_multiple_of(MIB) {
1604 format!("{} MiB", bytes / MIB)
1605 } else if bytes >= KIB && bytes.is_multiple_of(KIB) {
1606 format!("{} KiB", bytes / KIB)
1607 } else {
1608 format!("{bytes} B")
1609 }
1610}
1611
1612fn validate_file(root: &str, mut file: ParsedFile, checks: &Checks<'_>) -> ParsedFile {
1613 if !inside_root(&file.path) {
1614 file.dags.clear();
1616 file.connections.clear();
1617 file.error = Some(ErrorSummary {
1618 exception: INVALID_PATH_EXCEPTION.to_owned(),
1619 message: format!("`{}` isn't a relative path inside the root", file.path),
1620 traceback: String::new(),
1621 });
1622 return file;
1623 }
1624 if file.error.is_some() {
1625 file.dags.clear();
1627 file.connections.clear();
1628 return file;
1629 }
1630 let mut problems: Vec<String> = Vec::new();
1631 file.connections.retain(|def| {
1632 let size = serde_json::to_vec(def).map_or(usize::MAX, |json| json.len());
1633 if size <= schedr_model::connection::MAX_CONNECTION_SIZE {
1634 return true;
1635 }
1636 problems.push(format!(
1637 "connection `{}`: its values take {size} bytes, over the 1 MiB a connection may \
1638 hold (they travel with each task opening it); give bigger data to the task",
1639 def.name
1640 ));
1641 false
1642 });
1643 problems.extend(file.dags.iter().flat_map(|dag| {
1644 let mut problems = dag_problems(dag, root, &file.path, checks.master);
1645 problems.extend(output_problems(dag, checks.max_message_size));
1646 if let Some(storages) = checks.secret_storages {
1647 problems.extend(storage_problems(dag, storages));
1648 }
1649 if let Some(notifications) = checks.notifications {
1650 problems.extend(notifications.problems(dag));
1651 }
1652 problems
1653 .into_iter()
1654 .map(move |p| format!("DAG `{}`: {p}", dag.id))
1655 }));
1656 if !problems.is_empty() {
1657 file.dags.clear();
1658 file.error = Some(ErrorSummary {
1659 exception: INVALID_DAG_EXCEPTION.to_owned(),
1660 message: problems.join("\n"),
1661 traceback: String::new(),
1662 });
1663 }
1664 file
1665}
1666
1667fn inside_root(path: &str) -> bool {
1668 !path.is_empty()
1669 && !path.contains('\\')
1670 && Path::new(path)
1671 .components()
1672 .all(|c| matches!(c, Component::Normal(_)))
1673}