use std::collections::VecDeque;
use std::fmt;
use std::sync::atomic::{AtomicBool, AtomicU8, AtomicU64, Ordering};
use std::sync::{Arc, Mutex};
#[derive(Clone, Debug, PartialEq, Eq, thiserror::Error)]
#[non_exhaustive]
pub enum JobError {
#[error("the job was cancelled")]
Cancelled,
#[error("the job panicked: {0}")]
Panicked(String),
#[error("{0}")]
Failed(String),
}
impl JobError {
pub fn failed(message: impl Into<String>) -> Self {
Self::Failed(message.into())
}
}
#[derive(Clone, Debug, Default)]
pub struct CancellationToken {
cancelled: Arc<AtomicBool>,
}
impl CancellationToken {
pub fn new() -> Self {
Self::default()
}
pub fn cancel(&self) {
self.cancelled.store(true, Ordering::SeqCst);
}
pub fn is_cancelled(&self) -> bool {
self.cancelled.load(Ordering::SeqCst)
}
pub fn check(&self) -> Result<(), JobError> {
if self.is_cancelled() {
Err(JobError::Cancelled)
} else {
Ok(())
}
}
}
#[derive(Clone, Debug, Default)]
pub struct Progress {
state: Arc<ProgressState>,
}
#[derive(Debug, Default)]
struct ProgressState {
current: AtomicU64,
total: AtomicU64,
label: Mutex<String>,
}
impl Progress {
pub fn new() -> Self {
Self::default()
}
pub fn set_total(&self, total: u64) {
self.state.total.store(total, Ordering::Relaxed);
}
pub fn total(&self) -> Option<u64> {
match self.state.total.load(Ordering::Relaxed) {
0 => None,
total => Some(total),
}
}
pub fn set_current(&self, current: u64) {
self.state.current.store(current, Ordering::Relaxed);
}
pub fn step(&self) {
self.state.current.fetch_add(1, Ordering::Relaxed);
}
pub fn current(&self) -> u64 {
self.state.current.load(Ordering::Relaxed)
}
pub fn fraction(&self) -> Option<f32> {
let total = self.total()?;
Some((self.current() as f32 / total as f32).clamp(0.0, 1.0))
}
pub fn set_label(&self, label: impl Into<String>) {
if let Ok(mut current) = self.state.label.lock() {
*current = label.into();
}
}
pub fn label(&self) -> String {
self.state.label.lock().map(|label| label.clone()).unwrap_or_default()
}
}
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
#[non_exhaustive]
pub enum JobStatus {
Queued,
Running,
Finished,
Cancelled,
Failed,
}
impl JobStatus {
fn code(self) -> u8 {
match self {
Self::Queued => 0,
Self::Running => 1,
Self::Finished => 2,
Self::Cancelled => 3,
Self::Failed => 4,
}
}
fn from_code(code: u8) -> Self {
match code {
1 => Self::Running,
2 => Self::Finished,
3 => Self::Cancelled,
4 => Self::Failed,
_ => Self::Queued,
}
}
}
#[derive(Clone, Copy, Debug, PartialEq, Eq, PartialOrd, Ord, Hash)]
pub struct JobId(u64);
impl JobId {
pub const fn index(self) -> u64 {
self.0
}
}
impl fmt::Display for JobId {
fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
write!(formatter, "{}", self.0)
}
}
#[derive(Clone, Debug)]
pub struct JobContext {
token: CancellationToken,
progress: Progress,
}
impl JobContext {
pub fn token(&self) -> &CancellationToken {
&self.token
}
pub fn progress(&self) -> &Progress {
&self.progress
}
pub fn check(&self) -> Result<(), JobError> {
self.token.check()
}
}
pub trait Job: Send + Sync + 'static {
type Output: Send + 'static;
fn run(&self, context: &JobContext) -> Result<Self::Output, JobError>;
}
#[derive(Clone, Debug)]
pub struct JobHandle {
id: JobId,
token: CancellationToken,
progress: Progress,
status: Arc<AtomicU8>,
}
impl JobHandle {
pub fn id(&self) -> JobId {
self.id
}
pub fn cancel(&self) {
self.token.cancel();
}
pub fn is_cancelled(&self) -> bool {
self.token.is_cancelled()
}
pub fn progress(&self) -> &Progress {
&self.progress
}
pub fn status(&self) -> JobStatus {
JobStatus::from_code(self.status.load(Ordering::SeqCst))
}
}
type ResultRow<O> = (JobId, Result<O, JobError>);
type PendingJob<O> = (JobId, Arc<dyn Job<Output = O>>, JobContext, Arc<AtomicU8>);
pub struct JobQueue<O: Send + 'static> {
next_id: u64,
pending: Vec<PendingJob<O>>,
results: Arc<Mutex<VecDeque<ResultRow<O>>>>,
tokens: Vec<CancellationToken>,
#[cfg(feature = "threads")]
workers: Vec<std::thread::JoinHandle<()>>,
}
impl<O: Send + 'static> Default for JobQueue<O> {
fn default() -> Self {
Self::new()
}
}
impl<O: Send + 'static> fmt::Debug for JobQueue<O> {
fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
formatter
.debug_struct("JobQueue")
.field("pending", &self.pending.len())
.finish_non_exhaustive()
}
}
impl<O: Send + 'static> JobQueue<O> {
pub fn new() -> Self {
Self {
next_id: 1,
pending: Vec::new(),
results: Arc::new(Mutex::new(VecDeque::new())),
tokens: Vec::new(),
#[cfg(feature = "threads")]
workers: Vec::new(),
}
}
pub fn spawn<J: Job<Output = O>>(&mut self, job: J) -> JobHandle {
let id = JobId(self.next_id);
self.next_id += 1;
let token = CancellationToken::new();
let progress = Progress::new();
let status = Arc::new(AtomicU8::new(JobStatus::Queued.code()));
let context = JobContext {
token: token.clone(),
progress: progress.clone(),
};
let job: Arc<dyn Job<Output = O>> = Arc::new(job);
self.tokens.push(token.clone());
#[cfg(feature = "threads")]
{
let results = Arc::clone(&self.results);
let worker_status = Arc::clone(&status);
let worker_context = context.clone();
self.workers.push(std::thread::spawn(move || {
worker_status.store(JobStatus::Running.code(), Ordering::SeqCst);
let outcome = std::panic::catch_unwind(std::panic::AssertUnwindSafe(|| job.run(&worker_context)))
.unwrap_or_else(|payload| Err(JobError::Panicked(panic_message(&payload))));
let final_status = match &outcome {
Ok(_) => JobStatus::Finished,
Err(JobError::Cancelled) => JobStatus::Cancelled,
Err(_) => JobStatus::Failed,
};
worker_status.store(final_status.code(), Ordering::SeqCst);
if let Ok(mut results) = results.lock() {
results.push_back((id, outcome));
}
}));
}
#[cfg(not(feature = "threads"))]
{
self.pending.push((id, job, context, Arc::clone(&status)));
}
JobHandle {
id,
token,
progress,
status,
}
}
pub fn run_next(&mut self) -> Option<JobId> {
let (id, job, context, status) = self.pending.pop()?;
status.store(JobStatus::Running.code(), Ordering::SeqCst);
let outcome = std::panic::catch_unwind(std::panic::AssertUnwindSafe(|| job.run(&context)))
.unwrap_or_else(|payload| Err(JobError::Panicked(panic_message(&payload))));
let final_status = match &outcome {
Ok(_) => JobStatus::Finished,
Err(JobError::Cancelled) => JobStatus::Cancelled,
Err(_) => JobStatus::Failed,
};
status.store(final_status.code(), Ordering::SeqCst);
if let Ok(mut results) = self.results.lock() {
results.push_back((id, outcome));
}
Some(id)
}
pub fn drain(&self) -> Vec<ResultRow<O>> {
self.results
.lock()
.map(|mut results| results.drain(..).collect())
.unwrap_or_default()
}
#[cfg(feature = "threads")]
pub fn wait(&mut self) -> Vec<ResultRow<O>> {
let workers = std::mem::take(&mut self.workers);
for worker in workers {
let _ = worker.join();
}
self.drain()
}
pub fn cancel_all(&mut self) {
for token in &self.tokens {
token.cancel();
}
}
}
impl<O: Send + 'static> Drop for JobQueue<O> {
fn drop(&mut self) {
for token in &self.tokens {
token.cancel();
}
#[cfg(feature = "threads")]
{
let workers = std::mem::take(&mut self.workers);
for worker in workers {
let _ = worker.join();
}
}
self.pending.clear();
}
}
fn panic_message(payload: &Box<dyn std::any::Any + Send>) -> String {
if let Some(message) = payload.downcast_ref::<&str>() {
(*message).to_owned()
} else if let Some(message) = payload.downcast_ref::<String>() {
message.clone()
} else {
"unknown panic payload".to_owned()
}
}
pub mod events;
pub use events::{CallbackWaker, EventQueue, NoopWaker, Waker};
#[cfg(test)]
mod tests;