zwire 0.4.0

Zero-dependency, no_std-compatible transactional reactive state engine: scoped push-pull arena, rebaseable optimistic layers + STM drafts, exact incremental Top-K collections, and open @zwire/core wire protocols
Documentation
//! Executor-agnostic `#![no_std]` asynchronous reactive [`Resource<T, E, K>`].
use alloc::boxed::Box;
use alloc::rc::Rc;
use core::cell::Cell;
use core::fmt;
use core::future::{Future, poll_fn};
use core::mem::DropGuard;
use core::pin::Pin;
use core::task::Poll;

use zwire_core::{Atom, Scope, Signal};

/// Reactive lifecycle state of an asynchronous [`Resource`].
#[derive(Debug, Clone, PartialEq, Eq)]
pub enum ResourceState<T, E> {
    /// Initial load is in progress with no previously loaded value.
    Pending,
    /// A reload is in progress while preserving the last loaded value.
    Refreshing(T),
    /// A loaded value is available.
    Ready(T),
    /// The latest load failed, optionally preserving the last loaded value.
    Error {
        /// Error returned by the loader.
        error: E,
        /// Last known good value before this error, if any.
        previous: Option<T>,
    },
    /// The resource has been disposed and will ignore further completions.
    Disposed,
}

impl<T, E> ResourceState<T, E> {
    /// Returns `true` when the resource is currently loading (`Pending` or `Refreshing`).
    #[inline]
    pub const fn is_pending(&self) -> bool {
        matches!(self, Self::Pending | Self::Refreshing(_))
    }

    /// Returns `true` when the resource holds a fresh `Ready` value.
    #[inline]
    pub const fn is_ready(&self) -> bool {
        matches!(self, Self::Ready(_))
    }

    /// Returns `true` when the resource is in the `Error` state.
    #[inline]
    pub const fn is_error(&self) -> bool {
        matches!(self, Self::Error { .. })
    }

    /// Returns `true` when the resource has been disposed.
    #[inline]
    pub const fn is_disposed(&self) -> bool {
        matches!(self, Self::Disposed)
    }

    /// Borrows the latest known good value (`Ready`, `Refreshing`, or `Error.previous`).
    #[inline]
    pub const fn latest(&self) -> Option<&T> {
        match self {
            Self::Ready(v)
            | Self::Refreshing(v)
            | Self::Error {
                previous: Some(v), ..
            } => Some(v),
            Self::Pending | Self::Error { previous: None, .. } | Self::Disposed => None,
        }
    }

    /// Borrows the current error if in the `Error` state.
    #[inline]
    pub const fn error(&self) -> Option<&E> {
        match self {
            Self::Error { error, .. } => Some(error),
            _ => None,
        }
    }
}

/// Executor-agnostic asynchronous reactive resource driven by a reactive `source` signal.
///
/// Tracks a monotonic `u64` request generation so stale or out-of-order completions from
/// superseded requests are automatically ignored, and [`Self::drive`] drops in-flight futures
/// whenever `source` changes or [`Self::refetch`] is called.
pub struct Resource<T: 'static, E: 'static, K: 'static = ()> {
    scope: Scope,
    source: Signal<K>,
    state: Atom<ResourceState<T, E>>,
    trigger: Atom<u64>,
    generation: Rc<Cell<u64>>,
    disposed: Rc<Cell<bool>>,
    owns_source: bool,
}

impl<T: 'static, E: 'static, K: 'static> Clone for Resource<T, E, K> {
    fn clone(&self) -> Self {
        Self {
            scope: self.scope.clone(),
            source: self.source,
            state: self.state,
            trigger: self.trigger,
            generation: Rc::clone(&self.generation),
            disposed: Rc::clone(&self.disposed),
            owns_source: self.owns_source,
        }
    }
}

impl<T: 'static, E: 'static, K: 'static> fmt::Debug for Resource<T, E, K> {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        f.debug_struct("Resource")
            .field("source", &self.source)
            .field("state", &self.state)
            .field("generation", &self.generation.get())
            .field("disposed", &self.disposed.get())
            .finish_non_exhaustive()
    }
}

impl<T: PartialEq + 'static, E: PartialEq + 'static> Resource<T, E, ()> {
    /// Creates a keyless [`Resource<T, E>`] triggered only on initial drive and [`Self::refetch`].
    pub fn stateless(scope: &Scope) -> Self {
        let source = scope.atom(());
        Self {
            scope: scope.clone(),
            source: source.as_signal(),
            state: scope.atom(ResourceState::Pending),
            trigger: scope.atom(0u64),
            generation: Rc::new(Cell::new(0)),
            disposed: Rc::new(Cell::new(false)),
            owns_source: true,
        }
    }
}

impl<T: PartialEq + 'static, E: PartialEq + 'static, K: 'static> Resource<T, E, K> {
    /// Creates a new [`Resource`] starting in [`ResourceState::Pending`] and keyed by `source`.
    pub fn new(scope: &Scope, source: impl Into<Signal<K>>) -> Self {
        Self {
            scope: scope.clone(),
            source: source.into(),
            state: scope.atom(ResourceState::Pending),
            trigger: scope.atom(0u64),
            generation: Rc::new(Cell::new(0)),
            disposed: Rc::new(Cell::new(false)),
            owns_source: false,
        }
    }

    /// Creates a new [`Resource`] pre-populated in [`ResourceState::Ready`].
    pub fn with_initial(scope: &Scope, source: impl Into<Signal<K>>, initial: T) -> Self {
        Self {
            scope: scope.clone(),
            source: source.into(),
            state: scope.atom(ResourceState::Ready(initial)),
            trigger: scope.atom(0u64),
            generation: Rc::new(Cell::new(0)),
            disposed: Rc::new(Cell::new(false)),
            owns_source: false,
        }
    }

    /// Returns the reactive [`Atom<ResourceState<T, E>>`] holding the current lifecycle state.
    #[inline]
    pub const fn state(&self) -> Atom<ResourceState<T, E>> {
        self.state
    }

    /// Returns the monotonic request generation counter.
    #[inline]
    pub fn generation(&self) -> u64 {
        self.generation.get()
    }

    /// Returns the latest known good value, if any.
    pub fn latest(&self) -> Option<T>
    where
        T: Clone,
    {
        self.scope
            .try_with(self.state, |s| s.latest().cloned())
            .ok()
            .flatten()
    }

    /// Returns `true` when the resource is currently `Pending` or `Refreshing`.
    pub fn is_pending(&self) -> bool {
        self.scope
            .try_with(self.state, ResourceState::is_pending)
            .unwrap_or(false)
    }

    /// Requests a reload from any active [`Self::drive`] loop without changing `source`.
    pub fn refetch(&self) {
        if self.disposed.get() {
            return;
        }
        self.scope.update(self.trigger, |rev| rev + 1);
    }

    /// Optimistically or imperatively sets the resource to [`ResourceState::Ready`] and advances
    /// the generation counter so any currently in-flight request is ignored upon completion.
    pub fn mutate(&self, value: T) {
        if self.disposed.get() {
            return;
        }
        self.generation.set(self.generation.get() + 1);
        self.scope.set(self.state, ResourceState::Ready(value));
    }

    /// Transitions the resource to [`ResourceState::Disposed`], cancels any active [`Self::drive`]
    /// loop, and invalidates all in-flight requests. Safe to call repeatedly.
    pub fn dispose(&self) {
        if self.disposed.replace(true) {
            return;
        }
        self.generation.set(self.generation.get() + 1);
        self.scope.set(self.state, ResourceState::Disposed);
        let _ = self.scope.dispose(self.trigger);
        if self.owns_source {
            let _ = self.scope.dispose(self.source);
        }
    }

    fn begin_request(&self) -> Option<u64>
    where
        T: Clone,
    {
        if self.disposed.get() {
            return None;
        }
        let next_gen = self.generation.get() + 1;
        self.generation.set(next_gen);
        let prev = self.latest();
        let next_state = match prev {
            Some(v) => ResourceState::Refreshing(v),
            None => ResourceState::Pending,
        };
        self.scope.set(self.state, next_state);
        Some(next_gen)
    }

    fn finish_request(&self, request_gen: u64, result: Result<T, E>)
    where
        T: Clone,
    {
        if self.disposed.get() || self.generation.get() != request_gen {
            return;
        }
        let next_state = match result {
            Ok(value) => ResourceState::Ready(value),
            Err(error) => ResourceState::Error {
                error,
                previous: self.latest(),
            },
        };
        self.scope.set(self.state, next_state);
    }

    /// Runs a single generation-guarded load for the current `source` value.
    ///
    /// If another [`Self::load`], [`Self::mutate`], [`Self::refetch`], or [`Self::dispose`]
    /// advances the generation before `loader` resolves, this completion is discarded.
    #[expect(
        clippy::future_not_send,
        reason = "local Scope and Rc state are confined to their executor thread"
    )]
    pub async fn load<F, Fut>(&self, loader: F)
    where
        T: Clone,
        K: Clone,
        F: FnOnce(K) -> Fut,
        Fut: Future<Output = Result<T, E>>,
    {
        let Ok(key) = self.scope.try_get(self.source) else {
            return;
        };
        let Some(request_gen) = self.begin_request() else {
            return;
        };
        let result = loader(key).await;
        self.finish_request(request_gen, result);
    }

    /// Continuously drives this resource on any async executor using [`Scope::changes`].
    ///
    /// Loads immediately for the initial `source` value, and whenever `source` changes or
    /// [`Self::refetch`] is called, drops any still-pending future (cancelling it) and starts a
    /// fresh load. Ends cleanly when [`Self::dispose`] is called or `source` is disposed.
    #[expect(
        clippy::future_not_send,
        reason = "local Scope and Rc state are confined to their executor thread"
    )]
    pub async fn drive<F, Fut>(&self, mut loader: F)
    where
        T: Clone,
        K: Clone + PartialEq,
        F: FnMut(K) -> Fut,
        Fut: Future<Output = Result<T, E>>,
    {
        if self.disposed.get() {
            return;
        }
        let source = self.source;
        let trigger = self.trigger;
        let request_key = self.scope.computed(move |cx| {
            let rev = cx.try_get(trigger).ok()?;
            let key = cx.try_get(source).ok()?;
            Some((rev, key))
        });
        let scope_cleanup = self.scope.clone();
        let _cleanup = DropGuard::new(request_key, move |comp| {
            let _ = scope_cleanup.dispose(comp);
        });

        let mut changes = self.scope.changes(request_key);
        let Ok(init_key) = self.scope.try_get(source) else {
            return;
        };
        let mut in_flight: Option<(u64, Pin<Box<Fut>>)> = self
            .begin_request()
            .map(|request_gen| (request_gen, Box::pin(loader(init_key))));

        poll_fn(|cx| {
            loop {
                if self.disposed.get() {
                    in_flight = None;
                    return Poll::Ready(());
                }
                match changes.poll_next(cx) {
                    Poll::Ready(Some(Ok(snapshot))) => {
                        let Some((_, next_key)) = snapshot.as_ref() else {
                            in_flight = None;
                            return Poll::Ready(());
                        };
                        let next_key = next_key.clone();
                        in_flight = self
                            .begin_request()
                            .map(|request_gen| (request_gen, Box::pin(loader(next_key))));
                        continue;
                    }
                    Poll::Ready(Some(Err(_)) | None) => {
                        in_flight = None;
                        return Poll::Ready(());
                    }
                    Poll::Pending => {}
                }
                if let Some((request_gen, fut)) = in_flight.as_mut() {
                    match fut.as_mut().poll(cx) {
                        Poll::Ready(result) => {
                            let finished_gen = *request_gen;
                            in_flight = None;
                            self.finish_request(finished_gen, result);
                            continue;
                        }
                        Poll::Pending => return Poll::Pending,
                    }
                }
                return Poll::Pending;
            }
        })
        .await;
    }
}