rightkit_document_workspace/
settings.rs1use std::path::PathBuf;
5use std::sync::OnceLock;
6
7use rightkit_app_settings::{Document, Error as SettingsError, Schema, StoreOptions};
8use serde_json::{json, Map, Value};
9
10use crate::error::WorkspaceError;
11
12pub const SETTINGS_KEY: &str = "vr.settings.v1";
14const DOCUMENT_VERSION: u32 = 1;
18
19fn parse_object(raw: &str) -> Option<Map<String, Value>> {
20 match serde_json::from_str::<Value>(raw) {
21 Ok(Value::Object(map)) => Some(map),
22 _ => None,
23 }
24}
25
26#[derive(Debug)]
28pub struct SettingsWrite {
29 pub answer: Value,
31 pub committed: Option<Value>,
34}
35
36impl SettingsWrite {
37 pub fn diagnostics_enabled(&self) -> Option<bool> {
40 self.committed.as_ref().map(|settings| {
41 settings
42 .get("diagnostics")
43 .and_then(Value::as_bool)
44 .unwrap_or(true)
45 })
46 }
47}
48
49pub struct SettingsStore {
54 data_dir: Option<PathBuf>,
55 namespace: String,
56 document: OnceLock<Document>,
57 explorer: OnceLock<Document>,
58}
59
60impl SettingsStore {
61 pub fn new(data_dir: Option<PathBuf>, namespace: impl Into<String>) -> Self {
64 Self {
65 data_dir,
66 namespace: namespace.into(),
67 document: OnceLock::new(),
68 explorer: OnceLock::new(),
69 }
70 }
71
72 fn document_path(&self, name: &str) -> Result<PathBuf, WorkspaceError> {
73 let root = self
74 .data_dir
75 .as_ref()
76 .ok_or_else(|| WorkspaceError::Other("settings directory is unavailable".into()))?;
77 Ok(root.join(&self.namespace).join(name))
78 }
79
80 fn options(&self) -> StoreOptions {
81 StoreOptions::new(Schema::new(self.namespace.clone(), DOCUMENT_VERSION))
82 }
83
84 fn explorer_document(&self) -> Result<&Document, WorkspaceError> {
85 if let Some(document) = self.explorer.get() {
86 return Ok(document);
87 }
88 let opened =
89 Document::open_path_with(self.document_path("explorer.json")?, &self.options())
90 .map_err(settings_error)?;
91 Ok(self.explorer.get_or_init(|| opened))
92 }
93
94 fn document(&self) -> Result<&Document, WorkspaceError> {
97 if let Some(document) = self.document.get() {
98 return Ok(document);
99 }
100 let opened =
101 Document::open_path_with(self.document_path("settings.json")?, &self.options())
102 .map_err(settings_error)?;
103 Ok(self.document.get_or_init(|| opened))
104 }
105
106 pub fn persisted_diagnostics_enabled(&self) -> bool {
109 let Ok(path) = self.document_path("settings.json") else {
110 return true;
111 };
112 match Document::open_path_with(path, &self.options()) {
113 Ok(document) => diagnostics_of(&document),
114 Err(_) => true,
115 }
116 }
117
118 pub fn startup_diagnostics_enabled(&self) -> bool {
121 match self.document() {
122 Ok(document) => diagnostics_of(document),
123 Err(_) => false,
124 }
125 }
126
127 pub fn get(&self, key: &str, with_revision: Option<bool>) -> Result<Value, WorkspaceError> {
132 if key == SETTINGS_KEY {
133 let state = self.document()?.get().map_err(settings_error)?;
134 let revision = state.as_ref().map_or(0, |state| state.revision);
135 let value = state
136 .filter(|state| state.value.as_object().is_some_and(|map| !map.is_empty()))
137 .map(|state| state.value.to_string());
138 if with_revision == Some(true) {
139 return Ok(json!({ "value": value, "revision": revision }));
140 }
141 return Ok(value.map_or(Value::Null, Value::String));
142 }
143 let state = self.explorer_document()?.get().map_err(settings_error)?;
144 Ok(state
145 .and_then(|state| {
146 state
147 .value
148 .get(key)
149 .and_then(Value::as_str)
150 .map(str::to_owned)
151 })
152 .map_or(Value::Null, Value::String))
153 }
154
155 pub fn set(
163 &self,
164 key: &str,
165 value: &str,
166 expected_revision: Option<u64>,
167 merge: Option<bool>,
168 ) -> Result<SettingsWrite, WorkspaceError> {
169 if key == SETTINGS_KEY {
170 let map = parse_object(value)
171 .ok_or_else(|| WorkspaceError::Other("settings must be a JSON object".into()))?;
172 let document = self.document()?;
173 let state = if merge == Some(true) {
174 document.patch(DOCUMENT_VERSION, &Value::Object(map), expected_revision)
175 } else {
176 document.put(DOCUMENT_VERSION, Value::Object(map), expected_revision)
177 }
178 .map_err(settings_error)?;
179 let committed = state.value.to_string();
180 return Ok(SettingsWrite {
181 answer: json!({ "value": committed, "revision": state.revision }),
182 committed: Some(state.value),
183 });
184 }
185 self.explorer_document()?
186 .patch(DOCUMENT_VERSION, &json!({ key: value }), None)
187 .map_err(settings_error)?;
188 Ok(SettingsWrite {
189 answer: Value::Null,
190 committed: None,
191 })
192 }
193}
194
195fn diagnostics_of(document: &Document) -> bool {
196 document
197 .get()
198 .ok()
199 .flatten()
200 .and_then(|state| state.value.get("diagnostics").and_then(Value::as_bool))
201 .unwrap_or(true)
202}
203
204fn settings_error(error: SettingsError) -> WorkspaceError {
205 match error {
206 SettingsError::Conflict { expected, actual } => WorkspaceError::WriteConflict(format!(
209 "settings revision conflict: expected {expected}, found {actual}"
210 )),
211 other => WorkspaceError::Other(format!("settings store: {other}")),
212 }
213}
214
215#[cfg(test)]
216mod tests {
217 use super::*;
218
219 #[test]
220 fn settings_round_trip_with_revision() {
221 let dir =
222 std::env::temp_dir().join(format!("rightkit-settings-test-{}", std::process::id()));
223 std::fs::create_dir_all(dir.join("test-app")).unwrap();
224 let store = SettingsStore::new(Some(dir.clone()), "test-app");
225 assert_eq!(store.get(SETTINGS_KEY, None).unwrap(), Value::Null);
226 let write = store
227 .set(SETTINGS_KEY, r#"{"diagnostics":false}"#, None, None)
228 .unwrap();
229 assert_eq!(write.diagnostics_enabled(), Some(false));
230 let read = store.get(SETTINGS_KEY, Some(true)).unwrap();
231 assert_eq!(read["revision"], write.answer["revision"]);
232 assert!(!store.persisted_diagnostics_enabled());
233 let _ = std::fs::remove_dir_all(dir);
234 }
235
236 #[test]
237 fn missing_data_dir_is_an_error() {
238 let store = SettingsStore::new(None, "test-app");
239 assert!(store.get(SETTINGS_KEY, None).is_err());
240 assert!(store.persisted_diagnostics_enabled());
241 assert!(!store.startup_diagnostics_enabled());
242 }
243
244 #[test]
245 fn explorer_record_round_trips() {
246 let dir =
247 std::env::temp_dir().join(format!("rightkit-explorer-rec-{}", std::process::id()));
248 std::fs::create_dir_all(dir.join("test-app")).unwrap();
249 let store = SettingsStore::new(Some(dir.clone()), "test-app");
250 let write = store.set("k", "v", None, None).unwrap();
251 assert!(write.committed.is_none());
252 assert_eq!(store.get("k", None).unwrap(), Value::String("v".into()));
253 let _ = std::fs::remove_dir_all(dir);
254 }
255}