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). A value the backend refuses at once (the browser's
11//! `localStorage`) is not kept, as one past the quota. What another writer
12//! changes in the backend's entries (another browser tab of the app) the
13//! platform hands in ([`changed_elsewhere`]). Every app has its storage:
14//! what the host decides is where it is kept. The quota is checked here, in
15//! Rust.
16//!
17//! What changes the entries elsewhere, another core sharing them (another
18//! window of the app) or another writer the platform reports, is handed to
19//! the watchers of every other core ([`Storage::on_change`], TS
20//! `Storage.on("change", ...)`): each has a queue of its own, filled from
21//! any thread and drained on its core's engine thread. A core's own
22//! changes reach only the others.
23
24use std::{
25    collections::{BTreeMap, VecDeque},
26    sync::{
27        Arc, Mutex, Weak,
28        atomic::{AtomicU64, Ordering},
29    },
30    task::{Poll, Waker},
31};
32
33/// The most an app may keep, in UTF-8 bytes of its keys and values.
34pub const QUOTA: usize = 5 * 1024 * 1024;
35
36/// A change to the entries, for the backend to keep.
37#[derive(Debug, Clone, PartialEq, Eq)]
38pub enum StorageChange {
39    /// `key` now holds `value`.
40    Set(String, String),
41    /// `key` was removed.
42    Remove(String),
43    /// Every entry was removed.
44    Clear,
45}
46
47/// Where an app's entries are kept: the platform's.
48pub trait StorageBackend: Send + Sync {
49    /// The entries kept, read once when the app first uses its storage; an
50    /// error leaves the app with none (logged).
51    fn load(&self) -> Result<BTreeMap<String, String>, String>;
52    /// Keeps `change`. Called on the engine thread: a backend that blocks
53    /// writes elsewhere, in order, and returns before it knows how that
54    /// went (logging what fails there). An error means the change was not
55    /// kept: a value set is then refused ([`Storage::set_item`] fails and
56    /// the entries stay as they were); a removal stays done in memory
57    /// (logged), as the app asked.
58    fn write(&self, change: StorageChange) -> Result<(), String>;
59}
60
61/// Names the backend only, so that platforms' options holding one can
62/// derive `Debug`.
63impl std::fmt::Debug for dyn StorageBackend {
64    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
65        f.write_str("StorageBackend")
66    }
67}
68
69/// The app's key-value storage, from Rust: the same entries the app's JS
70/// reads and writes with `nsh/storage`, so an app with a TSX entry and a
71/// Rust entry sees one set of data. The functions are synchronous, as the
72/// entries are in memory; call them where components run (their bodies,
73/// handlers and tasks).
74///
75/// ```ignore
76/// use nsh_core::storage::Storage;
77///
78/// let draft = Storage::get_item("draft");
79/// Storage::set_item("draft", "hello")?;
80/// ```
81pub struct Storage;
82
83impl Storage {
84    /// The value of `key`, `None` when it has none (TS: `getItem`).
85    pub fn get_item(key: &str) -> Option<String> {
86        crate::element::with_storage(|s| s.get(key))
87    }
88
89    /// Sets `key` to `value` (TS: `setItem`); fails when the storage would
90    /// grow past [`QUOTA`] or the device refuses the value (the browser's
91    /// own quota, storage the user blocked), keeping what it held.
92    pub fn set_item(key: impl Into<String>, value: impl Into<String>) -> Result<(), StorageFull> {
93        crate::element::with_storage(|s| s.set(key.into(), value.into()))
94    }
95
96    /// Removes `key` (TS: `removeItem`).
97    pub fn remove_item(key: &str) {
98        crate::element::with_storage(|s| s.remove(key));
99    }
100
101    /// Every key, in order (TS: `keys`).
102    pub fn get_all_keys() -> Vec<String> {
103        crate::element::with_storage(|s| s.keys())
104    }
105
106    /// Removes every key (TS: `clear`).
107    pub fn clear() {
108        crate::element::with_storage(|s| s.clear());
109    }
110
111    /// Runs `f` with each change made to the entries elsewhere, while the
112    /// current owner lives (TS: `Storage.on("change", ...)`): by another
113    /// window or view of the app sharing its storage, or on the web by
114    /// another tab of the app. The entries hold the change already, so
115    /// [`Storage::get_item`] reads it; this core's own changes do not come.
116    /// A change that leaves an entry as it was does not come either. Runs
117    /// on the engine thread, in the order the changes were made.
118    ///
119    /// ```ignore
120    /// Storage::on_change(move |change| {
121    ///     if change.key().is_none_or(|key| key == "theme") {
122    ///         theme.set(Storage::get_item("theme"));
123    ///     }
124    /// });
125    /// ```
126    pub fn on_change(f: impl Fn(&StorageChange) + 'static) {
127        let watch = crate::element::with_storage(|s| s.watch());
128        // Ends with the owner, dropping the watch.
129        drop(crate::element::spawn(async move {
130            loop {
131                let change = watch.next().await;
132                f(&change);
133            }
134        }));
135    }
136}
137
138impl StorageChange {
139    /// The key changed; `None` for [`StorageChange::Clear`], which changes
140    /// every key.
141    pub fn key(&self) -> Option<&str> {
142        match self {
143            Self::Set(key, _) | Self::Remove(key) => Some(key),
144            Self::Clear => None,
145        }
146    }
147
148    /// The value the key holds now; `None` when it was removed (or every
149    /// key was).
150    pub fn value(&self) -> Option<&str> {
151        match self {
152            Self::Set(_, value) => Some(value),
153            Self::Remove(_) | Self::Clear => None,
154        }
155    }
156}
157
158/// A value refused because the storage would grow past [`QUOTA`], or
159/// because the device refused to keep it (the browser's own quota, storage
160/// the user blocked).
161#[derive(Debug, Clone, Copy, PartialEq, Eq)]
162pub struct StorageFull {
163    /// The bytes the storage would have held.
164    pub bytes: usize,
165}
166
167impl std::fmt::Display for StorageFull {
168    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
169        if self.bytes > QUOTA {
170            write!(
171                f,
172                "storage is full: {} bytes would exceed the quota of {QUOTA}",
173                self.bytes
174            )
175        } else {
176            write!(
177                f,
178                "storage is full: the device refused to keep {} bytes",
179                self.bytes
180            )
181        }
182    }
183}
184
185impl std::error::Error for StorageFull {}
186
187/// An app's entries, shared by cores using the same backend: one core's
188/// handle to them.
189#[derive(Clone)]
190pub(crate) struct Store {
191    state: Arc<Mutex<Entries>>,
192    /// The core's, telling its own changes from others'
193    /// ([`Watcher::view`]).
194    view: u64,
195}
196
197/// The changes made elsewhere one watch has not taken yet: filled under
198/// the entries' lock from any thread, taken on its core's engine thread.
199#[derive(Default)]
200struct Inbox {
201    state: Mutex<InboxState>,
202}
203
204#[derive(Default)]
205struct InboxState {
206    changes: VecDeque<StorageChange>,
207    waker: Option<Waker>,
208}
209
210impl Inbox {
211    fn push(&self, change: StorageChange) {
212        let waker = {
213            let mut state = self.state.lock().unwrap_or_else(|e| e.into_inner());
214            state.changes.push_back(change);
215            state.waker.take()
216        };
217        if let Some(waker) = waker {
218            waker.wake();
219        }
220    }
221}
222
223/// A watch of the changes made to the entries elsewhere ([`Store::watch`]),
224/// until dropped.
225pub(crate) struct Watch {
226    inbox: Arc<Inbox>,
227}
228
229impl Watch {
230    /// The next change made elsewhere, in order.
231    pub(crate) async fn next(&self) -> StorageChange {
232        std::future::poll_fn(|cx| {
233            let mut state = self.inbox.state.lock().unwrap_or_else(|e| e.into_inner());
234            match state.changes.pop_front() {
235                Some(change) => Poll::Ready(change),
236                None => {
237                    state.waker = Some(cx.waker().clone());
238                    Poll::Pending
239                }
240            }
241        })
242        .await
243    }
244
245    /// The next change made elsewhere, if one came.
246    #[cfg(test)]
247    fn try_next(&self) -> Option<StorageChange> {
248        let mut state = self.inbox.state.lock().unwrap_or_else(|e| e.into_inner());
249        state.changes.pop_front()
250    }
251}
252
253/// A watch held by a core ([`Entries::notify`]).
254struct Watcher {
255    /// The [`Store::view`] it watches from: its changes are its own.
256    view: u64,
257    inbox: Weak<Inbox>,
258}
259
260/// The next [`Store::view`].
261static NEXT_VIEW: AtomicU64 = AtomicU64::new(0);
262
263/// Weak references let the last core release its state and backend.
264struct Shared {
265    backend: Weak<dyn StorageBackend>,
266    state: Weak<Mutex<Entries>>,
267}
268
269/// The state of each backend in use. Indexed by backend identity, never by
270/// an engine or app id: the host decides which views share storage by
271/// sharing the backend.
272static SHARED: Mutex<Vec<Shared>> = Mutex::new(Vec::new());
273
274/// Takes in what another writer did to `backend`'s entries (another browser
275/// tab of the same app): `change` as the backend now holds it, or `None`
276/// when any entry may have changed, to be read again on next use. Every
277/// core using `backend` sees it; nothing is written back. A backend no core
278/// uses, or one not read yet, reads it when first used.
279#[doc(hidden)]
280pub fn changed_elsewhere(backend: &dyn StorageBackend, change: Option<StorageChange>) {
281    let state = SHARED
282        .lock()
283        .unwrap_or_else(|e| e.into_inner())
284        .iter()
285        .find(|s| std::ptr::addr_eq(s.backend.as_ptr(), backend as *const dyn StorageBackend))
286        .and_then(|s| s.state.upgrade());
287    if let Some(state) = state {
288        state
289            .lock()
290            .unwrap_or_else(|e| e.into_inner())
291            .changed_elsewhere(change);
292    }
293}
294
295impl Store {
296    /// Shares the state of `backend`; `None` creates independent in-memory
297    /// storage for this core.
298    pub(crate) fn new(backend: Option<Arc<dyn StorageBackend>>) -> Self {
299        let view = NEXT_VIEW.fetch_add(1, Ordering::Relaxed);
300        let Some(backend) = backend else {
301            return Self {
302                state: Arc::new(Mutex::new(Entries::new(None))),
303                view,
304            };
305        };
306        let mut shared = SHARED.lock().unwrap_or_else(|e| e.into_inner());
307        shared.retain(|s| s.state.strong_count() > 0);
308        let identity = Arc::downgrade(&backend);
309        if let Some(state) = shared
310            .iter()
311            .find(|s| s.backend.ptr_eq(&identity))
312            .and_then(|s| s.state.upgrade())
313        {
314            return Self { state, view };
315        }
316        let state = Arc::new(Mutex::new(Entries::new(Some(backend))));
317        shared.push(Shared {
318            backend: identity,
319            state: Arc::downgrade(&state),
320        });
321        Self { state, view }
322    }
323
324    fn entries(&self) -> std::sync::MutexGuard<'_, Entries> {
325        self.state.lock().unwrap_or_else(|e| e.into_inner())
326    }
327
328    /// The value of `key`.
329    pub(crate) fn get(&self, key: &str) -> Option<String> {
330        self.entries().get(key)
331    }
332
333    /// Sets `key` to `value`; fails past [`QUOTA`].
334    pub(crate) fn set(&self, key: String, value: String) -> Result<(), StorageFull> {
335        self.entries().set(key, value, self.view)
336    }
337
338    /// Removes `key`.
339    pub(crate) fn remove(&self, key: &str) {
340        self.entries().remove(key, self.view)
341    }
342
343    /// Every key, in order.
344    pub(crate) fn keys(&self) -> Vec<String> {
345        self.entries().keys()
346    }
347
348    /// Removes every entry.
349    pub(crate) fn clear(&self) {
350        self.entries().clear(self.view)
351    }
352
353    /// Watches the changes made to the entries elsewhere: by other cores,
354    /// or by other writers the platform reports ([`changed_elsewhere`]).
355    /// Loads the entries, so that what changes from then on is known.
356    pub(crate) fn watch(&self) -> Watch {
357        let inbox = Arc::new(Inbox::default());
358        let mut entries = self.entries();
359        entries.entries();
360        entries.watchers.retain(|w| w.inbox.strong_count() > 0);
361        entries.watchers.push(Watcher {
362            view: self.view,
363            inbox: Arc::downgrade(&inbox),
364        });
365        Watch { inbox }
366    }
367}
368
369/// The authoritative entries and quota, locked through backend dispatch
370/// so concurrent cores hand their changes to the backend in the same order.
371struct Entries {
372    backend: Option<Arc<dyn StorageBackend>>,
373    entries: Option<BTreeMap<String, String>>,
374    bytes: usize,
375    /// The cores' watches of changes made elsewhere ([`Store::watch`]).
376    watchers: Vec<Watcher>,
377}
378
379impl Entries {
380    /// Entries kept by `backend` (`None`: in memory, for the engine's
381    /// life).
382    fn new(backend: Option<Arc<dyn StorageBackend>>) -> Self {
383        Self {
384            backend,
385            entries: None,
386            bytes: 0,
387            watchers: Vec::new(),
388        }
389    }
390
391    /// Hands `change` to the watchers of every view but `from` (`None`: to
392    /// all), made only when one watches.
393    fn notify(&mut self, from: Option<u64>, change: impl FnOnce() -> StorageChange) {
394        if self.watchers.is_empty() {
395            return;
396        }
397        self.watchers.retain(|w| w.inbox.strong_count() > 0);
398        let inboxes: Vec<_> = self
399            .watchers
400            .iter()
401            .filter(|w| Some(w.view) != from)
402            .filter_map(|w| w.inbox.upgrade())
403            .collect();
404        if inboxes.is_empty() {
405            return;
406        }
407        let change = change();
408        for inbox in inboxes {
409            inbox.push(change.clone());
410        }
411    }
412
413    fn entries(&mut self) -> &mut BTreeMap<String, String> {
414        let backend = &self.backend;
415        let bytes = &mut self.bytes;
416        self.entries.get_or_insert_with(|| {
417            let entries = match backend.as_ref().map(|b| b.load()) {
418                Some(Ok(entries)) => entries,
419                Some(Err(e)) => {
420                    log::error!(target: "js", "the app's storage could not be read: {e}");
421                    BTreeMap::new()
422                }
423                None => BTreeMap::new(),
424            };
425            *bytes = entries.iter().map(|(k, v)| k.len() + v.len()).sum();
426            entries
427        })
428    }
429
430    fn write(&self, change: StorageChange) -> Result<(), String> {
431        match &self.backend {
432            Some(backend) => backend.write(change),
433            None => Ok(()),
434        }
435    }
436
437    /// Writes a removal, done in memory whatever comes of it: the app asked
438    /// for the entry gone, and a backend that refuses one (the browser's
439    /// `localStorage` only does when it cannot be reached at all) has
440    /// refused every value since it was read.
441    fn write_removal(&self, change: StorageChange) {
442        if let Err(e) = self.write(change) {
443            log::error!(target: "js", "the app's storage could not be written: {e}");
444        }
445    }
446
447    /// The value of `key`.
448    fn get(&mut self, key: &str) -> Option<String> {
449        self.entries().get(key).cloned()
450    }
451
452    /// Sets `key` to `value` for view `from`; fails past [`QUOTA`].
453    fn set(&mut self, key: String, value: String, from: u64) -> Result<(), StorageFull> {
454        // Loaded first: what the device kept counts too.
455        self.entries();
456        let bytes = self.bytes;
457        let entries = self.entries();
458        let old = entries.get(&key).map_or(0, |v| key.len() + v.len());
459        let new = bytes - old + key.len() + value.len();
460        if new > QUOTA {
461            return Err(StorageFull { bytes: new });
462        }
463        if entries.get(&key) == Some(&value) {
464            return Ok(());
465        }
466        // Written first, the entries changing only once it is kept: under
467        // the lock, so no other core sees it in between.
468        if let Err(e) = self.write(StorageChange::Set(key.clone(), value.clone())) {
469            log::warn!(target: "js", "the app's storage refused {key:?}: {e}");
470            return Err(StorageFull { bytes: new });
471        }
472        self.notify(Some(from), || {
473            StorageChange::Set(key.clone(), value.clone())
474        });
475        self.entries().insert(key, value);
476        self.bytes = new;
477        Ok(())
478    }
479
480    /// Removes `key` for view `from`.
481    fn remove(&mut self, key: &str, from: u64) {
482        let Some(value) = self.entries().remove(key) else {
483            return;
484        };
485        self.bytes -= key.len() + value.len();
486        self.write_removal(StorageChange::Remove(key.to_owned()));
487        self.notify(Some(from), || StorageChange::Remove(key.to_owned()));
488    }
489
490    /// Every key, in order.
491    fn keys(&mut self) -> Vec<String> {
492        self.entries().keys().cloned().collect()
493    }
494
495    /// Removes every entry for view `from`.
496    fn clear(&mut self, from: u64) {
497        let entries = self.entries();
498        if entries.is_empty() {
499            return;
500        }
501        entries.clear();
502        self.bytes = 0;
503        self.write_removal(StorageChange::Clear);
504        self.notify(Some(from), || StorageChange::Clear);
505    }
506
507    /// [`changed_elsewhere`]: told to every watcher when it changes what
508    /// the entries hold.
509    fn changed_elsewhere(&mut self, change: Option<StorageChange>) {
510        let Some(entries) = &mut self.entries else {
511            // The load reads it. Nothing watches yet: a watch loads.
512            return;
513        };
514        let size = |key: &str, value: &str| key.len() + value.len();
515        match change {
516            Some(StorageChange::Set(key, value)) => {
517                if entries.get(&key) == Some(&value) {
518                    return;
519                }
520                self.bytes += size(&key, &value);
521                if let Some(old) = entries.insert(key.clone(), value.clone()) {
522                    self.bytes -= size(&key, &old);
523                }
524                self.notify(None, || StorageChange::Set(key, value));
525            }
526            Some(StorageChange::Remove(key)) => {
527                let Some(old) = entries.remove(&key) else {
528                    return;
529                };
530                self.bytes -= size(&key, &old);
531                self.notify(None, || StorageChange::Remove(key));
532            }
533            Some(StorageChange::Clear) => {
534                if entries.is_empty() {
535                    return;
536                }
537                entries.clear();
538                self.bytes = 0;
539                self.notify(None, || StorageChange::Clear);
540            }
541            None => {
542                let old = self.entries.take().unwrap_or_default();
543                self.bytes = 0;
544                if self.watchers.iter().all(|w| w.inbox.strong_count() == 0) {
545                    // Read again on next use.
546                    return;
547                }
548                // Read again now, for the watchers to hear what changed.
549                let new = self.entries().clone();
550                for change in diff(&old, &new) {
551                    self.notify(None, || change);
552                }
553            }
554        }
555    }
556}
557
558/// The changes that make `old` into `new`, in key order.
559fn diff(old: &BTreeMap<String, String>, new: &BTreeMap<String, String>) -> Vec<StorageChange> {
560    let removed = old
561        .keys()
562        .filter(|key| !new.contains_key(*key))
563        .map(|key| (key, StorageChange::Remove(key.clone())));
564    let set = new
565        .iter()
566        .filter(|(key, value)| old.get(*key) != Some(value))
567        .map(|(key, value)| (key, StorageChange::Set(key.clone(), value.clone())));
568    let mut changes: Vec<_> = removed.chain(set).collect();
569    changes.sort_by(|a, b| a.0.cmp(b.0));
570    changes.into_iter().map(|(_, change)| change).collect()
571}
572
573#[cfg(test)]
574mod tests {
575    use std::sync::Mutex;
576
577    use super::*;
578
579    #[derive(Default)]
580    struct Recorder {
581        kept: BTreeMap<String, String>,
582        changes: Mutex<Vec<StorageChange>>,
583    }
584
585    impl StorageBackend for Recorder {
586        fn load(&self) -> Result<BTreeMap<String, String>, String> {
587            Ok(self.kept.clone())
588        }
589
590        fn write(&self, change: StorageChange) -> Result<(), String> {
591            self.changes.lock().unwrap().push(change);
592            Ok(())
593        }
594    }
595
596    #[test]
597    fn loads_once_and_writes_changes() {
598        let backend = Arc::new(Recorder {
599            kept: BTreeMap::from([("a".into(), "1".into())]),
600            ..Recorder::default()
601        });
602        let storage = Store::new(Some(backend.clone()));
603        assert_eq!(storage.get("a").as_deref(), Some("1"));
604        storage.set("b".into(), "2".into()).unwrap();
605        storage.set("b".into(), "2".into()).unwrap();
606        storage.remove("a");
607        storage.remove("missing");
608        assert_eq!(storage.keys(), ["b"]);
609        storage.clear();
610        assert_eq!(
611            *backend.changes.lock().unwrap(),
612            [
613                StorageChange::Set("b".into(), "2".into()),
614                StorageChange::Remove("a".into()),
615                StorageChange::Clear,
616            ]
617        );
618    }
619
620    #[test]
621    fn views_share_reads_removals_and_clear() {
622        let backend = Arc::new(Recorder::default());
623        let first = Store::new(Some(backend.clone()));
624        let second = Store::new(Some(backend));
625        assert_eq!(second.get("draft"), None);
626        first.set("draft".into(), "saved".into()).unwrap();
627        assert_eq!(second.get("draft").as_deref(), Some("saved"));
628        assert_eq!(second.keys(), ["draft"]);
629        second.remove("draft");
630        assert_eq!(first.get("draft"), None);
631        first.set("draft".into(), "new".into()).unwrap();
632        second.clear();
633        assert!(first.keys().is_empty());
634    }
635
636    #[test]
637    fn concurrent_views_share_the_quota() {
638        let backend = Arc::new(Recorder::default());
639        let barrier = Arc::new(std::sync::Barrier::new(2));
640        let views: Vec<_> = (0..2)
641            .map(|id| {
642                let storage = Store::new(Some(backend.clone()));
643                // Both views load before either writes.
644                assert!(storage.keys().is_empty());
645                let barrier = barrier.clone();
646                std::thread::spawn(move || {
647                    barrier.wait();
648                    storage.set(id.to_string(), "x".repeat(QUOTA - 1))
649                })
650            })
651            .collect();
652        let results: Vec<_> = views.into_iter().map(|v| v.join().unwrap()).collect();
653        assert_eq!(results.iter().filter(|r| r.is_ok()).count(), 1);
654        assert_eq!(backend.changes.lock().unwrap().len(), 1);
655    }
656
657    #[test]
658    fn independent_backends_and_in_memory_views_keep_apart() {
659        for backends in [
660            [None, None],
661            [
662                Some(Arc::new(Recorder::default()) as Arc<dyn StorageBackend>),
663                Some(Arc::new(Recorder::default()) as Arc<dyn StorageBackend>),
664            ],
665        ] {
666            let [first, second] = backends;
667            let first = Store::new(first);
668            let second = Store::new(second);
669            first.set("draft".into(), "saved".into()).unwrap();
670            assert_eq!(second.get("draft"), None);
671            second.clear();
672            assert_eq!(first.get("draft").as_deref(), Some("saved"));
673        }
674    }
675
676    #[test]
677    fn checks_the_quota() {
678        let storage = Store::new(None);
679        storage.set("k".into(), "x".repeat(QUOTA - 1)).unwrap();
680        assert!(storage.set("j".into(), "y".into()).is_err());
681        // Replacing a value counts the new one only.
682        storage.set("k".into(), "z".repeat(QUOTA - 1)).unwrap();
683    }
684
685    #[test]
686    fn the_quota_counts_utf8_bytes_and_frees_on_removal() {
687        let storage = Store::new(None);
688        // "键" is three bytes, "😀" four.
689        storage
690            .set("键".into(), "😀".repeat((QUOTA - 3) / 4))
691            .unwrap();
692        let used = 3 + (QUOTA - 3) / 4 * 4;
693        assert!(storage.set("x".into(), "y".repeat(QUOTA - used)).is_err());
694        // A refused value leaves the entries as they were.
695        assert_eq!(storage.keys(), ["键"]);
696        storage.remove("键");
697        storage.set("x".into(), "y".repeat(QUOTA - 1)).unwrap();
698        storage.clear();
699        assert!(storage.keys().is_empty());
700        storage.set("x".into(), "y".repeat(QUOTA - 1)).unwrap();
701    }
702
703    #[test]
704    fn the_quota_counts_what_was_loaded() {
705        let backend = Arc::new(Recorder {
706            kept: BTreeMap::from([("k".into(), "v".repeat(QUOTA - 1))]),
707            ..Recorder::default()
708        });
709        let storage = Store::new(Some(backend));
710        assert!(storage.set("a".into(), "b".into()).is_err());
711        storage.set("k".into(), "small".into()).unwrap();
712        storage.set("a".into(), "b".into()).unwrap();
713    }
714
715    #[test]
716    fn a_failed_load_starts_empty() {
717        struct Broken;
718        impl StorageBackend for Broken {
719            fn load(&self) -> Result<BTreeMap<String, String>, String> {
720                Err("unreadable".into())
721            }
722
723            fn write(&self, _: StorageChange) -> Result<(), String> {
724                Ok(())
725            }
726        }
727        let storage = Store::new(Some(Arc::new(Broken)));
728        assert_eq!(storage.get("a"), None);
729        storage.set("a".into(), "1".into()).unwrap();
730        assert_eq!(storage.get("a").as_deref(), Some("1"));
731    }
732
733    /// Storage that refuses every change, as `localStorage` does when the
734    /// user blocked it or the browser's quota is used up.
735    struct Refusing {
736        kept: BTreeMap<String, String>,
737    }
738
739    impl StorageBackend for Refusing {
740        fn load(&self) -> Result<BTreeMap<String, String>, String> {
741            Ok(self.kept.clone())
742        }
743
744        fn write(&self, _: StorageChange) -> Result<(), String> {
745            Err("QuotaExceededError".into())
746        }
747    }
748
749    #[test]
750    fn a_value_the_backend_refuses_is_not_kept() {
751        let backend: Arc<dyn StorageBackend> = Arc::new(Refusing {
752            kept: BTreeMap::from([("draft".into(), "old".into())]),
753        });
754        let storage = Store::new(Some(backend.clone()));
755        let other = Store::new(Some(backend));
756        let refused = storage.set("draft".into(), "new".into()).unwrap_err();
757        assert_eq!(refused, StorageFull { bytes: 8 });
758        assert!(refused.to_string().contains("refused"));
759        assert!(storage.set("added".into(), "1".into()).is_err());
760        for view in [&storage, &other] {
761            assert_eq!(view.get("draft").as_deref(), Some("old"));
762            assert_eq!(view.keys(), ["draft"]);
763        }
764    }
765
766    #[test]
767    fn removals_the_backend_refuses_are_done_in_memory() {
768        let storage = Store::new(Some(Arc::new(Refusing {
769            kept: BTreeMap::from([("a".into(), "1".into()), ("b".into(), "2".into())]),
770        })));
771        storage.remove("a");
772        assert_eq!(storage.keys(), ["b"]);
773        storage.clear();
774        assert!(storage.keys().is_empty());
775    }
776
777    #[test]
778    fn changes_made_elsewhere_reach_every_view() {
779        let backend: Arc<dyn StorageBackend> = Arc::new(Recorder {
780            kept: BTreeMap::from([("a".into(), "1".into())]),
781            ..Recorder::default()
782        });
783        let first = Store::new(Some(backend.clone()));
784        let second = Store::new(Some(backend.clone()));
785        assert_eq!(first.get("a").as_deref(), Some("1"));
786        changed_elsewhere(&*backend, Some(StorageChange::Set("a".into(), "2".into())));
787        changed_elsewhere(&*backend, Some(StorageChange::Set("b".into(), "3".into())));
788        assert_eq!(second.get("a").as_deref(), Some("2"));
789        assert_eq!(first.keys(), ["a", "b"]);
790        changed_elsewhere(&*backend, Some(StorageChange::Remove("a".into())));
791        assert_eq!(second.keys(), ["b"]);
792        changed_elsewhere(&*backend, Some(StorageChange::Clear));
793        assert!(first.keys().is_empty());
794        // Nothing went back to the backend.
795        assert!(
796            backend
797                .load()
798                .is_ok_and(|kept| kept == BTreeMap::from([("a".into(), "1".into())]))
799        );
800        // `None`: read again on next use.
801        changed_elsewhere(&*backend, None);
802        assert_eq!(second.get("a").as_deref(), Some("1"));
803    }
804
805    #[test]
806    fn changes_made_elsewhere_count_toward_the_quota() {
807        let backend: Arc<dyn StorageBackend> = Arc::new(Recorder::default());
808        let storage = Store::new(Some(backend.clone()));
809        assert!(storage.keys().is_empty());
810        changed_elsewhere(
811            &*backend,
812            Some(StorageChange::Set("k".into(), "x".repeat(QUOTA - 1))),
813        );
814        assert!(storage.set("j".into(), "y".into()).is_err());
815        changed_elsewhere(&*backend, Some(StorageChange::Set("k".into(), "x".into())));
816        // "k" and "x", then "j" and its value: the quota exactly.
817        storage.set("j".into(), "y".repeat(QUOTA - 3)).unwrap();
818        changed_elsewhere(&*backend, Some(StorageChange::Remove("j".into())));
819        storage.set("i".into(), "y".repeat(QUOTA - 3)).unwrap();
820    }
821
822    #[test]
823    fn changes_made_elsewhere_before_the_first_read_come_with_the_load() {
824        let backend: Arc<dyn StorageBackend> = Arc::new(Recorder {
825            kept: BTreeMap::from([("a".into(), "kept".into())]),
826            ..Recorder::default()
827        });
828        let storage = Store::new(Some(backend.clone()));
829        changed_elsewhere(
830            &*backend,
831            Some(StorageChange::Set("b".into(), "lost".into())),
832        );
833        assert_eq!(storage.keys(), ["a"]);
834        // A backend no core uses takes nothing in.
835        changed_elsewhere(&Recorder::default(), Some(StorageChange::Clear));
836    }
837
838    #[test]
839    fn watchers_hear_other_views_changes_only() {
840        let backend: Arc<dyn StorageBackend> = Arc::new(Recorder {
841            kept: BTreeMap::from([("a".into(), "1".into())]),
842            ..Recorder::default()
843        });
844        let first = Store::new(Some(backend.clone()));
845        let second = Store::new(Some(backend.clone()));
846        let third = Store::new(Some(backend));
847        let heard_by_first = first.watch();
848        let heard_by_second = second.watch();
849        // Each watch has a queue of its own.
850        let also_by_second = second.clone().watch();
851        first.set("theme".into(), "dark".into()).unwrap();
852        // Unchanged: nothing to hear.
853        first.set("theme".into(), "dark".into()).unwrap();
854        first.remove("missing");
855        third.remove("a");
856        second.set("own".into(), "x".into()).unwrap();
857        third.clear();
858        third.clear();
859        let drain = |watch: &Watch| std::iter::from_fn(|| watch.try_next()).collect::<Vec<_>>();
860        assert_eq!(
861            drain(&heard_by_first),
862            [
863                StorageChange::Remove("a".into()),
864                StorageChange::Set("own".into(), "x".into()),
865                StorageChange::Clear,
866            ]
867        );
868        let expected = [
869            StorageChange::Set("theme".into(), "dark".into()),
870            StorageChange::Remove("a".into()),
871            StorageChange::Clear,
872        ];
873        assert_eq!(drain(&heard_by_second), expected);
874        assert_eq!(drain(&also_by_second), expected);
875        // A dropped watch is let go.
876        drop(heard_by_first);
877        third.set("b".into(), "2".into()).unwrap();
878        assert_eq!(drain(&heard_by_second).len(), 1);
879    }
880
881    #[test]
882    fn watchers_hear_what_other_writers_changed() {
883        let backend = Arc::new(Recorder {
884            kept: BTreeMap::from([("a".into(), "1".into()), ("b".into(), "2".into())]),
885            ..Recorder::default()
886        });
887        let shared: Arc<dyn StorageBackend> = backend.clone();
888        let storage = Store::new(Some(shared.clone()));
889        let watch = storage.watch();
890        let drain = || std::iter::from_fn(|| watch.try_next()).collect::<Vec<_>>();
891        changed_elsewhere(&*shared, Some(StorageChange::Set("a".into(), "one".into())));
892        // What the entries hold already (this view wrote it since).
893        changed_elsewhere(&*shared, Some(StorageChange::Set("a".into(), "one".into())));
894        changed_elsewhere(&*shared, Some(StorageChange::Remove("missing".into())));
895        changed_elsewhere(&*shared, Some(StorageChange::Remove("b".into())));
896        assert_eq!(
897            drain(),
898            [
899                StorageChange::Set("a".into(), "one".into()),
900                StorageChange::Remove("b".into()),
901            ]
902        );
903        assert_eq!(storage.get("a").as_deref(), Some("one"));
904        // `None`: read again at once, what changed told key by key. The
905        // backend still holds what it was made with.
906        changed_elsewhere(&*shared, None);
907        assert_eq!(
908            drain(),
909            [
910                StorageChange::Set("a".into(), "1".into()),
911                StorageChange::Set("b".into(), "2".into()),
912            ]
913        );
914        changed_elsewhere(&*shared, Some(StorageChange::Set("c".into(), "3".into())));
915        changed_elsewhere(&*shared, Some(StorageChange::Remove("a".into())));
916        drain();
917        changed_elsewhere(&*shared, None);
918        assert_eq!(
919            drain(),
920            [
921                StorageChange::Set("a".into(), "1".into()),
922                StorageChange::Remove("c".into()),
923            ]
924        );
925        changed_elsewhere(&*shared, Some(StorageChange::Clear));
926        changed_elsewhere(&*shared, Some(StorageChange::Clear));
927        assert_eq!(drain(), [StorageChange::Clear]);
928        assert!(backend.changes.lock().unwrap().is_empty());
929    }
930
931    #[test]
932    fn a_watch_waits_for_the_next_change() {
933        use std::task::{Context, Wake};
934
935        struct Flag(std::sync::atomic::AtomicBool);
936        impl Wake for Flag {
937            fn wake(self: Arc<Self>) {
938                self.0.store(true, Ordering::SeqCst);
939            }
940        }
941        let backend: Arc<dyn StorageBackend> = Arc::new(Recorder::default());
942        let watching = Store::new(Some(backend.clone()));
943        let writing = Store::new(Some(backend));
944        let watch = watching.watch();
945        let flag = Arc::new(Flag(Default::default()));
946        let waker = Waker::from(flag.clone());
947        let mut cx = Context::from_waker(&waker);
948        let mut next = Box::pin(watch.next());
949        assert!(next.as_mut().poll(&mut cx).is_pending());
950        // Written on another thread, as another window's engine does.
951        std::thread::spawn(move || writing.set("k".into(), "v".into()).unwrap())
952            .join()
953            .unwrap();
954        assert!(flag.0.load(Ordering::SeqCst));
955        assert_eq!(
956            next.as_mut().poll(&mut cx),
957            Poll::Ready(StorageChange::Set("k".into(), "v".into()))
958        );
959    }
960
961    #[test]
962    fn a_change_names_its_key_and_value() {
963        let set = StorageChange::Set("k".into(), "v".into());
964        assert_eq!((set.key(), set.value()), (Some("k"), Some("v")));
965        let removed = StorageChange::Remove("k".into());
966        assert_eq!((removed.key(), removed.value()), (Some("k"), None));
967        assert_eq!(
968            (StorageChange::Clear.key(), StorageChange::Clear.value()),
969            (None, None)
970        );
971    }
972}