1use serde_json::Value;
5use std::path::PathBuf;
6use std::sync::{Arc, Mutex};
7
8pub trait DocumentStore: Send + Sync {
9 fn read(&self) -> Result<Option<Value>, String>;
11 fn write(&self, document: &Value) -> Result<(), String>;
12}
13
14impl<T: DocumentStore + ?Sized> DocumentStore for Box<T> {
15 fn read(&self) -> Result<Option<Value>, String> {
16 (**self).read()
17 }
18
19 fn write(&self, document: &Value) -> Result<(), String> {
20 (**self).write(document)
21 }
22}
23
24impl<T: DocumentStore + ?Sized> DocumentStore for Arc<T> {
25 fn read(&self) -> Result<Option<Value>, String> {
26 (**self).read()
27 }
28
29 fn write(&self, document: &Value) -> Result<(), String> {
30 (**self).write(document)
31 }
32}
33
34#[derive(Default)]
36pub struct MemoryDocumentStore {
37 document: Mutex<Option<Value>>,
38}
39
40impl MemoryDocumentStore {
41 pub fn new(initial: Option<Value>) -> Self {
42 Self {
43 document: Mutex::new(initial),
44 }
45 }
46}
47
48impl DocumentStore for MemoryDocumentStore {
49 fn read(&self) -> Result<Option<Value>, String> {
50 Ok(jsrt::sync::lock(&self.document).clone())
51 }
52
53 fn write(&self, document: &Value) -> Result<(), String> {
54 *jsrt::sync::lock(&self.document) = Some(document.clone());
55 Ok(())
56 }
57}
58
59pub struct FileDocumentStore {
61 path: PathBuf,
62}
63
64impl FileDocumentStore {
65 pub fn new(path: impl Into<PathBuf>) -> Self {
66 Self { path: path.into() }
67 }
68}
69
70impl DocumentStore for FileDocumentStore {
71 fn read(&self) -> Result<Option<Value>, String> {
72 match std::fs::read_to_string(&self.path) {
73 Ok(text) => serde_json::from_str(&text)
74 .map(Some)
75 .map_err(|error| format!("{}: {error}", self.path.display())),
76 Err(error) if error.kind() == std::io::ErrorKind::NotFound => Ok(None),
77 Err(error) => Err(format!("{}: {error}", self.path.display())),
78 }
79 }
80
81 fn write(&self, document: &Value) -> Result<(), String> {
82 if let Some(parent) = self.path.parent() {
83 std::fs::create_dir_all(parent).map_err(|error| error.to_string())?;
84 }
85 let temporary = PathBuf::from(format!("{}.{}.tmp", self.path.display(), jsrt::random::uuid_v4()));
86 std::fs::write(&temporary, serde_json::to_string(document).unwrap_or_default())
87 .map_err(|error| error.to_string())?;
88 std::fs::rename(&temporary, &self.path).map_err(|error| error.to_string())
89 }
90}