lunar-lib 0.4.4

Common utilities for lunar applications
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
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
use std::{
    panic::AssertUnwindSafe,
    sync::{
        Arc,
        atomic::{AtomicUsize, Ordering},
        mpsc::{Sender, channel},
    },
};

use crate::error;

mod cli_progress_bar;
pub use cli_progress_bar::*;

/// A thread safe, thread stable progress bar, abstracted for any frontend
#[derive(Clone)]
pub struct ProgressBar {
    handle: Arc<ProgressHandle>,
}

struct ProgressHandle {
    value: AtomicUsize,
    max: AtomicUsize,
    renderer: Arc<dyn ProgressRenderer>,
    sender: Sender<ProgressEvent>,
}

impl Drop for ProgressHandle {
    fn drop(&mut self) {
        let _ = self.sender.send(ProgressEvent::Exit);
        self.renderer.on_finish();
    }
}

impl ProgressBar {
    /// Runs a custom closure for this progress bar.
    ///
    /// # Panics
    ///
    /// Panics if the internal `GLOBAL_SENDER` thread cannot be communicated with. This usually signals critical failure somewhere
    ///
    /// # Notes
    ///
    /// If the input closure panics, it will not kill the thread, it will instead log the error and return
    pub fn custom<F>(&self, f: F)
    where
        F: FnOnce() + Send + 'static,
    {
        self.handle
            .sender
            .send(ProgressEvent::Custom {
                f: Box::new(f),
                _handle: self.handle.clone(),
            })
            .expect("Progress handler thread died.");
    }

    /// Waits until the flush is processed, allowing you to wait until all previous events have been processed
    ///
    /// # Panics
    ///
    /// Panics if the internal `GLOBAL_SENDER` thread cannot be communicated with. This usually signals critical failure somewhere
    pub fn flush(&self) {
        let (tx, rx) = channel();
        self.handle
            .sender
            .send(ProgressEvent::Flush {
                done: tx,
                _handle: self.handle.clone(),
            })
            .expect("Progress handler thread died.");
        let _ = rx.recv();
    }

    /// Gets the max value of the internal `ProgressHandle`
    ///
    /// # Notes
    ///
    /// While this will return the correct max value at time of call, In multi-threaded contexts, this max may have already changed by the time it has been used
    pub fn get_max(&self) -> usize {
        self.handle.max.load(Ordering::SeqCst)
    }

    /// Gets the value of the internal `ProgressHandle`
    ///
    /// # Notes
    ///
    /// While this will return the correct value at time of call, In multi-threaded contexts, this value may have already changed by the time it has been used
    pub fn get_value(&self) -> usize {
        self.handle.value.load(Ordering::SeqCst)
    }

    /// Increments the value of a progress bar by 1
    ///
    /// # Panics
    ///
    /// Panics if the internal `GLOBAL_SENDER` thread cannot be communicated with. This usually signals critical failure somewhere
    pub fn increment(&self) {
        self.handle
            .sender
            .send(ProgressEvent::Increment {
                handle: self.handle.clone(),
            })
            .expect("Progress handler thread died.");
    }

    /// Increments the value of the progress bar by 1 and runs a pre-write and post-write closure
    ///
    /// The `pre` closure, if some, will run before the value is incremented
    /// The `post` closure, if some, will run after the value is incremented, and before [`ProgressRenderer::on_update()`] method is run
    ///
    /// # Panics
    ///
    /// Panics if the internal `GLOBAL_SENDER` thread cannot be communicated with. This usually signals critical failure somewhere
    pub fn increment_and_run<P, Q>(&self, pre: Option<P>, post: Option<Q>)
    where
        P: FnOnce() + Send + 'static,
        Q: FnOnce() + Send + 'static,
    {
        self.handle
            .sender
            .send(ProgressEvent::IncrementAndRun {
                handle: self.handle.clone(),
                pre: pre.map(box_dyn),
                post: post.map(box_dyn),
            })
            .expect("Progress handler thread died.");
    }

    /// Creates a new progress bar instance using the renderer
    ///
    /// This progress bar can safely be shared and updated between threads
    pub fn new(value: usize, max: usize, renderer: Arc<dyn ProgressRenderer>) -> Self {
        let (tx, rx) = channel();

        let handle = Arc::new(ProgressHandle {
            value: AtomicUsize::new(value),
            max: AtomicUsize::new(max),
            renderer: renderer.clone(),
            sender: tx,
        });

        spawn_progress_thread(rx);

        renderer.on_start(value, max);

        Self { handle }
    }

    /// Sets the max-value of the progress bar
    ///
    /// # Panics
    ///
    /// Panics if the internal `GLOBAL_SENDER` thread cannot be communicated with. This usually signals critical failure somewhere
    pub fn set_max(&self, max: usize) {
        self.handle
            .sender
            .send(ProgressEvent::SetMax {
                handle: self.handle.clone(),
                max,
            })
            .expect("Progress handler thread died.");
    }

    /// Sets the max-value of the progress bar and runs a pre-write and post-write closure
    ///
    /// The `pre` closure, if some, will run before the value is incremented
    /// The `post` closure, if some, will run after the value is incremented, and before [`ProgressRenderer::on_update()`] method is run
    ///
    /// # Panics
    ///
    /// Panics if the internal `GLOBAL_SENDER` thread cannot be communicated with. This usually signals critical failure somewhere
    ///
    /// # Notes
    ///
    /// If the any of the input closures panic, it will not kill the thread, it will instead log the error and ignore it
    pub fn set_max_and_run<P, Q>(&self, max: usize, pre: Option<P>, post: Option<Q>)
    where
        P: FnOnce() + Send + 'static,
        Q: FnOnce() + Send + 'static,
    {
        self.handle
            .sender
            .send(ProgressEvent::SetMaxAndRun {
                handle: self.handle.clone(),
                max,
                pre: pre.map(box_dyn),
                post: post.map(box_dyn),
            })
            .expect("Progress handler thread died.");
    }

    /// Sets the value of the progress bar
    ///
    /// # Panics
    ///
    /// Panics if the internal `GLOBAL_SENDER` thread cannot be communicated with. This usually signals critical failure somewhere
    pub fn set_value(&self, value: usize) {
        self.handle
            .sender
            .send(ProgressEvent::SetValue {
                handle: self.handle.clone(),
                value,
            })
            .expect("Progress handler thread died.");
    }

    /// Sets the value of the progress bar and runs a pre-write and post-write closure
    ///
    /// The `pre` closure, if some, will run before the value is incremented
    /// The `post` closure, if some, will run after the value is incremented, and before [`ProgressRenderer::on_update()`] method is run
    ///
    /// # Panics
    ///
    /// Panics if the internal `GLOBAL_SENDER` thread cannot be communicated with. This usually signals critical failure somewhere
    ///
    /// # Notes
    ///
    /// If the any of the input closures panic, it will not kill the thread, it will instead log the error and ignore it
    pub fn set_value_and_run<P, Q>(&self, value: usize, pre: Option<P>, post: Option<Q>)
    where
        P: FnOnce() + Send + 'static,
        Q: FnOnce() + Send + 'static,
    {
        self.handle
            .sender
            .send(ProgressEvent::SetValueAndRun {
                handle: self.handle.clone(),
                value,
                pre: pre.map(box_dyn),
                post: post.map(box_dyn),
            })
            .expect("Progress handler thread died.");
    }

    /// Forces the [`ProgressRenderer`] to upate with the new values
    ///
    /// # Panics
    ///
    /// Panics if the progress bars handling thread cannot be communicated with.
    pub fn update(&self) {
        self.handle
            .sender
            .send(ProgressEvent::Update {
                handle: self.handle.clone(),
            })
            .expect("Progress handler thread died.")
    }

    /// Checks if the the handling thread is alive by sending a check to it and seeing if it returns [`Ok`]
    ///
    /// # Notes
    ///
    /// This function will correctly check if the handling thread is alive at the time of calling, but can not guarantee the thread will stay alive after calling or that it receives the check
    pub fn is_alive(&self) -> bool {
        self.handle.sender.send(ProgressEvent::Check).is_ok()
    }

    /// Calls the [`set_label()`] function for the held [`ProgressRenderer`]
    pub fn set_label(&self, label: &str) {
        self.handle.renderer.set_label(label);
    }

    /// Calls the [`on_notify()`] function for the held [`ProgressRenderer`] and then instantly updates self
    pub fn notify(&self, message: impl AsRef<str>) {
        self.handle.renderer.on_notify(message.as_ref());
        self.update();
    }
}

/// Defines how a progress bar should be rendered
pub trait ProgressRenderer: Send + Sync {
    /// Called when the [`ProgressBar`] which holds the instance of [`Self`] is spawned
    fn on_start(&self, value: usize, max: usize);

    /// Called when the [`ProgressBar`] which holds the instance of [`Self`] is updated
    fn on_update(&self, value: usize, max: usize);

    /// Called when the [`ProgressBar`] which holds the instance of [`Self`] is dropped
    ///
    /// # Notes
    ///
    /// [`Self::on_update()`] is NOT automatically called before finish, if you would like to update before the renderer is dropped, you can do so when defining this function
    fn on_finish(&self);

    /// Generic notification. Can be sent from anything with access to the [`ProgressBar`] that holds the instance of [`Self`]
    ///
    /// This function is not called internally by anything, its meant for other libraries to call when they want to notify your renderer of some message. If you do not care, you can ignore this function
    fn on_notify(&self, msg: &str);

    /// Sets the label of [`Self`]. Can be sent from anything with access to the [`ProgressBar`] that holds the instance of [`Self`]
    ///
    /// This function is not called internally by anything, its meant for other libraries to call when they want to label your progress bar. If you do not care, you can ignore this function
    fn set_label(&self, msg: &str);
}

// ==============================================================
// Thread stuff
// ==============================================================

enum ProgressEvent {
    Check,
    Exit,
    Update {
        handle: Arc<ProgressHandle>,
    },
    Increment {
        handle: Arc<ProgressHandle>,
    },
    IncrementAndRun {
        handle: Arc<ProgressHandle>,
        pre: Option<Box<dyn FnOnce() + Send>>,
        post: Option<Box<dyn FnOnce() + Send>>,
    },
    SetValue {
        handle: Arc<ProgressHandle>,
        value: usize,
    },
    SetValueAndRun {
        handle: Arc<ProgressHandle>,
        value: usize,
        pre: Option<Box<dyn FnOnce() + Send>>,
        post: Option<Box<dyn FnOnce() + Send>>,
    },
    SetMax {
        handle: Arc<ProgressHandle>,
        max: usize,
    },
    SetMaxAndRun {
        handle: Arc<ProgressHandle>,
        max: usize,
        pre: Option<Box<dyn FnOnce() + Send>>,
        post: Option<Box<dyn FnOnce() + Send>>,
    },
    Custom {
        _handle: Arc<ProgressHandle>,
        f: Box<dyn FnOnce() + Send>,
    },
    Flush {
        _handle: Arc<ProgressHandle>,
        done: std::sync::mpsc::Sender<()>,
    },
}

fn spawn_progress_thread(rx: std::sync::mpsc::Receiver<ProgressEvent>) {
    std::thread::spawn(move || {
        while let Ok(event) = rx.recv() {
            match event {
                ProgressEvent::Check => {}
                ProgressEvent::Exit => {
                    break;
                }
                ProgressEvent::Increment { handle } => {
                    let value = handle.value.fetch_add(1, Ordering::SeqCst);
                    let max = handle.max.load(Ordering::SeqCst);
                    handle.renderer.on_update(value + 1, max);
                }
                ProgressEvent::IncrementAndRun { handle, pre, post } => {
                    run_optional_log_panic(pre);
                    let value = handle.value.fetch_add(1, Ordering::SeqCst);
                    run_optional_log_panic(post);
                    let max = handle.max.load(Ordering::SeqCst);
                    handle.renderer.on_update(value + 1, max);
                }
                ProgressEvent::SetValue { handle, value } => {
                    handle.value.store(value, Ordering::SeqCst);
                    let max = handle.max.load(Ordering::SeqCst);
                    handle.renderer.on_update(value, max);
                }
                ProgressEvent::SetValueAndRun {
                    handle,
                    value,
                    pre,
                    post,
                } => {
                    handle.value.store(value, Ordering::SeqCst);
                    run_optional_log_panic(pre);
                    let max = handle.max.load(Ordering::SeqCst);
                    run_optional_log_panic(post);
                    handle.renderer.on_update(value, max);
                }
                ProgressEvent::SetMax { max, handle } => {
                    let value = handle.value.load(Ordering::SeqCst);
                    handle.max.store(max, Ordering::SeqCst);
                    handle.renderer.on_update(value, max);
                }
                ProgressEvent::SetMaxAndRun {
                    handle,
                    max,
                    pre,
                    post,
                } => {
                    let value = handle.value.load(Ordering::SeqCst);
                    run_optional_log_panic(pre);
                    handle.max.store(max, Ordering::SeqCst);
                    run_optional_log_panic(post);
                    handle.renderer.on_update(value, max);
                }
                ProgressEvent::Custom { f, _handle } => run_or_log_panic(f),
                ProgressEvent::Flush { done, _handle } => done.send(()).unwrap(),
                ProgressEvent::Update { handle } => {
                    let value = handle.value.load(Ordering::SeqCst);
                    let max = handle.max.load(Ordering::SeqCst);
                    handle.renderer.on_update(value, max);
                }
            }
        }
    });
}

fn box_dyn<F: FnOnce() + Send + 'static>(f: F) -> Box<dyn FnOnce() + Send + 'static> {
    Box::new(f)
}

#[inline(always)]
fn run_or_log_panic<F: FnOnce() + Send + 'static>(f: F) {
    if let Err(err) = std::panic::catch_unwind(AssertUnwindSafe(f)) {
        error!("ProgressBar closure panicked: {err:?}")
    }
}

#[inline(always)]
fn run_optional_log_panic<F: FnOnce() + Send + 'static>(f: Option<F>) {
    if let Some(f) = f {
        run_or_log_panic(f);
    }
}

#[cfg(test)]
mod tests {
    use std::sync::{
        Arc, Mutex,
        atomic::{AtomicBool, Ordering},
    };

    use crate::progress::{ProgressBar, ProgressRenderer};

    struct TestRenderer {
        log: Arc<Mutex<Vec<String>>>,
    }

    impl TestRenderer {
        fn new() -> Self {
            Self {
                log: Arc::new(Mutex::new(Vec::new())),
            }
        }

        fn log(&self) -> Vec<String> {
            self.log.lock().unwrap().clone()
        }

        fn push_log(&self, log: String) {
            self.log.lock().unwrap().push(log);
        }
    }

    impl ProgressRenderer for TestRenderer {
        fn on_start(&self, value: usize, max: usize) {
            self.push_log(format!("Start: [{value} / {max}]"));
        }

        fn on_update(&self, value: usize, max: usize) {
            self.push_log(format!("Update: [{value} / {max}]"));
        }

        fn on_finish(&self) {
            self.push_log(format!("Finish"));
        }

        fn on_notify(&self, msg: &str) {
            self.push_log(msg.to_owned());
        }

        fn set_label(&self, _msg: &str) {}
    }

    #[test]
    fn progress_increment() {
        let renderer = Arc::new(TestRenderer::new());
        let bar = ProgressBar::new(0, 3, renderer.clone());

        bar.increment();
        bar.increment();
        bar.flush();

        let log = renderer.log();
        assert_eq!(log.len(), 3);
        assert_eq!(log[0], "Start: [0 / 3]");
        assert_eq!(log[1], "Update: [1 / 3]");
        assert_eq!(log[2], "Update: [2 / 3]");
    }

    #[test]
    fn progress_notify() {
        let renderer = Arc::new(TestRenderer::new());
        let bar = ProgressBar::new(0, 3, renderer.clone());

        bar.increment();
        bar.flush();
        bar.notify("notification");
        bar.flush();

        let log = renderer.log();

        log.iter().for_each(|s| println!("{s}"));

        assert_eq!(log.len(), 4);
        assert_eq!(log[0], "Start: [0 / 3]");
        assert_eq!(log[1], "Update: [1 / 3]");
        assert_eq!(log[2], "notification");
        assert_eq!(log[3], "Update: [1 / 3]");
    }

    #[test]
    fn progress_finishes_on_drop() {
        let renderer = Arc::new(TestRenderer::new());
        let bar = ProgressBar::new(0, 0, renderer.clone());

        drop(bar);

        let log = renderer.log();
        assert_eq!(log.len(), 2);
        assert_eq!(log[0], "Start: [0 / 0]");
        assert_eq!(log[1], "Finish")
    }

    #[test]
    fn progress_closures_run_on_increment() {
        let renderer = Arc::new(TestRenderer::new());
        let bar = ProgressBar::new(0, 1, renderer.clone());

        let pre_ran = Arc::new(AtomicBool::new(false));
        let post_ran = Arc::new(AtomicBool::new(false));

        let pre_flag = pre_ran.clone();
        let post_flag = post_ran.clone();

        bar.increment_and_run(
            Some(move || pre_flag.store(true, Ordering::SeqCst)),
            Some(move || post_flag.store(true, Ordering::SeqCst)),
        );
        bar.flush();

        assert!(pre_ran.load(Ordering::SeqCst));
        assert!(post_ran.load(Ordering::SeqCst));

        let log = renderer.log();
        assert_eq!(log.len(), 2);
        assert_eq!(log[0], "Start: [0 / 1]");
        assert_eq!(log[1], "Update: [1 / 1]");
    }

    #[test]
    fn progress_closures_run_on_set_value() {
        let renderer = Arc::new(TestRenderer::new());
        let bar = ProgressBar::new(0, 5, renderer.clone());

        let pre_ran = Arc::new(AtomicBool::new(false));
        let post_ran = Arc::new(AtomicBool::new(false));

        let pre_flag = pre_ran.clone();
        let post_flag = post_ran.clone();

        bar.set_value_and_run(
            5,
            Some(move || pre_flag.store(true, Ordering::SeqCst)),
            Some(move || post_flag.store(true, Ordering::SeqCst)),
        );
        bar.flush();

        assert!(pre_ran.load(Ordering::SeqCst));
        assert!(post_ran.load(Ordering::SeqCst));

        let log = renderer.log();
        assert_eq!(log.len(), 2);
        assert_eq!(log[0], "Start: [0 / 5]");
        assert_eq!(log[1], "Update: [5 / 5]");
    }

    #[test]
    fn progress_closures_run_on_set_max() {
        let renderer = Arc::new(TestRenderer::new());
        let bar = ProgressBar::new(0, 3, renderer.clone());

        let pre_ran = Arc::new(AtomicBool::new(false));
        let post_ran = Arc::new(AtomicBool::new(false));

        let pre_flag = pre_ran.clone();
        let post_flag = post_ran.clone();

        bar.set_max_and_run(
            5,
            Some(move || pre_flag.store(true, Ordering::SeqCst)),
            Some(move || post_flag.store(true, Ordering::SeqCst)),
        );
        bar.flush();

        assert!(pre_ran.load(Ordering::SeqCst));
        assert!(post_ran.load(Ordering::SeqCst));

        let log = renderer.log();
        assert_eq!(log.len(), 2);
        assert_eq!(log[0], "Start: [0 / 3]");
        assert_eq!(log[1], "Update: [0 / 5]");
    }

    #[test]
    fn progress_thread_safe_on_closure_panic() {
        let renderer = Arc::new(TestRenderer::new());
        let bar = ProgressBar::new(0, 100, renderer.clone());

        bar.increment_and_run(Some(|| panic!()), Some(|| ()));
        bar.flush();
    }

    #[test]
    fn progress_thread_stability() {
        let renderer = Arc::new(TestRenderer::new());
        let bar = ProgressBar::new(0, 100, renderer.clone());

        let handles: Vec<_> = (0..5)
            .map(|_| {
                let bar = bar.clone();
                std::thread::spawn(move || {
                    for _ in 0..20 {
                        bar.increment();
                    }
                })
            })
            .collect();

        for h in handles {
            h.join().unwrap()
        }

        bar.flush();

        let log = renderer.log();
        assert_eq!(log.len(), 101);

        assert_eq!(log[0], "Start: [0 / 100]");
        for (i, entry) in log.iter().skip(1).enumerate() {
            assert_eq!(entry, &format!("Update: [{i} / 100]", i = i + 1))
        }
    }
}