Skip to main content

schedr_agent/
jobs.rs

1//! `schedr.toml`: the scripts a script root declares (archive/PROJECT.md, Plain script delivery;
2//! decisions 292-300). Read and checked here, in Rust, by the agent alone (decision 293): every
3//! key known, unknown ones an error. A declaration with a schedule (`schedule`, `every` or
4//! `once`) is a standalone job, a one-task DAG whose ID is its reference
5//! (`etl:team_a/schedr.toml#report_daily`); one without is a script for DAGs only (296).
6
7use std::collections::BTreeMap;
8
9use jiff::Timestamp;
10use jiff::civil::{Date, DateTime};
11use jiff::tz::TimeZone;
12use schedr_model::dag::Params;
13use schedr_model::runner::{ErrorSummary, ParsedFile, ScriptCleanupDeclaration};
14use schedr_model::secret::{SecretDecl, SecretName};
15use schedr_model::task::{
16    CleanupRun, DEFAULT_CLEANUP_RETRIES, DEFAULT_CLEANUP_RETRY_DELAY_MS, OutcomeDecl, TaskCleanup,
17    TaskKind, TaskSettings, default_outcomes,
18};
19use schedr_model::types::Field;
20use schedr_model::value::{Reference, Template, TemplatePart, TemplateRef};
21use schedr_model::{Dag, DagId, DagLocation, SchedrVersion, Task, TaskId, Trigger, TypeDesc};
22use toml::Value;
23use toml::value::Datetime;
24
25/// A script configuration file's name.
26pub const FILE_NAME: &str = "schedr.toml";
27
28/// The exception of a `schedr.toml` that can't be read or checked, shown as its import error.
29pub const INVALID_JOBS_EXCEPTION: &str = "InvalidScriptConfig";
30
31/// The keys a declaration may have.
32const JOB_KEYS: [&str; 27] = [
33    "script",
34    "interpreter",
35    "args",
36    "env",
37    "secrets",
38    "working_dir",
39    "schedule",
40    "every",
41    "once",
42    "timezone",
43    "start",
44    "end",
45    "initial_since",
46    "catchup",
47    "max_active_runs",
48    "notify",
49    "queue",
50    "retries",
51    "retry_delay",
52    "timeout",
53    "max_output_size",
54    "description",
55    "tags",
56    "cleanup_handles",
57    "outcomes",
58    "params",
59    "cleanup",
60];
61
62/// The keys only a standalone job has: without a schedule they would do nothing (296).
63const DAG_KEYS: [&str; 8] = [
64    "timezone",
65    "start",
66    "end",
67    "initial_since",
68    "catchup",
69    "max_active_runs",
70    "notify",
71    "params",
72];
73
74/// The keys of a job's `[cleanup]`.
75const CLEANUP_KEYS: [&str; 7] = [
76    "script",
77    "interpreter",
78    "args",
79    "timeout",
80    "retries",
81    "retry_delay",
82    "anywhere",
83];
84
85/// The highest exit code a process can have.
86const MAX_EXIT_CODE: i64 = 255;
87
88/// Where a `schedr.toml` is.
89pub struct Source<'a> {
90    /// The script root's name.
91    pub root: &'a str,
92    /// The file's path in the root, with `/` separators.
93    pub path: &'a str,
94    /// Whether a file exists at a path in the root (`/` separators).
95    pub exists: &'a dyn Fn(&str) -> bool,
96}
97
98impl Source<'_> {
99    /// The file's directory in the root: `""` at the root itself.
100    fn dir(&self) -> &str {
101        self.path.rsplit_once('/').map_or("", |(dir, _)| dir)
102    }
103
104    /// A path written in the file, as a path in the root: relative to the file, no `..`, not
105    /// absolute.
106    fn in_root(&self, written: &str) -> Result<String, String> {
107        if written.starts_with('/') || written.starts_with('\\') {
108            return Err(format!(
109                "`{written}` is absolute: a path is relative to `{FILE_NAME}`"
110            ));
111        }
112        let mut parts: Vec<&str> = self.dir().split('/').filter(|p| !p.is_empty()).collect();
113        for part in written.split('/') {
114            match part {
115                "" | "." => {}
116                ".." => {
117                    return Err(format!(
118                        "`{written}` has `..`: a path stays in `{FILE_NAME}`'s directory or below"
119                    ));
120                }
121                part => parts.push(part),
122            }
123        }
124        Ok(parts.join("/"))
125    }
126
127    /// The reference of a declaration: `<root>:<path>#<name>`.
128    fn reference(&self, name: &str) -> String {
129        format!("{}:{}#{name}", self.root, self.path)
130    }
131}
132
133/// A checked declaration.
134#[derive(Debug, Clone, PartialEq, Eq)]
135pub struct Declaration {
136    /// Its name in the file.
137    pub name: String,
138    /// Its reference, `<root>:<path>#<name>`.
139    pub reference: String,
140    /// The task it runs.
141    pub task: Task,
142    /// When it runs on its own: `None` for a script for DAGs only.
143    pub schedule: Option<Schedule>,
144    /// Its description.
145    pub description: Option<String>,
146    /// Its tags.
147    pub tags: Vec<String>,
148    /// The settings its file gives (the others are the defaults in `task`).
149    pub given: Given,
150}
151
152/// The task settings a declaration gives itself: a `ScriptOperator` takes these, and the
153/// DAG's defaults for the others.
154#[derive(Debug, Clone, Default, PartialEq, Eq)]
155pub struct Given {
156    /// `retries`.
157    pub retries: Option<u32>,
158    /// `retry_delay`.
159    pub retry_delay_ms: Option<u64>,
160    /// `timeout`.
161    pub timeout_ms: Option<u64>,
162    /// `queue`.
163    pub queue: Option<String>,
164    /// `max_output_size`.
165    pub max_output_size: Option<u64>,
166    /// `[outcomes]`; empty: none given.
167    pub outcomes: Vec<OutcomeDecl>,
168    /// `[cleanup]`.
169    pub cleanup: Option<ScriptCleanupDeclaration>,
170}
171
172impl Declaration {
173    /// What a `ScriptOperator` referring to it gets (decision 293).
174    #[must_use]
175    pub fn for_operator(&self) -> schedr_model::runner::ScriptDeclaration {
176        let TaskKind::Script {
177            job,
178            script,
179            interpreter,
180            args,
181            env,
182            working_dir,
183            ..
184        } = &self.task.kind
185        else {
186            unreachable!("a declaration's task is a script")
187        };
188        schedr_model::runner::ScriptDeclaration {
189            job: job.clone(),
190            script: script.clone(),
191            interpreter: interpreter.clone(),
192            args: args.clone(),
193            env: env.clone(),
194            secrets: self.task.secrets.clone(),
195            working_dir: working_dir.clone(),
196            retries: self.given.retries,
197            retry_delay_ms: self.given.retry_delay_ms,
198            timeout_ms: self.given.timeout_ms,
199            queue: self.given.queue.clone(),
200            max_output_size: self.given.max_output_size,
201            outcomes: self.given.outcomes.clone(),
202            cleanup: self.given.cleanup.clone(),
203        }
204    }
205}
206
207/// A standalone job's DAG-level settings.
208#[derive(Debug, Clone, PartialEq, Eq)]
209pub struct Schedule {
210    /// When it fires.
211    pub trigger: Trigger,
212    /// The `since` of its first run.
213    pub initial_since: Option<Timestamp>,
214    /// Its runs at once.
215    pub max_active_runs: u32,
216    /// Its run parameters (`[params]`).
217    pub params: Option<Params>,
218}
219
220impl Declaration {
221    /// A standalone job's one-task DAG at `location`; `None` for a script for DAGs only.
222    #[must_use]
223    pub fn dag(&self, location: &DagLocation) -> Option<Dag> {
224        let schedule = self.schedule.as_ref()?;
225        let id = DagId::new(self.reference.clone()).ok()?;
226        Some(Dag {
227            produced_by: SchedrVersion::current(),
228            id,
229            location: location.clone(),
230            description: self.description.clone(),
231            tags: self.tags.clone(),
232            trigger: schedule.trigger.clone(),
233            initial_since: schedule.initial_since,
234            max_active_runs: Some(schedule.max_active_runs),
235            max_active_tasks: None,
236            tasks: vec![self.task.clone()],
237            edges: Vec::new(),
238            groups: Vec::new(),
239            params: schedule.params.clone(),
240            resources: Vec::new(),
241            notify: Vec::new(),
242        })
243    }
244}
245
246/// Reads and checks a `schedr.toml`: its declarations in the order written, or every problem
247/// found, each naming the job and key.
248///
249/// # Errors
250///
251/// The problems, when there is one.
252pub fn read(text: &str, source: &Source<'_>) -> Result<Vec<Declaration>, Vec<String>> {
253    let table: toml::Table = text
254        .parse()
255        .map_err(|e: toml::de::Error| vec![format!("not valid TOML: {}", e.message())])?;
256    let mut problems = Vec::new();
257    for key in table.keys() {
258        if key != "jobs" {
259            problems.push(format!(
260                "unknown key `{key}`: a `{FILE_NAME}` has `[jobs.<name>]` tables"
261            ));
262        }
263    }
264    let jobs = match table.get("jobs") {
265        None => {
266            return if problems.is_empty() {
267                Ok(Vec::new())
268            } else {
269                Err(problems)
270            };
271        }
272        Some(Value::Table(jobs)) => jobs,
273        Some(_) => {
274            problems.push("`jobs` is a table of `[jobs.<name>]` tables".to_owned());
275            return Err(problems);
276        }
277    };
278    let mut declarations = Vec::new();
279    for (name, job) in jobs {
280        let mut job_problems = Vec::new();
281        let declaration = job_of(name, job, source, &mut job_problems);
282        problems.extend(
283            job_problems
284                .into_iter()
285                .map(|p| format!("job `{name}`: {p}")),
286        );
287        declarations.extend(declaration);
288    }
289    if problems.is_empty() {
290        Ok(declarations)
291    } else {
292        Err(problems)
293    }
294}
295
296/// One declaration, or `None` with its problems added.
297fn job_of(
298    name: &str,
299    job: &Value,
300    source: &Source<'_>,
301    problems: &mut Vec<String>,
302) -> Option<Declaration> {
303    if !valid_name(name) {
304        problems.push(
305            "a job's name is letters, digits, `_` and `-` (it names the job's task too)".to_owned(),
306        );
307    } else if let Err(error) = TaskId::new(name) {
308        problems.push(format!("its name names the job's task: {error}"));
309    }
310    let Value::Table(keys) = job else {
311        problems.push("a job is a table of keys".to_owned());
312        return None;
313    };
314    let mut keys = Keys {
315        table: keys,
316        problems,
317    };
318    keys.check_known();
319    let schedule = keys.schedule();
320    if matches!(schedule, Scheduling::Unscheduled) {
321        keys.none_of(
322            &DAG_KEYS,
323            "a script without `schedule`, `every` or `once` is for DAGs only: it would do nothing",
324        );
325    }
326    let task = keys.task(name, source);
327    let given = task
328        .as_ref()
329        .map(|(_, given)| given.clone())
330        .unwrap_or_default();
331    let task = task.map(|(task, _)| task);
332    let description = keys.string("description");
333    let tags = keys.strings("tags").unwrap_or_default();
334    let reference = source.reference(name);
335    if matches!(schedule, Scheduling::Scheduled(_)) && DagId::new(reference.clone()).is_err() {
336        keys.problems.push(format!(
337            "its ID `{reference}` isn't a valid DAG ID (at most 250 bytes of letters, digits and \
338             `_.-:/#`): shorten the path or the name"
339        ));
340    }
341    if !keys.problems.is_empty() {
342        return None;
343    }
344    Some(Declaration {
345        name: name.to_owned(),
346        reference,
347        task: task?,
348        given,
349        schedule: match schedule {
350            Scheduling::Scheduled(schedule) => Some(*schedule),
351            Scheduling::Unscheduled | Scheduling::Bad => None,
352        },
353        description,
354        tags,
355    })
356}
357
358/// What a job's schedule keys say.
359enum Scheduling {
360    /// None of `schedule`, `every` and `once`: the script is for DAGs only.
361    Unscheduled,
362    Scheduled(Box<Schedule>),
363    /// A problem, already reported.
364    Bad,
365}
366
367/// A declared `[cleanup]` as its task's.
368fn task_cleanup(declared: ScriptCleanupDeclaration) -> TaskCleanup {
369    TaskCleanup {
370        run: CleanupRun::Script {
371            script: declared.script,
372            interpreter: declared.interpreter,
373            args: declared.args,
374        },
375        timeout_ms: declared.timeout_ms,
376        retries: declared.retries.unwrap_or(DEFAULT_CLEANUP_RETRIES),
377        retry_delay_ms: declared
378            .retry_delay_ms
379            .unwrap_or(DEFAULT_CLEANUP_RETRY_DELAY_MS),
380        handles: declared.handles,
381        anywhere: declared.anywhere.unwrap_or(false),
382    }
383}
384
385/// A `[cleanup]` table, or `None` with its problems added.
386fn cleanup_of(
387    table: &toml::Table,
388    handles: Option<Vec<String>>,
389    source: &Source<'_>,
390    problems: &mut Vec<String>,
391) -> Option<ScriptCleanupDeclaration> {
392    for key in table.keys() {
393        if !CLEANUP_KEYS.contains(&key.as_str()) {
394            problems.push(format!("unknown key `{key}`"));
395        }
396    }
397    let mut keys = Keys { table, problems };
398    let script = keys.path("script", source, true);
399    let interpreter = keys.required_string("interpreter");
400    let args = keys
401        .strings("args")
402        .unwrap_or_default()
403        .into_iter()
404        .map(Template::text)
405        .collect();
406    Some(ScriptCleanupDeclaration {
407        args,
408        timeout_ms: keys.duration_ms("timeout"),
409        retries: keys.whole("retries", 0),
410        retry_delay_ms: keys.duration_ms("retry_delay"),
411        anywhere: keys.boolean("anywhere"),
412        handles,
413        script: script?,
414        interpreter: interpreter?,
415    })
416}
417
418/// A parameter, from its default.
419struct Param {
420    /// The type its default has.
421    ty: TypeDesc,
422    /// Its JSON Schema, as the native API's for that type.
423    schema: serde_json::Value,
424    /// Its default, as JSON.
425    value: serde_json::Value,
426}
427
428/// A parameter's type, schema and default, from its TOML default (decision 310): an empty or
429/// mixed list has no type to take.
430fn param_of(value: &Value, tz: &TimeZone) -> Result<Param, String> {
431    let scalar = |ty: TypeDesc, schema: serde_json::Value, value: serde_json::Value| {
432        Ok(Param { ty, schema, value })
433    };
434    match value {
435        Value::String(text) => scalar(
436            TypeDesc::Str,
437            serde_json::json!({"type": "string"}),
438            text.clone().into(),
439        ),
440        Value::Integer(number) => scalar(
441            TypeDesc::Int,
442            serde_json::json!({"type": "integer"}),
443            (*number).into(),
444        ),
445        Value::Float(number) if number.is_finite() => scalar(
446            TypeDesc::Float,
447            serde_json::json!({"type": "number"}),
448            (*number).into(),
449        ),
450        Value::Float(_) => Err("a number that isn't finite can't be stored".to_owned()),
451        Value::Boolean(flag) => scalar(
452            TypeDesc::Bool,
453            serde_json::json!({"type": "boolean"}),
454            (*flag).into(),
455        ),
456        Value::Datetime(when) if when.time.is_none() && when.date.is_some() => scalar(
457            TypeDesc::Date,
458            serde_json::json!({"type": "string", "format": "date"}),
459            when.to_string().into(),
460        ),
461        Value::Datetime(when) => scalar(
462            TypeDesc::Datetime,
463            serde_json::json!({"type": "string", "format": "date-time"}),
464            moment_of(when, tz)?.to_string().into(),
465        ),
466        Value::Array(items) => {
467            let mut params = items.iter().map(|item| param_of(item, tz));
468            let first = params.next().ok_or(
469                "an empty list has no type to take: give a default with an item".to_owned(),
470            )??;
471            let mut values = vec![first.value];
472            for param in params {
473                let param = param?;
474                if param.ty != first.ty {
475                    return Err("a list mixing types has no type to take".to_owned());
476                }
477                values.push(param.value);
478            }
479            Ok(Param {
480                ty: TypeDesc::List {
481                    item: Box::new(first.ty),
482                },
483                schema: serde_json::json!({"type": "array", "items": first.schema}),
484                value: values.into(),
485            })
486        }
487        Value::Table(table) => {
488            if table.is_empty() {
489                return Err("an empty table has no type to take".to_owned());
490            }
491            let mut fields = Vec::new();
492            let mut properties = serde_json::Map::new();
493            let mut values = serde_json::Map::new();
494            for (name, item) in table {
495                let param = param_of(item, tz).map_err(|why| format!("`{name}`: {why}"))?;
496                fields.push(Field {
497                    name: name.clone(),
498                    ty: param.ty,
499                    required: true,
500                });
501                properties.insert(name.clone(), param.schema);
502                values.insert(name.clone(), param.value);
503            }
504            let required: Vec<&String> = table.keys().collect();
505            Ok(Param {
506                ty: TypeDesc::TypedDict {
507                    name: "Table".to_owned(),
508                    fields,
509                },
510                schema: serde_json::json!({
511                    "type": "object",
512                    "properties": properties,
513                    "required": required,
514                    "additionalProperties": false,
515                }),
516                value: values.into(),
517            })
518        }
519    }
520}
521
522/// A name a script can read a field by, and an outcome's: letters, digits and `_`.
523fn valid_identifier(name: &str) -> bool {
524    name.chars()
525        .next()
526        .is_some_and(|c| c.is_ascii_alphabetic() || c == '_')
527        && name.chars().all(|c| c.is_ascii_alphanumeric() || c == '_')
528}
529
530/// A job name: letters, digits, `_` and `-` (decision 300).
531fn valid_name(name: &str) -> bool {
532    !name.is_empty()
533        && name
534            .chars()
535            .all(|c| c.is_ascii_alphanumeric() || c == '_' || c == '-')
536}
537
538/// A job's keys, read one by one, problems noted.
539struct Keys<'a> {
540    table: &'a toml::Table,
541    problems: &'a mut Vec<String>,
542}
543
544impl Keys<'_> {
545    fn check_known(&mut self) {
546        for key in self.table.keys() {
547            if !JOB_KEYS.contains(&key.as_str()) {
548                self.problems.push(format!("unknown key `{key}`"));
549            } else if key == "notify" {
550                // Decisions 298, 416: a job's failure is its task's; the DAG's `notify=` says.
551                self.problems.push(
552                    "`notify` isn't set on a job: notifications are a DAG's, \
553                     `Dag(notify=...)` in a DAG file"
554                        .to_owned(),
555                );
556            }
557        }
558    }
559
560    fn none_of(&mut self, keys: &[&str], why: &str) {
561        for key in keys {
562            if self.table.contains_key(*key) && *key != "notify" {
563                self.problems.push(format!("`{key}`: {why}"));
564            }
565        }
566    }
567
568    fn wrong(&mut self, key: &str, wanted: &str) {
569        self.problems.push(format!("`{key}` is {wanted}"));
570    }
571
572    fn string(&mut self, key: &str) -> Option<String> {
573        let value = self.table.get(key)?;
574        if let Value::String(text) = value {
575            return Some(text.clone());
576        }
577        self.wrong(key, "a string");
578        None
579    }
580
581    fn required_string(&mut self, key: &str) -> Option<String> {
582        if !self.table.contains_key(key) {
583            self.problems.push(format!("`{key}` is required"));
584            return None;
585        }
586        self.string(key)
587    }
588
589    fn strings(&mut self, key: &str) -> Option<Vec<String>> {
590        let Value::Array(items) = self.table.get(key)? else {
591            self.wrong(key, "a list of strings");
592            return None;
593        };
594        let strings: Option<Vec<String>> = items
595            .iter()
596            .map(|item| item.as_str().map(str::to_owned))
597            .collect();
598        if strings.is_none() {
599            self.wrong(key, "a list of strings");
600        }
601        strings
602    }
603
604    fn boolean(&mut self, key: &str) -> Option<bool> {
605        let value = self.table.get(key)?;
606        if let Value::Boolean(value) = value {
607            return Some(*value);
608        }
609        self.wrong(key, "`true` or `false`");
610        None
611    }
612
613    fn whole(&mut self, key: &str, min: i64) -> Option<u32> {
614        match self.table.get(key)? {
615            Value::Integer(n) if *n >= min => u32::try_from(*n).ok().or_else(|| {
616                self.wrong(key, "a smaller number");
617                None
618            }),
619            _ => {
620                self.wrong(key, &format!("a whole number of at least {min}"));
621                None
622            }
623        }
624    }
625
626    fn duration_ms(&mut self, key: &str) -> Option<u64> {
627        let text = self.string(key)?;
628        match schedr_config::units::parse_duration(&text) {
629            Ok(duration) => Some(u64::try_from(duration.as_millis()).unwrap_or(u64::MAX)),
630            Err(error) => {
631                self.problems.push(format!("`{key}`: {error}"));
632                None
633            }
634        }
635    }
636
637    fn size(&mut self, key: &str) -> Option<u64> {
638        let text = self.string(key)?;
639        match schedr_config::units::parse_size(&text) {
640            Ok(size) => Some(size),
641            Err(error) => {
642                self.problems.push(format!("`{key}`: {error}"));
643                None
644            }
645        }
646    }
647
648    /// The time zone dates and times without an offset are in, and its name (`UTC` by
649    /// default).
650    fn timezone(&mut self) -> (TimeZone, String) {
651        let Some(name) = self.string("timezone") else {
652            return (TimeZone::UTC, "UTC".to_owned());
653        };
654        let tz = TimeZone::get(&name).unwrap_or_else(|_| {
655            self.problems
656                .push(format!("`timezone`: `{name}` isn't a known time zone"));
657            TimeZone::UTC
658        });
659        (tz, name)
660    }
661
662    /// A TOML date or date-time as a moment: with an offset as written, without one in `tz`
663    /// (a date at its midnight).
664    fn moment(&mut self, key: &str, tz: &TimeZone) -> Option<Timestamp> {
665        let Value::Datetime(when) = self.table.get(key)? else {
666            self.wrong(
667                key,
668                "a TOML date or date-time (`2026-01-01`, `2026-01-01T03:00:00`)",
669            );
670            return None;
671        };
672        match moment_of(when, tz) {
673            Ok(moment) => Some(moment),
674            Err(error) => {
675                self.problems.push(format!("`{key}`: {error}"));
676                None
677            }
678        }
679    }
680
681    /// The job's schedule, if it has one.
682    fn schedule(&mut self) -> Scheduling {
683        let given: Vec<&str> = ["schedule", "every", "once"]
684            .into_iter()
685            .filter(|key| self.table.contains_key(*key))
686            .collect();
687        if given.len() > 1 {
688            self.problems.push(format!(
689                "at most one of `schedule`, `every` and `once` (it has `{}`)",
690                given.join("`, `")
691            ));
692            return Scheduling::Bad;
693        }
694        let Some(&kind) = given.first() else {
695            return Scheduling::Unscheduled;
696        };
697        self.scheduled(kind).map_or(Scheduling::Bad, |schedule| {
698            Scheduling::Scheduled(Box::new(schedule))
699        })
700    }
701
702    /// The schedule given by `kind` (`schedule`, `every` or `once`); `None` after a problem.
703    fn scheduled(&mut self, kind: &str) -> Option<Schedule> {
704        let (tz, tz_name) = self.timezone();
705        let start = self.moment("start", &tz);
706        let end = self.moment("end", &tz);
707        let catchup = self.boolean("catchup").unwrap_or(false);
708        let trigger = match kind {
709            "schedule" => Trigger::Cron {
710                expression: self.string("schedule")?,
711                timezone: tz_name,
712                catchup,
713                start,
714                end,
715            },
716            "every" => Trigger::Every {
717                interval_ms: self.duration_ms("every")?,
718                catchup,
719                start,
720                end,
721            },
722            _ => {
723                self.none_of(
724                    &["start", "end", "catchup"],
725                    "`once` fires once: it would do nothing",
726                );
727                Trigger::Once {
728                    at: self.moment("once", &tz)?,
729                }
730            }
731        };
732        if matches!(trigger, Trigger::Every { interval_ms: 0, .. }) {
733            self.wrong("every", "longer than nothing");
734        }
735        Some(Schedule {
736            trigger,
737            initial_since: self.moment("initial_since", &tz),
738            max_active_runs: self.whole("max_active_runs", 1).unwrap_or(1),
739            params: self.params(&tz),
740        })
741    }
742
743    /// `[params]`: run parameters, each one's type taken from its default (decision 310).
744    fn params(&mut self, tz: &TimeZone) -> Option<Params> {
745        let value = self.table.get("params")?;
746        let Value::Table(table) = value else {
747            self.wrong("params", "a table of defaults");
748            return None;
749        };
750        let mut fields = Vec::new();
751        let mut properties = serde_json::Map::new();
752        let mut defaults = serde_json::Map::new();
753        for (name, value) in table {
754            if !valid_identifier(name) {
755                self.problems.push(format!(
756                    "`params`: `{name}` isn't a name: letters, digits and `_`, not starting with \
757                     a digit"
758                ));
759                continue;
760            }
761            match param_of(value, tz) {
762                Ok(param) => {
763                    let mut schema = param.schema;
764                    schema["default"] = param.value.clone();
765                    fields.push(Field {
766                        name: name.clone(),
767                        ty: param.ty,
768                        required: false,
769                    });
770                    properties.insert(name.clone(), schema);
771                    defaults.insert(name.clone(), param.value);
772                }
773                Err(why) => self.problems.push(format!("`params`: `{name}`: {why}")),
774            }
775        }
776        Some(Params {
777            ty: TypeDesc::Dataclass {
778                name: "Params".to_owned(),
779                fields,
780            },
781            schema: serde_json::json!({
782                "type": "object",
783                "title": "Params",
784                "properties": properties,
785                "required": [],
786                "additionalProperties": false,
787            }),
788            defaults,
789        })
790    }
791
792    /// `[outcomes]`: each name with its exit code; none when not given.
793    fn outcomes(&mut self) -> Vec<OutcomeDecl> {
794        let Some(value) = self.table.get("outcomes") else {
795            return Vec::new();
796        };
797        let Value::Table(table) = value else {
798            self.wrong("outcomes", "a table of exit codes");
799            return Vec::new();
800        };
801        if table.is_empty() {
802            self.wrong("outcomes", "at least one name and its exit code");
803        }
804        let mut outcomes: Vec<OutcomeDecl> = Vec::new();
805        for (name, code) in table {
806            if !valid_identifier(name) {
807                self.problems.push(format!(
808                    "`outcomes`: `{name}` isn't a name: letters, digits and `_`, not starting \
809                     with a digit"
810                ));
811            }
812            let Some(code) = code
813                .as_integer()
814                .filter(|code| (0..=MAX_EXIT_CODE).contains(code))
815                .and_then(|code| i32::try_from(code).ok())
816            else {
817                self.problems
818                    .push(format!("`outcomes`: `{name}` is an exit code, 0 to 255"));
819                continue;
820            };
821            if let Some(same) = outcomes.iter().find(|o| o.exit_code == Some(code)) {
822                self.problems.push(format!(
823                    "`outcomes`: `{name}` and `{}` share the exit code {code}",
824                    same.name
825                ));
826            }
827            outcomes.push(OutcomeDecl {
828                name: name.clone(),
829                exit_code: Some(code),
830            });
831        }
832        outcomes
833    }
834
835    /// `cleanup_handles`: the handle types the attempt may register; `None`: any.
836    fn cleanup_handles(&mut self) -> Option<Vec<String>> {
837        let names = self.strings("cleanup_handles")?;
838        if names.iter().any(String::is_empty) {
839            self.wrong("cleanup_handles", "a list of type names");
840        }
841        if !self.table.contains_key("cleanup") {
842            self.problems
843                .push("`cleanup_handles` without `[cleanup]`: nothing would read them".to_owned());
844        }
845        Some(names)
846    }
847
848    /// `[cleanup]`: a script of the same root, with the same rules as the job's.
849    fn cleanup(&mut self, source: &Source<'_>) -> Option<ScriptCleanupDeclaration> {
850        let handles = self.cleanup_handles();
851        let value = self.table.get("cleanup")?;
852        let Value::Table(table) = value else {
853            self.wrong("cleanup", "a table of keys");
854            return None;
855        };
856        let mut problems = Vec::new();
857        let declared = cleanup_of(table, handles, source, &mut problems);
858        self.problems
859            .extend(problems.into_iter().map(|p| format!("`cleanup`: {p}")));
860        declared
861    }
862
863    /// The job's task, named after it, and the settings the file gives.
864    fn task(&mut self, name: &str, source: &Source<'_>) -> Option<(Task, Given)> {
865        let script = self.path("script", source, true);
866        // Checked by the worker that runs it (rejection 3): workers may have different ones.
867        let interpreter = self.required_string("interpreter");
868        let working_dir = match self.table.get("working_dir") {
869            None => Some(source.dir().to_owned()),
870            Some(_) => self.path("working_dir", source, false),
871        };
872        let args = self
873            .strings("args")
874            .unwrap_or_default()
875            .into_iter()
876            .map(Template::text)
877            .collect();
878        let env = self.env();
879        let secrets = self.secrets();
880        let outcomes = self.outcomes();
881        let declared_cleanup = self.cleanup(source);
882        let given = Given {
883            outcomes: outcomes.clone(),
884            cleanup: declared_cleanup.clone(),
885            retries: self.whole("retries", 0),
886            retry_delay_ms: self.duration_ms("retry_delay"),
887            timeout_ms: self.duration_ms("timeout"),
888            queue: self.string("queue"),
889            max_output_size: self.size("max_output_size"),
890        };
891        let defaults = TaskSettings::default();
892        let settings = TaskSettings {
893            retries: given.retries.unwrap_or(defaults.retries),
894            retry_delay_ms: given.retry_delay_ms.unwrap_or(defaults.retry_delay_ms),
895            timeout_ms: given.timeout_ms,
896            queue: given.queue.clone().unwrap_or(defaults.queue.clone()),
897            max_output_size: given.max_output_size.unwrap_or(defaults.max_output_size),
898            ..defaults
899        };
900        let id = TaskId::new(name).ok()?;
901        let task = Task {
902            id,
903            kind: TaskKind::Script {
904                job: source.reference(name),
905                script: script?,
906                interpreter: interpreter?,
907                args,
908                env,
909                working_dir: working_dir?,
910                resource: None,
911            },
912            settings,
913            output_type: TypeDesc::ProcessResult,
914            outcomes: if outcomes.is_empty() {
915                default_outcomes()
916            } else {
917                outcomes
918            },
919            group: None,
920            expand: None,
921            secrets,
922            connections: Vec::new(),
923            cleanup: declared_cleanup.map(task_cleanup),
924        };
925        Some((task, given))
926    }
927
928    /// A path key as a path in the root; a `script` must name a file there.
929    fn path(&mut self, key: &str, source: &Source<'_>, file: bool) -> Option<String> {
930        let written = if file {
931            self.required_string(key)?
932        } else {
933            self.string(key)?
934        };
935        match source.in_root(&written) {
936            Ok(path) if file && !(source.exists)(&path) => {
937                self.problems.push(format!(
938                    "`{key}`: `{written}` isn't a file in the script root"
939                ));
940                None
941            }
942            Ok(path) => Some(path),
943            Err(error) => {
944                self.problems.push(format!("`{key}`: {error}"));
945                None
946            }
947        }
948    }
949
950    /// `env`: a variable's value as it is, or `{ secret = "path#key", storage = "..." }`.
951    fn env(&mut self) -> BTreeMap<String, Template> {
952        let mut env = BTreeMap::new();
953        let Some(given) = self.table.get("env") else {
954            return env;
955        };
956        let Value::Table(given) = given else {
957            self.wrong("env", "a table of variables");
958            return env;
959        };
960        for (variable, value) in given {
961            if !valid_variable(variable) {
962                self.problems.push(format!(
963                    "`env`: `{variable}` isn't a variable name (letters, digits and `_`, not a \
964                     digit first)"
965                ));
966                continue;
967            }
968            let template = match value {
969                Value::String(text) => Some(Template::text(text.clone())),
970                Value::Table(secret) => secret_of(secret, false)
971                    .map(|name| {
972                        Template(vec![TemplatePart::Ref(TemplateRef {
973                            reference: Reference::Secret(name),
974                            format: None,
975                            encode: None,
976                        })])
977                    })
978                    .map_err(|e| self.problems.push(format!("`env`: `{variable}`: {e}")))
979                    .ok(),
980                _ => {
981                    self.problems.push(format!(
982                        "`env`: `{variable}` is a string or `{{ secret = \"path#key\" }}`"
983                    ));
984                    None
985                }
986            };
987            env.extend(template.map(|t| (variable.clone(), t)));
988        }
989        env
990    }
991
992    /// `secrets`: `"path#key"`, `{ secret = "path#key", storage = "..." }` or
993    /// `{ prefix = "dir/", storage = "..." }`.
994    fn secrets(&mut self) -> Vec<SecretDecl> {
995        let Some(given) = self.table.get("secrets") else {
996            return Vec::new();
997        };
998        let Value::Array(items) = given else {
999            self.wrong("secrets", "a list of secrets");
1000            return Vec::new();
1001        };
1002        let mut secrets = Vec::new();
1003        for item in items {
1004            let declared = match item {
1005                Value::String(spec) => Ok(SecretDecl::Secret(name_of(spec, None))),
1006                Value::Table(table) if table.contains_key("prefix") => prefix_of(table),
1007                Value::Table(table) => secret_of(table, true).map(SecretDecl::Secret),
1008                _ => Err("an entry is `\"path#key\"` or a table".to_owned()),
1009            };
1010            match declared.and_then(|d| d.check().map(|()| d)) {
1011                Ok(declared) => secrets.push(declared),
1012                Err(error) => self.problems.push(format!("`secrets`: {error}")),
1013            }
1014        }
1015        secrets
1016    }
1017}
1018
1019/// An environment variable's name.
1020fn valid_variable(name: &str) -> bool {
1021    !name.is_empty()
1022        && !name.starts_with(|c: char| c.is_ascii_digit())
1023        && name.chars().all(|c| c.is_ascii_alphanumeric() || c == '_')
1024}
1025
1026/// `path#key`, or `path` for a whole secret, of `storage` (none: the default one).
1027fn name_of(spec: &str, storage: Option<String>) -> SecretName {
1028    let (path, key) = match spec.split_once('#') {
1029        Some((path, key)) => (path, Some(key)),
1030        None => (spec, None),
1031    };
1032    SecretName {
1033        storage,
1034        path: path.to_owned(),
1035        key: key.map(str::to_owned),
1036        default: None,
1037    }
1038}
1039
1040/// `{ secret = "path#key", storage = "..." }`; in `env`, a key's (a variable is text).
1041fn secret_of(table: &toml::Table, whole: bool) -> Result<SecretName, String> {
1042    let mut storage = None;
1043    let mut spec = None;
1044    for (key, value) in table {
1045        match (key.as_str(), value) {
1046            ("secret", Value::String(text)) => spec = Some(text.as_str()),
1047            ("storage", Value::String(text)) => storage = Some(text.clone()),
1048            ("secret" | "storage", _) => return Err(format!("`{key}` is a string")),
1049            _ => {
1050                return Err(format!(
1051                    "unknown key `{key}` (a secret has `secret` and `storage`)"
1052                ));
1053            }
1054        }
1055    }
1056    let spec = spec.ok_or("`secret = \"path#key\"` is required")?;
1057    let name = name_of(spec, storage);
1058    if !whole && name.key.is_none() {
1059        return Err(format!(
1060            "`{spec}` is a whole secret: a variable takes one key (`path#key`)"
1061        ));
1062    }
1063    name.check()?;
1064    Ok(name)
1065}
1066
1067/// `{ prefix = "dir/", storage = "..." }`.
1068fn prefix_of(table: &toml::Table) -> Result<SecretDecl, String> {
1069    let mut storage = None;
1070    let mut prefix = None;
1071    for (key, value) in table {
1072        match (key.as_str(), value) {
1073            ("prefix", Value::String(text)) => prefix = Some(text.clone()),
1074            ("storage", Value::String(text)) => storage = Some(text.clone()),
1075            ("prefix" | "storage", _) => return Err(format!("`{key}` is a string")),
1076            _ => {
1077                return Err(format!(
1078                    "unknown key `{key}` (a prefix has `prefix` and `storage`)"
1079                ));
1080            }
1081        }
1082    }
1083    let prefix = prefix.ok_or("`prefix` is required")?;
1084    Ok(SecretDecl::Prefix { storage, prefix })
1085}
1086
1087/// A TOML date or date-time as a moment.
1088fn moment_of(when: &Datetime, tz: &TimeZone) -> Result<Timestamp, String> {
1089    let text = when.to_string();
1090    if when.date.is_none() {
1091        return Err(format!("`{text}` has no date"));
1092    }
1093    if when.offset.is_some() {
1094        return text
1095            .parse::<Timestamp>()
1096            .map_err(|e| format!("`{text}`: {e}"));
1097    }
1098    let civil = if when.time.is_some() {
1099        text.parse::<DateTime>()
1100            .map_err(|e| format!("`{text}`: {e}"))?
1101    } else {
1102        text.parse::<Date>()
1103            .map_err(|e| format!("`{text}`: {e}"))?
1104            .to_datetime(jiff::civil::Time::midnight())
1105    };
1106    tz.to_ambiguous_zoned(civil)
1107        .compatible()
1108        .map(|zoned| zoned.timestamp())
1109        .map_err(|e| format!("`{text}`: {e}"))
1110}
1111
1112/// A script root as a parse sees it: where it is configured, and the copy of its code the
1113/// worker reports (decision 102).
1114#[derive(Debug, Clone, PartialEq, Eq)]
1115pub struct ScriptRoot {
1116    /// The configured directory (an absolute reference is resolved against it).
1117    pub configured: std::path::PathBuf,
1118    /// The copy its files are read from.
1119    pub copy: std::path::PathBuf,
1120}
1121
1122/// The declaration a `ScriptOperator` refers to (decision 293): `reference` is
1123/// `<root>:<path>#<name>` or `/abs/path/schedr.toml#<name>`, read from the copies of this
1124/// worker's script roots `scripts`. Returns the script root it names, if it names one (the
1125/// DAG root then uses it, decision 304, found or not), and the declaration or why it can't
1126/// be used.
1127pub fn lookup(
1128    reference: &str,
1129    scripts: &BTreeMap<String, ScriptRoot>,
1130) -> (
1131    Option<String>,
1132    Result<schedr_model::runner::ScriptDeclaration, String>,
1133) {
1134    let Some((location, name)) = reference.rsplit_once('#') else {
1135        return (
1136            None,
1137            Err(format!(
1138                "`{reference}`: a reference is `<root>:<path>/{FILE_NAME}#<job>` (or an \
1139                 absolute path to the file, then `#<job>`)"
1140            )),
1141        );
1142    };
1143    let resolved = if location.starts_with('/') {
1144        let file = std::path::Path::new(location);
1145        scripts.iter().find_map(|(root, at)| {
1146            let configured = at
1147                .configured
1148                .canonicalize()
1149                .unwrap_or_else(|_| at.configured.clone());
1150            let relative = file
1151                .strip_prefix(&configured)
1152                .or_else(|_| file.strip_prefix(&at.configured))
1153                .ok()?;
1154            Some((root.clone(), relative.to_string_lossy().replace('\\', "/")))
1155        })
1156    } else {
1157        location
1158            .split_once(':')
1159            .map(|(root, path)| (root.to_owned(), path.to_owned()))
1160    };
1161    let Some((root, path)) = resolved else {
1162        let why = if location.starts_with('/') {
1163            format!("`{location}` isn't in a script root of this worker (`SCHEDR_SCRIPT_PATH`)")
1164        } else {
1165            format!(
1166                "`{reference}`: a reference is `<root>:<path>/{FILE_NAME}#<job>` (or an \
1167                 absolute path to the file, then `#<job>`)"
1168            )
1169        };
1170        return (None, Err(why));
1171    };
1172    let found = (|| {
1173        let at = scripts.get(&root).ok_or_else(|| {
1174            format!("script root `{root}` isn't on this worker (`SCHEDR_SCRIPT_PATH`)")
1175        })?;
1176        if !is_config(&path) {
1177            return Err(format!("`{root}:{path}` isn't a `{FILE_NAME}`"));
1178        }
1179        if !stays_inside(&path) {
1180            return Err(format!(
1181                "`{root}:{path}`: a reference goes down into its script root (no `..`, not \
1182                 absolute)"
1183            ));
1184        }
1185        let exists = |file: &str| at.copy.join(file).is_file();
1186        let source = Source {
1187            root: &root,
1188            path: &path,
1189            exists: &exists,
1190        };
1191        let text = std::fs::read_to_string(at.copy.join(&path))
1192            .map_err(|_| format!("`{root}:{path}` isn't in script root `{root}`"))?;
1193        let declared = read(&text, &source)
1194            .map_err(|problems| format!("`{root}:{path}`: {}", problems.join("; ")))?;
1195        declared
1196            .iter()
1197            .find(|declaration| declaration.name == name)
1198            .map(Declaration::for_operator)
1199            .ok_or_else(|| format!("`{root}:{path}` declares no job `{name}`"))
1200    })();
1201    (Some(root), found)
1202}
1203
1204/// Whether a path relative to a root stays in it: only names going down (`.` aside).
1205#[must_use]
1206pub fn stays_inside(path: &str) -> bool {
1207    use std::path::Component;
1208    !path.is_empty()
1209        && std::path::Path::new(path)
1210            .components()
1211            .all(|part| matches!(part, Component::Normal(_) | Component::CurDir))
1212}
1213
1214/// A warning for each declaration whose interpreter isn't one of `known`.
1215fn unknown_interpreters(declared: &[Declaration], known: &[String]) -> Vec<String> {
1216    declared
1217        .iter()
1218        .flat_map(|declaration| {
1219            let own = match &declaration.task.kind {
1220                TaskKind::Script { interpreter, .. } => Some(("interpreter", interpreter)),
1221                _ => None,
1222            };
1223            let cleanup = declaration
1224                .given
1225                .cleanup
1226                .as_ref()
1227                .map(|cleanup| ("cleanup.interpreter", &cleanup.interpreter));
1228            own.into_iter()
1229                .chain(cleanup)
1230                .filter(|(_, interpreter)| !known.contains(interpreter))
1231                .map(|(key, interpreter)| {
1232                    format!(
1233                        "job `{}`: `{key}`: `{interpreter}` isn't an `[interpreters]` entry here \
1234                         (a worker without it rejects the job's tasks)",
1235                        declaration.name
1236                    )
1237                })
1238        })
1239        .collect()
1240}
1241
1242/// Whether a path in a root is a `schedr.toml`.
1243#[must_use]
1244pub fn is_config(path: &str) -> bool {
1245    path.rsplit('/').next() == Some(FILE_NAME)
1246}
1247
1248/// The `schedr.toml` files `wanted` of script root `root`, whose files (`files`, paths with
1249/// `/`) are in `dir`: a parsed file each, its standalone jobs as DAGs, or its problems as its
1250/// import error. With `interpreters` (a local check's configuration), a job whose interpreter
1251/// isn't one of them gets a warning: a worker without it rejects the job's tasks.
1252#[must_use]
1253pub fn read_root(
1254    root: &str,
1255    dir: &std::path::Path,
1256    (files, wanted): (&[String], &[String]),
1257    interpreters: Option<&[String]>,
1258) -> Vec<ParsedFile> {
1259    let exists = |path: &str| files.iter().any(|file| file == path);
1260    wanted
1261        .iter()
1262        .map(|path| {
1263            let source = Source {
1264                root,
1265                path,
1266                exists: &exists,
1267            };
1268            let read = std::fs::read_to_string(dir.join(path))
1269                .map_err(|e| vec![format!("can't read it: {e}")])
1270                .and_then(|text| self::read(&text, &source));
1271            let location = DagLocation {
1272                root: root.to_owned(),
1273                path: path.clone(),
1274            };
1275            match read {
1276                Ok(declared) => ParsedFile {
1277                    script_roots: Vec::new(),
1278                    path: path.clone(),
1279                    dags: declared.iter().filter_map(|d| d.dag(&location)).collect(),
1280                    connections: Vec::new(),
1281                    error: None,
1282                    warnings: interpreters
1283                        .map_or_else(Vec::new, |known| unknown_interpreters(&declared, known)),
1284                },
1285                Err(problems) => ParsedFile {
1286                    script_roots: Vec::new(),
1287                    path: path.clone(),
1288                    dags: Vec::new(),
1289                    connections: Vec::new(),
1290                    error: Some(ErrorSummary {
1291                        exception: INVALID_JOBS_EXCEPTION.to_owned(),
1292                        message: message(&problems),
1293                        traceback: String::new(),
1294                    }),
1295                    warnings: Vec::new(),
1296                },
1297            }
1298        })
1299        .collect()
1300}
1301
1302/// The problems of a `schedr.toml` as one import error's message, a line each.
1303#[must_use]
1304pub fn message(problems: &[String]) -> String {
1305    problems.join("\n")
1306}
1307
1308#[cfg(test)]
1309mod tests;