1use 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
18pub struct FileStorage {
21 path: PathBuf,
22 entries: Mutex<Option<BTreeMap<String, String>>>,
24 in_memory: std::sync::atomic::AtomicBool,
27 writer: Mutex<Option<(Sender<StorageChange>, JoinHandle<()>)>>,
28}
29
30impl FileStorage {
31 pub fn open(dir: impl Into<PathBuf>) -> Arc<Self> {
34 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 pub fn path(&self) -> &Path {
60 &self.path
61 }
62}
63
64pub 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
75fn 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
86pub(crate) fn cache_dir() -> Option<PathBuf> {
92 cache_dir_in(std::env::consts::OS, |name| {
93 std::env::var_os(name).map(PathBuf::from)
94 })
95}
96
97fn cache_dir_in(os: &str, env: impl Fn(&str) -> Option<PathBuf>) -> Option<PathBuf> {
99 let env = |name| env(name).filter(|v| !v.as_os_str().is_empty());
100 match os {
101 "android" => None,
102 "macos" | "ios" => env("HOME").map(|home| home.join("Library/Caches")),
103 "windows" => env("LOCALAPPDATA"),
104 _ => env("XDG_CACHE_HOME").or_else(|| env("HOME").map(|home| home.join(".cache"))),
105 }
106}
107
108#[cfg(test)]
109use crate::app_dir_name;
110
111fn read(path: &Path) -> Result<BTreeMap<String, String>, String> {
112 match std::fs::read(path) {
113 Ok(bytes) => serde_json::from_slice(&bytes).map_err(|e| format!("{}: {e}", path.display())),
114 Err(e) if e.kind() == std::io::ErrorKind::NotFound => Ok(BTreeMap::new()),
115 Err(e) => Err(format!("{}: {e}", path.display())),
116 }
117}
118
119fn read_or_set_aside(path: &Path) -> Result<BTreeMap<String, String>, (String, bool)> {
123 read(path).map_err(|e| {
124 if std::fs::read(path).is_err() {
127 return (format!("{e}; it is kept in memory"), false);
128 }
129 let aside = path.with_extension("json.corrupt");
130 match std::fs::rename(path, &aside) {
131 Ok(()) => (
132 format!("{e}; it was set aside as {}", aside.display()),
133 true,
134 ),
135 Err(rename) => (
136 format!("{e}; it could not be set aside ({rename}), so it is kept in memory"),
137 false,
138 ),
139 }
140 })
141}
142
143fn write(path: &Path, entries: &BTreeMap<String, String>) -> std::io::Result<()> {
144 if let Some(dir) = path.parent() {
145 std::fs::create_dir_all(dir)?;
146 }
147 let temporary = path.with_extension("json.tmp");
148 let file = std::fs::File::create(&temporary)?;
149 let mut out = std::io::BufWriter::new(file);
150 serde_json::to_writer(&mut out, entries)?;
151 let file = out.into_inner().map_err(|e| e.into_error())?;
152 file.sync_all()?;
153 std::fs::rename(&temporary, path)
154}
155
156fn apply(entries: &mut BTreeMap<String, String>, change: StorageChange) {
157 match change {
158 StorageChange::Set(key, value) => {
159 entries.insert(key, value);
160 }
161 StorageChange::Remove(key) => {
162 entries.remove(&key);
163 }
164 StorageChange::Clear => entries.clear(),
165 }
166}
167
168fn run_writer(path: PathBuf, changes: Receiver<StorageChange>) {
170 let mut entries = read(&path).unwrap_or_default();
171 while let Ok(change) = changes.recv() {
172 apply(&mut entries, change);
173 changes
174 .try_iter()
175 .for_each(|change| apply(&mut entries, change));
176 if let Err(e) = write(&path, &entries) {
177 log::error!(target: "js", "the app's storage could not be written to {}: {e}", path.display());
178 }
179 }
180}
181
182impl StorageBackend for FileStorage {
183 fn load(&self) -> Result<BTreeMap<String, String>, String> {
184 let mut entries = self.entries.lock().unwrap_or_else(|e| e.into_inner());
185 if let Some(entries) = &*entries {
186 return Ok(entries.clone());
187 }
188 match read_or_set_aside(&self.path) {
189 Ok(read) => {
190 *entries = Some(read.clone());
191 Ok(read)
192 }
193 Err((e, writable)) => {
194 *entries = Some(BTreeMap::new());
195 if !writable {
196 self.in_memory
197 .store(true, std::sync::atomic::Ordering::Relaxed);
198 }
199 Err(e)
200 }
201 }
202 }
203
204 fn write(&self, change: StorageChange) {
205 if let Some(entries) = &mut *self.entries.lock().unwrap_or_else(|e| e.into_inner()) {
206 apply(entries, change.clone());
207 }
208 if self.in_memory.load(std::sync::atomic::Ordering::Relaxed) {
209 return;
210 }
211 let mut writer = self.writer.lock().unwrap_or_else(|e| e.into_inner());
212 let (changes, _) = writer.get_or_insert_with(|| {
213 let (tx, rx) = crossbeam_channel::unbounded();
214 let path = self.path.clone();
215 let thread = std::thread::Builder::new()
216 .name("nsh-storage".into())
217 .spawn(move || run_writer(path, rx))
218 .expect("the storage thread starts");
219 (tx, thread)
220 });
221 let _ = changes.send(change);
223 }
224}
225
226impl Drop for FileStorage {
227 fn drop(&mut self) {
229 let writer = self
230 .writer
231 .get_mut()
232 .unwrap_or_else(|e| e.into_inner())
233 .take();
234 if let Some((changes, thread)) = writer {
235 drop(changes);
236 let _ = thread.join();
237 }
238 }
239}
240
241#[cfg(test)]
242mod tests {
243 use super::*;
244
245 fn scratch(name: &str) -> PathBuf {
247 let dir =
248 std::env::temp_dir().join(format!("nsh-file-storage-{}-{name}", std::process::id()));
249 let _ = std::fs::remove_dir_all(&dir);
250 std::fs::create_dir_all(&dir).unwrap();
251 dir
252 }
253
254 #[test]
255 fn keeps_entries_across_instances() {
256 let dir = scratch("instances");
257 let storage = FileStorage::open(&dir);
258 assert!(storage.load().unwrap().is_empty());
259 storage.write(StorageChange::Set("a".into(), "1".into()));
260 storage.write(StorageChange::Set("b".into(), "2".into()));
261 let reloaded = FileStorage::open(&dir);
263 assert!(Arc::ptr_eq(&storage, &reloaded));
264 storage.write(StorageChange::Remove("a".into()));
265 assert_eq!(reloaded.load().unwrap().len(), 1);
266 drop((storage, reloaded));
267 let again = FileStorage::open(&dir);
268 assert_eq!(
269 again.load().unwrap(),
270 BTreeMap::from([("b".to_owned(), "2".to_owned())])
271 );
272 again.write(StorageChange::Clear);
273 drop(again);
274 assert!(FileStorage::open(&dir).load().unwrap().is_empty());
275 std::fs::remove_dir_all(&dir).unwrap();
276 }
277
278 #[test]
279 fn data_directories_follow_each_platform() {
280 let env = |vars: &'static [(&'static str, &'static str)]| {
281 move |name: &str| {
282 vars.iter()
283 .find(|(n, _)| *n == name)
284 .map(|(_, v)| PathBuf::from(v))
285 }
286 };
287 let home = env(&[
288 ("HOME", "/home/a"),
289 ("APPDATA", r"C:\Users\a\AppData\Roaming"),
290 ]);
291 assert_eq!(
292 data_dir_in("linux", home),
293 Some(PathBuf::from("/home/a/.local/share"))
294 );
295 assert_eq!(
296 data_dir_in(
297 "linux",
298 env(&[("XDG_DATA_HOME", "/data"), ("HOME", "/home/a")])
299 ),
300 Some(PathBuf::from("/data"))
301 );
302 assert_eq!(
304 data_dir_in("linux", env(&[("XDG_DATA_HOME", ""), ("HOME", "/home/a")])),
305 Some(PathBuf::from("/home/a/.local/share"))
306 );
307 let support = Some(PathBuf::from("/home/a/Library/Application Support"));
308 assert_eq!(data_dir_in("macos", home), support);
309 assert_eq!(data_dir_in("ios", home), support);
310 assert_eq!(
311 data_dir_in("windows", home),
312 Some(PathBuf::from(r"C:\Users\a\AppData\Roaming"))
313 );
314 assert_eq!(data_dir_in("android", home), None);
316 assert_eq!(data_dir_in("linux", env(&[])), None);
317 }
318
319 #[test]
320 fn cache_directories_follow_each_platform() {
321 let vars = |vars: &'static [(&'static str, &'static str)]| {
322 move |name: &str| {
323 vars.iter()
324 .find(|(n, _)| *n == name)
325 .map(|(_, v)| PathBuf::from(v))
326 }
327 };
328 let home = vars(&[
329 ("HOME", "/home/a"),
330 ("LOCALAPPDATA", r"C:\Users\a\AppData\Local"),
331 ]);
332 assert_eq!(
333 cache_dir_in("linux", home),
334 Some(PathBuf::from("/home/a/.cache"))
335 );
336 assert_eq!(
337 cache_dir_in(
338 "linux",
339 vars(&[("XDG_CACHE_HOME", "/c"), ("HOME", "/home/a")])
340 ),
341 Some(PathBuf::from("/c"))
342 );
343 assert_eq!(
344 cache_dir_in("macos", home),
345 Some(PathBuf::from("/home/a/Library/Caches"))
346 );
347 assert_eq!(
348 cache_dir_in("windows", home),
349 Some(PathBuf::from(r"C:\Users\a\AppData\Local"))
350 );
351 assert_eq!(cache_dir_in("android", home), None);
352 }
353
354 #[test]
355 fn apps_get_directories_of_their_own() {
356 assert_eq!(app_dir_name(Some("com.example.app")), "com.example.app");
357 assert_eq!(app_dir_name(Some("..app")), "..app");
358 assert_eq!(app_dir_name(None), "default");
359 for id in ["", ".", "..", "../etc", "a/b", r"a\b", "a\0b"] {
361 assert_eq!(app_dir_name(Some(id)), "default", "{id:?}");
362 }
363 }
364
365 #[test]
366 fn a_damaged_file_is_set_aside_not_replaced() {
367 let dir = scratch("damaged");
368 let file = dir.join("storage.json");
369 std::fs::write(&file, b"{ not json").unwrap();
370 let storage = FileStorage::open(&dir);
371 let error = storage.load().unwrap_err();
372 assert!(error.contains("set aside"), "{error}");
373 let aside = dir.join("storage.json.corrupt");
374 assert_eq!(std::fs::read(&aside).unwrap(), b"{ not json");
375 storage.write(StorageChange::Set("a".into(), "1".into()));
377 drop(storage);
378 assert_eq!(std::fs::read_to_string(&file).unwrap(), r#"{"a":"1"}"#);
379 assert_eq!(std::fs::read(&aside).unwrap(), b"{ not json");
380 let typed = scratch("typed");
382 std::fs::write(typed.join("storage.json"), br#"{"n": 1}"#).unwrap();
383 assert!(FileStorage::open(&typed).load().is_err());
384 assert!(typed.join("storage.json.corrupt").exists());
385 }
386
387 #[test]
388 #[cfg(unix)]
389 fn an_unreadable_file_is_never_replaced() {
390 use std::os::unix::fs::PermissionsExt;
391 let dir = scratch("unreadable");
392 let file = dir.join("storage.json");
393 std::fs::write(&file, br#"{"kept":"yes"}"#).unwrap();
394 std::fs::set_permissions(&file, std::fs::Permissions::from_mode(0o200)).unwrap();
395 if std::fs::read(&file).is_ok() {
396 return;
398 }
399 let storage = FileStorage::open(&dir);
400 assert!(storage.load().is_err());
401 storage.write(StorageChange::Set("a".into(), "1".into()));
402 drop(storage);
403 std::fs::set_permissions(&file, std::fs::Permissions::from_mode(0o600)).unwrap();
404 assert_eq!(std::fs::read_to_string(&file).unwrap(), r#"{"kept":"yes"}"#);
405 }
406
407 #[test]
408 fn a_failed_write_leaves_the_entries_in_memory() {
409 let dir = scratch("unwritable");
411 let blocked = dir.join("file");
412 std::fs::write(&blocked, b"").unwrap();
413 let storage = FileStorage::open(blocked.join("app"));
414 assert!(storage.load().unwrap_err().contains("kept in memory"));
415 storage.write(StorageChange::Set("a".into(), "1".into()));
416 assert_eq!(
417 storage.load().unwrap().get("a").map(String::as_str),
418 Some("1")
419 );
420 drop(storage);
421 assert!(!blocked.join("app").exists());
422 }
423}