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