From 91a13536858dd4ecd0db8e5a2e7adac9f48672be Mon Sep 17 00:00:00 2001 From: fylorn <249551762+fylorn@users.noreply.github.com> Date: Wed, 23 Sep 2026 23:15:38 +0800 Subject: [PATCH] feat: give core's own error sentences their own codes Fourteen control-plane codes (and l1.io) were pure passthrough wrappers: the template was "{detail}" and the detail was the Display of some core error, so a translated UI still showed English. Each of those errors now carries its own coded Msg instead. - tw-yaml PatchError, tw-engine RouteError/MatchError, tw-pricing SheetError, tw-config CredentialError/StoreError/EditError/ ValidationError, tw-adopt PlanError/ForeignError/McpError and tw-control RefreshError get a msg() with one code per variant; their Display is that Msg's text, so the English is written once. - tw_config::Rejected carries a Msg: semantic errors speak with their own code, serde's words get a coded frame (stage and line). - ApplyError keeps each cause's Msg (Invalid/InUse/BadPath/Build carry one) instead of an English string, so route, group, key and resource validation reaches the UI with its own code. - l1 maps the common io::ErrorKinds to codes; l1.io with {detail} remains only for the rest. - Truly external text (SQLite, serde, reqwest, OS) keeps a detail arg inside a coded sentence. Removed codes: control.adopt_failed, control.bad_credential, control.bad_price_sheet, control.bad_rule, control.config_rejected, control.internal, control.listen.bad_bind, control.mcp_failed, control.mcp_target_unknown, control.pricing_refresh_failed, control.route_failed, control.upstream_call_failed. Co-Authored-By: Claude Opus 5.5 --- Cargo.lock | 3 + crates/tw-adopt/src/foreign.rs | 54 +++- crates/tw-adopt/src/mcp.rs | 56 +++- crates/tw-adopt/src/plan.rs | 146 +++++++++- crates/tw-config/src/credential.rs | 138 +++++++--- crates/tw-config/src/edit.rs | 73 ++++- crates/tw-config/src/lib.rs | 2 +- crates/tw-config/src/refs.rs | 2 +- crates/tw-config/src/reload.rs | 52 +++- crates/tw-config/src/store.rs | 35 ++- crates/tw-config/src/validate.rs | 425 +++++++++++++++++++++++++---- crates/tw-control/src/chatgpt.rs | 39 ++- crates/tw-control/src/clients.rs | 11 +- crates/tw-control/src/config.rs | 146 +++++++--- crates/tw-control/src/dryrun.rs | 21 +- crates/tw-control/src/keys.rs | 35 +-- crates/tw-control/src/lib.rs | 65 +++-- crates/tw-control/src/listen.rs | 10 +- crates/tw-control/src/pricing.rs | 133 ++++++--- crates/tw-control/src/replay.rs | 55 +--- crates/tw-control/src/resources.rs | 37 +-- crates/tw-control/src/routes.rs | 307 +++++++++++++++++---- crates/tw-control/src/security.rs | 2 +- crates/tw-control/src/zai.rs | 179 +++++++++--- crates/tw-control/tests/adopt.rs | 4 +- crates/tw-control/tests/listen.rs | 2 +- crates/tw-engine/Cargo.toml | 1 + crates/tw-engine/src/engine.rs | 125 +++++++-- crates/tw-engine/src/rule.rs | 36 ++- crates/tw-gateway/src/l1.rs | 124 +++++++-- crates/tw-pricing/Cargo.toml | 1 + crates/tw-pricing/src/sheet.rs | 104 ++++++- crates/tw-yaml/Cargo.toml | 1 + crates/tw-yaml/src/lib.rs | 93 ++++++- 34 files changed, 1996 insertions(+), 521 deletions(-) diff --git a/Cargo.lock b/Cargo.lock index f8bb136b..a660177c 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -2893,6 +2893,7 @@ dependencies = [ "thiserror", "tracing", "tw-dialect", + "tw-types", ] [[package]] @@ -2959,6 +2960,7 @@ dependencies = [ "serde_json", "serde_yaml_ng", "thiserror", + "tw-types", ] [[package]] @@ -3104,6 +3106,7 @@ dependencies = [ "saphyr-parser", "serde_yaml_ng", "thiserror", + "tw-types", ] [[package]] diff --git a/crates/tw-adopt/src/foreign.rs b/crates/tw-adopt/src/foreign.rs index 935446ae..4fa6c048 100644 --- a/crates/tw-adopt/src/foreign.rs +++ b/crates/tw-adopt/src/foreign.rs @@ -24,32 +24,66 @@ use std::path::{Path, PathBuf}; use thiserror::Error; use tw_types::{Msg, msg}; +/// 往别人的配置文件里写的时候,哪一道没过。 +/// +/// **英文只写一遍**:`Display` 就是 [`ForeignError::msg`] 的原句,界面拿码去翻。 #[derive(Debug, Error)] pub enum ForeignError { - #[error("{path} could not be read: {source}")] + #[error("{}", self.msg())] Read { path: PathBuf, source: std::io::Error, }, - #[error("{path} could not be written: {source}")] + #[error("{}", self.msg())] Write { path: PathBuf, source: std::io::Error, }, - #[error( - "{path} changed after it was confirmed, so nothing was written. Look at the change again" - )] + #[error("{}", self.msg())] ChangedUnderUs { path: PathBuf }, - #[error("the edited content did not pass its check, so nothing was written ({0})")] + /// 里面是解析器的原话,或者「和预期的改动对不上」那一句 + #[error("{}", self.msg())] VerifyFailed(String), - #[error( - "what was read back after writing is not what was expected; restored from the backup: {path}" - )] + #[error("{}", self.msg())] Readback { path: PathBuf }, - #[error("too many levels of symbolic link: {path}")] + #[error("{}", self.msg())] LinkLoop { path: PathBuf }, } +impl ForeignError { + /// 给人看的那句话,带码。`Read` / `Write` 的 `detail` 是系统的原话。 + pub fn msg(&self) -> Msg { + match self { + ForeignError::Read { path, source } => msg!( + "adopt.file.read_failed", path = path.display(), detail = source => + "{path} could not be read: {detail}" + ), + ForeignError::Write { path, source } => msg!( + "adopt.file.write_failed", path = path.display(), detail = source => + "{path} could not be written: {detail}" + ), + ForeignError::ChangedUnderUs { path } => msg!( + "adopt.file.changed", path = path.display() => + "{path} changed after it was confirmed, so nothing was written. Look at the \ + change again" + ), + ForeignError::VerifyFailed(d) => msg!( + "adopt.file.verify_failed", detail = d => + "the edited content did not pass its check, so nothing was written ({detail})" + ), + ForeignError::Readback { path } => msg!( + "adopt.file.readback_mismatch", path = path.display() => + "what was read back after writing is not what was expected; restored from the \ + backup: {path}" + ), + ForeignError::LinkLoop { path } => msg!( + "adopt.file.link_loop", path = path.display() => + "too many levels of symbolic link: {path}" + ), + } + } +} + /// 写完之后的交代。**每一项都要能在 UI 上说出来** —— 用户敢按「接管」 /// 的前提是相信能退回去,那就得让他看见退路在哪儿。 #[derive(Debug, Clone)] diff --git a/crates/tw-adopt/src/mcp.rs b/crates/tw-adopt/src/mcp.rs index a5bbff2e..acc515ff 100644 --- a/crates/tw-adopt/src/mcp.rs +++ b/crates/tw-adopt/src/mcp.rs @@ -11,26 +11,53 @@ use std::collections::BTreeMap; use std::path::{Path, PathBuf}; -use tw_types::Msg; +use tw_types::{Msg, msg}; use crate::clients::Format; use crate::foreign::{self, Applied, Change, ForeignError}; use crate::json::Val; +/// 搬 MCP server 时的失败。 +/// +/// **英文只写一遍**:`Display` 就是 [`McpError::msg`] 的原句,界面拿码去翻。 #[derive(Debug, thiserror::Error)] pub enum McpError { - #[error("{0} is not a client we know")] + #[error("{}", self.msg())] UnknownClient(String), - #[error("the MCP configuration of {client} could not be parsed, so nothing was changed: {msg}")] + #[error("{}", self.msg())] Parse { client: String, msg: String }, - #[error("{0}")] + #[error(transparent)] Write(#[from] ForeignError), - #[error("{client} has no MCP server named `{name}`")] + #[error("{}", self.msg())] NotThere { client: String, name: String }, - #[error( - "the MCP configuration format of {client} is unverified, so it is not written to ({why})" - )] - NotCopyable { client: String, why: String }, + /// 不能写的那个理由,带码。见 [`Target::why_not`] + #[error("{}", self.msg())] + NotCopyable { client: String, why: Msg }, +} + +impl McpError { + /// 给人看的那句话,带码。 + pub fn msg(&self) -> Msg { + match self { + McpError::UnknownClient(client) => msg!( + "adopt.mcp.unknown_client", client = client => + "{client} is not a client we know" + ), + McpError::Parse { client, msg } => msg!( + "adopt.mcp.parse_failed", client = client, detail = msg => + "the MCP configuration of {client} could not be parsed, so nothing was changed: \ + {detail}" + ), + McpError::Write(e) => e.msg(), + McpError::NotThere { client, name } => msg!( + "adopt.mcp.not_there", client = client, name = name => + "{client} has no MCP server named `{name}`" + ), + // **理由那半句本来就有自己的码**(`adopt.mcp.unverified_format` 那几条), + // 套进一句「格式未验证」里就又成了英文 —— 直接说理由 + McpError::NotCopyable { why, .. } => why.clone(), + } + } } /// 一个能被写入的 MCP 配置位置。 @@ -151,9 +178,14 @@ impl Target { } else { Err(McpError::NotCopyable { client: self.client.to_string(), - // 这一条是护栏:界面对不能写的目标根本不给按钮。 - // 英文原句就够了,控制面会把它当 detail 包进去 - why: self.why_not.map(|(_, t)| t.to_string()).unwrap_or_default(), + // 这一条是护栏:界面对不能写的目标根本不给按钮 + why: self.why_not().unwrap_or_else(|| { + msg!( + "adopt.mcp.not_copyable", client = self.client => + "the MCP configuration format of {client} is unverified, so it is not \ + written to" + ) + }), }) } } diff --git a/crates/tw-adopt/src/plan.rs b/crates/tw-adopt/src/plan.rs index 98873e5d..25a0b485 100644 --- a/crates/tw-adopt/src/plan.rs +++ b/crates/tw-adopt/src/plan.rs @@ -25,31 +25,64 @@ use crate::foreign::{self, Applied, Change, ForeignError}; use crate::json::Val; use crate::sentinel::{self, Original, SidecarRecord, Was}; +/// 接管或还原算不出来、落不了盘的原因。 +/// +/// **英文只写一遍**:`Display` 就是 [`PlanError::msg`] 的原句,界面拿码去翻。 #[derive(Debug, thiserror::Error)] pub enum PlanError { - #[error("the configuration of {client} could not be read: {source}")] + #[error("{}", self.msg())] Read { client: String, source: ForeignError, }, - #[error("the configuration of {client} could not be parsed, so nothing was changed: {msg}")] + #[error("{}", self.msg())] Parse { client: String, msg: String }, - #[error("{0}")] + #[error(transparent)] Write(#[from] ForeignError), - #[error("the record beside {path} belongs to {other}, not {client}, so nothing was changed")] + #[error("{}", self.msg())] ForeignSidecar { path: PathBuf, other: String, client: String, }, - #[error( - "there is no record for {client}, so there is nothing to restore from. To restore by hand, look at {path}" - )] + #[error("{}", self.msg())] NoRecord { client: String, path: PathBuf }, - #[error( - "the original value for {client} is a secret kept only in the full backup, and the backup {backup} is gone" - )] - SecretGone { client: String, backup: PathBuf }, +} + +impl PlanError { + /// 给人看的那句话,带码。 + pub fn msg(&self) -> Msg { + match self { + // **读不到的那个文件本身就是该客户端的配置**,所以直接说文件那一句: + // 两句套在一起(「X 的配置读不出来:某文件读不出来:…」)只是把同一件 + // 事说了两遍 + PlanError::Read { client, source } => match source { + ForeignError::Read { path, source } => msg!( + "adopt.plan.read_failed", client = client, path = path.display(), detail = source => + "the configuration of {client} could not be read: {path}: {detail}" + ), + other => other.msg(), + }, + PlanError::Parse { client, msg } => msg!( + "adopt.plan.parse_failed", client = client, detail = msg => + "the configuration of {client} could not be parsed, so nothing was changed: {detail}" + ), + PlanError::Write(e) => e.msg(), + PlanError::ForeignSidecar { + path, + other, + client, + } => msg!( + "adopt.plan.foreign_record", path = path.display(), other = other, client = client => + "the record beside {path} belongs to {other}, not {client}, so nothing was changed" + ), + PlanError::NoRecord { client, path } => msg!( + "adopt.plan.no_record", client = client, path = path.display() => + "there is no record for {client}, so there is nothing to restore from. To restore \ + by hand, look at {path}" + ), + } + } } /// 这次改动对某条路径做了什么。写回校验的参照物就是它们叠出来的。 @@ -623,3 +656,94 @@ fn rollback(a: &Applied) -> std::io::Result<()> { std::fs::write(&a.real, text) } } + +#[cfg(test)] +mod msg_codes { + use super::*; + use crate::mcp::McpError; + + #[test] + fn every_adopt_error_has_its_own_code() { + let p = || PathBuf::from("/h/.claude/settings.json"); + let io = || std::io::Error::other("denied"); + let foreign = || { + vec![ + ForeignError::Read { + path: p(), + source: io(), + }, + ForeignError::Write { + path: p(), + source: io(), + }, + ForeignError::ChangedUnderUs { path: p() }, + ForeignError::VerifyFailed("x".into()), + ForeignError::Readback { path: p() }, + ForeignError::LinkLoop { path: p() }, + ] + }; + let mut all: Vec<(Msg, String)> = foreign() + .into_iter() + .map(|e| (e.msg(), e.to_string())) + .collect(); + for e in [ + PlanError::Read { + client: "claude-code".into(), + source: ForeignError::Read { + path: p(), + source: io(), + }, + }, + PlanError::Parse { + client: "claude-code".into(), + msg: "x".into(), + }, + PlanError::ForeignSidecar { + path: p(), + other: "codex".into(), + client: "claude-code".into(), + }, + PlanError::NoRecord { + client: "claude-code".into(), + path: p(), + }, + ] { + all.push((e.msg(), e.to_string())); + } + for e in [ + McpError::UnknownClient("x".into()), + McpError::Parse { + client: "zed".into(), + msg: "x".into(), + }, + McpError::NotThere { + client: "zed".into(), + name: "fs".into(), + }, + ] { + all.push((e.msg(), e.to_string())); + } + let mut seen = std::collections::HashSet::new(); + for (m, display) in &all { + assert!(m.code.starts_with("adopt."), "{m:?}"); + assert!(!m.text.is_empty() && &m.text == display, "{m:?}"); + assert!(seen.insert(m.code.clone()), "码重复了:{}", m.code); + } + // 包着的那几层用里面那一句的码 + let w = PlanError::Write(ForeignError::LinkLoop { path: p() }); + assert_eq!(w.msg().code, "adopt.file.link_loop"); + let r = PlanError::Read { + client: "x".into(), + source: ForeignError::LinkLoop { path: p() }, + }; + assert_eq!(r.msg().code, "adopt.file.link_loop"); + // 不能写的理由本来就有码,直接说它 + let e = crate::mcp::target("zed").unwrap().why_not().unwrap(); + let m = McpError::NotCopyable { + client: "zed".into(), + why: e.clone(), + } + .msg(); + assert_eq!(m, e); + } +} diff --git a/crates/tw-config/src/credential.rs b/crates/tw-config/src/credential.rs index e665fdaa..de9bd5c5 100644 --- a/crates/tw-config/src/credential.rs +++ b/crates/tw-config/src/credential.rs @@ -20,6 +20,7 @@ use serde::{Deserialize, Deserializer, Serialize, Serializer}; use crate::{Protocol, Provider}; +use tw_types::{Msg, msg}; /// `headers` 里换成 OAuth access token 的占位符。 pub const ACCESS_TOKEN: &str = "{{access_token}}"; @@ -248,61 +249,134 @@ pub fn auth_header(protocol: Option) -> (&'static str, &'static str) { } /// 凭据写法上的问题。**每一条都指到具体的那一行**,而不是「凭据无效」。 +/// +/// **英文只写一遍**:`Display` 就是 [`CredentialError::msg`] 的原句,界面拿码去翻。 #[derive(Debug, Clone, PartialEq, Eq, thiserror::Error)] pub enum CredentialError { - #[error("the API key is empty")] + #[error("{}", self.msg())] EmptyKey, - #[error("key and oauth are alternatives; fill in one of them")] + #[error("{}", self.msg())] KeyAndOauth, - #[error("neither refresh nor endpoint of oauth can be empty")] + #[error("{}", self.msg())] EmptyOauth, - #[error("a Claude subscription sign-in is not supported here; use an Anthropic API key")] + #[error("{}", self.msg())] ClaudeSubscription, - #[error("the Google sign-in of Gemini CLI is not supported here; use a Gemini API key")] + #[error("{}", self.msg())] GoogleSubscription, - #[error("a ChatGPT account upstream takes only the credential obtained by signing in")] + #[error("{}", self.msg())] ChatgptWithoutLogin, - #[error( - "the `{0}` header says where a request came from; the gateway sends it truthfully and it cannot be set in the configuration" - )] + #[error("{}", self.msg())] IdentityHeader(String), - #[error("there can be at most {MAX_HEADERS} headers")] + #[error("{}", self.msg())] TooManyHeaders, - #[error( - "the header name `{0}` is not valid: letters, digits and - _ . ~ only, and at most {MAX_HEADER_NAME} characters" - )] + #[error("{}", self.msg())] BadHeaderName(String), - #[error("the `{0}` header is the gateway's to manage and cannot be set in the configuration")] + #[error("{}", self.msg())] ReservedHeader(String), - #[error("the `{0}` header appears twice (header names are case-insensitive)")] + #[error("{}", self.msg())] DuplicateHeader(String), - #[error( - "the value of the `{0}` header cannot contain a newline and is at most {MAX_HEADER_VALUE} characters" - )] + #[error("{}", self.msg())] BadHeaderValue(String), - #[error( - "{placeholder} in the `{name}` header is not recognized; only {{{{access_token}}}} and {{{{client}}}} are" - )] + #[error("{}", self.msg())] UnknownPlaceholder { name: String, placeholder: String }, - #[error( - "the `{0}` header uses {{{{access_token}}}}, and this upstream has no oauth configured" - )] + #[error("{}", self.msg())] TokenWithoutOauth(String), - #[error( - "a key is filled in, so the API key goes out in the `{0}` header; `{0}` cannot also be set among the headers" - )] + #[error("{}", self.msg())] KeyAndAuthHeader(String), - #[error( - "with oauth configured, the token goes out in the `{0}` header by default. To set that header yourself, mark where the token goes with {{{{access_token}}}}" - )] + #[error("{}", self.msg())] OauthAndAuthHeader(String), - #[error("an OAuth access token could not be obtained")] + #[error("{}", self.msg())] NoToken, /// 环境变量没设之类。存成文字:这个错误要能比较,而底下那个类型不能 - #[error("{0}")] + #[error("{}", self.msg())] Env(String), } +impl CredentialError { + /// 给人看的那句话,带码。 + pub fn msg(&self) -> Msg { + use CredentialError::*; + match self { + EmptyKey => msg!("config.credential.empty_key" => "the API key is empty"), + KeyAndOauth => msg!( + "config.credential.key_and_oauth" => + "key and oauth are alternatives; fill in one of them" + ), + EmptyOauth => msg!( + "config.credential.empty_oauth" => + "neither refresh nor endpoint of oauth can be empty" + ), + ClaudeSubscription => msg!( + "config.credential.claude_subscription" => + "a Claude subscription sign-in is not supported here; use an Anthropic API key" + ), + GoogleSubscription => msg!( + "config.credential.google_subscription" => + "the Google sign-in of Gemini CLI is not supported here; use a Gemini API key" + ), + ChatgptWithoutLogin => msg!( + "config.credential.chatgpt_without_login" => + "a ChatGPT account upstream takes only the credential obtained by signing in" + ), + IdentityHeader(h) => msg!( + "config.credential.identity_header", header = h => + "the `{header}` header says where a request came from; the gateway sends it \ + truthfully and it cannot be set in the configuration" + ), + TooManyHeaders => msg!( + "config.credential.too_many_headers", max = MAX_HEADERS => + "there can be at most {max} headers" + ), + BadHeaderName(h) => msg!( + "config.credential.bad_header_name", header = h, max = MAX_HEADER_NAME => + "the header name `{header}` is not valid: letters, digits and - _ . ~ only, and at \ + most {max} characters" + ), + ReservedHeader(h) => msg!( + "config.credential.reserved_header", header = h => + "the `{header}` header is the gateway's to manage and cannot be set in the \ + configuration" + ), + DuplicateHeader(h) => msg!( + "config.credential.duplicate_header", header = h => + "the `{header}` header appears twice (header names are case-insensitive)" + ), + BadHeaderValue(h) => msg!( + "config.credential.bad_header_value", header = h, max = MAX_HEADER_VALUE => + "the value of the `{header}` header cannot contain a newline and is at most {max} \ + characters" + ), + UnknownPlaceholder { name, placeholder } => msg!( + "config.credential.unknown_placeholder", header = name, placeholder = placeholder => + "{placeholder} in the `{header}` header is not recognized; only {{{{access_token}}}} \ + and {{{{client}}}} are" + ), + TokenWithoutOauth(h) => msg!( + "config.credential.token_without_oauth", header = h => + "the `{header}` header uses {{{{access_token}}}}, and this upstream has no oauth \ + configured" + ), + KeyAndAuthHeader(h) => msg!( + "config.credential.key_and_auth_header", header = h => + "a key is filled in, so the API key goes out in the `{header}` header; `{header}` \ + cannot also be set among the headers" + ), + OauthAndAuthHeader(h) => msg!( + "config.credential.oauth_and_auth_header", header = h => + "with oauth configured, the token goes out in the `{header}` header by default. To \ + set that header yourself, mark where the token goes with {{{{access_token}}}}" + ), + NoToken => msg!( + "config.credential.no_token" => + "an OAuth access token could not be obtained" + ), + // 只在转发时出现(展开 `${VAR}`),写法检查碰不到它。**底下那句已经 + // 是文字了**,这里只能原样带出去 + Env(d) => msg!("config.credential.env", detail = d => "{detail}"), + } + } +} + impl From for CredentialError { fn from(e: SecretResolveError) -> Self { CredentialError::Env(e.to_string()) diff --git a/crates/tw-config/src/edit.rs b/crates/tw-config/src/edit.rs index 2fbcbc9a..65bb4a20 100644 --- a/crates/tw-config/src/edit.rs +++ b/crates/tw-config/src/edit.rs @@ -18,25 +18,78 @@ //! 和写之前完全一样。对不上就不返回。 use serde_yaml_ng::{Mapping, Value}; +use tw_types::{Msg, msg}; use tw_yaml::{Put, Step}; +/// 按名字改一项时的失败。 +/// +/// **英文只写一遍**:`Display` 就是 [`EditError::msg`] 的原句,界面拿码去翻。 #[derive(Debug, thiserror::Error)] pub enum EditError { - #[error("there is already a {what} named `{name}`")] + /// `what` 是 [`Section::what`] 那个词(`upstream`、`price sheet`), + /// 界面按它查自己的词表 + #[error("{}", self.msg())] NameTaken { what: &'static str, name: String }, - #[error("there is no {what} named `{name}`")] + #[error("{}", self.msg())] NotFound { what: &'static str, name: String }, - #[error("{0}")] + #[error(transparent)] Yaml(#[from] tw_yaml::PatchError), - #[error("the configuration file could not be parsed: {0}")] + #[error("{}", self.msg())] Parse(String), + /// 值里有换行。**这一种是用户能填出来的**,所以单独一个码 + #[error("{}", self.msg())] + Multiline, + /// 交过来的那一项没有 `name` + #[error("{}", self.msg())] + Nameless { what: &'static str }, /// 渲染不出一个能安全写进去的值。 - #[error("{0}")] + #[error("{}", self.msg())] Unwritable(String), - #[error("the edited content is not what was expected ({0}), so nothing was written")] + #[error("{}", self.msg())] SelfCheck(String), } +impl EditError { + /// 给人看的那句话,带码。 + /// + /// `Parse`、`Unwritable`、`SelfCheck` 的 `detail` 是解析器或序列化器的 + /// 原话 —— 这三种都是「我们自己写坏了」,正常使用碰不到,句子说清是 + /// 哪一步就够了。 + pub fn msg(&self) -> Msg { + match self { + EditError::NameTaken { what, name } => msg!( + "config.edit.name_taken", what = what, name = name => + "there is already a {what} named `{name}`" + ), + EditError::NotFound { what, name } => msg!( + "config.edit.not_found", what = what, name = name => + "there is no {what} named `{name}`" + ), + EditError::Yaml(e) => e.msg(), + EditError::Parse(d) => msg!( + "config.edit.parse", detail = d => + "the configuration file could not be parsed: {detail}" + ), + EditError::Multiline => msg!( + "config.edit.multiline" => + "a value cannot contain a newline" + ), + EditError::Nameless { what } => msg!( + "config.edit.nameless", what = what => + "the {what} has no name" + ), + EditError::Unwritable(d) => msg!( + "config.edit.unwritable", detail = d => + "the value cannot be written into the configuration: {detail}" + ), + EditError::SelfCheck(d) => msg!( + "config.edit.self_check", detail = d => + "the edited content is not what was expected ({detail}), so nothing was written" + ), + } + } +} + /// 配置里的一段列表,以及它在错误信息里叫什么。 #[derive(Debug, Clone, Copy)] pub struct Section { @@ -107,7 +160,7 @@ pub fn upsert( let name = item .get("name") .and_then(Value::as_str) - .ok_or_else(|| EditError::Unwritable(format!("the {} has no name", section.what)))? + .ok_or(EditError::Nameless { what: section.what })? .to_string(); let taken = section.index_of(&doc, &name); let steps = section.steps(); @@ -245,9 +298,7 @@ fn render_block(v: &Value) -> Result { /// 内容的一部分 —— 这一层不去冒那个险。配置里本来也没有需要多行的字段。 fn reject_multiline(v: &Value) -> Result<(), EditError> { match v { - Value::String(s) if s.contains('\n') || s.contains('\r') => Err(EditError::Unwritable( - "a value cannot contain a newline".to_string(), - )), + Value::String(s) if s.contains('\n') || s.contains('\r') => Err(EditError::Multiline), Value::Mapping(m) => m.iter().try_for_each(|(k, v)| { reject_multiline(k)?; reject_multiline(v) @@ -471,7 +522,7 @@ providers: &map("name: x\ntype: http\naddr: \"a\\nb\"\n"), ) .unwrap_err(); - assert!(matches!(e, EditError::Unwritable(_)), "{e}"); + assert!(matches!(e, EditError::Multiline), "{e}"); } #[test] diff --git a/crates/tw-config/src/lib.rs b/crates/tw-config/src/lib.rs index 32f854fb..9701cfa9 100644 --- a/crates/tw-config/src/lib.rs +++ b/crates/tw-config/src/lib.rs @@ -839,7 +839,7 @@ pub fn patch_oauth_tokens( // 而用户下一次启动才撞上它(「先校验再写」同一条)。 let re = try_parse(&out).map_err(|r| RotateError::Broke { provider: provider.to_string(), - why: r.message, + why: r.message.text, })?; let ok = re .providers diff --git a/crates/tw-config/src/refs.rs b/crates/tw-config/src/refs.rs index 677f46a2..c53783ec 100644 --- a/crates/tw-config/src/refs.rs +++ b/crates/tw-config/src/refs.rs @@ -416,7 +416,7 @@ routes: // 静默退回默认价的话,算出来的钱看起来正常,而折扣从没生效过 let text = CFG.replace(" proxy: hk\n", " proxy: hk\n pricing: 没有这张\n"); let e = crate::try_parse(&text).unwrap_err(); - assert!(e.message.contains("没有这张"), "{}", e.message); + assert!(e.message.text.contains("没有这张"), "{}", e.message); } #[test] diff --git a/crates/tw-config/src/reload.rs b/crates/tw-config/src/reload.rs index 06cfe67c..0458bc88 100644 --- a/crates/tw-config/src/reload.rs +++ b/crates/tw-config/src/reload.rs @@ -17,6 +17,8 @@ //! 这个模块只负责 ①②③ 并把失败说清楚。④⑤ 归数据面,因为运行时对象 //! (provider 池、Client、规则树)是它的东西。 +use tw_types::{Msg, msg}; + use crate::{Config, ValidationError, validate}; /// 卡在哪一关。**分开是为了让用户知道该看哪儿**:语法错要看那一行, @@ -54,7 +56,13 @@ impl Stage { #[derive(Debug, Clone, PartialEq)] pub struct Rejected { pub stage: Stage, - pub message: String, + /// 为什么。语义错是带码的一句话;语法和字段错是 serde 的原话,码是 + /// [`UNPARSABLE`]、句子只有 `{detail}` —— 那句话我们翻不了,给人看时 + /// 由 [`Rejected::msg`] 在外面补上哪一关、哪一行。 + /// + /// **装箱**:它是 `try_parse` 的 `Err` 侧,而一条 `Msg` 有三个堆上的字段, + /// 不装箱的话成功那一路每次都要抬着这么大一块走。 + pub message: Box, /// 1 起。**只有语法和字段错误有行号** —— 语义错误是整份配置的 /// 问题,硬指一行只会误导。 pub line: Option, @@ -73,6 +81,34 @@ impl std::fmt::Display for Rejected { } } +/// serde 读不进来时 [`Rejected::message`] 的码。 +pub const UNPARSABLE: &str = "config.unparsable"; + +impl Rejected { + /// 给人看的那句话,带码。 + /// + /// **语义错直接就是那一句**:它说清了是哪个上游、哪条规则,前面再垫 + /// 一句「语义错误」只会把人要找的那半句挤到后面去。语法和字段错的 + /// 原话是 serde 的英文,能翻的只有外面那一层:哪一关、第几行。 + pub fn msg(&self) -> Msg { + if self.message.code != UNPARSABLE { + return (*self.message).clone(); + } + let stage = self.stage.slug(); + let detail = &self.message.text; + match self.line { + Some(line) => msg!( + "config.rejected_at", stage = stage, line = line, detail = detail => + "{stage} error (line {line}): {detail}" + ), + None => msg!( + "config.rejected", stage = stage, detail = detail => + "{stage} error: {detail}" + ), + } + } +} + /// 试着把一份文本当成配置读进来。 /// /// **成功了也只是「这份配置是好的」,不代表已经生效** —— 换入是调用方 @@ -92,7 +128,7 @@ pub fn try_parse(text: &str) -> Result { } else { Stage::Syntax }, - message: e.to_string(), + message: Box::new(msg!(UNPARSABLE, detail = e => "{detail}")), line, column: loc.as_ref().map(|l| l.column()), excerpt: line.and_then(|l| excerpt_of(text, l)), @@ -102,7 +138,7 @@ pub fn try_parse(text: &str) -> Result { if let Err(e) = validate(&cfg) { return Err(Rejected { stage: stage_of(&e), - message: e.to_string(), + message: Box::new(e.msg()), // 语义错误没有一个诚实的行号。**编一个出来比不给更糟** —— // 用户会盯着那一行看半天,而问题在别处。 line: None, @@ -179,7 +215,7 @@ mod tests { // serde 的「missing field `clients`」说不出下一步做什么。 let r = try_parse("version: 1\n").unwrap_err(); assert_eq!(r.stage, Stage::Semantics, "{r:?}"); - assert!(r.message.contains("generated on first start"), "{r:?}"); + assert!(r.message.text.contains("generated on first start"), "{r:?}"); } #[test] @@ -188,7 +224,7 @@ mod tests { let bad = "version: 1\nclients:\n - name: c\n kye: tw-k\n"; let r = try_parse(bad).unwrap_err(); assert_eq!(r.stage, Stage::Schema, "{r:?}"); - assert!(r.message.contains("kye"), "{r:?}"); + assert!(r.message.text.contains("kye"), "{r:?}"); assert_eq!(r.line, Some(4), "{r:?}"); } @@ -199,7 +235,7 @@ mod tests { let r = try_parse(bad).unwrap_err(); assert_eq!(r.stage, Stage::Semantics, "{r:?}"); assert!(r.line.is_none(), "语义错不该编行号:{r:?}"); - assert!(r.message.contains("appears twice"), "{r:?}"); + assert!(r.message.text.contains("appears twice"), "{r:?}"); } #[test] @@ -209,7 +245,7 @@ mod tests { let bad = "version: 1\nclients:\n - name: c\n key: tw-k\nproviders:\n - name: a\n base_url: https://x\n key: k\nroutes:\n - name: 默认\n rules:\n - name: r\n to: 已经删掉的组\n"; let r = try_parse(bad).unwrap_err(); assert_eq!(r.stage, Stage::Semantics); - assert!(r.message.contains("已经删掉的组"), "{r:?}"); + assert!(r.message.text.contains("已经删掉的组"), "{r:?}"); } #[test] @@ -217,7 +253,7 @@ mod tests { let bad = "version: 999\nclients:\n - name: c\n key: tw-k\n"; let r = try_parse(bad).unwrap_err(); assert_eq!(r.stage, Stage::Schema); - assert!(r.message.contains("Upgrade the app"), "{r:?}"); + assert!(r.message.text.contains("Upgrade the app"), "{r:?}"); } #[test] diff --git a/crates/tw-config/src/store.rs b/crates/tw-config/src/store.rs index 73841a26..89576aac 100644 --- a/crates/tw-config/src/store.rs +++ b/crates/tw-config/src/store.rs @@ -15,6 +15,8 @@ use std::path::{Path, PathBuf}; use std::time::SystemTime; +use tw_types::{Msg, msg}; + /// 一次写入之后文件长什么样。 /// /// 三个字段缺一不可:**只看 mtime 会漏判**(文件系统的时间精度不够, @@ -73,22 +75,45 @@ pub fn version_of(text: &str) -> String { format!("blake3:{}", &hash_of(text)[..12]) } +/// 读写配置文件时的失败。 +/// +/// **英文只写一遍**:`Display` 就是 [`StoreError::msg`] 的原句,界面拿码去翻。 #[derive(Debug, thiserror::Error)] pub enum StoreError { - #[error("{path} could not be read: {source}")] + #[error("{}", self.msg())] Io { path: PathBuf, source: std::io::Error, }, - #[error("{path} does not exist")] + #[error("{}", self.msg())] Missing { path: PathBuf }, /// **有人在我们读到和写下之间改了这个文件。** - #[error( - "the configuration file changed in the meantime (it is now {current}, and this edit is based on {expected}), so it was not overwritten. Look at the current content and try again" - )] + #[error("{}", self.msg())] Conflict { expected: String, current: String }, } +impl StoreError { + /// 给人看的那句话,带码。`Io` 的 `detail` 是系统的原话,只能原样带出去。 + pub fn msg(&self) -> Msg { + match self { + StoreError::Io { path, source } => msg!( + "config.store.read_failed", path = path.display(), detail = source => + "{path} could not be read: {detail}" + ), + StoreError::Missing { path } => msg!( + "config.store.missing", path = path.display() => + "{path} does not exist" + ), + StoreError::Conflict { expected, current } => msg!( + "config.store.conflict", expected = expected, current = current => + "the configuration file changed in the meantime (it is now {current}, and this \ + edit is based on {expected}), so it was not overwritten. Look at the current \ + content and try again" + ), + } + } +} + /// 一份读到内存里的配置文本,带着它的来源和版本。 /// /// **它记住的是原始文本,不是解析后的结构。**最小替换要在原文 diff --git a/crates/tw-config/src/validate.rs b/crates/tw-config/src/validate.rs index 8dc0c02c..4cff06e6 100644 --- a/crates/tw-config/src/validate.rs +++ b/crates/tw-config/src/validate.rs @@ -1,88 +1,196 @@ //! 语义校验。**解析成功不等于配置对**,而错误信息要能直接行动。 +use tw_types::{Msg, msg}; + use crate::{Config, SCHEMA_VERSION}; +/// 配置合起来不成立的地方。 +/// +/// **英文只写一遍**:`Display` 就是 [`ValidationError::msg`] 的原句,界面拿码去翻。 +/// `what` 这类参数是一个英文词(`upstream`、`redaction`),界面按它查自己的词表。 #[derive(Debug, thiserror::Error)] pub enum ValidationError { - #[error( - "the configuration is schema version {found}, and this twcore supports up to {supported}. Upgrade the app, or put the configuration back in the older form" - )] + #[error("{}", self.msg())] SchemaTooNew { found: u32, supported: u32 }, - #[error( - "the configuration has no gateway key under `clients`, so every request is refused. One is generated on first start" - )] + #[error("{}", self.msg())] NoClients, - #[error( - "the upstream name {0} appears twice. Routing rules refer to an upstream by name, so names have to be unique" - )] + #[error("{}", self.msg())] DuplicateProvider(String), - #[error("the gateway key name {0} appears twice")] + #[error("{}", self.msg())] DuplicateClient(String), - #[error( - "gateway keys `{0}` and `{1}` have the same value. The gateway tells clients apart by key, so the values have to be unique" - )] + #[error("{}", self.msg())] DuplicateKey(String, String), - #[error("default_key points at gateway key `{0}`, which does not exist")] + #[error("{}", self.msg())] MissingDefaultKey(String), - #[error( - "the default gateway key `{0}` is disabled. Every client that has not been pointed at the gateway explicitly uses it, and disabling it breaks all of them" - )] + #[error("{}", self.msg())] DisabledDefaultKey(String), - #[error( - "gateway keys `{0}` and `{1}` both say they were made for client `{2}`. A client has exactly one" - )] + #[error("{}", self.msg())] DuplicateClientKey(String, String, String), - #[error("the endpoint of upstream `{name}` is neither http nor https: {url}")] + #[error("{}", self.msg())] BadBaseUrl { name: String, url: String }, - #[error("the value of gateway key `{name}` is empty")] + #[error("{}", self.msg())] EmptyKey { name: String }, - #[error( - "gateway key `{name}` has max_concurrent: 0, so every request made with it would wait forever. Leave max_concurrent out for no limit" - )] + #[error("{}", self.msg())] ZeroConcurrency { name: String }, - #[error("the routing configuration is wrong: {0}")] + #[error("{}", self.msg())] Routing(#[from] tw_engine::RouteError), - #[error( - "`{0}` is the name of both an upstream and a group, so a rule's `to` cannot say which one it means. Rename one of them" - )] + #[error("{}", self.msg())] NameCollision(String), - #[error("`{entry}` in listen.gateway.allow_from is wrong: {reason}")] - BadCidr { entry: String, reason: String }, - #[error("the credential of upstream `{name}`: {source}")] + #[error("{}", self.msg())] + BadCidr { entry: String }, + #[error("{}", self.msg())] Credential { name: String, source: crate::CredentialError, }, - #[error("{0}")] + #[error(transparent)] Pricing(#[from] tw_pricing::SheetError), - #[error("upstream `{provider}` uses price sheet `{sheet}`, which does not exist")] + #[error("{}", self.msg())] UnknownPriceSheet { provider: String, sheet: String }, - #[error( - "the scope of upstream `{name}` (models_only) is empty, so it offers no model at all. To pause the upstream, disable it instead (disabled: true)" - )] + #[error("{}", self.msg())] EmptyModelsOnly { name: String }, - #[error("the scope of upstream `{name}` (models_only) has an empty entry")] + #[error("{}", self.msg())] BlankModelsOnly { name: String }, - #[error( - "the {what} name `{name}` starts with __, which is reserved for built-ins. Use a different name" - )] + #[error("{}", self.msg())] ReservedName { what: &'static str, name: String }, - #[error("a custom {what} rule has no name")] + #[error("{}", self.msg())] EmptyRuleName { what: &'static str }, - #[error("the custom {what} rule name `{name}` appears twice")] + #[error("{}", self.msg())] DuplicateRuleName { what: &'static str, name: String }, - #[error( - "the pattern of custom {what} rule `{name}` is not a valid regular expression: {detail}" - )] + #[error("{}", self.msg())] + EmptyRulePattern { what: &'static str, name: String }, + /// `detail` 是正则库的原话 + #[error("{}", self.msg())] BadRulePattern { what: &'static str, name: String, detail: String, }, - #[error("security.{guard} names `{id}`, which is not a built-in rule")] + #[error("{}", self.msg())] UnknownRule { guard: &'static str, id: String }, } +impl ValidationError { + /// 给人看的那句话,带码。 + pub fn msg(&self) -> Msg { + use ValidationError::*; + match self { + SchemaTooNew { found, supported } => msg!( + "config.schema_too_new", found = found, supported = supported => + "the configuration is schema version {found}, and this twcore supports up to \ + {supported}. Upgrade the app, or put the configuration back in the older form" + ), + NoClients => msg!( + "config.no_clients" => + "the configuration has no gateway key under `clients`, so every request is \ + refused. One is generated on first start" + ), + DuplicateProvider(name) => msg!( + "config.duplicate_upstream", upstream = name => + "the upstream name {upstream} appears twice. Routing rules refer to an upstream by \ + name, so names have to be unique" + ), + DuplicateClient(name) => msg!( + "config.duplicate_key_name", key = name => + "the gateway key name {key} appears twice" + ), + DuplicateKey(a, b) => msg!( + "config.duplicate_key_value", key = a, other = b => + "gateway keys `{key}` and `{other}` have the same value. The gateway tells clients \ + apart by key, so the values have to be unique" + ), + MissingDefaultKey(key) => msg!( + "config.default_key_missing", key = key => + "default_key points at gateway key `{key}`, which does not exist" + ), + DisabledDefaultKey(key) => msg!( + "config.default_key_disabled", key = key => + "the default gateway key `{key}` is disabled. Every client that has not been \ + pointed at the gateway explicitly uses it, and disabling it breaks all of them" + ), + DuplicateClientKey(a, b, client) => msg!( + "config.duplicate_client_key", key = a, other = b, client = client => + "gateway keys `{key}` and `{other}` both say they were made for client `{client}`. \ + A client has exactly one" + ), + BadBaseUrl { name, url } => msg!( + "config.bad_base_url", upstream = name, url = url => + "the endpoint of upstream `{upstream}` is neither http nor https: {url}" + ), + EmptyKey { name } => msg!( + "config.empty_key", key = name => + "the value of gateway key `{key}` is empty" + ), + ZeroConcurrency { name } => msg!( + "config.zero_concurrency", key = name => + "gateway key `{key}` has max_concurrent: 0, so every request made with it would \ + wait forever. Leave max_concurrent out for no limit" + ), + // 路由那几句本身就说清了是哪条规则、哪个组,前面不用再垫一句 + Routing(e) => e.msg(), + NameCollision(name) => msg!( + "config.name_collision", name = name => + "`{name}` is the name of both an upstream and a group, so a rule's `to` cannot say \ + which one it means. Rename one of them" + ), + BadCidr { entry } => msg!( + "config.bad_allow_from", entry = entry => + "`{entry}` in listen.gateway.allow_from is wrong: not a valid IP address or CIDR; \ + it is written as 192.168.0.0/16" + ), + // **码还是凭据那一条的码,多带一个 `upstream`。**同一句话在编辑上游的 + // 对话框里不用说是哪个上游(就是正在改的那个),在整份配置的校验里 + // 必须说 —— 为此给每一条再造一个「带上游名」的码,码表就翻了一倍 + Credential { name, source } => { + let mut m = source.msg(); + m.text = format!("the credential of upstream `{name}`: {}", m.text); + m.args.insert("upstream".into(), name.clone()); + m + } + Pricing(e) => e.msg(), + UnknownPriceSheet { provider, sheet } => msg!( + "config.unknown_price_sheet", upstream = provider, sheet = sheet => + "upstream `{upstream}` uses price sheet `{sheet}`, which does not exist" + ), + EmptyModelsOnly { name } => msg!( + "config.empty_models_only", upstream = name => + "the scope of upstream `{upstream}` (models_only) is empty, so it offers no model \ + at all. To pause the upstream, disable it instead (disabled: true)" + ), + BlankModelsOnly { name } => msg!( + "config.blank_models_only", upstream = name => + "the scope of upstream `{upstream}` (models_only) has an empty entry" + ), + ReservedName { what, name } => msg!( + "config.reserved_name", what = what, name = name => + "the {what} name `{name}` starts with __, which is reserved for built-ins. Use a \ + different name" + ), + EmptyRuleName { what } => msg!( + "config.rule_name_empty", what = what => + "a custom {what} rule has no name" + ), + DuplicateRuleName { what, name } => msg!( + "config.rule_name_taken", what = what, name = name => + "the custom {what} rule name `{name}` appears twice" + ), + EmptyRulePattern { what, name } => msg!( + "config.rule_pattern_empty", what = what, name = name => + "the pattern of custom {what} rule `{name}` is empty" + ), + BadRulePattern { what, name, detail } => msg!( + "config.rule_pattern_bad", what = what, name = name, detail = detail => + "the pattern of custom {what} rule `{name}` is not a valid regular expression: \ + {detail}" + ), + UnknownRule { guard, id } => msg!( + "config.unknown_rule", guard = guard, rule = id => + "security.{guard} names `{rule}`, which is not a built-in rule" + ), + } + } +} + pub fn validate(cfg: &Config) -> Result<(), ValidationError> { // 版本检查放在最前面:一个来自更新版本的配置,我们对它的任何 // 其他判断都不作数(「schema 太新」)。 @@ -229,8 +337,6 @@ pub fn validate(cfg: &Config) -> Result<(), ValidationError> { let _ = e; return Err(ValidationError::BadCidr { entry: entry.clone(), - reason: "not a valid IP address or CIDR; it is written as 192.168.0.0/16" - .to_string(), }); } } @@ -303,18 +409,20 @@ fn check_rules<'a>( name: name.to_string(), }); } - let bad = |detail: String| ValidationError::BadRulePattern { - what, - name: name.to_string(), - detail, - }; if pattern.is_empty() { - return Err(bad("the pattern is empty".to_string())); + return Err(ValidationError::EmptyRulePattern { + what, + name: name.to_string(), + }); } regex::RegexBuilder::new(pattern) .size_limit(1 << 20) .build() - .map_err(|e| bad(e.to_string()))?; + .map_err(|e| ValidationError::BadRulePattern { + what, + name: name.to_string(), + detail: e.to_string(), + })?; } Ok(()) } @@ -397,7 +505,7 @@ mod tests { #[test] fn a_key_written_as_a_mapping_says_what_to_write_instead() { let y = "version: 1\nclients:\n - name: c\n key: tw-k\nproviders:\n - name: p\n base_url: https://api.example.com\n key:\n whatever: 1\n"; - let e = crate::try_parse(y).unwrap_err().message; + let e = crate::try_parse(y).unwrap_err().message.text; assert!(e.contains("a string"), "没说该写成什么:{e}"); } @@ -405,7 +513,7 @@ mod tests { fn an_oauth_typo_lets_serde_say_which_field() { // **serde 自己的话比我们能补的任何一句都准** let y = "version: 1\nclients:\n - name: c\n key: tw-k\nproviders:\n - name: p\n base_url: https://api.example.com\n oauth:\n refresh: r\n endpoint: https://a/token\n refresh_befor: 5m\n"; - let e = crate::try_parse(y).unwrap_err().message; + let e = crate::try_parse(y).unwrap_err().message.text; assert!(e.contains("refresh_befor"), "{e}"); assert!(e.contains("refresh_before"), "没提示正确的拼法:{e}"); } @@ -413,7 +521,7 @@ mod tests { #[test] fn an_oauth_missing_a_required_field_says_which_one() { let y = "version: 1\nclients:\n - name: c\n key: tw-k\nproviders:\n - name: p\n base_url: https://api.example.com\n oauth:\n endpoint: https://a/token\n"; - let e = crate::try_parse(y).unwrap_err().message; + let e = crate::try_parse(y).unwrap_err().message.text; assert!(e.contains("refresh"), "{e}"); } @@ -624,3 +732,202 @@ mod tests { } } } + +#[cfg(test)] +mod msg_codes { + use super::*; + use crate::CredentialError; + use crate::edit::EditError; + use crate::store::StoreError; + + /// 码非空、带层名、英文就是 `Display`、同一个枚举里不重复。 + fn check(prefix: &str, all: &[(Msg, String)]) { + let mut seen = std::collections::HashSet::new(); + for (m, display) in all { + assert!(m.code.starts_with(prefix), "{m:?}"); + assert!(!m.text.is_empty(), "{m:?}"); + assert_eq!(&m.text, display, "{m:?}"); + assert!(seen.insert(m.code.clone()), "码重复了:{}", m.code); + } + } + + #[test] + fn every_credential_error_has_its_own_code() { + use CredentialError::*; + let all = [ + EmptyKey, + KeyAndOauth, + EmptyOauth, + ClaudeSubscription, + GoogleSubscription, + ChatgptWithoutLogin, + IdentityHeader("h".into()), + TooManyHeaders, + BadHeaderName("h".into()), + ReservedHeader("h".into()), + DuplicateHeader("h".into()), + BadHeaderValue("h".into()), + UnknownPlaceholder { + name: "h".into(), + placeholder: "{{x}}".into(), + }, + TokenWithoutOauth("h".into()), + KeyAndAuthHeader("h".into()), + OauthAndAuthHeader("h".into()), + NoToken, + Env("the environment variable X is not set".into()), + ]; + check( + "config.credential.", + &all.iter() + .map(|e| (e.msg(), e.to_string())) + .collect::>(), + ); + } + + #[test] + fn every_store_and_edit_error_has_its_own_code() { + let path = std::path::PathBuf::from("/x/config.yaml"); + let store = [ + StoreError::Io { + path: path.clone(), + source: std::io::Error::other("denied"), + }, + StoreError::Missing { path }, + StoreError::Conflict { + expected: "a".into(), + current: "b".into(), + }, + ]; + check( + "config.store.", + &store + .iter() + .map(|e| (e.msg(), e.to_string())) + .collect::>(), + ); + let edit = [ + EditError::NameTaken { + what: "proxy", + name: "hk".into(), + }, + EditError::NotFound { + what: "proxy", + name: "hk".into(), + }, + EditError::Parse("x".into()), + EditError::Multiline, + EditError::Nameless { what: "proxy" }, + EditError::Unwritable("x".into()), + EditError::SelfCheck("x".into()), + ]; + check( + "config.edit.", + &edit + .iter() + .map(|e| (e.msg(), e.to_string())) + .collect::>(), + ); + // 包着的那一层直接用它自己的码 + let e = EditError::Yaml(tw_yaml::PatchError::NotScalar("a".into())); + assert_eq!(e.msg().code, "yaml.not_scalar"); + } + + #[test] + fn every_validation_error_has_its_own_code() { + use ValidationError::*; + let all = [ + SchemaTooNew { + found: 9, + supported: 1, + }, + NoClients, + DuplicateProvider("a".into()), + DuplicateClient("k".into()), + DuplicateKey("k".into(), "j".into()), + MissingDefaultKey("k".into()), + DisabledDefaultKey("k".into()), + DuplicateClientKey("k".into(), "j".into(), "codex".into()), + BadBaseUrl { + name: "a".into(), + url: "ftp://x".into(), + }, + EmptyKey { name: "k".into() }, + ZeroConcurrency { name: "k".into() }, + NameCollision("a".into()), + BadCidr { entry: "x".into() }, + UnknownPriceSheet { + provider: "a".into(), + sheet: "s".into(), + }, + EmptyModelsOnly { name: "a".into() }, + BlankModelsOnly { name: "a".into() }, + ReservedName { + what: "upstream", + name: "__a".into(), + }, + EmptyRuleName { what: "redaction" }, + DuplicateRuleName { + what: "redaction", + name: "r".into(), + }, + EmptyRulePattern { + what: "redaction", + name: "r".into(), + }, + BadRulePattern { + what: "redaction", + name: "r".into(), + detail: "unclosed group".into(), + }, + UnknownRule { + guard: "redact", + id: "x".into(), + }, + ]; + check( + "config.", + &all.iter() + .map(|e| (e.msg(), e.to_string())) + .collect::>(), + ); + // 包着的那几层:码是里面那一句的,不是一个套话 + assert_eq!( + Routing(tw_engine::RouteError::EmptyGroup("g".into())) + .msg() + .code, + "engine.empty_group" + ); + assert_eq!( + Pricing(tw_pricing::SheetError::EmptyName).msg().code, + "pricing.sheet.empty_name" + ); + // 凭据那一条多带一个上游名,英文前面也补上 + let e = Credential { + name: "官方".into(), + source: CredentialError::EmptyKey, + }; + let m = e.msg(); + assert_eq!(m.code, "config.credential.empty_key"); + assert_eq!(m.arg("upstream"), "官方"); + assert_eq!(m.text, e.to_string()); + assert!(m.text.contains("官方"), "{m:?}"); + } + + #[test] + fn a_rejected_config_says_which_stage_and_line_around_serdes_words() { + // 语法错:serde 的原话翻不了,外面那一层(哪一关、第几行)带码 + let r = + crate::try_parse("version: 1\nclients:\n - name: \"c\n key: tw-k\n").unwrap_err(); + let m = r.msg(); + assert_eq!(m.code, "config.rejected_at", "{m:?}"); + assert_eq!(m.arg("stage"), "syntax"); + assert!( + !m.arg("line").is_empty() && !m.arg("detail").is_empty(), + "{m:?}" + ); + // 语义错:直接就是那一句 + let r = crate::try_parse("version: 1\n").unwrap_err(); + assert_eq!(r.msg().code, "config.no_clients"); + } +} diff --git a/crates/tw-control/src/chatgpt.rs b/crates/tw-control/src/chatgpt.rs index d8fef6ee..c48aa075 100644 --- a/crates/tw-control/src/chatgpt.rs +++ b/crates/tw-control/src/chatgpt.rs @@ -35,7 +35,7 @@ use tw_config::history::Origin; use tw_gateway::chatgpt; use crate::{ControlState, Fail, fail}; -use tw_types::msg; +use tw_types::{Msg, msg}; /// 登录要在多久之内完成。和 Codex 一样是 15 分钟 const LOGIN_TTL: Duration = Duration::from_secs(15 * 60); @@ -204,7 +204,7 @@ impl Want { return Err(fail( StatusCode::CONFLICT, msg!( - "control.name_taken_not_chatgpt", name = name => + "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." ), @@ -327,12 +327,8 @@ 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, - msg!("control.upstream_call_failed", detail = e => "{detail}"), - ) - })?; + let http = + client_for(s, &want.name, &want.proxy).map_err(|e| fail(StatusCode::BAD_GATEWAY, e))?; let asked = serde_json::json!({ "client_id": chatgpt::CLIENT_ID }); let resp = send( &http, @@ -366,7 +362,10 @@ async fn start_device( let code: DeviceCode = serde_json::from_str(&text).map_err(|e| { fail( StatusCode::BAD_GATEWAY, - msg!("control.upstream_call_failed", detail = e => "{detail}"), + msg!( + "control.device_code_unreadable", detail = e => + "The answer to the device code request could not be read: {detail}" + ), ) })?; let id = chatgpt::new_state(); @@ -540,12 +539,7 @@ 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, - msg!("control.internal", detail = e => "{detail}"), - ) - })?; + let g = s.chatgpt.current.lock().map_err(crate::internal)?; let c = g.as_ref().filter(|c| c.status.id == id).ok_or_else(|| { fail( StatusCode::NOT_FOUND, @@ -679,7 +673,7 @@ async fn exchange_and_save( redirect_uri: &str, ) -> Result<(String, Option), String> { let endpoints = &s.chatgpt.endpoints; - let http = client_for(s, name, proxy)?; + let http = client_for(s, name, proxy).map_err(|m| m.text)?; let tokens = chatgpt::exchange_code(&http, &endpoints.token, code, verifier, redirect_uri).await?; let account = chatgpt::account(&tokens.id_token); @@ -705,8 +699,10 @@ async fn exchange_and_save( if let Some(e) = existing && e.effective_protocol() != Some(Protocol::Chatgpt) { - return Err(crate::resources::invalid(format!( - "there is already an upstream named `{name}`, and it is not a ChatGPT account" + return Err(crate::resources::invalid(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 mut p = existing.cloned().unwrap_or_else(|| tw_config::Provider { @@ -733,7 +729,7 @@ async fn exchange_and_save( } p.headers = tw_config::Headers::new(headers); p.check_credential() - .map_err(|e| crate::resources::invalid(e.to_string()))?; + .map_err(|e| crate::resources::invalid(e.msg()))?; let current = existing.map(|_| name.as_str()); Ok(tw_config::edit::upsert( text, @@ -754,14 +750,15 @@ async fn exchange_and_save( } /// 按出站方式建一个客户端。**要代理才能访问 OpenAI 的用户,直连会卡在换 token 这一步** -fn client_for(s: &ControlState, name: &str, proxy: &str) -> Result { +fn client_for(s: &ControlState, name: &str, proxy: &str) -> Result { let route = tw_config::Provider { name: name.to_string(), base_url: s.chatgpt.endpoints.backend.clone(), proxy: proxy.to_string(), ..Default::default() }; - tw_gateway::client_for_provider(&s.config(), &route).map_err(|e| e.message().to_string()) + // 代理没定义、密码读不到这些,数据面那句自己带码 + tw_gateway::client_for_provider(&s.config(), &route).map_err(|e| e.detail) } fn announce( diff --git a/crates/tw-control/src/clients.rs b/crates/tw-control/src/clients.rs index b29e5632..f0b936b9 100644 --- a/crates/tw-control/src/clients.rs +++ b/crates/tw-control/src/clients.rs @@ -436,7 +436,7 @@ fn bad(e: plan::PlanError) -> Fail { plan::PlanError::ForeignSidecar { .. } => StatusCode::CONFLICT, _ => StatusCode::BAD_REQUEST, }; - fail(code, msg!("control.adopt_failed", detail = e => "{detail}")) + fail(code, e.msg()) } /// 落盘。**用户在 diff 上点过确认之后才该到这里。** @@ -484,12 +484,7 @@ pub async fn restore( // ---------------------------------------------------------------- MCP 矩阵 fn mcp_target(id: &str) -> Result { - tw_adopt::mcp::target(id).map_err(|e| { - fail( - StatusCode::NOT_FOUND, - msg!("control.mcp_target_unknown", detail = e => "{detail}"), - ) - }) + tw_adopt::mcp::target(id).map_err(|e| fail(StatusCode::NOT_FOUND, e.msg())) } fn mcp_err(e: tw_adopt::mcp::McpError) -> Fail { @@ -501,7 +496,7 @@ fn mcp_err(e: tw_adopt::mcp::McpError) -> Fail { tw_adopt::mcp::McpError::NotCopyable { .. } => StatusCode::NOT_IMPLEMENTED, _ => StatusCode::BAD_REQUEST, }; - fail(code, msg!("control.mcp_failed", detail = e => "{detail}")) + fail(code, e.msg()) } /// 能写和不能写的分别是哪些。 diff --git a/crates/tw-control/src/config.rs b/crates/tw-control/src/config.rs index 03ae87c8..17bf5459 100644 --- a/crates/tw-control/src/config.rs +++ b/crates/tw-control/src/config.rs @@ -11,6 +11,7 @@ use std::sync::Arc; use tokio::sync::Mutex; use tw_config::history::Origin; use tw_config::store::{self, Fingerprint}; +use tw_types::{Msg, msg}; /// 配置的唯一入口。**UI、CLI、文件监听都走它** —— 三条路各写一遍, /// 就会有两条忘了存历史、一条忘了防回环。 @@ -23,6 +24,11 @@ pub struct ConfigManager { seen: Mutex>, } +/// 一次配置改动没成的原因。 +/// +/// **每一种都带着自己那句带码的话**([`ApplyError::msg`]),控制面原样发给 +/// 界面。以前这里存的是拼好的英文,发出去时再整句塞进一个 `{detail}` +/// —— 界面拿到的码只说「改配置失败了」,真正的原因在一句它翻不了的英文里。 #[derive(Debug, thiserror::Error)] pub enum ApplyError { #[error(transparent)] @@ -30,23 +36,46 @@ pub enum ApplyError { /// 三道校验里的任意一道没过。**旧配置还在服务。** #[error("{0}")] Rejected(tw_config::Rejected), - /// 校验过了但运行时对象建不起来 —— 同样保持旧的。 + /// 校验过了但运行时对象建不起来 —— 同样保持旧的。里面是数据面说的那句 #[error("the configuration parses but cannot be applied: {0}")] - Build(String), + Build(Msg), /// patch 指的那个位置有问题。**和 Build 分开**:那句「配置能读但 /// 用不起来」会让人去查配置,而该查的是这次请求写的路径。 #[error("{0}")] - BadPath(String), - #[error( - "version mismatch: this edit is based on {base}, and the current version is {current}. Refresh and edit again" - )] + BadPath(Msg), + #[error("{}", self.msg())] Stale { base: String, current: String }, /// 按资源改(上游、代理、价目表)时的失败:名字撞了、找不到、值写不进去。 #[error(transparent)] Edit(#[from] tw_config::edit::EditError), + /// 交过来的东西本身写得不对(名字空着、凭据写法不对、规则缺值)。 + /// **和 `Edit` 分开**:那边是「配置现在不允许」,这边是「请求写错了」 + #[error("{0}")] + Invalid(Msg), /// 还有别的配置在引用它,删不掉。**消息里要说清是谁。** #[error("{0}")] - InUse(String), + InUse(Msg), +} + +impl ApplyError { + /// 给人看的那句话,带码。 + pub fn msg(&self) -> Msg { + match self { + ApplyError::Store(e) => e.msg(), + ApplyError::Rejected(r) => r.msg(), + // 数据面那句本身就说清了哪个上游、哪个代理,前面不再垫一句 + ApplyError::Build(m) + | ApplyError::BadPath(m) + | ApplyError::Invalid(m) + | ApplyError::InUse(m) => m.clone(), + ApplyError::Stale { base, current } => msg!( + "control.config_stale", base = base, current = current => + "version mismatch: this edit is based on {base}, and the current version is \ + {current}. Refresh and edit again" + ), + ApplyError::Edit(e) => e.msg(), + } + } } impl ConfigManager { @@ -100,7 +129,7 @@ impl ConfigManager { self.bus.emit(tw_api::Event::ConfigRejected { id: self.bus.next_id(), stage: r.stage.slug().to_string(), - message: r.message.clone(), + message: r.message.text.clone(), line: r.line, excerpt: r.excerpt.clone(), origin: origin.slug().to_string(), @@ -113,7 +142,7 @@ impl ConfigManager { })?; self.gateway .reload(cfg) - .map_err(|e| ApplyError::Build(e.message().to_string()))?; + .map_err(|e| ApplyError::Build(e.detail))?; // 存刚刚生效的这一版。加上写入路径在写之前存的那一次,去重 // 之后的效果是「每个存在过的版本各一条」,最新那条就是现在跑 // 着的 —— 于是「回到上一版」在列表上就是第二条,不用数。 @@ -197,7 +226,12 @@ impl ConfigManager { .iter() .rev() .find(|v| v.version == version || v.version.ends_with(version)) - .ok_or_else(|| ApplyError::BadPath(format!("the version history has no {version}")))?; + .ok_or_else(|| { + ApplyError::BadPath(msg!( + "control.no_such_version", version = version => + "the version history has no {version}" + )) + })?; let text = tw_config::history::read(target)?; let cur = self.current().ok(); // 回滚也走同一条写入路径,所以它同样会:校验、存历史、防回环。 @@ -253,12 +287,7 @@ 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, - tw_types::msg!("control.internal", detail = e => "{detail}"), - ) - })?; + let cur = s.cfg.current().map_err(crate::unreadable_config)?; let path = tw_yaml::path_at(&cur.text, q.offset.min(cur.text.len())); let mut out = tw_api::ConfigAt { section: None, @@ -292,8 +321,8 @@ pub struct AtQuery { /// /// 段落是数字时仍然当下标用:`/routes/0/to` 是合理的写法,因为规则的 /// 顺序本身就是它的语义(自上而下首个命中)。 -pub fn resolve_path(text: &str, pointer: &str) -> Result, String> { - let nodes = tw_yaml::nodes(text).map_err(|e| e.to_string())?; +pub fn resolve_path(text: &str, pointer: &str) -> Result, Msg> { + let nodes = tw_yaml::nodes(text).map_err(|e| e.msg())?; let mut out: Vec = Vec::new(); for seg in pointer.trim_matches('/').split('/') { if seg.is_empty() { @@ -329,8 +358,9 @@ pub fn resolve_path(text: &str, pointer: &str) -> Result, Str match idx { Some(i) => out.push(tw_yaml::Step::Index(i)), None => { - return Err(format!( - "{pointer} has no entry named `{seg}`. List entries are found by name, or by index." + return Err(msg!( + "control.patch.no_entry", path = pointer, name = seg => + "{path} has no entry named `{name}`. List entries are found by name, or by index." )); } } @@ -376,41 +406,38 @@ impl ConfigManager { // **`insert` 而不是 `set`。**配置里绝大多数字段是可选的、 // 默认不写的,只能改「用户碰巧写过」的字段,等于表单模式在 // 他最需要的时候是死的。已经写过的走 `set`,那是它的第一步。 - tw_yaml::insert(&text, &steps, &scalar).map_err(|e| { - ApplyError::BadPath(format!("{path} could not be changed: {e}")) - })? + // 改不动的原因(找不到、不是标量、在锚点里)那一句本身就 + // 带着路径,前面不再垫一句「改不了」 + tw_yaml::insert(&text, &steps, &scalar).map_err(bad_path)? } 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!("nothing could be added to {path}: {e}")) - })? + tw_yaml::append(&text, &steps, item).map_err(bad_path)? } tw_api::PatchOp::Remove { path } => { let steps = resolve_path(&text, path).map_err(ApplyError::BadPath)?; // 路径指向那一项,最后一步就是它在列表里的位置。 // **按名字解析、按下标删** —— 名字是用户写的,下标是 // 我们刚刚算出来的,中间没有任何一次用户可见的重排。 - let (last, parent) = steps.split_last().ok_or_else(|| { - ApplyError::BadPath(format!("{path} does not point at an entry of a list")) - })?; + let not_an_entry = || { + ApplyError::BadPath(msg!( + "control.patch.not_an_entry", path = path => + "{path} does not point at an entry of a list. A delete names the \ + entry, as in /clients/codex." + )) + }; + let (last, parent) = steps.split_last().ok_or_else(not_an_entry)?; let tw_yaml::Step::Index(i) = last else { - return Err(ApplyError::BadPath(format!( - "{path} does not point at an entry of a list. A delete names the entry, as in /clients/codex." - ))); + return Err(not_an_entry()); }; - tw_yaml::remove(&text, parent, *i).map_err(|e| { - ApplyError::BadPath(format!("{path} could not be deleted: {e}")) - })? + tw_yaml::remove(&text, parent, *i).map_err(bad_path)? } 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} could not be cleared: {e}")) - })? + tw_yaml::clear_seq(&text, &steps).map_err(bad_path)? } }; } @@ -418,6 +445,10 @@ impl ConfigManager { } } +fn bad_path(e: tw_yaml::PatchError) -> ApplyError { + ApplyError::BadPath(e.msg()) +} + #[cfg(test)] mod patch_seq_tests { use super::*; @@ -464,3 +495,42 @@ mod patch_seq_tests { assert!(resolve_path(CFG, "/clients/不存在").is_err()); } } + +#[cfg(test)] +mod msg_codes { + use super::*; + + /// **改配置失败时发出去的是原因自己的码**,不是一个装着英文的套话。 + #[test] + fn an_apply_error_speaks_with_the_code_of_its_cause() { + let stale = ApplyError::Stale { + base: "a".into(), + current: "b".into(), + }; + assert_eq!(stale.msg().code, "control.config_stale"); + assert_eq!(stale.msg().text, stale.to_string()); + let inner = msg!("t.x" => "x"); + for e in [ + ApplyError::Invalid(inner.clone()), + ApplyError::InUse(inner.clone()), + ApplyError::BadPath(inner.clone()), + ApplyError::Build(inner.clone()), + ] { + assert_eq!(e.msg(), inner); + } + let e = ApplyError::Edit(tw_config::edit::EditError::Multiline); + assert_eq!(e.msg().code, "config.edit.multiline"); + let e = ApplyError::Store(tw_config::StoreError::Missing { path: "/x".into() }); + assert_eq!(e.msg().code, "config.store.missing"); + let e = ApplyError::Rejected(tw_config::try_parse("version: 1\n").unwrap_err()); + assert_eq!(e.msg().code, "config.no_clients"); + } + + #[test] + fn a_patch_path_that_names_no_entry_has_its_own_code() { + let cfg = "version: 1\nclients:\n - name: c\n key: tw-k\n"; + let m = resolve_path(cfg, "/clients/不存在").unwrap_err(); + assert_eq!(m.code, "control.patch.no_entry"); + assert_eq!(m.arg("name"), "不存在"); + } +} diff --git a/crates/tw-control/src/dryrun.rs b/crates/tw-control/src/dryrun.rs index 51f321ea..aac91b96 100644 --- a/crates/tw-control/src/dryrun.rs +++ b/crates/tw-control/src/dryrun.rs @@ -96,18 +96,10 @@ pub async fn dry_run( .iter() .map(|r| crate::routes::to_rule(r, &cfg)) .collect::, _>>() - .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}"), - ) - })?; + .map_err(|e| fail(StatusCode::BAD_REQUEST, e))?; + engine + .check_rules(&draft) + .map_err(|e| fail(StatusCode::BAD_REQUEST, e.msg()))?; (d.name.clone(), draft.as_slice()) } else if let Some(name) = req.route.as_deref().filter(|n| !n.is_empty()) { let rules = engine @@ -309,10 +301,7 @@ pub async fn dry_run( out.outcome = "no_match".into(); } Err(e) => { - return Err(fail( - StatusCode::BAD_REQUEST, - msg!("control.route_failed", detail = e => "{detail}"), - )); + return Err(fail(StatusCode::BAD_REQUEST, e.msg())); } } Ok(Json(out)) diff --git a/crates/tw-control/src/keys.rs b/crates/tw-control/src/keys.rs index 6f98a563..b627a57f 100644 --- a/crates/tw-control/src/keys.rs +++ b/crates/tw-control/src/keys.rs @@ -166,11 +166,11 @@ async fn update( let c = to_client(&req.key, Some(existing), cfg)?; // 默认密钥停用 = 把所有手动配置的客户端一起关掉,而它们不在这一页上 if c.disabled && cfg.default_client().map(|d| d.name.as_str()) == Some(name.as_str()) { - return Err(ApplyError::InUse( + return Err(ApplyError::InUse(msg!( + "control.default_key_cannot_disable" => "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 = edit::upsert(text, CLIENTS, Some(&name), &crate::resources::mapping(&c)?)?; @@ -203,24 +203,25 @@ async fn delete_key( .find(|c| c.name == name) .ok_or_else(|| not_found(&name))?; if cfg.default_client().map(|d| d.name.as_str()) == Some(name.as_str()) { - return Err(ApplyError::InUse( + return Err(ApplyError::InUse(msg!( + "control.default_key_cannot_delete" => "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} is pointed at the gateway and has this key in its configuration. Restore \ - it before deleting the key." + return Err(ApplyError::InUse(msg!( + "control.key_used_by_client", client = label => + "{client} 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!( - "Gateway key `{name}` is still referenced by {}; drop those references before \ - deleting it.", - used.join(", ") + return Err(ApplyError::InUse(msg!( + "control.key_in_use", key = name, refs = used.join(", ") => + "Gateway key `{key}` is still referenced by {refs}; drop those references \ + before deleting it." ))); } Ok(edit::remove(text, CLIENTS, &name)?) @@ -243,9 +244,9 @@ async fn set_default( .find(|c| c.name == req.name) .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 + return Err(ApplyError::InUse(msg!( + "control.disabled_key_cannot_be_default", key = req.name => + "Gateway key `{key}` is disabled, so it cannot be the default key." ))); } // 默认值不写进文件 @@ -367,7 +368,7 @@ fn to_client( cfg: &tw_config::Config, ) -> Result { let name = crate::resources::checked_name(&input.name, "gateway key") - .map_err(|e| crate::resources::invalid(e.text))?; + .map_err(crate::resources::invalid)?; if let Some(r) = input .route .as_deref() diff --git a/crates/tw-control/src/lib.rs b/crates/tw-control/src/lib.rs index 343f49b4..bf36eba9 100644 --- a/crates/tw-control/src/lib.rs +++ b/crates/tw-control/src/lib.rs @@ -655,7 +655,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(internal)?; + let x = g.db().cost_buckets(from, to, bucket).map_err(records)?; Ok(Json(x)) } @@ -677,7 +677,7 @@ async fn cost_buckets_by( let x = g .db() .cost_buckets_by(q.dim, from, to, bucket) - .map_err(internal)?; + .map_err(records)?; Ok(Json(x)) } @@ -688,7 +688,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(internal)?; + let x = g.db().cost_by(q.dim, from, to).map_err(records)?; Ok(Json(x)) } @@ -700,7 +700,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(internal)?; + let x = g.db().summary(from, to).map_err(records)?; Ok(Json(tw_api::Summary { requests: x.requests, failed: x.failed, @@ -715,7 +715,7 @@ async fn summary( no_usage_requests: x.no_usage_requests, cache_saved_micros: x.cache_saved_micros, // **和安全日志数的是同一批**:概览上点开这个数,落到的日志就是这么多条 - security: g.db().security_counts(from, to).map_err(internal)?, + security: g.db().security_counts(from, to).map_err(records)?, pricing_date: s.gateway.pricing.load().table().date.clone(), })) } @@ -727,14 +727,14 @@ async fn history( ) -> Result>, Fail> { let store = need_store(&s)?; let g = store.lock().await; - let rows = g.db().recent(q.within(), q.limit()).map_err(internal)?; + let rows = g.db().recent(q.within(), q.limit()).map_err(records)?; // 这一段里的安全记录一次取完,按请求号挂上去。**流量页的徽标靠它**: // 以前徽标只来自实时事件,关窗再开就没了 let mut security = match ( rows.iter().map(|r| r.id).min(), rows.iter().map(|r| r.id).max(), ) { - (Some(from), Some(to)) => g.db().security_of_requests(from, to).map_err(internal)?, + (Some(from), Some(to)) => g.db().security_of_requests(from, to).map_err(records)?, _ => Default::default(), }; Ok(Json( @@ -754,7 +754,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(internal)?; + let xs = g.db().latency_by_model(from, to).map_err(records)?; Ok(Json( xs.into_iter() .map(|l| tw_api::LatencyView { @@ -927,7 +927,7 @@ async fn request_detail( let g = store.lock().await; // **还在跑的也答。**记录要等结局才落库,而用户点开的往往正是那个跑了很久的 // 请求:给到目前为止知道的,标着还在跑 - let (row, in_flight) = match g.db().get(id).map_err(internal)? { + let (row, in_flight) = match g.db().get(id).map_err(records)? { Some(row) => (row, false), None => { let row = u64::try_from(id) @@ -959,7 +959,7 @@ async fn request_detail( let security = g .db() .security_of_requests(id, id) - .map_err(internal)? + .map_err(records)? .remove(&id) .unwrap_or_default(); let detail = tw_api::RequestDetail { @@ -1008,7 +1008,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(internal)?; + let xs = g.db().latency_by_provider(from, to).map_err(records)?; Ok(Json( xs.into_iter() .map(|l| tw_api::LatencyView { @@ -1220,7 +1220,7 @@ impl ListQuery { /// 当前配置的原文。**文本模式直接显示它。** async fn get_config(State(s): State) -> Result, Fail> { - let c = s.cfg.current().map_err(internal)?; + let c = s.cfg.current().map_err(unreadable_config)?; Ok(Json(tw_api::ConfigText { path: c.path.display().to_string(), version: c.version(), @@ -1265,7 +1265,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(internal)?; + let all = tw_config::history::list(s.config_path()).map_err(unreadable_config)?; let now = s.cfg.current().map(|c| c.version()).unwrap_or_default(); // **新的在前。**用户找的几乎总是最近那几版。 Ok(Json( @@ -1301,17 +1301,38 @@ pub(crate) fn fail(code: StatusCode, detail: Msg) -> Fail { (code, Json(detail)) } -/// 内部错误:数据库读不了、序列化不了之类。 +/// 内部错误:锁坏了、序列化不了之类 —— **正常使用碰不到的那一类**。 /// -/// **这一类只有一个码。**界面对它们能说的只有同一句话(「这一步没做成」), -/// 真正有用的是 `detail` 里那句原话,而那句话是给看日志的人读的。 +/// 界面对它们能说的只有同一句话(「网关内部出了问题」),真正有用的是 +/// `detail` 里那句原话,而那句话是给看日志的人读的。 pub(crate) fn internal(e: impl std::fmt::Display) -> Fail { fail( StatusCode::INTERNAL_SERVER_ERROR, - msg!("control.internal", detail = e => "{detail}"), + msg!( + "control.internal_error", detail = e => + "Something went wrong inside the gateway: {detail}" + ), + ) +} + +/// 请求记录的库读不了。**和 [`internal`] 分开**:这一类用户看得见后果 +/// (流量页空着),说清是记录读不出来,比一句「内部错误」有用。`detail` +/// 是 SQLite 的原话。 +pub(crate) fn records(e: tw_store::db::DbError) -> Fail { + fail( + StatusCode::INTERNAL_SERVER_ERROR, + msg!( + "control.records_unreadable", detail = e => + "The request records could not be read: {detail}" + ), ) } +/// 配置文件读不了(不存在、没权限)。那句话自己带码。 +pub(crate) fn unreadable_config(e: tw_config::StoreError) -> Fail { + fail(StatusCode::INTERNAL_SERVER_ERROR, e.msg()) +} + /// 配置里没有这个名字的上游。 pub(crate) fn no_such_upstream(name: &str) -> Fail { fail( @@ -1340,16 +1361,16 @@ pub(crate) fn apply_fail(e: ApplyError) -> Fail { ApplyError::Rejected(_) | ApplyError::Build(_) | ApplyError::BadPath(_) - | ApplyError::Edit(EditError::Unwritable(_)) + | ApplyError::Invalid(_) + | ApplyError::Edit( + EditError::Unwritable(_) | EditError::Multiline | EditError::Nameless { .. }, + ) | ApplyError::Edit(EditError::Yaml(_)) => StatusCode::BAD_REQUEST, ApplyError::Edit(EditError::Parse(_) | EditError::SelfCheck(_)) | ApplyError::Store(_) => { StatusCode::INTERNAL_SERVER_ERROR } }; - fail( - code, - msg!("control.config_rejected", detail = e => "{detail}"), - ) + fail(code, e.msg()) } fn session_view(s: &tw_store::db::SessionRow) -> tw_api::SessionView { diff --git a/crates/tw-control/src/listen.rs b/crates/tw-control/src/listen.rs index 1d46b899..5ece7e01 100644 --- a/crates/tw-control/src/listen.rs +++ b/crates/tw-control/src/listen.rs @@ -31,10 +31,16 @@ async fn save( // `bind` 的写法和配置文件里一样,按同一套规则读 —— 界面和手写的 // 配置不该有两种说法 let bind: tw_config::Bind = - serde_yaml_ng::from_value(Value::String(req.bind.trim().to_string())).map_err(|e| { + serde_yaml_ng::from_value(Value::String(req.bind.trim().to_string())).map_err(|_| { fail( StatusCode::BAD_REQUEST, - msg!("control.listen.bad_bind", detail = e => "{detail}"), + // 交进来的是一个字符串,**读不成 `Bind` 只有一种可能**:四种写法 + // 都不是。那句话是 `Bind` 自己的 serde 报错,这里照着说一遍、带上码 + msg!( + "control.listen.bind_invalid", bind = req.bind.trim() => + "bind takes loopback, all, the name of an interface such as en0, or an \ + address such as 192.168.1.5; it reads {bind}" + ), ) })?; if req.port == 0 { diff --git a/crates/tw-control/src/pricing.rs b/crates/tw-control/src/pricing.rs index a0fe379c..e1f6d835 100644 --- a/crates/tw-control/src/pricing.rs +++ b/crates/tw-control/src/pricing.rs @@ -170,16 +170,59 @@ struct Attempt { error: Option, } +/// 刷新默认价目表没成。 +/// +/// **英文只写一遍**:`Display` 就是 [`RefreshError::msg`] 的原句(它也是价目 +/// 页上「上次刷新失败」那一行),界面拿码去翻。`detail` 都是网络库、JSON +/// 解析器或文件系统的原话。 #[derive(Debug, thiserror::Error)] pub enum RefreshError { - #[error("{0}")] - Fetch(String), - #[error("what was downloaded is not a price data set: {0}")] + #[error("{}", self.msg())] + Unreachable(String), + #[error("{}", self.msg())] + Status(u16), + #[error("{}", self.msg())] + BrokeOff(String), + #[error("{}", self.msg())] + TooLarge { mb: usize }, + #[error("{}", self.msg())] Dataset(String), - #[error("the price sheet could not be saved: {0}")] + #[error("{}", self.msg())] Save(String), } +impl RefreshError { + /// 给人看的那句话,带码。 + pub fn msg(&self) -> Msg { + match self { + RefreshError::Unreachable(d) => msg!( + "control.pricing.unreachable", detail = d => + "the price data source could not be reached: {detail}" + ), + RefreshError::Status(status) => msg!( + "control.pricing.status", status = status => + "the price data source answered HTTP {status}" + ), + RefreshError::BrokeOff(d) => msg!( + "control.pricing.broke_off", detail = d => + "the download broke off: {detail}" + ), + RefreshError::TooLarge { mb } => msg!( + "control.pricing.too_large", mb = mb => + "what was downloaded is not a price data set: the file is over {mb} MB" + ), + RefreshError::Dataset(d) => msg!( + "control.pricing.not_a_dataset", detail = d => + "what was downloaded is not a price data set: {detail}" + ), + RefreshError::Save(d) => msg!( + "control.pricing.save_failed", detail = d => + "the price sheet could not be saved: {detail}" + ), + } + } +} + impl Default for Updater { fn default() -> Self { Self::new(tw_pricing::UPDATE_URL, Schedule::default()) @@ -278,29 +321,20 @@ async fn fetch(http: &reqwest::Client, url: &str) -> Result, RefreshErro .timeout(FETCH_TIMEOUT) .send() .await - .map_err(|e| { - RefreshError::Fetch(format!( - "the price data source could not be reached: {}", - chain(&e) - )) - })?; + .map_err(|e| RefreshError::Unreachable(chain(&e)))?; if !resp.status().is_success() { - return Err(RefreshError::Fetch(format!( - "the price data source answered HTTP {}", - resp.status().as_u16() - ))); + return Err(RefreshError::Status(resp.status().as_u16())); } let mut raw = Vec::new(); while let Some(chunk) = resp .chunk() .await - .map_err(|e| RefreshError::Fetch(format!("the download broke off: {}", chain(&e))))? + .map_err(|e| RefreshError::BrokeOff(chain(&e)))? { if raw.len() + chunk.len() > MAX_DATASET { - return Err(RefreshError::Dataset(format!( - "the file is over {} MB", - MAX_DATASET / 1024 / 1024 - ))); + return Err(RefreshError::TooLarge { + mb: MAX_DATASET / 1024 / 1024, + }); } raw.extend_from_slice(&chunk); } @@ -308,8 +342,13 @@ async fn fetch(http: &reqwest::Client, url: &str) -> Result, RefreshErro } fn apply(s: &ControlState, raw: &[u8]) -> Result { - let table = tw_pricing::Table::fetched(raw, local_date(SystemTime::now())) - .map_err(|e| RefreshError::Dataset(e.to_string()))?; + // 解析器那句外面还套着一层「价格数据解析不了」,和这里要说的是同一件事, + // 只取里面那句原话 + let table = tw_pricing::Table::fetched(raw, local_date(SystemTime::now())).map_err(|e| { + RefreshError::Dataset(match e { + tw_pricing::PricingError::Dataset(d) | tw_pricing::PricingError::Snapshot(d) => d, + }) + })?; // 解析成功就一定是 UTF-8(JSON 只能是) let text = std::str::from_utf8(raw).map_err(|e| RefreshError::Dataset(e.to_string()))?; tw_config::store::write_atomic(&data_path(s.config_path()), text) @@ -371,10 +410,7 @@ async fn refresh_now( RefreshError::Save(_) => StatusCode::INTERNAL_SERVER_ERROR, _ => StatusCode::BAD_GATEWAY, }; - fail( - code, - msg!("control.pricing_refresh_failed", detail = e => "{detail}"), - ) + fail(code, e.msg()) })?; Ok(Json(tw_api::PricingRefreshed { status: pricing_status(&s).await, @@ -431,12 +467,7 @@ async fn query( (loaded, Some(name)) } tw_api::SheetRef::Draft { sheet } => { - let def = sheet_def(&sheet).map_err(|e| { - fail( - StatusCode::BAD_REQUEST, - msg!("control.bad_price_sheet", detail = e => "{detail}"), - ) - })?; + let def = sheet_def(&sheet).map_err(|e| fail(StatusCode::BAD_REQUEST, e))?; let name = def.name.clone(); (Arc::new(loaded.with_draft(def)), Some(name)) } @@ -535,7 +566,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(|e| invalid(e.text))?; + let def = sheet_def(&req.sheet).map_err(invalid)?; 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)?; @@ -555,7 +586,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(|e| invalid(e.text))?; + let def = sheet_def(&req.sheet).map_err(invalid)?; let mut out = edit::upsert(text, edit::PRICE_SHEETS, Some(&name), &mapping(&def)?)?; if def.name != name { // **和那一张在同一个版本里改** —— 分两次写的话,中间那一版的 @@ -582,9 +613,10 @@ async fn delete_sheet( .transform(q.base_version.as_deref(), Origin::Ui, |text, cfg| { let users = refs::sheet_users(cfg, &name); if !users.is_empty() { - return Err(ApplyError::InUse(format!( - "Price sheet `{name}` is still used by upstream {}; unlink those before deleting it.", - quoted(&users) + return Err(ApplyError::InUse(msg!( + "control.sheet_in_use", sheet = name, upstreams = quoted(&users) => + "Price sheet `{sheet}` is still used by upstream {upstreams}; unlink those \ + before deleting it." ))); } Ok(edit::remove(text, edit::PRICE_SHEETS, &name)?) @@ -657,8 +689,7 @@ fn sheet_def(input: &tw_api::PriceSheetInput) -> Result "{detail}"))?; + def.validate().map_err(|e| e.msg())?; Ok(def) } @@ -738,8 +769,32 @@ mod tests { let tomorrow = now + Duration::from_secs(24 * 3600 + 1); assert!(u.due(&config, tomorrow)); // 那时刷新失败了:一小时之内不再试 - u.record(&Err(RefreshError::Fetch("离线".into())), tomorrow); + u.record(&Err(RefreshError::Unreachable("离线".into())), tomorrow); assert!(!u.due(&config, tomorrow + Duration::from_secs(60))); assert!(u.due(&config, tomorrow + Duration::from_secs(3601))); } } + +#[cfg(test)] +mod msg_codes { + use super::*; + + #[test] + fn every_refresh_error_has_its_own_code() { + let all = [ + RefreshError::Unreachable("x".into()), + RefreshError::Status(503), + RefreshError::BrokeOff("x".into()), + RefreshError::TooLarge { mb: 16 }, + RefreshError::Dataset("x".into()), + RefreshError::Save("x".into()), + ]; + let mut seen = std::collections::HashSet::new(); + for e in &all { + let m = e.msg(); + assert!(m.code.starts_with("control.pricing."), "{m:?}"); + assert!(!m.text.is_empty() && m.text == e.to_string(), "{m:?}"); + assert!(seen.insert(m.code.clone()), "码重复了:{}", m.code); + } + } +} diff --git a/crates/tw-control/src/replay.rs b/crates/tw-control/src/replay.rs index 0c0d22e7..275c8f1b 100644 --- a/crates/tw-control/src/replay.rs +++ b/crates/tw-control/src/replay.rs @@ -42,21 +42,12 @@ fn stored_body( g: &tw_store::Recorder, id: i64, ) -> Result<(tw_store::db::RequestRow, Vec), Fail> { - let row = g - .db() - .get(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 row = g.db().get(id).map_err(crate::records)?.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) @@ -212,11 +203,9 @@ 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, - msg!("control.upstream_call_failed", detail = why.message() => "{detail}"), - ) + fail(StatusCode::BAD_GATEWAY, why.detail) })?; let status = resp.status().as_u16(); @@ -263,21 +252,12 @@ pub async fn fixture( ) })?; let g = store.lock().await; - let row = g - .db() - .get(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 row = g.db().get(id).map_err(crate::records)?.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) @@ -332,10 +312,5 @@ pub async fn fixture( body: resp, }, ); - serde_yaml_ng::to_string(&f).map_err(|e| { - fail( - StatusCode::INTERNAL_SERVER_ERROR, - msg!("control.internal", detail = e => "{detail}"), - ) - }) + serde_yaml_ng::to_string(&f).map_err(crate::internal) } diff --git a/crates/tw-control/src/resources.rs b/crates/tw-control/src/resources.rs index 52119d4c..8b6bacb1 100644 --- a/crates/tw-control/src/resources.rs +++ b/crates/tw-control/src/resources.rs @@ -52,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(|e| invalid(e.text))?; + let p = to_provider(&req.provider, None).map_err(invalid)?; Ok(edit::upsert(text, edit::PROVIDERS, None, &mapping(&p)?)?) }) .await @@ -73,7 +73,7 @@ async fn update_provider( .iter() .find(|p| p.name == name) .ok_or_else(|| not_found("upstream", &name))?; - let p = to_provider(&req.provider, Some(existing)).map_err(|e| invalid(e.text))?; + let p = to_provider(&req.provider, Some(existing)).map_err(invalid)?; let mut out = edit::upsert(text, edit::PROVIDERS, Some(&name), &mapping(&p)?)?; if p.name != name { // **和那一项在同一个版本里改** —— 分两次写的话,中间那一版 @@ -100,9 +100,10 @@ async fn delete_provider( .transform(q.base_version.as_deref(), Origin::Ui, |text, cfg| { let used = refs::provider_refs(cfg, &name); if !used.is_empty() { - return Err(ApplyError::InUse(format!( - "Upstream `{name}` is still referenced by {}; drop those references before deleting it.", - describe(&used) + return Err(ApplyError::InUse(msg!( + "control.upstream_in_use", upstream = &name, refs = describe(&used) => + "Upstream `{upstream}` is still referenced by {refs}; drop those references \ + before deleting it." ))); } login = chatgpt_login(cfg, &name, &s.chatgpt.endpoints.token); @@ -425,9 +426,7 @@ fn to_provider( }; // **保存和检测之前就说清楚凭据写法哪儿不对**,而不是等整份配置校验时 // 报一条指着 YAML 的错误 - provider - .check_credential() - .map_err(|e| msg!("control.bad_credential", detail = e => "{detail}"))?; + provider.check_credential().map_err(|e| e.msg())?; Ok(provider) } @@ -440,7 +439,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(|e| invalid(e.text))?; + let px = to_proxy(&req.proxy, None).map_err(invalid)?; Ok(edit::upsert(text, edit::PROXIES, None, &mapping(&px)?)?) }) .await @@ -461,7 +460,7 @@ async fn update_proxy( .iter() .find(|p| p.name == name) .ok_or_else(|| not_found("proxy", &name))?; - let px = to_proxy(&req.proxy, Some(existing)).map_err(|e| invalid(e.text))?; + let px = to_proxy(&req.proxy, Some(existing)).map_err(invalid)?; 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)?; @@ -483,9 +482,10 @@ async fn delete_proxy( .transform(q.base_version.as_deref(), Origin::Ui, |text, cfg| { let users = refs::proxy_users(cfg, &name); if !users.is_empty() { - return Err(ApplyError::InUse(format!( - "Proxy `{name}` is still used by upstream {}; unlink those before deleting it.", - quoted(&users) + return Err(ApplyError::InUse(msg!( + "control.proxy_in_use", proxy = name, upstreams = quoted(&users) => + "Proxy `{proxy}` is still used by upstream {upstreams}; unlink those before \ + deleting it." ))); } Ok(edit::remove(text, edit::PROXIES, &name)?) @@ -597,16 +597,19 @@ fn slug(what: &'static str, v: &str) -> Result(v: &T) -> Result { + let unwritable = |d: String| ApplyError::Edit(EditError::Unwritable(d)); match serde_yaml_ng::to_value(v) { Ok(Value::Mapping(m)) => Ok(m), - Ok(_) => Err(invalid("it does not serialize to a mapping".to_string())), - Err(e) => Err(invalid(e.to_string())), + Ok(_) => Err(unwritable("it does not serialize to a mapping".to_string())), + Err(e) => Err(unwritable(e.to_string())), } } -pub(crate) fn invalid(msg: String) -> ApplyError { - ApplyError::Edit(EditError::Unwritable(msg)) +/// 交过来的东西写得不对。那句话自己带码,原样发给界面 +pub(crate) fn invalid(m: Msg) -> ApplyError { + ApplyError::Invalid(m) } pub(crate) fn not_found(what: &'static str, name: &str) -> ApplyError { diff --git a/crates/tw-control/src/routes.rs b/crates/tw-control/src/routes.rs index 08fada5c..e6e0da03 100644 --- a/crates/tw-control/src/routes.rs +++ b/crates/tw-control/src/routes.rs @@ -23,6 +23,7 @@ use tw_config::history::Origin; use tw_config::refs; use tw_engine::rule::{OneOrMany, When}; use tw_engine::{Group, GroupType, RouteSet, Rule, SetAction}; +use tw_types::{Msg, msg}; use tw_yaml::Step; use crate::resources::{checked_name, invalid, mapping}; @@ -110,9 +111,10 @@ async fn delete_route( .transform(q.base_version.as_deref(), Origin::Ui, |text, cfg| { let engine = cfg.engine(); if engine.default_route() == name { - return Err(ApplyError::InUse(format!( - "Route `{name}` is the default route and cannot be deleted. Make another route the \ - default first." + return Err(ApplyError::InUse(msg!( + "control.default_route_cannot_delete", route = name => + "Route `{route}` is the default route and cannot be deleted. Make another route \ + the default first." ))); } if !cfg.routes.iter().any(|r| r.name == name) { @@ -125,9 +127,10 @@ async fn delete_route( .filter(|t| !t.is_empty() && *t != engine.default_route()); if let Some(t) = target { if t == name { - return Err(invalid(format!( - "a key cannot be moved onto route `{name}`, which is being deleted" - ))); + return Err(invalid(msg!( + "control.reassign_to_deleted_route", route = name => + "a key cannot be moved onto route `{route}`, which is being deleted" + ))); } if engine.rules_of(t).is_none() { return Err(not_found("route", t)); @@ -224,8 +227,9 @@ fn route_probes(text: &str, probes: &[String]) -> Result { for p in probes { // 总称不是一个可以单独设置的类别 if p == "assistant_internal" || !INTENTS.contains(&p.as_str()) { - return Err(invalid(format!( - "there is no auxiliary-request class `{p}`" + return Err(invalid(msg!( + "control.unknown_probe_class", class = p => + "there is no auxiliary-request class `{class}`" ))); } out = edit::set( @@ -245,8 +249,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, "route").map_err(|e| e.text)?; +fn to_route(input: &tw_api::RouteInput, cfg: &tw_config::Config) -> Result { + let name = checked_name(&input.name, "route")?; reserved(&name, "route")?; let mut seen = HashSet::new(); let rules = input @@ -255,18 +259,21 @@ fn to_route(input: &tw_api::RouteInput, cfg: &tw_config::Config) -> Result + "the route has two rules named `{rule}`" + )); } Ok(rule) }) - .collect::, String>>()?; + .collect::, Msg>>()?; Ok(RouteSet { name, rules }) } /// 界面交过来的一条规则 → 配置里的规则。**写法错在哪儿,这里就说哪儿。** -pub(crate) fn to_rule(input: &tw_api::RuleInput, cfg: &tw_config::Config) -> Result { - 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}"))?; +pub(crate) fn to_rule(input: &tw_api::RuleInput, cfg: &tw_config::Config) -> Result { + let name = checked_name(&input.name, "rule")?; + let when = when_from(&name, &input.conditions, cfg)?; let to = input .to .as_deref() @@ -274,11 +281,19 @@ 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!("rule `{name}`: a denial needs a reason")), + Some("") => { + return Err(msg!( + "control.rule.deny_needs_reason", rule = name => + "rule `{rule}`: a denial needs a reason" + )); + } other => other.map(str::to_string), }; if to.is_some() && deny.is_some() { - return Err(format!("rule `{name}` cannot both forward and deny")); + return Err(msg!( + "control.rule.forward_and_deny", rule = name => + "rule `{rule}` cannot both forward and deny" + )); } let set = input.set.as_ref().and_then(|s| { let a = SetAction { @@ -320,13 +335,23 @@ const INTENTS: &[&str] = &[ /// **和视图用同一套写法**(`ConditionView`),界面拿到什么交回什么。取值 /// 在这里查:打错的客户端格式、不存在的密钥或上游,写进去的后果都是这条 /// 规则永远不命中,而那是完全静默的。 -fn when_from(conds: &[tw_api::ConditionView], cfg: &tw_config::Config) -> Result { +/// +/// **每一句都带着规则名**(`rule` 参数):一条路由里有好几条规则,只说 +/// 「条件没填值」的话,用户得一条条去找。 +fn when_from( + rule: &str, + conds: &[tw_api::ConditionView], + cfg: &tw_config::Config, +) -> Result { let mut w = When::default(); let mut seen = HashSet::new(); for c in conds { let field = c.field.as_str(); if !seen.insert(field) { - return Err(format!("condition `{field}` appears twice")); + return Err(msg!( + "control.rule.condition_twice", rule = rule, field = field => + "rule `{rule}`: condition `{field}` appears twice" + )); } let vals: Vec = c .values @@ -334,28 +359,40 @@ fn when_from(conds: &[tw_api::ConditionView], cfg: &tw_config::Config) -> Result .map(|v| v.trim().to_string()) .filter(|v| !v.is_empty()) .collect(); - let one = || -> Result { + let no_value = || { + msg!( + "control.rule.condition_no_value", rule = rule, field = field => + "rule `{rule}`: condition `{field}` has no value" + ) + }; + let one = || -> Result { match vals.as_slice() { [v] => Ok(v.clone()), - [] => Err(format!("condition `{field}` has no value")), - _ => Err(format!("condition `{field}` takes exactly one value")), + [] => Err(no_value()), + _ => Err(msg!( + "control.rule.condition_one_value", rule = rule, field = field => + "rule `{rule}`: condition `{field}` takes exactly one value" + )), } }; - let flag = || -> Result { + let flag = || -> Result { match one()?.as_str() { "true" => Ok(true), "false" => Ok(false), - v => Err(format!( - "condition `{field}` takes true or false, and got `{v}`" + v => Err(msg!( + "control.rule.condition_not_bool", rule = rule, field = field, value = v => + "rule `{rule}`: condition `{field}` takes true or false, and got `{value}`" )), } }; - let many = |allowed: &dyn Fn(&str) -> bool, what: &str| -> Result { + let many = |allowed: &dyn Fn(&str) -> bool, + unknown: &dyn Fn(&str) -> Msg| + -> Result { if let Some(bad) = vals.iter().find(|v| !allowed(v.as_str())) { - return Err(format!("there is no {what} `{bad}`")); + return Err(unknown(bad)); } match vals.as_slice() { - [] => Err(format!("condition `{field}` has no value")), + [] => Err(no_value()), [v] => Ok(OneOrMany::One(v.clone())), vs => Ok(OneOrMany::Many(vs.to_vec())), } @@ -365,14 +402,20 @@ 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!("there is no gateway key `{k}`")); + return Err(msg!( + "control.rule.no_such_key", rule = rule, key = k => + "rule `{rule}`: there is no gateway key `{key}`" + )); } w.client = Some(k); } "dialect" => { let d = one()?; if !DIALECTS.contains(&d.as_str()) { - return Err(format!("`{d}` is not a client format we support")); + return Err(msg!( + "control.rule.unknown_dialect", rule = rule, dialect = d => + "rule `{rule}`: `{dialect}` is not a client format we support" + )); } w.dialect = Some(d); } @@ -385,19 +428,43 @@ fn when_from(conds: &[tw_api::ConditionView], cfg: &tw_config::Config) -> Result "thinking" => w.thinking = Some(flag()?), "stream" => w.stream = Some(flag()?), "intent" => { - w.intent = Some(many(&|v| INTENTS.contains(&v), "auxiliary-request class")?) + w.intent = Some(many(&|v| INTENTS.contains(&v), &|v| { + msg!( + "control.rule.no_such_probe_class", rule = rule, class = v => + "rule `{rule}`: there is no auxiliary-request class `{class}`" + ) + })?) } "provider_would_be" => { w.provider_would_be = Some(many( &|v| cfg.providers.iter().any(|p| p.name == v), - "upstream", + &|v| { + msg!( + "control.rule.no_such_upstream", rule = rule, upstream = v => + "rule `{rule}`: there is no upstream `{upstream}`" + ) + }, )?) } - other => return Err(format!("`{other}` is not a condition we support")), + other => { + return Err(msg!( + "control.rule.unknown_condition", rule = rule, field = other => + "rule `{rule}`: `{field}` is not a condition we support" + )); + } } } // 比较式写错了(`200k` 少了比较符):保存之前就说 - w.validate().map_err(|e| e.to_string())?; + // + // 那句话是引擎的(`engine.compare.*`),不认识规则名。**码不变,多带一个 + // `rule`**,英文前面补上是哪条规则 —— 为此再给每一种写法错误造一个「带 + // 规则名」的码,码表就翻了一倍 + w.validate().map_err(|e| { + let mut m = e.msg(); + m.text = format!("rule `{rule}`: {}", m.text); + m.args.insert("rule".into(), rule.to_string()); + m + })?; Ok(w) } @@ -455,8 +522,10 @@ async fn delete_group( .map(|r| format!("rule `{}` of route `{}`", r.rule, r.route)) .collect::>() .join(", "); - return Err(ApplyError::InUse(format!( - "Group `{name}` is still referenced by {by}; drop those references before deleting it." + return Err(ApplyError::InUse(msg!( + "control.group_in_use", group = name, refs = by => + "Group `{group}` is still referenced by {refs}; drop those references before \ + deleting it." ))); } Ok(edit::remove(text, edit::GROUPS, &name)?) @@ -468,39 +537,54 @@ async fn delete_group( fn builtin_group(name: &str) -> Result<(), ApplyError> { if tw_engine::is_builtin_group(name) { - return Err(ApplyError::InUse( + return Err(ApplyError::InUse(msg!( + "control.builtin_group_fixed" => "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, "group").map_err(|e| e.text)?; +fn to_group(input: &tw_api::GroupInput, cfg: &tw_config::Config) -> Result { + let name = checked_name(&input.name, "group")?; reserved(&name, "group")?; if cfg.providers.iter().any(|p| p.name == name) { - return Err(format!( + return Err(msg!( + "control.group.name_is_upstream", name = 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!("`{}` is not a strategy we support", input.kind))?; + let kind: GroupType = + serde_yaml_ng::from_value(Value::String(input.kind.clone())).map_err(|_| { + msg!( + "control.group.unknown_strategy", strategy = &input.kind => + "`{strategy}` is not a strategy we support" + ) + })?; 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!("there is no upstream `{p}`")); + return Err(msg!( + "control.group.no_such_upstream", upstream = p => + "there is no upstream `{upstream}`" + )); } if providers.iter().any(|x| x == p) { - return Err(format!("upstream `{p}` appears twice")); + return Err(msg!( + "control.group.upstream_twice", upstream = p => + "upstream `{upstream}` appears twice" + )); } providers.push(p.to_string()); } if providers.is_empty() { - return Err("a group needs at least one upstream".to_string()); + return Err(msg!( + "control.group.empty" => + "a group needs at least one upstream" + )); } // 手动选择要有一个优先使用的成员;没选就是第一个。其余策略不写这一项 let selected = match kind { @@ -513,7 +597,10 @@ fn to_group(input: &tw_api::GroupInput, cfg: &tw_config::Config) -> Result + "the preferred upstream `{upstream}` is not a member" + )); } Some(sel) } @@ -575,11 +662,11 @@ pub(crate) fn rule_view(r: &Rule, n: tw_engine::RuleNotes) -> tw_api::RuleView { // ─────────────────────────────────────────────────────────── 共用 -fn reserved(name: &str, what: &str) -> Result<(), String> { +fn reserved(name: &str, what: &str) -> Result<(), Msg> { if name.starts_with(tw_engine::RESERVED_PREFIX) { - return Err(format!( - "a {what} name cannot start with {}; those are reserved for built-ins", - tw_engine::RESERVED_PREFIX + return Err(msg!( + "control.name_reserved", kind = what, prefix = tw_engine::RESERVED_PREFIX => + "a {kind} name cannot start with {prefix}; those are reserved for built-ins" )); } Ok(()) @@ -598,3 +685,119 @@ fn name_taken(what: &'static str, name: &str) -> ApplyError { name: name.to_string(), }) } + +#[cfg(test)] +mod msg_codes { + use super::*; + + fn cfg() -> tw_config::Config { + tw_config::try_parse( + "version: 1\nclients:\n - name: c\n key: tw-k\nproviders:\n - name: a\n base_url: https://x\n key: k\n", + ) + .unwrap() + } + + fn rule(conds: &[(&str, &[&str])]) -> tw_api::RuleInput { + tw_api::RuleInput { + name: "长上下文".into(), + conditions: conds + .iter() + .map(|(f, vs)| tw_api::ConditionView { + field: f.to_string(), + values: vs.iter().map(|v| v.to_string()).collect(), + }) + .collect(), + to: Some("a".into()), + deny: None, + set: None, + } + } + + /// **每一句都有自己的码,而且带着规则名。**以前这些是拼好的英文, + /// 经 `invalid` 塞进 `control.config_rejected` 的 `{detail}` + #[test] + fn a_rule_that_is_written_wrongly_says_so_with_its_own_code() { + let c = cfg(); + let code = |r: tw_api::RuleInput| { + let m = to_rule(&r, &c).unwrap_err(); + assert_eq!(m.arg("rule"), "长上下文", "{m:?}"); + assert!(!m.text.is_empty(), "{m:?}"); + m.code + }; + assert_eq!( + code(rule(&[("model", &[])])), + "control.rule.condition_no_value" + ); + assert_eq!( + code(rule(&[("model", &["a", "b"])])), + "control.rule.condition_one_value" + ); + assert_eq!( + code(rule(&[("model", &["a"]), ("model", &["b"])])), + "control.rule.condition_twice" + ); + assert_eq!( + code(rule(&[("cache", &["yes"])])), + "control.rule.condition_not_bool" + ); + assert_eq!( + code(rule(&[("client", &["nobody"])])), + "control.rule.no_such_key" + ); + assert_eq!( + code(rule(&[("dialect", &["cobol"])])), + "control.rule.unknown_dialect" + ); + assert_eq!( + code(rule(&[("intent", &["chat"])])), + "control.rule.no_such_probe_class" + ); + assert_eq!( + code(rule(&[("provider_would_be", &["b"])])), + "control.rule.no_such_upstream" + ); + assert_eq!( + code(rule(&[("color", &["red"])])), + "control.rule.unknown_condition" + ); + // 比较式写错是引擎那一句,**码不变,多带一个规则名** + assert_eq!( + code(rule(&[("input_tokens", &["200k"])])), + "engine.compare.no_operator" + ); + let mut r = rule(&[]); + r.deny = Some("no".into()); + assert_eq!(code(r), "control.rule.forward_and_deny"); + } + + #[test] + fn a_group_that_is_written_wrongly_says_so_with_its_own_code() { + let c = cfg(); + let g = |name: &str, kind: &str, providers: &[&str]| tw_api::GroupInput { + name: name.into(), + kind: kind.into(), + providers: providers.iter().map(|p| p.to_string()).collect(), + selected: None, + session_affinity: true, + }; + let code = |i: tw_api::GroupInput| to_group(&i, &c).unwrap_err().code; + assert_eq!( + code(g("a", "fallback", &["a"])), + "control.group.name_is_upstream" + ); + assert_eq!(code(g("__x", "fallback", &["a"])), "control.name_reserved"); + assert_eq!( + code(g("g", "random", &["a"])), + "control.group.unknown_strategy" + ); + assert_eq!( + code(g("g", "fallback", &["b"])), + "control.group.no_such_upstream" + ); + assert_eq!( + code(g("g", "fallback", &["a", "a"])), + "control.group.upstream_twice" + ); + assert_eq!(code(g("g", "fallback", &[])), "control.group.empty"); + } +} diff --git a/crates/tw-control/src/security.rs b/crates/tw-control/src/security.rs index 3e799e98..a2fd4c79 100644 --- a/crates/tw-control/src/security.rs +++ b/crates/tw-control/src/security.rs @@ -260,7 +260,7 @@ async fn events( q.before, q.limit.unwrap_or(100).clamp(1, PAGE_MAX), ) - .map_err(crate::internal)?; + .map_err(crate::records)?; Ok(Json(tw_api::SecurityEventsPage { events, more })) } diff --git a/crates/tw-control/src/zai.rs b/crates/tw-control/src/zai.rs index c025c58c..827557f2 100644 --- a/crates/tw-control/src/zai.rs +++ b/crates/tw-control/src/zai.rs @@ -38,7 +38,7 @@ use tw_config::Protocol; use tw_config::history::Origin; use crate::{ControlState, Fail, fail}; -use tw_types::msg; +use tw_types::{Msg, msg}; /// 登录要在多久之内完成。平台给的期限更短就按它的 const LOGIN_TTL: Duration = Duration::from_secs(15 * 60); @@ -228,7 +228,7 @@ impl Want { return Err(fail( StatusCode::CONFLICT, msg!( - "control.name_taken_not_zai", name = name => + "control.name_taken_not_zai", name = &name => "There is already an upstream named `{name}`, and it is not an account of this \ service. Use a different name." ), @@ -308,12 +308,7 @@ async fn init(s: &ControlState, want: &Want, http: &reqwest::Client) -> Result "{detail}"), - ) - })?; + .map_err(|e| fail(StatusCode::BAD_GATEWAY, e.msg()))?; let str_of = |k: &str| { d.get(k) .and_then(|v| v.as_str()) @@ -381,7 +376,7 @@ async fn await_login(s: ControlState, want: Want, http: reqwest::Client, flow: F .await { Ok(d) => d, - Err(why) => return settle(&s, &flow.id, Err(why)), + Err(why) => return settle(&s, &flow.id, Err(why.into())), }; match d.get("status").and_then(|v| v.as_str()) { Some("pending") => { @@ -602,8 +597,10 @@ async fn save(s: &ControlState, want: &Want, key: String) -> Result + "There is already an upstream named `{name}`, and it is not an account of this \ + service. Use a different name." ))); } let mut p = existing.cloned().unwrap_or_else(|| tw_config::Provider { @@ -619,7 +616,7 @@ async fn save(s: &ControlState, want: &Want, key: String) -> Result, ) -> Result, Fail> { let mut status = { - let g = s.zai.current.lock().map_err(|e| { - fail( - StatusCode::INTERNAL_SERVER_ERROR, - msg!("control.internal", detail = e => "{detail}"), - ) - })?; + let g = s.zai.current.lock().map_err(crate::internal)?; let c = g.as_ref().filter(|c| c.status.id == id).ok_or_else(|| { fail( StatusCode::NOT_FOUND, @@ -742,6 +734,75 @@ async fn cancel( /// /// 出错的话里只有**这一步在做什么**,没有地址:建 key 那几个地址的路径里带着密钥的 /// id,而错误会进日志、也会显示给用户。 +/// 调一次账号平台的接口没成。 +/// +/// **结构留着,句子等到要说的时候再拼。**登录流程里的那些失败最后是登录 +/// 状态里的一行字(`to_string`,带着「在做哪一步」);开始登录那一步是一条 +/// 控制面的错误,要带码([`CallError::msg`])。先拼成英文再往外发的话, +/// 后一种就只剩把整句塞进 `{detail}` 一条路。 +#[derive(Debug)] +struct CallError { + /// 在做哪一步,英文词组,只进 `Display` + doing: String, + why: CallFailure, +} + +#[derive(Debug)] +enum CallFailure { + /// 连不上、超时。数据面那句自己带码 + Unreachable(Msg), + Status { + status: u16, + body: String, + }, + NotJson { + body: String, + }, + Refused { + why: String, + }, +} + +impl std::fmt::Display for CallError { + fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { + let doing = &self.doing; + match &self.why { + CallFailure::Unreachable(m) => write!(f, "{doing} failed: {m}"), + CallFailure::Status { status, body } => write!(f, "{doing} answered {status}: {body}"), + CallFailure::NotJson { body } => write!(f, "{doing} did not answer JSON: {body}"), + CallFailure::Refused { why } => write!(f, "{doing} was refused: {why}"), + } + } +} + +impl From for String { + fn from(e: CallError) -> Self { + e.to_string() + } +} + +impl CallError { + /// 带码的说法。**不说在做哪一步** —— 那是一个英文词组,而用得上这句话的 + /// 只有开始登录那一处,界面自己知道那是哪一步。 + fn msg(&self) -> Msg { + match &self.why { + CallFailure::Unreachable(m) => m.clone(), + CallFailure::Status { status, body } => msg!( + "control.account_service_status", status = status, detail = body => + "The account service answered {status}: {detail}" + ), + CallFailure::NotJson { body } => msg!( + "control.account_service_not_json", detail = body => + "The account service did not answer JSON: {detail}" + ), + CallFailure::Refused { why } => msg!( + "control.account_service_refused", why = why => + "The account service refused the request: {why}" + ), + } + } +} + async fn data( http: &reqwest::Client, method: reqwest::Method, @@ -749,7 +810,11 @@ async fn data( doing: &str, auth: Option<&str>, body: Option, -) -> Result { +) -> Result { + let fail = |why| CallError { + doing: doing.to_string(), + why, + }; let mut req = http .request(method, url) .timeout(API_TIMEOUT) @@ -762,22 +827,20 @@ async fn data( req = req.json(&body); } let resp = req.send().await.map_err(|e| { - format!( - "{doing} failed: {}", - tw_gateway::forward::map_reqwest_error(e).message() - ) + fail(CallFailure::Unreachable( + tw_gateway::forward::map_reqwest_error(e).detail, + )) })?; let status = resp.status(); let text = resp.text().await.unwrap_or_default(); if !status.is_success() { - return Err(format!( - "{doing} answered {}: {}", - status.as_u16(), - brief(&text) - )); + return Err(fail(CallFailure::Status { + status: status.as_u16(), + body: brief(&text), + })); } let v: Value = serde_json::from_str(&text) - .map_err(|_| format!("{doing} did not answer JSON: {}", brief(&text)))?; + .map_err(|_| fail(CallFailure::NotJson { body: brief(&text) }))?; if !business_ok(v.get("code")) { let why = v .get("msg") @@ -785,7 +848,9 @@ async fn data( .map(str::trim) .filter(|m| !m.is_empty()) .unwrap_or("no reason given"); - return Err(format!("{doing} was refused: {why}")); + return Err(fail(CallFailure::Refused { + why: why.to_string(), + })); } Ok(v.get("data").cloned().unwrap_or(Value::Null)) } @@ -813,12 +878,9 @@ fn client_for(s: &ControlState, want: &Want) -> Result { proxy: want.proxy.clone(), ..Default::default() }; - tw_gateway::client_for_provider(&s.config(), &route).map_err(|e| { - fail( - StatusCode::BAD_GATEWAY, - msg!("control.upstream_call_failed", detail = e.message().to_string() => "{detail}"), - ) - }) + // 代理没定义、密码读不到这些,数据面那句自己带码 + tw_gateway::client_for_provider(&s.config(), &route) + .map_err(|e| fail(StatusCode::BAD_GATEWAY, e.detail)) } fn announce( @@ -895,3 +957,48 @@ mod tests { assert_eq!(pick_place(&json!({"organizations": []})), None); } } + +#[cfg(test)] +mod call_error_codes { + use super::*; + + /// 开始登录那一步的失败带码发出去;登录状态里那一行照旧说在做哪一步。 + #[test] + fn a_failed_call_has_a_code_and_still_says_what_it_was_doing() { + let e = |why| CallError { + doing: "asking for an authorization address".into(), + why, + }; + let unreachable = msg!("gw.upstream.timeout" => "timed out"); + let all = [ + ( + e(CallFailure::Unreachable(unreachable.clone())), + "gw.upstream.timeout", + ), + ( + e(CallFailure::Status { + status: 500, + body: "x".into(), + }), + "control.account_service_status", + ), + ( + e(CallFailure::NotJson { body: "x".into() }), + "control.account_service_not_json", + ), + ( + e(CallFailure::Refused { why: "x".into() }), + "control.account_service_refused", + ), + ]; + for (err, code) in all { + assert_eq!(err.msg().code, code); + assert!(!err.msg().text.is_empty()); + let line: String = err.into(); + assert!( + line.starts_with("asking for an authorization address"), + "{line}" + ); + } + } +} diff --git a/crates/tw-control/tests/adopt.rs b/crates/tw-control/tests/adopt.rs index affc5bad..bba52212 100644 --- a/crates/tw-control/tests/adopt.rs +++ b/crates/tw-control/tests/adopt.rs @@ -363,7 +363,9 @@ async fn a_client_whose_mcp_shape_we_have_not_verified_refuses_and_explains() { ) .await; assert_eq!(st, StatusCode::NOT_IMPLEMENTED, "{out}"); - assert!(out.contains("is unverified"), "{out}"); + // 说的是**为什么**不能写,带着那条理由自己的码 + let v: serde_json::Value = serde_json::from_str(&out).unwrap(); + assert_eq!(v["code"], "adopt.mcp.zed_structure", "{out}"); } #[tokio::test] diff --git a/crates/tw-control/tests/listen.rs b/crates/tw-control/tests/listen.rs index 592cae68..0fd30466 100644 --- a/crates/tw-control/tests/listen.rs +++ b/crates/tw-control/tests/listen.rs @@ -198,7 +198,7 @@ async fn an_interface_that_is_not_there_is_refused_by_name() { ) .await; assert_eq!(st, StatusCode::BAD_REQUEST, "{v}"); - assert_eq!(v["code"], "control.listen.bad_bind"); + assert_eq!(v["code"], "control.listen.bind_invalid"); let (st, v) = call( &b.app, diff --git a/crates/tw-engine/Cargo.toml b/crates/tw-engine/Cargo.toml index 99ca944e..c8254fe2 100644 --- a/crates/tw-engine/Cargo.toml +++ b/crates/tw-engine/Cargo.toml @@ -12,6 +12,7 @@ serde = { workspace = true } tw-dialect = { workspace = true } serde_json = { workspace = true } thiserror = { workspace = true } +tw-types = { workspace = true } tracing = { workspace = true } [dev-dependencies] diff --git a/crates/tw-engine/src/engine.rs b/crates/tw-engine/src/engine.rs index 8d45fd5c..c7e4fe4f 100644 --- a/crates/tw-engine/src/engine.rs +++ b/crates/tw-engine/src/engine.rs @@ -5,6 +5,7 @@ //! 所以引擎只有一条代码路径,用户看到的却是零配置可用。 use serde::{Deserialize, Serialize}; +use tw_types::{Msg, msg}; use crate::facts::RequestFacts; use crate::rule::{MatchError, When}; @@ -461,38 +462,82 @@ pub enum Outcome2 { }, } +/// 路由出不来的原因。 +/// +/// **英文只写一遍**:`Display` 就是 [`RouteError::msg`] 的原句,界面拿码去翻。 #[derive(Debug, thiserror::Error, PartialEq)] pub enum RouteError { - #[error("no rule matched, and there is no catch-all. Add a rule without a `when` at the end")] + #[error("{}", self.msg())] NoMatch, - #[error( - "rule `{0}` sets both provider_would_be and to. provider_would_be can only be evaluated once an upstream is chosen, so such a rule takes only set or deny" - )] + #[error("{}", self.msg())] PhaseTwoWithTo(String), - #[error("rule `{0}` sets none of to, deny or set, so matching it does nothing")] + #[error("{}", self.msg())] NoAction(String), - #[error("rule `{rule}` points at `{target}`, which is neither an upstream nor a group")] + #[error("{}", self.msg())] UnknownTarget { rule: String, target: String }, - #[error("group `{0}` has no upstream in it")] + #[error("{}", self.msg())] EmptyGroup(String), - #[error( - "there is more than one group named `{0}`. Rules refer to a group by name, so names have to be unique" - )] + #[error("{}", self.msg())] DuplicateGroup(String), - #[error( - "there is more than one route named `{0}`. A gateway key binds to a route by name, so names have to be unique" - )] + #[error("{}", self.msg())] DuplicateRoute(String), - #[error( - "default_route points at route `{0}`, which does not exist, so a gateway key with no route of its own matches nothing" - )] + #[error("{}", self.msg())] UnknownDefaultRoute(String), - #[error("gateway key `{client}` binds to route `{route}`, which does not exist")] + #[error("{}", self.msg())] UnknownRoute { client: String, route: String }, #[error(transparent)] Match(#[from] MatchError), } +impl RouteError { + /// 给人看的那句话,带码。 + pub fn msg(&self) -> Msg { + match self { + RouteError::NoMatch => msg!( + "engine.no_match" => + "no rule matched, and there is no catch-all. Add a rule without a `when` at the end" + ), + RouteError::PhaseTwoWithTo(rule) => msg!( + "engine.phase_two_with_to", rule = rule => + "rule `{rule}` sets both provider_would_be and to. provider_would_be can only be \ + evaluated once an upstream is chosen, so such a rule takes only set or deny" + ), + RouteError::NoAction(rule) => msg!( + "engine.no_action", rule = rule => + "rule `{rule}` sets none of to, deny or set, so matching it does nothing" + ), + RouteError::UnknownTarget { rule, target } => msg!( + "engine.unknown_target", rule = rule, target = target => + "rule `{rule}` points at `{target}`, which is neither an upstream nor a group" + ), + RouteError::EmptyGroup(group) => msg!( + "engine.empty_group", group = group => + "group `{group}` has no upstream in it" + ), + RouteError::DuplicateGroup(group) => msg!( + "engine.duplicate_group", group = group => + "there is more than one group named `{group}`. Rules refer to a group by name, so \ + names have to be unique" + ), + RouteError::DuplicateRoute(route) => msg!( + "engine.duplicate_route", route = route => + "there is more than one route named `{route}`. A gateway key binds to a route by \ + name, so names have to be unique" + ), + RouteError::UnknownDefaultRoute(route) => msg!( + "engine.unknown_default_route", route = route => + "default_route points at route `{route}`, which does not exist, so a gateway key \ + with no route of its own matches nothing" + ), + RouteError::UnknownRoute { client, route } => msg!( + "engine.unknown_route", key = client, route = route => + "gateway key `{key}` binds to route `{route}`, which does not exist" + ), + RouteError::Match(e) => e.msg(), + } + } +} + pub struct Engine { sets: Vec, /// 没绑定时走哪条。 @@ -1865,3 +1910,49 @@ mod builtin_tests { assert_eq!(e.validate(), Err(RouteError::DuplicateGroup("pool".into()))); } } + +#[cfg(test)] +mod msg_codes { + use super::*; + use crate::num::ParseError; + + #[test] + fn every_route_error_has_its_own_code() { + let bad = |source| { + RouteError::Match(MatchError::BadCompare { + field: "input_tokens", + source, + }) + }; + let all = [ + RouteError::NoMatch, + RouteError::PhaseTwoWithTo("r".into()), + RouteError::NoAction("r".into()), + RouteError::UnknownTarget { + rule: "r".into(), + target: "t".into(), + }, + RouteError::EmptyGroup("g".into()), + RouteError::DuplicateGroup("g".into()), + RouteError::DuplicateRoute("x".into()), + RouteError::UnknownDefaultRoute("x".into()), + RouteError::UnknownRoute { + client: "k".into(), + route: "x".into(), + }, + bad(ParseError::Empty), + bad(ParseError::NoOperator("200k".into())), + bad(ParseError::BadNumber(">x".into())), + bad(ParseError::BadUnit(">2q".into())), + ]; + let mut seen = std::collections::HashSet::new(); + for e in &all { + let m = e.msg(); + assert!(m.code.starts_with("engine."), "{m:?}"); + assert!(!m.text.is_empty() && m.text == e.to_string(), "{m:?}"); + assert!(seen.insert(m.code.clone()), "码重复了:{}", m.code); + } + let m = bad(ParseError::BadUnit(">2q".into())).msg(); + assert_eq!((m.arg("field"), m.arg("value")), ("input_tokens", ">2q")); + } +} diff --git a/crates/tw-engine/src/rule.rs b/crates/tw-engine/src/rule.rs index b314348b..bbf7e214 100644 --- a/crates/tw-engine/src/rule.rs +++ b/crates/tw-engine/src/rule.rs @@ -8,6 +8,7 @@ //! 括号嵌套直接消失。 use serde::{Deserialize, Serialize}; +use tw_types::{Msg, msg}; use crate::facts::RequestFacts; use crate::num::Compare; @@ -196,13 +197,46 @@ impl When { #[derive(Debug, thiserror::Error, PartialEq)] pub enum MatchError { - #[error("condition {field} is written wrongly: {source}")] + #[error("{}", self.msg())] BadCompare { field: &'static str, source: crate::num::ParseError, }, } +impl MatchError { + /// 给人看的那句话,带码。 + /// + /// **比较式错在哪儿要拆成各自的码**,不能把 `ParseError` 的原句当 `detail` + /// 塞进去 —— 那半句是英文,中文界面上就成了一句话两种语言。所以这里把 + /// `ParseError` 的四种说法各抄一遍:它自己的 `Display` 还要留给 serde, + /// 读配置文件时的报错走的是那一条。 + pub fn msg(&self) -> Msg { + use crate::num::ParseError; + let MatchError::BadCompare { field, source } = self; + match source { + ParseError::Empty => msg!( + "engine.compare.empty", field = field => + "condition {field} is written wrongly: the comparison is empty" + ), + ParseError::NoOperator(v) => msg!( + "engine.compare.no_operator", field = field, value = v => + "condition {field} is written wrongly: `{value}` has no comparison operator; it \ + starts with one of > < >= <= =, as in \">200k\"" + ), + ParseError::BadNumber(v) => msg!( + "engine.compare.bad_number", field = field, value = v => + "condition {field} is written wrongly: the number in `{value}` could not be parsed" + ), + ParseError::BadUnit(v) => msg!( + "engine.compare.bad_unit", field = field, value = v => + "condition {field} is written wrongly: the unit in `{value}` is not recognized. k \ + (thousand) and m (million) are; an amount is written as $2.5" + ), + } + } +} + /// 只支持 `*`,因为模型名里只需要这个。 /// /// 不引正则:模型名是 `claude-opus-4-5` 这种形状,`claude-opus-*` 已经 diff --git a/crates/tw-gateway/src/l1.rs b/crates/tw-gateway/src/l1.rs index 2dc7db7c..56910077 100644 --- a/crates/tw-gateway/src/l1.rs +++ b/crates/tw-gateway/src/l1.rs @@ -310,11 +310,51 @@ fn is_timeout(m: &Msg) -> bool { async fn phase(f: impl std::future::Future>) -> Result { match tokio::time::timeout(PHASE_TIMEOUT, f).await { Ok(Ok(v)) => Ok(v), - Ok(Err(e)) => Err(msg!("l1.io", detail = e => "{detail}")), + Ok(Err(e)) => Err(io_message(&e)), Err(_) => Err(timed_out()), } } +/// 一次读写失败怎么说。 +/// +/// **按 `ErrorKind` 分,不按系统原话分。**原话是英文的、带一个 errno,而 +/// 且每个平台说法不同(macOS 的「Connection reset by peer」到 Windows 上是 +/// 一整句 WSA 的解释);种类是标准库替各平台归好的类。常见的几种各有一个 +/// 码,界面能说成自己的话;剩下的才只能把原话原样带出去。 +fn io_message(e: &std::io::Error) -> Msg { + use std::io::ErrorKind::*; + match e.kind() { + ConnectionRefused => msg!("l1.io.refused" => "The connection was refused."), + ConnectionReset => msg!("l1.io.reset" => "The connection was reset by the other end."), + ConnectionAborted => msg!("l1.io.aborted" => "The connection was aborted."), + TimedOut => msg!("l1.io.timed_out" => "The connection timed out."), + AddrNotAvailable => msg!( + "l1.io.addr_not_available" => + "The address is not available on this machine." + ), + NotFound => msg!("l1.io.not_found" => "The target was not found."), + PermissionDenied => msg!( + "l1.io.permission_denied" => + "The operating system did not allow the connection. A firewall or a network \ + permission setting may be blocking it." + ), + UnexpectedEof => msg!( + "l1.io.eof" => + "The other end closed the connection before answering." + ), + BrokenPipe => msg!( + "l1.io.broken_pipe" => + "The other end closed the connection while data was being sent." + ), + HostUnreachable => msg!("l1.io.host_unreachable" => "The host cannot be reached."), + NetworkUnreachable => msg!( + "l1.io.network_unreachable" => + "The network cannot be reached. Check this machine's network." + ), + _ => msg!("l1.io", detail = e => "{detail}"), + } +} + /// 拆出 host / port / 要不要 TLS。 fn target_of(base_url: &str) -> Result<(String, u16, bool), Msg> { let u = reqwest::Url::parse(base_url).map_err(|e| { @@ -531,28 +571,32 @@ async fn connect_via_proxy( } } -/// TCP 建连失败的系统原话是英文的,而且只有一个 errno。 -/// 「Connection refused (os error 61)」和「那个端口上没有东西在听」 -/// 之间隔着一次搜索。 +/// TCP 建连失败时说哪一句。 +/// +/// 系统原话是英文的,而且只有一个 errno:「Connection refused (os error 61)」 +/// 和「那个端口上没有东西在听」之间隔着一次搜索。**按 [`io_message`] 给的 +/// 码判**,不按原话判 —— 原话每个平台不一样。 +/// +/// 拒绝、超时、不可达这三种在建连这一步有更能行动的说法(带着地址);其余 +/// 已经有码的种类原样用;只有落到 `l1.io` 的,才把原话放进 `l1.tcp.failed`。 fn tcp_message(e: &Msg, addr: SocketAddr) -> Msg { - let l = e.text.to_ascii_lowercase(); - if l.contains("refused") { - msg!( + match e.code.as_str() { + "l1.io.refused" => msg!( "l1.tcp.refused", addr = addr => "{addr} refused the connection: nothing is listening on that port. Check the address and the port." - ) - } else if is_timeout(e) || l.contains("timed out") { - msg!( + ), + "l1.io.timed_out" | TIMED_OUT => msg!( "l1.tcp.timeout", addr = addr => "{addr} did not answer. Check the network, or whether this address has to be reached through a proxy." - ) - } else if l.contains("unreachable") { - msg!( + ), + "l1.io.host_unreachable" | "l1.io.network_unreachable" => msg!( "l1.tcp.unreachable", addr = addr => "The network {addr} is on cannot be reached. Check this machine's network." - ) - } else { - msg!("l1.tcp.failed", addr = addr, detail = e.text.clone() => "{addr} could not be reached: {detail}") + ), + "l1.io" => { + msg!("l1.tcp.failed", addr = addr, detail = e.text.clone() => "{addr} could not be reached: {detail}") + } + _ => e.clone(), } } @@ -1345,3 +1389,51 @@ mod tests { assert_eq!(r.failed, Some(Stage::new(Step::Tcp, Peer::Proxy)), "{r:?}"); } } + +#[cfg(test)] +mod io_codes { + use super::*; + use std::io::{Error, ErrorKind}; + + /// **常见的几种各有一个码**,只有剩下的才把系统原话原样带出去。 + #[test] + fn common_io_failures_get_their_own_codes() { + let kinds = [ + (ErrorKind::ConnectionRefused, "l1.io.refused"), + (ErrorKind::ConnectionReset, "l1.io.reset"), + (ErrorKind::ConnectionAborted, "l1.io.aborted"), + (ErrorKind::TimedOut, "l1.io.timed_out"), + (ErrorKind::AddrNotAvailable, "l1.io.addr_not_available"), + (ErrorKind::NotFound, "l1.io.not_found"), + (ErrorKind::PermissionDenied, "l1.io.permission_denied"), + (ErrorKind::UnexpectedEof, "l1.io.eof"), + (ErrorKind::BrokenPipe, "l1.io.broken_pipe"), + (ErrorKind::HostUnreachable, "l1.io.host_unreachable"), + (ErrorKind::NetworkUnreachable, "l1.io.network_unreachable"), + ]; + for (kind, code) in kinds { + let m = io_message(&Error::new(kind, "os error 1")); + assert_eq!(m.code, code); + assert!(!m.text.is_empty() && !m.text.contains("os error"), "{m:?}"); + } + let m = io_message(&Error::other("something rare")); + assert_eq!( + (m.code.as_str(), m.arg("detail")), + ("l1.io", "something rare") + ); + } + + #[test] + fn connect_failures_name_the_address_where_that_helps() { + let addr: SocketAddr = "127.0.0.1:9".parse().unwrap(); + let at = |kind| tcp_message(&io_message(&Error::new(kind, "x")), addr).code; + assert_eq!(at(ErrorKind::ConnectionRefused), "l1.tcp.refused"); + assert_eq!(at(ErrorKind::TimedOut), "l1.tcp.timeout"); + assert_eq!(tcp_message(&timed_out(), addr).code, "l1.tcp.timeout"); + assert_eq!(at(ErrorKind::NetworkUnreachable), "l1.tcp.unreachable"); + assert_eq!(at(ErrorKind::HostUnreachable), "l1.tcp.unreachable"); + // 别的已有码的种类原样用;落到 `l1.io` 的才进 `l1.tcp.failed` + assert_eq!(at(ErrorKind::PermissionDenied), "l1.io.permission_denied"); + assert_eq!(at(ErrorKind::Other), "l1.tcp.failed"); + } +} diff --git a/crates/tw-pricing/Cargo.toml b/crates/tw-pricing/Cargo.toml index e8742d39..a39d0b21 100644 --- a/crates/tw-pricing/Cargo.toml +++ b/crates/tw-pricing/Cargo.toml @@ -13,6 +13,7 @@ serde = { workspace = true } serde_json = { workspace = true } flate2 = { workspace = true } thiserror = { workspace = true } +tw-types = { workspace = true } [dev-dependencies] # 价目表写在 config.yaml 里,而读 YAML 是 tw-config 的事。这里只在测试里用它 diff --git a/crates/tw-pricing/src/sheet.rs b/crates/tw-pricing/src/sheet.rs index 895e361e..30dcb11e 100644 --- a/crates/tw-pricing/src/sheet.rs +++ b/crates/tw-pricing/src/sheet.rs @@ -31,6 +31,7 @@ use std::collections::BTreeMap; use serde::{Deserialize, Serialize}; +use tw_types::{Msg, msg}; use crate::ModelPrice; @@ -100,35 +101,76 @@ pub struct PerMillion { pub output_above_200k: Option, } +/// 价目表写错的地方。 +/// +/// **英文只写一遍**:`Display` 就是 [`SheetError::msg`] 的原句,界面拿码去翻。 #[derive(Debug, thiserror::Error, PartialEq)] pub enum SheetError { - #[error("a price sheet has no name")] + #[error("{}", self.msg())] EmptyName, - #[error("the price sheet name `{0}` cannot start or end with whitespace")] + #[error("{}", self.msg())] PaddedName(String), - #[error("the price sheet name {0} appears twice")] + #[error("{}", self.msg())] DuplicateName(String), - #[error( - "the multiplier {value} of price sheet `{sheet}` is not valid; a multiplier is greater than 0" - )] + #[error("{}", self.msg())] BadMultiplier { sheet: String, value: f64 }, - #[error("a model in price sheet `{sheet}` has no name")] + #[error("{}", self.msg())] EmptyModel { sheet: String }, - #[error( - "the {field} of model {model} in price sheet `{sheet}` is {value}; a price cannot be negative" - )] + #[error("{}", self.msg())] BadPrice { sheet: String, model: String, + /// 哪一项价格,英文词组(`input price`)。界面按它查自己的词表 field: &'static str, value: f64, }, - #[error( - "model {model} in price sheet `{sheet}` needs both the long-context input price and the output price, or neither" - )] + #[error("{}", self.msg())] HalfLongContext { sheet: String, model: String }, } +impl SheetError { + /// 给人看的那句话,带码。 + pub fn msg(&self) -> Msg { + match self { + SheetError::EmptyName => { + msg!("pricing.sheet.empty_name" => "a price sheet has no name") + } + SheetError::PaddedName(sheet) => msg!( + "pricing.sheet.padded_name", sheet = sheet => + "the price sheet name `{sheet}` cannot start or end with whitespace" + ), + SheetError::DuplicateName(sheet) => msg!( + "pricing.sheet.duplicate_name", sheet = sheet => + "the price sheet name {sheet} appears twice" + ), + SheetError::BadMultiplier { sheet, value } => msg!( + "pricing.sheet.bad_multiplier", sheet = sheet, value = value => + "the multiplier {value} of price sheet `{sheet}` is not valid; a multiplier is \ + greater than 0" + ), + SheetError::EmptyModel { sheet } => msg!( + "pricing.sheet.empty_model", sheet = sheet => + "a model in price sheet `{sheet}` has no name" + ), + SheetError::BadPrice { + sheet, + model, + field, + value, + } => msg!( + "pricing.sheet.bad_price", sheet = sheet, model = model, field = field, value = value => + "the {field} of model {model} in price sheet `{sheet}` is {value}; a price cannot \ + be negative" + ), + SheetError::HalfLongContext { sheet, model } => msg!( + "pricing.sheet.half_long_context", sheet = sheet, model = model => + "model {model} in price sheet `{sheet}` needs both the long-context input price \ + and the output price, or neither" + ), + } + } +} + impl PricingConfig { /// **负价不是「便宜」,是写错了。**让它进去的话,`cheapest` 会永远 /// 选中那一家,而费用栏会往下走。 @@ -366,3 +408,39 @@ mod tests { assert_eq!(PerMillion::of(&v.to_price(None)), v); } } + +#[cfg(test)] +mod msg_codes { + use super::*; + + #[test] + fn every_sheet_error_has_its_own_code() { + let all = [ + SheetError::EmptyName, + SheetError::PaddedName(" a".into()), + SheetError::DuplicateName("a".into()), + SheetError::BadMultiplier { + sheet: "a".into(), + value: 0.0, + }, + SheetError::EmptyModel { sheet: "a".into() }, + SheetError::BadPrice { + sheet: "a".into(), + model: "m".into(), + field: "input price", + value: -1.0, + }, + SheetError::HalfLongContext { + sheet: "a".into(), + model: "m".into(), + }, + ]; + let mut seen = std::collections::HashSet::new(); + for e in &all { + let m = e.msg(); + assert!(m.code.starts_with("pricing.sheet."), "{m:?}"); + assert!(!m.text.is_empty() && m.text == e.to_string(), "{m:?}"); + assert!(seen.insert(m.code.clone()), "码重复了:{}", m.code); + } + } +} diff --git a/crates/tw-yaml/Cargo.toml b/crates/tw-yaml/Cargo.toml index bda564ee..fdc6cf49 100644 --- a/crates/tw-yaml/Cargo.toml +++ b/crates/tw-yaml/Cargo.toml @@ -10,6 +10,7 @@ description = "YAML patch layer that makes minimal edits to the original text" [dependencies] saphyr-parser = { workspace = true } thiserror = { workspace = true } +tw-types = { workspace = true } [dev-dependencies] serde_yaml_ng = { workspace = true } diff --git a/crates/tw-yaml/src/lib.rs b/crates/tw-yaml/src/lib.rs index 32e6adaf..3a72f462 100644 --- a/crates/tw-yaml/src/lib.rs +++ b/crates/tw-yaml/src/lib.rs @@ -15,6 +15,7 @@ use std::ops::Range; use saphyr_parser::{Event, Parser, ScalarStyle, Span}; +use tw_types::{Msg, msg}; mod edit; mod render; @@ -57,34 +58,72 @@ impl From for Step { } } +/// 改不动的原因。 +/// +/// **英文只写一遍**:`Display` 就是 [`PatchError::msg`] 的原句,界面拿码去 +/// 翻,命令行和日志看原句 —— 两处各写一份的话,迟早会说成两件事。 #[derive(Debug, thiserror::Error, PartialEq)] pub enum PatchError { - #[error("the YAML could not be parsed: {0}")] + #[error("{}", self.msg())] Parse(String), - #[error("{0} could not be located in the configuration")] + #[error("{}", self.msg())] NotFound(String), - #[error("{0} is not a scalar, and only a scalar can be changed in place")] + #[error("{}", self.msg())] NotScalar(String), /// **写之前的最后一道闸。**改完在内存里重新解析一遍,对不上就拒绝 /// 写入。开销几百微秒,换来「永远不会写出一个自己都解析不了的文件」。 - #[error("the edit did not pass its own check, so nothing was written: {0}")] + #[error("{}", self.msg())] SelfCheck(String), /// 同一个 map 里出现了两个同名的键。 - #[error( - "{0} appears more than once in the configuration, so a change to it may not take effect; remove the duplicates by hand first" - )] + #[error("{}", self.msg())] Duplicate(String), - #[error( - "{0} is a multi-line block (| or >) and cannot be changed automatically; edit the configuration file directly" - )] + #[error("{}", self.msg())] BlockScalar(String), /// 锚点和别名让「改一处」不再是改一处。 - #[error( - "{0} sits inside a YAML anchor or alias (&x / *x), so a change reaches every use of it; edit the configuration file directly" - )] + #[error("{}", self.msg())] AnchorOrAlias(String), } +impl PatchError { + /// 给人看的那句话,带码。`Parse` 和 `SelfCheck` 里是解析器的原话, + /// 只能原样放进 `detail`;其余几种的参数都是路径(`providers[1].base_url`)。 + pub fn msg(&self) -> Msg { + match self { + PatchError::Parse(d) => msg!( + "yaml.parse", detail = d => + "the YAML could not be parsed: {detail}" + ), + PatchError::NotFound(p) => msg!( + "yaml.not_found", path = p => + "{path} could not be located in the configuration" + ), + PatchError::NotScalar(p) => msg!( + "yaml.not_scalar", path = p => + "{path} is not a scalar, and only a scalar can be changed in place" + ), + PatchError::SelfCheck(d) => msg!( + "yaml.self_check", detail = d => + "the edit did not pass its own check, so nothing was written: {detail}" + ), + PatchError::Duplicate(p) => msg!( + "yaml.duplicate", path = p => + "{path} appears more than once in the configuration, so a change to it may not \ + take effect; remove the duplicates by hand first" + ), + PatchError::BlockScalar(p) => msg!( + "yaml.block_scalar", path = p => + "{path} is a multi-line block (| or >) and cannot be changed automatically; edit \ + the configuration file directly" + ), + PatchError::AnchorOrAlias(p) => msg!( + "yaml.anchor_or_alias", path = p => + "{path} sits inside a YAML anchor or alias (&x / *x), so a change reaches every \ + use of it; edit the configuration file directly" + ), + } + } +} + /// 路径的人话形式(`providers[1].base_url`)。错误信息和写回校验都用它。 pub fn show(path: &[Step]) -> String { let mut s = String::new(); @@ -1398,3 +1437,31 @@ mod undo_tests { assert_eq!(back["routes"].as_sequence().unwrap().len(), 1, "{out}"); } } + +#[cfg(test)] +mod msg_codes { + use super::*; + + /// **每一种都有自己的码。**以前这一层的话被人整句塞进 `{detail}`, + /// 界面拿到的码只说「改配置失败了」 + #[test] + fn every_patch_error_has_its_own_code() { + let all = [ + PatchError::Parse("x".into()), + PatchError::NotFound("a.b".into()), + PatchError::NotScalar("a.b".into()), + PatchError::SelfCheck("x".into()), + PatchError::Duplicate("a.b".into()), + PatchError::BlockScalar("a.b".into()), + PatchError::AnchorOrAlias("a.b".into()), + ]; + let mut seen = std::collections::HashSet::new(); + for e in &all { + let m = e.msg(); + assert!(m.code.starts_with("yaml."), "{m:?}"); + assert!(!m.text.is_empty() && m.text == e.to_string(), "{m:?}"); + assert!(seen.insert(m.code.clone()), "码重复了:{}", m.code); + } + assert_eq!(PatchError::NotFound("a.b".into()).msg().arg("path"), "a.b"); + } +}