Skip to content
1        10        20        30        40        50        60        70        801//! Background jobs for the Deploy tab. A job runs on its own thread and keeps2//! every event it produces. The page polls for the events it has not seen yet,3//! so progress shows while the work runs. Only one job runs at a time.45use std::{6    panic::{self, AssertUnwindSafe},7    sync::{Arc, Mutex, MutexGuard, PoisonError},8    thread,9};1011use serde_json::{Value, json};1213/// One unit of work and the events it has produced so far.14pub struct Job {15    id: String,16    kind: &'static str,17    state: Mutex<State>,18}1920#[derive(Default)]21struct State {22    events: Vec<Value>,23    outcome: Outcome,24}2526#[derive(Default)]27enum Outcome {28    #[default]29    Running,30    Succeeded(Value),31    Failed(String),32}3334impl Job {35    pub fn new(kind: &'static str) -> Self {36        Self {37            id: format!("{:016x}", rand::random::<u64>()),38            kind,39            state: Mutex::new(State::default()),40        }41    }4243    pub fn step(&self, message: &str) {44        self.push(json!({ "type": "step", "message": message }));45    }4647    pub fn output(&self, stream: &str, line: &str) {48        self.push(json!({ "type": "output", "stream": stream, "line": line }));49    }5051    /// Records an event produced by a child process or by this job.52    pub fn push(&self, event: Value) {53        self.lock().events.push(event);54    }5556    fn lock(&self) -> MutexGuard<'_, State> {57        self.state.lock().unwrap_or_else(PoisonError::into_inner)58    }5960    fn is_running(&self) -> bool {61        matches!(self.lock().outcome, Outcome::Running)62    }6364    fn finish(&self, outcome: Outcome) {65        self.lock().outcome = outcome;66    }6768    /// The job's status and the events from index `after` on.69    pub fn snapshot(&self, after: usize) -> Value {70        let state = self.lock();71        let (status, result, error) = match &state.outcome {72            Outcome::Running => ("running", Value::Null, Value::Null),73            Outcome::Succeeded(result) => ("succeeded", result.clone(), Value::Null),74            Outcome::Failed(message) => ("failed", Value::Null, json!(message)),75        };76        json!({77            "id": self.id,78            "kind": self.kind,79            "status": status,80            "events": state.events.get(after..).unwrap_or_default(),81            "next": state.events.len(),82            "result": result,83            "error": error,84        })85    }86}8788/// The job the console is running or last ran.89#[derive(Default)]90pub struct Jobs {91    current: Option<Arc<Job>>,92}9394/// Returned when a job is still running.95pub struct Busy;9697impl Jobs {98    pub fn find(&self, id: &str) -> Option<Arc<Job>> {99        self.current.as_ref().filter(|job| job.id == id).cloned()100    }101102    /// Starts `work` on a new thread and returns the job's id. The work's103    /// result, or its error message, becomes the job's outcome.104    pub fn start<F>(&mut self, kind: &'static str, work: F) -> Result<String, Busy>105    where106        F: FnOnce(&Job) -> Result<Value, String> + Send + 'static,107    {108        if self.current.as_ref().is_some_and(|job| job.is_running()) {109            return Err(Busy);110        }111        let job = Arc::new(Job::new(kind));112        let id = job.id.clone();113        self.current = Some(Arc::clone(&job));114        thread::spawn(move || {115            let run = panic::catch_unwind(AssertUnwindSafe(|| work(&job)));116            let outcome = match run {117                Ok(Ok(result)) => Outcome::Succeeded(result),118                Ok(Err(message)) => Outcome::Failed(message),119                Err(_) => Outcome::Failed("the job stopped unexpectedly".to_owned()),120            };121            job.finish(outcome);122        });123        Ok(id)124    }125}126127#[cfg(test)]128mod tests {129    use std::time::{Duration, Instant};130131    use serde_json::json;132133    use super::{Busy, Jobs};134135    fn wait_for_outcome(jobs: &Jobs, id: &str) -> serde_json::Value {136        let deadline = Instant::now() + Duration::from_secs(5);137        loop {138            let snapshot = jobs.find(id).unwrap().snapshot(0);139            if snapshot["status"] != "running" || Instant::now() > deadline {140                return snapshot;141            }142            std::thread::sleep(Duration::from_millis(5));143        }144    }145146    #[test]147    fn keeps_events_and_the_result_of_a_job() {148        let mut jobs = Jobs::default();149        let id = jobs150            .start("check", |job| {151                job.step("Cloning");152                job.output("stderr", "Receiving objects");153                Ok(json!({ "version": "1.0.0" }))154            })155            .ok()156            .unwrap();157        let snapshot = wait_for_outcome(&jobs, &id);158        assert_eq!(snapshot["status"], "succeeded");159        assert_eq!(snapshot["result"]["version"], "1.0.0");160        assert_eq!(snapshot["events"].as_array().unwrap().len(), 2);161        assert_eq!(snapshot["events"][0]["type"], "step");162        assert_eq!(snapshot["next"], 2);163        assert_eq!(jobs.find(&id).unwrap().snapshot(2)["events"], json!([]));164    }165166    #[test]167    fn reports_a_failure_and_a_panic_as_failed_jobs() {168        let mut jobs = Jobs::default();169        let id = jobs170            .start("release", |_| Err("ino exited with status 1".to_owned()))171            .ok()172            .unwrap();173        let snapshot = wait_for_outcome(&jobs, &id);174        assert_eq!(snapshot["status"], "failed");175        assert_eq!(snapshot["error"], "ino exited with status 1");176177        let id = jobs.start("release", |_| panic!("boom")).ok().unwrap();178        assert_eq!(wait_for_outcome(&jobs, &id)["status"], "failed");179    }180181    #[test]182    fn refuses_a_second_job_while_one_runs() {183        let mut jobs = Jobs::default();184        let (release, held) = std::sync::mpsc::channel::<()>();185        let _first = jobs186            .start("release", move |_| {187                let _ = held.recv();188                Ok(json!({}))189            })190            .ok()191            .unwrap();192        assert!(matches!(jobs.start("check", |_| Ok(json!({}))), Err(Busy)));193        let _ = release.send(());194    }195}