OXYGENHUB
# f2609cf795d8 oxygenflow / crates / flow-core / src / pipeline.rs
40.6 KiB · Rust · last changed Event::ScheduleAt: the jobs with a schedule line due at a minute (refs #24) 1 month ago source blame history raw
e0918b88 Andy McCall 1
//! `.flow/pipeline.kdl`: the M0 subset of spec §3 (docs/m0.md §1), parsed
2
//! from KDL 2.0 and validated before anything runs. Every problem is
3
//! reported with its line, and all of them at once.
4
5
use serde::{Deserialize, Serialize};
6
use std::collections::{BTreeMap, BTreeSet};
7
use std::fmt;
8
9
/// Where a pipeline lives in the state being built.
10
pub const PIPELINE_PATH: &str = ".flow/pipeline.kdl";
11
12
#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)]
13
pub struct Pipeline {
14
    pub schema_version: u32,
15
    /// By name.
16
    pub sandboxes: BTreeMap<String, Sandbox>,
17
    /// By name.
18
    pub jobs: BTreeMap<String, Job>,
bf7bb1b8 Andy McCall ↶ 19
    /// When the pipeline's jobs run, unless a job says (oxygenflow#24);
20
    /// absent: on every push and from "Run pipeline".
21
    #[serde(default, skip_serializing_if = "Option::is_none")]
22
    pub on: Option<On>,
23
}
24
25
/// What starts a job (`on { push "main"; tag "v*"; manual; schedule "0 3 * * *" }`).
26
#[derive(Clone, Debug, Default, PartialEq, Eq, Serialize, Deserialize)]
27
pub struct On {
28
    /// Bookmark globs a push runs it for; `Some(vec![])`: any bookmark.
29
    #[serde(default, skip_serializing_if = "Option::is_none")]
30
    pub push: Option<Vec<String>>,
31
    /// Tag globs a pushed tag runs it for; `Some(vec![])`: any tag.
32
    #[serde(default, skip_serializing_if = "Option::is_none")]
33
    pub tag: Option<Vec<String>>,
34
    /// From "Run pipeline" (and `oh run start`).
35
    #[serde(default, skip_serializing_if = "std::ops::Not::not")]
36
    pub manual: bool,
37
    /// Five-field cron lines, on the hub's clock, for the default bookmark.
38
    #[serde(default, skip_serializing_if = "Vec::is_empty")]
39
    pub schedule: Vec<String>,
e0918b88 Andy McCall 40
}
41
bf7bb1b8 Andy McCall ↶ 42
/// Why a run started, for [`On::matches`].
43
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
44
pub enum Event<'a> {
45
    /// A push moved this bookmark.
46
    Push(&'a str),
47
    /// This tag was pushed.
48
    Tag(&'a str),
49
    /// "Run pipeline", `oh run start`.
50
    Manual,
f2609cf7 Andy McCall ↶ 51
    /// A rerun of a scheduled run: any job with a schedule.
bf7bb1b8 Andy McCall ↶ 52
    Schedule,
f2609cf7 Andy McCall ↶ 53
    /// The hub's clock at a minute (UTC): the jobs with a line due then.
54
    ScheduleAt(When),
bf7bb1b8 Andy McCall ↶ 55
}
56
f2609cf7 Andy McCall ↶ 57
/// A minute of the hub's clock, UTC, as cron reads it.
58
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
59
pub struct When {
60
    pub minute: u32,
61
    pub hour: u32,
62
    pub day: u32,
63
    pub month: u32,
64
    /// 0 is Sunday.
65
    pub weekday: u32,
66
}
67
bf7bb1b8 Andy McCall ↶ 68
impl On {
69
    /// What a job without any `on` runs for: every push, and by hand.
70
    pub fn default_on() -> On {
71
        On { push: Some(vec![]), tag: None, manual: true, schedule: vec![] }
72
    }
73
74
    pub fn matches(&self, event: Event<'_>) -> bool {
75
        let any = |globs: &Option<Vec<String>>, name: &str| match globs {
76
            None => false,
77
            Some(g) if g.is_empty() => true,
78
            Some(g) => g.iter().any(|p| globset::Glob::new(p).is_ok_and(|p| p.compile_matcher().is_match(name))),
79
        };
80
        match event {
81
            Event::Push(b) => any(&self.push, b),
82
            Event::Tag(t) => any(&self.tag, t),
83
            Event::Manual => self.manual,
84
            Event::Schedule => !self.schedule.is_empty(),
f2609cf7 Andy McCall ↶ 85
            Event::ScheduleAt(w) => self
86
                .schedule
87
                .iter()
88
                .filter_map(|l| crate::cron::Cron::parse(l))
89
                .any(|c| c.matches(w.minute, w.hour, w.day, w.month, w.weekday)),
bf7bb1b8 Andy McCall ↶ 90
        }
91
    }
92
}
93
94
impl Pipeline {
95
    /// When `job` runs: its own `on`, else the pipeline's, else the default.
96
    pub fn on_of(&self, job: &Job) -> On {
97
        job.on.clone().or_else(|| self.on.clone()).unwrap_or_else(On::default_on)
98
    }
99
}
100
e0918b88 Andy McCall 101
#[derive(Clone, Copy, Debug, PartialEq, Eq, PartialOrd, Ord, Hash, Serialize, Deserialize)]
102
#[serde(rename_all = "lowercase")]
103
pub enum Runtime {
104
    /// Tier 0 (spec §4.1); refused in M0.
105
    Wasm,
106
    /// Tier 1 (spec §4.2): namespaces, Landlock, seccomp, cgroups.
107
    Syscall,
108
    /// Tier 2 (spec §4.3), the default.
109
    Microvm,
110
}
111
112
impl Runtime {
113
    pub fn as_str(self) -> &'static str {
114
        match self {
115
            Runtime::Wasm => "wasm",
116
            Runtime::Syscall => "syscall",
117
            Runtime::Microvm => "microvm",
118
        }
119
    }
120
}
121
122
#[derive(Clone, Copy, Debug, PartialEq, Eq, Serialize, Deserialize)]
123
#[serde(rename_all = "lowercase")]
124
pub enum Network {
125
    Isolated,
126
    Loopback,
127
    Egress,
128
}
129
130
impl Network {
131
    pub fn as_str(self) -> &'static str {
132
        match self {
133
            Network::Isolated => "isolated",
134
            Network::Loopback => "loopback",
135
            Network::Egress => "egress",
136
        }
137
    }
138
}
139
140
#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)]
141
pub struct Sandbox {
142
    pub name: String,
143
    pub runtime: Runtime,
144
    /// BLAKE3 of the rootfs image, hex.
145
    pub rootfs: String,
146
    pub memory_mib: u32,
147
    pub cpus: u32,
148
    pub network: Network,
a72abeee Andy McCall ↶ 149
    /// Environment every job in this sandbox starts from; a job's own `env`
150
    /// overrides it.
151
    #[serde(default, skip_serializing_if = "BTreeMap::is_empty")]
152
    pub env: BTreeMap<String, String>,
e576e086 Andy McCall ↶ 153
    /// Labels a runner must have to run jobs here (`runs-on`), sorted.
154
    #[serde(default, skip_serializing_if = "Vec::is_empty")]
155
    pub runs_on: Vec<String>,
02b127d2 Andy McCall ↶ 156
    /// How long each job here may run, in seconds (`timeout "2h"`), when
157
    /// the job does not say; the hub caps it at the site's maximum.
158
    #[serde(default, skip_serializing_if = "Option::is_none")]
159
    pub timeout_s: Option<u64>,
e0918b88 Andy McCall 160
}
161
162
#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)]
163
pub struct Job {
164
    pub name: String,
165
    pub sandbox: String,
166
    /// Glob patterns over repository paths (spec §6.2).
167
    pub scope: Vec<String>,
168
    /// Sorted.
169
    pub depends_on: Vec<String>,
170
    pub env: BTreeMap<String, String>,
171
    /// Executed as is: no shell, no expansion (spec §2.2 I2).
172
    pub exec: Vec<String>,
fc10d9e8 Andy McCall ↶ 173
    /// Ephemeral scratch mounts, sorted by target (spec §3.1 `mount`).
174
    #[serde(default, skip_serializing_if = "Vec::is_empty")]
175
    pub mounts: Vec<Mount>,
a67b97e9 Andy McCall ↶ 176
    /// Files the job produces, sorted by name (spec §5.2 `output`).
177
    #[serde(default, skip_serializing_if = "Vec::is_empty")]
178
    pub outputs: Vec<Output>,
e576e086 Andy McCall ↶ 179
    /// Labels a runner must have to take this job (`runs-on`), sorted;
180
    /// with its sandbox's, what the hub matches against a runner's.
181
    #[serde(default, skip_serializing_if = "Vec::is_empty")]
182
    pub runs_on: Vec<String>,
02b127d2 Andy McCall ↶ 183
    /// How long the job may run, in seconds (`timeout "90m"`); its
184
    /// sandbox's when absent, else the site's default (oxygenflow#23).
185
    #[serde(default, skip_serializing_if = "Option::is_none")]
186
    pub timeout_s: Option<u64>,
bf7bb1b8 Andy McCall ↶ 187
    /// When it runs, over the pipeline's `on` (oxygenflow#24).
188
    #[serde(default, skip_serializing_if = "Option::is_none")]
189
    pub on: Option<On>,
fc10d9e8 Andy McCall ↶ 190
}
191
c4285535 Andy McCall ↶ 192
impl Job {
a72abeee Andy McCall ↶ 193
    /// The job's environment on top of its sandbox's: what it runs with.
194
    pub fn in_sandbox(&self, sandbox: &Sandbox) -> Job {
195
        let mut job = self.clone();
196
        for (k, v) in &sandbox.env {
197
            job.env.entry(k.clone()).or_insert_with(|| v.clone());
198
        }
e576e086 Andy McCall ↶ 199
        job.runs_on.extend(sandbox.runs_on.iter().cloned());
200
        job.runs_on.sort();
201
        job.runs_on.dedup();
02b127d2 Andy McCall ↶ 202
        job.timeout_s = job.timeout_s.or(sandbox.timeout_s);
a72abeee Andy McCall ↶ 203
        job
204
    }
205
c4285535 Andy McCall ↶ 206
    /// The job with variables that tell it what it builds (`FLOW_STATE`,
207
    /// `FLOW_BOOKMARK` …) added to its environment; a variable the pipeline
208
    /// sets itself keeps the pipeline's value.
209
    pub fn with_flow_env(&self, vars: &[(String, String)]) -> Job {
210
        let mut job = self.clone();
211
        for (k, v) in vars {
212
            job.env.entry(k.clone()).or_insert_with(|| v.clone());
213
        }
214
        job
215
    }
216
}
217
fc10d9e8 Andy McCall ↶ 218
/// An ephemeral scratch mount: empty at the start of every job and gone
219
/// after it, so it cannot carry anything between jobs (spec §2.2 I4).
220
#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)]
221
pub struct Mount {
222
    pub source: MountSource,
223
    /// An absolute path under `/src` or `/tmp`.
224
    pub target: String,
225
    pub size_mib: u32,
226
}
227
228
#[derive(Clone, Copy, Debug, PartialEq, Eq, Serialize, Deserialize)]
229
#[serde(rename_all = "lowercase")]
230
pub enum MountSource {
231
    /// `ephemeral://tmpfs`: memory in the sandbox, counted against its memory-limit.
232
    Tmpfs,
233
    /// `ephemeral://disk`: a fresh sparse disk on the runner, for large build trees.
234
    Disk,
235
}
236
237
impl MountSource {
238
    pub fn as_str(self) -> &'static str {
239
        match self {
240
            MountSource::Tmpfs => "ephemeral://tmpfs",
241
            MountSource::Disk => "ephemeral://disk",
242
        }
243
    }
a67b97e9 Andy McCall ↶ 244
}
245
246
/// A file a job produces (spec §5.2): read from the job's disks when it
247
/// ends, kept in the repository as a blob, and named by its receipt.
248
#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)]
249
pub struct Output {
250
    /// The artifact's name, unique in the job.
251
    pub name: String,
252
    /// A clean absolute path under `/src`, not on a tmpfs mount.
253
    pub path: String,
254
}
255
256
/// Artifacts a job may declare.
257
pub const MAX_OUTPUTS: usize = 16;
258
259
/// Whether `p` is a clean absolute path strictly under `/src`, with nothing
260
/// a debugfs command line would have to quote.
261
fn output_path_ok(p: &str) -> bool {
262
    p.strip_prefix("/src/").is_some_and(|rest| {
263
        !rest.is_empty()
264
            && rest.split('/').all(|c| !c.is_empty() && c != "." && c != "..")
265
            && p.bytes().all(|b| b.is_ascii_graphic() && b != b'"' && b != b'\\')
266
    })
fc10d9e8 Andy McCall ↶ 267
}
268
269
/// Mounts a job may declare.
270
pub const MAX_MOUNTS: usize = 4;
271
/// Sizes a mount may have: 16 MiB to 64 GiB.
272
pub const MIN_MOUNT_MIB: u64 = 16;
273
pub const MAX_MOUNT_MIB: u64 = 64 * 1024;
274
275
/// Whether `t` is a clean absolute path strictly under `/src` or `/tmp`.
276
fn mount_target_ok(t: &str) -> bool {
277
    let under = t.strip_prefix("/src/").or_else(|| t.strip_prefix("/tmp/"));
278
    under.is_some_and(|rest| !rest.is_empty() && rest.split('/').all(|c| !c.is_empty() && c != "." && c != ".."))
e0918b88 Andy McCall 279
}
280
281
/// One problem in a pipeline, at a 1-based line.
282
#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)]
283
pub struct Problem {
284
    pub line: usize,
285
    pub message: String,
286
}
287
288
impl fmt::Display for Problem {
289
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
290
        write!(f, "line {}: {}", self.line, self.message)
291
    }
292
}
293
294
/// Every problem found, in line order.
295
#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize, thiserror::Error)]
296
pub struct Problems(pub Vec<Problem>);
297
298
impl fmt::Display for Problems {
299
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
300
        let lines: Vec<String> = self.0.iter().map(|p| p.to_string()).collect();
301
        f.write_str(&lines.join("\n"))
302
    }
303
}
304
305
const MIN_MEMORY_MIB: u64 = 64;
306
const MAX_MEMORY_MIB: u64 = 16 * 1024;
307
const MAX_CPUS: i128 = 16;
308
309
/// Nodes of the full spec that M0 recognises and refuses.
310
const LATER_TOP: &[&str] = &["publish", "secret"];
a67b97e9 Andy McCall ↶ 311
const LATER_JOB: &[&str] = &["secret", "attest"];
e0918b88 Andy McCall 312
313
struct Ctx<'a> {
314
    src: &'a str,
315
    problems: Vec<Problem>,
316
}
317
318
impl Ctx<'_> {
319
    fn line(&self, span: SourceSpan) -> usize {
320
        let at = span.offset().min(self.src.len());
321
        self.src[..at].bytes().filter(|b| *b == b'\n').count() + 1
322
    }
323
324
    fn err(&mut self, span: SourceSpan, message: impl Into<String>) {
325
        let line = self.line(span);
326
        self.problems.push(Problem { line, message: message.into() });
327
    }
328
329
    /// The node's arguments as strings; properties and other types are errors.
330
    fn strings(&mut self, node: &KdlNode) -> Vec<String> {
331
        let mut out = Vec::new();
332
        for e in node.entries() {
333
            if let Some(k) = e.name() {
334
                self.err(e.span(), format!("`{}` takes no property `{}`", node.name().value(), k.value()));
335
                continue;
336
            }
337
            match e.value() {
338
                KdlValue::String(s) => out.push(s.clone()),
339
                other => self.err(e.span(), format!("`{}` takes strings, not {}", node.name().value(), kind_of(other))),
340
            }
341
        }
342
        out
343
    }
344
345
    /// Exactly one string argument.
346
    fn one_string(&mut self, node: &KdlNode) -> Option<String> {
347
        let v = self.strings(node);
348
        if v.len() != 1 {
349
            self.err(node.span(), format!("`{}` takes one string", node.name().value()));
350
            return None;
351
        }
352
        v.into_iter().next()
353
    }
354
355
    fn one_integer(&mut self, node: &KdlNode) -> Option<i128> {
356
        match node.entries() {
357
            [e] if e.name().is_none() => match e.value() {
358
                KdlValue::Integer(n) => Some(*n),
359
                other => {
360
                    self.err(e.span(), format!("`{}` takes an integer, not {}", node.name().value(), kind_of(other)));
361
                    None
362
                }
363
            },
364
            _ => {
365
                self.err(node.span(), format!("`{}` takes one integer", node.name().value()));
366
                None
367
            }
368
        }
369
    }
370
371
    fn no_children(&mut self, node: &KdlNode) {
372
        if node.children().is_some() {
373
            self.err(node.span(), format!("`{}` takes no block", node.name().value()));
374
        }
375
    }
376
377
    fn name_ok(&mut self, span: SourceSpan, what: &str, name: &str) -> bool {
378
        let ok = !name.is_empty() && name.len() <= 64 && name.bytes().all(|b| b.is_ascii_alphanumeric() || b"._-".contains(&b));
379
        if !ok {
380
            self.err(span, format!("{what} name {name:?} must be 1 to 64 of A-Z a-z 0-9 . _ -"));
381
        }
382
        ok
383
    }
384
}
385
386
use kdl::{KdlDocument, KdlNode, KdlValue};
387
use miette::SourceSpan;
388
389
fn kind_of(v: &KdlValue) -> &'static str {
390
    match v {
391
        KdlValue::String(_) => "a string",
392
        KdlValue::Integer(_) => "an integer",
393
        KdlValue::Float(_) => "a number",
394
        KdlValue::Bool(_) => "a boolean",
395
        KdlValue::Null => "null",
396
    }
397
}
398
399
/// `"512MiB"`, `"4GiB"`, `"65536KiB"` to MiB.
400
fn parse_memory(s: &str) -> Option<u64> {
401
    let (num, unit) = s.split_at(s.find(|c: char| !c.is_ascii_digit())?);
402
    let n: u64 = num.parse().ok()?;
403
    let mib = match unit {
404
        "KiB" => n.is_multiple_of(1024).then_some(n / 1024)?,
405
        "MiB" => n,
406
        "GiB" => n.checked_mul(1024)?,
407
        _ => return None,
408
    };
409
    Some(mib)
410
}
411
b647ab72 Andy McCall ↶ 412
/// The line of the first escape KDL 2.0 does not have but shells and C
413
/// do (`\0NN`, `\e`, `\xNN`), as someone colouring output writes them.
414
fn foreign_escape_line(src: &str) -> Option<usize> {
415
    src.lines()
416
        .position(|l| {
417
            let b = l.as_bytes();
418
            b.windows(2).enumerate().any(|(i, w)| {
419
                w[0] == b'\\'
420
                    && (i == 0 || b[i - 1] != b'\\')
421
                    && (w[1] == b'e' || w[1] == b'x' || (w[1] == b'0' && b.get(i + 2).is_some_and(u8::is_ascii_digit)))
422
            })
423
        })
424
        .map(|i| i + 1)
425
}
426
e0918b88 Andy McCall 427
impl Pipeline {
428
    /// Parse and validate a pipeline document.
429
    pub fn parse(src: &str) -> Result<Pipeline, Problems> {
430
        let doc = match KdlDocument::parse_v2(src) {
431
            Ok(d) => d,
432
            Err(e) => {
433
                let mut ctx = Ctx { src, problems: Vec::new() };
434
                for d in &e.diagnostics {
435
                    let msg = d.message.clone().or_else(|| d.label.clone()).unwrap_or_else(|| "not valid KDL 2.0".into());
436
                    ctx.err(d.span, msg);
437
                }
438
                if ctx.problems.is_empty() {
439
                    ctx.problems.push(Problem { line: 1, message: "not valid KDL 2.0".into() });
b647ab72 Andy McCall ↶ 440
                }
441
                if let Some(line) = foreign_escape_line(src) {
442
                    ctx.problems.push(Problem {
443
                        line,
444
                        message: "KDL strings have no \\033, \\e or \\x escapes: write ESC (for ANSI colours) as \\u{1b}".into(),
445
                    });
e0918b88 Andy McCall 446
                }
447
                return Err(Problems(ctx.problems));
448
            }
449
        };
450
        let mut ctx = Ctx { src, problems: Vec::new() };
451
        let mut schema = None;
452
        let mut sandboxes = BTreeMap::new();
453
        let mut jobs: BTreeMap<String, (Job, SourceSpan)> = BTreeMap::new();
bf7bb1b8 Andy McCall ↶ 454
        let mut on = None;
e0918b88 Andy McCall 455
        for node in doc.nodes() {
456
            match node.name().value() {
bf7bb1b8 Andy McCall ↶ 457
                "on" => {
458
                    if on.is_some() {
459
                        ctx.err(node.span(), "`on` is given twice");
460
                    }
461
                    on = Some(parse_on(&mut ctx, node));
462
                }
e0918b88 Andy McCall 463
                "schema-version" => {
464
                    ctx.no_children(node);
465
                    match ctx.one_integer(node) {
466
                        Some(1) => schema = Some(1),
467
                        Some(n) => ctx.err(node.span(), format!("schema-version {n} is not supported; this runner reads 1")),
468
                        None => {}
469
                    }
470
                }
471
                "sandbox" => {
472
                    if let Some(sb) = parse_sandbox(&mut ctx, node) {
473
                        if sandboxes.contains_key(&sb.name) {
474
                            ctx.err(node.span(), format!("sandbox {:?} is declared twice", sb.name));
475
                        } else {
476
                            sandboxes.insert(sb.name.clone(), sb);
477
                        }
478
                    }
479
                }
480
                "job" => {
481
                    if let Some(job) = parse_job(&mut ctx, node) {
482
                        if jobs.contains_key(&job.name) {
483
                            ctx.err(node.span(), format!("job {:?} is declared twice", job.name));
484
                        } else {
485
                            jobs.insert(job.name.clone(), (job, node.span()));
486
                        }
487
                    }
488
                }
489
                n if LATER_TOP.contains(&n) => ctx.err(node.span(), format!("`{n}` is not in M0 yet")),
bf7bb1b8 Andy McCall ↶ 490
                n => ctx.err(node.span(), format!("unknown node `{n}`; expected schema-version, on, sandbox or job")),
e0918b88 Andy McCall 491
            }
492
        }
493
        if schema.is_none() && !ctx.problems.iter().any(|p| p.message.contains("schema-version")) {
494
            ctx.problems.push(Problem { line: 1, message: "`schema-version 1` is required".into() });
495
        }
496
        if jobs.is_empty() && ctx.problems.is_empty() {
497
            ctx.problems.push(Problem { line: 1, message: "a pipeline needs at least one job".into() });
498
        }
499
        // References and cycles.
500
        for (job, span) in jobs.values() {
501
            if !job.sandbox.is_empty() && !sandboxes.contains_key(&job.sandbox) {
502
                ctx.err(*span, format!("job {:?} uses sandbox {:?}, which is not declared", job.name, job.sandbox));
503
            }
504
            for d in &job.depends_on {
505
                if !jobs.contains_key(d) {
506
                    ctx.err(*span, format!("job {:?} depends on {:?}, which is not declared", job.name, d));
507
                } else if d == &job.name {
508
                    ctx.err(*span, format!("job {:?} depends on itself", job.name));
509
                }
510
            }
511
        }
512
        let graph: BTreeMap<&str, Vec<&str>> =
513
            jobs.values().map(|(j, _)| (j.name.as_str(), j.depends_on.iter().map(String::as_str).collect())).collect();
514
        if let Some(cycle) = find_cycle(&graph) {
515
            let span = jobs[cycle[0]].1;
516
            ctx.err(span, format!("jobs depend on each other in a cycle: {}", cycle.join(" → ")));
517
        }
518
        if !ctx.problems.is_empty() {
519
            ctx.problems.sort_by_key(|p| p.line);
520
            return Err(Problems(ctx.problems));
521
        }
bf7bb1b8 Andy McCall ↶ 522
        Ok(Pipeline { schema_version: 1, sandboxes, jobs: jobs.into_iter().map(|(k, (j, _))| (k, j)).collect(), on })
e0918b88 Andy McCall 523
    }
524
525
    /// Jobs in an order where each comes after what it depends on (ties by name).
526
    pub fn order(&self) -> Vec<&Job> {
527
        let mut done: BTreeSet<&str> = BTreeSet::new();
528
        let mut out = Vec::with_capacity(self.jobs.len());
529
        while out.len() < self.jobs.len() {
530
            let before = out.len();
531
            for j in self.jobs.values() {
532
                if !done.contains(j.name.as_str()) && j.depends_on.iter().all(|d| done.contains(d.as_str())) {
533
                    out.push(j);
534
                }
535
            }
536
            for j in &out[before..] {
537
                done.insert(j.name.as_str());
538
            }
539
            if out.len() == before {
540
                break; // validated pipelines have no cycles
541
            }
542
        }
543
        out
544
    }
545
546
    /// Each job's depth: 0 without dependencies, else one more than its deepest dependency.
547
    pub fn depths(&self) -> BTreeMap<&str, usize> {
548
        let mut depth: BTreeMap<&str, usize> = BTreeMap::new();
549
        for j in self.order() {
550
            let d = j.depends_on.iter().map(|x| depth.get(x.as_str()).copied().unwrap_or(0) + 1).max().unwrap_or(0);
551
            depth.insert(j.name.as_str(), d);
552
        }
553
        depth
554
    }
555
}
556
557
fn find_cycle<'a>(graph: &BTreeMap<&'a str, Vec<&'a str>>) -> Option<Vec<&'a str>> {
558
    #[derive(Clone, Copy, PartialEq)]
559
    enum Mark {
560
        Visiting,
561
        Done,
562
    }
563
    fn visit<'a>(
564
        n: &'a str,
565
        graph: &BTreeMap<&'a str, Vec<&'a str>>,
566
        marks: &mut BTreeMap<&'a str, Mark>,
567
        stack: &mut Vec<&'a str>,
568
    ) -> Option<Vec<&'a str>> {
569
        match marks.get(n) {
570
            Some(Mark::Done) => return None,
571
            Some(Mark::Visiting) => {
572
                let at = stack.iter().position(|s| *s == n).unwrap_or(0);
573
                let mut c = stack[at..].to_vec();
574
                c.push(n);
575
                return Some(c);
576
            }
577
            None => {}
578
        }
579
        marks.insert(n, Mark::Visiting);
580
        stack.push(n);
581
        for d in graph.get(n).into_iter().flatten() {
582
            if graph.contains_key(d) && *d != n {
583
                if let Some(c) = visit(d, graph, marks, stack) {
584
                    return Some(c);
585
                }
586
            }
587
        }
588
        stack.pop();
589
        marks.insert(n, Mark::Done);
590
        None
591
    }
592
    let mut marks = BTreeMap::new();
593
    for n in graph.keys() {
594
        let mut stack = Vec::new();
595
        if let Some(c) = visit(n, graph, &mut marks, &mut stack) {
596
            return Some(c);
597
        }
598
    }
599
    None
600
}
601
602
fn block<'a>(ctx: &mut Ctx, node: &'a KdlNode) -> &'a [KdlNode] {
603
    match node.children() {
604
        Some(d) => d.nodes(),
605
        None => {
606
            ctx.err(node.span(), format!("`{}` needs a block {{ … }}", node.name().value()));
607
            &[]
608
        }
609
    }
610
}
611
612
fn parse_sandbox(ctx: &mut Ctx, node: &KdlNode) -> Option<Sandbox> {
613
    let name = ctx.one_string(node)?;
614
    let named = ctx.name_ok(node.span(), "sandbox", &name);
615
    let (mut runtime, mut rootfs, mut memory, mut cpus, mut network) =
616
        (Some(Runtime::Microvm), None, Some(1024u32), Some(1u32), Some(Network::Isolated));
617
    let mut seen = BTreeSet::new();
a72abeee Andy McCall ↶ 618
    let mut env = BTreeMap::new();
e576e086 Andy McCall ↶ 619
    let mut runs_on = Vec::new();
02b127d2 Andy McCall ↶ 620
    let mut timeout_s = None;
e0918b88 Andy McCall 621
    for c in block(ctx, node) {
622
        let key = c.name().value();
e576e086 Andy McCall ↶ 623
        if key != "runs-on" && !seen.insert(key.to_string()) {
e0918b88 Andy McCall 624
            ctx.err(c.span(), format!("`{key}` is given twice"));
a72abeee Andy McCall ↶ 625
        }
626
        if key == "env" {
627
            parse_env(ctx, c, &mut env);
628
            continue;
e0918b88 Andy McCall 629
        }
e576e086 Andy McCall ↶ 630
        if key == "runs-on" {
631
            ctx.no_children(c);
632
            parse_labels(ctx, c, &mut runs_on);
633
            continue;
634
        }
e0918b88 Andy McCall 635
        ctx.no_children(c);
636
        match key {
637
            "runtime" => {
638
                runtime = match ctx.one_string(c).as_deref() {
639
                    Some("microvm") => Some(Runtime::Microvm),
640
                    Some("syscall") | Some("gvisor") => Some(Runtime::Syscall),
641
                    Some("wasm") => {
642
                        ctx.err(c.span(), "runtime \"wasm\" is not in M0 yet; use \"microvm\" or \"syscall\"");
643
                        None
644
                    }
645
                    Some(other) => {
646
                        ctx.err(c.span(), format!("runtime {other:?}: expected \"microvm\", \"syscall\" or \"wasm\""));
647
                        None
648
                    }
649
                    None => None,
650
                }
651
            }
652
            "rootfs" => {
653
                rootfs = match ctx.one_string(c) {
654
                    Some(r) => match r.strip_prefix("cas://blob/") {
655
                        Some(h) if h.len() == 64 && h.bytes().all(|b| b.is_ascii_hexdigit() && !b.is_ascii_uppercase()) => {
656
                            Some(h.to_string())
657
                        }
658
                        _ => {
659
                            ctx.err(c.span(), format!("rootfs {r:?}: expected \"cas://blob/\" and 64 lower-case hex digits"));
660
                            None
661
                        }
662
                    },
663
                    None => None,
664
                }
665
            }
666
            "memory-limit" => {
667
                memory = match ctx.one_string(c) {
668
                    Some(m) => match parse_memory(&m) {
669
                        Some(mib) if (MIN_MEMORY_MIB..=MAX_MEMORY_MIB).contains(&mib) => Some(mib as u32),
670
                        Some(_) => {
671
                            ctx.err(c.span(), format!("memory-limit {m:?} must be from 64MiB to 16GiB"));
672
                            None
673
                        }
674
                        None => {
675
                            ctx.err(c.span(), format!("memory-limit {m:?}: expected a whole number of KiB, MiB or GiB, as \"4GiB\""));
676
                            None
677
                        }
678
                    },
679
                    None => None,
680
                }
681
            }
682
            "cpu-limit" => {
683
                cpus = match ctx.one_integer(c) {
684
                    Some(n) if (1..=MAX_CPUS).contains(&n) => Some(n as u32),
685
                    Some(n) => {
686
                        ctx.err(c.span(), format!("cpu-limit {n} must be from 1 to {MAX_CPUS}"));
687
                        None
688
                    }
689
                    None => None,
690
                }
691
            }
692
            "network" => {
693
                network = match ctx.one_string(c).as_deref() {
694
                    Some("isolated") => Some(Network::Isolated),
eb5c4db6 Andy McCall ↶ 695
                    // Loopback only: the guest's `lo` comes up, and it still has
696
                    // no device that reaches anything outside it.
697
                    Some("loopback") => Some(Network::Loopback),
698
                    Some("egress") => {
699
                        ctx.err(c.span(), "network \"egress\" is not in M0; M0 has \"isolated\" and \"loopback\"");
e0918b88 Andy McCall 700
                        None
701
                    }
702
                    Some(other) => {
703
                        ctx.err(c.span(), format!("network {other:?}: expected \"isolated\", \"loopback\" or \"egress\""));
704
                        None
705
                    }
706
                    None => None,
707
                }
708
            }
02b127d2 Andy McCall ↶ 709
            "timeout" => timeout_s = parse_timeout(ctx, c),
e0918b88 Andy McCall 710
            other => ctx.err(c.span(), format!("unknown sandbox setting `{other}`")),
711
        }
712
    }
713
    if rootfs.is_none() && !seen.contains("rootfs") {
714
        ctx.err(node.span(), format!("sandbox {name:?} needs a rootfs"));
715
    }
716
    if !named {
717
        return None;
e576e086 Andy McCall ↶ 718
    }
02b127d2 Andy McCall ↶ 719
    Some(Sandbox { name, runtime: runtime?, rootfs: rootfs?, memory_mib: memory?, cpus: cpus?, network: network?, env, runs_on, timeout_s })
bf7bb1b8 Andy McCall ↶ 720
}
721
722
/// An `on` block: `push` and `tag` with globs (none: any), `manual`,
723
/// `schedule` with five-field cron lines.
724
fn parse_on(ctx: &mut Ctx, node: &KdlNode) -> On {
725
    let mut on = On::default();
726
    if !node.entries().is_empty() {
727
        ctx.err(node.span(), "`on` takes a block: on { push \"main\"; tag \"v*\"; manual }");
728
    }
729
    let globs = |ctx: &mut Ctx, c: &KdlNode| -> Vec<String> {
730
        let g = ctx.strings(c);
731
        for p in &g {
732
            if let Err(e) = globset::Glob::new(p) {
733
                ctx.err(c.span(), format!("{p:?}: {e}"));
734
            }
735
        }
736
        g
737
    };
738
    for c in block(ctx, node) {
739
        ctx.no_children(c);
740
        match c.name().value() {
741
            "push" => on.push.get_or_insert_with(Vec::new).extend(globs(ctx, c)),
742
            "tag" => on.tag.get_or_insert_with(Vec::new).extend(globs(ctx, c)),
743
            "manual" => on.manual = true,
744
            "schedule" => {
745
                for line in ctx.strings(c) {
746
                    if crate::cron::Cron::parse(&line).is_some() {
747
                        on.schedule.push(line);
748
                    } else {
749
                        ctx.err(
750
                            c.span(),
751
                            format!("schedule {line:?}: expected five cron fields (minute hour day month weekday), as \"0 3 * * *\""),
752
                        );
753
                    }
754
                }
755
            }
756
            other => ctx.err(c.span(), format!("unknown `on` event `{other}`; expected push, tag, manual or schedule")),
757
        }
758
    }
759
    if on.push.is_none() && on.tag.is_none() && !on.manual && on.schedule.is_empty() {
760
        ctx.err(node.span(), "`on` names no event, so nothing would run it");
761
    }
762
    on
e576e086 Andy McCall ↶ 763
}
764
02b127d2 Andy McCall ↶ 765
/// The longest a pipeline may ask a job to run.
766
pub const MAX_TIMEOUT_S: u64 = 24 * 3600;
767
768
/// A duration: whole hours, minutes and seconds in that order, each
769
/// optional, as "90m", "2h", "1h30m" or "45s".
770
pub fn parse_duration(s: &str) -> Option<u64> {
771
    let (mut total, mut num, mut last) = (0u64, String::new(), 0u8);
772
    for ch in s.chars() {
773
        if ch.is_ascii_digit() {
774
            num.push(ch);
775
            continue;
776
        }
777
        let (unit, mult) = match ch {
778
            'h' => (1, 3600),
779
            'm' => (2, 60),
780
            's' => (3, 1),
781
            _ => return None,
782
        };
783
        // Each unit once, largest first, each with its number.
784
        if num.is_empty() || unit <= last {
785
            return None;
786
        }
787
        last = unit;
788
        total = total.checked_add(num.parse::<u64>().ok()?.checked_mul(mult)?)?;
789
        num.clear();
790
    }
791
    (num.is_empty() && total > 0).then_some(total)
792
}
793
794
/// A `timeout` line: one duration, from a minute to a day.
795
fn parse_timeout(ctx: &mut Ctx, c: &KdlNode) -> Option<u64> {
796
    let t = ctx.one_string(c)?;
797
    match parse_duration(&t) {
798
        Some(secs) if (60..=MAX_TIMEOUT_S).contains(&secs) => Some(secs),
799
        Some(_) => {
800
            ctx.err(c.span(), format!("timeout {t:?} must be from 1m to 24h"));
801
            None
802
        }
803
        None => {
804
            ctx.err(c.span(), format!("timeout {t:?}: expected hours, minutes and seconds, as \"90m\" or \"1h30m\""));
805
            None
806
        }
807
    }
808
}
809
e576e086 Andy McCall ↶ 810
/// The labels of a `runs-on` line: lower-case letters, digits, `-`, `_`
811
/// and `.`, at most 64 bytes each; into `into`, sorted, once each.
812
fn parse_labels(ctx: &mut Ctx, c: &KdlNode, into: &mut Vec<String>) {
813
    let labels = ctx.strings(c);
814
    if labels.is_empty() {
815
        ctx.err(c.span(), "`runs-on` needs one or more labels, as runs-on \"riscv64\"");
a72abeee Andy McCall ↶ 816
    }
e576e086 Andy McCall ↶ 817
    for l in labels {
818
        let ok = !l.is_empty()
819
            && l.len() <= 64
820
            && l.bytes().all(|b| b.is_ascii_lowercase() || b.is_ascii_digit() || matches!(b, b'-' | b'_' | b'.'));
821
        if ok {
822
            into.push(l);
823
        } else {
824
            ctx.err(c.span(), format!("runs-on {l:?}: a label is lower-case letters, digits, -, _ and ., at most 64"));
825
        }
826
    }
827
    into.sort();
828
    into.dedup();
a72abeee Andy McCall ↶ 829
}
830
831
/// An `env` block of `NAME "value"` lines, into `env`.
832
fn parse_env(ctx: &mut Ctx, c: &KdlNode, env: &mut BTreeMap<String, String>) {
833
    if !c.entries().is_empty() {
834
        ctx.err(c.span(), "`env` takes a block of NAME \"value\" lines");
835
    }
836
    for e in block(ctx, c) {
837
        let k = e.name().value().to_string();
838
        let valid =
839
            !k.is_empty() && !k.starts_with(|c: char| c.is_ascii_digit()) && k.bytes().all(|b| b.is_ascii_alphanumeric() || b == b'_');
840
        if !valid {
841
            ctx.err(e.span(), format!("environment name {k:?} must be letters, digits and _"));
842
            continue;
843
        }
844
        ctx.no_children(e);
845
        if let Some(v) = ctx.one_string(e) {
846
            if env.insert(k.clone(), v).is_some() {
847
                ctx.err(e.span(), format!("environment {k} is set twice"));
848
            }
849
        }
e0918b88 Andy McCall 850
    }
851
}
852
fc10d9e8 Andy McCall ↶ 853
/// `mount { source "ephemeral://disk"; target "/src/target"; size "8GiB" }`.
854
fn parse_mount(ctx: &mut Ctx, node: &KdlNode) -> Option<Mount> {
855
    let (mut source, mut target, mut size) = (None, None, None);
856
    let mut seen = BTreeSet::new();
857
    for c in block(ctx, node) {
858
        let key = c.name().value();
859
        if !seen.insert(key.to_string()) {
860
            ctx.err(c.span(), format!("`{key}` is given twice"));
861
            continue;
862
        }
863
        ctx.no_children(c);
864
        match key {
865
            "source" => {
866
                source = match ctx.one_string(c).as_deref() {
867
                    Some("ephemeral://tmpfs") => Some(MountSource::Tmpfs),
868
                    Some("ephemeral://disk") => Some(MountSource::Disk),
869
                    Some(other) => {
870
                        ctx.err(
871
                            c.span(),
872
                            format!("mount source {other:?} is not in M0 yet; M0 mounts \"ephemeral://tmpfs\" or \"ephemeral://disk\""),
873
                        );
874
                        None
875
                    }
876
                    None => None,
877
                }
878
            }
879
            "target" => {
880
                target = match ctx.one_string(c) {
881
                    Some(t) if mount_target_ok(&t) => Some(t),
882
                    Some(t) => {
883
                        ctx.err(
884
                            c.span(),
885
                            format!("mount target {t:?} must be an absolute path under /src or /tmp, without . or .. or a trailing /"),
886
                        );
887
                        None
888
                    }
889
                    None => None,
890
                }
891
            }
892
            "size" => {
893
                size = match ctx.one_string(c) {
894
                    Some(m) => match parse_memory(&m) {
895
                        Some(mib) if (MIN_MOUNT_MIB..=MAX_MOUNT_MIB).contains(&mib) => Some(mib as u32),
896
                        Some(_) => {
897
                            ctx.err(c.span(), format!("mount size {m:?} must be from 16MiB to 64GiB"));
898
                            None
899
                        }
900
                        None => {
901
                            ctx.err(c.span(), format!("mount size {m:?}: expected a whole number of KiB, MiB or GiB, as \"8GiB\""));
902
                            None
903
                        }
904
                    },
905
                    None => None,
906
                }
907
            }
908
            "readonly" | "include" => ctx.err(c.span(), format!("mount `{key}` is not in M0 yet")),
909
            other => ctx.err(c.span(), format!("unknown mount setting `{other}`")),
910
        }
911
    }
912
    for (name, missing) in [("source", source.is_none()), ("target", target.is_none()), ("size", size.is_none())] {
913
        if missing && !seen.contains(name) {
914
            ctx.err(node.span(), format!("a mount needs a {name}"));
915
        }
916
    }
917
    Some(Mount { source: source?, target: target?, size_mib: size? })
918
}
919
a67b97e9 Andy McCall ↶ 920
/// `output { artifact "name" { path "/src/target/release/tool" } }`.
921
fn parse_output(ctx: &mut Ctx, node: &KdlNode, job: &mut Job) {
922
    if !node.entries().is_empty() {
923
        ctx.err(node.span(), "`output` takes a block of artifacts");
924
    }
925
    for a in block(ctx, node) {
926
        if a.name().value() != "artifact" {
927
            ctx.err(a.span(), format!("unknown output `{}`; outputs are `artifact \"name\" {{ path \"/src/…\" }}`", a.name().value()));
928
            continue;
929
        }
930
        let Some(name) = ctx.one_string(a) else { continue };
931
        if !ctx.name_ok(a.span(), "artifact", &name) {
932
            continue;
933
        }
934
        let mut path = None;
935
        for c in block(ctx, a) {
936
            ctx.no_children(c);
937
            match c.name().value() {
938
                "path" => match ctx.one_string(c) {
939
                    Some(p) if output_path_ok(&p) => path = Some(p),
940
                    Some(p) => ctx.err(
941
                        c.span(),
942
                        format!("artifact path {p:?} must be an absolute path under /src, without . or .., quotes or spaces"),
943
                    ),
944
                    None => {}
945
                },
946
                "format" => {
947
                    if ctx.one_string(c).as_deref() != Some("blob") {
948
                        ctx.err(c.span(), "artifact format is \"blob\"");
949
                    }
950
                }
951
                other => ctx.err(c.span(), format!("unknown artifact setting `{other}`")),
952
            }
953
        }
954
        let Some(path) = path else {
955
            ctx.err(a.span(), format!("artifact {name:?} needs a path"));
956
            continue;
957
        };
958
        if job.outputs.iter().any(|o| o.name == name) {
959
            ctx.err(a.span(), format!("artifact {name:?} is given twice"));
960
        } else if job.outputs.len() == MAX_OUTPUTS {
961
            ctx.err(a.span(), format!("a job has at most {MAX_OUTPUTS} artifacts"));
962
        } else {
963
            job.outputs.push(Output { name, path });
964
        }
965
    }
966
}
967
e0918b88 Andy McCall 968
fn parse_job(ctx: &mut Ctx, node: &KdlNode) -> Option<Job> {
969
    let name = ctx.one_string(node)?;
970
    let named = ctx.name_ok(node.span(), "job", &name);
fc10d9e8 Andy McCall ↶ 971
    let mut job = Job {
972
        name: name.clone(),
973
        sandbox: String::new(),
974
        scope: vec![],
975
        depends_on: vec![],
976
        env: BTreeMap::new(),
977
        exec: vec![],
978
        mounts: vec![],
a67b97e9 Andy McCall ↶ 979
        outputs: vec![],
e576e086 Andy McCall ↶ 980
        runs_on: vec![],
02b127d2 Andy McCall ↶ 981
        timeout_s: None,
bf7bb1b8 Andy McCall ↶ 982
        on: None,
fc10d9e8 Andy McCall ↶ 983
    };
e0918b88 Andy McCall 984
    let mut seen = BTreeSet::new();
a67b97e9 Andy McCall ↶ 985
    let mut outputs_at = None;
e0918b88 Andy McCall 986
    for c in block(ctx, node) {
987
        let key = c.name().value();
e576e086 Andy McCall ↶ 988
        if key != "scope" && key != "depends-on" && key != "mount" && key != "runs-on" && !seen.insert(key.to_string()) {
e0918b88 Andy McCall 989
            ctx.err(c.span(), format!("`{key}` is given twice"));
990
        }
991
        match key {
992
            "sandbox" => {
993
                ctx.no_children(c);
994
                job.sandbox = ctx.one_string(c).unwrap_or_default();
995
            }
996
            "scope" => {
997
                ctx.no_children(c);
998
                for g in ctx.strings(c) {
999
                    match globset::Glob::new(&g) {
1000
                        Ok(_) => job.scope.push(g),
1001
                        Err(e) => ctx.err(c.span(), format!("scope {g:?}: {e}")),
1002
                    }
1003
                }
1004
            }
1005
            "depends-on" => {
1006
                ctx.no_children(c);
1007
                job.depends_on.extend(ctx.strings(c));
e576e086 Andy McCall ↶ 1008
            }
1009
            "runs-on" => {
1010
                ctx.no_children(c);
1011
                parse_labels(ctx, c, &mut job.runs_on);
02b127d2 Andy McCall ↶ 1012
            }
1013
            "timeout" => {
1014
                ctx.no_children(c);
1015
                job.timeout_s = parse_timeout(ctx, c);
e0918b88 Andy McCall 1016
            }
bf7bb1b8 Andy McCall ↶ 1017
            "on" => job.on = Some(parse_on(ctx, c)),
a72abeee Andy McCall ↶ 1018
            "env" => parse_env(ctx, c, &mut job.env),
e0918b88 Andy McCall 1019
            "exec" => {
1020
                ctx.no_children(c);
1021
                job.exec = ctx.strings(c);
1022
                if job.exec.is_empty() {
1023
                    ctx.err(c.span(), "`exec` needs a program and its arguments");
1024
                } else if job.exec.iter().any(|a| a.contains('\0')) {
1025
                    ctx.err(c.span(), "`exec` arguments cannot contain NUL");
1026
                }
1027
            }
fc10d9e8 Andy McCall ↶ 1028
            "mount" => {
1029
                if !c.entries().is_empty() {
1030
                    ctx.err(c.span(), "`mount` takes a block of source, target and size");
1031
                }
1032
                if let Some(m) = parse_mount(ctx, c) {
1033
                    if job.mounts.len() == MAX_MOUNTS {
1034
                        ctx.err(c.span(), format!("a job has at most {MAX_MOUNTS} mounts"));
1035
                    } else if let Some(other) = job.mounts.iter().find(|o| {
1036
                        o.target == m.target
1037
                            || m.target.starts_with(&format!("{}/", o.target))
1038
                            || o.target.starts_with(&format!("{}/", m.target))
1039
                    }) {
1040
                        ctx.err(c.span(), format!("mount {:?} overlaps mount {:?}", m.target, other.target));
1041
                    } else {
1042
                        job.mounts.push(m);
1043
                    }
1044
                }
1045
            }
a67b97e9 Andy McCall ↶ 1046
            "output" => {
1047
                outputs_at = Some(c.span());
1048
                parse_output(ctx, c, &mut job);
1049
            }
e0918b88 Andy McCall 1050
            n if LATER_JOB.contains(&n) => ctx.err(c.span(), format!("`{n}` is not in M0 yet")),
1051
            other => ctx.err(c.span(), format!("unknown job setting `{other}`")),
1052
        }
1053
    }
fc10d9e8 Andy McCall ↶ 1054
    job.mounts.sort_by(|a, b| a.target.cmp(&b.target));
a67b97e9 Andy McCall ↶ 1055
    job.outputs.sort_by(|a, b| a.name.cmp(&b.name));
1056
    // A tmpfs is gone when the job ends; nothing on it can be kept.
1057
    for o in &job.outputs {
1058
        if let Some(m) = job.mounts.iter().find(|m| m.source == MountSource::Tmpfs && o.path.starts_with(&format!("{}/", m.target))) {
1059
            ctx.err(
1060
                outputs_at.unwrap_or(node.span()),
1061
                format!(
1062
                    "artifact {:?} is on the tmpfs mount {:?}, which is gone when the job ends; use ephemeral://disk",
1063
                    o.name, m.target
1064
                ),
1065
            );
1066
        }
1067
    }
e0918b88 Andy McCall 1068
    if job.sandbox.is_empty() && !seen.contains("sandbox") {
1069
        ctx.err(node.span(), format!("job {name:?} needs a sandbox"));
1070
    }
1071
    if job.exec.is_empty() && !seen.contains("exec") {
1072
        ctx.err(node.span(), format!("job {name:?} needs an exec"));
1073
    }
1074
    job.depends_on.sort();
1075
    job.depends_on.dedup();
1076
    // Kept even when incomplete, so its references are checked too; the
1077
    // problems above already make the pipeline invalid.
1078
    named.then_some(job)
1079
}