Skip to main content

rostra_client_db/
current_state.rs

1use std::error::Error;
2use std::fmt;
3
4use tokio::sync::watch;
5
6/// Error returned after a current-state publisher closes.
7#[derive(Debug, Clone, Copy, PartialEq, Eq)]
8pub struct CurrentStateClosed;
9
10impl fmt::Display for CurrentStateClosed {
11    fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
12        formatter.write_str("current-state publisher is closed")
13    }
14}
15
16impl Error for CurrentStateClosed {}
17
18/// A retained current-state subscription that returns owned snapshots.
19///
20/// The subscription initially contains the latest state published before it
21/// was created. [`Self::snapshot`] and [`Self::changed`] clone that state while
22/// holding the internal Tokio watch borrow only for the duration of the call,
23/// so the returned value can safely live across awaits and database writes.
24///
25/// Cloning a subscription creates an independent change cursor over the same
26/// retained state.
27///
28/// ```
29/// # use rostra_client_db::Database;
30/// # async fn inspect_state(db: &Database) {
31/// let mut state = db.self_wot_subscribe();
32/// let snapshot = state.snapshot();
33///
34/// // The snapshot is owned and may remain live across database operations.
35/// let _heads = db.get_heads_self().await;
36/// assert_eq!(
37///     snapshot.len(),
38///     snapshot.followees.len() + snapshot.extended.len()
39/// );
40///
41/// let _newer_snapshot = state.changed().await;
42/// # }
43/// ```
44///
45/// The raw Tokio receiver and its borrow guard are intentionally not exposed:
46///
47/// ```compile_fail
48/// # use rostra_client_db::Database;
49/// # fn borrow_state(db: &Database) {
50/// let state = db.self_wot_subscribe();
51/// let _borrow = state.borrow();
52/// # }
53/// ```
54#[derive(Debug, Clone)]
55pub struct CurrentState<T> {
56    /// Internal retained-state receiver.
57    receiver: watch::Receiver<T>,
58}
59
60impl<T> CurrentState<T> {
61    pub(crate) fn new(receiver: watch::Receiver<T>) -> Self {
62        Self { receiver }
63    }
64}
65
66impl<T> CurrentState<T>
67where
68    T: Clone,
69{
70    /// Return an owned snapshot of the latest retained state.
71    ///
72    /// This does not advance the subscription's change cursor. A subsequent
73    /// [`Self::changed`] call immediately returns if it has not yet observed
74    /// the publication that supplied this snapshot.
75    pub fn snapshot(&self) -> T {
76        self.receiver.borrow().clone()
77    }
78
79    /// Wait for a publication newer than the cursor and return the latest
80    /// owned snapshot.
81    ///
82    /// If multiple publications arrive before this call observes them, it
83    /// coalesces them and returns the latest value. The returned value may
84    /// equal a previous snapshot because snapshots do not advance the
85    /// cursor and publishers may publish equal values.
86    ///
87    /// After the publisher closes, this method delivers any last unseen
88    /// publication before returning [`CurrentStateClosed`]. [`Self::snapshot`]
89    /// remains available after closure.
90    ///
91    /// This method is cancellation safe: using it in [`tokio::select!`] does
92    /// not consume an update when another branch wins.
93    pub async fn changed(&mut self) -> Result<T, CurrentStateClosed> {
94        self.receiver
95            .changed()
96            .await
97            .map_err(|_| CurrentStateClosed)?;
98        Ok(self.receiver.borrow_and_update().clone())
99    }
100}