Skip to main content

nsh_core/
storage.rs

1//! An app's key-value storage (`nsh/storage`): strings by string key,
2//! kept on the device by the platform's [`StorageBackend`] (a file in the
3//! app's data directory, the browser's `localStorage`).
4//!
5//! The core keeps the entries in memory, loaded from the backend on first
6//! use. Cores using the same backend share entries and quota accounting,
7//! with each operation serialized; reads after loading never touch the
8//! disk. Every change is handed to the
9//! backend, which writes it where it may block (the file backend on a
10//! thread of its own). Every app has its storage: what the host decides is
11//! where it is kept. The quota is checked here, in Rust.
12
13use std::{
14    collections::BTreeMap,
15    sync::{Arc, Mutex, Weak},
16};
17
18/// The most an app may keep, in UTF-8 bytes of its keys and values.
19pub const QUOTA: usize = 5 * 1024 * 1024;
20
21/// A change to the entries, for the backend to keep.
22#[derive(Debug, Clone, PartialEq, Eq)]
23pub enum StorageChange {
24    /// `key` now holds `value`.
25    Set(String, String),
26    /// `key` was removed.
27    Remove(String),
28    /// Every entry was removed.
29    Clear,
30}
31
32/// Where an app's entries are kept: the platform's.
33pub trait StorageBackend: Send + Sync {
34    /// The entries kept, read once when the app first uses its storage; an
35    /// error leaves the app with none (logged).
36    fn load(&self) -> Result<BTreeMap<String, String>, String>;
37    /// Keeps `change`. Called on the engine thread: a backend that blocks
38    /// writes elsewhere, in order.
39    fn write(&self, change: StorageChange);
40}
41
42/// Names the backend only, so that platforms' options holding one can
43/// derive `Debug`.
44impl std::fmt::Debug for dyn StorageBackend {
45    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
46        f.write_str("StorageBackend")
47    }
48}
49
50/// The app's key-value storage, from Rust: the same entries the app's JS
51/// reads and writes with `nsh/storage`, so an app with a TSX entry and a
52/// Rust entry sees one set of data. The functions are synchronous, as the
53/// entries are in memory; call them where components run (their bodies,
54/// handlers and tasks).
55///
56/// ```ignore
57/// use nsh_core::storage::Storage;
58///
59/// let draft = Storage::get_item("draft");
60/// Storage::set_item("draft", "hello")?;
61/// ```
62pub struct Storage;
63
64impl Storage {
65    /// The value of `key`, `None` when it has none (TS: `getItem`).
66    pub fn get_item(key: &str) -> Option<String> {
67        crate::element::with_storage(|s| s.get(key))
68    }
69
70    /// Sets `key` to `value` (TS: `setItem`); fails when the storage would
71    /// grow past [`QUOTA`], keeping what it held.
72    pub fn set_item(key: impl Into<String>, value: impl Into<String>) -> Result<(), StorageFull> {
73        crate::element::with_storage(|s| s.set(key.into(), value.into()))
74    }
75
76    /// Removes `key` (TS: `removeItem`).
77    pub fn remove_item(key: &str) {
78        crate::element::with_storage(|s| s.remove(key));
79    }
80
81    /// Every key, in order (TS: `keys`).
82    pub fn get_all_keys() -> Vec<String> {
83        crate::element::with_storage(|s| s.keys())
84    }
85
86    /// Removes every key (TS: `clear`).
87    pub fn clear() {
88        crate::element::with_storage(|s| s.clear());
89    }
90}
91
92/// A value refused because the storage would grow past [`QUOTA`].
93#[derive(Debug, Clone, Copy, PartialEq, Eq)]
94pub struct StorageFull {
95    /// The bytes the storage would have held.
96    pub bytes: usize,
97}
98
99impl std::fmt::Display for StorageFull {
100    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
101        write!(
102            f,
103            "storage is full: {} bytes would exceed the quota of {QUOTA}",
104            self.bytes
105        )
106    }
107}
108
109impl std::error::Error for StorageFull {}
110
111/// An app's entries, shared by cores using the same backend.
112#[derive(Clone)]
113pub(crate) struct Store {
114    state: Arc<Mutex<Entries>>,
115}
116
117/// Weak references let the last core release its state and backend.
118struct Shared {
119    backend: Weak<dyn StorageBackend>,
120    state: Weak<Mutex<Entries>>,
121}
122
123impl Store {
124    /// Shares the state of `backend`; `None` creates independent in-memory
125    /// storage for this core.
126    pub(crate) fn new(backend: Option<Arc<dyn StorageBackend>>) -> Self {
127        // Index by backend identity, never by an engine or app id: the
128        // host decides which views share storage by sharing the backend.
129        static SHARED: Mutex<Vec<Shared>> = Mutex::new(Vec::new());
130        let Some(backend) = backend else {
131            return Self {
132                state: Arc::new(Mutex::new(Entries::new(None))),
133            };
134        };
135        let mut shared = SHARED.lock().unwrap_or_else(|e| e.into_inner());
136        shared.retain(|s| s.state.strong_count() > 0);
137        let identity = Arc::downgrade(&backend);
138        if let Some(state) = shared
139            .iter()
140            .find(|s| s.backend.ptr_eq(&identity))
141            .and_then(|s| s.state.upgrade())
142        {
143            return Self { state };
144        }
145        let state = Arc::new(Mutex::new(Entries::new(Some(backend))));
146        shared.push(Shared {
147            backend: identity,
148            state: Arc::downgrade(&state),
149        });
150        Self { state }
151    }
152
153    fn entries(&self) -> std::sync::MutexGuard<'_, Entries> {
154        self.state.lock().unwrap_or_else(|e| e.into_inner())
155    }
156
157    /// The value of `key`.
158    pub(crate) fn get(&self, key: &str) -> Option<String> {
159        self.entries().get(key)
160    }
161
162    /// Sets `key` to `value`; fails past [`QUOTA`].
163    pub(crate) fn set(&self, key: String, value: String) -> Result<(), StorageFull> {
164        self.entries().set(key, value)
165    }
166
167    /// Removes `key`.
168    pub(crate) fn remove(&self, key: &str) {
169        self.entries().remove(key)
170    }
171
172    /// Every key, in order.
173    pub(crate) fn keys(&self) -> Vec<String> {
174        self.entries().keys()
175    }
176
177    /// Removes every entry.
178    pub(crate) fn clear(&self) {
179        self.entries().clear()
180    }
181}
182
183/// The authoritative entries and quota, locked through backend dispatch
184/// so concurrent cores hand their changes to the backend in the same order.
185struct Entries {
186    backend: Option<Arc<dyn StorageBackend>>,
187    entries: Option<BTreeMap<String, String>>,
188    bytes: usize,
189}
190
191impl Entries {
192    /// Entries kept by `backend` (`None`: in memory, for the engine's
193    /// life).
194    fn new(backend: Option<Arc<dyn StorageBackend>>) -> Self {
195        Self {
196            backend,
197            entries: None,
198            bytes: 0,
199        }
200    }
201
202    fn entries(&mut self) -> &mut BTreeMap<String, String> {
203        let backend = &self.backend;
204        let bytes = &mut self.bytes;
205        self.entries.get_or_insert_with(|| {
206            let entries = match backend.as_ref().map(|b| b.load()) {
207                Some(Ok(entries)) => entries,
208                Some(Err(e)) => {
209                    log::error!(target: "js", "the app's storage could not be read: {e}");
210                    BTreeMap::new()
211                }
212                None => BTreeMap::new(),
213            };
214            *bytes = entries.iter().map(|(k, v)| k.len() + v.len()).sum();
215            entries
216        })
217    }
218
219    fn write(&self, change: StorageChange) {
220        if let Some(backend) = &self.backend {
221            backend.write(change);
222        }
223    }
224
225    /// The value of `key`.
226    fn get(&mut self, key: &str) -> Option<String> {
227        self.entries().get(key).cloned()
228    }
229
230    /// Sets `key` to `value`; fails past [`QUOTA`].
231    fn set(&mut self, key: String, value: String) -> Result<(), StorageFull> {
232        // Loaded first: what the device kept counts too.
233        self.entries();
234        let bytes = self.bytes;
235        let entries = self.entries();
236        let old = entries.get(&key).map_or(0, |v| key.len() + v.len());
237        let new = bytes - old + key.len() + value.len();
238        if new > QUOTA {
239            return Err(StorageFull { bytes: new });
240        }
241        if entries.get(&key) == Some(&value) {
242            return Ok(());
243        }
244        entries.insert(key.clone(), value.clone());
245        self.bytes = new;
246        self.write(StorageChange::Set(key, value));
247        Ok(())
248    }
249
250    /// Removes `key`.
251    fn remove(&mut self, key: &str) {
252        let Some(value) = self.entries().remove(key) else {
253            return;
254        };
255        self.bytes -= key.len() + value.len();
256        self.write(StorageChange::Remove(key.to_owned()));
257    }
258
259    /// Every key, in order.
260    fn keys(&mut self) -> Vec<String> {
261        self.entries().keys().cloned().collect()
262    }
263
264    /// Removes every entry.
265    fn clear(&mut self) {
266        let entries = self.entries();
267        if entries.is_empty() {
268            return;
269        }
270        entries.clear();
271        self.bytes = 0;
272        self.write(StorageChange::Clear);
273    }
274}
275
276#[cfg(test)]
277mod tests {
278    use std::sync::Mutex;
279
280    use super::*;
281
282    #[derive(Default)]
283    struct Recorder {
284        kept: BTreeMap<String, String>,
285        changes: Mutex<Vec<StorageChange>>,
286    }
287
288    impl StorageBackend for Recorder {
289        fn load(&self) -> Result<BTreeMap<String, String>, String> {
290            Ok(self.kept.clone())
291        }
292
293        fn write(&self, change: StorageChange) {
294            self.changes.lock().unwrap().push(change);
295        }
296    }
297
298    #[test]
299    fn loads_once_and_writes_changes() {
300        let backend = Arc::new(Recorder {
301            kept: BTreeMap::from([("a".into(), "1".into())]),
302            ..Recorder::default()
303        });
304        let storage = Store::new(Some(backend.clone()));
305        assert_eq!(storage.get("a").as_deref(), Some("1"));
306        storage.set("b".into(), "2".into()).unwrap();
307        storage.set("b".into(), "2".into()).unwrap();
308        storage.remove("a");
309        storage.remove("missing");
310        assert_eq!(storage.keys(), ["b"]);
311        storage.clear();
312        assert_eq!(
313            *backend.changes.lock().unwrap(),
314            [
315                StorageChange::Set("b".into(), "2".into()),
316                StorageChange::Remove("a".into()),
317                StorageChange::Clear,
318            ]
319        );
320    }
321
322    #[test]
323    fn views_share_reads_removals_and_clear() {
324        let backend = Arc::new(Recorder::default());
325        let first = Store::new(Some(backend.clone()));
326        let second = Store::new(Some(backend));
327        assert_eq!(second.get("draft"), None);
328        first.set("draft".into(), "saved".into()).unwrap();
329        assert_eq!(second.get("draft").as_deref(), Some("saved"));
330        assert_eq!(second.keys(), ["draft"]);
331        second.remove("draft");
332        assert_eq!(first.get("draft"), None);
333        first.set("draft".into(), "new".into()).unwrap();
334        second.clear();
335        assert!(first.keys().is_empty());
336    }
337
338    #[test]
339    fn concurrent_views_share_the_quota() {
340        let backend = Arc::new(Recorder::default());
341        let barrier = Arc::new(std::sync::Barrier::new(2));
342        let views: Vec<_> = (0..2)
343            .map(|id| {
344                let storage = Store::new(Some(backend.clone()));
345                // Both views load before either writes.
346                assert!(storage.keys().is_empty());
347                let barrier = barrier.clone();
348                std::thread::spawn(move || {
349                    barrier.wait();
350                    storage.set(id.to_string(), "x".repeat(QUOTA - 1))
351                })
352            })
353            .collect();
354        let results: Vec<_> = views.into_iter().map(|v| v.join().unwrap()).collect();
355        assert_eq!(results.iter().filter(|r| r.is_ok()).count(), 1);
356        assert_eq!(backend.changes.lock().unwrap().len(), 1);
357    }
358
359    #[test]
360    fn independent_backends_and_in_memory_views_keep_apart() {
361        for backends in [
362            [None, None],
363            [
364                Some(Arc::new(Recorder::default()) as Arc<dyn StorageBackend>),
365                Some(Arc::new(Recorder::default()) as Arc<dyn StorageBackend>),
366            ],
367        ] {
368            let [first, second] = backends;
369            let first = Store::new(first);
370            let second = Store::new(second);
371            first.set("draft".into(), "saved".into()).unwrap();
372            assert_eq!(second.get("draft"), None);
373            second.clear();
374            assert_eq!(first.get("draft").as_deref(), Some("saved"));
375        }
376    }
377
378    #[test]
379    fn checks_the_quota() {
380        let storage = Store::new(None);
381        storage.set("k".into(), "x".repeat(QUOTA - 1)).unwrap();
382        assert!(storage.set("j".into(), "y".into()).is_err());
383        // Replacing a value counts the new one only.
384        storage.set("k".into(), "z".repeat(QUOTA - 1)).unwrap();
385    }
386
387    #[test]
388    fn the_quota_counts_utf8_bytes_and_frees_on_removal() {
389        let storage = Store::new(None);
390        // "键" is three bytes, "😀" four.
391        storage
392            .set("键".into(), "😀".repeat((QUOTA - 3) / 4))
393            .unwrap();
394        let used = 3 + (QUOTA - 3) / 4 * 4;
395        assert!(storage.set("x".into(), "y".repeat(QUOTA - used)).is_err());
396        // A refused value leaves the entries as they were.
397        assert_eq!(storage.keys(), ["键"]);
398        storage.remove("键");
399        storage.set("x".into(), "y".repeat(QUOTA - 1)).unwrap();
400        storage.clear();
401        assert!(storage.keys().is_empty());
402        storage.set("x".into(), "y".repeat(QUOTA - 1)).unwrap();
403    }
404
405    #[test]
406    fn the_quota_counts_what_was_loaded() {
407        let backend = Arc::new(Recorder {
408            kept: BTreeMap::from([("k".into(), "v".repeat(QUOTA - 1))]),
409            ..Recorder::default()
410        });
411        let storage = Store::new(Some(backend));
412        assert!(storage.set("a".into(), "b".into()).is_err());
413        storage.set("k".into(), "small".into()).unwrap();
414        storage.set("a".into(), "b".into()).unwrap();
415    }
416
417    #[test]
418    fn a_failed_load_starts_empty() {
419        struct Broken;
420        impl StorageBackend for Broken {
421            fn load(&self) -> Result<BTreeMap<String, String>, String> {
422                Err("unreadable".into())
423            }
424
425            fn write(&self, _: StorageChange) {}
426        }
427        let storage = Store::new(Some(Arc::new(Broken)));
428        assert_eq!(storage.get("a"), None);
429        storage.set("a".into(), "1".into()).unwrap();
430        assert_eq!(storage.get("a").as_deref(), Some("1"));
431    }
432}