moonproof_utils/state.rs
1//! Generic "latest-snapshot" state cell over `tokio::sync::watch`.
2//!
3//! Single source of truth for the "hold a value, broadcast on
4//! change, let consumers pull snapshots" pattern. Used by
5//! [`moonproof_wallet::runtime::WalletRuntime`] (over `FacadeState`)
6//! and [`moonproof_runtime::sync::Watcher`] (over `ContractRuntimeState`).
7//! Each consumer composes its own cancel/lifecycle on top — this
8//! primitive only owns the state + change broadcast.
9//!
10//! Distinct from [`crate::events::EventBus`], which is a per-event
11//! firehose (broadcast). State cell is "latest value + change
12//! signal" (watch). Pick whichever fits the domain — they don't
13//! overlap.
14
15use std::sync::Arc;
16
17use tokio::sync::{watch, RwLock};
18
19/// Holds the current value of `T` behind an `Arc<RwLock>`, plus a
20/// `tokio::sync::watch` channel that fires every time the value
21/// changes. Cheap to clone — the inner state + sender are
22/// `Arc`-shared.
23#[derive(Debug)]
24pub struct StateCell<T: Clone + Send + Sync + 'static> {
25 state: Arc<RwLock<T>>,
26 changes_tx: watch::Sender<T>,
27}
28
29impl<T: Clone + Send + Sync + 'static> Clone for StateCell<T> {
30 fn clone(&self) -> Self {
31 Self {
32 state: Arc::clone(&self.state),
33 changes_tx: self.changes_tx.clone(),
34 }
35 }
36}
37
38impl<T: Clone + Send + Sync + 'static> StateCell<T> {
39 /// Wrap an initial value. The initial value is also the watch
40 /// channel's first observed snapshot — new subscribers see it
41 /// via `borrow_and_update`.
42 pub fn new(initial: T) -> Self {
43 let (changes_tx, _) = watch::channel(initial.clone());
44 Self {
45 state: Arc::new(RwLock::new(initial)),
46 changes_tx,
47 }
48 }
49
50 /// Cheap clone of the current value.
51 pub async fn current(&self) -> T {
52 self.state.read().await.clone()
53 }
54
55 /// Subscribe to value changes. Receivers' initial value is the
56 /// state at subscribe time — call `borrow_and_update` to read
57 /// without registering a "changed" notification.
58 pub fn changes(&self) -> watch::Receiver<T> {
59 self.changes_tx.subscribe()
60 }
61
62 /// Atomically transform the state. The closure receives ownership
63 /// of the previous value and returns `Result<T, E>`; on `Ok` the
64 /// new value is stored and broadcast; on `Err` the previous value
65 /// is preserved and the error is returned.
66 ///
67 /// Holds the write lock for the duration of `f` — keep folds
68 /// CPU-bound. Long async work belongs outside the lock.
69 pub async fn apply<F, E>(&self, f: F) -> Result<(), E>
70 where
71 F: FnOnce(T) -> Result<T, E>,
72 {
73 let mut guard = self.state.write().await;
74 let prev = guard.clone();
75 let next = f(prev)?;
76 *guard = next.clone();
77 drop(guard);
78 // `send` only fails when there are zero receivers — that's
79 // fine, no listeners is not an error.
80 let _ = self.changes_tx.send(next);
81 Ok(())
82 }
83
84 /// Replace the value unconditionally. Useful for resets / rewinds
85 /// that don't fit the fold pattern.
86 pub async fn set(&self, value: T) {
87 let mut guard = self.state.write().await;
88 *guard = value.clone();
89 drop(guard);
90 let _ = self.changes_tx.send(value);
91 }
92
93 /// Live receiver count. Cheap; useful for skipping work when no
94 /// one is listening.
95 pub fn receiver_count(&self) -> usize {
96 self.changes_tx.receiver_count()
97 }
98}
99
100#[cfg(test)]
101mod tests {
102 use super::*;
103
104 #[tokio::test]
105 async fn current_returns_initial() {
106 let cell = StateCell::new(7u32);
107 assert_eq!(cell.current().await, 7);
108 }
109
110 #[tokio::test]
111 async fn apply_advances_and_broadcasts() {
112 let cell = StateCell::new(7u32);
113 let mut rx = cell.changes();
114 let _ = rx.borrow_and_update();
115 cell.apply::<_, ()>(|v| Ok(v + 1)).await.unwrap();
116 rx.changed().await.unwrap();
117 assert_eq!(*rx.borrow(), 8);
118 }
119
120 #[tokio::test]
121 async fn apply_preserves_state_on_error() {
122 let cell = StateCell::new(7u32);
123 let result: Result<(), &str> = cell.apply(|_| Err("nope")).await;
124 assert!(result.is_err());
125 assert_eq!(cell.current().await, 7);
126 }
127
128 #[tokio::test]
129 async fn set_replaces_unconditionally() {
130 let cell = StateCell::new(7u32);
131 cell.set(99).await;
132 assert_eq!(cell.current().await, 99);
133 }
134
135 #[tokio::test]
136 async fn clones_share_state() {
137 let cell = StateCell::new(7u32);
138 let other = cell.clone();
139 cell.set(99).await;
140 assert_eq!(other.current().await, 99);
141 }
142}