icedwright-probe 0.1.4

What an iced app links for icedwright: semantic annotations, typed test ids and named tasks, all pass-through unless a feature turns them on
Documentation
//! Named tasks: a future wrapped with a name whose type fixes its output.

use std::future::Future;
#[cfg(feature = "control")]
use std::marker::PhantomData;
#[cfg(feature = "control")]
use std::pin::Pin;
#[cfg(feature = "control")]
use std::task::{Context, Poll};

/// A task name. Declare one with [`task_name!`](crate::task_name), never by hand.
///
/// The name is a type, so a test that answers `SaveNote` with a value of the wrong type does
/// not compile, and [`NAME`](TaskName::NAME) is the type's module path, so two names can only
/// share a string if they are the same type.
pub trait TaskName: Sized + 'static {
    /// What the named future returns.
    type Output: Send + 'static;

    /// The type's path, such as `notes::api::SaveNote`.
    const NAME: &'static str;

    /// Names a future. Its output must be this name's output. The one way to start a named
    /// task: `Task::perform(SaveNote::task(api.save(note)), Message::Saved)`.
    ///
    /// Without the `control` feature this returns `future` itself; with it, a [`Named`]
    /// wrapper a harness can control. Either way the type is opaque, so app code compiles the
    /// same in both.
    #[track_caller]
    #[inline]
    fn task<F>(future: F) -> impl NamedTask<Output = Self::Output> + Send + 'static
    where
        F: Future<Output = Self::Output> + Send + 'static,
    {
        #[cfg(feature = "control")]
        {
            Named::<Self, F>::new(future)
        }
        #[cfg(not(feature = "control"))]
        {
            future
        }
    }
}

/// What a named task offers beyond being a future. Bring it into scope to call
/// [`detail`](NamedTask::detail) or [`external`](NamedTask::external).
///
/// Without the `control` feature every future implements it and both methods return the
/// future unchanged. With `control` only [`Named`] does, so call them only on the value
/// [`TaskName::task`] returns.
pub trait NamedTask: Future + Sized {
    /// Text shown in traces and matched by tests, such as the id of the note being saved.
    /// The closure runs only under a harness.
    #[must_use = "a named task does nothing unless it is awaited or passed to `Task::perform`"]
    fn detail(self, detail: impl FnOnce() -> String + Send + 'static) -> Self;

    /// Marks the task as finished by a thread the harness does not own, such as the app's own
    /// worker. While it is in flight a harness waits for it rather than calling the app idle.
    #[must_use = "a named task does nothing unless it is awaited or passed to `Task::perform`"]
    fn external(self) -> Self;
}

#[cfg(not(feature = "control"))]
impl<F: Future> NamedTask for F {
    #[inline]
    fn detail(self, detail: impl FnOnce() -> String + Send + 'static) -> Self {
        let _ = detail;
        self
    }

    #[inline]
    fn external(self) -> Self {
        self
    }
}

/// A name whose output is a `Result`, so a test can fail it with the error type. Implemented
/// for every such name; asking to fail any other name does not compile.
pub trait Fallible: TaskName {
    /// The success type.
    type Ok: Send + 'static;
    /// The error type.
    type Err: Send + 'static;

    /// The output for a success.
    fn from_ok(value: Self::Ok) -> Self::Output;

    /// The output for a failure.
    fn from_err(error: Self::Err) -> Self::Output;
}

impl<N, T, E> Fallible for N
where
    N: TaskName<Output = Result<T, E>>,
    T: Send + 'static,
    E: Send + 'static,
{
    type Ok = T;
    type Err = E;

    #[inline]
    fn from_ok(value: T) -> Result<T, E> {
        Ok(value)
    }

    #[inline]
    fn from_err(error: E) -> Result<T, E> {
        Err(error)
    }
}

/// Declares task names: a unit struct for each, implementing [`TaskName`].
///
/// ```
/// # #[derive(Debug)] pub struct Note; #[derive(Debug)] pub struct ApiError;
/// icedwright_probe::task_name! {
///     pub ListNotes: Result<Vec<Note>, ApiError>;
///     pub SaveNote: Result<Note, ApiError>;
/// }
/// icedwright_probe::task_name!(pub PickFile: Option<std::path::PathBuf>);
/// ```
#[macro_export]
macro_rules! task_name {
    ($($(#[$meta:meta])* $vis:vis $name:ident : $output:ty);+ $(;)?) => {
        $(
            $(#[$meta])*
            #[derive(Debug, Clone, Copy, Default, PartialEq, Eq, Hash)]
            $vis struct $name;

            impl $crate::TaskName for $name {
                type Output = $output;
                const NAME: &'static str = ::core::concat!(
                    ::core::module_path!(),
                    "::",
                    ::core::stringify!($name)
                );
            }
        )+
    };
}

#[cfg(feature = "control")]
pin_project_lite::pin_project! {
    /// What [`TaskName::task`] returns with the `control` feature: a future with a name, which
    /// a harness can hold, answer without polling, or give a different output.
    #[must_use = "a named task does nothing unless it is awaited or passed to `Task::perform`"]
    pub struct Named<N, F> {
        #[pin]
        future: F,
        probe: crate::control::Probe,
        name: PhantomData<fn() -> N>,
    }

    impl<N, F> PinnedDrop for Named<N, F> {
        fn drop(this: Pin<&mut Self>) {
            this.project().probe.dropped();
        }
    }
}

#[cfg(feature = "control")]
impl<N: TaskName, F> std::fmt::Debug for Named<N, F> {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        f.debug_struct("Named")
            .field("name", &N::NAME)
            .finish_non_exhaustive()
    }
}

#[cfg(feature = "control")]
impl<N, F> Named<N, F> {
    #[track_caller]
    #[inline]
    fn new(future: F) -> Self {
        Self {
            future,
            probe: crate::control::Probe::new(std::panic::Location::caller()),
            name: PhantomData,
        }
    }
}

#[cfg(feature = "control")]
impl<N, F> NamedTask for Named<N, F>
where
    N: TaskName,
    F: Future<Output = N::Output>,
{
    #[inline]
    fn detail(mut self, detail: impl FnOnce() -> String + Send + 'static) -> Self {
        self.probe.detail = Some(Box::new(detail));
        self
    }

    #[inline]
    fn external(mut self) -> Self {
        self.probe.external = true;
        self
    }
}

#[cfg(feature = "control")]
impl<N, F> Future for Named<N, F>
where
    N: TaskName,
    F: Future<Output = N::Output>,
{
    type Output = N::Output;

    #[inline]
    fn poll(self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<N::Output> {
        let this = self.project();
        this.probe.poll::<N, F>(this.future, cx)
    }
}