Skip to main content

rightkit_document_workspace/
settings.rs

1//! The durable settings document and the explorer record, stored as `rightkit-app-settings`
2//! envelopes under `<data_dir>/<namespace>/`.
3
4use 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
12/// The settings key the frontend stores its document under.
13pub const SETTINGS_KEY: &str = "vr.settings.v1";
14/// The version the frontend stores the document under. The frontend's `migrate()` works on
15/// marker fields inside the object, so this stays 1: existing `settings.json` envelopes and older
16/// builds read the file unchanged.
17const 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/// The outcome of [`SettingsStore::set`].
27#[derive(Debug)]
28pub struct SettingsWrite {
29    /// The answer to hand back to the renderer.
30    pub answer: Value,
31    /// The committed settings object when the settings document (not the explorer record) was
32    /// written, so the host can apply side effects such as the diagnostics gate.
33    pub committed: Option<Value>,
34}
35
36impl SettingsWrite {
37    /// The diagnostics choice in the committed settings document (default on), or `None` when the
38    /// write did not touch the settings document.
39    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
49/// The settings document (`<data_dir>/<namespace>/settings.json`) and the explorer sidebar's
50/// record (`explorer.json`, an object of key to text). The TypeScript side owns the settings
51/// shape, so the store keeps one opaque JSON object. Only a successful open is cached; a failed
52/// open is reported on every call and retried.
53pub struct SettingsStore {
54    data_dir: Option<PathBuf>,
55    namespace: String,
56    document: OnceLock<Document>,
57    explorer: OnceLock<Document>,
58}
59
60impl SettingsStore {
61    /// `data_dir` is the host's per-user data directory (`None` when unavailable) and
62    /// `namespace` the app's folder name beneath it.
63    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    /// Open the settings document once. An open failure is returned to the caller; no second
95    /// store is opened and no in-memory fallback is used.
96    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    /// The diagnostics choice for the native log gate before the settings document is opened
107    /// (early startup events): an absent or unreadable choice means on (the default).
108    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    /// Open the settings document and answer the diagnostics choice, so the opt-out is in force
119    /// before the first native event. If the document cannot be opened, recording stays off.
120    pub fn startup_diagnostics_enabled(&self) -> bool {
121        match self.document() {
122            Ok(document) => diagnostics_of(document),
123            Err(_) => false,
124        }
125    }
126
127    /// Read a durable value. The [`SETTINGS_KEY`] key is the settings document (JSON string, or
128    /// `null` when nothing has ever been saved). With `with_revision`, the document read answers
129    /// `{ value, revision }` where `revision` is the committed revision from the store (`0` when
130    /// nothing is stored). Other keys (the explorer record) read the explorer document.
131    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    /// Persist a value: the settings document, or (any other key) the explorer document.
156    ///
157    /// For the settings document, `expected_revision` makes the commit a compare-and-swap on the
158    /// store's committed revision (a stale one fails as a write conflict, nothing is written),
159    /// and `merge` applies `value` as a top-level patch (`null` removes a key) inside the store's
160    /// write lock instead of replacing the whole document. The answer is `{ value, revision }`
161    /// with the committed document; other keys answer `null`.
162    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        // Another writer committed first (compare-and-swap on the committed revision). The
207        // frontend maps this to the settings store's `revision_conflict` and reloads.
208        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}