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,10 +1,10 @@
use crate::app_config::MultiAppConfig;
use crate::error::AppError;
use std::sync::Mutex;
use std::sync::RwLock;
/// 全局应用状态
pub struct AppState {
pub config: Mutex<MultiAppConfig>,
pub config: RwLock<MultiAppConfig>,
}
impl AppState {
@@ -16,13 +16,13 @@ impl AppState {
});
Self {
config: Mutex::new(config),
config: RwLock::new(config),
}
}
/// 保存配置到文件
pub fn save(&self) -> Result<(), AppError> {
let config = self.config.lock().map_err(AppError::from)?;
let config = self.config.read().map_err(AppError::from)?;
config.save()
}