refactor: reorganize source and tests
This commit is contained in:
1 parent
15d76c18a0
commit
c6205a337c
139 files changed
+5532
-5548
No files matched your search
@@ -0,0 +1,90 @@
|
||||
// thread-safe FIFO queue for error/warning toasts displayed in the UI.
|
||||
// also (ab)used for INFO toasts like "desktop shortcut created" because
|
||||
// why build a separate notification system when this one works fine.
|
||||
//
|
||||
// callers pass id: 0 and push_error assigns a real unique id. the id is
|
||||
// used by the render layer to track per-toast animation state.
|
||||
|
||||
use std::collections::VecDeque;
|
||||
use std::sync::atomic::{AtomicU64, Ordering};
|
||||
use std::sync::{Arc, Mutex};
|
||||
use std::time::Instant;
|
||||
|
||||
use std::sync::LazyLock;
|
||||
use tracing::Level;
|
||||
|
||||
const MAX_ERROR_EVENTS: usize = 50;
|
||||
static NEXT_ERROR_ID: AtomicU64 = AtomicU64::new(1);
|
||||
|
||||
#[derive(Debug, Clone)]
|
||||
pub struct ErrorEvent {
|
||||
pub id: u64,
|
||||
pub level: Level,
|
||||
pub message: String,
|
||||
pub pushed_at: Instant,
|
||||
}
|
||||
|
||||
pub static ERROR_EVENTS: LazyLock<Arc<Mutex<VecDeque<ErrorEvent>>>> =
|
||||
LazyLock::new(|| Arc::new(Mutex::new(VecDeque::new())));
|
||||
|
||||
pub fn push_error(event: ErrorEvent) {
|
||||
match ERROR_EVENTS.lock() {
|
||||
Ok(mut events) => {
|
||||
let mut event = event;
|
||||
event.id = NEXT_ERROR_ID.fetch_add(1, Ordering::Relaxed);
|
||||
|
||||
events.push_back(event);
|
||||
|
||||
while events.len() > MAX_ERROR_EVENTS {
|
||||
events.pop_front();
|
||||
}
|
||||
super::request_redraw();
|
||||
}
|
||||
Err(e) => {
|
||||
tracing::error!("Error buffer lock poisoned: {}", e);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[must_use]
|
||||
pub fn has_errors() -> bool {
|
||||
match ERROR_EVENTS.lock() {
|
||||
Ok(events) => !events.is_empty(),
|
||||
Err(_) => false,
|
||||
}
|
||||
}
|
||||
|
||||
#[must_use]
|
||||
pub fn pop_error() -> Option<ErrorEvent> {
|
||||
match ERROR_EVENTS.lock() {
|
||||
Ok(mut events) => {
|
||||
let event = events.pop_front();
|
||||
if event.is_some() {
|
||||
super::request_redraw();
|
||||
}
|
||||
event
|
||||
}
|
||||
Err(_) => None,
|
||||
}
|
||||
}
|
||||
|
||||
#[must_use]
|
||||
pub fn peek_error() -> Option<ErrorEvent> {
|
||||
match ERROR_EVENTS.lock() {
|
||||
Ok(events) => events.front().cloned(),
|
||||
Err(_) => None,
|
||||
}
|
||||
}
|
||||
|
||||
#[must_use]
|
||||
// returned in reverse order (newest first) so they stack top-down in the UI
|
||||
pub fn peek_all_errors() -> Vec<ErrorEvent> {
|
||||
match ERROR_EVENTS.lock() {
|
||||
Ok(events) => events.iter().rev().cloned().collect(),
|
||||
Err(_) => Vec::new(),
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
#[path = "tests/errors.rs"]
|
||||
mod tests;
|
||||
@@ -0,0 +1,16 @@
|
||||
// application feedback shared by background work and every frontend.
|
||||
|
||||
use std::sync::atomic::{AtomicBool, Ordering};
|
||||
|
||||
pub mod errors;
|
||||
pub mod progress;
|
||||
|
||||
static REDRAW_REQUESTED: AtomicBool = AtomicBool::new(true);
|
||||
|
||||
pub fn request_redraw() {
|
||||
REDRAW_REQUESTED.store(true, Ordering::Release);
|
||||
}
|
||||
|
||||
pub(crate) fn take_redraw_request() -> bool {
|
||||
REDRAW_REQUESTED.swap(false, Ordering::AcqRel)
|
||||
}
|
||||
@@ -0,0 +1,220 @@
|
||||
// global progress state shared between background tasks and the status bar widget.
|
||||
// background tasks set the action/progress, the render loop reads it every frame.
|
||||
|
||||
use std::collections::BTreeMap;
|
||||
use std::sync::LazyLock;
|
||||
use std::sync::atomic::{AtomicU64, Ordering};
|
||||
use std::sync::{Arc, Mutex};
|
||||
|
||||
#[derive(Debug, Default, Clone)]
|
||||
pub struct ProgressState {
|
||||
pub current_action: Option<String>,
|
||||
pub progress: Option<(u64, u64)>,
|
||||
pub sub_action: Option<String>,
|
||||
tasks: BTreeMap<u64, TaskState>,
|
||||
legacy_active: bool,
|
||||
}
|
||||
|
||||
#[derive(Debug, Clone)]
|
||||
struct TaskState {
|
||||
action: String,
|
||||
sub_action: Option<String>,
|
||||
progress: Option<(u64, u64)>,
|
||||
}
|
||||
|
||||
pub static PROGRESS: LazyLock<Arc<Mutex<ProgressState>>> =
|
||||
LazyLock::new(|| Arc::new(Mutex::new(ProgressState::default())));
|
||||
static NEXT_TASK_ID: AtomicU64 = AtomicU64::new(1);
|
||||
|
||||
pub struct ProgressTask {
|
||||
id: u64,
|
||||
finished: bool,
|
||||
}
|
||||
|
||||
#[derive(Clone)]
|
||||
pub struct ProgressTaskHandle {
|
||||
id: u64,
|
||||
}
|
||||
|
||||
impl ProgressTask {
|
||||
pub fn start(action: impl Into<String>) -> Self {
|
||||
let id = NEXT_TASK_ID.fetch_add(1, Ordering::Relaxed);
|
||||
let action = action.into();
|
||||
if let Ok(mut state) = PROGRESS.lock() {
|
||||
state.tasks.insert(
|
||||
id,
|
||||
TaskState {
|
||||
action: action.clone(),
|
||||
sub_action: None,
|
||||
progress: None,
|
||||
},
|
||||
);
|
||||
refresh_visible(&mut state);
|
||||
}
|
||||
tracing::info!("{}", action);
|
||||
super::request_redraw();
|
||||
Self {
|
||||
id,
|
||||
finished: false,
|
||||
}
|
||||
}
|
||||
|
||||
pub fn handle(&self) -> ProgressTaskHandle {
|
||||
ProgressTaskHandle { id: self.id }
|
||||
}
|
||||
|
||||
pub fn set_action(&self, text: impl Into<String>) {
|
||||
update_task_action(self.id, text.into());
|
||||
}
|
||||
|
||||
pub fn set_sub_action(&self, text: impl Into<String>) {
|
||||
update_task_sub_action(self.id, text.into());
|
||||
}
|
||||
|
||||
pub fn set_progress(&self, current: u64, total: u64) {
|
||||
update_task_progress(self.id, current, total);
|
||||
}
|
||||
|
||||
pub fn finish(mut self) {
|
||||
self.remove();
|
||||
self.finished = true;
|
||||
}
|
||||
|
||||
pub fn fail(mut self, error: impl std::fmt::Display) {
|
||||
tracing::warn!("Progress task failed: {error}");
|
||||
self.remove();
|
||||
self.finished = true;
|
||||
}
|
||||
|
||||
fn remove(&self) {
|
||||
if let Ok(mut state) = PROGRESS.lock() {
|
||||
state.tasks.remove(&self.id);
|
||||
refresh_visible(&mut state);
|
||||
}
|
||||
super::request_redraw();
|
||||
}
|
||||
}
|
||||
|
||||
impl ProgressTaskHandle {
|
||||
pub fn set_sub_action(&self, text: impl Into<String>) {
|
||||
update_task_sub_action(self.id, text.into());
|
||||
}
|
||||
|
||||
pub fn set_progress(&self, current: u64, total: u64) {
|
||||
update_task_progress(self.id, current, total);
|
||||
}
|
||||
}
|
||||
|
||||
fn update_task_action(id: u64, text: String) {
|
||||
if let Ok(mut state) = PROGRESS.lock() {
|
||||
if let Some(task) = state.tasks.get_mut(&id) {
|
||||
task.action = text;
|
||||
}
|
||||
refresh_visible(&mut state);
|
||||
}
|
||||
super::request_redraw();
|
||||
}
|
||||
|
||||
fn update_task_sub_action(id: u64, text: String) {
|
||||
if let Ok(mut state) = PROGRESS.lock() {
|
||||
if let Some(task) = state.tasks.get_mut(&id) {
|
||||
task.sub_action = Some(text);
|
||||
}
|
||||
refresh_visible(&mut state);
|
||||
}
|
||||
super::request_redraw();
|
||||
}
|
||||
|
||||
fn update_task_progress(id: u64, current: u64, total: u64) {
|
||||
if let Ok(mut state) = PROGRESS.lock() {
|
||||
if let Some(task) = state.tasks.get_mut(&id) {
|
||||
task.progress = Some((current, total));
|
||||
}
|
||||
refresh_visible(&mut state);
|
||||
}
|
||||
super::request_redraw();
|
||||
}
|
||||
|
||||
impl Drop for ProgressTask {
|
||||
fn drop(&mut self) {
|
||||
if !self.finished {
|
||||
self.remove();
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
fn refresh_visible(state: &mut ProgressState) {
|
||||
if let Some((_, task)) = state.tasks.last_key_value() {
|
||||
state.current_action = Some(task.action.clone());
|
||||
state.sub_action.clone_from(&task.sub_action);
|
||||
state.progress = task.progress;
|
||||
} else if !state.legacy_active {
|
||||
state.current_action = None;
|
||||
state.sub_action = None;
|
||||
state.progress = None;
|
||||
}
|
||||
}
|
||||
|
||||
pub fn set_action(text: impl Into<String>) {
|
||||
let text = text.into();
|
||||
match PROGRESS.lock() {
|
||||
Ok(mut state) => {
|
||||
state.legacy_active = true;
|
||||
state.current_action = Some(text.clone());
|
||||
super::request_redraw();
|
||||
}
|
||||
Err(e) => {
|
||||
tracing::error!("Progress lock poisoned: {}", e);
|
||||
}
|
||||
}
|
||||
tracing::info!("{}", text);
|
||||
}
|
||||
|
||||
pub fn set_progress(current: u64, total: u64) {
|
||||
match PROGRESS.lock() {
|
||||
Ok(mut state) => {
|
||||
state.progress = Some((current, total));
|
||||
super::request_redraw();
|
||||
}
|
||||
Err(e) => {
|
||||
tracing::error!("Progress lock poisoned: {}", e);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
pub fn set_sub_action(text: impl Into<String>) {
|
||||
let text = text.into();
|
||||
match PROGRESS.lock() {
|
||||
Ok(mut state) => {
|
||||
state.sub_action = Some(text.clone());
|
||||
super::request_redraw();
|
||||
}
|
||||
Err(e) => {
|
||||
tracing::error!("Progress lock poisoned: {}", e);
|
||||
}
|
||||
}
|
||||
tracing::debug!(" {}", text);
|
||||
}
|
||||
|
||||
pub fn clear() {
|
||||
match PROGRESS.lock() {
|
||||
Ok(mut state) => {
|
||||
state.legacy_active = false;
|
||||
refresh_visible(&mut state);
|
||||
super::request_redraw();
|
||||
}
|
||||
Err(e) => {
|
||||
tracing::error!("Progress lock poisoned: {}", e);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
pub fn is_active() -> bool {
|
||||
PROGRESS
|
||||
.lock()
|
||||
.is_ok_and(|state| state.current_action.is_some())
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
#[path = "tests/progress.rs"]
|
||||
mod tests;
|
||||
@@ -0,0 +1,85 @@
|
||||
use super::*;
|
||||
use crate::tests::TEST_LOCK;
|
||||
|
||||
fn clear_errors_for_test() {
|
||||
ERROR_EVENTS.lock().unwrap().clear();
|
||||
}
|
||||
|
||||
fn make_event(msg: &str) -> ErrorEvent {
|
||||
ErrorEvent {
|
||||
id: 0,
|
||||
level: Level::ERROR,
|
||||
message: msg.to_string(),
|
||||
pushed_at: Instant::now(),
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn peek_does_not_remove() {
|
||||
let _guard = TEST_LOCK.lock().unwrap();
|
||||
clear_errors_for_test();
|
||||
|
||||
push_error(make_event("peek-test"));
|
||||
|
||||
let count_before = peek_all_errors().len();
|
||||
let peeked = peek_error();
|
||||
let count_after = peek_all_errors().len();
|
||||
|
||||
assert_eq!(
|
||||
count_before, count_after,
|
||||
"peek should not change queue length"
|
||||
);
|
||||
|
||||
assert!(peeked.is_some());
|
||||
assert_eq!(peeked.unwrap().message, "peek-test");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn peek_all_returns_newest_first() {
|
||||
let _guard = TEST_LOCK.lock().unwrap();
|
||||
clear_errors_for_test();
|
||||
|
||||
push_error(make_event("newest_a"));
|
||||
push_error(make_event("newest_b"));
|
||||
|
||||
let all = peek_all_errors();
|
||||
|
||||
assert_eq!(all.len(), 2);
|
||||
assert!(all[0].message.ends_with("_b"));
|
||||
assert!(all[1].message.ends_with("_a"));
|
||||
assert!(all[0].id > all[1].id);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn auto_assigned_ids_are_unique() {
|
||||
let _guard = TEST_LOCK.lock().unwrap();
|
||||
clear_errors_for_test();
|
||||
|
||||
push_error(make_event("unique_1"));
|
||||
push_error(make_event("unique_2"));
|
||||
|
||||
let all = peek_all_errors();
|
||||
|
||||
assert_eq!(all.len(), 2);
|
||||
assert_ne!(all[0].id, all[1].id);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn overflow_drops_oldest() {
|
||||
let _guard = TEST_LOCK.lock().unwrap();
|
||||
clear_errors_for_test();
|
||||
|
||||
for i in 0..(MAX_ERROR_EVENTS + 10) {
|
||||
push_error(make_event(&format!("overflow_{i}")));
|
||||
}
|
||||
|
||||
let all = peek_all_errors();
|
||||
|
||||
assert_eq!(all.len(), MAX_ERROR_EVENTS);
|
||||
|
||||
assert!(!all.iter().any(|e| e.message == "overflow_0"));
|
||||
assert!(!all.iter().any(|e| e.message == "overflow_9"));
|
||||
|
||||
assert!(all.iter().any(|e| e.message == "overflow_10"));
|
||||
assert!(all.iter().any(|e| e.message == "overflow_59"));
|
||||
}
|
||||
@@ -0,0 +1,57 @@
|
||||
use super::*;
|
||||
use crate::tests::TEST_LOCK;
|
||||
|
||||
#[test]
|
||||
fn newest_task_is_visible_and_drop_restores_previous_task() {
|
||||
let _guard = TEST_LOCK.lock().unwrap();
|
||||
clear();
|
||||
let first = ProgressTask::start("first");
|
||||
first.set_progress(1, 2);
|
||||
{
|
||||
let second = ProgressTask::start("second");
|
||||
second.set_sub_action("working");
|
||||
let state = PROGRESS.lock().unwrap();
|
||||
assert_eq!(state.current_action.as_deref(), Some("second"));
|
||||
assert_eq!(state.sub_action.as_deref(), Some("working"));
|
||||
}
|
||||
let state = PROGRESS.lock().unwrap();
|
||||
assert_eq!(state.current_action.as_deref(), Some("first"));
|
||||
assert_eq!(state.progress, Some((1, 2)));
|
||||
drop(state);
|
||||
first.finish();
|
||||
clear();
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn changing_phase_keeps_the_existing_progress_visible() {
|
||||
let _guard = TEST_LOCK.lock().unwrap();
|
||||
clear();
|
||||
let task = ProgressTask::start("inventory");
|
||||
task.set_progress(4, 10);
|
||||
task.set_action("provider matching");
|
||||
|
||||
let state = PROGRESS.lock().unwrap();
|
||||
assert_eq!(state.current_action.as_deref(), Some("provider matching"));
|
||||
assert_eq!(state.progress, Some((4, 10)));
|
||||
drop(state);
|
||||
|
||||
task.finish();
|
||||
assert!(!is_active());
|
||||
clear();
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn clearing_legacy_progress_keeps_owned_tasks() {
|
||||
let _guard = TEST_LOCK.lock().unwrap();
|
||||
clear();
|
||||
let task = ProgressTask::start("indexing");
|
||||
set_action("legacy download");
|
||||
clear();
|
||||
|
||||
let state = PROGRESS.lock().unwrap();
|
||||
assert_eq!(state.current_action.as_deref(), Some("indexing"));
|
||||
drop(state);
|
||||
|
||||
task.finish();
|
||||
clear();
|
||||
}
|
||||
Reference in new issue
Block a user