LINE1 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.14pubstructJob {15 id: String,16 kind: &'staticstr,17 state: Mutex<State>,18}1920#[derive(Default)]21structState {22 events: Vec<Value>,23 outcome: Outcome,24}2526#[derive(Default)]27enumOutcome {28#[default]29Running,30Succeeded(Value),31Failed(String),32}3334implJob {35pubfnnew(kind: &'staticstr) -> Self {36Self {37 id: format!("{:016x}", rand::random::<u64>()),38 kind,39 state: Mutex::new(State::default()),40 }41 }4243pubfnstep(&self, message: &str) {44self.push(json!({ "type": "step", "message": message }));45 }4647pubfnoutput(&self, stream: &str, line: &str) {48self.push(json!({ "type": "output", "stream": stream, "line": line }));49 }5051/// Records an event produced by a child process or by this job.52pubfnpush(&self, event: Value) {53self.lock().events.push(event);54 }5556fnlock(&self) -> MutexGuard<'_, State> {57self.state.lock().unwrap_or_else(PoisonError::into_inner)58 }5960fnis_running(&self) -> bool {61matches!(self.lock().outcome, Outcome::Running)62 }6364fnfinish(&self, outcome: Outcome) {65self.lock().outcome = outcome;66 }6768/// The job's status and the events from index `after` on.69pubfnsnapshot(&self, after: usize) -> Value {70let state = self.lock();71let (status, result, error) = match &state.outcome {72Outcome::Running => ("running", Value::Null, Value::Null),73Outcome::Succeeded(result) => ("succeeded", result.clone(), Value::Null),74Outcome::Failed(message) => ("failed", Value::Null, json!(message)),75 };76json!({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)]90pubstructJobs {91 current: Option<Arc<Job>>,92}9394/// Returned when a job is still running.95pubstructBusy;9697implJobs {98pubfnfind(&self, id: &str) -> Option<Arc<Job>> {99self.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.104pubfn start<F>(&mutself, kind: &'staticstr, work: F) -> Result<String, Busy>105where106F: FnOnce(&Job) -> Result<Value, String> + Send + 'static,107 {108ifself.current.as_ref().is_some_and(|job| job.is_running()) {109returnErr(Busy);110 }111let job = Arc::new(Job::new(kind));112let id = job.id.clone();113self.current = Some(Arc::clone(&job));114 thread::spawn(move || {115let run = panic::catch_unwind(AssertUnwindSafe(|| work(&job)));116let outcome = match run {117Ok(Ok(result)) => Outcome::Succeeded(result),118Ok(Err(message)) => Outcome::Failed(message),119Err(_) => Outcome::Failed("the job stopped unexpectedly".to_owned()),120 };121 job.finish(outcome);122 });123Ok(id)124 }125}126127#[cfg(test)]128mod tests {129use std::time::{Duration, Instant};130131use serde_json::json;132133usesuper::{Busy, Jobs};134135fnwait_for_outcome(jobs: &Jobs, id: &str) -> serde_json::Value {136let deadline = Instant::now() + Duration::from_secs(5);137loop {138let snapshot = jobs.find(id).unwrap().snapshot(0);139if snapshot["status"] != "running" || Instant::now() > deadline {140return snapshot;141 }142 std::thread::sleep(Duration::from_millis(5));143 }144 }145146#[test]147fnkeeps_events_and_the_result_of_a_job() {148letmut jobs = Jobs::default();149let id = jobs150 .start("check", |job| {151 job.step("Cloning");152 job.output("stderr", "Receiving objects");153Ok(json!({ "version": "1.0.0" }))154 })155 .ok()156 .unwrap();157let snapshot = wait_for_outcome(&jobs, &id);158assert_eq!(snapshot["status"], "succeeded");159assert_eq!(snapshot["result"]["version"], "1.0.0");160assert_eq!(snapshot["events"].as_array().unwrap().len(), 2);161assert_eq!(snapshot["events"][0]["type"], "step");162assert_eq!(snapshot["next"], 2);163assert_eq!(jobs.find(&id).unwrap().snapshot(2)["events"], json!([]));164 }165166#[test]167fnreports_a_failure_and_a_panic_as_failed_jobs() {168letmut jobs = Jobs::default();169let id = jobs170 .start("release", |_| Err("ino exited with status 1".to_owned()))171 .ok()172 .unwrap();173let snapshot = wait_for_outcome(&jobs, &id);174assert_eq!(snapshot["status"], "failed");175assert_eq!(snapshot["error"], "ino exited with status 1");176177let id = jobs.start("release", |_| panic!("boom")).ok().unwrap();178assert_eq!(wait_for_outcome(&jobs, &id)["status"], "failed");179 }180181#[test]182fnrefuses_a_second_job_while_one_runs() {183letmut jobs = Jobs::default();184let (release, held) = std::sync::mpsc::channel::<()>();185let _first = jobs186 .start("release", move |_| {187let _ = held.recv();188Ok(json!({}))189 })190 .ok()191 .unwrap();192assert!(matches!(jobs.start("check", |_| Ok(json!({}))), Err(Busy)));193let _ = release.send(());194 }195}