diff --git a/.gitattributes b/.gitattributes new file mode 100644 index 00000000..b413575e --- /dev/null +++ b/.gitattributes @@ -0,0 +1,2 @@ +# 桌面端按行读消息码清单,换行不能随平台变 +crates/tw-api/msg-codes.txt text eol=lf diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml index 0c57bf46..98d0e401 100644 --- a/.github/workflows/ci.yml +++ b/.github/workflows/ci.yml @@ -36,6 +36,16 @@ jobs: - name: Test run: cargo test --workspace + # 桌面端从 tw-api 导出前端类型(`ts` feature)。**默认关**,上面几步一行都 + # 不编它 —— 而它坏掉的表现是桌面端接下一个 tag 时才发现导不出来。导出来 + # 的文件再过一遍 tsc:ts-rs 生成的东西本身也可能不是合法的 TypeScript + - name: TypeScript bindings (tw-api, ts) + run: | + cargo clippy -p tw-api --all-targets --features ts -- -D warnings + cargo test -p tw-api --features ts + cargo run -p tw-api --features ts --example export_ts -- "$RUNNER_TEMP/tw-api-ts" + npx --yes -p typescript@5 tsc --noEmit --strict --target es2022 "$RUNNER_TEMP/tw-api-ts/tw-api.ts" + - name: Build run: cargo build --release -p twcore diff --git a/Cargo.lock b/Cargo.lock index e2697c15..2584e34d 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -2045,6 +2045,15 @@ dependencies = [ "windows-sys 0.61.2", ] +[[package]] +name = "termcolor" +version = "1.4.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "06794f8f6c5c898b3275aebefa6b8a1cb24cd2c6c79397ab15774837a0bc5755" +dependencies = [ + "winapi-util", +] + [[package]] name = "thiserror" version = "2.0.20" @@ -2337,6 +2346,28 @@ version = "0.2.5" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "e421abadd41a4225275504ea4d6566923418b7f05506fbc9c0fe86ba7396114b" +[[package]] +name = "ts-rs" +version = "12.0.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "756050066659291d47a554a9f558125db17428b073c5ffce1daf5dcb0f7231d8" +dependencies = [ + "thiserror", + "ts-rs-macros", +] + +[[package]] +name = "ts-rs-macros" +version = "12.0.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "38d90eea51bc7988ef9e674bf80a85ba6804739e535e9cab48e4bb34a8b652aa" +dependencies = [ + "proc-macro2", + "quote", + "syn 2.0.119", + "termcolor", +] + [[package]] name = "tungstenite" version = "0.28.0" @@ -2393,6 +2424,7 @@ version = "0.41.0" dependencies = [ "serde", "serde_json", + "ts-rs", "tw-types", ] @@ -2444,6 +2476,7 @@ dependencies = [ "reqwest", "serde", "serde_json", + "serde_urlencoded", "serde_yaml_ng", "sha2", "tempfile", @@ -2616,6 +2649,7 @@ version = "0.41.0" dependencies = [ "serde", "serde_json", + "ts-rs", ] [[package]] diff --git a/Cargo.toml b/Cargo.toml index 4eef634e..f1d5e2c7 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -121,6 +121,9 @@ uuid = { version = "1", features = ["v4", "serde"] } rand = "0.10" clap = { version = "4", features = ["derive"] } +# 控制面契约导出成 TypeScript(tw-api 的 `ts` feature)。**不开任何 serde 以外的 +# 类型实现**:契约里只有 std 和 serde 的类型 +ts-rs = { version = "12", default-features = false, features = ["serde-compat"] } [profile.release] # 桌面 sidecar:体积比极限吞吐重要。企业版用 lto = true + codegen-units = 1, diff --git a/bin/twcore/src/main.rs b/bin/twcore/src/main.rs index d8da90a1..0e07655f 100644 --- a/bin/twcore/src/main.rs +++ b/bin/twcore/src/main.rs @@ -723,8 +723,8 @@ fn cmd_serve(path: &Path, port: Option, safe: bool, parent: Option) -> let rt = tokio::runtime::Builder::new_multi_thread() .enable_all() .build()?; - // 控制面听在哪由平台决定,见 `tw_api::control::Endpoint`。 - let endpoint = tw_api::control::Endpoint::in_dir(&dir); + // 控制面听在哪由平台决定,见 `tw_api::control::Address`。 + let endpoint = tw_api::control::Address::in_dir(&dir); // **在起任何东西之前问**。等到 bind 失败时,网关已经在监听、客户端 // 可能已经连上来了,而这条错误当时只会进日志。 tw_control::endpoint_usable(&endpoint)?; diff --git a/bin/twcore/tests/msg_codes.rs b/bin/twcore/tests/msg_codes.rs new file mode 100644 index 00000000..4bf6f75e --- /dev/null +++ b/bin/twcore/tests/msg_codes.rs @@ -0,0 +1,545 @@ +//! core 发得出的每一个消息码都在 `crates/tw-api/msg-codes.txt` 里,清单里也 +//! 没有发不出的码。 +//! +//! 桌面端按码翻译(`src/i18n/core.i18n.ts`),它钉着 core 的某个 tag,从那个 +//! tag 的 tw-api 里读这份清单([`tw_api::MSG_CODES`]),和自己的译文表对一遍: +//! 多一个没翻的码,中文界面上那一句就悄悄变成英文。以前两边对得上全靠人记得。 +//! +//! 码从源码里找,**不从运行时收集**:有的码只在另一个平台上编译得到 +//! (`#[cfg(windows)]` 那一支),而清单要两个平台的都有。认得的写法只有两种: +//! +//! - `msg!("码", …)`,或者 `msg!(常量, …)` 而那个常量是个字符串字面量; +//! - `code!("码")` —— 码和句子分开存在表里的地方(tw-adopt 的那几张表)。 +//! +//! `msg!` 的第一个参数是别的样子时这里直接失败,而不是漏掉它。 +//! +//! 清单一行一个码,按字母排。后面可以跟一个标记: +//! +//! - `passthrough`:句子只有占位符(`"{detail}"`),原文是系统或上游的话, +//! 界面照 `text` 显示,不用翻(位置参数 `"{}"` 不算,那是句子在别处写好了); +//! - `test`:只在测试里出现,不会到界面上。 + +use std::collections::{BTreeMap, BTreeSet, HashMap}; +use std::path::{Path, PathBuf}; + +const MANIFEST: &str = "crates/tw-api/msg-codes.txt"; +const UPDATE: &str = "UPDATE_MSG_CODES"; + +fn workspace() -> PathBuf { + Path::new(env!("CARGO_MANIFEST_DIR")).join("../..") +} + +fn rust_files(dir: &Path, out: &mut Vec) { + let Ok(rd) = std::fs::read_dir(dir) else { + return; + }; + for e in rd.flatten() { + let p = e.path(); + if p.is_dir() { + if p.file_name().is_some_and(|n| n == "target") { + continue; + } + rust_files(&p, out); + } else if p.extension().is_some_and(|x| x == "rs") { + out.push(p); + } + } +} + +#[derive(Debug, Clone, PartialEq)] +enum Tok { + Str(String), + Ident(String), + Punct(char), +} + +/// 把一段源码切成记号,连同所在行。**跳过注释、字符字面量和生命周期。** +fn lex(src: &str) -> Vec<(usize, Tok)> { + let c: Vec = src.chars().collect(); + let mut out = Vec::new(); + let (mut i, mut line) = (0, 1); + let ident = |ch: char| ch.is_alphanumeric() || ch == '_'; + while i < c.len() { + match c[i] { + '\n' => { + line += 1; + i += 1; + } + ch if ch.is_whitespace() => i += 1, + '/' if c.get(i + 1) == Some(&'/') => { + while i < c.len() && c[i] != '\n' { + i += 1; + } + } + '/' if c.get(i + 1) == Some(&'*') => { + let mut depth = 0; + while i < c.len() { + if c[i] == '/' && c.get(i + 1) == Some(&'*') { + depth += 1; + i += 2; + } else if c[i] == '*' && c.get(i + 1) == Some(&'/') { + depth -= 1; + i += 2; + if depth == 0 { + break; + } + } else { + if c[i] == '\n' { + line += 1; + } + i += 1; + } + } + } + '\'' => { + // 字符字面量('x'、'\n'、'中')整个跳过;否则是生命周期 + if c.get(i + 1) == Some(&'\\') { + i += 2; + while i < c.len() && c[i] != '\'' { + i += 1; + } + i += 1; + } else if c.get(i + 2) == Some(&'\'') { + i += 3; + } else { + i += 1; + while i < c.len() && ident(c[i]) { + i += 1; + } + } + } + // 原始字符串 r"…"、r#"…"#,以及字节串 b"…"、br"…" + 'r' | 'b' + if (i == 0 || !ident(c[i - 1])) + && (matches!(c.get(i + 1), Some('"') | Some('#')) + || (c[i] == 'b' + && c.get(i + 1) == Some(&'r') + && matches!(c.get(i + 2), Some('"') | Some('#')))) => + { + let raw = c[i] == 'r' || c.get(i + 1) == Some(&'r'); + let mut j = if c[i] == 'b' && raw { i + 2 } else { i + 1 }; + if !raw { + // b"…":和普通字符串一样读 + i = j; + let (lit, end) = quoted(&c, i); + line += lit.matches('\n').count(); + out.push((line, Tok::Str(lit))); + i = end; + continue; + } + let mut hashes = 0; + while c.get(j) == Some(&'#') { + hashes += 1; + j += 1; + } + if c.get(j) != Some(&'"') { + // r#ident:原始标识符 + let s = j; + while j < c.len() && ident(c[j]) { + j += 1; + } + out.push((line, Tok::Ident(c[s..j].iter().collect()))); + i = j; + continue; + } + let start = j + 1; + let mut k = start; + let end = loop { + if k >= c.len() { + break c.len(); + } + if c[k] == '"' && (1..=hashes).all(|h| c.get(k + h) == Some(&'#')) { + break k; + } + k += 1; + }; + let lit: String = c[start..end].iter().collect(); + out.push((line, Tok::Str(lit.clone()))); + line += lit.matches('\n').count(); + i = end + 1 + hashes; + } + '"' => { + let (lit, end) = quoted(&c, i); + out.push((line, Tok::Str(lit.clone()))); + line += lit.matches('\n').count(); + i = end; + } + ch if ident(ch) => { + let s = i; + while i < c.len() && ident(c[i]) { + i += 1; + } + out.push((line, Tok::Ident(c[s..i].iter().collect()))); + } + ch => { + out.push((line, Tok::Punct(ch))); + i += 1; + } + } + } + out +} + +/// 从 `c[at]` 的 `"` 读到配对的 `"`,返回内容(转义原样保留)和结束之后的位置。 +fn quoted(c: &[char], at: usize) -> (String, usize) { + let start = at + 1; + let mut k = start; + while k < c.len() && c[k] != '"' { + k += if c[k] == '\\' { 2 } else { 1 }; + } + let end = k.min(c.len()); + (c[start..end].iter().collect(), end + 1) +} + +fn is(t: Option<&(usize, Tok)>, want: &Tok) -> bool { + t.is_some_and(|(_, t)| t == want) +} + +/// 哪些记号在测试代码里:`#[cfg(test)]`、`#[test]`、`#[tokio::test]` 标着的那一项。 +fn test_mask(toks: &[(usize, Tok)]) -> Vec { + let mut mask = vec![false; toks.len()]; + let mut i = 0; + while i < toks.len() { + if !(is(toks.get(i), &Tok::Punct('#')) && is(toks.get(i + 1), &Tok::Punct('['))) { + i += 1; + continue; + } + // 这一条属性到哪儿结束 + let mut j = i + 2; + let mut depth = 1; + while j < toks.len() && depth > 0 { + match &toks[j].1 { + Tok::Punct('[') => depth += 1, + Tok::Punct(']') => depth -= 1, + _ => {} + } + j += 1; + } + let attr: Vec<&Tok> = toks[i + 2..j - 1].iter().map(|(_, t)| t).collect(); + let cfg_test = attr + == [ + &Tok::Ident("cfg".into()), + &Tok::Punct('('), + &Tok::Ident("test".into()), + &Tok::Punct(')'), + ]; + let test_fn = attr.last() == Some(&&Tok::Ident("test".into())); + if cfg_test || test_fn { + // 标着的那一项:到第一个 `;`(没有体)或者配对的 `}` 为止 + let mut k = j; + let mut depth = 0; + while k < toks.len() { + match &toks[k].1 { + Tok::Punct(';') if depth == 0 => break, + Tok::Punct('{') => depth += 1, + Tok::Punct('}') => { + depth -= 1; + if depth == 0 { + break; + } + } + _ => {} + } + k += 1; + } + for m in &mut mask[i..=k.min(toks.len() - 1)] { + *m = true; + } + } + i = j; + } + mask +} + +#[derive(Debug, Default, Clone, Copy)] +struct Seen { + product: bool, + test: bool, + /// 产品代码里有一处的句子不只是占位符 + worded: bool, +} + +/// 一处 `msg!` 的第一个参数:字面量,或者一个常量名。 +enum First { + Lit(String), + Const(String), +} + +struct Site { + file: String, + line: usize, + first: First, + /// `=>` 后面的第一个字符串字面量。`code!` 没有 + template: Option, + test: bool, +} + +fn scan(root: &Path) -> (Vec, HashMap) { + let mut files = Vec::new(); + rust_files(&root.join("crates"), &mut files); + rust_files(&root.join("bin"), &mut files); + files.sort(); + + let mut sites = Vec::new(); + let mut consts = HashMap::new(); + for f in &files { + let rel_path = f.strip_prefix(root).unwrap_or(f); + let rel = rel_path.display().to_string(); + // 这个文件自己的例子不算 + if rel_path.ends_with("tests/msg_codes.rs") { + continue; + } + // **按路径的组成部分判断**,Windows 上分隔符是 `\` + let test_file = rel_path.components().any(|c| { + let c = c.as_os_str(); + c.eq_ignore_ascii_case("tests") + || c.eq_ignore_ascii_case("examples") + || c.eq_ignore_ascii_case("benches") + }); + let src = std::fs::read_to_string(f).unwrap(); + let toks = lex(&src); + let mask = test_mask(&toks); + for i in 0..toks.len() { + // const NAME: &str = "…"; + if let (Tok::Ident(kw), Some((_, Tok::Ident(name)))) = (&toks[i].1, toks.get(i + 1)) + && kw == "const" + && let Some(eq) = + (i + 2..(i + 8).min(toks.len())).find(|&k| toks[k].1 == Tok::Punct('=')) + && let Some((_, Tok::Str(v))) = toks.get(eq + 1) + && toks[i + 2..eq] + .iter() + .any(|(_, t)| *t == Tok::Ident("str".into())) + { + consts.insert(name.clone(), v.clone()); + } + + let Tok::Ident(mac) = &toks[i].1 else { + continue; + }; + if !(mac == "msg" || mac == "code") + || !is(toks.get(i + 1), &Tok::Punct('!')) + || !is(toks.get(i + 2), &Tok::Punct('(')) + { + continue; + } + let line = toks[i].0; + let first = match toks.get(i + 3).map(|(_, t)| t) { + Some(Tok::Str(s)) => First::Lit(s.clone()), + Some(Tok::Ident(n)) if mac == "msg" => { + // 路径形式(`a::B`)取最后一段 + let mut k = i + 3; + while is(toks.get(k + 1), &Tok::Punct(':')) + && is(toks.get(k + 2), &Tok::Punct(':')) + { + k += 3; + } + match toks.get(k).map(|(_, t)| t) { + Some(Tok::Ident(n)) => First::Const(n.clone()), + _ => First::Const(n.clone()), + } + } + other => panic!( + "{rel}:{line}: `{mac}!` 的第一个参数不是字符串字面量也不是常量({other:?})。\ + 消息码要写成字面量,这个测试才找得到它" + ), + }; + let template = if mac == "msg" { + // 在这对括号里找 `=>`,取它后面的第一个字符串 + let mut k = i + 3; + let mut depth = 1; + let mut found = None; + while k < toks.len() && depth > 0 { + match &toks[k].1 { + Tok::Punct('(' | '[' | '{') => depth += 1, + Tok::Punct(')' | ']' | '}') => depth -= 1, + Tok::Punct('=') if depth == 1 && is(toks.get(k + 1), &Tok::Punct('>')) => { + found = toks[k + 2..].iter().find_map(|(_, t)| match t { + Tok::Str(s) => Some(s.clone()), + _ => None, + }); + break; + } + _ => {} + } + k += 1; + } + Some(found.unwrap_or_else(|| { + panic!("{rel}:{line}: 这处 `msg!` 找不到 `=>` 后面的英文原句") + })) + } else { + None + }; + sites.push(Site { + file: rel.clone(), + line, + first, + template, + test: test_file || mask[i], + }); + } + } + (sites, consts) +} + +/// 句子里除了具名的 `{占位符}` 什么都没有。 +/// +/// **位置参数(`"{}"`)不算**:那是句子在别处写好了、拿来填进格式串的写法 +/// (`msg!("adopt.takes_effect", … => "{}", note)`),界面照样要按码翻。 +fn only_placeholders(t: &str) -> bool { + let mut rest = t.trim(); + while let Some(s) = rest.strip_prefix('{') { + let Some(end) = s.find('}') else { + return false; + }; + if s[..end].trim().is_empty() { + return false; + } + rest = s[end + 1..].trim_start(); + } + rest.is_empty() +} + +/// 按源码生成的清单全文。 +fn manifest(root: &Path) -> String { + let (sites, consts) = scan(root); + let mut codes: BTreeMap = BTreeMap::new(); + for s in &sites { + let code = match &s.first { + First::Lit(c) => c.clone(), + First::Const(n) => consts.get(n).cloned().unwrap_or_else(|| { + panic!( + "{}:{}: `msg!({n}, …)` 里的 `{n}` 找不到一个 `const {n}: &str = \"…\"`", + s.file, s.line + ) + }), + }; + let e = codes.entry(code).or_default(); + if s.test { + e.test = true; + } else { + e.product = true; + if s.template.as_deref().is_none_or(|t| !only_placeholders(t)) { + e.worded = true; + } + } + } + let mut out = String::from( + "# Every message code core can emit, one per line, sorted.\n\ + # Generated: UPDATE_MSG_CODES=1 cargo test -p twcore --test msg_codes\n\ + # A second column marks codes a UI does not translate:\n\ + # passthrough the sentence is only placeholders (system or upstream text); show `text`\n\ + # test only produced by tests; never reaches a UI\n", + ); + for (code, s) in &codes { + out.push_str(code); + if !s.product { + out.push_str(" test"); + } else if !s.worded { + out.push_str(" passthrough"); + } + out.push('\n'); + } + out +} + +/// 从清单里读出码(去掉注释和标记)。 +fn codes_in(text: &str) -> BTreeSet { + text.lines() + .filter(|l| !l.starts_with('#') && !l.trim().is_empty()) + .map(|l| l.split_whitespace().next().unwrap().to_string()) + .collect() +} + +#[test] +fn the_manifest_lists_every_code_core_can_emit() { + let root = workspace(); + let want = manifest(&root); + let path = root.join(MANIFEST); + if std::env::var_os(UPDATE).is_some() { + std::fs::write(&path, &want).unwrap(); + return; + } + // Windows 上的检出可能把换行换成了 CRLF,内容一样就算一样 + let have = std::fs::read_to_string(&path) + .unwrap_or_default() + .replace("\r\n", "\n"); + if have != want { + let (h, w) = (codes_in(&have), codes_in(&want)); + let added: Vec<_> = w.difference(&h).collect(); + let gone: Vec<_> = h.difference(&w).collect(); + panic!( + "{MANIFEST} is stale. Run `{UPDATE}=1 cargo test -p twcore --test msg_codes` and commit it.\n\ + new codes: {added:?}\nremoved codes: {gone:?}\n\ + (if both are empty, a code's marker changed)" + ); + } + // 桌面端读的是 tw-api 里的这个常量,它就是这个文件 + assert_eq!(tw_api::MSG_CODES.replace("\r\n", "\n"), want); +} + +/// 表里的码运行时真的发出来的,清单里都有 —— 有人往表里加了一行却没用 +/// `code!` 包起来的话,这里会看到。 +#[test] +fn codes_from_the_adoption_tables_are_in_the_manifest() { + let listed = codes_in(tw_api::MSG_CODES); + let mut produced = Vec::new(); + for c in tw_adopt::clients::adoptable() { + produced.extend(c.costs.iter().map(|(code, _)| code.to_string())); + produced.extend(c.manual_steps().into_iter().map(|m| m.code)); + } + for m in tw_adopt::clients::manual_only() { + produced.extend(m.steps().into_iter().map(|m| m.code)); + produced.push(m.caveat().code); + } + for t in tw_adopt::mcp::targets() { + produced.extend(t.why_not().map(|m| m.code)); + } + assert!(!produced.is_empty()); + let missing: Vec<_> = produced.iter().filter(|c| !listed.contains(*c)).collect(); + assert!( + missing.is_empty(), + "these codes come out of tw-adopt's tables but are not in {MANIFEST}: {missing:?} \ + (wrap them in `code!(…)`)" + ); +} + +#[test] +fn the_scanner_reads_the_shapes_it_claims_to() { + let src = r####" +const K: &str = "x.from_const"; +fn f() { + msg!("x.plain", a = 1 => "Hello {a}"); + tw_types::msg!("x.path" => "{detail}"); + msg!("x.positional", k = 1 => "{}", note); + let t = (code!("x.table"), "Text"); + // msg!("x.comment" => "no") + msg!(K, detail = e => "{detail}"); +} +#[cfg(test)] +use tw_types::msg; +fn g() { msg!("x.after_cfg_use" => "Still product."); } +#[cfg(test)] +mod tests { + fn h() { msg!("t.only" => "x"); } +} +"####; + let dir = std::env::temp_dir().join(format!("tw-msg-codes-{}", std::process::id())); + let crate_src = dir.join("crates/x/src"); + std::fs::create_dir_all(&crate_src).unwrap(); + std::fs::write(crate_src.join("lib.rs"), src).unwrap(); + let got = manifest(&dir); + std::fs::remove_dir_all(&dir).unwrap(); + let body: Vec<&str> = got.lines().filter(|l| !l.starts_with('#')).collect(); + assert_eq!( + body, + [ + "t.only test", + "x.after_cfg_use", + "x.from_const passthrough", + "x.path passthrough", + "x.plain", + "x.positional", + "x.table", + ] + ); +} diff --git a/crates/tw-adopt/src/clients.rs b/crates/tw-adopt/src/clients.rs index 5cb13ec2..0263f2ed 100644 --- a/crates/tw-adopt/src/clients.rs +++ b/crates/tw-adopt/src/clients.rs @@ -11,7 +11,7 @@ use std::collections::BTreeMap; use std::path::PathBuf; use serde::{Deserialize, Serialize}; -use tw_types::Msg; +use tw_types::{Msg, msg}; use crate::json::Val; @@ -207,15 +207,15 @@ pub fn adoptable() -> Vec { shadowed_by: &[".claude/settings.local.json"], costs: &[ ( - "adopt.cost.claude_code.remote_control", + code!("adopt.cost.claude_code.remote_control"), "Remote Control and voice input do not work when the endpoint is not an official domain.", ), ( - "adopt.cost.claude_code.mcp_tool_search", + code!("adopt.cost.claude_code.mcp_tool_search"), "MCP tool search is off by default.", ), ( - "adopt.cost.claude_code.welcome_screen", + code!("adopt.cost.claude_code.welcome_screen"), "Claude Code may show its welcome screen once; closing it is enough.", ), ], @@ -251,11 +251,11 @@ pub fn adoptable() -> Vec { costs: &[ // 接管这个文件顺带接管了桌面版,**这件事要在确认之前说** ( - "adopt.cost.codex.chatgpt_desktop", + code!("adopt.cost.codex.chatgpt_desktop"), "The ChatGPT desktop app reads the same configuration file, so its local Codex sessions go through the gateway as well; the app has to be restarted for that to take effect.", ), ( - "adopt.cost.codex.reopen_terminal", + code!("adopt.cost.codex.reopen_terminal"), "The terminal has to be reopened afterwards.", ), ], @@ -274,7 +274,7 @@ pub fn adoptable() -> Vec { takes_effect: TakesEffect::OnRestart, shadowed_by: &[], costs: &[( - "adopt.cost.opencode.restart", + code!("adopt.cost.opencode.restart"), "opencode has to be restarted afterwards.", )], verified: Verified::FieldsOnly, @@ -294,7 +294,7 @@ pub fn adoptable() -> Vec { // **只算部分接管**:Zed 的密钥走它自己的凭据存储,不在 // settings.json 里,我们写不进去。 costs: &[( - "adopt.cost.zed.key_store", + code!("adopt.cost.zed.key_store"), "Zed keeps its key outside the configuration file, so it has to be filled in once in Zed's settings.", )], verified: Verified::FieldsOnly, @@ -302,7 +302,7 @@ pub fn adoptable() -> Vec { process: &["Zed"], env_vars: &[], key_elsewhere: Some(( - "adopt.manual.zed.key", + code!("adopt.manual.zed.key"), "Then enter the key in Zed's settings, under the ThinkWatch provider.", )), config_beats_env: false, @@ -318,11 +318,11 @@ pub fn adoptable() -> Vec { shadowed_by: &[], costs: &[ ( - "adopt.cost.aider.lookup_order", + code!("adopt.cost.aider.lookup_order"), "Aider reads the home directory, then the Git project root, then the current directory, and each one overrides the last; only the home directory is changed here.", ), ( - "adopt.cost.aider.restart", + code!("adopt.cost.aider.restart"), "Aider has to be restarted afterwards.", ), ], @@ -346,9 +346,7 @@ pub struct ManualOnly { /// 为它生成专用密钥时用的标识:`cursor` / `continue` / `gemini-cli` pub id: &'static str, pub name: &'static str, - /// 这个客户端的码前缀:每一步是 `.<后缀>`,提醒也是 `.<后缀>`(见 `caveat`) - code: &'static str, - /// 手动配置的几步,每步「码的后缀,英文原句」。 + /// 手动配置的几步,每步「码,英文原句」。 /// /// **地址和密钥不写进句子。**以前是一整句带着地址的话,用户得从句子里 /// 抠出一段 URL;现在两样东西各在界面上有自己的复制按钮,句子只说 @@ -356,8 +354,8 @@ pub struct ManualOnly { steps: &'static [(&'static str, &'static str)], /// 填带 `/v1` 的地址还是不带的 v1: bool, - /// 提醒,「码的后缀,英文原句」。**后缀也可以按平台分** —— 两个平台 - /// 说的不是一句话时,用各自的码,界面才能各翻各的 + /// 提醒,「码,英文原句」。**码也可以按平台分** —— 两个平台说的不是 + /// 一句话时,用各自的码,界面才能各翻各的 caveat: (&'static str, &'static str), } @@ -366,8 +364,8 @@ impl ManualOnly { pub fn steps(&self) -> Vec { self.steps .iter() - .map(|(suffix, text)| Msg { - code: format!("{}.{suffix}", self.code), + .map(|(code, text)| Msg { + code: code.to_string(), args: BTreeMap::new(), text: text.to_string(), }) @@ -386,9 +384,9 @@ impl ManualOnly { /// 接管不了的那一句提醒。**必须和步骤一起给** —— 只说怎么配、不说 /// 配完还漏什么,等于说了假话 pub fn caveat(&self) -> Msg { - let (suffix, text) = self.caveat; + let (code, text) = self.caveat; Msg { - code: format!("{}.{suffix}", self.code), + code: code.to_string(), args: BTreeMap::new(), text: text.to_string(), } @@ -400,35 +398,42 @@ pub fn manual_only() -> Vec { ManualOnly { id: "cursor", name: "Cursor", - code: "adopt.manual.cursor", steps: &[ - ("open", "In Cursor, open Settings → Models."), ( - "base", + code!("adopt.manual.cursor.open"), + "In Cursor, open Settings → Models.", + ), + ( + code!("adopt.manual.cursor.base"), "Turn on Override OpenAI Base URL and enter the gateway address.", ), ( - "key", + code!("adopt.manual.cursor.key"), "Enter the key as the OpenAI API Key, then click Verify.", ), ], v1: true, caveat: ( - "caveat", + code!("adopt.manual.cursor.caveat"), "Tab completion and inline edit still go to Cursor's own service rather than the gateway, so only part of Cursor is covered.", ), }, ManualOnly { id: "continue", name: "Continue", - code: "adopt.manual.continue", steps: &[ #[cfg(not(windows))] - ("open", "Open ~/.continue/config.yaml."), + ( + code!("adopt.manual.continue.open"), + "Open ~/.continue/config.yaml.", + ), #[cfg(windows)] - ("open_windows", r"Open %USERPROFILE%\.continue\config.yaml."), ( - "entry", + code!("adopt.manual.continue.open_windows"), + r"Open %USERPROFILE%\.continue\config.yaml.", + ), + ( + code!("adopt.manual.continue.entry"), "Add an entry to the models list with provider set to openai, apiBase set to the gateway address and apiKey set to the key.", ), ], @@ -438,31 +443,36 @@ pub fn manual_only() -> Vec { // (见 crate::yaml 开头那段)。宁可少接管一个客户端,也不 // 要写一段我们自己没把握的结构。 caveat: ( - "caveat", + code!("adopt.manual.continue.caveat"), "This needs a new entry in the models list, which is not written automatically; follow the steps above.", ), }, ManualOnly { id: "gemini-cli", name: "Gemini CLI", - code: "adopt.manual.gemini_cli", // **Windows 上没有 shell 配置文件可 export**:用户级环境变量用 setx // 写,写完只对之后打开的终端生效。两个平台各用各的码 #[cfg(not(windows))] steps: &[ ( - "export", + code!("adopt.manual.gemini_cli.export"), "In the shell configuration, export GOOGLE_GEMINI_BASE_URL set to the gateway address and GEMINI_API_KEY set to the key.", ), - ("reopen", "Then reopen the terminal."), + ( + code!("adopt.manual.gemini_cli.reopen"), + "Then reopen the terminal.", + ), ], #[cfg(windows)] steps: &[ ( - "setx", + code!("adopt.manual.gemini_cli.setx"), "In a terminal, run setx GOOGLE_GEMINI_BASE_URL followed by the gateway address, and setx GEMINI_API_KEY followed by the key.", ), - ("reopen", "Then reopen the terminal."), + ( + code!("adopt.manual.gemini_cli.reopen"), + "Then reopen the terminal.", + ), ], v1: false, // 它只认环境变量,没有可写的配置字段。改 .zshrc 超出了 @@ -470,12 +480,12 @@ pub fn manual_only() -> Vec { // **报告是我们的职责,修改是他的权利。** #[cfg(not(windows))] caveat: ( - "caveat", + code!("adopt.manual.gemini_cli.caveat"), "Gemini CLI reads the endpoint only from the environment. ThinkWatch does not edit shell configuration files, so add it by hand.", ), #[cfg(windows)] caveat: ( - "caveat_windows", + code!("adopt.manual.gemini_cli.caveat_windows"), "Gemini CLI reads the endpoint only from the environment. ThinkWatch does not change environment variables, so add them by hand.", ), }, @@ -625,11 +635,10 @@ impl Client { /// 用户目录下时,检测不到不等于用不了 —— 照着做一样能接上。 pub fn manual_steps(&self) -> Vec { let file = crate::paths::shown(self.config); - let mut out = vec![Msg { - code: "adopt.manual.file".into(), - args: BTreeMap::from([("file".to_string(), file.clone())]), - text: format!("Open {file} and set the fields below."), - }]; + let mut out = vec![msg!( + "adopt.manual.file", file = file => + "Open {file} and set the fields below." + )]; if let Some((code, text)) = self.key_elsewhere { out.push(Msg { code: code.into(), diff --git a/crates/tw-adopt/src/lib.rs b/crates/tw-adopt/src/lib.rs index f08d47b7..f04321e8 100644 --- a/crates/tw-adopt/src/lib.rs +++ b/crates/tw-adopt/src/lib.rs @@ -1,3 +1,15 @@ +/// 标出一个消息码:原样给出那个字面量。 +/// +/// **表里的码都要用它包起来。**`msg!` 以外造 [`tw_types::Msg`] 的地方(接管的 +/// 代价、手动配置的步骤、MCP 写不了的理由)码和句子分开存在表里,core 的码清单 +/// 测试(tw-control 的 `tests/msg_codes.rs`)靠这个记号在源码里找到它们 —— +/// 少了它,那个码就不在桌面端拿去对照译文的清单上。 +macro_rules! code { + ($c:literal) => { + $c + }; +} + pub mod clients; pub mod detect; pub mod foreign; diff --git a/crates/tw-adopt/src/mcp.rs b/crates/tw-adopt/src/mcp.rs index ce236871..bdf8a1b2 100644 --- a/crates/tw-adopt/src/mcp.rs +++ b/crates/tw-adopt/src/mcp.rs @@ -142,7 +142,7 @@ pub fn targets() -> Vec { key: "mcp", copyable: false, why_not: Some(( - "adopt.mcp.unverified_format", + code!("adopt.mcp.unverified_format"), "this client's MCP configuration format is not verified yet, and writing to it could leave the client unable to read its own configuration", )), }, @@ -154,7 +154,7 @@ pub fn targets() -> Vec { key: "context_servers", copyable: false, why_not: Some(( - "adopt.mcp.zed_structure", + code!("adopt.mcp.zed_structure"), "Zed's context servers use a different structure and do not take the command/args form", )), }, diff --git a/crates/tw-api/Cargo.toml b/crates/tw-api/Cargo.toml index a313f6e1..3faabdcb 100644 --- a/crates/tw-api/Cargo.toml +++ b/crates/tw-api/Cargo.toml @@ -14,3 +14,13 @@ serde_json = { workspace = true } # tw-adopt 都只依赖 tw-types),而契约这一层反过来依赖它没有问题 —— # tw-types 自己零依赖。 tw-types = { workspace = true } +ts-rs = { workspace = true, optional = true } + +[features] +# 把契约导出成 TypeScript:`tw_api::ts::export_all(dir)`。**默认关** —— +# 只有桌面端生成前端类型时开,core 自己和企业版都不背 ts-rs。 +ts = ["dep:ts-rs", "tw-types/ts"] + +[[example]] +name = "export_ts" +required-features = ["ts"] diff --git a/crates/tw-api/examples/export_ts.rs b/crates/tw-api/examples/export_ts.rs new file mode 100644 index 00000000..fde3f5ef --- /dev/null +++ b/crates/tw-api/examples/export_ts.rs @@ -0,0 +1,21 @@ +//! 把控制面契约导出成 TypeScript: +//! +//! ```sh +//! cargo run -p tw-api --features ts --example export_ts -- <目录> +//! ``` +//! +//! 写出 `<目录>/tw-api.ts`。CI 靠它确认导出没坏;桌面端也可以直接调 +//! `tw_api::ts::export_all`。 +fn main() { + let dir = std::env::args_os() + .nth(1) + .map(std::path::PathBuf::from) + .unwrap_or_else(|| std::path::PathBuf::from("bindings")); + match tw_api::ts::export_all(&dir) { + Ok(p) => println!("{}", p.display()), + Err(e) => { + eprintln!("could not write the bindings into {}: {e}", dir.display()); + std::process::exit(1); + } + } +} diff --git a/crates/tw-api/msg-codes.txt b/crates/tw-api/msg-codes.txt new file mode 100644 index 00000000..3135cded --- /dev/null +++ b/crates/tw-api/msg-codes.txt @@ -0,0 +1,406 @@ +# Every message code core can emit, one per line, sorted. +# Generated: UPDATE_MSG_CODES=1 cargo test -p twcore --test msg_codes +# A second column marks codes a UI does not translate: +# passthrough the sentence is only placeholders (system or upstream text); show `text` +# test only produced by tests; never reaches a UI +adopt.cost.aider.lookup_order +adopt.cost.aider.restart +adopt.cost.claude_code.mcp_tool_search +adopt.cost.claude_code.remote_control +adopt.cost.claude_code.welcome_screen +adopt.cost.codex.chatgpt_desktop +adopt.cost.codex.reopen_terminal +adopt.cost.opencode.restart +adopt.cost.zed.key_store +adopt.diag.adopt_again +adopt.diag.delete_line +adopt.diag.endpoint_ok +adopt.diag.endpoint_ok.detail +adopt.diag.fields_gone +adopt.diag.fields_gone.detail +adopt.diag.look_at +adopt.diag.look_at_fields +adopt.diag.managed +adopt.diag.managed.detail +adopt.diag.no_exports +adopt.diag.no_exports.detail +adopt.diag.no_managed +adopt.diag.no_managed.detail +adopt.diag.no_registry_env +adopt.diag.no_registry_env.detail +adopt.diag.no_shadow +adopt.diag.no_shadow.absent +adopt.diag.no_shadow.none +adopt.diag.not_adopted +adopt.diag.not_adopted.detail +adopt.diag.not_running +adopt.diag.not_running.detail +adopt.diag.project_config +adopt.diag.project_config.detail +adopt.diag.registry_env +adopt.diag.registry_env.overrides +adopt.diag.restart +adopt.diag.shadowed +adopt.diag.shadowed.fields +adopt.diag.shadowed.no_fields +adopt.diag.shell_export +adopt.diag.shell_export.harmless +adopt.diag.shell_export.overrides +adopt.diag.started_after +adopt.diag.started_after.detail +adopt.diag.started_before +adopt.diag.started_before.detail +adopt.diag.static_only +adopt.diag.static_only.detail +adopt.diag.unset_env +adopt.diag.unset_env_machine +adopt.file.changed +adopt.file.link_loop +adopt.file.read_failed +adopt.file.readback_mismatch +adopt.file.verify_failed +adopt.file.write_failed +adopt.manual.continue.caveat +adopt.manual.continue.entry +adopt.manual.continue.open +adopt.manual.continue.open_windows +adopt.manual.cursor.base +adopt.manual.cursor.caveat +adopt.manual.cursor.key +adopt.manual.cursor.open +adopt.manual.file +adopt.manual.gemini_cli.caveat +adopt.manual.gemini_cli.caveat_windows +adopt.manual.gemini_cli.export +adopt.manual.gemini_cli.reopen +adopt.manual.gemini_cli.setx +adopt.manual.zed.key +adopt.mcp.not_copyable +adopt.mcp.not_there +adopt.mcp.parse_failed +adopt.mcp.unknown_client +adopt.mcp.unverified_format +adopt.mcp.zed_structure +adopt.plan.fields_only +adopt.plan.foreign_record +adopt.plan.no_record +adopt.plan.parse_failed +adopt.plan.read_failed +adopt.plan.shadowed +adopt.restore.config_gone +adopt.restore.file_removed +adopt.restore.secret_lost +adopt.takes_effect +adopt.warn.symlink +adopt.warn.world_readable +config.bad_allow_from +config.bad_base_url +config.blank_models_only +config.credential.bad_header_name +config.credential.bad_header_value +config.credential.chatgpt_without_login +config.credential.claude_subscription +config.credential.duplicate_header +config.credential.empty_key +config.credential.empty_oauth +config.credential.env passthrough +config.credential.google_subscription +config.credential.identity_header +config.credential.key_and_auth_header +config.credential.key_and_oauth +config.credential.no_token +config.credential.oauth_and_auth_header +config.credential.reserved_header +config.credential.token_without_oauth +config.credential.too_many_headers +config.credential.unrecognized_placeholder +config.default_key_disabled +config.default_key_missing +config.duplicate_client_key +config.duplicate_key_name +config.duplicate_key_value +config.duplicate_upstream +config.edit.multiline +config.edit.name_taken +config.edit.nameless +config.edit.not_found +config.edit.parse +config.edit.self_check +config.edit.unwritable +config.empty_key +config.empty_models_only +config.name_collision +config.no_clients +config.rejected +config.rejected_at +config.reserved_name +config.rule_name_empty +config.rule_name_taken +config.rule_pattern_bad +config.rule_pattern_empty +config.schema_too_new +config.store.conflict +config.store.missing +config.store.read_failed +config.unknown_price_sheet +config.unknown_rule +config.unparsable passthrough +config.zero_concurrency +control.account_service_not_json +control.account_service_refused +control.account_service_status +control.api_key_empty +control.bad_idempotency_key +control.base_url_empty +control.builtin_group_fixed +control.callback_ports_busy +control.chatgpt_backend_not_json +control.chatgpt_backend_status +control.chatgpt_backend_unreachable +control.client_unknown +control.config_stale +control.credentials_failed +control.default_key_cannot_delete +control.default_key_cannot_disable +control.default_route_cannot_delete +control.device_code_failed +control.device_code_unavailable +control.device_code_unreadable +control.disabled_key_cannot_be_default +control.dryrun_needs_target +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 +control.internal_error +control.key_bind_failed +control.key_create_failed +control.key_in_use +control.key_not_found +control.key_used_by_client +control.listen.bad_port +control.listen.bind_invalid +control.method_not_allowed +control.name_empty +control.name_is_builtin +control.name_reserved +control.name_taken_not_chatgpt +control.name_taken_not_zai +control.name_whitespace +control.no_keys +control.no_such_endpoint +control.no_such_version +control.not_a_chatgpt_account +control.pass_has_expansion +control.patch.no_entry +control.patch.not_an_entry +control.pricing.broke_off +control.pricing.not_a_dataset +control.pricing.save_failed +control.pricing.status +control.pricing.too_large +control.pricing.unreachable +control.proxy_addr_form +control.proxy_in_use +control.proxy_not_found +control.reassign_to_deleted_route +control.records_unreadable +control.redirect_must_be_app_scheme +control.request_body_gone +control.request_body_truncated +control.request_not_found +control.request_rejected +control.reset_card_result_unreadable +control.reset_cards_unreadable +control.response_body_gone +control.route.duplicate_rule +control.route_not_found +control.rule.condition_no_value +control.rule.condition_not_bool +control.rule.condition_one_value +control.rule.condition_twice +control.rule.deny_needs_reason +control.rule.forward_and_deny +control.rule.no_such_key +control.rule.no_such_probe_class +control.rule.no_such_upstream +control.rule.unknown_condition +control.rule.unknown_dialect +control.session_not_found +control.sheet_in_use +control.sheet_not_found +control.shutdown +control.signin_gone +control.signin_response_unusable +control.store_off +control.store_unavailable +control.unauthorized +control.unknown_account_family +control.unknown_probe_class +control.unknown_signin_mode +control.unsupported_action +control.unsupported_value +control.upstream_in_use +control.upstream_not_found +control.user_empty +engine.compare.bad_number +engine.compare.bad_unit +engine.compare.empty +engine.compare.no_operator +engine.duplicate_group +engine.duplicate_route +engine.empty_group +engine.no_action +engine.no_match +engine.phase_two_with_to +engine.unknown_default_route +engine.unknown_route +engine.unknown_target +gw.auth.key_disabled +gw.auth.key_invalid +gw.auth.no_key +gw.auth.source_not_allowed +gw.auth.source_not_allowed_hint +gw.config.allow_from +gw.config.http_client +gw.config.no_upstreams +gw.config.proxy_password +gw.config.proxy_undefined +gw.config.proxy_unusable +gw.config.security_rules passthrough +gw.convert.failed +gw.credentials.failed +gw.internal +gw.listen.addr_unavailable +gw.listen.bind_failed +gw.listen.denied +gw.listen.nic_no_addr +gw.listen.no_such_nic +gw.listen.port_taken +gw.model.no_upstream +gw.model.no_upstream_available +gw.model.not_allowed +gw.model.unknown +gw.request.body_too_large +gw.route.all_selected_disabled +gw.route.denied +gw.route.failed +gw.route.no_upstream_alive +gw.route.protocol_mismatch +gw.route.rule_failed +gw.route.selected_upstream_missing +gw.route.upstream_missing +gw.toolcall.blocked +gw.toolcall.cut +gw.upstream.forward_failed +gw.upstream.rate_limited +gw.upstream.status +gw.upstream.timeout +gw.upstream.unreachable +gw.ws.bad_header +gw.ws.bad_url +gw.ws.connect_failed +gw.ws.proxy_unsupported +gw.ws.send_failed +gw.ws.toolcall_cut +gw.ws.upstream_broke +l1.config.bad_url +l1.config.no_host +l1.config.proxy_addr_form +l1.config.proxy_addr_ipv6_brackets +l1.config.proxy_addr_ipv6_form +l1.config.proxy_password +l1.config.proxy_port_not_a_number +l1.config.proxy_undefined +l1.config.system_proxy +l1.config.unsupported_scheme +l1.dns.failed +l1.dns.no_records +l1.dns.timeout +l1.http_proxy.auth_required +l1.http_proxy.connect_rejected +l1.http_proxy.headers_too_large +l1.http_proxy.unreadable_response +l1.io passthrough +l1.io.aborted +l1.io.addr_not_available +l1.io.broken_pipe +l1.io.eof +l1.io.host_unreachable +l1.io.network_unreachable +l1.io.not_found +l1.io.permission_denied +l1.io.refused +l1.io.reset +l1.io.timed_out +l1.socks5.address_type_unsupported +l1.socks5.auth_rejected +l1.socks5.auth_required +l1.socks5.command_unsupported +l1.socks5.connection_refused +l1.socks5.credentials_too_long +l1.socks5.general_failure +l1.socks5.host_too_long +l1.socks5.host_unreachable +l1.socks5.network_unreachable +l1.socks5.no_acceptable_auth +l1.socks5.not_allowed +l1.socks5.not_socks5 +l1.socks5.rejected +l1.socks5.ttl_expired +l1.socks5.unknown_address_type +l1.socks5.unsupported_auth +l1.tcp.failed +l1.tcp.refused +l1.tcp.timeout +l1.tcp.unreachable +l1.timeout +l1.tls.bad_hostname +l1.tls.cert_expired +l1.tls.cert_invalid +l1.tls.cert_untrusted_issuer +l1.tls.failed +l1.unreachable +l3.not_streamed +l3.refused +l3.stream_failed +pricing.sheet.bad_multiplier +pricing.sheet.bad_price +pricing.sheet.duplicate_name +pricing.sheet.empty_model +pricing.sheet.empty_name +pricing.sheet.half_long_context +pricing.sheet.padded_name +scan.hidden +scan.hidden.detail +scan.mcp.remote +scan.mcp.remote.detail +scan.rule +scan.rule.detail +scan.skill.all_tools +scan.skill.all_tools.detail +security.bad_pattern +security.no_action +security.rule_name_empty +security.unknown_action +security.unknown_guard +security.unknown_mode +security.unknown_rule +t.auth test +t.broke test +t.detail test +t.limited test +t.title test +t.upstream test +t.x test +yaml.anchor_or_alias +yaml.block_scalar +yaml.duplicate +yaml.not_found +yaml.not_scalar +yaml.parse +yaml.self_check diff --git a/crates/tw-api/src/endpoint.rs b/crates/tw-api/src/endpoint.rs new file mode 100644 index 00000000..43cc439a --- /dev/null +++ b/crates/tw-api/src/endpoint.rs @@ -0,0 +1,242 @@ +//! 控制面的每一个端点:方法、路径、请求和响应的类型,**只在这里写一次**。 +//! +//! 以前一个端点要写四遍:core 注册路由一遍、桌面端的 Rust 客户端拼路径一遍、 +//! Tauri 命令一遍、前端再一遍。路径是字符串,两边各拼各的,拼错的表现是 +//! 运行时的 404 —— 编译器看不见。现在路径和类型住在这里:core 按它注册, +//! 客户端按它拼,改了哪一边另一边都编不过。 +//! +//! 请求放在哪儿由方法决定:**GET 和 DELETE 走查询串,其余走 JSON 请求体**。 +//! 两样都不需要的端点,`Req` 是 `()`。 +//! +//! 失败时的响应体一律是 [`ErrorBody`],每个端点都一样,所以不在描述里重复。 + +use serde::Serialize; +use serde::de::DeserializeOwned; + +/// 控制面上所有非 2xx 响应的响应体:一条带码的 [`Msg`](crate::Msg)。 +/// +/// **每个端点都是它,包括框架替我们回的那些**(请求体解析不了、路径不存在、 +/// 方法不对、没带凭据)—— core 在最外层把它们也换成了这个形状。客户端拿到 +/// 非 2xx 就按它解析,不用看响应体是不是以 `{` 开头。 +pub type ErrorBody = crate::Msg; + +/// HTTP 方法。**只列控制面用到的这几个。** +#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)] +pub enum Method { + Get, + Post, + Put, + Patch, + Delete, +} + +impl Method { + pub const fn as_str(self) -> &'static str { + match self { + Method::Get => "GET", + Method::Post => "POST", + Method::Put => "PUT", + Method::Patch => "PATCH", + Method::Delete => "DELETE", + } + } + + /// 请求放在查询串里吗。否则是 JSON 请求体。 + pub const fn query(self) -> bool { + matches!(self, Method::Get | Method::Delete) + } +} + +/// 成功的响应体长什么样。 +#[derive(Debug, Clone, Copy, PartialEq, Eq)] +pub enum Format { + /// `Res` 的 JSON。绝大多数端点 + Json, + /// 一段纯文本,`Res` 是 `String`(诊断包、回放用例) + Text, + /// Server-Sent Events,每条 `data:` 是一个 `Res` 的 JSON。连着不断 + Events, +} + +impl Format { + pub const fn as_str(self) -> &'static str { + match self { + Format::Json => "json", + Format::Text => "text", + Format::Events => "events", + } + } +} + +/// 一个控制面端点。实现都在 [`ep`](crate::ep) 里,由 `endpoints!` 生成。 +/// +/// ```ignore +/// use tw_api::{Endpoint, ep}; +/// // 路径带参数的,拼路径用生成的 `path`,参数会做百分号编码 +/// let path = ep::UpdateProvider::path("relay cn"); // "/providers/relay%20cn" +/// let _: ::Req; // tw_api::ProviderSave +/// ``` +pub trait Endpoint { + const METHOD: Method; + /// 路径模板,参数写成 `{name}`(和 axum 同一种写法,core 直接拿它注册) + const PATH: &'static str; + /// 模板里的参数名,按出现的顺序 + const PARAMS: &'static [&'static str]; + const FORMAT: Format; + /// 名字,和 [`ep`](crate::ep) 里的类型名一样。导出给前端时用它当键 + const NAME: &'static str; + /// GET/DELETE 的查询串,或者其余方法的 JSON 请求体。没有就是 `()` + type Req: Serialize + DeserializeOwned; + /// 成功时的响应体。`Format::Events` 时是每一条事件 + type Res: Serialize + DeserializeOwned; +} + +/// 一个端点的静态描述,[`ep::ALL`](crate::ep::ALL) 里一个端点一条。 +#[derive(Debug, Clone, Copy, PartialEq, Eq)] +pub struct Info { + pub name: &'static str, + pub method: Method, + pub path: &'static str, + pub params: &'static [&'static str], + pub format: Format, + /// 请求类型在 Rust 里的写法,`()` 是没有请求。给人看、给测试用 + pub req: &'static str, + /// 响应类型在 Rust 里的写法 + pub res: &'static str, +} + +impl Info { + /// 这个端点带请求吗(查询串或者请求体) + pub fn has_req(&self) -> bool { + self.req != "()" + } +} + +/// 把参数填进路径模板。**每个值都做百分号编码**:名字里可以有空格、斜杠, +/// 原样拼进去的话 `a/b` 会变成两段路径。 +/// +/// 模板里没有的参数会 panic —— 那是 `endpoints!` 里写错了,测试里就会炸。 +pub fn fill(template: &str, params: &[(&str, &str)]) -> String { + let mut out = template.to_string(); + for (name, value) in params { + let slot = format!("{{{name}}}"); + assert!( + out.contains(&slot), + "`{template}` has no parameter `{name}`" + ); + out = out.replace(&slot, &encode(value)); + } + out +} + +/// RFC 3986 的 unreserved 以外一律编码。 +fn encode(s: &str) -> String { + let mut out = String::with_capacity(s.len()); + for b in s.bytes() { + match b { + b'A'..=b'Z' | b'a'..=b'z' | b'0'..=b'9' | b'-' | b'.' | b'_' | b'~' => { + out.push(b as char) + } + _ => out.push_str(&format!("%{b:02X}")), + } + } + out +} + +/// 一个端点一行: +/// +/// ```text +/// 名字: 方法 "路径" [路径参数…], 请求 => 响应, 格式; +/// ``` +/// +/// 格式缺省是 JSON。 +macro_rules! endpoints { + (@method GET) => { $crate::endpoint::Method::Get }; + (@method POST) => { $crate::endpoint::Method::Post }; + (@method PUT) => { $crate::endpoint::Method::Put }; + (@method PATCH) => { $crate::endpoint::Method::Patch }; + (@method DELETE) => { $crate::endpoint::Method::Delete }; + (@format) => { $crate::endpoint::Format::Json }; + (@format text) => { $crate::endpoint::Format::Text }; + (@format events) => { $crate::endpoint::Format::Events }; + ($( + $(#[$meta:meta])* + $name:ident: $method:ident $path:literal $([$($param:ident),+])?, $req:ty => $res:ty $(, $fmt:ident)?; + )*) => { + $( + $(#[$meta])* + #[derive(Debug, Clone, Copy)] + pub struct $name; + + impl $crate::endpoint::Endpoint for $name { + const METHOD: $crate::endpoint::Method = endpoints!(@method $method); + const PATH: &'static str = $path; + const PARAMS: &'static [&'static str] = &[$($(stringify!($param)),+)?]; + const FORMAT: $crate::endpoint::Format = endpoints!(@format $($fmt)?); + const NAME: &'static str = stringify!($name); + type Req = $req; + type Res = $res; + } + + impl $name { + /// 填好参数的路径 + #[allow(clippy::too_many_arguments)] + pub fn path($($($param: impl ::std::fmt::Display),+)?) -> String { + $crate::endpoint::fill( + $path, + &[$($((stringify!($param), $param.to_string().as_str())),+)?], + ) + } + } + )* + + /// 所有端点,按声明的顺序。 + pub const ALL: &[$crate::endpoint::Info] = &[ + $($crate::endpoint::Info { + name: stringify!($name), + method: endpoints!(@method $method), + path: $path, + params: &[$($(stringify!($param)),+)?], + format: endpoints!(@format $($fmt)?), + req: stringify!($req), + res: stringify!($res), + }),* + ]; + + /// 每个端点的请求和响应类型都走一遍。导出 TypeScript 用 + #[cfg(feature = "ts")] + pub(crate) fn visit_types(v: &mut impl $crate::ts::Visit) { + $( + v.endpoint::<$name>(); + )* + } + }; +} + +pub(crate) use endpoints; + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn values_are_percent_encoded_so_they_stay_one_segment() { + assert_eq!( + fill("/providers/{name}", &[("name", "relay cn/中")]), + "/providers/relay%20cn%2F%E4%B8%AD" + ); + assert_eq!( + fill( + "/security/{guard}/custom/{name}", + &[("guard", "outbound"), ("name", "a.b-c_d~e")] + ), + "/security/outbound/custom/a.b-c_d~e" + ); + } + + #[test] + #[should_panic(expected = "has no parameter")] + fn a_parameter_the_template_does_not_have_is_a_bug() { + fill("/providers/{name}", &[("id", "x")]); + } +} diff --git a/crates/tw-api/src/ep.rs b/crates/tw-api/src/ep.rs new file mode 100644 index 00000000..600625e6 --- /dev/null +++ b/crates/tw-api/src/ep.rs @@ -0,0 +1,188 @@ +//! 控制面的全部端点。**加端点从这里开始**:core 按这里注册,客户端按这里拼。 +//! +//! 写法见 `endpoints!`([`crate::endpoint`])。类型名就是端点名,和同名的 +//! 响应类型(比如 [`crate::Status`])不在一个模块里,所以不冲突。 + +use crate as api; +use crate::endpoint::endpoints; + +endpoints! { + // ─────────────────────────────────────────────── 进程 + /// 版本、监听地址、在途请求数 + Status: GET "/status", () => api::Status; + /// 请网关退出(202) + Shutdown: POST "/shutdown", () => api::Msg; + /// 本机的网卡,一张一行 + Interfaces: GET "/interfaces", () => Vec; + /// 实时事件流 + Events: GET "/events", () => api::Event, events; + /// 此刻还没结束的请求,按开始事件的样子给 + InFlight: GET "/in-flight", () => Vec; + Overview: GET "/overview", () => api::Overview; + /// 连通性分段测速 + L1: POST "/l1", api::L1Request => Vec; + Storage: GET "/storage", () => api::StorageStatus; + Quota: GET "/quota", () => Vec; + /// 诊断包(Markdown,已脱敏) + Diagnostics: GET "/diagnostics", () => String, text; + + // ─────────────────────────────────────────────── 配置原文与历史 + GetConfig: GET "/config", () => api::ConfigText; + PatchConfig: PATCH "/config", api::ConfigPatch => api::ConfigWritten; + PutConfig: PUT "/config", api::ConfigWrite => api::ConfigWritten; + ConfigHistory: GET "/config/history", () => Vec; + ConfigAt: GET "/config/at", api::ConfigAtQuery => api::ConfigAt; + ConfigRollback: POST "/config/rollback", api::RollbackRequest => api::ConfigWritten; + SaveListen: PUT "/listen", api::ListenSave => api::ConfigWritten; + + // ─────────────────────────────────────────────── 用量与记录 + Summary: GET "/summary", api::Window => api::Summary; + CostBuckets: GET "/summary/buckets", api::BucketQuery => Vec; + CostBucketsBy: GET "/summary/buckets/by", api::BucketGroupQuery => Vec; + CostBy: GET "/summary/by", api::GroupQuery => Vec; + History: GET "/history", api::ListQuery => Vec; + Latency: GET "/latency", api::Window => Vec; + LatencyByProvider: GET "/latency/provider", api::Window => Vec; + RequestDetail: GET "/request/{id}" [id], () => api::RequestDetail; + /// 把一条记录变成回放用例(YAML) + Fixture: GET "/request/{id}/fixture" [id], () => String, text; + Sessions: GET "/sessions", api::ListQuery => Vec; + SessionDetail: GET "/sessions/{id}" [id], () => api::SessionDetail; + + // ─────────────────────────────────────────────── 测速、回放、试路由 + SpeedQuote: POST "/speed/quote", api::SpeedRunRequest => api::SpeedQuote; + SpeedRun: POST "/speed/run", api::SpeedRunRequest => Vec; + ReplayQuote: POST "/replay/quote", api::ReplayRequest => api::ReplayQuote; + ReplayRun: POST "/replay/run", api::ReplayRequest => api::ReplayResult; + DryRun: POST "/dryrun", api::DryRunRequest => api::DryRunResult; + + // ─────────────────────────────────────────────── 客户端与接管 + Scan: POST "/scan", api::ScanRequest => api::ScanResponse; + Clients: GET "/clients", () => api::ClientsResponse; + PlanAdopt: POST "/clients/plan", api::AdoptRequest => api::PlanView; + Adopt: POST "/clients/adopt", api::AdoptRequest => api::AdoptResponse; + PlanRestore: GET "/clients/{id}/restore/plan" [id], () => api::PlanView; + Restore: POST "/clients/{id}/restore" [id], () => api::AdoptResponse; + Why: GET "/clients/{id}/why" [id], () => Vec; + ClientKey: POST "/clients/{id}/key" [id], () => api::ClientKey; + McpTargets: GET "/mcp/targets", () => Vec; + McpPlan: POST "/mcp/plan", api::McpOpRequest => api::PlanView; + McpApply: POST "/mcp/apply", api::McpOpRequest => api::AdoptResponse; + + // ─────────────────────────────────────────────── 密钥 + Keys: GET "/keys", () => Vec; + CreateKey: POST "/keys", api::KeySave => api::ConfigWritten; + UpdateKey: PUT "/keys/{name}" [name], api::KeySave => api::ConfigWritten; + DeleteKey: DELETE "/keys/{name}" [name], api::BaseVersion => api::ConfigWritten; + KeyValue: GET "/keys/{name}/value" [name], () => api::KeyValue; + RotateKey: POST "/keys/{name}/rotate" [name], api::KeyRotate => api::KeyRotated; + SetDefaultKey: PUT "/default_key", api::DefaultKeySave => api::ConfigWritten; + + // ─────────────────────────────────────────────── 上游与代理 + CreateProvider: POST "/providers", api::ProviderSave => api::ConfigWritten; + TestProvider: POST "/providers/test", api::ProviderTest => api::ProviderTestResult; + PreviewProvider: POST "/providers/preview", api::ProviderPreviewRequest => api::ProviderPreview; + UpdateProvider: PUT "/providers/{name}" [name], api::ProviderSave => api::ConfigWritten; + DeleteProvider: DELETE "/providers/{name}" [name], api::BaseVersion => api::ConfigWritten; + ProviderModels: GET "/providers/{name}/models" [name], () => api::ProviderModelsView; + RefreshProviderModels: POST "/providers/{name}/models/refresh" [name], () => api::ProviderModelsView; + RefreshStaleModels: POST "/models/refresh", () => api::ModelsRefreshing; + CreateProxy: POST "/proxies", api::ProxySave => api::ConfigWritten; + TestProxy: POST "/proxies/test", api::ProxyTest => api::L1Result; + UpdateProxy: PUT "/proxies/{name}" [name], api::ProxySave => api::ConfigWritten; + DeleteProxy: DELETE "/proxies/{name}" [name], api::BaseVersion => api::ConfigWritten; + + // ─────────────────────────────────────────────── 路由 + CreateRoute: POST "/routes", api::RouteSave => api::ConfigWritten; + UpdateRoute: PUT "/routes/{name}" [name], api::RouteSave => api::ConfigWritten; + DeleteRoute: DELETE "/routes/{name}" [name], api::RouteDelete => api::ConfigWritten; + SetDefaultRoute: PUT "/default_route", api::DefaultRouteSave => api::ConfigWritten; + CreateGroup: POST "/groups", api::GroupSave => api::ConfigWritten; + UpdateGroup: PUT "/groups/{name}" [name], api::GroupSave => api::ConfigWritten; + DeleteGroup: DELETE "/groups/{name}" [name], api::BaseVersion => api::ConfigWritten; + KnownModels: GET "/models", () => Vec; + + // ─────────────────────────────────────────────── 价目表 + Pricing: GET "/pricing", () => api::PricingStatus; + RefreshPricing: POST "/pricing/refresh", () => api::PricingRefreshed; + SetPricingAutoUpdate: PUT "/pricing/auto_update", api::AutoUpdateSave => api::ConfigWritten; + QueryPrice: POST "/pricing/query", api::PriceQuery => api::PriceQueryResult; + CreatePriceSheet: POST "/pricing/sheets", api::PriceSheetSave => api::ConfigWritten; + PriceSheet: GET "/pricing/sheets/{name}" [name], () => api::PriceSheetInput; + UpdatePriceSheet: PUT "/pricing/sheets/{name}" [name], api::PriceSheetSave => api::ConfigWritten; + DeletePriceSheet: DELETE "/pricing/sheets/{name}" [name], api::BaseVersion => api::ConfigWritten; + + // ─────────────────────────────────────────────── 安全 + Security: GET "/security", () => api::SecurityDetail; + SecurityEvents: GET "/security/events", api::SecurityEventsQuery => api::SecurityEventsPage; + SetSecurityMode: PUT "/security/{guard}/mode" [guard], api::ModeSave => api::ConfigWritten; + ToggleBuiltinRule: PUT "/security/{guard}/builtin/{id}" [guard, id], api::RuleToggle => api::ConfigWritten; + SetBuiltinRuleAction: PUT "/security/{guard}/builtin/{id}/action" [guard, id], api::ActionSave => api::ConfigWritten; + CreateCustomRule: POST "/security/{guard}/custom" [guard], api::CustomRuleSave => api::ConfigWritten; + UpdateCustomRule: PUT "/security/{guard}/custom/{name}" [guard, name], api::CustomRuleSave => api::ConfigWritten; + DeleteCustomRule: DELETE "/security/{guard}/custom/{name}" [guard, name], api::BaseVersion => api::ConfigWritten; + TestSecurity: POST "/security/{guard}/test" [guard], api::SecurityTestRequest => api::SecurityTestResult; + + // ─────────────────────────────────────────────── 账号登录 + StartChatgptLogin: POST "/chatgpt/login", api::ChatgptLoginStart => api::ChatgptLogin; + ChatgptLoginStatus: GET "/chatgpt/login/{id}" [id], () => api::ChatgptLoginStatus; + CancelChatgptLogin: DELETE "/chatgpt/login/{id}" [id], () => api::ChatgptLoginStatus; + ChatgptUsage: GET "/providers/{name}/chatgpt/usage" [name], () => api::ChatgptUsage; + ChatgptResets: GET "/providers/{name}/chatgpt/resets" [name], () => api::ResetCredits; + UseChatgptReset: POST "/providers/{name}/chatgpt/resets" [name], api::ResetCreditUse => api::ResetCreditUsed; + StartZaiLogin: POST "/zai/login", api::ZaiLoginStart => api::ZaiLogin; + ZaiLoginStatus: GET "/zai/login/{id}" [id], () => api::ZaiLoginStatus; + CancelZaiLogin: DELETE "/zai/login/{id}" [id], () => api::ZaiLoginStatus; +} + +#[cfg(test)] +mod tests { + use super::*; + use crate::endpoint::Method; + use std::collections::HashSet; + + /// 模板里的 `{参数}` 和声明的参数一一对上,顺序也一样。 + #[test] + fn every_template_parameter_is_declared_and_nothing_else() { + for e in ALL { + let in_template: Vec<&str> = e + .path + .split('/') + .filter_map(|s| s.strip_prefix('{')?.strip_suffix('}')) + .collect(); + assert_eq!(in_template, e.params, "{}: {}", e.name, e.path); + } + } + + /// 同一个路径上同一个方法只能有一个端点,名字也不能重。 + #[test] + fn no_two_endpoints_collide() { + let mut seen = HashSet::new(); + let mut names = HashSet::new(); + for e in ALL { + assert!( + seen.insert((e.method, e.path)), + "{} {}", + e.method.as_str(), + e.path + ); + assert!(names.insert(e.name), "{}", e.name); + } + } + + #[test] + fn paths_are_filled_and_encoded() { + assert_eq!(RequestDetail::path(42), "/request/42"); + assert_eq!( + UpdateCustomRule::path("outbound", "my rule"), + "/security/outbound/custom/my%20rule" + ); + assert_eq!(Status::path(), "/status"); + } + + #[test] + fn only_get_and_delete_carry_the_request_in_the_query() { + assert!(Method::Get.query() && Method::Delete.query()); + assert!(!Method::Post.query() && !Method::Put.query() && !Method::Patch.query()); + } +} diff --git a/crates/tw-api/src/lib.rs b/crates/tw-api/src/lib.rs index afacfd1e..83736b95 100644 --- a/crates/tw-api/src/lib.rs +++ b/crates/tw-api/src/lib.rs @@ -15,6 +15,22 @@ use serde::{Deserialize, Serialize}; /// 一句给人读的错误或说明,类型都是它**,不是 `String`。 pub use tw_types::Msg; +mod endpoint; +pub mod ep; +#[cfg(feature = "ts")] +pub mod ts; +pub use endpoint::{Endpoint, ErrorBody, Format, Info, Method, fill}; + +/// core 发得出的每一个消息码([`Msg::code`]),一行一个,按字母排。 +/// +/// **界面按码翻译,所以这就是它要翻的全部。**桌面端从钉着的那个 tag 读它,和 +/// 自己的译文表对一遍:清单里有、表里没有的,中文界面上就是英文。 +/// +/// `#` 开头的行是说明。码后面可以跟一个标记:`passthrough` 是句子只有占位符 +/// (系统或上游的原话),照 `text` 显示;`test` 是只在测试里出现的。这份清单由 +/// twcore 的 `tests/msg_codes.rs` 从源码生成、并且在 CI 上核对。 +pub const MSG_CODES: &str = include_str!("../msg-codes.txt"); + /// 控制面协议版本。UI 和 CLI 连上来时检查,不匹配就明确提示「请升级 /// 客户端」,而不是以奇怪的方式失败。 /// @@ -66,9 +82,15 @@ pub use tw_types::Msg; /// 「什么时候开始要凭据」是读它的人必须查得到的一件事。 /// /// 同一版加了 `POST /shutdown`。新增端点本身不破坏什么,它跟着这次走。 -pub const CONTROL_API_VERSION: u32 = 12; +/// +/// **13 起端点只在 [`ep`] 里写一次**,core 按它注册、客户端按它拼。顺带:扫描 +/// 换成了 `POST /scan`(项目目录走请求体,查询串里那种写法 core 一直读不了); +/// 框架替我们回的失败(路径不存在、方法不对、请求体读不成)也是 [`ErrorBody`], +/// 不再是纯文本或空响应体;传输地址改名 `control::Address`。 +pub const CONTROL_API_VERSION: u32 = 13; #[derive(Debug, Clone, Serialize, Deserialize)] +#[cfg_attr(feature = "ts", derive(ts_rs::TS))] pub struct Status { pub api_version: u32, /// 二进制的 CalVer @@ -97,6 +119,7 @@ pub struct Status { /// 一次请求的观测事件。UI 的实时列表吃这个。 #[derive(Debug, Clone, Serialize, Deserialize)] +#[cfg_attr(feature = "ts", derive(ts_rs::TS))] #[serde(tag = "kind", rename_all = "snake_case")] pub enum Event { /// 请求进来了 @@ -564,6 +587,7 @@ pub enum Event { /// **失败的原因要留着** —— 一条说「试过 A → B → C」的链,和一条还说清 /// 每一跳为什么失败的链,排查价值差得远。 #[derive(Debug, Clone, PartialEq, Serialize, Deserialize)] +#[cfg_attr(feature = "ts", derive(ts_rs::TS))] pub struct AttemptView { pub provider: String, /// - `served`:这一跳接下了请求,尝试链到此为止。上游回的是 4xx 也算 @@ -585,6 +609,7 @@ pub struct AttemptView { /// 一次请求的路由决策。**详情抽屉的 Routing 那一页吃它。** #[derive(Debug, Clone, Default, PartialEq, Serialize, Deserialize)] +#[cfg_attr(feature = "ts", derive(ts_rs::TS))] pub struct RoutingView { pub rule: String, #[serde(default, skip_serializing_if = "Option::is_none")] @@ -597,6 +622,7 @@ pub struct RoutingView { /// 我们自己推断的东西不放进这个结构 —— 界面上必须能区分「上游说的」和 /// 「我们猜的」,而混在一个类型里就区分不了了。 #[derive(Debug, Clone, PartialEq, Serialize, Deserialize)] +#[cfg_attr(feature = "ts", derive(ts_rs::TS))] pub struct QuotaWindow { /// `5h` / `7d`(Anthropic)/ `weekly`(Codex) pub window: String, @@ -612,6 +638,7 @@ pub struct QuotaWindow { /// 一次调用的用量。 #[derive(Debug, Clone, Copy, Default, PartialEq, Eq, Serialize, Deserialize)] +#[cfg_attr(feature = "ts", derive(ts_rs::TS))] pub struct UsageView { pub input: u64, pub output: u64, @@ -660,6 +687,7 @@ impl Event { /// **不是配置文件本身**:密钥一律只给来源描述,不给值(统一脱敏)。 /// 界面需要的是「有哪些上游、规则怎么写的、谁健康」,不是那份 YAML。 #[derive(Debug, Clone, Serialize, Deserialize)] +#[cfg_attr(feature = "ts", derive(ts_rs::TS))] pub struct Overview { /// 配置文件现在的版本号。和 `GET /config` 的 `version`、改配置时带的 /// `base_version` 是同一个。 @@ -694,6 +722,7 @@ pub struct Overview { /// 一张自定义价目表。 #[derive(Debug, Clone, Serialize, Deserialize)] +#[cfg_attr(feature = "ts", derive(ts_rs::TS))] pub struct PriceSheetView { pub name: String, pub multiplier: f64, @@ -709,6 +738,7 @@ pub struct PriceSheetView { /// 这个视图会进日志、进诊断包、进用户贴出来的截图。有没有认证是要 /// 显示的,认证内容不是。 #[derive(Debug, Clone, Serialize, Deserialize)] +#[cfg_attr(feature = "ts", derive(ts_rs::TS))] pub struct ProxyView { pub name: String, /// `socks5h` / `socks5` / `http` / `https` @@ -730,6 +760,7 @@ pub struct ProxyView { /// 网关发现一个代理不通时,检出来的样子。 #[derive(Debug, Clone, Serialize, Deserialize, PartialEq)] +#[cfg_attr(feature = "ts", derive(ts_rs::TS))] pub struct ProxyFault { /// 卡在哪一步。说不出来的没有 #[serde(default, skip_serializing_if = "Option::is_none")] @@ -745,6 +776,7 @@ pub struct ProxyFault { /// `when.intent` 只有在对应那一类被配成 `route` 时才可能命中,所以 /// 界面上那些写了 `intent` 的规则永远不会生效,而用户无从知道为什么。 #[derive(Debug, Clone, Serialize, Deserialize)] +#[cfg_attr(feature = "ts", derive(ts_rs::TS))] pub struct ProbeView { /// `health_check` / `warmup` / `titling` / `topic_detect` / `suggestion` pub id: String, @@ -755,6 +787,7 @@ pub struct ProbeView { /// 日志留多久。两个期限分开,因为正文和记录行的代价差三个数量级 —— /// 一条正文几十 KB,一行记录几百字节。 #[derive(Debug, Clone, Default, Serialize, Deserialize)] +#[cfg_attr(feature = "ts", derive(ts_rs::TS))] pub struct RetentionView { /// 请求和响应的正文留几天 pub body_days: u64, @@ -772,12 +805,14 @@ pub struct RetentionView { /// **「拦截」在两项上做的事不一样**:脱敏是替换成占位符,审查是切断响应。 /// 规则和日志在 [`SecurityDetail`] 和 `/security/events` 里,不塞进概览。 #[derive(Debug, Clone, Default, Serialize, Deserialize)] +#[cfg_attr(feature = "ts", derive(ts_rs::TS))] pub struct SecurityView { pub redact: String, pub inspect_tools: String, } #[derive(Debug, Clone, Serialize, Deserialize)] +#[cfg_attr(feature = "ts", derive(ts_rs::TS))] pub struct ProviderView { pub name: String, /// 已脱敏。**编辑时不要原样写回** —— 地址里带了凭据的话,写回去的 @@ -847,6 +882,7 @@ pub struct ProviderView { /// 一个可能是密钥的值给界面看的样子。 #[derive(Debug, Clone, Serialize, Deserialize, PartialEq)] +#[cfg_attr(feature = "ts", derive(ts_rs::TS))] pub struct SecretView { /// 打过码的值。带 `${NAME}` 的值原样给 —— 它写的是从哪个环境变量读 pub display: String, @@ -857,6 +893,7 @@ pub struct SecretView { /// 一行请求头给界面看的样子。 #[derive(Debug, Clone, Serialize, Deserialize, PartialEq)] +#[cfg_attr(feature = "ts", derive(ts_rs::TS))] pub struct HeaderView { pub name: String, /// **可能是密钥的值是打过码的**;公开的头(`anthropic-version` 之类)、 @@ -867,6 +904,7 @@ pub struct HeaderView { } #[derive(Debug, Clone, Serialize, Deserialize, PartialEq)] +#[cfg_attr(feature = "ts", derive(ts_rs::TS))] pub struct OAuthView { pub endpoint: String, #[serde(default, skip_serializing_if = "Option::is_none")] @@ -884,6 +922,7 @@ pub struct OAuthView { /// 配置里引用了某个上游的一处。 #[derive(Debug, Clone, Serialize, Deserialize, PartialEq)] +#[cfg_attr(feature = "ts", derive(ts_rs::TS))] #[serde(tag = "kind", rename_all = "snake_case")] pub enum ReferenceView { /// 路由规则的去向(`to`) @@ -899,6 +938,7 @@ pub enum ReferenceView { /// **是全文,不是摘要** —— 编辑对话框靠它回填:条件、去向、拒绝原因、 /// 参数改写、安全要求,交回来的 [`RuleInput`] 是同一套写法。 #[derive(Debug, Clone, Serialize, Deserialize)] +#[cfg_attr(feature = "ts", derive(ts_rs::TS))] pub struct RuleView { pub name: String, /// `when` 里写了的条件,按固定顺序。空 = 兜底 @@ -923,6 +963,7 @@ pub struct RuleView { /// 规则里的参数改写。每一项不写就是不改。 #[derive(Debug, Clone, Default, PartialEq, Serialize, Deserialize)] +#[cfg_attr(feature = "ts", derive(ts_rs::TS))] pub struct RuleRewrite { /// 换一个模型。**整个 prompt cache 随之作废** #[serde(default, skip_serializing_if = "Option::is_none")] @@ -936,6 +977,7 @@ pub struct RuleRewrite { /// 规则里的一个条件。 #[derive(Debug, Clone, PartialEq, Serialize, Deserialize)] +#[cfg_attr(feature = "ts", derive(ts_rs::TS))] pub struct ConditionView { /// `when` 里的键:`model` / `client` / `dialect` / `input_tokens` / /// `max_tokens` / `tool_count` / `intent` / `provider_would_be` / @@ -948,6 +990,7 @@ pub struct ConditionView { /// 一条路由 —— 一组规则,加上它分给了谁。 #[derive(Debug, Clone, Serialize, Deserialize)] +#[cfg_attr(feature = "ts", derive(ts_rs::TS))] pub struct RouteView { pub name: String, /// 没绑路由的密钥走的就是这条 @@ -964,6 +1007,7 @@ pub struct RouteView { } #[derive(Debug, Clone, Serialize, Deserialize)] +#[cfg_attr(feature = "ts", derive(ts_rs::TS))] pub struct GroupView { pub name: String, /// 内置的「全部上游」:成员是全部上游,按上游列表的顺序。不能编辑、不能删除 @@ -986,6 +1030,7 @@ pub struct GroupView { } #[derive(Debug, Clone, Serialize, Deserialize)] +#[cfg_attr(feature = "ts", derive(ts_rs::TS))] pub struct ClientView { pub name: String, /// `GET /keys` 给明文 —— 密钥页要把它原样显示出来、给出复制按钮。 @@ -1013,6 +1058,7 @@ pub struct ClientView { /// 新建或保存一把网关密钥(`POST /keys`、`PUT /keys/{name}`)。 #[derive(Debug, Clone, Default, Serialize, Deserialize)] +#[cfg_attr(feature = "ts", derive(ts_rs::TS))] pub struct KeySave { pub key: KeyInput, #[serde(default, skip_serializing_if = "Option::is_none")] @@ -1022,6 +1068,7 @@ pub struct KeySave { /// 一把密钥上用户能改的东西。**密钥的值不在里面** —— 它由 core 生成, /// 要换就走更换,那条路会把新值同步给已接管的客户端。 #[derive(Debug, Clone, Default, Serialize, Deserialize)] +#[cfg_attr(feature = "ts", derive(ts_rs::TS))] pub struct KeyInput { pub name: String, #[serde(default, skip_serializing_if = "Option::is_none")] @@ -1038,6 +1085,7 @@ pub struct KeyInput { /// 换哪把密钥(`POST /keys/{name}/rotate`)。 #[derive(Debug, Clone, Default, Serialize, Deserialize)] +#[cfg_attr(feature = "ts", derive(ts_rs::TS))] pub struct KeyRotate { #[serde(default, skip_serializing_if = "Option::is_none")] pub base_version: Option, @@ -1045,6 +1093,7 @@ pub struct KeyRotate { /// 换完之后的结果。 #[derive(Debug, Clone, Serialize, Deserialize)] +#[cfg_attr(feature = "ts", derive(ts_rs::TS))] pub struct KeyRotated { pub version: String, /// 新的密钥值。**只在这里给一次**,之后列表里只有脱敏的 @@ -1058,6 +1107,7 @@ pub struct KeyRotated { } #[derive(Debug, Clone, Serialize, Deserialize)] +#[cfg_attr(feature = "ts", derive(ts_rs::TS))] pub struct KeySynced { /// 客户端 id(`claude-code` …) pub client: String, @@ -1071,6 +1121,7 @@ pub struct KeySynced { } #[derive(Debug, Clone, Serialize, Deserialize)] +#[cfg_attr(feature = "ts", derive(ts_rs::TS))] pub struct KeySyncFailed { pub client: String, pub name: String, @@ -1082,6 +1133,7 @@ pub struct KeySyncFailed { /// **三项一起存**,而不是三个补丁:从「仅本机」换到「局域网」时网卡和 /// 端口往往一起改,分开存的话中间那一版监听在一个用户没选过的地址上。 #[derive(Debug, Clone, Default, Serialize, Deserialize)] +#[cfg_attr(feature = "ts", derive(ts_rs::TS))] pub struct ListenSave { /// 同配置里的 `listen.gateway.bind`:`loopback` / `all` / 网卡名 / 地址 pub bind: String, @@ -1095,6 +1147,7 @@ pub struct ListenSave { /// 设默认密钥(`PUT /default_key`)。 #[derive(Debug, Clone, Default, Serialize, Deserialize)] +#[cfg_attr(feature = "ts", derive(ts_rs::TS))] pub struct DefaultKeySave { pub name: String, #[serde(default, skip_serializing_if = "Option::is_none")] @@ -1104,12 +1157,14 @@ pub struct DefaultKeySave { /// 一把密钥的明文(`GET /keys/{name}/value`)。「复制」按名字取此刻配置里的 /// 值,不依赖界面手里那份列表是不是最新的。 #[derive(Debug, Clone, Serialize, Deserialize)] +#[cfg_attr(feature = "ts", derive(ts_rs::TS))] pub struct KeyValue { pub name: String, pub key: String, } #[derive(Debug, Clone, Serialize, Deserialize)] +#[cfg_attr(feature = "ts", derive(ts_rs::TS))] pub struct ListenView { pub bind: String, pub port: u16, @@ -1127,6 +1182,7 @@ pub struct ListenView { /// 说「这家不提供模型列表」,而那在第二种情况下是编的 —— 把我们自己的 /// 解析缺口说成了对方的特性。 #[derive(Debug, Clone, Serialize, Deserialize)] +#[cfg_attr(feature = "ts", derive(ts_rs::TS))] #[serde(tag = "kind", rename_all = "snake_case")] pub enum ModelList { Listed { @@ -1145,6 +1201,7 @@ pub enum ModelList { /// 检测一个上游的结果。 #[derive(Debug, Clone, Serialize, Deserialize)] +#[cfg_attr(feature = "ts", derive(ts_rs::TS))] pub struct ProviderTestResult { /// 地址通、凭据被接受 pub ok: bool, @@ -1168,6 +1225,7 @@ pub struct ProviderTestResult { /// 里存在两次,两边不通。这里的规矩是:测的候选池就是运行时故障转移的 /// 候选池,同一份数据(架构红线)。 #[derive(Debug, Clone, Default, Serialize, Deserialize)] +#[cfg_attr(feature = "ts", derive(ts_rs::TS))] pub struct L1Request { #[serde(default, skip_serializing_if = "Option::is_none")] pub provider: Option, @@ -1175,6 +1233,7 @@ pub struct L1Request { /// 建连的哪一步、对着谁。 #[derive(Debug, Clone, Serialize, Deserialize, PartialEq)] +#[cfg_attr(feature = "ts", derive(ts_rs::TS))] pub struct L1Stage { /// `config`(地址或代理配置用不了,没有开始建连)/ `dns` / `tcp` / /// `tls` / `handshake`(代理协议的握手,含认证) @@ -1184,6 +1243,7 @@ pub struct L1Stage { } #[derive(Debug, Clone, Serialize, Deserialize, PartialEq)] +#[cfg_attr(feature = "ts", derive(ts_rs::TS))] pub struct L1Segment { pub stage: L1Stage, pub ms: u64, @@ -1191,6 +1251,7 @@ pub struct L1Segment { /// 没有出现在分段里的那一步,和原因。**不说的话,缺一段看起来就像 bug。** #[derive(Debug, Clone, Serialize, Deserialize, PartialEq)] +#[cfg_attr(feature = "ts", derive(ts_rs::TS))] pub struct L1Skip { pub stage: L1Stage, /// `plain_http`(`http://` 地址没有 TLS)/ `ip_address`(地址已经是 IP, @@ -1201,6 +1262,7 @@ pub struct L1Skip { /// **分段是个列表而不是固定的 DNS/TCP/TLS 三段**,因为走代理时的形状本来 /// 就不同:多出代理握手,而 `socks5h` 下根本没有本地 DNS 那一段。 #[derive(Debug, Clone, Serialize, Deserialize)] +#[cfg_attr(feature = "ts", derive(ts_rs::TS))] pub struct L1Result { /// 测的是哪个上游或代理的名字 —— 回显出来,别让用户猜点的那一下测了谁 pub target: String, @@ -1225,6 +1287,7 @@ pub struct L1Result { /// **给的是原文,不是结构。**界面的文本模式直接显示它;表单模式改完 /// 之后带着 `version` 回来,那就是乐观并发的凭据。 #[derive(Debug, Clone, Serialize, Deserialize)] +#[cfg_attr(feature = "ts", derive(ts_rs::TS))] pub struct ConfigText { pub path: String, pub text: String, @@ -1237,6 +1300,7 @@ pub struct ConfigText { /// **界面上「绑在哪张网卡」那个选单要的就是它。**没有它,用户只能自己 /// 去 `ifconfig` 抄一个地址填进配置文件,而填错的后果是网关起不来。 #[derive(Debug, Clone, Serialize, Deserialize)] +#[cfg_attr(feature = "ts", derive(ts_rs::TS))] pub struct NicView { /// `en0`、`lo0`、`utun3`。配置里按它存 pub name: String, @@ -1252,6 +1316,7 @@ pub struct NicView { /// 整份发过来的话,两个人同时改就必然有一个人的改动被悄悄吃掉 —— /// 而那正是 cc-switch 那批 issue 的形状。 #[derive(Debug, Clone, Serialize, Deserialize)] +#[cfg_attr(feature = "ts", derive(ts_rs::TS))] pub struct ConfigPatch { /// 你基于哪一版。**对不上就是 409。**不给表示「我知道我在覆盖」 #[serde(default, skip_serializing_if = "Option::is_none")] @@ -1264,6 +1329,7 @@ pub struct ConfigPatch { /// `path` 用**名字**而不是下标:`/providers/relay-cn/base_url`。 /// 下标会在用户重排上游之后指向另一个东西,而那种错误完全静默。 #[derive(Debug, Clone, Serialize, Deserialize)] +#[cfg_attr(feature = "ts", derive(ts_rs::TS))] #[serde(tag = "op", rename_all = "snake_case")] pub enum PatchOp { Replace { @@ -1298,6 +1364,7 @@ pub enum PatchOp { } #[derive(Debug, Clone, Serialize, Deserialize)] +#[cfg_attr(feature = "ts", derive(ts_rs::TS))] #[serde(untagged)] pub enum PatchValue { Str(String), @@ -1311,6 +1378,7 @@ pub enum PatchValue { /// 默认价目表现在的状态。 #[derive(Debug, Clone, Serialize, Deserialize)] +#[cfg_attr(feature = "ts", derive(ts_rs::TS))] pub struct PricingStatus { /// 这份表的数据日期。**费用旁边要标它** pub date: String, @@ -1338,6 +1406,7 @@ pub struct PricingStatus { /// 一个无法计价的 (上游, 模型)。 #[derive(Debug, Clone, PartialEq, Serialize, Deserialize)] +#[cfg_attr(feature = "ts", derive(ts_rs::TS))] pub struct UnpricedModel { pub provider: String, pub model: String, @@ -1346,6 +1415,7 @@ pub struct UnpricedModel { /// 刷新了一次之后。 #[derive(Debug, Clone, Serialize, Deserialize)] +#[cfg_attr(feature = "ts", derive(ts_rs::TS))] pub struct PricingRefreshed { pub status: PricingStatus, /// 和刷新之前比,价格变了、新增或者移除了的模型数 @@ -1354,6 +1424,7 @@ pub struct PricingRefreshed { /// 开关定期刷新。 #[derive(Debug, Clone, Serialize, Deserialize)] +#[cfg_attr(feature = "ts", derive(ts_rs::TS))] pub struct AutoUpdateSave { pub on: bool, #[serde(default, skip_serializing_if = "Option::is_none")] @@ -1365,6 +1436,7 @@ pub struct AutoUpdateSave { /// 查价返回的是**实际计费用的**单价:数据集里没单独定价的缓存档已经按 /// 计费规则补上。所以它可以原样作为一条覆盖价的起点。 #[derive(Debug, Clone, PartialEq, Serialize, Deserialize)] +#[cfg_attr(feature = "ts", derive(ts_rs::TS))] pub struct PriceFields { pub input: f64, pub output: f64, @@ -1380,6 +1452,7 @@ pub struct PriceFields { /// 一个价格是从哪儿来的。**每一笔费用都要能追溯到它。** #[derive(Debug, Clone, PartialEq, Serialize, Deserialize)] +#[cfg_attr(feature = "ts", derive(ts_rs::TS))] #[serde(tag = "kind", rename_all = "snake_case")] pub enum PriceSourceView { /// 默认价目表。`date` 是那份表的数据日期 @@ -1396,6 +1469,7 @@ pub enum PriceSourceView { /// 新建或修改一张价目表时交过来的定义。 #[derive(Debug, Clone, Serialize, Deserialize)] +#[cfg_attr(feature = "ts", derive(ts_rs::TS))] pub struct PriceSheetInput { pub name: String, /// 作用于默认价目表的全部单价 @@ -1411,6 +1485,7 @@ fn one() -> f64 { } #[derive(Debug, Clone, Serialize, Deserialize)] +#[cfg_attr(feature = "ts", derive(ts_rs::TS))] pub struct PriceSheetSave { pub sheet: PriceSheetInput, #[serde(default, skip_serializing_if = "Option::is_none")] @@ -1424,6 +1499,7 @@ pub struct PriceSheetSave { /// 按哪张价目表查价。 #[derive(Debug, Clone, Serialize, Deserialize)] +#[cfg_attr(feature = "ts", derive(ts_rs::TS))] #[serde(tag = "kind", rename_all = "snake_case")] pub enum SheetRef { /// 默认价目表 @@ -1436,6 +1512,7 @@ pub enum SheetRef { /// 查价。**界面不自己实现计价顺序**,要显示什么价就来问。 #[derive(Debug, Clone, Serialize, Deserialize)] +#[cfg_attr(feature = "ts", derive(ts_rs::TS))] pub struct PriceQuery { pub sheet: SheetRef, /// 要查的模型。给了就只查这些 @@ -1451,6 +1528,7 @@ pub struct PriceQuery { /// 一个模型查到的价格。 #[derive(Debug, Clone, Serialize, Deserialize)] +#[cfg_attr(feature = "ts", derive(ts_rs::TS))] pub struct ResolvedPrice { pub model: String, /// 价格和来源。`None` = 无法计价 @@ -1466,6 +1544,7 @@ pub struct ResolvedPrice { } #[derive(Debug, Clone, Serialize, Deserialize)] +#[cfg_attr(feature = "ts", derive(ts_rs::TS))] pub struct PriceQueryResult { pub items: Vec, /// 按名字搜时,一共有多少个模型对得上(`items` 可能被 `limit` 截断) @@ -1474,6 +1553,7 @@ pub struct PriceQueryResult { /// 光标落在配置的哪一段上。 #[derive(Debug, Clone, Serialize, Deserialize)] +#[cfg_attr(feature = "ts", derive(ts_rs::TS))] pub struct ConfigAt { /// `providers` / `groups` / `routes` / `clients`… pub section: Option, @@ -1488,12 +1568,14 @@ pub struct ConfigAt { /// —— 后者是前者的退路(结构性的增删一律引导到文本模式),而两者 /// 都必须带 `base_version`,都会走那三道校验。 #[derive(Debug, Clone, Serialize, Deserialize)] +#[cfg_attr(feature = "ts", derive(ts_rs::TS))] pub struct ConfigWrite { pub base_version: String, pub text: String, } #[derive(Debug, Clone, Serialize, Deserialize)] +#[cfg_attr(feature = "ts", derive(ts_rs::TS))] pub struct ConfigWritten { pub version: String, } @@ -1505,6 +1587,7 @@ pub struct ConfigWritten { /// **结构,不是 YAML。**以前界面拼一段 YAML 交给补丁接口 —— 拼字符串的 /// 那一方不知道引号规则,一个带 `#` 的值就能写坏整份配置。 #[derive(Debug, Clone, Serialize, Deserialize)] +#[cfg_attr(feature = "ts", derive(ts_rs::TS))] pub struct ProviderInput { pub name: String, /// 修改时**不给就是保持原样**:视图里的地址是打过码的,原样写回去 @@ -1551,6 +1634,7 @@ pub struct ProviderInput { /// 按接口地址自动识别的结果。给编辑中、还没保存的上游显示「自动识别」 /// 会选成什么。 #[derive(Debug, Clone, Serialize, Deserialize)] +#[cfg_attr(feature = "ts", derive(ts_rs::TS))] pub struct ProviderPreviewRequest { pub base_url: String, /// 表单里选定的协议。不给就是「自动识别」。只影响 `auth_header` @@ -1559,6 +1643,7 @@ pub struct ProviderPreviewRequest { } #[derive(Debug, Clone, Serialize, Deserialize)] +#[cfg_attr(feature = "ts", derive(ts_rs::TS))] pub struct ProviderPreview { /// 按地址推断的接口协议。推断不出是空(转发时按 Anthropic 处理) #[serde(default, skip_serializing_if = "Option::is_none")] @@ -1570,6 +1655,7 @@ pub struct ProviderPreview { /// 一个上游的模型清单。 #[derive(Debug, Clone, Serialize, Deserialize)] +#[cfg_attr(feature = "ts", derive(ts_rs::TS))] pub struct ProviderModelsView { pub provider: String, /// `discovered`(上游列出的)/ `manual`(手动清单)/ `none` @@ -1589,12 +1675,14 @@ pub struct ProviderModelsView { /// 页面打开时补问模型清单:开始问的是哪几家。答案随 `models_changed` 到。 #[derive(Debug, Clone, Serialize, Deserialize)] +#[cfg_attr(feature = "ts", derive(ts_rs::TS))] pub struct ModelsRefreshing { pub providers: Vec, } /// 清单里的一个模型。 #[derive(Debug, Clone, Serialize, Deserialize)] +#[cfg_attr(feature = "ts", derive(ts_rs::TS))] pub struct ModelRow { pub id: String, /// 在启用范围里 @@ -1621,6 +1709,7 @@ fn fail_closed() -> String { /// 一个密钥类的值怎么改。**三态**,因为视图里拿不到原值:不动就得有「保持原样」。 #[derive(Debug, Clone, Default, Serialize, Deserialize, PartialEq)] +#[cfg_attr(feature = "ts", derive(ts_rs::TS))] #[serde(tag = "mode", rename_all = "snake_case")] pub enum SecretChange { #[default] @@ -1633,6 +1722,7 @@ pub enum SecretChange { } #[derive(Debug, Clone, Serialize, Deserialize, PartialEq)] +#[cfg_attr(feature = "ts", derive(ts_rs::TS))] pub struct HeaderInput { pub name: String, /// 不给表示沿用同名那一行的原值 @@ -1641,6 +1731,7 @@ pub struct HeaderInput { } #[derive(Debug, Clone, Default, Serialize, Deserialize, PartialEq)] +#[cfg_attr(feature = "ts", derive(ts_rs::TS))] #[serde(tag = "mode", rename_all = "snake_case")] pub enum OAuthChange { #[default] @@ -1662,6 +1753,7 @@ pub enum OAuthChange { } #[derive(Debug, Clone, Serialize, Deserialize)] +#[cfg_attr(feature = "ts", derive(ts_rs::TS))] pub struct ProviderSave { pub provider: ProviderInput, /// 你基于哪一版。**对不上就是 409** @@ -1671,6 +1763,7 @@ pub struct ProviderSave { /// 检测一个上游,**不保存**。 #[derive(Debug, Clone, Serialize, Deserialize)] +#[cfg_attr(feature = "ts", derive(ts_rs::TS))] pub struct ProviderTest { pub provider: ProviderInput, /// 正在编辑的是哪一家。给了的话,表单里没改的凭据和地址从它那儿取 @@ -1679,6 +1772,7 @@ pub struct ProviderTest { } #[derive(Debug, Clone, Serialize, Deserialize)] +#[cfg_attr(feature = "ts", derive(ts_rs::TS))] pub struct ProxyInput { pub name: String, /// `socks5h` / `socks5` / `http` / `https` @@ -1693,6 +1787,7 @@ pub struct ProxyInput { /// **三态**,因为视图里拿不到原来的用户名和密码:编辑时不动认证,就得有 /// 一个「保持原样」的说法,而不是把空值当成「清掉」。 #[derive(Debug, Clone, Serialize, Deserialize)] +#[cfg_attr(feature = "ts", derive(ts_rs::TS))] #[serde(tag = "mode", rename_all = "snake_case")] pub enum ProxyAuthInput { /// 保持原来的认证(新建时等同于不需要认证) @@ -1704,6 +1799,7 @@ pub enum ProxyAuthInput { } #[derive(Debug, Clone, Serialize, Deserialize)] +#[cfg_attr(feature = "ts", derive(ts_rs::TS))] pub struct ProxySave { pub proxy: ProxyInput, #[serde(default, skip_serializing_if = "Option::is_none")] @@ -1712,6 +1808,7 @@ pub struct ProxySave { /// 检测一个代理,**不保存**。 #[derive(Debug, Clone, Serialize, Deserialize)] +#[cfg_attr(feature = "ts", derive(ts_rs::TS))] pub struct ProxyTest { pub proxy: ProxyInput, #[serde(default, skip_serializing_if = "Option::is_none")] @@ -1722,6 +1819,7 @@ pub struct ProxyTest { /// 新建或修改一条路由时交过来的定义。**规则的顺序就是数组的顺序。** #[derive(Debug, Clone, Serialize, Deserialize)] +#[cfg_attr(feature = "ts", derive(ts_rs::TS))] pub struct RouteInput { pub name: String, #[serde(default)] @@ -1733,6 +1831,7 @@ pub struct RouteInput { /// **条件和视图是同一套写法**([`ConditionView`]):界面拿到什么,就交回 /// 什么,不必再学一种格式。 #[derive(Debug, Clone, Serialize, Deserialize)] +#[cfg_attr(feature = "ts", derive(ts_rs::TS))] pub struct RuleInput { pub name: String, /// 空 = 兜底,匹配全部请求 @@ -1748,6 +1847,7 @@ pub struct RuleInput { } #[derive(Debug, Clone, Serialize, Deserialize)] +#[cfg_attr(feature = "ts", derive(ts_rs::TS))] pub struct RouteSave { pub route: RouteInput, #[serde(default, skip_serializing_if = "Option::is_none")] @@ -1767,6 +1867,7 @@ pub struct RouteSave { /// 删除一条路由。 #[derive(Debug, Clone, Default, Serialize, Deserialize)] +#[cfg_attr(feature = "ts", derive(ts_rs::TS))] pub struct RouteDelete { #[serde(default, skip_serializing_if = "Option::is_none")] pub base_version: Option, @@ -1777,6 +1878,7 @@ pub struct RouteDelete { /// 更换默认路由。 #[derive(Debug, Clone, Serialize, Deserialize)] +#[cfg_attr(feature = "ts", derive(ts_rs::TS))] pub struct DefaultRouteSave { pub name: String, #[serde(default, skip_serializing_if = "Option::is_none")] @@ -1785,6 +1887,7 @@ pub struct DefaultRouteSave { /// 新建或修改一个策略组时交过来的定义。 #[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` @@ -1800,6 +1903,7 @@ pub struct GroupInput { } #[derive(Debug, Clone, Serialize, Deserialize)] +#[cfg_attr(feature = "ts", derive(ts_rs::TS))] pub struct GroupSave { pub group: GroupInput, #[serde(default, skip_serializing_if = "Option::is_none")] @@ -1808,13 +1912,122 @@ pub struct GroupSave { /// 网关知道的一个模型,以及能提供它的上游(已按启用范围与停用过滤)。 #[derive(Debug, Clone, Serialize, Deserialize)] +#[cfg_attr(feature = "ts", derive(ts_rs::TS))] pub struct KnownModel { pub id: String, pub providers: Vec, } +/// 聚合类端点的时间窗(`GET /summary`、`/latency`)。**缺省是「今天」而不是 +/// 「最近 24 小时」** —— 用户问的是「今天花了多少」,那是个从零点算起的问题。 +/// +/// **查询串里的类型都把字段摊平写,不用 `#[serde(flatten)]`。**flatten 会让 +/// serde 走 `deserialize_any`,而查询串里一切都是字符串 —— `from_ms=123` 被当成 +/// 字符串喂给 `i64`,整个请求 400。只在同时带上时间窗时才失败,单元测试看不见。 +#[derive(Debug, Clone, Default, Serialize, Deserialize)] +#[cfg_attr(feature = "ts", derive(ts_rs::TS))] +pub struct Window { + #[serde(default, skip_serializing_if = "Option::is_none")] + pub from_ms: Option, + #[serde(default, skip_serializing_if = "Option::is_none")] + pub to_ms: Option, +} + +/// `GET /summary/buckets`:时间窗 + 桶宽。 +#[derive(Debug, Clone, Default, Serialize, Deserialize)] +#[cfg_attr(feature = "ts", derive(ts_rs::TS))] +pub struct BucketQuery { + #[serde(default, skip_serializing_if = "Option::is_none")] + pub from_ms: Option, + #[serde(default, skip_serializing_if = "Option::is_none")] + pub to_ms: Option, + #[serde(default, skip_serializing_if = "Option::is_none")] + pub bucket_ms: Option, +} + +/// `GET /summary/buckets/by`:再按一个维度分组。 +#[derive(Debug, Clone, Serialize, Deserialize)] +#[cfg_attr(feature = "ts", derive(ts_rs::TS))] +pub struct BucketGroupQuery { + #[serde(default, skip_serializing_if = "Option::is_none")] + pub from_ms: Option, + #[serde(default, skip_serializing_if = "Option::is_none")] + pub to_ms: Option, + #[serde(default, skip_serializing_if = "Option::is_none")] + pub bucket_ms: Option, + /// 和 `GroupQuery` 同一条理由:是枚举不是字符串,它会变成列名。 + pub dim: CostDim, +} + +/// `GET /summary/by`。 +#[derive(Debug, Clone, Serialize, Deserialize)] +#[cfg_attr(feature = "ts", derive(ts_rs::TS))] +pub struct GroupQuery { + #[serde(default, skip_serializing_if = "Option::is_none")] + pub from_ms: Option, + #[serde(default, skip_serializing_if = "Option::is_none")] + pub to_ms: Option, + /// **是枚举不是字符串。**它会决定 SQL 里的列名,用字符串就是一个 + /// 注入口;写错的值在这里被 serde 直接拒掉,而不是拼进查询。 + pub dim: CostDim, +} + +/// 一张列表要的两样:看哪一段,最多几条(`GET /history`、`/sessions`)。 +/// +/// **时间窗是可选的,而且缺省不是「今天」。**「最近 N 条」本身就是一个完整 +/// 的回答,而缺省成今天的话,过了零点这张表会空掉。两端各自可缺:只给 +/// `from_ms` 就是「从那时起到现在」。条数缺省 200、最多 2000。 +#[derive(Debug, Clone, Default, Serialize, Deserialize)] +#[cfg_attr(feature = "ts", derive(ts_rs::TS))] +pub struct ListQuery { + #[serde(default, skip_serializing_if = "Option::is_none")] + pub from_ms: Option, + #[serde(default, skip_serializing_if = "Option::is_none")] + pub to_ms: Option, + #[serde(default, skip_serializing_if = "Option::is_none")] + pub limit: Option, +} + +/// 安全日志一页要的:哪一项、哪一段、从哪条往前、几条(`GET /security/events`)。 +/// 缺省是全部,不是今天;条数缺省 100、最多 500。 +#[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, + #[serde(default, skip_serializing_if = "Option::is_none")] + pub from_ms: Option, + #[serde(default, skip_serializing_if = "Option::is_none")] + pub to_ms: Option, + /// 只要这条之前的(翻页) + #[serde(default, skip_serializing_if = "Option::is_none")] + pub before: Option, + #[serde(default, skip_serializing_if = "Option::is_none")] + pub limit: Option, +} + +/// `GET /config/at`:配置原文里的第几个字节落在哪个字段上。 +#[derive(Debug, Clone, Serialize, Deserialize)] +#[cfg_attr(feature = "ts", derive(ts_rs::TS))] +pub struct ConfigAtQuery { + pub offset: usize, +} + +/// `POST /scan`:除了用户级的配置面,还扫哪些项目目录。**我们不去找项目, +/// 只看用户指的。** +/// +/// 是请求体不是查询串:一串目录在查询串里是同一个键写好几次,而 axum 的 +/// `Query` 读不了那种写法 —— 以前是 `GET /scan?project=…`,带上一个目录就 400。 +#[derive(Debug, Clone, Default, Serialize, Deserialize)] +#[cfg_attr(feature = "ts", derive(ts_rs::TS))] +pub struct ScanRequest { + #[serde(default)] + pub projects: Vec, +} + /// 删除时带上的版本。 #[derive(Debug, Clone, Default, Serialize, Deserialize)] +#[cfg_attr(feature = "ts", derive(ts_rs::TS))] pub struct BaseVersion { #[serde(default, skip_serializing_if = "Option::is_none")] pub base_version: Option, @@ -1822,6 +2035,7 @@ pub struct BaseVersion { /// 历史里的一版。 #[derive(Debug, Clone, Serialize, Deserialize)] +#[cfg_attr(feature = "ts", derive(ts_rs::TS))] pub struct ConfigVersion { pub version: String, pub at_ms: u64, @@ -1837,6 +2051,7 @@ pub struct ConfigVersion { } #[derive(Debug, Clone, Serialize, Deserialize)] +#[cfg_attr(feature = "ts", derive(ts_rs::TS))] pub struct RollbackRequest { pub version: String, } @@ -1852,6 +2067,7 @@ pub struct RollbackRequest { /// 把第三种当成 0 加进柱子,那根柱子就是偏低的,而看图的人没有线索 /// 知道少算了什么。 #[derive(Debug, Clone, Serialize, Deserialize)] +#[cfg_attr(feature = "ts", derive(ts_rs::TS))] pub struct CostBucket { /// 桶的起点 pub at_ms: i64, @@ -1872,6 +2088,7 @@ pub struct CostBucket { /// 这两个问题只用看一次;而把它们拆成一张趋势图加一张构成图,读的人 /// 要在两张图之间自己对时间。 #[derive(Debug, Clone, Serialize, Deserialize)] +#[cfg_attr(feature = "ts", derive(ts_rs::TS))] pub struct CostBucketGroup { pub at_ms: i64, /// 模型名或上游名,看查的是哪一维 @@ -1892,6 +2109,7 @@ pub struct CostBucketGroup { /// 按模型或上游分组的花费(钱花在哪儿)。 #[derive(Debug, Clone, Serialize, Deserialize)] +#[cfg_attr(feature = "ts", derive(ts_rs::TS))] pub struct CostGroup { pub name: String, pub requests: i64, @@ -1907,6 +2125,7 @@ pub struct CostGroup { /// 分组维度。**是个枚举不是字符串** —— 它最终来自 query string, /// 而把它拼进 SQL 的列名里就是一个注入口。 #[derive(Debug, Clone, Copy, Serialize, Deserialize)] +#[cfg_attr(feature = "ts", derive(ts_rs::TS))] #[serde(rename_all = "lowercase")] pub enum CostDim { Model, @@ -1917,6 +2136,7 @@ pub enum CostDim { } #[derive(Debug, Clone, Default, Serialize, Deserialize)] +#[cfg_attr(feature = "ts", derive(ts_rs::TS))] pub struct Summary { pub requests: i64, pub failed: i64, @@ -1956,6 +2176,7 @@ pub struct Summary { } #[derive(Debug, Clone, Serialize, Deserialize)] +#[cfg_attr(feature = "ts", derive(ts_rs::TS))] pub struct LatencyView { pub model: String, pub p50: i64, @@ -1966,6 +2187,7 @@ pub struct LatencyView { /// 一条历史请求。 #[derive(Debug, Clone, Serialize, Deserialize)] +#[cfg_attr(feature = "ts", derive(ts_rs::TS))] pub struct HistoryRow { pub id: i64, pub at_ms: i64, @@ -2037,6 +2259,7 @@ pub struct HistoryRow { /// 一次请求做过的格式转换。 #[derive(Debug, Clone, PartialEq, Serialize, Deserialize)] +#[cfg_attr(feature = "ts", derive(ts_rs::TS))] pub struct TranslatedView { /// 客户端的格式:`anthropic` / `openai-chat` / `openai-responses` / `gemini` pub from: String, @@ -2049,6 +2272,7 @@ pub struct TranslatedView { /// 一条请求的全部细节。**详情抽屉吃这个。** #[derive(Debug, Clone, Serialize, Deserialize)] +#[cfg_attr(feature = "ts", derive(ts_rs::TS))] pub struct RequestDetail { pub row: HistoryRow, pub request_body: Option, @@ -2062,6 +2286,7 @@ pub struct RequestDetail { /// 一份存下来的 body。 #[derive(Debug, Clone, Serialize, Deserialize)] +#[cfg_attr(feature = "ts", derive(ts_rs::TS))] pub struct BodyView { /// **已脱敏**。这段文字会被复制到 issue 里 pub text: String, @@ -2073,6 +2298,7 @@ pub struct BodyView { /// 一个上游的订阅额度。 #[derive(Debug, Clone, Serialize, Deserialize)] +#[cfg_attr(feature = "ts", derive(ts_rs::TS))] pub struct ProviderQuota { pub provider: String, pub windows: Vec, @@ -2082,6 +2308,7 @@ pub struct ProviderQuota { /// 发起 ChatGPT 登录(`POST /chatgpt/login`)。 #[derive(Debug, Clone, Default, Serialize, Deserialize)] +#[cfg_attr(feature = "ts", derive(ts_rs::TS))] pub struct ChatgptLoginStart { /// 登录后写进配置的上游名。不给就是 `chatgpt`;已经有同名的 ChatGPT 账号上游时, /// 换掉它的凭据(重新登录),其余设置不动 @@ -2102,6 +2329,7 @@ pub struct ChatgptLoginStart { /// 一次进行中的登录。 #[derive(Debug, Clone, Serialize, Deserialize)] +#[cfg_attr(feature = "ts", derive(ts_rs::TS))] pub struct ChatgptLogin { pub id: String, /// 在浏览器里打开的授权地址。`browser` 登录才有 @@ -2119,6 +2347,7 @@ pub struct ChatgptLogin { /// 登录进行到哪一步(`GET /chatgpt/login/{id}`)。 #[derive(Debug, Clone, Serialize, Deserialize)] +#[cfg_attr(feature = "ts", derive(ts_rs::TS))] pub struct ChatgptLoginStatus { pub id: String, /// `pending` / `done` / `failed` / `expired` / `cancelled` @@ -2136,6 +2365,7 @@ pub struct ChatgptLoginStatus { /// ChatGPT 账号的用量(`GET /providers/{name}/chatgpt/usage`)。 #[derive(Debug, Clone, Serialize, Deserialize)] +#[cfg_attr(feature = "ts", derive(ts_rs::TS))] pub struct ChatgptUsage { /// 登的是哪个账号。**只有邮箱** —— 同一份回答里的用户 ID /// 和账户 ID 不往外带:界面认账号靠邮箱,那两个读不出是谁 @@ -2152,6 +2382,7 @@ pub struct ChatgptUsage { /// 一张额度重置卡。 #[derive(Debug, Clone, Serialize, Deserialize, PartialEq)] +#[cfg_attr(feature = "ts", derive(ts_rs::TS))] pub struct ResetCreditView { pub id: String, /// 重置哪种额度,后端的原词 @@ -2169,6 +2400,7 @@ pub struct ResetCreditView { /// 账号上的额度重置卡(`GET /providers/{name}/chatgpt/resets`)。 #[derive(Debug, Clone, Serialize, Deserialize)] +#[cfg_attr(feature = "ts", derive(ts_rs::TS))] pub struct ResetCredits { pub available_count: i64, pub credits: Vec, @@ -2178,6 +2410,7 @@ pub struct ResetCredits { /// /// **卡用掉就回不来**,所以只在用户明确点下去时发,网关自己从不用。 #[derive(Debug, Clone, Serialize, Deserialize)] +#[cfg_attr(feature = "ts", derive(ts_rs::TS))] pub struct ResetCreditUse { /// 幂等键。同一次操作重试时用同一个值,后端不会重复扣卡 pub idempotency_key: String, @@ -2187,6 +2420,7 @@ pub struct ResetCreditUse { } #[derive(Debug, Clone, Serialize, Deserialize, PartialEq)] +#[cfg_attr(feature = "ts", derive(ts_rs::TS))] pub struct ResetCreditUsed { /// - `reset`:额度已重置 /// - `nothing_to_reset`:额度没用完,不需要重置,没有扣卡 @@ -2200,6 +2434,7 @@ pub struct ResetCreditUsed { /// 用 Z.ai 或 BigModel 的账号登录(`POST /zai/login`)。 #[derive(Debug, Clone, Serialize, Deserialize)] +#[cfg_attr(feature = "ts", derive(ts_rs::TS))] pub struct ZaiLoginStart { /// 登哪一家:`zai`(api.z.ai)或 `bigmodel`(open.bigmodel.cn)。不给是 `zai` #[serde(default, skip_serializing_if = "Option::is_none")] @@ -2219,6 +2454,7 @@ pub struct ZaiLoginStart { /// **没有回到应用的地址**:授权完成后浏览器停在对方自己的页面上,那一页不是我们的, /// 我们只能靠轮询知道登录成了。 #[derive(Debug, Clone, Serialize, Deserialize)] +#[cfg_attr(feature = "ts", derive(ts_rs::TS))] pub struct ZaiLogin { pub id: String, /// 在浏览器里打开的授权地址 @@ -2229,6 +2465,7 @@ pub struct ZaiLogin { /// 登录进行到哪一步(`GET /zai/login/{id}`)。 #[derive(Debug, Clone, Serialize, Deserialize)] +#[cfg_attr(feature = "ts", derive(ts_rs::TS))] pub struct ZaiLoginStatus { pub id: String, /// `pending` / `done` / `failed` / `expired` / `cancelled` @@ -2249,6 +2486,7 @@ pub struct ZaiLoginStatus { /// **这是「你确认要花钱吗」那个对话框的全部内容。**触发前必须显示它, /// 而不是点了才知道。 #[derive(Debug, Clone, Serialize, Deserialize)] +#[cfg_attr(feature = "ts", derive(ts_rs::TS))] pub struct SpeedEstimate { pub provider: String, pub model: String, @@ -2271,6 +2509,7 @@ pub struct SpeedEstimate { /// 一批测速的账。 #[derive(Debug, Clone, Serialize, Deserialize)] +#[cfg_attr(feature = "ts", derive(ts_rs::TS))] pub struct SpeedQuote { pub items: Vec, /// 总计。有一项算不出来就是 None —— 给一个看起来完整的数字,用户会 @@ -2281,6 +2520,7 @@ pub struct SpeedQuote { } #[derive(Debug, Clone, Deserialize, Serialize)] +#[cfg_attr(feature = "ts", derive(ts_rs::TS))] pub struct SpeedRunRequest { /// 测哪几家。空 = 所有上游 #[serde(default, skip_serializing_if = "Vec::is_empty")] @@ -2292,6 +2532,7 @@ pub struct SpeedRunRequest { /// 一次 L3 测速的结果。 #[derive(Debug, Clone, Serialize, Deserialize)] +#[cfg_attr(feature = "ts", derive(ts_rs::TS))] pub struct SpeedResult { pub provider: String, pub model: String, @@ -2315,6 +2556,7 @@ pub struct SpeedResult { /// **不看磁盘还剩多少。**那是操作系统的事,网关管好自己占的那一份就够了 /// —— 正文按天数和总量回收(见 `tw_store::blobs`),摘要按天数回收。 #[derive(Debug, Clone, Serialize, Deserialize)] +#[cfg_attr(feature = "ts", derive(ts_rs::TS))] pub struct StorageStatus { /// 请求记录启动了没有。`false` = 数据库打不开之类,这段时间的请求都不会留下 pub recording: bool, @@ -2333,6 +2575,7 @@ pub struct StorageStatus { /// **孤立地看单个请求,看不出任何有用的东西** —— Claude Code 的一次任务 /// 是几十到上百个请求,携带不断增长的上下文。 #[derive(Debug, Clone, Serialize, Deserialize)] +#[cfg_attr(feature = "ts", derive(ts_rs::TS))] pub struct SessionView { pub id: String, pub client: String, @@ -2364,6 +2607,7 @@ pub struct SessionView { /// 会话里的一轮。上下文增长曲线和成本瀑布画的就是它。 #[derive(Debug, Clone, Serialize, Deserialize)] +#[cfg_attr(feature = "ts", derive(ts_rs::TS))] pub struct TurnView { pub id: i64, pub at_ms: u64, @@ -2387,6 +2631,7 @@ pub struct TurnView { } #[derive(Debug, Clone, Serialize, Deserialize)] +#[cfg_attr(feature = "ts", derive(ts_rs::TS))] pub struct SessionDetail { pub session: SessionView, pub turns: Vec, @@ -2396,6 +2641,7 @@ pub struct SessionDetail { /// 把存下来的那条请求,原样发给另一个上游。 #[derive(Debug, Clone, Serialize, Deserialize)] +#[cfg_attr(feature = "ts", derive(ts_rs::TS))] pub struct ReplayRequest { pub id: i64, pub provider: String, @@ -2403,6 +2649,7 @@ pub struct ReplayRequest { /// 报价。**按下确认之前必须看到它**(和 L3 测速同一条纪律)。 #[derive(Debug, Clone, Serialize, Deserialize)] +#[cfg_attr(feature = "ts", derive(ts_rs::TS))] pub struct ReplayQuote { pub model: String, pub provider: String, @@ -2419,6 +2666,7 @@ pub struct ReplayQuote { /// 原来那一次长什么样,用来并排比。 #[derive(Debug, Clone, Serialize, Deserialize)] +#[cfg_attr(feature = "ts", derive(ts_rs::TS))] pub struct ReplayOriginal { pub provider: String, pub status: Option, @@ -2428,6 +2676,7 @@ pub struct ReplayOriginal { } #[derive(Debug, Clone, Serialize, Deserialize)] +#[cfg_attr(feature = "ts", derive(ts_rs::TS))] pub struct ReplayResult { pub provider: String, pub status: u16, @@ -2443,6 +2692,7 @@ pub struct ReplayResult { /// 一处发现。 #[derive(Debug, Clone, Serialize, Deserialize)] +#[cfg_attr(feature = "ts", derive(ts_rs::TS))] pub struct ScanFinding { /// `high` | `medium` | `low` pub level: String, @@ -2461,6 +2711,7 @@ pub struct ScanFinding { } #[derive(Debug, Clone, Serialize, Deserialize)] +#[cfg_attr(feature = "ts", derive(ts_rs::TS))] pub struct McpView { pub name: String, pub client: String, @@ -2477,6 +2728,7 @@ pub struct McpView { } #[derive(Debug, Clone, Serialize, Deserialize)] +#[cfg_attr(feature = "ts", derive(ts_rs::TS))] pub struct SkillView { pub name: String, pub client: String, @@ -2485,6 +2737,7 @@ pub struct SkillView { } #[derive(Debug, Clone, Serialize, Deserialize)] +#[cfg_attr(feature = "ts", derive(ts_rs::TS))] pub struct HookView { pub client: String, pub event: String, @@ -2496,6 +2749,7 @@ pub struct HookView { /// /// **不存任何东西**:这是此刻磁盘上的真实情况,页面关了就没了。 #[derive(Debug, Clone, Serialize, Deserialize)] +#[cfg_attr(feature = "ts", derive(ts_rs::TS))] pub struct ScanResponse { pub findings: Vec, pub mcp: Vec, @@ -2512,6 +2766,7 @@ pub struct ScanResponse { /// 在矩阵上点一下。 #[derive(Debug, Clone, Serialize, Deserialize)] +#[cfg_attr(feature = "ts", derive(ts_rs::TS))] pub struct McpOpRequest { /// `copy` 或 `remove` pub op: String, @@ -2525,6 +2780,7 @@ pub struct McpOpRequest { /// 哪些客户端能被写入,哪些只能看。 #[derive(Debug, Clone, Serialize, Deserialize)] +#[cfg_attr(feature = "ts", derive(ts_rs::TS))] pub struct McpTargetView { pub client: String, pub name: String, @@ -2543,6 +2799,7 @@ pub struct McpTargetView { /// **每个字段都对应规则里能写的一个条件**。默认值就是一个最 /// 普通的请求 —— 用户只需要改他关心的那一两个。 #[derive(Debug, Clone, Serialize, Deserialize)] +#[cfg_attr(feature = "ts", derive(ts_rs::TS))] pub struct DryRunRequest { pub model: String, /// 哪把密钥发的。只给它时按这把密钥使用的路由求值;规则里的 `client` @@ -2590,6 +2847,7 @@ fn default_true() -> bool { /// 一条规则在这次试算里的下场。**没命中的也要列出来,并说清为什么** —— /// 「为什么没走我以为的那条」和「走了哪条」是同一个问题的两面。 #[derive(Debug, Clone, Serialize, Deserialize)] +#[cfg_attr(feature = "ts", derive(ts_rs::TS))] pub struct RuleTrace { pub name: String, /// `matched` | `skipped` | `phase_two`(条件要等选定上游之后才能求值, @@ -2609,6 +2867,7 @@ pub struct RuleTrace { /// 一个没对上的条件。 #[derive(Debug, Clone, PartialEq, Serialize, Deserialize)] +#[cfg_attr(feature = "ts", derive(ts_rs::TS))] pub struct MismatchView { /// 和 `ConditionView.field` 同一个词表 pub field: String, @@ -2620,6 +2879,7 @@ pub struct MismatchView { /// 一项参数改写。 #[derive(Debug, Clone, PartialEq, Serialize, Deserialize)] +#[cfg_attr(feature = "ts", derive(ts_rs::TS))] pub struct SetView { /// `model`(换模型,整个 prompt cache 作废)/ `max_tokens` / `thinking` / /// `only_at_session_start`(以上改写只在新会话开始时应用,值是 `true`) @@ -2628,6 +2888,7 @@ pub struct SetView { } #[derive(Debug, Clone, Serialize, Deserialize)] +#[cfg_attr(feature = "ts", derive(ts_rs::TS))] pub struct DryRunResult { /// 按哪条路由求的值。草稿是草稿的名字 pub route: String, @@ -2668,6 +2929,7 @@ pub struct DryRunResult { /// 一个要转换格式的候选上游。 #[derive(Debug, Clone, PartialEq, Serialize, Deserialize)] +#[cfg_attr(feature = "ts", derive(ts_rs::TS))] pub struct ConvertedView { pub provider: String, /// 客户端的格式:`anthropic` / `openai-chat` / `openai-responses` / `gemini` @@ -2678,6 +2940,7 @@ pub struct ConvertedView { /// 一个被跳过的候选上游。 #[derive(Debug, Clone, PartialEq, Serialize, Deserialize)] +#[cfg_attr(feature = "ts", derive(ts_rs::TS))] pub struct SkippedView { pub provider: String, /// `disabled` / `out_of_scope` / `not_offered` @@ -2692,6 +2955,7 @@ pub struct SkippedView { /// 一个客户端此刻的样子。 #[derive(Debug, Clone, Serialize, Deserialize)] +#[cfg_attr(feature = "ts", derive(ts_rs::TS))] pub struct DetectedClient { pub id: String, pub name: String, @@ -2735,6 +2999,7 @@ pub struct DetectedClient { /// 接管不了、只能给指引的。 #[derive(Debug, Clone, Serialize, Deserialize)] +#[cfg_attr(feature = "ts", derive(ts_rs::TS))] pub struct ManualClient { /// `cursor` / `continue` / `gemini-cli`。为它生成专用密钥时用 pub id: String, @@ -2755,6 +3020,7 @@ pub struct ManualClient { /// **地址和密钥不写进句子里**:界面各给一个复制按钮。写进句子的话,用户 /// 得从一句话里抠出一段 URL,而密钥根本不该出现在一句说明里。 #[derive(Debug, Clone, Serialize, Deserialize)] +#[cfg_attr(feature = "ts", derive(ts_rs::TS))] pub struct ManualSetup { /// 按顺序做的几步 pub steps: Vec, @@ -2767,6 +3033,7 @@ pub struct ManualSetup { /// 为某个客户端准备的那把网关密钥(`POST /clients/{id}/key`)。 #[derive(Debug, Clone, Serialize, Deserialize)] +#[cfg_attr(feature = "ts", derive(ts_rs::TS))] pub struct ClientKey { pub name: String, /// 明文。这一步就是为了拿去填进客户端 @@ -2776,6 +3043,7 @@ pub struct ClientKey { } #[derive(Debug, Clone, Serialize, Deserialize)] +#[cfg_attr(feature = "ts", derive(ts_rs::TS))] pub struct ClientsResponse { pub clients: Vec, pub manual: Vec, @@ -2786,6 +3054,7 @@ pub struct ClientsResponse { } #[derive(Debug, Clone, Serialize, Deserialize)] +#[cfg_attr(feature = "ts", derive(ts_rs::TS))] pub struct AdoptRequest { pub client: String, /// 用哪把网关密钥。不写就用第一把 —— 为「一个 key 就够」的人设计 @@ -2795,6 +3064,7 @@ pub struct AdoptRequest { /// 算好但还没落盘的改动。**UI 拿它画 diff 让用户确认。** #[derive(Debug, Clone, Serialize, Deserialize)] +#[cfg_attr(feature = "ts", derive(ts_rs::TS))] pub struct PlanView { pub client: String, pub path: String, @@ -2822,6 +3092,7 @@ pub struct PlanView { /// 配置文件里的一处改动。 #[derive(Debug, Clone, PartialEq, Serialize, Deserialize)] +#[cfg_attr(feature = "ts", derive(ts_rs::TS))] pub struct FieldChange { /// `set` | `remove` pub op: String, @@ -2836,6 +3107,7 @@ pub struct FieldChange { } #[derive(Debug, Clone, Serialize, Deserialize)] +#[cfg_attr(feature = "ts", derive(ts_rs::TS))] pub struct AdoptResponse { pub real: String, pub backup: String, @@ -2848,6 +3120,7 @@ pub struct AdoptResponse { /// 一条诊断发现。 #[derive(Debug, Clone, Serialize, Deserialize)] +#[cfg_attr(feature = "ts", derive(ts_rs::TS))] pub struct FindingView { /// `blocking` | `suspect` | `clear` pub level: String, @@ -2861,6 +3134,7 @@ pub struct FindingView { /// 出站脱敏找到的一项:哪条规则、哪个值(已打码)、在这个请求里出现了几次。 #[derive(Debug, Clone, PartialEq, Serialize, Deserialize)] +#[cfg_attr(feature = "ts", derive(ts_rs::TS))] pub struct SecretItem { /// 内置规则的 id(`anthropic-api-key` …),或者自定义规则的名字 pub rule: String, @@ -2876,6 +3150,7 @@ pub struct SecretItem { /// 两项防护在一段时间里各留下了几条记录。 #[derive(Debug, Clone, Default, PartialEq, Serialize, Deserialize)] +#[cfg_attr(feature = "ts", derive(ts_rs::TS))] pub struct SecurityCounts { /// 出站脱敏找到的(每条 = 一个请求里的一个值) pub secrets: i64, @@ -2892,6 +3167,7 @@ pub struct SecurityCounts { /// **一条是一次命中**:出站脱敏是「一个请求里的一个值」(出现几次合成 /// 一条,`count` 说几次),工具调用审查是「一个工具调用命中一条规则」。 #[derive(Debug, Clone, PartialEq, Serialize, Deserialize)] +#[cfg_attr(feature = "ts", derive(ts_rs::TS))] pub struct SecurityEventView { pub id: i64, pub at_ms: i64, @@ -2932,6 +3208,7 @@ pub struct SecurityEventView { /// 安全日志的一页。**按时间倒序**,`more` 说后面还有没有。 #[derive(Debug, Clone, Serialize, Deserialize)] +#[cfg_attr(feature = "ts", derive(ts_rs::TS))] pub struct SecurityEventsPage { pub events: Vec, pub more: bool, @@ -2939,6 +3216,7 @@ pub struct SecurityEventsPage { /// 一条内置规则按什么认。**给界面说明用**,界面按类型写成自己的话。 #[derive(Debug, Clone, PartialEq, Serialize, Deserialize)] +#[cfg_attr(feature = "ts", derive(ts_rs::TS))] #[serde(tag = "kind", rename_all = "kebab-case")] pub enum Matcher { /// 以 `prefix` 开头,其后至少还有 `min_tail` 个字符 @@ -2961,6 +3239,7 @@ pub enum Matcher { /// 一条规则。 #[derive(Debug, Clone, PartialEq, Serialize, Deserialize)] +#[cfg_attr(feature = "ts", derive(ts_rs::TS))] pub struct SecurityRuleView { /// 内置规则的 id,或者自定义规则的名字 pub id: String, @@ -2987,6 +3266,7 @@ pub struct SecurityRuleView { /// 一项防护的档位和规则。 #[derive(Debug, Clone, Serialize, Deserialize)] +#[cfg_attr(feature = "ts", derive(ts_rs::TS))] pub struct GuardDetail { /// `off` / `observe` / `enforce` pub mode: String, @@ -2996,6 +3276,7 @@ pub struct GuardDetail { /// 两项防护。 #[derive(Debug, Clone, Serialize, Deserialize)] +#[cfg_attr(feature = "ts", derive(ts_rs::TS))] pub struct SecurityDetail { pub redact: GuardDetail, pub inspect_tools: GuardDetail, @@ -3003,6 +3284,7 @@ pub struct SecurityDetail { /// 改档位。 #[derive(Debug, Clone, Serialize, Deserialize)] +#[cfg_attr(feature = "ts", derive(ts_rs::TS))] pub struct ModeSave { /// `off` / `observe` / `enforce` pub mode: String, @@ -3012,6 +3294,7 @@ pub struct ModeSave { /// 启用或停用一条规则(内置的或自定义的)。 #[derive(Debug, Clone, Serialize, Deserialize)] +#[cfg_attr(feature = "ts", derive(ts_rs::TS))] pub struct RuleToggle { pub enabled: bool, #[serde(default, skip_serializing_if = "Option::is_none")] @@ -3021,6 +3304,7 @@ pub struct RuleToggle { /// 改一条内置规则在拦截档下做什么。只有工具调用审查的规则有这一项 —— /// 出站脱敏命中之后做什么由档位决定。 #[derive(Debug, Clone, Serialize, Deserialize)] +#[cfg_attr(feature = "ts", derive(ts_rs::TS))] pub struct ActionSave { /// `cut` / `record` pub action: String, @@ -3030,6 +3314,7 @@ pub struct ActionSave { /// 新建或修改一条自定义规则。改的时候名字可以变,那就是改名。 #[derive(Debug, Clone, Serialize, Deserialize)] +#[cfg_attr(feature = "ts", derive(ts_rs::TS))] pub struct CustomRuleSave { pub name: String, pub pattern: String, @@ -3049,6 +3334,7 @@ fn yes() -> bool { /// 拿一段文本试一试。给了 `pattern` 就只试这一条正则,给了 `rule` 就只试 /// 这一条内置规则(停用着的也能试),都不给就按现在启用的全部规则。 #[derive(Debug, Clone, Serialize, Deserialize)] +#[cfg_attr(feature = "ts", derive(ts_rs::TS))] pub struct SecurityTestRequest { pub sample: String, #[serde(default, skip_serializing_if = "Option::is_none")] @@ -3059,6 +3345,7 @@ pub struct SecurityTestRequest { /// 试出来的一处。 #[derive(Debug, Clone, PartialEq, Serialize, Deserialize)] +#[cfg_attr(feature = "ts", derive(ts_rs::TS))] pub struct SecurityTestHit { pub rule: String, #[serde(default)] @@ -3075,6 +3362,7 @@ pub struct SecurityTestHit { } #[derive(Debug, Clone, Serialize, Deserialize)] +#[cfg_attr(feature = "ts", derive(ts_rs::TS))] pub struct SecurityTestResult { pub hits: Vec, } @@ -3230,7 +3518,7 @@ mod tests { /// 凭据文件、配置都在里面,两边各算一遍、算得不一样的话,界面找不到一个正在 /// 跑的网关。以前桌面端自己只看 `HOME`,Windows 上那个变量默认不存在,于是它 /// 落到当前目录下的 `.thinkwatch`,而 core 在 `%APPDATA%\ThinkWatch`。控制面 -/// 的地址(`control::Endpoint`)因为同样的理由搬到了这里。 +/// 的地址(`control::Address`)因为同样的理由搬到了这里。 pub mod data { use std::path::PathBuf; @@ -3410,9 +3698,11 @@ pub mod control { /// 同用户进程都看得见别人的命令行。 pub const TOKEN_ENV: &str = "TW_CONTROL_TOKEN"; - /// 控制面听在哪。 + /// 控制面听在哪,客户端到哪儿连。 + /// + /// 叫 `Address` 不叫 `Endpoint`:[`crate::Endpoint`] 是控制面上的一个端点。 #[derive(Debug, Clone, PartialEq, Eq)] - pub enum Endpoint { + pub enum Address { /// 一个 `0700` 的 unix socket 文件。**权限是文件系统给的**,所以这 /// 一档天然只有当前用户连得上。 Socket(PathBuf), @@ -3426,16 +3716,16 @@ pub mod control { Loopback { port_file: PathBuf }, } - impl Endpoint { + impl Address { /// 这个平台默认听在数据目录的什么位置。 pub fn in_dir(dir: &Path) -> Self { #[cfg(unix)] { - Endpoint::Socket(dir.join(SOCKET_FILE)) + Address::Socket(dir.join(SOCKET_FILE)) } #[cfg(not(unix))] { - Endpoint::Loopback { + Address::Loopback { port_file: dir.join(PORT_FILE), } } @@ -3455,9 +3745,9 @@ pub mod control { #[test] fn the_endpoint_lands_in_the_data_directory() { let d = Path::new("/data"); - match Endpoint::in_dir(d) { - Endpoint::Socket(p) => assert_eq!(p, d.join(SOCKET_FILE)), - Endpoint::Loopback { port_file } => assert_eq!(port_file, d.join(PORT_FILE)), + match Address::in_dir(d) { + Address::Socket(p) => assert_eq!(p, d.join(SOCKET_FILE)), + Address::Loopback { port_file } => assert_eq!(port_file, d.join(PORT_FILE)), } assert_eq!(token_file(d), d.join(TOKEN_FILE)); } @@ -3465,11 +3755,11 @@ pub mod control { /// 平台决定用哪一档,不是调用方挑。 #[test] fn each_platform_gets_the_only_transport_it_has() { - let got = Endpoint::in_dir(Path::new("/data")); + let got = Address::in_dir(Path::new("/data")); if cfg!(unix) { - assert!(matches!(got, Endpoint::Socket(_))); + assert!(matches!(got, Address::Socket(_))); } else { - assert!(matches!(got, Endpoint::Loopback { .. })); + assert!(matches!(got, Address::Loopback { .. })); } } } diff --git a/crates/tw-api/src/ts.rs b/crates/tw-api/src/ts.rs new file mode 100644 index 00000000..e022a66a --- /dev/null +++ b/crates/tw-api/src/ts.rs @@ -0,0 +1,227 @@ +//! 把契约导出成一个 TypeScript 文件(`ts` feature)。 +//! +//! **从端点表出发,不从一张手写的类型清单出发。**每个端点的请求和响应类型 +//! 连同它们引用到的一切都会导出;一个不在任何端点上出现的类型不在线上, +//! 也就不该出现在前端。手写清单会漏,而漏掉的表现是前端又开始手写那个类型。 +//! +//! 几个取舍: +//! - **64 位整数导出成 `number`,不是 ts-rs 默认的 `bigint`。**线上是 JSON, +//! `JSON.parse` 给出来的就是 `number`;类型写成 `bigint` 只会让类型和值对不上。 +//! 毫秒时间戳、字节数、token 数都远小于 2^53。 +//! - `Option` + `skip_serializing_if` 的字段是 `name?: T`,没带的是 `name: T | null`, +//! 和 serde 实际发出的一致。 +//! - 文档注释原样带过去,成了 JSDoc。 + +use std::any::TypeId; +use std::collections::{BTreeMap, HashSet}; +use std::path::{Path, PathBuf}; + +use ts_rs::{Config, TS, TypeVisitor}; + +use crate::endpoint::Endpoint; + +/// 导出的文件名。 +pub const FILE: &str = "tw-api.ts"; + +/// 端点表对每个端点做的事。由 `endpoints!` 生成的 `visit_types` 调用。 +pub(crate) trait Visit { + fn endpoint(&mut self) + where + E::Req: TS + 'static, + E::Res: TS + 'static; +} + +struct Collect { + cfg: Config, + seen: HashSet, + /// 名字 → 声明。按名字排,输出稳定 + decls: BTreeMap, + endpoints: Vec<(&'static str, String, String)>, +} + +impl TypeVisitor for Collect { + fn visit(&mut self) { + // 基本类型、Vec、Option 这些没有自己的声明 + if T::output_path().is_none() || !self.seen.insert(TypeId::of::()) { + return; + } + let name = T::ident(&self.cfg); + let mut decl = T::docs().unwrap_or_default(); + decl.push_str("export "); + decl.push_str(&T::decl(&self.cfg)); + if let Some((other, _)) = self.decls.insert(name.clone(), (TypeId::of::(), decl)) { + // 两个 Rust 类型导出成同一个名字,前端只能看到其中一个 + assert_eq!( + other, + TypeId::of::(), + "two wire types are both named `{name}` in TypeScript" + ); + } + T::visit_dependencies(self); + } +} + +impl Collect { + /// 一个出现在端点上的类型:它自己,加上它的类型参数(`Vec` 的 `X`)。 + fn root(&mut self) { + self.visit::(); + T::visit_generics(self); + } +} + +impl Visit for Collect { + fn endpoint(&mut self) + where + E::Req: TS + 'static, + E::Res: TS + 'static, + { + self.root::(); + self.root::(); + let req = ::name(&self.cfg); + let res = ::name(&self.cfg); + self.endpoints.push((E::NAME, req, res)); + } +} + +/// 整个契约,一个 TypeScript 模块。 +pub fn typescript() -> String { + let mut c = Collect { + cfg: Config::new().with_large_int("number"), + seen: HashSet::new(), + decls: BTreeMap::new(), + endpoints: Vec::new(), + }; + crate::ep::visit_types(&mut c); + c.root::(); + + let mut out = + String::from("// Generated by tw-api (`tw_api::ts::export_all`). Do not edit by hand.\n\n"); + out.push_str(&format!( + "export const CONTROL_API_VERSION = {};\n\n", + crate::CONTROL_API_VERSION + )); + for (_, decl) in c.decls.values() { + out.push_str(decl); + out.push_str("\n\n"); + } + out.push_str( + "// The body of every non-2xx control-plane response.\nexport type ErrorBody = Msg;\n\n", + ); + + out.push_str("export const ENDPOINTS = {\n"); + for e in crate::ep::ALL { + let params: Vec = e.params.iter().map(|p| format!("\"{p}\"")).collect(); + out.push_str(&format!( + " {}: {{ method: \"{}\", path: \"{}\", params: [{}], format: \"{}\" }},\n", + e.name, + e.method.as_str(), + e.path, + params.join(", "), + e.format.as_str() + )); + } + out.push_str("} as const;\n\n"); + + out.push_str( + "// Request and response types per endpoint. `req` travels as the query string for GET\n// and DELETE, as the JSON body otherwise; `null` means none.\nexport type Endpoints = {\n", + ); + for (name, req, res) in &c.endpoints { + out.push_str(&format!(" {name}: {{ req: {req}; res: {res} }};\n")); + } + out.push_str("};\n\nexport type EndpointName = keyof Endpoints;\n"); + out +} + +/// 把 [`typescript`] 写到 `dir/tw-api.ts`,返回写到的路径。目录不存在就建。 +pub fn export_all(dir: &Path) -> std::io::Result { + std::fs::create_dir_all(dir)?; + let path = dir.join(FILE); + std::fs::write(&path, typescript())?; + Ok(path) +} + +#[cfg(test)] +mod tests { + use super::*; + + fn decl_of(ts: &str, name: &str) -> String { + let start = ts + .find(&format!("export type {name} = ")) + .unwrap_or_else(|| panic!("`{name}` was not exported")); + let rest = &ts[start..]; + rest[..rest.find(";\n").unwrap()].to_string() + } + + /// 线上是 JSON,64 位整数在 JS 里就是 `number`。 + #[test] + fn large_integers_are_numbers_not_bigints() { + let ts = typescript(); + assert!(!ts.contains("bigint"), "a bigint slipped through"); + let usage = decl_of(&ts, "UsageView"); + assert!(usage.contains("input: number"), "{usage}"); + } + + /// `Option` + `skip_serializing_if` 是可以不出现的字段;没带的是可以为 null 的字段。 + #[test] + fn optional_fields_follow_what_serde_actually_sends() { + let ts = typescript(); + let status = decl_of(&ts, "Status"); + assert!(status.contains("listen_error?: Msg"), "{status}"); + assert!(status.contains("gateway_addr: string | null"), "{status}"); + let usage = decl_of(&ts, "UsageView"); + assert!(usage.contains("cache_1h?: boolean"), "{usage}"); + } + + /// 带 tag 的枚举导出成可辨识联合,前端按 `kind` 分派。 + #[test] + fn tagged_enums_become_discriminated_unions() { + let ts = typescript(); + let event = decl_of(&ts, "Event"); + assert!(event.contains("\"kind\": \"request_started\""), "{event}"); + let patch = decl_of(&ts, "PatchValue"); + assert!(!patch.contains("\"kind\""), "untagged: {patch}"); + } + + #[test] + fn maps_and_messages_come_through() { + let ts = typescript(); + let msg = decl_of(&ts, "Msg"); + assert!(msg.contains("args?: { [key in string]: string }"), "{msg}"); + let sheet = decl_of(&ts, "PriceSheetInput"); + assert!( + sheet.contains("{ [key in string]: PriceFields }"), + "{sheet}" + ); + } + + #[test] + fn every_endpoint_is_in_the_table() { + let ts = typescript(); + for e in crate::ep::ALL { + assert!( + ts.contains(&format!(" {}: {{ method: ", e.name)), + "{}", + e.name + ); + assert!( + ts.contains(&format!(" {}: {{ req: ", e.name)), + "{}", + e.name + ); + } + assert!(ts.contains(" Status: { req: null; res: Status };")); + assert!(ts.contains(" L1: { req: L1Request; res: Array };")); + assert!(ts.contains( + " Events: { method: \"GET\", path: \"/events\", params: [], format: \"events\" }," + )); + } + + #[test] + fn it_writes_one_file() { + let dir = std::env::temp_dir().join(format!("tw-api-ts-{}", std::process::id())); + let path = export_all(&dir).unwrap(); + assert_eq!(path, dir.join(FILE)); + assert_eq!(std::fs::read_to_string(&path).unwrap(), typescript()); + std::fs::remove_dir_all(&dir).unwrap(); + } +} diff --git a/crates/tw-control/Cargo.toml b/crates/tw-control/Cargo.toml index 576ece01..d953a4e2 100644 --- a/crates/tw-control/Cargo.toml +++ b/crates/tw-control/Cargo.toml @@ -42,6 +42,8 @@ tower = { workspace = true } tracing = { workspace = true } [dev-dependencies] +# 契约测试按 tw-api 的类型拼查询串,和客户端一样 +serde_urlencoded = "0.7" # 测试里的假 OpenAI:拼 id_token、核对 PKCE base64 = { workspace = true } sha2 = { workspace = true } diff --git a/crates/tw-control/src/chatgpt.rs b/crates/tw-control/src/chatgpt.rs index 0496476f..0fb378c5 100644 --- a/crates/tw-control/src/chatgpt.rs +++ b/crates/tw-control/src/chatgpt.rs @@ -28,13 +28,15 @@ use axum::Json; use axum::extract::{Path, Query, State}; use axum::http::StatusCode; use axum::response::Html; -use axum::routing::{get, post}; +use axum::routing::get; use serde_json::Value; use tw_config::Protocol; use tw_config::history::Origin; use tw_gateway::chatgpt; +use crate::contract::RouterExt; use crate::{ControlState, Fail, fail}; +use tw_api::ep; use tw_types::{Msg, msg}; /// 登录要在多久之内完成。和 Codex 一样是 15 分钟 @@ -49,13 +51,12 @@ const API_TIMEOUT: Duration = Duration::from_secs(15); pub fn router() -> axum::Router { axum::Router::new() - .route("/chatgpt/login", post(start)) - .route("/chatgpt/login/{id}", get(status).delete(cancel)) - .route("/providers/{name}/chatgpt/usage", get(usage)) - .route( - "/providers/{name}/chatgpt/resets", - get(list_resets).post(use_reset), - ) + .at(ep::StartChatgptLogin, start) + .at(ep::ChatgptLoginStatus, status) + .at(ep::CancelChatgptLogin, cancel) + .at(ep::ChatgptUsage, usage) + .at(ep::ChatgptResets, list_resets) + .at(ep::UseChatgptReset, use_reset) } /// 登录要用的地址。**平时是 OpenAI 的**,测试里换成本机的假服务器 diff --git a/crates/tw-control/src/config.rs b/crates/tw-control/src/config.rs index 17bf5459..4df2b9f2 100644 --- a/crates/tw-control/src/config.rs +++ b/crates/tw-control/src/config.rs @@ -285,7 +285,7 @@ pub fn spawn_watcher( /// 是「显示哪个表单」,而不是精确到字段。 pub async fn path_at( axum::extract::State(s): axum::extract::State, - axum::extract::Query(q): axum::extract::Query, + axum::extract::Query(q): axum::extract::Query, ) -> Result, crate::Fail> { let cur = s.cfg.current().map_err(crate::unreadable_config)?; let path = tw_yaml::path_at(&cur.text, q.offset.min(cur.text.len())); @@ -309,11 +309,6 @@ pub async fn path_at( Ok(axum::Json(out)) } -#[derive(serde::Deserialize)] -pub struct AtQuery { - pub offset: usize, -} - /// 把 `/providers/relay-cn/base_url` 这样的路径解析成 `tw-yaml` 的步骤。 /// /// **用名字而不是下标。**下标会在用户重排上游之后指向另一个东西,而那 diff --git a/crates/tw-control/src/contract.rs b/crates/tw-control/src/contract.rs new file mode 100644 index 00000000..c4bec8da --- /dev/null +++ b/crates/tw-control/src/contract.rs @@ -0,0 +1,158 @@ +//! 按 tw-api 的端点描述挂处理函数,**并让编译器核对两边说的是同一件事**。 +//! +//! 路径和方法只在 [`tw_api::ep`] 里写一次。挂的时候([`RouterExt::at`])还要求: +//! +//! - 处理函数的最后一个参数是 `Json` / `Query`;没有请求的端点 +//! (`Req = ()`)最后一个参数是 `State` 或 `Path`,或者干脆没有参数; +//! - 它的返回值是 `E::Res` 的 JSON(或文本、事件流)。 +//! +//! 所以描述里的类型和处理函数对不上时,编不过 —— 而不是等客户端解析失败。 +//! +//! 另外,[`errors_are_messages`] 把框架替我们回的那些错误(请求体解析不了、 +//! 路径不存在、方法不对)也换成 [`tw_api::ErrorBody`],客户端碰到的每一个 +//! 非 2xx 都是同一个形状。 + +use std::future::Future; + +use axum::Json; +use axum::extract::{Path, Query, Request, State}; +use axum::handler::Handler; +use axum::http::{StatusCode, header}; +use axum::middleware::Next; +use axum::response::sse::Sse; +use axum::response::{IntoResponse, Response}; +use axum::routing::{MethodFilter, on}; +use tw_api::{Endpoint, Method}; +use tw_types::msg; + +use crate::{ControlState, Fail}; + +pub(crate) trait RouterExt { + /// 把 `h` 挂到端点 `E` 上:路径、方法都取自 `E`。 + fn at(self, e: E, h: H) -> Self + where + E: Endpoint, + H: Handler + Serves, + T: 'static; +} + +impl RouterExt for axum::Router { + fn at(self, _: E, h: H) -> Self + where + E: Endpoint, + H: Handler + Serves, + T: 'static, + { + self.route(E::PATH, on(filter(E::METHOD), h)) + } +} + +fn filter(m: Method) -> MethodFilter { + match m { + Method::Get => MethodFilter::GET, + Method::Post => MethodFilter::POST, + Method::Put => MethodFilter::PUT, + Method::Patch => MethodFilter::PATCH, + Method::Delete => MethodFilter::DELETE, + } +} + +/// 这个处理函数服务得了端点 `E`。`T` 和 axum 的 `Handler` 是同一个元组。 +pub(crate) trait Serves {} + +/// 处理函数的最后一个参数收的是 `E` 的请求。 +pub(crate) trait Takes {} + +impl Takes for Json {} +impl Takes for Query {} +impl, S> Takes for State {} +impl, P> Takes for Path

{} + +/// 处理函数的返回值是 `E` 的响应。 +pub(crate) trait Answer {} + +impl Answer for Json {} +impl Answer for Result, Fail> {} +impl Answer for (StatusCode, Json) {} +impl> Answer for String {} +impl> Answer for Result {} +impl, S> Answer for Sse {} + +macro_rules! serves { + ($($a:ident),*) => { + impl Serves for F + where + E: Endpoint, + F: FnOnce($($a,)* Last) -> Fut, + Fut: Future, + Fut::Output: Answer, + Last: Takes, + { + } + }; +} + +/// 一个参数都不收的:只能是没有请求的端点 +impl Serves for F +where + E: Endpoint, + F: FnOnce() -> Fut, + Fut: Future, + Fut::Output: Answer, +{ +} + +serves!(); +serves!(A1); +serves!(A1, A2); +serves!(A1, A2, A3); + +/// 框架自己回的错误也换成 [`tw_api::ErrorBody`]。 +/// +/// 处理函数的失败本来就是带码的 JSON([`crate::fail`])。剩下的是 axum 在走到 +/// 处理函数之前就回掉的:请求体不是合法 JSON、查询串对不上类型、路径不存在、 +/// 方法不对 —— 那些是纯文本或者空的,客户端只能看响应体是不是以 `{` 开头来猜。 +pub(crate) async fn errors_are_messages(req: Request, next: Next) -> Response { + let method = req.method().to_string(); + let path = req.uri().path().to_string(); + let res = next.run(req).await; + let status = res.status(); + if !(status.is_client_error() || status.is_server_error()) { + return res; + } + let json = res + .headers() + .get(header::CONTENT_TYPE) + .and_then(|v| v.to_str().ok()) + .is_some_and(|v| v.starts_with("application/json")); + if json { + return res; + } + let body = axum::body::to_bytes(res.into_body(), 64 * 1024) + .await + .map(|b| String::from_utf8_lossy(&b).trim().to_string()) + .unwrap_or_default(); + let m = match status { + StatusCode::METHOD_NOT_ALLOWED => msg!( + "control.method_not_allowed", method = method, path = path => + "The control plane does not accept {method} on {path}. The desktop app and the gateway may be different versions." + ), + _ => msg!( + "control.request_rejected", detail = body => + "The control plane could not read the request: {detail}" + ), + }; + (status, Json(m)).into_response() +} + +/// 没有这个端点。**不靠上面那层**:axum 的 `layer` 只包已经注册的路由, +/// 走到兜底的请求不经过它。 +pub(crate) async fn no_such_endpoint(method: axum::http::Method, uri: axum::http::Uri) -> Fail { + crate::fail( + StatusCode::NOT_FOUND, + msg!( + "control.no_such_endpoint", method = method, path = uri.path() => + "The control plane has no endpoint {method} {path}. The desktop app and the gateway may be different versions." + ), + ) +} diff --git a/crates/tw-control/src/keys.rs b/crates/tw-control/src/keys.rs index b627a57f..ad62f22b 100644 --- a/crates/tw-control/src/keys.rs +++ b/crates/tw-control/src/keys.rs @@ -20,7 +20,6 @@ use axum::Json; use axum::extract::{Path, Query, State}; use axum::http::StatusCode; -use axum::routing::{get, post, put}; use serde_yaml_ng::Value; use tw_adopt::{detect, plan}; use tw_config::edit; @@ -28,16 +27,20 @@ use tw_config::history::Origin; use tw_config::refs; use tw_yaml::Step; +use crate::contract::RouterExt; use crate::{ApplyError, ControlState, Fail, apply_fail, fail}; +use tw_api::ep; use tw_types::msg; pub fn router() -> axum::Router { axum::Router::new() - .route("/keys", get(list).post(create)) - .route("/keys/{name}", put(update).delete(delete_key)) - .route("/keys/{name}/value", get(value)) - .route("/keys/{name}/rotate", post(rotate)) - .route("/default_key", put(set_default)) + .at(ep::Keys, list) + .at(ep::CreateKey, create) + .at(ep::UpdateKey, update) + .at(ep::DeleteKey, delete_key) + .at(ep::KeyValue, value) + .at(ep::RotateKey, rotate) + .at(ep::SetDefaultKey, set_default) } /// 配置里密钥那一段。**没有 `edit::Section` 常量**:它在 `tw-config` 里 diff --git a/crates/tw-control/src/lib.rs b/crates/tw-control/src/lib.rs index 241176f8..b3385f93 100644 --- a/crates/tw-control/src/lib.rs +++ b/crates/tw-control/src/lib.rs @@ -13,15 +13,18 @@ use std::sync::Arc; use axum::extract::State; use axum::http::StatusCode; use axum::response::sse::{Event as SseEvent, KeepAlive, Sse}; -use axum::routing::{get, post}; use axum::{Json, Router}; use futures::stream::Stream; use tokio::sync::broadcast; +use tw_api::ep; use tw_types::{Msg, msg}; +use contract::RouterExt; + pub mod chatgpt; pub mod clients; pub mod config; +mod contract; pub mod diagnostics; pub mod dryrun; pub mod keys; @@ -112,65 +115,66 @@ impl ControlState { pub fn router(state: ControlState) -> Router { Router::new() - .route("/status", get(status)) - .route("/shutdown", post(ask_shutdown)) - .route("/interfaces", get(interfaces)) + .at(ep::Status, status) + .at(ep::Shutdown, ask_shutdown) + .at(ep::Interfaces, interfaces) .merge(keys::router()) .merge(listen::router()) - .route("/events", get(events)) - .route("/in-flight", get(in_flight)) - .route("/overview", get(overview)) - .route("/l1", post(l1)) - .route( - "/config", - get(get_config).patch(patch_config).put(put_config), - ) - .route("/config/history", get(config_history)) - .route("/config/at", get(config::path_at)) - .route("/config/rollback", post(config_rollback)) - .route("/summary", get(summary)) - .route("/summary/buckets", get(cost_buckets)) - .route("/summary/buckets/by", get(cost_buckets_by)) - .route("/summary/by", get(cost_by)) - .route("/history", get(history)) - .route("/latency", get(latency)) - .route("/latency/provider", get(latency_by_provider)) - .route("/storage", get(storage)) - .route("/quota", get(quota)) - .route("/speed/quote", post(speed_quote)) - .route("/speed/run", post(speed_run)) - .route("/request/{id}", get(request_detail)) - // 接管:**plan 和 adopt 是两个端点**,中间夹一次人的确认 + .at(ep::Events, events) + .at(ep::InFlight, in_flight) + .at(ep::Overview, overview) + .at(ep::L1, l1) + .at(ep::GetConfig, get_config) + .at(ep::PatchConfig, patch_config) + .at(ep::PutConfig, put_config) + .at(ep::ConfigHistory, config_history) + .at(ep::ConfigAt, config::path_at) + .at(ep::ConfigRollback, config_rollback) + .at(ep::Summary, summary) + .at(ep::CostBuckets, cost_buckets) + .at(ep::CostBucketsBy, cost_buckets_by) + .at(ep::CostBy, cost_by) + .at(ep::History, history) + .at(ep::Latency, latency) + .at(ep::LatencyByProvider, latency_by_provider) + .at(ep::Storage, storage) + .at(ep::Quota, quota) + .at(ep::SpeedQuote, speed_quote) + .at(ep::SpeedRun, speed_run) + .at(ep::RequestDetail, request_detail) // 诊断包(脱敏纪律)。**只读,不写任何文件** - .route("/diagnostics", get(diagnostics::bundle)) - // **报价和真跑是两个端点**:这一步花钱(和 L3 测速同一条纪律) + .at(ep::Diagnostics, diagnostics::bundle) // 把一条真实请求变成回放用例。**录制不是新功能** —— // 每个请求本来就在存储里 - .route("/request/{id}/fixture", get(replay::fixture)) - .route("/replay/quote", post(replay::quote)) - .route("/replay/run", post(replay::run)) - .route("/sessions", get(sessions)) - .route("/sessions/{id}", get(session_detail)) - .route("/dryrun", post(dryrun::dry_run)) + .at(ep::Fixture, replay::fixture) + // **报价和真跑是两个端点**:这一步花钱(和 L3 测速同一条纪律) + .at(ep::ReplayQuote, replay::quote) + .at(ep::ReplayRun, replay::run) + .at(ep::Sessions, sessions) + .at(ep::SessionDetail, session_detail) + .at(ep::DryRun, dryrun::dry_run) // **每次现扫,什么都不存** - .route("/scan", get(scan::scan)) - .route("/clients", get(clients::list)) - .route("/clients/plan", post(clients::plan_adopt)) - .route("/clients/adopt", post(clients::adopt)) - .route("/clients/{id}/restore/plan", get(clients::plan_restore)) - .route("/clients/{id}/restore", post(clients::restore)) - .route("/clients/{id}/why", get(clients::why)) - .route("/clients/{id}/key", post(clients::client_key)) + .at(ep::Scan, scan::scan) + // 接管:**plan 和 adopt 是两个端点**,中间夹一次人的确认 + .at(ep::Clients, clients::list) + .at(ep::PlanAdopt, clients::plan_adopt) + .at(ep::Adopt, clients::adopt) + .at(ep::PlanRestore, clients::plan_restore) + .at(ep::Restore, clients::restore) + .at(ep::Why, clients::why) + .at(ep::ClientKey, clients::client_key) // 矩阵上点一下。**plan 和 apply 同样是两步** - .route("/mcp/targets", get(clients::mcp_targets)) - .route("/mcp/plan", post(clients::mcp_plan_op)) - .route("/mcp/apply", post(clients::mcp_apply)) + .at(ep::McpTargets, clients::mcp_targets) + .at(ep::McpPlan, clients::mcp_plan_op) + .at(ep::McpApply, clients::mcp_apply) .merge(resources::router()) .merge(routes::router()) .merge(security::router()) .merge(pricing::router()) .merge(chatgpt::router()) .merge(zai::router()) + .fallback(contract::no_such_endpoint) + .layer(axum::middleware::from_fn(contract::errors_are_messages)) .with_state(state) } @@ -649,9 +653,9 @@ fn l1_stage(s: tw_gateway::Stage) -> tw_api::L1Stage { /// 请求会让我们凭空造出几万个零。 async fn cost_buckets( State(s): State, - axum::extract::Query(q): axum::extract::Query, + axum::extract::Query(q): axum::extract::Query, ) -> Result>, Fail> { - let (from, to) = q.range(); + let (from, to) = range(q.from_ms, q.to_ms); // 桶宽有下限,否则一个 `bucket_ms=1` 能让这条查询扫出几百万个分组。 let bucket = q.bucket_ms.unwrap_or(3_600_000).max(1_000); let store = need_store(&s)?; @@ -663,13 +667,9 @@ async fn cost_buckets( /// 按模型或上游分组的花费(钱花在哪儿)。 async fn cost_buckets_by( State(s): State, - axum::extract::Query(q): axum::extract::Query, + axum::extract::Query(q): axum::extract::Query, ) -> Result>, Fail> { - let (from, to) = Window { - from_ms: q.from_ms, - to_ms: q.to_ms, - } - .range(); + let (from, to) = range(q.from_ms, q.to_ms); // 桶宽有下限,和 `/summary/buckets` 同一条理由:`bucket_ms=1` 能让 // 这条查询扫出几百万个分组,而这一条还要再乘上模型个数。 let bucket = q.bucket_ms.unwrap_or(3_600_000).max(1_000); @@ -684,9 +684,9 @@ async fn cost_buckets_by( async fn cost_by( State(s): State, - axum::extract::Query(q): axum::extract::Query, + axum::extract::Query(q): axum::extract::Query, ) -> Result>, Fail> { - let (from, to) = q.range(); + let (from, to) = range(q.from_ms, q.to_ms); let store = need_store(&s)?; let g = store.lock().await; let x = g.db().cost_by(q.dim, from, to).map_err(records)?; @@ -696,9 +696,9 @@ async fn cost_by( /// 一段时间的汇总。不给参数就是「今天」。 async fn summary( State(s): State, - axum::extract::Query(q): axum::extract::Query, + axum::extract::Query(q): axum::extract::Query, ) -> Result, Fail> { - let (from, to) = q.range(); + let (from, to) = range(q.from_ms, q.to_ms); let store = need_store(&s)?; let g = store.lock().await; let x = g.db().summary(from, to).map_err(records)?; @@ -724,11 +724,11 @@ async fn summary( /// 最近的请求。**实时列表走内存 ring buffer,这个是给「翻历史」的**。 async fn history( State(s): State, - axum::extract::Query(q): axum::extract::Query, + axum::extract::Query(q): axum::extract::Query, ) -> Result>, Fail> { let store = need_store(&s)?; let g = store.lock().await; - let rows = g.db().recent(q.within(), q.limit()).map_err(records)?; + let rows = g.db().recent(within(&q), list_limit(&q)).map_err(records)?; // 这一段里的安全记录一次取完,按请求号挂上去。**流量页的徽标靠它**: // 以前徽标只来自实时事件,关窗再开就没了 let mut security = match ( @@ -750,9 +750,9 @@ async fn history( async fn latency( State(s): State, - axum::extract::Query(q): axum::extract::Query, + axum::extract::Query(q): axum::extract::Query, ) -> Result>, Fail> { - let (from, to) = q.range(); + let (from, to) = range(q.from_ms, q.to_ms); let store = need_store(&s)?; let g = store.lock().await; let xs = g.db().latency_by_model(from, to).map_err(records)?; @@ -1004,9 +1004,9 @@ async fn quota(State(s): State) -> Json /// 和按模型分是两个问题:前者的下一步是换上游,后者是换模型。 async fn latency_by_provider( State(s): State, - axum::extract::Query(q): axum::extract::Query, + axum::extract::Query(q): axum::extract::Query, ) -> Result>, Fail> { - let (from, to) = q.range(); + let (from, to) = range(q.from_ms, q.to_ms); let store = need_store(&s)?; let g = store.lock().await; let xs = g.db().latency_by_provider(from, to).map_err(records)?; @@ -1104,76 +1104,13 @@ fn history_row( } } -/// 时间窗。**默认是「今天」而不是「最近 24 小时」** —— 用户问的是 -/// 「今天花了多少」,那是个从零点算起的问题。 -#[derive(Debug, serde::Deserialize)] -struct Window { - from_ms: Option, - to_ms: Option, -} - -/// **不能用 `#[serde(flatten)]` 摊平 `Window`。** -/// -/// flatten 会让 serde 走 `deserialize_any`,而 query string 里一切都是 -/// 字符串 —— 于是 `from_ms=123` 被当成字符串喂给 `i64`,整个请求 400: -/// `invalid type: string "123", expected i64`。 -/// -/// 表现很坏:不带参数时一切正常,只有在**同时带上时间窗**的时候才失败, -/// 而界面恰恰总是带着它调。单元测试看不见这件事 —— 它只在真的经过一次 -/// query string 解析时才发生。 -#[derive(serde::Deserialize)] -struct BucketQuery { - from_ms: Option, - to_ms: Option, - bucket_ms: Option, -} - -impl BucketQuery { - fn range(&self) -> (i64, i64) { - Window { - from_ms: self.from_ms, - to_ms: self.to_ms, - } - .range() - } -} - -#[derive(serde::Deserialize)] -struct BucketGroupQuery { - from_ms: Option, - to_ms: Option, - bucket_ms: Option, - /// 和 `GroupQuery` 同一条理由:是枚举不是字符串,它会变成列名。 - dim: tw_api::CostDim, -} - -#[derive(serde::Deserialize)] -struct GroupQuery { - from_ms: Option, - to_ms: Option, - /// **是枚举不是字符串。**它会决定 SQL 里的列名,用字符串就是一个 - /// 注入口;写错的值在这里被 serde 直接拒掉,而不是拼进查询。 - dim: tw_api::CostDim, -} - -impl GroupQuery { - fn range(&self) -> (i64, i64) { - Window { - from_ms: self.from_ms, - to_ms: self.to_ms, - } - .range() - } -} - -impl Window { - fn range(&self) -> (i64, i64) { - let now = now_ms(); - // 本地时区的零点。UTC 零点对一个桌面工具没有意义 —— 用户在 - // 东八区,UTC 零点是他的早上八点。 - let midnight = local_midnight_ms(now); - (self.from_ms.unwrap_or(midnight), self.to_ms.unwrap_or(now)) - } +/// 时间窗的两端。**缺省是「今天」**,理由见 [`tw_api::Window`]。 +fn range(from_ms: Option, to_ms: Option) -> (i64, i64) { + let now = now_ms(); + // 本地时区的零点。UTC 零点对一个桌面工具没有意义 —— 用户在 + // 东八区,UTC 零点是他的早上八点。 + let midnight = local_midnight_ms(now); + (from_ms.unwrap_or(midnight), to_ms.unwrap_or(now)) } fn local_midnight_ms(now_ms: i64) -> i64 { @@ -1189,34 +1126,16 @@ fn now_ms() -> i64 { .unwrap_or(0) } -/// 一张列表要的两样:看哪一段,最多几条。 -/// -/// **时间窗是可选的,而且缺省不是「今天」。**聚合类的端点缺省到今天是 -/// 对的(见 [`Window`]);列表类的不是 —— 「最近 N 条」本身就是一个 -/// 完整的回答,而缺省成今天的话,过了零点这张表会空掉,那时用户什么 -/// 都没做。 -/// -/// 两端各自可缺:只给 `from_ms` 就是「从那时起到现在」。 -/// -/// 字段摊平写、不用 `#[serde(flatten)]`,理由见 [`Window`] 上面那段。 -#[derive(Debug, serde::Deserialize)] -struct ListQuery { - from_ms: Option, - to_ms: Option, - limit: Option, -} - -impl ListQuery { - fn within(&self) -> Option<(i64, i64)> { - match (self.from_ms, self.to_ms) { - (None, None) => None, - (f, t) => Some((f.unwrap_or(i64::MIN), t.unwrap_or_else(now_ms))), - } +/// 列表的时间窗:**缺省是不限**,不是今天(见 [`tw_api::ListQuery`])。 +fn within(q: &tw_api::ListQuery) -> Option<(i64, i64)> { + match (q.from_ms, q.to_ms) { + (None, None) => None, + (f, t) => Some((f.unwrap_or(i64::MIN), t.unwrap_or_else(now_ms))), } +} - fn limit(&self) -> usize { - self.limit.unwrap_or(200).min(2000) - } +fn list_limit(q: &tw_api::ListQuery) -> usize { + q.limit.unwrap_or(200).min(2000) } /// 当前配置的原文。**文本模式直接显示它。** @@ -1426,7 +1345,7 @@ fn turn_view(t: &tw_store::db::TurnRow) -> tw_api::TurnView { /// 界面上少一块统计,而不是弹一个错。 async fn sessions( State(s): State, - axum::extract::Query(q): axum::extract::Query, + axum::extract::Query(q): axum::extract::Query, ) -> Json> { let Some(store) = &s.store else { return Json(Vec::new()); @@ -1434,7 +1353,7 @@ async fn sessions( let g = store.lock().await; Json( g.db() - .sessions(q.within(), q.limit()) + .sessions(within(&q), list_limit(&q)) .unwrap_or_default() .iter() .map(session_view) @@ -1504,7 +1423,7 @@ pub enum ControlError { }, /// 这个平台上没有 unix socket。 /// - /// `Endpoint::in_dir` 不会给出这一档,所以走到这里说明有人显式指定了它 + /// `Address::in_dir` 不会给出这一档,所以走到这里说明有人显式指定了它 /// —— 与其静默换一种传输,不如说清楚。 #[cfg(not(unix))] #[error("this platform has no unix sockets, so the control plane cannot listen on {path}")] @@ -1531,23 +1450,23 @@ pub fn socket_path_fits(path: &Path) -> Result<(), ControlError> { /// 起控制面。 /// -/// 两种传输,**挑哪一种不是调用方的事**:`Endpoint::in_dir` 按平台给出这台 -/// 机器上唯一可用的那一种(见 [`tw_api::control::Endpoint`])。这里只负责把 +/// 两种传输,**挑哪一种不是调用方的事**:`Address::in_dir` 按平台给出这台 +/// 机器上唯一可用的那一种(见 [`tw_api::control::Address`])。这里只负责把 /// 它听起来。 pub async fn serve( state: ControlState, - at: &tw_api::control::Endpoint, + at: &tw_api::control::Address, token: token::Token, ) -> Result<(), ControlError> { - use tw_api::control::Endpoint; + use tw_api::control::Address; // 门装在这儿,不装进 `router()` —— 理由见 `token::guard` let app = token::guard(router(state), token); match at { #[cfg(unix)] - Endpoint::Socket(path) => serve_socket(app, path).await, + Address::Socket(path) => serve_socket(app, path).await, #[cfg(not(unix))] - Endpoint::Socket(path) => Err(ControlError::NoUnixSockets { path: path.clone() }), - Endpoint::Loopback { port_file } => serve_loopback(app, port_file).await, + Address::Socket(path) => Err(ControlError::NoUnixSockets { path: path.clone() }), + Address::Loopback { port_file } => serve_loopback(app, port_file).await, } } @@ -1652,13 +1571,13 @@ where /// /// **不是等到 bind 的那一刻才发现。**那时网关已经在监听、客户端可能已经 /// 连上来了,而这条错误当时只会进日志。 -pub fn endpoint_usable(at: &tw_api::control::Endpoint) -> Result<(), ControlError> { - use tw_api::control::Endpoint; +pub fn endpoint_usable(at: &tw_api::control::Address) -> Result<(), ControlError> { + use tw_api::control::Address; match at { - Endpoint::Socket(p) => socket_path_fits(p), + Address::Socket(p) => socket_path_fits(p), // 回环那一档没有等价的前置条件:端口由系统挑,挑不出来时 bind 自己 // 会说,而那句话已经够清楚了。 - Endpoint::Loopback { .. } => Ok(()), + Address::Loopback { .. } => Ok(()), } } diff --git a/crates/tw-control/src/listen.rs b/crates/tw-control/src/listen.rs index 5ece7e01..2cbd02aa 100644 --- a/crates/tw-control/src/listen.rs +++ b/crates/tw-control/src/listen.rs @@ -11,17 +11,18 @@ use axum::Json; use axum::extract::State; use axum::http::StatusCode; -use axum::routing::put; use serde_yaml_ng::Value; use tw_config::edit; use tw_config::history::Origin; use tw_yaml::Step; +use crate::contract::RouterExt; use crate::{ControlState, Fail, apply_fail, fail}; +use tw_api::ep; use tw_types::msg; pub fn router() -> axum::Router { - axum::Router::new().route("/listen", put(save)) + axum::Router::new().at(ep::SaveListen, save) } async fn save( diff --git a/crates/tw-control/src/pricing.rs b/crates/tw-control/src/pricing.rs index 310a6d66..dfc0c0a9 100644 --- a/crates/tw-control/src/pricing.rs +++ b/crates/tw-control/src/pricing.rs @@ -19,28 +19,28 @@ use std::time::{Duration, SystemTime, UNIX_EPOCH}; use axum::Json; use axum::extract::{Path as UrlPath, Query, State}; use axum::http::StatusCode; -use axum::routing::{get, post, put}; use serde_yaml_ng::Value; use tw_config::edit; use tw_config::history::Origin; use tw_config::refs; use tw_yaml::Step; +use crate::contract::RouterExt; use crate::resources::{checked_name, invalid, mapping, quoted}; use crate::{ApplyError, ControlState, Fail, apply_fail, fail}; +use tw_api::ep; use tw_types::{Msg, msg}; pub fn router() -> axum::Router { axum::Router::new() - .route("/pricing", get(status)) - .route("/pricing/refresh", post(refresh_now)) - .route("/pricing/auto_update", put(set_auto_update)) - .route("/pricing/query", post(query)) - .route("/pricing/sheets", post(create_sheet)) - .route( - "/pricing/sheets/{name}", - get(sheet).put(update_sheet).delete(delete_sheet), - ) + .at(ep::Pricing, status) + .at(ep::RefreshPricing, refresh_now) + .at(ep::SetPricingAutoUpdate, set_auto_update) + .at(ep::QueryPrice, query) + .at(ep::CreatePriceSheet, create_sheet) + .at(ep::PriceSheet, sheet) + .at(ep::UpdatePriceSheet, update_sheet) + .at(ep::DeletePriceSheet, delete_sheet) } // ─────────────────────────────────────────────────────────── 默认价目表 diff --git a/crates/tw-control/src/resources.rs b/crates/tw-control/src/resources.rs index 95fd1569..6d9d40b0 100644 --- a/crates/tw-control/src/resources.rs +++ b/crates/tw-control/src/resources.rs @@ -17,30 +17,30 @@ use axum::Json; use axum::extract::{Path, Query, State}; use axum::http::StatusCode; -use axum::routing::{get, post, put}; use serde_yaml_ng::Value; use tw_config::edit::{self, EditError}; use tw_config::history::Origin; use tw_config::refs::{self, ProviderRef}; +use crate::contract::RouterExt; use crate::{ApplyError, ControlState, Fail, apply_fail, fail}; +use tw_api::ep; use tw_types::{Msg, msg}; pub fn router() -> axum::Router { axum::Router::new() - .route("/providers", post(create_provider)) - .route("/providers/test", post(test_provider)) - .route("/providers/preview", post(preview_provider)) - .route( - "/providers/{name}", - put(update_provider).delete(delete_provider), - ) - .route("/providers/{name}/models", get(provider_models)) - .route("/providers/{name}/models/refresh", post(refresh_models)) - .route("/models/refresh", post(refresh_stale_models)) - .route("/proxies", post(create_proxy)) - .route("/proxies/test", post(test_proxy)) - .route("/proxies/{name}", put(update_proxy).delete(delete_proxy)) + .at(ep::CreateProvider, create_provider) + .at(ep::TestProvider, test_provider) + .at(ep::PreviewProvider, preview_provider) + .at(ep::UpdateProvider, update_provider) + .at(ep::DeleteProvider, delete_provider) + .at(ep::ProviderModels, provider_models) + .at(ep::RefreshProviderModels, refresh_models) + .at(ep::RefreshStaleModels, refresh_stale_models) + .at(ep::CreateProxy, create_proxy) + .at(ep::TestProxy, test_proxy) + .at(ep::UpdateProxy, update_proxy) + .at(ep::DeleteProxy, delete_proxy) } // ─────────────────────────────────────────────────────────── 上游 diff --git a/crates/tw-control/src/routes.rs b/crates/tw-control/src/routes.rs index e6e0da03..d1349a12 100644 --- a/crates/tw-control/src/routes.rs +++ b/crates/tw-control/src/routes.rs @@ -16,7 +16,6 @@ use std::collections::HashSet; use axum::Json; use axum::extract::{Path, Query, State}; -use axum::routing::{get, post, put}; use serde_yaml_ng::Value; use tw_config::edit::{self, EditError}; use tw_config::history::Origin; @@ -26,17 +25,21 @@ use tw_engine::{Group, GroupType, RouteSet, Rule, SetAction}; use tw_types::{Msg, msg}; use tw_yaml::Step; +use crate::contract::RouterExt; use crate::resources::{checked_name, invalid, mapping}; use crate::{ApplyError, ControlState, Fail, apply_fail}; +use tw_api::ep; pub fn router() -> axum::Router { axum::Router::new() - .route("/routes", post(create_route)) - .route("/routes/{name}", put(update_route).delete(delete_route)) - .route("/default_route", put(set_default_route)) - .route("/groups", post(create_group)) - .route("/groups/{name}", put(update_group).delete(delete_group)) - .route("/models", get(known_models)) + .at(ep::CreateRoute, create_route) + .at(ep::UpdateRoute, update_route) + .at(ep::DeleteRoute, delete_route) + .at(ep::SetDefaultRoute, set_default_route) + .at(ep::CreateGroup, create_group) + .at(ep::UpdateGroup, update_group) + .at(ep::DeleteGroup, delete_group) + .at(ep::KnownModels, known_models) } // ─────────────────────────────────────────────────────────── 路由 diff --git a/crates/tw-control/src/scan.rs b/crates/tw-control/src/scan.rs index 1dd99684..2ebe472c 100644 --- a/crates/tw-control/src/scan.rs +++ b/crates/tw-control/src/scan.rs @@ -9,11 +9,7 @@ use std::sync::Arc; -use axum::{ - Json, - extract::{Query, State}, -}; -use serde::Deserialize; +use axum::{Json, extract::State}; use crate::ControlState; @@ -39,24 +35,16 @@ pub fn finding_view(f: &tw_scan::report::Finding) -> tw_api::ScanFinding { } } -#[derive(Debug, Deserialize)] -pub struct Params { - /// 额外扫哪些项目目录。**我们不去找项目,只看用户指的**( - /// 范围约定) - #[serde(default)] - pub project: Vec, -} - pub async fn scan( State(s): State, - Query(p): Query, + Json(p): Json, ) -> Json { // **只用内置规则。**安全页上的规则只作用于经过网关的请求:在那边停用 // 一条误报,不该让这边悄悄少查一样东西 let rules = tw_guard::tools::rules::scan_rules(); let mut sources = tw_scan::sources::user_level(&s.home); - for proj in &p.project { + for proj in &p.projects { sources.extend(tw_scan::sources::in_project(std::path::Path::new(proj))); } let scanned = sources.len(); @@ -102,7 +90,7 @@ pub async fn scan( .collect(), unreadable: r.unreadable, scanned, - projects: p.project, + projects: p.projects, }) } diff --git a/crates/tw-control/src/security.rs b/crates/tw-control/src/security.rs index 9b27d128..54fbab6b 100644 --- a/crates/tw-control/src/security.rs +++ b/crates/tw-control/src/security.rs @@ -17,7 +17,6 @@ use axum::Json; use axum::extract::{Path, Query, State}; use axum::http::StatusCode; -use axum::routing::{get, post, put}; use serde_yaml_ng::{Mapping, Value}; use tw_config::edit; use tw_config::history::Origin; @@ -25,24 +24,21 @@ use tw_config::{SecurityMode, ToolAction}; use tw_types::msg; use tw_yaml::Step; +use crate::contract::RouterExt; use crate::{ApplyError, ControlState, Fail, apply_fail, fail}; +use tw_api::ep; pub fn router() -> axum::Router { axum::Router::new() - .route("/security", get(detail)) - .route("/security/events", get(events)) - .route("/security/{guard}/mode", put(set_mode)) - .route("/security/{guard}/builtin/{id}", put(toggle_builtin)) - .route( - "/security/{guard}/builtin/{id}/action", - put(set_builtin_action), - ) - .route("/security/{guard}/custom", post(create_custom)) - .route( - "/security/{guard}/custom/{name}", - put(update_custom).delete(delete_custom), - ) - .route("/security/{guard}/test", post(test)) + .at(ep::Security, detail) + .at(ep::SecurityEvents, events) + .at(ep::SetSecurityMode, set_mode) + .at(ep::ToggleBuiltinRule, toggle_builtin) + .at(ep::SetBuiltinRuleAction, set_builtin_action) + .at(ep::CreateCustomRule, create_custom) + .at(ep::UpdateCustomRule, update_custom) + .at(ep::DeleteCustomRule, delete_custom) + .at(ep::TestSecurity, test) } /// 哪一项防护。路径里写的就是配置里的那个键。 @@ -225,23 +221,12 @@ fn tools_view(p: &tw_config::ToolPolicy) -> tw_api::GuardDetail { } } -/// 日志一页要的:哪一项、哪一段、从哪条往前、几条。 -#[derive(Debug, serde::Deserialize)] -struct EventsQuery { - guard: Option, - from_ms: Option, - to_ms: Option, - /// 只要这条之前的(翻页) - before: Option, - limit: Option, -} - /// 一页最多多少条。 const PAGE_MAX: usize = 500; async fn events( State(s): State, - Query(q): Query, + Query(q): Query, ) -> Result, Fail> { let guard = match q.guard.as_deref() { None | Some("") => None, @@ -471,15 +456,10 @@ async fn update_custom( Ok(Json(tw_api::ConfigWritten { version })) } -#[derive(Debug, serde::Deserialize)] -struct DeleteQuery { - base_version: Option, -} - async fn delete_custom( State(s): State, Path((guard, name)): Path<(String, String)>, - Query(q): Query, + Query(q): Query, ) -> Result, Fail> { let guard = Guard::parse(&guard)?; let version = s diff --git a/crates/tw-control/src/zai.rs b/crates/tw-control/src/zai.rs index 827557f2..7433d6d3 100644 --- a/crates/tw-control/src/zai.rs +++ b/crates/tw-control/src/zai.rs @@ -32,12 +32,13 @@ use std::time::Duration; use axum::Json; use axum::extract::{Path, State}; use axum::http::StatusCode; -use axum::routing::{get, post}; use serde_json::{Value, json}; use tw_config::Protocol; use tw_config::history::Origin; +use crate::contract::RouterExt; use crate::{ControlState, Fail, fail}; +use tw_api::ep; use tw_types::{Msg, msg}; /// 登录要在多久之内完成。平台给的期限更短就按它的 @@ -59,8 +60,9 @@ const DEFAULT_PROJECT: &str = "默认项目"; pub fn router() -> axum::Router { axum::Router::new() - .route("/zai/login", post(start)) - .route("/zai/login/{id}", get(status).delete(cancel)) + .at(ep::StartZaiLogin, start) + .at(ep::ZaiLoginStatus, status) + .at(ep::CancelZaiLogin, cancel) } // ---------------------------------------------------------------- 哪一家 diff --git a/crates/tw-control/tests/contract.rs b/crates/tw-control/tests/contract.rs new file mode 100644 index 00000000..c0f4934d --- /dev/null +++ b/crates/tw-control/tests/contract.rs @@ -0,0 +1,209 @@ +//! tw-api 的端点表和真正挂上去的路由是一回事,失败一律是 [`tw_api::ErrorBody`]。 +//! +//! 类型对不对在编译时就核过了(`contract.rs` 里的 `Serves`)。这里核的是编译器 +//! 看不见的两件:**表里的每个端点都真的挂上了**,以及**每一种失败都能按 +//! `ErrorBody` 解析** —— 包括 axum 在走到处理函数之前就回掉的那些。 + +use std::sync::Arc; + +use axum::body::Body; +use axum::http::{Request, StatusCode}; +use tower::ServiceExt; +use tw_api::{Endpoint, ErrorBody, Method, ep}; +use tw_control::{ConfigManager, ControlState}; + +const BASE: &str = "version: 1\nclients:\n - name: me\n key: tw-contract-test-key\nproviders:\n - name: official\n base_url: https://api.anthropic.com\n key: sk-x\n"; + +fn app() -> (tempfile::TempDir, axum::Router) { + let d = tempfile::tempdir().unwrap(); + let p = d.path().join("config.yaml"); + std::fs::write(&p, BASE).unwrap(); + let cfg: tw_config::Config = serde_yaml_ng::from_str(BASE).unwrap(); + let gw = tw_gateway::AppState::new(cfg).unwrap(); + let bus = gw.bus.clone(); + let state = ControlState { + shutdown: Default::default(), + cfg: Arc::new(ConfigManager::new(p, gw.clone(), bus)), + gateway: gw, + store: None, + started: std::time::Instant::now(), + price_updater: Default::default(), + chatgpt: Default::default(), + zai: Default::default(), + // **测试里绝不能碰开发者自己的配置** + home: d.path().join("home"), + }; + (d, tw_control::router(state)) +} + +async fn send( + app: &axum::Router, + method: &str, + uri: &str, + body: Option<&str>, +) -> (StatusCode, Option) { + let mut req = Request::builder().method(method).uri(uri); + if body.is_some() { + req = req.header("content-type", "application/json"); + } + let r = app + .clone() + .oneshot( + req.body(Body::from(body.unwrap_or("").to_string())) + .unwrap(), + ) + .await + .unwrap(); + let st = r.status(); + // 事件流不会自己结束,不读它的响应体 + if st.is_success() { + return (st, None); + } + let b = axum::body::to_bytes(r.into_body(), 1 << 20).await.unwrap(); + (st, Some(String::from_utf8_lossy(&b).to_string())) +} + +fn error(body: &str) -> ErrorBody { + serde_json::from_str(body).unwrap_or_else(|e| panic!("not an ErrorBody ({e}): {body}")) +} + +/// 表里的每个端点都挂上了,方法也对。 +/// +/// **不让处理函数真的跑起来**(有的会去联网、有的会让进程退出): +/// +/// - 带请求体的端点发一个不是 JSON 的请求体。挂上了的话,axum 在走到处理函数 +/// 之前就拒掉它(400);没挂上是 404 或 405。顺带核了「请求走请求体」这一条。 +/// - 没有请求体的 POST 换一个它不收的方法去问:路径在,就是 405;不在是 404。 +/// 这几个端点的路径上只有它自己,所以 405 就说明它挂上了。 +/// - GET 和 DELETE 真的发 —— 它们只读,或者删一个不存在的名字。 +#[tokio::test] +async fn every_endpoint_in_the_table_is_served() { + let (_d, app) = app(); + for e in ep::ALL { + let path = tw_api::fill( + e.path, + &e.params.iter().map(|p| (*p, "1")).collect::>(), + ); + let what = format!("{} {} ({})", e.method.as_str(), e.path, e.name); + match e.method { + Method::Post | Method::Put | Method::Patch if e.has_req() => { + let (st, body) = send(&app, e.method.as_str(), &path, Some("not json")).await; + assert_eq!(st, StatusCode::BAD_REQUEST, "{what}: {body:?}"); + assert_eq!( + error(&body.unwrap()).code, + "control.request_rejected", + "{what}" + ); + } + Method::Post | Method::Put | Method::Patch => { + let (st, body) = send(&app, "TRACE", &path, None).await; + assert_eq!(st, StatusCode::METHOD_NOT_ALLOWED, "{what}: {body:?}"); + assert_eq!( + error(&body.unwrap()).code, + "control.method_not_allowed", + "{what}" + ); + } + Method::Get | Method::Delete => { + let (st, body) = send(&app, e.method.as_str(), &path, None).await; + assert_ne!(st, StatusCode::METHOD_NOT_ALLOWED, "{what}"); + if let Some(body) = body { + assert_ne!(error(&body).code, "control.no_such_endpoint", "{what}"); + } + } + } + } +} + +/// 框架替我们回的失败也是 `ErrorBody`,带着各自的码。 +#[tokio::test] +async fn failures_the_framework_answers_are_messages_too() { + let (_d, app) = app(); + + let (st, body) = send(&app, "GET", "/no/such/thing", None).await; + assert_eq!(st, StatusCode::NOT_FOUND); + let m = error(&body.unwrap()); + assert_eq!(m.code, "control.no_such_endpoint"); + assert_eq!(m.arg("path"), "/no/such/thing"); + + let (st, body) = send(&app, "DELETE", ep::Status::PATH, None).await; + assert_eq!(st, StatusCode::METHOD_NOT_ALLOWED); + assert_eq!(error(&body.unwrap()).code, "control.method_not_allowed"); + + // 请求体读不成请求类型 + let (st, body) = send( + &app, + "POST", + ep::ConfigRollback::PATH, + Some("{\"version\":5}"), + ) + .await; + assert!(st.is_client_error(), "{st}"); + let m = error(&body.unwrap()); + assert_eq!(m.code, "control.request_rejected"); + assert!(!m.arg("detail").is_empty(), "{m:?}"); + + // 路径参数读不成数字 + let (st, body) = send(&app, "GET", &ep::RequestDetail::path("abc"), None).await; + assert_eq!(st, StatusCode::BAD_REQUEST); + assert_eq!(error(&body.unwrap()).code, "control.request_rejected"); + + // 处理函数自己的失败照旧是它自己的码 + let (st, body) = send(&app, "GET", &ep::ProviderModels::path("nobody"), None).await; + assert_eq!(st, StatusCode::NOT_FOUND); + assert_eq!(error(&body.unwrap()).code, "control.upstream_not_found"); +} + +/// 客户端按 tw-api 的类型拼查询串,core 按同一个类型读回来。 +#[tokio::test] +async fn query_strings_built_from_the_contract_types_are_accepted() { + let (_d, app) = app(); + let q = tw_api::GroupQuery { + from_ms: Some(1), + to_ms: Some(2), + dim: tw_api::CostDim::Model, + }; + let uri = format!( + "{}?{}", + ep::CostBy::PATH, + serde_urlencoded::to_string(&q).unwrap() + ); + let (st, body) = send(&app, "GET", &uri, None).await; + // 没有请求库,处理函数说的是「记录读不了」,不是查询串读不懂 + let code = body.map(|b| error(&b).code); + assert_ne!(code.as_deref(), Some("control.request_rejected"), "{st}"); +} + +/// 扫描可以带好几个项目目录。 +#[tokio::test] +async fn scan_takes_more_than_one_project() { + let (d, app) = app(); + let dirs: Vec = ["a", "b"] + .iter() + .map(|n| { + let p = d.path().join(n); + std::fs::create_dir_all(&p).unwrap(); + p.display().to_string() + }) + .collect(); + let body = serde_json::to_string(&tw_api::ScanRequest { + projects: dirs.clone(), + }) + .unwrap(); + let r = app + .clone() + .oneshot( + Request::builder() + .method(ep::Scan::METHOD.as_str()) + .uri(ep::Scan::PATH) + .header("content-type", "application/json") + .body(Body::from(body)) + .unwrap(), + ) + .await + .unwrap(); + assert_eq!(r.status(), StatusCode::OK); + let b = axum::body::to_bytes(r.into_body(), 1 << 20).await.unwrap(); + let got: tw_api::ScanResponse = serde_json::from_slice(&b).unwrap(); + assert_eq!(got.projects, dirs); +} diff --git a/crates/tw-control/tests/m4_acceptance.rs b/crates/tw-control/tests/m4_acceptance.rs index dc2d8e9c..acd86b2f 100644 --- a/crates/tw-control/tests/m4_acceptance.rs +++ b/crates/tw-control/tests/m4_acceptance.rs @@ -168,7 +168,7 @@ async fn two_a_zero_width_character_in_a_skill_is_found_and_located_to_a_line() ) .unwrap(); - let body = get(&b.app, "/scan").await; + let (_, body) = post(&b.app, "/scan", "{}").await; let v: serde_json::Value = serde_json::from_str(&body).unwrap(); let found = v["findings"] .as_array() @@ -192,7 +192,7 @@ async fn three_scanning_never_touches_a_single_byte() { std::fs::write(&skill, text).unwrap(); let before = std::fs::metadata(&skill).unwrap().len(); - let body = get(&b.app, "/scan").await; + let (_, body) = post(&b.app, "/scan", "{}").await; assert!(body.contains("SKILL.md"), "什么都没扫出来:{body}"); assert_eq!( diff --git a/crates/tw-types/Cargo.toml b/crates/tw-types/Cargo.toml index c2287d44..5af0619a 100644 --- a/crates/tw-types/Cargo.toml +++ b/crates/tw-types/Cargo.toml @@ -9,6 +9,11 @@ description = "A message for people: a stable code, its arguments, and the Engli [dependencies] serde = { workspace = true } +# 给桌面端导出 TypeScript 类型用(`Msg`)。**默认关**:企业版不背它 +ts-rs = { workspace = true, optional = true } + +[features] +ts = ["dep:ts-rs"] [dev-dependencies] serde_json = { workspace = true } diff --git a/crates/tw-types/src/lib.rs b/crates/tw-types/src/lib.rs index 9489257b..592fbcff 100644 --- a/crates/tw-types/src/lib.rs +++ b/crates/tw-types/src/lib.rs @@ -24,6 +24,7 @@ use serde::{Deserialize, Serialize}; /// 码的写法是点分小写,从粗到细:`l1.dns.timeout`、`l1.proxy.auth_rejected`。 /// 第一段是发出它的那一层。 #[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)] +#[cfg_attr(feature = "ts", derive(ts_rs::TS))] pub struct Msg { pub code: String, /// 填进句子里的参数,按名字取。**值已经写成字符串** —— 界面只是 diff --git a/scripts/smoke.sh b/scripts/smoke.sh index 463ea80d..e1aa47fc 100755 --- a/scripts/smoke.sh +++ b/scripts/smoke.sh @@ -319,13 +319,14 @@ for ep in "/summary?from_ms=$DAY" "/summary/buckets?from_ms=$DAY&bucket_ms=36000 done for ep in /status /overview /summary /history /latency /latency/provider /storage /quota /security \ - /security/events /clients /scan /sessions /mcp/targets /diagnostics /config /config/history /models; do + /security/events /clients /sessions /mcp/targets /diagnostics /config /config/history /models; do C=$(get "$ep") [ "$C" = "200" ] && ok "GET $ep" || bad "GET $ep 返回 $C" done # 试算要说清按哪条路由算:不指定密钥或路由时是 400,不再悄悄取第一把密钥 C=$(post /dryrun '{"model":"claude-sonnet-4-5","route":"默认"}'); [ "$C" = "200" ] && ok "POST /dryrun" || bad "POST /dryrun 返回 $C" +C=$(post /scan '{"projects":["'"$TMP"'"]}'); [ "$C" = "200" ] && ok "POST /scan(带项目目录)" || bad "POST /scan 返回 $C" C=$(post /clients/plan '{"client":"claude-code"}'); [ "$C" = "200" ] && ok "POST /clients/plan" || bad "POST /clients/plan 返回 $C" # 页面打开时补问模型清单:立刻返回开始问的那几家,不等上游回话 C=$(post /models/refresh '{}'); [ "$C" = "200" ] && ok "POST /models/refresh" || bad "POST /models/refresh 返回 $C"