From 66cc8b416b972f9196b03ccc074edd2a02fea39d Mon Sep 17 00:00:00 2001 From: fylorn <249551762+fylorn@users.noreply.github.com> Date: Sun, 20 Sep 2026 13:03:36 +0800 Subject: [PATCH] feat(gateway): the gateway speaks English, and its errors carry a code MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Everything the gateway said about a failure was Chinese: the body a Claude Code or Codex session prints when a request is refused, and the `RequestFailed` event the desktop app renders in its traffic table. Neither audience is reliably Chinese-reading, and the app has to say it in whichever of its two languages is in use. `GatewayError` carries a `Msg` instead of a `String`, and so does `Event::RequestFailed`. The sentence that reaches an AI client is `detail.text`, in English, behind the `[ThinkWatch]` prefix it always had; the app reads `detail.code` and says it in its own words. About fifty messages carry a code now, from `gw.auth.key_disabled` to `gw.toolcall.cut`. Two of them stopped being strings in a more useful way: - The failover chain used to be pasted onto the end of the message (`"…(已尝试:a → b)"`). It is `with_attempts`, which leaves the code alone and puts the chain in `args`, so an app can put it where its own sentence wants it. - A stream that breaks mid-flight keeps the code of whatever broke it and only prefixes the English text, instead of becoming a new, codeless "响应流中断:…". The rest of the crate is English too: the `thiserror` messages in `access`, `limits` and `oauth`; the ChatGPT sign-in and token paths; the probe and inference-test results; the tool wall's "(unnamed)" and "(response text)"; the fixture replay's field names; every `tracing` line and every `expect`. `crates/tw-gateway/src` no longer contains a Chinese string literal. `tw-store` writes `message.text` to the history row, so a row's `error` column is English now — the app renders a row from the event, not from that column. Tests that read a message read a code where one exists (`assert_eq!(e.detail.code, "gw.config.proxy_undefined")`), which is shorter and no longer breaks when a sentence is reworded. The no-key test also checks the key never reaches `args`, not only the text. Still Chinese, and not in this change: everything outside `tw-gateway` — `tw-control`, `tw-adopt`, `tw-config`, `tw-scan`, `tw-engine` and the `twcore` CLI. Co-Authored-By: Claude Opus 5 --- bin/twcore/src/main.rs | 2 +- crates/tw-api/src/lib.rs | 4 +- crates/tw-control/src/chatgpt.rs | 4 +- crates/tw-control/src/config.rs | 2 +- crates/tw-control/src/replay.rs | 4 +- crates/tw-control/src/resources.rs | 2 +- crates/tw-gateway/src/access.rs | 8 +- crates/tw-gateway/src/chatgpt.rs | 40 +- crates/tw-gateway/src/ending.rs | 16 +- crates/tw-gateway/src/error.rs | 71 +++- crates/tw-gateway/src/fixture.rs | 26 +- crates/tw-gateway/src/forward.rs | 36 +- crates/tw-gateway/src/l3.rs | 10 +- crates/tw-gateway/src/latency.rs | 8 +- crates/tw-gateway/src/limits.rs | 21 +- crates/tw-gateway/src/live.rs | 2 +- crates/tw-gateway/src/models.rs | 42 +- crates/tw-gateway/src/oauth.rs | 32 +- crates/tw-gateway/src/probe.rs | 10 +- crates/tw-gateway/src/server.rs | 389 ++++++++++++------- crates/tw-gateway/src/toolwall.rs | 16 +- crates/tw-gateway/src/ws.rs | 70 ++-- crates/tw-gateway/tests/endings.rs | 7 +- crates/tw-gateway/tests/headers_and_paths.rs | 2 +- crates/tw-gateway/tests/hotreload.rs | 4 +- crates/tw-gateway/tests/m1_acceptance.rs | 4 +- crates/tw-gateway/tests/models.rs | 9 +- crates/tw-gateway/tests/oauth.rs | 4 +- crates/tw-gateway/tests/passthrough.rs | 13 +- crates/tw-store/src/recorder.rs | 27 +- scripts/smoke.sh | 2 +- 31 files changed, 561 insertions(+), 326 deletions(-) diff --git a/bin/twcore/src/main.rs b/bin/twcore/src/main.rs index 08b27708..09c73f4f 100644 --- a/bin/twcore/src/main.rs +++ b/bin/twcore/src/main.rs @@ -697,7 +697,7 @@ fn cmd_serve(path: &Path, port: Option, safe: bool, parent: Option) -> let config_path = path.to_path_buf(); rt.block_on(async move { let state = tw_gateway::AppState::new(cfg.clone()) - .map_err(|e| anyhow::anyhow!("{}", e.message))?; + .map_err(|e| anyhow::anyhow!("{}", e.message()))?; // 默认价目表:上次联网刷新存下的那份,或者内置的。自定义价目表已经 // 随配置进了价格簿 state.set_price_table(tw_control::pricing::load_table(&config_path)); diff --git a/crates/tw-api/src/lib.rs b/crates/tw-api/src/lib.rs index 87bb67c0..8e5da6d0 100644 --- a/crates/tw-api/src/lib.rs +++ b/crates/tw-api/src/lib.rs @@ -93,7 +93,7 @@ pub enum Event { RequestFailed { id: u64, source: String, - message: String, + message: Msg, /// 失败之前从上游收到了多少字节。**响应头都没到的没有** #[serde(default, skip_serializing_if = "Option::is_none")] bytes: Option, @@ -2790,7 +2790,7 @@ mod tests { Event::RequestFailed { id: 7, source: "upstream".into(), - message: "x".into(), + message: tw_types::msg!("t.x" => "x"), bytes: None, duration_ms: None, usage: None, diff --git a/crates/tw-control/src/chatgpt.rs b/crates/tw-control/src/chatgpt.rs index 2729a532..e30f85c9 100644 --- a/crates/tw-control/src/chatgpt.rs +++ b/crates/tw-control/src/chatgpt.rs @@ -723,7 +723,7 @@ fn client_for(s: &ControlState, name: &str, proxy: &str) -> Result h, - Err(e) => return Ok(Json(failed(e.message))), + Err(e) => return Ok(Json(failed(e.message().to_string()))), }; // OAuth 的 token:新填的那份只能用现成的 access token;沿用原来那份时走网关, // **按原来的名字换** —— 缓存和轮换写回都认名字,而表单里可能刚改了名 diff --git a/crates/tw-gateway/src/access.rs b/crates/tw-gateway/src/access.rs index eec8bb69..5664f652 100644 --- a/crates/tw-gateway/src/access.rs +++ b/crates/tw-gateway/src/access.rs @@ -18,9 +18,11 @@ pub struct Cidr { #[derive(Debug, thiserror::Error, PartialEq)] pub enum CidrError { - #[error("「{0}」不是合法的 CIDR,应写成 192.168.0.0/16 的形式")] + #[error("`{0}` is not a valid CIDR; it is written as 192.168.0.0/16")] Malformed(String), - #[error("「{cidr}」的前缀长度 {prefix} 超出范围(IPv4 最大为 32,IPv6 最大为 128)")] + #[error( + "the prefix length {prefix} in `{cidr}` is out of range (at most 32 for IPv4, 128 for IPv6)" + )] BadPrefix { cidr: String, prefix: u8 }, } @@ -122,7 +124,7 @@ impl AllowList { .map(|s| s.to_string()) .collect::>(), ) - .expect("内置私网段是合法的 CIDR") + .expect("the built-in private ranges are valid CIDRs") } pub fn allows(&self, ip: IpAddr) -> bool { diff --git a/crates/tw-gateway/src/chatgpt.rs b/crates/tw-gateway/src/chatgpt.rs index cf675c97..0e4c9915 100644 --- a/crates/tw-gateway/src/chatgpt.rs +++ b/crates/tw-gateway/src/chatgpt.rs @@ -259,7 +259,7 @@ pub fn redirect_uri(port: u16) -> String { pub fn authorize_url(issuer: &str, redirect_uri: &str, pkce: &Pkce, state: &str) -> String { let mut url = reqwest::Url::parse(&format!("{}/oauth/authorize", issuer.trim_end_matches('/'))) .unwrap_or_else(|_| { - reqwest::Url::parse(&format!("{ISSUER}/oauth/authorize")).expect("常量拼出的地址") + reqwest::Url::parse(&format!("{ISSUER}/oauth/authorize")).expect("built from constants") }); url.query_pairs_mut() .append_pair("response_type", "code") @@ -336,18 +336,27 @@ pub async fn exchange_code( ]) .send() .await - .map_err(|e| format!("无法连接 {}:{e}", tw_secret::redact_url(token_endpoint)))?; + .map_err(|e| { + format!( + "{} could not be reached: {e}", + tw_secret::redact_url(token_endpoint) + ) + })?; let status = resp.status().as_u16(); let text = resp.text().await.unwrap_or_default(); if status >= 400 { - let body = tw_secret::mask_body(&text.replace(code, "<省略>").replace(verifier, "<省略>")); + let body = tw_secret::mask_body( + &text + .replace(code, "") + .replace(verifier, ""), + ); return Err(format!( - "token 端点返回 {status}:{}", + "the token endpoint answered {status}: {}", body.chars().take(400).collect::() )); } - let v: Value = - serde_json::from_str(&text).map_err(|_| "token 端点的响应不是 JSON".to_string())?; + let v: Value = serde_json::from_str(&text) + .map_err(|_| "the token endpoint's response is not JSON".to_string())?; let field = |k: &str| { v.get(k) .and_then(|x| x.as_str()) @@ -355,9 +364,10 @@ pub async fn exchange_code( .map(str::to_string) }; Ok(Tokens { - id_token: field("id_token").ok_or("token 端点的响应中没有 id_token")?, - access: field("access_token").ok_or("token 端点的响应中没有 access_token")?, - refresh: field("refresh_token").ok_or("token 端点的响应中没有 refresh_token")?, + id_token: field("id_token").ok_or("the token endpoint's response has no id_token")?, + access: field("access_token").ok_or("the token endpoint's response has no access_token")?, + refresh: field("refresh_token") + .ok_or("the token endpoint's response has no refresh_token")?, expires_in: v.get("expires_in").and_then(|x| x.as_u64()), }) } @@ -378,11 +388,19 @@ pub async fn revoke( .timeout(std::time::Duration::from_secs(10)) .send() .await - .map_err(|e| format!("无法连接 {}:{e}", tw_secret::redact_url(revoke_endpoint)))?; + .map_err(|e| { + format!( + "{} could not be reached: {e}", + tw_secret::redact_url(revoke_endpoint) + ) + })?; if resp.status().is_success() { Ok(()) } else { - Err(format!("吊销接口返回 {}", resp.status().as_u16())) + Err(format!( + "the revoke endpoint answered {}", + resp.status().as_u16() + )) } } diff --git a/crates/tw-gateway/src/ending.rs b/crates/tw-gateway/src/ending.rs index 1e12f5c8..e8592ad6 100644 --- a/crates/tw-gateway/src/ending.rs +++ b/crates/tw-gateway/src/ending.rs @@ -24,13 +24,14 @@ use std::time::Instant; use crate::bodies::{BodyKind, BodyRecord, BodySender, ResponseTap}; use crate::usage::{Sniffer, Usage}; +use tw_types::{Msg, msg}; /// 一个还欠着结局的请求。 /// /// **到目前为止对响应知道的一切都在它身上**:状态码、收到多少字节、嗅到 /// 多少用量、攒下的响应体。放在一处是因为结局要用的正是这些 —— 不管这个 /// 结局是显式报的,还是在 Drop 里报的。 -#[must_use = "丢弃它等同于报告客户端已断开"] +#[must_use = "dropping it reports that the client disconnected"] pub struct Ending { bus: tw_observe::EventBus, id: u64, @@ -112,7 +113,7 @@ impl Ending { /// `x-thinkwatch-error` 那个词表。 /// /// **断在流中间的失败也带着用量** —— 上游已经为它计了费。 - pub fn failed(mut self, source: &str, message: String) { + pub fn failed(mut self, source: &str, message: Msg) { let usage = self.settle(); self.bus.emit(tw_api::Event::RequestFailed { id: self.id, @@ -169,7 +170,9 @@ impl Drop for Ending { self.bus.emit(tw_api::Event::RequestFailed { id: self.id, source: "internal".to_string(), - message: "请求中断:网关内部错误".to_string(), + message: msg!( + "gw.internal" => "The request was interrupted by an error inside the gateway." + ), bytes: self.received(), duration_ms: Some(self.duration_ms()), usage, @@ -252,7 +255,10 @@ mod tests { let mut rx = bus.subscribe(); let mut e = responding(&bus); e.feed(MESSAGE_START); - e.failed("upstream", "流中断:上游断开了".into()); + e.failed( + "upstream", + msg!("t.broke" => "the stream broke: the upstream disconnected"), + ); let got = drain(&mut rx); assert_eq!(got.len(), 1, "{got:?}"); @@ -280,7 +286,7 @@ mod tests { let bus = tw_observe::EventBus::new(); let mut rx = bus.subscribe(); Ending::new(bus.clone(), 7, Instant::now(), 1_000, None) - .failed("rate_limited", "`up` 限流了".into()); + .failed("rate_limited", msg!("t.limited" => "`up` rate-limited us")); let got = drain(&mut rx); assert!( diff --git a/crates/tw-gateway/src/error.rs b/crates/tw-gateway/src/error.rs index 20de64e3..6c4c2cf3 100644 --- a/crates/tw-gateway/src/error.rs +++ b/crates/tw-gateway/src/error.rs @@ -7,6 +7,9 @@ use axum::http::{HeaderValue, StatusCode}; use axum::response::{IntoResponse, Response}; +use tw_types::Msg; +#[cfg(test)] +use tw_types::msg; /// 失败源。分类的意义在于**用户能看出该去哪儿修**。 #[derive(Debug, Clone, Copy, PartialEq, Eq)] @@ -124,43 +127,65 @@ impl Dialect { #[derive(Debug)] pub struct GatewayError { pub source: Source, - pub message: String, + /// 为什么失败。**发给 AI 客户端的是 `detail.text`**(它们只认字符串), + /// 界面拿 `detail.code` 去自己的词表里找句子。见 [`tw_types::Msg`]。 + pub detail: Msg, /// 用哪种方言的形状回。**认证失败时还不知道方言**(key 就是没认出 /// 来),所以它有默认值而不是必填。 pub dialect: Dialect, } impl GatewayError { - pub fn new(source: Source, message: impl Into) -> Self { + pub fn new(source: Source, detail: Msg) -> Self { Self { source, - message: message.into(), + detail, dialect: Dialect::default(), } } + + /// 给人看的那句话。 + pub fn message(&self) -> &str { + &self.detail.text + } + + /// 在原因后面补上尝试过哪几家上游。 + /// + /// **码不变,补的是同一条消息的细节。**界面照 `code` 说它自己那句话, + /// 需要时从 `attempts` 参数里取这份链路;只读字符串的客户端拿到的是 + /// 补过的 `text`。 + pub fn with_attempts(mut self, attempts: &[String]) -> Self { + if attempts.is_empty() { + return self; + } + let chain = attempts.join(" → "); + self.detail.text = format!("{} (tried: {chain})", self.detail.text); + self.detail.args.insert("attempts".into(), chain); + self + } /// 认出客户端之后补上方言。**忘了调只会退回 Anthropic 形状**, /// 那是个安全的默认,不是一个静默的错误。 pub fn in_dialect(mut self, d: Dialect) -> Self { self.dialect = d; self } - pub fn rate_limited(m: impl Into) -> Self { - Self::new(Source::RateLimited, m) + pub fn rate_limited(detail: Msg) -> Self { + Self::new(Source::RateLimited, detail) } - pub fn denied(m: impl Into) -> Self { - Self::new(Source::Denied, m) + pub fn denied(detail: Msg) -> Self { + Self::new(Source::Denied, detail) } - pub fn auth(m: impl Into) -> Self { - Self::new(Source::Auth, m) + pub fn auth(detail: Msg) -> Self { + Self::new(Source::Auth, detail) } - pub fn config(m: impl Into) -> Self { - Self::new(Source::Config, m) + pub fn config(detail: Msg) -> Self { + Self::new(Source::Config, detail) } - pub fn upstream(m: impl Into) -> Self { - Self::new(Source::Upstream, m) + pub fn upstream(detail: Msg) -> Self { + Self::new(Source::Upstream, detail) } - pub fn request(m: impl Into) -> Self { - Self::new(Source::Request, m) + pub fn request(detail: Msg) -> Self { + Self::new(Source::Request, detail) } } @@ -171,7 +196,7 @@ impl GatewayError { /// 客户端看到的是一个**戛然而止的流**,而截断和「答完了」在 SSE /// 里长得一模一样。 pub fn sse_frame(&self) -> String { - let msg = format!("[ThinkWatch] {}", self.message); + let msg = format!("[ThinkWatch] {}", self.detail.text); let data = match self.dialect { Dialect::Anthropic => serde_json::json!({ "type": "error", @@ -200,7 +225,7 @@ impl IntoResponse for GatewayError { fn into_response(self) -> Response { // `[ThinkWatch]` 前缀不是装饰。没有它,用户看到一个 401 会先去 // 查上游的密钥 —— 而问题在中间这一层。 - let msg = format!("[ThinkWatch] {}", self.message); + let msg = format!("[ThinkWatch] {}", self.detail.text); let body = match self.dialect { Dialect::Anthropic => serde_json::json!({ "type": "error", @@ -253,7 +278,8 @@ mod tests { #[tokio::test] async fn an_auth_failure_is_401_and_says_who_rejected_it() { - let (status, slug, json) = body_of(GatewayError::auth("密钥不对")).await; + let (status, slug, json) = + body_of(GatewayError::auth(msg!("t.auth" => "the key is wrong"))).await; assert_eq!(status, StatusCode::UNAUTHORIZED); assert_eq!(slug, "auth"); // 客户端解析的是 Anthropic 的形状 @@ -270,7 +296,10 @@ mod tests { #[tokio::test] async fn upstream_failures_are_502_not_500() { // 500 会让人怀疑我们;502 说清楚是上游那边。 - let (status, slug, _) = body_of(GatewayError::upstream("连不上")).await; + let (status, slug, _) = body_of(GatewayError::upstream( + msg!("t.upstream" => "cannot connect"), + )) + .await; assert_eq!(status, StatusCode::BAD_GATEWAY); assert_eq!(slug, "upstream"); } @@ -279,12 +308,12 @@ mod tests { async fn each_source_maps_to_its_own_status_and_slug() { for (e, want_status, want_slug) in [ ( - GatewayError::config("x"), + GatewayError::config(msg!("t.x" => "x")), StatusCode::INTERNAL_SERVER_ERROR, "config", ), ( - GatewayError::request("x"), + GatewayError::request(msg!("t.x" => "x")), StatusCode::BAD_REQUEST, "request", ), diff --git a/crates/tw-gateway/src/fixture.rs b/crates/tw-gateway/src/fixture.rs index 180265f1..9a604c49 100644 --- a/crates/tw-gateway/src/fixture.rs +++ b/crates/tw-gateway/src/fixture.rs @@ -240,24 +240,24 @@ pub fn replay(f: &Fixture) -> Vec { ($field:ident, $label:expr) => { if got.$field != f.expect.$field { diffs.push(format!( - "{}:录制时为 {:?},当前为 {:?}", + "{}: {:?} when recorded, {:?} now", $label, f.expect.$field, got.$field )); } }; } cmp!(model, "model"); - cmp!(input_tokens_estimate, "输入 token 估算"); - cmp!(cache, "带缓存"); - cmp!(tools, "带工具"); - cmp!(tool_count, "工具数"); - cmp!(image, "带图片"); - cmp!(thinking, "扩展思考"); - cmp!(stream, "流式"); - cmp!(usage, "用量四项"); + cmp!(input_tokens_estimate, "input token estimate"); + cmp!(cache, "carries cache"); + cmp!(tools, "carries tools"); + cmp!(tool_count, "tool count"); + cmp!(image, "carries images"); + cmp!(thinking, "extended thinking"); + cmp!(stream, "streaming"); + cmp!(usage, "the four usage figures"); cmp!(stop_reason, "stop_reason"); - cmp!(tool_calls, "工具调用"); - cmp!(error_kind, "错误分类"); + cmp!(tool_calls, "tool calls"); + cmp!(error_kind, "error class"); diffs } @@ -332,11 +332,11 @@ mod tests { .replace("\"usage\":{\"output_tokens\":30}", "\"usage\":{}"); let d = replay(&f); assert_eq!(d.len(), 1, "{d:?}"); - assert!(d[0].contains("用量四项"), "{d:?}"); + assert!(d[0].contains("the four usage figures"), "{d:?}"); // **差异要说清「录的是什么、现在是什么」** —— 只说「不一致」 // 的话,看的人还得自己去翻 assert!( - d[0].contains("录制时为") && d[0].contains("当前为"), + d[0].contains("when recorded") && d[0].contains("now"), "{}", d[0] ); diff --git a/crates/tw-gateway/src/forward.rs b/crates/tw-gateway/src/forward.rs index 971be46b..e40960ce 100644 --- a/crates/tw-gateway/src/forward.rs +++ b/crates/tw-gateway/src/forward.rs @@ -9,6 +9,7 @@ use axum::http::{HeaderMap, HeaderName, HeaderValue}; use bytes::Bytes; use crate::error::GatewayError; +use tw_types::msg; /// 这些头是「我们和客户端之间」的,不该转给上游。 /// @@ -147,7 +148,7 @@ pub fn apply_set( } let Ok(mut v) = serde_json::from_slice::(body) else { // 解不开就别动。我们的解析器不认识的东西,上游可能完全认识。 - tracing::warn!("请求体不是 JSON,跳过参数改写"); + tracing::warn!("the request body is not JSON; skipping the parameter rewrites"); return body.clone(); }; let Some(obj) = v.as_object_mut() else { @@ -190,7 +191,9 @@ pub fn apply_set( if th { // 开启思考需要一个 budget,而我们没有一个合理的值可以编。 // **只做「关掉」这一个方向** —— 那是降级场景真正需要的。 - tracing::warn!("set.thinking: true 暂不支持(需要 budget_tokens),已忽略"); + tracing::warn!( + "set.thinking: true is not supported yet (it needs budget_tokens); ignoring it" + ); } else { match client { Dialect::Anthropic => { @@ -217,7 +220,9 @@ pub fn apply_set( Ok(b) => Bytes::from(b), // 序列化不该失败,但真失败了宁可发原文也不要发半个 body Err(e) => { - tracing::error!("改写后的请求体序列化失败,改为发送原始请求体:{e}"); + tracing::error!( + "the rewritten request body could not be serialized; sending the original instead: {e}" + ); body.clone() } } @@ -237,24 +242,29 @@ pub fn gemini_path_with_model(path: &str, model: &str) -> String { pub fn map_reqwest_error(e: reqwest::Error) -> GatewayError { // 分类要能让人看出该去哪儿修。 if e.is_timeout() { - GatewayError::upstream("上游响应超时") + GatewayError::upstream(msg!( + "gw.upstream.timeout" => "The upstream did not answer in time." + )) } else if e.is_connect() { - GatewayError::upstream(format!( - "无法连接上游,请检查接口地址、网络和代理设置:{}", - tw_secret::redact_url(e.url().map(|u| u.as_str()).unwrap_or("")) + GatewayError::upstream(msg!( + "gw.upstream.unreachable", + url = tw_secret::redact_url(e.url().map(|u| u.as_str()).unwrap_or("")) => + "The upstream could not be reached at {url}. Check the endpoint address, the network \ + and the proxy settings." )) } else { - GatewayError::upstream(format!("转发失败:{e}")) + GatewayError::upstream(msg!( + "gw.upstream.forward_failed", detail = e => "Forwarding failed: {detail}" + )) } } /// 请求体原样转发,只在这里做一次大小检查。 pub fn check_body_size(body: &Bytes, max: usize) -> Result<(), GatewayError> { if body.len() > max { - return Err(GatewayError::request(format!( - "请求体大小为 {} 字节,超过上限 {} 字节", - body.len(), - max + return Err(GatewayError::request(msg!( + "gw.request.body_too_large", size = body.len(), max = max => + "The request body is {size} bytes, over the {max}-byte limit." ))); } Ok(()) @@ -478,7 +488,7 @@ mod tests { #[test] fn body_size_limit_reports_both_numbers() { let e = check_body_size(&Bytes::from(vec![0u8; 10]), 5).unwrap_err(); - assert!(e.message.contains("10") && e.message.contains('5')); + assert!(e.message().contains("10") && e.message().contains('5')); assert!(check_body_size(&Bytes::from(vec![0u8; 5]), 5).is_ok()); } } diff --git a/crates/tw-gateway/src/l3.rs b/crates/tw-gateway/src/l3.rs index 94f2b734..1a5d99d4 100644 --- a/crates/tw-gateway/src/l3.rs +++ b/crates/tw-gateway/src/l3.rs @@ -154,7 +154,7 @@ pub async fn run( output_tokens: None, input_tokens: None, error: Some(format!( - "推理测速暂不支持 {} 协议的上游,未发送请求", + "an inference test does not support a {} upstream yet, so nothing was sent", protocol.map(|p| format!("{p:?}")).unwrap_or_default() )), }; @@ -187,7 +187,7 @@ pub async fn run( Ok(r) => r, Err(e) => { return fail( - crate::forward::map_reqwest_error(e).message, + crate::forward::map_reqwest_error(e).message().to_string(), started.elapsed().as_millis() as u64, ); } @@ -197,7 +197,7 @@ pub async fn run( let code = resp.status().as_u16(); let body = resp.text().await.unwrap_or_default(); let short: String = body.chars().take(200).collect(); - return fail(format!("上游返回 {code}:{short}"), connect_ms); + return fail(format!("the upstream answered {code}: {short}"), connect_ms); } // 一边流一边计时。**首个带内容的帧才算首 token** —— `message_start` @@ -344,8 +344,8 @@ mod tests { .await; assert!(!r.ok); let e = r.error.unwrap(); - assert!(e.contains("暂不支持"), "{e}"); - assert!(e.contains("未发送请求"), "{e}"); + assert!(e.contains("does not support"), "{e}"); + assert!(e.contains("nothing was sent"), "{e}"); } #[test] diff --git a/crates/tw-gateway/src/latency.rs b/crates/tw-gateway/src/latency.rs index 124f199a..199a4949 100644 --- a/crates/tw-gateway/src/latency.rs +++ b/crates/tw-gateway/src/latency.rs @@ -44,7 +44,7 @@ impl Latency { /// 记一次。**转发路径上调,所以必须便宜**:一次哈希加一次 push。 pub fn record(&self, provider: &str, ttfb_ms: u32) { - let mut g = self.inner.lock().expect("锁未中毒"); + let mut g = self.inner.lock().expect("lock not poisoned"); let w = g.entry(provider.to_string()).or_default(); if w.len() == WINDOW { w.pop_front(); @@ -57,7 +57,7 @@ impl Latency { /// **只在完全没有真实样本时垫**。真实流量一到就该由它说了算 —— /// L1 量的是建连,不含上游排队和推理,天生偏乐观。 pub fn seed(&self, provider: &str, ttfb_ms: u32) { - let mut g = self.inner.lock().expect("锁未中毒"); + let mut g = self.inner.lock().expect("lock not poisoned"); let w = g.entry(provider.to_string()).or_default(); if w.is_empty() { // 垫满 `MIN_SAMPLES` 才算数 —— 否则它自己也是「样本不够」 @@ -69,7 +69,7 @@ impl Latency { /// 这家的典型 TTFB。`None` = 样本不够,**不是「很快」**。 pub fn typical(&self, provider: &str) -> Option { - let g = self.inner.lock().expect("锁未中毒"); + let g = self.inner.lock().expect("lock not poisoned"); let w = g.get(provider)?; if w.len() < MIN_SAMPLES { return None; @@ -81,7 +81,7 @@ impl Latency { /// 一次取一批 —— 排序时要用到,逐个取会连着锁好几次。 pub fn snapshot(&self, names: &[String]) -> HashMap { - let g = self.inner.lock().expect("锁未中毒"); + let g = self.inner.lock().expect("lock not poisoned"); let mut out = HashMap::new(); for n in names { if let Some(w) = g.get(n) diff --git a/crates/tw-gateway/src/limits.rs b/crates/tw-gateway/src/limits.rs index b7623a0b..494ecd88 100644 --- a/crates/tw-gateway/src/limits.rs +++ b/crates/tw-gateway/src/limits.rs @@ -21,9 +21,13 @@ pub use tw_types::Limits; #[derive(Debug, thiserror::Error)] pub enum LimitError { - #[error("排队超过 {0:?} 仍未获得处理。上游可能均无响应,或并发上限设置过低")] + #[error( + "still queued after {0:?}. Every upstream may be unresponsive, or the concurrency limit may be too low" + )] Timeout(Duration), - #[error("等待队列已满({0} 个),请求量异常,请检查是否有脚本在大量发送请求")] + #[error( + "the wait queue is full ({0} entries). The request volume is unusual — check whether a script is sending in bulk" + )] QueueFull(usize), } @@ -109,7 +113,11 @@ impl Gate { let acquire_all = async { let mut permits = Vec::with_capacity(sems.len()); for s in sems { - permits.push(s.acquire_owned().await.expect("信号量不会被关闭")); + permits.push( + s.acquire_owned() + .await + .expect("the semaphore is never closed"), + ); } permits }; @@ -181,7 +189,7 @@ mod tests { let _held = g.acquire("p", "c", None).await.unwrap(); let e = g.acquire("p", "c", None).await.unwrap_err(); assert!(matches!(e, LimitError::Timeout(_))); - assert!(e.to_string().contains("并发上限"), "{e}"); + assert!(e.to_string().contains("concurrency limit"), "{e}"); } #[tokio::test] @@ -200,7 +208,10 @@ mod tests { tokio::time::sleep(Duration::from_millis(80)).await; let e = g.acquire("p", "c", None).await.unwrap_err(); assert!(matches!(e, LimitError::QueueFull(2)), "{e:?}"); - assert!(e.to_string().contains("脚本"), "错误要指向真正的原因:{e}"); + assert!( + e.to_string().contains("a script is sending in bulk"), + "错误要指向真正的原因:{e}" + ); for w in waiters { w.abort(); } diff --git a/crates/tw-gateway/src/live.rs b/crates/tw-gateway/src/live.rs index 8f026933..4e96a427 100644 --- a/crates/tw-gateway/src/live.rs +++ b/crates/tw-gateway/src/live.rs @@ -23,7 +23,7 @@ pub struct Live(Arc); /// 一个请求的通行证。**Drop 时自动减一** —— 手工减的话,迟早有一条错误 /// 路径会漏掉,而漏掉的表现是这个数只增不减,等它归零的人永远等不到。 -#[must_use = "丢弃通行证等同于请求已结束"] +#[must_use = "dropping the permit says the request has ended"] pub struct Pass(Arc); impl Live { diff --git a/crates/tw-gateway/src/models.rs b/crates/tw-gateway/src/models.rs index 0cd22745..69410c04 100644 --- a/crates/tw-gateway/src/models.rs +++ b/crates/tw-gateway/src/models.rs @@ -27,6 +27,7 @@ use std::time::Duration; use crate::probe::ModelList; use crate::server::{AppState, Runtime, now_ms}; +use tw_types::msg; /// 多久向每个上游重新问一次。 const REFRESH_EVERY: Duration = Duration::from_secs(24 * 3600); @@ -372,21 +373,23 @@ async fn ask(state: &AppState, rt: &Runtime, p: &tw_config::Provider) -> Answer let http = rt.clients.get(&p.name).unwrap_or(&state.http); let headers = match state.headers_for(p, http, None).await { Ok(h) => h, - Err(e) => return Answer::Failed(format!("无法获取凭据:{e}")), + Err(e) => return Answer::Failed(format!("the credential could not be obtained: {e}")), }; let r = crate::probe::probe(http, &p.base_url, &headers, p.effective_protocol()).await; if !r.ok { - return Answer::Failed(r.error.unwrap_or_else(|| "检测失败".to_string())); + return Answer::Failed(r.error.unwrap_or_else(|| "the check failed".to_string())); } match r.models { ModelList::Listed { models } => Answer::Listed(models), - ModelList::NotImplemented { status } => { - Answer::NoList(format!("上游未提供模型列表接口(HTTP {status})")) + ModelList::NotImplemented { status } => Answer::NoList(format!( + "the upstream has no model-list endpoint (HTTP {status})" + )), + ModelList::Unrecognized { .. } => Answer::NoList( + "the model list the upstream returned is in an unrecognized format".to_string(), + ), + ModelList::Empty => { + Answer::NoList("the model list the upstream returned is empty".to_string()) } - ModelList::Unrecognized { .. } => { - Answer::NoList("上游返回的模型列表格式无法识别".to_string()) - } - ModelList::Empty => Answer::NoList("上游返回的模型列表为空".to_string()), } } @@ -447,10 +450,10 @@ async fn finish(state: &AppState, asking: Vec) { }; match &answer { Answer::Listed(models) => { - tracing::debug!(provider = %a.name, models = models.len(), "已获取模型列表") + tracing::debug!(provider = %a.name, models = models.len(), "fetched the model list") } Answer::NoList(why) | Answer::Failed(why) => { - tracing::info!(provider = %a.name, "未能获取模型列表:{why}") + tracing::info!(provider = %a.name, "the model list could not be fetched: {why}") } Answer::Pending => {} } @@ -546,11 +549,12 @@ impl Skip { Skip::NotOffered => "not_offered", } } + /// 进给客户端的那句话里。**界面不用它** —— 界面按 `slug` 自己说。 pub fn label(&self) -> &'static str { match self { - Skip::Disabled => "已停用", - Skip::OutOfScope => "不在启用范围内", - Skip::NotOffered => "未提供此模型", + Skip::Disabled => "disabled", + Skip::OutOfScope => "out of scope", + Skip::NotOffered => "does not offer this model", } } } @@ -570,14 +574,20 @@ impl Serving { .iter() .map(|(p, s)| format!("{p} {}", s.label())) .collect::>() - .join(";"); + .join("; "); // 全是停用:请求没问题,是配置里能用的上游都关掉了 if self.skipped.iter().all(|(_, s)| *s == Skip::Disabled) { - crate::GatewayError::config(format!("路由选中的上游均已停用:{why}")) + crate::GatewayError::config(msg!( + "gw.route.all_selected_disabled", detail = why => + "Every upstream the route selected is disabled: {detail}" + )) } else { crate::GatewayError::new( crate::error::Source::Request, - format!("没有可用的上游提供模型 {model}:{why}"), + msg!( + "gw.model.no_upstream_available", model = model, detail = why => + "No upstream is available to serve model {model}: {detail}" + ), ) } } diff --git a/crates/tw-gateway/src/oauth.rs b/crates/tw-gateway/src/oauth.rs index f96be68c..12acb4d8 100644 --- a/crates/tw-gateway/src/oauth.rs +++ b/crates/tw-gateway/src/oauth.rs @@ -52,16 +52,16 @@ const EXPIRED_BACKOFF: Duration = Duration::from_secs(24 * 3600); #[derive(Debug, thiserror::Error)] pub enum OauthError { - #[error("刷新 token 时无法连接 {endpoint}:{why}")] + #[error("{endpoint} could not be reached while refreshing the token: {why}")] Http { endpoint: String, why: String }, - #[error("token 端点返回 {status}:{body}")] + #[error("the token endpoint answered {status}: {body}")] Status { status: u16, body: String }, - #[error("token 端点的响应中没有 access_token")] + #[error("the token endpoint's response has no access_token")] NoToken, - #[error("上次刷新 token 失败({why}),将在 {secs} 秒后重试")] + #[error("the last token refresh failed ({why}); retrying in {secs} s")] Backoff { why: String, secs: u64 }, /// refresh token 已经作废。**重试没有用**,要重新登录或换一个 refresh token - #[error("OAuth 凭据已失效,需要重新登录或更换 refresh token({why})")] + #[error("the OAuth credential has expired; sign in again or replace the refresh token ({why})")] Expired { why: String }, } @@ -237,7 +237,7 @@ impl Cache { let flight = self.flight(provider); let _one = flight.lock().await; { - let mut g = self.inner.lock().expect("锁未中毒"); + let mut g = self.inner.lock().expect("lock not poisoned"); if let Some(live) = g.get_mut(provider).filter(|l| l.usable_for(cfg)) { let renewed = !live.access.is_empty() && live @@ -258,7 +258,7 @@ impl Cache { /// 这家最近一次刷新失败的原因,和是不是要重新登录。没失败过、或者已经恢复,是 `None`。 pub fn failure(&self, provider: &str, cfg: &OAuth) -> Option<(String, bool)> { - let g = self.inner.lock().expect("锁未中毒"); + let g = self.inner.lock().expect("lock not poisoned"); let f = g .get(provider) .filter(|l| l.usable_for(cfg))? @@ -270,7 +270,7 @@ impl Cache { fn flight(&self, provider: &str) -> Arc> { self.flights .lock() - .expect("锁未中毒") + .expect("lock not poisoned") .entry(provider.to_string()) .or_default() .clone() @@ -278,7 +278,7 @@ impl Cache { /// 手里能直接用的 token。`Err` 是还在退避。 fn cached(&self, provider: &str, cfg: &OAuth) -> Result, OauthError> { - let mut g = self.inner.lock().expect("锁未中毒"); + let mut g = self.inner.lock().expect("lock not poisoned"); if let Some(live) = g.get(provider).filter(|l| l.usable_for(cfg)) { if let Some(f) = &live.failed && Instant::now() < f.until @@ -328,7 +328,7 @@ impl Cache { ) -> Result<(String, Option), OauthError> { // 用手里那个 refresh(可能是服务器换过的),没有就用配置里的 let refresh = { - let g = self.inner.lock().expect("锁未中毒"); + let g = self.inner.lock().expect("lock not poisoned"); g.get(provider) // 认不出来 = 用户改了配置,缓存里那个(哪怕是服务器 // 换发的)一律不算,用配置里的重新开始 @@ -346,7 +346,7 @@ impl Cache { other => (other.to_string(), false), }; let until = Instant::now() + if expired { EXPIRED_BACKOFF } else { BACKOFF }; - let mut g = self.inner.lock().expect("锁未中毒"); + let mut g = self.inner.lock().expect("lock not poisoned"); let entry = g.entry(provider.to_string()).or_insert_with(|| Live { fp: fingerprint(cfg), access: String::new(), @@ -373,7 +373,7 @@ impl Cache { // **每一次轮换都要往外送,不能在这儿去重。**新值要写回 // config.yaml,而漏掉一次写回就等于让配置文件从那一刻 // 起是坏的。「同一句话别说第二遍」是报事件那一层的事,不是这一层的。 - let mut g = self.inner.lock().expect("锁未中毒"); + let mut g = self.inner.lock().expect("lock not poisoned"); g.insert( provider.to_string(), Live { @@ -466,11 +466,11 @@ fn scrub_sent(text: &str, sent: &[&str]) -> String { // 太短的不抹:一个三个字母的 client_secret 会把正文里无关的地方也 // 换掉,那时错误消息本身变得不可读,比漏一点更妨碍排查 for v in sent.iter().filter(|v| v.len() >= 6) { - out = out.replace(*v, "<省略>"); + out = out.replace(*v, ""); // 表单是百分号编码之后发出去的,对方回显的很可能是编码后的样子 let enc = form_encode(v); if enc != *v { - out = out.replace(&enc, "<省略>"); + out = out.replace(&enc, ""); } } out @@ -533,7 +533,7 @@ async fn exchange(cfg: &OAuth, refresh: &str, http: &reqwest::Client) -> Result< let body = masked.chars().take(400).collect::(); if is_expired(status, &text) { return Err(OauthError::Expired { - why: format!("token 端点返回 {status}:{body}"), + why: format!("the token endpoint answered {status}: {body}"), }); } return Err(OauthError::Status { status, body }); @@ -632,7 +632,7 @@ mod tests { let second = rt.block_on(c.token("p", &o, &http)).unwrap_err(); // 第二次直接被退避挡住,没有再去连 assert!(matches!(second, OauthError::Backoff { .. }), "{second}"); - assert!(second.to_string().contains("秒后重试"), "{second}"); + assert!(second.to_string().contains("retrying in"), "{second}"); } #[test] diff --git a/crates/tw-gateway/src/probe.rs b/crates/tw-gateway/src/probe.rs index 683cfd16..b227385d 100644 --- a/crates/tw-gateway/src/probe.rs +++ b/crates/tw-gateway/src/probe.rs @@ -103,13 +103,13 @@ pub async fn probe( let ms = started.elapsed().as_millis() as u64; let msg = if e.is_timeout() { format!( - "{PROBE_TIMEOUT:?} 内没有响应。请检查接口地址,或确认该上游是否需要经代理访问" + "no answer within {PROBE_TIMEOUT:?}. Check the endpoint address, or whether this upstream has to be reached through a proxy" ) } else if e.is_connect() { - "无法连接。请检查接口地址拼写和网络;如果该上游需要经代理访问,请先配置代理" + "could not connect. Check the spelling of the endpoint address and the network; if this upstream has to be reached through a proxy, configure the proxy first" .to_string() } else { - format!("请求失败:{e}") + format!("the request failed: {e}") }; return ProbeResult::fail(ms, proto_name, msg); } @@ -125,7 +125,7 @@ pub async fn probe( ms, proto_name, format!( - "上游拒绝了该密钥(HTTP {})。请检查密钥是否包含多余的空格,以及是否属于该上游", + "the upstream rejected this key (HTTP {}). Check the key for stray whitespace, and that it belongs to this upstream", status.as_u16() ), ); @@ -138,7 +138,7 @@ pub async fn probe( // 拿到了 2xx 但读 body 失败 —— 归到「没认出」而不是「不提供」, // 因为它确实有这个接口。 Err(e) => ModelList::Unrecognized { - sample: format!("读取响应体失败:{e}"), + sample: format!("the response body could not be read: {e}"), }, } } else { diff --git a/crates/tw-gateway/src/server.rs b/crates/tw-gateway/src/server.rs index 9b5766e7..c45046fb 100644 --- a/crates/tw-gateway/src/server.rs +++ b/crates/tw-gateway/src/server.rs @@ -15,6 +15,7 @@ use crate::auth::key_eq; use crate::error::GatewayError; use crate::forward; use crate::health::Health; +use tw_types::msg; /// 256 MiB。大到能装下几张 4K 图的 base64(膨胀 33%),小到失控的 /// 客户端打不爆内存。 @@ -58,20 +59,18 @@ pub fn client_for_provider( } name => { let proxy = cfg.proxies.iter().find(|x| x.name == name).ok_or_else(|| { - // 用 concat! 而不是反斜杠续行:续行后面那行的缩进会 - // 原样进字符串,而错误信息里冒出一串空格没人会注意到。 - // 今天已经犯过一次了(还没有配置任何上游那条)。 - GatewayError::config(format!( - concat!( - "上游「{}」使用的代理「{}」未在 proxies 中定义,", - "内置选项只有 direct 和 system" - ), - p.name, name + GatewayError::config(msg!( + "gw.config.proxy_undefined", upstream = p.name.clone(), proxy = name => + "Upstream `{upstream}` uses proxy `{proxy}`, which is not defined under \ + `proxies`; the only built-in choices are direct and system." + )) + })?; + let url = proxy.url().map_err(|e| { + GatewayError::config(msg!( + "gw.config.proxy_password", proxy = name, detail = e => + "The password for proxy `{proxy}` could not be read: {detail}" )) })?; - let url = proxy - .url() - .map_err(|e| GatewayError::config(format!("无法读取代理「{name}」的密码:{e}")))?; match reqwest::Proxy::all(&url) { Ok(px) => b = b.proxy(px), Err(e) => { @@ -81,21 +80,24 @@ pub fn client_for_provider( if p.on_proxy_fail == tw_config::OnProxyFail::Direct { tracing::warn!( provider = %p.name, proxy = %name, - "代理不可用,按 on_proxy_fail 设置改为直连:{e}" + "proxy unusable, going direct as on_proxy_fail says: {e}" ); b = b.no_proxy(); } else { - return Err(GatewayError::config(format!( - "上游「{}」的代理「{name}」不可用:{e}", - p.name + return Err(GatewayError::config(msg!( + "gw.config.proxy_unusable", upstream = p.name.clone(), proxy = name, detail = e => + "Proxy `{proxy}`, used by upstream `{upstream}`, is unusable: {detail}" ))); } } } } } - b.build() - .map_err(|e| GatewayError::config(format!("无法创建 HTTP 客户端:{e}"))) + b.build().map_err(|e| { + GatewayError::config(msg!( + "gw.config.http_client", detail = e => "The HTTP client could not be created: {detail}" + )) + }) } /// 一次配置换入时**整块换掉**的那部分。 @@ -149,15 +151,20 @@ impl Runtime { }; } let allow = crate::access::AllowList::parse(&config.listen.gateway.effective_allow_from()) - .map_err(|e| GatewayError::config(format!("listen.gateway.allow_from:{e}")))?; + .map_err(|e| { + GatewayError::config(msg!( + "gw.config.allow_from", detail = e => "listen.gateway.allow_from: {detail}" + )) + })?; // 规则集编译一次,跟着运行时一起换 —— 它现在住在 config.yaml 的 // `security.scan_rules` 里,所以「改了规则」和「改了别的配置」 // 走同一条热重载路径。 // // **用户写坏的那几条被跳过,其余照常工作**:一个因为配置写错就 // 整个不工作的安全功能等于没有。但跳过要大声说出来。 - let rules = tw_scan::rules::build(&config.security.scan_rules) - .map_err(|e| GatewayError::config(e.to_string()))?; + let rules = tw_scan::rules::build(&config.security.scan_rules).map_err(|e| { + GatewayError::config(msg!("gw.config.scan_rules", detail = e => "{detail}")) + })?; for w in &rules.warnings { tracing::warn!("{w}"); } @@ -295,9 +302,11 @@ const PROXY_RECHECK: std::time::Duration = std::time::Duration::from_secs(30); impl AppState { pub fn new(config: tw_config::Config) -> Result { - let http = base_client_builder() - .build() - .map_err(|e| GatewayError::config(format!("无法创建 HTTP 客户端:{e}")))?; + let http = base_client_builder().build().map_err(|e| { + GatewayError::config(msg!( + "gw.config.http_client", detail = e => "The HTTP client could not be created: {detail}" + )) + })?; let limits = config.limits.clone(); let pricing_config = config.pricing.clone(); let price_assign = config.price_assign(); @@ -323,7 +332,7 @@ impl AppState { Arc::new(tw_pricing::Table::builtin().unwrap_or_else(|e| { // **加载不了不能挡住启动**:那时成本显示「未知」, // 而转发照常 - tracing::warn!("内置价目表加载失败,所有请求的费用记为未知:{e}"); + tracing::warn!("the built-in price sheet failed to load; every request is recorded with an unknown cost: {e}"); tw_pricing::Table::empty() })), pricing_config, @@ -380,7 +389,7 @@ impl AppState { let o = p .oauth .as_ref() - .ok_or_else(|| format!("上游「{}」未配置 OAuth", p.name))?; + .ok_or_else(|| format!("upstream `{}` has no OAuth configured", p.name))?; self.oauth_token(p, o, http).await } @@ -398,7 +407,7 @@ impl AppState { let o = p .oauth .as_ref() - .ok_or_else(|| format!("上游「{}」未配置 OAuth", p.name))?; + .ok_or_else(|| format!("upstream `{}` has no OAuth configured", p.name))?; let got = self .oauth .invalidate_and_refresh(&p.name, o, http, sent_at) @@ -446,9 +455,15 @@ impl AppState { // **交出去就不管了。**写文件、存历史、防回环都在控制面, // 而这里是转发路径 —— 它不能等一次磁盘写。 // 通道满 = 前一次还没写完 - Some(tx) => tx.try_send(r).err().map(|_| "写回队列已满,本次未能写回"), + Some(tx) => tx + .try_send(r) + .err() + .map(|_| "the write-back queue is full, so this rotation was not written back"), // 控制面没起来:**只报不写**,而且要说清没写 - None => Some("网关独立运行,没有配置管理器,无法写回"), + None => Some( + "the gateway is running on its own, with no configuration manager, so this \ + rotation was not written back", + ), }; // **换发的 refresh token 没写回才要说** —— 丢掉的是一份还没落盘、旧的已经作废的 // 凭据。access token 没写回不要紧:下次启动拿 refresh token 再换一个就是 @@ -484,7 +499,7 @@ impl AppState { return; } if rejected { - tracing::warn!(provider, status, "上游拒绝了凭据"); + tracing::warn!(provider, status, "the upstream rejected the credential"); } self.bus.emit(tw_api::Event::AuthChanged { id: self.bus.next_id(), @@ -646,7 +661,10 @@ impl AppState { if !first { return; } - tracing::warn!(provider, "OAuth 凭据已失效,需要重新登录:{e}"); + tracing::warn!( + provider, + "the OAuth credential has expired and needs a new sign-in: {e}" + ); self.bus.emit(tw_api::Event::CredentialExpired { id: self.bus.next_id(), provider: provider.to_string(), @@ -702,7 +720,7 @@ impl AppState { }) .unwrap_or(false); if changed { - tracing::warn!(provider, window = %w.window, "订阅额度已用完"); + tracing::warn!(provider, window = %w.window, "the subscription quota is used up"); self.bus.emit(tw_api::Event::QuotaExhausted { id: self.bus.next_id(), provider: provider.to_string(), @@ -721,11 +739,14 @@ impl AppState { /// 而那时他应该已经知道原因。 pub fn report_rotation(&self, provider: &str, persisted: bool, detail: &str) { { - let mut told = self.rotation_told.lock().expect("锁未中毒"); + let mut told = self.rotation_told.lock().expect("lock not poisoned"); if persisted { if !told.insert(provider.to_string()) { // 这家的「已经帮你写回去了」说过了 - tracing::debug!(provider, "凭据再次轮换,已写回"); + tracing::debug!( + provider, + "the credential rotated again and was written back" + ); return; } } else { @@ -737,13 +758,15 @@ impl AppState { if persisted { tracing::info!( provider, - "token 端点换发了新的 refresh token,已写回 config.yaml" + "the token endpoint issued a new refresh token; it was written back to config.yaml" ); } else { tracing::warn!( provider, detail, - "token 端点换发了新的 refresh token,但未能写回 config.yaml。重启前必须处理,否则该上游的请求将全部返回 401" + "the token endpoint issued a new refresh token and it could not be written back to \ + config.yaml; this has to be dealt with before a restart, or every request to this \ + upstream will come back 401" ); } self.bus.emit(tw_api::Event::CredentialRotated { @@ -911,9 +934,11 @@ impl AppState { query: Option<&str>, ) -> Result<(String, crate::auth::KeyPosition), GatewayError> { let Some((key, position)) = crate::auth::extract_key_with_position(headers, query) else { - return Err(GatewayError::auth( - "请求未携带网关密钥。请将 config.yaml 的 clients 中的网关密钥配置到客户端", - )); + return Err(GatewayError::auth(msg!( + "gw.auth.no_key" => + "The request carried no gateway key. Configure the client with one of the gateway \ + keys under `clients` in config.yaml." + ))); }; let rt = self.rt.load(); let found = rt.config.clients.iter().find(|c| key_eq(&c.key, &key)); @@ -921,16 +946,18 @@ impl AppState { // **停用的密钥要说清楚是停用了。**这一条和「密钥无效」不同: // 用户是自己停的,而把它说成无效会让他去查客户端配置 —— 那里 // 什么问题都没有 - Some(c) if c.disabled => Err(GatewayError::auth(format!( - "网关密钥「{}」已停用。在应用的密钥页启用它即可恢复", - c.name + Some(c) if c.disabled => Err(GatewayError::auth(msg!( + "gw.auth.key_disabled", key = c.name.clone() => + "Gateway key `{key}` is disabled. Enable it on the app's keys page to use it again." ))), Some(c) => Ok((c.name.clone(), position)), // 不回显收到的 key,哪怕是打码的 —— 回显会让「猜密钥」 // 这件事有了反馈信号。 - None => Err(GatewayError::auth( - "网关密钥无效。请检查客户端配置中的密钥与 config.yaml 是否一致", - )), + None => Err(GatewayError::auth(msg!( + "gw.auth.key_invalid" => + "The gateway key is not valid. Check that the key in the client's configuration \ + matches the one in config.yaml." + ))), } } } @@ -985,37 +1012,49 @@ async fn ws_upgrade( client: client_name.clone(), ..Default::default() }; - let decision = match rt - .engine - .route(&facts) - .map_err(|e| GatewayError::config(format!("路由失败:{e}")))? - { + let decision = match rt.engine.route(&facts).map_err(|e| { + GatewayError::config(msg!("gw.route.failed", detail = e => "Routing failed: {detail}")) + })? { tw_engine::Outcome::Route(d) => d, tw_engine::Outcome::Deny { rule, reason } => { - tracing::info!(%rule, "按规则拒绝 WebSocket 升级"); - return Err(GatewayError::denied(reason)); + tracing::info!(%rule, "a rule denied the WebSocket upgrade"); + return Err(GatewayError::denied(msg!( + "gw.route.denied", rule = rule, reason = reason => + "Rule `{rule}` denied this request: {reason}" + ))); } }; let (alive, _) = state.health.filter(&decision.candidates); let Some(name) = alive.first().map(|s| s.to_string()) else { - return Err(GatewayError::config("没有可用的上游".to_string())); + return Err(GatewayError::config(msg!( + "gw.route.no_upstream_alive" => "No upstream is available." + ))); }; let Some(provider) = rt.config.providers.iter().find(|p| p.name == name) else { - return Err(GatewayError::config(format!("配置中不存在「{name}」"))); + return Err(GatewayError::config(msg!( + "gw.route.upstream_missing", upstream = name.clone() => + "`{upstream}` is not in the configuration." + ))); }; // **走代理的上游不代理 WS**,而且要明说。悄悄绕过用户配的代理, // 等于把他以为在代理后面的流量直接发出去 if provider.proxy != tw_config::DIRECT { - return Err(GatewayError::config(format!( - "上游「{name}」配置了代理({}),WebSocket 连接暂不支持经代理转发,仅支持直连的上游", - provider.proxy + return Err(GatewayError::config(msg!( + "gw.ws.proxy_unsupported", upstream = name.clone(), proxy = provider.proxy.clone() => + "Upstream `{upstream}` goes through proxy `{proxy}`. WebSocket connections are not \ + forwarded through a proxy yet; only directly connected upstreams are." ))); } let http = rt.clients.get(&name).unwrap_or(&state.http); let upstream_headers = state .headers_for(provider, http, Some(&client_name)) .await - .map_err(|e| GatewayError::config(format!("无法获取上游「{name}」的凭据:{e}")))?; + .map_err(|e| { + GatewayError::config(msg!( + "gw.credentials.failed", upstream = name.clone(), detail = e => + "The credential for upstream `{upstream}` could not be obtained: {detail}" + )) + })?; let url = crate::ws::upstream_url(&provider.base_url, uri.path(), query.as_deref()); let id = state.bus.next_id(); state.bus.emit(tw_api::Event::RequestStarted { @@ -1112,9 +1151,9 @@ async fn list_models( ) -> Result { let rt = state.runtime(); if !rt.allow.allows(peer.ip()) { - return Err(GatewayError::auth(format!( - "{} 不在允许的来源地址中", - peer.ip() + return Err(GatewayError::auth(msg!( + "gw.auth.source_not_allowed", peer = peer.ip() => + "{peer} is not among the allowed source addresses." ))); } let (client, position) = state.identify(&headers, query.as_deref())?; @@ -1163,9 +1202,9 @@ async fn get_model( ) -> Result { let rt = state.runtime(); if !rt.allow.allows(peer.ip()) { - return Err(GatewayError::auth(format!( - "{} 不在允许的来源地址中", - peer.ip() + return Err(GatewayError::auth(msg!( + "gw.auth.source_not_allowed", peer = peer.ip() => + "{peer} is not among the allowed source addresses." ))); } let (client, position) = state.identify(&headers, query.as_deref())?; @@ -1182,7 +1221,10 @@ async fn get_model( if !catalog.is_empty() && !catalog.admits(&model, Some(&shape.protocols()), allow.as_deref()) { return Err(GatewayError::new( crate::error::Source::Request, - format!("不存在模型 {model},可用模型请参见 GET /v1/models"), + msg!( + "gw.model.unknown", model = model.clone() => + "There is no model {model}. GET /v1/models lists the models that are available." + ), )); } let now = now_ms() / 1000; @@ -1219,9 +1261,10 @@ async fn passthrough( if !rt.allow.allows(peer.ip()) { return Err(GatewayError::new( crate::error::Source::Auth, - format!( - "{} 不在允许的来源地址中。请修改 listen.gateway.allow_from,或将 bind 改为 loopback", - peer.ip() + msg!( + "gw.auth.source_not_allowed_hint", peer = peer.ip() => + "{peer} is not among the allowed source addresses. Change \ + listen.gateway.allow_from, or set bind to loopback." ), )); } @@ -1281,7 +1324,7 @@ async fn passthrough( .await; if let Some(end) = ending.take() { match &result { - Err(e) => end.failed(e.source.slug(), e.message.clone()), + Err(e) => end.failed(e.source.slug(), e.detail.clone()), // 成功的路径都把结局交给了响应体,**走到这里是漏交了**。那也只能 // 按拿到的状态码报结束 —— 不能让它掉在地上,被记成一次取消 Ok(resp) => end.finished(resp.status().as_u16()), @@ -1384,7 +1427,7 @@ async fn pipeline( probe: kind.slug().to_string(), at_ms: now_ms(), }); - tracing::debug!(client = %client_name, kind = kind.slug(), "本地应答"); + tracing::debug!(client = %client_name, kind = kind.slug(), "answered locally"); return Ok(local_answer(kind, &body)); } // `route` 交给规则处理:打一个标记让 `when: { intent: ... }` @@ -1402,9 +1445,10 @@ async fn pipeline( // 因为「一个 provider 都没有」时任何路由结果都是空的,而那条错误 // 说不清下一步。 if rt.config.providers.is_empty() { - return Err(GatewayError::config(concat!( - "尚未配置任何上游。请在 ThinkWatch Lite 中添加上游,", - "或在 config.yaml 的 providers 中添加" + return Err(GatewayError::config(msg!( + "gw.config.no_upstreams" => + "No upstream is configured yet. Add one in ThinkWatch Lite, or under `providers` in \ + config.yaml." ))); } @@ -1443,33 +1487,36 @@ async fn pipeline( if !catalog.admits(&facts.model, servable.as_deref(), allow.as_deref()) { // 错误信息要说清是哪一种:没有上游提供它,和这个客户端不让用它, // 该去改的地方不一样 - let msg = if catalog.providers_for(&facts.model).is_empty() { - format!( - "没有上游提供模型 {},可用模型请参见 GET /v1/models", - facts.model + let why = if catalog.providers_for(&facts.model).is_empty() { + msg!( + "gw.model.no_upstream", model = facts.model.clone() => + "No upstream serves model {model}. GET /v1/models lists the models that \ + are available." ) } else { - format!( - "网关密钥「{client_name}」无权使用模型 {},可用模型请参见 GET /v1/models", - facts.model + msg!( + "gw.model.not_allowed", key = client_name.clone(), model = facts.model.clone() => + "Gateway key `{key}` may not use model {model}. GET /v1/models lists the \ + models that are available." ) }; - return Err(GatewayError::new(crate::error::Source::Request, msg)); + return Err(GatewayError::new(crate::error::Source::Request, why)); } } } - let mut decision = match rt - .engine - .route(&facts) - .map_err(|e| GatewayError::config(format!("路由失败:{e}")))? - { + let mut decision = match rt.engine.route(&facts).map_err(|e| { + GatewayError::config(msg!("gw.route.failed", detail = e => "Routing failed: {detail}")) + })? { tw_engine::Outcome::Route(d) => d, tw_engine::Outcome::Deny { rule, reason } => { // **带理由的拒绝。**一个没有理由的拒绝,和一个 bug,在用户 // 眼里没有区别。 - tracing::info!(%rule, "按规则拒绝"); - return Err(GatewayError::denied(reason)); + tracing::info!(%rule, "a rule denied the request"); + return Err(GatewayError::denied(msg!( + "gw.route.denied", rule = rule, reason = reason => + "Rule `{rule}` denied this request: {reason}" + ))); } }; // 去掉服务不了这个请求的候选:停用的、范围外的、清单里没有这个模型的。 @@ -1487,7 +1534,7 @@ async fn pipeline( return Err(serving.explain(&facts.model)); } if !serving.skipped.is_empty() { - tracing::debug!(skipped = ?serving.skipped, model = %facts.model, "跳过无法服务该请求的候选上游"); + tracing::debug!(skipped = ?serving.skipped, model = %facts.model, "skipping the candidates that cannot serve this request"); } decision.candidates = serving.usable; // 策略组排序。**引擎给的是集合,顺序在这儿定** —— @@ -1548,7 +1595,12 @@ async fn pipeline( client_limit, ) .await - .map_err(|e| GatewayError::new(crate::error::Source::Overloaded, e.to_string()))?; + .map_err(|e| { + GatewayError::new( + crate::error::Source::Overloaded, + msg!("gw.overloaded", detail = e => "{detail}"), + ) + })?; // 熔断过滤。**只有一个候选时完全旁路**,全都熔断时 fail-open —— // 两条边界都在 `Health::filter` 里,理由写在那儿。 @@ -1556,7 +1608,7 @@ async fn pipeline( if fail_open { tracing::warn!( candidates = ?decision.candidates, - "所有候选上游均处于熔断状态,仍照常尝试(fail-open)" + "every candidate upstream is open-circuited; trying them anyway (fail-open)" ); } @@ -1644,9 +1696,10 @@ async fn pipeline( for name in &alive { let Some(provider) = rt.config.providers.iter().find(|p| &p.name == *name) else { // 校验时挡过一次,能到这儿说明配置在运行中被换过。 - last_err = Some(GatewayError::config(format!( - "规则「{}」选中的上游「{name}」在配置中不存在", - decision.matched_rule + last_err = Some(GatewayError::config(msg!( + "gw.route.selected_upstream_missing", + rule = decision.matched_rule.clone(), upstream = name => + "Rule `{rule}` selected upstream `{upstream}`, which is not in the configuration." ))); continue; }; @@ -1660,11 +1713,20 @@ async fn pipeline( && let (Some(a), Some(p)) = (api, provider.effective_protocol()) && a.protocol() != p { - let why = format!("{} 只能由 {} 格式的上游处理", uri.path(), a.slug()); + let why = format!( + "{} can only be served by a {} upstream", + uri.path(), + a.slug() + ); chain.push(hop_failed(&provider.name, why.clone(), hop_started)); last_err = Some(GatewayError::new( crate::error::Source::Request, - format!("{why},上游「{}」是 {} 格式", provider.name, p.slug()), + msg!( + "gw.route.protocol_mismatch", + path = uri.path(), wanted = a.slug(), + upstream = provider.name.clone(), got = p.slug() => + "{path} can only be served by a {wanted} upstream, and `{upstream}` is {got}." + ), )); continue; } @@ -1674,18 +1736,26 @@ async fn pipeline( // **在循环里面,因为故障转移换了 provider 之后必须重算**。 // 否则「走中转的一律脱敏」这条规则,在从官方转移到中转时会漏掉 // —— 而那正是最需要它的时刻。 - let (effective_set, guard) = - match rt - .engine - .phase_two(&facts, &provider.name, &decision.set, &decision.guard) - { - Ok(tw_engine::Outcome2::Proceed(s, g)) => (s, g), - Ok(tw_engine::Outcome2::Deny { rule, reason }) => { - tracing::info!(%rule, provider = %provider.name, "阶段二拒绝"); - return Err(GatewayError::denied(reason)); - } - Err(e) => return Err(GatewayError::config(format!("规则求值失败:{e}"))), - }; + let (effective_set, guard) = match rt.engine.phase_two( + &facts, + &provider.name, + &decision.set, + &decision.guard, + ) { + Ok(tw_engine::Outcome2::Proceed(s, g)) => (s, g), + Ok(tw_engine::Outcome2::Deny { rule, reason }) => { + tracing::info!(%rule, provider = %provider.name, "a phase-two rule denied the request"); + return Err(GatewayError::denied(msg!( + "gw.route.denied", rule = rule, reason = reason => + "Rule `{rule}` denied this request: {reason}" + ))); + } + Err(e) => { + return Err(GatewayError::config(msg!( + "gw.route.rule_failed", detail = e => "A rule could not be evaluated: {detail}" + ))); + } + }; // 方言互转。**同格式时是 None,这一整段零成本** let client_dialect = api.map(|a| a.dialect()); let target = crate::translate::plan(api, generates, provider.effective_protocol()); @@ -1757,16 +1827,20 @@ async fn pipeline( // 转换不了就换下一家:同格式的上游可能还在后面 let why = match other { Some(Err(rej)) => rej.0.clone(), - _ => "请求体不是合法的 JSON".to_string(), + _ => "the request body is not valid JSON".to_string(), }; chain.push(hop_failed( &provider.name, - format!("无法转换为 {} 格式:{why}", dialect.slug()), + format!("could not be converted to {}: {why}", dialect.slug()), hop_started, )); last_err = Some(GatewayError::new( crate::error::Source::Request, - format!("无法转换为上游「{}」的格式:{why}", provider.name), + msg!( + "gw.convert.failed", upstream = provider.name.clone(), detail = why => + "The request could not be converted to the format upstream \ + `{upstream}` speaks: {detail}" + ), )); continue; } @@ -1857,18 +1931,18 @@ async fn pipeline( ); chain.push(hop_failed( &provider.name, - format!("无法获取凭据:{e}"), + format!("the credential could not be obtained: {e}"), hop_started, )); - last_err = Some(GatewayError::config(format!( - "无法获取上游「{}」的凭据:{e}", - provider.name + last_err = Some(GatewayError::config(msg!( + "gw.credentials.failed", upstream = provider.name.clone(), detail = e => + "The credential for upstream `{upstream}` could not be obtained: {detail}" ))); continue; } }; let url = forward::upstream_url(&provider.base_url, &path, upstream_query.as_deref()); - let method = reqwest::Method::from_bytes(b"POST").expect("POST 是合法方法"); + let method = reqwest::Method::from_bytes(b"POST").expect("POST is a valid method"); tracing::debug!( client = %client_name, @@ -1877,7 +1951,7 @@ async fn pipeline( group = ?decision.via_group, url = %tw_secret::redact_url(&url), attempt = attempts.len(), - "转发" + "forwarding" ); let required = target @@ -1928,7 +2002,7 @@ async fn pipeline( } Ok(_) => {} Err(e) => { - tracing::debug!(provider = %provider.name, "上游返回 401,换 token 失败:{e}") + tracing::debug!(provider = %provider.name, "the upstream answered 401 and the token could not be renewed: {e}") } } } @@ -1956,9 +2030,15 @@ async fn pipeline( // **429 要保住 429。**塌成 502 的话,客户端会当成「服务器 // 坏了」而不是「该退避了」,而它们该做的事完全不同。 last_err = Some(if r.status() == 429 { - GatewayError::rate_limited(format!("上游「{}」触发限流", provider.name)) + GatewayError::rate_limited(msg!( + "gw.upstream.rate_limited", upstream = provider.name.clone() => + "Upstream `{upstream}` rate-limited the request." + )) } else { - GatewayError::upstream(format!("上游「{}」返回 {}", provider.name, r.status())) + GatewayError::upstream(msg!( + "gw.upstream.status", upstream = provider.name.clone(), status = r.status().as_u16() => + "Upstream `{upstream}` answered {status}." + )) }); continue; } @@ -1991,7 +2071,11 @@ async fn pipeline( // 连不上的可能是代理而不是上游 —— 检一次那个代理,说清是哪一件事 state.check_proxy(&provider.proxy); let err = forward::map_reqwest_error(e); - chain.push(hop_failed(&provider.name, err.message.clone(), hop_started)); + chain.push(hop_failed( + &provider.name, + err.message().to_string(), + hop_started, + )); last_err = Some(err); continue; } @@ -2014,13 +2098,15 @@ async fn pipeline( }); let (Some(upstream), Some(provider)) = (upstream, used) else { - let mut err = last_err.unwrap_or_else(|| GatewayError::config("没有可用的上游")); + let mut err = last_err.unwrap_or_else(|| { + GatewayError::config(msg!("gw.route.no_upstream_alive" => "No upstream is available.")) + }); // **尝试链要进客户端看到的那条错误**,不只进我们的事件流 —— // 用户看的是他自己终端里的报错。一条说「试过 A → B → C 都不行」 // 的错误,和一条只说「503」的错误,是两种产品:前者说明我们替 // 他做了工作,后者让他以为我们什么都没干。 if attempts.len() > 1 { - err.message = format!("{}(已尝试:{})", err.message, attempts.join(" → ")); + err = err.with_attempts(&attempts); } // 失败也必须有结局。少了它,UI 上那一行会永远停在「进行中」—— // 而「一直转圈」比「明确失败」更让人怀疑是我们卡住了。它由 @@ -2031,7 +2117,7 @@ async fn pipeline( if attempts.len() > 1 { tracing::info!( chain = %attempts.join(" → "), - "故障转移:最终由 {} 响应", + "failed over; {} answered in the end", provider.name ); } @@ -2078,7 +2164,9 @@ async fn pipeline( // // **结局跟着流走,而不是只写在流的末尾。**客户端中途走掉时,末尾的 // 代码一行都不会执行,而上游已经为这次请求计了费(见 `crate::ending`)。 - let mut ending = ending.take().expect("发出开始事件时已写入"); + let mut ending = ending + .take() + .expect("written when the start event was emitted"); ending.responded(status.as_u16()); let chunks = upstream.bytes_stream(); // **中途断掉不能只是让流消失。**首字节已经发出去了,状态码和响应头 @@ -2242,12 +2330,16 @@ async fn pipeline( if blocked { tracing::warn!( provider = %wall_provider, tool = %v.tool, rule = %v.rule, - "已切断响应流:上游返回了高危工具调用" + "cut the response stream: the upstream returned a dangerous tool call" ); cut = Some(( - GatewayError::denied(format!( - "上游「{}」(非官方端点)返回的 {} 调用命中规则「{}」({}),已切断响应", - wall_provider, v.tool, v.rule, v.why + GatewayError::denied(msg!( + "gw.toolcall.cut", + upstream = wall_provider.clone(), tool = v.tool.clone(), + rule = v.rule.clone(), why = v.why.clone() => + "The {tool} call returned by upstream `{upstream}` (an \ + unofficial endpoint) matched rule `{rule}` ({why}), so \ + the response was cut off." )), v.safe_prefix, )); @@ -2345,16 +2437,19 @@ async fn pipeline( // // `source` 用这个错误自己的:上游断了是 `upstream`,被 // 防火墙切断是 `denied` —— 后者不是上游坏了,是策略拦的。 - ending.failed(err.source.slug(), format!("响应流中断:{}", err.message)); + // 码保持不变,只在句子前面点明它断在流里 —— 界面认的是码 + let mut why = err.detail.clone(); + why.text = format!("the response stream broke: {}", why.text); + ending.failed(err.source.slug(), why); if let Some(c) = back.as_mut() { // 转换过的流按客户端的格式收尾 - yield Ok(Bytes::from(c.fail(&format!("[ThinkWatch] {}", err.message)))); + yield Ok(Bytes::from(c.fail(&format!("[ThinkWatch] {}", err.message())))); } else if let (true, Some(s)) = (collect, session.as_ref()) { // 要收齐的整包一个字节都还没发:按客户端的格式回一个错误体 yield Ok(Bytes::from(tw_dialect::convert::error_body( s.client, 502, - &format!("[ThinkWatch] {}", err.message), + &format!("[ThinkWatch] {}", err.message()), ))); } else if is_sse && session.is_none() { yield Ok(Bytes::from(err.sse_frame())); @@ -2405,20 +2500,20 @@ pub async fn seed_latency(state: &AppState) { let hop = match crate::l1::hop_for(&rt.config, p) { Ok(h) => h, Err(why) => { - tracing::debug!(provider = %name, %why, "该上游无法进行链路测速,不补充延迟样本"); + tracing::debug!(provider = %name, %why, "this upstream cannot be link-tested, so no latency sample is seeded"); continue; } }; let r = crate::l1::l1(&p.base_url, hop.as_ref()).await; if r.ok { - tracing::debug!(provider = %name, ms = r.total_ms, "以链路测速结果补充延迟样本"); + tracing::debug!(provider = %name, ms = r.total_ms, "seeding a latency sample from the link test"); state .latency .seed(&name, r.total_ms.min(u32::MAX as u64) as u32); } else { // **连都连不上的那家不垫。**它会因为「没样本」排在最后, // 而那正是对的 - tracing::debug!(provider = %name, "链路测速无法连接,不补充延迟样本"); + tracing::debug!(provider = %name, "the link test could not connect, so no latency sample is seeded"); } } } @@ -2454,7 +2549,7 @@ pub async fn serve_following_config( // 通知来了但地址没变(比如又改回去了)—— 原样重来 continue; } - tracing::info!(from = %next, to = %want, "监听地址已变化,重建监听器"); + tracing::info!(from = %next, to = %want, "the listen address changed; rebuilding the listener"); next = want; } } @@ -2469,9 +2564,9 @@ async fn serve_once( let listener = tokio::net::TcpListener::bind(addr).await?; let actual = listener.local_addr()?; if !state.runtime().allow.is_empty() { - tracing::info!(%actual, "网关已开始监听(启用来源地址白名单)"); + tracing::info!(%actual, "the gateway is listening (source allow-list in effect)"); } else { - tracing::info!(%actual, "网关已开始监听"); + tracing::info!(%actual, "the gateway is listening"); } // `into_make_service_with_connect_info` 是拿到对端地址的唯一办法 —— // 少了它,来源白名单收到的永远是 unwrap 出来的默认值。 @@ -2626,13 +2721,14 @@ mod tests { // 用户十有八九是想写 `direct`。 let cfg = tw_config::Config::default(); let e = client_for_provider(&cfg, &provider_with_proxy("airport")).unwrap_err(); - assert!(e.message.contains("airport"), "{}", e.message); - assert!(e.message.contains("direct"), "{}", e.message); + assert_eq!(e.detail.code, "gw.config.proxy_undefined"); + assert_eq!(e.detail.arg("proxy"), "airport"); + assert!(e.message().contains("direct"), "{}", e.message()); // 行续接留下的缩进不该进错误信息 assert!( - !e.message.contains(" "), + !e.message().contains(" "), "错误信息里有多余空格:{}", - e.message + e.message() ); } @@ -2696,7 +2792,8 @@ mod tests { let s = AppState::new(cfg()).unwrap(); let e = s.identify(&HeaderMap::new(), None).unwrap_err(); assert_eq!(e.source, crate::error::Source::Auth); - assert!(e.message.contains("clients")); + assert_eq!(e.detail.code, "gw.auth.no_key"); + assert!(e.message().contains("clients")); } #[test] @@ -2704,8 +2801,10 @@ mod tests { // 回显会给「猜密钥」这件事一个反馈信号,哪怕只是打码的。 let s = AppState::new(cfg()).unwrap(); let e = s.identify(&hdr("x-api-key", "tw-wrong"), None).unwrap_err(); - assert!(!e.message.contains("tw-wrong")); - assert!(!e.message.contains("tw-wr")); + assert!(!e.message().contains("tw-wrong")); + assert!(!e.message().contains("tw-wr")); + // 参数里也不许有 —— 界面拿的是参数,不是那句话 + assert!(!e.detail.args.values().any(|v| v.contains("tw-wr"))); } #[test] diff --git a/crates/tw-gateway/src/toolwall.rs b/crates/tw-gateway/src/toolwall.rs index 099d9ef2..254f2f75 100644 --- a/crates/tw-gateway/src/toolwall.rs +++ b/crates/tw-gateway/src/toolwall.rs @@ -125,7 +125,7 @@ fn complete_tool_calls(v: &Value) -> Vec<(String, String)> { let name = v .get("name") .and_then(|x| x.as_str()) - .unwrap_or("(未命名)") + .unwrap_or("(unnamed)") .to_string(); out.push((name, input.to_string())); } @@ -271,7 +271,7 @@ impl Wall { let name = call .get("name") .and_then(|x| x.as_str()) - .unwrap_or("(未命名)") + .unwrap_or("(unnamed)") .to_string(); let args = call.get("args").map(|a| a.to_string()).unwrap_or_default(); self.check(&name, &args, safe_prefix, out); @@ -425,7 +425,7 @@ impl Wall { let name = call .get("name") .and_then(|x| x.as_str()) - .unwrap_or("(未命名)") + .unwrap_or("(unnamed)") .to_string(); let args = call.get("args").map(|a| a.to_string()).unwrap_or_default(); self.check(&name, &args, safe_prefix, out); @@ -441,7 +441,7 @@ impl Wall { fn open_call(&mut self, index: u64, name: Option<&Value>) { let name = name .and_then(|x| x.as_str()) - .unwrap_or("(未命名)") + .unwrap_or("(unnamed)") .to_string(); self.blocks.insert(index, (name, String::new())); self.tool_calls += 1; @@ -510,9 +510,9 @@ impl Wall { self.fired.push(r.id.clone()); out.push(Verdict { rule: r.id.clone(), - why: format!("{}。这段文字会进入下一轮对话的上下文", r.why), + why: format!("{}. This text enters the context of the next turn", r.why), high: false, - tool: "(响应正文)".into(), + tool: "(response text)".into(), excerpt: excerpt(m.as_str()), safe_prefix, }); @@ -836,8 +836,8 @@ mod tests { ); assert_eq!(v.len(), 1, "{v:?}"); assert!(!v[0].high, "提示注入不该切断响应"); - assert_eq!(v[0].tool, "(响应正文)"); - assert!(v[0].why.contains("下一轮"), "{}", v[0].why); + assert_eq!(v[0].tool, "(response text)"); + assert!(v[0].why.contains("next turn"), "{}", v[0].why); } #[test] diff --git a/crates/tw-gateway/src/ws.rs b/crates/tw-gateway/src/ws.rs index 4fffa7f2..d4420426 100644 --- a/crates/tw-gateway/src/ws.rs +++ b/crates/tw-gateway/src/ws.rs @@ -32,6 +32,7 @@ use futures::{SinkExt, StreamExt}; use tokio_tungstenite::tungstenite::protocol::Message as UpMsg; use crate::server::AppState; +use tw_types::{Msg, msg}; /// `Option` 的替身。 /// @@ -127,9 +128,13 @@ pub async fn proxy( ) { Ok(r) => r, Err(e) => { - let why = format!("上游地址不是合法的 WebSocket 地址:{e}"); - ending.failed("config", why.clone()); - close_with(client, &why).await; + let why = msg!( + "gw.ws.bad_url", detail = e => + "The upstream address is not a valid WebSocket address: {detail}" + ); + let text = why.text.clone(); + ending.failed("config", why); + close_with(client, &text).await; return; } }; @@ -143,9 +148,13 @@ pub async fn proxy( req.headers_mut().insert(n, v); } _ => { - let why = format!("上游的请求头「{name}」包含请求头中不允许的字符"); - ending.failed("config", why.clone()); - close_with(client, &why).await; + let why = msg!( + "gw.ws.bad_header", header = name => + "The upstream header `{header}` contains characters a header may not carry." + ); + let text = why.text.clone(); + ending.failed("config", why); + close_with(client, &text).await; return; } } @@ -153,9 +162,13 @@ pub async fn proxy( let up = match dial(&upstream_url, req).await { Ok(x) => x, Err(e) => { - let why = format!("无法连接上游的 WebSocket:{e}"); - ending.failed("upstream", why.clone()); - close_with(client, &why).await; + let why = msg!( + "gw.ws.connect_failed", detail = e => + "The upstream WebSocket could not be connected: {detail}" + ); + let text = why.text.clone(); + ending.failed("upstream", why); + close_with(client, &text).await; return; } }; @@ -206,10 +219,10 @@ async fn dial( }; let tcp = tokio::net::TcpStream::connect((host.as_str(), port)) .await - .map_err(|e| format!("无法连接 {host}:{port}:{e}"))?; + .map_err(|e| format!("{host}:{port} could not be reached: {e}"))?; let io: Box = if tls { let name = rustls::pki_types::ServerName::try_from(host.clone()) - .map_err(|_| format!("{host} 不是有效的 TLS 主机名"))?; + .map_err(|_| format!("{host} is not a valid TLS host name"))?; let conn = tokio_rustls::TlsConnector::from(crate::l1::tls_config()); Box::new(conn.connect(name, tcp).await.map_err(|e| e.to_string())?) } else { @@ -232,9 +245,9 @@ enum End { /// 都算这一种** —— 一次会话就是由客户端结束的,那是正常收场 Closed, /// 上游那边出错断了,或者写不过去了 - Broke(String), + Broke(Msg), /// 上游返回了高危工具调用,被切断了 - Cut(String), + Cut(Msg), } async fn pump( @@ -286,7 +299,9 @@ async fn pump( Message::Close(_) => break End::Closed, }; if let Err(e) = u_tx.send(out).await { - break End::Broke(format!("向上游发送数据失败:{e}")); + break End::Broke(msg!( + "gw.ws.send_failed", detail = e => "Sending to the upstream failed: {detail}" + )); } } // 上游 → 客户端:先还原占位符,再过工具墙 @@ -295,20 +310,29 @@ async fn pump( Some(Ok(m)) => m, // 上游把连接收掉了,没有关闭帧也算收场 None => break End::Closed, - Some(Err(e)) => break End::Broke(format!("上游连接中断:{e}")), + Some(Err(e)) => { + break End::Broke(msg!( + "gw.ws.upstream_broke", detail = e => + "The upstream connection broke: {detail}" + )); + } }; let out = match m { UpMsg::Text(t) => { let restored = tw_redact::redact::restore(t.as_str(), &p.ledger); let hits = p.wall.feed(as_sse(&restored).as_bytes()); let mut deadly = false; - let mut why = String::new(); + let mut why: Option = None; for h in &hits { - if h.high && p.cut && !deadly { - why = format!( - "上游「{}」(非官方端点)返回的 {} 调用命中规则「{}」({}),已切断连接", - p.provider, h.tool, h.rule, h.why - ); + if h.high && p.cut && why.is_none() { + why = Some(msg!( + "gw.ws.toolcall_cut", + upstream = p.provider.clone(), tool = h.tool.clone(), + rule = h.rule.clone(), detail = h.why.clone() => + "The {tool} call returned by upstream `{upstream}` (an \ + unofficial endpoint) matched rule `{rule}` ({detail}), so \ + the connection was cut." + )); } deadly |= h.high && p.cut; state.bus.emit(tw_api::Event::ToolCallFlagged { @@ -327,9 +351,9 @@ async fn pump( // **命中那一帧不发。**和 SSE 那条路同一条纪律: // 先判断再转发,而不是发完再说 let _ = c_tx.send(Message::Text( - "[ThinkWatch] 上游返回了高危工具调用,连接已切断".into(), + "[ThinkWatch] the upstream returned a dangerous tool call; the connection was cut".into(), )).await; - break End::Cut(why); + break End::Cut(why.expect("set on the same pass that set deadly")); } ending.count(restored.len()); Message::Text(restored.into()) diff --git a/crates/tw-gateway/tests/endings.rs b/crates/tw-gateway/tests/endings.rs index f578a78f..cc69b072 100644 --- a/crates/tw-gateway/tests/endings.rs +++ b/crates/tw-gateway/tests/endings.rs @@ -363,7 +363,8 @@ async fn a_stream_the_tool_firewall_cuts_is_denied_and_keeps_its_usage() { .. } => { assert_eq!(source, "denied"); - assert!(message.contains("Bash"), "{message}"); + assert_eq!(message.code, "gw.toolcall.cut", "{message}"); + assert_eq!(message.arg("tool"), "Bash", "{message}"); let u = usage.expect("切断之前的用量没有带上"); assert_eq!(u.input, 5000); } @@ -437,7 +438,7 @@ async fn a_phase_two_deny_after_the_request_started_is_reported_as_denied() { matches!( &got[0], Event::RequestFailed { source, message, .. } - if source == "denied" && message.contains("这段内容不发给中转站") + if source == "denied" && message.text.contains("这段内容不发给中转站") ), "该是一次带着理由的拒绝:{got:?}" ); @@ -563,7 +564,7 @@ async fn a_websocket_cut_for_a_dangerous_tool_call_is_failed_as_denied() { matches!( &got[0], Event::RequestFailed { source, message, .. } - if source == "denied" && message.contains("Bash") + if source == "denied" && message.arg("tool") == "Bash" ), "该是一次带着工具名的拦截:{got:?}" ); diff --git a/crates/tw-gateway/tests/headers_and_paths.rs b/crates/tw-gateway/tests/headers_and_paths.rs index 4b2a2e3b..81eaaa5c 100644 --- a/crates/tw-gateway/tests/headers_and_paths.rs +++ b/crates/tw-gateway/tests/headers_and_paths.rs @@ -280,7 +280,7 @@ async fn a_disabled_key_is_refused_and_says_it_was_disabled_on_purpose() { let text = resp.text().await.unwrap(); // **和「密钥无效」是两回事**:说成无效的话,用户会去查客户端配置, // 而那里什么问题都没有 - assert!(text.contains("已停用"), "{text}"); + assert!(text.contains("disabled"), "{text}"); assert!(text.contains("试用"), "要说清是哪一把:{text}"); // 同一个网关上,没停用的那把照常能用 diff --git a/crates/tw-gateway/tests/hotreload.rs b/crates/tw-gateway/tests/hotreload.rs index 5fc16a53..1f9c2b54 100644 --- a/crates/tw-gateway/tests/hotreload.rs +++ b/crates/tw-gateway/tests/hotreload.rs @@ -488,7 +488,7 @@ async fn reloading_from_zero_providers_to_one_starts_working_without_a_restart() let state = tw_gateway::AppState::new(cfg(vec![], vec![])).unwrap(); let gw = serve(state.clone()).await; let first = ask(gw).await; - assert!(first.contains("尚未配置任何上游"), "{first}"); + assert!(first.contains("No upstream is configured"), "{first}"); state.reload(cfg(vec![provider("a", a)], vec![])).unwrap(); assert!(ask(gw).await.contains("\"a\""), "加完上游还是不通"); @@ -509,7 +509,7 @@ async fn the_allow_list_is_reloaded_too() { state.reload(c).unwrap(); let after = ask(gw).await; assert!( - after.contains("不在允许的来源地址中"), + after.contains("not among the allowed source addresses"), "白名单没生效:{after}" ); } diff --git a/crates/tw-gateway/tests/m1_acceptance.rs b/crates/tw-gateway/tests/m1_acceptance.rs index 89473629..9218a184 100644 --- a/crates/tw-gateway/tests/m1_acceptance.rs +++ b/crates/tw-gateway/tests/m1_acceptance.rs @@ -297,7 +297,7 @@ async fn four_an_upstream_401_is_readable_and_you_can_tell_which_layer_it_came_f assert!(r.headers().get("x-thinkwatch-upstream").is_none()); let t = r.text().await.unwrap(); assert!(t.contains("[ThinkWatch]"), "{t}"); - assert!(t.contains("网关密钥"), "得说清是哪把 key:{t}"); + assert!(t.contains("gateway key"), "得说清是哪把 key:{t}"); } /// 上游成功时也带这个头 —— 它是「谁服务的」而不是「谁出错了」。 @@ -353,5 +353,5 @@ async fn a_single_model_lookup_obeys_the_same_allow_list_as_the_list() { let r = get("/v1/models/claude-opus-4".into()).await; assert_ne!(r.status(), 200, "**限制了的模型单点还是查得到**"); let body = r.text().await.unwrap(); - assert!(body.contains("不存在模型"), "{body}"); + assert!(body.contains("There is no model"), "{body}"); } diff --git a/crates/tw-gateway/tests/models.rs b/crates/tw-gateway/tests/models.rs index 15f2b9ce..66f30416 100644 --- a/crates/tw-gateway/tests/models.rs +++ b/crates/tw-gateway/tests/models.rs @@ -227,7 +227,10 @@ async fn a_disabled_upstream_takes_no_requests_and_lists_nothing() { let (status, body) = ask(gw, "shared").await; assert_eq!(status, 500, "{body}"); let msg = body["error"]["message"].as_str().unwrap(); - assert!(msg.contains("已停用") && msg.contains("official"), "{msg}"); + assert!( + msg.contains("disabled") && msg.contains("official"), + "{msg}" + ); } #[tokio::test] @@ -279,7 +282,7 @@ async fn when_no_candidate_serves_the_model_the_error_names_each_one_and_why() { assert_eq!(status, 400, "{body}"); let msg = body["error"]["message"].as_str().unwrap(); assert!( - msg.contains("official-only") && msg.contains("relay 未提供此模型"), + msg.contains("official-only") && msg.contains("relay does not offer this model"), "{msg}" ); @@ -287,5 +290,5 @@ async fn when_no_candidate_serves_the_model_the_error_names_each_one_and_why() { let (status, body) = ask(gw, "nobody-has-this").await; assert_eq!(status, 400, "{body}"); let msg = body["error"]["message"].as_str().unwrap(); - assert!(msg.contains("没有上游提供模型"), "{msg}"); + assert!(msg.contains("No upstream serves model"), "{msg}"); } diff --git a/crates/tw-gateway/tests/oauth.rs b/crates/tw-gateway/tests/oauth.rs index 1cdec740..9cf52467 100644 --- a/crates/tw-gateway/tests/oauth.rs +++ b/crates/tw-gateway/tests/oauth.rs @@ -426,7 +426,7 @@ async fn without_a_config_manager_the_rotation_is_reported_as_not_persisted() { for one in &seen { assert_eq!(one.0, "p"); assert!(!one.1, "没写却说写了:{seen:?}"); - assert!(one.2.contains("无法写回"), "{seen:?}"); + assert!(one.2.contains("not written back"), "{seen:?}"); } // 事件里一个 token 都不能有 assert!(!seen.iter().any(|s| s.2.contains("rt-")), "{seen:?}"); @@ -512,5 +512,5 @@ async fn an_error_body_from_the_token_endpoint_is_masked_before_being_reported() !e.contains("OPAQUE-nothing-matches"), "**凭据从错误消息里漏出去了**:{e}" ); - assert!(e.contains("<省略>"), "抹掉了但没说抹掉了什么:{e}"); + assert!(e.contains(""), "抹掉了但没说抹掉了什么:{e}"); } diff --git a/crates/tw-gateway/tests/passthrough.rs b/crates/tw-gateway/tests/passthrough.rs index 141689e5..603d7c86 100644 --- a/crates/tw-gateway/tests/passthrough.rs +++ b/crates/tw-gateway/tests/passthrough.rs @@ -399,7 +399,7 @@ async fn an_unreachable_upstream_emits_a_failure_event_and_a_502() { assert_eq!(source, "upstream"); // 错误信息要能直接行动 assert!( - message.contains("base_url") || message.contains("代理"), + message.text.contains("endpoint address") || message.text.contains("proxy"), "{message}" ); } @@ -760,7 +760,7 @@ async fn everything_broken_still_tries_rather_than_refusing() { let msg = body["error"]["message"].as_str().unwrap(); // 错误里要能看出「试过谁」—— 用户能看见故障转移在替他工作, // 这是信任的来源。 - assert!(msg.contains("已尝试"), "{msg}"); + assert!(msg.contains("tried:"), "{msg}"); } /// 一个慢上游:每个请求要 `delay`,用来观察并发行为。 @@ -1601,7 +1601,12 @@ async fn a_health_check_works_before_any_upstream_is_configured() { .await .unwrap(); assert_ne!(real.status(), 200); - assert!(real.text().await.unwrap().contains("尚未配置任何上游")); + assert!( + real.text() + .await + .unwrap() + .contains("No upstream is configured") + ); } /// **错误必须用入站方言的原生格式返回。**一个 Anthropic 客户端 @@ -1812,7 +1817,7 @@ async fn a_stream_that_dies_midway_says_so_instead_of_just_stopping() { for _ in 0..6 { match tokio::time::timeout(Duration::from_secs(2), rx.recv()).await { Ok(Ok(tw_api::Event::RequestFailed { message, .. })) => { - assert!(message.contains("流中断"), "{message}"); + assert!(message.text.contains("stream broke"), "{message}"); saw_failed = true; break; } diff --git a/crates/tw-store/src/recorder.rs b/crates/tw-store/src/recorder.rs index 4062ac93..461fbef4 100644 --- a/crates/tw-store/src/recorder.rs +++ b/crates/tw-store/src/recorder.rs @@ -367,7 +367,7 @@ impl Recorder { *bytes, *duration_ms, *usage, - Ending::Failed(message), + Ending::Failed(&message.text), ), Event::LocallyAnswered { id, @@ -925,13 +925,17 @@ mod tests { r.on_event(&Event::RequestFailed { id: 1, source: "upstream".into(), - message: "连不上".into(), + message: tw_api::Msg { + code: "t.unreachable".into(), + args: Default::default(), + text: "cannot connect".into(), + }, bytes: None, duration_ms: None, usage: None, }); let row = r.db().get(1).unwrap().unwrap(); - assert_eq!(row.error.as_deref(), Some("连不上")); + assert_eq!(row.error.as_deref(), Some("cannot connect")); assert_eq!(r.db().summary(0, i64::MAX).unwrap().failed, 1); } @@ -1585,7 +1589,11 @@ mod failure_tests { Event::RequestFailed { id, source: "upstream".into(), - message: "流中断:上游断开了".into(), + message: tw_api::Msg { + code: "t.broke".into(), + args: Default::default(), + text: "the stream broke: the upstream disconnected".into(), + }, bytes: Some(312), duration_ms: Some(2_500), usage, @@ -1614,7 +1622,10 @@ mod failure_tests { r.on_event(&failed(1, partial())); let row = r.db().get(1).unwrap().unwrap(); - assert_eq!(row.error.as_deref(), Some("流中断:上游断开了")); + assert_eq!( + row.error.as_deref(), + Some("the stream broke: the upstream disconnected") + ); assert!(!row.cancelled); assert_eq!(row.status, Some(200), "状态码来自响应头那个事件"); assert_eq!(row.bytes, Some(312)); @@ -1655,7 +1666,11 @@ mod failure_tests { r.on_event(&Event::RequestFailed { id: 1, source: "rate_limited".into(), - message: "`up` 限流了".into(), + message: tw_api::Msg { + code: "t.limited".into(), + args: Default::default(), + text: "`up` rate-limited us".into(), + }, bytes: None, duration_ms: Some(20_000), usage: None, diff --git a/scripts/smoke.sh b/scripts/smoke.sh index 57313adc..19d21182 100755 --- a/scripts/smoke.sh +++ b/scripts/smoke.sh @@ -268,7 +268,7 @@ for _ in $(seq 1 20); do | python3 -c 'import sys, json rows = json.load(sys.stdin) r = rows[0] if rows else {} -good = ("已切断" in (r.get("error") or "") and r.get("input_tokens") == 2345 +good = ("was cut off" in (r.get("error") or "") and r.get("input_tokens") == 2345 and r.get("cost_micros") is not None and r.get("cost_estimated") is True) print("ok" if good else json.dumps(r, ensure_ascii=False, sort_keys=True))' 2>/dev/null) [ "$GOT" = "ok" ] && break