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    fn write(&self, change: StorageChange) {
248        if let Some(entries) = &mut *self.entries.lock().unwrap_or_else(|e| e.into_inner()) {
249            apply(entries, change.clone());
250        }
251        if self.in_memory.load(std::sync::atomic::Ordering::Relaxed) {
252            return;
253        }
254        let mut writer = self.writer.lock().unwrap_or_else(|e| e.into_inner());
255        let (changes, _) = writer.get_or_insert_with(|| {
256            let (tx, rx) = crossbeam_channel::unbounded();
257            let path = self.path.clone();
258            let thread = std::thread::Builder::new()
259                .name("nsh-storage".into())
260                .spawn(move || run_writer(path, rx))
261                .expect("the storage thread starts");
262            (tx, thread)
263        });
264        // The writer only stops when this is dropped.
265        let _ = changes.send(change);
266    }
267}
268
269impl Drop for FileStorage {
270    /// Waits for the last changes to be written.
271    fn drop(&mut self) {
272        let writer = self
273            .writer
274            .get_mut()
275            .unwrap_or_else(|e| e.into_inner())
276            .take();
277        if let Some((changes, thread)) = writer {
278            drop(changes);
279            let _ = thread.join();
280        }
281    }
282}
283
284#[cfg(test)]
285mod tests {
286    use super::*;
287
288    /// An empty directory of its own under the test's temporary directory.
289    fn scratch(name: &str) -> PathBuf {
290        let dir =
291            std::env::temp_dir().join(format!("nsh-file-storage-{}-{name}", std::process::id()));
292        let _ = std::fs::remove_dir_all(&dir);
293        std::fs::create_dir_all(&dir).unwrap();
294        dir
295    }
296
297    #[test]
298    fn keeps_entries_across_instances() {
299        let dir = scratch("instances");
300        let storage = FileStorage::open(&dir);
301        assert!(storage.load().unwrap().is_empty());
302        storage.write(StorageChange::Set("a".into(), "1".into()));
303        storage.write(StorageChange::Set("b".into(), "2".into()));
304        // A reload while the first is open shares its entries, written or not.
305        let reloaded = FileStorage::open(&dir);
306        assert!(Arc::ptr_eq(&storage, &reloaded));
307        storage.write(StorageChange::Remove("a".into()));
308        assert_eq!(reloaded.load().unwrap().len(), 1);
309        drop((storage, reloaded));
310        let again = FileStorage::open(&dir);
311        assert_eq!(
312            again.load().unwrap(),
313            BTreeMap::from([("b".to_owned(), "2".to_owned())])
314        );
315        again.write(StorageChange::Clear);
316        drop(again);
317        assert!(FileStorage::open(&dir).load().unwrap().is_empty());
318        std::fs::remove_dir_all(&dir).unwrap();
319    }
320
321    #[test]
322    fn an_apps_data_dir_is_absolute_or_under_the_home_directory() {
323        let home = std::env::temp_dir().join("home");
324        let resolve = |template| resolve_data_dir_in(template, Some(&home));
325        assert_eq!(resolve("${homeDir}/.myapp"), Some(home.join(".myapp")));
326        assert_eq!(
327            resolve("${homeDir}/.myapp/ui"),
328            Some(home.join(".myapp/ui"))
329        );
330        assert_eq!(resolve("${homeDir}"), Some(home.clone()));
331        let absolute = std::env::temp_dir().join("myapp");
332        assert_eq!(
333            resolve_data_dir_in(absolute.to_str().unwrap(), None),
334            Some(absolute.clone())
335        );
336        // Refused: relative, other placeholders, `..`, a home that is not there.
337        assert_eq!(resolve(".myapp"), None);
338        assert_eq!(resolve("${homeDir}.myapp"), None);
339        assert_eq!(resolve("${appId}/data"), None);
340        assert_eq!(resolve("${homeDir}/${appId}"), None);
341        assert_eq!(resolve("${homeDir}/../elsewhere"), None);
342        assert_eq!(resolve_data_dir_in("${homeDir}/.myapp", None), None);
343    }
344
345    #[test]
346    fn data_directories_follow_each_platform() {
347        let env = |vars: &'static [(&'static str, &'static str)]| {
348            move |name: &str| {
349                vars.iter()
350                    .find(|(n, _)| *n == name)
351                    .map(|(_, v)| PathBuf::from(v))
352            }
353        };
354        let home = env(&[
355            ("HOME", "/home/a"),
356            ("APPDATA", r"C:\Users\a\AppData\Roaming"),
357        ]);
358        assert_eq!(
359            support_dir_in("linux", home),
360            Some(PathBuf::from("/home/a/.local/share"))
361        );
362        assert_eq!(
363            support_dir_in(
364                "linux",
365                env(&[("XDG_DATA_HOME", "/data"), ("HOME", "/home/a")])
366            ),
367            Some(PathBuf::from("/data"))
368        );
369        // An empty variable counts as unset.
370        assert_eq!(
371            support_dir_in("linux", env(&[("XDG_DATA_HOME", ""), ("HOME", "/home/a")])),
372            Some(PathBuf::from("/home/a/.local/share"))
373        );
374        let support = Some(PathBuf::from("/home/a/Library/Application Support"));
375        assert_eq!(support_dir_in("macos", home), support);
376        assert_eq!(support_dir_in("ios", home), support);
377        assert_eq!(
378            support_dir_in("windows", home),
379            Some(PathBuf::from(r"C:\Users\a\AppData\Roaming"))
380        );
381        // Android's files directory is the platform's to give.
382        assert_eq!(support_dir_in("android", home), None);
383        assert_eq!(support_dir_in("linux", env(&[])), None);
384    }
385
386    #[test]
387    fn cache_directories_follow_each_platform() {
388        let vars = |vars: &'static [(&'static str, &'static str)]| {
389            move |name: &str| {
390                vars.iter()
391                    .find(|(n, _)| *n == name)
392                    .map(|(_, v)| PathBuf::from(v))
393            }
394        };
395        let home = vars(&[
396            ("HOME", "/home/a"),
397            ("LOCALAPPDATA", r"C:\Users\a\AppData\Local"),
398        ]);
399        assert_eq!(
400            cache_dir_in("linux", home),
401            Some(PathBuf::from("/home/a/.cache"))
402        );
403        assert_eq!(
404            cache_dir_in(
405                "linux",
406                vars(&[("XDG_CACHE_HOME", "/c"), ("HOME", "/home/a")])
407            ),
408            Some(PathBuf::from("/c"))
409        );
410        assert_eq!(
411            cache_dir_in("macos", home),
412            Some(PathBuf::from("/home/a/Library/Caches"))
413        );
414        assert_eq!(
415            cache_dir_in("windows", home),
416            Some(PathBuf::from(r"C:\Users\a\AppData\Local"))
417        );
418        assert_eq!(cache_dir_in("android", home), None);
419    }
420
421    #[test]
422    fn apps_get_directories_of_their_own() {
423        assert_eq!(app_dir_name(Some("com.example.app")), "com.example.app");
424        assert_eq!(app_dir_name(Some("..app")), "..app");
425        assert_eq!(app_dir_name(None), "default");
426        // An id that is no directory name cannot reach another directory.
427        for id in ["", ".", "..", "../etc", "a/b", r"a\b", "a\0b"] {
428            assert_eq!(app_dir_name(Some(id)), "default", "{id:?}");
429        }
430    }
431
432    #[test]
433    fn a_damaged_file_is_set_aside_not_replaced() {
434        let dir = scratch("damaged");
435        let file = dir.join("storage.json");
436        std::fs::write(&file, b"{ not json").unwrap();
437        let storage = FileStorage::open(&dir);
438        let error = storage.load().unwrap_err();
439        assert!(error.contains("set aside"), "{error}");
440        let aside = dir.join("storage.json.corrupt");
441        assert_eq!(std::fs::read(&aside).unwrap(), b"{ not json");
442        // The app goes on with new entries, and the old file is still there.
443        storage.write(StorageChange::Set("a".into(), "1".into()));
444        drop(storage);
445        assert_eq!(std::fs::read_to_string(&file).unwrap(), r#"{"a":"1"}"#);
446        assert_eq!(std::fs::read(&aside).unwrap(), b"{ not json");
447        // Values that are not strings are no storage either.
448        let typed = scratch("typed");
449        std::fs::write(typed.join("storage.json"), br#"{"n": 1}"#).unwrap();
450        assert!(FileStorage::open(&typed).load().is_err());
451        assert!(typed.join("storage.json.corrupt").exists());
452    }
453
454    #[test]
455    #[cfg(unix)]
456    fn an_unreadable_file_is_never_replaced() {
457        use std::os::unix::fs::PermissionsExt;
458        let dir = scratch("unreadable");
459        let file = dir.join("storage.json");
460        std::fs::write(&file, br#"{"kept":"yes"}"#).unwrap();
461        std::fs::set_permissions(&file, std::fs::Permissions::from_mode(0o200)).unwrap();
462        if std::fs::read(&file).is_ok() {
463            // Root reads it anyway: nothing to check.
464            return;
465        }
466        let storage = FileStorage::open(&dir);
467        assert!(storage.load().is_err());
468        storage.write(StorageChange::Set("a".into(), "1".into()));
469        drop(storage);
470        std::fs::set_permissions(&file, std::fs::Permissions::from_mode(0o600)).unwrap();
471        assert_eq!(std::fs::read_to_string(&file).unwrap(), r#"{"kept":"yes"}"#);
472    }
473
474    #[test]
475    fn a_failed_write_leaves_the_entries_in_memory() {
476        // A file where the directory should be: nothing can be written.
477        let dir = scratch("unwritable");
478        let blocked = dir.join("file");
479        std::fs::write(&blocked, b"").unwrap();
480        let storage = FileStorage::open(blocked.join("app"));
481        assert!(storage.load().unwrap_err().contains("kept in memory"));
482        storage.write(StorageChange::Set("a".into(), "1".into()));
483        assert_eq!(
484            storage.load().unwrap().get("a").map(String::as_str),
485            Some("1")
486        );
487        drop(storage);
488        assert!(!blocked.join("app").exists());
489    }
490}