Skip to main content

specfold_core/plugins/runner/
pool.rs

1//! Runs a batch of commands: identical ones once, light ones on a worker pool, heavy ones one at a
2//! time in their own lane alongside it. Results come back in the order the jobs were given. Each
3//! command's deadline starts when it is spawned, so time spent queued never counts against it.
4
5use super::shell::{self, Outcome, Verdict};
6use super::tools;
7use regex::Regex;
8use std::collections::{HashMap, VecDeque};
9use std::path::Path;
10use std::sync::Mutex;
11use std::time::Duration;
12
13/// Rules run in parallel and X1 and G1 each call `run`; one batch at a time keeps the process
14/// within `jobs` light commands plus one heavy one.
15static BATCH: Mutex<()> = Mutex::new(());
16
17#[derive(Debug, Clone, PartialEq, Eq, Hash)]
18pub struct Job {
19    pub cmd: String,
20    pub env: Vec<(String, String)>,
21    pub timeout: Duration,
22}
23
24#[derive(Debug, Clone, Default)]
25pub struct Settings {
26    /// Workers for light commands; 0 means the number of CPUs, at most 8.
27    pub jobs: usize,
28    /// Commands matching any of these run one at a time.
29    pub serial: Vec<Regex>,
30    /// The shell to run commands in; `sh` when unset.
31    pub shell: Option<String>,
32}
33
34impl Settings {
35    fn workers(&self) -> usize {
36        if self.jobs > 0 {
37            return self.jobs;
38        }
39        std::thread::available_parallelism().map(|n| n.get().min(8)).unwrap_or(2)
40    }
41}
42
43fn one(root: &Path, job: &Job, shell_prog: Option<&str>) -> Outcome {
44    let missing = tools::missing_programs(root, &job.cmd);
45    if !missing.is_empty() {
46        return Outcome {
47            verdict: Verdict::CannotRun(format!("not installed: {}", missing.join(", "))),
48            tail: String::new(),
49            elapsed: Duration::ZERO,
50        };
51    }
52    shell::run(root, &job.cmd, &job.env, job.timeout, shell_prog)
53}
54
55fn drain(
56    root: &Path,
57    queue: &Mutex<VecDeque<usize>>,
58    unique: &[&Job],
59    done: &Mutex<Vec<Option<Outcome>>>,
60    shell_prog: Option<&str>,
61) {
62    loop {
63        let Some(i) = queue.lock().ok().and_then(|mut q| q.pop_front()) else { return };
64        let o = one(root, unique[i], shell_prog);
65        if let Ok(mut d) = done.lock() {
66            d[i] = Some(o);
67        }
68    }
69}
70
71pub fn run(root: &Path, jobs: &[Job], settings: &Settings) -> Vec<Outcome> {
72    let mut index: HashMap<&Job, usize> = HashMap::new();
73    let mut unique: Vec<&Job> = vec![];
74    let slots: Vec<usize> = jobs
75        .iter()
76        .map(|j| {
77            *index.entry(j).or_insert_with(|| {
78                unique.push(j);
79                unique.len() - 1
80            })
81        })
82        .collect();
83    let heavy = |j: &Job| settings.serial.iter().any(|r| r.is_match(&j.cmd));
84    let light: Mutex<VecDeque<usize>> = Mutex::new((0..unique.len()).filter(|&i| !heavy(unique[i])).collect());
85    let serial: Mutex<VecDeque<usize>> = Mutex::new((0..unique.len()).filter(|&i| heavy(unique[i])).collect());
86    let done: Mutex<Vec<Option<Outcome>>> = Mutex::new(vec![None; unique.len()]);
87    let shell_prog = settings.shell.as_deref();
88    let _turn = BATCH.lock().unwrap_or_else(std::sync::PoisonError::into_inner);
89    std::thread::scope(|s| {
90        s.spawn(|| drain(root, &serial, &unique, &done, shell_prog));
91        for _ in 0..settings.workers() {
92            s.spawn(|| drain(root, &light, &unique, &done, shell_prog));
93        }
94    });
95    let done = done.into_inner().unwrap_or_default();
96    slots
97        .into_iter()
98        .map(|i| {
99            done.get(i).cloned().flatten().unwrap_or(Outcome {
100                verdict: Verdict::CannotRun("not run".into()),
101                tail: String::new(),
102                elapsed: Duration::ZERO,
103            })
104        })
105        .collect()
106}
107
108#[cfg(all(test, unix))]
109mod tests {
110    use super::*;
111
112    fn job(cmd: &str) -> Job {
113        Job { cmd: cmd.into(), env: vec![], timeout: Duration::from_secs(10) }
114    }
115
116    #[test]
117    fn identical_commands_run_once_and_results_keep_order() {
118        let dir = tempfile::tempdir().unwrap();
119        let cmd = "echo x >> count.txt";
120        let jobs = [job(cmd), job("exit 2"), job(cmd), job("true")];
121        let settings = Settings { jobs: 3, serial: vec![Regex::new("^exit").unwrap()], shell: None };
122        let out = run(dir.path(), &jobs, &settings);
123        let verdicts: Vec<&Verdict> = out.iter().map(|o| &o.verdict).collect();
124        assert_eq!(verdicts, [&Verdict::Pass, &Verdict::Fail(Some(2)), &Verdict::Pass, &Verdict::Pass]);
125        assert_eq!(std::fs::read_to_string(dir.path().join("count.txt")).unwrap(), "x\n");
126    }
127
128    #[test]
129    fn a_missing_program_is_not_run() {
130        let dir = tempfile::tempdir().unwrap();
131        let out = run(dir.path(), &[job("no-such-tool-xyz && touch ran")], &Settings::default());
132        assert!(matches!(&out[0].verdict, Verdict::CannotRun(m) if m.contains("no-such-tool-xyz")));
133        assert!(!dir.path().join("ran").exists());
134    }
135
136    /// Jobs that each record how many of them were running at their start, in `dir/peak`.
137    fn counted(prefix: &str, n: usize, timeout: Duration) -> Vec<Job> {
138        (0..n)
139            .map(|i| Job {
140                cmd: format!("touch run.{prefix}{i}; ls run.* | wc -l >> peak; sleep 0.8; rm run.{prefix}{i}"),
141                env: vec![],
142                timeout,
143            })
144            .collect()
145    }
146
147    fn peak(dir: &Path) -> usize {
148        let text = std::fs::read_to_string(dir.join("peak")).expect("every job appends to peak");
149        text.lines().filter_map(|l| l.trim().parse::<usize>().ok()).max().expect("peak holds counts")
150    }
151
152    #[test]
153    fn parallel_batches_take_turns_within_one_pool_budget() {
154        let dir = tempfile::tempdir().unwrap();
155        let settings = Settings { jobs: 2, serial: vec![], shell: None };
156        std::thread::scope(|s| {
157            for prefix in ["a", "b"] {
158                let (dir, settings) = (dir.path(), &settings);
159                s.spawn(move || run(dir, &counted(prefix, 2, Duration::from_secs(10)), settings));
160            }
161        });
162        assert!(peak(dir.path()) <= 2, "two batches of two ran at most two at once, saw {}", peak(dir.path()));
163    }
164
165    #[test]
166    fn queued_commands_keep_their_whole_deadline() {
167        let dir = tempfile::tempdir().unwrap();
168        let cap = Duration::from_millis(2000);
169        let started = std::time::Instant::now();
170        let out = run(dir.path(), &counted("q", 6, cap), &Settings { jobs: 2, serial: vec![], shell: None });
171        assert!(started.elapsed() > cap, "six jobs two at a time outlast one cap: {:?}", started.elapsed());
172        assert!(out.iter().all(|o| o.verdict == Verdict::Pass), "{out:?}");
173        assert!(peak(dir.path()) <= 2, "at most two ran at once, saw {}", peak(dir.path()));
174    }
175
176    #[test]
177    fn a_hang_in_the_pool_fails_at_its_cap_and_frees_its_worker() {
178        let dir = tempfile::tempdir().unwrap();
179        let cap = Duration::from_millis(500);
180        let hang = Job { cmd: "sleep 30".into(), env: vec![], timeout: cap };
181        let after = Job { cmd: "true".into(), env: vec![], timeout: cap };
182        let out = run(dir.path(), &[hang, after], &Settings { jobs: 1, serial: vec![], shell: None });
183        assert_eq!(out[0].verdict, Verdict::Timeout);
184        assert!(out[0].elapsed >= cap && out[0].elapsed < Duration::from_secs(5), "{:?}", out[0].elapsed);
185        assert_eq!(out[1].verdict, Verdict::Pass);
186    }
187}