Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
3 changes: 2 additions & 1 deletion crates/tw-api/src/ep.rs
Original file line number Diff line number Diff line change
Expand Up @@ -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;
Expand Down
16 changes: 11 additions & 5 deletions crates/tw-api/src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -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;

Expand Down Expand Up @@ -4740,15 +4741,16 @@ 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",
/// Moonshot(Kimi)开放平台的可用余额(`/v1/users/me/balance`)
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",
Expand Down Expand Up @@ -4806,7 +4808,8 @@ pub struct Balance {
/// 密钥或套餐什么时候到期,Unix 毫秒。不会到期、上游没说都是空
pub expires_at_ms: Option<u64>,
/// 已经花了多少,和算的是哪一段时间:没有上限可比时说得出的就是它(New API 不限
/// 额度的密钥、Sub2API 今天的花费、企业网关这个月的花费)
/// 额度的密钥、OpenRouter 这把密钥这个月的花费、Sub2API 今天实际扣的、企业网关这个月的
/// 花费)
pub spent: Option<Spent>,
/// 最近一次没读成的原因。读成了是空
pub error: Option<Msg>,
Expand Down Expand Up @@ -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,
/// 花的是谁的:这把密钥自己的,还是它所属的用户整体的(几把密钥合计)。只有企业网关
Expand All @@ -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,
}

Expand Down
20 changes: 15 additions & 5 deletions crates/tw-control/src/resources.rs
Original file line number Diff line number Diff line change
Expand Up @@ -232,6 +232,9 @@ async fn preview_provider(
}))
}

/// 「检测连接」顺带读余额最多等多久
const CHECK_BALANCE_WAIT: std::time::Duration = std::time::Duration::from_secs(5);

/// 检测一个上游,**不保存**。
///
/// 走的出站路径和转发完全一样:同一个构造 client 的函数、同一套凭据取法。
Expand Down Expand Up @@ -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
};
Expand All @@ -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<ControlState>,
Path(name): Path<String>,
Expand All @@ -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 =>
Expand Down
83 changes: 83 additions & 0 deletions crates/tw-control/tests/resources.rs
Original file line number Diff line number Diff line change
Expand Up @@ -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() {
Expand Down Expand Up @@ -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);
Expand Down
97 changes: 59 additions & 38 deletions crates/tw-gateway/src/balances.rs
Original file line number Diff line number Diff line change
Expand Up @@ -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`])。**只做个记号,不联网**
Expand Down Expand Up @@ -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<Value, Failure> {
/// 发一个 GET,读回 JSON。`auth` 是 `None` 的不带凭据(公开的接口)
async fn get_json(http: &reqwest::Client, url: &str, auth: Option<&str>) -> Result<Value, Failure> {
let mut req = http.get(url).timeout(TIMEOUT);
for (name, value) in crate::egress::balance_headers(auth) {
req = req.header(name, value);
Expand Down Expand Up @@ -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<Value>) {
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<Value, Failure>| 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,
}
}

Expand All @@ -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();
Expand All @@ -284,13 +295,9 @@ pub async fn read(
};
let parsed = |r: Option<Reading>| 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 => {
// 回答里不写货币:国际站是美元,国内站是人民币
Expand All @@ -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))
}
}
}
Expand All @@ -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 {
Expand All @@ -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,
};
}
Expand Down
Loading
Loading