Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
102 changes: 67 additions & 35 deletions packages/cli/src/service/jobs.rs
Original file line number Diff line number Diff line change
Expand Up @@ -19,35 +19,72 @@ pub(super) const MAX_QUEUED_JOBS: usize = 16;
pub(super) struct Job {
pub(super) id: String,
pub(super) runner: Runner,
pub(super) result: Mutex<JobResult>,
pub(super) state: Mutex<JobState>,
pub(super) finished: Notify,
}

pub(super) struct JobResult {
pub(super) status: &'static str,
pub(super) diagnostics: Vec<Value>,
pub(super) document: Option<(&'static str, Value)>,
/// What a job collected: its document (`extraction` or `comparison`) and its notices.
pub(super) struct Collected {
pub(super) kind: &'static str,
pub(super) document: Value,
pub(super) notices: Vec<String>,
}

/// Where a job is. Waiting for its turn and running are both `running` on the wire: clients poll while it is.
pub(super) enum JobState {
Queued,
Running,
Completed(Collected),
Failed {
diagnostics: Vec<Value>,
},
/// Cancelled before it ran, or while it ran, with what it collected regardless.
Cancelled(Option<Collected>),
}

impl JobState {
pub(super) fn name(&self) -> &'static str {
match self {
Self::Queued | Self::Running => "running",
Self::Completed(_) => "completed",
Self::Failed { .. } => "failed",
Self::Cancelled(_) => "cancelled",
}
}

pub(super) fn finished(&self) -> bool {
!matches!(self, Self::Queued | Self::Running)
}
}

impl Job {
pub(super) fn value(&self) -> Value {
let result = self.result.lock().unwrap_or_else(|e| e.into_inner());
let state = self.state.lock().unwrap_or_else(|e| e.into_inner());
let (diagnostics, collected): (&[Value], Option<&Collected>) = match &*state {
JobState::Queued | JobState::Running | JobState::Cancelled(None) => (&[], None),
JobState::Completed(collected) | JobState::Cancelled(Some(collected)) => (&[], Some(collected)),
JobState::Failed { diagnostics } => (diagnostics, None),
};
let notices: &[String] = collected.map_or(&[], |collected| &collected.notices);
let mut value = json!({
"id": self.id,
"status": result.status,
"status": state.name(),
"outputs": *self.runner.outputs.lock().unwrap_or_else(|e| e.into_inner()),
"diagnostics": result.diagnostics,
"notices": result.notices,
"diagnostics": diagnostics,
"notices": notices,
});
if let Some((kind, document)) = &result.document {
value[*kind] = document.clone();
if let Some(collected) = collected {
value[collected.kind] = collected.document.clone();
}
value
}

pub(super) fn running(&self) -> bool {
self.result.lock().unwrap_or_else(|e| e.into_inner()).status == "running"
!self.state.lock().unwrap_or_else(|e| e.into_inner()).finished()
}

fn set(&self, state: JobState) {
*self.state.lock().unwrap_or_else(|e| e.into_inner()) = state;
}

pub(super) async fn wait(&self) {
Expand Down Expand Up @@ -148,12 +185,7 @@ pub(super) async fn start(state: &Arc<ServiceState>, request: Request) -> Result
let job = Arc::new(Job {
id: Uuid::new_v4().to_string(),
runner: state.runner(),
result: Mutex::new(JobResult {
status: "running",
diagnostics: Vec::new(),
document: None,
notices: Vec::new(),
}),
state: Mutex::new(JobState::Queued),
finished: Notify::new(),
});
jobs.push_back(job.clone());
Expand All @@ -166,10 +198,11 @@ pub(super) async fn start(state: &Arc<ServiceState>, request: Request) -> Result
let _turn = queue.collecting.lock().await;
// Cancelled (or the service closed) while it waited: it never runs.
if job.runner.cancel.load(Ordering::SeqCst) {
job.result.lock().unwrap_or_else(|e| e.into_inner()).status = "cancelled";
job.set(JobState::Cancelled(None));
job.finished.notify_waiters();
return;
}
job.set(JobState::Running);
let runner = job.runner.clone();
let kind = if input.after.is_some() { "comparison" } else { "extraction" };
let collected = tokio::task::spawn_blocking(move || {
Expand Down Expand Up @@ -215,24 +248,23 @@ pub(super) async fn start(state: &Arc<ServiceState>, request: Request) -> Result
})
.await;
let cancelled = job.runner.cancel.load(Ordering::SeqCst);
{
let mut result = job.result.lock().unwrap_or_else(|e| e.into_inner());
match collected {
Ok(Ok((document, notices))) => {
result.document = Some((kind, document));
result.notices = notices;
result.status = if cancelled { "cancelled" } else { "completed" };
}
error => {
result.status = if cancelled { "cancelled" } else { "failed" };
result.diagnostics = match error {
Ok(Err(error)) => error_diagnostics(&error),
Err(error) => vec![diagnostic(error.to_string())],
Ok(Ok(_)) => unreachable!(),
};
job.set(match collected {
Ok(Ok((document, notices))) => {
let collected = Collected { kind, document, notices };
if cancelled {
JobState::Cancelled(Some(collected))
} else {
JobState::Completed(collected)
}
}
}
_ if cancelled => JobState::Cancelled(None),
Ok(Err(error)) => JobState::Failed {
diagnostics: error_diagnostics(&error),
},
Err(error) => JobState::Failed {
diagnostics: vec![diagnostic(error.to_string())],
},
});
job.finished.notify_waiters();
});
Ok(json_response(StatusCode::ACCEPTED, created))
Expand Down
77 changes: 55 additions & 22 deletions packages/cli/src/service/prepare.rs
Original file line number Diff line number Diff line change
Expand Up @@ -15,18 +15,56 @@ use super::{
state::ServiceState,
};

/// Where an environment preparation is.
pub(super) enum PrepareStatus {
Running,
Succeeded(Value),
Failed(String),
Cancelled(String),
}

/// A preparation's status and its progress events (200 at most).
pub(super) struct Progress {
pub(super) status: PrepareStatus,
pub(super) events: Vec<Value>,
}

/// An environment preparation the Inspector started: its progress events and
/// outcome, and the cancellation flag its runner watches.
pub(super) struct PrepareRun {
pub(super) id: String,
pub(super) cancel: Arc<AtomicBool>,
pub(super) state: Mutex<Value>,
pub(super) revision: Option<String>,
pub(super) progress: Mutex<Progress>,
}

impl PrepareRun {
pub(super) fn running(&self) -> bool {
matches!(
self.progress.lock().unwrap_or_else(|e| e.into_inner()).status,
PrepareStatus::Running
)
}

pub(super) fn value(&self) -> Value {
let mut value = self.state.lock().unwrap_or_else(|e| e.into_inner()).clone();
value["id"] = json!(self.id);
let progress = self.progress.lock().unwrap_or_else(|e| e.into_inner());
let mut value = json!({"id": self.id, "revision": self.revision, "events": progress.events});
match &progress.status {
PrepareStatus::Running => value["status"] = json!("running"),
PrepareStatus::Succeeded(report) => {
value["status"] = json!("succeeded");
value["report"] = report.clone();
}
PrepareStatus::Failed(error) => {
value["status"] = json!("failed");
value["error"] = json!(error);
}
PrepareStatus::Cancelled(error) => {
value["status"] = json!("cancelled");
value["error"] = json!(error);
}
}
drop(progress);
// The latest step's log, as it is now: its last 64 KiB.
if let Some(log) = value["events"]
.as_array()
Expand Down Expand Up @@ -84,8 +122,7 @@ pub(super) async fn start(state: &Arc<ServiceState>, request: Request) -> Result
};
let run = {
let mut prepares = state.prepares.lock().unwrap_or_else(|e| e.into_inner());
let running = |run: &Arc<PrepareRun>| run.state.lock().unwrap_or_else(|e| e.into_inner())["status"] == "running";
if prepares.iter().any(running) {
if prepares.iter().any(|run| run.running()) {
return Err(HttpError::new(
StatusCode::CONFLICT,
"An environment is already being prepared; wait for it or cancel it",
Expand All @@ -97,7 +134,11 @@ pub(super) async fn start(state: &Arc<ServiceState>, request: Request) -> Result
let run = Arc::new(PrepareRun {
id: Uuid::new_v4().to_string(),
cancel: Arc::new(AtomicBool::new(false)),
state: Mutex::new(json!({"status": "running", "revision": revision, "events": []})),
revision: revision.clone(),
progress: Mutex::new(Progress {
status: PrepareStatus::Running,
events: Vec::new(),
}),
});
prepares.push_back(run.clone());
run
Expand All @@ -106,28 +147,20 @@ pub(super) async fn start(state: &Arc<ServiceState>, request: Request) -> Result
runner.cancel = run.cancel.clone();
let listening = run.clone();
let runner = runner.with_listener(Arc::new(move |event: &Value| {
let mut state = listening.state.lock().unwrap_or_else(|e| e.into_inner());
if let Some(events) = state["events"].as_array_mut()
&& events.len() < 200
{
events.push(event.clone());
let mut progress = listening.progress.lock().unwrap_or_else(|e| e.into_inner());
if progress.events.len() < 200 {
progress.events.push(event.clone());
}
}));
let finished = run.clone();
tokio::task::spawn_blocking(move || {
let outcome = runner.prepare_environment(revision.as_deref(), &crate::environment::Options { force, steps });
let cancelled = finished.cancel.load(Ordering::SeqCst);
let mut state = finished.state.lock().unwrap_or_else(|e| e.into_inner());
match outcome {
Ok(report) => {
state["status"] = json!("succeeded");
state["report"] = report;
}
Err(error) => {
state["status"] = json!(if cancelled { "cancelled" } else { "failed" });
state["error"] = json!(format!("{error:#}"));
}
}
finished.progress.lock().unwrap_or_else(|e| e.into_inner()).status = match outcome {
Ok(report) => PrepareStatus::Succeeded(report),
Err(error) if cancelled => PrepareStatus::Cancelled(format!("{error:#}")),
Err(error) => PrepareStatus::Failed(format!("{error:#}")),
};
});
Ok(json_response(StatusCode::ACCEPTED, run.value()))
}
47 changes: 35 additions & 12 deletions packages/cli/src/service/sweeps.rs
Original file line number Diff line number Diff line change
Expand Up @@ -24,11 +24,37 @@ use super::{
};
use crate::runtime::DefinitionSource;

/// Where a history sweep is.
pub(super) enum SweepStatus {
Running,
Completed,
Failed(String),
/// Stopped, keeping what it found; the error, if it also failed.
Cancelled(Option<String>),
}

impl SweepStatus {
fn name(&self) -> &'static str {
match self {
Self::Running => "running",
Self::Completed => "completed",
Self::Failed(_) => "failed",
Self::Cancelled(_) => "cancelled",
}
}

fn error(&self) -> Option<&str> {
match self {
Self::Failed(error) | Self::Cancelled(Some(error)) => Some(error),
Self::Running | Self::Completed | Self::Cancelled(None) => None,
}
}
}

/// A history sweep the Inspector started.
pub(super) struct SweepRun {
pub(super) id: String,
pub(super) status: &'static str,
pub(super) error: Option<String>,
pub(super) status: SweepStatus,
pub(super) changes: Vec<Value>,
/// The same changes, for bookmarking them.
pub(super) swept: Vec<crate::sweep::Change>,
Expand All @@ -41,7 +67,7 @@ pub(super) struct SweepRun {

impl SweepRun {
pub(super) fn value(&self) -> Value {
json!({"id": self.id, "status": self.status, "error": self.error, "changes": self.changes,
json!({"id": self.id, "status": self.status.name(), "error": self.status.error(), "changes": self.changes,
"projections": self.rows, "cells": self.cells})
}
}
Expand Down Expand Up @@ -112,8 +138,7 @@ pub(super) fn start_sweep(state: &Arc<ServiceState>, body: &Value) -> Result<Val
}
*sweep = Some(SweepRun {
id: id.clone(),
status: "running",
error: None,
status: SweepStatus::Running,
changes: Vec::new(),
swept: Vec::new(),
rows: Vec::new(),
Expand Down Expand Up @@ -200,14 +225,12 @@ pub(super) fn start_sweep(state: &Arc<ServiceState>, body: &Value) -> Result<Val
})();
let cancelled = cancel.load(Ordering::SeqCst);
update(&|sweep| {
sweep.status = match (&result, cancelled) {
(_, true) => "cancelled",
(Ok(()), false) => "completed",
(Err(_), false) => "failed",
let error = result.as_ref().err().map(|error| format!("{error:#}"));
sweep.status = match (error, cancelled) {
(error, true) => SweepStatus::Cancelled(error),
(None, false) => SweepStatus::Completed,
(Some(error), false) => SweepStatus::Failed(error),
};
if let Err(error) = &result {
sweep.error = Some(format!("{error:#}"));
}
});
});
Ok(json!({"id": id, "status": "running"}))
Expand Down
Loading