moonproof-utils 0.2.2

Shared helpers (hex parsing, validation) used across moonproof crates. Mirror of midnight-js/packages/utils.
Documentation
//! Generic "latest-snapshot" state cell over `tokio::sync::watch`.
//!
//! Single source of truth for the "hold a value, broadcast on
//! change, let consumers pull snapshots" pattern. Used by
//! [`moonproof_wallet::runtime::WalletRuntime`] (over `FacadeState`)
//! and [`moonproof_runtime::sync::Watcher`] (over `ContractRuntimeState`).
//! Each consumer composes its own cancel/lifecycle on top — this
//! primitive only owns the state + change broadcast.
//!
//! Distinct from [`crate::events::EventBus`], which is a per-event
//! firehose (broadcast). State cell is "latest value + change
//! signal" (watch). Pick whichever fits the domain — they don't
//! overlap.

use std::sync::Arc;

use tokio::sync::{watch, RwLock};

/// Holds the current value of `T` behind an `Arc<RwLock>`, plus a
/// `tokio::sync::watch` channel that fires every time the value
/// changes. Cheap to clone — the inner state + sender are
/// `Arc`-shared.
#[derive(Debug)]
pub struct StateCell<T: Clone + Send + Sync + 'static> {
    state: Arc<RwLock<T>>,
    changes_tx: watch::Sender<T>,
}

impl<T: Clone + Send + Sync + 'static> Clone for StateCell<T> {
    fn clone(&self) -> Self {
        Self {
            state: Arc::clone(&self.state),
            changes_tx: self.changes_tx.clone(),
        }
    }
}

impl<T: Clone + Send + Sync + 'static> StateCell<T> {
    /// Wrap an initial value. The initial value is also the watch
    /// channel's first observed snapshot — new subscribers see it
    /// via `borrow_and_update`.
    pub fn new(initial: T) -> Self {
        let (changes_tx, _) = watch::channel(initial.clone());
        Self {
            state: Arc::new(RwLock::new(initial)),
            changes_tx,
        }
    }

    /// Cheap clone of the current value.
    pub async fn current(&self) -> T {
        self.state.read().await.clone()
    }

    /// Subscribe to value changes. Receivers' initial value is the
    /// state at subscribe time — call `borrow_and_update` to read
    /// without registering a "changed" notification.
    pub fn changes(&self) -> watch::Receiver<T> {
        self.changes_tx.subscribe()
    }

    /// Atomically transform the state. The closure receives ownership
    /// of the previous value and returns `Result<T, E>`; on `Ok` the
    /// new value is stored and broadcast; on `Err` the previous value
    /// is preserved and the error is returned.
    ///
    /// Holds the write lock for the duration of `f` — keep folds
    /// CPU-bound. Long async work belongs outside the lock.
    pub async fn apply<F, E>(&self, f: F) -> Result<(), E>
    where
        F: FnOnce(T) -> Result<T, E>,
    {
        let mut guard = self.state.write().await;
        let prev = guard.clone();
        let next = f(prev)?;
        *guard = next.clone();
        drop(guard);
        // `send` only fails when there are zero receivers — that's
        // fine, no listeners is not an error.
        let _ = self.changes_tx.send(next);
        Ok(())
    }

    /// Replace the value unconditionally. Useful for resets / rewinds
    /// that don't fit the fold pattern.
    pub async fn set(&self, value: T) {
        let mut guard = self.state.write().await;
        *guard = value.clone();
        drop(guard);
        let _ = self.changes_tx.send(value);
    }

    /// Live receiver count. Cheap; useful for skipping work when no
    /// one is listening.
    pub fn receiver_count(&self) -> usize {
        self.changes_tx.receiver_count()
    }
}

#[cfg(test)]
mod tests {
    use super::*;

    #[tokio::test]
    async fn current_returns_initial() {
        let cell = StateCell::new(7u32);
        assert_eq!(cell.current().await, 7);
    }

    #[tokio::test]
    async fn apply_advances_and_broadcasts() {
        let cell = StateCell::new(7u32);
        let mut rx = cell.changes();
        let _ = rx.borrow_and_update();
        cell.apply::<_, ()>(|v| Ok(v + 1)).await.unwrap();
        rx.changed().await.unwrap();
        assert_eq!(*rx.borrow(), 8);
    }

    #[tokio::test]
    async fn apply_preserves_state_on_error() {
        let cell = StateCell::new(7u32);
        let result: Result<(), &str> = cell.apply(|_| Err("nope")).await;
        assert!(result.is_err());
        assert_eq!(cell.current().await, 7);
    }

    #[tokio::test]
    async fn set_replaces_unconditionally() {
        let cell = StateCell::new(7u32);
        cell.set(99).await;
        assert_eq!(cell.current().await, 99);
    }

    #[tokio::test]
    async fn clones_share_state() {
        let cell = StateCell::new(7u32);
        let other = cell.clone();
        cell.set(99).await;
        assert_eq!(other.current().await, 99);
    }
}