diff --git a/crates/tw-api/src/ep.rs b/crates/tw-api/src/ep.rs index 78369172..5a950125 100644 --- a/crates/tw-api/src/ep.rs +++ b/crates/tw-api/src/ep.rs @@ -118,7 +118,8 @@ endpoints! { SetManualModels: PUT "/provider-manual-models", api::ManualModelsSave => api::ConfigWritten; RefreshProviderModels: POST "/providers/{name}/models/refresh" [name], () => api::ProviderModelsView; /// 马上读一次这家的余额(`balance` 是 `auto` 时先认出是哪一种中转站)。没有余额可读的 - /// 是 404(`control.balance_none`) + /// 是 404(`control.balance_none`);`auto` 的没问成是哪一种(连不上、超时、对方出错) + /// 是 502,带着原因(`gw.balance.*`) RefreshBalance: POST "/providers/{name}/balance/refresh" [name], () => api::Balance; RefreshStaleModels: POST "/models/refresh", () => api::ModelsRefreshing; CreateProxy: POST "/proxies", api::ProxySave => api::ConfigWritten; diff --git a/crates/tw-api/src/lib.rs b/crates/tw-api/src/lib.rs index eb57765c..ffe527b1 100644 --- a/crates/tw-api/src/lib.rs +++ b/crates/tw-api/src/lib.rs @@ -893,7 +893,8 @@ pub const MSG_CODES: &str = include_str!("../msg-codes.txt"); /// `balance`(不给是 `auto`),[`ProviderTestResult`] 多了 `balance`(检测时顺带读一次)。 /// 新事件 [`Event::BalanceUpdated`]:一家的余额读过了,重读它的视图。新端点 /// `POST /providers/{name}/balance/refresh`(→ [`Balance`])马上读一次;没有余额可读是 404 -/// (`control.balance_none`)。读失败的原因是 `gw.balance.*`。配置里的 `balance:` 写了不认识的 +/// (`control.balance_none`),`auto` 的没问成是哪一种中转站是 502(原因是 `gw.balance.*`)。 +/// 读失败的原因是 `gw.balance.*`。配置里的 `balance:` 写了不认识的 /// 取值时加载不了(`config.unknown_variant`,一键修复改回 `auto`)。照 45 写的界面不认这个事件。 pub const CONTROL_API_VERSION: u32 = 46; @@ -4740,7 +4741,7 @@ pub struct ProviderQuota { slug_enum! { /// 上游的余额从哪个接口读。每一种都用这家上游自己的密钥、走它自己的出站设置。 pub enum BalanceSource { - /// OpenRouter:这把密钥的额度(`/api/v1/key`),没有额度时是账户余额(`/api/v1/credits`) + /// OpenRouter:这把密钥的额度和花费(`/api/v1/key`)。账户余额只有管理密钥问得到,不读 Openrouter = "openrouter", /// DeepSeek 开放平台的账户余额(`/user/balance`) Deepseek = "deepseek", @@ -4748,7 +4749,8 @@ slug_enum! { Moonshot = "moonshot", /// Sub2API 中转站的用量接口(`/v1/usage`) Sub2api = "sub2api", - /// New API / One API 中转站的账单接口(`/v1/dashboard/billing/...`) + /// New API / One API 中转站的账单接口(`/v1/dashboard/billing/...`),单位看站点的 + /// 状态接口(`/api/status`) Newapi = "newapi", /// ThinkWatch 企业网关的密钥用量接口(`/v1/usage`) Thinkwatch = "thinkwatch", @@ -4806,7 +4808,8 @@ pub struct Balance { /// 密钥或套餐什么时候到期,Unix 毫秒。不会到期、上游没说都是空 pub expires_at_ms: Option, /// 已经花了多少,和算的是哪一段时间:没有上限可比时说得出的就是它(New API 不限 - /// 额度的密钥、Sub2API 今天的花费、企业网关这个月的花费) + /// 额度的密钥、OpenRouter 这把密钥这个月的花费、Sub2API 今天实际扣的、企业网关这个月的 + /// 花费) pub spent: Option, /// 最近一次没读成的原因。读成了是空 pub error: Option, @@ -4836,6 +4839,8 @@ slug_enum! { #[cfg_attr(feature = "ts", derive(ts_rs::TS))] pub struct Spent { pub amount: f64, + /// `USD`、`CNY` 这样的货币代码。New API 站点的额度按 token 显示时是 `tokens`(花掉的是 + /// token,不是钱),站点没说怎么显示时是 `unknown`(只是一个数) pub currency: String, pub period: SpentPeriod, /// 花的是谁的:这把密钥自己的,还是它所属的用户整体的(几把密钥合计)。只有企业网关 @@ -4859,7 +4864,8 @@ slug_enum! { pub struct BalanceQuota { pub limit: f64, pub used: f64, - /// `USD` / `CNY` / `tokens` / `requests` + /// `USD` / `CNY` / `tokens` / `requests`,或者 `unknown`:上游没说数是按什么计的 + /// (New API 站点的状态接口说不出它的额度怎么显示),只是一个数,**不是美元** pub unit: String, } diff --git a/crates/tw-control/src/resources.rs b/crates/tw-control/src/resources.rs index 7f68290e..91161bd6 100644 --- a/crates/tw-control/src/resources.rs +++ b/crates/tw-control/src/resources.rs @@ -232,6 +232,9 @@ async fn preview_provider( })) } +/// 「检测连接」顺带读余额最多等多久 +const CHECK_BALANCE_WAIT: std::time::Duration = std::time::Duration::from_secs(5); + /// 检测一个上游,**不保存**。 /// /// 走的出站路径和转发完全一样:同一个构造 client 的函数、同一套凭据取法。 @@ -305,9 +308,14 @@ async fn test_provider( tw_gateway::probe(&http, &p.base_url, &headers, protocol).await }; // 通了就顺带读一次余额(`auto` 的先认是哪一种)。不通的不读:地址或凭据不对, - // 余额也读不到,只是多等一会儿 + // 余额也读不到,只是多等一会儿。**最多等 [`CHECK_BALANCE_WAIT`]**:认来源加读最多三个 + // 请求、每个最多等十秒,检测结果不该陪着等半分钟;没读完的就不带余额,保存下来的上游 + // 由后台照常读(读到了报 `balance_updated`) let balance = if r.ok { - s.gateway.check_balance(&http, &p).await + tokio::time::timeout(CHECK_BALANCE_WAIT, s.gateway.check_balance(&http, &p)) + .await + .ok() + .flatten() } else { None }; @@ -323,7 +331,8 @@ async fn test_provider( } /// 马上读一次这家的余额。没有这一家是 404(`control.upstream_not_found`),它没有余额 -/// 可读也是 404(`control.balance_none`) +/// 可读也是 404(`control.balance_none`)。`auto` 的这一家没问成是哪一种中转站(连不上、 +/// 超时、对方出错)是 502,带着没问成的原因(`gw.balance.*`):那不是「没有余额」 async fn refresh_balance( State(s): State, Path(name): Path, @@ -332,8 +341,9 @@ async fn refresh_balance( return Err(crate::no_such_upstream(&name)); } match s.gateway.refresh_balance(&name).await { - Some(b) => Ok(Json(b)), - None => Err(fail( + Ok(Some(b)) => Ok(Json(b)), + Err(why) => Err(fail(StatusCode::BAD_GATEWAY, why)), + Ok(None) => Err(fail( StatusCode::NOT_FOUND, msg!( "control.balance_none", upstream = &name => diff --git a/crates/tw-control/tests/resources.rs b/crates/tw-control/tests/resources.rs index fbb4d100..3fd30884 100644 --- a/crates/tw-control/tests/resources.rs +++ b/crates/tw-control/tests/resources.rs @@ -981,6 +981,60 @@ async fn checking_an_upstream_also_reads_its_balance() { assert_eq!(json(&body)["balance"], serde_json::Value::Null, "{body}"); } +/// 余额读得慢的中转站:模型清单马上回,用量接口一直不回 +async fn fake_relay_with_a_slow_balance() -> std::net::SocketAddr { + let app = axum::Router::new() + .route( + "/anthropic/v1/models", + axum::routing::get(|| async { + ( + StatusCode::OK, + r#"{"data":[{"id":"claude-sonnet-4-5"}]}"#.to_string(), + ) + }), + ) + .route( + "/v1/usage", + axum::routing::get(|| async { + tokio::time::sleep(std::time::Duration::from_secs(60)).await; + (StatusCode::OK, "{}".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 +} + +/// 余额读得慢:「检测连接」**最多等五秒**,到时候先交回检测结果,不带余额 +#[tokio::test] +async fn checking_an_upstream_does_not_wait_long_for_its_balance() { + let b = bed(BASE); + let up = fake_relay_with_a_slow_balance().await; + let started = std::time::Instant::now(); + let (st, body) = call( + &b.app, + "POST", + "/provider-test", + serde_json::json!({ "provider": { + "name": "relay", + "base_url": format!("http://{up}/anthropic"), + "key": "sk-good", + "protocol": "anthropic", + }}), + ) + .await; + let took = started.elapsed(); + assert_eq!(st, StatusCode::OK, "{body}"); + let v = json(&body); + assert_eq!(v["ok"], true, "{body}"); + assert_eq!(v["balance"], serde_json::Value::Null, "{body}"); + assert!( + took >= std::time::Duration::from_secs(5) && took < std::time::Duration::from_secs(8), + "{took:?}" + ); +} + /// `balance` 写进配置;`auto` 不写。概览原样给回 `balance_setting` #[tokio::test] async fn the_balance_setting_is_saved_and_shown() { @@ -1069,6 +1123,35 @@ async fn refreshing_a_balance_reads_it_now_and_the_overview_shows_it() { assert!(updated); } +/// `auto` 的中转站没问成是哪一种(对方出错):502,带着原因,不说「没有余额」 +#[tokio::test] +async fn refreshing_an_upstream_that_could_not_be_asked_says_why() { + let app = axum::Router::new().route( + "/v1/usage", + axum::routing::get(|| async { (StatusCode::SERVICE_UNAVAILABLE, "{}") }), + ); + let l = tokio::net::TcpListener::bind("127.0.0.1:0").await.unwrap(); + let up = l.local_addr().unwrap(); + tokio::spawn(async move { axum::serve(l, app).await.unwrap() }); + 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 (st, body) = call( + &b.app, + "POST", + "/providers/relay/balance/refresh", + serde_json::Value::Null, + ) + .await; + assert_eq!(st, StatusCode::BAD_GATEWAY, "{body}"); + let v = json(&body); + assert_eq!(v["code"], "gw.balance.status", "{body}"); + assert_eq!(v["args"]["status"], "503", "{body}"); +} + #[tokio::test] async fn refreshing_an_upstream_without_a_balance_is_a_404() { let b = bed(BASE); diff --git a/crates/tw-gateway/src/balances.rs b/crates/tw-gateway/src/balances.rs index a1c7a191..95bda5a2 100644 --- a/crates/tw-gateway/src/balances.rs +++ b/crates/tw-gateway/src/balances.rs @@ -24,7 +24,7 @@ use tw_api::BalanceSource; use tw_types::{Msg, msg}; pub use parse::Reading; -pub use tracker::{Detection, Outcome, Plan, Step, Tracker, Why}; +pub use tracker::{Claim, Detection, Outcome, Plan, Step, Tracker, Why}; /// 跟着一个经过这一家的请求走:请求结束时(它被丢掉时,正常交完、客户端走掉都一样) /// 记一笔,到了时候就重读这一家的余额(见 [`tracker`])。**只做个记号,不联网** @@ -160,19 +160,22 @@ impl Failure { } } - /// 对方说了话(4xx、读不懂的回答):它就是这样,再问也一样。连不上、超时、5xx、429 - /// 说明不了什么 + /// 对方说了话(转到别处去、4xx、读不懂的回答):它就是这样,再问也一样。连不上、超时、 + /// 5xx、429 说明不了什么。 + /// + /// **3xx 也是回答**:出站的 client 不跟跳转,问到一个跳去登录页、首页的地址,说明这里 + /// 没有这个接口,不是没问成 fn answered(&self) -> bool { match self { Failure::Transport(_) => false, - Failure::Status(s) => (400..500).contains(s) && *s != 429, + Failure::Status(s) => (300..500).contains(s) && *s != 429, Failure::Unrecognized => true, } } } -/// 发一个 GET,读回 JSON。 -async fn get_json(http: &reqwest::Client, url: &str, auth: &str) -> Result { +/// 发一个 GET,读回 JSON。`auth` 是 `None` 的不带凭据(公开的接口) +async fn get_json(http: &reqwest::Client, url: &str, auth: Option<&str>) -> Result { let mut req = http.get(url).timeout(TIMEOUT); for (name, value) in crate::egress::balance_headers(auth) { req = req.header(name, value); @@ -223,40 +226,48 @@ fn chain(e: &reqwest::Error) -> String { 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; +/// 问出来的是哪一种。 +#[derive(Debug)] +pub enum Detected { + /// 认出来了,**连同认出它的那一次回答**:Sub2API 和企业网关的余额就在里面,New API 的 + /// 总额度也在,不用再问一遍 + Found(BalanceSource, Value), + /// 两个都答了话,可都不是 + Neither, + /// 有一个没问成:连不上、超时、对方出错。带着头一个没问成的原因 + Undecided(Failure), +} + +/// 先问 Sub2API(和企业网关)的用量接口,再问 New API 的账单接口。 +pub async fn detect(http: &reqwest::Client, origin: &str, auth: &str) -> Detected { + let usage = get_json(http, &format!("{origin}/v1/usage"), Some(auth)).await; if let Ok(v) = &usage { if parse::is_sub2api(v) { - return (Detection::Found(BalanceSource::Sub2api), usage.ok()); + return Detected::Found(BalanceSource::Sub2api, v.clone()); } if parse::is_thinkwatch(v) { - return (Detection::Found(BalanceSource::Thinkwatch), usage.ok()); + return Detected::Found(BalanceSource::Thinkwatch, v.clone()); } } let billing = get_json( http, &format!("{origin}/v1/dashboard/billing/subscription"), - auth, + Some(auth), ) .await; if let Ok(v) = &billing && parse::is_newapi(v) { - return (Detection::Found(BalanceSource::Newapi), billing.ok()); + return Detected::Found(BalanceSource::Newapi, v.clone()); } - // 两个都答了话(不是这个形状、没有这个接口、不认这把密钥):两种都不是。有一个没问成, - // 就说不准 - 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) + // 两个都答了话(不是这个形状、没有这个接口、不认这把密钥、转到别处去):两种都不是。 + // 有一个没问成,就说不准 + match [usage, billing] + .into_iter() + .find_map(|r| r.err().filter(|f| !f.answered())) + { + Some(f) => Detected::Undecided(f), + None => Detected::Neither, } } @@ -271,7 +282,7 @@ pub async fn read( 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 } + async move { get_json(http, &url, Some(auth)).await } }; let known_or = |path: &'static str| { let known = known.clone(); @@ -284,13 +295,9 @@ pub async fn read( }; 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), - }, + // **只问这把密钥自己的接口**:账户余额(`/api/v1/credits`)只有管理密钥问得到, + // 能转发请求的密钥问它是 403 + BalanceSource::Openrouter => parsed(parse::openrouter(&get("/api/v1/key").await?)), BalanceSource::Deepseek => parsed(parse::deepseek(&get("/user/balance").await?)), BalanceSource::Moonshot => { // 回答里不写货币:国际站是美元,国内站是人民币 @@ -309,7 +316,15 @@ pub async fn read( 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)) + // 账单接口的数按站点的额度显示方式折算(美元、人民币或者 token),回答里不说是 + // 哪一种:问站点的状态接口。它是公开的,不带凭据。答了话却说不出来的,单位是 + // 「不知道」;没问成的这一次就没读成,留着上一次读到的 + let unit = match get_json(http, &format!("{origin}/api/status"), None).await { + Ok(status) => parse::newapi_unit(&status), + Err(f) if f.answered() => parse::UNKNOWN, + Err(f) => return Err(f), + }; + parsed(parse::newapi(&subscription, &usage, unit)) } } } @@ -326,7 +341,7 @@ fn newapi_usage_path(today: chrono::NaiveDate) -> String { ) } -/// 做一步:要先认来源的先认,认出来了接着读。交回这一次的结果(给 [`Tracker::settle`]) +/// 做一步:要先认来源的先认,认出来了接着读。交回这一次的结果(给 [`tracker::Claim::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 { @@ -337,10 +352,16 @@ pub async fn run(http: &reqwest::Client, step: Step, base_url: &str, auth: &str) 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, _) => { + Detected::Found(s, known) => (s, Some(known), Some(Detection::Found(s))), + Detected::Neither => { + return Outcome { + detection: Some(Detection::Neither), + read: None, + }; + } + Detected::Undecided(f) => { return Outcome { - detection: Some(other), + detection: Some(Detection::Undecided(f.msg())), read: None, }; } diff --git a/crates/tw-gateway/src/balances/parse.rs b/crates/tw-gateway/src/balances/parse.rs index fbf82be7..f5fe462f 100644 --- a/crates/tw-gateway/src/balances/parse.rs +++ b/crates/tw-gateway/src/balances/parse.rs @@ -55,54 +55,53 @@ fn stamp(n: f64) -> Option { // ---------------------------------------------------------------- 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,…}}`,美元。 +/// `GET /api/v1/key`:`{"data":{"limit":10,"limit_remaining":7.5,"limit_reset":"monthly", +/// "usage":42.25,"usage_daily":0.5,"usage_monthly":2.5,"expires_at":null,…}}`,美元。 /// -/// **已用按额度减剩余算**:设了按天、按月重置的额度时,`usage` 是这把密钥从来用过的 -/// 总数,`limit_remaining` 才是这一期还剩多少。没给剩余时才用 `usage` -pub fn openrouter_key(v: &Value) -> Option { +/// - 设了额度(`limit` 不是 null)是总额度。**已用按额度减剩余算**:设了按天、按月重置的 +/// 额度时,`usage` 是这把密钥从来用过的总数,`limit_remaining` 才是这一期还剩多少。没给 +/// 剩余时才用 `usage`; +/// - 花了多少:这个月的(`usage_monthly`),没给就是从来一共的(`usage`); +/// - `expires_at` 是到期时刻。 +/// +/// **没有钱包**:账户余额只有管理密钥问得到,能转发请求的密钥看不到 +pub fn openrouter(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, + let usage = data.get("usage").and_then(number); + let quota = match data.get("limit") { + None | Some(Value::Null) => None, + Some(l) => { + let limit = number(l)?; + let used = match (data.get("limit_remaining").and_then(number), usage) { + (Some(remaining), _) => (limit - remaining).max(0.0), + (None, Some(usage)) => usage, + (None, None) => return None, + }; + Some(BalanceQuota { + limit, + used, + unit: USD.to_string(), + }) + } }; - 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")?)?; + let spent = match data.get("usage_monthly").and_then(number) { + Some(month) => Some((month, SpentPeriod::Month)), + None => usage.map(|total| (total, SpentPeriod::Total)), + } + .map(|(amount, period)| Spent { + amount, + currency: USD.to_string(), + period, + scope: None, + }); + // 额度和花费都说不出来的,不是这个接口的回答 + if quota.is_none() && spent.is_none() { + return None; + } Some(Reading { - wallet: Some(Money { - amount: credits - usage, - currency: USD.to_string(), - }), + quota, + spent, + expires_at_ms: data.get("expires_at").and_then(moment), ..Default::default() }) } @@ -170,7 +169,8 @@ pub fn is_sub2api(v: &Value) -> bool { /// 或者钱包余额(`balance`)。 /// /// 金额的单位看顶层的 `unit`,没写是美元。`expires_at` 是到期时刻。用量明细里只取今天 -/// 花了多少(`usage.today.cost`),别的(`daily_usage`、`model_stats`)不要 +/// 花了多少:**实际扣的**(`usage.today.actual_cost`,按分组倍率算过的),没给才用按标价 +/// 算的 `cost`;别的(`daily_usage`、`model_stats`)不要 pub fn sub2api(v: &Value) -> Option { let mode = v.get("mode")?.as_str()?; let unit = v @@ -187,8 +187,12 @@ pub fn sub2api(v: &Value) -> Option { .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) + .and_then(|u| u.get("today")) + .and_then(|t| { + t.get("actual_cost") + .and_then(number) + .or_else(|| t.get("cost").and_then(number)) + }) .map(|amount| Spent { amount, currency: unit.clone(), @@ -256,9 +260,14 @@ pub fn sub2api(v: &Value) -> Option { // ---------------------------------------------------------------- New API / One API -/// 「不限额度」的密钥报的总额度就是这个数(或者更大) +/// 「不限额度」的密钥报的总额度就是这个数(New API 和 One API 都写死成它) const UNLIMITED: f64 = 100_000_000.0; +/// 数是按 token 计的(New API 站点的额度按 token 显示) +pub const TOKENS: &str = "tokens"; +/// 说不清数是按什么计的:站点没说它的额度怎么显示 +pub const UNKNOWN: &str = "unknown"; + /// 这是 New API / One API 的账单接口吗:有 `hard_limit_usd` 或 `system_hard_limit_usd` pub fn is_newapi(v: &Value) -> bool { hard_limit(v).is_some() @@ -270,22 +279,59 @@ fn hard_limit(v: &Value) -> Option { .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`,**美分**)。 +/// New API / One API 账单接口里的数是按什么计的,看站点的状态接口(`GET /api/status`, +/// 公开的):`{"success":true,"data":{"quota_display_type":"CNY","display_in_currency":true,…}}`。 /// -/// 不限额度的密钥(总额度 ≥ 1 亿)没有额度可言,只说得出花了多少 -pub fn newapi(subscription: &Value, usage: &Value) -> Option { +/// 账单接口**按站点的额度显示方式折算**,字段名里的 `usd` 不作数: +/// - `quota_display_type`(New API 新版):`USD` 是美元;`CNY` 是人民币;`TOKENS` 是 token; +/// `CUSTOM`(自定义货币)在账单接口里仍按美元折算,是美元; +/// - 没有它的(New API 旧版、One API)看 `display_in_currency`:是 true 按美元折算, +/// false 是 token; +/// - 都说不出来的是 [`UNKNOWN`],**不当作美元**:猜错了,一个 token 数就成了一笔钱 +pub fn newapi_unit(status: &Value) -> &'static str { + let Some(data) = status.get("data") else { + return UNKNOWN; + }; + let in_currency = data.get("display_in_currency").and_then(Value::as_bool); + match data.get("quota_display_type").and_then(Value::as_str) { + Some("USD" | "CUSTOM") => USD, + Some("CNY") => "CNY", + Some("TOKENS") => TOKENS, + // 不认识的显示方式:只说得出是不是 token + Some(_) => match in_currency { + Some(false) => TOKENS, + _ => UNKNOWN, + }, + None => match in_currency { + Some(true) => USD, + Some(false) => TOKENS, + None => UNKNOWN, + }, + } +} + +/// `GET /v1/dashboard/billing/subscription`(总额度 `hard_limit_usd`;到期 `access_until`, +/// Unix 秒,0 是不到期)加 `GET /v1/dashboard/billing/usage`(已用 `total_usage`,**乘过 +/// 100**,美元时是美分)。单位 `unit` 是 [`newapi_unit`] 问出来的,两个接口一样。 +/// +/// 不限额度的密钥报的总额度是 1 亿,没有额度可言,只说得出花了多少。按钱计的,1 亿以上 +/// 都不会是真的额度;**按 token 计(或者不知道按什么计)的只认正好 1 亿**:比它大的 +/// token 额度是真的 +pub fn newapi(subscription: &Value, usage: &Value, unit: &str) -> 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 { + let unlimited = match unit { + TOKENS | UNKNOWN => limit == UNLIMITED, + _ => limit >= UNLIMITED, + }; + if unlimited { r.spent = Some(Spent { amount: used, - currency: USD.to_string(), + currency: unit.to_string(), period: SpentPeriod::Total, scope: None, }); @@ -293,7 +339,7 @@ pub fn newapi(subscription: &Value, usage: &Value) -> Option { r.quota = Some(BalanceQuota { limit, used, - unit: USD.to_string(), + unit: unit.to_string(), }); } Some(r) @@ -390,51 +436,76 @@ mod tests { // ------------------------------------------------------------ OpenRouter + /// 设了额度的密钥,照 `/api/v1/key` 真实回答的字段写 + const OPENROUTER_LIMITED: &str = r#"{"data":{"label":"sk-or-v1-abc...xyz","limit":10,"limit_remaining":7.5,"limit_reset":"monthly","include_byok_in_limit":false, + "usage":42.25,"usage_daily":0.5,"usage_weekly":1.75,"usage_monthly":2.5, + "byok_usage":0,"byok_usage_daily":0,"byok_usage_weekly":0,"byok_usage_monthly":0, + "is_free_tier":false,"is_management_key":false,"is_provisioning_key":false, + "expires_at":"2027-01-01T00:00:00Z","creator_user_id":"user_x","organization_id":null,"workspace_id":null, + "allowed_data_regions":["global"],"free_model_daily_requests":{"limit":1000,"used":0,"remaining":1000}, + "rate_limit":{"requests":-1,"interval":"10s","note":"deprecated"}}}"#; + + /// 没设额度的密钥:大多数密钥都是这样 + const OPENROUTER_UNLIMITED: &str = r#"{"data":{"label":"sk-or-v1-def...uvw","limit":null,"limit_remaining":null,"limit_reset":null,"include_byok_in_limit":false, + "usage":3.1,"usage_daily":0.2,"usage_weekly":0.9,"usage_monthly":1.4, + "byok_usage":0,"byok_usage_daily":0,"byok_usage_weekly":0,"byok_usage_monthly":0, + "is_free_tier":false,"is_management_key":false,"is_provisioning_key":false, + "creator_user_id":"user_x","organization_id":null,"workspace_id":null, + "allowed_data_regions":["global"],"free_model_daily_requests":{"limit":1000,"used":3,"remaining":997}, + "rate_limit":{"requests":-1,"interval":"10s","note":"deprecated"}}}"#; + + fn spent_usd(amount: f64, period: SpentPeriod) -> Option { + Some(Spent { + amount, + currency: "USD".into(), + period, + scope: None, + }) + } + #[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}}"#, - )); + let r = openrouter(&json(OPENROUTER_LIMITED)).unwrap(); // **已用是这一期的**:额度 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() - })) + r.quota, + Some(BalanceQuota { + limit: 10.0, + used: 2.5, + unit: "USD".into() + }) ); - // 没给剩余就用 usage - let r = openrouter_key(&json(r#"{"data":{"limit":10,"usage":4}}"#)); - let Some(OpenRouterKey::Limited(r)) = r else { - panic!("{r:?}") - }; + assert_eq!(r.spent, spent_usd(2.5, SpentPeriod::Month)); + assert_eq!(r.expires_at_ms, Some(ms("2027-01-01T00:00:00Z"))); + assert_eq!(r.wallet, None); + // 没给剩余就用 usage;没给这个月的,花费是从来一共的 + let r = openrouter(&json(r#"{"data":{"limit":10,"usage":4}}"#)).unwrap(); assert_eq!(r.quota.unwrap().used, 4.0); + assert_eq!(r.spent, spent_usd(4.0, SpentPeriod::Total)); } + /// 没设额度:**只说得出花了多少**,没有钱包 —— 账户余额这把密钥问不到 #[test] - fn an_openrouter_key_without_a_limit_needs_the_account_credits() { + fn an_openrouter_key_without_a_limit_says_what_it_spent() { + let r = openrouter(&json(OPENROUTER_UNLIMITED)).unwrap(); assert_eq!( - openrouter_key(&json( - r#"{"data":{"label":"x","limit":null,"limit_remaining":null,"usage":3.1}}"# - )), - Some(OpenRouterKey::Unlimited) + r, + Reading { + spent: spent_usd(1.4, SpentPeriod::Month), + ..Default::default() + } ); - let r = openrouter_credits(&json(r#"{"data":{"total_credits":20,"total_usage":12.5}}"#)) - .unwrap(); - assert_eq!(r.wallet, usd(7.5)); + let r = openrouter(&json(r#"{"data":{"limit":null,"usage":3.1}}"#)).unwrap(); + assert_eq!(r.spent, spent_usd(3.1, SpentPeriod::Total)); 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); + assert_eq!(openrouter(&json(r#"{"error":"nope"}"#)), None); + assert_eq!(openrouter(&json(r#"{"data":{"limit":"ten"}}"#)), None); + assert_eq!(openrouter(&json(r#"{"data":{"limit":10}}"#)), None); + assert_eq!(openrouter(&json(r#"{"data":{"limit":null}}"#)), None); } // ------------------------------------------------------------ DeepSeek @@ -511,7 +582,7 @@ mod tests { 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}}, + "usage":{"today":{"requests":3,"cost":0.12,"actual_cost":0.096},"total":{"requests":90,"cost":7.65,"actual_cost":6.12}}, "daily_usage":[{"date":"2026-10-10","cost":0.12}], "model_stats":[{"model":"claude-sonnet-4-5","requests":3}]}"#, ); @@ -522,16 +593,22 @@ mod tests { assert_eq!(r.quota, None); assert!(r.windows.is_empty()); assert_eq!(r.expires_at_ms, None); - // 今天花了多少 + // 今天花了多少:**实际扣的**,不是按标价算的 0.12 assert_eq!( r.spent, Some(Spent { - amount: 0.12, + amount: 0.096, currency: "USD".into(), period: SpentPeriod::Today, scope: None, }) ); + // 没给实际扣的:按标价算的 + let r = sub2api(&json( + r#"{"mode":"unrestricted","balance":1,"usage":{"today":{"requests":3,"cost":0.12}}}"#, + )) + .unwrap(); + assert_eq!(r.spent.unwrap().amount, 0.12); } #[test] @@ -614,7 +691,12 @@ mod tests { 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(); + let r = newapi( + &sub, + &json(r#"{"object":"list","total_usage":1234.5}"#), + "USD", + ) + .unwrap(); // 已用是美分 assert_eq!( r.quota, @@ -633,28 +715,129 @@ mod tests { 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(); + let r = newapi(&sub, &json(r#"{"total_usage":500}"#), "USD").unwrap(); assert_eq!(r.quota, None, "1 亿美元不是一个额度"); + assert_eq!(r.spent, spent_usd(5.0, 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}"#), "USD").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"}"#), "USD"), None); + } + + /// 站点的状态接口:照 New API 新版、旧版和 One API 回答里的那两个字段写 + fn status(data: &str) -> Value { + json(&format!( + r#"{{"success":true,"message":"","data":{{"version":"v0.9.0","system_name":"New API",{data}"quota_per_unit":500000}}}}"# + )) + } + + #[test] + fn the_newapi_unit_is_the_display_type_of_the_site() { + let unit = |data: &str| newapi_unit(&status(data)); + assert_eq!( + unit(r#""quota_display_type":"USD","display_in_currency":true,"#), + "USD" + ); + assert_eq!( + unit( + r#""quota_display_type":"CNY","display_in_currency":true,"usd_exchange_rate":7.3,"# + ), + "CNY" + ); + assert_eq!( + unit(r#""quota_display_type":"TOKENS","display_in_currency":false,"#), + "tokens" + ); + // 自定义货币只在网页上换算,账单接口仍按美元折算 + assert_eq!( + unit( + r#""quota_display_type":"CUSTOM","display_in_currency":true,"custom_currency_symbol":"€","# + ), + "USD" + ); + // 旧版和 One API 只有 display_in_currency + assert_eq!(unit(r#""display_in_currency":true,"#), "USD"); + assert_eq!(unit(r#""display_in_currency":false,"#), "tokens"); + // 说不出来的:不知道,**不当作美元** + assert_eq!(unit(""), "unknown"); + assert_eq!( + unit(r#""quota_display_type":"POINTS","display_in_currency":true,"#), + "unknown" + ); + assert_eq!( + unit(r#""quota_display_type":"POINTS","display_in_currency":false,"#), + "tokens" + ); + assert_eq!(newapi_unit(&json(r#"{"error":"not found"}"#)), "unknown"); + } + + #[test] + fn a_newapi_site_in_yuan_reads_in_yuan() { + let sub = json(r#"{"hard_limit_usd":73,"access_until":0}"#); + let r = newapi(&sub, &json(r#"{"total_usage":1460}"#), "CNY").unwrap(); + assert_eq!( + r.quota, + Some(BalanceQuota { + limit: 73.0, + used: 14.6, + unit: "CNY".into() + }) + ); + } + + /// 按 token 计:数是 token;**只有正好 1 亿是不限额度**,比它大的 token 额度是真的 + #[test] + fn a_newapi_site_in_tokens_reads_in_tokens() { + let r = newapi( + &json(r#"{"hard_limit_usd":500000000}"#), + &json(r#"{"total_usage":12000000000}"#), + "tokens", + ) + .unwrap(); + assert_eq!( + r.quota, + Some(BalanceQuota { + limit: 500_000_000.0, + used: 120_000_000.0, + unit: "tokens".into() + }) + ); + let r = newapi( + &json(r#"{"hard_limit_usd":100000000}"#), + &json(r#"{"total_usage":250000}"#), + "tokens", + ) + .unwrap(); + assert_eq!(r.quota, None); assert_eq!( r.spent, Some(Spent { - amount: 5.0, - currency: "USD".into(), + amount: 2500.0, + currency: "tokens".into(), period: SpentPeriod::Total, scope: None, }) ); - 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); + fn a_newapi_site_that_does_not_say_has_an_unknown_unit() { + let r = newapi( + &json(r#"{"hard_limit_usd":300000000}"#), + &json(r#"{"total_usage":100}"#), + "unknown", + ) + .unwrap(); + let q = r.quota.unwrap(); + assert_eq!((q.limit, q.unit.as_str()), (300_000_000.0, "unknown")); } // ------------------------------------------------------------ ThinkWatch diff --git a/crates/tw-gateway/src/balances/tracker.rs b/crates/tw-gateway/src/balances/tracker.rs index 5ffba9f1..22c333b6 100644 --- a/crates/tw-gateway/src/balances/tracker.rs +++ b/crates/tw-gateway/src/balances/tracker.rs @@ -10,9 +10,13 @@ //! `auto` 而地址不认识的,先问它是哪一种中转站(见 [`super::detect`])。**只问一次**: //! 认出来了就记住,两种都不是就不再问(换了地址、凭据或者 `balance:` 才从头来); //! 连不上、对方出错算没问成,隔 [`EVERY_MS`] 再问,**不跟着请求问**。 +//! +//! 去读的占上一家([`Tracker::claim`] 交回的 [`Claim`]),读完交回结果([`Claim::settle`])。 +//! **没交回就丢掉的也放手**:读的任务被取消、界面那头断开了,这一家照样按节奏读,不会 +//! 一直算作「正在读」。 use std::collections::HashMap; -use std::sync::{Mutex, MutexGuard}; +use std::sync::{Arc, Mutex, MutexGuard}; use tw_api::{Balance, BalanceSource, Msg}; @@ -31,13 +35,13 @@ pub enum Plan { } /// 问「是哪一种中转站」的结果。 -#[derive(Debug, Clone, Copy, PartialEq, Eq)] +#[derive(Debug, Clone, PartialEq, Eq)] pub enum Detection { Found(BalanceSource), /// 两种都不是:这一家没有余额可读 Neither, - /// 没问成:连不上、超时、对方出错 - Undecided, + /// 没问成:连不上、超时、对方出错。带着没问成的原因(`gw.balance.*`) + Undecided(Msg), } /// 为什么去读。 @@ -57,7 +61,7 @@ pub enum Step { Detect, } -/// 一次读完的结果,交给 [`Tracker::settle`]。 +/// 一次读完的结果,交给 [`Claim::settle`]。 #[derive(Debug, Clone, Default)] pub struct Outcome { /// 问过「是哪一种」的话,问出来的 @@ -102,8 +106,9 @@ struct Slot { impl Slot { /// 这一家读的是哪儿:配置定了的,或者问出来的 fn source(&self, plan: Plan) -> Option { - match (plan, self.detection) { - (Plan::Known(s), _) | (Plan::Detect, Some(Detection::Found(s))) => Some(s), + match (plan, &self.detection) { + (Plan::Known(s), _) => Some(s), + (Plan::Detect, Some(Detection::Found(s))) => Some(*s), _ => None, } } @@ -123,7 +128,7 @@ impl Slot { match self.detection { None => true, // 没问成的隔一阵再问;**不看请求**,问一次就是两个请求 - Some(Detection::Undecided) => since >= EVERY_MS, + Some(Detection::Undecided(_)) => since >= EVERY_MS, Some(Detection::Neither | Detection::Found(_)) => false, } } @@ -143,17 +148,18 @@ impl Tracker { self.slots.lock().unwrap_or_else(|p| p.into_inner()) } - /// 这一家现在要读吗、读什么。要读就占上,读完必须 [`Tracker::settle`]。 + /// 这一家现在要读吗、读什么。要读就占上,交回占着的那一份:读完交给 [`Claim::settle`]; + /// 没读完就丢掉的,丢掉时放手(见 [`Claim`])。 /// /// `Demand` 不看节奏:认出过的直接读,没认出来的(两种都不是、没问成)再问一次 pub fn claim( - &self, + self: &Arc, provider: &str, ident: &str, plan: Plan, why: Why, now_ms: u64, - ) -> Option { + ) -> Option { let mut g = self.lock(); let slot = g.entry(provider.to_string()).or_default(); if slot.ident != ident { @@ -167,10 +173,18 @@ impl Tracker { } slot.running += 1; // 这一次读到的已经算上了到此刻为止结束的请求 - slot.dirty = false; - Some(match slot.source(plan) { + let dirty = std::mem::take(&mut slot.dirty); + let step = match slot.source(plan) { Some(s) => Step::Read(s), None => Step::Detect, + }; + Some(Claim { + tracker: self.clone(), + provider: provider.to_string(), + ident: ident.to_string(), + step, + dirty, + settled: false, }) } @@ -179,7 +193,7 @@ impl Tracker { /// /// 读成了的整份换上;没读成的**留着上一次读到的**,只记下原因 —— 一次超时不该让界面上 /// 的余额消失。之前读的是别的来源(问出来的变了)就不留 - pub fn settle( + fn settle( &self, provider: &str, ident: &str, @@ -191,11 +205,14 @@ impl Tracker { slot.running = slot.running.saturating_sub(1); slot.tried_at = Some(now_ms); if let Some(d) = outcome.detection { + let found = matches!(d, Detection::Found(_)); // 认出来过的不因为一次没问成就忘掉 - if !matches!(slot.detection, Some(Detection::Found(_))) || d != Detection::Undecided { + if !matches!(slot.detection, Some(Detection::Found(_))) + || !matches!(d, Detection::Undecided(_)) + { slot.detection = Some(d); } - if !matches!(d, Detection::Found(_)) && outcome.read.is_none() { + if !found && outcome.read.is_none() { slot.balance = None; } } @@ -212,6 +229,16 @@ impl Tracker { Some(slot.balance.clone()) } + /// 占着却没读完就放手了:不再算作正在读,占上时清掉的「有请求结束了」还回去。**节奏 + /// 照旧**:没读成也没读坏,上一次读的时刻不动 + fn release(&self, provider: &str, ident: &str, dirty: bool) { + let mut g = self.lock(); + if let Some(slot) = g.get_mut(provider).filter(|s| s.ident == ident) { + slot.running = slot.running.saturating_sub(1); + slot.dirty |= dirty; + } + } + /// 有请求经过这一家结束了。**只做个记号**:读不读、什么时候读由节奏定 pub fn note_request(&self, provider: &str) { let known = match self.lock().get_mut(provider) { @@ -240,6 +267,50 @@ impl Tracker { } } +/// 占着一家去读:[`Tracker::claim`] 交回,读完交给 [`Claim::settle`]。 +/// +/// **丢掉就放手**:读到一半任务被取消(界面那头断开、进程在收尾)、或者读的代码 panic 了, +/// 这一家不会一直算作「正在读」—— 那样后台的节奏就再也不读它了 +#[must_use = "dropping a claim gives the upstream back unread"] +pub struct Claim { + tracker: Arc, + provider: String, + ident: String, + step: Step, + /// 占上时清掉的「有请求结束了」:没读完就放手时还回去 + dirty: bool, + settled: bool, +} + +impl Claim { + /// 这一次要做什么 + pub fn step(&self) -> Step { + self.step + } + + /// 读的是哪一家 + pub fn provider(&self) -> &str { + &self.provider + } + + /// 读完了:记下节奏和读到的,交回这一家现在的余额。凭据在这中间换了的话,这个结果 + /// 说的是旧的那一份,不记,是 `None`。没读成的留着上一次读到的,只记下原因 + pub fn settle(mut self, outcome: Outcome, now_ms: u64) -> Option> { + self.settled = true; + self.tracker + .settle(&self.provider, &self.ident, outcome, now_ms) + } +} + +impl Drop for Claim { + fn drop(&mut self) { + if !self.settled { + self.tracker + .release(&self.provider, &self.ident, self.dirty); + } + } +} + #[cfg(test)] mod tests { use super::*; @@ -249,6 +320,10 @@ mod tests { const NOW: u64 = 1_790_000_000_000; const DS: Plan = Plan::Known(BalanceSource::Deepseek); + fn tracker() -> Arc { + Arc::new(Tracker::default()) + } + fn wallet(amount: f64) -> Reading { Reading { wallet: Some(Money { @@ -266,67 +341,92 @@ mod tests { } } + fn detected(d: Detection) -> Outcome { + Outcome { + detection: Some(d), + read: None, + } + } + fn failed() -> Msg { msg!("gw.balance.status", status = 502 => "x") } + /// 按节奏现在读不读:读的话交回要做的那一步,**占着的随即放手** + fn due(t: &Arc, provider: &str, plan: Plan, now: u64) -> Option { + t.claim(provider, "k", plan, Why::Due, now) + .map(|c| c.step()) + } + /// 读一次:占上、读到 `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); + fn read_at(t: &Arc, now: u64, amount: f64) { + let c = t.claim("ds", "k", DS, Why::Due, now).expect("due"); + assert_eq!(c.step(), Step::Read(BalanceSource::Deepseek)); + c.settle(read(Ok(wallet(amount))), now); } #[test] fn it_reads_at_start_and_then_every_ten_minutes() { - let t = Tracker::default(); + let t = tracker(); 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()); + assert_eq!(due(&t, "ds", DS, NOW + EVERY_MS - 1), None); + assert!(due(&t, "ds", DS, NOW + EVERY_MS).is_some()); } /// 请求结束之后最多每 60 秒读一次:一阵连着的请求,在最后补读一次 #[test] fn requests_ending_trigger_a_read_at_most_every_minute() { - let t = Tracker::default(); + let t = tracker(); 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); + assert_eq!(due(&t, "ds", DS, NOW + 10_000), None); + assert_eq!(due(&t, "ds", DS, 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 - ); + assert_eq!(due(&t, "ds", DS, 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() - ); + assert!(due(&t, "ds", DS, 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()); + let t = tracker(); + let reading = t.claim("ds", "k", DS, Why::Due, NOW).unwrap(); // 正在读:不另读 - assert_eq!(t.claim("ds", "k", DS, Why::Due, NOW + 1), None); + assert_eq!(due(&t, "ds", DS, 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() - ); + reading.settle(read(Ok(wallet(1.0))), NOW + 500); + assert!(due(&t, "ds", DS, NOW + 500 + AFTER_REQUEST_MS).is_some()); + } + + /// 读到一半放手了(任务被取消、界面那头断开):**不再算作正在读**,后台照样按节奏读 + #[test] + fn a_claim_dropped_mid_read_gives_the_upstream_back() { + let t = tracker(); + let first = t.claim("ds", "k", DS, Why::Due, NOW).unwrap(); + assert_eq!(due(&t, "ds", DS, NOW + 1), None, "正在读"); + drop(first); + assert!(due(&t, "ds", DS, NOW + 2).is_some(), "从没读成过:马上该读"); + + // 占上时清掉的「有请求结束了」还回去:这一次没读成,那些请求还等着一次读 + read_at(&t, NOW, 10.0); + t.note_request("ds"); + let reading = t + .claim("ds", "k", DS, Why::Due, NOW + AFTER_REQUEST_MS) + .unwrap(); + drop(reading); + assert!(due(&t, "ds", DS, NOW + AFTER_REQUEST_MS + 1).is_some()); + // 界面要的那一次放手了也一样 + let demand = t.claim("ds", "k", DS, Why::Demand, NOW + 5).unwrap(); + drop(demand); + assert!(due(&t, "ds", DS, NOW + AFTER_REQUEST_MS + 2).is_some()); } #[test] fn a_demand_reads_now_whatever_the_rhythm() { - let t = Tracker::default(); + let t = tracker(); read_at(&t, NOW, 10.0); assert!(t.claim("ds", "k", DS, Why::Demand, NOW + 1).is_some()); } @@ -334,20 +434,22 @@ mod tests { /// 读失败了:**留着上一次读到的**,只记下原因;之后读成了,原因清掉 #[test] fn a_failed_read_keeps_the_last_good_reading_and_says_why() { - let t = Tracker::default(); + let t = tracker(); 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) + .claim("ds", "k", DS, Why::Demand, NOW + 5) + .unwrap() + .settle(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) + .claim("ds", "k", DS, Why::Demand, NOW + 9) + .unwrap() + .settle(read(Ok(wallet(8.0))), NOW + 9) .unwrap() .unwrap(); assert_eq!(b.wallet.unwrap().amount, 8.0); @@ -356,40 +458,44 @@ mod tests { #[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 t = tracker(); let b = t - .settle("ds", "k", read(Err(failed())), NOW) + .claim("ds", "k", DS, Why::Due, NOW) + .unwrap() + .settle(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); + assert_eq!(due(&t, "ds", DS, NOW + 30_000), None); } #[test] fn a_new_key_starts_over() { - let t = Tracker::default(); + let t = tracker(); 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()); + let old = t.claim("ds", "k", DS, Why::Demand, NOW + 1).unwrap(); + let late = t.claim("ds", "k", DS, Why::Demand, NOW + 1).unwrap(); + let new = t.claim("ds", "k2", DS, Why::Due, NOW + 1).unwrap(); // 旧 key 的那一次晚到了:不记 - assert_eq!(t.settle("ds", "k", read(Ok(wallet(1.0))), NOW + 2), None); + assert_eq!(old.settle(read(Ok(wallet(1.0))), NOW + 2), None); + // 旧 key 的那一次放手了:不碰新的那一份,新的还在读 + drop(late); + assert!(t.claim("ds", "k2", DS, Why::Due, NOW + 3).is_none()); + new.settle(read(Ok(wallet(2.0))), NOW + 4); + assert_eq!(t.get("ds", "k2").unwrap().wallet.unwrap().amount, 2.0); } #[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", + let t = tracker(); + let c = t.claim("r", "k", Plan::Detect, Why::Due, NOW).unwrap(); + assert_eq!(c.step(), Step::Detect); + c.settle( Outcome { detection: Some(Detection::Found(BalanceSource::Sub2api)), read: Some((BalanceSource::Sub2api, Ok(Reading::default()))), @@ -398,7 +504,7 @@ mod tests { ); // 认出来了:之后直接读 assert_eq!( - t.claim("r", "k", Plan::Detect, Why::Due, NOW + EVERY_MS), + due(&t, "r", Plan::Detect, NOW + EVERY_MS), Some(Step::Read(BalanceSource::Sub2api)) ); } @@ -406,27 +512,19 @@ mod tests { /// 两种都不是:**不再问**,请求再多也不问;只有界面要的时候再问一次 #[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, - ); + let t = tracker(); + let left = t + .claim("r", "k", Plan::Detect, Why::Due, NOW) + .unwrap() + .settle(detected(Detection::Neither), 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!(due(&t, "r", Plan::Detect, NOW + i * EVERY_MS), None); } assert_eq!( - t.claim("r", "k", Plan::Detect, Why::Demand, NOW + 1), + t.claim("r", "k", Plan::Detect, Why::Demand, NOW + 1) + .map(|c| c.step()), Some(Step::Detect) ); } @@ -434,70 +532,50 @@ mod tests { /// 没问成:隔十分钟再问,**不跟着请求问** #[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, - ); + let t = tracker(); + t.claim("r", "k", Plan::Detect, Why::Due, NOW) + .unwrap() + .settle(detected(Detection::Undecided(failed())), NOW); t.note_request("r"); + assert_eq!(due(&t, "r", Plan::Detect, NOW + AFTER_REQUEST_MS), None); 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), + due(&t, "r", Plan::Detect, 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, - ); + let t = tracker(); + t.claim("r", "k", Plan::Detect, Why::Due, NOW) + .unwrap() + .settle( + Outcome { + detection: Some(Detection::Found(BalanceSource::Newapi)), + read: Some((BalanceSource::Newapi, Ok(Reading::default()))), + }, + NOW, + ); + t.claim("r", "k", Plan::Detect, Why::Demand, NOW + 1) + .unwrap() + .settle(detected(Detection::Undecided(failed())), NOW + 2); assert_eq!( - t.claim("r", "k", Plan::Detect, Why::Demand, NOW + 3), + t.claim("r", "k", Plan::Detect, Why::Demand, NOW + 3) + .map(|c| c.step()), Some(Step::Read(BalanceSource::Newapi)) ); } #[test] fn a_request_on_an_upstream_never_read_changes_nothing() { - let t = Tracker::default(); + let t = tracker(); t.note_request("nobody"); assert_eq!(t.get("nobody", ""), None); } #[test] fn upstreams_no_longer_configured_are_forgotten() { - let t = Tracker::default(); + let t = tracker(); 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 ea4b6c2a..4da44d6b 100644 --- a/crates/tw-gateway/src/egress.rs +++ b/crates/tw-gateway/src/egress.rs @@ -93,13 +93,16 @@ const CLIENT_IDENTITY_PREFIX: &str = "x-codex-"; /// 读余额([`crate::balances`])时发的头,**只有这三个**:ThinkWatch 的 User-Agent、 /// `Accept` 和凭据。那不是转发,没有客户端的头可取;上游配置里写的别的头也不发 —— -/// 余额接口只认凭据 -pub fn balance_headers(authorization: &str) -> [(&'static str, String); 3] { - [ +/// 余额接口只认凭据。不要凭据的公开接口(`authorization` 是 `None`)连凭据也不发 +pub fn balance_headers(authorization: Option<&str>) -> Vec<(&'static str, String)> { + let mut h = vec![ ("user-agent", crate::user_agent()), ("accept", "application/json".to_string()), - ("authorization", authorization.to_string()), - ] + ]; + if let Some(a) = authorization { + h.push(("authorization", a.to_string())); + } + h } /// 客户端请求里的这个头发不发给这家。 diff --git a/crates/tw-gateway/src/state/balances.rs b/crates/tw-gateway/src/state/balances.rs index 1d1564b1..84ec1f4c 100644 --- a/crates/tw-gateway/src/state/balances.rs +++ b/crates/tw-gateway/src/state/balances.rs @@ -1,7 +1,7 @@ //! 上游的余额:读谁、什么时候读、读到的怎么告诉界面(见 [`crate::balances`])。 use super::AppState; -use crate::balances::{self, Plan, Step, Why}; +use crate::balances::{self, Claim, Detection, Plan, Step, Why}; use crate::server::now_ms; /// 一家要读余额的上游:怎么读、凭什么读。 @@ -57,65 +57,109 @@ impl AppState { } /// 到了时候的都去读,每家一个任务(见 [`crate::balances::tracker`])。后台不等它们; - /// 测试等 + /// 测试等。 + /// + /// **配置和 client 取自同一份运行时**:分两次取,中间换了配置,就可能拿着这一份的密钥 + /// 配上另一份的 client(没有这一家的 client 时退回的默认 client 不走它的代理) pub fn start_due_balances(&self) -> Vec> { - let cfg = self.config(); + let rt = self.runtime(); self.balances - .retain(|name| cfg.providers.iter().any(|p| p.name == name)); - cfg.providers + .retain(|name| rt.config.providers.iter().any(|p| p.name == name)); + rt.config + .providers .iter() .filter_map(|p| { let t = self.saved_target(p)?; - let step = self + let http = rt.clients.get(&p.name)?.clone(); + let claim = 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()); + let base_url = p.base_url.clone(); Some(tokio::spawn(async move { - state.run_balance(&name, &base_url, t, step).await; + let _ = state.run_balance(http, base_url, t.auth, claim).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 + /// 界面要:马上读这一家,`auto` 而没认出来的再问一次。 + /// + /// - `Ok(Some)`:读到的(没读成的话带着原因,留着上一次读到的); + /// - `Ok(None)`:没有这一家,或者它没有余额可读(两种中转站都不是); + /// - `Err`:`auto` 的这一家**没问成**是哪一种(连不上、超时、对方出错),没问成的原因。 + /// + /// **读在自己的任务里**:界面那头断开了(这个 future 被丢掉),这一次照样读完、记下、 + /// 报 `balance_updated`,这一家也不会一直算作「正在读」 + pub async fn refresh_balance( + &self, + name: &str, + ) -> Result, tw_types::Msg> { + let rt = self.runtime(); + let Some(p) = rt.config.providers.iter().find(|p| p.name == name) else { + return Ok(None); + }; + let Some(t) = self.saved_target(p) else { + return Ok(None); + }; + let Some(http) = rt.clients.get(name).cloned() else { + return Ok(None); + }; + let Some(claim) = self .balances - .claim(name, &t.ident, t.plan, Why::Demand, now_ms())?; - self.run_balance(name, &p.base_url, t, step).await.flatten() + .claim(name, &t.ident, t.plan, Why::Demand, now_ms()) + else { + return Ok(None); + }; + let state = self.clone(); + let base_url = p.base_url.clone(); + let read = + tokio::spawn(async move { state.run_balance(http, base_url, t.auth, claim).await }); + match read.await { + Ok(r) => r, + // 读的代码 panic 了:照原样抛出去,和在这里直接读一样 + Err(e) if e.is_panic() => std::panic::resume_unwind(e.into_panic()), + Err(_) => Ok(None), + } } - /// 做一步、记下来;读过了就报一条 `balance_updated`。交回这一家现在的余额;凭据在这 - /// 中间换了的话是 `None` + /// 做一步、记下来;读过了就报一条 `balance_updated`。交回同 [`Self::refresh_balance`]; + /// 凭据在这中间换了的话是 `Ok(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; + http: reqwest::Client, + base_url: String, + auth: String, + claim: Claim, + ) -> Result, tw_types::Msg> { + let name = claim.provider().to_string(); + let outcome = balances::run(&http, claim.step(), &base_url, &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 undecided = match &outcome.detection { + Some(Detection::Undecided(why)) => { + tracing::debug!(provider = name, "the balance source is undecided: {why}"); + Some(why.clone()) + } + _ => None, + }; let now = now_ms(); - let left = self.balances.settle(name, &t.ident, outcome, now)?; + let Some(left) = claim.settle(outcome, now) else { + return Ok(None); + }; if read { self.bus.emit(tw_api::Event::BalanceUpdated { id: self.bus.next_id(), - provider: name.to_string(), + provider: name, at_ms: now, }); } - Some(left) + match undecided { + Some(why) => Err(why), + None => Ok(left), + } } /// 检测一家(可能还没保存的)上游时顺带读一次余额,`auto` 的先认是哪一种。**不记**: diff --git a/crates/tw-gateway/tests/balances.rs b/crates/tw-gateway/tests/balances.rs index ec085a7a..2fe78adb 100644 --- a/crates/tw-gateway/tests/balances.rs +++ b/crates/tw-gateway/tests/balances.rs @@ -25,11 +25,12 @@ struct Seen { accept: String, } -/// 一台假服务器:每个路径回什么(没写的是 404),收到过什么 +/// 一台假服务器:每个路径回什么(没写的是 404),收到过什么;扣着的路径等放行了才回 #[derive(Default)] struct Fake { answers: Mutex>, seen: Mutex>, + holds: Mutex>>, } impl Fake { @@ -39,6 +40,15 @@ impl Fake { .unwrap() .insert(path.to_string(), (status, body.to_string())); } + /// 这个路径的请求收下、先不回,等放行(`add_permits`) + fn hold(&self, path: &str) -> Arc { + let gate = Arc::new(tokio::sync::Semaphore::new(0)); + self.holds + .lock() + .unwrap() + .insert(path.to_string(), gate.clone()); + gate + } fn paths(&self) -> Vec { self.seen .lock() @@ -71,6 +81,10 @@ async fn handle(State(f): State>, uri: Uri, h: HeaderMap) -> axum::res user_agent: header("user-agent"), accept: header("accept"), }); + let gate = f.holds.lock().unwrap().get(uri.path()).cloned(); + if let Some(gate) = gate { + gate.acquire().await.unwrap().forget(); + } let (status, body) = f .answers .lock() @@ -129,6 +143,26 @@ fn balance(state: &tw_gateway::AppState) -> Option { state.balance_of(&state.config().providers[0]) } +/// 马上读一次,读到的余额。没有余额可读、没问成是哪一种的,测试失败 +async fn refresh(state: &tw_gateway::AppState) -> tw_api::Balance { + state + .refresh_balance("relay") + .await + .expect("decided") + .expect("a balance") +} + +/// 等到 `cond` 成立,最多五秒 +async fn until(cond: impl Fn() -> bool) { + tokio::time::timeout(Duration::from_secs(5), async { + while !cond() { + tokio::time::sleep(Duration::from_millis(10)).await; + } + }) + .await + .expect("timed out waiting"); +} + /// 总线上已经有的 `balance_updated` fn updates(rx: &mut tokio::sync::broadcast::Receiver) -> usize { std::iter::from_fn(|| rx.try_recv().ok()) @@ -137,7 +171,7 @@ fn updates(rx: &mut tokio::sync::broadcast::Receiver) -> usize { } 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}}, + "usage":{"today":{"requests":3,"input_tokens":1200,"output_tokens":300,"cost":0.12,"actual_cost":0.096},"total":{"requests":90,"cost":7.65,"actual_cost":6.12}}, "daily_usage":[{"date":"2026-10-10","requests":3,"cost":0.12}], "model_stats":[{"model":"claude-sonnet-4-5","requests":3,"cost":0.12}]}"#; @@ -158,10 +192,11 @@ async fn auto_finds_a_sub2api_relay_and_reads_its_wallet_from_the_same_answer() currency: "USD".into() }) ); + // 今天实际扣的 assert_eq!( b.spent, Some(Spent { - amount: 0.12, + amount: 0.096, currency: "USD".into(), period: SpentPeriod::Today, scope: None, @@ -184,19 +219,27 @@ async fn auto_finds_a_sub2api_relay_and_reads_its_wallet_from_the_same_answer() assert_eq!(f.paths().len(), 1); } +const NEWAPI_SUBSCRIPTION: &str = r#"{"object":"billing_subscription","has_payment_method":true,"soft_limit_usd":25,"hard_limit_usd":25,"system_hard_limit_usd":25,"access_until":0}"#; +const NEWAPI_USAGE: &str = r#"{"object":"list","total_usage":1234.5}"#; + +/// New API 站点的状态接口,额度按 `display` 显示 +fn newapi_status(display: &str) -> String { + format!( + r#"{{"success":true,"message":"","data":{{"version":"v0.9.0","system_name":"New API","quota_per_unit":500000,"display_in_currency":{},"quota_display_type":"{display}","usd_exchange_rate":7.3}}}}"#, + display != "TOKENS" + ) +} + #[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}"#, + NEWAPI_SUBSCRIPTION, ); + f.answer("/v1/dashboard/billing/usage", 200, NEWAPI_USAGE); + f.answer("/api/status", 200, &newapi_status("USD")); let state = state_for(start(f.clone()).await, BalanceSetting::Auto); read_due(&state).await; @@ -210,14 +253,51 @@ async fn auto_finds_a_new_api_relay_and_reads_its_quota() { [ "/v1/usage", "/v1/dashboard/billing/subscription", - "/v1/dashboard/billing/usage" + "/v1/dashboard/billing/usage", + "/api/status" ] ); - let usage = f.seen.lock().unwrap()[2].query.clone().unwrap_or_default(); + let seen = f.seen.lock().unwrap().clone(); + let usage = seen[2].query.clone().unwrap_or_default(); assert!( usage.contains("start_date=") && usage.contains("end_date="), "{usage}" ); + // 状态接口是公开的:不带密钥 + assert_eq!(seen[3].auth, "", "{seen:?}"); + assert_eq!(seen[2].auth, "Bearer sk-relay-fake"); +} + +/// 账单接口的数按站点的额度显示方式折算:人民币、token;站点说不出来的,单位是「不知道」 +#[tokio::test] +async fn a_new_api_relay_reads_in_the_unit_its_site_displays() { + let f = Arc::new(Fake::default()); + f.answer( + "/v1/dashboard/billing/subscription", + 200, + NEWAPI_SUBSCRIPTION, + ); + f.answer("/v1/dashboard/billing/usage", 200, NEWAPI_USAGE); + let state = state_for(start(f.clone()).await, BalanceSetting::Newapi); + let unit = |b: tw_api::Balance| b.quota.unwrap().unit; + + f.answer("/api/status", 200, &newapi_status("CNY")); + assert_eq!(unit(refresh(&state).await), "CNY"); + f.answer("/api/status", 200, &newapi_status("TOKENS")); + assert_eq!(unit(refresh(&state).await), "tokens"); + // 没有这个接口(或者回的不是它):不知道,不当作美元 + f.answer("/api/status", 404, r#"{"error":"not found"}"#); + assert_eq!(unit(refresh(&state).await), "unknown"); + f.answer("/api/status", 200, r#"{"success":true,"data":{}}"#); + assert_eq!(unit(refresh(&state).await), "unknown"); + + // 没问成(对方出错):这一次没读成,**留着上一次读到的** + f.answer("/api/status", 200, &newapi_status("CNY")); + let good = refresh(&state).await; + f.answer("/api/status", 503, r#"{"error":"busy"}"#); + let failed = refresh(&state).await; + assert_eq!(failed.error.unwrap().arg("status"), "503"); + assert_eq!(failed.quota, good.quota); } /// 两种都不是:没有余额,**不再问**,请求结束了也不问。只有界面要的时候再问一次 @@ -237,10 +317,50 @@ async fn a_host_that_is_neither_has_no_balance_and_is_not_asked_again() { assert_eq!(f.paths().len(), 2, "又去问了:{:?}", f.paths()); assert_eq!(updates(&mut rx), 0, "没有余额,不用报"); - assert_eq!(state.refresh_balance("relay").await, None); + assert_eq!(state.refresh_balance("relay").await, Ok(None)); assert_eq!(f.paths().len(), 4, "界面要的时候再问一次"); } +/// 跳转也是回答:出站不跟跳转,跳去登录页、首页的地址没有这个接口,两种都不是 +#[tokio::test] +async fn a_redirect_is_an_answer() { + let f = Arc::new(Fake::default()); + f.answer("/v1/usage", 302, ""); + f.answer("/v1/dashboard/billing/subscription", 301, ""); + let state = state_for(start(f.clone()).await, BalanceSetting::Auto); + + read_due(&state).await; + assert_eq!(balance(&state), None); + for _ in 0..3 { + state.balances.note_request("relay"); + read_due(&state).await; + } + assert_eq!( + f.paths().len(), + 2, + "认定了两种都不是,不再问:{:?}", + f.paths() + ); + assert_eq!(state.refresh_balance("relay").await, Ok(None)); +} + +/// 没问成是哪一种(对方出错):界面要的时候说没问成的原因,不说「没有余额」 +#[tokio::test] +async fn an_undecided_refresh_says_why() { + let f = Arc::new(Fake::default()); + f.answer("/v1/usage", 503, r#"{"error":"busy"}"#); + let state = state_for(start(f.clone()).await, BalanceSetting::Auto); + + let why = state.refresh_balance("relay").await.unwrap_err(); + assert_eq!(why.code, "gw.balance.status"); + assert_eq!(why.arg("status"), "503"); + assert_eq!(balance(&state), None); + + // 问成了:两种都不是,就是没有余额 + f.answer("/v1/usage", 404, r#"{"error":"not found"}"#); + assert_eq!(state.refresh_balance("relay").await, Ok(None)); +} + #[tokio::test] async fn an_explicit_source_reads_on_the_origin_not_on_the_base_path() { let f = Arc::new(Fake::default()); @@ -264,24 +384,55 @@ async fn an_explicit_source_reads_on_the_origin_not_on_the_base_path() { ); } +/// OpenRouter 只问这把密钥自己的接口:**不问账户余额**(`/api/v1/credits` 只有管理密钥 +/// 问得到,能转发请求的密钥问它是 403) #[tokio::test] -async fn openrouter_without_a_key_limit_reads_the_account_credits() { +async fn openrouter_reads_only_the_key_itself() { let f = Arc::new(Fake::default()); + f.answer( + "/api/v1/credits", + 403, + r#"{"error":{"code":403,"message":"Only management keys can perform this operation"}}"#, + ); + let state = state_for(start(f.clone()).await, BalanceSetting::Openrouter); + + // 没设额度:这个月花了多少 f.answer( "/api/v1/key", 200, - r#"{"data":{"label":"sk-or-v1-fak...e","limit":null,"limit_remaining":null,"usage":3.1}}"#, + r#"{"data":{"label":"sk-or-v1-fak...e","limit":null,"limit_remaining":null,"limit_reset":null,"include_byok_in_limit":false, + "usage":3.1,"usage_daily":0.2,"usage_weekly":0.9,"usage_monthly":1.4,"is_free_tier":false,"is_management_key":false, + "free_model_daily_requests":{"limit":1000,"used":3,"remaining":997}}}"#, ); + let b = refresh(&state).await; + assert_eq!(b.error, None, "{b:?}"); + assert_eq!(b.wallet, None); + assert_eq!(b.quota, None); + assert_eq!( + b.spent, + Some(Spent { + amount: 1.4, + currency: "USD".into(), + period: SpentPeriod::Month, + scope: None, + }) + ); + + // 设了额度:额度和这一期用了多少,到期时刻 f.answer( - "/api/v1/credits", + "/api/v1/key", 200, - r#"{"data":{"total_credits":20,"total_usage":12.5}}"#, + r#"{"data":{"label":"sk-or-v1-fak...e","limit":20,"limit_remaining":12.5,"limit_reset":"monthly","include_byok_in_limit":false, + "usage":30,"usage_daily":1,"usage_weekly":4,"usage_monthly":7.5,"is_free_tier":false,"is_management_key":false, + "expires_at":"2027-01-01T00:00:00Z"}}"#, ); - let state = state_for(start(f.clone()).await, BalanceSetting::Openrouter); + let b = refresh(&state).await; + let q = b.quota.unwrap(); + assert_eq!((q.limit, q.used, q.unit.as_str()), (20.0, 7.5, "USD")); + assert_eq!(b.spent.unwrap().amount, 7.5); + assert!(b.expires_at_ms.is_some()); - read_due(&state).await; - assert_eq!(f.paths(), ["/api/v1/key", "/api/v1/credits"]); - assert_eq!(balance(&state).unwrap().wallet.unwrap().amount, 7.5); + assert_eq!(f.paths(), ["/api/v1/key", "/api/v1/key"]); } const ENTERPRISE: &str = r#"{"usage":{"requests_today":3,"tokens_today":9000,"requests_month":80,"tokens_month":400000,"cost_usd_month":12.5}, @@ -297,14 +448,14 @@ async fn a_failing_read_keeps_the_last_good_reading_and_says_why() { let state = state_for(start(f.clone()).await, BalanceSetting::Thinkwatch); let mut rx = state.bus.subscribe(); - let first = state.refresh_balance("relay").await.unwrap(); + let first = refresh(&state).await; 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 failed = refresh(&state).await; let why = failed.error.clone().expect("the reason"); assert_eq!(why.code, "gw.balance.status"); assert_eq!(why.arg("status"), "503"); @@ -314,7 +465,7 @@ async fn a_failing_read_keeps_the_last_good_reading_and_says_why() { assert_eq!(balance(&state), Some(failed)); f.answer("/v1/usage", 200, ENTERPRISE); - let again = state.refresh_balance("relay").await.unwrap(); + let again = refresh(&state).await; assert_eq!(again.error, None); assert_eq!(updates(&mut rx), 3, "每读一次报一次"); } @@ -325,12 +476,12 @@ 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(); + let b = refresh(&state).await; 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 b = refresh(&state).await; let why = b.error.unwrap(); assert_eq!(why.code, "gw.balance.rejected"); assert!(!why.text.contains("sk-relay-fake")); @@ -382,3 +533,58 @@ async fn a_request_through_the_upstream_wakes_the_balance_reader() { read_due(&state).await; assert_eq!(f.paths(), ["/v1/usage"]); } + +/// 界面要读,读到一半界面那头走了(这个 future 被丢掉):**这一次照样读完、记下、报事件**; +/// 读着的时候后台不另读 +#[tokio::test] +async fn a_refresh_whose_caller_goes_away_still_reads() { + let f = Arc::new(Fake::default()); + f.answer("/v1/usage", 200, SUB2API_WALLET); + let gate = f.hold("/v1/usage"); + let state = state_for(start(f.clone()).await, BalanceSetting::Sub2api); + let mut rx = state.bus.subscribe(); + + let caller = tokio::spawn({ + let state = state.clone(); + async move { state.refresh_balance("relay").await } + }); + until(|| f.paths().len() == 1).await; + caller.abort(); + assert!(caller.await.unwrap_err().is_cancelled()); + + assert!(state.start_due_balances().is_empty(), "正在读:不另读"); + gate.add_permits(1); + tokio::time::timeout(Duration::from_secs(5), async { + while updates(&mut rx) == 0 { + tokio::time::sleep(Duration::from_millis(10)).await; + } + }) + .await + .expect("the read did not finish"); + assert_eq!(balance(&state).unwrap().wallet.unwrap().amount, 12.3456); + assert_eq!(f.paths().len(), 1); +} + +/// 读到一半任务被取消了:这一家**不会一直算作「正在读」**,后台照样按节奏读它 +#[tokio::test] +async fn a_read_cancelled_mid_way_leaves_the_upstream_to_the_timer() { + let f = Arc::new(Fake::default()); + f.answer("/v1/usage", 200, SUB2API_WALLET); + let gate = f.hold("/v1/usage"); + let state = state_for(start(f.clone()).await, BalanceSetting::Sub2api); + + let reads = state.start_due_balances(); + assert_eq!(reads.len(), 1); + until(|| f.paths().len() == 1).await; + for r in reads { + r.abort(); + assert!(r.await.unwrap_err().is_cancelled()); + } + assert_eq!(balance(&state), None, "没读成"); + + // 从没读成过:马上该读 + gate.add_permits(2); + read_due(&state).await; + assert_eq!(f.paths().len(), 2, "{:?}", f.paths()); + assert_eq!(balance(&state).unwrap().wallet.unwrap().amount, 12.3456); +}