Skip to main content

rings_node/
release.rs

1//! The release of a node's stores (#1085): the witnesses a close awaits.
2//!
3//! A native store is released when its last holder drops it, which unlocks its directory (#1039;
4//! the release law of `rings_core::storage::file`). A browser node's storage namespace is
5//! released when its last store drops, which resolves its exclusive Web Lock (`rings-node/<name>`,
6//! #1055) and settles once the browser's `LockManager` has released it. A node keeps the release
7//! witnesses of the stores it was built over, taken at open before each store is boxed behind its
8//! trait, and [`StoresReleased`] resolves once each of them has.
9//!
10//! ```text
11//!   StoresReleased(w₁ … wₙ) resolves  ⟺  ∀ i. wᵢ resolved   (n = 0 resolves at once)
12//! ```
13
14use std::fmt;
15use std::future::IntoFuture;
16
17#[cfg(any(rings_native, rings_browser))]
18use futures::future::join_all;
19use futures::future::BoxFuture;
20#[cfg(any(rings_native, rings_browser))]
21use futures::FutureExt;
22#[cfg(rings_native)]
23use rings_core::storage::file::StoreRelease;
24
25#[cfg(rings_browser)]
26use crate::provider::browser::provider::lock::BrowserLockRelease;
27
28/// The release witnesses of a node's stores: it resolves once every store it names is released.
29///
30/// Cloning shares the witnesses.
31#[derive(Clone, Default)]
32pub struct StoresReleased {
33    /// One witness per file store.
34    #[cfg(rings_native)]
35    stores: Vec<StoreRelease>,
36    /// The witness of the browser origin lock (`rings-node/<storage_name>`, #1055).
37    #[cfg(rings_browser)]
38    stores: Vec<BrowserLockRelease>,
39}
40
41impl StoresReleased {
42    /// The witnesses `stores`, one per file store.
43    #[cfg(rings_native)]
44    pub fn of(stores: impl IntoIterator<Item = StoreRelease>) -> Self {
45        Self {
46            stores: stores.into_iter().collect(),
47        }
48    }
49
50    /// The witnesses `stores` of a browser node's storage lock (#1055).
51    #[cfg(rings_browser)]
52    pub fn of(stores: impl IntoIterator<Item = BrowserLockRelease>) -> Self {
53        Self {
54            stores: stores.into_iter().collect(),
55        }
56    }
57
58    /// How many stores these witnesses name.
59    pub fn len(&self) -> usize {
60        #[cfg(any(rings_native, rings_browser))]
61        {
62            self.stores.len()
63        }
64        #[cfg(not(any(rings_native, rings_browser)))]
65        {
66            0
67        }
68    }
69
70    /// Whether these witnesses name no store, so they resolve at once.
71    pub fn is_empty(&self) -> bool {
72        self.len() == 0
73    }
74}
75
76impl IntoFuture for StoresReleased {
77    type Output = ();
78    type IntoFuture = BoxFuture<'static, ()>;
79
80    /// Resolves once every store is released.
81    fn into_future(self) -> Self::IntoFuture {
82        #[cfg(any(rings_native, rings_browser))]
83        {
84            join_all(self.stores).map(drop).boxed()
85        }
86        #[cfg(not(any(rings_native, rings_browser)))]
87        {
88            Box::pin(std::future::ready(()))
89        }
90    }
91}
92
93impl fmt::Debug for StoresReleased {
94    /// How many stores the witnesses name; whether they resolved is learned only by awaiting.
95    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
96        f.debug_struct("StoresReleased")
97            .field("stores", &self.len())
98            .finish()
99    }
100}
101
102#[cfg(all(test, rings_native))]
103mod tests {
104    use std::future::IntoFuture;
105
106    use futures::FutureExt;
107    use rings_core::storage::file::FileStorage;
108    use rings_core::storage::RecordAuthority;
109    use uuid::Uuid;
110
111    use super::StoresReleased;
112
113    #[tokio::test]
114    async fn test_stores_released_empty_and_partial_vs_full_resolution() {
115        // Boundary `n = 0`: `default()` and `of([])` report `len() == 0`, `is_empty()`, and
116        // resolve immediately on first poll.
117        let empty = StoresReleased::default();
118        assert_eq!(empty.len(), 0);
119        assert!(empty.is_empty());
120        assert_eq!(format!("{empty:?}"), "StoresReleased { stores: 0 }");
121        assert_eq!(empty.into_future().now_or_never(), Some(()));
122        assert_eq!(
123            StoresReleased::of([]).into_future().now_or_never(),
124            Some(())
125        );
126
127        // Partial vs. full resolution (`n = 2`): remains `Pending` while any store stays live, and
128        // resolves (along with clones) once all stores drop.
129        let root = std::env::temp_dir().join(format!("rings-stores-released-{}", Uuid::new_v4()));
130        let first = FileStorage::new_with_cap_path_and_authority(
131            64,
132            root.join("first"),
133            RecordAuthority::DurableCache,
134        )
135        .await
136        .expect("open first store");
137        let second = FileStorage::new_with_cap_path_and_authority(
138            64,
139            root.join("second"),
140            RecordAuthority::DurableCache,
141        )
142        .await
143        .expect("open second store");
144
145        let released = StoresReleased::of([first.released(), second.released()]);
146        let cloned = released.clone();
147        assert_eq!(released.len(), 2);
148        assert!(!released.is_empty());
149        assert_eq!(format!("{released:?}"), "StoresReleased { stores: 2 }");
150
151        let mut fut = released.into_future();
152        assert!(futures::poll!(&mut fut).is_pending());
153
154        // Dropping only 1 of 2 stores must leave `StoresReleased` pending.
155        drop(first);
156        assert!(futures::poll!(&mut fut).is_pending());
157
158        // Dropping the 2nd store resolves both the in-flight future and any cloned witness.
159        drop(second);
160        assert_eq!(fut.now_or_never(), Some(()));
161        assert_eq!(cloned.into_future().now_or_never(), Some(()));
162
163        let _ = std::fs::remove_dir_all(root);
164    }
165}