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>/` (or directly in the app's own folder, `in_app_folder`).
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    /// The folder holding `settings.json` and `explorer.json` (`None` when unavailable).
55    folder: Option<PathBuf>,
56    namespace: String,
57    document: OnceLock<Document>,
58    explorer: OnceLock<Document>,
59}
60
61impl SettingsStore {
62    /// `data_dir` is the host's per-user data directory (`None` when unavailable) and
63    /// `namespace` the app's folder name beneath it.
64    pub fn new(data_dir: Option<PathBuf>, namespace: impl Into<String>) -> Self {
65        let namespace = namespace.into();
66        Self {
67            folder: data_dir.map(|dir| dir.join(&namespace)),
68            namespace,
69            document: OnceLock::new(),
70            explorer: OnceLock::new(),
71        }
72    }
73
74    /// The store in the app's own data folder, as rightkit-fs resolves it (`AppDirs::data`):
75    /// `settings.json` and `explorer.json` live directly in `app_folder`, so the host keeps no
76    /// parent-folder resolver of its own (viewright#57). `namespace` names the document schema.
77    pub fn in_app_folder(app_folder: PathBuf, namespace: impl Into<String>) -> Self {
78        Self {
79            folder: Some(app_folder),
80            namespace: namespace.into(),
81            document: OnceLock::new(),
82            explorer: OnceLock::new(),
83        }
84    }
85
86    fn document_path(&self, name: &str) -> Result<PathBuf, WorkspaceError> {
87        let folder = self
88            .folder
89            .as_ref()
90            .ok_or_else(|| WorkspaceError::Other("settings directory is unavailable".into()))?;
91        Ok(folder.join(name))
92    }
93
94    fn options(&self) -> StoreOptions {
95        StoreOptions::new(Schema::new(self.namespace.clone(), DOCUMENT_VERSION))
96    }
97
98    fn explorer_document(&self) -> Result<&Document, WorkspaceError> {
99        if let Some(document) = self.explorer.get() {
100            return Ok(document);
101        }
102        let opened =
103            Document::open_path_with(self.document_path("explorer.json")?, &self.options())
104                .map_err(settings_error)?;
105        Ok(self.explorer.get_or_init(|| opened))
106    }
107
108    /// Open the settings document once. An open failure is returned to the caller; no second
109    /// store is opened and no in-memory fallback is used.
110    fn document(&self) -> Result<&Document, WorkspaceError> {
111        if let Some(document) = self.document.get() {
112            return Ok(document);
113        }
114        let opened =
115            Document::open_path_with(self.document_path("settings.json")?, &self.options())
116                .map_err(settings_error)?;
117        Ok(self.document.get_or_init(|| opened))
118    }
119
120    /// The diagnostics choice for the native log gate before the settings document is opened
121    /// (early startup events): an absent or unreadable choice means on (the default).
122    pub fn persisted_diagnostics_enabled(&self) -> bool {
123        let Ok(path) = self.document_path("settings.json") else {
124            return true;
125        };
126        match Document::open_path_with(path, &self.options()) {
127            Ok(document) => diagnostics_of(&document),
128            Err(_) => true,
129        }
130    }
131
132    /// Open the settings document and answer the diagnostics choice, so the opt-out is in force
133    /// before the first native event. If the document cannot be opened, recording stays off.
134    pub fn startup_diagnostics_enabled(&self) -> bool {
135        match self.document() {
136            Ok(document) => diagnostics_of(document),
137            Err(_) => false,
138        }
139    }
140
141    /// Read a durable value. The [`SETTINGS_KEY`] key is the settings document (JSON string, or
142    /// `null` when nothing has ever been saved). With `with_revision`, the document read answers
143    /// `{ value, revision }` where `revision` is the committed revision from the store (`0` when
144    /// nothing is stored). Other keys (the explorer record) read the explorer document.
145    pub fn get(&self, key: &str, with_revision: Option<bool>) -> Result<Value, WorkspaceError> {
146        if key == SETTINGS_KEY {
147            let state = self.document()?.get().map_err(settings_error)?;
148            let revision = state.as_ref().map_or(0, |state| state.revision);
149            let value = state
150                .filter(|state| state.value.as_object().is_some_and(|map| !map.is_empty()))
151                .map(|state| state.value.to_string());
152            if with_revision == Some(true) {
153                return Ok(json!({ "value": value, "revision": revision }));
154            }
155            return Ok(value.map_or(Value::Null, Value::String));
156        }
157        let state = self.explorer_document()?.get().map_err(settings_error)?;
158        Ok(state
159            .and_then(|state| {
160                state
161                    .value
162                    .get(key)
163                    .and_then(Value::as_str)
164                    .map(str::to_owned)
165            })
166            .map_or(Value::Null, Value::String))
167    }
168
169    /// Persist a value: the settings document, or (any other key) the explorer document.
170    ///
171    /// For the settings document, `expected_revision` makes the commit a compare-and-swap on the
172    /// store's committed revision (a stale one fails as a write conflict, nothing is written),
173    /// and `merge` applies `value` as a top-level patch (`null` removes a key) inside the store's
174    /// write lock instead of replacing the whole document. The answer is `{ value, revision }`
175    /// with the committed document; other keys answer `null`.
176    pub fn set(
177        &self,
178        key: &str,
179        value: &str,
180        expected_revision: Option<u64>,
181        merge: Option<bool>,
182    ) -> Result<SettingsWrite, WorkspaceError> {
183        if key == SETTINGS_KEY {
184            let map = parse_object(value)
185                .ok_or_else(|| WorkspaceError::Other("settings must be a JSON object".into()))?;
186            let document = self.document()?;
187            let state = if merge == Some(true) {
188                document.patch(DOCUMENT_VERSION, &Value::Object(map), expected_revision)
189            } else {
190                document.put(DOCUMENT_VERSION, Value::Object(map), expected_revision)
191            }
192            .map_err(settings_error)?;
193            let committed = state.value.to_string();
194            return Ok(SettingsWrite {
195                answer: json!({ "value": committed, "revision": state.revision }),
196                committed: Some(state.value),
197            });
198        }
199        self.explorer_document()?
200            .patch(DOCUMENT_VERSION, &json!({ key: value }), None)
201            .map_err(settings_error)?;
202        Ok(SettingsWrite {
203            answer: Value::Null,
204            committed: None,
205        })
206    }
207}
208
209fn diagnostics_of(document: &Document) -> bool {
210    document
211        .get()
212        .ok()
213        .flatten()
214        .and_then(|state| state.value.get("diagnostics").and_then(Value::as_bool))
215        .unwrap_or(true)
216}
217
218fn settings_error(error: SettingsError) -> WorkspaceError {
219    match error {
220        // Another writer committed first (compare-and-swap on the committed revision). The
221        // frontend maps this to the settings store's `revision_conflict` and reloads.
222        SettingsError::Conflict { expected, actual } => WorkspaceError::WriteConflict(format!(
223            "settings revision conflict: expected {expected}, found {actual}"
224        )),
225        other => WorkspaceError::Other(format!("settings store: {other}")),
226    }
227}