Skip to main content

sui_reactive/
task.rs

1use std::{
2    fmt,
3    future::Future,
4    sync::{
5        Arc,
6        atomic::{AtomicU64, Ordering},
7    },
8};
9
10use crate::{Changed, Observable, Observer, Selector, Signal, SourceId, Subscription};
11
12/// Lifecycle of a background operation observed through a [`Task`].
13#[derive(Debug, Clone, PartialEq)]
14pub enum TaskState<T, E = String> {
15    Idle,
16    /// Running. `progress` is `None` while indeterminate, otherwise in `0..=1`.
17    /// `previous` holds the last result while a [`Task::refresh`] runs.
18    Loading {
19        progress: Option<f32>,
20        previous: Option<T>,
21    },
22    Ready(T),
23    Failed(E),
24}
25
26impl<T, E> TaskState<T, E> {
27    pub fn is_idle(&self) -> bool {
28        matches!(self, Self::Idle)
29    }
30
31    pub fn is_loading(&self) -> bool {
32        matches!(self, Self::Loading { .. })
33    }
34
35    /// Progress while loading; `None` when indeterminate or not loading.
36    pub fn progress(&self) -> Option<f32> {
37        match self {
38            Self::Loading { progress, .. } => *progress,
39            _ => None,
40        }
41    }
42
43    pub fn ready(&self) -> Option<&T> {
44        match self {
45            Self::Ready(value) => Some(value),
46            _ => None,
47        }
48    }
49
50    /// The current result, or while refreshing, the previous one.
51    pub fn latest(&self) -> Option<&T> {
52        match self {
53            Self::Ready(value) => Some(value),
54            Self::Loading { previous, .. } => previous.as_ref(),
55            _ => None,
56        }
57    }
58
59    pub fn error(&self) -> Option<&E> {
60        match self {
61            Self::Failed(error) => Some(error),
62            _ => None,
63        }
64    }
65}
66
67/// Observable state of a background operation: a [`Signal`] holding a
68/// [`TaskState`], plus a generation counter that keeps stale workers from
69/// overwriting newer results.
70///
71/// [`start`](Self::start) moves to `Loading` and returns a [`TaskHandle`] for
72/// the worker; [`refresh`](Self::refresh) does the same but keeps the last
73/// result visible. Starting again, [`reset`](Self::reset), or setting a result
74/// directly retires every earlier handle, whose later reports are ignored.
75///
76/// For async work, [`TaskHandle::run`] wraps a future that you spawn on any
77/// executor; dropping that future cancels the run.
78///
79/// ```ignore
80/// let thumbnails: Task<Arc<Vec<Image>>> = Task::named("thumbnails");
81/// let handle = thumbnails.start();
82/// std::thread::spawn(move || {
83///     for (index, path) in paths.iter().enumerate() {
84///         handle.set_progress(index as f32 / paths.len() as f32);
85///         // ...
86///     }
87///     handle.complete(load_all(&paths).map(Arc::new));
88/// });
89/// ```
90///
91/// Writes need no `Clone` or `PartialEq` on `T` or `E`. Observers run on the
92/// reporting thread, as with any [`Signal`]. Wrap large results in `Arc` so
93/// [`state`](Self::state) stays cheap, or read with [`with`](Self::with).
94pub struct Task<T, E = String> {
95    state: Signal<TaskState<T, E>>,
96    // Changed only while `state` is write-locked, so a check and the write it
97    // guards are atomic with respect to other transitions.
98    generation: Arc<AtomicU64>,
99}
100
101impl<T, E> Clone for Task<T, E> {
102    fn clone(&self) -> Self {
103        Self {
104            state: self.state.clone(),
105            generation: Arc::clone(&self.generation),
106        }
107    }
108}
109
110impl<T, E> fmt::Debug for Task<T, E>
111where
112    T: fmt::Debug,
113    E: fmt::Debug,
114{
115    fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
116        formatter
117            .debug_struct("Task")
118            .field("state", &self.state)
119            .field("generation", &self.generation.load(Ordering::Acquire))
120            .finish()
121    }
122}
123
124impl<T, E> Default for Task<T, E> {
125    fn default() -> Self {
126        Self::new()
127    }
128}
129
130impl<T, E> Task<T, E> {
131    pub fn new() -> Self {
132        Self::named("Task")
133    }
134
135    pub fn named(name: impl Into<Arc<str>>) -> Self {
136        Self {
137            state: Signal::named(name, TaskState::Idle),
138            generation: Arc::new(AtomicU64::new(0)),
139        }
140    }
141
142    /// Enter `Loading` with indeterminate progress and return the handle the
143    /// worker reports through. Retires earlier handles and drops any result.
144    pub fn start(&self) -> TaskHandle<T, E> {
145        self.begin(false)
146    }
147
148    /// Like [`start`](Self::start), but keep the current result as
149    /// `Loading { previous }` so the UI can show it until the new one lands.
150    /// Cancelling the run restores it as `Ready`.
151    pub fn refresh(&self) -> TaskHandle<T, E> {
152        self.begin(true)
153    }
154
155    /// Return to `Idle`, retiring every outstanding handle.
156    pub fn reset(&self) -> bool {
157        self.retire_and_set(TaskState::Idle)
158    }
159
160    /// Store a result directly, retiring every outstanding handle.
161    pub fn finish(&self, value: T) -> bool {
162        self.retire_and_set(TaskState::Ready(value))
163    }
164
165    /// Store a failure directly, retiring every outstanding handle.
166    pub fn fail(&self, error: E) -> bool {
167        self.retire_and_set(TaskState::Failed(error))
168    }
169
170    pub fn complete(&self, result: Result<T, E>) -> bool {
171        self.retire_and_set(result.into())
172    }
173
174    pub fn state(&self) -> TaskState<T, E>
175    where
176        T: Clone,
177        E: Clone,
178    {
179        self.state.get()
180    }
181
182    /// Read the state by reference without cloning a result.
183    pub fn with<R>(&self, read: impl FnOnce(&TaskState<T, E>) -> R) -> R {
184        self.state.with(read)
185    }
186
187    pub fn is_loading(&self) -> bool {
188        self.with(TaskState::is_loading)
189    }
190
191    pub fn progress(&self) -> Option<f32> {
192        self.with(TaskState::progress)
193    }
194
195    /// The underlying signal, for APIs that take a [`Signal`].
196    pub fn signal(&self) -> &Signal<TaskState<T, E>> {
197        &self.state
198    }
199
200    pub fn source_id(&self) -> SourceId {
201        self.state.source_id()
202    }
203
204    pub fn version(&self) -> u64 {
205        self.state.version()
206    }
207
208    pub fn subscribe(&self, observer: Observer) -> Subscription {
209        self.state.subscribe(observer)
210    }
211
212    /// A future that resolves at the next state change.
213    pub fn changed(&self) -> Changed {
214        self.state.changed()
215    }
216
217    pub fn select<U>(
218        &self,
219        select: impl Fn(&TaskState<T, E>) -> U + Send + Sync + 'static,
220    ) -> Selector<Signal<TaskState<T, E>>, TaskState<T, E>, U>
221    where
222        T: Clone + Send + Sync + 'static,
223        E: Clone + Send + Sync + 'static,
224        U: Clone + PartialEq + Send + Sync + 'static,
225    {
226        self.state.select_named(self.state.source_name(), select)
227    }
228
229    pub fn select_named<U>(
230        &self,
231        name: impl Into<Arc<str>>,
232        select: impl Fn(&TaskState<T, E>) -> U + Send + Sync + 'static,
233    ) -> Selector<Signal<TaskState<T, E>>, TaskState<T, E>, U>
234    where
235        T: Clone + Send + Sync + 'static,
236        E: Clone + Send + Sync + 'static,
237        U: Clone + PartialEq + Send + Sync + 'static,
238    {
239        self.state.select_named(name, select)
240    }
241
242    fn begin(&self, keep_previous: bool) -> TaskHandle<T, E> {
243        let mut generation = 0;
244        self.state.modify(|state| {
245            generation = self.generation.fetch_add(1, Ordering::AcqRel) + 1;
246            let unchanged = matches!(
247                state,
248                TaskState::Loading {
249                    progress: None,
250                    previous: None
251                }
252            );
253            let previous = match std::mem::replace(state, TaskState::Idle) {
254                TaskState::Ready(value) if keep_previous => Some(value),
255                TaskState::Loading { previous, .. } if keep_previous => previous,
256                _ => None,
257            };
258            let changed = !(unchanged && previous.is_none());
259            *state = TaskState::Loading {
260                progress: None,
261                previous,
262            };
263            changed
264        });
265        TaskHandle {
266            task: self.clone(),
267            generation,
268        }
269    }
270
271    fn retire_and_set(&self, next: TaskState<T, E>) -> bool {
272        self.state.modify(|state| {
273            self.generation.fetch_add(1, Ordering::AcqRel);
274            let changed = !(state.is_idle() && next.is_idle());
275            *state = next;
276            changed
277        })
278    }
279
280    /// Apply `write` only while `generation` is still current.
281    fn write_if_current(
282        &self,
283        generation: u64,
284        retire: bool,
285        write: impl FnOnce(&mut TaskState<T, E>) -> bool,
286    ) -> bool {
287        self.state.modify(|state| {
288            if self.generation.load(Ordering::Acquire) != generation {
289                return false;
290            }
291            if retire {
292                self.generation.fetch_add(1, Ordering::AcqRel);
293            }
294            write(state)
295        })
296    }
297}
298
299impl<T, E> From<Result<T, E>> for TaskState<T, E> {
300    fn from(result: Result<T, E>) -> Self {
301        match result {
302            Ok(value) => Self::Ready(value),
303            Err(error) => Self::Failed(error),
304        }
305    }
306}
307
308impl<T, E> Observable<TaskState<T, E>> for Task<T, E>
309where
310    T: Clone + 'static,
311    E: Clone + 'static,
312{
313    fn source_id(&self) -> SourceId {
314        self.state.source_id()
315    }
316
317    fn source_name(&self) -> Arc<str> {
318        self.state.source_name()
319    }
320
321    fn get(&self) -> TaskState<T, E> {
322        self.state.get()
323    }
324
325    fn read(&self, reader: &mut dyn FnMut(&TaskState<T, E>)) {
326        self.state.with(|state| reader(state));
327    }
328
329    fn value_version(&self) -> Option<u64> {
330        Some(self.state.version())
331    }
332
333    fn subscribe(&self, observer: Observer) -> Subscription {
334        self.state.subscribe(observer)
335    }
336}
337
338/// A worker's reporting channel for one run of a [`Task`].
339///
340/// Every report is ignored once the run is retired: after the task is started
341/// again, reset, or completed or cancelled by this or another handle. Dropping
342/// a handle without completing leaves the task `Loading`; call
343/// [`cancel`](Self::cancel) to abandon a run.
344pub struct TaskHandle<T, E = String> {
345    task: Task<T, E>,
346    generation: u64,
347}
348
349impl<T, E> Clone for TaskHandle<T, E> {
350    fn clone(&self) -> Self {
351        Self {
352            task: self.task.clone(),
353            generation: self.generation,
354        }
355    }
356}
357
358impl<T, E> fmt::Debug for TaskHandle<T, E> {
359    fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
360        formatter
361            .debug_struct("TaskHandle")
362            .field("source_id", &self.task.source_id())
363            .field("generation", &self.generation)
364            .finish()
365    }
366}
367
368impl<T, E> TaskHandle<T, E> {
369    /// Whether this run is still the task's current one. A worker may poll
370    /// this to stop early after being superseded.
371    pub fn is_current(&self) -> bool {
372        self.task.generation.load(Ordering::Acquire) == self.generation
373    }
374
375    /// Report determinate progress, clamped to `0..=1`. Repeating the current
376    /// value does not notify. NaN reports indeterminate progress.
377    pub fn set_progress(&self, progress: f32) -> bool {
378        let progress = (!progress.is_nan()).then(|| progress.clamp(0.0, 1.0));
379        self.task
380            .write_if_current(self.generation, false, |state| match state {
381                TaskState::Loading {
382                    progress: current, ..
383                } => {
384                    let changed = *current != progress;
385                    *current = progress;
386                    changed
387                }
388                _ => {
389                    *state = TaskState::Loading {
390                        progress,
391                        previous: None,
392                    };
393                    true
394                }
395            })
396    }
397
398    /// Abandon the run: back to `Idle`, or to the previous result after a
399    /// [`Task::refresh`]. Ignored if the run was already retired.
400    pub fn cancel(self) -> bool {
401        self.task.write_if_current(self.generation, true, |state| {
402            *state = match std::mem::replace(state, TaskState::Idle) {
403                TaskState::Loading {
404                    previous: Some(value),
405                    ..
406                } => TaskState::Ready(value),
407                _ => TaskState::Idle,
408            };
409            true
410        })
411    }
412
413    /// Wrap `work` so its output completes this run. Spawn the returned
414    /// future on any executor; it resolves to whether the result was stored.
415    /// Dropping it before `work` finishes [cancels](Self::cancel) the run.
416    ///
417    /// ```ignore
418    /// let handle = results.refresh();
419    /// let progress = handle.clone();
420    /// wasm_bindgen_futures::spawn_local(async move {
421    ///     handle
422    ///         .run(async move {
423    ///             progress.set_progress(0.5);
424    ///             fetch_results().await
425    ///         })
426    ///         .await;
427    /// });
428    /// ```
429    pub fn run<Work>(self, work: Work) -> impl Future<Output = bool> + use<T, E, Work>
430    where
431        Work: Future<Output = Result<T, E>>,
432    {
433        let mut run = CancelOnDrop(Some(self));
434        async move {
435            let result = work.await;
436            run.0.take().is_some_and(|handle| handle.complete(result))
437        }
438    }
439
440    pub fn finish(self, value: T) -> bool {
441        self.complete(Ok(value))
442    }
443
444    pub fn fail(self, error: E) -> bool {
445        self.complete(Err(error))
446    }
447
448    /// Store the run's result unless the run was retired. Returns whether it
449    /// was stored.
450    pub fn complete(self, result: Result<T, E>) -> bool {
451        self.task.write_if_current(self.generation, true, |state| {
452            *state = result.into();
453            true
454        })
455    }
456
457    pub fn task(&self) -> &Task<T, E> {
458        &self.task
459    }
460}
461
462/// Cancels the run if [`TaskHandle::run`]'s future is dropped unfinished.
463struct CancelOnDrop<T, E>(Option<TaskHandle<T, E>>);
464
465impl<T, E> Drop for CancelOnDrop<T, E> {
466    fn drop(&mut self) {
467        if let Some(handle) = self.0.take() {
468            handle.cancel();
469        }
470    }
471}
472
473#[cfg(test)]
474mod tests {
475    use std::sync::atomic::AtomicUsize;
476
477    use super::*;
478
479    fn count_notifications<T, E>(task: &Task<T, E>) -> (Arc<AtomicUsize>, Subscription) {
480        let notifications = Arc::new(AtomicUsize::new(0));
481        let count = Arc::clone(&notifications);
482        let subscription = task.subscribe(Observer::new(move |_| {
483            count.fetch_add(1, Ordering::Relaxed);
484        }));
485        (notifications, subscription)
486    }
487
488    #[test]
489    fn task_reports_progress_and_result_from_a_worker() {
490        let task: Task<u32> = Task::named("load");
491        let (notifications, _subscription) = count_notifications(&task);
492        let handle = task.start();
493        assert_eq!(
494            task.state(),
495            TaskState::Loading {
496                progress: None,
497                previous: None
498            }
499        );
500
501        std::thread::spawn(move || {
502            assert!(handle.set_progress(0.5));
503            assert!(!handle.set_progress(0.5), "equal progress is deduplicated");
504            assert!(handle.set_progress(2.0));
505            assert!(handle.finish(7));
506        })
507        .join()
508        .unwrap();
509
510        assert_eq!(task.state(), TaskState::Ready(7));
511        // start, 0.5, 1.0 (clamped), ready
512        assert_eq!(notifications.load(Ordering::Relaxed), 4);
513    }
514
515    #[test]
516    fn restarting_retires_the_previous_handle() {
517        let task: Task<&'static str> = Task::new();
518        let stale = task.start();
519        let current = task.start();
520
521        assert!(!stale.is_current());
522        assert!(!stale.set_progress(0.9));
523        assert!(!stale.clone().finish("stale"));
524        assert!(task.is_loading());
525
526        let progress = current.clone();
527        assert!(current.finish("fresh"));
528        assert!(!progress.set_progress(0.1), "completion retires clones too");
529        assert_eq!(task.state(), TaskState::Ready("fresh"));
530    }
531
532    #[test]
533    fn reset_cancels_a_running_worker() {
534        let task: Task<u32> = Task::new();
535        let handle = task.start();
536        assert!(task.reset());
537        assert!(!task.reset(), "already idle");
538        assert!(!handle.fail("late".to_string()));
539        assert!(task.with(TaskState::is_idle));
540    }
541
542    #[test]
543    fn task_state_needs_no_clone_or_equality_to_write() {
544        struct Opaque;
545        struct OpaqueError;
546
547        let task: Task<Opaque, OpaqueError> = Task::new();
548        let handle = task.start();
549        assert!(handle.complete(Err(OpaqueError)));
550        assert!(task.with(|state| state.error().is_some()));
551        assert!(task.finish(Opaque));
552        assert!(task.with(|state| state.ready().is_some()));
553    }
554
555    #[test]
556    fn selector_tracks_task_progress() {
557        let task: Task<u32> = Task::new();
558        let percent = task.select(|state| state.progress().map(|p| (p * 100.0) as u32));
559        let handle = task.start();
560        handle.set_progress(0.25);
561        assert_eq!(percent.get(), Some(25));
562    }
563
564    #[test]
565    fn refresh_keeps_the_previous_result_until_replaced_or_cancelled() {
566        let task: Task<&'static str> = Task::new();
567        task.finish("first");
568
569        let handle = task.refresh();
570        assert_eq!(task.with(|state| state.latest().copied()), Some("first"));
571        assert!(handle.set_progress(0.5));
572        assert_eq!(task.progress(), Some(0.5));
573        assert_eq!(task.with(|state| state.latest().copied()), Some("first"));
574        assert!(handle.cancel());
575        assert_eq!(task.state(), TaskState::Ready("first"));
576
577        let handle = task.refresh();
578        assert!(handle.finish("second"));
579        assert_eq!(task.state(), TaskState::Ready("second"));
580
581        // A plain start drops the result.
582        task.start();
583        assert_eq!(task.with(|state| state.latest().copied()), None);
584    }
585
586    /// Poll a future to completion on this thread, parking between polls.
587    fn block_on<F: Future>(future: F) -> F::Output {
588        struct ThreadWaker(std::thread::Thread);
589        impl std::task::Wake for ThreadWaker {
590            fn wake(self: Arc<Self>) {
591                self.0.unpark();
592            }
593        }
594        let waker = std::task::Waker::from(Arc::new(ThreadWaker(std::thread::current())));
595        let mut context = std::task::Context::from_waker(&waker);
596        let mut future = std::pin::pin!(future);
597        loop {
598            if let std::task::Poll::Ready(output) = future.as_mut().poll(&mut context) {
599                return output;
600            }
601            std::thread::park();
602        }
603    }
604
605    #[test]
606    fn run_completes_the_task_from_a_future() {
607        let task: Task<u32> = Task::new();
608        let handle = task.start();
609        let progress = handle.clone();
610        let stored = block_on(handle.run(async move {
611            progress.set_progress(0.5);
612            Ok(42)
613        }));
614        assert!(stored);
615        assert_eq!(task.state(), TaskState::Ready(42));
616    }
617
618    #[test]
619    fn dropping_a_run_future_cancels_the_run() {
620        let task: Task<u32> = Task::new();
621        task.finish(1);
622        let run = task.refresh().run(std::future::pending());
623        assert!(task.is_loading());
624        drop(run);
625        assert_eq!(task.state(), TaskState::Ready(1));
626
627        // A superseded run's drop leaves the newer run alone.
628        let stale = task.start().run(std::future::pending());
629        let current = task.start();
630        drop(stale);
631        assert!(task.is_loading());
632        assert!(current.finish(2));
633    }
634
635    #[test]
636    fn changed_resolves_when_a_worker_finishes() {
637        let task: Task<u32> = Task::new();
638        let handle = task.start();
639        let changed = task.changed();
640        let worker = std::thread::spawn(move || {
641            std::thread::sleep(std::time::Duration::from_millis(20));
642            handle.finish(5);
643        });
644        let change = block_on(changed);
645        assert_eq!(change.source_id, task.source_id());
646        assert_eq!(task.state(), TaskState::Ready(5));
647        worker.join().unwrap();
648    }
649}