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 data
19/// directory ([`crate::EngineConfig::data_dir`]), or one the embedding app
20/// chooses.
21pub struct FileStorage {
22    path: PathBuf,
23    /// The entries as changed so far, once read.
24    entries: Mutex<Option<BTreeMap<String, String>>>,
25    /// The file could not be read: changes stay in memory, never replacing
26    /// what it holds.
27    in_memory: std::sync::atomic::AtomicBool,
28    writer: Mutex<Option<(Sender<StorageChange>, JoinHandle<()>)>>,
29}
30
31impl FileStorage {
32    /// The storage in `dir/storage.json`: the one already open in this
33    /// process, or a new one (the directory is made on the first write).
34    pub fn open(dir: impl Into<PathBuf>) -> Arc<Self> {
35        // By path, so that finding one upgrades no other: a reference taken
36        // even briefly would move the other's last drop, which waits for
37        // its writes, to this thread, after its owner thought it done.
38        static OPEN: Mutex<Vec<(PathBuf, Weak<FileStorage>)>> = Mutex::new(Vec::new());
39        let path = dir.into().join("storage.json");
40        let mut open = OPEN.lock().unwrap_or_else(|e| e.into_inner());
41        open.retain(|(_, s)| s.strong_count() > 0);
42        if let Some(storage) = open
43            .iter()
44            .find(|(p, _)| *p == path)
45            .and_then(|(_, s)| s.upgrade())
46        {
47            return storage;
48        }
49        let storage = Arc::new(Self {
50            path,
51            entries: Mutex::new(None),
52            in_memory: std::sync::atomic::AtomicBool::new(false),
53            writer: Mutex::new(None),
54        });
55        open.push((storage.path.clone(), Arc::downgrade(&storage)));
56        storage
57    }
58
59    /// The file it keeps the entries in.
60    pub fn path(&self) -> &Path {
61        &self.path
62    }
63}
64
65/// The system's directory for apps' data, where each app keeps its own
66/// under its id unless it names one (what the platforms give as
67/// [`crate::EngineConfig::support_dir`]): Application Support on Apple platforms, `%APPDATA%` on
68/// Windows, `$XDG_DATA_HOME` (`~/.local/share`) elsewhere. `None` on
69/// Android, whose files directory only the platform knows, and without a
70/// home directory.
71#[doc(hidden)]
72pub fn support_dir() -> Option<PathBuf> {
73    support_dir_in(std::env::consts::OS, |name| {
74        std::env::var_os(name).map(PathBuf::from)
75    })
76}
77
78/// [`support_dir`] on `os` (`std::env::consts::OS`) with the environment
79/// `env`.
80fn support_dir_in(os: &str, env: impl Fn(&str) -> Option<PathBuf>) -> Option<PathBuf> {
81    let env = |name| env(name).filter(|v| !v.as_os_str().is_empty());
82    match os {
83        "android" => None,
84        "macos" | "ios" => env("HOME").map(|home| home.join("Library/Application Support")),
85        "windows" => env("APPDATA"),
86        _ => env("XDG_DATA_HOME").or_else(|| env("HOME").map(|home| home.join(".local/share"))),
87    }
88}
89
90/// The data directory `nsh.json` `"dataDir"` names (`template`), which the
91/// desktop runners give the engine ([`crate::EngineConfig::data_dir`]): an
92/// absolute path, or `${homeDir}` followed by one under this user's home
93/// directory (`$HOME`; `%USERPROFILE%` on Windows). `None` for anything
94/// else (a relative path, `..`, another `${...}`) and for `${homeDir}`
95/// without a home: the app then keeps its data where it would without
96/// `"dataDir"`, rather than somewhere relative to where it started.
97pub fn resolve_data_dir(template: &str) -> Option<PathBuf> {
98    let home = if cfg!(windows) { "USERPROFILE" } else { "HOME" };
99    let home = std::env::var_os(home)
100        .filter(|v| !v.is_empty())
101        .map(PathBuf::from);
102    resolve_data_dir_in(template, home.as_deref())
103}
104
105/// [`resolve_data_dir`] with the home directory `home`.
106fn resolve_data_dir_in(template: &str, home: Option<&Path>) -> Option<PathBuf> {
107    const HOME: &str = "${homeDir}";
108    let path = match template.strip_prefix(HOME) {
109        Some("") => home?.to_path_buf(),
110        Some(rest) => {
111            let rest = rest.strip_prefix(['/', '\\'])?;
112            home?.join(rest)
113        }
114        None => PathBuf::from(template),
115    };
116    let rest = template.strip_prefix(HOME).unwrap_or(template);
117    if rest.contains("${") || !path.is_absolute() {
118        return None;
119    }
120    if path
121        .components()
122        .any(|c| matches!(c, std::path::Component::ParentDir))
123    {
124        return None;
125    }
126    Some(path)
127}
128
129/// The system's directory for caches: Caches on Apple platforms,
130/// `%LOCALAPPDATA%` on Windows, `$XDG_CACHE_HOME` (`~/.cache`) elsewhere.
131/// `None` on Android, whose cache directory only the platform knows, and
132/// without a home directory: what [`crate::CacheLocation::System`] is
133/// unless the platform resolves it itself.
134pub(crate) fn cache_dir() -> Option<PathBuf> {
135    cache_dir_in(std::env::consts::OS, |name| {
136        std::env::var_os(name).map(PathBuf::from)
137    })
138}
139
140/// [`cache_dir`] on `os` (`std::env::consts::OS`) with the environment `env`.
141fn cache_dir_in(os: &str, env: impl Fn(&str) -> Option<PathBuf>) -> Option<PathBuf> {
142    let env = |name| env(name).filter(|v| !v.as_os_str().is_empty());
143    match os {
144        "android" => None,
145        "macos" | "ios" => env("HOME").map(|home| home.join("Library/Caches")),
146        "windows" => env("LOCALAPPDATA"),
147        _ => env("XDG_CACHE_HOME").or_else(|| env("HOME").map(|home| home.join(".cache"))),
148    }
149}
150
151#[cfg(test)]
152use crate::app_dir_name;
153
154fn read(path: &Path) -> Result<BTreeMap<String, String>, String> {
155    match std::fs::read(path) {
156        Ok(bytes) => serde_json::from_slice(&bytes).map_err(|e| format!("{}: {e}", path.display())),
157        Err(e) if e.kind() == std::io::ErrorKind::NotFound => Ok(BTreeMap::new()),
158        Err(e) => Err(format!("{}: {e}", path.display())),
159    }
160}
161
162/// [`read`], setting a file that is no storage aside (`storage.json.corrupt`)
163/// rather than letting the next write replace what it held. The error says
164/// whether the file may be written: not when it is still there, unread.
165fn read_or_set_aside(path: &Path) -> Result<BTreeMap<String, String>, (String, bool)> {
166    read(path).map_err(|e| {
167        // Only a file that reads but does not parse is set aside: one that
168        // cannot be read now may hold the app's data.
169        if std::fs::read(path).is_err() {
170            return (format!("{e}; it is kept in memory"), false);
171        }
172        let aside = path.with_extension("json.corrupt");
173        match std::fs::rename(path, &aside) {
174            Ok(()) => (
175                format!("{e}; it was set aside as {}", aside.display()),
176                true,
177            ),
178            Err(rename) => (
179                format!("{e}; it could not be set aside ({rename}), so it is kept in memory"),
180                false,
181            ),
182        }
183    })
184}
185
186fn write(path: &Path, entries: &BTreeMap<String, String>) -> std::io::Result<()> {
187    if let Some(dir) = path.parent() {
188        std::fs::create_dir_all(dir)?;
189    }
190    let temporary = path.with_extension("json.tmp");
191    let file = std::fs::File::create(&temporary)?;
192    let mut out = std::io::BufWriter::new(file);
193    serde_json::to_writer(&mut out, entries)?;
194    let file = out.into_inner().map_err(|e| e.into_error())?;
195    file.sync_all()?;
196    std::fs::rename(&temporary, path)
197}
198
199fn apply(entries: &mut BTreeMap<String, String>, change: StorageChange) {
200    match change {
201        StorageChange::Set(key, value) => {
202            entries.insert(key, value);
203        }
204        StorageChange::Remove(key) => {
205            entries.remove(&key);
206        }
207        StorageChange::Clear => entries.clear(),
208    }
209}
210
211/// Applies the changes as they come, writing the file once per burst.
212fn run_writer(path: PathBuf, changes: Receiver<StorageChange>) {
213    let mut entries = read(&path).unwrap_or_default();
214    while let Ok(change) = changes.recv() {
215        apply(&mut entries, change);
216        changes
217            .try_iter()
218            .for_each(|change| apply(&mut entries, change));
219        if let Err(e) = write(&path, &entries) {
220            log::error!(target: "js", "the app's storage could not be written to {}: {e}", path.display());
221        }
222    }
223}
224
225impl StorageBackend for FileStorage {
226    fn load(&self) -> Result<BTreeMap<String, String>, String> {
227        let mut entries = self.entries.lock().unwrap_or_else(|e| e.into_inner());
228        if let Some(entries) = &*entries {
229            return Ok(entries.clone());
230        }
231        match read_or_set_aside(&self.path) {
232            Ok(read) => {
233                *entries = Some(read.clone());
234                Ok(read)
235            }
236            Err((e, writable)) => {
237                *entries = Some(BTreeMap::new());
238                if !writable {
239                    self.in_memory
240                        .store(true, std::sync::atomic::Ordering::Relaxed);
241                }
242                Err(e)
243            }
244        }
245    }
246
247    /// Hands `change` to the writer thread: the file is written after this
248    /// returns, so an error writing it is only logged, and the change stays
249    /// in memory, written with the next.
250    fn write(&self, change: StorageChange) -> Result<(), String> {
251        if let Some(entries) = &mut *self.entries.lock().unwrap_or_else(|e| e.into_inner()) {
252            apply(entries, change.clone());
253        }
254        if self.in_memory.load(std::sync::atomic::Ordering::Relaxed) {
255            return Ok(());
256        }
257        let mut writer = self.writer.lock().unwrap_or_else(|e| e.into_inner());
258        let (changes, _) = writer.get_or_insert_with(|| {
259            let (tx, rx) = crossbeam_channel::unbounded();
260            let path = self.path.clone();
261            let thread = std::thread::Builder::new()
262                .name("nsh-storage".into())
263                .spawn(move || run_writer(path, rx))
264                .expect("the storage thread starts");
265            (tx, thread)
266        });
267        // The writer only stops when this is dropped.
268        let _ = changes.send(change);
269        Ok(())
270    }
271}
272
273impl Drop for FileStorage {
274    /// Waits for the last changes to be written.
275    fn drop(&mut self) {
276        let writer = self
277            .writer
278            .get_mut()
279            .unwrap_or_else(|e| e.into_inner())
280            .take();
281        if let Some((changes, thread)) = writer {
282            drop(changes);
283            let _ = thread.join();
284        }
285    }
286}
287
288#[cfg(test)]
289mod tests {
290    use super::*;
291
292    /// An empty directory of its own under the test's temporary directory.
293    fn scratch(name: &str) -> PathBuf {
294        let dir =
295            std::env::temp_dir().join(format!("nsh-file-storage-{}-{name}", std::process::id()));
296        let _ = std::fs::remove_dir_all(&dir);
297        std::fs::create_dir_all(&dir).unwrap();
298        dir
299    }
300
301    #[test]
302    fn keeps_entries_across_instances() {
303        let dir = scratch("instances");
304        let storage = FileStorage::open(&dir);
305        assert!(storage.load().unwrap().is_empty());
306        storage
307            .write(StorageChange::Set("a".into(), "1".into()))
308            .unwrap();
309        storage
310            .write(StorageChange::Set("b".into(), "2".into()))
311            .unwrap();
312        // A reload while the first is open shares its entries, written or not.
313        let reloaded = FileStorage::open(&dir);
314        assert!(Arc::ptr_eq(&storage, &reloaded));
315        storage.write(StorageChange::Remove("a".into())).unwrap();
316        assert_eq!(reloaded.load().unwrap().len(), 1);
317        drop((storage, reloaded));
318        let again = FileStorage::open(&dir);
319        assert_eq!(
320            again.load().unwrap(),
321            BTreeMap::from([("b".to_owned(), "2".to_owned())])
322        );
323        again.write(StorageChange::Clear).unwrap();
324        drop(again);
325        assert!(FileStorage::open(&dir).load().unwrap().is_empty());
326        std::fs::remove_dir_all(&dir).unwrap();
327    }
328
329    #[test]
330    fn an_apps_data_dir_is_absolute_or_under_the_home_directory() {
331        let home = std::env::temp_dir().join("home");
332        let resolve = |template| resolve_data_dir_in(template, Some(&home));
333        assert_eq!(resolve("${homeDir}/.myapp"), Some(home.join(".myapp")));
334        assert_eq!(
335            resolve("${homeDir}/.myapp/ui"),
336            Some(home.join(".myapp/ui"))
337        );
338        assert_eq!(resolve("${homeDir}"), Some(home.clone()));
339        let absolute = std::env::temp_dir().join("myapp");
340        assert_eq!(
341            resolve_data_dir_in(absolute.to_str().unwrap(), None),
342            Some(absolute.clone())
343        );
344        // Refused: relative, other placeholders, `..`, a home that is not there.
345        assert_eq!(resolve(".myapp"), None);
346        assert_eq!(resolve("${homeDir}.myapp"), None);
347        assert_eq!(resolve("${appId}/data"), None);
348        assert_eq!(resolve("${homeDir}/${appId}"), None);
349        assert_eq!(resolve("${homeDir}/../elsewhere"), None);
350        assert_eq!(resolve_data_dir_in("${homeDir}/.myapp", None), None);
351    }
352
353    #[test]
354    fn data_directories_follow_each_platform() {
355        let env = |vars: &'static [(&'static str, &'static str)]| {
356            move |name: &str| {
357                vars.iter()
358                    .find(|(n, _)| *n == name)
359                    .map(|(_, v)| PathBuf::from(v))
360            }
361        };
362        let home = env(&[
363            ("HOME", "/home/a"),
364            ("APPDATA", r"C:\Users\a\AppData\Roaming"),
365        ]);
366        assert_eq!(
367            support_dir_in("linux", home),
368            Some(PathBuf::from("/home/a/.local/share"))
369        );
370        assert_eq!(
371            support_dir_in(
372                "linux",
373                env(&[("XDG_DATA_HOME", "/data"), ("HOME", "/home/a")])
374            ),
375            Some(PathBuf::from("/data"))
376        );
377        // An empty variable counts as unset.
378        assert_eq!(
379            support_dir_in("linux", env(&[("XDG_DATA_HOME", ""), ("HOME", "/home/a")])),
380            Some(PathBuf::from("/home/a/.local/share"))
381        );
382        let support = Some(PathBuf::from("/home/a/Library/Application Support"));
383        assert_eq!(support_dir_in("macos", home), support);
384        assert_eq!(support_dir_in("ios", home), support);
385        assert_eq!(
386            support_dir_in("windows", home),
387            Some(PathBuf::from(r"C:\Users\a\AppData\Roaming"))
388        );
389        // Android's files directory is the platform's to give.
390        assert_eq!(support_dir_in("android", home), None);
391        assert_eq!(support_dir_in("linux", env(&[])), None);
392    }
393
394    #[test]
395    fn cache_directories_follow_each_platform() {
396        let vars = |vars: &'static [(&'static str, &'static str)]| {
397            move |name: &str| {
398                vars.iter()
399                    .find(|(n, _)| *n == name)
400                    .map(|(_, v)| PathBuf::from(v))
401            }
402        };
403        let home = vars(&[
404            ("HOME", "/home/a"),
405            ("LOCALAPPDATA", r"C:\Users\a\AppData\Local"),
406        ]);
407        assert_eq!(
408            cache_dir_in("linux", home),
409            Some(PathBuf::from("/home/a/.cache"))
410        );
411        assert_eq!(
412            cache_dir_in(
413                "linux",
414                vars(&[("XDG_CACHE_HOME", "/c"), ("HOME", "/home/a")])
415            ),
416            Some(PathBuf::from("/c"))
417        );
418        assert_eq!(
419            cache_dir_in("macos", home),
420            Some(PathBuf::from("/home/a/Library/Caches"))
421        );
422        assert_eq!(
423            cache_dir_in("windows", home),
424            Some(PathBuf::from(r"C:\Users\a\AppData\Local"))
425        );
426        assert_eq!(cache_dir_in("android", home), None);
427    }
428
429    #[test]
430    fn apps_get_directories_of_their_own() {
431        assert_eq!(app_dir_name(Some("com.example.app")), "com.example.app");
432        assert_eq!(app_dir_name(Some("..app")), "..app");
433        assert_eq!(app_dir_name(None), "default");
434        // An id that is no directory name cannot reach another directory.
435        for id in ["", ".", "..", "../etc", "a/b", r"a\b", "a\0b"] {
436            assert_eq!(app_dir_name(Some(id)), "default", "{id:?}");
437        }
438    }
439
440    #[test]
441    fn a_damaged_file_is_set_aside_not_replaced() {
442        let dir = scratch("damaged");
443        let file = dir.join("storage.json");
444        std::fs::write(&file, b"{ not json").unwrap();
445        let storage = FileStorage::open(&dir);
446        let error = storage.load().unwrap_err();
447        assert!(error.contains("set aside"), "{error}");
448        let aside = dir.join("storage.json.corrupt");
449        assert_eq!(std::fs::read(&aside).unwrap(), b"{ not json");
450        // The app goes on with new entries, and the old file is still there.
451        storage
452            .write(StorageChange::Set("a".into(), "1".into()))
453            .unwrap();
454        drop(storage);
455        assert_eq!(std::fs::read_to_string(&file).unwrap(), r#"{"a":"1"}"#);
456        assert_eq!(std::fs::read(&aside).unwrap(), b"{ not json");
457        // Values that are not strings are no storage either.
458        let typed = scratch("typed");
459        std::fs::write(typed.join("storage.json"), br#"{"n": 1}"#).unwrap();
460        assert!(FileStorage::open(&typed).load().is_err());
461        assert!(typed.join("storage.json.corrupt").exists());
462    }
463
464    #[test]
465    #[cfg(unix)]
466    fn an_unreadable_file_is_never_replaced() {
467        use std::os::unix::fs::PermissionsExt;
468        let dir = scratch("unreadable");
469        let file = dir.join("storage.json");
470        std::fs::write(&file, br#"{"kept":"yes"}"#).unwrap();
471        std::fs::set_permissions(&file, std::fs::Permissions::from_mode(0o200)).unwrap();
472        if std::fs::read(&file).is_ok() {
473            // Root reads it anyway: nothing to check.
474            return;
475        }
476        let storage = FileStorage::open(&dir);
477        assert!(storage.load().is_err());
478        storage
479            .write(StorageChange::Set("a".into(), "1".into()))
480            .unwrap();
481        drop(storage);
482        std::fs::set_permissions(&file, std::fs::Permissions::from_mode(0o600)).unwrap();
483        assert_eq!(std::fs::read_to_string(&file).unwrap(), r#"{"kept":"yes"}"#);
484    }
485
486    #[test]
487    fn a_failed_write_leaves_the_entries_in_memory() {
488        // A file where the directory should be: nothing can be written.
489        let dir = scratch("unwritable");
490        let blocked = dir.join("file");
491        std::fs::write(&blocked, b"").unwrap();
492        let storage = FileStorage::open(blocked.join("app"));
493        // Windows reads the path under a file as an absent file rather than
494        // an error; either way nothing can be written there.
495        #[cfg(not(windows))]
496        assert!(storage.load().unwrap_err().contains("kept in memory"));
497        #[cfg(windows)]
498        let _ = storage.load();
499        #[cfg(not(windows))]
500        storage
501            .write(StorageChange::Set("a".into(), "1".into()))
502            .unwrap();
503        #[cfg(windows)]
504        let _ = storage.write(StorageChange::Set("a".into(), "1".into()));
505        assert_eq!(
506            storage.load().unwrap().get("a").map(String::as_str),
507            Some("1")
508        );
509        drop(storage);
510        assert!(!blocked.join("app").exists());
511    }
512}