use std::path::PathBuf;
use std::sync::OnceLock;
use rightkit_app_settings::{Document, Error as SettingsError, Schema, StoreOptions};
use serde_json::{json, Map, Value};
use crate::error::WorkspaceError;
pub const SETTINGS_KEY: &str = "vr.settings.v1";
const DOCUMENT_VERSION: u32 = 1;
fn parse_object(raw: &str) -> Option<Map<String, Value>> {
match serde_json::from_str::<Value>(raw) {
Ok(Value::Object(map)) => Some(map),
_ => None,
}
}
#[derive(Debug)]
pub struct SettingsWrite {
pub answer: Value,
pub committed: Option<Value>,
}
impl SettingsWrite {
pub fn diagnostics_enabled(&self) -> Option<bool> {
self.committed.as_ref().map(|settings| {
settings
.get("diagnostics")
.and_then(Value::as_bool)
.unwrap_or(true)
})
}
}
pub struct SettingsStore {
data_dir: Option<PathBuf>,
namespace: String,
document: OnceLock<Document>,
explorer: OnceLock<Document>,
}
impl SettingsStore {
pub fn new(data_dir: Option<PathBuf>, namespace: impl Into<String>) -> Self {
Self {
data_dir,
namespace: namespace.into(),
document: OnceLock::new(),
explorer: OnceLock::new(),
}
}
fn document_path(&self, name: &str) -> Result<PathBuf, WorkspaceError> {
let root = self
.data_dir
.as_ref()
.ok_or_else(|| WorkspaceError::Other("settings directory is unavailable".into()))?;
Ok(root.join(&self.namespace).join(name))
}
fn options(&self) -> StoreOptions {
StoreOptions::new(Schema::new(self.namespace.clone(), DOCUMENT_VERSION))
}
fn explorer_document(&self) -> Result<&Document, WorkspaceError> {
if let Some(document) = self.explorer.get() {
return Ok(document);
}
let opened =
Document::open_path_with(self.document_path("explorer.json")?, &self.options())
.map_err(settings_error)?;
Ok(self.explorer.get_or_init(|| opened))
}
fn document(&self) -> Result<&Document, WorkspaceError> {
if let Some(document) = self.document.get() {
return Ok(document);
}
let opened =
Document::open_path_with(self.document_path("settings.json")?, &self.options())
.map_err(settings_error)?;
Ok(self.document.get_or_init(|| opened))
}
pub fn persisted_diagnostics_enabled(&self) -> bool {
let Ok(path) = self.document_path("settings.json") else {
return true;
};
match Document::open_path_with(path, &self.options()) {
Ok(document) => diagnostics_of(&document),
Err(_) => true,
}
}
pub fn startup_diagnostics_enabled(&self) -> bool {
match self.document() {
Ok(document) => diagnostics_of(document),
Err(_) => false,
}
}
pub fn get(&self, key: &str, with_revision: Option<bool>) -> Result<Value, WorkspaceError> {
if key == SETTINGS_KEY {
let state = self.document()?.get().map_err(settings_error)?;
let revision = state.as_ref().map_or(0, |state| state.revision);
let value = state
.filter(|state| state.value.as_object().is_some_and(|map| !map.is_empty()))
.map(|state| state.value.to_string());
if with_revision == Some(true) {
return Ok(json!({ "value": value, "revision": revision }));
}
return Ok(value.map_or(Value::Null, Value::String));
}
let state = self.explorer_document()?.get().map_err(settings_error)?;
Ok(state
.and_then(|state| {
state
.value
.get(key)
.and_then(Value::as_str)
.map(str::to_owned)
})
.map_or(Value::Null, Value::String))
}
pub fn set(
&self,
key: &str,
value: &str,
expected_revision: Option<u64>,
merge: Option<bool>,
) -> Result<SettingsWrite, WorkspaceError> {
if key == SETTINGS_KEY {
let map = parse_object(value)
.ok_or_else(|| WorkspaceError::Other("settings must be a JSON object".into()))?;
let document = self.document()?;
let state = if merge == Some(true) {
document.patch(DOCUMENT_VERSION, &Value::Object(map), expected_revision)
} else {
document.put(DOCUMENT_VERSION, Value::Object(map), expected_revision)
}
.map_err(settings_error)?;
let committed = state.value.to_string();
return Ok(SettingsWrite {
answer: json!({ "value": committed, "revision": state.revision }),
committed: Some(state.value),
});
}
self.explorer_document()?
.patch(DOCUMENT_VERSION, &json!({ key: value }), None)
.map_err(settings_error)?;
Ok(SettingsWrite {
answer: Value::Null,
committed: None,
})
}
}
fn diagnostics_of(document: &Document) -> bool {
document
.get()
.ok()
.flatten()
.and_then(|state| state.value.get("diagnostics").and_then(Value::as_bool))
.unwrap_or(true)
}
fn settings_error(error: SettingsError) -> WorkspaceError {
match error {
SettingsError::Conflict { expected, actual } => WorkspaceError::WriteConflict(format!(
"settings revision conflict: expected {expected}, found {actual}"
)),
other => WorkspaceError::Other(format!("settings store: {other}")),
}
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn settings_round_trip_with_revision() {
let dir =
std::env::temp_dir().join(format!("rightkit-settings-test-{}", std::process::id()));
std::fs::create_dir_all(dir.join("test-app")).unwrap();
let store = SettingsStore::new(Some(dir.clone()), "test-app");
assert_eq!(store.get(SETTINGS_KEY, None).unwrap(), Value::Null);
let write = store
.set(SETTINGS_KEY, r#"{"diagnostics":false}"#, None, None)
.unwrap();
assert_eq!(write.diagnostics_enabled(), Some(false));
let read = store.get(SETTINGS_KEY, Some(true)).unwrap();
assert_eq!(read["revision"], write.answer["revision"]);
assert!(!store.persisted_diagnostics_enabled());
let _ = std::fs::remove_dir_all(dir);
}
#[test]
fn missing_data_dir_is_an_error() {
let store = SettingsStore::new(None, "test-app");
assert!(store.get(SETTINGS_KEY, None).is_err());
assert!(store.persisted_diagnostics_enabled());
assert!(!store.startup_diagnostics_enabled());
}
#[test]
fn explorer_record_round_trips() {
let dir =
std::env::temp_dir().join(format!("rightkit-explorer-rec-{}", std::process::id()));
std::fs::create_dir_all(dir.join("test-app")).unwrap();
let store = SettingsStore::new(Some(dir.clone()), "test-app");
let write = store.set("k", "v", None, None).unwrap();
assert!(write.committed.is_none());
assert_eq!(store.get("k", None).unwrap(), Value::String("v".into()));
let _ = std::fs::remove_dir_all(dir);
}
}