Skip to main content

async_deferred/
lib.rs

1#![doc = include_str!("../README.md")]
2#![cfg_attr(not(feature = "std"), no_std)]
3
4extern crate alloc;
5
6mod embassy;
7mod spawner;
8
9#[doc(hidden)]
10pub mod __private {
11    pub use alloc::boxed::Box;
12}
13
14use alloc::string::String;
15use core::fmt;
16use core::future::Future;
17
18use futures_channel::oneshot;
19use futures_util::future::{AbortHandle, Abortable};
20
21#[cfg(feature = "smol")]
22pub use spawner::Smol;
23#[cfg(feature = "tokio")]
24pub use spawner::Tokio;
25pub use spawner::{LocalSpawner, Spawner};
26
27/// What the task sends back: the value and the callback's panic message, or the task's
28/// panic message.
29type Outcome<T> = Result<(T, Option<String>), String>;
30
31/// The state of a [`Deferred`] task.
32#[derive(Debug, Clone, Copy, PartialEq, Eq)]
33pub enum State {
34    /// No task has been started, or its result was taken.
35    NotStarted,
36    /// The task is running.
37    Pending,
38    /// The task finished and its result is available.
39    Completed,
40    /// The task panicked. See [`Deferred::panic_message`].
41    ///
42    /// Only reported with the `std` feature; without it, a panic is not caught.
43    TaskPanicked,
44    /// The task finished but its callback panicked. The result is still available.
45    /// See [`Deferred::panic_message`].
46    ///
47    /// Only reported with the `std` feature; without it, a panic is not caught.
48    CallbackPanicked,
49    /// The runtime dropped the task before it finished, for example on shutdown.
50    Cancelled,
51}
52
53/// Why [`Deferred::join`] has no result.
54#[derive(Debug, Clone, PartialEq, Eq)]
55pub enum Error {
56    /// No task has been started, or its result was taken.
57    NotStarted,
58    /// The task panicked. Contains the panic message.
59    Panicked(String),
60    /// The runtime dropped the task before it finished, for example on shutdown.
61    Cancelled,
62}
63
64impl fmt::Display for Error {
65    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
66        match self {
67            Error::NotStarted => f.write_str("no task has been started"),
68            Error::Panicked(msg) => write!(f, "task panicked: {msg}"),
69            Error::Cancelled => f.write_str("task was cancelled"),
70        }
71    }
72}
73
74#[cfg(feature = "std")]
75impl std::error::Error for Error {}
76
77#[derive(Debug)]
78enum Inner<T> {
79    NotStarted,
80    Running {
81        receiver: oneshot::Receiver<Outcome<T>>,
82        abort: AbortHandle,
83    },
84    Done {
85        value: T,
86        callback_panic: Option<String>,
87    },
88    Panicked(String),
89    Cancelled,
90}
91
92/// A background task whose result you can check or collect later.
93///
94/// Tasks run on any async runtime through a [`Spawner`]. With the default `tokio`
95/// feature, [`start`](Self::start) and [`begin`](Self::begin) spawn on the current
96/// Tokio runtime.
97///
98/// The result is kept until you [`take`](Self::take) it or drop the `Deferred`.
99/// Dropping a `Deferred` does not stop its task; use [`cancel`](Self::cancel) for that.
100///
101/// # Examples
102///
103/// ```rust
104/// use async_deferred::Deferred;
105///
106/// # tokio_test::block_on(async {
107/// let mut deferred = Deferred::start(async { 42 });
108///
109/// // ... do other work ...
110///
111/// assert_eq!(deferred.join().await, Ok(&42));
112/// # })
113/// ```
114#[derive(Debug)]
115pub struct Deferred<T> {
116    inner: Inner<T>,
117}
118
119impl<T> Deferred<T> {
120    /// Creates a `Deferred` with no task. Start one with [`begin_on`](Self::begin_on).
121    pub fn new() -> Self {
122        Self {
123            inner: Inner::NotStarted,
124        }
125    }
126
127    /// Spawns `future` with `spawner` and returns its `Deferred`.
128    ///
129    /// See [`Spawner`] for using your own runtime.
130    ///
131    /// ```rust
132    /// use async_deferred::Deferred;
133    ///
134    /// // Start a task from outside a Tokio runtime
135    /// let runtime = tokio::runtime::Runtime::new().unwrap();
136    /// let mut deferred = Deferred::start_on(runtime.handle(), async { 42 });
137    /// assert_eq!(runtime.block_on(deferred.join()), Ok(&42));
138    /// ```
139    pub fn start_on<S, F>(spawner: &S, future: F) -> Self
140    where
141        S: Spawner,
142        F: Future<Output = T> + Send + 'static,
143        T: Send + 'static,
144    {
145        let mut deferred = Self::new();
146        deferred.begin_on(spawner, future);
147        deferred
148    }
149
150    /// Like [`start_on`](Self::start_on), and runs `callback` with the result once
151    /// `future` finishes.
152    ///
153    /// The callback is not run if `future` panics.
154    pub fn start_with_callback_on<S, F, C>(spawner: &S, future: F, callback: C) -> Self
155    where
156        S: Spawner,
157        F: Future<Output = T> + Send + 'static,
158        C: FnOnce(&T) + Send + 'static,
159        T: Send + 'static,
160    {
161        let mut deferred = Self::new();
162        deferred.begin_with_callback_on(spawner, future, callback);
163        deferred
164    }
165
166    /// Spawns `future` with `spawner`.
167    ///
168    /// Returns `false` and does nothing if a task was already started and its result
169    /// has not been taken.
170    pub fn begin_on<S, F>(&mut self, spawner: &S, future: F) -> bool
171    where
172        S: Spawner,
173        F: Future<Output = T> + Send + 'static,
174        T: Send + 'static,
175    {
176        self.begin_with_callback_on(spawner, future, |_: &T| {})
177    }
178
179    /// Like [`begin_on`](Self::begin_on), and runs `callback` with the result once
180    /// `future` finishes.
181    ///
182    /// The callback is not run if `future` panics.
183    pub fn begin_with_callback_on<S, F, C>(&mut self, spawner: &S, future: F, callback: C) -> bool
184    where
185        S: Spawner,
186        F: Future<Output = T> + Send + 'static,
187        C: FnOnce(&T) + Send + 'static,
188        T: Send + 'static,
189    {
190        if !self.is_not_started() {
191            return false;
192        }
193        let (task, running) = task(future, callback);
194        spawner.spawn(task);
195        self.inner = running;
196        true
197    }
198
199    /// Like [`start_on`](Self::start_on), for futures that are not `Send`.
200    pub fn start_local_on<S, F>(spawner: &S, future: F) -> Self
201    where
202        S: LocalSpawner,
203        F: Future<Output = T> + 'static,
204        T: 'static,
205    {
206        let mut deferred = Self::new();
207        deferred.begin_local_on(spawner, future);
208        deferred
209    }
210
211    /// Like [`start_with_callback_on`](Self::start_with_callback_on), for futures that
212    /// are not `Send`.
213    pub fn start_with_callback_local_on<S, F, C>(spawner: &S, future: F, callback: C) -> Self
214    where
215        S: LocalSpawner,
216        F: Future<Output = T> + 'static,
217        C: FnOnce(&T) + 'static,
218        T: 'static,
219    {
220        let mut deferred = Self::new();
221        deferred.begin_with_callback_local_on(spawner, future, callback);
222        deferred
223    }
224
225    /// Like [`begin_on`](Self::begin_on), for futures that are not `Send`.
226    pub fn begin_local_on<S, F>(&mut self, spawner: &S, future: F) -> bool
227    where
228        S: LocalSpawner,
229        F: Future<Output = T> + 'static,
230        T: 'static,
231    {
232        self.begin_with_callback_local_on(spawner, future, |_: &T| {})
233    }
234
235    /// Like [`begin_with_callback_on`](Self::begin_with_callback_on), for futures that
236    /// are not `Send`.
237    pub fn begin_with_callback_local_on<S, F, C>(
238        &mut self,
239        spawner: &S,
240        future: F,
241        callback: C,
242    ) -> bool
243    where
244        S: LocalSpawner,
245        F: Future<Output = T> + 'static,
246        C: FnOnce(&T) + 'static,
247        T: 'static,
248    {
249        if !self.is_not_started() {
250            return false;
251        }
252        let (task, running) = task(future, callback);
253        spawner.spawn_local(task);
254        self.inner = running;
255        true
256    }
257
258    /// If the task has finished, stores its outcome. Never waits.
259    fn poll_task(&mut self) {
260        let Inner::Running { receiver, .. } = &mut self.inner else {
261            return;
262        };
263        match receiver.try_recv() {
264            Ok(None) => {}
265            Ok(Some(outcome)) => self.inner = Inner::finished(Some(outcome)),
266            Err(oneshot::Canceled) => self.inner = Inner::finished(None),
267        }
268    }
269
270    /// Waits for the task to finish and returns its result.
271    ///
272    /// Returns immediately if the task already finished. If the task finished but its
273    /// callback panicked, the result is still returned; check [`state`](Self::state)
274    /// to detect that.
275    ///
276    /// ```rust
277    /// use async_deferred::{Deferred, Error};
278    ///
279    /// # tokio_test::block_on(async {
280    /// let mut deferred: Deferred<u32> = Deferred::start(async { panic!("boom") });
281    /// assert_eq!(deferred.join().await, Err(Error::Panicked("boom".into())));
282    /// # })
283    /// ```
284    pub async fn join(&mut self) -> Result<&T, Error> {
285        if let Inner::Running { receiver, .. } = &mut self.inner {
286            let outcome = receiver.await.ok();
287            self.inner = Inner::finished(outcome);
288        }
289        match &self.inner {
290            Inner::Done { value, .. } => Ok(value),
291            Inner::Panicked(msg) => Err(Error::Panicked(msg.clone())),
292            Inner::Cancelled => Err(Error::Cancelled),
293            Inner::NotStarted => Err(Error::NotStarted),
294            Inner::Running { .. } => unreachable!("the task was awaited above"),
295        }
296    }
297
298    /// Returns the current [`State`] without waiting.
299    pub fn state(&mut self) -> State {
300        self.poll_task();
301        match &self.inner {
302            Inner::NotStarted => State::NotStarted,
303            Inner::Running { .. } => State::Pending,
304            Inner::Done {
305                callback_panic: None,
306                ..
307            } => State::Completed,
308            Inner::Done {
309                callback_panic: Some(_),
310                ..
311            } => State::CallbackPanicked,
312            Inner::Panicked(_) => State::TaskPanicked,
313            Inner::Cancelled => State::Cancelled,
314        }
315    }
316
317    /// Returns the panic message if the task or its callback panicked.
318    pub fn panic_message(&mut self) -> Option<&str> {
319        self.poll_task();
320        match &self.inner {
321            Inner::Panicked(msg)
322            | Inner::Done {
323                callback_panic: Some(msg),
324                ..
325            } => Some(msg),
326            _ => None,
327        }
328    }
329
330    /// Returns the result if the task has finished, without waiting.
331    pub fn try_get(&mut self) -> Option<&T> {
332        self.poll_task();
333        match &self.inner {
334            Inner::Done { value, .. } => Some(value),
335            _ => None,
336        }
337    }
338
339    /// Moves the result out if the task has finished, without waiting.
340    ///
341    /// On success, the `Deferred` is reset and can start a new task.
342    ///
343    /// ```rust
344    /// use async_deferred::{Deferred, State};
345    ///
346    /// # tokio_test::block_on(async {
347    /// let mut deferred = Deferred::start(async { vec![1, 2, 3] });
348    /// deferred.join().await.unwrap();
349    /// assert_eq!(deferred.take(), Some(vec![1, 2, 3]));
350    /// assert_eq!(deferred.state(), State::NotStarted);
351    /// # })
352    /// ```
353    pub fn take(&mut self) -> Option<T> {
354        self.poll_task();
355        if !matches!(self.inner, Inner::Done { .. }) {
356            return None;
357        }
358        match core::mem::replace(&mut self.inner, Inner::NotStarted) {
359            Inner::Done { value, .. } => Some(value),
360            _ => unreachable!("checked above"),
361        }
362    }
363
364    /// Stops a running task and resets the `Deferred` so it can start a new one.
365    ///
366    /// The task stops the next time the runtime polls it.
367    /// Returns `false` and does nothing if no task is running.
368    ///
369    /// ```rust
370    /// use async_deferred::{Deferred, State};
371    ///
372    /// # tokio_test::block_on(async {
373    /// let mut deferred = Deferred::start(std::future::pending::<u32>());
374    /// assert!(deferred.cancel());
375    /// assert_eq!(deferred.state(), State::NotStarted);
376    /// # })
377    /// ```
378    pub fn cancel(&mut self) -> bool {
379        self.poll_task();
380        let Inner::Running { abort, .. } = &self.inner else {
381            return false;
382        };
383        abort.abort();
384        self.inner = Inner::NotStarted;
385        true
386    }
387
388    /// Returns `true` if the result is available, even if the callback panicked.
389    pub fn is_ready(&mut self) -> bool {
390        self.try_get().is_some()
391    }
392
393    /// Returns `true` if the task and its callback finished without panicking.
394    pub fn is_complete(&mut self) -> bool {
395        self.state() == State::Completed
396    }
397
398    /// Returns `true` if the task is still running.
399    pub fn is_pending(&mut self) -> bool {
400        self.state() == State::Pending
401    }
402
403    /// Returns `true` if no task has been started, or its result was taken.
404    pub fn is_not_started(&mut self) -> bool {
405        self.state() == State::NotStarted
406    }
407
408    /// Returns `true` if the task panicked.
409    pub fn has_task_panicked(&mut self) -> bool {
410        self.state() == State::TaskPanicked
411    }
412}
413
414#[cfg(feature = "tokio")]
415impl<T> Deferred<T> {
416    /// Spawns `future` on the current Tokio runtime and returns its `Deferred`.
417    ///
418    /// # Panics
419    ///
420    /// Panics if called outside a Tokio runtime. Use [`start_on`](Self::start_on) with a
421    /// [`tokio::runtime::Handle`] there.
422    pub fn start<F>(future: F) -> Self
423    where
424        F: Future<Output = T> + Send + 'static,
425        T: Send + 'static,
426    {
427        Self::start_on(&Tokio, future)
428    }
429
430    /// Like [`start`](Self::start), and runs `callback` with the result once `future` finishes.
431    ///
432    /// The callback is not run if `future` panics.
433    ///
434    /// ```rust
435    /// use async_deferred::Deferred;
436    ///
437    /// # tokio_test::block_on(async {
438    /// let deferred = Deferred::start_with_callback(
439    ///     async { 42 },
440    ///     |result| println!("computed {result}"),
441    /// );
442    /// # })
443    /// ```
444    pub fn start_with_callback<F, C>(future: F, callback: C) -> Self
445    where
446        F: Future<Output = T> + Send + 'static,
447        C: FnOnce(&T) + Send + 'static,
448        T: Send + 'static,
449    {
450        Self::start_with_callback_on(&Tokio, future, callback)
451    }
452
453    /// Spawns `future` on the current Tokio runtime.
454    ///
455    /// Returns `false` and does nothing if a task was already started and its result
456    /// has not been taken.
457    ///
458    /// # Panics
459    ///
460    /// Panics if called outside a Tokio runtime.
461    ///
462    /// ```rust
463    /// use async_deferred::Deferred;
464    ///
465    /// # tokio_test::block_on(async {
466    /// let mut deferred = Deferred::new();
467    /// assert!(deferred.begin(async { 42 }));
468    /// assert!(!deferred.begin(async { 24 }));
469    /// # })
470    /// ```
471    pub fn begin<F>(&mut self, future: F) -> bool
472    where
473        F: Future<Output = T> + Send + 'static,
474        T: Send + 'static,
475    {
476        self.begin_on(&Tokio, future)
477    }
478
479    /// Like [`begin`](Self::begin), and runs `callback` with the result once `future` finishes.
480    ///
481    /// The callback is not run if `future` panics.
482    pub fn begin_with_callback<F, C>(&mut self, future: F, callback: C) -> bool
483    where
484        F: Future<Output = T> + Send + 'static,
485        C: FnOnce(&T) + Send + 'static,
486        T: Send + 'static,
487    {
488        self.begin_with_callback_on(&Tokio, future, callback)
489    }
490}
491
492impl<T> Default for Deferred<T> {
493    /// Same as [`Deferred::new`].
494    fn default() -> Self {
495        Self::new()
496    }
497}
498
499impl<T> Inner<T> {
500    /// `None` means the task was dropped before sending its outcome.
501    fn finished(outcome: Option<Outcome<T>>) -> Self {
502        match outcome {
503            Some(Ok((value, callback_panic))) => Inner::Done {
504                value,
505                callback_panic,
506            },
507            Some(Err(msg)) => Inner::Panicked(msg),
508            None => Inner::Cancelled,
509        }
510    }
511}
512
513/// Builds the task to spawn, and the `Running` state that tracks it.
514///
515/// The task is `Send` whenever `F`, `C` and `T` are.
516fn task<T, F, C>(future: F, callback: C) -> (impl Future<Output = ()>, Inner<T>)
517where
518    F: Future<Output = T> + 'static,
519    C: FnOnce(&T) + 'static,
520    T: 'static,
521{
522    let (sender, receiver) = oneshot::channel();
523    let (abort, abort_registration) = AbortHandle::new_pair();
524    let task = Abortable::new(
525        async move {
526            let outcome = match catch_unwind(future).await {
527                Ok(value) => {
528                    // Catch a callback panic so the computed value is not lost with it.
529                    let callback_panic = call_catching_panic(callback, &value).err();
530                    Ok((value, callback_panic))
531                }
532                Err(msg) => Err(msg),
533            };
534            // The `Deferred` may have been dropped; the result is then discarded.
535            let _ = sender.send(outcome);
536        },
537        abort_registration,
538    );
539    let task = async move {
540        let _ = task.await;
541    };
542    (task, Inner::Running { receiver, abort })
543}
544
545/// Awaits `future`, turning a panic into its message.
546#[cfg(feature = "std")]
547async fn catch_unwind<F: Future>(future: F) -> Result<F::Output, String> {
548    use futures_util::FutureExt;
549    std::panic::AssertUnwindSafe(future)
550        .catch_unwind()
551        .await
552        .map_err(|payload| panic_message(&*payload))
553}
554
555/// Awaits `future`. Without `std`, panics cannot be caught.
556#[cfg(not(feature = "std"))]
557async fn catch_unwind<F: Future>(future: F) -> Result<F::Output, String> {
558    Ok(future.await)
559}
560
561/// Calls `callback`, turning a panic into its message.
562#[cfg(feature = "std")]
563fn call_catching_panic<T, C: FnOnce(&T)>(callback: C, value: &T) -> Result<(), String> {
564    std::panic::catch_unwind(std::panic::AssertUnwindSafe(|| callback(value)))
565        .map_err(|payload| panic_message(&*payload))
566}
567
568/// Calls `callback`. Without `std`, panics cannot be caught.
569#[cfg(not(feature = "std"))]
570fn call_catching_panic<T, C: FnOnce(&T)>(callback: C, value: &T) -> Result<(), String> {
571    callback(value);
572    Ok(())
573}
574
575/// Extracts a readable message from a panic payload.
576#[cfg(feature = "std")]
577fn panic_message(payload: &(dyn std::any::Any + Send)) -> String {
578    if let Some(s) = payload.downcast_ref::<&str>() {
579        s.to_string()
580    } else if let Some(s) = payload.downcast_ref::<String>() {
581        s.clone()
582    } else {
583        "unknown panic payload".to_string()
584    }
585}