From a56e2a1e336378aaab43b1cddf848783f31ead19 Mon Sep 17 00:00:00 2001 From: fylorn <249551762+fylorn@users.noreply.github.com> Date: Thu, 17 Sep 2026 12:54:10 +0800 Subject: [PATCH 1/2] feat(models): what each upstream serves, and routing that respects it Two failures shared one cause: the model catalog knew which models existed, but not reliably which upstream served them. - A config reload rebuilt the catalog from the hand-written `models` lists alone. Every model discovered from an upstream's /v1/models vanished, so requests for them were refused, until the daily refresh. A newly added upstream also waited up to a day to be asked for its models. - Routing ignored the catalog. When a group put an upstream first that did not offer the requested model, that upstream answered 404, which does not trigger failover, and the request failed with an upstream that could serve it right beside. The gateway now keeps a model directory beside the catalog: - Each upstream's last answer is kept across reloads: listed, no list (and why), or failed (and why), with the time it was checked. An answer stays valid while the address, credential account, protocol and proxy stay the same. - The catalog is derived from the directory and the current config on every change, so disabling an upstream or narrowing its scope applies at once. New and changed upstreams are asked straight away in the background. Everything else is re-asked daily, and a failure retries after an hour. Checks compare wall-clock time, so a laptop that slept still refreshes. - Candidates are filtered before a group orders them. Disabled upstreams, models outside `models_only`, and models missing from a known list are skipped. An upstream without a list is kept, since not knowing is not the same as not offering. When nothing is left, the error names each upstream and why. The dry run reports the same skips, with an `unavailable` outcome. - Admission says "no upstream offers this model" when that is the reason, rather than blaming the client's allow list. Config: - `disabled` keeps an upstream's settings but takes it out of routing and out of /v1/models. - `models_only` limits which of an upstream's models are used, by ID or glob. An empty list is refused in favour of `disabled`. - `billing: free` records an exact $0, and sorts first for `cheapest`. Control plane: - `GET /providers/{name}/models` lists an upstream's models with source, check time, error, scope, context window and price. `POST /providers/{name}/models/refresh` asks the upstream now. - `ProviderView` reports `model_source`, `model_count`, `models_only` and `disabled`. `ProviderInput` accepts the last two. - Speed-test and replay quotes share one quote per billing mode, and carry `billing` in place of `subscription`. A quote for an upstream with unknown billing no longer reads as a per-token price. - The diagnostics bundle shows each upstream's state and model list. Co-Authored-By: Claude Opus 5 --- README.zh-CN.md | 3 +- bin/twcore/src/main.rs | 2 +- crates/tw-api/src/lib.rs | 80 +++- crates/tw-config/src/lib.rs | 72 ++-- crates/tw-config/src/validate.rs | 29 ++ crates/tw-control/src/diagnostics.rs | 30 +- crates/tw-control/src/dryrun.rs | 38 +- crates/tw-control/src/lib.rs | 21 +- crates/tw-control/src/pricing.rs | 2 +- crates/tw-control/src/replay.rs | 39 +- crates/tw-control/src/resources.rs | 73 +++- crates/tw-control/tests/models.rs | 280 +++++++++++++ crates/tw-control/tests/speed.rs | 2 +- crates/tw-engine/src/catalog.rs | 42 ++ crates/tw-gateway/src/l3.rs | 153 +------ crates/tw-gateway/src/lib.rs | 8 +- crates/tw-gateway/src/models.rs | 573 +++++++++++++++++++++++++++ crates/tw-gateway/src/quote.rs | 136 +++++++ crates/tw-gateway/src/server.rs | 197 ++++----- crates/tw-gateway/tests/models.rs | 291 ++++++++++++++ crates/tw-store/src/recorder.rs | 24 +- 21 files changed, 1741 insertions(+), 354 deletions(-) create mode 100644 crates/tw-control/tests/models.rs create mode 100644 crates/tw-gateway/src/models.rs create mode 100644 crates/tw-gateway/src/quote.rs create mode 100644 crates/tw-gateway/tests/models.rs diff --git a/README.zh-CN.md b/README.zh-CN.md index d19a4718..0067305c 100644 --- a/README.zh-CN.md +++ b/README.zh-CN.md @@ -28,7 +28,8 @@ cargo run -p twcore -- serve # 起网关和控制面 有没有工具调用;动作是换上游、改参数、或者直接拒绝。 - **流式故障转移** —— 首字节之前可以透明换一家;首字节之后唯一诚实的 做法是如实报告发生了什么。 -- **看得见成本** —— token 用量、缓存命中、按内置价目表快照计价。 +- **看得见成本** —— token 用量、缓存命中,按每天刷新的公开价目表计价; + 价格不同的上游可以选用自定义价目表。 **算不出价钱的明确标「未知」,而不是编一个数字。** - **出站脱敏** —— 发给中转站之前,把请求里的密钥换成占位符;模型回显时 再换回来。 diff --git a/bin/twcore/src/main.rs b/bin/twcore/src/main.rs index 329a6f1f..d00202a2 100644 --- a/bin/twcore/src/main.rs +++ b/bin/twcore/src/main.rs @@ -766,7 +766,7 @@ fn cmd_serve(path: &Path, port: Option, safe: bool, parent: Option) -> // 模型目录:后台去问每个上游有哪些模型。**不挡启动** —— // 探测要打网络,而网关不该因为一次探测慢而起不来。 - tw_gateway::spawn_catalog_refresh(state.clone()); + tw_gateway::models::spawn(state.clone()); tracing::info!(%addr, "启动"); tokio::select! { diff --git a/crates/tw-api/src/lib.rs b/crates/tw-api/src/lib.rs index 2175a416..ffb2499d 100644 --- a/crates/tw-api/src/lib.rs +++ b/crates/tw-api/src/lib.rs @@ -563,9 +563,20 @@ pub struct ProviderView { pub on_proxy_fail: String, /// 服务不提供模型列表时用的手动清单 pub models: Vec, + /// 启用范围:只用这些模型(ID 或 glob)。空 = 它提供的全部 + #[serde(default, skip_serializing_if = "Option::is_none")] + pub models_only: Option>, + /// 模型清单从哪儿来:`discovered`(上游列出的)/ `manual`(手动清单)/ + /// `none`(不知道它有什么) + pub model_source: String, + /// 现在能服务的模型数,已按启用范围过滤。停用时是 0 + pub model_count: usize, + /// 停用:不参与路由,模型不出现在 `/v1/models` 里 + pub disabled: bool, /// closed / open pub health: String, - /// 配置里写明的计费方式。空 = 自动识别 + /// 配置里写明的计费方式:`per-token` / `subscription` / `free` / `unknown`。 + /// 空 = 自动识别 #[serde(default)] pub billing: Option, /// 判完的信任级别:`official` / `untrusted` @@ -1046,7 +1057,10 @@ pub struct ProviderInput { /// 服务不提供模型列表时的手动清单 #[serde(default, skip_serializing_if = "Vec::is_empty")] pub models: Vec, - /// `per-token` / `subscription` / `unknown`。不给就自动识别 + /// 启用范围:只用这些模型(ID 或 glob)。不给就是它提供的全部 + #[serde(default, skip_serializing_if = "Option::is_none")] + pub models_only: Option>, + /// `per-token` / `subscription` / `free` / `unknown`。不给就自动识别 #[serde(default, skip_serializing_if = "Option::is_none")] pub billing: Option, /// `official` / `untrusted`。不给就按地址识别 @@ -1058,6 +1072,42 @@ pub struct ProviderInput { /// 按哪张价目表计价。不给就是默认价目表 #[serde(default, skip_serializing_if = "Option::is_none")] pub pricing: Option, + /// 停用 + #[serde(default)] + pub disabled: bool, +} + +/// 一个上游的模型清单。 +#[derive(Debug, Clone, Serialize, Deserialize)] +pub struct ProviderModelsView { + pub provider: String, + /// `discovered`(上游列出的)/ `manual`(手动清单)/ `none` + pub source: String, + /// 最近一次向上游获取清单的时间。还没获取过是空 + #[serde(default, skip_serializing_if = "Option::is_none")] + pub checked_at_ms: Option, + /// 没从上游拿到清单的原因 + #[serde(default, skip_serializing_if = "Option::is_none")] + pub error: Option, + pub models: Vec, +} + +/// 清单里的一个模型。 +#[derive(Debug, Clone, Serialize, Deserialize)] +pub struct ModelRow { + pub id: String, + /// 在启用范围里 + pub enabled: bool, + /// 上下文窗口,来自默认价目表 + #[serde(default, skip_serializing_if = "Option::is_none")] + pub context_window: Option, + /// 按这个上游选的价目表查到的价格。空 = 无法计价 + #[serde(default, skip_serializing_if = "Option::is_none")] + pub price: Option, + #[serde(default, skip_serializing_if = "Option::is_none")] + pub price_source: Option, + /// 价格是从别的平台借来的。**按它算出来的钱是估算** + pub estimated: bool, } fn direct() -> String { @@ -1397,12 +1447,13 @@ pub struct SpeedEstimate { /// 输入 token。**精确值** —— 请求是固定的 pub input_tokens: u64, pub max_output_tokens: u64, + /// 微分。按量计费算得出来时是那个数,不计费时是 0。订阅制、计费方式 + /// 未知、无法计价时是空 #[serde(default, skip_serializing_if = "Option::is_none")] pub cost_micros: Option, - /// 订阅制上游:不按 token 收钱,消耗的是额度。它没有金额,但**不让 - /// 合计变成空** —— 空只留给「按量计费却算不出来」 - #[serde(default)] - pub subscription: bool, + /// 这家的计费方式:`per-token` / `subscription` / `free` / `unknown`。 + /// **订阅制那几项没有金额,但不让合计变成空** + pub billing: String, /// 给人看的那一句 pub note: String, } @@ -1569,8 +1620,10 @@ pub struct ReplayQuote { pub provider: String, pub body_bytes: i64, pub input_tokens: i64, - /// `None` = 订阅型,或者这个模型不在价目表里。**不是 0** + /// `None` = 订阅制、计费方式未知,或者这个模型无法计价。**不是 0** pub cost_micros: Option, + /// 要重放到的那家的计费方式:`per-token` / `subscription` / `free` / `unknown` + pub billing: String, pub note: String, /// 发出去之前会不会脱敏。用户有权在按下去之前知道 pub will_redact: bool, @@ -1806,7 +1859,7 @@ pub struct DryRunResult { /// 写在第一个」。直指 provider 时是 None。 #[serde(default, skip_serializing_if = "Option::is_none")] pub strategy: Option, - /// `route` | `deny` | `no_match` + /// `route` | `deny` | `no_match` | `unavailable`(选中的上游都服务不了) pub outcome: String, /// 命中的规则名 pub rule: Option, @@ -1823,6 +1876,17 @@ pub struct DryRunResult { pub hurts_cache: bool, /// 候选链里此刻熔断着的那些。**试算是静态的,但熔断是当下的事实** pub circuit_open: Vec, + /// 规则选中、但服务不了这个请求而被跳过的上游 + #[serde(default)] + pub skipped: Vec, +} + +/// 一个被跳过的候选上游。 +#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)] +pub struct SkippedView { + pub provider: String, + /// `disabled` / `out_of_scope` / `not_offered` + pub reason: String, } // ---------------------------------------------------------- 客户端接管 diff --git a/crates/tw-config/src/lib.rs b/crates/tw-config/src/lib.rs index 9961fdaa..8b5bfd22 100644 --- a/crates/tw-config/src/lib.rs +++ b/crates/tw-config/src/lib.rs @@ -137,13 +137,15 @@ impl Default for Provider { base_url: String::new(), key: Secret::Literal(String::new()), protocol: None, - models: Vec::new(), - billing: None, - redact: None, - trust: None, proxy: default_proxy(), on_proxy_fail: OnProxyFail::default(), + models: Vec::new(), + models_only: None, + billing: None, pricing: None, + trust: None, + redact: None, + disabled: false, } } } @@ -538,18 +540,35 @@ pub struct Provider { /// **默认 `direct` 而不是 `system`**:显式优于隐式。默认跟随系统的 /// 话,用户在系统里开了全局代理,本地 Ollama 就会莫名连不上,而 /// 配置文件里看不出任何线索。 + #[serde(default = "default_proxy", skip_serializing_if = "is_direct")] + pub proxy: String, + #[serde(default, skip_serializing_if = "is_default_on_proxy_fail")] + pub on_proxy_fail: OnProxyFail, /// 探测不到时的兜底清单。 /// /// 有些中转站没实现 `/v1/models`。**这是 provider 级的「这家有什么」, /// 不是全局的「我们对外暴露什么」** —— 那个由汇总推导出来。 #[serde(default, skip_serializing_if = "Vec::is_empty")] pub models: Vec, + /// 只用这家的这些模型:模型 ID 或 glob。不写就是它提供的全部。 + /// + /// **和 `models` 说的不是一件事**:`models` 说这家有什么,这里说我们 + /// 用它的哪些。范围外的模型不出现在 `/v1/models` 里,路由也不会把 + /// 它们的请求交给这家。 + #[serde(default, skip_serializing_if = "Option::is_none")] + pub models_only: Option>, /// 这家怎么收钱。 /// /// **不写就自动判**:响应头里报过订阅额度的就是订阅型。 /// 那个信号一直在我们手上,不该变成一个用户要填的字段。 #[serde(default, skip_serializing_if = "Option::is_none")] pub billing: Option, + /// 按哪张价目表计价。不写就是默认价目表。 + #[serde(default, skip_serializing_if = "Option::is_none")] + pub pricing: Option, + /// 这家可不可信。**不写就按 base_url 判。** + #[serde(default, skip_serializing_if = "Option::is_none")] + pub trust: Option, /// 发给这家之前,把哪几类东西换成占位符。 /// /// **不写就按 base_url 判**:官方端点不脱,其余脱默认那几类。理由很 @@ -558,16 +577,23 @@ pub struct Provider { /// 自废武功。而中转站是完整的中间人。 #[serde(default, skip_serializing_if = "Option::is_none")] pub redact: Option>, - /// 这家可不可信。**不写就按 base_url 判。** - #[serde(default, skip_serializing_if = "Option::is_none")] - pub trust: Option, - #[serde(default = "default_proxy", skip_serializing_if = "is_direct")] - pub proxy: String, - #[serde(default, skip_serializing_if = "is_default_on_proxy_fail")] - pub on_proxy_fail: OnProxyFail, - /// 按哪张价目表计价。不写就是默认价目表。 - #[serde(default, skip_serializing_if = "Option::is_none")] - pub pricing: Option, + /// 停用。**配置原样留着**:不参与路由,它的模型也不出现在 + /// `/v1/models` 里。要暂时不用一家上游时,比删掉再重新填一遍凭据好。 + #[serde(default, skip_serializing_if = "is_default")] + pub disabled: bool, +} + +impl Provider { + /// 这家的这个模型在不在启用范围里(`models_only`)。**不管这家到底 + /// 有没有这个模型** —— 那要看模型目录。 + pub fn uses_model(&self, model: &str) -> bool { + match &self.models_only { + None => true, + Some(patterns) => patterns + .iter() + .any(|p| tw_engine::rule::glob_match(p, model)), + } + } } /// 这家上游可不可信。 @@ -621,21 +647,19 @@ pub enum Billing { /// 结果,会让人误以为这次调用真的免费;「订阅」表达的是「这笔账不在 /// 这个维度上」。 Subscription, + /// 不计费:本地模型、免费额度。**费用记 $0,是一个确定的数** —— + /// 和订阅制不同,这里的钱确实是零 + Free, /// 上游价格未知。成本栏标「未知」,**不参与合计** Unknown, } impl Billing { - /// 这次调用该不该进金额合计。 - /// - /// **宁可显示「不知道」,也不显示一个编出来的精确数字**。 - pub fn counts_toward_money(&self) -> bool { - matches!(self, Billing::PerToken) - } pub fn label(&self) -> &'static str { match self { Billing::PerToken => "按量", Billing::Subscription => "订阅", + Billing::Free => "不计费", Billing::Unknown => "未知", } } @@ -643,16 +667,10 @@ impl Billing { match self { Billing::PerToken => "per-token", Billing::Subscription => "subscription", + Billing::Free => "free", Billing::Unknown => "unknown", } } - pub fn parse(s: &str) -> Billing { - match s { - "subscription" => Billing::Subscription, - "unknown" => Billing::Unknown, - _ => Billing::PerToken, - } - } } /// 和默认值相等吗。用于 `skip_serializing_if`。 diff --git a/crates/tw-config/src/validate.rs b/crates/tw-config/src/validate.rs index ca54b6bc..450229d1 100644 --- a/crates/tw-config/src/validate.rs +++ b/crates/tw-config/src/validate.rs @@ -38,6 +38,12 @@ pub enum ValidationError { Pricing(#[from] tw_pricing::SheetError), #[error("上游「{provider}」选的价目表「{sheet}」不存在")] UnknownPriceSheet { provider: String, sheet: String }, + #[error( + "上游「{name}」的启用范围(models_only)是空的,这样它一个模型都不服务。暂时不用这家上游的话,请停用它(disabled: true)" + )] + EmptyModelsOnly { name: String }, + #[error("上游「{name}」的启用范围(models_only)里有一项是空的")] + BlankModelsOnly { name: String }, } /// `key:` 到底哪儿写错了。 @@ -119,6 +125,20 @@ pub fn validate(cfg: &Config) -> Result<(), ValidationError> { name: p.name.clone(), }); } + // **空范围不是「全部」,也不是一个合理的「停用」。**两种读法各有 + // 人会当真,而停用有自己的开关 + if let Some(only) = &p.models_only { + if only.is_empty() { + return Err(ValidationError::EmptyModelsOnly { + name: p.name.clone(), + }); + } + if only.iter().any(|m| m.trim().is_empty()) { + return Err(ValidationError::BlankModelsOnly { + name: p.name.clone(), + }); + } + } } let mut names = std::collections::HashSet::new(); @@ -332,6 +352,15 @@ mod tests { assert_eq!(k.listen.gateway.effective_allow_from(), vec!["10.1.2.0/24"]); } + #[test] + fn an_empty_model_scope_is_refused_and_points_at_disabling_instead() { + let mut prov = p("relay", "https://relay.example"); + prov.models_only = Some(vec![]); + let e = validate(&cfg(vec![c("a", "tw-a")], vec![prov])).unwrap_err(); + assert!(matches!(e, ValidationError::EmptyModelsOnly { .. }), "{e}"); + assert!(e.to_string().contains("disabled"), "{e}"); + } + #[test] fn a_base_url_without_a_scheme_is_refused() { // 「api.example.com」是最常见的手滑,而它的失败模式是建连时的 diff --git a/crates/tw-control/src/diagnostics.rs b/crates/tw-control/src/diagnostics.rs index c109b758..08437668 100644 --- a/crates/tw-control/src/diagnostics.rs +++ b/crates/tw-control/src/diagnostics.rs @@ -90,13 +90,13 @@ pub async fn bundle(State(s): State) -> String { // ---- 上游 let _ = writeln!( out, - "\n## 上游({} 个)\n\n| 名字 | 地址 | 协议 | 代理 | 熔断 | 脱敏 | 信任 | 价目表 |\n|---|---|---|---|---|---|---|---|", + "\n## 上游({} 个)\n\n| 名字 | 地址 | 协议 | 代理 | 状态 | 模型 | 脱敏 | 信任 | 价目表 |\n|---|---|---|---|---|---|---|---|---|", cfg.providers.len() ); for p in &cfg.providers { let _ = writeln!( out, - "| {} | {} | {} | {} | {} | {} | {} | {} |", + "| {} | {} | {} | {} | {} | {} | {} | {} | {} |", p.name, // **地址也要脱敏** —— 中转站的 base_url 里常常带着 key tw_secret::redact_url(&p.base_url), @@ -104,11 +104,35 @@ pub async fn bundle(State(s): State) -> String { .map(|x| format!("{x:?}")) .unwrap_or_else(|| "猜不出".into()), p.proxy, - if s.health().is_available(&p.name) { + if p.disabled { + "已停用" + } else if s.health().is_available(&p.name) { "正常" } else { "**熔断中**" }, + { + // 「这家为什么收不到某个模型的请求」多半答在这一栏 + let l = s.gateway.models.listing(p); + let served = s.gateway.catalog.load().count_for(&p.name); + let scope = if p.models_only.is_some() { + ",限定范围" + } else { + "" + }; + match l.source { + tw_gateway::models::Source::Discovered => { + format!("{served}(上游列出 {}{scope})", l.models.len()) + } + tw_gateway::models::Source::Manual => { + format!("{served}(手动清单 {}{scope})", l.models.len()) + } + tw_gateway::models::Source::None => match &l.error { + Some(why) => format!("未知:{why}"), + None => "未知".to_string(), + }, + } + }, { let k = p.effective_redact(); if k.is_empty() { diff --git a/crates/tw-control/src/dryrun.rs b/crates/tw-control/src/dryrun.rs index e14dd945..29928212 100644 --- a/crates/tw-control/src/dryrun.rs +++ b/crates/tw-control/src/dryrun.rs @@ -129,10 +129,11 @@ pub async fn dry_run( trace, hurts_cache: false, circuit_open: Vec::new(), + skipped: Vec::new(), }; match engine.route(&f) { - Ok(Outcome::Route(d)) => { + Ok(Outcome::Route(mut d)) => { out.outcome = "route".into(); out.rule = Some(d.matched_rule.clone()); out.via_group = d.via_group.clone(); @@ -142,6 +143,35 @@ pub async fn dry_run( .and_then(|g| engine.groups().iter().find(|x| x.name == g)) .map(|g| g.kind.hurts_cache()) .unwrap_or(false); + out.set = describe(&d.set); + out.strategy = d + .via_group + .as_deref() + .and_then(|g| engine.groups().iter().find(|x| x.name == g)) + .map(|g| g.kind.label().to_string()); + // 和数据面同一步:去掉服务不了这个请求的候选(停用的、范围外的、 + // 清单里没有这个模型的)。**被跳过的要列出来** —— 「规则明明写的 + // 是 A」正是用户会来试算的原因 + let serving = tw_gateway::models::serving( + &rt.config, + &s.gateway.catalog.load(), + &d.candidates, + &f.model, + ); + out.skipped = serving + .skipped + .iter() + .map(|(provider, why)| tw_api::SkippedView { + provider: provider.clone(), + reason: why.slug().to_string(), + }) + .collect(); + if serving.usable.is_empty() { + out.outcome = "unavailable".into(); + out.reason = Some(serving.explain(&f.model).message); + return Ok(Json(out)); + } + d.candidates = serving.usable; // **熔断是当下的事实,不是静态结论。**试算说「会走 A」,而 A // 此刻正熔断着 —— 不说出来的话,用户会拿着一个对的答案去查 // 一个错的现象。 @@ -151,7 +181,6 @@ pub async fn dry_run( .filter(|c| !s.health().is_available(c)) .cloned() .collect(); - out.set = describe(&d.set); // **顺序要和数据面一样,否则试算就是在撒谎。**`load-balance` // / `url-test` / `cheapest` 的次序由运行时的数字定, // 这里走的是同一个 `order`,喂的是同一份延迟表和价目表。 @@ -161,11 +190,6 @@ pub async fn dry_run( // 于是它显示的是轮转序列里的当前位置 —— 而那正是一个没有 // 会话指纹的请求真的会走的路。 out.candidates = order_like_the_data_plane(&s, engine, &d, &f); - out.strategy = d - .via_group - .as_deref() - .and_then(|g| engine.groups().iter().find(|x| x.name == g)) - .map(|g| g.kind.label().to_string()); } Ok(Outcome::Deny { rule, reason }) => { out.outcome = "deny".into(); diff --git a/crates/tw-control/src/lib.rs b/crates/tw-control/src/lib.rs index 6c463236..3ea96566 100644 --- a/crates/tw-control/src/lib.rs +++ b/crates/tw-control/src/lib.rs @@ -371,6 +371,10 @@ fn provider_view( proxy: p.proxy.clone(), on_proxy_fail: p.on_proxy_fail.slug().to_string(), models: p.models.clone(), + models_only: p.models_only.clone(), + model_source: s.gateway.models.listing(p).source.slug().to_string(), + model_count: s.gateway.catalog.load().count_for(&p.name), + disabled: p.disabled, health: match s.health().state(&p.name) { tw_gateway::health::State::Closed => "ok".into(), tw_gateway::health::State::Open => "open".into(), @@ -680,17 +684,12 @@ async fn speed_quote( let items: Vec = targets(&cfg, req.provider.as_deref())? .iter() .map(|p| { - tw_gateway::l3::estimate( - &book, - &p.name, - &req.model, - // 和记账同一个口径:配置里写明了,或者最近一次响应里报过额度 - s.gateway.billing_of(p) == tw_config::Billing::Subscription, - ) + // 计费方式和记账同一个口径:配置里写明了,或者最近一次响应里报过额度 + tw_gateway::l3::estimate(&book, &p.name, &req.model, s.gateway.billing_of(p)) }) .collect(); Ok(Json(tw_api::SpeedQuote { - total_micros: tw_gateway::l3::total_micros(&items), + total_micros: tw_gateway::quote::total(items.iter().map(|e| &e.quote)), items: items.into_iter().map(quote_item).collect(), pricing_date: book.table().date.clone(), })) @@ -758,9 +757,9 @@ fn quote_item(e: tw_gateway::Estimate) -> tw_api::SpeedEstimate { model: e.model, input_tokens: e.input_tokens, max_output_tokens: e.max_output_tokens, - cost_micros: e.cost_micros, - subscription: e.subscription, - note: e.note, + cost_micros: e.quote.cost_micros, + billing: e.quote.billing.slug().to_string(), + note: e.quote.note, } } diff --git a/crates/tw-control/src/pricing.rs b/crates/tw-control/src/pricing.rs index e263cce9..44ea70ef 100644 --- a/crates/tw-control/src/pricing.rs +++ b/crates/tw-control/src/pricing.rs @@ -583,7 +583,7 @@ fn per_million(p: &tw_api::PriceFields) -> tw_pricing::PerMillion { } } -fn price_fields(p: &tw_pricing::PerMillion) -> tw_api::PriceFields { +pub(crate) fn price_fields(p: &tw_pricing::PerMillion) -> tw_api::PriceFields { tw_api::PriceFields { input: p.input, output: p.output, diff --git a/crates/tw-control/src/replay.rs b/crates/tw-control/src/replay.rs index 485f45f9..0bbb9dd8 100644 --- a/crates/tw-control/src/replay.rs +++ b/crates/tw-control/src/replay.rs @@ -105,8 +105,6 @@ pub async fn quote( let input = row.input_tokens.unwrap_or((raw.len() / 4) as i64).max(0) as u64; let output = row.output_tokens.unwrap_or(0).max(0) as u64; let book = s.gateway.pricing.load(); - // 和记账同一个口径:配置里写明了,或者最近一次响应里报过额度 - let subscription = s.gateway.billing_of(provider) == tw_config::Billing::Subscription; let usage = tw_pricing::Usage { input, // 输出按上次那条的实际输出估。**它只是个估计**,模型这次可能 @@ -114,36 +112,23 @@ pub async fn quote( output: output.max(256), ..Default::default() }; - let (cost_micros, note) = if subscription { - ( - None, - format!("不计费,但会消耗约 {} tokens 的额度", input + usage.output), - ) - } else { - // **按要重放到的那个上游查价**,不是原来那条走的上游 - match book.cost_for(&provider.name, &row.model, &usage, false) { - tw_pricing::Cost::Known(m) | tw_pricing::Cost::Estimated(m) => ( - Some(m), - // **金额再小也要显示。**用户按下按钮时有权知道自己在花什么 - format!("约 ${:.5}", m as f64 / 1e6), - ), - tw_pricing::Cost::Unpriced { .. } => ( - None, - format!( - "价格未知(`{}` 不在价目表里),将消耗约 {} tokens", - row.model, - input + usage.output - ), - ), - } - }; + // **按要重放到的那个上游报价**,不是原来那条走的上游。计费方式和记账 + // 同一个口径:配置里写明了,或者最近一次响应里报过额度 + let quote = tw_gateway::quote::quote( + &book, + &provider.name, + &row.model, + &usage, + s.gateway.billing_of(provider), + ); Ok(Json(tw_api::ReplayQuote { model: row.model.clone(), provider: provider.name.clone(), body_bytes: raw.len() as i64, input_tokens: input as i64, - cost_micros, - note, + cost_micros: quote.cost_micros, + billing: quote.billing.slug().to_string(), + note: quote.note, // 脱敏在重放里照做,但用户有权在按下去之前知道 will_redact: !tw_gateway::guard::effective_kinds(provider, &tw_engine::Guard::default()) .is_empty(), diff --git a/crates/tw-control/src/resources.rs b/crates/tw-control/src/resources.rs index b72565c6..0d5d7753 100644 --- a/crates/tw-control/src/resources.rs +++ b/crates/tw-control/src/resources.rs @@ -17,7 +17,7 @@ use axum::Json; use axum::extract::{Path, Query, State}; use axum::http::StatusCode; -use axum::routing::{post, put}; +use axum::routing::{get, post, put}; use serde_yaml_ng::Value; use tw_config::edit::{self, EditError}; use tw_config::history::Origin; @@ -33,6 +33,8 @@ pub fn router() -> axum::Router { "/providers/{name}", put(update_provider).delete(delete_provider), ) + .route("/providers/{name}/models", get(provider_models)) + .route("/providers/{name}/models/refresh", post(refresh_models)) .route("/proxies", post(create_proxy)) .route("/proxies/test", post(test_proxy)) .route("/proxies/{name}", put(update_proxy).delete(delete_proxy)) @@ -168,6 +170,70 @@ async fn test_provider( })) } +/// 一个上游的模型清单:每个模型在不在启用范围里、上下文窗口多大、按它选的 +/// 价目表怎么计价。 +async fn provider_models( + State(s): State, + Path(name): Path, +) -> Result, Fail> { + let cfg = s.config(); + let p = cfg + .providers + .iter() + .find(|p| p.name == name) + .ok_or_else(|| fail(StatusCode::NOT_FOUND, format!("没有叫「{name}」的上游")))?; + Ok(Json(models_view(&s, p, s.gateway.models.listing(p)))) +} + +/// 马上向上游重新获取模型清单。 +async fn refresh_models( + State(s): State, + Path(name): Path, +) -> Result, Fail> { + let listing = tw_gateway::models::refresh_one(&s.gateway, &name) + .await + .ok_or_else(|| fail(StatusCode::NOT_FOUND, format!("没有叫「{name}」的上游")))?; + let cfg = s.config(); + let p = cfg + .providers + .iter() + .find(|p| p.name == name) + .ok_or_else(|| fail(StatusCode::NOT_FOUND, format!("没有叫「{name}」的上游")))?; + Ok(Json(models_view(&s, p, listing))) +} + +fn models_view( + s: &ControlState, + p: &tw_config::Provider, + listing: tw_gateway::models::Listing, +) -> tw_api::ProviderModelsView { + let book = s.gateway.pricing.load(); + let date = &book.table().date; + tw_api::ProviderModelsView { + provider: p.name.clone(), + source: listing.source.slug().to_string(), + checked_at_ms: listing.checked_at_ms, + error: listing.error, + models: listing + .models + .into_iter() + .map(|id| { + let r = book.resolve_for(&p.name, &id); + tw_api::ModelRow { + enabled: p.uses_model(&id), + context_window: r.as_ref().and_then(|r| r.price.max_input_tokens), + price: r.as_ref().map(|r| { + crate::pricing::price_fields(&tw_pricing::PerMillion::of(&r.price)) + }), + price_source: r.as_ref().map(|r| tw_store::price_source(&r.source, date)), + estimated: r.as_ref().is_some_and(|r| r.cross_platform), + id, + } + }) + .collect(), + } +} + fn to_provider( input: &tw_api::ProviderInput, existing: Option<&tw_config::Provider>, @@ -219,7 +285,12 @@ fn to_provider( .transpose()?, proxy: input.proxy.trim().to_string(), on_proxy_fail: slug("代理不可用时的处理", &input.on_proxy_fail)?, + models_only: input + .models_only + .as_ref() + .map(|ms| ms.iter().map(|m| m.trim().to_string()).collect::>()), pricing: input.pricing.clone(), + disabled: input.disabled, }) } diff --git a/crates/tw-control/tests/models.rs b/crates/tw-control/tests/models.rs new file mode 100644 index 00000000..833580de --- /dev/null +++ b/crates/tw-control/tests/models.rs @@ -0,0 +1,280 @@ +//! 上游的模型:清单从哪儿来、哪些在启用范围里、怎么计价;停用和启用范围 +//! 怎么写进配置;试算怎么说出被跳过的上游。 + +use std::sync::Arc; + +use axum::body::Body; +use axum::http::{Request, StatusCode}; +use tower::ServiceExt; +use tw_control::{ConfigManager, ControlState}; + +struct Bed { + dir: tempfile::TempDir, + app: axum::Router, +} + +impl Bed { + fn file(&self) -> String { + std::fs::read_to_string(self.dir.path().join("config.yaml")).unwrap() + } +} + +fn bed(yaml: &str) -> Bed { + let d = tempfile::tempdir().unwrap(); + let p = d.path().join("config.yaml"); + std::fs::write(&p, yaml).unwrap(); + let cfg = tw_config::try_parse(yaml).unwrap(); + let gw = tw_gateway::AppState::new(cfg).unwrap(); + let bus = gw.bus.clone(); + let state = ControlState { + cfg: Arc::new(ConfigManager::new(p, gw.clone(), bus)), + gateway: gw, + gateway_addr: None, + store: None, + started: std::time::Instant::now(), + price_updater: Default::default(), + // **测试里绝不能碰开发者自己的配置** + home: d.path().join("home"), + }; + Bed { + app: tw_control::router(state), + dir: d, + } +} + +async fn call( + app: &axum::Router, + method: &str, + path: &str, + body: serde_json::Value, +) -> (StatusCode, serde_json::Value) { + let r = app + .clone() + .oneshot( + Request::builder() + .method(method) + .uri(path) + .header("content-type", "application/json") + .body(Body::from(body.to_string())) + .unwrap(), + ) + .await + .unwrap(); + let st = r.status(); + let b = axum::body::to_bytes(r.into_body(), 1 << 20).await.unwrap(); + let text = String::from_utf8_lossy(&b).to_string(); + let v = serde_json::from_str(&text).unwrap_or(serde_json::Value::String(text)); + (st, v) +} + +/// 一个假上游:认 `sk-good`,列出三个模型。 +async fn upstream() -> std::net::SocketAddr { + let app = axum::Router::new().route( + "/v1/models", + axum::routing::get(|h: axum::http::HeaderMap| async move { + if h.get("x-api-key").and_then(|v| v.to_str().ok()) != Some("sk-good") { + return (StatusCode::UNAUTHORIZED, "{}".to_string()); + } + ( + StatusCode::OK, + r#"{"data":[{"id":"claude-sonnet-4-5"},{"id":"claude-haiku-4-5"},{"id":"中转自有模型"}]}"# + .to_string(), + ) + }), + ); + let l = tokio::net::TcpListener::bind("127.0.0.1:0").await.unwrap(); + let a = l.local_addr().unwrap(); + tokio::spawn(async move { axum::serve(l, app).await.unwrap() }); + a +} + +fn config(up: std::net::SocketAddr, key: &str, extra: &str) -> String { + format!( + "version: 1 +clients: + - name: c + key: tw-k +providers: + - name: relay + base_url: http://{up} + key: {key} + protocol: anthropic +{extra}" + ) +} + +#[tokio::test] +async fn an_upstreams_models_come_with_their_scope_context_window_and_price() { + let up = upstream().await; + let b = bed(&config( + up, + "sk-good", + " models_only: [claude-sonnet-*]\n", + )); + + // 还没问过:不知道它有什么 + let (st, v) = call( + &b.app, + "GET", + "/providers/relay/models", + serde_json::json!(null), + ) + .await; + assert_eq!(st, StatusCode::OK, "{v}"); + assert_eq!(v["source"], "none"); + assert!(v.get("checked_at_ms").is_none(), "{v}"); + + let (st, v) = call( + &b.app, + "POST", + "/providers/relay/models/refresh", + serde_json::json!(null), + ) + .await; + assert_eq!(st, StatusCode::OK, "{v}"); + assert_eq!(v["source"], "discovered"); + assert!(v["checked_at_ms"].as_u64().is_some(), "{v}"); + let models = v["models"].as_array().unwrap(); + let find = |id: &str| models.iter().find(|m| m["id"] == id).unwrap().clone(); + let sonnet = find("claude-sonnet-4-5"); + assert_eq!(sonnet["enabled"], true); + assert_eq!(sonnet["context_window"], 200_000); + assert_eq!(sonnet["price"]["input"], 3.0); + assert_eq!(sonnet["price_source"]["kind"], "default"); + assert_eq!(find("claude-haiku-4-5")["enabled"], false); + // 无法计价就是无法计价 + assert!(find("中转自有模型").get("price").is_none(), "{v}"); + + let (_, ov) = call(&b.app, "GET", "/overview", serde_json::json!(null)).await; + let p = &ov["providers"][0]; + assert_eq!(p["model_source"], "discovered"); + assert_eq!(p["model_count"], 1, "范围外的不算:{p}"); + assert_eq!(p["models_only"], serde_json::json!(["claude-sonnet-*"])); + assert_eq!(p["disabled"], false); +} + +#[tokio::test] +async fn a_refresh_the_upstream_refuses_says_why_and_the_manual_list_stands_in() { + let up = upstream().await; + let b = bed(&config(up, "sk-bad", " models: [手写的模型]\n")); + let (st, v) = call( + &b.app, + "POST", + "/providers/relay/models/refresh", + serde_json::json!(null), + ) + .await; + assert_eq!(st, StatusCode::OK, "{v}"); + assert_eq!(v["source"], "manual"); + assert!(v["error"].as_str().unwrap().contains("401"), "{v}"); + assert_eq!(v["models"][0]["id"], "手写的模型"); + + let (st, _) = call( + &b.app, + "GET", + "/providers/没有这家/models", + serde_json::json!(null), + ) + .await; + assert_eq!(st, StatusCode::NOT_FOUND); +} + +#[tokio::test] +async fn disabling_and_scoping_an_upstream_is_written_and_an_empty_scope_is_refused() { + let up = upstream().await; + let b = bed(&config(up, "sk-good", "")); + let (st, v) = call( + &b.app, + "PUT", + "/providers/relay", + serde_json::json!({ "provider": { + "name": "relay", + "protocol": "anthropic", + "models_only": ["claude-*"], + "disabled": true, + }}), + ) + .await; + assert_eq!(st, StatusCode::OK, "{v}"); + let written = &tw_config::try_parse(&b.file()).unwrap().providers[0]; + assert!(written.disabled); + assert_eq!(written.models_only, Some(vec!["claude-*".to_string()])); + let (_, ov) = call(&b.app, "GET", "/overview", serde_json::json!(null)).await; + assert_eq!(ov["providers"][0]["disabled"], true); + assert_eq!(ov["providers"][0]["model_count"], 0); + + // 空范围:一个模型都不服务。停用有自己的开关 + let before = b.file(); + let (st, v) = call( + &b.app, + "PUT", + "/providers/relay", + serde_json::json!({ "provider": { + "name": "relay", + "protocol": "anthropic", + "models_only": [], + }}), + ) + .await; + assert_eq!(st, StatusCode::BAD_REQUEST, "{v}"); + assert!(v.as_str().unwrap().contains("disabled"), "{v}"); + assert_eq!(b.file(), before); +} + +#[tokio::test] +async fn the_dry_run_names_the_upstreams_it_skips_and_why() { + let yaml = "version: 1 +clients: + - name: c + key: tw-k +providers: + - name: 中转 + base_url: https://relay.example.com + key: sk-b + disabled: true + - name: 官方 + base_url: https://api.anthropic.com + key: sk-a + models_only: [claude-sonnet-*] +groups: + - name: 都试试 + type: fallback + providers: [中转, 官方] +routes: + - name: 默认 + rules: + - name: 全部 + to: 都试试 +"; + let b = bed(yaml); + let (st, v) = call( + &b.app, + "POST", + "/dryrun", + serde_json::json!({ "model": "claude-sonnet-4-5" }), + ) + .await; + assert_eq!(st, StatusCode::OK, "{v}"); + assert_eq!(v["outcome"], "route"); + assert_eq!(v["candidates"], serde_json::json!(["官方"])); + assert_eq!( + v["skipped"], + serde_json::json!([{ "provider": "中转", "reason": "disabled" }]) + ); + + // 两家都服务不了:说出来,而不是给一条空的候选链 + let (_, v) = call( + &b.app, + "POST", + "/dryrun", + serde_json::json!({ "model": "claude-opus-4-1" }), + ) + .await; + assert_eq!(v["outcome"], "unavailable", "{v}"); + assert_eq!(v["candidates"], serde_json::json!([])); + assert_eq!(v["skipped"][1]["reason"], "out_of_scope", "{v}"); + assert!( + v["reason"].as_str().unwrap().contains("claude-opus-4-1"), + "{v}" + ); +} diff --git a/crates/tw-control/tests/speed.rs b/crates/tw-control/tests/speed.rs index a2dad773..56a02de4 100644 --- a/crates/tw-control/tests/speed.rs +++ b/crates/tw-control/tests/speed.rs @@ -166,7 +166,7 @@ providers: let items = v["items"].as_array().unwrap(); let official = items.iter().find(|i| i["provider"] == "official").unwrap(); let max = items.iter().find(|i| i["provider"] == "max").unwrap(); - assert_eq!(max["subscription"], true, "{v}"); + assert_eq!(max["billing"], "subscription", "{v}"); assert!(max.get("cost_micros").is_none(), "订阅制不该给金额:{v}"); assert_eq!( v["total_micros"], official["cost_micros"], diff --git a/crates/tw-engine/src/catalog.rs b/crates/tw-engine/src/catalog.rs index 3025137a..27721841 100644 --- a/crates/tw-engine/src/catalog.rs +++ b/crates/tw-engine/src/catalog.rs @@ -22,6 +22,9 @@ pub struct ProviderModels { pub provider: String, /// 这家说的方言。客户端按方言过滤时用它 pub protocol: String, + /// 知不知道这家有什么。**不知道时 `models` 是空的,而那不代表它什么都 + /// 不提供**;知道、但按启用范围过滤完是空的,才是真的什么都不提供 + pub known: bool, pub models: Vec, } @@ -35,14 +38,20 @@ pub struct Catalog { by_model: BTreeMap>, /// provider → 它说的方言 protocols: BTreeMap, + /// 有模型清单的 provider。**不在里面的不是「什么都不提供」,是「不知道」** + listed: BTreeSet, } impl Catalog { pub fn build(sources: &[ProviderModels]) -> Self { let mut by_model: BTreeMap> = BTreeMap::new(); let mut protocols = BTreeMap::new(); + let mut listed = BTreeSet::new(); for s in sources { protocols.insert(s.provider.clone(), s.protocol.clone()); + if s.known { + listed.insert(s.provider.clone()); + } for m in &s.models { let v = by_model.entry(m.clone()).or_default(); if !v.contains(&s.provider) { @@ -53,9 +62,28 @@ impl Catalog { Self { by_model, protocols, + listed, } } + /// 这家能不能提供这个模型。`None` = 不知道:它没有模型清单。 + /// + /// **不知道不等于不能。**把没有清单的上游当成「什么都没有」,一家不 + /// 实现 `/v1/models` 的中转站就再也收不到请求 —— 而它可能什么都能服务。 + pub fn offers(&self, provider: &str, model: &str) -> Option { + self.listed + .contains(provider) + .then(|| self.providers_for(model).iter().any(|p| p == provider)) + } + + /// 这家能服务几个模型。 + pub fn count_for(&self, provider: &str) -> usize { + self.by_model + .values() + .filter(|ps| ps.iter().any(|p| p == provider)) + .count() + } + /// 全集。 pub fn all(&self) -> Vec<&str> { self.by_model.keys().map(|s| s.as_str()).collect() @@ -127,6 +155,7 @@ mod tests { ProviderModels { provider: p.into(), protocol: proto.into(), + known: !models.is_empty(), models: models.iter().map(|s| s.to_string()).collect(), } } @@ -152,6 +181,19 @@ mod tests { v.iter().map(|s| s.to_string()).collect() } + #[test] + fn an_upstream_without_a_list_is_unknown_not_empty() { + let c = Catalog::build(&[ + pm("relay-cn", "anthropic", &["claude-sonnet-4-5"]), + pm("no-list", "anthropic", &[]), + ]); + assert_eq!(c.offers("relay-cn", "claude-sonnet-4-5"), Some(true)); + assert_eq!(c.offers("relay-cn", "claude-opus-4-1"), Some(false)); + assert_eq!(c.offers("no-list", "claude-opus-4-1"), None); + assert_eq!(c.count_for("relay-cn"), 1); + assert_eq!(c.count_for("no-list"), 0); + } + #[test] fn merging_records_who_can_serve_each_model() { let c = catalog(); diff --git a/crates/tw-gateway/src/l3.rs b/crates/tw-gateway/src/l3.rs index 0d1feb7b..69559eb0 100644 --- a/crates/tw-gateway/src/l3.rs +++ b/crates/tw-gateway/src/l3.rs @@ -21,11 +21,7 @@ const PROMPT: &str = "Hi"; const MAX_TOKENS: u64 = 8; /// 这次测速会花多少。 -/// -/// **三种情况都要说清楚**:算得出金额的给金额;订阅型的说 -/// 「不计费」;价格未知的说「价格未知」—— 而三者都要给出 token 数, -/// 因为那是唯一一个我们确定知道的量。 -#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)] +#[derive(Debug, Clone, PartialEq)] pub struct Estimate { pub provider: String, pub model: String, @@ -33,16 +29,8 @@ pub struct Estimate { pub input_tokens: u64, /// 输出上限 pub max_output_tokens: u64, - /// 微分。`None` 表示价目表里没有这个模型,或者这家是订阅制 - #[serde(default, skip_serializing_if = "Option::is_none")] - pub cost_micros: Option, - /// 订阅制上游。**没有金额不等于算不出来** —— 它消耗的是额度,不该 - /// 让一批测速的合计因为它变成「算不出来」 - #[serde(default)] - pub subscription: bool, - /// 给人看的那一句。**金额再小也要显示** —— 用户按下按钮时有权知道 - /// 自己在花什么 - pub note: String, + /// 按这家的计费方式和价目表报的价,见 [`crate::quote`] + pub quote: crate::quote::Quote, } /// 探测请求的输入 token 数。 @@ -251,10 +239,10 @@ fn has_content(chunk: &[u8]) -> bool { /// 算一次测速要花多少。 pub fn estimate( - prices: &tw_pricing::PriceBook, + book: &tw_pricing::PriceBook, provider: &str, model: &str, - subscription: bool, + billing: tw_config::Billing, ) -> Estimate { let input = probe_input_tokens(); let usage = tw_pricing::Usage { @@ -262,60 +250,15 @@ pub fn estimate( output: MAX_TOKENS, ..Default::default() }; - let (cost_micros, note) = if subscription { - // **订阅型上游不按 token 计费**,但它照样消耗额度 —— 说清楚 - // 消耗多少,而不是说「免费」 - ( - None, - format!("不计费,但会消耗约 {} tokens 的额度", input + MAX_TOKENS), - ) - } else { - match prices.cost_for(provider, model, &usage, false) { - tw_pricing::Cost::Known(m) | tw_pricing::Cost::Estimated(m) => ( - Some(m), - // **金额再小也要显示。**用户按下按钮时有权知道自己在花 - // 什么 - format!("约 ${:.5}", m as f64 / 1e6), - ), - tw_pricing::Cost::Unpriced { .. } => ( - None, - format!( - "价格未知(这个模型不在价目表里),将消耗约 {} tokens", - input + MAX_TOKENS - ), - ), - } - }; Estimate { provider: provider.to_string(), model: model.to_string(), input_tokens: input, max_output_tokens: MAX_TOKENS, - cost_micros, - subscription, - note, + quote: crate::quote::quote(book, provider, model, &usage, billing), } } -/// 一批测速的总计。 -/// -/// **批量是最容易让人手滑的地方** —— 点一下「全部测速」可能是 -/// 十几次真实调用,所以要列出每一项**并给出总计**。 -/// -/// **订阅制那几项不进合计**:它们不按 token 收钱,消耗的是额度,界面上 -/// 单独说。以前它们和「价格未知」一样让合计变成空 —— 于是只要勾上一家 -/// 订阅制上游,用户就再也看不到这批测速要花多少钱。 -pub fn total_micros(es: &[Estimate]) -> Option { - // 有任何一项按量计费却算不出来,总计就不该给一个看起来完整的数字 - if es - .iter() - .any(|e| !e.subscription && e.cost_micros.is_none()) - { - return None; - } - Some(es.iter().filter_map(|e| e.cost_micros).sum()) -} - #[cfg(test)] mod tests { use super::*; @@ -340,80 +283,26 @@ mod tests { } #[test] - fn an_estimate_names_a_concrete_amount_however_small() { - // **金额再小也要显示。**用户按下按钮时有权知道自己在花什么。 - let e = estimate(&prices(), "官方", "claude-sonnet-4-5", false); - assert!(e.cost_micros.is_some()); - assert!(e.note.starts_with("约 $"), "{}", e.note); - // 五位小数:这次测速是几百微分的量级,**两位小数会显示成 - // $0.00**,而那等于告诉用户「这不花钱」。 - assert!(e.note.contains("0.000"), "{}", e.note); - assert_ne!(e.note, "约 $0.00", "精度不够,看起来像免费的"); - } - - #[test] - fn a_subscription_upstream_says_it_costs_quota_not_that_it_is_free() { - // 「免费」是错的 —— 它照样消耗额度。 - let e = estimate(&prices(), "订阅", "claude-sonnet-4-5", true); - assert!(e.cost_micros.is_none()); - assert!(e.note.contains("不计费"), "{}", e.note); - assert!(e.note.contains("额度"), "得说清消耗的是什么:{}", e.note); - assert!(e.note.contains("18"), "得给出 token 数:{}", e.note); - } - - #[test] - fn an_unpriced_model_says_so_and_still_gives_the_token_count() { - // token 数是唯一一个我们确定知道的量。 - let e = estimate(&prices(), "中转", "某个自己起的名字", false); - assert!(e.cost_micros.is_none()); - assert!(e.note.contains("价格未知"), "{}", e.note); - assert!(e.note.contains("18"), "{}", e.note); - } - - #[test] - fn the_input_token_count_is_exact_not_approximate() { + fn an_estimate_prices_the_fixed_probe_with_an_exact_token_count() { // 「约 10 tokens」和「10 tokens」在一个「你确认要花钱吗」的 // 对话框里是两种可信度。 - let e = estimate(&prices(), "p", "claude-sonnet-4-5", false); + let e = estimate( + &prices(), + "官方", + "claude-sonnet-4-5", + tw_config::Billing::PerToken, + ); assert_eq!(e.input_tokens, probe_input_tokens()); assert_eq!(e.max_output_tokens, MAX_TOKENS); - } - - #[test] - fn a_batch_gives_a_total() { - // **批量是最容易让人手滑的地方**。 - let es: Vec<_> = ["claude-sonnet-4-5", "claude-opus-4-1", "claude-haiku-4-5"] - .iter() - .map(|m| estimate(&prices(), "p", m, false)) - .collect(); - let total = total_micros(&es).expect("三个都有价格,总计该算得出来"); - assert_eq!( - total, - es.iter().map(|e| e.cost_micros.unwrap()).sum::() + assert!(e.quote.cost_micros.is_some()); + let tokens = (probe_input_tokens() + MAX_TOKENS).to_string(); + let e = estimate( + &prices(), + "订阅", + "claude-sonnet-4-5", + tw_config::Billing::Subscription, ); - } - - #[test] - fn a_batch_with_one_unpriced_model_refuses_to_show_a_complete_looking_total() { - // **有一项算不出来,总计就不该给一个看起来完整的数字** —— - // 那会让用户以为「全部测速」的代价就是那个数。 - let mut es = vec![estimate(&prices(), "p", "claude-sonnet-4-5", false)]; - es.push(estimate(&prices(), "p", "某个中转站的模型", false)); - assert!(total_micros(&es).is_none()); - } - - #[test] - fn a_subscription_item_stays_out_of_the_total_instead_of_voiding_it() { - // 勾上一家订阅制上游,不该让用户看不到其余几家要花多少钱。 - let es = vec![ - estimate(&prices(), "官方", "claude-sonnet-4-5", false), - estimate(&prices(), "订阅", "claude-sonnet-4-5", true), - ]; - assert_eq!(total_micros(&es), es[0].cost_micros); - // 价格未知的那一项照样让合计不成立 - let mut es = es; - es.push(estimate(&prices(), "中转", "某个中转站的模型", false)); - assert!(total_micros(&es).is_none()); + assert!(e.quote.note.contains(&tokens), "{}", e.quote.note); } #[test] diff --git a/crates/tw-gateway/src/lib.rs b/crates/tw-gateway/src/lib.rs index 36bc1127..2535be03 100644 --- a/crates/tw-gateway/src/lib.rs +++ b/crates/tw-gateway/src/lib.rs @@ -22,9 +22,11 @@ pub mod latency; pub mod leak; pub mod limits; pub mod live; +pub mod models; pub mod oauth; pub mod probe; pub mod quota; +pub mod quote; pub mod server; pub mod session; pub mod toolwall; @@ -42,8 +44,6 @@ pub use l3::{Estimate, L3Result}; pub use limits::{Gate, LimitError, Limits}; pub use probe::{ModelList, ProbeResult, probe}; pub use quota::{Quota, from_headers as quota_from_headers}; -pub use server::{ - AppState, Runtime, client_for_provider, refresh_catalog, router, serve, serve_following_config, - spawn_catalog_refresh, -}; +pub use quote::Quote; +pub use server::{AppState, Runtime, client_for_provider, router, serve, serve_following_config}; pub use usage::{Sniffer, Usage}; diff --git a/crates/tw-gateway/src/models.rs b/crates/tw-gateway/src/models.rs new file mode 100644 index 00000000..bf28c44d --- /dev/null +++ b/crates/tw-gateway/src/models.rs @@ -0,0 +1,573 @@ +//! 每个上游提供哪些模型:向上游要来的、配置里手写的,以及它们是什么时候、 +//! 怎么来的。 +//! +//! # 两份东西 +//! +//! - **目录([`Directory`])**记每个上游的原始答案:列出了什么、上次什么时候 +//! 问的、没问到的话为什么。它跨重载存活。 +//! - **汇总(`tw_engine::Catalog`)**从目录和当前配置推出来:停用的上游不算, +//! 启用范围(`models_only`)之外的模型不算。`/v1/models`、准入、挑候选 +//! 都只看它。 +//! +//! 配置一变,汇总马上按新配置重算;只有地址、凭据、协议、代理变了的上游 +//! 才需要重新去问,其余的答案原样留着。以前改一次配置,汇总就换回只含手写 +//! 清单的那份:已经问到的模型全部消失,新加的上游要等到第二天的定时刷新。 +//! +//! **向上游问是后台的事。**探测零成本,但要打网络:它不挡启动,`/v1/models` +//! 也不现问 —— 每次有人列模型就去打一遍上游,会把一个本该零成本的端点变成 +//! 一串网络往返。 + +use std::collections::HashMap; +use std::sync::Mutex; +use std::time::Duration; + +use crate::probe::ModelList; +use crate::server::{AppState, Runtime, now_ms}; + +/// 多久向每个上游重新问一次。 +const REFRESH_EVERY: Duration = Duration::from_secs(24 * 3600); +/// 没问到(连不上、密钥被拒)之后多久再试。 +const RETRY_AFTER: Duration = Duration::from_secs(3600); +/// 多久看一次有没有到时间的。看一次只是比较时间,不联网。 +/// +/// **不是睡满一天再醒。**笔记本合盖时单调时钟不走,睡「24 小时」可能睡上 +/// 好几天;按墙上时间一轮轮比,开盖之后下一轮就会去问。 +const TICK: Duration = Duration::from_secs(10 * 60); + +/// 一个上游的模型清单从哪儿来。 +#[derive(Debug, Clone, Copy, PartialEq, Eq)] +pub enum Source { + /// 上游自己列出来的 + Discovered, + /// 上游没给出清单,用配置里手写的 `models` + Manual, + /// 都没有。**不知道它有什么**,不是它什么都没有 + None, +} + +impl Source { + pub fn slug(&self) -> &'static str { + match self { + Source::Discovered => "discovered", + Source::Manual => "manual", + Source::None => "none", + } + } +} + +/// 一个上游的模型清单。 +#[derive(Debug, Clone)] +pub struct Listing { + pub source: Source, + /// 清单本身。**还没按启用范围过滤** + pub models: Vec, + /// 最近一次向上游问的时间。还没问过是空 + pub checked_at_ms: Option, + /// 没从上游拿到清单的原因 + pub error: Option, +} + +/// 最近一次向上游问的结果。 +#[derive(Debug, Clone)] +enum Answer { + /// 还没问过 + Pending, + /// 列出来了 + Listed(Vec), + /// 问到了,但上游没给出清单:没有这个接口、格式认不出、空的 + NoList(String), + /// 没问到:连不上、密钥被拒、取不到密钥 + Failed(String), +} + +#[derive(Debug, Clone)] +struct Entry { + /// 问的时候这家长什么样。地址、凭据、协议、代理变了,答案就作废 + identity: String, + answer: Answer, + checked_at_ms: Option, +} + +#[derive(Debug, Default)] +pub struct Directory { + entries: Mutex>, + /// 有上游等着去问 + wake: tokio::sync::Notify, +} + +/// 决定答案还作不作数的那几样。 +/// +/// **OAuth 只看账号,不看 token**:refresh token 轮换一次就重问一遍,问到的 +/// 是同一份清单。 +fn identity(cfg: &tw_config::Config, p: &tw_config::Provider) -> String { + let key = match &p.key { + tw_config::Secret::Literal(v) => v.clone(), + tw_config::Secret::OAuth { oauth } => format!( + "oauth|{}|{}", + oauth.endpoint, + oauth.client_id.as_deref().unwrap_or_default() + ), + tw_config::Secret::Unknown(_) => String::new(), + }; + let raw = format!( + "{}|{key}|{:?}|{}", + p.base_url, + p.effective_protocol(), + crate::server::proxy_shape(cfg, p) + ); + // **存指纹,不存原文** —— 这张表不该多出一份密钥 + blake3::hash(raw.as_bytes()).to_hex().to_string() +} + +impl Directory { + fn lock(&self) -> std::sync::MutexGuard<'_, HashMap> { + self.entries.lock().unwrap_or_else(|e| e.into_inner()) + } + + /// 配置换了之后对一遍:删掉的上游忘掉,新加的、身份变了的等着去问。 + /// 返回有没有要去问的。 + pub(crate) fn reconcile(&self, cfg: &tw_config::Config) -> bool { + let mut entries = self.lock(); + entries.retain(|name, _| cfg.providers.iter().any(|p| &p.name == name)); + let mut pending = false; + for p in &cfg.providers { + let id = identity(cfg, p); + if entries.get(&p.name).is_some_and(|e| e.identity == id) { + continue; + } + entries.insert( + p.name.clone(), + Entry { + identity: id, + answer: Answer::Pending, + checked_at_ms: None, + }, + ); + pending = true; + } + pending + } + + pub(crate) fn wake(&self) { + self.wake.notify_one(); + } + + /// 这个上游的模型清单。 + pub fn listing(&self, p: &tw_config::Provider) -> Listing { + let entry = self.lock().get(&p.name).cloned(); + listing_of(entry.as_ref(), p) + } + + /// 按目录和配置推出汇总,并换进 `into`。 + /// + /// **推算和换入在同一把锁里,配置在锁里现取。**否则一次探测回来和一次 + /// 配置重载交错时,后换入的可能是按旧配置推出来的那份。 + pub(crate) fn publish( + &self, + config: impl Fn() -> std::sync::Arc, + into: &arc_swap::ArcSwap, + ) { + let entries = self.lock(); + let cfg = config(); + let sources: Vec = cfg + .providers + .iter() + // 停用的上游不提供任何东西 + .filter(|p| !p.disabled) + .map(|p| { + let l = listing_of(entries.get(&p.name), p); + tw_engine::ProviderModels { + provider: p.name.clone(), + protocol: p + .effective_protocol() + .map(|x| format!("{x:?}")) + // 猜不出协议时按 Anthropic 算 —— 和转发时的默认一致 + // (forward::apply_credential)。两处不一致会让「列出来 + // 了但发过去 401」变成可能。 + .unwrap_or_else(|| "Anthropic".to_string()), + known: l.source != Source::None, + models: l.models.into_iter().filter(|m| p.uses_model(m)).collect(), + } + }) + .collect(); + into.store(std::sync::Arc::new(tw_engine::Catalog::build(&sources))); + } + + /// 到时间该去问的上游。 + fn due(&self, cfg: &tw_config::Config, now: u64) -> Vec { + let entries = self.lock(); + cfg.providers + .iter() + // 停用的上游用不着:打开它时身份不变,也会在到时间时补上 + .filter(|p| !p.disabled) + .filter(|p| match entries.get(&p.name) { + None => true, + Some(e) => match (&e.answer, e.checked_at_ms) { + (Answer::Pending, _) | (_, None) => true, + (Answer::Failed(_), Some(at)) => { + now.saturating_sub(at) >= RETRY_AFTER.as_millis() as u64 + } + (_, Some(at)) => now.saturating_sub(at) >= REFRESH_EVERY.as_millis() as u64, + }, + }) + .map(|p| p.name.clone()) + .collect() + } + + /// 记下一次答案。**问的时候那家的身份已经变了的话,这个答案作废** —— + /// 配置重载已经把它排进了下一轮。 + fn record(&self, name: &str, identity: &str, answer: Answer, at: u64) { + let mut entries = self.lock(); + if let Some(e) = entries.get_mut(name) + && e.identity == identity + { + e.answer = answer; + e.checked_at_ms = Some(at); + } + } +} + +fn listing_of(entry: Option<&Entry>, p: &tw_config::Provider) -> Listing { + let checked_at_ms = entry.and_then(|e| e.checked_at_ms); + let error = entry.and_then(|e| match &e.answer { + Answer::NoList(why) | Answer::Failed(why) => Some(why.clone()), + Answer::Pending | Answer::Listed(_) => None, + }); + match entry.map(|e| &e.answer) { + Some(Answer::Listed(models)) => Listing { + source: Source::Discovered, + models: models.clone(), + checked_at_ms, + error: None, + }, + // 问不到就用手写的兜底。**两者不合并** —— 合并的话,用户删掉一个 + // 上游不再提供的模型时会发现它删不掉 + _ if !p.models.is_empty() => Listing { + source: Source::Manual, + models: p.models.clone(), + checked_at_ms, + error, + }, + _ => Listing { + source: Source::None, + models: Vec::new(), + checked_at_ms, + error, + }, + } +} + +/// 问一家上游有哪些模型。 +async fn ask(state: &AppState, rt: &Runtime, p: &tw_config::Provider) -> Answer { + // 用这一家自己的 client:它带着该走的代理,换 OAuth token 也要走那条路 + let http = rt.clients.get(&p.name).unwrap_or(&state.http); + let key = match state.key_for(p, http).await { + Ok(k) => k, + Err(e) => return Answer::Failed(format!("取不到凭据:{e}")), + }; + let r = crate::probe::probe(http, &p.base_url, &key, p.effective_protocol()).await; + if !r.ok { + return Answer::Failed(r.error.unwrap_or_else(|| "检测失败".to_string())); + } + match r.models { + ModelList::Listed { models } => Answer::Listed(models), + ModelList::NotImplemented { status } => { + Answer::NoList(format!("上游没有提供模型列表接口(HTTP {status})")) + } + ModelList::Unrecognized { .. } => { + Answer::NoList("上游返回的模型列表格式无法识别".to_string()) + } + ModelList::Empty => Answer::NoList("上游返回的模型列表为空".to_string()), + } +} + +/// 去问这几家,记下答案,重算汇总。**几家一起问** —— 探测互不干扰,而一家 +/// 连不上要等满超时,挨个问会让排在后面的都跟着等。 +async fn refresh(state: &AppState, names: &[String]) { + let rt = state.runtime(); + let asks = names.iter().filter_map(|name| { + let p = rt.config.providers.iter().find(|p| &p.name == name)?; + let id = identity(&rt.config, p); + let rt = &rt; + Some(async move { (p, id, ask(state, rt, p).await) }) + }); + for (p, id, answer) in futures::future::join_all(asks).await { + match &answer { + Answer::Listed(models) => { + tracing::debug!(provider = %p.name, models = models.len(), "模型清单已获取") + } + Answer::NoList(why) | Answer::Failed(why) => { + tracing::info!(provider = %p.name, "没有获取到模型清单:{why}") + } + Answer::Pending => {} + } + state.models.record(&p.name, &id, answer, now_ms()); + } + state.publish_catalog(); +} + +/// 马上向所有上游问一遍。 +pub async fn refresh_all(state: &AppState) { + let names: Vec = state + .config() + .providers + .iter() + .map(|p| p.name.clone()) + .collect(); + refresh(state, &names).await; +} + +/// 马上问这一家,返回它现在的清单。**停用了也问** —— 这是用户点的。 +pub async fn refresh_one(state: &AppState, name: &str) -> Option { + refresh(state, &[name.to_string()]).await; + let cfg = state.config(); + let p = cfg.providers.iter().find(|p| p.name == name)?; + Some(state.models.listing(p)) +} + +/// 后台:启动时问一遍,之后每天一遍;配置里新加、改了的上游随时补问。 +/// +/// **`url-test` 的垫底跟着它一起跑**:两者都是「启动时打一次网络、之后靠 +/// 真实流量」,而且都不该挡住启动。 +pub fn spawn(state: AppState) { + tokio::spawn(async move { + let mut seeded_at: Option = None; + loop { + let now = now_ms(); + if seeded_at.is_none_or(|t| now.saturating_sub(t) >= REFRESH_EVERY.as_millis() as u64) { + crate::server::seed_latency(&state).await; + seeded_at = Some(now); + } + let due = state.models.due(&state.config(), now); + if !due.is_empty() { + refresh(&state, &due).await; + } + tokio::select! { + _ = tokio::time::sleep(TICK) => {} + _ = state.models.wake.notified() => {} + } + } + }); +} + +/// 为什么跳过一个候选上游。 +#[derive(Debug, Clone, Copy, PartialEq, Eq)] +pub enum Skip { + /// 停用了 + Disabled, + /// 这个模型不在它的启用范围里 + OutOfScope, + /// 它的模型清单里没有这个模型 + NotOffered, +} + +impl Skip { + pub fn slug(&self) -> &'static str { + match self { + Skip::Disabled => "disabled", + Skip::OutOfScope => "out_of_scope", + Skip::NotOffered => "not_offered", + } + } + pub fn label(&self) -> &'static str { + match self { + Skip::Disabled => "已停用", + Skip::OutOfScope => "该模型不在启用范围内", + Skip::NotOffered => "不提供该模型", + } + } +} + +/// 路由选出的候选里,哪些能服务这个请求。 +#[derive(Debug, Clone, Default)] +pub struct Serving { + pub usable: Vec, + pub skipped: Vec<(String, Skip)>, +} + +impl Serving { + /// 一个都不剩时给客户端的那句话。 + pub fn explain(&self, model: &str) -> crate::GatewayError { + let why = self + .skipped + .iter() + .map(|(p, s)| format!("{p} {}", s.label())) + .collect::>() + .join(";"); + // 全是停用:请求没问题,是配置里能用的上游都关掉了 + if self.skipped.iter().all(|(_, s)| *s == Skip::Disabled) { + crate::GatewayError::config(format!("路由选中的上游都已停用:{why}")) + } else { + crate::GatewayError::new( + crate::error::Source::Request, + format!("没有可用的上游提供模型 `{model}`:{why}"), + ) + } + } +} + +/// 在路由选出的候选里去掉服务不了这个请求的上游。 +/// +/// **没有模型清单的上游不跳过**:不知道它有什么,不等于它没有。`model` +/// 是空的(请求体解析不了)时只看停用。 +pub fn serving( + cfg: &tw_config::Config, + catalog: &tw_engine::Catalog, + candidates: &[String], + model: &str, +) -> Serving { + let mut out = Serving::default(); + for name in candidates { + let Some(p) = cfg.providers.iter().find(|p| &p.name == name) else { + // 配置里没有这一家:留给尝试那一步报出来 + out.usable.push(name.clone()); + continue; + }; + let skip = if p.disabled { + Some(Skip::Disabled) + } else if model.is_empty() { + None + } else if !p.uses_model(model) { + Some(Skip::OutOfScope) + } else if catalog.offers(name, model) == Some(false) { + Some(Skip::NotOffered) + } else { + None + }; + match skip { + Some(s) => out.skipped.push((name.clone(), s)), + None => out.usable.push(name.clone()), + } + } + out +} + +#[cfg(test)] +mod tests { + use super::*; + + fn provider(name: &str) -> tw_config::Provider { + tw_config::Provider { + name: name.into(), + base_url: format!("https://{name}.example"), + key: "sk".into(), + ..Default::default() + } + } + + fn cfg(providers: Vec) -> tw_config::Config { + tw_config::Config { + providers, + ..Default::default() + } + } + + fn published(d: &Directory, c: &tw_config::Config) -> tw_engine::Catalog { + let into = arc_swap::ArcSwap::from_pointee(tw_engine::Catalog::default()); + let c = std::sync::Arc::new(c.clone()); + d.publish(|| c.clone(), &into); + (*into.load_full()).clone() + } + + #[test] + fn an_edit_that_does_not_change_how_to_reach_an_upstream_keeps_its_answer() { + let d = Directory::default(); + let mut c = cfg(vec![provider("a"), provider("b")]); + assert!(d.reconcile(&c)); + for p in &c.providers { + d.record( + &p.name, + &identity(&c, p), + Answer::Listed(vec![format!("{}-m", p.name)]), + 1, + ); + } + // 改计费方式、启用范围:不用重问 + c.providers[0].billing = Some(tw_config::Billing::Free); + c.providers[0].models_only = Some(vec!["a-*".into()]); + assert!(!d.reconcile(&c)); + assert_eq!(d.listing(&c.providers[0]).models, ["a-m"]); + // 改地址:重问,旧答案不再作数 + c.providers[1].base_url = "https://elsewhere.example".into(); + assert!(d.reconcile(&c)); + let l = d.listing(&c.providers[1]); + assert_eq!(l.source, Source::None); + assert_eq!(d.due(&c, 2), ["b"]); + // 删掉的上游忘掉 + c.providers.remove(0); + d.reconcile(&c); + assert!(d.lock().get("a").is_none()); + } + + #[test] + fn an_answer_for_an_upstream_that_changed_meanwhile_is_dropped() { + let d = Directory::default(); + let mut c = cfg(vec![provider("a")]); + d.reconcile(&c); + let before = identity(&c, &c.providers[0]); + c.providers[0].base_url = "https://elsewhere.example".into(); + d.reconcile(&c); + d.record("a", &before, Answer::Listed(vec!["stale".into()]), 1); + assert_eq!(d.listing(&c.providers[0]).source, Source::None); + } + + #[test] + fn the_catalog_leaves_out_disabled_upstreams_and_models_out_of_scope() { + let d = Directory::default(); + let mut c = cfg(vec![provider("a"), provider("b"), provider("c")]); + d.reconcile(&c); + for p in &c.providers { + d.record( + &p.name, + &identity(&c, p), + Answer::Listed(vec![format!("{}-1", p.name), format!("{}-2", p.name)]), + 1, + ); + } + c.providers[1].disabled = true; + c.providers[2].models_only = Some(vec!["c-1".into()]); + let cat = published(&d, &c); + assert_eq!(cat.all(), ["a-1", "a-2", "c-1"]); + let s = serving(&c, &cat, &["a".into(), "b".into(), "c".into()], "c-2"); + assert_eq!( + s.skipped, + [ + ("a".to_string(), Skip::NotOffered), + ("b".to_string(), Skip::Disabled), + ("c".to_string(), Skip::OutOfScope) + ] + ); + assert!(s.usable.is_empty()); + } + + #[test] + fn an_upstream_without_a_list_is_kept_and_a_failure_retries_sooner_than_a_day() { + let d = Directory::default(); + let c = cfg(vec![provider("a"), provider("b")]); + d.reconcile(&c); + d.record( + "a", + &identity(&c, &c.providers[0]), + Answer::Failed("连不上".into()), + 0, + ); + d.record( + "b", + &identity(&c, &c.providers[1]), + Answer::NoList("没有接口".into()), + 0, + ); + let cat = published(&d, &c); + // 不知道它们有什么:不跳过 + let s = serving(&c, &cat, &["a".into(), "b".into()], "m"); + assert_eq!(s.usable, ["a", "b"]); + // 失败的一小时后重问,没有接口的一天后 + let hour = RETRY_AFTER.as_millis() as u64; + assert_eq!(d.due(&c, hour), ["a"]); + assert_eq!(d.due(&c, REFRESH_EVERY.as_millis() as u64), ["a", "b"]); + assert_eq!( + d.listing(&c.providers[1]).error.as_deref(), + Some("没有接口") + ); + } +} diff --git a/crates/tw-gateway/src/quote.rs b/crates/tw-gateway/src/quote.rs new file mode 100644 index 00000000..a1569cef --- /dev/null +++ b/crates/tw-gateway/src/quote.rs @@ -0,0 +1,136 @@ +//! 发出一个会花钱的请求之前的报价。推理测速和回放共用。 +//! +//! **四种计费方式各说各的**,而都要给出 token 数 —— 那是唯一一个我们确定 +//! 知道的量。 + +use tw_config::Billing; + +#[derive(Debug, Clone, PartialEq)] +pub struct Quote { + /// 微分。按量计费且算得出来时是那个数;不计费时是 0。**订阅制、计费方式 + /// 未知、无法计价时是空** —— 不是 0 + pub cost_micros: Option, + pub billing: Billing, + /// 给人看的那一句。**金额再小也要显示** —— 用户按下按钮时有权知道自己在 + /// 花什么 + pub note: String, +} + +/// 这家上游跑这个模型、用这么多 token,报一个价。 +pub fn quote( + book: &tw_pricing::PriceBook, + provider: &str, + model: &str, + usage: &tw_pricing::Usage, + billing: Billing, +) -> Quote { + let tokens = usage.input + usage.output; + let (cost_micros, note) = match billing { + // **订阅制不是免费**:它不按 token 收钱,消耗的是额度 + Billing::Subscription => (None, format!("计入订阅额度,约 {tokens} tokens")), + Billing::Free => (Some(0), format!("不计费,约 {tokens} tokens")), + Billing::Unknown => ( + None, + format!("计费方式未知,无法预估费用,约 {tokens} tokens"), + ), + Billing::PerToken => match book.cost_for(provider, model, usage, false) { + tw_pricing::Cost::Known(m) | tw_pricing::Cost::Estimated(m) => { + // 五位小数:一次测速是几百微分的量级,两位小数会显示成 + // $0.00,而那等于告诉用户「这不花钱」 + (Some(m), format!("约 ${:.5}", m as f64 / 1e6)) + } + tw_pricing::Cost::Unpriced { .. } => ( + None, + format!("无法计价:`{model}` 不在价目表中,约 {tokens} tokens"), + ), + }, + }; + Quote { + cost_micros, + billing, + note, + } +} + +/// 一批报价的合计。 +/// +/// **订阅制那几项不进合计**:它们消耗的是额度,界面上单独说。以前它们和 +/// 「无法计价」一样让合计变成空 —— 于是只要勾上一家订阅制上游,用户就再也 +/// 看不到这批请求要花多少钱。 +/// +/// **其余任何一项没有金额,合计就是空**:给一个看起来完整的数字,用户会以为 +/// 那就是全部代价。 +pub fn total<'a>(quotes: impl IntoIterator) -> Option { + quotes + .into_iter() + .filter(|q| q.billing != Billing::Subscription) + .map(|q| q.cost_micros) + .sum() +} + +#[cfg(test)] +mod tests { + use super::*; + + fn book() -> tw_pricing::PriceBook { + tw_pricing::PriceBook::builtin().unwrap() + } + + fn usage() -> tw_pricing::Usage { + tw_pricing::Usage { + input: 10, + output: 8, + ..Default::default() + } + } + + #[test] + fn each_billing_mode_says_what_it_costs_and_how_many_tokens() { + let q = |b| quote(&book(), "p", "claude-sonnet-4-5", &usage(), b); + let per_token = q(Billing::PerToken); + assert!(per_token.cost_micros.unwrap() > 0); + assert!( + per_token.note.starts_with("约 $0.000"), + "{}", + per_token.note + ); + let sub = q(Billing::Subscription); + assert_eq!(sub.cost_micros, None); + assert!( + sub.note.contains("额度") && sub.note.contains("18"), + "{}", + sub.note + ); + let free = q(Billing::Free); + assert_eq!(free.cost_micros, Some(0)); + let unknown = q(Billing::Unknown); + assert_eq!(unknown.cost_micros, None); + assert!(unknown.note.contains("18"), "{}", unknown.note); + let unpriced = quote( + &book(), + "p", + "中转站自己起的名字", + &usage(), + Billing::PerToken, + ); + assert_eq!(unpriced.cost_micros, None); + assert!(unpriced.note.contains("无法计价"), "{}", unpriced.note); + } + + #[test] + fn a_subscription_stays_out_of_the_total_and_anything_else_without_an_amount_voids_it() { + let q = |m: &str, b| quote(&book(), "p", m, &usage(), b); + let priced = q("claude-sonnet-4-5", Billing::PerToken); + let sub = q("claude-sonnet-4-5", Billing::Subscription); + let free = q("claude-sonnet-4-5", Billing::Free); + assert_eq!( + total([&priced, &sub, &free]), + priced.cost_micros, + "订阅不进合计,不计费是 0" + ); + let unknown = q("claude-sonnet-4-5", Billing::Unknown); + assert_eq!(total([&priced, &unknown]), None); + let unpriced = q("中转站自己起的名字", Billing::PerToken); + assert_eq!(total([&priced, &unpriced]), None); + } +} diff --git a/crates/tw-gateway/src/server.rs b/crates/tw-gateway/src/server.rs index 9bb755ed..1c73a67d 100644 --- a/crates/tw-gateway/src/server.rs +++ b/crates/tw-gateway/src/server.rs @@ -98,32 +98,6 @@ pub fn client_for_provider( .map_err(|e| GatewayError::config(format!("HTTP 客户端建不起来:{e}"))) } -/// 目录的来源清单:每个 provider 声明了哪些模型、说什么协议。 -/// -/// **单独一个函数是为了让「上游名单变没变」有一个确切的判据**。 -/// 改一条路由规则不该重置模型目录(那会让 `/v1/models` 短暂地空一下), -/// 而删掉一个 provider 必须立刻反映(列表即承诺)。 -fn catalog_sources(cfg: &tw_config::Config) -> Vec { - cfg.providers - .iter() - .map(|p| tw_engine::ProviderModels { - provider: p.name.clone(), - protocol: p - .effective_protocol() - .map(|x| format!("{x:?}")) - // 猜不出协议时按 Anthropic 算 —— 和转发时的默认一致 - // (forward::apply_credential)。两处不一致会让「列出来了 - // 但发过去 401」变成可能。 - .unwrap_or_else(|| "Anthropic".to_string()), - models: p.models.clone(), - }) - .collect() -} - -fn catalog_from(cfg: &tw_config::Config) -> tw_engine::Catalog { - tw_engine::Catalog::build(&catalog_sources(cfg)) -} - /// 一次配置换入时**整块换掉**的那部分。 /// /// 分成「换的」和「不换的」两堆,判据是**这个东西丢了会不会让用户感觉 @@ -201,7 +175,7 @@ impl Runtime { /// /// base_url 和 key 都**不在**里面:Client 不绑 URL,凭据是每个请求现加 /// 的。把它们算进来只会让「改个 key」白白丢掉一整个连接池。 -fn proxy_shape(cfg: &tw_config::Config, p: &tw_config::Provider) -> String { +pub(crate) fn proxy_shape(cfg: &tw_config::Config, p: &tw_config::Provider) -> String { let px = cfg .proxies .iter() @@ -233,11 +207,13 @@ pub struct AppState { /// 上游健康。**不持久化**,但**跨重载存活** —— 一家刚被熔断的上游 /// 不该因为你改了条规则就立刻又被试一遍。 pub health: Arc, - /// 模型目录。**列表和准入的唯一真相来源**。 + /// 模型汇总。**列表、准入和挑候选的唯一真相来源**。 /// - /// 启动时用配置里的 `models:` 填一份,L2 探测回来后原子换入 —— - /// 探测要打网络,不能挡住启动。 + /// 从 `models` 和当前配置推出来(见 [`crate::models`]):启动时只有手写 + /// 的清单,向上游问到之后、配置换了之后都会重算。 pub catalog: Arc>, + /// 每个上游的模型清单,以及是什么时候、怎么来的。**跨重载存活** + pub models: Arc, /// 请求体和响应体往哪儿交。 /// /// **有界通道,满了就丢。**直接调用意味着文件 I/O 跑在转发那条路上 @@ -295,11 +271,12 @@ impl AppState { .build() .map_err(|e| GatewayError::config(format!("HTTP 客户端建不起来:{e}")))?; let limits = config.limits.clone(); - let catalog = catalog_from(&config); let pricing_config = config.pricing.clone(); let price_assign = config.price_assign(); + let models = Arc::new(crate::models::Directory::default()); + models.reconcile(&config); let rt = Runtime::build(config, None)?; - Ok(Self { + let state = Self { rt: Arc::new(arc_swap::ArcSwap::from_pointee(rt)), gate: Arc::new(arc_swap::ArcSwap::from_pointee(crate::limits::Gate::new( limits, @@ -307,7 +284,8 @@ impl AppState { http, bus: tw_observe::EventBus::new(), health: Arc::new(Health::new()), - catalog: Arc::new(arc_swap::ArcSwap::from_pointee(catalog)), + catalog: Arc::new(arc_swap::ArcSwap::from_pointee(Default::default())), + models, body_sink: Arc::new(std::sync::Mutex::new(None)), quotas: Arc::new(std::sync::Mutex::new(Default::default())), relisten: Arc::new(tokio::sync::Notify::new()), @@ -326,7 +304,15 @@ impl AppState { rotation_sink: Arc::new(std::sync::Mutex::new(None)), rotation_told: Arc::new(std::sync::Mutex::new(Default::default())), live: crate::live::Live::default(), - }) + }; + // 手写的清单马上可用;向上游问是后台的事,不挡启动 + state.publish_catalog(); + Ok(state) + } + + /// 按目录和当前配置重算模型汇总。 + pub(crate) fn publish_catalog(&self) { + self.models.publish(|| self.config(), &self.catalog); } /// 取这一家的密钥。**OAuth 那一类要联网换 token,所以这条路是 @@ -504,10 +490,12 @@ impl AppState { .iter() .filter_map(|name| { let p = providers.iter().find(|p| &p.name == name)?; - // **订阅制的边际成本是零,它就是最便宜的那家**。 + // **订阅制和不计费的边际成本是零,它们就是最便宜的**。 // 而「价格未知」不是「免费」 —— 它不在这张表里,排到最后去 match p.billing { - Some(tw_config::Billing::Subscription) => Some((name.clone(), (0, 0))), + Some(tw_config::Billing::Subscription | tw_config::Billing::Free) => { + Some((name.clone(), (0, 0))) + } Some(tw_config::Billing::Unknown) => None, _ => book.unit_micros(name, model).map(|u| (name.clone(), u)), } @@ -540,14 +528,7 @@ impl AppState { let old = self.rt.load(); let limits_changed = old.config.limits != config.limits; let new_limits = config.limits.clone(); - let catalog_stale = catalog_sources(&old.config) != catalog_sources(&config); let next = Runtime::build(config, Some(&old))?; - if catalog_stale { - // 上游名单变了,目录里那些属于已删上游的模型必须立刻消失 —— - // 不然 `/v1/models` 会继续列出一个已经不存在的东西,而 - // 「列表即承诺」。真正的探测在后台补。 - self.catalog.store(Arc::new(catalog_from(&next.config))); - } let relisten = old.config.listen.gateway.socket_addr() != next.config.listen.gateway.socket_addr(); // 自定义价目表和上游的选择跟着配置走,默认价目表不变 @@ -555,6 +536,12 @@ impl AppState { self.pricing .rcu(|book| book.with_config(sheets.clone(), assign.clone())); self.rt.store(Arc::new(next)); + // 模型汇总马上按新配置重算:删掉、停用的上游的模型必须立刻消失(列表 + // 即承诺),改了范围的立刻生效。新加的、地址凭据变了的在后台补问 + if self.models.reconcile(&self.config()) { + self.models.wake(); + } + self.publish_catalog(); if relisten { // 只通知,不在这里重建 —— 换监听器要 await,而这个函数被 // 文件监听那条同步路径调用。谁在监听谁去换。 @@ -1030,20 +1017,25 @@ async fn pipeline( .find(|c| c.name == client_name) .and_then(|c| c.allow.clone()); if !catalog.admits(&facts.model, Some(position.dialect()), allow.as_deref()) { - // 错误信息要说人话 —— 而不是一个干巴巴的 permission - // denied。 - return Err(GatewayError::new( - crate::error::Source::Request, + // 错误信息要说清是哪一种:没有上游提供它,和这个客户端不让用它, + // 该去改的地方不一样 + let msg = if catalog.providers_for(&facts.model).is_empty() { + format!( + "没有上游提供模型 {}。能用的模型见 GET /v1/models。", + facts.model + ) + } else { format!( "客户端 `{client_name}` 不允许使用 {}。它能用的模型见 GET /v1/models。", facts.model - ), - )); + ) + }; + return Err(GatewayError::new(crate::error::Source::Request, msg)); } } } - let decision = match rt + let mut decision = match rt .engine .route(&facts) .map_err(|e| GatewayError::config(format!("路由失败:{e}")))? @@ -1056,13 +1048,30 @@ async fn pipeline( return Err(GatewayError::denied(reason)); } }; + // 去掉服务不了这个请求的候选:停用的、范围外的、清单里没有这个模型的。 + // **在排序之前** —— `cheapest` 和 `url-test` 要在能服务的上游里挑。 + // + // 不跳过的话,一家没有这个模型的上游排在前面,它回的 404 不触发故障 + // 转移,请求就在一家能服务它的上游旁边失败了。 + let serving = crate::models::serving( + &rt.config, + &state.catalog.load(), + &decision.candidates, + &facts.model, + ); + if serving.usable.is_empty() { + return Err(serving.explain(&facts.model)); + } + if !serving.skipped.is_empty() { + tracing::debug!(skipped = ?serving.skipped, model = %facts.model, "跳过服务不了的候选"); + } + decision.candidates = serving.usable; // 策略组排序。**引擎给的是集合,顺序在这儿定** —— // 因为 `load-balance` / `url-test` / `cheapest` 都要运行时的数字, // 而路由决策本身必须是纯的、可试算的。 // // `fallback` 和 `select` 走不到这里面 —— 那是绝大多数人的配置, // 它们连一个 HashMap 都不用建。 - let mut decision = decision; if let Some(gname) = decision.via_group.clone() && let Some(kind) = rt .engine @@ -1671,17 +1680,10 @@ async fn pipeline( Ok(resp) } -/// 去问每个上游有哪些模型,把目录换掉。 -/// -/// **探测是零成本的**(L2),但它要打网络,所以在后台跑而不是 -/// 挡住启动。配置里手写的 `models:` 是它回来之前的兜底。 -/// -/// 结果缓存 24 小时 ——模型列表变化不频繁,而**每次有人调 -/// `/v1/models` 就去打上游,会把一个本该零成本的端点变成一次串行网络 -/// 往返**。 /// 给 `url-test` 组的成员垫一个底(样本不够时用零成本的 L1 补)。 /// -/// **只测 `url-test` 组里的那些,而且只在启动和换配置时测一次。** +/// **只测 `url-test` 组里的那些,启动时和之后每天各测一次**(跟着模型清单 +/// 的刷新一起跑,见 [`crate::models::spawn`])。 /// 没有这一步的话,`url-test` 在攒够真实样本之前完全等同于 `fallback` /// —— 用户配了「选最快的」,而头几十个请求全落在配置里排第一那家。 /// @@ -1701,7 +1703,13 @@ pub async fn seed_latency(state: &AppState) { return; } for name in want { - let Some(p) = rt.config.providers.iter().find(|p| p.name == name) else { + // 停用的不参与路由,用不着垫 + let Some(p) = rt + .config + .providers + .iter() + .find(|p| p.name == name && !p.disabled) + else { continue; }; // 走代理的那家要测它真正会走的那条路。`system` 测不了, @@ -1727,73 +1735,6 @@ pub async fn seed_latency(state: &AppState) { } } -pub async fn refresh_catalog(state: &AppState) { - // 探测要打网络,一轮下来可能几秒。**整轮用同一份运行时** —— 中途 - // 换了配置的话,这一轮探的是旧名单,而下面换入前会再确认一次。 - let rt = state.runtime(); - let mut sources = Vec::new(); - for p in rt.config.providers.iter() { - let protocol = p - .effective_protocol() - .map(|x| format!("{x:?}")) - .unwrap_or_else(|| "Anthropic".to_string()); - let http = rt.clients.get(&p.name).unwrap_or(&state.http); - let key = match state.key_for(p, http).await { - Ok(k) => k, - Err(e) => { - tracing::warn!(provider = %p.name, "密钥取不到,跳过探测:{e}"); - sources.push(tw_engine::ProviderModels { - provider: p.name.clone(), - protocol, - models: p.models.clone(), - }); - continue; - } - }; - let r = crate::probe::probe(http, &p.base_url, &key, p.effective_protocol()).await; - let discovered = match &r.models { - crate::probe::ModelList::Listed { models } => models.clone(), - // 探不到就用手写的兜底。**两者不合并** —— 合并的话,用户 - // 删掉一个上游不再提供的模型时会发现它删不掉。 - other => { - if !p.models.is_empty() { - tracing::debug!(provider = %p.name, ?other, "用配置里手写的模型清单"); - } else { - tracing::info!( - provider = %p.name, ?other, - "这家没给模型列表,也没写 models: 兜底 —— 它的模型不会出现在 /v1/models 里" - ); - } - p.models.clone() - } - }; - sources.push(tw_engine::ProviderModels { - provider: p.name.clone(), - protocol, - models: discovered, - }); - } - let total: usize = sources.iter().map(|s| s.models.len()).sum(); - state - .catalog - .store(Arc::new(tw_engine::Catalog::build(&sources))); - tracing::info!(providers = sources.len(), models = total, "模型目录已刷新"); -} - -/// 后台刷新循环。 -/// -/// **`url-test` 的垫底跟着它一起跑**:两者都是「启动时打一次网络、 -/// 之后靠真实流量」,而且都不该挡住启动。 -pub fn spawn_catalog_refresh(state: AppState) { - tokio::spawn(async move { - loop { - seed_latency(&state).await; - refresh_catalog(&state).await; - tokio::time::sleep(std::time::Duration::from_secs(24 * 3600)).await; - } - }); -} - /// 起服务。返回实际绑定的地址 —— 端口写 0 时调用方需要知道拿到了哪个。 pub async fn serve(state: AppState, addr: std::net::SocketAddr) -> std::io::Result<()> { serve_once(state, addr, std::future::pending()).await diff --git a/crates/tw-gateway/tests/models.rs b/crates/tw-gateway/tests/models.rs new file mode 100644 index 00000000..93297b8f --- /dev/null +++ b/crates/tw-gateway/tests/models.rs @@ -0,0 +1,291 @@ +//! 每个上游提供哪些模型,以及路由怎么用这件事。 +//! +//! 假上游会回答 `GET /v1/models`,并在响应里说出自己是谁 —— 断言落在 +//! 「请求真的落在了哪一家」上。 + +use std::net::SocketAddr; +use std::time::Duration; + +use axum::Router; +use axum::routing::{get, post}; +use tw_config::{Client, Config, Provider}; + +/// 一个假上游:列出 `models`,只接受这些模型的请求,其余回 404。 +async fn upstream(name: &'static str, models: &'static [&'static str]) -> SocketAddr { + let app = Router::new() + .route( + "/v1/models", + get(move || async move { + axum::Json(serde_json::json!({ + "data": models.iter().map(|m| serde_json::json!({ "id": m })).collect::>() + })) + }), + ) + .route( + "/v1/messages", + post(move |body: axum::body::Bytes| async move { + let v: serde_json::Value = serde_json::from_slice(&body).unwrap_or_default(); + let model = v["model"].as_str().unwrap_or_default().to_string(); + if models.contains(&model.as_str()) { + ( + axum::http::StatusCode::OK, + axum::Json(serde_json::json!({ "by": name, "model": model })), + ) + } else { + // 中转站对它没有的模型就是这么回的:一个 4xx,不会触发故障转移 + ( + axum::http::StatusCode::NOT_FOUND, + axum::Json(serde_json::json!({ + "type": "error", + "error": { "type": "not_found_error", "message": format!("model: {model}") } + })), + ) + } + }), + ); + let l = tokio::net::TcpListener::bind("127.0.0.1:0").await.unwrap(); + let a = l.local_addr().unwrap(); + tokio::spawn(async move { axum::serve(l, app).await.unwrap() }); + a +} + +fn provider(name: &str, at: SocketAddr) -> Provider { + Provider { + name: name.into(), + base_url: format!("http://{at}"), + key: "k".into(), + protocol: Some(tw_config::Protocol::Anthropic), + ..Default::default() + } +} + +fn config(providers: Vec) -> Config { + Config { + clients: vec![Client { + name: "c".into(), + key: "tw-k".into(), + ..Default::default() + }], + providers, + ..Default::default() + } +} + +/// 所有上游进一个按顺序尝试的组,默认路由走这个组。 +fn grouped(mut cfg: Config, order: &[&str]) -> Config { + cfg.groups = vec![ + serde_yaml_ng::from_str(&format!( + "name: pool\ntype: fallback\nproviders: [{}]\n", + order.join(", ") + )) + .unwrap(), + ]; + cfg.routes = vec![tw_engine::RouteSet::default_with(vec![tw_engine::Rule { + name: "全部".into(), + when: Default::default(), + to: Some("pool".into()), + set: None, + deny: None, + guard: None, + }])]; + cfg +} + +async fn serve(state: tw_gateway::AppState) -> SocketAddr { + let addr = { + let l = tokio::net::TcpListener::bind("127.0.0.1:0").await.unwrap(); + l.local_addr().unwrap() + }; + let s = state.clone(); + tokio::spawn(async move { tw_gateway::serve(s, addr).await.unwrap() }); + tokio::time::sleep(Duration::from_millis(50)).await; + addr +} + +async fn ask(gw: SocketAddr, model: &str) -> (u16, serde_json::Value) { + let r = reqwest::Client::new() + .post(format!("http://{gw}/v1/messages")) + .header("x-api-key", "tw-k") + .body(serde_json::json!({ "model": model, "messages": [] }).to_string()) + .send() + .await + .unwrap(); + let status = r.status().as_u16(); + (status, r.json().await.unwrap_or_default()) +} + +async fn listed(gw: SocketAddr) -> Vec { + let v: serde_json::Value = reqwest::Client::new() + .get(format!("http://{gw}/v1/models")) + .header("x-api-key", "tw-k") + .send() + .await + .unwrap() + .json() + .await + .unwrap(); + v["data"] + .as_array() + .unwrap() + .iter() + .map(|m| m["id"].as_str().unwrap().to_string()) + .collect() +} + +/// 等到 `/v1/models` 列出 `model`。 +async fn until_listed(gw: SocketAddr, model: &str) -> bool { + let deadline = std::time::Instant::now() + Duration::from_secs(5); + while std::time::Instant::now() < deadline { + if listed(gw).await.iter().any(|m| m == model) { + return true; + } + tokio::time::sleep(Duration::from_millis(20)).await; + } + false +} + +// ─────────────────────────────────────────────────────────── 改配置之后 + +#[tokio::test] +async fn adding_an_upstream_keeps_what_was_discovered_and_lists_the_new_one_promptly() { + let a = upstream("a", &["a-model"]).await; + let b = upstream("b", &["b-model"]).await; + // 手写清单的那一家:让目录在改配置之后不是空的(空目录不做准入检查) + let mut manual = provider("manual", a); + manual.models = vec!["manual-model".into()]; + let cfg = config(vec![provider("a", a), manual]); + let state = tw_gateway::AppState::new(cfg.clone()).unwrap(); + tw_gateway::models::spawn(state.clone()); + let gw = serve(state.clone()).await; + assert!(until_listed(gw, "a-model").await, "启动之后没探到 a 的模型"); + + let mut next = cfg.clone(); + next.providers.push(provider("b", b)); + state.reload(next).unwrap(); + + // 已经探到的模型不能因为别处改了配置就消失 + let (status, body) = ask(gw, "a-model").await; + assert_eq!(status, 200, "改配置之后 a 的模型被拒了:{body}"); + // 新加的上游不用等到明天 + assert!(until_listed(gw, "b-model").await, "{:?}", listed(gw).await); + let (status, body) = ask(gw, "b-model").await; + assert_eq!(status, 200, "{body}"); +} + +// ─────────────────────────────────────────────────────────── 路由 + +#[tokio::test] +async fn a_group_skips_an_upstream_that_does_not_offer_the_model() { + // relay 排在前面,但它没有这个模型。它回的 404 不会触发故障转移, + // 所以不跳过它的话,这个请求在一家能服务它的上游就在旁边时失败 + let relay = upstream("relay", &["shared"]).await; + let official = upstream("official", &["shared", "official-only"]).await; + let cfg = grouped( + config(vec![ + provider("relay", relay), + provider("official", official), + ]), + &["relay", "official"], + ); + let state = tw_gateway::AppState::new(cfg).unwrap(); + tw_gateway::models::refresh_all(&state).await; + let gw = serve(state).await; + + let (status, body) = ask(gw, "official-only").await; + assert_eq!(status, 200, "{body}"); + assert_eq!(body["by"], "official"); + // 两家都有的还是按组里的顺序 + let (_, body) = ask(gw, "shared").await; + assert_eq!(body["by"], "relay"); +} + +#[tokio::test] +async fn a_disabled_upstream_takes_no_requests_and_lists_nothing() { + let relay = upstream("relay", &["shared", "relay-only"]).await; + let official = upstream("official", &["shared"]).await; + let mut cfg = grouped( + config(vec![ + provider("relay", relay), + provider("official", official), + ]), + &["relay", "official"], + ); + cfg.providers[0].disabled = true; + let state = tw_gateway::AppState::new(cfg.clone()).unwrap(); + tw_gateway::models::refresh_all(&state).await; + let gw = serve(state.clone()).await; + + let (status, body) = ask(gw, "shared").await; + assert_eq!(status, 200, "{body}"); + assert_eq!(body["by"], "official"); + assert_eq!(listed(gw).await, ["shared"], "停用的上游的模型还在列表里"); + + // 组里的都停了:说清是配置的事,而不是请求写错了 + let mut all_off = cfg.clone(); + all_off.providers[1].disabled = true; + state.reload(all_off).unwrap(); + let (status, body) = ask(gw, "shared").await; + assert_eq!(status, 500, "{body}"); + let msg = body["error"]["message"].as_str().unwrap(); + assert!(msg.contains("已停用") && msg.contains("official"), "{msg}"); +} + +#[tokio::test] +async fn a_model_outside_an_upstreams_scope_is_not_listed_or_sent_there() { + let relay = upstream("relay", &["scoped", "other"]).await; + let official = upstream("official", &["other"]).await; + let mut cfg = grouped( + config(vec![ + provider("relay", relay), + provider("official", official), + ]), + &["relay", "official"], + ); + cfg.providers[0].models_only = Some(vec!["scop*".into()]); + let state = tw_gateway::AppState::new(cfg).unwrap(); + tw_gateway::models::refresh_all(&state).await; + let gw = serve(state).await; + + assert_eq!(listed(gw).await, ["other", "scoped"]); + let (_, body) = ask(gw, "scoped").await; + assert_eq!(body["by"], "relay"); + // relay 也有 other,但不在它的范围里 + let (_, body) = ask(gw, "other").await; + assert_eq!(body["by"], "official"); +} + +#[tokio::test] +async fn when_no_candidate_serves_the_model_the_error_names_each_one_and_why() { + let relay = upstream("relay", &["relay-only"]).await; + let official = upstream("official", &["official-only"]).await; + let mut cfg = config(vec![ + provider("relay", relay), + provider("official", official), + ]); + // 这条规则只把请求交给 relay + cfg.routes = vec![tw_engine::RouteSet::default_with(vec![tw_engine::Rule { + name: "都给 relay".into(), + when: Default::default(), + to: Some("relay".into()), + set: None, + deny: None, + guard: None, + }])]; + let state = tw_gateway::AppState::new(cfg).unwrap(); + tw_gateway::models::refresh_all(&state).await; + let gw = serve(state).await; + + let (status, body) = ask(gw, "official-only").await; + assert_eq!(status, 400, "{body}"); + let msg = body["error"]["message"].as_str().unwrap(); + assert!( + msg.contains("official-only") && msg.contains("relay 不提供该模型"), + "{msg}" + ); + + // 没有任何上游提供的模型:准入就拦下,而不是说客户端不允许 + let (status, body) = ask(gw, "nobody-has-this").await; + assert_eq!(status, 400, "{body}"); + let msg = body["error"]["message"].as_str().unwrap(); + assert!(msg.contains("没有上游提供模型"), "{msg}"); +} diff --git a/crates/tw-store/src/recorder.rs b/crates/tw-store/src/recorder.rs index 92fdd335..7c48192f 100644 --- a/crates/tw-store/src/recorder.rs +++ b/crates/tw-store/src/recorder.rs @@ -453,10 +453,13 @@ impl Recorder { // 撒谎。 // **不引 tw-config** —— 存储层不该知道配置的形状。这个 // 字符串是事件契约的一部分,比较它就够了。 - let counts_toward_money = p.billing.is_empty() || p.billing == "per-token"; + // // **订阅型不按价目表算钱。**订阅制的边际成本是零,按 API // 价目表乘出来的数字是纯虚构的 —— 而它会混进 - // 「今日花费」里,把一个诚实的面板变成一个编出来的。 + // 「今日花费」里,把一个诚实的面板变成一个编出来的。计费方式未知的 + // 同样不算。**不计费的记 $0**:那是一个确定的数,和订阅不是一回事。 + let counts_toward_money = p.billing.is_empty() || p.billing == "per-token"; + let free = p.billing == "free"; // // **没跑完的一律按估算记**(取消、失败)。输出只算到断开那一刻,而 // Anthropic 在流的末尾才报累计输出 —— 断在中间时手里那个数是个 @@ -470,6 +473,7 @@ impl Recorder { None }; let cost = match (&u, &resolved) { + _ if free => Some(Cost::Known(0)), (Some(u), Some(r)) => Some(r.cost(u, partial)), _ => None, }; @@ -991,6 +995,22 @@ mod billing_tests { assert_eq!(row.billing, "subscription"); } + #[test] + fn a_free_call_costs_exactly_zero_rather_than_nothing() { + // 「不计费」和「订阅」在费用栏上是两句不同的话:$0 是一个确定的数, + // 能进合计;订阅那一栏说的是这笔账不在金额这个维度上 + let (_d, mut r) = rec(); + r.on_event(&started(1, "claude-sonnet-4-5")); + r.on_event(&routed(1, "free")); + r.on_event(&finished(1, usage())); + let row = r.db().get(1).unwrap().unwrap(); + assert_eq!(row.cost_micros, Some(0)); + assert!(!row.cost_estimated); + assert_eq!(row.price_source, None, "没有按任何价目表算"); + let s = r.db().summary(0, i64::MAX).unwrap(); + assert_eq!((s.unpriced_requests, s.subscription_requests), (0, 0)); + } + #[test] fn a_per_token_call_next_to_it_still_gets_priced() { let (_d, mut r) = rec(); From d80d96f89e33c36b332d59cb33b307dc166090a4 Mon Sep 17 00:00:00 2001 From: fylorn <249551762+fylorn@users.noreply.github.com> Date: Thu, 17 Sep 2026 12:55:29 +0800 Subject: [PATCH 2/2] chore: 0.2.0 Co-Authored-By: Claude Opus 5 --- Cargo.lock | 40 ++++++++++++++++++++-------------------- Cargo.toml | 2 +- 2 files changed, 21 insertions(+), 21 deletions(-) diff --git a/Cargo.lock b/Cargo.lock index 5847388c..ba5663d7 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -2775,7 +2775,7 @@ dependencies = [ [[package]] name = "tw-adopt" -version = "0.1.2" +version = "0.2.0" dependencies = [ "serde", "serde_json", @@ -2789,7 +2789,7 @@ dependencies = [ [[package]] name = "tw-api" -version = "0.1.2" +version = "0.2.0" dependencies = [ "serde", "serde_json", @@ -2797,7 +2797,7 @@ dependencies = [ [[package]] name = "tw-config" -version = "0.1.2" +version = "0.2.0" dependencies = [ "blake3", "notify", @@ -2817,7 +2817,7 @@ dependencies = [ [[package]] name = "tw-control" -version = "0.1.2" +version = "0.2.0" dependencies = [ "axum", "bytes", @@ -2852,7 +2852,7 @@ dependencies = [ [[package]] name = "tw-crypto" -version = "0.1.2" +version = "0.2.0" dependencies = [ "aes-gcm", "anyhow", @@ -2864,7 +2864,7 @@ dependencies = [ [[package]] name = "tw-dialect" -version = "0.1.2" +version = "0.2.0" dependencies = [ "serde", "serde_json", @@ -2872,7 +2872,7 @@ dependencies = [ [[package]] name = "tw-engine" -version = "0.1.2" +version = "0.2.0" dependencies = [ "serde", "serde_json", @@ -2884,7 +2884,7 @@ dependencies = [ [[package]] name = "tw-gateway" -version = "0.1.2" +version = "0.2.0" dependencies = [ "arc-swap", "async-stream", @@ -2924,7 +2924,7 @@ dependencies = [ [[package]] name = "tw-observe" -version = "0.1.2" +version = "0.2.0" dependencies = [ "tokio", "tracing", @@ -2933,7 +2933,7 @@ dependencies = [ [[package]] name = "tw-pricing" -version = "0.1.2" +version = "0.2.0" dependencies = [ "arc-swap", "flate2", @@ -2945,7 +2945,7 @@ dependencies = [ [[package]] name = "tw-protocol" -version = "0.1.2" +version = "0.2.0" dependencies = [ "bytes", "futures", @@ -2957,7 +2957,7 @@ dependencies = [ [[package]] name = "tw-provider" -version = "0.1.2" +version = "0.2.0" dependencies = [ "async-stream", "aws-credential-types", @@ -2982,7 +2982,7 @@ dependencies = [ [[package]] name = "tw-redact" -version = "0.1.2" +version = "0.2.0" dependencies = [ "base64", "serde", @@ -2992,7 +2992,7 @@ dependencies = [ [[package]] name = "tw-resil" -version = "0.1.2" +version = "0.2.0" dependencies = [ "futures", "metrics", @@ -3005,7 +3005,7 @@ dependencies = [ [[package]] name = "tw-scan" -version = "0.1.2" +version = "0.2.0" dependencies = [ "notify", "regex", @@ -3022,14 +3022,14 @@ dependencies = [ [[package]] name = "tw-secret" -version = "0.1.2" +version = "0.2.0" dependencies = [ "thiserror", ] [[package]] name = "tw-store" -version = "0.1.2" +version = "0.2.0" dependencies = [ "bytes", "libc", @@ -3047,7 +3047,7 @@ dependencies = [ [[package]] name = "tw-types" -version = "0.1.2" +version = "0.2.0" dependencies = [ "serde", "serde_json", @@ -3056,7 +3056,7 @@ dependencies = [ [[package]] name = "tw-yaml" -version = "0.1.2" +version = "0.2.0" dependencies = [ "saphyr-parser", "serde_yaml_ng", @@ -3065,7 +3065,7 @@ dependencies = [ [[package]] name = "twcore" -version = "0.1.2" +version = "0.2.0" dependencies = [ "anyhow", "chrono", diff --git a/Cargo.toml b/Cargo.toml index 9c57f8f7..44f65c5e 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -38,7 +38,7 @@ repository = "https://github.com/ThinkWatchProject/ThinkWatch-Core" # 二进制走 CalVer,crate 走 SemVer —— 两者是两回事,卖给不同的人。 # 这里是 crate 的版本。 -version = "0.1.2" +version = "0.2.0" [workspace.dependencies] # ── 内部 crate ───────────────────────────────────────────