refactor(backend): phase 5 - optimize concurrency with RwLock and async IO

Replace Mutex with RwLock for AppState.config to enable concurrent reads,
improving performance for tray menu building and query operations that
previously blocked each other unnecessarily.

Key changes:
- Migrate AppState.config from Mutex<MultiAppConfig> to RwLock<MultiAppConfig>
- Distinguish read-only operations (read()) from mutations (write()) across
  all command handlers and service layers
- Offload blocking file I/O in import/export commands to spawn_blocking threads,
  minimizing lock hold time and preventing main thread blocking
- Extract load_config_for_import() to separate I/O logic from state updates
- Update all integration tests to use RwLock semantics

Performance impact:
- Concurrent reads: Multiple threads can now query config simultaneously
  (tray menu, provider list, MCP config)
- Reduced contention: Write locks only acquired during actual mutations
- Non-blocking I/O: Config import/export no longer freezes UI thread

All existing tests pass with new locking semantics.
This commit is contained in:
Jason
2025-10-28 12:23:44 +08:00
parent 7e27f88154
commit 7b1a68ee4e
9 changed files with 107 additions and 80 deletions

View File

@@ -1,5 +1,5 @@
use serde_json::json;
use std::{fs, path::Path, sync::Mutex};
use std::{fs, path::Path, sync::RwLock};
use tauri::async_runtime;
use cc_switch_lib::{
@@ -728,7 +728,7 @@ fn import_config_from_path_overwrites_state_and_creates_backup() {
.expect("write import file");
let app_state = AppState {
config: Mutex::new(MultiAppConfig::default()),
config: RwLock::new(MultiAppConfig::default()),
};
let backup_id =
@@ -757,7 +757,7 @@ fn import_config_from_path_overwrites_state_and_creates_backup() {
"saved config should record new current provider"
);
let guard = app_state.config.lock().expect("lock state after import");
let guard = app_state.config.read().expect("lock state after import");
let claude_manager = guard
.get_manager(&AppType::Claude)
.expect("claude manager in state");
@@ -784,7 +784,7 @@ fn import_config_from_path_invalid_json_returns_error() {
fs::write(&invalid_path, "{ not-json ").expect("write invalid json");
let app_state = AppState {
config: Mutex::new(MultiAppConfig::default()),
config: RwLock::new(MultiAppConfig::default()),
};
let err = import_config_from_path(&invalid_path, &app_state).expect_err("import should fail");
@@ -802,7 +802,7 @@ fn import_config_from_path_missing_file_produces_io_error() {
let missing_path = Path::new("/nonexistent/import.json");
let app_state = AppState {
config: Mutex::new(MultiAppConfig::default()),
config: RwLock::new(MultiAppConfig::default()),
};
let err = import_config_from_path(missing_path, &app_state)