refine(usage): enhance query robustness and error handling

Backend improvements:
- Add InvalidHttpMethod error enum for better error semantics
- Clamp HTTP timeout to 2-30s to prevent config abuse
- Strict HTTP method validation instead of silent fallback to GET

Frontend improvements:
- Add i18n support for usage query errors (en/zh)
- Improve error handling with type-safe unknown instead of any
- Optimize i18n import (direct import instead of dynamic)
- Disable auto-retry for usage queries to avoid API stampede

Additional changes:
- Apply prettier formatting to affected files

Files changed:
- src-tauri/src/error.rs (+2)
- src-tauri/src/usage_script.rs (+8 -2)
- src/i18n/locales/{en,zh}.json (+4 -1 each)
- src/lib/api/usage.ts (+21 -4)
- src/lib/query/queries.ts (+1)
- style: prettier formatting on 6 other files
This commit is contained in:
Jason
2025-11-03 10:24:59 +08:00
parent ab2833e626
commit 85334d8dce
12 changed files with 94 additions and 36 deletions

View File

@@ -46,6 +46,8 @@ pub enum AppError {
McpValidation(String),
#[error("{0}")]
Message(String),
#[error("不支持的 HTTP 方法: {0}")]
InvalidHttpMethod(String),
#[error("{zh} ({en})")]
Localized {
key: &'static str,

View File

@@ -116,12 +116,18 @@ struct RequestConfig {
/// 发送 HTTP 请求
async fn send_http_request(config: &RequestConfig, timeout_secs: u64) -> Result<String, AppError> {
// 约束超时范围,防止异常配置导致长时间阻塞
let timeout = timeout_secs.clamp(2, 30);
let client = Client::builder()
.timeout(Duration::from_secs(timeout_secs))
.timeout(Duration::from_secs(timeout))
.build()
.map_err(|e| AppError::Message(format!("创建客户端失败: {}", e)))?;
let method = config.method.parse().unwrap_or(reqwest::Method::GET);
// 严格校验 HTTP 方法,非法值不回退为 GET
let method: reqwest::Method = config
.method
.parse()
.map_err(|_| AppError::InvalidHttpMethod(config.method.clone()))?;
let mut req = client.request(method.clone(), &config.url);