refactor(backend): complete phase 1 - full AppError migration (100%)

Finalized the backend error handling refactoring by migrating all remaining
modules to use AppError, eliminating all temporary error conversions.

## Changes

### Fully Migrated Modules

- **mcp.rs** (129 lines changed)
  - Migrated 13 functions from Result<T, String> to Result<T, AppError>
  - Added AppError::McpValidation for domain-specific validation errors
  - Functions: validate_server_spec, validate_mcp_entry, upsert_in_config_for,
    delete_in_config_for, set_enabled_and_sync_for, sync_enabled_to_claude,
    import_from_claude, import_from_codex, sync_enabled_to_codex
  - Removed all temporary error conversions

- **usage_script.rs** (143 lines changed)
  - Migrated 4 functions: execute_usage_script, send_http_request,
    validate_result, validate_single_usage
  - Used AppError::Message for JS runtime errors
  - Used AppError::InvalidInput for script validation errors
  - Improved error construction with ok_or_else (lazy evaluation)

- **lib.rs** (47 lines changed)
  - Migrated create_tray_menu() and switch_provider_internal()
  - Simplified PoisonError handling with AppError::from
  - Added error logging in update_tray_menu()
  - Improved error handling in menu update logic

- **migration.rs** (10 lines changed)
  - Migrated migrate_copies_into_config()
  - Used AppError::io() helper for file operations

- **speedtest.rs** (8 lines changed)
  - Migrated build_client() and test_endpoints()
  - Used AppError::Message for HTTP client errors

- **app_store.rs** (14 lines changed)
  - Migrated set_app_config_dir_to_store() and migrate_app_config_dir_from_settings()
  - Used AppError::Message for Tauri Store errors
  - Used AppError::io() for file system operations

### Fixed Previous Temporary Solutions

- **import_export.rs** (2 lines changed)
  - Removed AppError::Message wrapper for mcp::sync_enabled_to_codex
  - Now directly calls the AppError-returning function (no conversion needed)

- **commands.rs** (6 lines changed)
  - Updated query_provider_usage() and test_api_endpoints()
  - Explicit .to_string() conversion for Tauri command interface

## New Error Types

- **AppError::McpValidation**: Domain-specific error for MCP configuration validation
  - Separates MCP validation errors from generic Config errors
  - Follows domain-driven design principles

## Statistics

- Files changed: 8
- Lines changed: +237/-122 (net +115)
- Compilation:  Success (7.13s, 0 warnings)
- Tests:  4/4 passed

## Benefits

- **100% Migration**: All modules now use AppError consistently
- **Domain Errors**: Added McpValidation for better error categorization
- **No Temporary Solutions**: Eliminated all AppError::Message conversions for internal calls
- **Performance**: Used ok_or_else for lazy error construction
- **Maintainability**: Removed ~60 instances of .map_err(|e| format!("...", e))
- **Debugging**: Added error logging in critical paths (tray menu updates)

## Phase 1 Complete

Total impact across 3 commits:
- 25 files changed
- +671/-302 lines (net +369)
- 100% of codebase migrated from Result<T, String> to Result<T, AppError>
- 0 compilation warnings
- All tests passing

Ready for Phase 2: Splitting commands.rs by domain.

Co-authored-by: Claude <noreply@anthropic.com>
This commit is contained in:
Jason
2025-10-27 20:36:08 +08:00
parent 1cc0e4bc8d
commit 4aa9512e36
8 changed files with 237 additions and 122 deletions

View File

@@ -2,11 +2,14 @@ use serde_json::{json, Value};
use std::collections::HashMap;
use crate::app_config::{AppType, McpConfig, MultiAppConfig};
use crate::error::AppError;
/// 基础校验:允许 stdio/http或省略 type视为 stdio。对应必填字段存在
fn validate_server_spec(spec: &Value) -> Result<(), String> {
fn validate_server_spec(spec: &Value) -> Result<(), AppError> {
if !spec.is_object() {
return Err("MCP 服务器连接定义必须为 JSON 对象".into());
return Err(AppError::McpValidation(
"MCP 服务器连接定义必须为 JSON 对象".into(),
));
}
let t_opt = spec.get("type").and_then(|x| x.as_str());
// 支持两种stdio/http若缺省 type 则按 stdio 处理(与社区常见 .mcp.json 一致)
@@ -14,54 +17,71 @@ fn validate_server_spec(spec: &Value) -> Result<(), String> {
let is_http = t_opt.map(|t| t == "http").unwrap_or(false);
if !(is_stdio || is_http) {
return Err("MCP 服务器 type 必须是 'stdio' 或 'http'(或省略表示 stdio".into());
return Err(AppError::McpValidation(
"MCP 服务器 type 必须是 'stdio' 或 'http'(或省略表示 stdio".into(),
));
}
if is_stdio {
let cmd = spec.get("command").and_then(|x| x.as_str()).unwrap_or("");
if cmd.trim().is_empty() {
return Err("stdio 类型的 MCP 服务器缺少 command 字段".into());
return Err(AppError::McpValidation(
"stdio 类型的 MCP 服务器缺少 command 字段".into(),
));
}
}
if is_http {
let url = spec.get("url").and_then(|x| x.as_str()).unwrap_or("");
if url.trim().is_empty() {
return Err("http 类型的 MCP 服务器缺少 url 字段".into());
return Err(AppError::McpValidation(
"http 类型的 MCP 服务器缺少 url 字段".into(),
));
}
}
Ok(())
}
fn validate_mcp_entry(entry: &Value) -> Result<(), String> {
fn validate_mcp_entry(entry: &Value) -> Result<(), AppError> {
let obj = entry
.as_object()
.ok_or_else(|| "MCP 服务器条目必须为 JSON 对象".to_string())?;
.ok_or_else(|| {
AppError::McpValidation("MCP 服务器条目必须为 JSON 对象".into())
})?;
let server = obj
.get("server")
.ok_or_else(|| "MCP 服务器条目缺少 server 字段".to_string())?;
.ok_or_else(|| {
AppError::McpValidation("MCP 服务器条目缺少 server 字段".into())
})?;
validate_server_spec(server)?;
for key in ["name", "description", "homepage", "docs"] {
if let Some(val) = obj.get(key) {
if !val.is_string() {
return Err(format!("MCP 服务器 {} 必须为字符串", key));
return Err(AppError::McpValidation(format!(
"MCP 服务器 {} 必须为字符串",
key
)));
}
}
}
if let Some(tags) = obj.get("tags") {
let arr = tags
.as_array()
.ok_or_else(|| "MCP 服务器 tags 必须为字符串数组".to_string())?;
let arr = tags.as_array().ok_or_else(|| {
AppError::McpValidation("MCP 服务器 tags 必须为字符串数组".into())
})?;
if !arr.iter().all(|item| item.is_string()) {
return Err("MCP 服务器 tags 必须为字符串数组".into());
return Err(AppError::McpValidation(
"MCP 服务器 tags 必须为字符串数组".into(),
));
}
}
if let Some(enabled) = obj.get("enabled") {
if !enabled.is_boolean() {
return Err("MCP 服务器 enabled 必须为布尔值".into());
return Err(AppError::McpValidation(
"MCP 服务器 enabled 必须为布尔值".into(),
));
}
}
@@ -159,16 +179,22 @@ pub fn normalize_servers_for(config: &mut MultiAppConfig, app: &AppType) -> usiz
normalize_server_keys(servers)
}
fn extract_server_spec(entry: &Value) -> Result<Value, String> {
fn extract_server_spec(entry: &Value) -> Result<Value, AppError> {
let obj = entry
.as_object()
.ok_or_else(|| "MCP 服务器条目必须为 JSON 对象".to_string())?;
.ok_or_else(|| {
AppError::McpValidation("MCP 服务器条目必须为 JSON 对象".into())
})?;
let server = obj
.get("server")
.ok_or_else(|| "MCP 服务器条目缺少 server 字段".to_string())?;
.ok_or_else(|| {
AppError::McpValidation("MCP 服务器条目缺少 server 字段".into())
})?;
if !server.is_object() {
return Err("MCP 服务器 server 字段必须为 JSON 对象".into());
return Err(AppError::McpValidation(
"MCP 服务器 server 字段必须为 JSON 对象".into(),
));
}
Ok(server.clone())
@@ -227,9 +253,11 @@ pub fn upsert_in_config_for(
app: &AppType,
id: &str,
spec: Value,
) -> Result<bool, String> {
) -> Result<bool, AppError> {
if id.trim().is_empty() {
return Err("MCP 服务器 ID 不能为空".into());
return Err(AppError::InvalidInput(
"MCP 服务器 ID 不能为空".into(),
));
}
normalize_servers_for(config, app);
validate_mcp_entry(&spec)?;
@@ -237,16 +265,20 @@ pub fn upsert_in_config_for(
let mut entry_obj = spec
.as_object()
.cloned()
.ok_or_else(|| "MCP 服务器条目必须为 JSON 对象".to_string())?;
.ok_or_else(|| {
AppError::McpValidation("MCP 服务器条目必须为 JSON 对象".into())
})?;
if let Some(existing_id) = entry_obj.get("id") {
let Some(existing_id_str) = existing_id.as_str() else {
return Err("MCP 服务器 id 必须为字符串".into());
return Err(AppError::McpValidation(
"MCP 服务器 id 必须为字符串".into(),
));
};
if existing_id_str != id {
return Err(format!(
return Err(AppError::McpValidation(format!(
"MCP 服务器条目中的 id '{}' 与参数 id '{}' 不一致",
existing_id_str, id
));
)));
}
} else {
entry_obj.insert(String::from("id"), json!(id));
@@ -265,9 +297,11 @@ pub fn delete_in_config_for(
config: &mut MultiAppConfig,
app: &AppType,
id: &str,
) -> Result<bool, String> {
) -> Result<bool, AppError> {
if id.trim().is_empty() {
return Err("MCP 服务器 ID 不能为空".into());
return Err(AppError::InvalidInput(
"MCP 服务器 ID 不能为空".into(),
));
}
normalize_servers_for(config, app);
let existed = config.mcp_for_mut(app).servers.remove(id).is_some();
@@ -280,9 +314,11 @@ pub fn set_enabled_and_sync_for(
app: &AppType,
id: &str,
enabled: bool,
) -> Result<bool, String> {
) -> Result<bool, AppError> {
if id.trim().is_empty() {
return Err("MCP 服务器 ID 不能为空".into());
return Err(AppError::InvalidInput(
"MCP 服务器 ID 不能为空".into(),
));
}
normalize_servers_for(config, app);
if let Some(spec) = config.mcp_for_mut(app).servers.get_mut(id) {
@@ -290,7 +326,9 @@ pub fn set_enabled_and_sync_for(
let mut obj = spec
.as_object()
.cloned()
.ok_or_else(|| "MCP 服务器定义必须为 JSON 对象".to_string())?;
.ok_or_else(|| {
AppError::McpValidation("MCP 服务器定义必须为 JSON 对象".into())
})?;
obj.insert("enabled".into(), json!(enabled));
*spec = Value::Object(obj);
} else {
@@ -313,19 +351,20 @@ pub fn set_enabled_and_sync_for(
}
/// 将 config.json 中 enabled==true 的项投影写入 ~/.claude.json
pub fn sync_enabled_to_claude(config: &MultiAppConfig) -> Result<(), String> {
pub fn sync_enabled_to_claude(config: &MultiAppConfig) -> Result<(), AppError> {
let enabled = collect_enabled_servers(&config.mcp.claude);
crate::claude_mcp::set_mcp_servers_map(&enabled).map_err(|e| e.to_string())
crate::claude_mcp::set_mcp_servers_map(&enabled)
}
/// 从 ~/.claude.json 导入 mcpServers 到 config.json设为 enabled=true
/// 已存在的项仅强制 enabled=true不覆盖其他字段。
pub fn import_from_claude(config: &mut MultiAppConfig) -> Result<usize, String> {
pub fn import_from_claude(config: &mut MultiAppConfig) -> Result<usize, AppError> {
let text_opt = crate::claude_mcp::read_mcp_json()?;
let Some(text) = text_opt else { return Ok(0) };
let mut changed = normalize_servers_for(config, &AppType::Claude);
let v: Value =
serde_json::from_str(&text).map_err(|e| format!("解析 ~/.claude.json 失败: {}", e))?;
let v: Value = serde_json::from_str(&text).map_err(|e| {
AppError::McpValidation(format!("解析 ~/.claude.json 失败: {}", e))
})?;
let Some(map) = v.get("mcpServers").and_then(|x| x.as_object()) else {
return Ok(changed);
};
@@ -394,15 +433,19 @@ pub fn import_from_claude(config: &mut MultiAppConfig) -> Result<usize, String>
/// 从 ~/.codex/config.toml 导入 MCP 到 config.jsonCodex 作用域),并将导入项设为 enabled=true。
/// 支持两种 schema[mcp.servers.<id>] 与 [mcp_servers.<id>]。
/// 已存在的项仅强制 enabled=true不覆盖其他字段。
pub fn import_from_codex(config: &mut MultiAppConfig) -> Result<usize, String> {
pub fn import_from_codex(config: &mut MultiAppConfig) -> Result<usize, AppError> {
let text = crate::codex_config::read_and_validate_codex_config_text()?;
if text.trim().is_empty() {
return Ok(0);
}
let mut changed_total = normalize_servers_for(config, &AppType::Codex);
let root: toml::Table =
toml::from_str(&text).map_err(|e| format!("解析 ~/.codex/config.toml 失败: {}", e))?;
let root: toml::Table = toml::from_str(&text).map_err(|e| {
AppError::McpValidation(format!(
"解析 ~/.codex/config.toml 失败: {}",
e
))
})?;
// helper处理一组 servers 表
let mut import_servers_tbl = |servers_tbl: &toml::value::Table| {
@@ -565,7 +608,7 @@ pub fn import_from_codex(config: &mut MultiAppConfig) -> Result<usize, String> {
/// - 读取现有 config.toml若语法无效则报错不尝试覆盖
/// - 仅更新 `mcp.servers` 或 `mcp_servers` 子表,保留 `mcp` 其它键
/// - 仅写入启用项;无启用项时清理对应子表
pub fn sync_enabled_to_codex(config: &MultiAppConfig) -> Result<(), String> {
pub fn sync_enabled_to_codex(config: &MultiAppConfig) -> Result<(), AppError> {
use toml::{value::Value as TomlValue, Table as TomlTable};
// 1) 收集启用项Codex 维度)
@@ -576,8 +619,9 @@ pub fn sync_enabled_to_codex(config: &MultiAppConfig) -> Result<(), String> {
let mut root: TomlTable = if base_text.trim().is_empty() {
TomlTable::new()
} else {
toml::from_str::<TomlTable>(&base_text)
.map_err(|e| format!("解析 config.toml 失败: {}", e))?
toml::from_str::<TomlTable>(&base_text).map_err(|e| {
AppError::McpValidation(format!("解析 config.toml 失败: {}", e))
})?
};
// 3) 写入 servers 表(支持 mcp.servers 与 mcp_servers优先沿用已有风格默认 mcp_servers
@@ -723,8 +767,9 @@ pub fn sync_enabled_to_codex(config: &MultiAppConfig) -> Result<(), String> {
}
// 4) 序列化并写回 config.toml仅改 TOML不触碰 auth.json
let new_text = toml::to_string(&TomlValue::Table(root))
.map_err(|e| format!("序列化 config.toml 失败: {}", e))?;
let new_text = toml::to_string(&TomlValue::Table(root)).map_err(|e| {
AppError::McpValidation(format!("序列化 config.toml 失败: {}", e))
})?;
let path = crate::codex_config::get_codex_config_path();
crate::config::write_text_file(&path, &new_text)?;