From 21845172abe49eacdc040fbf21b13b70883415da Mon Sep 17 00:00:00 2001 From: fylorn <249551762+fylorn@users.noreply.github.com> Date: Sat, 10 Oct 2026 22:27:28 +0800 Subject: [PATCH] feat(gateway): read each upstream's balance Users of relays and pay-as-you-go keys want to see what is left before a request fails for lack of money. Each upstream now has a balance read from its own balance endpoint, with its own key and proxy: - openrouter (key limit, or account credits when the key has none), deepseek, moonshot, sub2api (quota/rate limits, subscription windows, wallet, today's cost), newapi (quota, or what an unlimited key spent), and thinkwatch (an enterprise gateway's per-key windows and the month's cost). - `providers[].balance` picks the source; `auto`, the default, knows the OpenRouter, DeepSeek and Moonshot hosts and asks any other relay once which kind it is. The answer stays in memory; it is never written to config. ChatGPT and Z.ai accounts and Bedrock have their quota elsewhere and never read a balance. - Reads happen at start, at most once a minute after a request through the upstream ends (a guard dropped with the response body or the WebSocket turn, so a client disconnect counts too), every ten minutes otherwise, and on demand. A failed read keeps the last good reading and records why. Reading never touches forwarding. Protocol 46: `ProviderView.balance` and `balance_setting`, `ProviderInput.balance`, `ProviderTestResult.balance` ("Check connection" reads it too), the `balance_updated` event and `POST /providers/{name}/balance/refresh`. An unknown `balance:` value is refused like every other closed set (`config.unknown_variant`), which keeps the line number and lets the safe-mode repair put it back to `auto`. Co-Authored-By: Claude Opus 5.5 --- bin/twcore/src/main.rs | 2 + crates/tw-api/msg-codes.txt | 7 + crates/tw-api/src/ep.rs | 3 + crates/tw-api/src/lib.rs | 191 ++++- crates/tw-config/src/lib.rs | 55 ++ crates/tw-config/src/reload.rs | 63 ++ crates/tw-config/tests/manual/schema.rs | 12 + crates/tw-control/src/lib.rs | 2 + crates/tw-control/src/resources.rs | 32 + crates/tw-control/tests/resources.rs | 183 +++++ crates/tw-gateway/src/balances.rs | 479 +++++++++++ crates/tw-gateway/src/balances/parse.rs | 753 ++++++++++++++++++ crates/tw-gateway/src/balances/tracker.rs | 505 ++++++++++++ crates/tw-gateway/src/egress.rs | 11 + crates/tw-gateway/src/lib.rs | 1 + .../tw-gateway/src/server/pipeline/relay.rs | 3 + crates/tw-gateway/src/state.rs | 5 + crates/tw-gateway/src/state/balances.rs | 249 ++++++ crates/tw-gateway/src/ws/turn.rs | 3 + crates/tw-gateway/tests/balances.rs | 383 +++++++++ crates/tw-observe/src/bus.rs | 1 + crates/tw-store/src/recorder.rs | 2 + docs/config.md | 1 + docs/config.zh-CN.md | 1 + scripts/smoke.sh | 5 + 25 files changed, 2951 insertions(+), 1 deletion(-) create mode 100644 crates/tw-gateway/src/balances.rs create mode 100644 crates/tw-gateway/src/balances/parse.rs create mode 100644 crates/tw-gateway/src/balances/tracker.rs create mode 100644 crates/tw-gateway/src/state/balances.rs create mode 100644 crates/tw-gateway/tests/balances.rs diff --git a/bin/twcore/src/main.rs b/bin/twcore/src/main.rs index d759d16d..f85aab7f 100644 --- a/bin/twcore/src/main.rs +++ b/bin/twcore/src/main.rs @@ -984,6 +984,8 @@ fn cmd_serve(path: &Path, port: Option, safe: bool, parent: Option) -> // 模型目录:后台去问每个上游有哪些模型。**不挡启动** —— // 探测要打网络,而网关不该因为一次探测慢而起不来。 tw_gateway::models::spawn(state.clone()); + // 余额:启动时读一遍,之后按节奏读(见 `tw_gateway::balances`)。**不挡启动,不挡转发** + tw_gateway::balances::spawn(state.clone()); tracing::info!(listen = %listen_at, "starting"); tokio::select! { diff --git a/crates/tw-api/msg-codes.txt b/crates/tw-api/msg-codes.txt index c2d8eaab..fc92533d 100644 --- a/crates/tw-api/msg-codes.txt +++ b/crates/tw-api/msg-codes.txt @@ -121,6 +121,7 @@ control.account_service_refused control.account_service_status control.api_key_empty control.bad_idempotency_key +control.balance_none control.base_url_empty control.builtin_group_fixed control.callback_ports_busy @@ -275,6 +276,12 @@ gw.auth.key_invalid gw.auth.no_key gw.auth.source_not_allowed gw.auth.source_not_allowed_hint +gw.balance.connect +gw.balance.rejected +gw.balance.request_failed +gw.balance.status +gw.balance.timeout +gw.balance.unrecognized gw.busy_all gw.busy_upstream gw.chatgpt.token_missing diff --git a/crates/tw-api/src/ep.rs b/crates/tw-api/src/ep.rs index 0d3dcbc8..78369172 100644 --- a/crates/tw-api/src/ep.rs +++ b/crates/tw-api/src/ep.rs @@ -117,6 +117,9 @@ endpoints! { /// 模型,和列出的一样算这家提供。**不在 `/providers/` 底下**,同上 SetManualModels: PUT "/provider-manual-models", api::ManualModelsSave => api::ConfigWritten; RefreshProviderModels: POST "/providers/{name}/models/refresh" [name], () => api::ProviderModelsView; + /// 马上读一次这家的余额(`balance` 是 `auto` 时先认出是哪一种中转站)。没有余额可读的 + /// 是 404(`control.balance_none`) + RefreshBalance: POST "/providers/{name}/balance/refresh" [name], () => api::Balance; RefreshStaleModels: POST "/models/refresh", () => api::ModelsRefreshing; CreateProxy: POST "/proxies", api::ProxySave => api::ConfigWritten; TestProxy: POST "/proxy-test", api::ProxyTest => api::L1Result; diff --git a/crates/tw-api/src/lib.rs b/crates/tw-api/src/lib.rs index da222dea..ecc6ca6e 100644 --- a/crates/tw-api/src/lib.rs +++ b/crates/tw-api/src/lib.rs @@ -885,7 +885,17 @@ pub const MSG_CODES: &str = include_str!("../msg-codes.txt"); /// 请求体没存下来、已经清掉、只存了开头或读不懂的,`kept` 是 false、`parts` 是 null。 /// 会话不存在是 404(`control.session_not_found`),那一轮不在这次会话里也是 404 /// (`control.request_not_found`)。照 44 写的界面读不到 `context_window`。 -pub const CONTROL_API_VERSION: u32 = 45; +/// +/// **46 起上游有余额**:[`ProviderView`] 多了 `balance`([`Balance`]:钱包余额、总额度、 +/// 时间窗口额度(企业网关的带着管的是密钥还是用户)、到期时刻、花了多少,和最近一次没读成 +/// 的原因;没有余额可读是 null) +/// 和 `balance_setting`(配置里的 `balance:`,[`BalanceSetting`]);[`ProviderInput`] 多了 +/// `balance`(不给是 `auto`),[`ProviderTestResult`] 多了 `balance`(检测时顺带读一次)。 +/// 新事件 [`Event::BalanceUpdated`]:一家的余额读过了,重读它的视图。新端点 +/// `POST /providers/{name}/balance/refresh`(→ [`Balance`])马上读一次;没有余额可读是 404 +/// (`control.balance_none`)。读失败的原因是 `gw.balance.*`。配置里的 `balance:` 写了不认识的 +/// 取值时加载不了(`config.unknown_variant`,一键修复改回 `auto`)。照 45 写的界面不认这个事件。 +pub const CONTROL_API_VERSION: u32 = 46; #[derive(Debug, Clone, Serialize, Deserialize)] #[cfg_attr(feature = "ts", derive(ts_rs::TS))] @@ -1479,6 +1489,14 @@ pub enum Event { resets_at_ms: Option, at_ms: u64, }, + /// 一家上游的余额读过了一次:读到了、读失败了,或者不再有余额可读。 + /// + /// **不带余额本身**:现状在 [`ProviderView::balance`] 里,收到它就重读那一家。 + BalanceUpdated { + id: u64, + provider: String, + at_ms: u64, + }, /// 一把网关密钥这一期(天、周、月)的用量到了一条上限的八成,或者到了上限。 /// /// **每一期、每一档只报一次**:同一期里之后的请求照样被拒,同一句话说第二遍只会 @@ -1867,6 +1885,7 @@ impl Event { | Event::ConfigRejected { id, .. } | Event::QuotaSeen { id, .. } | Event::QuotaExhausted { id, .. } + | Event::BalanceUpdated { id, .. } | Event::KeyLimitAlert { id, .. } | Event::SecretsFound { id, .. } | Event::ContentMatched { id, .. } @@ -2231,6 +2250,12 @@ pub struct ProviderView { /// 同时最多发给这家几个请求。不限是空 #[serde(default, skip_serializing_if = "Option::is_none")] pub max_concurrent: Option, + /// 配置里的 `balance:`,原样:编辑对话框保存时交回去([`ProviderInput::balance`]) + pub balance_setting: BalanceSetting, + /// 最近一次读到的余额。**是空的:这家没有余额可读**(关掉了、账号上游和 Bedrock、 + /// 认不出是哪一种中转站),或者还没读完第一次。读到了、读失败了都报 + /// [`Event::BalanceUpdated`] + pub balance: Option, } /// 一行请求头,配置里写的原样。 @@ -2684,6 +2709,9 @@ pub struct ProviderTestResult { pub via: Option, /// 失败的原因,和下一步该查什么 pub error: Option, + /// 顺带读到的余额(`balance` 是 `auto` 时先认出是哪一种中转站)。没有余额可读、 + /// 检测没通过时是空 + pub balance: Option, } /// L1 测速:只握手,不发业务请求。**零成本零副作用**。 @@ -3174,6 +3202,9 @@ pub struct ProviderInput { /// 停用 #[serde(default)] pub disabled: bool, + /// 余额从哪儿读。不给就是 `auto` + #[serde(default, skip_serializing_if = "Option::is_none")] + pub balance: Option, } /// 按接口地址自动识别的结果。给编辑中、还没保存的上游显示「自动识别」 @@ -4704,6 +4735,148 @@ pub struct ProviderQuota { pub windows: Vec, } +// ---------------------------------------------------------------- 余额 + +slug_enum! { + /// 上游的余额从哪个接口读。每一种都用这家上游自己的密钥、走它自己的出站设置。 + pub enum BalanceSource { + /// OpenRouter:这把密钥的额度(`/api/v1/key`),没有额度时是账户余额(`/api/v1/credits`) + Openrouter = "openrouter", + /// DeepSeek 开放平台的账户余额(`/user/balance`) + Deepseek = "deepseek", + /// Moonshot(Kimi)开放平台的可用余额(`/v1/users/me/balance`) + Moonshot = "moonshot", + /// Sub2API 中转站的用量接口(`/v1/usage`) + Sub2api = "sub2api", + /// New API / One API 中转站的账单接口(`/v1/dashboard/billing/...`) + Newapi = "newapi", + /// ThinkWatch 企业网关的密钥用量接口(`/v1/usage`) + Thinkwatch = "thinkwatch", + } +} + +slug_enum! { + /// 一家上游的 `balance:` 写的是什么。 + pub enum BalanceSetting { + /// 默认:官方地址按主机认,别的地址问一次它是哪一种中转站(结果只在内存里) + Auto = "auto", + /// 不读余额 + Off = "off", + Openrouter = "openrouter", + Deepseek = "deepseek", + Moonshot = "moonshot", + Sub2api = "sub2api", + Newapi = "newapi", + Thinkwatch = "thinkwatch", + } +} + +impl BalanceSetting { + /// 写明了的来源。`auto` 和 `off` 没有 + pub fn source(self) -> Option { + match self { + Self::Auto | Self::Off => None, + Self::Openrouter => Some(BalanceSource::Openrouter), + Self::Deepseek => Some(BalanceSource::Deepseek), + Self::Moonshot => Some(BalanceSource::Moonshot), + Self::Sub2api => Some(BalanceSource::Sub2api), + Self::Newapi => Some(BalanceSource::Newapi), + Self::Thinkwatch => Some(BalanceSource::Thinkwatch), + } + } +} + +/// 一家上游的余额:最近一次从它的余额接口读到的。**每个数都是上游给的**,没有一个是 +/// 我们按请求记录推算的。 +/// +/// 读失败了 `error` 是原因,**其余字段留着上一次读到的**(从没读到过就是空的), +/// `read_at_ms` 也还是那一次的。 +#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)] +#[cfg_attr(feature = "ts", derive(ts_rs::TS))] +pub struct Balance { + pub source: BalanceSource, + /// 这些数是什么时候读到的,Unix 毫秒。从没读到过时是最近一次去读的时刻 + pub read_at_ms: u64, + /// 还能花的钱:账户余额、钱包余额 + pub wallet: Option, + /// 一笔总的额度和用了多少:密钥的额度、套餐的总额 + pub quota: Option, + /// 按时间窗口算的额度,每个窗口一项。没有是空的 + pub windows: Vec, + /// 密钥或套餐什么时候到期,Unix 毫秒。不会到期、上游没说都是空 + pub expires_at_ms: Option, + /// 已经花了多少,和算的是哪一段时间:没有上限可比时说得出的就是它(New API 不限 + /// 额度的密钥、Sub2API 今天的花费、企业网关这个月的花费) + pub spent: Option, + /// 最近一次没读成的原因。读成了是空 + pub error: Option, +} + +/// 一笔钱。 +#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)] +#[cfg_attr(feature = "ts", derive(ts_rs::TS))] +pub struct Money { + pub amount: f64, + /// `USD`、`CNY` 这样的货币代码,上游怎么写就是什么 + pub currency: String, +} + +slug_enum! { + /// 花费算的是哪一段时间。 + pub enum SpentPeriod { + Today = "today", + Month = "month", + /// 从来一共 + Total = "total", + } +} + +/// 已经花掉的一笔钱。 +#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)] +#[cfg_attr(feature = "ts", derive(ts_rs::TS))] +pub struct Spent { + pub amount: f64, + pub currency: String, + pub period: SpentPeriod, +} + +slug_enum! { + /// 企业网关的一条限额管的是谁。 + pub enum BalanceScope { + /// 这把密钥自己的 + Key = "key", + /// 密钥所属的用户的:同一个用户的几把密钥合在一起算 + User = "user", + } +} + +/// 一笔总的额度。 +#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)] +#[cfg_attr(feature = "ts", derive(ts_rs::TS))] +pub struct BalanceQuota { + pub limit: f64, + pub used: f64, + /// `USD` / `CNY` / `tokens` / `requests` + pub unit: String, +} + +/// 一个时间窗口里的额度。 +#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)] +#[cfg_attr(feature = "ts", derive(ts_rs::TS))] +pub struct BalanceWindow { + /// `5h` / `1d` / `7d` / `30d` / `daily` / `weekly` / `monthly`(企业网关还有 `1m`、`5m`、 + /// `1h`、`1w`),上游怎么叫就是什么 + pub window: String, + pub limit: f64, + pub used: f64, + /// `USD` / `CNY` / `tokens` / `requests` + pub unit: String, + /// 什么时候重置,Unix 毫秒。上游没说是空 + pub resets_at_ms: Option, + /// 管的是谁:这把密钥,还是它所属的用户。只有企业网关说,别的来源是空 + pub scope: Option, +} + // ---------------------------------------------------------------- ChatGPT 账号 /// 发起 ChatGPT 登录(`POST /chatgpt/login`)。 @@ -6427,6 +6600,22 @@ mod tests { assert!(from("no-such-word").is_none()); } check(Billing::ALL, Billing::slug, Billing::from_slug); + check( + BalanceSource::ALL, + BalanceSource::slug, + BalanceSource::from_slug, + ); + check( + BalanceSetting::ALL, + BalanceSetting::slug, + BalanceSetting::from_slug, + ); + check(SpentPeriod::ALL, SpentPeriod::slug, SpentPeriod::from_slug); + check( + BalanceScope::ALL, + BalanceScope::slug, + BalanceScope::from_slug, + ); check(Protocol::ALL, Protocol::slug, Protocol::from_slug); check(Dialect::ALL, Dialect::slug, Dialect::from_slug); check(ProxyKind::ALL, ProxyKind::slug, ProxyKind::from_slug); diff --git a/crates/tw-config/src/lib.rs b/crates/tw-config/src/lib.rs index 32d48cf4..967280b9 100644 --- a/crates/tw-config/src/lib.rs +++ b/crates/tw-config/src/lib.rs @@ -194,6 +194,7 @@ impl Default for Provider { model_specs: std::collections::BTreeMap::new(), max_concurrent: None, disabled: false, + balance: BalanceSetting::Auto, } } } @@ -844,6 +845,60 @@ pub struct Provider { /// `/v1/models` 里。要暂时不用一家上游时,比删掉再重新填一遍凭据好。 #[serde(default, skip_serializing_if = "is_default")] pub disabled: bool, + /// 余额从哪儿读,见 [`BalanceSetting`]。不写就是 `auto` + #[serde(default, skip_serializing_if = "is_default")] + pub balance: BalanceSetting, +} + +/// 一家上游的余额从哪儿读。 +/// +/// **`auto` 不写进配置**:官方地址按主机认(OpenRouter、DeepSeek、Moonshot),别的地址由 +/// 网关问一次它是哪一种中转站,认出来的只记在内存里。向导按用户选的那一项写明来源, +/// 就不用再问。ChatGPT、Z.ai 账号和 Bedrock 不读余额,写了什么都一样:它们的额度另有来处 +#[derive(Debug, Clone, Copy, PartialEq, Eq, Default, Serialize, Deserialize)] +#[serde(rename_all = "lowercase")] +pub enum BalanceSetting { + #[default] + Auto, + /// 不读 + Off, + Openrouter, + Deepseek, + Moonshot, + Sub2api, + Newapi, + Thinkwatch, +} + +impl From for tw_api::BalanceSetting { + fn from(b: BalanceSetting) -> Self { + match b { + BalanceSetting::Auto => Self::Auto, + BalanceSetting::Off => Self::Off, + BalanceSetting::Openrouter => Self::Openrouter, + BalanceSetting::Deepseek => Self::Deepseek, + BalanceSetting::Moonshot => Self::Moonshot, + BalanceSetting::Sub2api => Self::Sub2api, + BalanceSetting::Newapi => Self::Newapi, + BalanceSetting::Thinkwatch => Self::Thinkwatch, + } + } +} + +impl From for BalanceSetting { + fn from(b: tw_api::BalanceSetting) -> Self { + use tw_api::BalanceSetting as B; + match b { + B::Auto => Self::Auto, + B::Off => Self::Off, + B::Openrouter => Self::Openrouter, + B::Deepseek => Self::Deepseek, + B::Moonshot => Self::Moonshot, + B::Sub2api => Self::Sub2api, + B::Newapi => Self::Newapi, + B::Thinkwatch => Self::Thinkwatch, + } + } } /// 一家上游的并发上限最多写多少 diff --git a/crates/tw-config/src/reload.rs b/crates/tw-config/src/reload.rs index da9594e6..e9ecff49 100644 --- a/crates/tw-config/src/reload.rs +++ b/crates/tw-config/src/reload.rs @@ -437,6 +437,69 @@ routes: } } + /// 一家上游的 `balance:`:`auto`、`off` 和每一种来源都读得进;不写就是 `auto`, + /// 而且写回去时不写出来 + #[test] + fn every_balance_setting_loads() { + use crate::BalanceSetting as B; + let with = |value: &str| { + format!( + "{GOOD}providers:\n - name: relay\n base_url: https://relay.example\n key: sk\n balance: {value}\n" + ) + }; + for (value, want) in [ + ("auto", B::Auto), + ("off", B::Off), + ("openrouter", B::Openrouter), + ("deepseek", B::Deepseek), + ("moonshot", B::Moonshot), + ("sub2api", B::Sub2api), + ("newapi", B::Newapi), + ("thinkwatch", B::Thinkwatch), + ] { + let cfg = try_parse(&with(value)).unwrap_or_else(|e| panic!("{value}: {e}")); + assert_eq!(cfg.providers[0].balance, want, "{value}"); + // 和契约里的那个词一一对应 + assert_eq!(tw_api::BalanceSetting::from(want).slug(), value); + assert_eq!( + crate::BalanceSetting::from(tw_api::BalanceSetting::from(want)), + want + ); + } + let plain = format!( + "{GOOD}providers:\n - name: relay\n base_url: https://relay.example\n key: sk\n" + ); + let cfg = try_parse(&plain).unwrap(); + assert_eq!(cfg.providers[0].balance, B::Auto); + let written = serde_yaml_ng::to_string(&cfg.providers[0]).unwrap(); + assert!(!written.contains("balance"), "{written}"); + } + + /// 不认识的取值:加载不了,说清楚是哪个字段、写了什么、能写哪几个、在第几行;一键修复 + /// 删掉这一行,回到 `auto` + #[test] + fn an_unknown_balance_setting_is_refused_and_repaired_to_auto() { + let text = format!( + "{GOOD}providers:\n - name: relay\n base_url: https://relay.example\n key: sk\n balance: wallet\n" + ); + let r = try_parse(&text).unwrap_err(); + assert_eq!(r.stage, Stage::Schema, "{r:?}"); + assert_eq!(r.message.code, "config.unknown_variant", "{r:?}"); + assert_eq!(r.message.arg("field"), "providers[0].balance"); + assert_eq!(r.message.arg("value"), "wallet"); + assert_eq!( + r.message.arg("expected"), + "auto, off, openrouter, deepseek, moonshot, sub2api, newapi, thinkwatch" + ); + assert_eq!(r.line, Some(text.lines().count())); + let fix = crate::repair::repair(&text).expect("一键修复改得了"); + assert_eq!(fix.fixes[0].field, "providers[0].balance"); + assert_eq!( + try_parse(&fix.text).unwrap().providers[0].balance, + crate::BalanceSetting::Auto + ); + } + #[test] fn the_display_form_reads_like_a_sentence_a_person_can_act_on() { let bad = "version: 1\nclients:\n - name: c\n kye: tw-k\n"; diff --git a/crates/tw-config/tests/manual/schema.rs b/crates/tw-config/tests/manual/schema.rs index b1ecc01a..526fa22b 100644 --- a/crates/tw-config/tests/manual/schema.rs +++ b/crates/tw-config/tests/manual/schema.rs @@ -34,6 +34,9 @@ fn protocols() -> Vec<&'static str> { fn billings() -> Vec<&'static str> { super::fields::() } +fn balance_settings() -> Vec<&'static str> { + super::fields::() +} fn proxy_kinds() -> Vec<&'static str> { super::fields::() } @@ -651,6 +654,15 @@ pub fn sections() -> Vec
{ "不参与路由,模型也不出现在模型列表里;配置原样保留。", ), ), + row( + "balance", + Kind::Enum(balance_settings), + Def::Is("auto"), + t( + "Where the upstream's balance is read from, with its own key and proxy: `openrouter`, `deepseek`, `moonshot`, `sub2api`, `newapi` (New API and One API) or `thinkwatch` (a ThinkWatch Enterprise gateway). `auto`: recognized from `base_url` for OpenRouter, DeepSeek and Moonshot; any other address, except Anthropic's, OpenAI's and Gemini's own, is asked once whether it is a Sub2API, ThinkWatch Enterprise or New API relay, and the answer is kept in memory only. `off`: no balance. ChatGPT and Z.ai accounts and Bedrock have no balance whatever is written here.", + "从哪里读这家上游的余额,用它自己的密钥、走它自己的代理:`openrouter`、`deepseek`、`moonshot`、`sub2api`、`newapi`(New API 和 One API)或 `thinkwatch`(ThinkWatch 企业网关)。`auto`:OpenRouter、DeepSeek、Moonshot 按 `base_url` 识别;其他地址(Anthropic、OpenAI、Gemini 的官方地址除外)询问一次它是不是 Sub2API、ThinkWatch 企业网关或 New API 中转站,结果只保存在内存中。`off`:不读余额。ChatGPT、Z.ai 账号和 Bedrock 不读余额,与这里写什么无关。", + ), + ), ], }, Section { diff --git a/crates/tw-control/src/lib.rs b/crates/tw-control/src/lib.rs index 6790d897..74e041b0 100644 --- a/crates/tw-control/src/lib.rs +++ b/crates/tw-control/src/lib.rs @@ -514,6 +514,8 @@ fn provider_view( .collect(), pricing: p.pricing.clone(), max_concurrent: p.max_concurrent, + balance_setting: p.balance.into(), + balance: s.gateway.balance_of(p), } } diff --git a/crates/tw-control/src/resources.rs b/crates/tw-control/src/resources.rs index 7c729f2d..7f68290e 100644 --- a/crates/tw-control/src/resources.rs +++ b/crates/tw-control/src/resources.rs @@ -39,6 +39,7 @@ pub fn router() -> axum::Router { .at(ep::SetManualModels, set_manual_models) .at(ep::RefreshProviderModels, refresh_models) .at(ep::RefreshStaleModels, refresh_stale_models) + .at(ep::RefreshBalance, refresh_balance) .at(ep::CreateProxy, create_proxy) .at(ep::TestProxy, test_proxy) .at(ep::UpdateProxy, update_proxy) @@ -259,6 +260,7 @@ async fn test_provider( models: tw_api::ModelList::Empty, via: via.clone(), error: Some(error), + balance: None, }; let http = match tw_gateway::client_for_provider(&cfg, &p) { Ok(h) => h, @@ -302,6 +304,13 @@ async fn test_provider( } else { tw_gateway::probe(&http, &p.base_url, &headers, protocol).await }; + // 通了就顺带读一次余额(`auto` 的先认是哪一种)。不通的不读:地址或凭据不对, + // 余额也读不到,只是多等一会儿 + let balance = if r.ok { + s.gateway.check_balance(&http, &p).await + } else { + None + }; Ok(Json(tw_api::ProviderTestResult { ok: r.ok, protocol: protocol.map(Into::into), @@ -309,9 +318,31 @@ async fn test_provider( models: crate::model_list(r.models), via, error: r.error, + balance, })) } +/// 马上读一次这家的余额。没有这一家是 404(`control.upstream_not_found`),它没有余额 +/// 可读也是 404(`control.balance_none`) +async fn refresh_balance( + State(s): State, + Path(name): Path, +) -> Result, Fail> { + if !s.config().providers.iter().any(|p| p.name == name) { + return Err(crate::no_such_upstream(&name)); + } + match s.gateway.refresh_balance(&name).await { + Some(b) => Ok(Json(b)), + None => Err(fail( + StatusCode::NOT_FOUND, + msg!( + "control.balance_none", upstream = &name => + "Upstream `{upstream}` has no balance to read." + ), + )), + } +} + /// 一个上游的模型清单:每个模型在不在启用范围里、上下文窗口和输出上限多大(手写的 /// 还是价目表的)、按它选的价目表怎么计价。 async fn provider_models( @@ -510,6 +541,7 @@ fn to_provider( model_specs: existing.map(|e| e.model_specs.clone()).unwrap_or_default(), max_concurrent: input.max_concurrent, disabled: input.disabled, + balance: input.balance.map(Into::into).unwrap_or_default(), }; // **保存和检测之前就说清楚凭据写法哪儿不对**,而不是等整份配置校验时 // 报一条指着 YAML 的错误 diff --git a/crates/tw-control/tests/resources.rs b/crates/tw-control/tests/resources.rs index 01335248..fbb4d100 100644 --- a/crates/tw-control/tests/resources.rs +++ b/crates/tw-control/tests/resources.rs @@ -908,3 +908,186 @@ async fn testing_a_proxy_checks_its_credentials() { .await; assert_eq!(json(&body)["ok"], true, "{body}"); } + +// ─────────────────────────────────────────────────────────── 余额 + +/// 一家假中转站,地址带着 `/anthropic`:模型清单只认 `sk-good`,用量接口(接在源后面)回 +/// Sub2API 的钱包 +async fn fake_relay_with_a_wallet() -> std::net::SocketAddr { + let app = axum::Router::new() + .route( + "/anthropic/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"}]}"#.to_string(), + ) + }), + ) + .route( + "/v1/usage", + axum::routing::get(|h: axum::http::HeaderMap| async move { + if h.get("authorization").and_then(|v| v.to_str().ok()) != Some("Bearer sk-good") { + return (StatusCode::UNAUTHORIZED, "{}".to_string()); + } + ( + StatusCode::OK, + r#"{"mode":"unrestricted","planName":"钱包余额","unit":"USD","balance":8.25,"remaining":8.25}"# + .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 +} + +/// 「检测连接」顺带读余额:`auto` 的先认出是哪一种中转站 +#[tokio::test] +async fn checking_an_upstream_also_reads_its_balance() { + let b = bed(BASE); + let up = fake_relay_with_a_wallet().await; + let test = |key: &str| { + serde_json::json!({ "provider": { + "name": "relay", + "base_url": format!("http://{up}/anthropic"), + "key": key, + "protocol": "anthropic", + }}) + }; + let (st, body) = call(&b.app, "POST", "/provider-test", test("sk-good")).await; + assert_eq!(st, StatusCode::OK, "{body}"); + let v = json(&body); + assert_eq!(v["ok"], true, "{body}"); + assert_eq!(v["balance"]["source"], "sub2api", "{body}"); + assert_eq!(v["balance"]["wallet"]["amount"], 8.25); + assert_eq!(v["balance"]["wallet"]["currency"], "USD"); + assert_eq!(v["balance"]["error"], serde_json::Value::Null); + + // 不通的不读 + let (_, body) = call(&b.app, "POST", "/provider-test", test("sk-bad")).await; + let v = json(&body); + assert_eq!(v["ok"], false, "{body}"); + assert_eq!(v["balance"], serde_json::Value::Null); + + // 关掉了就不读 + let mut off = test("sk-good"); + off["provider"]["balance"] = "off".into(); + let (_, body) = call(&b.app, "POST", "/provider-test", off).await; + assert_eq!(json(&body)["balance"], serde_json::Value::Null, "{body}"); +} + +/// `balance` 写进配置;`auto` 不写。概览原样给回 `balance_setting` +#[tokio::test] +async fn the_balance_setting_is_saved_and_shown() { + let b = bed(BASE); + let mut p = relay("relay"); + p["balance"] = "sub2api".into(); + let (st, body) = call( + &b.app, + "POST", + "/providers", + serde_json::json!({ "provider": p }), + ) + .await; + assert_eq!(st, StatusCode::OK, "{body}"); + assert!(b.file().contains("balance: sub2api"), "{}", b.file()); + assert_eq!( + b.parsed().providers[1].balance, + tw_config::BalanceSetting::Sub2api + ); + let (_, body) = call(&b.app, "GET", "/overview", serde_json::Value::Null).await; + let v = json(&body); + assert_eq!(v["providers"][0]["balance_setting"], "auto"); + assert_eq!(v["providers"][1]["balance_setting"], "sub2api"); + + let (st, body) = call( + &b.app, + "POST", + "/providers", + serde_json::json!({ "provider": relay("relay2") }), + ) + .await; + assert_eq!(st, StatusCode::OK, "{body}"); + assert_eq!(b.file().matches("balance:").count(), 1, "{}", b.file()); + + // 不认识的取值交不进来 + let mut bad = relay("relay3"); + bad["balance"] = "wallet".into(); + let (st, _) = call( + &b.app, + "POST", + "/providers", + serde_json::json!({ "provider": bad }), + ) + .await; + assert!(st.is_client_error(), "{st}"); +} + +/// 马上读一次:读到的进概览,报一条 `balance_updated` +#[tokio::test] +async fn refreshing_a_balance_reads_it_now_and_the_overview_shows_it() { + let up = fake_relay_with_a_wallet().await; + let b = bed(&BASE.replace( + " key: sk-official\n", + &format!( + " key: sk-official\n - name: relay\n base_url: http://{up}/anthropic\n key: sk-good\n protocol: anthropic\n" + ), + )); + let mut rx = b.gateway().bus.subscribe(); + let (st, body) = call( + &b.app, + "POST", + "/providers/relay/balance/refresh", + serde_json::Value::Null, + ) + .await; + assert_eq!(st, StatusCode::OK, "{body}"); + let v = json(&body); + assert_eq!(v["source"], "sub2api"); + assert_eq!(v["wallet"]["amount"], 8.25); + + let (_, body) = call(&b.app, "GET", "/overview", serde_json::Value::Null).await; + let v = json(&body); + let relay = v["providers"] + .as_array() + .unwrap() + .iter() + .find(|p| p["name"] == "relay") + .unwrap(); + assert_eq!(relay["balance"]["wallet"]["amount"], 8.25, "{relay}"); + // 官方地址没有余额可读 + assert_eq!(v["providers"][0]["balance"], serde_json::Value::Null); + + let updated = std::iter::from_fn(|| rx.try_recv().ok()).any( + |e| matches!(e, tw_api::Event::BalanceUpdated { provider, .. } if provider == "relay"), + ); + assert!(updated); +} + +#[tokio::test] +async fn refreshing_an_upstream_without_a_balance_is_a_404() { + let b = bed(BASE); + let (st, body) = call( + &b.app, + "POST", + "/providers/官方/balance/refresh", + serde_json::Value::Null, + ) + .await; + assert_eq!(st, StatusCode::NOT_FOUND, "{body}"); + assert_eq!(json(&body)["code"], "control.balance_none"); + let (st, body) = call( + &b.app, + "POST", + "/providers/nobody/balance/refresh", + serde_json::Value::Null, + ) + .await; + assert_eq!(st, StatusCode::NOT_FOUND, "{body}"); + assert_eq!(json(&body)["code"], "control.upstream_not_found"); +} diff --git a/crates/tw-gateway/src/balances.rs b/crates/tw-gateway/src/balances.rs new file mode 100644 index 00000000..a1c7a191 --- /dev/null +++ b/crates/tw-gateway/src/balances.rs @@ -0,0 +1,479 @@ +//! 上游的余额:钱包里还有多少、额度用了多少、到期时刻,从各家自己的余额接口读。 +//! +//! (不要和 [`crate::balance`] 混了:那个是 `load-balance` 组轮到了谁。) +//! +//! 每一种接口一个读法([`tw_api::BalanceSource`]),都用这家上游自己的密钥、走它自己的 +//! 出站设置(代理),请求头只有 ThinkWatch 的 User-Agent、`Accept` 和凭据 +//! ([`crate::egress::balance_headers`]),每个请求最多等 [`TIMEOUT`]。接口的路径接在地址的 +//! **源**(`https://主机:端口`)后面,不接在 `/anthropic` 这类路径后面。 +//! +//! 哪一种:配置里写明的(`balance:`),或者 `auto` 时按主机认(OpenRouter、DeepSeek、 +//! Moonshot 的官方地址);别的地址问一次它是哪一种中转站([`detect`]),问出来的只记在内存里。 +//! ChatGPT、Z.ai 账号和 Bedrock 不读:它们的额度另有来处([`crate::quota`]、[`crate::glm`])。 +//! +//! **读不读、读成没有都不影响转发**:读在后台,结果只进视图和 `balance_updated` 事件。 +//! 什么时候读见 [`tracker`],读懂回答见 [`parse`]。 + +pub mod parse; +pub mod tracker; + +use std::time::Duration; + +use serde_json::Value; +use tw_api::BalanceSource; +use tw_types::{Msg, msg}; + +pub use parse::Reading; +pub use tracker::{Detection, Outcome, Plan, Step, Tracker, Why}; + +/// 跟着一个经过这一家的请求走:请求结束时(它被丢掉时,正常交完、客户端走掉都一样) +/// 记一笔,到了时候就重读这一家的余额(见 [`tracker`])。**只做个记号,不联网** +#[must_use = "dropping it at once counts the request as ended"] +pub struct Passing { + tracker: std::sync::Arc, + provider: String, +} + +impl Passing { + pub fn new(tracker: std::sync::Arc, provider: &str) -> Self { + Self { + tracker, + provider: provider.to_string(), + } + } +} + +impl Drop for Passing { + fn drop(&mut self) { + self.tracker.note_request(&self.provider); + } +} + +/// 读余额的每一个请求最多等多久 +pub const TIMEOUT: Duration = Duration::from_secs(10); + +/// 余额接口的回答最多读这么多。都是几百字节的 JSON,大得多的不是余额 +const BODY_MAX: usize = 256 * 1024; + +/// 后台多久看一次该读谁。请求结束时会提前叫醒它 +const TICK: Duration = Duration::from_secs(5); + +/// 地址的源:`https://主机[:端口]`。读不出主机的是 `None` +pub fn origin(base_url: &str) -> Option { + let u = reqwest::Url::parse(base_url.trim()).ok()?; + u.host_str()?; + let o = u.origin(); + o.is_tuple().then(|| o.ascii_serialization()) +} + +/// 主机,小写 +fn host(base_url: &str) -> Option { + let u = reqwest::Url::parse(base_url.trim()).ok()?; + Some(u.host_str()?.to_ascii_lowercase()) +} + +/// `auto` 时按主机认得出的官方地址。 +pub fn by_host(base_url: &str) -> Option { + match host(base_url)?.as_str() { + "openrouter.ai" => Some(BalanceSource::Openrouter), + "api.deepseek.com" => Some(BalanceSource::Deepseek), + "api.moonshot.cn" | "api.moonshot.ai" => Some(BalanceSource::Moonshot), + _ => None, + } +} + +/// 模型厂商自己的接口地址:**不问**它是哪一种中转站,它不是中转站 +const VENDOR_HOSTS: &[&str] = &[ + "api.anthropic.com", + "api.openai.com", + "generativelanguage.googleapis.com", +]; + +/// `balance:` 和地址定下来的读法。`None`:这家没有余额可读(关掉了、地址读不出主机、 +/// 模型厂商自己的地址) +pub fn plan(setting: tw_config::BalanceSetting, base_url: &str) -> Option { + let setting = tw_api::BalanceSetting::from(setting); + if setting == tw_api::BalanceSetting::Off { + return None; + } + let host = host(base_url)?; + if let Some(s) = setting.source() { + return Some(Plan::Known(s)); + } + if let Some(s) = by_host(base_url) { + return Some(Plan::Known(s)); + } + (!VENDOR_HOSTS.contains(&host.as_str())).then_some(Plan::Detect) +} + +/// 读余额用的 `Authorization`:这家的 API 密钥,按 Bearer 发。密钥写在 `headers` 里的, +/// 取鉴权的那一个头。OAuth 的、没有凭据的、凭据读不出来的是 `None` +pub fn authorization(p: &tw_config::Provider) -> Option { + if let Some(k) = &p.key { + return k.resolve().ok().map(|k| format!("Bearer {k}")); + } + if p.oauth.is_some() { + return None; + } + let headers = p.outbound_headers(None).ok()?; + let named = |want: &[&str]| { + headers + .iter() + .find(|(n, _)| want.iter().any(|w| n.eq_ignore_ascii_case(w))) + .map(|(_, v)| v.clone()) + }; + named(&["authorization"]).or_else(|| { + named(&["x-api-key", "api-key", "x-goog-api-key"]).map(|v| format!("Bearer {v}")) + }) +} + +// ---------------------------------------------------------------- 取数 + +/// 一个余额请求没成的样子。 +#[derive(Debug, Clone, PartialEq)] +pub enum Failure { + /// 连不上、超时、读到一半断了 + Transport(Msg), + /// 回的不是 2xx + Status(u16), + /// 2xx,可不是我们认得的回答 + Unrecognized, +} + +impl Failure { + /// 给界面的那句话 + pub fn msg(&self) -> Msg { + match self { + Failure::Transport(why) => why.clone(), + Failure::Status(status @ (401 | 403)) => msg!( + "gw.balance.rejected", status = status => + "The balance could not be read: the upstream rejected the key (HTTP {status})." + ), + Failure::Status(status) => msg!( + "gw.balance.status", status = status => + "The balance could not be read: the upstream answered HTTP {status}." + ), + Failure::Unrecognized => msg!( + "gw.balance.unrecognized" => + "The balance could not be read: the answer is in an unrecognized format." + ), + } + } + + /// 对方说了话(4xx、读不懂的回答):它就是这样,再问也一样。连不上、超时、5xx、429 + /// 说明不了什么 + fn answered(&self) -> bool { + match self { + Failure::Transport(_) => false, + Failure::Status(s) => (400..500).contains(s) && *s != 429, + Failure::Unrecognized => true, + } + } +} + +/// 发一个 GET,读回 JSON。 +async fn get_json(http: &reqwest::Client, url: &str, auth: &str) -> Result { + let mut req = http.get(url).timeout(TIMEOUT); + for (name, value) in crate::egress::balance_headers(auth) { + req = req.header(name, value); + } + let mut r = req.send().await.map_err(transport)?; + let status = r.status().as_u16(); + if !(200..300).contains(&status) { + return Err(Failure::Status(status)); + } + let mut body = Vec::new(); + while let Some(chunk) = r.chunk().await.map_err(transport)? { + if body.len() + chunk.len() > BODY_MAX { + return Err(Failure::Unrecognized); + } + body.extend_from_slice(&chunk); + } + serde_json::from_slice(&body).map_err(|_| Failure::Unrecognized) +} + +fn transport(e: reqwest::Error) -> Failure { + Failure::Transport(if e.is_timeout() { + msg!( + "gw.balance.timeout", secs = TIMEOUT.as_secs() => + "The balance could not be read: no answer within {secs} seconds." + ) + } else if e.is_connect() { + msg!( + "gw.balance.connect" => + "The balance could not be read: the upstream could not be reached." + ) + } else { + msg!( + "gw.balance.request_failed", detail = chain(&e) => + "The balance could not be read: {detail}" + ) + }) +} + +/// 错误连同它的每一层原因:reqwest 自己只说最外面一层 +fn chain(e: &reqwest::Error) -> String { + let mut detail = e.to_string(); + let mut cur = std::error::Error::source(e); + while let Some(c) = cur { + detail.push_str(": "); + detail.push_str(&c.to_string()); + cur = c.source(); + } + detail +} + +/// 先问 Sub2API(和企业网关)的用量接口,再问 New API 的账单接口。**认出来了就交回那一次 +/// 的回答**:Sub2API 和企业网关的余额就在里面,不用再问一遍 +pub async fn detect( + http: &reqwest::Client, + origin: &str, + auth: &str, +) -> (Detection, Option) { + let usage = get_json(http, &format!("{origin}/v1/usage"), auth).await; + if let Ok(v) = &usage { + if parse::is_sub2api(v) { + return (Detection::Found(BalanceSource::Sub2api), usage.ok()); + } + if parse::is_thinkwatch(v) { + return (Detection::Found(BalanceSource::Thinkwatch), usage.ok()); + } + } + let billing = get_json( + http, + &format!("{origin}/v1/dashboard/billing/subscription"), + auth, + ) + .await; + if let Ok(v) = &billing + && parse::is_newapi(v) + { + return (Detection::Found(BalanceSource::Newapi), billing.ok()); + } + // 两个都答了话(不是这个形状、没有这个接口、不认这把密钥):两种都不是。有一个没问成, + // 就说不准 + let answered = |r: &Result| r.as_ref().map_or_else(Failure::answered, |_| true); + if answered(&usage) && answered(&billing) { + (Detection::Neither, None) + } else { + (Detection::Undecided, None) + } +} + +/// 读一次。`known`:检测时已经拿到的那一份回答(Sub2API、企业网关的用量,New API 的账单) +pub async fn read( + http: &reqwest::Client, + source: BalanceSource, + base_url: &str, + auth: &str, + known: Option, +) -> Result { + let origin = origin(base_url).ok_or(Failure::Unrecognized)?; + let get = |path: &str| { + let url = format!("{origin}{path}"); + async move { get_json(http, &url, auth).await } + }; + let known_or = |path: &'static str| { + let known = known.clone(); + async move { + match known { + Some(v) => Ok(v), + None => get(path).await, + } + } + }; + let parsed = |r: Option| r.ok_or(Failure::Unrecognized); + match source { + BalanceSource::Openrouter => match parse::openrouter_key(&get("/api/v1/key").await?) { + Some(parse::OpenRouterKey::Limited(r)) => Ok(r), + Some(parse::OpenRouterKey::Unlimited) => { + parsed(parse::openrouter_credits(&get("/api/v1/credits").await?)) + } + None => Err(Failure::Unrecognized), + }, + BalanceSource::Deepseek => parsed(parse::deepseek(&get("/user/balance").await?)), + BalanceSource::Moonshot => { + // 回答里不写货币:国际站是美元,国内站是人民币 + let currency = if host(base_url).is_some_and(|h| h.ends_with(".ai")) { + "USD" + } else { + "CNY" + }; + parsed(parse::moonshot( + &get("/v1/users/me/balance").await?, + currency, + )) + } + BalanceSource::Sub2api => parsed(parse::sub2api(&known_or("/v1/usage").await?)), + BalanceSource::Thinkwatch => parsed(parse::thinkwatch(&known_or("/v1/usage").await?)), + BalanceSource::Newapi => { + let subscription = known_or("/v1/dashboard/billing/subscription").await?; + let usage = get(&newapi_usage_path(chrono::Utc::now().date_naive())).await?; + parsed(parse::newapi(&subscription, &usage)) + } + } +} + +/// New API 的用量接口要一个日期范围。它算的是这把密钥一共用了多少,范围给宽一些: +/// 一百天前到明天 +fn newapi_usage_path(today: chrono::NaiveDate) -> String { + let start = today - chrono::Days::new(100); + let end = today + chrono::Days::new(1); + format!( + "/v1/dashboard/billing/usage?start_date={}&end_date={}", + start.format("%Y-%m-%d"), + end.format("%Y-%m-%d") + ) +} + +/// 做一步:要先认来源的先认,认出来了接着读。交回这一次的结果(给 [`Tracker::settle`]) +pub async fn run(http: &reqwest::Client, step: Step, base_url: &str, auth: &str) -> Outcome { + let Some(origin) = origin(base_url) else { + return Outcome { + detection: Some(Detection::Neither), + read: None, + }; + }; + let (source, known, detection) = match step { + Step::Read(s) => (s, None, None), + Step::Detect => match detect(http, &origin, auth).await { + (Detection::Found(s), known) => (s, known, Some(Detection::Found(s))), + (other, _) => { + return Outcome { + detection: Some(other), + read: None, + }; + } + }, + }; + let r = read(http, source, base_url, auth, known).await; + Outcome { + detection, + read: Some((source, r.map_err(|f| f.msg()))), + } +} + +/// 后台:启动时读一遍,之后按节奏读(见 [`tracker`])。有请求结束时被提前叫醒。 +pub fn spawn(state: crate::AppState) { + tokio::spawn(async move { + loop { + let _ = state.start_due_balances(); + tokio::select! { + _ = tokio::time::sleep(TICK) => {} + _ = state.balances.wake.notified() => {} + } + } + }); +} + +#[cfg(test)] +mod tests { + use super::*; + use tw_config::BalanceSetting as S; + + #[test] + fn the_origin_drops_the_path_and_keeps_the_port() { + assert_eq!( + origin("https://api.deepseek.com/anthropic").as_deref(), + Some("https://api.deepseek.com") + ); + assert_eq!( + origin("http://127.0.0.1:8080/v1/").as_deref(), + Some("http://127.0.0.1:8080") + ); + assert_eq!( + origin("https://relay.example:443/api").as_deref(), + Some("https://relay.example") + ); + assert_eq!(origin("不是地址"), None); + } + + #[test] + fn auto_knows_the_official_hosts() { + let known = |url: &str| match plan(S::Auto, url) { + Some(Plan::Known(s)) => Some(s), + _ => None, + }; + assert_eq!( + known("https://openrouter.ai/api/v1"), + Some(BalanceSource::Openrouter) + ); + assert_eq!( + known("https://api.deepseek.com/anthropic"), + Some(BalanceSource::Deepseek) + ); + assert_eq!( + known("https://api.moonshot.cn/v1"), + Some(BalanceSource::Moonshot) + ); + assert_eq!( + known("https://API.Moonshot.AI/anthropic"), + Some(BalanceSource::Moonshot) + ); + // 只是名字里含着的不算 + assert_eq!( + plan(S::Auto, "https://openrouter.ai.example.com/v1"), + Some(Plan::Detect) + ); + assert_eq!( + plan(S::Auto, "https://relay.example/v1"), + Some(Plan::Detect) + ); + // 模型厂商自己的地址不是中转站,不问 + assert_eq!(plan(S::Auto, "https://api.anthropic.com"), None); + assert_eq!(plan(S::Auto, "https://api.openai.com/v1"), None); + } + + #[test] + fn an_explicit_source_wins_and_off_reads_nothing() { + assert_eq!( + plan(S::Sub2api, "https://api.deepseek.com"), + Some(Plan::Known(BalanceSource::Sub2api)) + ); + assert_eq!( + plan(S::Thinkwatch, "https://gw.corp.example"), + Some(Plan::Known(BalanceSource::Thinkwatch)) + ); + assert_eq!(plan(S::Off, "https://openrouter.ai/api/v1"), None); + assert_eq!(plan(S::Auto, "不是地址"), None); + } + + #[test] + fn the_key_goes_as_a_bearer_whatever_header_the_protocol_uses() { + let p = tw_config::Provider { + base_url: "https://api.deepseek.com/anthropic".into(), + key: Some("sk-ds".into()), + protocol: Some(tw_config::Protocol::Anthropic), + ..Default::default() + }; + assert_eq!(authorization(&p).as_deref(), Some("Bearer sk-ds")); + // 写在 headers 里的:鉴权头原样,别的鉴权头补上 Bearer + let h = |name: &str, value: &str| tw_config::Provider { + base_url: "https://relay.example".into(), + headers: tw_config::Headers::new(vec![tw_config::Header { + name: name.into(), + value: value.into(), + }]), + ..Default::default() + }; + assert_eq!( + authorization(&h("Authorization", "Bearer sk-h")).as_deref(), + Some("Bearer sk-h") + ); + assert_eq!( + authorization(&h("x-api-key", "sk-x")).as_deref(), + Some("Bearer sk-x") + ); + assert_eq!(authorization(&h("x-team", "blue")), None); + assert_eq!(authorization(&tw_config::Provider::default()), None); + } + + #[test] + fn newapi_usage_asks_for_a_wide_range() { + let today = chrono::NaiveDate::from_ymd_opt(2026, 10, 10).unwrap(); + assert_eq!( + newapi_usage_path(today), + "/v1/dashboard/billing/usage?start_date=2026-07-02&end_date=2026-10-11" + ); + } +} diff --git a/crates/tw-gateway/src/balances/parse.rs b/crates/tw-gateway/src/balances/parse.rs new file mode 100644 index 00000000..229feec2 --- /dev/null +++ b/crates/tw-gateway/src/balances/parse.rs @@ -0,0 +1,753 @@ +//! 读懂各家余额接口的回答。**只看 JSON,不联网**:取数在 [`super`],这里每一种回答一个 +//! 小函数,读不懂的是 `None`([`super::Failure::Unrecognized`])。 +//! +//! 一条贯穿这里的纪律和订阅额度一样:**每个数都是上游给的**。上游没给的不补成 0 —— +//! 「余额 $0」和「不知道余额」是两句话,前者会让人去充值。 + +use serde_json::Value; +use tw_api::{BalanceQuota, BalanceScope, BalanceWindow, Money, Spent, SpentPeriod}; + +/// 一次读到的余额:[`tw_api::Balance`] 里从上游来的那几样。 +#[derive(Debug, Clone, Default, PartialEq)] +pub struct Reading { + pub wallet: Option, + pub quota: Option, + pub windows: Vec, + pub expires_at_ms: Option, + pub spent: Option, +} + +const USD: &str = "USD"; + +/// 一个数:JSON 的数,或者写成字符串的数(DeepSeek 的余额就是字符串)。**不是有限的数不要** +fn number(v: &Value) -> Option { + let n = match v { + Value::Number(n) => n.as_f64()?, + Value::String(s) => s.trim().parse::().ok()?, + _ => return None, + }; + n.is_finite().then_some(n) +} + +/// 一个时刻:RFC 3339,或者 Unix 时间戳(秒或毫秒,按大小分)。0 和负数是「没有」 +fn moment(v: &Value) -> Option { + match v { + Value::String(s) if !s.trim().is_empty() => { + let s = s.trim(); + if let Ok(t) = chrono::DateTime::parse_from_rfc3339(s) { + return u64::try_from(t.timestamp_millis()).ok().filter(|t| *t > 0); + } + number(v).and_then(stamp) + } + Value::Number(_) => number(v).and_then(stamp), + _ => None, + } +} + +/// 数字的时间戳:比这个大的是毫秒,否则是秒。近年的秒数在十亿上下,毫秒在一万亿以上 +fn stamp(n: f64) -> Option { + if n <= 0.0 { + return None; + } + let ms = if n >= 1e11 { n } else { n * 1000.0 }; + Some(ms as u64) +} + +// ---------------------------------------------------------------- OpenRouter + +/// `GET /api/v1/key` 的回答。 +#[derive(Debug, Clone, PartialEq)] +pub enum OpenRouterKey { + /// 这把密钥设了额度:额度和用了多少 + Limited(Reading), + /// 没设额度:要看账户的余额(`/api/v1/credits`) + Unlimited, +} + +/// `{"data":{"limit":10,"limit_remaining":7.5,"usage":2.5,…}}`,美元。 +/// +/// **已用按额度减剩余算**:设了按天、按月重置的额度时,`usage` 是这把密钥从来用过的 +/// 总数,`limit_remaining` 才是这一期还剩多少。没给剩余时才用 `usage` +pub fn openrouter_key(v: &Value) -> Option { + let data = v.get("data")?.as_object()?; + let limit = match data.get("limit") { + None | Some(Value::Null) => return Some(OpenRouterKey::Unlimited), + Some(l) => number(l)?, + }; + let used = match ( + data.get("limit_remaining").and_then(number), + data.get("usage").and_then(number), + ) { + (Some(remaining), _) => (limit - remaining).max(0.0), + (None, Some(usage)) => usage, + (None, None) => return None, + }; + Some(OpenRouterKey::Limited(Reading { + quota: Some(BalanceQuota { + limit, + used, + unit: USD.to_string(), + }), + ..Default::default() + })) +} + +/// `GET /api/v1/credits`:`{"data":{"total_credits":20,"total_usage":12.5}}`,美元。 +/// 钱包是买过的减用掉的 +pub fn openrouter_credits(v: &Value) -> Option { + let data = v.get("data")?; + let credits = number(data.get("total_credits")?)?; + let usage = number(data.get("total_usage")?)?; + Some(Reading { + wallet: Some(Money { + amount: credits - usage, + currency: USD.to_string(), + }), + ..Default::default() + }) +} + +// ---------------------------------------------------------------- DeepSeek + +/// `GET /user/balance`:`{"is_available":true,"balance_infos":[{"currency":"CNY", +/// "total_balance":"110.00",…}]}`。 +/// +/// 每种货币一项。**显示第一个有钱的**,都没钱就是第一个:充的是人民币的账户,美元那一项 +/// 是 0,显示它就成了「余额 $0」 +pub fn deepseek(v: &Value) -> Option { + let infos = v.get("balance_infos")?.as_array()?; + let wallets: Vec = infos + .iter() + .filter_map(|i| { + Some(Money { + amount: number(i.get("total_balance")?)?, + currency: i.get("currency")?.as_str()?.trim().to_string(), + }) + }) + .collect(); + if wallets.is_empty() && !infos.is_empty() { + return None; + } + let wallet = wallets + .iter() + .find(|w| w.amount > 0.0) + .or(wallets.first()) + .cloned(); + Some(Reading { + wallet, + ..Default::default() + }) +} + +// ---------------------------------------------------------------- Moonshot + +/// `GET /v1/users/me/balance`:`{"code":0,"data":{"available_balance":49.58,…},"status":true}`。 +/// +/// 回答里不写货币:`currency` 由调用方按站点给(`.cn` 是人民币,`.ai` 是美元) +pub fn moonshot(v: &Value, currency: &str) -> Option { + let amount = number(v.get("data")?.get("available_balance")?)?; + Some(Reading { + wallet: Some(Money { + amount, + currency: currency.to_string(), + }), + ..Default::default() + }) +} + +// ---------------------------------------------------------------- Sub2API + +/// 这是 Sub2API 的用量接口吗:顶层有一个字符串的 `mode` +pub fn is_sub2api(v: &Value) -> bool { + v.get("mode").is_some_and(Value::is_string) +} + +/// `GET /v1/usage`,两种模式: +/// +/// - `quota_limited`:密钥有总额度(`quota{limit,used}`)和按时间窗口的限额 +/// (`rate_limits[]{window,limit,used,reset_at}`),美元; +/// - `unrestricted`:订阅的日、周、月限额(`subscription{daily_usage_usd,daily_limit_usd,…}`), +/// 或者钱包余额(`balance`)。 +/// +/// 金额的单位看顶层的 `unit`,没写是美元。`expires_at` 是到期时刻。用量明细里只取今天 +/// 花了多少(`usage.today.cost`),别的(`daily_usage`、`model_stats`)不要 +pub fn sub2api(v: &Value) -> Option { + let mode = v.get("mode")?.as_str()?; + let unit = v + .get("unit") + .and_then(Value::as_str) + .map(str::trim) + .filter(|u| !u.is_empty()) + .unwrap_or(USD) + .to_string(); + let mut r = Reading { + expires_at_ms: v + .get("expires_at") + .and_then(moment) + .or_else(|| v.get("subscription")?.get("expires_at").and_then(moment)), + spent: v + .get("usage") + .and_then(|u| u.get("today")?.get("cost")) + .and_then(number) + .map(|amount| Spent { + amount, + currency: unit.clone(), + period: SpentPeriod::Today, + }), + ..Default::default() + }; + if mode == "quota_limited" { + r.quota = v.get("quota").and_then(|q| { + Some(BalanceQuota { + limit: number(q.get("limit")?)?, + used: q.get("used").and_then(number).unwrap_or(0.0), + unit: unit.clone(), + }) + }); + r.windows = v + .get("rate_limits") + .and_then(Value::as_array) + .into_iter() + .flatten() + .filter_map(|w| { + Some(BalanceWindow { + window: w.get("window")?.as_str()?.trim().to_string(), + limit: number(w.get("limit")?)?, + used: w.get("used").and_then(number).unwrap_or(0.0), + unit: unit.clone(), + resets_at_ms: w.get("reset_at").and_then(moment), + scope: None, + }) + }) + .filter(|w| !w.window.is_empty()) + .collect(); + return Some(r); + } + if let Some(sub) = v.get("subscription").filter(|s| s.is_object()) { + for name in ["daily", "weekly", "monthly"] { + // 限额没写、写了 0 的窗口不限,不是「额度为 0」 + let Some(limit) = sub + .get(format!("{name}_limit_usd")) + .and_then(number) + .filter(|l| *l > 0.0) + else { + continue; + }; + r.windows.push(BalanceWindow { + window: name.to_string(), + limit, + used: sub + .get(format!("{name}_usage_usd")) + .and_then(number) + .unwrap_or(0.0), + unit: USD.to_string(), + resets_at_ms: None, + scope: None, + }); + } + } + r.wallet = v.get("balance").and_then(number).map(|amount| Money { + amount, + currency: unit, + }); + Some(r) +} + +// ---------------------------------------------------------------- New API / One API + +/// 「不限额度」的密钥报的总额度就是这个数(或者更大) +const UNLIMITED: f64 = 100_000_000.0; + +/// 这是 New API / One API 的账单接口吗:有 `hard_limit_usd` 或 `system_hard_limit_usd` +pub fn is_newapi(v: &Value) -> bool { + hard_limit(v).is_some() +} + +fn hard_limit(v: &Value) -> Option { + v.get("hard_limit_usd") + .and_then(number) + .or_else(|| v.get("system_hard_limit_usd").and_then(number)) +} + +/// `GET /v1/dashboard/billing/subscription`(总额度 `hard_limit_usd`,美元;到期 +/// `access_until`,Unix 秒,0 是不到期)加 `GET /v1/dashboard/billing/usage`(已用 +/// `total_usage`,**美分**)。 +/// +/// 不限额度的密钥(总额度 ≥ 1 亿)没有额度可言,只说得出花了多少 +pub fn newapi(subscription: &Value, usage: &Value) -> Option { + let limit = hard_limit(subscription)?; + let used = number(usage.get("total_usage")?)? / 100.0; + let mut r = Reading { + expires_at_ms: subscription.get("access_until").and_then(moment), + ..Default::default() + }; + if limit >= UNLIMITED { + r.spent = Some(Spent { + amount: used, + currency: USD.to_string(), + period: SpentPeriod::Total, + }); + } else { + r.quota = Some(BalanceQuota { + limit, + used, + unit: USD.to_string(), + }); + } + Some(r) +} + +// ---------------------------------------------------------------- ThinkWatch 企业网关 + +/// 这是 ThinkWatch 企业网关的用量接口吗:顶层有一个 `limits` 数组(没有 `mode`) +pub fn is_thinkwatch(v: &Value) -> bool { + !is_sub2api(v) && v.get("limits").is_some_and(Value::is_array) +} + +/// `GET /v1/usage`: +/// +/// ```json +/// {"usage":{"requests_today":3,"tokens_today":9000,"requests_month":80,"tokens_month":400000, +/// "cost_usd_month":12.5}, +/// "limits":[{"scope":"key","kind":"requests","window":"1h","window_secs":3600,"limit":100, +/// "used":7,"resets_at":"…"}], +/// "expires_at":null} +/// ``` +/// +/// 每一条限额是一个窗口,单位就是 `kind`(`requests`、`tokens`),带着它管的是这把密钥还是 +/// 它所属的用户(`scope`);认不出的一条不要。这个月花了多少(`usage.cost_usd_month`)是 +/// 花费。**没有钱包,也没有总额度**:企业网关的限额都是按时间窗口的 +pub fn thinkwatch(v: &Value) -> Option { + let limits = v.get("limits")?.as_array()?; + let windows = limits + .iter() + .filter_map(|item| { + let unit = match item.get("kind")?.as_str()? { + "requests" => "requests", + "tokens" => "tokens", + _ => return None, + }; + let window = item.get("window")?.as_str()?.trim(); + if window.is_empty() { + return None; + } + Some(BalanceWindow { + window: window.to_string(), + limit: number(item.get("limit")?)?, + used: item.get("used").and_then(number).unwrap_or(0.0), + unit: unit.to_string(), + resets_at_ms: item.get("resets_at").and_then(moment), + scope: item + .get("scope") + .and_then(Value::as_str) + .and_then(BalanceScope::from_slug), + }) + }) + .collect(); + Some(Reading { + windows, + expires_at_ms: v.get("expires_at").and_then(moment), + spent: v + .get("usage") + .and_then(|u| u.get("cost_usd_month")) + .and_then(number) + .map(|amount| Spent { + amount, + currency: USD.to_string(), + period: SpentPeriod::Month, + }), + ..Default::default() + }) +} + +#[cfg(test)] +mod tests { + use super::*; + + fn json(s: &str) -> Value { + serde_json::from_str(s).unwrap() + } + + fn usd(amount: f64) -> Option { + Some(Money { + amount, + currency: "USD".into(), + }) + } + + fn ms(rfc3339: &str) -> u64 { + chrono::DateTime::parse_from_rfc3339(rfc3339) + .unwrap() + .timestamp_millis() as u64 + } + + // ------------------------------------------------------------ OpenRouter + + #[test] + fn an_openrouter_key_with_a_limit_reads_as_a_quota() { + let r = openrouter_key(&json( + r#"{"data":{"label":"sk-or-v1-abc...xyz","limit":10,"limit_remaining":7.5,"limit_reset":"monthly","usage":42.25,"is_free_tier":false}}"#, + )); + // **已用是这一期的**:额度 10、剩 7.5,用了 2.5;42.25 是这把密钥从来用过的 + assert_eq!( + r, + Some(OpenRouterKey::Limited(Reading { + quota: Some(BalanceQuota { + limit: 10.0, + used: 2.5, + unit: "USD".into() + }), + ..Default::default() + })) + ); + // 没给剩余就用 usage + let r = openrouter_key(&json(r#"{"data":{"limit":10,"usage":4}}"#)); + let Some(OpenRouterKey::Limited(r)) = r else { + panic!("{r:?}") + }; + assert_eq!(r.quota.unwrap().used, 4.0); + } + + #[test] + fn an_openrouter_key_without_a_limit_needs_the_account_credits() { + assert_eq!( + openrouter_key(&json( + r#"{"data":{"label":"x","limit":null,"limit_remaining":null,"usage":3.1}}"# + )), + Some(OpenRouterKey::Unlimited) + ); + let r = openrouter_credits(&json(r#"{"data":{"total_credits":20,"total_usage":12.5}}"#)) + .unwrap(); + assert_eq!(r.wallet, usd(7.5)); + assert_eq!(r.quota, None); + } + + #[test] + fn an_openrouter_answer_it_cannot_read_is_none() { + assert_eq!(openrouter_key(&json(r#"{"error":"nope"}"#)), None); + assert_eq!(openrouter_key(&json(r#"{"data":{"limit":"ten"}}"#)), None); + assert_eq!(openrouter_key(&json(r#"{"data":{"limit":10}}"#)), None); + assert_eq!(openrouter_credits(&json(r#"{"data":{}}"#)), None); + } + + // ------------------------------------------------------------ DeepSeek + + #[test] + fn deepseek_shows_the_first_currency_that_has_money() { + let r = deepseek(&json( + r#"{"is_available":true,"balance_infos":[ + {"currency":"USD","total_balance":"0.00","granted_balance":"0.00","topped_up_balance":"0.00"}, + {"currency":"CNY","total_balance":"110.00","granted_balance":"10.00","topped_up_balance":"100.00"} + ]}"#, + )) + .unwrap(); + assert_eq!( + r.wallet, + Some(Money { + amount: 110.0, + currency: "CNY".into() + }) + ); + // 都没钱:第一个,**是 0,不是没有** + let r = deepseek(&json( + r#"{"is_available":false,"balance_infos":[ + {"currency":"CNY","total_balance":"0.00"}, + {"currency":"USD","total_balance":"0.00"} + ]}"#, + )) + .unwrap(); + assert_eq!( + r.wallet, + Some(Money { + amount: 0.0, + currency: "CNY".into() + }) + ); + } + + #[test] + fn deepseek_without_balance_infos_is_not_understood() { + assert_eq!(deepseek(&json(r#"{"error":{"message":"x"}}"#)), None); + assert_eq!( + deepseek(&json(r#"{"balance_infos":[{"currency":"CNY"}]}"#)), + None + ); + // 空的清单:读懂了,只是没有钱包 + assert_eq!( + deepseek(&json(r#"{"balance_infos":[]}"#)), + Some(Reading::default()) + ); + } + + // ------------------------------------------------------------ Moonshot + + #[test] + fn moonshot_reads_the_available_balance_in_the_currency_of_its_site() { + let body = json( + r#"{"code":0,"data":{"available_balance":49.58894,"voucher_balance":46.58893,"cash_balance":3.00001},"scode":"0x0","status":true}"#, + ); + assert_eq!( + moonshot(&body, "CNY").unwrap().wallet, + Some(Money { + amount: 49.58894, + currency: "CNY".into() + }) + ); + assert_eq!(moonshot(&body, "USD").unwrap().wallet, usd(49.58894)); + assert_eq!(moonshot(&json(r#"{"code":5,"data":null}"#), "CNY"), None); + } + + // ------------------------------------------------------------ Sub2API + + /// 一个真实的钱包模式回答的样子:用量明细一概不要 + #[test] + fn a_sub2api_wallet_reads_as_a_wallet() { + let v = json( + r#"{"mode":"unrestricted","isValid":true,"planName":"钱包余额","unit":"USD","balance":12.3456,"remaining":12.3456, + "usage":{"today":{"requests":3,"cost":0.12},"total":{"requests":90,"cost":7.65}}, + "daily_usage":[{"date":"2026-10-10","cost":0.12}], + "model_stats":[{"model":"claude-sonnet-4-5","requests":3}]}"#, + ); + assert!(is_sub2api(&v)); + assert!(!is_thinkwatch(&v)); + let r = sub2api(&v).unwrap(); + assert_eq!(r.wallet, usd(12.3456)); + assert_eq!(r.quota, None); + assert!(r.windows.is_empty()); + assert_eq!(r.expires_at_ms, None); + // 今天花了多少 + assert_eq!( + r.spent, + Some(Spent { + amount: 0.12, + currency: "USD".into(), + period: SpentPeriod::Today + }) + ); + } + + #[test] + fn a_sub2api_subscription_reads_as_daily_weekly_and_monthly_windows() { + let r = sub2api(&json( + r#"{"mode":"unrestricted","unit":"USD","expires_at":"2026-12-31T00:00:00Z", + "subscription":{"daily_usage_usd":1.5,"daily_limit_usd":10,"weekly_usage_usd":20,"weekly_limit_usd":50, + "monthly_usage_usd":20,"monthly_limit_usd":0}}"#, + )) + .unwrap(); + let names: Vec<_> = r.windows.iter().map(|w| w.window.as_str()).collect(); + // 月限额是 0:不限,不是「额度为 0」 + assert_eq!(names, ["daily", "weekly"]); + assert_eq!(r.windows[0].limit, 10.0); + assert_eq!(r.windows[0].used, 1.5); + assert_eq!(r.windows[0].unit, "USD"); + assert_eq!(r.windows[1].used, 20.0); + assert_eq!(r.wallet, None, "没写钱包就没有,不是 $0"); + assert_eq!(r.expires_at_ms, Some(ms("2026-12-31T00:00:00Z"))); + } + + #[test] + fn a_sub2api_quota_limited_key_reads_as_a_quota_and_its_rate_limits() { + let r = sub2api(&json( + r#"{"mode":"quota_limited","unit":"USD","expires_at":1798675200, + "quota":{"limit":100,"used":37.5,"remaining":62.5}, + "rate_limits":[ + {"window":"5h","limit":5,"used":1.25,"reset_at":"2026-10-11T03:00:00Z"}, + {"window":"1d","limit":20,"used":4,"reset_at":null}, + {"window":"7d","limit":"60","used":4}, + {"limit":1,"used":0} + ]}"#, + )) + .unwrap(); + assert_eq!( + r.quota, + Some(BalanceQuota { + limit: 100.0, + used: 37.5, + unit: "USD".into() + }) + ); + let names: Vec<_> = r.windows.iter().map(|w| w.window.as_str()).collect(); + assert_eq!(names, ["5h", "1d", "7d"], "没有名字的窗口不要"); + assert_eq!(r.windows[0].resets_at_ms, Some(ms("2026-10-11T03:00:00Z"))); + assert_eq!(r.windows[1].resets_at_ms, None); + assert_eq!(r.windows[2].limit, 60.0); + // 秒的时间戳 + assert_eq!(r.expires_at_ms, Some(1_798_675_200_000)); + assert_eq!(r.wallet, None); + } + + #[test] + fn sub2api_takes_the_unit_it_says() { + let r = sub2api(&json( + r#"{"mode":"unrestricted","unit":"CNY","balance":"8.5"}"#, + )) + .unwrap(); + assert_eq!( + r.wallet, + Some(Money { + amount: 8.5, + currency: "CNY".into() + }) + ); + } + + #[test] + fn without_a_string_mode_it_is_not_sub2api() { + assert!(!is_sub2api(&json(r#"{"mode":1}"#))); + assert!(!is_sub2api(&json(r#"{"object":"list"}"#))); + assert_eq!(sub2api(&json(r#"{"balance":3}"#)), None); + } + + // ------------------------------------------------------------ New API + + #[test] + fn a_limited_newapi_key_reads_as_a_quota_in_dollars() { + let sub = json( + r#"{"object":"billing_subscription","has_payment_method":true,"soft_limit_usd":25,"hard_limit_usd":25,"system_hard_limit_usd":25,"access_until":1798675200}"#, + ); + assert!(is_newapi(&sub)); + let r = newapi(&sub, &json(r#"{"object":"list","total_usage":1234.5}"#)).unwrap(); + // 已用是美分 + assert_eq!( + r.quota, + Some(BalanceQuota { + limit: 25.0, + used: 12.345, + unit: "USD".into() + }) + ); + assert_eq!(r.spent, None); + assert_eq!(r.expires_at_ms, Some(1_798_675_200_000)); + } + + #[test] + fn an_unlimited_newapi_key_only_says_what_it_spent() { + let sub = json( + r#"{"object":"billing_subscription","hard_limit_usd":100000000,"system_hard_limit_usd":100000000,"access_until":0}"#, + ); + let r = newapi(&sub, &json(r#"{"total_usage":500}"#)).unwrap(); + assert_eq!(r.quota, None, "1 亿美元不是一个额度"); + assert_eq!( + r.spent, + Some(Spent { + amount: 5.0, + currency: "USD".into(), + period: SpentPeriod::Total + }) + ); + assert_eq!(r.expires_at_ms, None, "0 是不到期"); + } + + #[test] + fn the_system_hard_limit_is_enough_to_recognize_newapi() { + let sub = json(r#"{"system_hard_limit_usd":7}"#); + assert!(is_newapi(&sub)); + let r = newapi(&sub, &json(r#"{"total_usage":100}"#)).unwrap(); + assert_eq!(r.quota.unwrap().limit, 7.0); + assert!(!is_newapi(&json(r#"{"object":"billing_subscription"}"#))); + assert_eq!(newapi(&sub, &json(r#"{"object":"list"}"#)), None); + } + + // ------------------------------------------------------------ ThinkWatch + + /// 企业网关的回答:`limits` 是这里给的那几条,`usage` 和 `expires_at` 照真实的写 + fn enterprise(limits: &str) -> Value { + json(&format!( + r#"{{"usage":{{"requests_today":3,"tokens_today":9000,"requests_month":80,"tokens_month":400000,"cost_usd_month":12.5}}, + "limits":[{limits}],"expires_at":"2027-01-01T00:00:00Z"}}"# + )) + } + + fn scopes(r: &Reading) -> Vec<(String, Option)> { + r.windows + .iter() + .map(|w| (w.window.clone(), w.scope)) + .collect() + } + + #[test] + fn enterprise_limits_of_the_key_alone() { + let v = enterprise( + r#"{"scope":"key","kind":"requests","window":"1h","window_secs":3600,"limit":100,"used":7,"resets_at":"2026-10-10T15:00:00Z"}, + {"scope":"key","kind":"tokens","window":"daily","window_secs":null,"limit":1000000,"used":250000,"resets_at":null}"#, + ); + assert!(is_thinkwatch(&v)); + assert!(!is_sub2api(&v)); + let r = thinkwatch(&v).unwrap(); + assert_eq!( + r.windows[0], + BalanceWindow { + window: "1h".into(), + limit: 100.0, + used: 7.0, + unit: "requests".into(), + resets_at_ms: Some(ms("2026-10-10T15:00:00Z")), + scope: Some(BalanceScope::Key), + } + ); + assert_eq!(r.windows[1].unit, "tokens"); + assert_eq!(r.windows[1].resets_at_ms, None); + assert_eq!( + r.spent, + Some(Spent { + amount: 12.5, + currency: "USD".into(), + period: SpentPeriod::Month + }) + ); + assert_eq!(r.expires_at_ms, Some(ms("2027-01-01T00:00:00Z"))); + // 企业网关没有钱包、没有总额度 + assert_eq!(r.wallet, None); + assert_eq!(r.quota, None); + } + + #[test] + fn enterprise_limits_of_the_user_alone() { + let r = thinkwatch(&enterprise( + r#"{"scope":"user","kind":"tokens","window":"1w","window_secs":604800,"limit":5000000,"used":1200000,"resets_at":"2026-10-13T00:00:00Z"}"#, + )) + .unwrap(); + assert_eq!(scopes(&r), [("1w".to_string(), Some(BalanceScope::User))]); + assert_eq!(r.windows[0].used, 1_200_000.0); + } + + #[test] + fn enterprise_limits_of_the_key_and_the_user_together() { + let r = thinkwatch(&enterprise( + r#"{"scope":"key","kind":"requests","window":"1m","window_secs":60,"limit":20,"used":2,"resets_at":null}, + {"scope":"user","kind":"requests","window":"1m","window_secs":60,"limit":60,"used":9,"resets_at":null}, + {"scope":"user","kind":"tokens","window":"monthly","window_secs":null,"limit":9000000,"used":400000,"resets_at":null}, + {"scope":"team","kind":"cost","window":"1d","limit":5,"used":1}"#, + )) + .unwrap(); + assert_eq!( + scopes(&r), + [ + ("1m".to_string(), Some(BalanceScope::Key)), + ("1m".to_string(), Some(BalanceScope::User)), + ("monthly".to_string(), Some(BalanceScope::User)), + ], + "认不出的 kind 不要" + ); + } + + /// 没有限额:只说得出这个月花了多少 + #[test] + fn an_enterprise_key_without_limits_only_says_what_it_spent() { + let r = thinkwatch(&json( + r#"{"usage":{"requests_today":0,"tokens_today":0,"requests_month":4,"tokens_month":800,"cost_usd_month":0.42},"limits":[],"expires_at":null}"#, + )) + .unwrap(); + assert!(r.windows.is_empty()); + assert_eq!(r.spent.as_ref().unwrap().amount, 0.42); + assert_eq!(r.spent.unwrap().period, SpentPeriod::Month); + assert_eq!(r.expires_at_ms, None); + // 这个月的花费不知道(null):没有花费,不是 $0 + let r = thinkwatch(&json( + r#"{"usage":{"cost_usd_month":null},"limits":[],"expires_at":null}"#, + )) + .unwrap(); + assert_eq!(r, Reading::default()); + assert_eq!(thinkwatch(&json(r#"{"limits":"none"}"#)), None); + } +} diff --git a/crates/tw-gateway/src/balances/tracker.rs b/crates/tw-gateway/src/balances/tracker.rs new file mode 100644 index 00000000..5ffba9f1 --- /dev/null +++ b/crates/tw-gateway/src/balances/tracker.rs @@ -0,0 +1,505 @@ +//! 什么时候去读余额,和读到的记在哪儿。**只算时间,不联网**:测试把时刻传进来。 +//! +//! 读的节奏: +//! - **启动时读一次**(还没读过的就该读); +//! - **有请求经过这一家、结束之后**,离上一次读满 [`AFTER_REQUEST_MS`] 就再读:余额是 +//! 请求结束时扣的,一阵连着的请求只在最后多读一次,不是每个请求读一次; +//! - 没有请求时每 [`EVERY_MS`] 读一次:别处(网页上、别的设备)花掉的也要看得见; +//! - 界面要的时候马上读([`Why::Demand`]),不看节奏。 +//! +//! `auto` 而地址不认识的,先问它是哪一种中转站(见 [`super::detect`])。**只问一次**: +//! 认出来了就记住,两种都不是就不再问(换了地址、凭据或者 `balance:` 才从头来); +//! 连不上、对方出错算没问成,隔 [`EVERY_MS`] 再问,**不跟着请求问**。 + +use std::collections::HashMap; +use std::sync::{Mutex, MutexGuard}; + +use tw_api::{Balance, BalanceSource, Msg}; + +use super::parse::Reading; + +/// 请求结束之后,离上一次读至少隔这么久才再读 +pub const AFTER_REQUEST_MS: u64 = 60_000; +/// 没有请求时隔这么久读一次;没问成的检测也隔这么久再问 +pub const EVERY_MS: u64 = 10 * 60_000; + +/// 这一家的余额从哪儿来:配置和地址就定了的,还是要先问一次。 +#[derive(Debug, Clone, Copy, PartialEq, Eq)] +pub enum Plan { + Known(BalanceSource), + Detect, +} + +/// 问「是哪一种中转站」的结果。 +#[derive(Debug, Clone, Copy, PartialEq, Eq)] +pub enum Detection { + Found(BalanceSource), + /// 两种都不是:这一家没有余额可读 + Neither, + /// 没问成:连不上、超时、对方出错 + Undecided, +} + +/// 为什么去读。 +#[derive(Debug, Clone, Copy, PartialEq, Eq)] +pub enum Why { + /// 后台的节奏:启动、请求结束之后、定时 + Due, + /// 界面要:马上读,不看节奏 + Demand, +} + +/// 这一次要做什么。 +#[derive(Debug, Clone, Copy, PartialEq, Eq)] +pub enum Step { + Read(BalanceSource), + /// 先问是哪一种中转站,认出来了接着读 + Detect, +} + +/// 一次读完的结果,交给 [`Tracker::settle`]。 +#[derive(Debug, Clone, Default)] +pub struct Outcome { + /// 问过「是哪一种」的话,问出来的 + pub detection: Option, + /// 读过的话:从哪儿读的、读到的或者没读成的原因 + pub read: Option<(BalanceSource, Result)>, +} + +/// 一次读的结果写成 [`Balance`]:读成了是读到的,没读成是空的加上原因。 +pub fn fresh(source: BalanceSource, read: Result, now_ms: u64) -> Balance { + let (r, error) = match read { + Ok(r) => (r, None), + Err(why) => (Reading::default(), Some(why)), + }; + Balance { + source, + read_at_ms: now_ms, + wallet: r.wallet, + quota: r.quota, + windows: r.windows, + expires_at_ms: r.expires_at_ms, + spent: r.spent, + error, + } +} + +/// 一家上游。 +#[derive(Debug, Default)] +struct Slot { + /// 地址、凭据和 `balance:` 的指纹。**变了就从头来**:之前读到的、问出来的说的是旧的 + ident: String, + detection: Option, + /// 最近一次读或者问完的时刻,不论结果 + tried_at: Option, + /// 上一次开始读之后,有请求经过这一家结束了 + dirty: bool, + /// 正在读的有几个。后台的节奏只在一个都没有时才读 + running: u32, + balance: Option, +} + +impl Slot { + /// 这一家读的是哪儿:配置定了的,或者问出来的 + fn source(&self, plan: Plan) -> Option { + match (plan, self.detection) { + (Plan::Known(s), _) | (Plan::Detect, Some(Detection::Found(s))) => Some(s), + _ => None, + } + } + + /// 按后台的节奏,现在该读(或者该问)了吗 + fn due(&self, plan: Plan, now_ms: u64) -> bool { + if self.running > 0 { + return false; + } + let Some(at) = self.tried_at else { + return true; + }; + let since = now_ms.saturating_sub(at); + if self.source(plan).is_some() { + return (self.dirty && since >= AFTER_REQUEST_MS) || since >= EVERY_MS; + } + match self.detection { + None => true, + // 没问成的隔一阵再问;**不看请求**,问一次就是两个请求 + Some(Detection::Undecided) => since >= EVERY_MS, + Some(Detection::Neither | Detection::Found(_)) => false, + } + } +} + +/// 每家上游的余额和读的节奏。**跨重载存活**:改一条路由规则不该让所有余额重读一遍。 +#[derive(Default)] +pub struct Tracker { + slots: Mutex>, + /// 有请求经过的上游结束了:叫醒后台(见 [`super::spawn`]),到了时候就读 + pub wake: tokio::sync::Notify, +} + +impl Tracker { + fn lock(&self) -> MutexGuard<'_, HashMap> { + // 锁中毒了照样用里面的:余额晚一点更新,好过不再更新 + self.slots.lock().unwrap_or_else(|p| p.into_inner()) + } + + /// 这一家现在要读吗、读什么。要读就占上,读完必须 [`Tracker::settle`]。 + /// + /// `Demand` 不看节奏:认出过的直接读,没认出来的(两种都不是、没问成)再问一次 + pub fn claim( + &self, + provider: &str, + ident: &str, + plan: Plan, + why: Why, + now_ms: u64, + ) -> Option { + let mut g = self.lock(); + let slot = g.entry(provider.to_string()).or_default(); + if slot.ident != ident { + *slot = Slot { + ident: ident.to_string(), + ..Default::default() + }; + } + if why == Why::Due && !slot.due(plan, now_ms) { + return None; + } + slot.running += 1; + // 这一次读到的已经算上了到此刻为止结束的请求 + slot.dirty = false; + Some(match slot.source(plan) { + Some(s) => Step::Read(s), + None => Step::Detect, + }) + } + + /// 读完了:记下节奏和读到的,交回这一家现在的余额。**凭据在这中间换了的话**,这个结果 + /// 说的是旧的那一份,不记,是 `None`。 + /// + /// 读成了的整份换上;没读成的**留着上一次读到的**,只记下原因 —— 一次超时不该让界面上 + /// 的余额消失。之前读的是别的来源(问出来的变了)就不留 + pub fn settle( + &self, + provider: &str, + ident: &str, + outcome: Outcome, + now_ms: u64, + ) -> Option> { + let mut g = self.lock(); + let slot = g.get_mut(provider).filter(|s| s.ident == ident)?; + slot.running = slot.running.saturating_sub(1); + slot.tried_at = Some(now_ms); + if let Some(d) = outcome.detection { + // 认出来过的不因为一次没问成就忘掉 + if !matches!(slot.detection, Some(Detection::Found(_))) || d != Detection::Undecided { + slot.detection = Some(d); + } + if !matches!(d, Detection::Found(_)) && outcome.read.is_none() { + slot.balance = None; + } + } + if let Some((source, read)) = outcome.read { + let before = slot.balance.take().filter(|b| b.source == source); + slot.balance = Some(match (read, before) { + (Err(why), Some(b)) => Balance { + error: Some(why), + ..b + }, + (read, _) => fresh(source, read, now_ms), + }); + } + Some(slot.balance.clone()) + } + + /// 有请求经过这一家结束了。**只做个记号**:读不读、什么时候读由节奏定 + pub fn note_request(&self, provider: &str) { + let known = match self.lock().get_mut(provider) { + Some(slot) => { + slot.dirty = true; + true + } + None => false, + }; + if known { + self.wake.notify_one(); + } + } + + /// 这一家现在的余额。凭据、地址或者 `balance:` 变过的话,记着的那份不作数 + pub fn get(&self, provider: &str, ident: &str) -> Option { + self.lock() + .get(provider) + .filter(|s| s.ident == ident) + .and_then(|s| s.balance.clone()) + } + + /// 配置里没有了的上游:忘掉 + pub fn retain(&self, keep: impl Fn(&str) -> bool) { + self.lock().retain(|name, _| keep(name)); + } +} + +#[cfg(test)] +mod tests { + use super::*; + use tw_api::Money; + use tw_types::msg; + + const NOW: u64 = 1_790_000_000_000; + const DS: Plan = Plan::Known(BalanceSource::Deepseek); + + fn wallet(amount: f64) -> Reading { + Reading { + wallet: Some(Money { + amount, + currency: "CNY".into(), + }), + ..Default::default() + } + } + + fn read(r: Result) -> Outcome { + Outcome { + detection: None, + read: Some((BalanceSource::Deepseek, r)), + } + } + + fn failed() -> Msg { + msg!("gw.balance.status", status = 502 => "x") + } + + /// 读一次:占上、读到 `amount`、记下 + fn read_at(t: &Tracker, now: u64, amount: f64) { + assert_eq!( + t.claim("ds", "k", DS, Why::Due, now), + Some(Step::Read(BalanceSource::Deepseek)) + ); + t.settle("ds", "k", read(Ok(wallet(amount))), now); + } + + #[test] + fn it_reads_at_start_and_then_every_ten_minutes() { + let t = Tracker::default(); + read_at(&t, NOW, 10.0); + assert_eq!(t.claim("ds", "k", DS, Why::Due, NOW + EVERY_MS - 1), None); + assert!(t.claim("ds", "k", DS, Why::Due, NOW + EVERY_MS).is_some()); + } + + /// 请求结束之后最多每 60 秒读一次:一阵连着的请求,在最后补读一次 + #[test] + fn requests_ending_trigger_a_read_at_most_every_minute() { + let t = Tracker::default(); + read_at(&t, NOW, 10.0); + t.note_request("ds"); + // 刚读过:一分钟之内不读 + assert_eq!(t.claim("ds", "k", DS, Why::Due, NOW + 10_000), None); + assert_eq!(t.claim("ds", "k", DS, Why::Due, NOW + 59_999), None); + read_at(&t, NOW + AFTER_REQUEST_MS, 9.0); + // 这之后没有请求:等满十分钟 + assert_eq!( + t.claim("ds", "k", DS, Why::Due, NOW + 3 * AFTER_REQUEST_MS), + None + ); + // 又有请求结束了:离上一次读已经过了一分钟,马上读 + t.note_request("ds"); + assert!( + t.claim("ds", "k", DS, Why::Due, NOW + 3 * AFTER_REQUEST_MS) + .is_some() + ); + } + + #[test] + fn a_request_ending_while_reading_counts_for_the_next_read() { + let t = Tracker::default(); + assert!(t.claim("ds", "k", DS, Why::Due, NOW).is_some()); + // 正在读:不另读 + assert_eq!(t.claim("ds", "k", DS, Why::Due, NOW + 1), None); + t.note_request("ds"); + t.settle("ds", "k", read(Ok(wallet(1.0))), NOW + 500); + assert!( + t.claim("ds", "k", DS, Why::Due, NOW + 500 + AFTER_REQUEST_MS) + .is_some() + ); + } + + #[test] + fn a_demand_reads_now_whatever_the_rhythm() { + let t = Tracker::default(); + read_at(&t, NOW, 10.0); + assert!(t.claim("ds", "k", DS, Why::Demand, NOW + 1).is_some()); + } + + /// 读失败了:**留着上一次读到的**,只记下原因;之后读成了,原因清掉 + #[test] + fn a_failed_read_keeps_the_last_good_reading_and_says_why() { + let t = Tracker::default(); + read_at(&t, NOW, 10.0); + assert!(t.claim("ds", "k", DS, Why::Demand, NOW + 5).is_some()); + let b = t + .settle("ds", "k", read(Err(failed())), NOW + 5) + .unwrap() + .unwrap(); + assert_eq!(b.wallet.as_ref().unwrap().amount, 10.0); + assert_eq!(b.read_at_ms, NOW, "是那一次读到的时刻"); + assert_eq!(b.error.as_ref().unwrap().code, "gw.balance.status"); + + assert!(t.claim("ds", "k", DS, Why::Demand, NOW + 9).is_some()); + let b = t + .settle("ds", "k", read(Ok(wallet(8.0))), NOW + 9) + .unwrap() + .unwrap(); + assert_eq!(b.wallet.unwrap().amount, 8.0); + assert_eq!(b.error, None); + } + + #[test] + fn a_first_read_that_fails_is_an_empty_balance_with_the_reason() { + let t = Tracker::default(); + assert!(t.claim("ds", "k", DS, Why::Due, NOW).is_some()); + let b = t + .settle("ds", "k", read(Err(failed())), NOW) + .unwrap() + .unwrap(); + assert_eq!(b.wallet, None); + assert_eq!(b.read_at_ms, NOW); + assert!(b.error.is_some()); + // 失败了也按节奏来,不重试个不停 + assert_eq!(t.claim("ds", "k", DS, Why::Due, NOW + 30_000), None); + } + + #[test] + fn a_new_key_starts_over() { + let t = Tracker::default(); + read_at(&t, NOW, 10.0); + assert!(t.get("ds", "k").is_some()); + assert_eq!(t.get("ds", "k2"), None, "换了凭据,旧的余额不作数"); + assert!(t.claim("ds", "k2", DS, Why::Due, NOW + 1).is_some()); + // 旧 key 的那一次晚到了:不记 + assert_eq!(t.settle("ds", "k", read(Ok(wallet(1.0))), NOW + 2), None); + } + + #[test] + fn detection_is_asked_once_and_remembered() { + let t = Tracker::default(); + assert_eq!( + t.claim("r", "k", Plan::Detect, Why::Due, NOW), + Some(Step::Detect) + ); + t.settle( + "r", + "k", + Outcome { + detection: Some(Detection::Found(BalanceSource::Sub2api)), + read: Some((BalanceSource::Sub2api, Ok(Reading::default()))), + }, + NOW, + ); + // 认出来了:之后直接读 + assert_eq!( + t.claim("r", "k", Plan::Detect, Why::Due, NOW + EVERY_MS), + Some(Step::Read(BalanceSource::Sub2api)) + ); + } + + /// 两种都不是:**不再问**,请求再多也不问;只有界面要的时候再问一次 + #[test] + fn a_host_that_is_neither_is_not_asked_again() { + let t = Tracker::default(); + assert!(t.claim("r", "k", Plan::Detect, Why::Due, NOW).is_some()); + let left = t.settle( + "r", + "k", + Outcome { + detection: Some(Detection::Neither), + read: None, + }, + NOW, + ); + assert_eq!(left, Some(None), "没有余额"); + for i in 1..20 { + t.note_request("r"); + assert_eq!( + t.claim("r", "k", Plan::Detect, Why::Due, NOW + i * EVERY_MS), + None + ); + } + assert_eq!( + t.claim("r", "k", Plan::Detect, Why::Demand, NOW + 1), + Some(Step::Detect) + ); + } + + /// 没问成:隔十分钟再问,**不跟着请求问** + #[test] + fn an_undecided_detection_waits_ten_minutes_whatever_the_traffic() { + let t = Tracker::default(); + assert!(t.claim("r", "k", Plan::Detect, Why::Due, NOW).is_some()); + t.settle( + "r", + "k", + Outcome { + detection: Some(Detection::Undecided), + read: None, + }, + NOW, + ); + t.note_request("r"); + assert_eq!( + t.claim("r", "k", Plan::Detect, Why::Due, NOW + AFTER_REQUEST_MS), + None + ); + assert_eq!( + t.claim("r", "k", Plan::Detect, Why::Due, NOW + EVERY_MS), + Some(Step::Detect) + ); + } + + #[test] + fn a_found_source_is_not_forgotten_because_one_detection_failed() { + let t = Tracker::default(); + assert!(t.claim("r", "k", Plan::Detect, Why::Due, NOW).is_some()); + t.settle( + "r", + "k", + Outcome { + detection: Some(Detection::Found(BalanceSource::Newapi)), + read: Some((BalanceSource::Newapi, Ok(Reading::default()))), + }, + NOW, + ); + assert!( + t.claim("r", "k", Plan::Detect, Why::Demand, NOW + 1) + .is_some() + ); + t.settle( + "r", + "k", + Outcome { + detection: Some(Detection::Undecided), + read: None, + }, + NOW + 2, + ); + assert_eq!( + t.claim("r", "k", Plan::Detect, Why::Demand, NOW + 3), + Some(Step::Read(BalanceSource::Newapi)) + ); + } + + #[test] + fn a_request_on_an_upstream_never_read_changes_nothing() { + let t = Tracker::default(); + t.note_request("nobody"); + assert_eq!(t.get("nobody", ""), None); + } + + #[test] + fn upstreams_no_longer_configured_are_forgotten() { + let t = Tracker::default(); + read_at(&t, NOW, 1.0); + t.retain(|name| name != "ds"); + assert_eq!(t.get("ds", "k"), None); + } +} diff --git a/crates/tw-gateway/src/egress.rs b/crates/tw-gateway/src/egress.rs index c294ebc0..ea4b6c2a 100644 --- a/crates/tw-gateway/src/egress.rs +++ b/crates/tw-gateway/src/egress.rs @@ -91,6 +91,17 @@ pub const CLIENT_IDENTITY: &[&str] = /// [`CLIENT_IDENTITY`] 之外,按前缀认的那一族 const CLIENT_IDENTITY_PREFIX: &str = "x-codex-"; +/// 读余额([`crate::balances`])时发的头,**只有这三个**:ThinkWatch 的 User-Agent、 +/// `Accept` 和凭据。那不是转发,没有客户端的头可取;上游配置里写的别的头也不发 —— +/// 余额接口只认凭据 +pub fn balance_headers(authorization: &str) -> [(&'static str, String); 3] { + [ + ("user-agent", crate::user_agent()), + ("accept", "application/json".to_string()), + ("authorization", authorization.to_string()), + ] +} + /// 客户端请求里的这个头发不发给这家。 pub fn takes_from_client(hop: &Hop, name: &str) -> bool { let n = name.to_ascii_lowercase(); diff --git a/crates/tw-gateway/src/lib.rs b/crates/tw-gateway/src/lib.rs index 98407c8d..e3b9bd29 100644 --- a/crates/tw-gateway/src/lib.rs +++ b/crates/tw-gateway/src/lib.rs @@ -11,6 +11,7 @@ pub mod affinity; pub mod answer_model; pub mod auth; pub mod balance; +pub mod balances; pub mod bedrock; pub mod bodies; pub mod cache_marks; diff --git a/crates/tw-gateway/src/server/pipeline/relay.rs b/crates/tw-gateway/src/server/pipeline/relay.rs index e046a743..b4cc0617 100644 --- a/crates/tw-gateway/src/server/pipeline/relay.rs +++ b/crates/tw-gateway/src/server/pipeline/relay.rs @@ -176,6 +176,8 @@ pub(super) fn respond( let mut pulse = crate::pulse::Pulse::new(plan.is_sse.then_some(upstream_dialect)); let abort = req.abort.clone(); let (bus, health) = (state.bus.clone(), state.health.clone()); + // 这个请求结束时记一笔,到了时候重读这一家的余额(见 `crate::balances`) + let passing = state.balance_passing(&upstream_name); let stream = async_stream::stream! { // **通行证跟着响应体走。**这个流被丢掉的时候它才还回去:正常 // 发完是一种,客户端中途断开、hyper 丢掉响应体是另一种 —— 两种 @@ -185,6 +187,7 @@ pub(super) fn respond( // 回答交完、客户端走掉,才轮到下一个 let _pass = pass; let _slot = slot; + let _passing = passing; // 结局也一样:流被丢掉的时候,它替流报「客户端取消」。 let mut ending = ending; let mut chunks = std::pin::pin!(chunks); diff --git a/crates/tw-gateway/src/state.rs b/crates/tw-gateway/src/state.rs index 5ffe8cfb..ecccc73d 100644 --- a/crates/tw-gateway/src/state.rs +++ b/crates/tw-gateway/src/state.rs @@ -10,6 +10,7 @@ use crate::health::Health; use crate::outbound::{base_client_builder, client_for_provider, proxy_shape}; use tw_types::{Msg, msg}; +mod balances; mod credentials; mod glm; pub use credentials::credential_failed; @@ -180,6 +181,9 @@ pub struct AppState { quotas: Arc>>, /// 每个 GLM Coding Plan 上游问额度的节奏(见 [`crate::glm`])。**跨重载存活** glm: Arc, + /// 每家上游的余额和读的节奏(见 [`crate::balances`])。**跨重载存活**:改一条规则不该 + /// 让所有余额重读一遍 + pub balances: Arc, /// 监听地址变了。**这是「温」那一级**(三级热重载) —— /// 换端口不能只换配置:监听器是启动时建的,不重建的话新端口上什么 /// 都没有,而旧端口还在服务。那种「改了没反应」比报错难查得多。 @@ -305,6 +309,7 @@ impl AppState { body_sink: Arc::new(std::sync::Mutex::new(None)), quotas: Arc::new(std::sync::Mutex::new(Default::default())), glm: Default::default(), + balances: Default::default(), relisten: Arc::new(tokio::sync::Notify::new()), listening: Arc::new(std::sync::Mutex::new(Default::default())), oauth: Arc::new(crate::oauth::Cache::new()), diff --git a/crates/tw-gateway/src/state/balances.rs b/crates/tw-gateway/src/state/balances.rs new file mode 100644 index 00000000..1d1564b1 --- /dev/null +++ b/crates/tw-gateway/src/state/balances.rs @@ -0,0 +1,249 @@ +//! 上游的余额:读谁、什么时候读、读到的怎么告诉界面(见 [`crate::balances`])。 + +use super::AppState; +use crate::balances::{self, Plan, Step, Why}; +use crate::server::now_ms; + +/// 一家要读余额的上游:怎么读、凭什么读。 +struct Target { + plan: Plan, + /// 地址、凭据和 `balance:` 的指纹,**不是凭据本身**:它只用来认出「换了」 + ident: String, + /// `Authorization` 的值 + auth: String, +} + +impl AppState { + /// 这一家读不读余额、怎么读。 + /// + /// **不读的**:ChatGPT 账号、Z.ai / BigModel 的地址(额度另有来处,见 [`crate::quota`]、 + /// [`crate::glm`])、Bedrock、OAuth 凭据的、没有凭据可发的、`balance: off` 的 + fn balance_target(&self, p: &tw_config::Provider) -> Option { + if p.is_bedrock() || p.effective_protocol() == Some(tw_config::Protocol::Chatgpt) { + return None; + } + if self.glm.sites().quota_url(&p.base_url).is_some() { + return None; + } + let plan = balances::plan(p.balance, &p.base_url)?; + let auth = balances::authorization(p)?; + let ident = blake3::hash( + format!( + "{}\n{}\n{}", + p.base_url.trim(), + p.credential_identity(), + tw_api::BalanceSetting::from(p.balance) + ) + .as_bytes(), + ) + .to_hex() + .to_string(); + Some(Target { plan, ident, auth }) + } + + /// 配置里的这一家读不读。**停用的不读**:用户不想用它了,不该再拿它的密钥去问 + fn saved_target(&self, p: &tw_config::Provider) -> Option { + if p.disabled { + return None; + } + self.balance_target(p) + } + + /// 这一家现在的余额([`tw_api::ProviderView::balance`])。没有余额可读、还没读完第一次 + /// 都是 `None` + pub fn balance_of(&self, p: &tw_config::Provider) -> Option { + let t = self.saved_target(p)?; + self.balances.get(&p.name, &t.ident) + } + + /// 到了时候的都去读,每家一个任务(见 [`crate::balances::tracker`])。后台不等它们; + /// 测试等 + pub fn start_due_balances(&self) -> Vec> { + let cfg = self.config(); + self.balances + .retain(|name| cfg.providers.iter().any(|p| p.name == name)); + cfg.providers + .iter() + .filter_map(|p| { + let t = self.saved_target(p)?; + let step = self + .balances + .claim(&p.name, &t.ident, t.plan, Why::Due, now_ms())?; + let state = self.clone(); + let (name, base_url) = (p.name.clone(), p.base_url.clone()); + Some(tokio::spawn(async move { + state.run_balance(&name, &base_url, t, step).await; + })) + }) + .collect() + } + + /// 界面要:马上读这一家,`auto` 而没认出来的再问一次。`None`:没有这一家,或者它 + /// 没有余额可读 + pub async fn refresh_balance(&self, name: &str) -> Option { + let cfg = self.config(); + let p = cfg.providers.iter().find(|p| p.name == name)?; + let t = self.saved_target(p)?; + let step = self + .balances + .claim(name, &t.ident, t.plan, Why::Demand, now_ms())?; + self.run_balance(name, &p.base_url, t, step).await.flatten() + } + + /// 做一步、记下来;读过了就报一条 `balance_updated`。交回这一家现在的余额;凭据在这 + /// 中间换了的话是 `None` + async fn run_balance( + &self, + name: &str, + base_url: &str, + t: Target, + step: Step, + ) -> Option> { + // 这一家自己的 client:走它该走的代理 + let http = self.client_for(name); + let outcome = balances::run(&http, step, base_url, &t.auth).await; + let read = outcome.read.is_some(); + if let Some((_, Err(why))) = &outcome.read { + tracing::debug!(provider = name, "the balance could not be read: {why}"); + } + let now = now_ms(); + let left = self.balances.settle(name, &t.ident, outcome, now)?; + if read { + self.bus.emit(tw_api::Event::BalanceUpdated { + id: self.bus.next_id(), + provider: name.to_string(), + at_ms: now, + }); + } + Some(left) + } + + /// 检测一家(可能还没保存的)上游时顺带读一次余额,`auto` 的先认是哪一种。**不记**: + /// 表单里的还不是配置。`http` 是检测用的那个 client,和转发走同一条出站路径 + pub async fn check_balance( + &self, + http: &reqwest::Client, + p: &tw_config::Provider, + ) -> Option { + let t = self.balance_target(p)?; + let step = match t.plan { + Plan::Known(s) => Step::Read(s), + Plan::Detect => Step::Detect, + }; + let (source, read) = balances::run(http, step, &p.base_url, &t.auth).await.read?; + Some(balances::tracker::fresh(source, read, now_ms())) + } + + /// 一个请求开始经过这一家:交回跟着它走的记号(见 [`balances::Passing`]) + pub(crate) fn balance_passing(&self, provider: &str) -> balances::Passing { + balances::Passing::new(self.balances.clone(), provider) + } +} + +#[cfg(test)] +mod tests { + use super::*; + use tw_config::{BalanceSetting, Config, Provider}; + + fn state(providers: Vec) -> AppState { + AppState::new(Config { + version: 1, + clients: vec![tw_config::Client { + name: "default".into(), + key: "tw-good".into(), + ..Default::default() + }], + providers, + ..Default::default() + }) + .unwrap() + } + + fn up(name: &str, base_url: &str) -> Provider { + Provider { + name: name.into(), + base_url: base_url.into(), + key: Some("sk-test".into()), + ..Default::default() + } + } + + /// 账号上游、Bedrock、Z.ai 的地址、OAuth、没有凭据的、停用的、关掉的:都不读 + #[test] + fn who_has_a_balance_to_read() { + let s = state(vec![]); + let reads = |p: Provider| s.saved_target(&p).is_some(); + assert!(reads(up("or", "https://openrouter.ai/api/v1"))); + assert!(reads(up("relay", "https://relay.example/v1"))); + assert!(!reads(up( + "chatgpt", + "https://chatgpt.com/backend-api/codex" + ))); + assert!(!reads(up( + "bedrock", + "https://bedrock-runtime.us-east-1.amazonaws.com" + ))); + assert!(!reads(up("glm", "https://api.z.ai/api/anthropic"))); + assert!(!reads(up( + "bigmodel", + "https://open.bigmodel.cn/api/anthropic" + ))); + // 写明了也不读:它们的额度另有来处 + assert!(!reads(Provider { + balance: BalanceSetting::Sub2api, + ..up("glm", "https://api.z.ai/api/anthropic") + })); + assert!(!reads(Provider { + key: None, + ..up("ollama", "http://127.0.0.1:11434") + })); + assert!(!reads(Provider { + disabled: true, + ..up("or", "https://openrouter.ai/api/v1") + })); + assert!(!reads(Provider { + balance: BalanceSetting::Off, + ..up("or", "https://openrouter.ai/api/v1") + })); + assert!(!reads(Provider { + key: None, + oauth: Some(tw_config::OAuth { + access: None, + expires_at: None, + refresh: "rt".into(), + endpoint: "https://auth.example/token".into(), + client_id: None, + client_secret: None, + refresh_before: None, + }), + ..up("corp", "https://llm.corp.example") + })); + } + + #[test] + fn a_new_key_or_setting_is_a_new_ident() { + let s = state(vec![]); + let ident = |p: &Provider| s.balance_target(p).unwrap().ident; + let a = up("relay", "https://relay.example/v1"); + let b = Provider { + key: Some("sk-other".into()), + ..a.clone() + }; + let c = Provider { + balance: BalanceSetting::Newapi, + ..a.clone() + }; + assert_ne!(ident(&a), ident(&b)); + assert_ne!(ident(&a), ident(&c)); + assert_eq!(ident(&a), ident(&a.clone())); + assert!(!ident(&a).contains("sk-test"), "指纹不是凭据本身"); + } + + /// 请求结束时只做记号:从没读过的上游什么都不发生,读过的到了时候才读 + #[tokio::test] + async fn a_request_ending_only_marks_the_upstream() { + let s = state(vec![up("relay", "https://relay.example/v1")]); + drop(s.balance_passing("relay")); + assert!(s.balances.get("relay", "").is_none()); + } +} diff --git a/crates/tw-gateway/src/ws/turn.rs b/crates/tw-gateway/src/ws/turn.rs index d7239642..cf20ec47 100644 --- a/crates/tw-gateway/src/ws/turn.rs +++ b/crates/tw-gateway/src/ws/turn.rs @@ -266,6 +266,8 @@ pub(crate) struct Turn { /// 密钥的并发通行证和这一家的位置:**跟着这一轮走**,回答完了、连接断了就还 _pass: crate::limits::Pass, _slot: crate::slots::Slot, + /// 这一轮结束时记一笔,到了时候重读这一家的余额(见 [`crate::balances`]) + _passing: crate::balances::Passing, } impl Turn { @@ -594,6 +596,7 @@ pub(crate) async fn admit(a: Admit) -> Result { cut: None, _pass: pass, _slot: slot, + _passing: state.balance_passing(&line.provider), }) } diff --git a/crates/tw-gateway/tests/balances.rs b/crates/tw-gateway/tests/balances.rs new file mode 100644 index 00000000..b7b125fd --- /dev/null +++ b/crates/tw-gateway/tests/balances.rs @@ -0,0 +1,383 @@ +//! 上游的余额:认出是哪一种中转站、读、读不成时留着上一次的、请求结束时记一笔。 +//! +//! **全程只对本机的假服务器**:每一种余额接口的回答照它们的字段写,密钥是编的。 + +use std::collections::HashMap; +use std::net::SocketAddr; +use std::sync::{Arc, Mutex}; +use std::time::Duration; + +use axum::Router; +use axum::extract::State; +use axum::http::{HeaderMap, Uri}; +use axum::response::IntoResponse; +use axum::routing::any; +use tw_api::{BalanceScope, BalanceSource, Event, Money, Spent, SpentPeriod}; +use tw_config::{BalanceSetting, Client, Config, Provider}; + +/// 收到的一个余额请求 +#[derive(Debug, Clone)] +struct Seen { + path: String, + query: Option, + auth: String, + user_agent: String, + accept: String, +} + +/// 一台假服务器:每个路径回什么(没写的是 404),收到过什么 +#[derive(Default)] +struct Fake { + answers: Mutex>, + seen: Mutex>, +} + +impl Fake { + fn answer(&self, path: &str, status: u16, body: &str) { + self.answers + .lock() + .unwrap() + .insert(path.to_string(), (status, body.to_string())); + } + fn paths(&self) -> Vec { + self.seen + .lock() + .unwrap() + .iter() + .map(|s| s.path.clone()) + .collect() + } +} + +async fn handle(State(f): State>, uri: Uri, h: HeaderMap) -> axum::response::Response { + let header = |name: &str| { + h.get(name) + .and_then(|v| v.to_str().ok()) + .unwrap_or_default() + .to_string() + }; + // 模型请求不算余额请求 + if uri.path().ends_with("/v1/messages") { + return ( + [("content-type", "application/json")], + r#"{"type":"message","role":"assistant","content":[{"type":"text","text":"ok"}],"usage":{"input_tokens":3,"output_tokens":1}}"#, + ) + .into_response(); + } + f.seen.lock().unwrap().push(Seen { + path: uri.path().to_string(), + query: uri.query().map(str::to_string), + auth: header("authorization"), + user_agent: header("user-agent"), + accept: header("accept"), + }); + let (status, body) = f + .answers + .lock() + .unwrap() + .get(uri.path()) + .cloned() + .unwrap_or((404, r#"{"error":"not found"}"#.to_string())); + ( + axum::http::StatusCode::from_u16(status).unwrap(), + [("content-type", "application/json")], + body, + ) + .into_response() +} + +async fn start(f: Arc) -> SocketAddr { + let app = Router::new().fallback(any(handle)).with_state(f); + 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 +} + +/// 一家指向假服务器的上游。地址带着 `/anthropic`:余额接口接在源后面,不接在它后面 +fn state_for(addr: SocketAddr, balance: BalanceSetting) -> tw_gateway::AppState { + tw_gateway::AppState::new(Config { + clients: vec![Client { + name: "c".into(), + key: "tw-k".into(), + ..Default::default() + }], + providers: vec![Provider { + name: "relay".into(), + base_url: format!("http://{addr}/anthropic"), + key: Some("sk-relay-fake".into()), + protocol: Some(tw_config::Protocol::Anthropic), + balance, + ..Default::default() + }], + ..Default::default() + }) + .unwrap() +} + +/// 到了时候的都读完 +async fn read_due(state: &tw_gateway::AppState) { + for h in state.start_due_balances() { + tokio::time::timeout(Duration::from_secs(15), h) + .await + .expect("a read took too long") + .unwrap(); + } +} + +fn balance(state: &tw_gateway::AppState) -> Option { + state.balance_of(&state.config().providers[0]) +} + +/// 总线上已经有的 `balance_updated` +fn updates(rx: &mut tokio::sync::broadcast::Receiver) -> usize { + std::iter::from_fn(|| rx.try_recv().ok()) + .filter(|e| matches!(e, Event::BalanceUpdated { provider, .. } if provider == "relay")) + .count() +} + +const SUB2API_WALLET: &str = r#"{"mode":"unrestricted","isValid":true,"planName":"钱包余额","unit":"USD","balance":12.3456,"remaining":12.3456, + "usage":{"today":{"requests":3,"input_tokens":1200,"output_tokens":300,"cost":0.12},"total":{"requests":90,"cost":7.65}}, + "daily_usage":[{"date":"2026-10-10","requests":3,"cost":0.12}], + "model_stats":[{"model":"claude-sonnet-4-5","requests":3,"cost":0.12}]}"#; + +#[tokio::test] +async fn auto_finds_a_sub2api_relay_and_reads_its_wallet_from_the_same_answer() { + let f = Arc::new(Fake::default()); + f.answer("/v1/usage", 200, SUB2API_WALLET); + let state = state_for(start(f.clone()).await, BalanceSetting::Auto); + let mut rx = state.bus.subscribe(); + + read_due(&state).await; + let b = balance(&state).expect("a balance"); + assert_eq!(b.source, BalanceSource::Sub2api); + assert_eq!( + b.wallet, + Some(Money { + amount: 12.3456, + currency: "USD".into() + }) + ); + assert_eq!( + b.spent, + Some(Spent { + amount: 0.12, + currency: "USD".into(), + period: SpentPeriod::Today + }) + ); + assert_eq!(b.error, None); + assert_eq!(updates(&mut rx), 1); + + // **认出来的那一次回答就是余额**:只问了一次。凭据是这家的密钥,按 Bearer 发; + // User-Agent 是 ThinkWatch 的 + let seen = f.seen.lock().unwrap().clone(); + assert_eq!(seen.len(), 1, "{seen:?}"); + assert_eq!(seen[0].path, "/v1/usage"); + assert_eq!(seen[0].auth, "Bearer sk-relay-fake"); + assert!(seen[0].user_agent.starts_with("thinkwatch/"), "{seen:?}"); + assert_eq!(seen[0].accept, "application/json"); + + // 刚读过:不再读 + read_due(&state).await; + assert_eq!(f.paths().len(), 1); +} + +#[tokio::test] +async fn auto_finds_a_new_api_relay_and_reads_its_quota() { + let f = Arc::new(Fake::default()); + f.answer( + "/v1/dashboard/billing/subscription", + 200, + r#"{"object":"billing_subscription","has_payment_method":true,"soft_limit_usd":25,"hard_limit_usd":25,"system_hard_limit_usd":25,"access_until":0}"#, + ); + f.answer( + "/v1/dashboard/billing/usage", + 200, + r#"{"object":"list","total_usage":1234.5}"#, + ); + let state = state_for(start(f.clone()).await, BalanceSetting::Auto); + + read_due(&state).await; + let b = balance(&state).expect("a balance"); + assert_eq!(b.source, BalanceSource::Newapi); + let q = b.quota.unwrap(); + assert_eq!((q.limit, q.used, q.unit.as_str()), (25.0, 12.345, "USD")); + assert_eq!(b.wallet, None); + assert_eq!( + f.paths(), + [ + "/v1/usage", + "/v1/dashboard/billing/subscription", + "/v1/dashboard/billing/usage" + ] + ); + let usage = f.seen.lock().unwrap()[2].query.clone().unwrap_or_default(); + assert!( + usage.contains("start_date=") && usage.contains("end_date="), + "{usage}" + ); +} + +/// 两种都不是:没有余额,**不再问**,请求结束了也不问。只有界面要的时候再问一次 +#[tokio::test] +async fn a_host_that_is_neither_has_no_balance_and_is_not_asked_again() { + let f = Arc::new(Fake::default()); + let state = state_for(start(f.clone()).await, BalanceSetting::Auto); + let mut rx = state.bus.subscribe(); + + read_due(&state).await; + assert_eq!(balance(&state), None); + assert_eq!(f.paths().len(), 2, "{:?}", f.paths()); + for _ in 0..5 { + state.balances.note_request("relay"); + read_due(&state).await; + } + assert_eq!(f.paths().len(), 2, "又去问了:{:?}", f.paths()); + assert_eq!(updates(&mut rx), 0, "没有余额,不用报"); + + assert_eq!(state.refresh_balance("relay").await, None); + assert_eq!(f.paths().len(), 4, "界面要的时候再问一次"); +} + +#[tokio::test] +async fn an_explicit_source_reads_on_the_origin_not_on_the_base_path() { + let f = Arc::new(Fake::default()); + f.answer( + "/user/balance", + 200, + r#"{"is_available":true,"balance_infos":[{"currency":"USD","total_balance":"0.00"},{"currency":"CNY","total_balance":"110.00"}]}"#, + ); + let state = state_for(start(f.clone()).await, BalanceSetting::Deepseek); + + read_due(&state).await; + assert_eq!(f.paths(), ["/user/balance"], "不是 /anthropic/user/balance"); + let b = balance(&state).unwrap(); + assert_eq!(b.source, BalanceSource::Deepseek); + assert_eq!( + b.wallet, + Some(Money { + amount: 110.0, + currency: "CNY".into() + }) + ); +} + +#[tokio::test] +async fn openrouter_without_a_key_limit_reads_the_account_credits() { + let f = Arc::new(Fake::default()); + f.answer( + "/api/v1/key", + 200, + r#"{"data":{"label":"sk-or-v1-fak...e","limit":null,"limit_remaining":null,"usage":3.1}}"#, + ); + f.answer( + "/api/v1/credits", + 200, + r#"{"data":{"total_credits":20,"total_usage":12.5}}"#, + ); + let state = state_for(start(f.clone()).await, BalanceSetting::Openrouter); + + read_due(&state).await; + assert_eq!(f.paths(), ["/api/v1/key", "/api/v1/credits"]); + assert_eq!(balance(&state).unwrap().wallet.unwrap().amount, 7.5); +} + +const ENTERPRISE: &str = r#"{"usage":{"requests_today":3,"tokens_today":9000,"requests_month":80,"tokens_month":400000,"cost_usd_month":12.5}, + "limits":[{"scope":"key","kind":"requests","window":"1h","window_secs":3600,"limit":100,"used":7,"resets_at":null}, + {"scope":"user","kind":"tokens","window":"daily","window_secs":null,"limit":1000000,"used":250000,"resets_at":null}], + "expires_at":null}"#; + +/// 企业网关回了 503:**留着上一次读到的**,记下原因;之后读成了,原因清掉 +#[tokio::test] +async fn a_failing_read_keeps_the_last_good_reading_and_says_why() { + let f = Arc::new(Fake::default()); + f.answer("/v1/usage", 200, ENTERPRISE); + let state = state_for(start(f.clone()).await, BalanceSetting::Thinkwatch); + let mut rx = state.bus.subscribe(); + + let first = state.refresh_balance("relay").await.unwrap(); + assert_eq!(first.source, BalanceSource::Thinkwatch); + assert_eq!(first.windows.len(), 2); + assert_eq!(first.windows[1].scope, Some(BalanceScope::User)); + assert_eq!(first.spent.as_ref().unwrap().period, SpentPeriod::Month); + + f.answer("/v1/usage", 503, r#"{"error":"busy"}"#); + let failed = state.refresh_balance("relay").await.unwrap(); + let why = failed.error.clone().expect("the reason"); + assert_eq!(why.code, "gw.balance.status"); + assert_eq!(why.arg("status"), "503"); + assert_eq!(failed.windows, first.windows, "上一次读到的留着"); + assert_eq!(failed.spent, first.spent); + assert_eq!(failed.read_at_ms, first.read_at_ms, "还是那一次读到的时刻"); + assert_eq!(balance(&state), Some(failed)); + + f.answer("/v1/usage", 200, ENTERPRISE); + let again = state.refresh_balance("relay").await.unwrap(); + assert_eq!(again.error, None); + assert_eq!(updates(&mut rx), 3, "每读一次报一次"); +} + +/// 读不懂的回答、拒绝密钥:原因各说各的 +#[tokio::test] +async fn the_reason_says_what_went_wrong() { + let f = Arc::new(Fake::default()); + f.answer("/user/balance", 200, r#"maintenance"#); + let state = state_for(start(f.clone()).await, BalanceSetting::Deepseek); + let b = state.refresh_balance("relay").await.unwrap(); + assert_eq!(b.error.unwrap().code, "gw.balance.unrecognized"); + assert_eq!(b.wallet, None); + + f.answer("/user/balance", 401, r#"{"error":"bad key"}"#); + let b = state.refresh_balance("relay").await.unwrap(); + let why = b.error.unwrap(); + assert_eq!(why.code, "gw.balance.rejected"); + assert!(!why.text.contains("sk-relay-fake")); +} + +/// 换了 `balance:`:之前读到的不再作数,从头来 +#[tokio::test] +async fn changing_the_setting_starts_over() { + let f = Arc::new(Fake::default()); + f.answer("/v1/usage", 200, SUB2API_WALLET); + let state = state_for(start(f.clone()).await, BalanceSetting::Sub2api); + read_due(&state).await; + assert!(balance(&state).is_some()); + + let mut cfg = (*state.config()).clone(); + cfg.providers[0].balance = BalanceSetting::Off; + state.reload(cfg).unwrap(); + assert_eq!(balance(&state), None); + read_due(&state).await; + assert_eq!(f.paths().len(), 1, "关掉了就不读"); +} + +/// 一个请求经过这一家、结束了:叫醒后台(到了时候就读,见 tracker 的测试) +#[tokio::test] +async fn a_request_through_the_upstream_wakes_the_balance_reader() { + let f = Arc::new(Fake::default()); + f.answer("/v1/usage", 200, SUB2API_WALLET); + let state = state_for(start(f.clone()).await, BalanceSetting::Sub2api); + read_due(&state).await; + let gw = tw_gateway::serve(state.clone(), ([127, 0, 0, 1], 0).into()) + .await + .unwrap(); + + let r = reqwest::Client::new() + .post(format!("http://{gw}/v1/messages")) + .header("x-api-key", "tw-k") + .header("content-type", "application/json") + .body(r#"{"model":"claude-sonnet-4-5","max_tokens":8,"messages":[{"role":"user","content":"hi"}]}"#) + .send() + .await + .unwrap(); + assert!(r.status().is_success(), "{}", r.status()); + let _ = r.bytes().await.unwrap(); + + tokio::time::timeout(Duration::from_secs(5), state.balances.wake.notified()) + .await + .expect("the end of the request did not reach the balance reader"); + // 刚读过:一分钟之内不因为这个请求再读 + read_due(&state).await; + assert_eq!(f.paths(), ["/v1/usage"]); +} diff --git a/crates/tw-observe/src/bus.rs b/crates/tw-observe/src/bus.rs index 28d24f6c..1c9c845d 100644 --- a/crates/tw-observe/src/bus.rs +++ b/crates/tw-observe/src/bus.rs @@ -112,6 +112,7 @@ fn about_the_request(ev: &tw_api::Event) -> bool { | E::RequestPriced { .. } | E::QuotaSeen { .. } | E::QuotaExhausted { .. } + | E::BalanceUpdated { .. } // 一把密钥的用量到了上限:说的是那把密钥,不是哪一个请求 | E::KeyLimitAlert { .. } | E::LocallyAnswered { .. } diff --git a/crates/tw-store/src/recorder.rs b/crates/tw-store/src/recorder.rs index 91d620d1..2c46e62f 100644 --- a/crates/tw-store/src/recorder.rs +++ b/crates/tw-store/src/recorder.rs @@ -666,6 +666,8 @@ impl Recorder { | Event::ConfigRejected { .. } | Event::QuotaSeen { .. } | Event::QuotaExhausted { .. } + // 余额同理:是那家上游现在的样子 + | Event::BalanceUpdated { .. } // 密钥用量到了上限:说的是那把密钥现在的样子,它的用量就是这张表里的那些行 | Event::KeyLimitAlert { .. } // 凭据轮换说的是配置文件该改了,跟哪一次请求无关 diff --git a/docs/config.md b/docs/config.md index fac9474c..80ea475e 100644 --- a/docs/config.md +++ b/docs/config.md @@ -405,6 +405,7 @@ Upstreams: the APIs requests are forwarded to. | `model_specs` | map of model id → [`providers[].model_specs.*`](#cfg-providers-model_specs) | `{}` | Context window, output limit, reasoning and image input of single models of this upstream, written by hand, by exact model id. They take precedence over the price table: for models it does not know, or gets wrong. | | `max_concurrent` | integer | — | Most requests sent to this upstream at the same time, from 1 to 1000. When it is full, a conversation that stays on it waits for a free slot and other requests go to the next upstream; see `failover.slot_wait_secs`. Unset: no limit. | | `disabled` | bool | `false` | Take the upstream out of routing and out of the model list, and keep its configuration. | +| `balance` | `auto` \| `off` \| `openrouter` \| `deepseek` \| `moonshot` \| `sub2api` \| `newapi` \| `thinkwatch` | `auto` | Where the upstream's balance is read from, with its own key and proxy: `openrouter`, `deepseek`, `moonshot`, `sub2api`, `newapi` (New API and One API) or `thinkwatch` (a ThinkWatch Enterprise gateway). `auto`: recognized from `base_url` for OpenRouter, DeepSeek and Moonshot; any other address, except Anthropic's, OpenAI's and Gemini's own, is asked once whether it is a Sub2API, ThinkWatch Enterprise or New API relay, and the answer is kept in memory only. `off`: no balance. ChatGPT and Z.ai accounts and Bedrock have no balance whatever is written here. | A credential is one of four things: `key`, which goes in the header the diff --git a/docs/config.zh-CN.md b/docs/config.zh-CN.md index 94b7cf7b..f03a0029 100644 --- a/docs/config.zh-CN.md +++ b/docs/config.zh-CN.md @@ -303,6 +303,7 @@ clients: | `model_specs` | 映射: 模型 ID → [`providers[].model_specs.*`](#cfg-providers-model_specs) | `{}` | 手写这家上游某些模型的上下文窗口、输出上限、会不会推理、收不收图,按模型 ID 完全匹配。写了就优先于价目表,用于价目表里没有或写错的模型。 | | `max_concurrent` | 整数 | — | 同时发给这家的请求最多几个,取值 1 到 1000。满了的时候,留在这家的对话等空位,别的请求换下一家;等多久见 `failover.slot_wait_secs`。不写:不限。 | | `disabled` | 布尔 | `false` | 不参与路由,模型也不出现在模型列表里;配置原样保留。 | +| `balance` | `auto` \| `off` \| `openrouter` \| `deepseek` \| `moonshot` \| `sub2api` \| `newapi` \| `thinkwatch` | `auto` | 从哪里读这家上游的余额,用它自己的密钥、走它自己的代理:`openrouter`、`deepseek`、`moonshot`、`sub2api`、`newapi`(New API 和 One API)或 `thinkwatch`(ThinkWatch 企业网关)。`auto`:OpenRouter、DeepSeek、Moonshot 按 `base_url` 识别;其他地址(Anthropic、OpenAI、Gemini 的官方地址除外)询问一次它是不是 Sub2API、ThinkWatch 企业网关或 New API 中转站,结果只保存在内存中。`off`:不读余额。ChatGPT、Z.ai 账号和 Bedrock 不读余额,与这里写什么无关。 | 凭据有四种写法:`key`,放进协议规定的请求头;`oauth`,用 refresh token 换取 token;`aws`,Bedrock 上游签名请求用的访问密钥;`headers`,用于上游自有的鉴权方式。`headers` 可以和其余几种同时使用,但不能再设置已经承载凭据的那个请求头。 diff --git a/scripts/smoke.sh b/scripts/smoke.sh index 258cf9c4..2f18b3fa 100755 --- a/scripts/smoke.sh +++ b/scripts/smoke.sh @@ -534,6 +534,11 @@ done C=$(post /dryrun '{"model":"claude-sonnet-4-5","route":"默认"}'); [ "$C" = "200" ] && ok "POST /dryrun" || bad "POST /dryrun 返回 $C" # 页面打开时补问模型清单:立刻返回开始问的那几家,不等上游回话 C=$(post /models/refresh '{}'); [ "$C" = "200" ] && ok "POST /models/refresh" || bad "POST /models/refresh 返回 $C" +# 余额:假上游哪一种中转站都不是,马上读一次是 404 并说清没有余额可读;概览带着配置里的 balance +C=$(post /providers/relay/balance/refresh '{}') +if [ "$C" = "404" ] && grep -q '"control.balance_none"' "$TMP/out"; then ok "POST /providers/{name}/balance/refresh"; else bad "POST /providers/relay/balance/refresh 返回 $C" "$(head -c 300 "$TMP/out")"; fi +C=$(ctl /overview | python3 -c 'import json,sys;p=json.load(sys.stdin)["providers"][0];print(p["balance_setting"]=="auto" and "balance" in p)') +[ "$C" = "True" ] && ok "/overview 带余额字段" || bad "/overview 的余额字段不对:$C" C=$(ctl /overview | python3 -c 'import json,sys;p=json.load(sys.stdin)["providers"][0];print(p["model_status"] in ("pending","listed","no_list","failed") and isinstance(p["model_fetching"],bool))') [ "$C" = "True" ] && ok "/overview 带模型获取状态" || bad "/overview 的模型状态字段不对:$C"