use std::fmt;
use std::sync::atomic::{AtomicBool, AtomicU64, Ordering};
use std::sync::mpsc::{sync_channel, Receiver, SyncSender, TrySendError};
use std::sync::Arc;
use std::time::{Duration, Instant};
use crate::error::GuiError;
use crate::widgets::WidgetId;
pub const DEFAULT_TASK_QUEUE_CAPACITY: usize = 256;
const LOSSLESS_RETRY_BACKOFF_START: Duration = Duration::from_micros(50);
const LOSSLESS_RETRY_BACKOFF_MAX: Duration = Duration::from_millis(2);
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, PartialOrd, Ord)]
pub struct TaskId(pub u64);
impl fmt::Display for TaskId {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
write!(f, "task-{}", self.0)
}
}
#[derive(Debug, Clone, PartialEq)]
pub enum TaskCommand {
SetDataListItems {
widget_id: WidgetId,
items: Vec<String>,
},
SetDataGridRows {
widget_id: WidgetId,
rows: Vec<Vec<String>>,
},
SetText { widget_id: WidgetId, text: String },
SetValue { widget_id: WidgetId, value: i32 },
SetChecked { widget_id: WidgetId, checked: bool },
SetEnabled { widget_id: WidgetId, enabled: bool },
SetVisible { widget_id: WidgetId, visible: bool },
Progress { task: TaskId, value: f64 },
Finished { task: TaskId },
Failed { task: TaskId, message: String },
}
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum TaskClass {
Lossy,
Lossless,
}
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum TaskCommandKind {
SetDataListItems,
SetDataGridRows,
SetText,
SetValue,
SetChecked,
SetEnabled,
SetVisible,
}
impl TaskCommand {
pub fn class(&self) -> TaskClass {
match self {
TaskCommand::Finished { .. } | TaskCommand::Failed { .. } => TaskClass::Lossless,
TaskCommand::SetDataListItems { .. }
| TaskCommand::SetDataGridRows { .. }
| TaskCommand::SetText { .. }
| TaskCommand::SetValue { .. }
| TaskCommand::SetChecked { .. }
| TaskCommand::SetEnabled { .. }
| TaskCommand::SetVisible { .. }
| TaskCommand::Progress { .. } => TaskClass::Lossy,
}
}
pub fn widget_target(&self) -> Option<(WidgetId, TaskCommandKind)> {
match self {
TaskCommand::SetDataListItems { widget_id, .. } => {
Some((*widget_id, TaskCommandKind::SetDataListItems))
}
TaskCommand::SetDataGridRows { widget_id, .. } => {
Some((*widget_id, TaskCommandKind::SetDataGridRows))
}
TaskCommand::SetText { widget_id, .. } => Some((*widget_id, TaskCommandKind::SetText)),
TaskCommand::SetValue { widget_id, .. } => {
Some((*widget_id, TaskCommandKind::SetValue))
}
TaskCommand::SetChecked { widget_id, .. } => {
Some((*widget_id, TaskCommandKind::SetChecked))
}
TaskCommand::SetEnabled { widget_id, .. } => {
Some((*widget_id, TaskCommandKind::SetEnabled))
}
TaskCommand::SetVisible { widget_id, .. } => {
Some((*widget_id, TaskCommandKind::SetVisible))
}
TaskCommand::Progress { .. }
| TaskCommand::Finished { .. }
| TaskCommand::Failed { .. } => None,
}
}
}
#[derive(Debug, Clone, PartialEq, Eq)]
pub enum TaskAbortReason {
WidgetRemoved,
Refused(GuiError),
}
#[derive(Debug, Clone, PartialEq)]
pub enum TaskEvent {
Progress { task: TaskId, value: f64 },
Finished { task: TaskId },
Failed { task: TaskId, message: String },
Aborted {
widget_id: WidgetId,
command: TaskCommandKind,
reason: TaskAbortReason,
},
}
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum TaskSendError {
Full,
Closed,
}
impl fmt::Display for TaskSendError {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
match self {
TaskSendError::Full => write!(f, "background task queue is full"),
TaskSendError::Closed => write!(f, "UI thread command channel is closed"),
}
}
}
impl std::error::Error for TaskSendError {}
#[derive(Debug, Default, Clone, Copy, PartialEq, Eq)]
pub struct TaskDrainReport {
pub applied: usize,
pub rejected: usize,
}
impl TaskDrainReport {
pub fn total(&self) -> usize {
self.applied + self.rejected
}
}
#[derive(Debug, Clone)]
pub struct TaskToken {
id: TaskId,
cancelled: Arc<AtomicBool>,
}
impl TaskToken {
pub fn id(&self) -> TaskId {
self.id
}
pub fn cancel(&self) {
self.cancelled.store(true, Ordering::SeqCst);
}
pub fn is_cancelled(&self) -> bool {
self.cancelled.load(Ordering::SeqCst)
}
pub fn sleep_or_cancelled(&self, duration: Duration) -> bool {
if self.is_cancelled() {
return false;
}
let start = Instant::now();
let quantum = Duration::from_millis(25);
while start.elapsed() < duration {
if self.is_cancelled() {
return false;
}
let remaining = duration.saturating_sub(start.elapsed());
let step = remaining.min(quantum);
std::thread::sleep(step);
}
!self.is_cancelled()
}
}
#[derive(Debug, Clone)]
pub struct TaskHandle {
token: TaskToken,
finished: Arc<AtomicBool>,
}
impl TaskHandle {
pub fn new(token: TaskToken) -> Self {
Self {
token,
finished: Arc::new(AtomicBool::new(false)),
}
}
pub fn id(&self) -> TaskId {
self.token.id()
}
pub fn cancel(&self) {
self.token.cancel();
}
pub fn is_cancelled(&self) -> bool {
self.token.is_cancelled()
}
pub fn is_finished(&self) -> bool {
self.finished.load(Ordering::SeqCst)
}
pub fn token(&self) -> &TaskToken {
&self.token
}
pub(crate) fn mark_finished(&self) {
self.finished.store(true, Ordering::SeqCst);
}
}
#[derive(Clone)]
pub struct UiProxy {
inner: Arc<UiProxyInner>,
}
struct UiProxyInner {
sender: SyncSender<TaskCommand>,
wake: Option<Arc<dyn Fn() + Send + Sync>>,
next_task: AtomicU64,
capacity: usize,
}
impl fmt::Debug for UiProxy {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
f.debug_struct("UiProxy")
.field("capacity", &self.inner.capacity)
.field("has_wake_hook", &self.inner.wake.is_some())
.finish()
}
}
impl UiProxy {
pub(crate) fn new(
wake: Option<Arc<dyn Fn() + Send + Sync>>,
capacity: usize,
) -> (Self, Receiver<TaskCommand>) {
let capacity = capacity.max(1);
let (sender, receiver) = sync_channel(capacity);
let proxy = Self {
inner: Arc::new(UiProxyInner {
sender,
wake,
next_task: AtomicU64::new(1),
capacity,
}),
};
(proxy, receiver)
}
pub fn post(&self, command: TaskCommand) -> Result<(), TaskSendError> {
match self.inner.sender.try_send(command) {
Ok(()) => {
self.wake();
Ok(())
}
Err(TrySendError::Full(_)) => Err(TaskSendError::Full),
Err(TrySendError::Disconnected(_)) => Err(TaskSendError::Closed),
}
}
pub fn send_lossless(
&self,
command: TaskCommand,
timeout: Duration,
) -> Result<(), TaskSendError> {
let deadline = Instant::now() + timeout;
let mut backoff = LOSSLESS_RETRY_BACKOFF_START;
let mut pending = command;
loop {
match self.inner.sender.try_send(pending) {
Ok(()) => {
self.wake();
return Ok(());
}
Err(TrySendError::Full(command)) => {
if Instant::now() >= deadline {
return Err(TaskSendError::Full);
}
pending = command;
std::thread::sleep(backoff);
backoff = (backoff * 2).min(LOSSLESS_RETRY_BACKOFF_MAX);
}
Err(TrySendError::Disconnected(_)) => return Err(TaskSendError::Closed),
}
}
}
fn wake(&self) {
if let Some(wake) = &self.inner.wake {
wake();
}
}
pub fn start_task(&self) -> TaskToken {
let id = TaskId(self.inner.next_task.fetch_add(1, Ordering::SeqCst));
TaskToken {
id,
cancelled: Arc::new(AtomicBool::new(false)),
}
}
pub fn capacity(&self) -> usize {
self.inner.capacity
}
pub fn set_text(
&self,
widget_id: WidgetId,
text: impl Into<String>,
) -> Result<(), TaskSendError> {
self.post(TaskCommand::SetText {
widget_id,
text: text.into(),
})
}
pub fn set_data_list_items(
&self,
widget_id: WidgetId,
items: impl IntoIterator<Item = String>,
) -> Result<(), TaskSendError> {
self.post(TaskCommand::SetDataListItems {
widget_id,
items: items.into_iter().collect(),
})
}
pub fn set_data_grid_rows(
&self,
widget_id: WidgetId,
rows: impl IntoIterator<Item = Vec<String>>,
) -> Result<(), TaskSendError> {
self.post(TaskCommand::SetDataGridRows {
widget_id,
rows: rows.into_iter().collect(),
})
}
pub fn set_value(&self, widget_id: WidgetId, value: i32) -> Result<(), TaskSendError> {
self.post(TaskCommand::SetValue { widget_id, value })
}
pub fn set_checked(&self, widget_id: WidgetId, checked: bool) -> Result<(), TaskSendError> {
self.post(TaskCommand::SetChecked { widget_id, checked })
}
pub fn set_enabled(&self, widget_id: WidgetId, enabled: bool) -> Result<(), TaskSendError> {
self.post(TaskCommand::SetEnabled { widget_id, enabled })
}
pub fn set_visible(&self, widget_id: WidgetId, visible: bool) -> Result<(), TaskSendError> {
self.post(TaskCommand::SetVisible { widget_id, visible })
}
pub fn progress(&self, token: &TaskToken, value: f64) -> Result<(), TaskSendError> {
self.post(TaskCommand::Progress {
task: token.id(),
value,
})
}
pub fn finish(&self, token: &TaskToken) -> Result<(), TaskSendError> {
self.post(TaskCommand::Finished { task: token.id() })
}
pub fn fail(&self, token: &TaskToken, message: impl Into<String>) -> Result<(), TaskSendError> {
self.post(TaskCommand::Failed {
task: token.id(),
message: message.into(),
})
}
pub fn finish_lossless(
&self,
token: &TaskToken,
timeout: Duration,
) -> Result<(), TaskSendError> {
self.send_lossless(TaskCommand::Finished { task: token.id() }, timeout)
}
pub fn fail_lossless(
&self,
token: &TaskToken,
message: impl Into<String>,
timeout: Duration,
) -> Result<(), TaskSendError> {
self.send_lossless(
TaskCommand::Failed {
task: token.id(),
message: message.into(),
},
timeout,
)
}
}
#[cfg(test)]
mod tests {
use super::*;
fn proxy(capacity: usize) -> (UiProxy, Receiver<TaskCommand>) {
UiProxy::new(None, capacity)
}
#[test]
fn task_ids_are_unique_and_monotonic() {
let (proxy, _receiver) = proxy(4);
let first = proxy.start_task();
let second = proxy.start_task();
let clone = proxy.clone();
let third = clone.start_task();
assert_eq!(first.id(), TaskId(1));
assert_eq!(second.id(), TaskId(2));
assert_eq!(third.id(), TaskId(3));
assert_ne!(first.id(), third.id());
}
#[test]
fn cancellation_flag_is_visible_across_clones() {
let (proxy, _receiver) = proxy(4);
let ui_side = proxy.start_task();
let worker_side = ui_side.clone();
assert!(!worker_side.is_cancelled());
ui_side.cancel();
assert!(worker_side.is_cancelled());
ui_side.cancel();
assert!(worker_side.is_cancelled());
}
#[test]
fn posts_fail_closed_after_receiver_drops() {
let (proxy, receiver) = proxy(4);
drop(receiver);
assert_eq!(
proxy.post(TaskCommand::Finished { task: TaskId(1) }),
Err(TaskSendError::Closed)
);
assert_eq!(
proxy.finish(&TaskToken {
id: TaskId(1),
cancelled: Arc::new(AtomicBool::new(false))
}),
Err(TaskSendError::Closed)
);
}
#[test]
fn queue_bound_rejects_then_recovers() {
let (proxy, receiver) = proxy(3);
assert_eq!(proxy.capacity(), 3);
for _ in 0..3 {
assert_eq!(proxy.set_value(WidgetId(1), 1), Ok(()));
}
assert_eq!(proxy.set_value(WidgetId(1), 1), Err(TaskSendError::Full));
let _ = receiver.try_recv().expect("queued command");
assert_eq!(proxy.set_value(WidgetId(1), 2), Ok(()));
}
#[test]
fn commands_are_received_in_fifo_order() {
let (proxy, receiver) = proxy(8);
let token = proxy.start_task();
proxy.set_text(WidgetId(1), "first").expect("post");
proxy.progress(&token, 50.0).expect("post");
proxy.set_text(WidgetId(1), "second").expect("post");
assert_eq!(
receiver.try_recv().expect("cmd"),
TaskCommand::SetText {
widget_id: WidgetId(1),
text: "first".to_owned()
}
);
assert_eq!(
receiver.try_recv().expect("cmd"),
TaskCommand::Progress {
task: token.id(),
value: 50.0
}
);
assert_eq!(
receiver.try_recv().expect("cmd"),
TaskCommand::SetText {
widget_id: WidgetId(1),
text: "second".to_owned()
}
);
}
#[test]
fn lifecycle_helpers_carry_the_task_id() {
let (proxy, receiver) = proxy(4);
let token = proxy.start_task();
proxy.finish(&token).expect("post");
proxy.fail(&token, "boom").expect("post");
assert_eq!(
receiver.try_recv().expect("cmd"),
TaskCommand::Finished { task: token.id() }
);
assert_eq!(
receiver.try_recv().expect("cmd"),
TaskCommand::Failed {
task: token.id(),
message: "boom".to_owned()
}
);
}
#[test]
fn proxy_and_token_are_send_and_sync() {
fn assert_send_sync<T: Send + Sync>() {}
assert_send_sync::<UiProxy>();
assert_send_sync::<TaskToken>();
assert_send_sync::<TaskSendError>();
}
#[test]
fn drain_report_totals_add_up() {
let report = TaskDrainReport {
applied: 3,
rejected: 2,
};
assert_eq!(report.total(), 5);
}
#[test]
fn command_class_taxonomy_matches_the_documented_split() {
let task = TaskId(1);
let lossless = [
TaskCommand::Finished { task },
TaskCommand::Failed {
task,
message: "boom".to_owned(),
},
];
for command in lossless {
assert_eq!(command.class(), TaskClass::Lossless, "{command:?}");
}
let lossy = [
TaskCommand::SetDataListItems {
widget_id: WidgetId(1),
items: vec!["row".to_owned()],
},
TaskCommand::SetDataGridRows {
widget_id: WidgetId(1),
rows: vec![vec!["cell".to_owned()]],
},
TaskCommand::SetText {
widget_id: WidgetId(1),
text: "text".to_owned(),
},
TaskCommand::SetValue {
widget_id: WidgetId(1),
value: 1,
},
TaskCommand::SetChecked {
widget_id: WidgetId(1),
checked: true,
},
TaskCommand::SetEnabled {
widget_id: WidgetId(1),
enabled: true,
},
TaskCommand::SetVisible {
widget_id: WidgetId(1),
visible: false,
},
TaskCommand::Progress { task, value: 50.0 },
];
for command in lossy {
assert_eq!(command.class(), TaskClass::Lossy, "{command:?}");
}
}
#[test]
fn lossless_send_waits_for_capacity_instead_of_dropping() {
let (proxy, receiver) = proxy(2);
proxy.set_value(WidgetId(1), 1).expect("fills slot 1");
proxy.set_value(WidgetId(1), 2).expect("fills slot 2");
assert_eq!(proxy.set_value(WidgetId(1), 3), Err(TaskSendError::Full));
let worker_proxy = proxy.clone();
let worker = std::thread::spawn(move || {
worker_proxy.send_lossless(
TaskCommand::Finished { task: TaskId(9) },
Duration::from_secs(5),
)
});
std::thread::sleep(Duration::from_millis(20));
let _ = receiver.try_recv().expect("drained slot 1");
let _ = receiver.try_recv().expect("drained slot 2");
worker
.join()
.expect("worker thread")
.expect("lossless send must succeed once capacity frees up");
assert_eq!(
receiver.try_recv().expect("queued completion"),
TaskCommand::Finished { task: TaskId(9) },
"the lossless command is queued after the drained samples"
);
}
#[test]
fn lossless_send_times_out_without_silently_dropping() {
let (proxy, receiver) = proxy(1);
proxy.set_value(WidgetId(1), 1).expect("fills the queue");
let error = proxy
.send_lossless(TaskCommand::Finished { task: TaskId(9) }, Duration::ZERO)
.expect_err("a full queue with no slack must report Full");
assert_eq!(error, TaskSendError::Full);
assert_eq!(
receiver.try_recv().expect("original sample"),
TaskCommand::SetValue {
widget_id: WidgetId(1),
value: 1
}
);
assert!(
receiver.try_recv().is_err(),
"a timed-out lossless send must not leave a partial post behind"
);
proxy
.send_lossless(TaskCommand::Finished { task: TaskId(10) }, Duration::ZERO)
.expect("zero timeout succeeds when there is room");
assert_eq!(
receiver.try_recv().expect("queued completion"),
TaskCommand::Finished { task: TaskId(10) }
);
}
#[test]
fn lossless_send_fails_fast_when_the_ui_is_gone() {
let (proxy, receiver) = proxy(1);
drop(receiver);
assert_eq!(
proxy.send_lossless(
TaskCommand::Finished { task: TaskId(1) },
Duration::from_secs(30)
),
Err(TaskSendError::Closed),
"a closed channel must not wait out the timeout"
);
}
#[test]
fn task_handle_lifecycle_and_cancellation() {
let (proxy, _receiver) = proxy(4);
let token = proxy.start_task();
let handle = TaskHandle::new(token.clone());
assert_eq!(handle.id(), token.id());
assert!(!handle.is_cancelled());
assert!(!handle.is_finished());
handle.cancel();
assert!(handle.is_cancelled());
assert!(token.is_cancelled());
handle.mark_finished();
assert!(handle.is_finished());
}
#[test]
fn test_b1491_sleep_or_cancelled_completes_when_not_cancelled() {
let (proxy, _receiver) = proxy(4);
let token = proxy.start_task();
let start = Instant::now();
let ok = token.sleep_or_cancelled(Duration::from_millis(60));
assert!(ok, "un-cancelled sleep should return true");
assert!(start.elapsed() >= Duration::from_millis(50));
}
#[test]
fn test_b1491_sleep_or_cancelled_returns_immediately_if_already_cancelled() {
let (proxy, _receiver) = proxy(4);
let token = proxy.start_task();
token.cancel();
let start = Instant::now();
let ok = token.sleep_or_cancelled(Duration::from_secs(10));
assert!(!ok, "pre-cancelled sleep should return false");
assert!(
start.elapsed() < Duration::from_secs(1),
"pre-cancelled sleep must return without waiting out the 10s sleep"
);
}
#[test]
fn test_b1491_sleep_or_cancelled_awakens_early_on_cancellation() {
let (proxy, _receiver) = proxy(4);
let token = proxy.start_task();
let cancel_token = token.clone();
let cancel_thread = std::thread::spawn(move || {
std::thread::sleep(Duration::from_millis(40));
cancel_token.cancel();
});
let start = Instant::now();
let ok = token.sleep_or_cancelled(Duration::from_secs(5));
assert!(!ok, "sleep interrupted by cancel should return false");
let elapsed = start.elapsed();
assert!(
elapsed < Duration::from_secs(2),
"expected early cancellation awakening, took {elapsed:?}"
);
cancel_thread.join().unwrap();
}
}