Job state handling cleanup

This commit is contained in:
2023-08-09 19:39:06 -04:00
parent f5f6869029
commit 94924047b7
10 changed files with 102 additions and 76 deletions

View File

@@ -27,14 +27,72 @@ pub enum Job {
Update,
}
pub static JOB_ID: AtomicUsize = AtomicUsize::new(0);
#[derive(Default)]
pub struct JobQueue {
pub jobs: Vec<JobState>,
}
impl JobQueue {
/// Adds a job to the queue.
pub fn push(&mut self, state: JobState) { self.jobs.push(state); }
/// Returns whether a job of the given kind is running.
pub fn is_running(&self, kind: Job) -> bool {
self.jobs.iter().any(|j| j.kind == kind && j.handle.is_some())
}
/// Returns whether any job is running.
pub fn any_running(&self) -> bool {
self.jobs.iter().any(|job| {
if let Some(handle) = &job.handle {
return !handle.is_finished();
}
false
})
}
/// Iterates over all jobs mutably.
pub fn iter_mut(&mut self) -> impl Iterator<Item = &mut JobState> + '_ { self.jobs.iter_mut() }
/// Iterates over all finished jobs, returning the job state and the result.
pub fn iter_finished(
&mut self,
) -> impl Iterator<Item = (&mut JobState, std::thread::Result<JobResult>)> + '_ {
self.jobs.iter_mut().filter_map(|job| {
if let Some(handle) = &job.handle {
if !handle.is_finished() {
return None;
}
let result = job.handle.take().unwrap().join();
return Some((job, result));
}
None
})
}
/// Clears all finished jobs.
pub fn clear_finished(&mut self) {
self.jobs.retain(|job| {
!(job.should_remove
&& job.handle.is_none()
&& job.status.read().unwrap().error.is_none())
});
}
/// Removes a job from the queue given its ID.
pub fn remove(&mut self, id: usize) { self.jobs.retain(|job| job.id != id); }
}
pub struct JobState {
pub id: usize,
pub job_type: Job,
pub kind: Job,
pub handle: Option<JoinHandle<JobResult>>,
pub status: Arc<RwLock<JobStatus>>,
pub cancel: Sender<()>,
pub should_remove: bool,
}
#[derive(Default)]
pub struct JobStatus {
pub title: String,
@@ -43,6 +101,7 @@ pub struct JobStatus {
pub status: String,
pub error: Option<anyhow::Error>,
}
pub enum JobResult {
None,
ObjDiff(Box<ObjDiffResult>),
@@ -60,9 +119,9 @@ fn should_cancel(rx: &Receiver<()>) -> bool {
type Status = Arc<RwLock<JobStatus>>;
fn queue_job(
fn start_job(
title: &str,
job_type: Job,
kind: Job,
run: impl FnOnce(&Status, Receiver<()>) -> Result<JobResult> + Send + 'static,
) -> JobState {
let status = Arc::new(RwLock::new(JobStatus {
@@ -89,7 +148,7 @@ fn queue_job(
log::info!("Started job {}", id);
JobState {
id,
job_type,
kind,
handle: Some(handle),
status: status_clone,
cancel: tx,