crisol-core 1.1.0

Crisol core: an egui-free data model, themes, metrics, localization, commands, state, and storage.
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
//! Background jobs, cooperative cancellation, progress, and an event queue.
//!
//! With the `threads` feature (the default on native), [`JobQueue::spawn`] runs a job on
//! a worker thread. Without it, the queue is cooperative: [`JobQueue::run_next`] runs
//! one job inline, which is the wasm model. Dropping the queue cancels every job and
//! joins the workers; a panicking job is reported as [`JobError`], never lost.
//!
//! ```
//! use crisol_core::jobs::{CancellationToken, Job, JobContext, JobError, JobQueue};
//!
//! struct Double(u64);
//! impl Job for Double {
//!     type Output = u64;
//!     fn run(&self, _ctx: &JobContext) -> Result<u64, JobError> {
//!         Ok(self.0 * 2)
//!     }
//! }
//!
//! let mut queue = JobQueue::new();
//! queue.spawn(Double(21));
//! # #[cfg(all(feature = "threads", not(target_family = "wasm")))]
//! # {
//! let results = queue.wait();
//! assert_eq!(results[0].1, Ok(42));
//! # }
//! ```

use std::collections::VecDeque;
use std::fmt;
use std::sync::atomic::{AtomicBool, AtomicU8, AtomicU64, Ordering};
use std::sync::{Arc, Mutex};

/// Why a job failed.
#[derive(Clone, Debug, PartialEq, Eq, thiserror::Error)]
#[non_exhaustive]
/// # Example
///
/// ```
/// use crisol_core::jobs::JobError;
/// ```
pub enum JobError {
    /// The job was cancelled before or during its work.
    #[error("the job was cancelled")]
    Cancelled,
    /// The job panicked.
    #[error("the job panicked: {0}")]
    Panicked(String),
    /// The job returned an application error.
    #[error("{0}")]
    Failed(String),
}

impl JobError {
    /// An application failure.
    pub fn failed(message: impl Into<String>) -> Self {
        Self::Failed(message.into())
    }
}

/// A cooperative cancellation flag shared by a job and its owner.
#[derive(Clone, Debug, Default)]
/// # Example
///
/// ```
/// use crisol_core::jobs::CancellationToken;
/// ```
pub struct CancellationToken {
    cancelled: Arc<AtomicBool>,
}

impl CancellationToken {
    /// A token that is not cancelled.
    pub fn new() -> Self {
        Self::default()
    }

    /// Cancel the job.
    pub fn cancel(&self) {
        self.cancelled.store(true, Ordering::SeqCst);
    }

    /// Whether the job was cancelled.
    pub fn is_cancelled(&self) -> bool {
        self.cancelled.load(Ordering::SeqCst)
    }

    /// Return [`JobError::Cancelled`] when the token is cancelled.
    ///
    /// # Errors
    /// When the job was cancelled.
    pub fn check(&self) -> Result<(), JobError> {
        if self.is_cancelled() {
            Err(JobError::Cancelled)
        } else {
            Ok(())
        }
    }
}

/// A shared progress counter.
#[derive(Clone, Debug, Default)]
/// # Example
///
/// ```
/// use crisol_core::jobs::Progress;
/// ```
pub struct Progress {
    state: Arc<ProgressState>,
}

#[derive(Debug, Default)]
struct ProgressState {
    current: AtomicU64,
    total: AtomicU64,
    label: Mutex<String>,
}

impl Progress {
    /// Zero of an unknown total.
    pub fn new() -> Self {
        Self::default()
    }

    /// Set the total; zero means unknown.
    pub fn set_total(&self, total: u64) {
        self.state.total.store(total, Ordering::Relaxed);
    }

    /// The total, or `None` when unknown.
    pub fn total(&self) -> Option<u64> {
        match self.state.total.load(Ordering::Relaxed) {
            0 => None,
            total => Some(total),
        }
    }

    /// Set the completed count.
    pub fn set_current(&self, current: u64) {
        self.state.current.store(current, Ordering::Relaxed);
    }

    /// Advance by one.
    pub fn step(&self) {
        self.state.current.fetch_add(1, Ordering::Relaxed);
    }

    /// The completed count.
    pub fn current(&self) -> u64 {
        self.state.current.load(Ordering::Relaxed)
    }

    /// The fraction from 0.0 to 1.0, or `None` when the total is unknown.
    pub fn fraction(&self) -> Option<f32> {
        let total = self.total()?;
        Some((self.current() as f32 / total as f32).clamp(0.0, 1.0))
    }

    /// Set the human label.
    pub fn set_label(&self, label: impl Into<String>) {
        if let Ok(mut current) = self.state.label.lock() {
            *current = label.into();
        }
    }

    /// The human label.
    pub fn label(&self) -> String {
        self.state.label.lock().map(|label| label.clone()).unwrap_or_default()
    }
}

/// The lifecycle of one job.
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
#[non_exhaustive]
/// # Example
///
/// ```
/// use crisol_core::jobs::JobStatus;
/// ```
pub enum JobStatus {
    /// Waiting to run.
    Queued,
    /// Running now.
    Running,
    /// Finished successfully.
    Finished,
    /// Cancelled before or during the work.
    Cancelled,
    /// Failed or panicked.
    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,
        }
    }
}

/// A stable job id.
#[derive(Clone, Copy, Debug, PartialEq, Eq, PartialOrd, Ord, Hash)]
/// # Example
///
/// ```
/// use crisol_core::jobs::JobId;
/// ```
pub struct JobId(u64);

impl JobId {
    /// The numeric id.
    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)
    }
}

/// What a job receives: cancellation and progress.
#[derive(Clone, Debug)]
/// # Example
///
/// ```
/// use crisol_core::jobs::JobContext;
/// ```
pub struct JobContext {
    token: CancellationToken,
    progress: Progress,
}

impl JobContext {
    /// The cancellation token.
    pub fn token(&self) -> &CancellationToken {
        &self.token
    }

    /// The progress counter.
    pub fn progress(&self) -> &Progress {
        &self.progress
    }

    /// Return [`JobError::Cancelled`] when cancelled.
    ///
    /// # Errors
    /// When the job was cancelled.
    pub fn check(&self) -> Result<(), JobError> {
        self.token.check()
    }
}

/// One unit of background work.
/// # Example
///
/// ```
/// use crisol_core::jobs::Job;
/// ```
pub trait Job: Send + Sync + 'static {
    /// What the job produces.
    type Output: Send + 'static;

    /// Run the job.
    ///
    /// # Errors
    /// When the work fails; cancellation should return [`JobError::Cancelled`].
    fn run(&self, context: &JobContext) -> Result<Self::Output, JobError>;
}

/// A handle to a spawned job.
#[derive(Clone, Debug)]
/// # Example
///
/// ```
/// use crisol_core::jobs::JobHandle;
/// ```
pub struct JobHandle {
    id: JobId,
    token: CancellationToken,
    progress: Progress,
    status: Arc<AtomicU8>,
}

impl JobHandle {
    /// The job id.
    pub fn id(&self) -> JobId {
        self.id
    }

    /// Cancel the job.
    pub fn cancel(&self) {
        self.token.cancel();
    }

    /// Whether the job was cancelled.
    pub fn is_cancelled(&self) -> bool {
        self.token.is_cancelled()
    }

    /// The progress.
    pub fn progress(&self) -> &Progress {
        &self.progress
    }

    /// The current status.
    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>);

/// A queue of jobs and their results.
/// # Example
///
/// ```
/// use crisol_core::jobs::JobQueue;
/// ```
pub struct JobQueue<O: Send + 'static> {
    next_id: u64,
    pending: Vec<PendingJob<O>>,
    results: Arc<Mutex<VecDeque<ResultRow<O>>>>,
    tokens: Vec<CancellationToken>,
    #[cfg(all(feature = "threads", not(target_family = "wasm")))]
    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> {
    /// An empty queue.
    pub fn new() -> Self {
        Self {
            next_id: 1,
            pending: Vec::new(),
            results: Arc::new(Mutex::new(VecDeque::new())),
            tokens: Vec::new(),
            #[cfg(all(feature = "threads", not(target_family = "wasm")))]
            workers: Vec::new(),
        }
    }

    /// Spawn a job and return its handle.
    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(all(feature = "threads", not(target_family = "wasm")))]
        {
            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(all(feature = "threads", not(target_family = "wasm"))))]
        {
            self.pending.push((id, job, context, Arc::clone(&status)));
        }
        JobHandle {
            id,
            token,
            progress,
            status,
        }
    }

    /// Run one pending job inline. Returns its id, or `None` when nothing is pending.
    ///
    /// This is the wasm model; with threads the queue spawns immediately and this returns
    /// `None` unless a job was queued differently.
    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)
    }

    /// Take every finished result.
    pub fn drain(&self) -> Vec<ResultRow<O>> {
        self.results
            .lock()
            .map(|mut results| results.drain(..).collect())
            .unwrap_or_default()
    }

    /// Wait for every worker and return all results. Requires the `threads` feature.
    #[cfg(all(feature = "threads", not(target_family = "wasm")))]
    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()
    }

    /// Cancel every job and drain the results.
    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(all(feature = "threads", not(target_family = "wasm")))]
        {
            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;