Skip to content

armgit / Cap

Public Imported from GitHub
0

Open source Loom alternative. Beautiful, shareable screen recordings.

fix(desktop-gpui): serialize shared settings store writes

Aditya Garud51aa7aff4d56
diff --git a/apps/desktop-gpui/src/store.rs b/apps/desktop-gpui/src/store.rs
index 9c75aec9d..9f02b1218 100644
--- a/apps/desktop-gpui/src/store.rs
+++ b/apps/desktop-gpui/src/store.rs
@@ -362,6 +362,8 @@ pub fn tauri_store_path() -> PathBuf {
}
}
+static STORE_UPDATE_LOCK: std::sync::Mutex<()> = std::sync::Mutex::new(());
+
/// The whole store as raw JSON.
///
/// A missing file is an empty store. A file that exists but does not parse is
@@ -426,39 +428,47 @@ pub fn notification_sounds_enabled() -> bool {
/// already updated its in-memory copy, which is the same optimistic order
/// `handleChange` uses in `general.tsx`.
pub fn set_store_setting(section: &str, key: &str, value: Value) -> bool {
- let path = tauri_store_path();
- let Some(mut store) = read_store(&path) else {
- return false;
- };
-
- let entry = store
- .entry(section.to_string())
- .or_insert_with(|| Value::Object(Map::new()));
- if !entry.is_object() {
- *entry = Value::Object(Map::new());
- }
- entry
- .as_object_mut()
- .expect("just replaced any non-object with an object")
- .insert(key.to_string(), value);
-
- write_store(&path, &Value::Object(store))
+ update_store(|store| {
+ let entry = store
+ .entry(section.to_string())
+ .or_insert_with(|| Value::Object(Map::new()));
+ if !entry.is_object() {
+ *entry = Value::Object(Map::new());
+ }
+ entry
+ .as_object_mut()
+ .expect("just replaced any non-object with an object")
+ .insert(key.to_string(), value);
+ true
+ })
}
/// Replace or remove one top-level store section. `authStore.set(null)` in
/// the Tauri app drops the whole `auth` object; writing keys one at a time
/// would leave a half-signed-out session behind.
pub fn set_store_value(section: &str, value: Value) -> bool {
+ update_store(|store| {
+ if value.is_null() {
+ store.remove(section);
+ } else {
+ store.insert(section.to_string(), value);
+ }
+ true
+ })
+}
+
+/// Reads, mutates and rewrites the store as one step, so two writers cannot
+/// both start from the same snapshot and drop each other's changes. Returning
+/// false from `mutate` leaves the file untouched.
+fn update_store(mutate: impl FnOnce(&mut Map<String, Value>) -> bool) -> bool {
+ let _guard = STORE_UPDATE_LOCK
+ .lock()
+ .unwrap_or_else(std::sync::PoisonError::into_inner);
let path = tauri_store_path();
let Some(mut store) = read_store(&path) else {
return false;
};
- if value.is_null() {
- store.remove(section);
- } else {
- store.insert(section.to_string(), value);
- }
- write_store(&path, &Value::Object(store))
+ mutate(&mut store) && write_store(&path, &Value::Object(store))
}
/// Pretty JSON, two-space indent, no trailing newline -- byte-shape identical
@@ -1020,36 +1030,34 @@ fn set_device_format_settings(
let Ok(Value::Object(fields)) = serde_json::to_value(settings) else {
return false;
};
- let path = tauri_store_path();
- let Some(mut store) = read_store(&path) else {
- return false;
- };
- let section = store
- .entry(RECORDING_SETTINGS.to_string())
- .or_insert_with(|| Value::Object(Map::new()));
- let Some(section) = section.as_object_mut() else {
- return false;
- };
- let map = section
- .entry(map_key.to_string())
- .or_insert_with(|| Value::Object(Map::new()));
- let Some(map) = map.as_object_mut() else {
- return false;
- };
- for key in keys {
- let entry = map.entry(key).or_insert_with(|| Value::Object(Map::new()));
- let Some(entry) = entry.as_object_mut() else {
+ update_store(|store| {
+ let section = store
+ .entry(RECORDING_SETTINGS.to_string())
+ .or_insert_with(|| Value::Object(Map::new()));
+ let Some(section) = section.as_object_mut() else {
+ return false;
+ };
+ let map = section
+ .entry(map_key.to_string())
+ .or_insert_with(|| Value::Object(Map::new()));
+ let Some(map) = map.as_object_mut() else {
return false;
};
- for (key, value) in &fields {
- if value.is_null() {
- entry.remove(key);
- } else {
- entry.insert(key.clone(), value.clone());
+ for key in keys {
+ let entry = map.entry(key).or_insert_with(|| Value::Object(Map::new()));
+ let Some(entry) = entry.as_object_mut() else {
+ return false;
+ };
+ for (key, value) in &fields {
+ if value.is_null() {
+ entry.remove(key);
+ } else {
+ entry.insert(key.clone(), value.clone());
+ }
}
}
- }
- write_store(&path, &Value::Object(store))
+ true
+ })
}
#[derive(Clone, Debug, Default, PartialEq)]
@@ -1838,12 +1846,7 @@ pub fn set_automations(automations: &AutomationsStore) -> bool {
return false;
}
};
- let path = tauri_store_path();
- let Some(mut store) = read_store(&path) else {
- return false;
- };
- store.insert(AUTOMATIONS.to_string(), value);
- write_store(&path, &Value::Object(store))
+ set_store_value(AUTOMATIONS, value)
}
/// The preset names `applyPreset` offers -- `presetsStore.createQuery()` in
@@ -2148,6 +2151,66 @@ mod tests {
assert_eq!(after[RECORDING_SETTINGS]["future"], 42);
}
+ #[test]
+ fn concurrent_store_writers_preserve_each_others_changes() {
+ let contents = serde_json::json!({"unknown": "x".repeat(64 * 1024)}).to_string();
+ let store = TempStore::new("concurrent-writers", Some(&contents));
+ let barrier = std::sync::Arc::new(std::sync::Barrier::new(16));
+ let workers = (0..16)
+ .map(|index| {
+ let path = store.path.clone();
+ let barrier = barrier.clone();
+ std::thread::spawn(move || {
+ set_test_tauri_store_path(Some(path));
+ barrier.wait();
+ let saved = match index {
+ 0..=3 => set_store_setting(
+ GENERAL_SETTINGS,
+ &format!("setting-{index}"),
+ Value::from(index),
+ ),
+ 4..=7 => set_store_value(&format!("section-{index}"), Value::from(index)),
+ 8..=11 => set_microphone_device_settings(
+ &format!("microphone-{index}"),
+ cap_recording::feeds::microphone::MicrophoneDeviceSettings {
+ sample_rate: Some(48000),
+ channels: Some(2),
+ },
+ ),
+ _ => set_automations(&AutomationsStore::default()),
+ };
+ set_test_tauri_store_path(None);
+ saved
+ })
+ })
+ .collect::<Vec<_>>();
+ let results = workers
+ .into_iter()
+ .map(|worker| worker.join().unwrap())
+ .collect::<Vec<_>>();
+ assert!(results.into_iter().all(|saved| saved));
+
+ let after = store.read();
+ assert_eq!(after["unknown"], "x".repeat(64 * 1024));
+ for index in 0..4 {
+ assert_eq!(after[GENERAL_SETTINGS][format!("setting-{index}")], index);
+ }
+ for index in 4..8 {
+ assert_eq!(after[format!("section-{index}")], index);
+ }
+ for index in 8..12 {
+ assert_eq!(
+ after[RECORDING_SETTINGS]["microphoneDeviceSettings"]
+ [format!("microphone-{index}")],
+ serde_json::json!({"sampleRate": 48000, "channels": 2})
+ );
+ }
+ assert_eq!(
+ after[AUTOMATIONS],
+ serde_json::to_value(AutomationsStore::default()).unwrap()
+ );
+ }
+
#[test]
fn temporary_stores_are_thread_local_without_mutating_process_environment() {
let original = std::env::var_os("CAP_GPUI_TAURI_STORE");