icedwright-probe 0.1.3

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
//! The interface a harness or the remote endpoint implements to control named tasks.
//!
//! The controller is installed for one thread with [`install`]. A [`Named`](crate::Named)
//! future looks for it on its first poll: with one it reports [`Controller::start`] and asks
//! [`Controller::gate`] on every poll; without one it runs as the plain future from then on.
//! Outputs cross this boundary as a [`Payload`] or a [`Replace`], which can only be built and
//! read through the task name they were made for.

use std::any::{Any, TypeId};
use std::cell::RefCell;
use std::fmt;
use std::future::Future;
use std::marker::PhantomData;
use std::panic::Location;
use std::pin::Pin;
use std::rc::Rc;
use std::task::{Context, Poll};

use crate::task::{Fallible, TaskName};

/// Identifies one named task to its controller. The controller chooses the number.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, PartialOrd, Ord)]
pub struct ProbeId(pub u64);

/// What a named task reports when it first runs under a controller.
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct ProbeMeta {
    /// [`TaskName::NAME`].
    pub name: &'static str,
    /// The name's type, for matching a typed rule.
    pub name_type: TypeId,
    /// The output's type name, for messages.
    pub output: &'static str,
    /// Where `N::task(..)` was called.
    pub location: &'static Location<'static>,
    /// Whether it was marked with [`NamedTask::external`](crate::NamedTask::external).
    pub external: bool,
    /// The [`NamedTask::detail`](crate::NamedTask::detail) text, if one was given.
    pub detail: Option<String>,
}

impl ProbeMeta {
    /// Whether the task was named `N`.
    #[must_use]
    pub fn is<N: TaskName>(&self) -> bool {
        self.name_type == TypeId::of::<N>()
    }
}

/// What a controller tells a named task to do on one poll.
#[derive(Debug)]
pub enum Gate {
    /// Poll the real future.
    Run,
    /// Stay pending. The controller keeps the waker and wakes it when the task may move.
    Hold,
    /// Finish with this output without polling the real future, which is dropped unpolled.
    Resolve(Payload),
}

/// How a named task ended.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
pub enum Finish {
    /// The real future finished.
    Completed,
    /// The controller's [`Gate::Resolve`] answered it.
    Resolved,
    /// It was dropped before it finished: an aborted task or a subscription that went away.
    Dropped,
}

/// Controls the named tasks polled on the thread it is installed for.
pub trait Controller {
    /// A named task's first poll. The returned id names it in every later call.
    fn start(&self, meta: ProbeMeta) -> ProbeId;

    /// Asked on every poll of a started task. For [`Gate::Hold`], keep `cx.waker()` and wake
    /// it when the task may move.
    fn gate(&self, id: ProbeId, cx: &mut Context<'_>) -> Gate;

    /// The real future finished. A [`Replace`] made for the same name changes its output.
    fn complete(&self, id: ProbeId) -> Option<Replace> {
        let _ = id;
        None
    }

    /// The task ended.
    fn finish(&self, id: ProbeId, how: Finish);

    /// A [`Gate::Resolve`] payload was made for another name. The task runs its real future
    /// instead, and the payload comes back here.
    fn rejected(&self, id: ProbeId, payload: Payload) {
        let _ = (id, payload);
    }

    /// A component declared a timer on the real clock through
    /// [`time::real_timer`](crate::time::real_timer).
    fn real_timer(&self, component: &'static str) {
        let _ = component;
    }
}

thread_local! {
    static CONTROLLER: RefCell<Option<Rc<dyn Controller>>> = const { RefCell::new(None) };
}

/// Installs a controller for the current thread until the guard is dropped, when the one it
/// replaced comes back.
#[must_use = "the controller is removed again when the guard is dropped"]
pub fn install(controller: Rc<dyn Controller>) -> Installed {
    let previous = CONTROLLER.with(|slot| slot.borrow_mut().replace(controller));
    Installed {
        previous,
        thread: PhantomData,
    }
}

/// Keeps a controller installed. Not `Send`: it must be dropped on the thread it installed on.
#[must_use = "the controller is removed again when the guard is dropped"]
pub struct Installed {
    previous: Option<Rc<dyn Controller>>,
    thread: PhantomData<Rc<()>>,
}

impl fmt::Debug for Installed {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        f.debug_struct("Installed")
            .field("restores_previous", &self.previous.is_some())
            .finish()
    }
}

impl Drop for Installed {
    fn drop(&mut self) {
        let previous = self.previous.take();
        CONTROLLER.with(|slot| *slot.borrow_mut() = previous);
    }
}

/// The controller installed for this thread, if any.
pub(crate) fn current() -> Option<Rc<dyn Controller>> {
    CONTROLLER.with(|slot| slot.borrow().clone())
}

/// A task output in transit, readable only as the name it was made for.
pub struct Payload {
    name: TypeId,
    name_str: &'static str,
    value: Box<dyn Any + Send>,
}

impl fmt::Debug for Payload {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        f.debug_struct("Payload")
            .field("name", &self.name_str)
            .finish_non_exhaustive()
    }
}

impl Payload {
    /// An output for tasks named `N`.
    pub fn new<N: TaskName>(output: N::Output) -> Self {
        Self {
            name: TypeId::of::<N>(),
            name_str: N::NAME,
            value: Box::new(output),
        }
    }

    /// A failure for tasks named `N`, whose output must be a `Result`.
    pub fn fail<N: Fallible>(error: N::Err) -> Self {
        Self::new::<N>(N::from_err(error))
    }

    /// The name it was made for.
    #[must_use]
    pub fn name(&self) -> &'static str {
        self.name_str
    }

    /// Whether it was made for `N`.
    #[must_use]
    pub fn is<N: TaskName>(&self) -> bool {
        self.name == TypeId::of::<N>()
    }

    /// The output, if it was made for `N`; otherwise the payload unchanged.
    pub fn take<N: TaskName>(self) -> Result<N::Output, Payload> {
        if !self.is::<N>() {
            return Err(self);
        }
        let Self {
            name,
            name_str,
            value,
        } = self;
        value
            .downcast::<N::Output>()
            .map(|output| *output)
            .map_err(|value| Payload {
                name,
                name_str,
                value,
            })
    }
}

type Map<T> = Box<dyn FnOnce(T) -> T>;

/// A change to the output of a task's real future, made for one name.
pub struct Replace {
    name: TypeId,
    name_str: &'static str,
    /// A `Map<N::Output>`, boxed again so it can be stored untyped.
    map: Box<dyn Any>,
}

impl fmt::Debug for Replace {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        f.debug_struct("Replace")
            .field("name", &self.name_str)
            .finish_non_exhaustive()
    }
}

impl Replace {
    /// Maps the output of tasks named `N`.
    pub fn new<N: TaskName>(map: impl FnOnce(N::Output) -> N::Output + 'static) -> Self {
        Self {
            name: TypeId::of::<N>(),
            name_str: N::NAME,
            map: Box::new(Box::new(map) as Map<N::Output>),
        }
    }

    /// The name it was made for.
    #[must_use]
    pub fn name(&self) -> &'static str {
        self.name_str
    }

    /// The mapped output if it was made for `N`, otherwise `output` unchanged.
    pub fn apply<N: TaskName>(self, output: N::Output) -> N::Output {
        if self.name != TypeId::of::<N>() {
            return output;
        }
        match self.map.downcast::<Map<N::Output>>() {
            Ok(map) => map(output),
            Err(_) => output,
        }
    }
}

/// The controller's view of one [`Named`](crate::Named) future.
pub(crate) struct Probe {
    location: &'static Location<'static>,
    pub(crate) external: bool,
    pub(crate) detail: Option<Box<dyn FnOnce() -> String + Send>>,
    state: State,
}

#[derive(Debug, Clone, Copy, PartialEq, Eq)]
enum State {
    Unstarted,
    Uncontrolled,
    Controlled(ProbeId),
    Done,
}

impl Probe {
    pub(crate) fn new(location: &'static Location<'static>) -> Self {
        Self {
            location,
            external: false,
            detail: None,
            state: State::Unstarted,
        }
    }

    pub(crate) fn poll<N, F>(
        &mut self,
        future: Pin<&mut F>,
        cx: &mut Context<'_>,
    ) -> Poll<N::Output>
    where
        N: TaskName,
        F: Future<Output = N::Output>,
    {
        if self.state == State::Unstarted {
            self.state = match current() {
                Some(controller) => State::Controlled(controller.start(ProbeMeta {
                    name: N::NAME,
                    name_type: TypeId::of::<N>(),
                    output: std::any::type_name::<N::Output>(),
                    location: self.location,
                    external: self.external,
                    detail: self.detail.take().map(|detail| detail()),
                })),
                None => State::Uncontrolled,
            };
        }
        let State::Controlled(id) = self.state else {
            return future.poll(cx);
        };
        let Some(controller) = current() else {
            self.state = State::Uncontrolled;
            return future.poll(cx);
        };
        match controller.gate(id, cx) {
            Gate::Hold => return Poll::Pending,
            Gate::Run => {}
            Gate::Resolve(payload) => match payload.take::<N>() {
                Ok(output) => {
                    self.state = State::Done;
                    controller.finish(id, Finish::Resolved);
                    return Poll::Ready(output);
                }
                Err(payload) => controller.rejected(id, payload),
            },
        }
        let Poll::Ready(output) = future.poll(cx) else {
            return Poll::Pending;
        };
        let output = match controller.complete(id) {
            Some(replace) => replace.apply::<N>(output),
            None => output,
        };
        self.state = State::Done;
        controller.finish(id, Finish::Completed);
        Poll::Ready(output)
    }

    pub(crate) fn dropped(&mut self) {
        let State::Controlled(id) = self.state else {
            return;
        };
        self.state = State::Done;
        if let Some(controller) = current() {
            controller.finish(id, Finish::Dropped);
        }
    }
}