Skip to main content

icedwright_probe/
task.rs

1//! Named tasks: a future wrapped with a name whose type fixes its output.
2
3use std::future::Future;
4#[cfg(feature = "control")]
5use std::marker::PhantomData;
6#[cfg(feature = "control")]
7use std::pin::Pin;
8#[cfg(feature = "control")]
9use std::task::{Context, Poll};
10
11/// A task name. Declare one with [`task_name!`](crate::task_name), never by hand.
12///
13/// The name is a type, so a test that answers `SaveNote` with a value of the wrong type does
14/// not compile, and [`NAME`](TaskName::NAME) is the type's module path, so two names can only
15/// share a string if they are the same type.
16pub trait TaskName: Sized + 'static {
17    /// What the named future returns.
18    type Output: Send + 'static;
19
20    /// The type's path, such as `notes::api::SaveNote`.
21    const NAME: &'static str;
22
23    /// Names a future. Its output must be this name's output. The one way to start a named
24    /// task: `Task::perform(SaveNote::task(api.save(note)), Message::Saved)`.
25    ///
26    /// Without the `control` feature this returns `future` itself; with it, a [`Named`]
27    /// wrapper a harness can control. Either way the type is opaque, so app code compiles the
28    /// same in both.
29    #[track_caller]
30    #[inline]
31    fn task<F>(future: F) -> impl NamedTask<Output = Self::Output> + Send + 'static
32    where
33        F: Future<Output = Self::Output> + Send + 'static,
34    {
35        #[cfg(feature = "control")]
36        {
37            Named::<Self, F>::new(future)
38        }
39        #[cfg(not(feature = "control"))]
40        {
41            future
42        }
43    }
44}
45
46/// What a named task offers beyond being a future. Bring it into scope to call
47/// [`detail`](NamedTask::detail) or [`external`](NamedTask::external).
48///
49/// Without the `control` feature every future implements it and both methods return the
50/// future unchanged. With `control` only [`Named`] does, so call them only on the value
51/// [`TaskName::task`] returns.
52pub trait NamedTask: Future + Sized {
53    /// Text shown in traces and matched by tests, such as the id of the note being saved.
54    /// The closure runs only under a harness.
55    #[must_use = "a named task does nothing unless it is awaited or passed to `Task::perform`"]
56    fn detail(self, detail: impl FnOnce() -> String + Send + 'static) -> Self;
57
58    /// Marks the task as finished by a thread the harness does not own, such as the app's own
59    /// worker. While it is in flight a harness waits for it rather than calling the app idle.
60    #[must_use = "a named task does nothing unless it is awaited or passed to `Task::perform`"]
61    fn external(self) -> Self;
62}
63
64#[cfg(not(feature = "control"))]
65impl<F: Future> NamedTask for F {
66    #[inline]
67    fn detail(self, detail: impl FnOnce() -> String + Send + 'static) -> Self {
68        let _ = detail;
69        self
70    }
71
72    #[inline]
73    fn external(self) -> Self {
74        self
75    }
76}
77
78/// A name whose output is a `Result`, so a test can fail it with the error type. Implemented
79/// for every such name; asking to fail any other name does not compile.
80pub trait Fallible: TaskName {
81    /// The success type.
82    type Ok: Send + 'static;
83    /// The error type.
84    type Err: Send + 'static;
85
86    /// The output for a success.
87    fn from_ok(value: Self::Ok) -> Self::Output;
88
89    /// The output for a failure.
90    fn from_err(error: Self::Err) -> Self::Output;
91}
92
93impl<N, T, E> Fallible for N
94where
95    N: TaskName<Output = Result<T, E>>,
96    T: Send + 'static,
97    E: Send + 'static,
98{
99    type Ok = T;
100    type Err = E;
101
102    #[inline]
103    fn from_ok(value: T) -> Result<T, E> {
104        Ok(value)
105    }
106
107    #[inline]
108    fn from_err(error: E) -> Result<T, E> {
109        Err(error)
110    }
111}
112
113/// Declares task names: a unit struct for each, implementing [`TaskName`].
114///
115/// ```
116/// # #[derive(Debug)] pub struct Note; #[derive(Debug)] pub struct ApiError;
117/// icedwright_probe::task_name! {
118///     pub ListNotes: Result<Vec<Note>, ApiError>;
119///     pub SaveNote: Result<Note, ApiError>;
120/// }
121/// icedwright_probe::task_name!(pub PickFile: Option<std::path::PathBuf>);
122/// ```
123#[macro_export]
124macro_rules! task_name {
125    ($($(#[$meta:meta])* $vis:vis $name:ident : $output:ty);+ $(;)?) => {
126        $(
127            $(#[$meta])*
128            #[derive(Debug, Clone, Copy, Default, PartialEq, Eq, Hash)]
129            $vis struct $name;
130
131            impl $crate::TaskName for $name {
132                type Output = $output;
133                const NAME: &'static str = ::core::concat!(
134                    ::core::module_path!(),
135                    "::",
136                    ::core::stringify!($name)
137                );
138            }
139        )+
140    };
141}
142
143#[cfg(feature = "control")]
144pin_project_lite::pin_project! {
145    /// What [`TaskName::task`] returns with the `control` feature: a future with a name, which
146    /// a harness can hold, answer without polling, or give a different output.
147    #[must_use = "a named task does nothing unless it is awaited or passed to `Task::perform`"]
148    pub struct Named<N, F> {
149        #[pin]
150        future: F,
151        probe: crate::control::Probe,
152        name: PhantomData<fn() -> N>,
153    }
154
155    impl<N, F> PinnedDrop for Named<N, F> {
156        fn drop(this: Pin<&mut Self>) {
157            this.project().probe.dropped();
158        }
159    }
160}
161
162#[cfg(feature = "control")]
163impl<N: TaskName, F> std::fmt::Debug for Named<N, F> {
164    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
165        f.debug_struct("Named")
166            .field("name", &N::NAME)
167            .finish_non_exhaustive()
168    }
169}
170
171#[cfg(feature = "control")]
172impl<N, F> Named<N, F> {
173    #[track_caller]
174    #[inline]
175    fn new(future: F) -> Self {
176        Self {
177            future,
178            probe: crate::control::Probe::new(std::panic::Location::caller()),
179            name: PhantomData,
180        }
181    }
182}
183
184#[cfg(feature = "control")]
185impl<N, F> NamedTask for Named<N, F>
186where
187    N: TaskName,
188    F: Future<Output = N::Output>,
189{
190    #[inline]
191    fn detail(mut self, detail: impl FnOnce() -> String + Send + 'static) -> Self {
192        self.probe.detail = Some(Box::new(detail));
193        self
194    }
195
196    #[inline]
197    fn external(mut self) -> Self {
198        self.probe.external = true;
199        self
200    }
201}
202
203#[cfg(feature = "control")]
204impl<N, F> Future for Named<N, F>
205where
206    N: TaskName,
207    F: Future<Output = N::Output>,
208{
209    type Output = N::Output;
210
211    #[inline]
212    fn poll(self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<N::Output> {
213        let this = self.project();
214        this.probe.poll::<N, F>(this.future, cx)
215    }
216}