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