OXYGENHUB

Coverage / crates/flow-core/src/pipeline.rs 91.0%

986 of 1083 lines run, 133 of 228 functions · run #177 on main · run missed

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 rerun of a scheduled run: any job with a schedule.
52
    Schedule,
53
    /// The hub's clock at a minute (UTC): the jobs with a line due then.
54
    ScheduleAt(When),
55
}
56
57
/// A minute of the hub's clock, UTC, as cron reads it.
58
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
59
pub struct When {
60
    pub minute: u32,
61
    pub hour: u32,
62
    pub day: u32,
63
    pub month: u32,
64
    /// 0 is Sunday.
65
    pub weekday: u32,
66
}
67
68
impl On {
69
    /// What a job without any `on` runs for: every push, and by hand.
702×
    pub fn default_on() -> On {
712×
        On { push: Some(vec![]), tag: None, manual: true, schedule: vec![] }
722×
    }
73
7416×
    pub fn matches(&self, event: Event<'_>) -> bool {
7516×
        let any = |globs: &Option<Vec<String>>, name: &str| match globs {
762×
            None => false,
776×
            Some(g) if g.is_empty() => true,
787×
            Some(g) => g.iter().any(|p| globset::Glob::new(p).is_ok_and(|p| p.compile_matcher().is_match(name))),
798×
        };
8016×
        match event {
815×
            Event::Push(b) => any(&self.push, b),
823×
            Event::Tag(t) => any(&self.tag, t),
834×
            Event::Manual => self.manual,
841×
            Event::Schedule => !self.schedule.is_empty(),
853×
            Event::ScheduleAt(w) => self
863×
                .schedule
873×
                .iter()
883×
                .filter_map(|l| crate::cron::Cron::parse(l))
893×
                .any(|c| c.matches(w.minute, w.hour, w.day, w.month, w.weekday)),
90
        }
9116×
    }
92
}
93
94
impl Pipeline {
95
    /// When `job` runs: its own `on`, else the pipeline's, else the default.
9616×
    pub fn on_of(&self, job: &Job) -> On {
9716×
        job.on.clone().or_else(|| self.on.clone()).unwrap_or_else(On::default_on)
9816×
    }
99
}
100
101
#[derive(Clone, Copy, Debug, PartialEq, Eq, PartialOrd, Ord, Hash, Serialize, Deserialize)]
102
#[serde(rename_all = "lowercase")]
103
pub enum Runtime {
104
    /// Tier 0 (spec §4.1); refused in M0.
105
    Wasm,
106
    /// Tier 1 (spec §4.2): namespaces, Landlock, seccomp, cgroups.
107
    Syscall,
108
    /// Tier 2 (spec §4.3), the default.
109
    Microvm,
110
}
111
112
impl Runtime {
11342×
    pub fn as_str(self) -> &'static str {
11442×
        match self {
1150×
            Runtime::Wasm => "wasm",
1160×
            Runtime::Syscall => "syscall",
11742×
            Runtime::Microvm => "microvm",
118
        }
11942×
    }
120
}
121
122
#[derive(Clone, Copy, Debug, PartialEq, Eq, Serialize, Deserialize)]
123
#[serde(rename_all = "lowercase")]
124
pub enum Network {
125
    Isolated,
126
    Loopback,
127
    Egress,
128
}
129
130
impl Network {
13142×
    pub fn as_str(self) -> &'static str {
13242×
        match self {
13339×
            Network::Isolated => "isolated",
1341×
            Network::Loopback => "loopback",
1352×
            Network::Egress => "egress",
136
        }
13742×
    }
138
}
139
140
#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)]
141
pub struct Sandbox {
142
    pub name: String,
143
    pub runtime: Runtime,
144
    /// BLAKE3 of the rootfs image, hex.
145
    pub rootfs: String,
146
    pub memory_mib: u32,
147
    pub cpus: u32,
148
    pub network: Network,
149
    /// Environment every job in this sandbox starts from; a job's own `env`
150
    /// overrides it.
151
    #[serde(default, skip_serializing_if = "BTreeMap::is_empty")]
152
    pub env: BTreeMap<String, String>,
153
    /// Labels a runner must have to run jobs here (`runs-on`), sorted.
154
    #[serde(default, skip_serializing_if = "Vec::is_empty")]
155
    pub runs_on: Vec<String>,
156
    /// The hosts a `network "egress"` sandbox may reach (oxygenflow#55):
157
    /// names, or `*.` and a domain for any name under it; sorted. Its jobs
158
    /// reach them through the runner's proxy, and nothing else.
159
    #[serde(default, skip_serializing_if = "Vec::is_empty")]
160
    pub egress_allow: Vec<String>,
161
    /// How long each job here may run, in seconds (`timeout "2h"`), when
162
    /// the job does not say; the hub caps it at the site's maximum.
163
    #[serde(default, skip_serializing_if = "Option::is_none")]
164
    pub timeout_s: Option<u64>,
165
    /// The architecture the jobs need (`arch "riscv64"`, spec §11.3);
166
    /// without it, the rootfs image's.
167
    #[serde(default, skip_serializing_if = "Option::is_none")]
168
    pub arch: Option<String>,
169
}
170
171
/// An architecture name as runners report it: `x86_64`, `aarch64`, `riscv64`.
1726×
pub fn arch_ok(a: &str) -> bool {
17322×
    (2..=16).contains(&a.len()) && a.bytes().all(|b| b.is_ascii_lowercase() || b.is_ascii_digit() || b == b'_')
1746×
}
175
176
#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)]
177
pub struct Job {
178
    pub name: String,
179
    pub sandbox: String,
180
    /// Glob patterns over repository paths (spec §6.2).
181
    pub scope: Vec<String>,
182
    /// Sorted.
183
    pub depends_on: Vec<String>,
184
    pub env: BTreeMap<String, String>,
185
    /// Executed as is: no shell, no expansion (spec §2.2 I2).
186
    pub exec: Vec<String>,
187
    /// Ephemeral scratch mounts, sorted by target (spec §3.1 `mount`).
188
    #[serde(default, skip_serializing_if = "Vec::is_empty")]
189
    pub mounts: Vec<Mount>,
190
    /// Files the job produces, sorted by name (spec §5.2 `output`).
191
    #[serde(default, skip_serializing_if = "Vec::is_empty")]
192
    pub outputs: Vec<Output>,
193
    /// Artifacts of jobs this one depends on, put in its workspace before it
194
    /// starts (oxygenflow#58), sorted by path. The runner checks each against
195
    /// the producing job's receipt; this job's receipt lists them as inputs.
196
    #[serde(default, skip_serializing_if = "Vec::is_empty")]
197
    pub inputs: Vec<Input>,
198
    /// Wait for a person before running (oxygenflow#57): `approval { by
199
    /// "maintain"; others-only #true; expires "24h" }`.
200
    #[serde(default, skip_serializing_if = "Option::is_none")]
201
    pub approval: Option<Approval>,
202
    /// The environment the job deploys to (oxygenflow#59), e.g. `prod`: the
203
    /// hub records what each environment runs, and the job's identity token
204
    /// names it once the job has been approved.
205
    #[serde(default, skip_serializing_if = "Option::is_none")]
206
    pub environment: Option<String>,
207
    /// Secrets the job mounts, sorted by name (spec §9 `secret`): the hub
208
    /// supplies each by name, the runner mounts it as a file.
209
    #[serde(default, skip_serializing_if = "Vec::is_empty")]
210
    pub secrets: Vec<Secret>,
211
    /// Identities the job asks the hub for (oxygenhub#103): an OIDC token
212
    /// for an audience, mounted as a file like a secret.
213
    #[serde(default, skip_serializing_if = "Vec::is_empty")]
214
    pub identities: Vec<Identity>,
215
    /// Labels a runner must have to take this job (`runs-on`), sorted;
216
    /// with its sandbox's, what the hub matches against a runner's.
217
    #[serde(default, skip_serializing_if = "Vec::is_empty")]
218
    pub runs_on: Vec<String>,
219
    /// How long the job may run, in seconds (`timeout "90m"`); its
220
    /// sandbox's when absent, else the site's default (oxygenflow#23).
221
    #[serde(default, skip_serializing_if = "Option::is_none")]
222
    pub timeout_s: Option<u64>,
223
    /// When it runs, over the pipeline's `on` (oxygenflow#24).
224
    #[serde(default, skip_serializing_if = "Option::is_none")]
225
    pub on: Option<On>,
226
    /// `low` or `normal` (`priority "low"`, or the pipeline's): a pipeline
227
    /// may lower its jobs below the repository's level, never raise them
228
    /// (oxygenhub#244); higher levels are the hub's to give.
229
    #[serde(default, skip_serializing_if = "Option::is_none")]
230
    pub priority: Option<String>,
231
}
232
233
impl Job {
234
    /// The job's environment on top of its sandbox's: what it runs with.
23516×
    pub fn in_sandbox(&self, sandbox: &Sandbox) -> Job {
23616×
        let mut job = self.clone();
23716×
        for (k, v) in &sandbox.env {
2382×
            job.env.entry(k.clone()).or_insert_with(|| v.clone());
239
        }
24016×
        job.runs_on.extend(sandbox.runs_on.iter().cloned());
24116×
        job.runs_on.sort();
24216×
        job.runs_on.dedup();
24316×
        job.timeout_s = job.timeout_s.or(sandbox.timeout_s);
24416×
        job
24516×
    }
246
247
    /// The job with variables that tell it what it builds (`FLOW_STATE`,
248
    /// `FLOW_BOOKMARK` …) added to its environment; a variable the pipeline
249
    /// sets itself keeps the pipeline's value.
25025×
    pub fn with_flow_env(&self, vars: &[(String, String)]) -> Job {
25125×
        let mut job = self.clone();
25231×
        for (k, v) in vars {
25331×
            job.env.entry(k.clone()).or_insert_with(|| v.clone());
254
        }
25525×
        job
25625×
    }
257
}
258
259
/// An ephemeral scratch mount: empty at the start of every job and gone
260
/// after it, so it cannot carry anything between jobs (spec §2.2 I4) --
261
/// unless it names a `cache` (spec §5.4, #28): then a disk kept from an
262
/// earlier passing job may start it, and the receipt says which.
263
#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)]
264
pub struct Mount {
265
    pub source: MountSource,
266
    /// An absolute path under `/src` or `/tmp`.
267
    pub target: String,
268
    pub size_mib: u32,
269
    /// `cache "name"`: keep this disk after a passing job and start later
270
    /// jobs from it (disk mounts only).
271
    #[serde(default, skip_serializing_if = "Option::is_none")]
272
    pub cache: Option<String>,
273
    /// `key "Cargo.lock" ...`: files whose content picks the cache entry.
274
    #[serde(default, skip_serializing_if = "Vec::is_empty")]
275
    pub key: Vec<String>,
276
}
277
278
#[derive(Clone, Copy, Debug, PartialEq, Eq, Serialize, Deserialize)]
279
#[serde(rename_all = "lowercase")]
280
pub enum MountSource {
281
    /// `ephemeral://tmpfs`: memory in the sandbox, counted against its memory-limit.
282
    Tmpfs,
283
    /// `ephemeral://disk`: a fresh sparse disk on the runner, for large build trees.
284
    Disk,
285
}
286
287
impl MountSource {
28814×
    pub fn as_str(self) -> &'static str {
28914×
        match self {
2905×
            MountSource::Tmpfs => "ephemeral://tmpfs",
2919×
            MountSource::Disk => "ephemeral://disk",
292
        }
29314×
    }
294
}
295
296
/// A file a job produces (spec §5.2): read from the job's disks when it
297
/// ends, kept in the repository as a blob, and named by its receipt.
298
#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)]
299
pub struct Output {
300
    /// The artifact's name, unique in the job.
301
    pub name: String,
302
    /// A clean absolute path under `/src`, not on a tmpfs mount.
303
    pub path: String,
304
    /// `when "always"`: kept from a failing job too, such as a test report
305
    /// (oxygenflow#37). From a failing job it is never in the receipt.
306
    #[serde(default, skip_serializing_if = "std::ops::Not::not")]
307
    pub always: bool,
308
    /// An artifact is one file; a report is a directory with a
309
    /// `report.toml`, kept file by file with a manifest (oxygenhub#127).
310
    #[serde(default, skip_serializing_if = "OutputKind::is_artifact")]
311
    pub kind: OutputKind,
312
}
313
314
/// An artifact a job takes from a job it depends on (oxygenflow#58):
315
/// `input { artifact "tfplan" from "plan"; path "/src/tfplan" }`.
316
#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)]
317
pub struct Input {
318
    /// The producing job's artifact.
319
    pub artifact: String,
320
    /// The producing job: one this job depends on.
321
    pub from: String,
322
    /// Where it is put: a clean absolute path under `/src`.
323
    pub path: String,
324
}
325
326
/// Who must approve a job before it runs, and for how long it waits
327
/// (oxygenflow#57).
328
#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)]
329
pub struct Approval {
330
    /// The least role that approves: `write`, `maintain` (the default) or `admin`.
331
    pub by: String,
332
    /// Not the person whose push started the run.
333
    #[serde(default, skip_serializing_if = "std::ops::Not::not")]
334
    pub others_only: bool,
335
    /// How long it waits once the jobs it depends on are done, in seconds.
336
    pub expires_s: u64,
337
    /// The approval must be signed with the approver's own key
338
    /// (`oxy seal --flow`; oxygenhub#235). Defaults to on for a job that
339
    /// names an environment.
340
    #[serde(default, skip_serializing_if = "std::ops::Not::not")]
341
    pub sealed: bool,
342
}
343
344
/// The longest a job waits for approval: 30 days.
345
const MAX_APPROVAL_S: u64 = 30 * 24 * 3600;
346
347
/// The most inputs a job takes.
348
const MAX_INPUTS: usize = 8;
349
350
/// What an [`Output`] is.
351
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Serialize, Deserialize)]
352
#[serde(rename_all = "lowercase")]
353
pub enum OutputKind {
354
    #[default]
355
    Artifact,
356
    Report,
357
}
358
359
impl OutputKind {
36016×
    pub fn is_artifact(&self) -> bool {
36116×
        *self == OutputKind::Artifact
36216×
    }
363
36440×
    pub fn word(&self) -> &'static str {
36540×
        match self {
36624×
            OutputKind::Artifact => "artifact",
36716×
            OutputKind::Report => "report",
368
        }
36940×
    }
370
}
371
372
/// A secret the job reads as a file (spec §9): never in the environment.
373
#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)]
374
pub struct Secret {
375
    /// Which secret, as the hub names it; unique in the job.
376
    pub name: String,
377
    /// A clean absolute path under `/run/secrets/`, unique in the job;
378
    /// the file is 0400, the job's user's, on an in-memory mount.
379
    pub mount_path: String,
380
}
381
382
/// An OIDC token the hub mints for the job (oxygenhub#103), naming the
383
/// repository, bookmark, run and job, for `audience`; read as a file.
384
#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)]
385
pub struct Identity {
386
    /// Who the token is for (`sts.amazonaws.com`, a Vault role's audience, …).
387
    pub audience: String,
388
    /// A clean absolute path under `/run/secrets/`, unique among the
389
    /// job's secrets and identities.
390
    pub mount_path: String,
391
}
392
393
/// A secret's mount path: under `/run/secrets/`, no `.` or `..`.
39417×
pub fn secret_path_ok(p: &str) -> bool {
39517×
    p.strip_prefix("/run/secrets/").is_some_and(|rest| !rest.is_empty() && rest.split('/').all(|c| !c.is_empty() && c != "." && c != ".."))
39617×
}
397
398
/// Artifacts a job may declare.
399
pub const MAX_OUTPUTS: usize = 16;
400
401
/// Whether `p` is a clean absolute path strictly under `/src`, with nothing
402
/// a debugfs command line would have to quote.
40344×
fn output_path_ok(p: &str) -> bool {
40444×
    p.strip_prefix("/src/").is_some_and(|rest| {
40542×
        !rest.is_empty()
40670×
            && rest.split('/').all(|c| !c.is_empty() && c != "." && c != "..")
407467×
            && p.bytes().all(|b| b.is_ascii_graphic() && b != b'"' && b != b'\\')
40842×
    })
40944×
}
410
411
/// Mounts a job may declare.
412
pub const MAX_MOUNTS: usize = 4;
413
/// The most secrets a job may mount.
414
pub const MAX_SECRETS: usize = 8;
415
/// The most identities a job may ask for.
416
pub const MAX_IDENTITIES: usize = 4;
417
/// Sizes a mount may have: 16 MiB to 64 GiB.
418
pub const MIN_MOUNT_MIB: u64 = 16;
419
pub const MAX_MOUNT_MIB: u64 = 64 * 1024;
420
421
/// Whether `t` is a clean absolute path strictly under `/src` or `/tmp`.
42259×
fn mount_target_ok(t: &str) -> bool {
42359×
    let under = t.strip_prefix("/src/").or_else(|| t.strip_prefix("/tmp/"));
42459×
    under.is_some_and(|rest| !rest.is_empty() && rest.split('/').all(|c| !c.is_empty() && c != "." && c != ".."))
42559×
}
426
427
/// One problem in a pipeline, at a 1-based line.
428
#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)]
429
pub struct Problem {
430
    pub line: usize,
431
    pub message: String,
432
}
433
434
impl fmt::Display for Problem {
43522×
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
43622×
        write!(f, "line {}: {}", self.line, self.message)
43722×
    }
438
}
439
440
/// Every problem found, in line order.
441
#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize, thiserror::Error)]
442
pub struct Problems(pub Vec<Problem>);
443
444
impl fmt::Display for Problems {
44517×
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
44622×
        let lines: Vec<String> = self.0.iter().map(|p| p.to_string()).collect();
44717×
        f.write_str(&lines.join("\n"))
44817×
    }
449
}
450
451
const MIN_MEMORY_MIB: u64 = 64;
452
const MAX_MEMORY_MIB: u64 = 16 * 1024;
453
const MAX_CPUS: i128 = 16;
454
455
/// Nodes of the full spec that M0 recognises and refuses.
456
const LATER_TOP: &[&str] = &["publish", "secret"];
457
const LATER_JOB: &[&str] = &["attest"];
458
459
struct Ctx<'a> {
460
    src: &'a str,
461
    problems: Vec<Problem>,
462
}
463
464
impl Ctx<'_> {
465108×
    fn line(&self, span: SourceSpan) -> usize {
466108×
        let at = span.offset().min(self.src.len());
46728700×
        self.src[..at].bytes().filter(|b| *b == b'\n').count() + 1
468108×
    }
469
470108×
    fn err(&mut self, span: SourceSpan, message: impl Into<String>) {
471108×
        let line = self.line(span);
472108×
        self.problems.push(Problem { line, message: message.into() });
473108×
    }
474
475
    /// The node's arguments as strings; properties and other types are errors.
4761516×
    fn strings(&mut self, node: &KdlNode) -> Vec<String> {
4771516×
        let mut out = Vec::new();
4781558×
        for e in node.entries() {
4791558×
            if let Some(k) = e.name() {
4800×
                self.err(e.span(), format!("`{}` takes no property `{}`", node.name().value(), k.value()));
4810×
                continue;
4821558×
            }
4831558×
            match e.value() {
4841557×
                KdlValue::String(s) => out.push(s.clone()),
4851×
                other => self.err(e.span(), format!("`{}` takes strings, not {}", node.name().value(), kind_of(other))),
486
            }
487
        }
4881516×
        out
4891516×
    }
490
491
    /// Exactly one string argument.
4921289×
    fn one_string(&mut self, node: &KdlNode) -> Option<String> {
4931289×
        let v = self.strings(node);
4941289×
        if v.len() != 1 {
4950×
            self.err(node.span(), format!("`{}` takes one string", node.name().value()));
4960×
            return None;
4971289×
        }
4981289×
        v.into_iter().next()
4991289×
    }
500
501241×
    fn one_integer(&mut self, node: &KdlNode) -> Option<i128> {
502241×
        match node.entries() {
503241×
            [e] if e.name().is_none() => match e.value() {
504240×
                KdlValue::Integer(n) => Some(*n),
5051×
                other => {
5061×
                    self.err(e.span(), format!("`{}` takes an integer, not {}", node.name().value(), kind_of(other)));
5071×
                    None
508
                }
509
            },
510
            _ => {
5110×
                self.err(node.span(), format!("`{}` takes one integer", node.name().value()));
5120×
                None
513
            }
514
        }
515241×
    }
516
5171404×
    fn no_children(&mut self, node: &KdlNode) {
5181404×
        if node.children().is_some() {
5191×
            self.err(node.span(), format!("`{}` takes no block", node.name().value()));
5201403×
        }
5211404×
    }
522
523371×
    fn name_ok(&mut self, span: SourceSpan, what: &str, name: &str) -> bool {
5241373×
        let ok = !name.is_empty() && name.len() <= 64 && name.bytes().all(|b| b.is_ascii_alphanumeric() || b"._-".contains(&b));
525371×
        if !ok {
5260×
            self.err(span, format!("{what} name {name:?} must be 1 to 64 of A-Z a-z 0-9 . _ -"));
527371×
        }
528371×
        ok
529371×
    }
530
}
531
532
use kdl::{KdlDocument, KdlNode, KdlValue};
533
use miette::SourceSpan;
534
5352×
fn kind_of(v: &KdlValue) -> &'static str {
5362×
    match v {
5371×
        KdlValue::String(_) => "a string",
5381×
        KdlValue::Integer(_) => "an integer",
5390×
        KdlValue::Float(_) => "a number",
5400×
        KdlValue::Bool(_) => "a boolean",
5410×
        KdlValue::Null => "null",
542
    }
5432×
}
544
545
/// `"512MiB"`, `"4GiB"`, `"65536KiB"` to MiB.
546171×
fn parse_memory(s: &str) -> Option<u64> {
547570×
    let (num, unit) = s.split_at(s.find(|c: char| !c.is_ascii_digit())?);
548171×
    let n: u64 = num.parse().ok()?;
549170×
    let mib = match unit {
550170×
        "KiB" => n.is_multiple_of(1024).then_some(n / 1024)?,
551170×
        "MiB" => n,
55245×
        "GiB" => n.checked_mul(1024)?,
5531×
        _ => return None,
554
    };
555169×
    Some(mib)
556171×
}
557
558
/// The line of the first escape KDL 2.0 does not have but shells and C
559
/// do (`\0NN`, `\e`, `\xNN`), as someone colouring output writes them.
5602×
fn foreign_escape_line(src: &str) -> Option<usize> {
5612×
    src.lines()
56217×
        .position(|l| {
56317×
            let b = l.as_bytes();
564287×
            b.windows(2).enumerate().any(|(i, w)| {
565287×
                w[0] == b'\\'
5661×
                    && (i == 0 || b[i - 1] != b'\\')
5671×
                    && (w[1] == b'e' || w[1] == b'x' || (w[1] == b'0' && b.get(i + 2).is_some_and(u8::is_ascii_digit)))
568287×
            })
56917×
        })
5702×
        .map(|i| i + 1)
5712×
}
572
573
impl Pipeline {
574
    /// Parse and validate a pipeline document.
575134×
    pub fn parse(src: &str) -> Result<Pipeline, Problems> {
576134×
        let doc = match KdlDocument::parse_v2(src) {
577132×
            Ok(d) => d,
5782×
            Err(e) => {
5792×
                let mut ctx = Ctx { src, problems: Vec::new() };
5802×
                for d in &e.diagnostics {
5812×
                    let msg = d.message.clone().or_else(|| d.label.clone()).unwrap_or_else(|| "not valid KDL 2.0".into());
5822×
                    ctx.err(d.span, msg);
583
                }
5842×
                if ctx.problems.is_empty() {
5850×
                    ctx.problems.push(Problem { line: 1, message: "not valid KDL 2.0".into() });
5862×
                }
5872×
                if let Some(line) = foreign_escape_line(src) {
5881×
                    ctx.problems.push(Problem {
5891×
                        line,
5901×
                        message: "KDL strings have no \\033, \\e or \\x escapes: write ESC (for ANSI colours) as \\u{1b}".into(),
5911×
                    });
5921×
                }
5932×
                return Err(Problems(ctx.problems));
594
            }
595
        };
596132×
        let mut ctx = Ctx { src, problems: Vec::new() };
597132×
        let mut schema = None;
598132×
        let mut sandboxes = BTreeMap::new();
599132×
        let mut jobs: BTreeMap<String, (Job, SourceSpan)> = BTreeMap::new();
600132×
        let mut on = None;
601132×
        let mut priority = None;
602442×
        for node in doc.nodes() {
603442×
            match node.name().value() {
604442×
                "priority" => {
6051×
                    if priority.is_some() {
6060×
                        ctx.err(node.span(), "`priority` is given twice");
6071×
                    }
6081×
                    priority = parse_priority(&mut ctx, node);
609
                }
610441×
                "on" => {
6114×
                    if on.is_some() {
6120×
                        ctx.err(node.span(), "`on` is given twice");
6134×
                    }
6144×
                    on = Some(parse_on(&mut ctx, node));
615
                }
616437×
                "schema-version" => {
617132×
                    ctx.no_children(node);
618132×
                    match ctx.one_integer(node) {
619131×
                        Some(1) => schema = Some(1),
6201×
                        Some(n) => ctx.err(node.span(), format!("schema-version {n} is not supported; this runner reads 1")),
6210×
                        None => {}
622
                    }
623
                }
624305×
                "sandbox" => {
625131×
                    if let Some(sb) = parse_sandbox(&mut ctx, node) {
626129×
                        if sandboxes.contains_key(&sb.name) {
6270×
                            ctx.err(node.span(), format!("sandbox {:?} is declared twice", sb.name));
628129×
                        } else {
629129×
                            sandboxes.insert(sb.name.clone(), sb);
630129×
                        }
6312×
                    }
632
                }
633174×
                "job" => {
634173×
                    if let Some(job) = parse_job(&mut ctx, node) {
635173×
                        if jobs.contains_key(&job.name) {
6360×
                            ctx.err(node.span(), format!("job {:?} is declared twice", job.name));
637173×
                        } else {
638173×
                            jobs.insert(job.name.clone(), (job, node.span()));
639173×
                        }
6400×
                    }
641
                }
6421×
                n if LATER_TOP.contains(&n) => ctx.err(node.span(), format!("`{n}` is not in M0 yet")),
6431×
                n => ctx.err(node.span(), format!("unknown node `{n}`; expected schema-version, on, priority, sandbox or job")),
644
            }
645
        }
646132×
        if schema.is_none() && !ctx.problems.iter().any(|p| p.message.contains("schema-version")) {
6470×
            ctx.problems.push(Problem { line: 1, message: "`schema-version 1` is required".into() });
648132×
        }
649132×
        if jobs.is_empty() && ctx.problems.is_empty() {
6500×
            ctx.problems.push(Problem { line: 1, message: "a pipeline needs at least one job".into() });
651132×
        }
652
        // References and cycles.
653173×
        for (job, span) in jobs.values() {
654173×
            if !job.sandbox.is_empty() && !sandboxes.contains_key(&job.sandbox) {
6553×
                ctx.err(*span, format!("job {:?} uses sandbox {:?}, which is not declared", job.name, job.sandbox));
656170×
            }
657173×
            for d in &job.depends_on {
65817×
                if !jobs.contains_key(d) {
6591×
                    ctx.err(*span, format!("job {:?} depends on {:?}, which is not declared", job.name, d));
66016×
                } else if d == &job.name {
6611×
                    ctx.err(*span, format!("job {:?} depends on itself", job.name));
66215×
                }
663
            }
664
            // Inputs come from a job this one depends on, which declares
665
            // that artifact (oxygenflow#58).
666173×
            for i in &job.inputs {
6676×
                let Some((producer, _)) = jobs.get(&i.from) else {
6681×
                    ctx.err(*span, format!("job {:?} takes an input from {:?}, which is not declared", job.name, i.from));
6691×
                    continue;
670
                };
6715×
                if !job.depends_on.contains(&i.from) {
6721×
                    ctx.err(*span, format!("job {:?} takes {:?} from {:?}: add depends-on \"{}\"", job.name, i.artifact, i.from, i.from));
6734×
                }
6749×
                match producer.outputs.iter().find(|o| o.name == i.artifact) {
6754×
                    Some(o) if o.kind == OutputKind::Artifact => {}
6761×
                    Some(_) => ctx.err(*span, format!("{:?} of job {:?} is a report; inputs are artifacts", i.artifact, i.from)),
6771×
                    None => ctx.err(*span, format!("job {:?} declares no artifact {:?}", i.from, i.artifact)),
678
                }
679
            }
680
        }
681132×
        let graph: BTreeMap<&str, Vec<&str>> =
682173×
            jobs.values().map(|(j, _)| (j.name.as_str(), j.depends_on.iter().map(String::as_str).collect())).collect();
683132×
        if let Some(cycle) = find_cycle(&graph) {
6841×
            let span = jobs[cycle[0]].1;
6851×
            ctx.err(span, format!("jobs depend on each other in a cycle: {}", cycle.join(" → ")));
686131×
        }
687132×
        if !ctx.problems.is_empty() {
68879×
            ctx.problems.sort_by_key(|p| p.line);
68979×
            return Err(Problems(ctx.problems));
69053×
        }
691
        // The pipeline's priority is each job's that does not say.
69253×
        let jobs = jobs
69353×
            .into_iter()
69475×
            .map(|(k, (mut j, _))| {
69575×
                if j.priority.is_none() {
69673×
                    j.priority.clone_from(&priority);
69773×
                }
69875×
                (k, j)
69975×
            })
70053×
            .collect();
70153×
        Ok(Pipeline { schema_version: 1, sandboxes, jobs, on })
702134×
    }
703
704
    /// Jobs in an order where each comes after what it depends on (ties by name).
7054×
    pub fn order(&self) -> Vec<&Job> {
7064×
        let mut done: BTreeSet<&str> = BTreeSet::new();
7074×
        let mut out = Vec::with_capacity(self.jobs.len());
70810×
        while out.len() < self.jobs.len() {
7096×
            let before = out.len();
71020×
            for j in self.jobs.values() {
71120×
                if !done.contains(j.name.as_str()) && j.depends_on.iter().all(|d| done.contains(d.as_str())) {
71216×
                    out.push(j);
71316×
                }
714
            }
71516×
            for j in &out[before..] {
71616×
                done.insert(j.name.as_str());
71716×
            }
7186×
            if out.len() == before {
7190×
                break; // validated pipelines have no cycles
7206×
            }
721
        }
7224×
        out
7234×
    }
724
725
    /// Each job's depth: 0 without dependencies, else one more than its deepest dependency.
7261×
    pub fn depths(&self) -> BTreeMap<&str, usize> {
7271×
        let mut depth: BTreeMap<&str, usize> = BTreeMap::new();
7282×
        for j in self.order() {
7292×
            let d = j.depends_on.iter().map(|x| depth.get(x.as_str()).copied().unwrap_or(0) + 1).max().unwrap_or(0);
7302×
            depth.insert(j.name.as_str(), d);
731
        }
7321×
        depth
7331×
    }
734
}
735
736132×
fn find_cycle<'a>(graph: &BTreeMap<&'a str, Vec<&'a str>>) -> Option<Vec<&'a str>> {
737
    #[derive(Clone, Copy, PartialEq)]
738
    enum Mark {
739
        Visiting,
740
        Done,
741
    }
742185×
    fn visit<'a>(
743185×
        n: &'a str,
744185×
        graph: &BTreeMap<&'a str, Vec<&'a str>>,
745185×
        marks: &mut BTreeMap<&'a str, Mark>,
746185×
        stack: &mut Vec<&'a str>,
747185×
    ) -> Option<Vec<&'a str>> {
748185×
        match marks.get(n) {
74912×
            Some(Mark::Done) => return None,
750
            Some(Mark::Visiting) => {
7511×
                let at = stack.iter().position(|s| *s == n).unwrap_or(0);
7521×
                let mut c = stack[at..].to_vec();
7531×
                c.push(n);
7541×
                return Some(c);
755
            }
756172×
            None => {}
757
        }
758172×
        marks.insert(n, Mark::Visiting);
759172×
        stack.push(n);
760172×
        for d in graph.get(n).into_iter().flatten() {
76116×
            if graph.contains_key(d) && *d != n {
76215×
                if let Some(c) = visit(d, graph, marks, stack) {
7633×
                    return Some(c);
76412×
                }
7651×
            }
766
        }
767169×
        stack.pop();
768169×
        marks.insert(n, Mark::Done);
769169×
        None
770185×
    }
771132×
    let mut marks = BTreeMap::new();
772170×
    for n in graph.keys() {
773170×
        let mut stack = Vec::new();
774170×
        if let Some(c) = visit(n, graph, &mut marks, &mut stack) {
7751×
            return Some(c);
776169×
        }
777
    }
778131×
    None
779132×
}
780
781483×
fn block<'a>(ctx: &mut Ctx, node: &'a KdlNode) -> &'a [KdlNode] {
782483×
    match node.children() {
783482×
        Some(d) => d.nodes(),
784
        None => {
7851×
            ctx.err(node.span(), format!("`{}` needs a block {{ … }}", node.name().value()));
7861×
            &[]
787
        }
788
    }
789483×
}
790
791131×
fn parse_sandbox(ctx: &mut Ctx, node: &KdlNode) -> Option<Sandbox> {
792131×
    let name = ctx.one_string(node)?;
793131×
    let named = ctx.name_ok(node.span(), "sandbox", &name);
794131×
    let (mut runtime, mut rootfs, mut memory, mut cpus, mut network) =
795131×
        (Some(Runtime::Microvm), None, Some(1024u32), Some(1u32), Some(Network::Isolated));
796131×
    let mut seen = BTreeSet::new();
797131×
    let mut env = BTreeMap::new();
798131×
    let mut runs_on = Vec::new();
799131×
    let mut timeout_s = None;
800131×
    let mut arch: Option<String> = None;
801131×
    let mut egress_allow = Vec::new();
802593×
    for c in block(ctx, node) {
803593×
        let key = c.name().value();
804593×
        if key != "runs-on" && !seen.insert(key.to_string()) {
8050×
            ctx.err(c.span(), format!("`{key}` is given twice"));
806593×
        }
807593×
        if key == "env" {
8082×
            parse_env(ctx, c, &mut env);
8092×
            continue;
810591×
        }
811591×
        if key == "runs-on" {
8121×
            ctx.no_children(c);
8131×
            parse_labels(ctx, c, &mut runs_on);
8141×
            continue;
815590×
        }
816590×
        if key != "network" {
817468×
            ctx.no_children(c);
818468×
        }
819590×
        match key {
820590×
            "runtime" => {
821114×
                runtime = match ctx.one_string(c).as_deref() {
822114×
                    Some("microvm") => Some(Runtime::Microvm),
8236×
                    Some("syscall") | Some("gvisor") => Some(Runtime::Syscall),
824
                    // A WASI module run by wasmtime (spec §4.1, oxygenflow#75).
8255×
                    Some("wasm") => Some(Runtime::Wasm),
8260×
                    Some(other) => {
8270×
                        ctx.err(c.span(), format!("runtime {other:?}: expected \"microvm\", \"syscall\" or \"wasm\""));
8280×
                        None
829
                    }
8300×
                    None => None,
831
                }
832
            }
833476×
            "rootfs" => {
834127×
                rootfs = match ctx.one_string(c) {
835127×
                    Some(r) => match r.strip_prefix("cas://blob/") {
8368064×
                        Some(h) if h.len() == 64 && h.bytes().all(|b| b.is_ascii_hexdigit() && !b.is_ascii_uppercase()) => {
837126×
                            Some(h.to_string())
838
                        }
839
                        _ => {
8401×
                            ctx.err(c.span(), format!("rootfs {r:?}: expected \"cas://blob/\" and 64 lower-case hex digits"));
8411×
                            None
842
                        }
843
                    },
8440×
                    None => None,
845
                }
846
            }
847349×
            "arch" => {
8482×
                arch = match ctx.one_string(c) {
8492×
                    Some(a) if arch_ok(&a) => Some(a),
8501×
                    Some(a) => {
8511×
                        ctx.err(c.span(), format!("arch {a:?} is not an architecture name such as x86_64, aarch64 or riscv64"));
8521×
                        None
853
                    }
8540×
                    None => None,
855
                }
856
            }
857347×
            "memory-limit" => {
858113×
                memory = match ctx.one_string(c) {
859113×
                    Some(m) => match parse_memory(&m) {
860112×
                        Some(mib) if (MIN_MEMORY_MIB..=MAX_MEMORY_MIB).contains(&mib) => Some(mib as u32),
861
                        Some(_) => {
8620×
                            ctx.err(c.span(), format!("memory-limit {m:?} must be from 64MiB to 16GiB"));
8630×
                            None
864
                        }
865
                        None => {
8661×
                            ctx.err(c.span(), format!("memory-limit {m:?}: expected a whole number of KiB, MiB or GiB, as \"4GiB\""));
8671×
                            None
868
                        }
869
                    },
8700×
                    None => None,
871
                }
872
            }
873234×
            "cpu-limit" => {
874109×
                cpus = match ctx.one_integer(c) {
875108×
                    Some(n) if (1..=MAX_CPUS).contains(&n) => Some(n as u32),
8760×
                    Some(n) => {
8770×
                        ctx.err(c.span(), format!("cpu-limit {n} must be from 1 to {MAX_CPUS}"));
8780×
                        None
879
                    }
8801×
                    None => None,
881
                }
882
            }
883125×
            "network" => {
884122×
                let kind = ctx.one_string(c);
885122×
                if kind.as_deref() != Some("egress") {
886113×
                    ctx.no_children(c);
887113×
                }
888122×
                network = match kind.as_deref() {
889122×
                    Some("isolated") => Some(Network::Isolated),
890
                    // Loopback only: the guest's `lo` comes up, and it still has
891
                    // no device that reaches anything outside it.
89213×
                    Some("loopback") => Some(Network::Loopback),
893
                    // Allow-listed egress (oxygenflow#55): still no network
894
                    // device; a proxy in the guest relays to the runner, which
895
                    // lets through only the hosts named here.
89610×
                    Some("egress") => {
8979×
                        egress_allow = parse_egress(ctx, c);
8989×
                        Some(Network::Egress)
899
                    }
9001×
                    Some(other) => {
9011×
                        ctx.err(c.span(), format!("network {other:?}: expected \"isolated\", \"loopback\" or \"egress\""));
9021×
                        None
903
                    }
9040×
                    None => None,
905
                }
906
            }
9073×
            "timeout" => timeout_s = parse_timeout(ctx, c),
9080×
            other => ctx.err(c.span(), format!("unknown sandbox setting `{other}`")),
909
        }
910
    }
911
    // A WASM sandbox has no image: its module is a file of the job (its
912
    // scope or an earlier job's artifact), and it reaches no network.
913131×
    let wasm = runtime == Some(Runtime::Wasm);
914131×
    if wasm {
9155×
        if seen.contains("rootfs") {
9161×
            ctx.err(node.span(), format!("sandbox {name:?}: runtime \"wasm\" takes no rootfs; its module is a file the job has"));
9174×
        }
9185×
        if network.is_some_and(|n| n != Network::Isolated) {
9191×
            ctx.err(node.span(), format!("sandbox {name:?}: runtime \"wasm\" has no network; leave out `network` or say \"isolated\""));
9204×
        }
9215×
        rootfs = Some(String::new());
9225×
        network = Some(Network::Isolated);
923126×
    } else if rootfs.is_none() && !seen.contains("rootfs") {
9240×
        ctx.err(node.span(), format!("sandbox {name:?} needs a rootfs"));
925126×
    }
926131×
    if network == Some(Network::Egress) {
9279×
        if runtime == Some(Runtime::Syscall) {
9281×
            ctx.err(node.span(), format!("sandbox {name:?}: network \"egress\" needs runtime \"microvm\""));
9298×
        }
930
        // Only a runner that allows egress offers this label.
9319×
        if !runs_on.iter().any(|l| l == EGRESS_LABEL) {
9329×
            runs_on.push(EGRESS_LABEL.to_string());
9339×
            runs_on.sort();
9349×
        }
935122×
    }
936131×
    if !named {
9370×
        return None;
938131×
    }
939
    Some(Sandbox {
940131×
        name,
941131×
        runtime: runtime?,
942131×
        rootfs: rootfs?,
943130×
        memory_mib: memory?,
944129×
        cpus: cpus?,
945129×
        network: network?,
946129×
        env,
947129×
        runs_on,
948129×
        egress_allow,
949129×
        timeout_s,
950129×
        arch,
951
    })
952131×
}
953
954
/// The label a runner offers when it allows egress, and an egress sandbox
955
/// needs (oxygenflow#55).
956
pub const EGRESS_LABEL: &str = "egress";
957
958
/// The most hosts one sandbox may name.
959
const MAX_EGRESS_HOSTS: usize = 32;
960
961
/// Whether `pattern` is a host name, or `*.` and a domain: lower-case
962
/// letters, digits, `-` and dots, at least two labels.
9638×
pub fn egress_pattern_ok(pattern: &str) -> bool {
9648×
    let name = pattern.strip_prefix("*.").unwrap_or(pattern);
9658×
    let labels: Vec<&str> = name.split('.').collect();
9668×
    name.len() <= 253
9678×
        && labels.len() >= 2
96815×
        && labels.iter().all(|l| {
96915×
            !l.is_empty()
97015×
                && l.len() <= 63
97115×
                && !l.starts_with('-')
97215×
                && !l.ends_with('-')
97386×
                && l.bytes().all(|b| b.is_ascii_lowercase() || b.is_ascii_digit() || b == b'-')
97415×
        })
9758×
}
976
977
/// Whether `host` is one `patterns` allow: a name exactly, or a name under
978
/// a `*.` domain (not the domain itself). Case and a final dot are ignored.
97914×
pub fn egress_allows(patterns: &[String], host: &str) -> bool {
98014×
    let host = host.trim_end_matches('.').to_ascii_lowercase();
98125×
    patterns.iter().any(|p| match p.strip_prefix("*.") {
98214×
        Some(domain) => host.len() > domain.len() + 1 && host.ends_with(domain) && host[..host.len() - domain.len()].ends_with('.'),
98311×
        None => host == *p,
98425×
    })
98514×
}
986
987
/// `network "egress" { allow "*.googleapis.com" "registry.opentofu.org" }`.
9889×
fn parse_egress(ctx: &mut Ctx, node: &KdlNode) -> Vec<String> {
9899×
    let mut out = Vec::new();
9909×
    for c in block(ctx, node) {
9918×
        ctx.no_children(c);
9928×
        if c.name().value() != "allow" {
9931×
            ctx.err(c.span(), format!("unknown egress setting `{}`; egress takes `allow \"host\"...`", c.name().value()));
9941×
            continue;
9957×
        }
9968×
        for h in ctx.strings(c) {
9978×
            if egress_pattern_ok(&h) {
9985×
                out.push(h);
9995×
            } else {
10003×
                ctx.err(
10013×
                    c.span(),
10023×
                    format!("allow {h:?}: expected a lower-case host name such as \"registry.opentofu.org\", or \"*.\" and a domain"),
10033×
                );
10043×
            }
1005
        }
1006
    }
10079×
    out.sort();
10089×
    out.dedup();
10099×
    if out.is_empty() {
10106×
        ctx.err(node.span(), "network \"egress\" needs at least one `allow \"host\"`");
10116×
    } else if out.len() > MAX_EGRESS_HOSTS {
10120×
        ctx.err(node.span(), format!("network \"egress\" may allow at most {MAX_EGRESS_HOSTS} hosts"));
10133×
    }
10149×
    out
10159×
}
1016
1017
/// An `on` block: `push` and `tag` with globs (none: any), `manual`,
1018
/// `schedule` with five-field cron lines.
101914×
fn parse_on(ctx: &mut Ctx, node: &KdlNode) -> On {
102014×
    let mut on = On::default();
102114×
    if !node.entries().is_empty() {
10220×
        ctx.err(node.span(), "`on` takes a block: on { push \"main\"; tag \"v*\"; manual }");
102314×
    }
102414×
    let globs = |ctx: &mut Ctx, c: &KdlNode| -> Vec<String> {
10256×
        let g = ctx.strings(c);
10267×
        for p in &g {
10277×
            if let Err(e) = globset::Glob::new(p) {
10280×
                ctx.err(c.span(), format!("{p:?}: {e}"));
10297×
            }
1030
        }
10316×
        g
10326×
    };
103319×
    for c in block(ctx, node) {
103419×
        ctx.no_children(c);
103519×
        match c.name().value() {
103619×
            "push" => on.push.get_or_insert_with(Vec::new).extend(globs(ctx, c)),
103718×
            "tag" => on.tag.get_or_insert_with(Vec::new).extend(globs(ctx, c)),
103813×
            "manual" => on.manual = true,
10397×
            "schedule" => {
10406×
                for line in ctx.strings(c) {
10416×
                    if crate::cron::Cron::parse(&line).is_some() {
10425×
                        on.schedule.push(line);
10435×
                    } else {
10441×
                        ctx.err(
10451×
                            c.span(),
10461×
                            format!("schedule {line:?}: expected five cron fields (minute hour day month weekday), as \"0 3 * * *\""),
10471×
                        );
10481×
                    }
1049
                }
1050
            }
10511×
            other => ctx.err(c.span(), format!("unknown `on` event `{other}`; expected push, tag, manual or schedule")),
1052
        }
1053
    }
105414×
    if on.push.is_none() && on.tag.is_none() && !on.manual && on.schedule.is_empty() {
10553×
        ctx.err(node.span(), "`on` names no event, so nothing would run it");
105611×
    }
105714×
    on
105814×
}
1059
1060
/// The longest a pipeline may ask a job to run.
1061
pub const MAX_TIMEOUT_S: u64 = 24 * 3600;
1062
1063
/// A duration: whole hours, minutes and seconds in that order, each
1064
/// optional, as "90m", "2h", "1h30m" or "45s".
106519×
pub fn parse_duration(s: &str) -> Option<u64> {
106619×
    let (mut total, mut num, mut last) = (0u64, String::new(), 0u8);
106750×
    for ch in s.chars() {
106850×
        if ch.is_ascii_digit() {
106929×
            num.push(ch);
107029×
            continue;
107121×
        }
107221×
        let (unit, mult) = match ch {
107312×
            'h' => (1, 3600),
10745×
            'm' => (2, 60),
10751×
            's' => (3, 1),
10763×
            _ => return None,
1077
        };
1078
        // Each unit once, largest first, each with its number.
107918×
        if num.is_empty() || unit <= last {
10803×
            return None;
108115×
        }
108215×
        last = unit;
108315×
        total = total.checked_add(num.parse::<u64>().ok()?.checked_mul(mult)?)?;
108415×
        num.clear();
1085
    }
108613×
    (num.is_empty() && total > 0).then_some(total)
108719×
}
1088
1089
/// A `timeout` line: one duration, from a minute to a day.
1090
/// `priority "low"`: a pipeline may lower its jobs, never raise them
1091
/// (oxygenhub#244).
10926×
fn parse_priority(ctx: &mut Ctx, c: &KdlNode) -> Option<String> {
10936×
    ctx.no_children(c);
10946×
    let p = ctx.one_string(c)?;
10956×
    match p.as_str() {
10966×
        "low" | "normal" => Some(p),
10973×
        "high" | "urgent" => {
10982×
            ctx.err(
10992×
                c.span(),
11002×
                format!("priority {p:?}: a pipeline may lower its jobs (`low`, `normal`), not raise them; higher levels are set on the hub, and a person may expedite a run"),
1101
            );
11022×
            None
1103
        }
1104
        _ => {
11051×
            ctx.err(c.span(), format!("priority {p:?}: expected `low` or `normal`"));
11061×
            None
1107
        }
1108
    }
11096×
}
1110
11116×
fn parse_timeout(ctx: &mut Ctx, c: &KdlNode) -> Option<u64> {
11126×
    let t = ctx.one_string(c)?;
11136×
    match parse_duration(&t) {
11145×
        Some(secs) if (60..=MAX_TIMEOUT_S).contains(&secs) => Some(secs),
1115
        Some(_) => {
11161×
            ctx.err(c.span(), format!("timeout {t:?} must be from 1m to 24h"));
11171×
            None
1118
        }
1119
        None => {
11201×
            ctx.err(c.span(), format!("timeout {t:?}: expected hours, minutes and seconds, as \"90m\" or \"1h30m\""));
11211×
            None
1122
        }
1123
    }
11246×
}
1125
1126
/// The labels of a `runs-on` line: lower-case letters, digits, `-`, `_`
1127
/// and `.`, at most 64 bytes each; into `into`, sorted, once each.
11284×
fn parse_labels(ctx: &mut Ctx, c: &KdlNode, into: &mut Vec<String>) {
11294×
    let labels = ctx.strings(c);
11304×
    if labels.is_empty() {
11311×
        ctx.err(c.span(), "`runs-on` needs one or more labels, as runs-on \"riscv64\"");
11323×
    }
11334×
    for l in labels {
11344×
        let ok = !l.is_empty()
11354×
            && l.len() <= 64
113619×
            && l.bytes().all(|b| b.is_ascii_lowercase() || b.is_ascii_digit() || matches!(b, b'-' | b'_' | b'.'));
11374×
        if ok {
11383×
            into.push(l);
11393×
        } else {
11401×
            ctx.err(c.span(), format!("runs-on {l:?}: a label is lower-case letters, digits, -, _ and ., at most 64"));
11411×
        }
1142
    }
11434×
    into.sort();
11444×
    into.dedup();
11454×
}
1146
1147
/// An `env` block of `NAME "value"` lines, into `env`.
11487×
fn parse_env(ctx: &mut Ctx, c: &KdlNode, env: &mut BTreeMap<String, String>) {
11497×
    if !c.entries().is_empty() {
11500×
        ctx.err(c.span(), "`env` takes a block of NAME \"value\" lines");
11517×
    }
11528×
    for e in block(ctx, c) {
11538×
        let k = e.name().value().to_string();
11548×
        let valid =
115549×
            !k.is_empty() && !k.starts_with(|c: char| c.is_ascii_digit()) && k.bytes().all(|b| b.is_ascii_alphanumeric() || b == b'_');
11568×
        if !valid {
11571×
            ctx.err(e.span(), format!("environment name {k:?} must be letters, digits and _"));
11581×
            continue;
11597×
        }
11607×
        ctx.no_children(e);
11617×
        if let Some(v) = ctx.one_string(e) {
11627×
            if env.insert(k.clone(), v).is_some() {
11630×
                ctx.err(e.span(), format!("environment {k} is set twice"));
11647×
            }
11650×
        }
1166
    }
11677×
}
1168
1169
/// `mount { source "ephemeral://disk"; target "/src/target"; size "8GiB" }`.
117060×
fn parse_mount(ctx: &mut Ctx, node: &KdlNode) -> Option<Mount> {
117160×
    let (mut source, mut target, mut size) = (None, None, None);
117260×
    let (mut cache, mut keys) = (None, Vec::new());
117360×
    let mut seen = BTreeSet::new();
1174187×
    for c in block(ctx, node) {
1175187×
        let key = c.name().value();
1176187×
        if !seen.insert(key.to_string()) {
11771×
            ctx.err(c.span(), format!("`{key}` is given twice"));
11781×
            continue;
1179186×
        }
1180186×
        ctx.no_children(c);
1181186×
        match key {
1182186×
            "source" => {
118360×
                source = match ctx.one_string(c).as_deref() {
118460×
                    Some("ephemeral://tmpfs") => Some(MountSource::Tmpfs),
118539×
                    Some("ephemeral://disk") => Some(MountSource::Disk),
11862×
                    Some(other) => {
11872×
                        ctx.err(
11882×
                            c.span(),
11892×
                            format!("mount source {other:?} is not in M0 yet; M0 mounts \"ephemeral://tmpfs\" or \"ephemeral://disk\""),
1190
                        );
11912×
                        None
1192
                    }
11930×
                    None => None,
1194
                }
1195
            }
1196126×
            "target" => {
119759×
                target = match ctx.one_string(c) {
119859×
                    Some(t) if mount_target_ok(&t) => Some(t),
11994×
                    Some(t) => {
12004×
                        ctx.err(
12014×
                            c.span(),
12024×
                            format!("mount target {t:?} must be an absolute path under /src or /tmp, without . or .. or a trailing /"),
1203
                        );
12044×
                        None
1205
                    }
12060×
                    None => None,
1207
                }
1208
            }
120967×
            "size" => {
121058×
                size = match ctx.one_string(c) {
121158×
                    Some(m) => match parse_memory(&m) {
121257×
                        Some(mib) if (MIN_MOUNT_MIB..=MAX_MOUNT_MIB).contains(&mib) => Some(mib as u32),
1213
                        Some(_) => {
12142×
                            ctx.err(c.span(), format!("mount size {m:?} must be from 16MiB to 64GiB"));
12152×
                            None
1216
                        }
1217
                        None => {
12181×
                            ctx.err(c.span(), format!("mount size {m:?}: expected a whole number of KiB, MiB or GiB, as \"8GiB\""));
12191×
                            None
1220
                        }
1221
                    },
12220×
                    None => None,
1223
                }
1224
            }
12259×
            "cache" => {
12265×
                cache = match ctx.one_string(c) {
122717×
                    Some(n) if !n.is_empty() && n.len() <= 64 && n.bytes().all(|b| b.is_ascii_alphanumeric() || b"._-".contains(&b)) => {
12284×
                        Some(n)
1229
                    }
12301×
                    Some(n) => {
12311×
                        ctx.err(c.span(), format!("cache name {n:?}: letters, digits, '.', '_' and '-', at most 64"));
12321×
                        None
1233
                    }
12340×
                    None => None,
1235
                }
1236
            }
12374×
            "key" => {
12383×
                keys = ctx.strings(c);
12393×
                if keys.is_empty() {
12400×
                    ctx.err(c.span(), "`key` names one or more files, as \"Cargo.lock\"");
12413×
                }
12424×
                for k in &keys {
12434×
                    if k.starts_with('/') || k.split('/').any(|p| p.is_empty() || p == "." || p == "..") {
12441×
                        ctx.err(c.span(), format!("key file {k:?} must be a path in the repository, without . or .."));
12453×
                    }
1246
                }
1247
            }
12481×
            "readonly" | "include" => ctx.err(c.span(), format!("mount `{key}` is not in M0 yet")),
12490×
            other => ctx.err(c.span(), format!("unknown mount setting `{other}`")),
1250
        }
1251
    }
1252180×
    for (name, missing) in [("source", source.is_none()), ("target", target.is_none()), ("size", size.is_none())] {
1253180×
        if missing && !seen.contains(name) {
12543×
            ctx.err(node.span(), format!("a mount needs a {name}"));
1255177×
        }
1256
    }
125760×
    if source == Some(MountSource::Tmpfs) && cache.is_some() {
12581×
        ctx.err(node.span(), "only an ephemeral://disk mount can be a cache");
125959×
    }
126060×
    if !keys.is_empty() && cache.is_none() {
12611×
        ctx.err(node.span(), "`key` goes with `cache`");
126259×
    }
126360×
    Some(Mount { source: source?, target: target?, size_mib: size?, cache, key: keys })
126460×
}
1265
1266
/// `output { artifact "name" { path "/src/target/release/tool" } }`.
1267
/// `secret "deploy-token" { mount-path "/run/secrets/token" }` (spec §9.1).
1268
/// The hub is the vault: the secret of that name set for the repository,
1269
/// its organisation or the site. `vault-ref` is not in this slice.
127012×
fn parse_secret(ctx: &mut Ctx, node: &KdlNode, job: &mut Job) {
127112×
    let Some(name) = ctx.one_string(node) else {
12720×
        ctx.err(node.span(), "`secret` takes a name and a block with mount-path");
12730×
        return;
1274
    };
127512×
    if !ctx.name_ok(node.span(), "secret", &name) {
12760×
        return;
127712×
    }
127812×
    let mut path = None;
127912×
    for c in block(ctx, node) {
128012×
        ctx.no_children(c);
128112×
        match c.name().value() {
128212×
            "mount-path" => match ctx.one_string(c) {
128311×
                Some(p) if secret_path_ok(&p) => path = Some(p),
12842×
                Some(p) => {
12852×
                    ctx.err(c.span(), format!("secret mount-path {p:?} must be an absolute path under /run/secrets/, without . or .."))
1286
                }
12870×
                None => {}
1288
            },
12891×
            "vault-ref" => ctx.err(c.span(), "`vault-ref` is not in M0; the hub supplies the secret of that name"),
12900×
            other => ctx.err(c.span(), format!("unknown secret setting `{other}`")),
1291
        }
1292
    }
129312×
    let Some(mount_path) = path else {
12943×
        ctx.err(node.span(), format!("secret {name:?} needs a mount-path"));
12953×
        return;
1296
    };
12979×
    if job.secrets.iter().any(|s| s.name == name) {
12981×
        ctx.err(node.span(), format!("secret {name:?} is given twice"));
12998×
    } else if job.secrets.iter().any(|s| s.mount_path == mount_path) || job.identities.iter().any(|i| i.mount_path == mount_path) {
13002×
        ctx.err(node.span(), format!("two files mount at {mount_path:?}"));
13016×
    } else if job.secrets.len() == MAX_SECRETS {
13020×
        ctx.err(node.span(), format!("a job has at most {MAX_SECRETS} secrets"));
13036×
    } else {
13046×
        job.secrets.push(Secret { name, mount_path });
13056×
    }
130612×
}
1307
1308
/// `identity "sts.amazonaws.com" { mount-path "/run/secrets/aws-token" }`:
1309
/// the hub mints an OIDC token for that audience and the runner mounts it
1310
/// as a file (oxygenhub#103).
13118×
fn parse_identity(ctx: &mut Ctx, node: &KdlNode, job: &mut Job) {
13128×
    let Some(audience) = ctx.one_string(node) else {
13130×
        ctx.err(node.span(), "`identity` takes an audience and a block with mount-path");
13140×
        return;
1315
    };
131645×
    let aud_ok = !audience.is_empty() && audience.len() <= 255 && !audience.chars().any(|c| c.is_whitespace() || c.is_control());
13178×
    if !aud_ok {
13181×
        ctx.err(node.span(), format!("identity audience {audience:?} must be 1 to 255 characters without spaces"));
13191×
        return;
13207×
    }
13217×
    let mut path = None;
13227×
    for c in block(ctx, node) {
13236×
        ctx.no_children(c);
13246×
        match c.name().value() {
13256×
            "mount-path" => match ctx.one_string(c) {
13266×
                Some(p) if secret_path_ok(&p) => path = Some(p),
13271×
                Some(p) => {
13281×
                    ctx.err(c.span(), format!("identity mount-path {p:?} must be an absolute path under /run/secrets/, without . or .."))
1329
                }
13300×
                None => {}
1331
            },
13320×
            other => ctx.err(c.span(), format!("unknown identity setting `{other}`")),
1333
        }
1334
    }
13357×
    let Some(mount_path) = path else {
13362×
        ctx.err(node.span(), format!("identity {audience:?} needs a mount-path"));
13372×
        return;
1338
    };
13395×
    if job.identities.iter().any(|i| i.audience == audience) {
13401×
        ctx.err(node.span(), format!("identity {audience:?} is given twice"));
13414×
    } else if job.identities.iter().any(|i| i.mount_path == mount_path) || job.secrets.iter().any(|s| s.mount_path == mount_path) {
13420×
        ctx.err(node.span(), format!("two files mount at {mount_path:?}"));
13434×
    } else if job.identities.len() == MAX_IDENTITIES {
13440×
        ctx.err(node.span(), format!("a job has at most {MAX_IDENTITIES} identities"));
13454×
    } else {
13464×
        job.identities.push(Identity { audience, mount_path });
13474×
    }
13488×
}
1349
135023×
fn parse_output(ctx: &mut Ctx, node: &KdlNode, job: &mut Job) {
135123×
    if !node.entries().is_empty() {
13520×
        ctx.err(node.span(), "`output` takes a block of artifacts and reports");
135323×
    }
135437×
    for a in block(ctx, node) {
135537×
        let kind = match a.name().value() {
135637×
            "artifact" => OutputKind::Artifact,
135713×
            "report" => OutputKind::Report,
13580×
            other => {
13590×
                ctx.err(
13600×
                    a.span(),
13610×
                    format!("unknown output `{other}`; outputs are `artifact \"name\" {{ path \"/src/file\" }}` and `report \"name\" {{ path \"/src/dir\" }}`"),
1362
                );
13630×
                continue;
1364
            }
1365
        };
136637×
        let word = kind.word();
136737×
        let Some(name) = ctx.one_string(a) else { continue };
136837×
        if !ctx.name_ok(a.span(), word, &name) {
13690×
            continue;
137037×
        }
137137×
        let mut path = None;
137237×
        let mut always = false;
137342×
        for c in block(ctx, a) {
137442×
            ctx.no_children(c);
137542×
            match c.name().value() {
137642×
                "path" => match ctx.one_string(c) {
137735×
                    Some(p) if output_path_ok(&p) => path = Some(p),
13782×
                    Some(p) => ctx
13792×
                        .err(c.span(), format!("{word} path {p:?} must be an absolute path under /src, without . or .., quotes or spaces")),
13800×
                    None => {}
1381
                },
13827×
                "format" if kind == OutputKind::Artifact => {
13832×
                    if ctx.one_string(c).as_deref() != Some("blob") {
13841×
                        ctx.err(c.span(), "artifact format is \"blob\"");
13851×
                    }
1386
                }
13875×
                "when" => match ctx.one_string(c).as_deref() {
13885×
                    Some("passed") => always = false,
13894×
                    Some("always") => always = true,
13901×
                    Some(_) => ctx.err(c.span(), format!("{word} `when` is \"passed\" (the default) or \"always\"")),
13910×
                    None => {}
1392
                },
13930×
                other => ctx.err(c.span(), format!("unknown {word} setting `{other}`")),
1394
            }
1395
        }
139637×
        let Some(path) = path else {
13974×
            ctx.err(a.span(), format!("{word} {name:?} needs a path"));
13984×
            continue;
1399
        };
140033×
        if job.outputs.iter().any(|o| o.name == name) {
14012×
            ctx.err(a.span(), format!("output {name:?} is given twice (artifacts and reports share names)"));
140231×
        } else if job.outputs.len() == MAX_OUTPUTS {
14030×
            ctx.err(a.span(), format!("a job has at most {MAX_OUTPUTS} artifacts and reports"));
140431×
        } else {
140531×
            job.outputs.push(Output { name, path, always, kind });
140631×
        }
1407
    }
140823×
}
1409
1410
/// `approval { by "maintain"; others-only #true; expires "24h" }`, each
1411
/// optional: `maintain`, anyone with the role, 24 hours.
1412
/// The approval, and whether it said `sealed` itself (else the job's
1413
/// environment decides).
141411×
fn parse_approval(ctx: &mut Ctx, node: &KdlNode) -> Option<(Approval, bool)> {
141511×
    if !node.entries().is_empty() {
14160×
        ctx.err(node.span(), "`approval` takes a block: approval { by \"maintain\"; others-only #true; expires \"24h\" }");
141711×
    }
141811×
    let mut a = Approval { by: "maintain".into(), others_only: false, expires_s: 24 * 3600, sealed: false };
141911×
    let mut sealed_said = false;
142011×
    let Some(children) = node.children() else { return Some((a, false)) };
142111×
    for c in children.nodes() {
142211×
        ctx.no_children(c);
142311×
        match c.name().value() {
142411×
            "by" => match ctx.one_string(c).as_deref() {
14252×
                Some(r @ ("write" | "maintain" | "admin")) => a.by = r.to_string(),
14261×
                Some(r) => ctx.err(c.span(), format!("approval by {r:?}: expected \"write\", \"maintain\" or \"admin\"")),
14270×
                None => {}
1428
            },
14299×
            "others-only" => match c.entries() {
14302×
                [e] if e.name().is_none() => match e.value() {
14311×
                    KdlValue::Bool(b) => a.others_only = *b,
14321×
                    _ => ctx.err(c.span(), "`others-only` takes #true or #false"),
1433
                },
14340×
                _ => ctx.err(c.span(), "`others-only` takes #true or #false"),
1435
            },
14367×
            "sealed" => match c.entries() {
14374×
                [e] if e.name().is_none() => match e.value() {
14383×
                    KdlValue::Bool(b) => {
14393×
                        a.sealed = *b;
14403×
                        sealed_said = true;
14413×
                    }
14421×
                    _ => ctx.err(c.span(), "`sealed` takes #true or #false"),
1443
                },
14440×
                _ => ctx.err(c.span(), "`sealed` takes #true or #false"),
1445
            },
14463×
            "expires" => {
14472×
                let Some(t) = ctx.one_string(c) else { continue };
14482×
                match parse_duration(&t) {
14492×
                    Some(secs) if (60..=MAX_APPROVAL_S).contains(&secs) => a.expires_s = secs,
14501×
                    Some(_) => ctx.err(c.span(), format!("expires {t:?} must be from 1m to 720h")),
14510×
                    None => ctx.err(c.span(), format!("expires {t:?}: expected hours, minutes and seconds, as \"24h\"")),
1452
                }
1453
            }
14541×
            other => {
14551×
                ctx.err(c.span(), format!("unknown approval setting `{other}`; approval takes `by`, `others-only`, `expires` and `sealed`"))
1456
            }
1457
        }
1458
    }
14599×
    Some((a, sealed_said))
146011×
}
1461
1462
/// `input { artifact "NAME" from "JOB"; path "/src/FILE" }`.
146310×
fn parse_input(ctx: &mut Ctx, node: &KdlNode, job: &mut Job) {
146410×
    if !node.entries().is_empty() {
14650×
        ctx.err(node.span(), "`input` takes a block: input { artifact \"tfplan\" from \"plan\"; path \"/src/tfplan\" }");
146610×
    }
146710×
    let (mut artifact, mut from, mut path) = (None, None, None);
146819×
    for c in block(ctx, node) {
146919×
        ctx.no_children(c);
147019×
        match c.name().value() {
147119×
            "artifact" => match ctx.strings(c).as_slice() {
14729×
                [name, word, producer] if word == "from" => {
14739×
                    if ctx.name_ok(c.span(), "artifact", name) && ctx.name_ok(c.span(), "job", producer) {
14749×
                        artifact = Some(name.clone());
14759×
                        from = Some(producer.clone());
14769×
                    }
1477
                }
14781×
                _ => ctx.err(c.span(), "`artifact` names the artifact and its job: artifact \"tfplan\" from \"plan\""),
1479
            },
14809×
            "path" => match ctx.one_string(c) {
14819×
                Some(p) if output_path_ok(&p) => path = Some(p),
14821×
                Some(p) => {
14831×
                    ctx.err(c.span(), format!("input path {p:?} must be an absolute path under /src, without . or .., quotes or spaces"))
1484
                }
14850×
                None => {}
1486
            },
14870×
            other => ctx.err(c.span(), format!("unknown input setting `{other}`; an input has `artifact` and `path`")),
1488
        }
1489
    }
149010×
    match (artifact, from, path) {
14917×
        (Some(artifact), Some(from), Some(path)) => {
14927×
            if job.inputs.iter().any(|i| i.path == path) {
14931×
                ctx.err(node.span(), format!("two inputs are put at {path:?}"));
14946×
            } else if job.inputs.len() == MAX_INPUTS {
14950×
                ctx.err(node.span(), format!("a job takes at most {MAX_INPUTS} inputs"));
14966×
            } else {
14976×
                job.inputs.push(Input { artifact, from, path });
14986×
            }
1499
        }
15003×
        (a, _, p) => {
15013×
            if a.is_some() && p.is_none() {
15022×
                ctx.err(node.span(), "an input needs a `path`");
15032×
            } else if a.is_none() && p.is_some() {
15041×
                ctx.err(node.span(), "an input needs `artifact \"NAME\" from \"JOB\"`");
15051×
            }
1506
        }
1507
    }
150810×
}
1509
1510173×
fn parse_job(ctx: &mut Ctx, node: &KdlNode) -> Option<Job> {
1511173×
    let name = ctx.one_string(node)?;
1512173×
    let named = ctx.name_ok(node.span(), "job", &name);
1513173×
    let mut approval: Option<(Approval, bool)> = None;
1514173×
    let mut job = Job {
1515173×
        name: name.clone(),
1516173×
        sandbox: String::new(),
1517173×
        scope: vec![],
1518173×
        depends_on: vec![],
1519173×
        env: BTreeMap::new(),
1520173×
        exec: vec![],
1521173×
        mounts: vec![],
1522173×
        secrets: vec![],
1523173×
        identities: vec![],
1524173×
        outputs: vec![],
1525173×
        inputs: vec![],
1526173×
        approval: None,
1527173×
        environment: None,
1528173×
        runs_on: vec![],
1529173×
        timeout_s: None,
1530173×
        on: None,
1531173×
        priority: None,
1532173×
    };
1533173×
    let mut seen = BTreeSet::new();
1534173×
    let mut outputs_at = None;
1535518×
    for c in block(ctx, node) {
1536518×
        let key = c.name().value();
1537518×
        if key != "scope"
1538517×
            && key != "depends-on"
1539500×
            && key != "mount"
1540440×
            && key != "secret"
1541428×
            && key != "identity"
1542420×
            && key != "runs-on"
1543417×
            && !seen.insert(key.to_string())
15441×
        {
15451×
            ctx.err(c.span(), format!("`{key}` is given twice"));
1546517×
        }
15470×
        match key {
1548518×
            "sandbox" => {
1549173×
                ctx.no_children(c);
1550173×
                job.sandbox = ctx.one_string(c).unwrap_or_default();
1551173×
            }
1552345×
            "scope" => {
15531×
                ctx.no_children(c);
15542×
                for g in ctx.strings(c) {
15552×
                    match globset::Glob::new(&g) {
15562×
                        Ok(_) => job.scope.push(g),
15570×
                        Err(e) => ctx.err(c.span(), format!("scope {g:?}: {e}")),
1558
                    }
1559
                }
1560
            }
1561344×
            "depends-on" => {
156217×
                ctx.no_children(c);
156317×
                job.depends_on.extend(ctx.strings(c));
156417×
            }
1565327×
            "runs-on" => {
15663×
                ctx.no_children(c);
15673×
                parse_labels(ctx, c, &mut job.runs_on);
15683×
            }
1569324×
            "timeout" => {
15703×
                ctx.no_children(c);
15713×
                job.timeout_s = parse_timeout(ctx, c);
15723×
            }
1573321×
            "priority" => job.priority = parse_priority(ctx, c),
1574316×
            "on" => job.on = Some(parse_on(ctx, c)),
1575306×
            "env" => parse_env(ctx, c, &mut job.env),
1576301×
            "exec" => {
1577173×
                ctx.no_children(c);
1578173×
                job.exec = ctx.strings(c);
1579173×
                if job.exec.is_empty() {
15801×
                    ctx.err(c.span(), "`exec` needs a program and its arguments");
1581191×
                } else if job.exec.iter().any(|a| a.contains('\0')) {
15820×
                    ctx.err(c.span(), "`exec` arguments cannot contain NUL");
1583172×
                }
1584
            }
1585128×
            "mount" => {
158660×
                if !c.entries().is_empty() {
15870×
                    ctx.err(c.span(), "`mount` takes a block of source, target and size");
158860×
                }
158960×
                if let Some(m) = parse_mount(ctx, c) {
159050×
                    if job.mounts.len() == MAX_MOUNTS {
15911×
                        ctx.err(c.span(), format!("a job has at most {MAX_MOUNTS} mounts"));
159249×
                    } else if let Some(other) = job.mounts.iter().find(|o| {
159324×
                        o.target == m.target
159423×
                            || m.target.starts_with(&format!("{}/", o.target))
159522×
                            || o.target.starts_with(&format!("{}/", m.target))
159624×
                    }) {
15972×
                        ctx.err(c.span(), format!("mount {:?} overlaps mount {:?}", m.target, other.target));
159847×
                    } else {
159947×
                        job.mounts.push(m);
160047×
                    }
160110×
                }
1602
            }
160368×
            "output" => {
160423×
                outputs_at = Some(c.span());
160523×
                parse_output(ctx, c, &mut job);
160623×
            }
160745×
            "input" => parse_input(ctx, c, &mut job),
160835×
            "approval" => approval = parse_approval(ctx, c),
160924×
            "environment" => {
16104×
                ctx.no_children(c);
16114×
                if let Some(e) = ctx.one_string(c) {
161213×
                    let ok = !e.is_empty() && e.len() <= 32 && e.bytes().all(|b| b.is_ascii_lowercase() || b.is_ascii_digit() || b == b'-');
16134×
                    if ok {
16143×
                        job.environment = Some(e);
16153×
                    } else {
16161×
                        ctx.err(c.span(), format!("environment {e:?}: 1 to 32 of a-z 0-9 -, as \"prod\""));
16171×
                    }
16180×
                }
1619
            }
162020×
            "secret" => parse_secret(ctx, c, &mut job),
16218×
            "identity" => parse_identity(ctx, c, &mut job),
16220×
            n if LATER_JOB.contains(&n) => ctx.err(c.span(), format!("`{n}` is not in M0 yet")),
16230×
            other => ctx.err(c.span(), format!("unknown job setting `{other}`")),
1624
        }
1625
    }
1626
    // A job for an environment takes a sealed approval unless it says not.
1627173×
    job.approval = approval.map(|(mut a, said)| {
162811×
        if !said {
16298×
            a.sealed = job.environment.is_some();
16308×
        }
163111×
        a
163211×
    });
1633173×
    job.mounts.sort_by(|a, b| a.target.cmp(&b.target));
1634173×
    job.outputs.sort_by(|a, b| a.name.cmp(&b.name));
1635173×
    job.inputs.sort_by(|a, b| a.path.cmp(&b.path));
1636173×
    job.secrets.sort_by(|a, b| a.name.cmp(&b.name));
1637173×
    job.identities.sort_by(|a, b| a.audience.cmp(&b.audience));
1638
    // A tmpfs is gone when the job ends; nothing on it can be kept.
1639173×
    for o in &job.outputs {
164031×
        if let Some(m) = job.mounts.iter().find(|m| m.source == MountSource::Tmpfs && o.path.starts_with(&format!("{}/", m.target))) {
16411×
            ctx.err(
16421×
                outputs_at.unwrap_or(node.span()),
16431×
                format!(
16441×
                    "artifact {:?} is on the tmpfs mount {:?}, which is gone when the job ends; use ephemeral://disk",
16451×
                    o.name, m.target
16461×
                ),
16471×
            );
164830×
        }
1649
    }
1650173×
    if job.sandbox.is_empty() && !seen.contains("sandbox") {
16510×
        ctx.err(node.span(), format!("job {name:?} needs a sandbox"));
1652173×
    }
1653173×
    if job.exec.is_empty() && !seen.contains("exec") {
16540×
        ctx.err(node.span(), format!("job {name:?} needs an exec"));
1655173×
    }
1656173×
    job.depends_on.sort();
1657173×
    job.depends_on.dedup();
1658
    // Kept even when incomplete, so its references are checked too; the
1659
    // problems above already make the pipeline invalid.
1660173×
    named.then_some(job)
1661173×
}