From 4ada23f5ad018685d7f949b207483c17815af5ec Mon Sep 17 00:00:00 2001 From: fylorn <249551762+fylorn@users.noreply.github.com> Date: Thu, 24 Sep 2026 17:13:37 +0800 Subject: [PATCH] feat(api): closed sets are enums; attempt, model-list and probe reasons are coded Fields whose value comes from a fixed set were `String` on the wire, so the desktop UI had to narrow them by hand. They are enums now, with the same wire words, and export to TypeScript as string-literal unions: - Guard: SecurityEventView.guard, SecurityEventsQuery.guard - GroupKind: GroupView.kind, GroupInput.kind - ModelListStatus: ProviderView.model_status, ProviderModelsView.status - TakesEffect: DetectedClient/KeySynced/AdoptResponse.takes_effect - AttemptOutcome: AttemptView.outcome - RuleAction: SecurityRuleView.action/default_action, ActionSave.action, CustomRuleSave.action, SecurityTestHit.action, and the action of the ContentMatched / ToolCallFlagged events - ScanLevel: ScanFinding.level; FindingLevel: FindingView.level - L1Step / L1Peer / L1SkipReason: L1Stage.step/peer, L1Skip.reason (tw-gateway's l1 now uses these instead of its own copies) Three reasons that reached the UI as English strings are `Msg` now: - AttemptView.error is the same coded message the hop reports to the client (the separate English sentence per hop is gone) - ProviderView.model_error / ProviderModelsView.error: new gw.models.* codes; failures from the probe carry its gw.probe.* code - ProviderTestResult.error: new gw.probe.* codes for timeout, connect, rejected key and other request failures (reqwest's text as `detail`), and control.provider_test.* for the OAuth cases An unknown group strategy is now a request-body error, so control.group.unknown_strategy is gone. CONTROL_API_VERSION is 14; the stored routing JSON changed shape, so the request store SCHEMA is 19. Co-Authored-By: Claude Opus 5.5 --- bin/twcore/src/main.rs | 2 +- crates/tw-api/msg-codes.txt | 12 +- crates/tw-api/src/lib.rs | 315 ++++++++++++++++--- crates/tw-control/src/clients.rs | 22 +- crates/tw-control/src/keys.rs | 2 +- crates/tw-control/src/lib.rs | 21 +- crates/tw-control/src/resources.rs | 25 +- crates/tw-control/src/routes.rs | 36 ++- crates/tw-control/src/scan.rs | 6 +- crates/tw-control/src/security.rs | 161 +++++----- crates/tw-control/tests/adopt.rs | 7 +- crates/tw-control/tests/live_state.rs | 2 +- crates/tw-control/tests/models.rs | 7 +- crates/tw-control/tests/resources.rs | 4 +- crates/tw-control/tests/security.rs | 5 +- crates/tw-gateway/src/guard.rs | 6 +- crates/tw-gateway/src/l1.rs | 87 +---- crates/tw-gateway/src/models.rs | 68 ++-- crates/tw-gateway/src/probe.rs | 37 ++- crates/tw-gateway/src/server.rs | 16 +- crates/tw-gateway/src/server/pipeline/hop.rs | 70 ++--- crates/tw-gateway/src/state/upstream.rs | 4 +- crates/tw-gateway/src/ws.rs | 6 +- crates/tw-gateway/tests/m5_toolwall.rs | 2 +- crates/tw-gateway/tests/passthrough.rs | 18 +- crates/tw-gateway/tests/ws.rs | 8 +- crates/tw-store/src/db.rs | 18 +- crates/tw-store/src/recorder.rs | 47 +-- 28 files changed, 639 insertions(+), 375 deletions(-) diff --git a/bin/twcore/src/main.rs b/bin/twcore/src/main.rs index 0e07655f..9dd161dc 100644 --- a/bin/twcore/src/main.rs +++ b/bin/twcore/src/main.rs @@ -546,7 +546,7 @@ fn print_l1(target: &str, via: Option<&str>, r: &tw_gateway::L1Result) { } } for s in &r.skipped { - println!(" · {}", s.reason.label()); + println!(" · {}", s.label()); } println!(); } diff --git a/crates/tw-api/msg-codes.txt b/crates/tw-api/msg-codes.txt index ecdfedec..6433f97a 100644 --- a/crates/tw-api/msg-codes.txt +++ b/crates/tw-api/msg-codes.txt @@ -174,7 +174,6 @@ control.group.empty control.group.name_is_upstream control.group.no_such_upstream control.group.preferred_not_member -control.group.unknown_strategy control.group.upstream_twice control.group_in_use control.header_no_value @@ -206,6 +205,8 @@ control.pricing.save_failed control.pricing.status control.pricing.too_large control.pricing.unreachable +control.provider_test.credentials +control.provider_test.oauth_unsaved control.proxy_addr_form control.proxy_in_use control.proxy_not_found @@ -290,8 +291,17 @@ gw.model.no_upstream gw.model.no_upstream_available gw.model.not_allowed gw.model.unknown +gw.models.check_failed +gw.models.credentials +gw.models.empty +gw.models.no_endpoint +gw.models.unrecognized gw.output_limit.cut gw.output_limit.withheld +gw.probe.connect +gw.probe.key_rejected +gw.probe.request_failed +gw.probe.timeout gw.request.body_too_large gw.route.all_selected_disabled gw.route.denied diff --git a/crates/tw-api/src/lib.rs b/crates/tw-api/src/lib.rs index 6f18e23f..9e40ef28 100644 --- a/crates/tw-api/src/lib.rs +++ b/crates/tw-api/src/lib.rs @@ -21,6 +21,44 @@ pub mod ep; pub mod ts; pub use endpoint::{Endpoint, ErrorBody, Format, Info, Method, fill}; +/// 取值是一个固定集合的字段:线上是 slug,类型是枚举。 +/// +/// **线上仍然是那个词**(`#[serde(rename)]`),导出到前端是字符串字面量的联合, +/// 界面不用再自己收窄一遍 —— 手写的收窄和这边的集合对不上时,多出来的值会 +/// 悄悄走进错的分支。`slug()` / `from_slug()` 给存库、拼路径这些要字符串的地方。 +macro_rules! slug_enum { + ( + $(#[$m:meta])* + pub enum $name:ident { + $( $(#[$vm:meta])* $v:ident = $s:literal, )+ + } + ) => { + $(#[$m])* + #[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, Serialize, Deserialize)] + #[cfg_attr(feature = "ts", derive(ts_rs::TS))] + pub enum $name { + $( $(#[$vm])* #[serde(rename = $s)] $v, )+ + } + impl $name { + /// 全部取值,按声明的顺序 + pub const ALL: &'static [Self] = &[$(Self::$v),+]; + /// 线上的那个词 + pub fn slug(self) -> &'static str { + match self { + $(Self::$v => $s,)+ + } + } + /// 反过来。不在集合里的是 `None` + pub fn from_slug(s: &str) -> Option { + match s { + $($s => Some(Self::$v),)+ + _ => None, + } + } + } + }; +} + /// core 发得出的每一个消息码([`Msg::code`]),一行一个,按字母排。 /// /// **界面按码翻译,所以这就是它要翻的全部。**桌面端从钉着的那个 tag 读它,和 @@ -87,7 +125,13 @@ pub const MSG_CODES: &str = include_str!("../msg-codes.txt"); /// 换成了 `POST /scan`(项目目录走请求体,查询串里那种写法 core 一直读不了); /// 框架替我们回的失败(路径不存在、方法不对、请求体读不成)也是 [`ErrorBody`], /// 不再是纯文本或空响应体;传输地址改名 `control::Address`。 -pub const CONTROL_API_VERSION: u32 = 13; +/// +/// **14 起取值固定的字段是枚举,三处原因是 [`Msg`]。**线上的词没变(防护、策略组 +/// 类型、模型清单状态、生效时机、尝试结果、规则动作、发现等级、测速的步骤), +/// 变的是类型;尝试链每一跳的 `error`、模型清单的 `model_error` / `error`、 +/// 检测上游的 `error` 原来是一句英文字符串,中文界面上只能原样显示。照 13 写的 +/// 界面会把这三处画成一个对象。 +pub const CONTROL_API_VERSION: u32 = 14; #[derive(Debug, Clone, Serialize, Deserialize)] #[cfg_attr(feature = "ts", derive(ts_rs::TS))] @@ -288,7 +332,7 @@ pub enum Event { rule: String, custom: bool, /// 这条规则在拦截档下做什么:`block` / `record` - action: String, + action: RuleAction, /// 请求被拒了吗。**拦截档 + 规则是拦**两者同时成立才会 blocked: bool, /// 在工具结果里,而不是调用方自己打的字 @@ -409,7 +453,7 @@ pub enum Event { /// 命中的那一小段,**已截断** excerpt: String, /// 这条规则在拦截档下做什么:`cut` / `record` - action: String, + action: RuleAction, /// 真的切断了流吗。**拦截档 + 规则是切断**两者同时成立才会 blocked: bool, at_ms: u64, @@ -624,6 +668,19 @@ pub enum Event { EventsDropped { id: u64, count: u64, at_ms: u64 }, } +slug_enum! { + /// 尝试链里一跳的结果。 + pub enum AttemptOutcome { + /// 这一跳接下了请求,尝试链到此为止。上游回的是 4xx 也算 —— 请求本身有 + /// 问题,换一个上游也一样被拒 + Served = "served", + /// 上游返回 5xx 或 429,换下一个上游 + Status = "status", + /// 没有收到响应(超时、无法连接),或者这一跳没有发出去 + Error = "error", + } +} + /// 尝试链里的一跳。 /// /// **失败的原因要留着** —— 一条说「试过 A → B → C」的链,和一条还说清 @@ -632,20 +689,15 @@ pub enum Event { #[cfg_attr(feature = "ts", derive(ts_rs::TS))] pub struct AttemptView { pub provider: String, - /// - `served`:这一跳接下了请求,尝试链到此为止。上游回的是 4xx 也算 - /// —— 请求本身有问题,换一个上游也一样被拒。 - /// - `status`:上游返回 5xx 或 429,换下一个上游。 - /// - `error`:没有收到响应(超时、无法连接)。 - /// /// WebSocket 的那一跳是一次握手:上游同意升级(101)是 `served`,回了别的 /// 状态码是 `status`,连不上是 `error`。 - pub outcome: String, + pub outcome: AttemptOutcome, /// 上游返回的状态码。`error` 时没有 #[serde(default, skip_serializing_if = "Option::is_none")] pub status: Option, - /// `error` 时的说明 + /// `error` 时的说明。和这一跳报给客户端的那条错误是同一句 #[serde(default, skip_serializing_if = "Option::is_none")] - pub error: Option, + pub error: Option, pub ms: u64, } @@ -927,9 +979,8 @@ pub struct ProviderView { /// 模型清单从哪儿来:`discovered`(上游列出的)/ `manual`(手动清单)/ /// `none`(不知道它有什么) pub model_source: String, - /// 最近一次向上游获取清单的结果:`pending`(还没获取,停用的上游一直是 - /// 这样)/ `listed` / `no_list`(上游不提供清单)/ `failed`(没问到) - pub model_status: String, + /// 最近一次向上游获取清单的结果 + pub model_status: ModelListStatus, /// 正在获取。上一次的结果照常有效 pub model_fetching: bool, /// 最近一次获取的时间。还没获取过是空 @@ -937,7 +988,7 @@ pub struct ProviderView { pub model_checked_at_ms: Option, /// `no_list` / `failed` 的原因 #[serde(default, skip_serializing_if = "Option::is_none")] - pub model_error: Option, + pub model_error: Option, /// 现在能服务的模型数,已按启用范围过滤。停用时是 0 pub model_count: usize, /// 停用:不参与路由,模型不出现在 `/v1/models` 里 @@ -1091,9 +1142,8 @@ pub struct GroupView { pub name: String, /// 内置的「全部上游」:成员是全部上游,按上游列表的顺序。不能编辑、不能删除 pub builtin: bool, - /// 配置里写的 `type`:`fallback` / `select` / `load-balance` / - /// `url-test` / `cheapest` - pub kind: String, + /// 配置里写的 `type` + pub kind: GroupKind, /// 同一次会话固定走同一家。**这一项直接决定账单** pub session_affinity: bool, /// `select` 组当前选中谁。 @@ -1192,9 +1242,7 @@ pub struct KeySynced { pub client: String, /// 界面上显示的名字 pub name: String, - /// `immediately` 下一个请求就用新的;`on_restart` 要重启那个客户端。 - /// 和 `DetectedClient.takes_effect` 同一个词表 - pub takes_effect: String, + pub takes_effect: TakesEffect, /// 改之前的全文备份在哪 pub backup: String, } @@ -1291,7 +1339,8 @@ pub struct ProviderTestResult { /// 经由哪个代理。直连时为空 #[serde(default, skip_serializing_if = "Option::is_none")] pub via: Option, - pub error: Option, + /// 失败的原因,和下一步该查什么 + pub error: Option, } /// L1 测速:只握手,不发业务请求。**零成本零副作用**。 @@ -1310,15 +1359,45 @@ pub struct L1Request { pub provider: Option, } +slug_enum! { + /// 建连的哪一步。 + pub enum L1Step { + /// 地址或代理配置用不了,没有开始建连 + Config = "config", + Dns = "dns", + Tcp = "tcp", + Tls = "tls", + /// 代理协议的握手,含认证 + Handshake = "handshake", + } +} + +slug_enum! { + /// 建连的那一步对着谁。 + pub enum L1Peer { + Upstream = "upstream", + Proxy = "proxy", + } +} + +slug_enum! { + /// 建连时没有出现的那一步为什么没有。 + pub enum L1SkipReason { + /// `http://` 地址没有 TLS + PlainHttp = "plain_http", + /// 地址已经是 IP,不需要解析 + IpAddress = "ip_address", + /// `socks5h` 和 HTTP CONNECT 由代理解析域名 + ProxyResolves = "proxy_resolves", + } +} + /// 建连的哪一步、对着谁。 #[derive(Debug, Clone, Serialize, Deserialize, PartialEq)] #[cfg_attr(feature = "ts", derive(ts_rs::TS))] pub struct L1Stage { - /// `config`(地址或代理配置用不了,没有开始建连)/ `dns` / `tcp` / - /// `tls` / `handshake`(代理协议的握手,含认证) - pub step: String, - /// `upstream` / `proxy` - pub peer: String, + pub step: L1Step, + pub peer: L1Peer, } #[derive(Debug, Clone, Serialize, Deserialize, PartialEq)] @@ -1333,9 +1412,7 @@ pub struct L1Segment { #[cfg_attr(feature = "ts", derive(ts_rs::TS))] pub struct L1Skip { pub stage: L1Stage, - /// `plain_http`(`http://` 地址没有 TLS)/ `ip_address`(地址已经是 IP, - /// 不需要解析)/ `proxy_resolves`(`socks5h` 和 HTTP CONNECT 由代理解析域名) - pub reason: String, + pub reason: L1SkipReason, } /// **分段是个列表而不是固定的 DNS/TCP/TLS 三段**,因为走代理时的形状本来 @@ -1732,6 +1809,20 @@ pub struct ProviderPreview { pub auth_header: String, } +slug_enum! { + /// 最近一次向上游获取模型清单的结果。 + pub enum ModelListStatus { + /// 还没获取。停用的上游一直是这样 + Pending = "pending", + /// 上游列出了清单 + Listed = "listed", + /// 问到了,但上游不提供清单(没有这个接口、格式认不出、空的) + NoList = "no_list", + /// 没问到:连不上、凭据被拒、取不到凭据 + Failed = "failed", + } +} + /// 一个上游的模型清单。 #[derive(Debug, Clone, Serialize, Deserialize)] #[cfg_attr(feature = "ts", derive(ts_rs::TS))] @@ -1740,7 +1831,7 @@ pub struct ProviderModelsView { /// `discovered`(上游列出的)/ `manual`(手动清单)/ `none` pub source: String, /// 最近一次获取的结果,同 [`ProviderView::model_status`] - pub status: String, + pub status: ModelListStatus, /// 正在获取 pub fetching: bool, /// 最近一次向上游获取清单的时间。还没获取过是空 @@ -1748,7 +1839,7 @@ pub struct ProviderModelsView { pub checked_at_ms: Option, /// 没从上游拿到清单的原因 #[serde(default, skip_serializing_if = "Option::is_none")] - pub error: Option, + pub error: Option, pub models: Vec, } @@ -1964,13 +2055,28 @@ pub struct DefaultRouteSave { pub base_version: Option, } +slug_enum! { + /// 策略组按什么排候选:配置里 `type` 写的那个词。 + pub enum GroupKind { + /// 按顺序,前一个不可用才用下一个 + Fallback = "fallback", + /// 用选中的那一个,不可用时按顺序 + Select = "select", + /// 轮流 + LoadBalance = "load-balance", + /// 选最快的 + UrlTest = "url-test", + /// 选最便宜的 + Cheapest = "cheapest", + } +} + /// 新建或修改一个策略组时交过来的定义。 #[derive(Debug, Clone, Serialize, Deserialize)] #[cfg_attr(feature = "ts", derive(ts_rs::TS))] pub struct GroupInput { pub name: String, - /// `fallback` / `select` / `load-balance` / `url-test` / `cheapest` - pub kind: String, + pub kind: GroupKind, /// 成员,按顺序 pub providers: Vec, /// `select` 组优先使用的成员 @@ -2072,8 +2178,9 @@ pub struct ListQuery { #[derive(Debug, Clone, Default, Serialize, Deserialize)] #[cfg_attr(feature = "ts", derive(ts_rs::TS))] pub struct SecurityEventsQuery { + /// 只要这一项的。不给是全部 #[serde(default, skip_serializing_if = "Option::is_none")] - pub guard: Option, + pub guard: Option, #[serde(default, skip_serializing_if = "Option::is_none")] pub from_ms: Option, #[serde(default, skip_serializing_if = "Option::is_none")] @@ -2769,12 +2876,20 @@ pub struct ReplayResult { // ---------------------------------------------------------------- 静态扫描 +slug_enum! { + /// 一处扫描发现有多要紧。 + pub enum ScanLevel { + High = "high", + Medium = "medium", + Low = "low", + } +} + /// 一处发现。 #[derive(Debug, Clone, Serialize, Deserialize)] #[cfg_attr(feature = "ts", derive(ts_rs::TS))] pub struct ScanFinding { - /// `high` | `medium` | `low` - pub level: String, + pub level: ScanLevel, /// 哪条规则命中的 pub rule: String, /// `hooks` | `mcp` | `skill` | `command` | `agent` | `instructions` @@ -3032,6 +3147,16 @@ pub struct SkippedView { // config.yaml 里的一把网关密钥,这个是本机上装着的一个 AI 客户端 App。 // 中文都叫「客户端」,混起来的话,「有几个客户端」这句话就有两个答案。 +slug_enum! { + /// 改了客户端的配置之后,什么时候生效。 + pub enum TakesEffect { + /// 下一个请求就使用新配置 + Immediately = "immediately", + /// 客户端重新启动后才生效,读环境变量的要重开终端 + OnRestart = "on_restart", + } +} + /// 一个客户端此刻的样子。 #[derive(Debug, Clone, Serialize, Deserialize)] #[cfg_attr(feature = "ts", derive(ts_rs::TS))] @@ -3050,9 +3175,7 @@ pub struct DetectedClient { /// 配置里此刻的端点。**读出来的**,不是拿我们自己的记录充数 pub endpoint: Option, pub shadows: Vec, - /// `immediately`(下一个请求就使用新配置)| `on_restart`(客户端重新 - /// 启动后才生效,读环境变量的要重开终端) - pub takes_effect: String, + pub takes_effect: TakesEffect, /// 接管之后要不要在「一直没收到请求」时提示。 /// /// **需要重开终端的客户端不提示** —— 用户可能一整天都没重开过,那时 @@ -3193,16 +3316,27 @@ pub struct AdoptResponse { pub created: bool, /// 不至于失败、但用户该知道的事(符号链接、权限太松……) pub warnings: Vec, - /// 改动什么时候生效,和 `DetectedClient.takes_effect` 同一个词表 - pub takes_effect: String, + /// 改动什么时候生效 + pub takes_effect: TakesEffect, +} + +slug_enum! { + /// 一条诊断发现的结论。 + pub enum FindingLevel { + /// 就是它让接管没有生效 + Blocking = "blocking", + /// 可能有关,要人看一眼 + Suspect = "suspect", + /// 查过了,没有问题 + Clear = "clear", + } } /// 一条诊断发现。 #[derive(Debug, Clone, Serialize, Deserialize)] #[cfg_attr(feature = "ts", derive(ts_rs::TS))] pub struct FindingView { - /// `blocking` | `suspect` | `clear` - pub level: String, + pub level: FindingLevel, pub title: Msg, pub detail: Msg, /// 用户可以自己执行的下一步。**我们不替他执行。** @@ -3242,6 +3376,35 @@ pub struct HiddenItem { pub revealed: String, } +slug_enum! { + /// 哪一项防护。配置里 `security` 下的那个键,也是接口路径里的那一段。 + pub enum Guard { + /// 出站脱敏 + Redact = "redact", + /// 工具调用审查 + InspectTools = "inspect_tools", + /// 藏匿字符 + HiddenText = "hidden_text", + /// 内容过滤 + Content = "content", + /// 输出长度 + OutputLimit = "output_limit", + } +} + +slug_enum! { + /// 一条规则在拦截档下做什么。工具调用审查是 `cut` / `record`,内容过滤是 + /// `block` / `record`;别的防护命中之后做什么由档位决定,没有这一项。 + pub enum RuleAction { + /// 切断这个工具调用所在的流(工具调用审查) + Cut = "cut", + /// 拒绝这个请求,不发出去(内容过滤) + Block = "block", + /// 只记录 + Record = "record", + } +} + /// 各项防护在一段时间里各留下了几条记录。 #[derive(Debug, Clone, Default, PartialEq, Serialize, Deserialize)] #[cfg_attr(feature = "ts", derive(ts_rs::TS))] @@ -3278,8 +3441,7 @@ pub struct SecurityEventView { pub id: i64, pub at_ms: i64, pub request_id: i64, - /// `redact` / `inspect_tools` / `hidden_text` / `content` / `output_limit` - pub guard: String, + pub guard: Guard, /// 内置规则的 id,或者自定义规则的名字。藏匿字符是那一种(`tag` / `bidi`), /// 输出长度是 `max_chars` pub rule: String, @@ -3371,12 +3533,12 @@ pub struct SecurityRuleView { pub enabled: bool, /// 出厂时开不开。自定义规则是 `true` pub on_by_default: bool, - /// 工具调用审查:拦截档下做什么,`cut` / `record`;内容过滤:`block` / `record` + /// 工具调用审查、内容过滤:拦截档下做什么 #[serde(default, skip_serializing_if = "Option::is_none")] - pub action: Option, + pub action: Option, /// 内置规则出厂时拦截档下做什么。和 `action` 不一样就是改过 #[serde(default, skip_serializing_if = "Option::is_none")] - pub default_action: Option, + pub default_action: Option, } /// 一项防护的档位和规则。 @@ -3440,7 +3602,7 @@ pub struct RuleToggle { #[cfg_attr(feature = "ts", derive(ts_rs::TS))] pub struct ActionSave { /// 工具调用审查:`cut` / `record`;内容过滤:`block` / `record` - pub action: String, + pub action: RuleAction, #[serde(default, skip_serializing_if = "Option::is_none")] pub base_version: Option, } @@ -3453,7 +3615,7 @@ pub struct CustomRuleSave { pub pattern: String, /// 工具调用审查:`cut` / `record`;内容过滤:`block` / `record`。不给按 `record` #[serde(default, skip_serializing_if = "Option::is_none")] - pub action: Option, + pub action: Option, /// 内容过滤才有:`contains`(不分大小写的子串)/ `regex`。不给按 `contains`。 /// 别的防护的自定义规则都是正则 #[serde(rename = "match", default, skip_serializing_if = "Option::is_none")] @@ -3509,7 +3671,7 @@ pub struct SecurityTestHit { pub excerpt: String, /// 工具调用审查、内容过滤:拦截档下做什么 #[serde(default, skip_serializing_if = "Option::is_none")] - pub action: Option, + pub action: Option, } #[derive(Debug, Clone, Serialize, Deserialize)] @@ -3522,6 +3684,55 @@ pub struct SecurityTestResult { mod tests { use super::*; + /// 枚举化的字段在线上仍然是那个词,`slug()` 说的也是它。 + #[test] + fn closed_sets_keep_their_words_on_the_wire() { + fn check< + T: Copy + Serialize + serde::de::DeserializeOwned + PartialEq + std::fmt::Debug, + >( + all: &[T], + slug: fn(T) -> &'static str, + from: fn(&str) -> Option, + ) { + for &v in all { + let wire = serde_json::to_value(v).unwrap(); + assert_eq!(wire, serde_json::Value::from(slug(v)), "{v:?}"); + assert_eq!(serde_json::from_value::(wire).unwrap(), v); + assert_eq!(from(slug(v)), Some(v)); + } + assert!(from("no-such-word").is_none()); + } + check(Guard::ALL, Guard::slug, Guard::from_slug); + check(GroupKind::ALL, GroupKind::slug, GroupKind::from_slug); + check( + ModelListStatus::ALL, + ModelListStatus::slug, + ModelListStatus::from_slug, + ); + check(TakesEffect::ALL, TakesEffect::slug, TakesEffect::from_slug); + check( + AttemptOutcome::ALL, + AttemptOutcome::slug, + AttemptOutcome::from_slug, + ); + check(RuleAction::ALL, RuleAction::slug, RuleAction::from_slug); + check(ScanLevel::ALL, ScanLevel::slug, ScanLevel::from_slug); + check( + FindingLevel::ALL, + FindingLevel::slug, + FindingLevel::from_slug, + ); + check(L1Step::ALL, L1Step::slug, L1Step::from_slug); + check(L1Peer::ALL, L1Peer::slug, L1Peer::from_slug); + check( + L1SkipReason::ALL, + L1SkipReason::slug, + L1SkipReason::from_slug, + ); + assert_eq!(GroupKind::LoadBalance.slug(), "load-balance"); + assert_eq!(Guard::InspectTools.slug(), "inspect_tools"); + } + #[test] fn events_carry_a_discriminating_tag() { // 前端按 `kind` 分派。少了它,TypeScript 那边只能靠字段有无来猜。 diff --git a/crates/tw-control/src/clients.rs b/crates/tw-control/src/clients.rs index abed5985..d6ea504d 100644 --- a/crates/tw-control/src/clients.rs +++ b/crates/tw-control/src/clients.rs @@ -17,6 +17,14 @@ use tw_types::msg; use crate::{Fail, fail}; +/// 契约里的「什么时候生效」。 +pub(crate) fn takes_effect(t: tw_adopt::clients::TakesEffect) -> tw_api::TakesEffect { + match t { + tw_adopt::clients::TakesEffect::Immediately => tw_api::TakesEffect::Immediately, + tw_adopt::clients::TakesEffect::OnRestart => tw_api::TakesEffect::OnRestart, + } +} + fn find(id: &str) -> Result { adoptable().into_iter().find(|c| c.id == id).ok_or_else(|| { fail( @@ -266,7 +274,7 @@ pub async fn list(State(s): State) -> Result "blocking".into(), - detect::Level::Suspect => "suspect".into(), - detect::Level::Clear => "clear".into(), + detect::Level::Blocking => tw_api::FindingLevel::Blocking, + detect::Level::Suspect => tw_api::FindingLevel::Suspect, + detect::Level::Clear => tw_api::FindingLevel::Clear, }, title: f.title, detail: f.detail, diff --git a/crates/tw-control/src/keys.rs b/crates/tw-control/src/keys.rs index ad62f22b..d9de80fa 100644 --- a/crates/tw-control/src/keys.rs +++ b/crates/tw-control/src/keys.rs @@ -330,7 +330,7 @@ async fn rotate( Ok(a) => synced.push(tw_api::KeySynced { client: c.id.to_string(), name: c.name.to_string(), - takes_effect: c.takes_effect.slug().to_string(), + takes_effect: crate::clients::takes_effect(c.takes_effect), backup: a.backup.display().to_string(), }), // **密钥已经换了**,这一条不能把整次更换报成失败 —— 那会让用户 diff --git a/crates/tw-control/src/lib.rs b/crates/tw-control/src/lib.rs index 3e1b321a..7529e08e 100644 --- a/crates/tw-control/src/lib.rs +++ b/crates/tw-control/src/lib.rs @@ -364,7 +364,7 @@ async fn overview(State(s): State) -> Json { .map(|g| tw_api::GroupView { name: g.name.clone(), builtin: tw_engine::is_builtin_group(&g.name), - kind: g.kind.slug().to_string(), + kind: routes::group_kind(g.kind), session_affinity: g.session_affinity, selected: g.selected.clone(), providers: g.providers.clone(), @@ -470,7 +470,7 @@ fn provider_view( models: p.models.clone(), models_only: p.models_only.clone(), model_source: listing.source.slug().to_string(), - model_status: listing.status.slug().to_string(), + model_status: model_status(listing.status), model_fetching: listing.fetching, model_checked_at_ms: listing.checked_at_ms, model_error: listing.error, @@ -633,7 +633,7 @@ pub(crate) fn l1_view( .into_iter() .map(|x| tw_api::L1Skip { stage: l1_stage(x.stage), - reason: x.reason.slug().to_string(), + reason: x.reason, }) .collect(), failed: r.failed.map(l1_stage), @@ -643,8 +643,19 @@ pub(crate) fn l1_view( fn l1_stage(s: tw_gateway::Stage) -> tw_api::L1Stage { tw_api::L1Stage { - step: s.step.slug().to_string(), - peer: s.peer.slug().to_string(), + step: s.step, + peer: s.peer, + } +} + +/// 契约里的模型清单状态。 +pub(crate) fn model_status(s: tw_gateway::models::Status) -> tw_api::ModelListStatus { + use tw_gateway::models::Status; + match s { + Status::Pending => tw_api::ModelListStatus::Pending, + Status::Listed => tw_api::ModelListStatus::Listed, + Status::NoList => tw_api::ModelListStatus::NoList, + Status::Failed => tw_api::ModelListStatus::Failed, } } diff --git a/crates/tw-control/src/resources.rs b/crates/tw-control/src/resources.rs index 6d9d40b0..465a5d43 100644 --- a/crates/tw-control/src/resources.rs +++ b/crates/tw-control/src/resources.rs @@ -190,7 +190,7 @@ async fn test_provider( let p = to_provider(&req.provider, existing).map_err(|e| fail(StatusCode::BAD_REQUEST, e))?; let protocol = p.effective_protocol(); let via = (p.proxy != tw_config::DIRECT).then(|| p.proxy.clone()); - let failed = |error: String| tw_api::ProviderTestResult { + let failed = |error: Msg| tw_api::ProviderTestResult { ok: false, protocol: protocol.map(|x| x.slug().to_string()), latency_ms: 0, @@ -200,7 +200,7 @@ async fn test_provider( }; let http = match tw_gateway::client_for_provider(&cfg, &p) { Ok(h) => h, - Err(e) => return Ok(Json(failed(e.message().to_string()))), + Err(e) => return Ok(Json(failed(e.detail))), }; // OAuth 的 token:新填的那份只能用现成的 access token;沿用原来那份时走网关, // **按原来的名字换** —— 缓存和轮换写回都认名字,而表单里可能刚改了名 @@ -211,25 +211,30 @@ async fn test_provider( match access.as_deref().map(str::trim).filter(|a| !a.is_empty()) { Some(a) => Some(a.to_string()), None => { - return Ok(Json(failed( - "An OAuth credential has to be saved before it can be checked. To check it now, \ - fill in an access token as well." - .to_string(), - ))); + return Ok(Json(failed(msg!( + "control.provider_test.oauth_unsaved" => + "An OAuth credential has to be saved before it can be checked. To check it \ + now, fill in an access token as well." + )))); } } } (tw_api::OAuthChange::Keep, Some(e)) if e.oauth.is_some() && p.oauth.is_some() => { match s.gateway.oauth_token_for(e, &http).await { Ok(t) => Some(t), - Err(e) => return Ok(Json(failed(e))), + Err(e) => { + return Ok(Json(failed(msg!( + "control.provider_test.credentials", detail = e => + "The credential could not be obtained: {detail}" + )))); + } } } _ => None, }; let headers = match p.outbound_headers(token.as_deref()) { Ok(h) => h, - Err(e) => return Ok(Json(failed(e.to_string()))), + Err(e) => return Ok(Json(failed(e.msg()))), }; let r = tw_gateway::probe(&http, &p.base_url, &headers, protocol).await; Ok(Json(tw_api::ProviderTestResult { @@ -292,7 +297,7 @@ fn models_view( tw_api::ProviderModelsView { provider: p.name.clone(), source: listing.source.slug().to_string(), - status: listing.status.slug().to_string(), + status: crate::model_status(listing.status), fetching: listing.fetching, checked_at_ms: listing.checked_at_ms, error: listing.error, diff --git a/crates/tw-control/src/routes.rs b/crates/tw-control/src/routes.rs index d1349a12..4755edd0 100644 --- a/crates/tw-control/src/routes.rs +++ b/crates/tw-control/src/routes.rs @@ -549,6 +549,28 @@ fn builtin_group(name: &str) -> Result<(), ApplyError> { Ok(()) } +/// 契约里的策略组类型和引擎里的是同一组词,两边各写一遍,靠这两个穷尽的 +/// `match` 对齐。 +pub(crate) fn group_kind(t: GroupType) -> tw_api::GroupKind { + match t { + GroupType::Fallback => tw_api::GroupKind::Fallback, + GroupType::Select => tw_api::GroupKind::Select, + GroupType::LoadBalance => tw_api::GroupKind::LoadBalance, + GroupType::UrlTest => tw_api::GroupKind::UrlTest, + GroupType::Cheapest => tw_api::GroupKind::Cheapest, + } +} + +fn group_type(k: tw_api::GroupKind) -> GroupType { + match k { + tw_api::GroupKind::Fallback => GroupType::Fallback, + tw_api::GroupKind::Select => GroupType::Select, + tw_api::GroupKind::LoadBalance => GroupType::LoadBalance, + tw_api::GroupKind::UrlTest => GroupType::UrlTest, + tw_api::GroupKind::Cheapest => GroupType::Cheapest, + } +} + fn to_group(input: &tw_api::GroupInput, cfg: &tw_config::Config) -> Result { let name = checked_name(&input.name, "group")?; reserved(&name, "group")?; @@ -559,13 +581,7 @@ fn to_group(input: &tw_api::GroupInput, cfg: &tw_config::Config) -> Result - "`{strategy}` is not a strategy we support" - ) - })?; + let kind = group_type(input.kind); let mut providers = Vec::new(); for p in &input.providers { let p = p.trim(); @@ -778,7 +794,7 @@ mod msg_codes { let c = cfg(); let g = |name: &str, kind: &str, providers: &[&str]| tw_api::GroupInput { name: name.into(), - kind: kind.into(), + kind: tw_api::GroupKind::from_slug(kind).unwrap(), providers: providers.iter().map(|p| p.to_string()).collect(), selected: None, session_affinity: true, @@ -789,10 +805,6 @@ mod msg_codes { "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" diff --git a/crates/tw-control/src/scan.rs b/crates/tw-control/src/scan.rs index 2ebe472c..bb424ba8 100644 --- a/crates/tw-control/src/scan.rs +++ b/crates/tw-control/src/scan.rs @@ -23,7 +23,11 @@ fn now_ms() -> u64 { /// 把一条发现变成给界面看的样子。 pub fn finding_view(f: &tw_scan::report::Finding) -> tw_api::ScanFinding { tw_api::ScanFinding { - level: f.level.slug().to_string(), + level: match f.level { + tw_scan::report::Level::High => tw_api::ScanLevel::High, + tw_scan::report::Level::Medium => tw_api::ScanLevel::Medium, + tw_scan::report::Level::Low => tw_api::ScanLevel::Low, + }, rule: f.rule.clone(), kind: f.kind.slug().to_string(), client: f.client.clone(), diff --git a/crates/tw-control/src/security.rs b/crates/tw-control/src/security.rs index ee198dc8..df27e326 100644 --- a/crates/tw-control/src/security.rs +++ b/crates/tw-control/src/security.rs @@ -26,7 +26,7 @@ use tw_yaml::Step; use crate::contract::RouterExt; use crate::{ApplyError, ControlState, Fail, apply_fail, fail}; -use tw_api::ep; +use tw_api::{RuleAction, ep}; pub fn router() -> axum::Router { axum::Router::new() @@ -42,28 +42,27 @@ pub fn router() -> axum::Router { .at(ep::TestSecurity, test) } -/// 哪一项防护。路径里写的就是配置里的那个键。 -#[derive(Debug, Clone, Copy, PartialEq, Eq)] -enum Guard { - Redact, - Tools, - Hidden, - Content, - Output, +/// 哪一项防护:契约里的那个集合。路径里写的就是配置里的那个键。 +use tw_api::Guard; + +/// 这一边对每项防护要知道的事。 +trait GuardExt: Sized { + fn parse(s: &str) -> Result; + fn key(self) -> &'static str; + fn custom_section(self) -> Result; + fn path(self, leaf: &str) -> Vec; + fn default_mode(self) -> SecurityMode; + fn lists(self, cfg: &tw_config::Config) -> (&[String], &[String]); } -impl Guard { +impl GuardExt for Guard { fn parse(s: &str) -> Result { - match s { - "redact" => Ok(Guard::Redact), - "inspect_tools" => Ok(Guard::Tools), - "hidden_text" => Ok(Guard::Hidden), - "content" => Ok(Guard::Content), - "output_limit" => Ok(Guard::Output), - other => Err(fail( + match Guard::from_slug(s) { + Some(g) => Ok(g), + None => Err(fail( StatusCode::NOT_FOUND, msg!( - "security.guard_unknown", guard = other => + "security.guard_unknown", guard = s => "`{guard}` is not a line of defence; it is redact, inspect_tools, hidden_text, \ content or output_limit." ), @@ -71,13 +70,7 @@ impl Guard { } } fn key(self) -> &'static str { - match self { - Guard::Redact => "redact", - Guard::Tools => "inspect_tools", - Guard::Hidden => "hidden_text", - Guard::Content => "content", - Guard::Output => "output_limit", - } + self.slug() } /// 自定义规则那一节。**只有这三项有自定义规则** fn custom_section(self) -> Result { @@ -86,7 +79,7 @@ impl Guard { path: &["security", "redact", "custom"], what: "redaction rule", }), - Guard::Tools => Ok(edit::Section { + Guard::InspectTools => Ok(edit::Section { path: &["security", "inspect_tools", "custom"], what: "tool-call rule", }), @@ -94,7 +87,7 @@ impl Guard { path: &["security", "content", "custom"], what: "content rule", }), - Guard::Hidden | Guard::Output => Err(fail( + Guard::HiddenText | Guard::OutputLimit => Err(fail( StatusCode::BAD_REQUEST, msg!( "security.no_custom_rules", guard = self.key() => @@ -113,7 +106,7 @@ impl Guard { /// 出厂的档位:输出长度出厂是关的,其余是观察 fn default_mode(self) -> SecurityMode { match self { - Guard::Output => SecurityMode::Off, + Guard::OutputLimit => SecurityMode::Off, _ => SecurityMode::default(), } } @@ -122,14 +115,30 @@ impl Guard { let s = &cfg.security; match self { Guard::Redact => (&s.redact.enable, &s.redact.disable), - Guard::Tools => (&s.inspect_tools.enable, &s.inspect_tools.disable), + Guard::InspectTools => (&s.inspect_tools.enable, &s.inspect_tools.disable), Guard::Content => (&s.content.enable, &s.content.disable), - Guard::Hidden => (&[], &s.hidden_text.disable), - Guard::Output => (&[], &[]), + Guard::HiddenText => (&[], &s.hidden_text.disable), + Guard::OutputLimit => (&[], &[]), } } } +/// 工具调用审查的动作在契约里的样子。 +fn tool_action(a: ToolAction) -> RuleAction { + match a { + ToolAction::Cut => RuleAction::Cut, + ToolAction::Record => RuleAction::Record, + } +} + +/// 内容过滤的动作在契约里的样子。 +fn content_action(a: ContentAction) -> RuleAction { + match a { + ContentAction::Block => RuleAction::Block, + ContentAction::Record => RuleAction::Record, + } +} + // ---------------------------------------------------------------- 读 async fn detail(State(s): State) -> Json { @@ -198,8 +207,8 @@ fn content_view(p: &tw_config::ContentPolicy) -> tw_api::GuardDetail { matcher: content_matcher(b.matching, &b.pattern), enabled: p.builtin_on(b), on_by_default: b.on_by_default, - action: Some(p.builtin_action(b).slug().into()), - default_action: Some(ContentAction::factory(b).slug().into()), + action: Some(content_action(p.builtin_action(b))), + default_action: Some(content_action(ContentAction::factory(b))), }) .collect(); rules.extend(p.custom.iter().map(|c| tw_api::SecurityRuleView { @@ -211,7 +220,7 @@ fn content_view(p: &tw_config::ContentPolicy) -> tw_api::GuardDetail { matcher: content_matcher(c.matching.engine(), &c.pattern), enabled: !c.disabled, on_by_default: true, - action: Some(c.action.slug().into()), + action: Some(content_action(c.action)), default_action: None, })); tw_api::GuardDetail { @@ -296,15 +305,13 @@ fn tools_view(p: &tw_config::ToolPolicy) -> tw_api::GuardDetail { }, enabled: !p.disable.contains(&r.id), on_by_default: true, - action: Some( + action: Some(tool_action( p.actions .get(&r.id) .copied() - .unwrap_or_else(|| tw_config::ToolAction::factory(r)) - .slug() - .into(), - ), - default_action: Some(tw_config::ToolAction::factory(r).slug().into()), + .unwrap_or_else(|| tw_config::ToolAction::factory(r)), + )), + default_action: Some(tool_action(tw_config::ToolAction::factory(r))), }) .collect(); rules.extend(p.custom.iter().map(|c| tw_api::SecurityRuleView { @@ -318,7 +325,7 @@ fn tools_view(p: &tw_config::ToolPolicy) -> tw_api::GuardDetail { }, enabled: !c.disabled, on_by_default: true, - action: Some(c.action.slug().into()), + action: Some(tool_action(c.action)), default_action: None, })); tw_api::GuardDetail { @@ -334,10 +341,7 @@ async fn events( State(s): State, Query(q): Query, ) -> Result, Fail> { - let guard = match q.guard.as_deref() { - None | Some("") => None, - Some(g) => Some(Guard::parse(g)?.key()), - }; + let guard = q.guard.map(Guard::slug); let store = crate::need_store(&s)?; let g = store.lock().await; // **缺省是「全部」,不是「今天」。**这是一张列表,「最近 N 条」本身就是 @@ -399,17 +403,17 @@ async fn toggle_builtin( let guard = Guard::parse(&guard)?; let on_by_default = match guard { Guard::Redact => tw_guard::redact::rules::builtin(&id).map(|b| b.on_by_default), - Guard::Tools => tw_guard::tools::rules::builtin() + Guard::InspectTools => tw_guard::tools::rules::builtin() .dangerous .iter() .any(|r| r.id == id) .then_some(true), Guard::Content => tw_guard::content::builtin(&id).map(|b| b.on_by_default), - Guard::Hidden => tw_guard::hidden::SMUGGLING + Guard::HiddenText => tw_guard::hidden::SMUGGLING .iter() .any(|k| k.slug() == id) .then_some(true), - Guard::Output => None, + Guard::OutputLimit => None, } .ok_or_else(|| unknown_rule(&id))?; let version = s @@ -435,12 +439,13 @@ async fn toggle_builtin( Ok(Json(tw_api::ConfigWritten { version })) } -fn action_of(slug: &str) -> Result { - ToolAction::from_slug(slug).ok_or_else(|| { +/// 契约里的规则动作,工具调用审查认的那两个。 +fn action_of(a: RuleAction) -> Result { + ToolAction::from_slug(a.slug()).ok_or_else(|| { fail( StatusCode::BAD_REQUEST, msg!( - "security.unknown_action", action = slug.to_string() => + "security.unknown_action", action = a.slug() => "`{action}` is not an action; it is cut or record." ), ) @@ -459,25 +464,25 @@ async fn set_builtin_action( let guard = Guard::parse(&guard)?; // 这条改成什么、出厂是什么,都写成 slug:两项各有各的词 let (action, factory) = match guard { - Guard::Tools => { + Guard::InspectTools => { let spec = tw_guard::tools::rules::builtin() .dangerous .iter() .find(|r| r.id == id) .ok_or_else(|| unknown_rule(&id))?; ( - action_of(&req.action)?.slug(), + action_of(req.action)?.slug(), tw_config::ToolAction::factory(spec).slug(), ) } Guard::Content => { let b = tw_guard::content::builtin(&id).ok_or_else(|| unknown_rule(&id))?; ( - content_action_of(&req.action)?.slug(), + content_action_of(req.action)?.slug(), ContentAction::factory(b).slug(), ) } - Guard::Redact | Guard::Hidden | Guard::Output => { + Guard::Redact | Guard::HiddenText | Guard::OutputLimit => { return Err(fail( StatusCode::BAD_REQUEST, msg!( @@ -505,12 +510,13 @@ async fn set_builtin_action( Ok(Json(tw_api::ConfigWritten { version })) } -fn content_action_of(slug: &str) -> Result { - ContentAction::from_slug(slug).ok_or_else(|| { +/// 契约里的规则动作,内容过滤认的那两个。 +fn content_action_of(a: RuleAction) -> Result { + ContentAction::from_slug(a.slug()).ok_or_else(|| { fail( StatusCode::BAD_REQUEST, msg!( - "security.unknown_content_action", action = slug.to_string() => + "security.unknown_content_action", action = a.slug() => "`{action}` is not an action; it is block or record." ), ) @@ -524,7 +530,7 @@ async fn set_limit( Json(req): Json, ) -> Result, Fail> { let guard = Guard::parse(&guard)?; - if guard != Guard::Output { + if guard != Guard::OutputLimit { return Err(fail( StatusCode::BAD_REQUEST, msg!( @@ -579,7 +585,7 @@ fn custom_item(guard: Guard, req: &tw_api::CustomRuleSave) -> Result ContentAction::default(), Some(a) => content_action_of(a)?, }; @@ -614,8 +620,8 @@ fn custom_item(guard: Guard, req: &tw_api::CustomRuleSave) -> Result ToolAction::default(), Some(a) => action_of(a)?, }; @@ -753,7 +759,7 @@ async fn test( }) .collect() } - Guard::Tools => { + Guard::InspectTools => { let trial; let rules = match (&req.pattern, &req.rule) { (Some(p), _) => { @@ -794,7 +800,11 @@ async fn test( start: utf16_at(&req.sample, m.start()), end: utf16_at(&req.sample, m.end()), excerpt: m.as_str().chars().take(120).collect(), - action: Some(if r.high { "cut" } else { "record" }.into()), + action: Some(if r.high { + RuleAction::Cut + } else { + RuleAction::Record + }), }) }) .collect(); @@ -846,20 +856,17 @@ async fn test( start: utf16_at(&req.sample, h.bytes.start), end: utf16_at(&req.sample, h.bytes.end), excerpt: req.sample[h.bytes.clone()].chars().take(120).collect(), - action: Some( - if h.action == tw_guard::content::Action::Block { - "block" - } else { - "record" - } - .into(), - ), + action: Some(if h.action == tw_guard::content::Action::Block { + RuleAction::Block + } else { + RuleAction::Record + }), rule: h.rule, custom: h.custom, }) .collect() } - Guard::Hidden => { + Guard::HiddenText => { // 给了 `rule` 就只试那一种(关着的也能试),不给按现在开着的 let kinds = match &req.rule { Some(id) => vec![ @@ -892,7 +899,7 @@ async fn test( }) .collect() } - Guard::Output => { + Guard::OutputLimit => { return Err(fail( StatusCode::BAD_REQUEST, msg!( @@ -966,12 +973,12 @@ mod tests { ..Default::default() }); let curl = v.rules.iter().find(|r| r.id == "curl-pipe-sh").unwrap(); - assert_eq!(curl.action.as_deref(), Some("cut")); + assert_eq!(curl.action, Some(RuleAction::Cut)); assert!(!curl.why.is_empty()); let rm = v.rules.iter().find(|r| r.id == "rm-rf-root").unwrap(); - assert_eq!(rm.action.as_deref(), Some("record")); + assert_eq!(rm.action, Some(RuleAction::Record)); let mine = v.rules.last().unwrap(); assert!(mine.custom && !mine.enabled); - assert_eq!(mine.action.as_deref(), Some("cut")); + assert_eq!(mine.action, Some(RuleAction::Cut)); } } diff --git a/crates/tw-control/tests/adopt.rs b/crates/tw-control/tests/adopt.rs index a24a7e0b..092dc297 100644 --- a/crates/tw-control/tests/adopt.rs +++ b/crates/tw-control/tests/adopt.rs @@ -110,7 +110,7 @@ async fn a_client_that_needs_a_restart_says_so_and_gets_no_silence_warning() { let (_, body) = get(&b.app, "/clients").await; let v: tw_api::ClientsResponse = serde_json::from_str(&body).unwrap(); let codex = v.clients.iter().find(|c| c.id == "codex").unwrap(); - assert_eq!(codex.takes_effect, "on_restart"); + assert_eq!(codex.takes_effect, tw_api::TakesEffect::OnRestart); assert!(!codex.warns_when_silent); } @@ -235,7 +235,10 @@ async fn the_diagnosis_hands_over_a_command_rather_than_running_it() { "我们把用户的 .zshrc 改了" ); // 查干净的项也要说出来 - assert!(v.iter().any(|f| f.level == "clear"), "{v:?}"); + assert!( + v.iter().any(|f| f.level == tw_api::FindingLevel::Clear), + "{v:?}" + ); } #[tokio::test] diff --git a/crates/tw-control/tests/live_state.rs b/crates/tw-control/tests/live_state.rs index 2d663f20..f8441302 100644 --- a/crates/tw-control/tests/live_state.rs +++ b/crates/tw-control/tests/live_state.rs @@ -139,7 +139,7 @@ async fn a_request_still_running_can_be_opened_and_becomes_whole_when_it_ends() group: Some("__all__".into()), attempts: vec![tw_api::AttemptView { provider: "官方".into(), - outcome: "served".into(), + outcome: tw_api::AttemptOutcome::Served, status: Some(200), error: None, ms: 900, diff --git a/crates/tw-control/tests/models.rs b/crates/tw-control/tests/models.rs index 499f489d..cbd25641 100644 --- a/crates/tw-control/tests/models.rs +++ b/crates/tw-control/tests/models.rs @@ -223,7 +223,9 @@ async fn an_upstream_that_refuses_the_key_is_failed_with_the_reason_not_merely_u (p["model_status"].as_str(), p["model_source"].as_str()), (Some("failed"), Some("none")) ); - assert!(p["model_error"].as_str().unwrap().contains("401"), "{p}"); + // 一句带码的话,界面按码翻;状态码是参数 + assert_eq!(p["model_error"]["code"], "gw.probe.key_rejected", "{p}"); + assert_eq!(p["model_error"]["args"]["status"], "401", "{p}"); } #[tokio::test] @@ -239,7 +241,8 @@ async fn a_refresh_the_upstream_refuses_says_why_and_the_manual_list_stands_in() .await; assert_eq!(st, StatusCode::OK, "{v}"); assert_eq!(v["source"], "manual"); - assert!(v["error"].as_str().unwrap().contains("401"), "{v}"); + assert_eq!(v["error"]["code"], "gw.probe.key_rejected", "{v}"); + assert!(v["error"]["text"].as_str().unwrap().contains("401"), "{v}"); assert_eq!(v["models"][0]["id"], "手写的模型"); let (st, _) = call( diff --git a/crates/tw-control/tests/resources.rs b/crates/tw-control/tests/resources.rs index 55dbabcd..6725e950 100644 --- a/crates/tw-control/tests/resources.rs +++ b/crates/tw-control/tests/resources.rs @@ -569,8 +569,8 @@ async fn an_unsaved_oauth_credential_is_not_refreshed_just_to_test_it() { .await; let v = json(&body); assert_eq!(v["ok"], false); - assert!( - v["error"].as_str().unwrap().contains("has to be saved"), + assert_eq!( + v["error"]["code"], "control.provider_test.oauth_unsaved", "{body}" ); } diff --git a/crates/tw-control/tests/security.rs b/crates/tw-control/tests/security.rs index 6dea2fe3..15d28d0a 100644 --- a/crates/tw-control/tests/security.rs +++ b/crates/tw-control/tests/security.rs @@ -82,7 +82,7 @@ fn event( tw_store::SecurityEvent { at_ms, request_id, - guard: guard.into(), + guard: tw_api::Guard::from_slug(guard).unwrap(), rule: rule.into(), custom: false, action: action.into(), @@ -447,7 +447,8 @@ async fn a_built_in_rule_s_action_is_written_only_while_it_differs_from_the_fact &b.app, "PUT", "/security/inspect_tools/builtin/rm-rf-root/action", - json!({ "action": "delete" }), + // 内容过滤的动作,工具调用审查不认 + json!({ "action": "block" }), ) .await; assert_eq!(st, StatusCode::BAD_REQUEST, "{v}"); diff --git a/crates/tw-gateway/src/guard.rs b/crates/tw-gateway/src/guard.rs index 78ccaa27..413dfe63 100644 --- a/crates/tw-gateway/src/guard.rs +++ b/crates/tw-gateway/src/guard.rs @@ -207,7 +207,11 @@ fn content_matched( provider: provider.to_string(), rule: h.rule.clone(), custom: h.custom, - action: if blocking { "block" } else { "record" }.to_string(), + action: if blocking { + tw_api::RuleAction::Block + } else { + tw_api::RuleAction::Record + }, blocked: refuse && blocking, in_tool_result: h.in_tool_result, excerpt: h.snippet.clone(), diff --git a/crates/tw-gateway/src/l1.rs b/crates/tw-gateway/src/l1.rs index 56910077..331e17bc 100644 --- a/crates/tw-gateway/src/l1.rs +++ b/crates/tw-gateway/src/l1.rs @@ -24,47 +24,8 @@ use tw_types::{Msg, msg}; /// 一句「8 秒超时」和「TLS 握手 8 秒没完成」的可修复性差得远。 const PHASE_TIMEOUT: Duration = Duration::from_secs(8); -/// 建连的哪一步。 -#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)] -#[serde(rename_all = "snake_case")] -pub enum Step { - /// 地址或代理配置用不了,还没有开始建连 - Config, - Dns, - Tcp, - Tls, - /// 代理协议的握手,含认证 - Handshake, -} - -impl Step { - pub fn slug(&self) -> &'static str { - match self { - Step::Config => "config", - Step::Dns => "dns", - Step::Tcp => "tcp", - Step::Tls => "tls", - Step::Handshake => "handshake", - } - } -} - -/// 这一步对着谁。 -#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)] -#[serde(rename_all = "snake_case")] -pub enum Peer { - Upstream, - Proxy, -} - -impl Peer { - pub fn slug(&self) -> &'static str { - match self { - Peer::Upstream => "upstream", - Peer::Proxy => "proxy", - } - } -} +/// 建连的哪一步、对着谁、为什么缺一步:契约里的那几个集合,这里直接用。 +pub use tw_api::{L1Peer as Peer, L1SkipReason as SkipReason, L1Step as Step}; /// 建连的一步,连同它对着谁。**失败时报的就是它**:「卡在到代理的 TCP /// 握手」和「卡在上游的 TLS 握手」该去修的地方完全不同。 @@ -95,30 +56,23 @@ impl Stage { } } -/// 某一步为什么没有出现在分段里。 -#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)] -#[serde(rename_all = "snake_case")] -pub enum SkipReason { - /// `http://` 地址没有 TLS - PlainHttp, - /// 地址已经是 IP,不需要解析 - IpAddress, - /// `socks5h` 和 HTTP CONNECT 把域名交给代理解析 - ProxyResolves, +#[derive(Debug, Clone, Serialize, Deserialize, PartialEq)] +pub struct Segment { + pub stage: Stage, + pub ms: u64, } -impl SkipReason { - pub fn slug(&self) -> &'static str { - match self { - SkipReason::PlainHttp => "plain_http", - SkipReason::IpAddress => "ip_address", - SkipReason::ProxyResolves => "proxy_resolves", - } - } +/// 没出现在分段里的一步。**不说的话,缺一段看起来就像 bug。** +#[derive(Debug, Clone, Serialize, Deserialize, PartialEq)] +pub struct Skip { + pub stage: Stage, + pub reason: SkipReason, +} +impl Skip { /// 命令行里的说法。 pub fn label(&self) -> &'static str { - match self { + match self.reason { SkipReason::PlainHttp => "an http:// address has no TLS handshake", SkipReason::IpAddress => "already an IP address, so no DNS lookup", SkipReason::ProxyResolves => { @@ -128,19 +82,6 @@ impl SkipReason { } } -#[derive(Debug, Clone, Serialize, Deserialize, PartialEq)] -pub struct Segment { - pub stage: Stage, - pub ms: u64, -} - -/// 没出现在分段里的一步。**不说的话,缺一段看起来就像 bug。** -#[derive(Debug, Clone, Serialize, Deserialize, PartialEq)] -pub struct Skip { - pub stage: Stage, - pub reason: SkipReason, -} - /// **分段是个列表而不是固定的三个字段**,因为走代理时的形状本来就不同: /// 多出代理握手,而 `socks5h` 下根本没有本地 DNS 这一段。用 /// `Option` 表达会把「测不到」和「0 毫秒」混成一件事。 diff --git a/crates/tw-gateway/src/models.rs b/crates/tw-gateway/src/models.rs index cbf79eb9..4eb82943 100644 --- a/crates/tw-gateway/src/models.rs +++ b/crates/tw-gateway/src/models.rs @@ -103,7 +103,7 @@ pub struct Listing { /// 最近一次向上游问的时间。还没问过是空 pub checked_at_ms: Option, /// 没从上游拿到清单的原因 - pub error: Option, + pub error: Option, } /// 最近一次向上游问的结果。 @@ -114,9 +114,9 @@ enum Answer { /// 列出来了 Listed(Vec), /// 问到了,但上游没给出清单:没有这个接口、格式认不出、空的 - NoList(String), + NoList(tw_types::Msg), /// 没问到:连不上、密钥被拒、取不到密钥 - Failed(String), + Failed(tw_types::Msg), } #[derive(Debug, Clone)] @@ -374,23 +374,33 @@ async fn ask(state: &AppState, rt: &Runtime, p: &tw_config::Provider) -> Answer let http = rt.clients.get(&p.name).unwrap_or(&state.http); let headers = match state.headers_for(p, http).await { Ok(h) => h, - Err(e) => return Answer::Failed(format!("the credential could not be obtained: {e}")), + Err(e) => { + return Answer::Failed(msg!( + "gw.models.credentials", detail = e => + "The credential could not be obtained: {detail}" + )); + } }; let r = crate::probe::probe(http, &p.base_url, &headers, p.effective_protocol()).await; if !r.ok { - return Answer::Failed(r.error.unwrap_or_else(|| "the check failed".to_string())); + return Answer::Failed( + r.error + .unwrap_or_else(|| msg!("gw.models.check_failed" => "The check failed.")), + ); } match r.models { ModelList::Listed { models } => Answer::Listed(models), - ModelList::NotImplemented { status } => Answer::NoList(format!( - "the upstream has no model-list endpoint (HTTP {status})" + ModelList::NotImplemented { status } => Answer::NoList(msg!( + "gw.models.no_endpoint", status = status => + "The upstream has no model-list endpoint (HTTP {status})." + )), + ModelList::Unrecognized { .. } => Answer::NoList(msg!( + "gw.models.unrecognized" => + "The model list the upstream returned is in an unrecognized format." + )), + ModelList::Empty => Answer::NoList(msg!( + "gw.models.empty" => "The model list the upstream returned is empty." )), - ModelList::Unrecognized { .. } => Answer::NoList( - "the model list the upstream returned is in an unrecognized format".to_string(), - ), - ModelList::Empty => { - Answer::NoList("the model list the upstream returned is empty".to_string()) - } } } @@ -642,6 +652,15 @@ pub fn serving( mod tests { use super::*; + /// 一句原因。码不要紧,这里比的是哪一句 + fn why(text: &str) -> tw_types::Msg { + tw_types::Msg { + code: "test.why".into(), + args: Default::default(), + text: text.into(), + } + } + fn provider(name: &str) -> tw_config::Provider { tw_config::Provider { name: name.into(), @@ -744,13 +763,13 @@ mod tests { d.record( "a", &identity(&c, &c.providers[0]), - Answer::Failed("连不上".into()), + Answer::Failed(why("连不上")), 0, ); d.record( "b", &identity(&c, &c.providers[1]), - Answer::NoList("没有接口".into()), + Answer::NoList(why("没有接口")), 0, ); let cat = published(&d, &c); @@ -762,7 +781,10 @@ mod tests { assert_eq!(d.due(&c, hour), ["a"]); assert_eq!(d.due(&c, REFRESH_EVERY.as_millis() as u64), ["a", "b"]); assert_eq!( - d.listing(&c.providers[1]).error.as_deref(), + d.listing(&c.providers[1]) + .error + .as_ref() + .map(|m| m.text.as_str()), Some("没有接口") ); } @@ -792,13 +814,13 @@ mod tests { d.record( "failed", &id("failed"), - Answer::Failed("连不上".into()), + Answer::Failed(why("连不上")), now - minute, ); d.record( "failed-now", &id("failed-now"), - Answer::Failed("连不上".into()), + Answer::Failed(why("连不上")), now - 1, ); d.record( @@ -816,7 +838,7 @@ mod tests { d.record( "no-list", &id("no-list"), - Answer::NoList("没有接口".into()), + Answer::NoList(why("没有接口")), now - minute, ); d.begin("asking", &id("asking")); @@ -836,12 +858,12 @@ mod tests { assert!(!d.listing(p).fetching); d.begin("a", &id); d.begin("a", &id); - d.record("a", &id, Answer::Failed("连不上".into()), 1); + d.record("a", &id, Answer::Failed(why("连不上")), 1); // 一个回来了,另一个还在问;上一次的答案照常可用 let l = d.listing(p); assert!(l.fetching); assert_eq!(l.status, Status::Failed); - assert_eq!(l.error.as_deref(), Some("连不上")); + assert_eq!(l.error.as_ref().map(|m| m.text.as_str()), Some("连不上")); // 正在问的不再排进后台那一轮 assert!(d.due(&c, REFRESH_EVERY.as_millis() as u64).is_empty()); d.record("a", &id, Answer::Listed(vec!["m".into()]), 2); @@ -881,13 +903,13 @@ mod tests { d.record( "a", &identity(&c, &c.providers[0]), - Answer::Failed("密钥被拒".into()), + Answer::Failed(why("密钥被拒")), 1, ); let l = d.listing(&c.providers[0]); // 清单来自手写的兜底,但「问了、没问到、为什么」一样要说 assert_eq!((l.source, l.status), (Source::Manual, Status::Failed)); assert_eq!(l.models, ["手写"]); - assert_eq!(l.error.as_deref(), Some("密钥被拒")); + assert_eq!(l.error.as_ref().map(|m| m.text.as_str()), Some("密钥被拒")); } } diff --git a/crates/tw-gateway/src/probe.rs b/crates/tw-gateway/src/probe.rs index b227385d..8862cbd8 100644 --- a/crates/tw-gateway/src/probe.rs +++ b/crates/tw-gateway/src/probe.rs @@ -7,6 +7,7 @@ use std::time::{Duration, Instant}; use serde::{Deserialize, Serialize}; +use tw_types::{Msg, msg}; /// 探测超时。比数据面的建连超时短 —— 探测是交互式的,用户在等着看结果, /// 十秒的白屏比一条「连不上」难受得多。 @@ -57,17 +58,17 @@ pub struct ProbeResult { /// L2 的结果,**带上为什么** pub models: ModelList, /// 失败时说清楚下一步做什么 - pub error: Option, + pub error: Option, } impl ProbeResult { - fn fail(latency_ms: u64, protocol: Option, msg: impl Into) -> Self { + fn fail(latency_ms: u64, protocol: Option, why: Msg) -> Self { Self { ok: false, protocol, latency_ms, models: ModelList::Empty, - error: Some(msg.into()), + error: Some(why), } } } @@ -101,17 +102,26 @@ pub async fn probe( Ok(r) => r, Err(e) => { let ms = started.elapsed().as_millis() as u64; - let msg = if e.is_timeout() { - format!( - "no answer within {PROBE_TIMEOUT:?}. Check the endpoint address, or whether this upstream has to be reached through a proxy" + let why = if e.is_timeout() { + msg!( + "gw.probe.timeout", secs = PROBE_TIMEOUT.as_secs() => + "No answer within {secs} seconds. Check the endpoint address, or whether this \ + upstream has to be reached through a proxy." ) } else if e.is_connect() { - "could not connect. Check the spelling of the endpoint address and the network; if this upstream has to be reached through a proxy, configure the proxy first" - .to_string() + msg!( + "gw.probe.connect" => + "Could not connect. Check the spelling of the endpoint address and the network; \ + if this upstream has to be reached through a proxy, configure the proxy first." + ) } else { - format!("the request failed: {e}") + // reqwest 的原话:系统或 TLS 库给的,没有别的说法 + msg!( + "gw.probe.request_failed", detail = e => + "The request failed: {detail}" + ) }; - return ProbeResult::fail(ms, proto_name, msg); + return ProbeResult::fail(ms, proto_name, why); } }; @@ -124,9 +134,10 @@ pub async fn probe( return ProbeResult::fail( ms, proto_name, - format!( - "the upstream rejected this key (HTTP {}). Check the key for stray whitespace, and that it belongs to this upstream", - status.as_u16() + msg!( + "gw.probe.key_rejected", status = status.as_u16() => + "The upstream rejected this key (HTTP {status}). Check the key for stray whitespace, \ + and that it belongs to this upstream." ), ); } diff --git a/crates/tw-gateway/src/server.rs b/crates/tw-gateway/src/server.rs index 082e56ef..e990ce61 100644 --- a/crates/tw-gateway/src/server.rs +++ b/crates/tw-gateway/src/server.rs @@ -222,28 +222,28 @@ pub async fn serve(state: AppState, addr: std::net::SocketAddr) -> std::io::Resu /// 上游回了话的一跳:`served` 或者 `status`。 pub(crate) fn hop( provider: &str, - outcome: &str, + outcome: tw_api::AttemptOutcome, status: u16, started: std::time::Instant, ) -> tw_api::AttemptView { tw_api::AttemptView { provider: provider.to_string(), - outcome: outcome.to_string(), + outcome, status: Some(status), error: None, ms: started.elapsed().as_millis() as u64, } } -/// 没有收到响应的一跳。 +/// 没有收到响应的一跳。`error` 和这一跳报给客户端的那条错误是同一句。 pub(crate) fn hop_failed( provider: &str, - error: String, + error: tw_types::Msg, started: std::time::Instant, ) -> tw_api::AttemptView { tw_api::AttemptView { provider: provider.to_string(), - outcome: "error".to_string(), + outcome: tw_api::AttemptOutcome::Error, status: None, error: Some(error), ms: started.elapsed().as_millis() as u64, @@ -283,7 +283,11 @@ pub(crate) fn flagged( custom: v.custom, why: v.why.clone(), excerpt: v.excerpt.clone(), - action: if v.cut { "cut" } else { "record" }.to_string(), + action: if v.cut { + tw_api::RuleAction::Cut + } else { + tw_api::RuleAction::Record + }, blocked, at_ms: now_ms(), } diff --git a/crates/tw-gateway/src/server/pipeline/hop.rs b/crates/tw-gateway/src/server/pipeline/hop.rs index 0a00b8aa..0dab27d5 100644 --- a/crates/tw-gateway/src/server/pipeline/hop.rs +++ b/crates/tw-gateway/src/server/pipeline/hop.rs @@ -41,8 +41,8 @@ struct Outbound { session: Option, } -/// 这一跳没发出去的原因:给尝试链的一句,和给客户端的那个错误。 -type Skip = (String, GatewayError); +/// 这一跳没发出去的原因。尝试链里记的和报给客户端的是同一句。 +type Skip = GatewayError; pub(super) async fn try_upstreams<'a>( state: &AppState, @@ -73,8 +73,8 @@ pub(super) async fn try_upstreams<'a>( attempts.push(provider.name.clone()); let hop_started = std::time::Instant::now(); - if let Some((why, err)) = protocol_mismatch(req, reading.generates, provider) { - chain.push(hop_failed(&provider.name, why, hop_started)); + if let Some(err) = protocol_mismatch(req, reading.generates, provider) { + chain.push(hop_failed(&provider.name, err.detail.clone(), hop_started)); last_err = Some(err); continue; } @@ -105,8 +105,8 @@ pub(super) async fn try_upstreams<'a>( let out = match prepare(state, req, reading, provider, &effective_set, id) { Ok(out) => out, - Err((why, err)) => { - chain.push(hop_failed(&provider.name, why, hop_started)); + Err(err) => { + chain.push(hop_failed(&provider.name, err.detail.clone(), hop_started)); last_err = Some(err); continue; } @@ -132,15 +132,12 @@ pub(super) async fn try_upstreams<'a>( &provider.name, state.health.record_failure(&provider.name), ); - chain.push(hop_failed( - &provider.name, - format!("the credential could not be obtained: {e}"), - hop_started, - )); - last_err = Some(GatewayError::config(msg!( + let err = GatewayError::config(msg!( "gw.credentials.failed", upstream = provider.name.clone(), detail = e => "The credential for upstream `{upstream}` could not be obtained: {detail}" - ))); + )); + chain.push(hop_failed(&provider.name, err.detail.clone(), hop_started)); + last_err = Some(err); continue; } }; @@ -172,7 +169,7 @@ pub(super) async fn try_upstreams<'a>( ); chain.push(hop( &provider.name, - "status", + tw_api::AttemptOutcome::Status, r.status().as_u16(), hop_started, )); @@ -200,7 +197,7 @@ pub(super) async fn try_upstreams<'a>( ); chain.push(hop( &provider.name, - "served", + tw_api::AttemptOutcome::Served, r.status().as_u16(), hop_started, )); @@ -222,11 +219,7 @@ pub(super) async fn try_upstreams<'a>( // 连不上的可能是代理而不是上游 —— 检一次那个代理,说清是哪一件事 state.check_proxy(&provider.proxy); let err = forward::map_reqwest_error(e); - chain.push(hop_failed( - &provider.name, - err.message().to_string(), - hop_started, - )); + chain.push(hop_failed(&provider.name, err.detail.clone(), hop_started)); last_err = Some(err); continue; } @@ -293,21 +286,13 @@ fn protocol_mismatch( if a.protocol() == p { return None; } - let why = format!( - "{} can only be served by a {} upstream", - req.uri.path(), - a.slug() - ); - Some(( - why, - GatewayError::new( - crate::error::Source::Request, - msg!( - "gw.route.protocol_mismatch", - path = req.uri.path(), wanted = a.slug(), - upstream = provider.name.clone(), got = p.slug() => - "{path} can only be served by a {wanted} upstream, and `{upstream}` is {got}." - ), + Some(GatewayError::new( + crate::error::Source::Request, + msg!( + "gw.route.protocol_mismatch", + path = req.uri.path(), wanted = a.slug(), + upstream = provider.name.clone(), got = p.slug() => + "{path} can only be served by a {wanted} upstream, and `{upstream}` is {got}." ), )) } @@ -393,15 +378,12 @@ fn prepare( Some(Err(rej)) => rej.0.clone(), _ => "the request body is not valid JSON".to_string(), }; - return Err(( - format!("could not be converted to {}: {why}", dialect.slug()), - GatewayError::new( - crate::error::Source::Request, - msg!( - "gw.convert.failed", upstream = provider.name.clone(), detail = why => - "The request could not be converted to the format upstream \ - `{upstream}` speaks: {detail}" - ), + return Err(GatewayError::new( + crate::error::Source::Request, + msg!( + "gw.convert.failed", upstream = provider.name.clone(), detail = why => + "The request could not be converted to the format upstream \ + `{upstream}` speaks: {detail}" ), )); } diff --git a/crates/tw-gateway/src/state/upstream.rs b/crates/tw-gateway/src/state/upstream.rs index 8de881b4..097976b1 100644 --- a/crates/tw-gateway/src/state/upstream.rs +++ b/crates/tw-gateway/src/state/upstream.rs @@ -163,8 +163,8 @@ impl AppState { }; let fault = result.as_ref().map(|(stage, why)| tw_api::ProxyFault { failed: stage.as_ref().map(|s| tw_api::L1Stage { - step: s.step.slug().into(), - peer: s.peer.slug().into(), + step: s.step, + peer: s.peer, }), detail: why.clone(), at_ms: now_ms(), diff --git a/crates/tw-gateway/src/ws.rs b/crates/tw-gateway/src/ws.rs index ab55c3d0..4f8f0e0d 100644 --- a/crates/tw-gateway/src/ws.rs +++ b/crates/tw-gateway/src/ws.rs @@ -160,11 +160,11 @@ pub async fn proxy( // 报在结局之前,存储层落库时手上才有它 let name = &upstream.provider.name; let attempt = match &connected { - Ok(_) => crate::server::hop(name, "served", 101, hop_started), + Ok(_) => crate::server::hop(name, tw_api::AttemptOutcome::Served, 101, hop_started), Err(NotConnected { status: Some(s), .. - }) => crate::server::hop(name, "status", *s, hop_started), - Err(e) => crate::server::hop_failed(name, e.why.text.clone(), hop_started), + }) => crate::server::hop(name, tw_api::AttemptOutcome::Status, *s, hop_started), + Err(e) => crate::server::hop_failed(name, e.why.clone(), hop_started), }; // 和 HTTP 那条路同一个规矩:没接下的不按那一家记账 let billing = match &connected { diff --git a/crates/tw-gateway/tests/m5_toolwall.rs b/crates/tw-gateway/tests/m5_toolwall.rs index 14a7fde1..371616ea 100644 --- a/crates/tw-gateway/tests/m5_toolwall.rs +++ b/crates/tw-gateway/tests/m5_toolwall.rs @@ -136,7 +136,7 @@ async fn flagged( .. } = ev { - return Some((action == "cut", blocked, tool, rule)); + return Some((action == tw_api::RuleAction::Cut, blocked, tool, rule)); } } None diff --git a/crates/tw-gateway/tests/passthrough.rs b/crates/tw-gateway/tests/passthrough.rs index c3f5db5a..55bc823e 100644 --- a/crates/tw-gateway/tests/passthrough.rs +++ b/crates/tw-gateway/tests/passthrough.rs @@ -2057,12 +2057,17 @@ async fn the_attempt_chain_records_every_hop_and_why_each_one_failed() { assert_eq!(group.as_deref(), Some("全部")); assert_eq!(attempts.len(), 3, "{attempts:?}"); assert_eq!(attempts[0].provider, "挂了的"); - assert_eq!(attempts[0].outcome, "status", "{:?}", attempts[0]); + assert_eq!( + attempts[0].outcome, + tw_api::AttemptOutcome::Status, + "{:?}", + attempts[0] + ); assert_eq!(attempts[0].status, Some(503), "{:?}", attempts[0]); assert_eq!(attempts[1].provider, "限流的"); assert_eq!(attempts[1].status, Some(429), "{:?}", attempts[1]); assert_eq!(attempts[2].provider, "好的"); - assert_eq!(attempts[2].outcome, "served"); + assert_eq!(attempts[2].outcome, tw_api::AttemptOutcome::Served); assert_eq!(attempts[2].status, Some(200)); } @@ -2095,7 +2100,7 @@ async fn a_request_that_succeeds_first_try_still_has_a_chain_of_one() { tokio::time::timeout(Duration::from_secs(2), rx.recv()).await { assert_eq!(attempts.len(), 1); - assert_eq!(attempts[0].outcome, "served"); + assert_eq!(attempts[0].outcome, tw_api::AttemptOutcome::Served); return; } } @@ -2131,7 +2136,12 @@ async fn a_request_that_fails_everywhere_still_reports_the_chain() { tokio::time::timeout(Duration::from_secs(2), rx.recv()).await { assert_eq!(attempts.len(), 1); - assert_eq!(attempts[0].outcome, "status", "{:?}", attempts[0]); + assert_eq!( + attempts[0].outcome, + tw_api::AttemptOutcome::Status, + "{:?}", + attempts[0] + ); assert_eq!(attempts[0].status, Some(503), "{:?}", attempts[0]); return; } diff --git a/crates/tw-gateway/tests/ws.rs b/crates/tw-gateway/tests/ws.rs index 41adb647..05f12fe9 100644 --- a/crates/tw-gateway/tests/ws.rs +++ b/crates/tw-gateway/tests/ws.rs @@ -405,7 +405,7 @@ async fn a_websocket_session_reports_its_route_and_its_upstreams_billing() { assert_eq!(rule, "Codex 走账号"); assert_eq!(group.as_deref(), Some("账号池")); assert_eq!( - (hop.provider.as_str(), hop.outcome.as_str(), hop.status), + (hop.provider.as_str(), hop.outcome.slug(), hop.status), ("订阅账号", "served", Some(101)) ); assert_eq!(billing, "free"); @@ -431,7 +431,7 @@ async fn an_upstream_that_refuses_the_upgrade_is_reported_with_its_status() { let evs = until_the_ending(&mut events).await; let (_, _, hop, billing) = the_route(&evs); - assert_eq!((hop.outcome.as_str(), hop.status), ("status", Some(403))); + assert_eq!((hop.outcome.slug(), hop.status), ("status", Some(403))); assert_eq!(hop.error, None); assert_eq!(billing, "per-token", "没接下的请求被按那一家记成了不计费"); assert!( @@ -453,9 +453,9 @@ async fn an_unreachable_upstream_is_reported_as_a_failed_hop() { let evs = until_the_ending(&mut events).await; let (_, _, hop, billing) = the_route(&evs); - assert_eq!((hop.outcome.as_str(), hop.status), ("error", None)); + assert_eq!((hop.outcome.slug(), hop.status), ("error", None)); let why = hop.error.expect("失败的那一跳没说原因"); - assert!(why.contains(&dead.to_string()), "{why}"); + assert!(why.text.contains(&dead.to_string()), "{why}"); assert_eq!(billing, "per-token"); assert!( matches!(evs.last(), Some(Event::RequestFailed { source, .. }) if source == "upstream"), diff --git a/crates/tw-store/src/db.rs b/crates/tw-store/src/db.rs index a5fc1ad7..82b20a7c 100644 --- a/crates/tw-store/src/db.rs +++ b/crates/tw-store/src/db.rs @@ -19,7 +19,7 @@ use tw_api::Msg; /// 当前 schema 版本。**表的样子一变就加一,改 [`Db::create`] 里那一份。** /// 不写迁移:项目还没有存量用户,版本对不上的库整个重建。 -const SCHEMA: i64 = 18; +const SCHEMA: i64 = 19; /// 这一行算不出钱,**因为价目表里没有这个模型**:用量是有的,缺的是单价。 /// @@ -697,7 +697,7 @@ impl Db { params![ e.at_ms, e.request_id, - e.guard, + e.guard.slug(), e.rule, e.custom as i64, e.action, @@ -1088,8 +1088,7 @@ pub struct Summary { pub struct SecurityEvent { pub at_ms: i64, pub request_id: i64, - /// `redact` / `inspect_tools` / `hidden_text` / `content` / `output_limit` - pub guard: String, + pub guard: tw_api::Guard, /// 内置规则的 id,或者自定义规则的名字 pub rule: String, pub custom: bool, @@ -1118,7 +1117,16 @@ fn security_view(r: &rusqlite::Row) -> rusqlite::Result(5)? != 0, action: r.get(6)?, diff --git a/crates/tw-store/src/recorder.rs b/crates/tw-store/src/recorder.rs index 081eadb5..c8be3888 100644 --- a/crates/tw-store/src/recorder.rs +++ b/crates/tw-store/src/recorder.rs @@ -326,7 +326,7 @@ impl Recorder { self.record_security(crate::db::SecurityEvent { at_ms: *at_ms as i64, request_id: *id as i64, - guard: "redact".into(), + guard: tw_api::Guard::Redact, rule: it.rule.clone(), custom: it.custom, action: if *replaced { "replaced" } else { "recorded" }.into(), @@ -356,7 +356,7 @@ impl Recorder { self.record_security(crate::db::SecurityEvent { at_ms: *at_ms as i64, request_id: *id as i64, - guard: "hidden_text".into(), + guard: tw_api::Guard::HiddenText, rule: it.kind.clone(), custom: false, action: if *blocked { "blocked" } else { "recorded" }.into(), @@ -383,7 +383,7 @@ impl Recorder { self.record_security(crate::db::SecurityEvent { at_ms: *at_ms as i64, request_id: *id as i64, - guard: "content".into(), + guard: tw_api::Guard::Content, rule: rule.clone(), custom: *custom, action: if *blocked { "blocked" } else { "recorded" }.into(), @@ -406,7 +406,7 @@ impl Recorder { self.record_security(crate::db::SecurityEvent { at_ms: *at_ms as i64, request_id: *id as i64, - guard: "output_limit".into(), + guard: tw_api::Guard::OutputLimit, rule: "max_chars".into(), custom: false, action: if *cut { "cut" } else { "recorded" }.into(), @@ -437,7 +437,7 @@ impl Recorder { self.record_security(crate::db::SecurityEvent { at_ms: *at_ms as i64, request_id: *id as i64, - guard: "inspect_tools".into(), + guard: tw_api::Guard::InspectTools, rule: rule.clone(), custom: *custom, action: if *blocked { "cut" } else { "recorded" }.into(), @@ -797,14 +797,18 @@ mod tests { attempts: vec![ tw_api::AttemptView { provider: "官方".into(), - outcome: "error".into(), + outcome: tw_api::AttemptOutcome::Error, status: None, - error: Some("上游响应超时".into()), + error: Some(tw_api::Msg { + code: "gw.upstream.timeout".into(), + args: Default::default(), + text: "上游响应超时".into(), + }), ms: 10_003, }, tw_api::AttemptView { provider: "中转".into(), - outcome: "served".into(), + outcome: tw_api::AttemptOutcome::Served, status: Some(200), error: None, ms: 5_042, @@ -825,8 +829,11 @@ mod tests { serde_json::from_str(row.routing.as_deref().unwrap()).unwrap(); assert_eq!(routing.attempts.len(), 2); assert_eq!(routing.attempts[0].provider, "官方"); - assert_eq!(routing.attempts[0].outcome, "error"); - assert_eq!(routing.attempts[0].error.as_deref(), Some("上游响应超时")); + assert_eq!(routing.attempts[0].outcome, tw_api::AttemptOutcome::Error); + assert_eq!( + routing.attempts[0].error.as_ref().map(|m| m.text.as_str()), + Some("上游响应超时") + ); } /// 一次就成的请求不该被这条规则改坏:链长度为 1,最后一跳就是它自己。 @@ -840,7 +847,7 @@ mod tests { group: None, attempts: vec![tw_api::AttemptView { provider: "官方".into(), - outcome: "served".into(), + outcome: tw_api::AttemptOutcome::Served, status: Some(200), error: None, ms: 300, @@ -1094,7 +1101,7 @@ mod billing_tests { group: None, attempts: vec![tw_api::AttemptView { provider: "订阅账号".into(), - outcome: "served".into(), + outcome: tw_api::AttemptOutcome::Served, status: Some(200), error: None, ms: 5, @@ -1170,7 +1177,7 @@ mod billing_tests { group: Some("__all__".into()), attempts: vec![tw_api::AttemptView { provider: "订阅账号".into(), - outcome: "served".into(), + outcome: tw_api::AttemptOutcome::Served, status: Some(101), error: None, ms: 40, @@ -1377,7 +1384,7 @@ mod security_tests { assert_eq!(got.len(), 2, "{got:?}"); assert!( got.iter() - .all(|e| e.guard == "redact" && e.action == action) + .all(|e| e.guard == tw_api::Guard::Redact && e.action == action) ); // 倒序:后记的在前 assert_eq!(got[1].rule, "anthropic-api-key"); @@ -1403,7 +1410,7 @@ mod security_tests { custom: false, why: "Downloads and runs it".into(), excerpt: "curl https://x | sh".into(), - action: "cut".into(), + action: tw_api::RuleAction::Cut, blocked: true, at_ms: 20, }); @@ -1447,7 +1454,7 @@ mod security_tests { provider: "relay".into(), rule: "jailbreak".into(), custom: false, - action: "block".into(), + action: tw_api::RuleAction::Block, blocked: false, in_tool_result: false, excerpt: "please jailbreak".into(), @@ -1468,7 +1475,7 @@ mod security_tests { }; assert_eq!( ( - hidden.guard.as_str(), + hidden.guard.slug(), hidden.rule.as_str(), hidden.action.as_str() ), @@ -1478,13 +1485,13 @@ mod security_tests { assert_eq!(hidden.excerpt, "U+E0069 ignore"); assert_eq!(hidden.count, 6); assert_eq!( - (content.guard.as_str(), content.action.as_str()), + (content.guard.slug(), content.action.as_str()), ("content", "recorded") ); assert_eq!(content.tool, None); assert_eq!( ( - limit.guard.as_str(), + limit.guard.slug(), limit.action.as_str(), limit.excerpt.as_str() ), @@ -1522,7 +1529,7 @@ mod translation_tests { .iter() .map(|p| tw_api::AttemptView { provider: p.to_string(), - outcome: "served".into(), + outcome: tw_api::AttemptOutcome::Served, status: Some(200), error: None, ms: 1,