diff --git a/Cargo.lock b/Cargo.lock index b7e828b5..a6eb23f4 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -2850,6 +2850,7 @@ dependencies = [ "tw-scan", "tw-secret", "tw-store", + "tw-types", "tw-yaml", ] diff --git a/crates/tw-control/Cargo.toml b/crates/tw-control/Cargo.toml index 94ac1189..ddd04e1c 100644 --- a/crates/tw-control/Cargo.toml +++ b/crates/tw-control/Cargo.toml @@ -9,6 +9,7 @@ description = "Control-plane API server over a unix socket" [dependencies] tw-api = { workspace = true } +tw-types = { workspace = true } # 列网卡用 getifaddrs —— 比引一个 crate 便宜 libc = { workspace = true } tw-config = { workspace = true } @@ -47,4 +48,5 @@ serde_yaml_ng = { workspace = true } tempfile = "3" tw-observe = { workspace = true } tw-api = { workspace = true } +tw-types = { workspace = true } tokio = { workspace = true, features = ["rt", "macros"] } diff --git a/crates/tw-control/src/chatgpt.rs b/crates/tw-control/src/chatgpt.rs index e30f85c9..0fcdc669 100644 --- a/crates/tw-control/src/chatgpt.rs +++ b/crates/tw-control/src/chatgpt.rs @@ -35,6 +35,7 @@ use tw_config::history::Origin; use tw_gateway::chatgpt; use crate::{ControlState, Fail, fail}; +use tw_types::msg; /// 登录要在多久之内完成。和 Codex 一样是 15 分钟 const LOGIN_TTL: Duration = Duration::from_secs(15 * 60); @@ -181,7 +182,7 @@ impl Want { Some(other) => { return Err(fail( StatusCode::BAD_REQUEST, - format!("不支持的登录方式「{other}」"), + msg!("control.unknown_signin_mode", mode = other => "`{mode}` is not a sign-in mode we support."), )); } }; @@ -194,7 +195,7 @@ impl Want { { return Err(fail( StatusCode::BAD_REQUEST, - format!("代理「{proxy}」不存在"), + msg!("control.proxy_not_found", proxy = proxy => "There is no proxy named `{proxy}`."), )); } if let Some(p) = cfg.providers.iter().find(|p| p.name == name) @@ -202,7 +203,11 @@ impl Want { { return Err(fail( StatusCode::CONFLICT, - format!("已有名为「{name}」的上游,且不是 ChatGPT 账号上游,请使用其他名称"), + msg!( + "control.name_taken_not_chatgpt", name = name => + "There is already an upstream named `{name}`, and it is not a ChatGPT account. \ + Use a different name." + ), )); } let return_to = match given(&req.return_to) { @@ -210,7 +215,11 @@ impl Want { Some(_) => { return Err(fail( StatusCode::BAD_REQUEST, - "登录完成后的跳转地址只能使用应用自己的协议,不能是网页地址", + msg!( + "control.redirect_must_be_app_scheme" => + "The address to return to after signing in has to use the app's own scheme, not a \ + web address." + ), )); } None => None, @@ -264,10 +273,14 @@ async fn start_browser( .iter() .map(|p| p.to_string()) .collect::>() - .join("、"); + .join(", "); fail( StatusCode::CONFLICT, - format!("登录回调端口 {ports} 均被占用。如果 Codex 正在登录,请先完成或关闭它"), + msg!( + "control.callback_ports_busy", ports = ports => + "Every sign-in callback port ({ports}) is taken. If Codex is signing in, finish or \ + close it first." + ), ) })?; @@ -314,8 +327,12 @@ async fn start_device( want: Want, ) -> Result<(Current, tw_api::ChatgptLogin), Fail> { let issuer = s.chatgpt.endpoints.issuer.clone(); - let http = - client_for(s, &want.name, &want.proxy).map_err(|e| fail(StatusCode::BAD_GATEWAY, e))?; + let http = client_for(s, &want.name, &want.proxy).map_err(|e| { + fail( + StatusCode::BAD_GATEWAY, + msg!("control.upstream_call_failed", detail = e => "{detail}"), + ) + })?; let asked = serde_json::json!({ "client_id": chatgpt::CLIENT_ID }); let resp = send( &http, @@ -329,18 +346,29 @@ async fn start_device( if status == StatusCode::NOT_FOUND { return Err(fail( StatusCode::CONFLICT, - "这个账号还不能用设备码登录,请改用在这台电脑上登录", + msg!( + "control.device_code_unavailable" => + "This account cannot sign in with a device code yet. Sign in on this computer \ + instead." + ), )); } let text = resp.text().await.unwrap_or_default(); if !status.is_success() { return Err(fail( StatusCode::BAD_GATEWAY, - format!("换设备码时返回 {}:{}", status.as_u16(), brief(&text)), + msg!( + "control.device_code_failed", status = status.as_u16(), detail = brief(&text) => + "Asking for a device code answered {status}: {detail}" + ), )); } - let code: DeviceCode = - serde_json::from_str(&text).map_err(|e| fail(StatusCode::BAD_GATEWAY, e))?; + let code: DeviceCode = serde_json::from_str(&text).map_err(|e| { + fail( + StatusCode::BAD_GATEWAY, + msg!("control.upstream_call_failed", detail = e => "{detail}"), + ) + })?; let id = chatgpt::new_state(); let user_code = code.user_code.clone(); Ok(( @@ -406,7 +434,7 @@ async fn await_device( while tokio::time::Instant::now() < deadline { let resp = match send(&http, reqwest::Method::POST, &url, &[], Some(&asked)).await { Ok(r) => r, - Err((_, why)) => return settle(&s, &id, Err(why)), + Err((_, why)) => return settle(&s, &id, Err(why.0.text)), }; let status = resp.status(); // 还没批:接着等 @@ -419,7 +447,11 @@ async fn await_device( return settle( &s, &id, - Err(format!("登录时返回 {}:{}", status.as_u16(), brief(&text))), + Err(format!( + "signing in answered {}: {}", + status.as_u16(), + brief(&text) + )), ); } let done = match serde_json::from_str::(&text) { @@ -434,7 +466,7 @@ async fn await_device( ) .await } - Err(e) => Err(format!("批准登录的响应看不懂:{e}")), + Err(e) => Err(format!("the approval response could not be read: {e}")), }; return settle(&s, &id, done); } @@ -443,7 +475,7 @@ async fn await_device( status: "expired".into(), provider: None, plan: None, - error: Some("15 分钟内没有完成授权".into()), + error: Some("the authorization was not completed within 15 minutes".into()), }); announce(&s, &id, "expired", None, None); } @@ -459,7 +491,7 @@ fn settle(s: &ControlState, id: &str, done: Result<(String, Option), Str error: None, }, Err(why) => { - tracing::warn!("ChatGPT 登录未完成:{why}"); + tracing::warn!("the ChatGPT sign-in did not finish: {why}"); tw_api::ChatgptLoginStatus { id: id.to_string(), status: "failed".into(), @@ -495,7 +527,10 @@ async fn status( .ok_or_else(|| { fail( StatusCode::NOT_FOUND, - "没有这次登录,或者它已被新的登录替代", + msg!( + "control.signin_gone" => + "There is no such sign-in, or a newer one replaced it." + ), ) }) } @@ -505,15 +540,19 @@ async fn cancel( Path(id): Path, ) -> Result, Fail> { let mut status = { - let g = s - .chatgpt - .current - .lock() - .map_err(|e| fail(StatusCode::INTERNAL_SERVER_ERROR, e))?; + let g = s.chatgpt.current.lock().map_err(|e| { + fail( + StatusCode::INTERNAL_SERVER_ERROR, + msg!("control.internal", detail = e => "{detail}"), + ) + })?; let c = g.as_ref().filter(|c| c.status.id == id).ok_or_else(|| { fail( StatusCode::NOT_FOUND, - "没有这次登录,或者它已被新的登录替代", + msg!( + "control.signin_gone" => + "There is no such sign-in, or a newer one replaced it." + ), ) })?; if c.status.status != "pending" { @@ -567,7 +606,7 @@ async fn serve_callback(flow: Arc, listener: tokio::net::TcpListener) { status: "expired".into(), provider: None, plan: None, - error: Some("15 分钟内没有完成授权".into()), + error: Some("the authorization was not completed within 15 minutes".into()), }); announce(&flow.s, &flow.id, "expired", None, None); } @@ -580,8 +619,8 @@ async fn callback( // **state 对不上就当没来过**:可能是别的网页在试探这个端口,不能让它终止这次登录 if q.get("state") != Some(&flow.state) { return Html(page( - "登录链接已失效", - "请回到 ThinkWatch 重新发起登录。", + "This sign-in link has expired", + "Go back to ThinkWatch and start again.", None, )); } @@ -593,7 +632,7 @@ async fn callback( (Some(e), _) => { let detail = q.get("error_description").unwrap_or(e); Err(format!( - "授权页返回错误:{}", + "the authorization page returned an error: {}", detail.chars().take(200).collect::() )) } @@ -608,17 +647,17 @@ async fn callback( ) .await } - (None, None) => Err("回调中缺少授权码".to_string()), + (None, None) => Err("the callback carried no authorization code".to_string()), }; let html = match &result { Ok(_) => page( - "ChatGPT 登录已完成", - "此页可以关闭。", + "Signed in to ChatGPT", + "This page can be closed.", flow.return_to.as_deref(), ), Err(why) => page( - "ChatGPT 登录未完成", - &format!("{why}。请回到 ThinkWatch 重新发起登录。"), + "The ChatGPT sign-in did not finish", + &format!("{why}. Go back to ThinkWatch and start again."), flow.return_to.as_deref(), ), }; @@ -667,7 +706,7 @@ async fn exchange_and_save( && e.effective_protocol() != Some(Protocol::Chatgpt) { return Err(crate::resources::invalid(format!( - "已有名为「{name}」的上游,且不是 ChatGPT 账号上游" + "there is already an upstream named `{name}`, and it is not a ChatGPT account" ))); } let mut p = existing.cloned().unwrap_or_else(|| tw_config::Provider { @@ -705,7 +744,7 @@ async fn exchange_and_save( )?) }) .await - .map_err(|e| format!("无法写入配置:{e}"))?; + .map_err(|e| format!("the configuration could not be written: {e}"))?; // 模型清单现在就问一次:不然要等到下一轮定时刷新,新上游的模型才出现 let gateway = s.gateway.clone(); let provider = name.clone(); @@ -788,13 +827,13 @@ fn page(title: &str, detail: &str, return_to: Option<&str>) -> String { let u = escape(url); ( format!(r#""#), - format!(r#"

返回 ThinkWatch

"#), + format!(r#"

Back to ThinkWatch

"#), ) } None => (String::new(), String::new()), }; format!( - r#"ThinkWatch{redirect}

{}

{}

{link}
"#, + r#"ThinkWatch{redirect}

{}

{}

{link}
"#, escape(title), escape(detail) ) @@ -827,11 +866,14 @@ async fn account_call( .providers .iter() .find(|p| p.name == name) - .ok_or_else(|| fail(StatusCode::NOT_FOUND, format!("上游「{name}」不存在")))?; + .ok_or_else(|| crate::no_such_upstream(name))?; if p.effective_protocol() != Some(Protocol::Chatgpt) { return Err(fail( StatusCode::BAD_REQUEST, - format!("上游「{name}」不是 ChatGPT 账号上游"), + msg!( + "control.not_a_chatgpt_account", upstream = name => + "Upstream `{upstream}` is not a ChatGPT account." + ), )); } let http = s.gateway.client_for(name); @@ -839,7 +881,10 @@ async fn account_call( let no_credential = |e: String| { fail( StatusCode::BAD_GATEWAY, - format!("无法获取上游「{name}」的凭据:{e}"), + msg!( + "control.credentials_failed", upstream = name, detail = e => + "The credential for upstream `{upstream}` could not be obtained: {detail}" + ), ) }; let headers = s @@ -864,11 +909,19 @@ async fn account_call( .collect::(); return Err(fail( StatusCode::BAD_GATEWAY, - format!("ChatGPT 后端返回 {}:{body}", status.as_u16()), + msg!( + "control.chatgpt_backend_status", status = status.as_u16(), detail = body => + "The ChatGPT backend answered {status}: {detail}" + ), )); } serde_json::from_str(&text) - .map_err(|_| fail(StatusCode::BAD_GATEWAY, "ChatGPT 后端的响应不是 JSON")) + .map_err(|_| { + fail( + StatusCode::BAD_GATEWAY, + msg!("control.chatgpt_backend_not_json" => "The ChatGPT backend's response is not JSON."), + ) + }) } /// 发一次。**这几个接口也如实报身份**;它们不是流式对话,不带会话 ID 和流式的 accept @@ -891,11 +944,12 @@ async fn send( req = req.json(b); } req.send().await.map_err(|e| { + let why = tw_gateway::forward::map_reqwest_error(e); fail( StatusCode::BAD_GATEWAY, - format!( - "无法连接 ChatGPT 后端:{}", - tw_gateway::forward::map_reqwest_error(e).message() + msg!( + "control.chatgpt_backend_unreachable", detail = why.message() => + "The ChatGPT backend could not be reached: {detail}" ), ) }) @@ -968,7 +1022,12 @@ async fn list_resets( .await?; serde_json::from_value(v) .map(Json) - .map_err(|e| fail(StatusCode::BAD_GATEWAY, format!("无法识别重置卡清单:{e}"))) + .map_err(|e| { + fail( + StatusCode::BAD_GATEWAY, + msg!("control.reset_cards_unreadable", detail = e => "The list of reset cards could not be read: {detail}"), + ) + }) } async fn use_reset( @@ -980,7 +1039,10 @@ async fn use_reset( if key.is_empty() || key.len() > 128 || key.chars().any(|c| c.is_control()) { return Err(fail( StatusCode::BAD_REQUEST, - "幂等键不能为空,且不超过 128 个字符", + msg!( + "control.bad_idempotency_key" => + "An idempotency key cannot be empty, and cannot be longer than 128 characters." + ), )); } let mut body = serde_json::json!({ "redeem_request_id": key }); @@ -1002,9 +1064,14 @@ async fn use_reset( .await?; let code = v["code"] .as_str() - .ok_or_else(|| fail(StatusCode::BAD_GATEWAY, "无法识别使用重置卡的结果"))? + .ok_or_else(|| { + fail( + StatusCode::BAD_GATEWAY, + msg!("control.reset_card_result_unreadable" => "The result of using the reset card could not be read."), + ) + })? .to_ascii_lowercase(); - tracing::info!(provider = %name, %code, "已请求使用额度重置卡"); + tracing::info!(provider = %name, %code, "asked to use a quota reset card"); Ok(Json(tw_api::ResetCreditUsed { code, windows_reset: v["windows_reset"].as_i64().unwrap_or(0), diff --git a/crates/tw-control/src/clients.rs b/crates/tw-control/src/clients.rs index 600fe65a..8b27846f 100644 --- a/crates/tw-control/src/clients.rs +++ b/crates/tw-control/src/clients.rs @@ -13,14 +13,17 @@ use tw_adopt::clients::{Gateway, adoptable, manual_only}; use tw_adopt::{detect, plan}; use crate::ControlState; +use tw_types::msg; -type Fail = (StatusCode, String); +use crate::{Fail, fail}; fn find(id: &str) -> Result { - adoptable() - .into_iter() - .find(|c| c.id == id) - .ok_or_else(|| (StatusCode::NOT_FOUND, format!("未知的客户端 {id}"))) + adoptable().into_iter().find(|c| c.id == id).ok_or_else(|| { + fail( + StatusCode::NOT_FOUND, + msg!("control.client_unknown", client = id => "`{client}` is not a client we know."), + ) + }) } /// 客户端该连的地址。 @@ -49,9 +52,12 @@ fn key_for( .find(|c| c.name == n) .cloned() .ok_or_else(|| { - ( + fail( StatusCode::NOT_FOUND, - format!("config.yaml 中没有名为「{n}」的网关密钥"), + msg!( + "control.key_not_found", key = n => + "config.yaml has no gateway key named `{key}`." + ), ) }); } @@ -59,9 +65,13 @@ fn key_for( return Ok(c.clone()); } cfg.default_client().cloned().ok_or_else(|| { - ( + fail( StatusCode::CONFLICT, - "config.yaml 中尚无网关密钥,请先创建网关密钥,再接管客户端".to_string(), + msg!( + "control.no_keys" => + "config.yaml has no gateway key yet. Create one before pointing a client at the \ + gateway." + ), ) }) } @@ -122,7 +132,12 @@ async fn ensure_key( )?) }) .await - .map_err(|e| (StatusCode::CONFLICT, format!("无法创建网关密钥:{e}")))?; + .map_err(|e| { + fail( + StatusCode::CONFLICT, + msg!("control.key_create_failed", detail = e => "The gateway key could not be created: {detail}"), + ) + })?; Ok(Gateway { base: gateway_base(s), key: Some(key), @@ -149,7 +164,12 @@ async fn bind(s: &ControlState, key: &str, client: &str) -> Result<(), Fail> { )?) }) .await - .map_err(|e| (StatusCode::CONFLICT, format!("无法记录密钥归属:{e}")))?; + .map_err(|e| { + fail( + StatusCode::CONFLICT, + msg!("control.key_bind_failed", detail = e => "The key's owner could not be recorded: {detail}"), + ) + })?; Ok(()) } @@ -216,7 +236,7 @@ pub async fn list(State(s): State) -> Result) -> String { match key { @@ -298,7 +318,7 @@ fn bad(e: plan::PlanError) -> Fail { plan::PlanError::ForeignSidecar { .. } => StatusCode::CONFLICT, _ => StatusCode::BAD_REQUEST, }; - (code, e.to_string()) + fail(code, msg!("control.adopt_failed", detail = e => "{detail}")) } /// 落盘。**用户在 diff 上点过确认之后才该到这里。** @@ -346,7 +366,12 @@ pub async fn restore( // ---------------------------------------------------------------- MCP 矩阵 fn mcp_target(id: &str) -> Result { - tw_adopt::mcp::target(id).map_err(|e| (StatusCode::NOT_FOUND, e.to_string())) + tw_adopt::mcp::target(id).map_err(|e| { + fail( + StatusCode::NOT_FOUND, + msg!("control.mcp_target_unknown", detail = e => "{detail}"), + ) + }) } fn mcp_err(e: tw_adopt::mcp::McpError) -> Fail { @@ -358,7 +383,7 @@ fn mcp_err(e: tw_adopt::mcp::McpError) -> Fail { tw_adopt::mcp::McpError::NotCopyable { .. } => StatusCode::NOT_IMPLEMENTED, _ => StatusCode::BAD_REQUEST, }; - (code, e.to_string()) + fail(code, msg!("control.mcp_failed", detail = e => "{detail}")) } /// 能写和不能写的分别是哪些。 @@ -386,7 +411,10 @@ fn mcp_plan(s: &ControlState, req: &tw_api::McpOpRequest) -> Result Err((StatusCode::BAD_REQUEST, format!("不支持的操作 {other}"))), + other => Err(fail( + StatusCode::BAD_REQUEST, + msg!("control.unsupported_action", action = other => "`{action}` is not an action we support."), + )), } } diff --git a/crates/tw-control/src/config.rs b/crates/tw-control/src/config.rs index 9ae94eab..4bd7cfc9 100644 --- a/crates/tw-control/src/config.rs +++ b/crates/tw-control/src/config.rs @@ -31,13 +31,15 @@ pub enum ApplyError { #[error("{0}")] Rejected(tw_config::Rejected), /// 校验过了但运行时对象建不起来 —— 同样保持旧的。 - #[error("配置可以解析,但无法应用:{0}")] + #[error("the configuration parses but cannot be applied: {0}")] Build(String), /// patch 指的那个位置有问题。**和 Build 分开**:那句「配置能读但 /// 用不起来」会让人去查配置,而该查的是这次请求写的路径。 #[error("{0}")] BadPath(String), - #[error("配置版本不一致:本次修改基于 {base},当前版本为 {current}。请刷新后重新修改")] + #[error( + "version mismatch: this edit is based on {base}, and the current version is {current}. Refresh and edit again" + )] Stale { base: String, current: String }, /// 按资源改(上游、代理、价目表)时的失败:名字撞了、找不到、值写不进去。 #[error(transparent)] @@ -104,7 +106,9 @@ impl ConfigManager { origin: origin.slug().to_string(), at_ms: now_ms(), }); - tracing::warn!("配置未通过校验,继续使用上一版本:{r}"); + tracing::warn!( + "the configuration did not validate; staying on the previous version: {r}" + ); ApplyError::Rejected(r) })?; self.gateway @@ -115,7 +119,7 @@ impl ConfigManager { // 着的 —— 于是「回到上一版」在列表上就是第二条,不用数。 let _ = tw_config::history::snapshot(&self.path, text, origin); let version = store::version_of(text); - tracing::info!(%version, origin = origin.slug(), "配置已生效"); + tracing::info!(%version, origin = origin.slug(), "the configuration is in effect"); self.bus.emit(tw_api::Event::ConfigReloaded { id: self.bus.next_id(), version: version.clone(), @@ -193,7 +197,7 @@ impl ConfigManager { .iter() .rev() .find(|v| v.version == version || v.version.ends_with(version)) - .ok_or_else(|| ApplyError::BadPath(format!("版本历史中没有 {version}")))?; + .ok_or_else(|| ApplyError::BadPath(format!("the version history has no {version}")))?; let text = tw_config::history::read(target)?; let cur = self.current().ok(); // 回滚也走同一条写入路径,所以它同样会:校验、存历史、防回环。 @@ -229,10 +233,12 @@ pub fn spawn_watcher( tokio::spawn(async move { while rx.recv().await.is_some() { match mgr.reload_from_disk().await { - Ok(Some(v)) => tracing::debug!(version = %v, "配置文件已被修改,已重新加载"), - Ok(None) => tracing::trace!("文件变更由本进程写入,忽略"), + Ok(Some(v)) => { + tracing::debug!(version = %v, "the configuration file changed and was reloaded") + } + Ok(None) => tracing::trace!("this process wrote that change; ignoring it"), // 错误已经在 apply_text 里发过事件了,这里只记一行 - Err(e) => tracing::debug!("重新加载失败:{e}"), + Err(e) => tracing::debug!("the reload failed: {e}"), } } }); @@ -247,10 +253,12 @@ pub async fn path_at( axum::extract::State(s): axum::extract::State, axum::extract::Query(q): axum::extract::Query, ) -> Result, crate::Fail> { - let cur = s - .cfg - .current() - .map_err(|e| crate::fail(axum::http::StatusCode::INTERNAL_SERVER_ERROR, e.to_string()))?; + let cur = s.cfg.current().map_err(|e| { + crate::fail( + axum::http::StatusCode::INTERNAL_SERVER_ERROR, + tw_types::msg!("control.internal", detail = e => "{detail}"), + ) + })?; let path = tw_yaml::path_at(&cur.text, q.offset.min(cur.text.len())); let mut out = tw_api::ConfigAt { section: None, @@ -322,7 +330,7 @@ pub fn resolve_path(text: &str, pointer: &str) -> Result, Str Some(i) => out.push(tw_yaml::Step::Index(i)), None => { return Err(format!( - "{pointer} 中没有名为「{seg}」的项。列表项按 name 查找,也可以使用下标" + "{pointer} has no entry named `{seg}`. List entries are found by name, or by index." )); } } @@ -368,13 +376,15 @@ impl ConfigManager { // **`insert` 而不是 `set`。**配置里绝大多数字段是可选的、 // 默认不写的,只能改「用户碰巧写过」的字段,等于表单模式在 // 他最需要的时候是死的。已经写过的走 `set`,那是它的第一步。 - tw_yaml::insert(&text, &steps, &scalar) - .map_err(|e| ApplyError::BadPath(format!("修改 {path} 失败:{e}")))? + tw_yaml::insert(&text, &steps, &scalar).map_err(|e| { + ApplyError::BadPath(format!("{path} could not be changed: {e}")) + })? } tw_api::PatchOp::Append { path, item } => { let steps = resolve_path(&text, path).map_err(ApplyError::BadPath)?; - tw_yaml::append(&text, &steps, item) - .map_err(|e| ApplyError::BadPath(format!("向 {path} 添加项失败:{e}")))? + tw_yaml::append(&text, &steps, item).map_err(|e| { + ApplyError::BadPath(format!("nothing could be added to {path}: {e}")) + })? } tw_api::PatchOp::Remove { path } => { let steps = resolve_path(&text, path).map_err(ApplyError::BadPath)?; @@ -382,23 +392,25 @@ impl ConfigManager { // **按名字解析、按下标删** —— 名字是用户写的,下标是 // 我们刚刚算出来的,中间没有任何一次用户可见的重排。 let (last, parent) = steps.split_last().ok_or_else(|| { - ApplyError::BadPath(format!("{path} 没有指向列表中的某一项")) + ApplyError::BadPath(format!("{path} does not point at an entry of a list")) })?; let tw_yaml::Step::Index(i) = last else { return Err(ApplyError::BadPath(format!( - "{path} 没有指向列表中的某一项。删除时需要指定具体的项,例如 /clients/codex" + "{path} does not point at an entry of a list. A delete names the entry, as in /clients/codex." ))); }; - tw_yaml::remove(&text, parent, *i) - .map_err(|e| ApplyError::BadPath(format!("删除 {path} 失败:{e}")))? + tw_yaml::remove(&text, parent, *i).map_err(|e| { + ApplyError::BadPath(format!("{path} could not be deleted: {e}")) + })? } tw_api::PatchOp::Clear { path } => { // 要清的列表可能根本还没写进文件 —— 「一个都不给」 // 正是用户第一次碰 `allow` 的那一下。`resolve_path` // 对没写过的键会原样留成 Key,走得通。 let steps = resolve_path(&text, path).map_err(ApplyError::BadPath)?; - tw_yaml::clear_seq(&text, &steps) - .map_err(|e| ApplyError::BadPath(format!("清空 {path} 失败:{e}")))? + tw_yaml::clear_seq(&text, &steps).map_err(|e| { + ApplyError::BadPath(format!("{path} could not be cleared: {e}")) + })? } }; } diff --git a/crates/tw-control/src/diagnostics.rs b/crates/tw-control/src/diagnostics.rs index 6c542165..f5bf8bfb 100644 --- a/crates/tw-control/src/diagnostics.rs +++ b/crates/tw-control/src/diagnostics.rs @@ -32,55 +32,58 @@ fn line(out: &mut String, k: &str, v: impl std::fmt::Display) { pub async fn bundle(State(s): State) -> String { let mut out = String::new(); let cfg = s.config(); - let _ = writeln!(out, "# ThinkWatch 诊断包\n"); + let _ = writeln!(out, "# ThinkWatch diagnostics bundle\n"); let _ = writeln!( out, - "> 本文件中的密钥、地址和请求正文均已脱敏。ThinkWatch 作为网关可以接触到所有 API \ - 密钥,发送本文件之前,请再次检查其中是否含有敏感信息。\n" + "> The keys, addresses and request bodies in this file are redacted. ThinkWatch is a \ + gateway and can see every API key you own, so read this through once more before you \ + send it anywhere.\n" ); // ---- 版本和平台 - let _ = writeln!(out, "## 版本\n\n| | |\n|---|---|"); + let _ = writeln!(out, "## Versions\n\n| | |\n|---|---|"); line(&mut out, "core", env!("CARGO_PKG_VERSION")); - line(&mut out, "控制面 API", tw_api::CONTROL_API_VERSION); - line(&mut out, "配置 schema", cfg.version); + line(&mut out, "Control-plane API", tw_api::CONTROL_API_VERSION); + line(&mut out, "Config schema", cfg.version); { // **生效的那一份,不是内置快照的日期** —— 刷新过之后两者不同,而对账 // 对不上时要问的正是「按哪天的价格算的」 let book = s.gateway.pricing.load(); let t = book.table(); let source = match t.source { - tw_pricing::TableSource::Builtin => "内置", - tw_pricing::TableSource::Fetched => "联网更新", - tw_pricing::TableSource::Empty => "未加载", + tw_pricing::TableSource::Builtin => "built in", + tw_pricing::TableSource::Fetched => "fetched", + tw_pricing::TableSource::Empty => "not loaded", }; line( &mut out, - "默认价目表", - format!("{}({source},{} 个模型)", t.date, t.len()), + "Default price sheet", + format!("{} ({source}, {} models)", t.date, t.len()), ); - line(&mut out, "自定义价目表", cfg.pricing.sheets.len()); + line(&mut out, "Custom price sheets", cfg.pricing.sheets.len()); } - line(&mut out, "平台", std::env::consts::OS); - line(&mut out, "架构", std::env::consts::ARCH); + line(&mut out, "Platform", std::env::consts::OS); + line(&mut out, "Architecture", std::env::consts::ARCH); line( &mut out, - "运行时长", - format!("{} 秒", s.started.elapsed().as_secs()), + "Uptime", + format!("{} s", s.started.elapsed().as_secs()), ); // ---- 监听 - let _ = writeln!(out, "\n## 监听\n\n| | |\n|---|---|"); + let _ = writeln!(out, "\n## Listening\n\n| | |\n|---|---|"); line( &mut out, - "网关", - s.gateway_addr.as_deref().unwrap_or("未启动(安全模式)"), + "Gateway", + s.gateway_addr + .as_deref() + .unwrap_or("not started (safe mode)"), ); - line(&mut out, "绑定", format!("{:?}", cfg.listen.gateway.bind)); - line(&mut out, "端口", cfg.listen.gateway.port); + line(&mut out, "Bind", format!("{:?}", cfg.listen.gateway.bind)); + line(&mut out, "Port", cfg.listen.gateway.port); line( &mut out, - "控制面", + "Control plane", s.config_path() .parent() .map(|p| p.display().to_string()) @@ -90,7 +93,7 @@ pub async fn bundle(State(s): State) -> String { // ---- 上游 let _ = writeln!( out, - "\n## 上游({} 个)\n\n| 名称 | 接口地址 | 协议 | 代理 | 状态 | 模型 | 脱敏 | 信任级别 | 价目表 |\n|---|---|---|---|---|---|---|---|---|", + "\n## Upstreams ({})\n\n| Name | Endpoint | Protocol | Proxy | State | Models | Redaction | Trust | Price sheet |\n|---|---|---|---|---|---|---|---|---|", cfg.providers.len() ); for p in &cfg.providers { @@ -102,54 +105,54 @@ pub async fn bundle(State(s): State) -> String { tw_secret::redact_url(&p.base_url), p.effective_protocol() .map(|x| format!("{x:?}")) - .unwrap_or_else(|| "未识别".into()), + .unwrap_or_else(|| "unrecognized".into()), p.proxy, if p.disabled { - "已停用" + "disabled" } else if s.health().is_available(&p.name) { - "正常" + "ok" } else { - "熔断中" + "circuit open" }, { // 「这家为什么收不到某个模型的请求」多半答在这一栏 let l = s.gateway.models.listing(p); let served = s.gateway.catalog.load().count_for(&p.name); let scope = if p.models_only.is_some() { - ",已限定启用范围" + ", scoped" } else { "" }; match l.source { tw_gateway::models::Source::Discovered => { - format!("{served}(上游提供 {}{scope})", l.models.len()) + format!("{served} (upstream offers {}{scope})", l.models.len()) } tw_gateway::models::Source::Manual => { - format!("{served}(手动清单 {}{scope})", l.models.len()) + format!("{served} (manual list of {}{scope})", l.models.len()) } tw_gateway::models::Source::None => match &l.error { - Some(why) => format!("未知:{why}"), - None => "未知".to_string(), + Some(why) => format!("unknown: {why}"), + None => "unknown".to_string(), }, } }, { let k = p.effective_redact(); if k.is_empty() { - "不脱敏".to_string() + "none".to_string() } else { k.iter().map(|x| x.slug()).collect::>().join(" ") } }, p.effective_trust().label(), - p.pricing.as_deref().unwrap_or("默认价目表"), + p.pricing.as_deref().unwrap_or("the default sheet"), ); } // ---- 客户端条目(**只有名字和脱敏后的 key**) let _ = writeln!( out, - "\n## 网关密钥({} 个)\n\n| 名称 | 密钥 |\n|---|---|", + "\n## Gateway keys ({})\n\n| Name | Key |\n|---|---|", cfg.clients.len() ); for c in &cfg.clients { @@ -157,25 +160,32 @@ pub async fn bundle(State(s): State) -> String { } // ---- 安全三态 - let _ = writeln!(out, "\n## 安全\n\n| | |\n|---|---|"); - line(&mut out, "出站脱敏", cfg.security.redact.label()); - line(&mut out, "工具调用审查", cfg.security.inspect_tools.label()); - line(&mut out, "配置面扫描", cfg.security.scan_configs.label()); + let _ = writeln!(out, "\n## Security\n\n| | |\n|---|---|"); + line(&mut out, "Outbound redaction", cfg.security.redact.label()); + line( + &mut out, + "Tool-call inspection", + cfg.security.inspect_tools.label(), + ); + line(&mut out, "Config scan", cfg.security.scan_configs.label()); // ---- 存储和最近的失败 match &s.store { None => { - let _ = writeln!(out, "\n## 请求记录\n\n未启动,此期间的请求未被记录。"); + let _ = writeln!( + out, + "\n## Request recording\n\nNot running, so nothing from this period was recorded." + ); } Some(store) => { let g = store.lock().await; - let _ = writeln!(out, "\n## 请求记录\n\n| | |\n|---|---|"); - line(&mut out, "磁盘状态", g.level().label()); - line(&mut out, "请求条数", g.db().count().unwrap_or(0)); + let _ = writeln!(out, "\n## Request recording\n\n| | |\n|---|---|"); + line(&mut out, "Disk state", g.level().label()); + line(&mut out, "Requests recorded", g.db().count().unwrap_or(0)); line( &mut out, - "请求体存储大小", - format!("{} 字节", g.blobs().total_bytes()), + "Request bodies on disk", + format!("{} bytes", g.blobs().total_bytes()), ); let recent = g.db().recent(200).unwrap_or_default(); @@ -186,14 +196,17 @@ pub async fn bundle(State(s): State) -> String { .collect(); let _ = writeln!( out, - "\n### 最近失败的请求({} 条,取自最近 {} 条请求)\n", + "\n### Recent failures ({} of the last {} requests)\n", failed.len(), recent.len() ); if failed.is_empty() { - let _ = writeln!(out, "无。"); + let _ = writeln!(out, "None."); } else { - let _ = writeln!(out, "| 时间 | 上游 | 状态 | 错误 |\n|---|---|---|---|"); + let _ = writeln!( + out, + "| Time | Upstream | Status | Error |\n|---|---|---|---|" + ); for r in failed { let _ = writeln!( out, @@ -213,7 +226,7 @@ pub async fn bundle(State(s): State) -> String { } // ---- 配置原文(脱敏后) - let _ = writeln!(out, "\n## config.yaml(已脱敏)\n\n```yaml"); + let _ = writeln!(out, "\n## config.yaml (redacted)\n\n```yaml"); match std::fs::read_to_string(s.config_path()) { // **`mask_body` 一个人不够。**它认的是值的形状,而配置里有一 // 类密钥没有形状:自建中转那把普通样子的 key、OAuth 的 refresh @@ -225,14 +238,14 @@ pub async fn bundle(State(s): State) -> String { let _ = writeln!(out, "{}", tw_secret::mask_config_yaml(&text)); } Err(e) => { - let _ = writeln!(out, "# 无法读取:{e}"); + let _ = writeln!(out, "# could not be read: {e}"); } } let _ = writeln!(out, "```"); let _ = writeln!( out, - "\n---\n\n本文件不包含请求体和响应体,如有需要,请在请求详情中查看。" + "\n---\n\nThis file carries no request or response bodies. They are in the request detail view." ); out } diff --git a/crates/tw-control/src/dryrun.rs b/crates/tw-control/src/dryrun.rs index a81760c8..698b5832 100644 --- a/crates/tw-control/src/dryrun.rs +++ b/crates/tw-control/src/dryrun.rs @@ -47,8 +47,9 @@ fn order_like_the_data_plane( use tw_engine::{Outcome, RequestFacts, RouteError}; use crate::ControlState; +use tw_types::msg; -type Fail = (StatusCode, String); +use crate::{Fail, fail}; fn facts(req: &tw_api::DryRunRequest) -> RequestFacts { RequestFacts { @@ -76,9 +77,12 @@ pub async fn dry_run( let engine = &rt.engine; let f = facts(&req); if !f.client.is_empty() && !cfg.clients.iter().any(|c| c.name == f.client) { - return Err(( + return Err(fail( StatusCode::NOT_FOUND, - format!("未找到名为「{}」的网关密钥", f.client), + msg!( + "control.key_not_found", key = f.client.clone() => + "There is no gateway key named `{key}`." + ), )); } @@ -92,21 +96,37 @@ pub async fn dry_run( .iter() .map(|r| crate::routes::to_rule(r, &cfg)) .collect::, _>>() - .map_err(|e| (StatusCode::BAD_REQUEST, e))?; - engine - .check_rules(&draft) - .map_err(|e| (StatusCode::BAD_REQUEST, e.to_string()))?; + .map_err(|e| { + fail( + StatusCode::BAD_REQUEST, + msg!("control.bad_rule", detail = e => "{detail}"), + ) + })?; + engine.check_rules(&draft).map_err(|e| { + fail( + StatusCode::BAD_REQUEST, + msg!("control.bad_rule", detail = e => "{detail}"), + ) + })?; (d.name.clone(), draft.as_slice()) } else if let Some(name) = req.route.as_deref().filter(|n| !n.is_empty()) { let rules = engine .rules_of(name) - .ok_or_else(|| (StatusCode::NOT_FOUND, format!("未找到名为「{name}」的路由")))?; + .ok_or_else(|| { + fail( + StatusCode::NOT_FOUND, + msg!("control.route_not_found", route = name => "There is no route named `{route}`."), + ) + })?; (name.to_string(), rules) } else if !f.client.is_empty() { let name = engine.route_of(&f.client).to_string(); (name, engine.rules_for_client(&f.client)) } else { - return Err((StatusCode::BAD_REQUEST, "请指定网关密钥或路由".to_string())); + return Err(fail( + StatusCode::BAD_REQUEST, + msg!("control.dryrun_needs_target" => "Name a gateway key or a route."), + )); }; // 每条规则的下场。**先走一遍这个,再问结果** —— 顺序反过来的话, @@ -265,7 +285,12 @@ pub async fn dry_run( Err(RouteError::NoMatch) => { out.outcome = "no_match".into(); } - Err(e) => return Err((StatusCode::BAD_REQUEST, e.to_string())), + Err(e) => { + return Err(fail( + StatusCode::BAD_REQUEST, + msg!("control.route_failed", detail = e => "{detail}"), + )); + } } Ok(Json(out)) } diff --git a/crates/tw-control/src/keys.rs b/crates/tw-control/src/keys.rs index 20f65904..238177ef 100644 --- a/crates/tw-control/src/keys.rs +++ b/crates/tw-control/src/keys.rs @@ -29,6 +29,7 @@ use tw_config::refs; use tw_yaml::Step; use crate::{ApplyError, ControlState, Fail, apply_fail, fail}; +use tw_types::msg; pub fn router() -> axum::Router { axum::Router::new() @@ -43,11 +44,11 @@ pub fn router() -> axum::Router { /// 按用途分段,而密钥这一段之前没人按资源改过 pub(crate) const CLIENTS: edit::Section = edit::Section { path: &["clients"], - what: "网关密钥", + what: "gateway key", }; fn not_found(name: &str) -> ApplyError { - crate::resources::not_found("网关密钥", name) + crate::resources::not_found("gateway key", name) } // ---------------------------------------------------------------- 读 @@ -99,7 +100,12 @@ async fn value( .clients .iter() .find(|c| c.name == name) - .ok_or_else(|| fail(StatusCode::NOT_FOUND, format!("网关密钥「{name}」不存在")))?; + .ok_or_else(|| { + fail( + StatusCode::NOT_FOUND, + msg!("control.key_not_found", key = name.clone() => "There is no gateway key named `{key}`."), + ) + })?; Ok(Json(tw_api::KeyValue { name: c.name.clone(), key: c.key.clone(), @@ -145,7 +151,9 @@ async fn update( // 默认密钥停用 = 把所有手动配置的客户端一起关掉,而它们不在这一页上 if c.disabled && cfg.default_client().map(|d| d.name.as_str()) == Some(name.as_str()) { return Err(ApplyError::InUse( - "默认密钥不能停用。未接管的客户端均使用它,停用将使这些客户端一并失效".into(), + "The default key cannot be disabled. Every client that has not been pointed \ + at the gateway explicitly uses it, and disabling it would break all of them." + .to_string(), )); } let mut out = @@ -180,19 +188,23 @@ async fn delete_key( .ok_or_else(|| not_found(&name))?; if cfg.default_client().map(|d| d.name.as_str()) == Some(name.as_str()) { return Err(ApplyError::InUse( - "默认密钥不能删除。未接管的客户端均使用它,删除后这些客户端将无法连接".into(), + "The default key cannot be deleted. Every client that has not been pointed at \ + the gateway explicitly uses it, and they could not connect without it." + .to_string(), )); } if let Some(label) = &adopted { return Err(ApplyError::InUse(format!( - "{label} 正在被接管,其配置中记录着此密钥。请先取消接管,再删除" + "{label} is pointed at the gateway and has this key in its configuration. Restore \ + it before deleting the key." ))); } let used = refs::client_refs(cfg, &c.name); if !used.is_empty() { return Err(ApplyError::InUse(format!( - "网关密钥「{name}」仍被{}引用,请先解除引用再删除", - used.join("、") + "Gateway key `{name}` is still referenced by {}; drop those references before \ + deleting it.", + used.join(", ") ))); } Ok(edit::remove(text, CLIENTS, &name)?) @@ -216,7 +228,7 @@ async fn set_default( .ok_or_else(|| not_found(&req.name))?; if c.disabled { return Err(ApplyError::InUse(format!( - "网关密钥「{}」已停用,不能设为默认密钥", + "Gateway key `{}` is disabled, so it cannot be the default key.", req.name ))); } @@ -254,7 +266,12 @@ async fn rotate( .clients .iter() .find(|c| c.name == name) - .ok_or_else(|| fail(StatusCode::NOT_FOUND, format!("网关密钥「{name}」不存在")))?; + .ok_or_else(|| { + fail( + StatusCode::NOT_FOUND, + msg!("control.key_not_found", key = name.clone() => "There is no gateway key named `{key}`."), + ) + })?; c.client.clone() }; let version = s @@ -333,8 +350,8 @@ fn to_client( existing: Option<&tw_config::Client>, cfg: &tw_config::Config, ) -> Result { - let name = crate::resources::checked_name(&input.name, "网关密钥") - .map_err(crate::resources::invalid)?; + let name = crate::resources::checked_name(&input.name, "gateway key") + .map_err(|e| crate::resources::invalid(e.text))?; if let Some(r) = input .route .as_deref() @@ -342,7 +359,7 @@ fn to_client( .filter(|r| !r.is_empty()) && cfg.engine().rules_of(r).is_none() { - return Err(crate::resources::not_found("路由", r)); + return Err(crate::resources::not_found("route", r)); } Ok(tw_config::Client { name, diff --git a/crates/tw-control/src/lib.rs b/crates/tw-control/src/lib.rs index 8f302541..4abc3868 100644 --- a/crates/tw-control/src/lib.rs +++ b/crates/tw-control/src/lib.rs @@ -14,6 +14,7 @@ use axum::routing::{get, post}; use axum::{Json, Router}; use futures::stream::Stream; use tokio::sync::broadcast; +use tw_types::{Msg, msg}; pub mod chatgpt; pub mod clients; @@ -202,7 +203,10 @@ fn async_stream_from( // 订阅者跟不上时 broadcast 会丢最老的。**继续收而不是断开** —— // UI 少几行实时日志无所谓,断掉重连才是真的难受。 Err(broadcast::error::RecvError::Lagged(n)) => { - tracing::warn!(dropped = n, "控制面订阅者处理不及,部分事件已丢弃"); + tracing::warn!( + dropped = n, + "a control-plane subscriber fell behind; some events were dropped" + ); continue; } Err(broadcast::error::RecvError::Closed) => return None, @@ -480,7 +484,7 @@ pub(crate) fn model_list(m: tw_gateway::ModelList) -> tw_api::ModelList { async fn l1( State(s): State, Json(req): Json, -) -> Result>, (StatusCode, String)> { +) -> Result>, Fail> { let cfg = s.config(); let mut out = Vec::new(); @@ -489,7 +493,7 @@ async fn l1( cfg.providers .iter() .find(|p| p.name == *n) - .ok_or_else(|| (StatusCode::NOT_FOUND, format!("未找到名为「{n}」的上游")))?, + .ok_or_else(|| no_such_upstream(n))?, ], None => cfg.providers.iter().collect(), }; @@ -575,10 +579,7 @@ async fn cost_buckets( let bucket = q.bucket_ms.unwrap_or(3_600_000).max(1_000); let store = need_store(&s)?; let g = store.lock().await; - let x = g - .db() - .cost_buckets(from, to, bucket) - .map_err(|e| fail(StatusCode::INTERNAL_SERVER_ERROR, e))?; + let x = g.db().cost_buckets(from, to, bucket).map_err(internal)?; Ok(Json(x)) } @@ -600,7 +601,7 @@ async fn cost_buckets_by( let x = g .db() .cost_buckets_by(q.dim, from, to, bucket) - .map_err(|e| fail(StatusCode::INTERNAL_SERVER_ERROR, e))?; + .map_err(internal)?; Ok(Json(x)) } @@ -611,10 +612,7 @@ async fn cost_by( let (from, to) = q.range(); let store = need_store(&s)?; let g = store.lock().await; - let x = g - .db() - .cost_by(q.dim, from, to) - .map_err(|e| fail(StatusCode::INTERNAL_SERVER_ERROR, e))?; + let x = g.db().cost_by(q.dim, from, to).map_err(internal)?; Ok(Json(x)) } @@ -626,10 +624,7 @@ async fn summary( let (from, to) = q.range(); let store = need_store(&s)?; let g = store.lock().await; - let x = g - .db() - .summary(from, to) - .map_err(|e| fail(StatusCode::INTERNAL_SERVER_ERROR, e))?; + let x = g.db().summary(from, to).map_err(internal)?; Ok(Json(tw_api::Summary { requests: x.requests, failed: x.failed, @@ -661,7 +656,7 @@ async fn history( let rows = g .db() .recent(q.limit.unwrap_or(200).min(2000)) - .map_err(|e| fail(StatusCode::INTERNAL_SERVER_ERROR, e))?; + .map_err(internal)?; Ok(Json(rows.into_iter().map(history_row).collect())) } @@ -672,10 +667,7 @@ async fn latency( let (from, to) = q.range(); let store = need_store(&s)?; let g = store.lock().await; - let xs = g - .db() - .latency_by_model(from, to) - .map_err(|e| fail(StatusCode::INTERNAL_SERVER_ERROR, e))?; + let xs = g.db().latency_by_model(from, to).map_err(internal)?; Ok(Json( xs.into_iter() .map(|l| tw_api::LatencyView { @@ -756,7 +748,7 @@ async fn speed_run( total_ms: 0, input_tokens: None, output_tokens: None, - error: Some(format!("无法获取凭据:{e}")), + error: Some(format!("the credential could not be obtained: {e}")), }); continue; } @@ -816,7 +808,7 @@ fn targets<'a>( cfg.providers .iter() .find(|p| &p.name == n) - .ok_or_else(|| (StatusCode::NOT_FOUND, format!("未找到名为「{n}」的上游"))) + .ok_or_else(|| no_such_upstream(n)) }) .collect() } @@ -831,10 +823,7 @@ async fn leaks( let since = now_ms() - (q.days.unwrap_or(7) as i64) * 86_400_000; let store = need_store(&s)?; let g = store.lock().await; - let xs = g - .db() - .leak_summary(since) - .map_err(|e| fail(StatusCode::INTERNAL_SERVER_ERROR, e))?; + let xs = g.db().leak_summary(since).map_err(internal)?; Ok(Json( xs.into_iter() .map(|l| tw_api::LeakGroup { @@ -863,11 +852,12 @@ async fn request_detail( ) -> Result, Fail> { let store = need_store(&s)?; let g = store.lock().await; - let row = g - .db() - .get(id) - .map_err(|e| fail(StatusCode::INTERNAL_SERVER_ERROR, e))? - .ok_or_else(|| (StatusCode::NOT_FOUND, format!("未找到第 {id} 号请求")))?; + let row = g.db().get(id).map_err(internal)?.ok_or_else(|| { + fail( + StatusCode::NOT_FOUND, + msg!("control.request_not_found", id = id => "There is no request {id}."), + ) + })?; let at = row.at_ms; let body = |which| { let raw = g.blobs().get(at, id, which)?; @@ -927,10 +917,7 @@ async fn latency_by_provider( let (from, to) = q.range(); let store = need_store(&s)?; let g = store.lock().await; - let xs = g - .db() - .latency_by_provider(from, to) - .map_err(|e| fail(StatusCode::INTERNAL_SERVER_ERROR, e))?; + let xs = g.db().latency_by_provider(from, to).map_err(internal)?; Ok(Json( xs.into_iter() .map(|l| tw_api::LatencyView { @@ -965,9 +952,13 @@ async fn storage(State(s): State) -> Json { fn need_store(s: &ControlState) -> Result<&Arc>, Fail> { s.store.as_ref().ok_or_else(|| { - ( + fail( StatusCode::SERVICE_UNAVAILABLE, - "请求记录不可用,数据库无法打开或磁盘出错,转发不受影响".to_string(), + msg!( + "control.store_unavailable" => + "Request recording is unavailable: the database could not be opened, or the disk \ + is failing. Forwarding is unaffected." + ), ) }) } @@ -1105,10 +1096,7 @@ struct Limit { /// 当前配置的原文。**文本模式直接显示它。** async fn get_config(State(s): State) -> Result, Fail> { - let c = s - .cfg - .current() - .map_err(|e| fail(StatusCode::INTERNAL_SERVER_ERROR, e))?; + let c = s.cfg.current().map_err(internal)?; Ok(Json(tw_api::ConfigText { path: c.path.display().to_string(), version: c.version(), @@ -1153,8 +1141,7 @@ async fn put_config( async fn config_history( State(s): State, ) -> Result>, Fail> { - let all = tw_config::history::list(s.config_path()) - .map_err(|e| fail(StatusCode::INTERNAL_SERVER_ERROR, e))?; + let all = tw_config::history::list(s.config_path()).map_err(internal)?; let now = s.cfg.current().map(|c| c.version()).unwrap_or_default(); // **新的在前。**用户找的几乎总是最近那几版。 Ok(Json( @@ -1179,10 +1166,37 @@ async fn config_rollback( Ok(Json(tw_api::ConfigWritten { version })) } -pub(crate) type Fail = (StatusCode, String); +/// 控制面的错误响应。 +/// +/// **响应体是一个 JSON 的 [`Msg`],不是一句纯文本。**上一版发的是文本, +/// 于是界面只能把它原样贴出来 —— 一个中英双语的界面里,那句话必然有 +/// 一半人读不懂。现在带着码发出去,界面照码说它自己那句话。 +pub(crate) type Fail = (StatusCode, Json); + +pub(crate) fn fail(code: StatusCode, detail: Msg) -> Fail { + (code, Json(detail)) +} + +/// 内部错误:数据库读不了、序列化不了之类。 +/// +/// **这一类只有一个码。**界面对它们能说的只有同一句话(「这一步没做成」), +/// 真正有用的是 `detail` 里那句原话,而那句话是给看日志的人读的。 +pub(crate) fn internal(e: impl std::fmt::Display) -> Fail { + fail( + StatusCode::INTERNAL_SERVER_ERROR, + msg!("control.internal", detail = e => "{detail}"), + ) +} -pub(crate) fn fail(code: StatusCode, e: impl std::fmt::Display) -> Fail { - (code, e.to_string()) +/// 配置里没有这个名字的上游。 +pub(crate) fn no_such_upstream(name: &str) -> Fail { + fail( + StatusCode::NOT_FOUND, + msg!( + "control.upstream_not_found", upstream = name => + "There is no upstream named `{upstream}`." + ), + ) } /// 把配置改动的失败翻成 HTTP。 @@ -1208,7 +1222,10 @@ pub(crate) fn apply_fail(e: ApplyError) -> Fail { StatusCode::INTERNAL_SERVER_ERROR } }; - (code, e.to_string()) + fail( + code, + msg!("control.config_rejected", detail = e => "{detail}"), + ) } /// 最近这一段有多长。 @@ -1336,9 +1353,12 @@ async fn sessions(State(s): State) -> Json, axum::extract::Path(id): axum::extract::Path, -) -> Result, (StatusCode, String)> { +) -> Result, Fail> { let Some(store) = &s.store else { - return Err((StatusCode::SERVICE_UNAVAILABLE, "请求记录未启动".into())); + return Err(fail( + StatusCode::SERVICE_UNAVAILABLE, + msg!("control.store_off" => "Request recording is not running."), + )); }; let g = store.lock().await; let session = g @@ -1348,7 +1368,12 @@ async fn session_detail( .iter() .find(|x| x.id == id) .map(session_view) - .ok_or_else(|| (StatusCode::NOT_FOUND, format!("未找到会话 {id}")))?; + .ok_or_else(|| { + fail( + StatusCode::NOT_FOUND, + msg!("control.session_not_found", id = id.clone() => "There is no session {id}."), + ) + })?; let turns = g .db() .turns(&id) @@ -1361,7 +1386,7 @@ async fn session_detail( #[derive(Debug, thiserror::Error)] pub enum ControlError { - #[error("无法启动控制面 socket {path}:{source}")] + #[error("the control-plane socket {path} could not be started: {source}")] Bind { path: PathBuf, source: std::io::Error, @@ -1371,7 +1396,7 @@ pub enum ControlError { /// 给的原话是「path must be shorter than SUN_LEN」,看不出上限是多少、 /// 也看不出自己超了多少。 #[error( - "控制面 socket 的路径过长:{len} 字节,系统上限为 {max}。\n{path}\n请将配置放在路径较短的目录中(默认的 ~/.thinkwatch 不受此限制)" + "the control-plane socket path is {len} bytes, over the system limit of {max}.\n{path}\nPut the configuration in a directory with a shorter path (the default ~/.thinkwatch is well within the limit)." )] PathTooLong { path: PathBuf, @@ -1420,14 +1445,14 @@ pub async fn serve_unix(state: ControlState, path: &Path) -> Result<(), ControlE // 0700:只有当前用户能连。这就是不需要 token 的原因。 let _ = std::fs::set_permissions(path, std::fs::Permissions::from_mode(0o700)); } - tracing::info!(path = %path.display(), "控制面已开始监听"); + tracing::info!(path = %path.display(), "the control plane is listening"); let app = router(state); loop { let (stream, _) = match listener.accept().await { Ok(x) => x, Err(e) => { - tracing::warn!("控制面 accept 失败:{e}"); + tracing::warn!("the control plane could not accept a connection: {e}"); continue; } }; @@ -1443,7 +1468,7 @@ pub async fn serve_unix(state: ControlState, path: &Path) -> Result<(), ControlE .serve_connection(io, svc) .await { - tracing::debug!("控制面连接结束:{e}"); + tracing::debug!("a control-plane connection ended: {e}"); } }); } diff --git a/crates/tw-control/src/pricing.rs b/crates/tw-control/src/pricing.rs index 3178a35d..a0fe379c 100644 --- a/crates/tw-control/src/pricing.rs +++ b/crates/tw-control/src/pricing.rs @@ -28,6 +28,7 @@ use tw_yaml::Step; use crate::resources::{checked_name, invalid, mapping, quoted}; use crate::{ApplyError, ControlState, Fail, apply_fail, fail}; +use tw_types::{Msg, msg}; pub fn router() -> axum::Router { axum::Router::new() @@ -77,7 +78,7 @@ pub fn load_table(config: &Path) -> tw_pricing::Table { _ => builtin, }, Err(e) => { - tracing::warn!("内置价目表加载失败:{e}"); + tracing::warn!("the built-in price sheet failed to load: {e}"); saved.unwrap_or_else(tw_pricing::Table::empty) } } @@ -88,7 +89,10 @@ fn read_saved(path: &Path) -> Option { Ok(raw) => raw, Err(e) if e.kind() == std::io::ErrorKind::NotFound => return None, Err(e) => { - tracing::warn!("无法读取 {},改用内置价目表计价:{e}", path.display()); + tracing::warn!( + "{} could not be read; pricing with the built-in sheet: {e}", + path.display() + ); return None; } }; @@ -97,7 +101,10 @@ fn read_saved(path: &Path) -> Option { match tw_pricing::Table::fetched(&raw, local_date(saved_at)) { Ok(t) => Some(t), Err(e) => { - tracing::warn!("无法解析 {},改用内置价目表计价:{e}", path.display()); + tracing::warn!( + "{} could not be parsed; pricing with the built-in sheet: {e}", + path.display() + ); None } } @@ -167,9 +174,9 @@ struct Attempt { pub enum RefreshError { #[error("{0}")] Fetch(String), - #[error("下载的内容不是价格数据集:{0}")] + #[error("what was downloaded is not a price data set: {0}")] Dataset(String), - #[error("价目表无法保存:{0}")] + #[error("the price sheet could not be saved: {0}")] Save(String), } @@ -237,7 +244,7 @@ pub fn spawn(s: ControlState) { && u.due(s.config_path(), SystemTime::now()) && let Err(e) = refresh(&s).await { - tracing::info!("默认价目表更新失败,稍后重试:{e}"); + tracing::info!("the default price sheet could not be updated; retrying later: {e}"); } u.pause(u.schedule.tick).await; } @@ -271,10 +278,15 @@ async fn fetch(http: &reqwest::Client, url: &str) -> Result, RefreshErro .timeout(FETCH_TIMEOUT) .send() .await - .map_err(|e| RefreshError::Fetch(format!("无法连接价格数据源:{}", chain(&e))))?; + .map_err(|e| { + RefreshError::Fetch(format!( + "the price data source could not be reached: {}", + chain(&e) + )) + })?; if !resp.status().is_success() { return Err(RefreshError::Fetch(format!( - "价格数据源返回 HTTP {}", + "the price data source answered HTTP {}", resp.status().as_u16() ))); } @@ -282,11 +294,11 @@ async fn fetch(http: &reqwest::Client, url: &str) -> Result, RefreshErro while let Some(chunk) = resp .chunk() .await - .map_err(|e| RefreshError::Fetch(format!("下载中断:{}", chain(&e))))? + .map_err(|e| RefreshError::Fetch(format!("the download broke off: {}", chain(&e))))? { if raw.len() + chunk.len() > MAX_DATASET { return Err(RefreshError::Dataset(format!( - "文件大小超过 {} MB", + "the file is over {} MB", MAX_DATASET / 1024 / 1024 ))); } @@ -333,7 +345,7 @@ async fn pricing_status(s: &ControlState) -> tw_api::PricingStatus { // **拿不到存储就是 0** —— 观测层起不来时网关照常转发,这一页也该照常打开 let (unpriced_recent, unpriced_models) = match &s.store { Some(st) => st.lock().await.db().unpriced_recent(7).unwrap_or_else(|e| { - tracing::debug!("未能获取无法计价请求的统计:{e}"); + tracing::debug!("the count of unpriced requests could not be read: {e}"); (0, Vec::new()) }), None => (0, Vec::new()), @@ -359,7 +371,10 @@ async fn refresh_now( RefreshError::Save(_) => StatusCode::INTERNAL_SERVER_ERROR, _ => StatusCode::BAD_GATEWAY, }; - fail(code, e) + fail( + code, + msg!("control.pricing_refresh_failed", detail = e => "{detail}"), + ) })?; Ok(Json(tw_api::PricingRefreshed { status: pricing_status(&s).await, @@ -407,13 +422,21 @@ async fn query( if loaded.config().sheet(&name).is_none() { return Err(fail( StatusCode::NOT_FOUND, - format!("未找到名为「{name}」的价目表"), + msg!( + "control.sheet_not_found", sheet = name => + "There is no price sheet named `{sheet}`." + ), )); } (loaded, Some(name)) } tw_api::SheetRef::Draft { sheet } => { - let def = sheet_def(&sheet).map_err(|e| fail(StatusCode::BAD_REQUEST, e))?; + let def = sheet_def(&sheet).map_err(|e| { + fail( + StatusCode::BAD_REQUEST, + msg!("control.bad_price_sheet", detail = e => "{detail}"), + ) + })?; let name = def.name.clone(); (Arc::new(loaded.with_draft(def)), Some(name)) } @@ -488,7 +511,10 @@ async fn sheet( let def = cfg.pricing.sheet(&name).ok_or_else(|| { fail( StatusCode::NOT_FOUND, - format!("未找到名为「{name}」的价目表"), + msg!( + "control.sheet_not_found", sheet = name => + "There is no price sheet named `{sheet}`." + ), ) })?; Ok(Json(tw_api::PriceSheetInput { @@ -509,7 +535,7 @@ async fn create_sheet( let version = s .cfg .transform(req.base_version.as_deref(), Origin::Ui, |text, cfg| { - let def = sheet_def(&req.sheet).map_err(invalid)?; + let def = sheet_def(&req.sheet).map_err(|e| invalid(e.text))?; let mut out = edit::upsert(text, edit::PRICE_SHEETS, None, &mapping(&def)?)?; if let Some(used_by) = &req.used_by { out = assign(&out, cfg, None, &def.name, used_by)?; @@ -529,7 +555,7 @@ async fn update_sheet( let version = s .cfg .transform(req.base_version.as_deref(), Origin::Ui, |text, cfg| { - let def = sheet_def(&req.sheet).map_err(invalid)?; + let def = sheet_def(&req.sheet).map_err(|e| invalid(e.text))?; let mut out = edit::upsert(text, edit::PRICE_SHEETS, Some(&name), &mapping(&def)?)?; if def.name != name { // **和那一张在同一个版本里改** —— 分两次写的话,中间那一版的 @@ -557,7 +583,7 @@ async fn delete_sheet( let users = refs::sheet_users(cfg, &name); if !users.is_empty() { return Err(ApplyError::InUse(format!( - "价目表「{name}」仍被上游{}使用,请先解除关联再删除", + "Price sheet `{name}` is still used by upstream {}; unlink those before deleting it.", quoted(&users) ))); } @@ -584,7 +610,7 @@ fn assign( .find(|u| !cfg.providers.iter().any(|p| &p.name == *u)) { return Err(ApplyError::Edit(edit::EditError::NotFound { - what: "上游", + what: "upstream", name: missing.clone(), })); } @@ -621,9 +647,9 @@ pub(crate) fn sheet_views(cfg: &tw_config::Config) -> Vec Result { +fn sheet_def(input: &tw_api::PriceSheetInput) -> Result { let def = tw_pricing::SheetDef { - name: checked_name(&input.name, "价目表")?, + name: checked_name(&input.name, "price sheet")?, multiplier: input.multiplier, models: input .models @@ -631,7 +657,8 @@ fn sheet_def(input: &tw_api::PriceSheetInput) -> Result "{detail}"))?; Ok(def) } diff --git a/crates/tw-control/src/replay.rs b/crates/tw-control/src/replay.rs index ae625a43..adb3ae98 100644 --- a/crates/tw-control/src/replay.rs +++ b/crates/tw-control/src/replay.rs @@ -26,11 +26,12 @@ use std::time::Instant; use axum::{Json, extract::State, http::StatusCode}; use crate::ControlState; +use tw_types::msg; -type Fail = (StatusCode, String); +use crate::Fail; -fn fail(code: StatusCode, e: impl std::fmt::Display) -> Fail { - (code, e.to_string()) +fn fail(code: StatusCode, detail: tw_types::Msg) -> Fail { + (code, axum::Json(detail)) } /// 找到那条请求,把**原样的**请求体取出来。 @@ -44,15 +45,28 @@ fn stored_body( let row = g .db() .get(id) - .map_err(|e| fail(StatusCode::INTERNAL_SERVER_ERROR, e))? - .ok_or_else(|| (StatusCode::NOT_FOUND, format!("未找到第 {id} 号请求")))?; + .map_err(|e| { + fail( + StatusCode::INTERNAL_SERVER_ERROR, + msg!("control.internal", detail = e => "{detail}"), + ) + })? + .ok_or_else(|| { + fail( + StatusCode::NOT_FOUND, + msg!("control.request_not_found", id = id => "There is no request {id}."), + ) + })?; let raw = g .blobs() .get(row.at_ms, id, tw_store::Which::Request) .ok_or_else(|| { - ( + fail( StatusCode::NOT_FOUND, - format!("第 {id} 号请求的请求体已不存在,可能已被清理"), + msg!( + "control.request_body_gone", id = id => + "The request body of request {id} is gone; it may have been cleaned up." + ), ) })?; let original = g @@ -62,11 +76,12 @@ fn stored_body( if original > raw.len() { // **截断之后的 body 是另一个请求。**拿它跑出来的结果去比对, // 比不跑更糟 —— 用户会以为那是同一条 - return Err(( + return Err(fail( StatusCode::CONFLICT, - format!( - "第 {id} 号请求的请求体有 {original} 字节,仅保存了 {} 字节,无法原样重放", - raw.len() + msg!( + "control.request_body_truncated", id = id, original = original, kept = raw.len() => + "The request body of request {id} was {original} bytes and only {kept} of them \ + were kept, so it cannot be replayed as it was." ), )); } @@ -79,9 +94,9 @@ pub async fn quote( Json(req): Json, ) -> Result, Fail> { let store = s.store.as_ref().ok_or_else(|| { - ( + fail( StatusCode::SERVICE_UNAVAILABLE, - "请求记录未启动".to_string(), + msg!("control.store_off" => "Request recording is not running."), ) })?; let (row, raw) = { @@ -94,9 +109,12 @@ pub async fn quote( .iter() .find(|p| p.name == req.provider) .ok_or_else(|| { - ( + fail( StatusCode::NOT_FOUND, - format!("未找到名为「{}」的上游", req.provider), + msg!( + "control.upstream_not_found", upstream = req.provider.clone() => + "There is no upstream named `{upstream}`." + ), ) })?; @@ -141,9 +159,9 @@ pub async fn run( Json(req): Json, ) -> Result, Fail> { let store = s.store.as_ref().ok_or_else(|| { - ( + fail( StatusCode::SERVICE_UNAVAILABLE, - "请求记录未启动".to_string(), + msg!("control.store_off" => "Request recording is not running."), ) })?; let (row, raw) = { @@ -156,9 +174,12 @@ pub async fn run( .iter() .find(|p| p.name == req.provider) .ok_or_else(|| { - ( + fail( StatusCode::NOT_FOUND, - format!("未找到名为「{}」的上游", req.provider), + msg!( + "control.upstream_not_found", upstream = req.provider.clone() => + "There is no upstream named `{upstream}`." + ), ) })?; // OAuth 要联网换 token。重放不经过数据面,但**凭据这一层 @@ -171,7 +192,10 @@ pub async fn run( .map_err(|e| { fail( StatusCode::BAD_REQUEST, - format!("无法获取上游「{}」的凭据:{e}", provider.name), + msg!( + "control.credentials_failed", upstream = provider.name.clone(), detail = e => + "The credential for upstream `{upstream}` could not be obtained: {detail}" + ), ) })?; @@ -190,11 +214,10 @@ pub async fn run( let mut r = http.post(&url).header("content-type", "application/json"); r = tw_gateway::forward::apply_headers(r, &headers); let resp = r.body(body).send().await.map_err(|e| { + let why = tw_gateway::forward::map_reqwest_error(e); fail( StatusCode::BAD_GATEWAY, - tw_gateway::forward::map_reqwest_error(e) - .message() - .to_string(), + msg!("control.upstream_call_failed", detail = why.message() => "{detail}"), ) })?; @@ -236,17 +259,27 @@ pub async fn fixture( axum::extract::Path(id): axum::extract::Path, ) -> Result { let store = s.store.as_ref().ok_or_else(|| { - ( + fail( StatusCode::SERVICE_UNAVAILABLE, - "请求记录未启动".to_string(), + msg!("control.store_off" => "Request recording is not running."), ) })?; let g = store.lock().await; let row = g .db() .get(id) - .map_err(|e| fail(StatusCode::INTERNAL_SERVER_ERROR, e))? - .ok_or_else(|| (StatusCode::NOT_FOUND, format!("未找到第 {id} 号请求")))?; + .map_err(|e| { + fail( + StatusCode::INTERNAL_SERVER_ERROR, + msg!("control.internal", detail = e => "{detail}"), + ) + })? + .ok_or_else(|| { + fail( + StatusCode::NOT_FOUND, + msg!("control.request_not_found", id = id => "There is no request {id}."), + ) + })?; let body = |which| -> String { g.blobs() .get(row.at_ms, id, which) @@ -256,9 +289,12 @@ pub async fn fixture( let req = body(tw_store::Which::Request); let resp = body(tw_store::Which::Response); if req.is_empty() && resp.is_empty() { - return Err(( + return Err(fail( StatusCode::NOT_FOUND, - format!("第 {id} 号请求的响应体已不存在,可能已被清理"), + msg!( + "control.response_body_gone", id = id => + "The response body of request {id} is gone; it may have been cleaned up." + ), )); } // 截断过的照样能当用例用 —— 它验的是「我们怎么理解这段字节」, @@ -268,11 +304,11 @@ pub async fn fixture( .original_len(row.at_ms, id, tw_store::Which::Response) .is_some_and(|o| o > resp.len()); let note = format!( - "录制自上游「{}」,时间戳 {}{}", + "recorded from upstream `{}` at {}{}", row.provider, row.at_ms, if truncated { - "。响应体在存储时已被截断,仅包含开头部分" + ". The response body was truncated when it was stored, so only its beginning is here." } else { "" } @@ -298,5 +334,10 @@ pub async fn fixture( body: resp, }, ); - serde_yaml_ng::to_string(&f).map_err(|e| fail(StatusCode::INTERNAL_SERVER_ERROR, e)) + serde_yaml_ng::to_string(&f).map_err(|e| { + fail( + StatusCode::INTERNAL_SERVER_ERROR, + msg!("control.internal", detail = e => "{detail}"), + ) + }) } diff --git a/crates/tw-control/src/resources.rs b/crates/tw-control/src/resources.rs index 4668d8a5..0f391571 100644 --- a/crates/tw-control/src/resources.rs +++ b/crates/tw-control/src/resources.rs @@ -24,6 +24,7 @@ use tw_config::history::Origin; use tw_config::refs::{self, ProviderRef}; use crate::{ApplyError, ControlState, Fail, apply_fail, fail}; +use tw_types::{Msg, msg}; pub fn router() -> axum::Router { axum::Router::new() @@ -51,7 +52,7 @@ async fn create_provider( let version = s .cfg .transform(req.base_version.as_deref(), Origin::Ui, |text, _| { - let p = to_provider(&req.provider, None).map_err(invalid)?; + let p = to_provider(&req.provider, None).map_err(|e| invalid(e.text))?; Ok(edit::upsert(text, edit::PROVIDERS, None, &mapping(&p)?)?) }) .await @@ -71,8 +72,8 @@ async fn update_provider( .providers .iter() .find(|p| p.name == name) - .ok_or_else(|| not_found("上游", &name))?; - let p = to_provider(&req.provider, Some(existing)).map_err(invalid)?; + .ok_or_else(|| not_found("upstream", &name))?; + let p = to_provider(&req.provider, Some(existing)).map_err(|e| invalid(e.text))?; let mut out = edit::upsert(text, edit::PROVIDERS, Some(&name), &mapping(&p)?)?; if p.name != name { // **和那一项在同一个版本里改** —— 分两次写的话,中间那一版 @@ -100,7 +101,7 @@ async fn delete_provider( let used = refs::provider_refs(cfg, &name); if !used.is_empty() { return Err(ApplyError::InUse(format!( - "上游「{name}」仍被{}引用,请先解除引用再删除", + "Upstream `{name}` is still referenced by {}; drop those references before deleting it.", describe(&used) ))); } @@ -113,8 +114,10 @@ async fn delete_provider( let endpoint = s.chatgpt.endpoints.revoke.clone(); tokio::spawn(async move { match tw_gateway::chatgpt::revoke(&http, &endpoint, &refresh).await { - Ok(()) => tracing::info!(provider = %name, "已吊销 ChatGPT 登录凭据"), - Err(why) => tracing::warn!(provider = %name, "未能吊销 ChatGPT 登录凭据:{why}"), + Ok(()) => tracing::info!(provider = %name, "the ChatGPT sign-in was revoked"), + Err(why) => { + tracing::warn!(provider = %name, "the ChatGPT sign-in could not be revoked: {why}") + } } }); } @@ -154,7 +157,7 @@ async fn preview_provider( protocol: req .protocol .as_deref() - .map(|v| slug("接口协议", v)) + .map(|v| slug("protocol", v)) .transpose() .map_err(|e| fail(StatusCode::BAD_REQUEST, e))?, ..p.clone() @@ -185,7 +188,7 @@ async fn test_provider( cfg.providers .iter() .find(|p| p.name == n) - .ok_or_else(|| fail(StatusCode::NOT_FOUND, format!("未找到名为「{n}」的上游")))?, + .ok_or_else(|| crate::no_such_upstream(n))?, ), None => None, }; @@ -214,7 +217,8 @@ async fn test_provider( Some(a) => Some(a.to_string()), None => { return Ok(Json(failed( - "OAuth 凭据需要保存后才能检测。如需立即检测,请同时填写 access token" + "An OAuth credential has to be saved before it can be checked. To check it now, \ + fill in an access token as well." .to_string(), ))); } @@ -254,7 +258,7 @@ async fn provider_models( .providers .iter() .find(|p| p.name == name) - .ok_or_else(|| fail(StatusCode::NOT_FOUND, format!("未找到名为「{name}」的上游")))?; + .ok_or_else(|| crate::no_such_upstream(&name))?; Ok(Json(models_view(&s, p, s.gateway.models.listing(p)))) } @@ -265,13 +269,13 @@ async fn refresh_models( ) -> Result, Fail> { let listing = tw_gateway::models::refresh_one(&s.gateway, &name) .await - .ok_or_else(|| fail(StatusCode::NOT_FOUND, format!("未找到名为「{name}」的上游")))?; + .ok_or_else(|| crate::no_such_upstream(&name))?; let cfg = s.config(); let p = cfg .providers .iter() .find(|p| p.name == name) - .ok_or_else(|| fail(StatusCode::NOT_FOUND, format!("未找到名为「{name}」的上游")))?; + .ok_or_else(|| crate::no_such_upstream(&name))?; Ok(Json(models_view(&s, p, listing))) } @@ -320,12 +324,16 @@ fn models_view( fn to_provider( input: &tw_api::ProviderInput, existing: Option<&tw_config::Provider>, -) -> Result { - let name = checked_name(&input.name, "上游")?; +) -> Result { + let name = checked_name(&input.name, "upstream")?; let base_url = match (&input.base_url, existing) { (Some(u), _) => u.trim().to_string(), (None, Some(e)) => e.base_url.clone(), - (None, None) => return Err("接口地址不能为空".to_string()), + (None, None) => { + return Err(msg!( + "control.base_url_empty" => "The endpoint address cannot be empty." + )); + } }; let key = match (&input.key, existing) { (tw_api::SecretChange::Keep, Some(e)) => e.key.clone(), @@ -333,7 +341,7 @@ fn to_provider( (tw_api::SecretChange::Set { value }, _) => { let v = value.trim(); if v.is_empty() { - return Err("API 密钥不能为空".to_string()); + return Err(msg!("control.api_key_empty" => "The API key cannot be empty.")); } Some(tw_config::Secret::new(v)) } @@ -349,11 +357,13 @@ fn to_provider( None => existing .and_then(|e| e.headers.get(&name)) .map(|x| x.value.clone()) - .ok_or_else(|| format!("请求头「{name}」缺少值"))?, + .ok_or_else(|| { + msg!("control.header_no_value", header = name.clone() => "Header `{header}` has no value.") + })?, }; Ok(tw_config::Header { name, value }) }) - .collect::, String>>()?; + .collect::, Msg>>()?; let oauth = match (&input.oauth, existing) { (tw_api::OAuthChange::Keep, Some(e)) => e.oauth.clone(), (tw_api::OAuthChange::Keep, None) | (tw_api::OAuthChange::None, _) => None, @@ -396,7 +406,7 @@ fn to_provider( protocol: input .protocol .as_deref() - .map(|v| slug("接口协议", v)) + .map(|v| slug("protocol", v)) .transpose()?, models: input .models @@ -407,24 +417,24 @@ fn to_provider( billing: input .billing .as_deref() - .map(|v| slug("计费方式", v)) + .map(|v| slug("billing mode", v)) .transpose()?, redact: input .redact .as_ref() .map(|ks| { ks.iter() - .map(|k| slug("脱敏类别", k)) + .map(|k| slug("redaction class", k)) .collect::, _>>() }) .transpose()?, trust: input .trust .as_deref() - .map(|v| slug("信任级别", v)) + .map(|v| slug("trust level", v)) .transpose()?, proxy: input.proxy.trim().to_string(), - on_proxy_fail: slug("代理不可用时的处理", &input.on_proxy_fail)?, + on_proxy_fail: slug("setting for an unusable proxy", &input.on_proxy_fail)?, models_only: input .models_only .as_ref() @@ -434,7 +444,9 @@ fn to_provider( }; // **保存和检测之前就说清楚凭据写法哪儿不对**,而不是等整份配置校验时 // 报一条指着 YAML 的错误 - provider.check_credential().map_err(|e| e.to_string())?; + provider + .check_credential() + .map_err(|e| msg!("control.bad_credential", detail = e => "{detail}"))?; Ok(provider) } @@ -447,7 +459,7 @@ async fn create_proxy( let version = s .cfg .transform(req.base_version.as_deref(), Origin::Ui, |text, _| { - let px = to_proxy(&req.proxy, None).map_err(invalid)?; + let px = to_proxy(&req.proxy, None).map_err(|e| invalid(e.text))?; Ok(edit::upsert(text, edit::PROXIES, None, &mapping(&px)?)?) }) .await @@ -467,8 +479,8 @@ async fn update_proxy( .proxies .iter() .find(|p| p.name == name) - .ok_or_else(|| not_found("代理", &name))?; - let px = to_proxy(&req.proxy, Some(existing)).map_err(invalid)?; + .ok_or_else(|| not_found("proxy", &name))?; + let px = to_proxy(&req.proxy, Some(existing)).map_err(|e| invalid(e.text))?; let mut out = edit::upsert(text, edit::PROXIES, Some(&name), &mapping(&px)?)?; if px.name != name { out = refs::rename_proxy(&out, cfg, &name, &px.name)?; @@ -491,7 +503,7 @@ async fn delete_proxy( let users = refs::proxy_users(cfg, &name); if !users.is_empty() { return Err(ApplyError::InUse(format!( - "代理「{name}」仍被上游{}使用,请先解除关联再删除", + "Proxy `{name}` is still used by upstream {}; unlink those before deleting it.", quoted(&users) ))); } @@ -509,12 +521,12 @@ async fn test_proxy( ) -> Result, Fail> { let cfg = s.config(); let existing = match req.current.as_deref() { - Some(n) => Some( - cfg.proxies - .iter() - .find(|p| p.name == n) - .ok_or_else(|| fail(StatusCode::NOT_FOUND, format!("未找到名为「{n}」的代理")))?, - ), + Some(n) => Some(cfg.proxies.iter().find(|p| p.name == n).ok_or_else(|| { + fail( + StatusCode::NOT_FOUND, + msg!("control.proxy_not_found", proxy = n => "There is no proxy named `{proxy}`."), + ) + })?), None => None, }; let px = to_proxy(&req.proxy, existing).map_err(|e| fail(StatusCode::BAD_REQUEST, e))?; @@ -528,17 +540,23 @@ async fn test_proxy( fn to_proxy( input: &tw_api::ProxyInput, existing: Option<&tw_config::Proxy>, -) -> Result { - let name = checked_name(&input.name, "代理")?; +) -> Result { + let name = checked_name(&input.name, "proxy")?; if matches!(name.as_str(), tw_config::DIRECT | tw_config::SYSTEM) { - return Err(format!("「{name}」是内置选项的名称,请使用其他名称")); + return Err(msg!( + "control.name_is_builtin", name = name => + "`{name}` is the name of a built-in choice; use a different one." + )); } let addr = input.addr.trim().to_string(); let port_ok = addr .rsplit_once(':') .is_some_and(|(h, p)| !h.is_empty() && p.parse::().is_ok_and(|p| p > 0)); if !port_ok { - return Err(format!("代理地址「{addr}」应写成 主机:端口 的形式")); + return Err(msg!( + "control.proxy_addr_form", addr = addr => + "The proxy address `{addr}` is written as host:port." + )); } let auth = match &input.auth { // 没动认证:沿用原来那一份,**原值不经过界面** @@ -547,11 +565,13 @@ fn to_proxy( tw_api::ProxyAuthInput::Set { user, pass } => { let user = user.trim(); if user.is_empty() { - return Err("用户名不能为空".to_string()); + return Err(msg!("control.user_empty" => "The user name cannot be empty.")); } // `${` 在配置里表示「从环境变量读」 if pass.contains("${") { - return Err("密码中不能包含 ${".to_string()); + return Err( + msg!("control.pass_has_expansion" => "A password cannot contain `${{`."), + ); } Some(tw_config::proxy::ProxyAuth { user: user.to_string(), @@ -561,7 +581,7 @@ fn to_proxy( }; Ok(tw_config::Proxy { name, - kind: slug("代理类型", &input.kind)?, + kind: slug("proxy kind", &input.kind)?, addr, auth, }) @@ -569,26 +589,37 @@ fn to_proxy( // ─────────────────────────────────────────────────────────── 共用 -pub(crate) fn checked_name(raw: &str, what: &str) -> Result { +/// 名字得有、而且不能带首尾空白。`what` 是这种资源的英文名(`upstream`、 +/// `proxy`…),进句子也进 `args` —— 界面照码说话时用它挑自己的词。 +pub(crate) fn checked_name(raw: &str, what: &'static str) -> Result { if raw.trim().is_empty() { - return Err(format!("{what}名称不能为空")); + return Err(msg!( + "control.name_empty", kind = what => "An {kind} needs a name." + )); } if raw.trim() != raw { - return Err(format!("{what}名称首尾不能包含空白")); + return Err(msg!( + "control.name_whitespace", kind = what => + "An {kind} name cannot start or end with whitespace." + )); } Ok(raw.to_string()) } /// 界面上的一个选项值 → 配置里的枚举。**和 YAML 里写的词是同一套**。 -fn slug(what: &str, v: &str) -> Result { - serde_yaml_ng::from_value(Value::String(v.to_string())) - .map_err(|_| format!("{what}「{v}」不受支持")) +fn slug(what: &'static str, v: &str) -> Result { + serde_yaml_ng::from_value(Value::String(v.to_string())).map_err(|_| { + msg!( + "control.unsupported_value", kind = what, value = v => + "`{value}` is not a {kind} we support." + ) + }) } pub(crate) fn mapping(v: &T) -> Result { match serde_yaml_ng::to_value(v) { Ok(Value::Mapping(m)) => Ok(m), - Ok(_) => Err(invalid("无法序列化为映射".to_string())), + Ok(_) => Err(invalid("it does not serialize to a mapping".to_string())), Err(e) => Err(invalid(e.to_string())), } } @@ -604,13 +635,13 @@ pub(crate) fn not_found(what: &'static str, name: &str) -> ApplyError { }) } -/// 「「relay-hk」、「relay-sg」」 +/// `` `relay-hk`, `relay-sg` `` pub(crate) fn quoted(names: &[String]) -> String { names .iter() - .map(|n| format!("「{n}」")) + .map(|n| format!("`{n}`")) .collect::>() - .join("、") + .join(", ") } /// 「路由「默认」的规则「长上下文」、策略组「pool」」 @@ -619,12 +650,12 @@ fn describe(refs: &[ProviderRef]) -> String { .map(|r| match r { ProviderRef::RuleTarget { route, rule } | ProviderRef::RuleCondition { route, rule } => { - format!("路由「{route}」的规则「{rule}」") + format!("rule `{rule}` of route `{route}`") } - ProviderRef::Group { group } => format!("策略组「{group}」"), + ProviderRef::Group { group } => format!("group `{group}`"), }) .collect::>() - .join("、") + .join(", ") } pub(crate) fn reference_view(r: &ProviderRef) -> tw_api::ReferenceView { diff --git a/crates/tw-control/src/rotation.rs b/crates/tw-control/src/rotation.rs index 2dacb378..0364354e 100644 --- a/crates/tw-control/src/rotation.rs +++ b/crates/tw-control/src/rotation.rs @@ -53,7 +53,7 @@ pub fn spawn(state: crate::ControlState) { // 换发了 refresh token:成没成都要报(「成功」只报一次,由网关那边管) state.gateway.report_rotation(&r.provider, ok, &detail); } else if !ok { - tracing::warn!(provider = %r.provider, "access token 未能写回 config.yaml:{detail}"); + tracing::warn!(provider = %r.provider, "the access token could not be written back to config.yaml: {detail}"); } } }); @@ -67,7 +67,10 @@ async fn persist(state: &crate::ControlState, r: &Renewed) -> (bool, String) { Ok(version) => { return ( true, - format!("已写回 {}(版本 {version})", state.cfg.path().display()), + format!( + "written back to {} (version {version})", + state.cfg.path().display() + ), ); } Err(why) => { @@ -81,7 +84,9 @@ async fn persist(state: &crate::ControlState, r: &Renewed) -> (bool, String) { ( false, format!( - "{last}。请在重启前处理:检查该文件的权限,以及是否被其他程序占用。问题解决后,下一次轮换会自动写回;如仍无法写回,请重新授权以获取新凭据" + "{last}. Deal with this before a restart: check the file's permissions, and whether \ + another program is holding it. Once that is fixed the next rotation writes itself \ + back; if it still cannot, authorize again for a fresh credential." ), ) } @@ -90,7 +95,7 @@ async fn once(state: &crate::ControlState, r: &Renewed) -> Result Result { for p in probes { // 总称不是一个可以单独设置的类别 if p == "assistant_internal" || !INTENTS.contains(&p.as_str()) { - return Err(invalid(format!("辅助请求类别「{p}」不存在"))); + return Err(invalid(format!( + "there is no auxiliary-request class `{p}`" + ))); } out = edit::set( &out, @@ -241,8 +246,8 @@ fn route_of(client: usize) -> [Step; 3] { } fn to_route(input: &tw_api::RouteInput, cfg: &tw_config::Config) -> Result { - let name = checked_name(&input.name, "路由")?; - reserved(&name, "路由")?; + let name = checked_name(&input.name, "route").map_err(|e| e.text)?; + reserved(&name, "route")?; let mut seen = HashSet::new(); let rules = input .rules @@ -250,7 +255,7 @@ fn to_route(input: &tw_api::RouteInput, cfg: &tw_config::Config) -> Result Result Result { - let name = checked_name(&input.name, "规则")?; - let when = when_from(&input.conditions, cfg).map_err(|e| format!("规则「{name}」:{e}"))?; + let name = checked_name(&input.name, "rule").map_err(|e| e.text)?; + let when = when_from(&input.conditions, cfg).map_err(|e| format!("rule `{name}`: {e}"))?; let to = input .to .as_deref() @@ -269,11 +274,11 @@ pub(crate) fn to_rule(input: &tw_api::RuleInput, cfg: &tw_config::Config) -> Res .filter(|t| !t.is_empty()) .map(str::to_string); let deny = match input.deny.as_deref().map(str::trim) { - Some("") => return Err(format!("规则「{name}」:拒绝原因不能为空")), + Some("") => return Err(format!("rule `{name}`: a denial needs a reason")), other => other.map(str::to_string), }; if to.is_some() && deny.is_some() { - return Err(format!("规则「{name}」不能同时转发和拒绝")); + return Err(format!("rule `{name}` cannot both forward and deny")); } let set = input.set.as_ref().and_then(|s| { let a = SetAction { @@ -295,8 +300,9 @@ pub(crate) fn to_rule(input: &tw_api::RuleInput, cfg: &tw_config::Config) -> Res .redact .iter() .map(|k| { - serde_yaml_ng::from_value(Value::String(k.clone())) - .map_err(|_| format!("规则「{name}」:脱敏类别「{k}」不受支持")) + serde_yaml_ng::from_value(Value::String(k.clone())).map_err(|_| { + format!("rule `{name}`: `{k}` is not a redaction class we support") + }) }) .collect::, _>>()?; let g = Guard { @@ -340,7 +346,7 @@ fn when_from(conds: &[tw_api::ConditionView], cfg: &tw_config::Config) -> Result for c in conds { let field = c.field.as_str(); if !seen.insert(field) { - return Err(format!("条件「{field}」重复")); + return Err(format!("condition `{field}` appears twice")); } let vals: Vec = c .values @@ -351,8 +357,8 @@ fn when_from(conds: &[tw_api::ConditionView], cfg: &tw_config::Config) -> Result let one = || -> Result { match vals.as_slice() { [v] => Ok(v.clone()), - [] => Err(format!("条件「{field}」缺少取值")), - _ => Err(format!("条件「{field}」只能有一个取值")), + [] => Err(format!("condition `{field}` has no value")), + _ => Err(format!("condition `{field}` takes exactly one value")), } }; let flag = || -> Result { @@ -360,16 +366,16 @@ fn when_from(conds: &[tw_api::ConditionView], cfg: &tw_config::Config) -> Result "true" => Ok(true), "false" => Ok(false), v => Err(format!( - "条件「{field}」的取值应为 true 或 false,实际为「{v}」" + "condition `{field}` takes true or false, and got `{v}`" )), } }; let many = |allowed: &dyn Fn(&str) -> bool, what: &str| -> Result { if let Some(bad) = vals.iter().find(|v| !allowed(v.as_str())) { - return Err(format!("{what}「{bad}」不存在")); + return Err(format!("there is no {what} `{bad}`")); } match vals.as_slice() { - [] => Err(format!("条件「{field}」缺少取值")), + [] => Err(format!("condition `{field}` has no value")), [v] => Ok(OneOrMany::One(v.clone())), vs => Ok(OneOrMany::Many(vs.to_vec())), } @@ -379,14 +385,14 @@ fn when_from(conds: &[tw_api::ConditionView], cfg: &tw_config::Config) -> Result "client" => { let k = one()?; if !cfg.clients.iter().any(|c| c.name == k) { - return Err(format!("网关密钥「{k}」不存在")); + return Err(format!("there is no gateway key `{k}`")); } w.client = Some(k); } "dialect" => { let d = one()?; if !DIALECTS.contains(&d.as_str()) { - return Err(format!("客户端格式「{d}」不受支持")); + return Err(format!("`{d}` is not a client format we support")); } w.dialect = Some(d); } @@ -398,14 +404,16 @@ fn when_from(conds: &[tw_api::ConditionView], cfg: &tw_config::Config) -> Result "image" => w.image = Some(flag()?), "thinking" => w.thinking = Some(flag()?), "stream" => w.stream = Some(flag()?), - "intent" => w.intent = Some(many(&|v| INTENTS.contains(&v), "辅助请求类别")?), + "intent" => { + w.intent = Some(many(&|v| INTENTS.contains(&v), "auxiliary-request class")?) + } "provider_would_be" => { w.provider_would_be = Some(many( &|v| cfg.providers.iter().any(|p| p.name == v), - "上游", + "upstream", )?) } - other => return Err(format!("条件「{other}」不受支持")), + other => return Err(format!("`{other}` is not a condition we support")), } } // 比较式写错了(`200k` 少了比较符):保存之前就说 @@ -464,11 +472,11 @@ async fn delete_group( if !used.is_empty() { let by = used .iter() - .map(|r| format!("路由「{}」的规则「{}」", r.route, r.rule)) + .map(|r| format!("rule `{}` of route `{}`", r.rule, r.route)) .collect::>() - .join("、"); + .join(", "); return Err(ApplyError::InUse(format!( - "策略组「{name}」仍被{by}引用,请先解除引用再删除" + "Group `{name}` is still referenced by {by}; drop those references before deleting it." ))); } Ok(edit::remove(text, edit::GROUPS, &name)?) @@ -481,35 +489,38 @@ async fn delete_group( fn builtin_group(name: &str) -> Result<(), ApplyError> { if tw_engine::is_builtin_group(name) { return Err(ApplyError::InUse( - "「全部上游」是内置策略组,成员随上游列表更新,不能修改或删除".to_string(), + "The built-in group of every upstream follows the upstream list; it cannot be edited \ + or deleted." + .to_string(), )); } Ok(()) } fn to_group(input: &tw_api::GroupInput, cfg: &tw_config::Config) -> Result { - let name = checked_name(&input.name, "策略组")?; - reserved(&name, "策略组")?; + let name = checked_name(&input.name, "group").map_err(|e| e.text)?; + reserved(&name, "group")?; if cfg.providers.iter().any(|p| p.name == name) { return Err(format!( - "「{name}」已是上游名称。规则按名称指向上游或策略组,两者不能同名" + "`{name}` is already the name of an upstream. A rule points at an upstream or a group \ + by name, so the two cannot share one." )); } let kind: GroupType = serde_yaml_ng::from_value(Value::String(input.kind.clone())) - .map_err(|_| format!("策略「{}」不受支持", input.kind))?; + .map_err(|_| format!("`{}` is not a strategy we support", input.kind))?; let mut providers = Vec::new(); for p in &input.providers { let p = p.trim(); if !cfg.providers.iter().any(|x| x.name == p) { - return Err(format!("上游「{p}」不存在")); + return Err(format!("there is no upstream `{p}`")); } if providers.iter().any(|x| x == p) { - return Err(format!("上游「{p}」重复")); + return Err(format!("upstream `{p}` appears twice")); } providers.push(p.to_string()); } if providers.is_empty() { - return Err("策略组至少需要一个上游".to_string()); + return Err("a group needs at least one upstream".to_string()); } // 手动选择要有一个优先使用的成员;没选就是第一个。其余策略不写这一项 let selected = match kind { @@ -522,7 +533,7 @@ fn to_group(input: &tw_api::GroupInput, cfg: &tw_config::Config) -> Result tw_api::RuleView { fn reserved(name: &str, what: &str) -> Result<(), String> { if name.starts_with(tw_engine::RESERVED_PREFIX) { return Err(format!( - "{what}名称不能以 {} 开头,这类名称留给内置项", + "a {what} name cannot start with {}; those are reserved for built-ins", tw_engine::RESERVED_PREFIX )); } diff --git a/crates/tw-control/src/scan.rs b/crates/tw-control/src/scan.rs index 5869f4fb..ebea219f 100644 --- a/crates/tw-control/src/scan.rs +++ b/crates/tw-control/src/scan.rs @@ -126,7 +126,7 @@ pub async fn scan( rules_disabled: rules.disabled.len(), // **写坏的那几条要说出来** —— 一条静默失效的安全规则,比没有那条 // 规则更糟,因为用户以为它在 - rules_warning: (!rules.warnings.is_empty()).then(|| rules.warnings.join(";")), + rules_warning: (!rules.warnings.is_empty()).then(|| rules.warnings.join("; ")), projects: p.project, }) } @@ -145,7 +145,10 @@ pub fn spawn_watcher( let home = state.home.clone(); let cfg = state.config(); let dirs = tw_scan::watch::dirs_for(&tw_scan::sources::user_level(&home)); - tracing::debug!(dirs = dirs.len(), "开始监控客户端配置面"); + tracing::debug!( + dirs = dirs.len(), + "watching the clients' configuration surface" + ); let (w, mut rx) = tw_scan::watch::watch(&dirs)?; let bus = state.bus().clone(); @@ -155,7 +158,7 @@ pub fn spawn_watcher( let scan_now = |home: &std::path::Path| { let rules = tw_scan::rules::build(&cfg.security.scan_rules).unwrap_or_else(|_| { tw_scan::rules::build(&tw_config::ScanRules::default()) - .expect("内置规则的正则表达式有效,由测试保证") + .expect("the built-in rules' patterns are valid, and a test keeps them so") }); tw_scan::report::scan(&tw_scan::sources::user_level(home), &rules) }; @@ -178,7 +181,10 @@ pub fn spawn_watcher( if fresh.is_empty() { continue; } - tracing::info!(count = fresh.len(), "客户端配置面出现了新的可疑内容"); + tracing::info!( + count = fresh.len(), + "something new and suspicious appeared in the clients' configuration" + ); let id = bus.next_id(); bus.emit(tw_api::Event::ScanAlert { id, diff --git a/crates/tw-control/tests/adopt.rs b/crates/tw-control/tests/adopt.rs index 907bee3e..261433c3 100644 --- a/crates/tw-control/tests/adopt.rs +++ b/crates/tw-control/tests/adopt.rs @@ -248,7 +248,7 @@ async fn the_diff_never_shows_the_real_key_either() { v.after ); assert!( - v.after.contains("网关密钥"), + v.after.contains("gateway key"), "打码之后得让人看得懂那儿是什么:\n{}", v.after ); @@ -489,7 +489,7 @@ async fn replaying_a_truncated_body_is_refused_rather_than_misleading() { let b = bed_with_store(Some(store)); let (st, body) = post(&b.app, "/replay/quote", r#"{"id":1,"provider":"官方"}"#).await; assert_eq!(st, StatusCode::CONFLICT, "{body}"); - assert!(body.contains("无法原样重放"), "{body}"); + assert!(body.contains("cannot be replayed as it was"), "{body}"); } #[tokio::test] @@ -544,19 +544,22 @@ async fn the_bundle_is_something_a_person_will_actually_read() { // 里面有什么不该有的。所以是 Markdown 不是 JSON dump。 let b = bed(); let (_, text) = get(&b.app, "/diagnostics").await; - assert!(text.starts_with("# ThinkWatch 诊断包"), "{text}"); + assert!( + text.starts_with("# ThinkWatch diagnostics bundle"), + "{text}" + ); for section in [ - "## 版本", - "## 监听", - "## 上游", - "## 安全", - "## 请求记录", + "## Versions", + "## Listening", + "## Upstreams", + "## Security", + "## Request recording", "## config.yaml", ] { assert!(text.contains(section), "少了 {section}:\n{text}"); } // 第一屏就要提醒他自己检查一遍 - assert!(text.contains("发送本文件之前,请再次检查"), "{text}"); + assert!(text.contains("read this through once more"), "{text}"); } #[tokio::test] @@ -565,7 +568,10 @@ async fn the_bundle_says_it_has_no_bodies_because_that_is_the_dangerous_part() { // 他自己打开的,不会被顺手贴进 issue。 let b = bed(); let (_, text) = get(&b.app, "/diagnostics").await; - assert!(text.contains("不包含请求体和响应体"), "{text}"); + assert!( + text.contains("carries no request or response bodies"), + "{text}" + ); } #[tokio::test] @@ -573,8 +579,11 @@ async fn a_bundle_without_observability_says_so_rather_than_showing_zeros() { // 「没有记录」和「记录了零条」是两个结论。 let b = bed(); let (_, text) = get(&b.app, "/diagnostics").await; - assert!(text.contains("未启动,此期间的请求未被记录"), "{text}"); - assert!(!text.contains("请求条数 | 0"), "{text}"); + assert!( + text.contains("Not running, so nothing from this period was recorded"), + "{text}" + ); + assert!(!text.contains("Requests recorded | 0"), "{text}"); } // ────────────────────────────────────────────────── 接管与密钥的关系 @@ -687,5 +696,5 @@ async fn a_key_of_an_adopted_client_cannot_be_deleted_until_it_is_released() { assert_eq!(r.status(), StatusCode::CONFLICT); let body = axum::body::to_bytes(r.into_body(), 1 << 20).await.unwrap(); let text = String::from_utf8_lossy(&body); - assert!(text.contains("取消接管"), "要说清怎样才能删:{text}"); + assert!(text.contains("Restore it"), "要说清怎样才能删:{text}"); } diff --git a/crates/tw-control/tests/chatgpt.rs b/crates/tw-control/tests/chatgpt.rs index 8240e722..6fc280de 100644 --- a/crates/tw-control/tests/chatgpt.rs +++ b/crates/tw-control/tests/chatgpt.rs @@ -445,7 +445,7 @@ async fn a_browser_login_writes_the_account_into_the_config_and_hands_back_to_th let (code, page) = browser(&format!("{}?code=code-1&state={}", s.redirect_uri, s.state)).await; assert_eq!(code, 200); - assert!(page.contains("ChatGPT 登录已完成"), "{page}"); + assert!(page.contains("Signed in to ChatGPT"), "{page}"); assert!( page.contains("thinkwatch://chatgpt/login"), "登录完成后要能回到应用:{page}" @@ -515,7 +515,7 @@ async fn a_callback_that_arrives_twice_exchanges_the_code_once() { // 浏览器有时会把同一个跳转发两次。token 端点慢一点,让两次挤在一起 let url = format!("{}?code=slow&state={}", s.redirect_uri, s.state); let ((_, one), (_, two)) = tokio::join!(browser(&url), browser(&url)); - assert!(one.contains("ChatGPT 登录已完成"), "{one}"); + assert!(one.contains("Signed in to ChatGPT"), "{one}"); assert_eq!(one, two); assert_eq!(b.openai.token_forms.lock().unwrap().len(), 1); } @@ -525,7 +525,7 @@ async fn the_callback_server_stops_once_the_login_is_settled() { let b = bed(|_| String::new()).await; let s = start_login(&b, json!({})).await; let (_, page) = browser(&format!("{}?code=code-1&state={}", s.redirect_uri, s.state)).await; - assert!(page.contains("ChatGPT 登录已完成"), "{page}"); + assert!(page.contains("Signed in to ChatGPT"), "{page}"); let addr = s .redirect_uri .trim_start_matches("http://localhost:") @@ -554,7 +554,7 @@ async fn a_callback_with_the_wrong_state_does_not_end_the_login() { // 别的网页来试探这个端口:不理它,登录还在等 let (_, page) = browser(&format!("{}?code=stolen&state=guess", s.redirect_uri)).await; - assert!(page.contains("登录链接已失效"), "{page}"); + assert!(page.contains("This sign-in link has expired"), "{page}"); let (_, v) = b .call("GET", &format!("/chatgpt/login/{}", s.id), Value::Null) .await; @@ -567,7 +567,10 @@ async fn a_callback_with_the_wrong_state_does_not_end_the_login() { s.redirect_uri, s.state )) .await; - assert!(page.contains("ChatGPT 登录未完成"), "{page}"); + assert!( + page.contains("The ChatGPT sign-in did not finish"), + "{page}" + ); let (_, v) = b .call("GET", &format!("/chatgpt/login/{}", s.id), Value::Null) .await; @@ -589,7 +592,10 @@ async fn a_rejected_code_fails_the_login_and_leaves_the_config_alone() { let before = b.file(); let s = start_login(&b, json!({})).await; let (_, page) = browser(&format!("{}?code=bad&state={}", s.redirect_uri, s.state)).await; - assert!(page.contains("ChatGPT 登录未完成"), "{page}"); + assert!( + page.contains("The ChatGPT sign-in did not finish"), + "{page}" + ); assert!(page.contains("400"), "{page}"); let (_, v) = b .call("GET", &format!("/chatgpt/login/{}", s.id), Value::Null) @@ -614,7 +620,7 @@ async fn logging_in_again_replaces_the_credentials_and_keeps_the_settings() { .await; let s = start_login(&b, json!({"name": "chatgpt"})).await; let (_, page) = browser(&format!("{}?code=code-1&state={}", s.redirect_uri, s.state)).await; - assert!(page.contains("ChatGPT 登录已完成"), "{page}"); + assert!(page.contains("Signed in to ChatGPT"), "{page}"); let p = b.provider("chatgpt").unwrap(); let o = p.oauth.as_ref().unwrap(); assert_eq!( @@ -783,7 +789,7 @@ async fn an_account_without_device_login_is_told_to_use_the_browser() { .await; assert_eq!(st, StatusCode::CONFLICT); assert!( - v.to_string().contains("这台电脑"), + v.to_string().contains("Sign in on this computer"), "要告诉用户改用浏览器登录:{v}" ); assert!(b.provider("chatgpt").is_none()); diff --git a/crates/tw-control/tests/keys.rs b/crates/tw-control/tests/keys.rs index 3b6ca0cd..9bb035ec 100644 --- a/crates/tw-control/tests/keys.rs +++ b/crates/tw-control/tests/keys.rs @@ -197,7 +197,7 @@ async fn the_default_key_can_be_neither_deleted_nor_disabled() { let b = bed(BASE); let (st, v) = call(&b.app, "DELETE", "/keys/default", serde_json::Value::Null).await; assert_eq!(st, StatusCode::CONFLICT, "{v}"); - assert!(v.to_string().contains("默认密钥"), "{v}"); + assert!(v.to_string().contains("default key"), "{v}"); let (st, v) = call( &b.app, diff --git a/crates/tw-control/tests/models.rs b/crates/tw-control/tests/models.rs index 52bd2aba..6c115a52 100644 --- a/crates/tw-control/tests/models.rs +++ b/crates/tw-control/tests/models.rs @@ -289,7 +289,8 @@ async fn disabling_and_scoping_an_upstream_is_written_and_an_empty_scope_is_refu ) .await; assert_eq!(st, StatusCode::BAD_REQUEST, "{v}"); - assert!(v.as_str().unwrap().contains("disabled"), "{v}"); + // 错误体现在是一个 JSON 的 Msg:码给界面,text 给读日志的人 + assert!(v["text"].as_str().unwrap().contains("disabled"), "{v}"); assert_eq!(b.file(), before); } diff --git a/crates/tw-control/tests/pricing.rs b/crates/tw-control/tests/pricing.rs index 3fc1a2f7..0a8b1375 100644 --- a/crates/tw-control/tests/pricing.rs +++ b/crates/tw-control/tests/pricing.rs @@ -168,7 +168,10 @@ async fn a_sheet_is_created_chosen_renamed_and_deleted_only_once_nobody_uses_it( ) .await; assert_eq!(st, StatusCode::CONFLICT, "{body}"); - assert!(body.as_str().unwrap().contains("relay-hk"), "{body}"); + assert!( + body["text"].as_str().unwrap().contains("relay-hk"), + "{body}" + ); // 上游改回默认价目表之后才能删;删完不留空段 let (st, body) = call( @@ -277,7 +280,10 @@ async fn an_upstream_cannot_choose_a_sheet_that_does_not_exist() { ) .await; assert_eq!(st, StatusCode::BAD_REQUEST, "{body}"); - assert!(body.as_str().unwrap().contains("没有这张"), "{body}"); + assert!( + body["text"].as_str().unwrap().contains("没有这张"), + "{body}" + ); assert_eq!(b.file(), BASE); } @@ -298,7 +304,10 @@ async fn a_sheet_with_a_half_written_override_is_refused_with_the_reason() { ) .await; assert_eq!(st, StatusCode::BAD_REQUEST, "{body}"); - assert!(body.as_str().unwrap().contains("长上下文"), "{body}"); + assert!( + body["text"].as_str().unwrap().contains("长上下文"), + "{body}" + ); assert_eq!(b.file(), BASE); } @@ -483,7 +492,7 @@ async fn a_failed_refresh_keeps_the_table_and_reports_why() { let b = bed_with(BASE, Updater::new(url, Schedule::default())); let (st, r) = call(&b.app, "POST", "/pricing/refresh", serde_json::json!(null)).await; assert_eq!(st, StatusCode::BAD_GATEWAY, "{r}"); - assert!(r.as_str().unwrap().contains(says), "{r}"); + assert!(r["text"].as_str().unwrap().contains(says), "{r}"); let (_, status) = call(&b.app, "GET", "/pricing", serde_json::json!(null)).await; assert_eq!(status["source"], "builtin"); assert!(status["error"].as_str().unwrap().contains(says), "{status}"); diff --git a/crates/tw-control/tests/resources.rs b/crates/tw-control/tests/resources.rs index 4bd15675..a234c998 100644 --- a/crates/tw-control/tests/resources.rs +++ b/crates/tw-control/tests/resources.rs @@ -191,7 +191,7 @@ async fn an_upstream_still_in_use_is_not_deleted_and_the_answer_names_who_uses_i let b = bed(BASE); let (st, body) = call(&b.app, "DELETE", "/providers/官方", serde_json::json!({})).await; assert_eq!(st, StatusCode::CONFLICT, "{body}"); - assert!(body.contains("策略组「pool」"), "{body}"); + assert!(body.contains("group `pool`"), "{body}"); assert_eq!(b.parsed().providers.len(), 1); // 没人用的那家删得掉 @@ -389,7 +389,7 @@ async fn renaming_a_proxy_moves_the_upstreams_that_use_it_and_a_used_proxy_is_no let (st, body) = call(&b.app, "DELETE", "/proxies/corp", serde_json::json!({})).await; assert_eq!(st, StatusCode::CONFLICT, "{body}"); - assert!(body.contains("「relay」"), "{body}"); + assert!(body.contains("`relay`"), "{body}"); let (st, body) = call( &b.app, @@ -499,7 +499,7 @@ async fn an_unsaved_oauth_credential_is_not_refreshed_just_to_test_it() { let v = json(&body); assert_eq!(v["ok"], false); assert!( - v["error"].as_str().unwrap().contains("保存后才能检测"), + v["error"].as_str().unwrap().contains("has to be saved"), "{body}" ); } diff --git a/crates/tw-control/tests/routes.rs b/crates/tw-control/tests/routes.rs index e4fc665f..e190a4aa 100644 --- a/crates/tw-control/tests/routes.rs +++ b/crates/tw-control/tests/routes.rs @@ -341,7 +341,7 @@ async fn a_broken_condition_is_refused_before_anything_is_written() { ), ( json!([{ "field": "cache", "values": ["yes"] }]), - "true 或 false", + "takes true or false", ), (json!([{ "field": "colour", "values": ["red"] }]), "colour"), ] { @@ -356,7 +356,7 @@ async fn a_broken_condition_is_refused_before_anything_is_written() { ) .await; assert_eq!(st, StatusCode::BAD_REQUEST, "{v}"); - assert!(v.as_str().unwrap_or_default().contains(says), "{v}"); + assert!(v["text"].as_str().unwrap_or_default().contains(says), "{v}"); } assert_eq!(b.file(), before); } @@ -497,7 +497,10 @@ async fn a_group_forwarded_to_by_a_rule_cannot_be_deleted() { ) .await; assert_eq!(st, StatusCode::CONFLICT, "{v}"); - assert!(v.as_str().unwrap().contains("codex"), "说清是谁在用:{v}"); + assert!( + v["text"].as_str().unwrap().contains("codex"), + "说清是谁在用:{v}" + ); } #[tokio::test] diff --git a/crates/tw-control/tests/sync.rs b/crates/tw-control/tests/sync.rs index 48bf0fb8..f697869d 100644 --- a/crates/tw-control/tests/sync.rs +++ b/crates/tw-control/tests/sync.rs @@ -127,7 +127,7 @@ async fn writing_on_a_stale_version_is_refused_with_both_versions() { .await .unwrap_err(); assert!(matches!(e, ApplyError::Stale { .. }), "{e:?}"); - assert!(e.to_string().contains("刷新"), "{e}"); + assert!(e.to_string().contains("Refresh and edit again"), "{e}"); // 而且真的没写 assert!( std::fs::read_to_string(mgr.path())