Skip to main content

nsh_engine/
storage.rs

1//! The app's storage in a file (`nsh/storage` on the native platforms):
2//! its entries as one JSON object, rewritten whole (to a temporary file,
3//! then renamed over it) on a thread of its own after changes, so a crash
4//! leaves the old file or the new one. One instance per file in the
5//! process ([`FileStorage::open`]), which keeps the entries in memory: an
6//! app reloaded before its writes reached the disk reads them all the same.
7
8use std::{
9    collections::BTreeMap,
10    path::{Path, PathBuf},
11    sync::{Arc, Mutex, Weak},
12    thread::JoinHandle,
13};
14
15use crossbeam_channel::{Receiver, Sender};
16use nsh_core::storage::{StorageBackend, StorageChange};
17
18/// An app's storage kept in `storage.json` of a directory: the app's in
19/// [`crate::EngineConfig::data_dir`], or one the embedding app chooses.
20pub struct FileStorage {
21    path: PathBuf,
22    /// The entries as changed so far, once read.
23    entries: Mutex<Option<BTreeMap<String, String>>>,
24    /// The file could not be read: changes stay in memory, never replacing
25    /// what it holds.
26    in_memory: std::sync::atomic::AtomicBool,
27    writer: Mutex<Option<(Sender<StorageChange>, JoinHandle<()>)>>,
28}
29
30impl FileStorage {
31    /// The storage in `dir/storage.json`: the one already open in this
32    /// process, or a new one (the directory is made on the first write).
33    pub fn open(dir: impl Into<PathBuf>) -> Arc<Self> {
34        // By path, so that finding one upgrades no other: a reference taken
35        // even briefly would move the other's last drop, which waits for
36        // its writes, to this thread, after its owner thought it done.
37        static OPEN: Mutex<Vec<(PathBuf, Weak<FileStorage>)>> = Mutex::new(Vec::new());
38        let path = dir.into().join("storage.json");
39        let mut open = OPEN.lock().unwrap_or_else(|e| e.into_inner());
40        open.retain(|(_, s)| s.strong_count() > 0);
41        if let Some(storage) = open
42            .iter()
43            .find(|(p, _)| *p == path)
44            .and_then(|(_, s)| s.upgrade())
45        {
46            return storage;
47        }
48        let storage = Arc::new(Self {
49            path,
50            entries: Mutex::new(None),
51            in_memory: std::sync::atomic::AtomicBool::new(false),
52            writer: Mutex::new(None),
53        });
54        open.push((storage.path.clone(), Arc::downgrade(&storage)));
55        storage
56    }
57
58    /// The file it keeps the entries in.
59    pub fn path(&self) -> &Path {
60        &self.path
61    }
62}
63
64/// The system's directory for apps' data: Application Support on Apple
65/// platforms, `%APPDATA%` on Windows, `$XDG_DATA_HOME` (`~/.local/share`)
66/// elsewhere. `None` on Android, whose files directory only the platform
67/// knows, and without a home directory. An app of its own keeps its data in
68/// `<data_dir>/<app id>` ([`crate::EngineConfig::data_dir`]).
69pub fn data_dir() -> Option<PathBuf> {
70    data_dir_in(std::env::consts::OS, |name| {
71        std::env::var_os(name).map(PathBuf::from)
72    })
73}
74
75/// [`data_dir`] on `os` (`std::env::consts::OS`) with the environment `env`.
76fn data_dir_in(os: &str, env: impl Fn(&str) -> Option<PathBuf>) -> Option<PathBuf> {
77    let env = |name| env(name).filter(|v| !v.as_os_str().is_empty());
78    match os {
79        "android" => None,
80        "macos" | "ios" => env("HOME").map(|home| home.join("Library/Application Support")),
81        "windows" => env("APPDATA"),
82        _ => env("XDG_DATA_HOME").or_else(|| env("HOME").map(|home| home.join(".local/share"))),
83    }
84}
85
86#[cfg(test)]
87use crate::app_dir_name;
88
89fn read(path: &Path) -> Result<BTreeMap<String, String>, String> {
90    match std::fs::read(path) {
91        Ok(bytes) => serde_json::from_slice(&bytes).map_err(|e| format!("{}: {e}", path.display())),
92        Err(e) if e.kind() == std::io::ErrorKind::NotFound => Ok(BTreeMap::new()),
93        Err(e) => Err(format!("{}: {e}", path.display())),
94    }
95}
96
97/// [`read`], setting a file that is no storage aside (`storage.json.corrupt`)
98/// rather than letting the next write replace what it held. The error says
99/// whether the file may be written: not when it is still there, unread.
100fn read_or_set_aside(path: &Path) -> Result<BTreeMap<String, String>, (String, bool)> {
101    read(path).map_err(|e| {
102        // Only a file that reads but does not parse is set aside: one that
103        // cannot be read now may hold the app's data.
104        if std::fs::read(path).is_err() {
105            return (format!("{e}; it is kept in memory"), false);
106        }
107        let aside = path.with_extension("json.corrupt");
108        match std::fs::rename(path, &aside) {
109            Ok(()) => (
110                format!("{e}; it was set aside as {}", aside.display()),
111                true,
112            ),
113            Err(rename) => (
114                format!("{e}; it could not be set aside ({rename}), so it is kept in memory"),
115                false,
116            ),
117        }
118    })
119}
120
121fn write(path: &Path, entries: &BTreeMap<String, String>) -> std::io::Result<()> {
122    if let Some(dir) = path.parent() {
123        std::fs::create_dir_all(dir)?;
124    }
125    let temporary = path.with_extension("json.tmp");
126    let file = std::fs::File::create(&temporary)?;
127    let mut out = std::io::BufWriter::new(file);
128    serde_json::to_writer(&mut out, entries)?;
129    let file = out.into_inner().map_err(|e| e.into_error())?;
130    file.sync_all()?;
131    std::fs::rename(&temporary, path)
132}
133
134fn apply(entries: &mut BTreeMap<String, String>, change: StorageChange) {
135    match change {
136        StorageChange::Set(key, value) => {
137            entries.insert(key, value);
138        }
139        StorageChange::Remove(key) => {
140            entries.remove(&key);
141        }
142        StorageChange::Clear => entries.clear(),
143    }
144}
145
146/// Applies the changes as they come, writing the file once per burst.
147fn run_writer(path: PathBuf, changes: Receiver<StorageChange>) {
148    let mut entries = read(&path).unwrap_or_default();
149    while let Ok(change) = changes.recv() {
150        apply(&mut entries, change);
151        changes
152            .try_iter()
153            .for_each(|change| apply(&mut entries, change));
154        if let Err(e) = write(&path, &entries) {
155            log::error!(target: "js", "the app's storage could not be written to {}: {e}", path.display());
156        }
157    }
158}
159
160impl StorageBackend for FileStorage {
161    fn load(&self) -> Result<BTreeMap<String, String>, String> {
162        let mut entries = self.entries.lock().unwrap_or_else(|e| e.into_inner());
163        if let Some(entries) = &*entries {
164            return Ok(entries.clone());
165        }
166        match read_or_set_aside(&self.path) {
167            Ok(read) => {
168                *entries = Some(read.clone());
169                Ok(read)
170            }
171            Err((e, writable)) => {
172                *entries = Some(BTreeMap::new());
173                if !writable {
174                    self.in_memory
175                        .store(true, std::sync::atomic::Ordering::Relaxed);
176                }
177                Err(e)
178            }
179        }
180    }
181
182    fn write(&self, change: StorageChange) {
183        if let Some(entries) = &mut *self.entries.lock().unwrap_or_else(|e| e.into_inner()) {
184            apply(entries, change.clone());
185        }
186        if self.in_memory.load(std::sync::atomic::Ordering::Relaxed) {
187            return;
188        }
189        let mut writer = self.writer.lock().unwrap_or_else(|e| e.into_inner());
190        let (changes, _) = writer.get_or_insert_with(|| {
191            let (tx, rx) = crossbeam_channel::unbounded();
192            let path = self.path.clone();
193            let thread = std::thread::Builder::new()
194                .name("nsh-storage".into())
195                .spawn(move || run_writer(path, rx))
196                .expect("the storage thread starts");
197            (tx, thread)
198        });
199        // The writer only stops when this is dropped.
200        let _ = changes.send(change);
201    }
202}
203
204impl Drop for FileStorage {
205    /// Waits for the last changes to be written.
206    fn drop(&mut self) {
207        let writer = self
208            .writer
209            .get_mut()
210            .unwrap_or_else(|e| e.into_inner())
211            .take();
212        if let Some((changes, thread)) = writer {
213            drop(changes);
214            let _ = thread.join();
215        }
216    }
217}
218
219#[cfg(test)]
220mod tests {
221    use super::*;
222
223    /// An empty directory of its own under the test's temporary directory.
224    fn scratch(name: &str) -> PathBuf {
225        let dir =
226            std::env::temp_dir().join(format!("nsh-file-storage-{}-{name}", std::process::id()));
227        let _ = std::fs::remove_dir_all(&dir);
228        std::fs::create_dir_all(&dir).unwrap();
229        dir
230    }
231
232    #[test]
233    fn keeps_entries_across_instances() {
234        let dir = scratch("instances");
235        let storage = FileStorage::open(&dir);
236        assert!(storage.load().unwrap().is_empty());
237        storage.write(StorageChange::Set("a".into(), "1".into()));
238        storage.write(StorageChange::Set("b".into(), "2".into()));
239        // A reload while the first is open shares its entries, written or not.
240        let reloaded = FileStorage::open(&dir);
241        assert!(Arc::ptr_eq(&storage, &reloaded));
242        storage.write(StorageChange::Remove("a".into()));
243        assert_eq!(reloaded.load().unwrap().len(), 1);
244        drop((storage, reloaded));
245        let again = FileStorage::open(&dir);
246        assert_eq!(
247            again.load().unwrap(),
248            BTreeMap::from([("b".to_owned(), "2".to_owned())])
249        );
250        again.write(StorageChange::Clear);
251        drop(again);
252        assert!(FileStorage::open(&dir).load().unwrap().is_empty());
253        std::fs::remove_dir_all(&dir).unwrap();
254    }
255
256    #[test]
257    fn data_directories_follow_each_platform() {
258        let env = |vars: &'static [(&'static str, &'static str)]| {
259            move |name: &str| {
260                vars.iter()
261                    .find(|(n, _)| *n == name)
262                    .map(|(_, v)| PathBuf::from(v))
263            }
264        };
265        let home = env(&[
266            ("HOME", "/home/a"),
267            ("APPDATA", r"C:\Users\a\AppData\Roaming"),
268        ]);
269        assert_eq!(
270            data_dir_in("linux", home),
271            Some(PathBuf::from("/home/a/.local/share"))
272        );
273        assert_eq!(
274            data_dir_in(
275                "linux",
276                env(&[("XDG_DATA_HOME", "/data"), ("HOME", "/home/a")])
277            ),
278            Some(PathBuf::from("/data"))
279        );
280        // An empty variable counts as unset.
281        assert_eq!(
282            data_dir_in("linux", env(&[("XDG_DATA_HOME", ""), ("HOME", "/home/a")])),
283            Some(PathBuf::from("/home/a/.local/share"))
284        );
285        let support = Some(PathBuf::from("/home/a/Library/Application Support"));
286        assert_eq!(data_dir_in("macos", home), support);
287        assert_eq!(data_dir_in("ios", home), support);
288        assert_eq!(
289            data_dir_in("windows", home),
290            Some(PathBuf::from(r"C:\Users\a\AppData\Roaming"))
291        );
292        // Android's files directory is the platform's to give.
293        assert_eq!(data_dir_in("android", home), None);
294        assert_eq!(data_dir_in("linux", env(&[])), None);
295    }
296
297    #[test]
298    fn apps_get_directories_of_their_own() {
299        assert_eq!(app_dir_name(Some("com.example.app")), "com.example.app");
300        assert_eq!(app_dir_name(Some("..app")), "..app");
301        assert_eq!(app_dir_name(None), "default");
302        // An id that is no directory name cannot reach another directory.
303        for id in ["", ".", "..", "../etc", "a/b", r"a\b", "a\0b"] {
304            assert_eq!(app_dir_name(Some(id)), "default", "{id:?}");
305        }
306    }
307
308    #[test]
309    fn a_damaged_file_is_set_aside_not_replaced() {
310        let dir = scratch("damaged");
311        let file = dir.join("storage.json");
312        std::fs::write(&file, b"{ not json").unwrap();
313        let storage = FileStorage::open(&dir);
314        let error = storage.load().unwrap_err();
315        assert!(error.contains("set aside"), "{error}");
316        let aside = dir.join("storage.json.corrupt");
317        assert_eq!(std::fs::read(&aside).unwrap(), b"{ not json");
318        // The app goes on with new entries, and the old file is still there.
319        storage.write(StorageChange::Set("a".into(), "1".into()));
320        drop(storage);
321        assert_eq!(std::fs::read_to_string(&file).unwrap(), r#"{"a":"1"}"#);
322        assert_eq!(std::fs::read(&aside).unwrap(), b"{ not json");
323        // Values that are not strings are no storage either.
324        let typed = scratch("typed");
325        std::fs::write(typed.join("storage.json"), br#"{"n": 1}"#).unwrap();
326        assert!(FileStorage::open(&typed).load().is_err());
327        assert!(typed.join("storage.json.corrupt").exists());
328    }
329
330    #[test]
331    #[cfg(unix)]
332    fn an_unreadable_file_is_never_replaced() {
333        use std::os::unix::fs::PermissionsExt;
334        let dir = scratch("unreadable");
335        let file = dir.join("storage.json");
336        std::fs::write(&file, br#"{"kept":"yes"}"#).unwrap();
337        std::fs::set_permissions(&file, std::fs::Permissions::from_mode(0o200)).unwrap();
338        if std::fs::read(&file).is_ok() {
339            // Root reads it anyway: nothing to check.
340            return;
341        }
342        let storage = FileStorage::open(&dir);
343        assert!(storage.load().is_err());
344        storage.write(StorageChange::Set("a".into(), "1".into()));
345        drop(storage);
346        std::fs::set_permissions(&file, std::fs::Permissions::from_mode(0o600)).unwrap();
347        assert_eq!(std::fs::read_to_string(&file).unwrap(), r#"{"kept":"yes"}"#);
348    }
349
350    #[test]
351    fn a_failed_write_leaves_the_entries_in_memory() {
352        // A file where the directory should be: nothing can be written.
353        let dir = scratch("unwritable");
354        let blocked = dir.join("file");
355        std::fs::write(&blocked, b"").unwrap();
356        let storage = FileStorage::open(blocked.join("app"));
357        assert!(storage.load().unwrap_err().contains("kept in memory"));
358        storage.write(StorageChange::Set("a".into(), "1".into()));
359        assert_eq!(
360            storage.load().unwrap().get("a").map(String::as_str),
361            Some("1")
362        );
363        drop(storage);
364        assert!(!blocked.join("app").exists());
365    }
366}