Skip to main content

rings_node/native/
stores.rs

1//! The native stores of a node, each in its own directory and opened at its authority
2//! (durable-records, Table I): the one layout the daemon and the FFI provider share.
3//!
4//! ```text
5//! <data>                  DHT data store            Disposable      configured budget
6//! <data>/../relay-inbox        relay carriers       Retained        RELAY_INBOX_STORAGE_CAPACITY
7//! <data>/../dht-removals       remove sides         Retained      DHT_REMOVAL_STORAGE_CAPACITY
8//! <data>/../transaction-replay replay windows       Authoritative   TRANSACTION_REPLAY_STORAGE_CAPACITY
9//! <data>/../onion-entry-guards entry guards         DurableCache    ONION_ENTRY_GUARD_STORAGE_CAPACITY
10//! <measure>               peer measurements         Disposable      configured budget
11//! <measure>/../provisional-evidence                 Disposable      the measure budget
12//! ```
13//!
14//! Every store beside the data or the measure store is a sibling directory of it
15//! ([`sibling_storage_path`]). Each store locks its own directory at open (#1039), so a second
16//! daemon or FFI provider given a store an open node holds fails to open it, with
17//! `StorageDirectoryLocked`, instead of writing beside it.
18
19use std::path::Path;
20
21use rings_core::dht::EntryStorage;
22use rings_core::dht::RemovalStorage;
23use rings_core::message::ReplayStorage;
24use rings_core::storage::file::FileStorage;
25use rings_core::storage::RecordAuthority;
26
27pub use crate::consts::DHT_REMOVAL_STORAGE_CAPACITY;
28pub use crate::consts::ONION_ENTRY_GUARD_STORAGE_CAPACITY;
29pub use crate::consts::RELAY_INBOX_STORAGE_CAPACITY;
30pub use crate::consts::TRANSACTION_REPLAY_STORAGE_CAPACITY;
31use crate::error::Error;
32use crate::error::Result;
33use crate::measure::EvidenceStorage;
34use crate::measure::MeasureStorage;
35use crate::native::config::StorageConfig;
36use crate::native::config::DEFAULT_STORAGE_CAPACITY;
37use crate::onion::OnionEntryGuardStorage;
38use crate::release::StoresReleased;
39/// Directory of the store of the data namespace's remove sides, beside the data store.
40pub const DHT_REMOVAL_STORAGE_DIR: &str = "dht-removals";
41/// Directory of the onion entry-guard store, beside the data store.
42pub const ONION_ENTRY_GUARD_STORAGE_DIR: &str = "onion-entry-guards";
43/// Directory of the transaction replay store, beside the data store.
44pub const TRANSACTION_REPLAY_STORAGE_DIR: &str = "transaction-replay";
45/// Directory of the relay-inbox store, beside the data store.
46pub const RELAY_INBOX_STORAGE_DIR: &str = "relay-inbox";
47/// Directory of the provisional-evidence store, beside the measure store.
48pub const PROVISIONAL_EVIDENCE_STORAGE_DIR: &str = "provisional-evidence";
49/// Directory of the DHT data store under a storage root ([`NodeStores::open_under`]).
50pub const DATA_STORAGE_DIR: &str = "data";
51/// Directory of the measure store under a storage root ([`NodeStores::open_under`]).
52pub const MEASURE_STORAGE_DIR: &str = "measure";
53
54/// The path of the store directory `dir` beside the store at `storage_path`: in its parent, or
55/// in the working directory when it has none (pure).
56pub fn sibling_storage_path(storage_path: &str, dir: &str) -> String {
57    Path::new(storage_path)
58        .parent()
59        .filter(|path| !path.as_os_str().is_empty())
60        .unwrap_or_else(|| Path::new("."))
61        .join(dir)
62        .to_string_lossy()
63        .to_string()
64}
65
66/// Every native store of a node, opened at its authority (module docs).
67pub struct NodeStores {
68    /// The DHT data store (disposable).
69    pub data: EntryStorage,
70    /// The relay-inbox store (retained).
71    pub relay: EntryStorage,
72    /// The store of the data namespace's remove sides (retained).
73    pub removals: RemovalStorage,
74    /// The peer measurement store (disposable).
75    pub measure: MeasureStorage,
76    /// The provisional-evidence store (disposable).
77    pub evidence: EvidenceStorage,
78    /// The onion entry-guard store (durable cache).
79    pub guards: OnionEntryGuardStorage,
80    /// The transaction replay store (authoritative).
81    pub replay: ReplayStorage,
82    /// The release witnesses of the seven stores above: a node built over them hands them to
83    /// its builder ([`ProcessorBuilder::stores_released`]), so its close awaits them (#1085).
84    ///
85    /// [`ProcessorBuilder::stores_released`]: crate::processor::ProcessorBuilder::stores_released
86    pub released: StoresReleased,
87}
88
89/// Open the file store at `path` under `capacity` bytes with `authority`.
90async fn open_file(path: String, capacity: u32, authority: RecordAuthority) -> Result<FileStorage> {
91    FileStorage::new_with_cap_path_and_authority(capacity, path, authority)
92        .await
93        .map_err(Error::Storage)
94}
95
96impl NodeStores {
97    /// Open every store of a node whose data store is `data` and measure store is `measure`,
98    /// the others beside them (module docs).
99    pub async fn open(data: &StorageConfig, measure: &StorageConfig) -> Result<Self> {
100        let beside_data = |dir| sibling_storage_path(&data.path, dir);
101        let data_store = open_file(
102            data.path.clone(),
103            data.capacity,
104            RecordAuthority::Disposable,
105        )
106        .await?;
107        let relay = open_file(
108            beside_data(RELAY_INBOX_STORAGE_DIR),
109            RELAY_INBOX_STORAGE_CAPACITY,
110            RecordAuthority::Retained,
111        )
112        .await?;
113        let removals = open_file(
114            beside_data(DHT_REMOVAL_STORAGE_DIR),
115            DHT_REMOVAL_STORAGE_CAPACITY,
116            RecordAuthority::Retained,
117        )
118        .await?;
119        let measure_store = open_file(
120            measure.path.clone(),
121            measure.capacity,
122            RecordAuthority::Disposable,
123        )
124        .await?;
125        let evidence = open_file(
126            sibling_storage_path(&measure.path, PROVISIONAL_EVIDENCE_STORAGE_DIR),
127            measure.capacity,
128            RecordAuthority::Disposable,
129        )
130        .await?;
131        let guards = open_file(
132            beside_data(ONION_ENTRY_GUARD_STORAGE_DIR),
133            ONION_ENTRY_GUARD_STORAGE_CAPACITY,
134            RecordAuthority::DurableCache,
135        )
136        .await?;
137        let replay = open_file(
138            beside_data(TRANSACTION_REPLAY_STORAGE_DIR),
139            TRANSACTION_REPLAY_STORAGE_CAPACITY,
140            RecordAuthority::Authoritative,
141        )
142        .await?;
143        // Taken before each store is boxed behind its trait, which hides the witness.
144        let released = StoresReleased::of(
145            [
146                &data_store,
147                &relay,
148                &removals,
149                &measure_store,
150                &evidence,
151                &guards,
152                &replay,
153            ]
154            .map(FileStorage::released),
155        );
156        Ok(Self {
157            data: Box::new(data_store),
158            relay: Box::new(relay),
159            removals: Box::new(removals),
160            measure: Box::new(measure_store),
161            evidence: Box::new(evidence),
162            guards: Box::new(guards),
163            replay: Box::new(replay),
164            released,
165        })
166    }
167
168    /// Open every store of a node under the storage root `root`: the data store at
169    /// `<root>/data` and the measure store at `<root>/measure`, each under
170    /// [`DEFAULT_STORAGE_CAPACITY`], and the others beside them (the FFI provider's layout).
171    pub async fn open_under(root: &Path) -> Result<Self> {
172        let store = |dir: &str| root.join(dir).to_string_lossy().to_string();
173        Self::open(
174            &StorageConfig::new(&store(DATA_STORAGE_DIR), DEFAULT_STORAGE_CAPACITY),
175            &StorageConfig::new(&store(MEASURE_STORAGE_DIR), DEFAULT_STORAGE_CAPACITY),
176        )
177        .await
178    }
179}
180
181#[cfg(test)]
182mod tests {
183    use super::*;
184
185    /// Every store beside the data or the measure store is a sibling directory of it, in the
186    /// working directory when the store path has no parent.
187    #[test]
188    fn test_sibling_stores_sit_beside_their_store() {
189        for dir in [
190            ONION_ENTRY_GUARD_STORAGE_DIR,
191            TRANSACTION_REPLAY_STORAGE_DIR,
192            RELAY_INBOX_STORAGE_DIR,
193            DHT_REMOVAL_STORAGE_DIR,
194            PROVISIONAL_EVIDENCE_STORAGE_DIR,
195        ] {
196            assert_eq!(
197                sibling_storage_path(".rings/data", dir),
198                format!(".rings/{dir}")
199            );
200            assert_eq!(
201                sibling_storage_path("/tmp/rings/data", dir),
202                format!("/tmp/rings/{dir}")
203            );
204            assert_eq!(sibling_storage_path("data", dir), format!("./{dir}"));
205        }
206    }
207
208    /// A full replay store always fits the replay store's budget, so the stream-count bound,
209    /// not the store's budget, is what fails closed.
210    #[test]
211    fn test_transaction_replay_storage_holds_a_full_store(
212    ) -> std::result::Result<(), std::num::TryFromIntError> {
213        let capacity = usize::try_from(TRANSACTION_REPLAY_STORAGE_CAPACITY)?;
214        assert!(rings_core::message::TRANSACTION_REPLAY_STORE_MAX_BYTES <= capacity);
215        Ok(())
216    }
217
218    /// The FFI layout opens every store, each in its own directory under the root.
219    #[tokio::test]
220    async fn test_open_under_lays_every_store_out_under_the_root() -> Result<()> {
221        let root = std::env::temp_dir().join(format!("rings-node-stores-{}", uuid::Uuid::new_v4()));
222        let stores = NodeStores::open_under(&root).await;
223        let mut dirs = std::fs::read_dir(&root)
224            .map(|entries| {
225                entries
226                    .flatten()
227                    .map(|entry| entry.file_name().to_string_lossy().to_string())
228                    .collect::<Vec<_>>()
229            })
230            .unwrap_or_default();
231        dirs.sort();
232        let _ = std::fs::remove_dir_all(&root);
233        stores?;
234        assert_eq!(dirs, [
235            DATA_STORAGE_DIR,
236            DHT_REMOVAL_STORAGE_DIR,
237            MEASURE_STORAGE_DIR,
238            ONION_ENTRY_GUARD_STORAGE_DIR,
239            PROVISIONAL_EVIDENCE_STORAGE_DIR,
240            RELAY_INBOX_STORAGE_DIR,
241            TRANSACTION_REPLAY_STORAGE_DIR,
242        ]);
243        Ok(())
244    }
245
246    /// A second node over the stores of an open node fails at open, at the first store it
247    /// shares (#1039), whether it is a daemon or an FFI provider: both open through
248    /// [`NodeStores`]. Once the first node drops, the root opens again.
249    #[tokio::test]
250    async fn test_a_second_node_on_open_stores_fails_at_open() -> Result<()> {
251        let root = std::env::temp_dir().join(format!("rings-node-lock-{}", uuid::Uuid::new_v4()));
252        let first = NodeStores::open_under(&root).await;
253        let second = NodeStores::open_under(&root).await;
254        let first_opened = first.is_ok();
255        drop(first);
256        let reopened = NodeStores::open_under(&root).await;
257        let _ = std::fs::remove_dir_all(&root);
258        assert!(first_opened);
259        assert!(matches!(
260            second,
261            Err(Error::Storage(
262                rings_core::error::Error::StorageDirectoryLocked(_)
263            ))
264        ));
265        reopened.map(drop)
266    }
267}