diff --git a/Cargo.lock b/Cargo.lock index 698301bc..473332eb 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -3730,7 +3730,7 @@ dependencies = [ [[package]] name = "tw-api" -version = "0.89.0" +version = "0.89.1" dependencies = [ "serde", "serde_json", @@ -3741,7 +3741,7 @@ dependencies = [ [[package]] name = "tw-bedrock" -version = "0.89.0" +version = "0.89.1" dependencies = [ "aws-credential-types", "aws-sigv4", @@ -3762,7 +3762,7 @@ dependencies = [ [[package]] name = "tw-breaker" -version = "0.89.0" +version = "0.89.1" dependencies = [ "serde", "serde_json", @@ -3770,7 +3770,7 @@ dependencies = [ [[package]] name = "tw-config" -version = "0.89.0" +version = "0.89.1" dependencies = [ "blake3", "libc", @@ -3796,7 +3796,7 @@ dependencies = [ [[package]] name = "tw-control" -version = "0.89.0" +version = "0.89.1" dependencies = [ "axum", "base64 0.22.1", @@ -3842,7 +3842,7 @@ dependencies = [ [[package]] name = "tw-dialect" -version = "0.89.0" +version = "0.89.1" dependencies = [ "memchr", "serde", @@ -3851,7 +3851,7 @@ dependencies = [ [[package]] name = "tw-engine" -version = "0.89.0" +version = "0.89.1" dependencies = [ "chrono", "serde", @@ -3865,7 +3865,7 @@ dependencies = [ [[package]] name = "tw-gateway" -version = "0.89.0" +version = "0.89.1" dependencies = [ "arc-swap", "async-stream", @@ -3917,7 +3917,7 @@ dependencies = [ [[package]] name = "tw-guard" -version = "0.89.0" +version = "0.89.1" dependencies = [ "aho-corasick", "base64 0.22.1", @@ -3938,7 +3938,7 @@ dependencies = [ [[package]] name = "tw-handover" -version = "0.89.0" +version = "0.89.1" dependencies = [ "libc", "serde", @@ -3951,7 +3951,7 @@ dependencies = [ [[package]] name = "tw-link" -version = "0.89.0" +version = "0.89.1" dependencies = [ "serde", "serde_json", @@ -3965,7 +3965,7 @@ dependencies = [ [[package]] name = "tw-observe" -version = "0.89.0" +version = "0.89.1" dependencies = [ "tokio", "tracing", @@ -3974,7 +3974,7 @@ dependencies = [ [[package]] name = "tw-pack" -version = "0.89.0" +version = "0.89.1" dependencies = [ "age", "blake3", @@ -3998,7 +3998,7 @@ dependencies = [ [[package]] name = "tw-plugin" -version = "0.89.0" +version = "0.89.1" dependencies = [ "libc", "rand 0.10.2", @@ -4014,7 +4014,7 @@ dependencies = [ [[package]] name = "tw-pricing" -version = "0.89.0" +version = "0.89.1" dependencies = [ "arc-swap", "flate2", @@ -4027,14 +4027,14 @@ dependencies = [ [[package]] name = "tw-secret" -version = "0.89.0" +version = "0.89.1" dependencies = [ "thiserror 2.0.20", ] [[package]] name = "tw-store" -version = "0.89.0" +version = "0.89.1" dependencies = [ "blake3", "bytes", @@ -4054,7 +4054,7 @@ dependencies = [ [[package]] name = "tw-sync" -version = "0.89.0" +version = "0.89.1" dependencies = [ "age", "axum", @@ -4082,7 +4082,7 @@ dependencies = [ [[package]] name = "tw-types" -version = "0.89.0" +version = "0.89.1" dependencies = [ "serde", "serde_json", @@ -4091,7 +4091,7 @@ dependencies = [ [[package]] name = "tw-watch" -version = "0.89.0" +version = "0.89.1" dependencies = [ "libc", "notify", @@ -4102,7 +4102,7 @@ dependencies = [ [[package]] name = "tw-yaml" -version = "0.89.0" +version = "0.89.1" dependencies = [ "saphyr-parser", "serde_yaml_ng", @@ -4112,7 +4112,7 @@ dependencies = [ [[package]] name = "twcore" -version = "0.89.0" +version = "0.89.1" dependencies = [ "anyhow", "axum", diff --git a/Cargo.toml b/Cargo.toml index e089d1d3..be2c670e 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -61,7 +61,7 @@ categories = ["network-programming", "web-programming::http-server"] # 二进制走 CalVer,crate 走 SemVer —— 两者是两回事,卖给不同的人。 # 这里是 crate 的版本。 -version = "0.89.0" +version = "0.89.1" [workspace.dependencies] # ── 内部 crate ─────────────────────────────────────────── diff --git a/bin/twcore/src/background.rs b/bin/twcore/src/background.rs index 38d3279b..d32d947e 100644 --- a/bin/twcore/src/background.rs +++ b/bin/twcore/src/background.rs @@ -1,4 +1,4 @@ -//! 后台事务:OAuth 写回、同步、价目表刷新、默认插件、模型目录、余额、日志回收。 +//! 后台事务:OAuth 写回、同步、价目表刷新、默认插件、模型目录、额度、余额、日志回收。 //! //! # 为什么放在一个单独的运行时上 //! @@ -8,8 +8,8 @@ //! [`Background::stop`] 一次关掉整个运行时,任务连同它们派生的任务一起停下,转发那一边 //! (主运行时)不受影响。 //! -//! **模型目录、余额例外**,见 [`Background::start`] 里的说明:它们和转发共用连接池, -//! 不能跟着这个运行时一起关。 +//! **模型目录、额度、余额例外**,见 [`Background::start`] 里的说明:它们和转发共用连接池, +//! 不能跟着这个运行时一起关。额度任务单独持有把手,交接时取消。 //! //! **OAuth 写回例外地先收尾**:它手上那份新 refresh token 要是丢了,新 core 读到的就是一张 //! 已经作废的(见 [`tw_control::rotation::Rotation::settle`])。 @@ -28,12 +28,13 @@ const ROTATION_SETTLE: Duration = Duration::from_secs(5); pub struct Background { rt: Option, rotation: Option>, + quotas: Option>, } /// 起后台事务要的东西。 pub struct Start<'a> { pub control: &'a tw_control::ControlState, - /// 安全模式:只起写回、同步(暂停着)、价目表;不起默认插件、模型目录、余额 + /// 安全模式:只起写回、同步(暂停着)、价目表;不起默认插件、模型目录、额度、余额 pub safe: bool, pub seeder: Option, pub store: Option, @@ -82,6 +83,9 @@ impl Background { tw_gateway::models::spawn(s.control.gateway.clone()); // 余额:启动时读一遍,之后按节奏读(见 `tw_gateway::balances`)。**不挡启动,不挡转发** tw_gateway::balances::spawn(s.control.gateway.clone()); + // Account quota reads also share gateway connections. Keep their drivers on the + // main runtime, but cancel the poller at handover so the old Core cannot rotate tokens. + self.quotas = Some(tw_control::chatgpt::quotas::spawn(s.control.clone())); } self.rt = Some(rt); Ok(sync) @@ -94,6 +98,9 @@ impl Background { /// 全部停下(交接提交之后)。**先在锁外收尾 OAuth 写回**(见模块文档),再调这个。 pub fn stop(&mut self) { + if let Some(task) = self.quotas.take() { + task.abort(); + } self.rotation = None; if let Some(rt) = self.rt.take() { rt.shutdown_background(); diff --git a/crates/tw-control/Cargo.toml b/crates/tw-control/Cargo.toml index 8da9bb56..96ac56d9 100644 --- a/crates/tw-control/Cargo.toml +++ b/crates/tw-control/Cargo.toml @@ -73,6 +73,6 @@ tw-types = { workspace = true } tw-config = { workspace = true } # 测试挑端口:从远程控制端口那一段里随机挑(见 tests/common) rand = { workspace = true } -tokio = { workspace = true, features = ["rt", "macros"] } +tokio = { workspace = true, features = ["rt", "macros", "test-util"] } # Responses 的 WebSocket 上每一轮怎么记账,要走真的连接:客户端那一侧需要 connect tokio-tungstenite = { workspace = true, features = ["connect"] } diff --git a/crates/tw-control/src/chatgpt.rs b/crates/tw-control/src/chatgpt.rs index 00212605..73d09f92 100644 --- a/crates/tw-control/src/chatgpt.rs +++ b/crates/tw-control/src/chatgpt.rs @@ -39,6 +39,8 @@ use crate::{ControlState, Fail, fail}; use tw_api::{LoginStatus, ep}; use tw_types::{Msg, msg}; +pub mod quotas; + /// 登录要在多久之内完成。和 Codex 一样是 15 分钟 const LOGIN_TTL: Duration = Duration::from_secs(15 * 60); /// 设备码最快多久问一次「批准了没有」。服务端给的间隔比它还短就按它来 —— 问得再勤, @@ -91,6 +93,7 @@ impl Default for Endpoints { pub struct Accounts { pub endpoints: Endpoints, current: Mutex>, + quotas: quotas::Cache, } impl Accounts { @@ -98,6 +101,7 @@ impl Accounts { Self { endpoints, current: Mutex::new(None), + quotas: Default::default(), } } @@ -997,13 +1001,21 @@ async fn usage( State(s): State, Path(name): Path, ) -> Result, Fail> { - let v = account_call(&s, &name, reqwest::Method::GET, "usage", None).await?; + quotas::usage(&s, &name).await.map(Json) +} + +async fn read_usage(s: &ControlState, name: &str) -> Result { + let v = account_call(s, name, reqwest::Method::GET, "usage", None).await?; let usage = parse_usage(&v, now_ms()); + Ok(usage) +} + +fn record_usage(s: &ControlState, name: &str, usage: &tw_api::ChatgptUsage) { // 问来的额度和响应头里读到的一样记下来:**额度只在内存里**,冷启动之后要等这个账号 // 第一次有请求才会有,而界面一打开就该看得见 s.gateway.record_quota( s.bus().next_id(), - &name, + name, tw_gateway::quota::Quota { windows: usage .windows @@ -1018,7 +1030,6 @@ async fn usage( .collect(), }, ); - Ok(Json(usage)) } /// `wham/usage` 的回答。**只取额度和重置卡**:同一份回答里的邮箱、套餐由上游视图从 diff --git a/crates/tw-control/src/chatgpt/quotas.rs b/crates/tw-control/src/chatgpt/quotas.rs new file mode 100644 index 00000000..51bf42bd --- /dev/null +++ b/crates/tw-control/src/chatgpt/quotas.rs @@ -0,0 +1,316 @@ +//! Account quotas are shared Core state, independent of which desktop page is open. + +use std::collections::HashMap; +use std::sync::{Arc, Mutex}; +use std::time::Duration; + +use tokio::sync::{OwnedMutexGuard, Semaphore}; +use tokio::task::JoinSet; +use tokio::time::Instant; +use tw_config::{Protocol, Provider}; + +use crate::{ControlState, Fail}; + +// Real traffic supplies quota headers. Query only to fill a cold/stale cache or after a reset. +const REFRESH: Duration = Duration::from_secs(15 * 60); +const RETRY: Duration = Duration::from_secs(60); +const TICK: Duration = Duration::from_secs(5); + +type Answer = Result; + +#[derive(Default)] +struct Reading { + answer: Option, + finished: Option, + next: Option, + failures: u32, +} + +impl Reading { + fn due(&self, now: Instant) -> bool { + self.next.is_none_or(|at| now >= at) + } + + fn finish(&mut self, answer: Answer, now: Instant) { + self.failures = if answer.is_ok() { + 0 + } else { + self.failures.saturating_add(1) + }; + let delay = match &answer { + Ok(usage) => refresh_after(&usage.windows, super::now_ms()), + Err(_) => retry_after(self.failures), + }; + self.next = Some(now + delay); + self.finished = Some(now); + self.answer = Some(answer); + } + + fn observe(&mut self, windows: &[tw_api::QuotaWindow], now: Instant) { + self.failures = 0; + self.next = Some(now + refresh_after(windows, super::now_ms())); + } +} + +fn retry_after(failures: u32) -> Duration { + RETRY + .saturating_mul(1 << failures.saturating_sub(1).min(4)) + .min(REFRESH) +} + +fn refresh_after(windows: &[tw_api::QuotaWindow], now_ms: u64) -> Duration { + windows + .iter() + .filter_map(|w| w.resets_at_ms) + .filter(|&at| at > now_ms) + // Let the upstream finish resetting; never automatically query twice within a minute. + .map(|at| Duration::from_millis(at - now_ms).saturating_add(TICK)) + .min() + .unwrap_or(REFRESH) + .clamp(RETRY, REFRESH) +} + +struct Slot { + identity: (String, String), + reading: Arc>, +} + +pub(super) struct Cache { + slots: Mutex>, + limit: Semaphore, +} + +impl Default for Cache { + fn default() -> Self { + Self { + slots: Default::default(), + limit: Semaphore::new(4), + } + } +} + +fn identity(p: &Provider) -> (String, String) { + (p.base_url.clone(), p.credential_identity()) +} + +impl Cache { + fn slot(&self, p: &Provider) -> Arc> { + let mut slots = self.slots.lock().expect("quota cache lock poisoned"); + let id = identity(p); + let slot = slots.entry(p.name.clone()).or_insert_with(|| Slot { + identity: id.clone(), + reading: Default::default(), + }); + if slot.identity != id { + *slot = Slot { + identity: id, + reading: Default::default(), + }; + } + slot.reading.clone() + } + + fn observe(&self, p: &Provider, windows: &[tw_api::QuotaWindow]) { + // Do not assign queued events from a deleted/replaced account to its replacement. + let reading = self + .slots + .lock() + .expect("quota cache lock poisoned") + .get(&p.name) + .filter(|slot| slot.identity == identity(p)) + .map(|slot| slot.reading.clone()); + if let Some(reading) = reading + && let Ok(mut reading) = reading.try_lock() + { + reading.observe(windows, Instant::now()); + } + // A read holding the slot will set its own deadline on completion. + } +} + +fn accounts(s: &ControlState) -> Vec { + s.config() + .providers + .iter() + .filter(|p| { + !p.disabled + && p.effective_protocol() == Some(Protocol::Chatgpt) + && !p.oauth.as_ref().is_some_and(|oauth| { + s.gateway + .oauth + .failure(&p.name, oauth) + .is_some_and(|(_, relogin)| relogin) + }) + }) + .cloned() + .collect() +} + +/// Poll without a desktop window. Dropping/aborting this task also cancels its reads. +/// It must run on the gateway runtime, whose HTTP connection pools it shares. +pub fn spawn(s: ControlState) -> tokio::task::JoinHandle<()> { + let mut events = s.bus().subscribe(); + tokio::spawn(async move { + let mut tasks = JoinSet::new(); + let mut tick = tokio::time::interval(TICK); + tick.set_missed_tick_behavior(tokio::time::MissedTickBehavior::Skip); + loop { + for (p, reading) in due(&s) { + let state = s.clone(); + tasks.spawn(async move { read(&state, &p, reading).await }); + } + tokio::select! { + _ = tick.tick() => {}, + _ = tasks.join_next(), if !tasks.is_empty() => {}, + event = async { + loop { + match events.recv().await { + Ok(event @ (tw_api::Event::QuotaSeen { .. } | tw_api::Event::ConfigReloaded { .. })) => break Some(event), + Err(tokio::sync::broadcast::error::RecvError::Closed) => break None, + _ => {}, + } + } + } => { + let Some(event) = event else { return }; + if let tw_api::Event::QuotaSeen { provider, windows, .. } = event + && let Some(p) = s.config().providers.iter().find(|p| p.name == provider) + { + s.chatgpt.quotas.observe(p, &windows); + } + }, + } + } + }) +} + +fn due(s: &ControlState) -> Vec<(Provider, OwnedMutexGuard)> { + let providers = accounts(s); + s.chatgpt + .quotas + .slots + .lock() + .expect("quota cache lock poisoned") + .retain(|name, _| providers.iter().any(|p| &p.name == name)); + providers + .into_iter() + .filter_map(|p| { + let reading = s.chatgpt.quotas.slot(&p).try_lock_owned().ok()?; + reading.due(Instant::now()).then_some((p, reading)) + }) + .collect() +} + +/// All quota readers, including overview and the menu bar, can warm a cold cache. +/// A caller timing out leaves the bounded reads running; QuotaSeen delivers the result. +pub async fn refresh(s: &ControlState, wait: Duration) { + let tasks: Vec<_> = due(s) + .into_iter() + .map(|(p, reading)| { + let state = s.clone(); + tokio::spawn(async move { read(&state, &p, reading).await }) + }) + .collect(); + let _ = tokio::time::timeout(wait, futures::future::join_all(tasks)).await; +} + +/// Explicit account details share the same in-flight read, including failures. +pub(super) async fn usage(s: &ControlState, name: &str) -> Answer { + let p = s + .config() + .providers + .iter() + .find(|p| p.name == name) + .cloned() + .ok_or_else(|| crate::no_such_upstream(name))?; + let started = Instant::now(); + let reading = s.chatgpt.quotas.slot(&p).lock_owned().await; + if reading.finished.is_some_and(|at| at >= started) { + return reading + .answer + .clone() + .expect("finished quota read has an answer"); + } + read(s, &p, reading).await +} + +async fn read(s: &ControlState, p: &Provider, mut reading: OwnedMutexGuard) -> Answer { + let _permit = s + .chatgpt + .quotas + .limit + .acquire() + .await + .expect("quota semaphore closed"); + let answer = super::read_usage(s, &p.name).await; + // A disabled, deleted or replaced account must not be overwritten by an old answer. + let current = s.config().providers.iter().any(|now| { + now.name == p.name + && now.disabled == p.disabled + && now.effective_protocol() == p.effective_protocol() + && identity(now) == identity(p) + }); + if !current { + return Err(crate::no_such_upstream(&p.name)); + } + if let Ok(usage) = &answer { + super::record_usage(s, &p.name, usage); + } + reading.finish(answer.clone(), Instant::now()); + answer +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn refreshes_stale_quotas_and_backs_off_failures() { + let now = Instant::now(); + let mut r = Reading::default(); + assert!(r.due(now)); + let ok = tw_api::ChatgptUsage { + windows: vec![], + reset_credits: None, + }; + r.finish(Ok(ok.clone()), now); + assert!(!r.due(now + REFRESH - Duration::from_millis(1))); + assert!(r.due(now + REFRESH)); + assert_eq!(retry_after(1), RETRY); + assert_eq!(retry_after(2), Duration::from_secs(120)); + assert_eq!(retry_after(100), Duration::from_secs(900)); + r.failures = 4; + r.finish(Ok(ok), now); + assert_eq!(r.failures, 0); + assert_eq!(r.next, Some(now + REFRESH)); + } + + #[test] + fn fresh_traffic_postpones_queries_and_resets_schedule_one_earlier_read() { + let now = Instant::now(); + let mut r = Reading { + failures: 3, + ..Default::default() + }; + r.observe(&[], now); + assert_eq!(r.failures, 0); + assert_eq!(r.next, Some(now + REFRESH)); + r.observe(&[], now + Duration::from_secs(800)); + assert!(!r.due(now + REFRESH)); + + let wall = 1_000_000; + let window = |at| tw_api::QuotaWindow { + window: "5h".into(), + used_percent: 99.0, + resets_at_ms: Some(at), + status: None, + credits: None, + }; + assert_eq!( + refresh_after(&[window(wall + 120_000)], wall), + Duration::from_secs(125) + ); + assert_eq!(refresh_after(&[window(wall + 1_000)], wall), RETRY); + assert_eq!(refresh_after(&[window(wall - 1)], wall), REFRESH); + assert_eq!(refresh_after(&[window(wall + 3_600_000)], wall), REFRESH); + } +} diff --git a/crates/tw-control/src/lib.rs b/crates/tw-control/src/lib.rs index f0801ccc..61e55542 100644 --- a/crates/tw-control/src/lib.rs +++ b/crates/tw-control/src/lib.rs @@ -1236,10 +1236,14 @@ fn not_running(id: u64) -> Fail { /// 按量付费的账号没有这些头,那时这个列表是空的 —— 界面据此决定显示 /// 金额还是百分比,两种人格共用同一块地方。 /// -/// GLM Coding Plan 的额度不在响应头里:**界面来要时去问**(60 秒内合成一次),问得慢的 -/// 不等,问完由 `QuotaSeen` 补上;判定没有套餐的,由一条窗口为空的 `QuotaSeen` 撤下 +/// ChatGPT 和 GLM Coding Plan 都可主动查询:**所有读取者共用同一份额度**,不依赖上游页。 +/// ChatGPT 优先跟随真实流量的响应头,过期或窗口重置时才补问;GLM 60 秒内合成一次。 +/// 问得慢的由 `QuotaSeen` 补上;GLM 没有套餐时用空窗口撤下。 async fn quota(State(s): State) -> Json> { - s.gateway.refresh_glm_quotas(GLM_QUOTA_WAIT).await; + tokio::join!( + s.gateway.refresh_glm_quotas(QUOTA_WAIT), + chatgpt::quotas::refresh(&s, QUOTA_WAIT), + ); let mut out: Vec = s .gateway .quotas() @@ -1253,8 +1257,8 @@ async fn quota(State(s): State) -> Json Json(out) } -/// 界面来要额度时,最多等 GLM 的额度接口多久 -const GLM_QUOTA_WAIT: std::time::Duration = std::time::Duration::from_secs(5); +/// 界面来要额度时,最多等账号的额度接口多久 +const QUOTA_WAIT: std::time::Duration = std::time::Duration::from_secs(5); /// 按上游分的延迟。**「哪家 TTFT 最差」问的是这个。** /// diff --git a/crates/tw-control/tests/chatgpt.rs b/crates/tw-control/tests/chatgpt.rs index 5dc895fe..b0702959 100644 --- a/crates/tw-control/tests/chatgpt.rs +++ b/crates/tw-control/tests/chatgpt.rs @@ -45,6 +45,9 @@ struct OpenAi { device_asks: Mutex>, /// 登录换 token 时发的 id_token。不设就是 [`id_token`] id_token: Mutex>, + usage_percent: Mutex>, + usage_failed: Mutex, + usage_delay: Mutex, } fn jwt(claims: Value) -> String { @@ -220,9 +223,15 @@ async fn start_openai(o: Arc) -> Endpoints { h.get("authorization").and_then(|v| v.to_str().ok()) == Some(&format!("Bearer {t}")) }); seen(&o, &uri, h); + let delay = *o.usage_delay.lock().unwrap(); + tokio::time::sleep(delay).await; if rejected { return (StatusCode::UNAUTHORIZED, axum::Json(json!({"detail": "Unauthorized"}))); } + if *o.usage_failed.lock().unwrap() { + return (StatusCode::SERVICE_UNAVAILABLE, axum::Json(json!({"detail": "Try later"}))); + } + let used = o.usage_percent.lock().unwrap().unwrap_or(21.0); (StatusCode::OK, axum::Json(json!({ "user_id": "user-1", "account_id": "acct-1", @@ -231,7 +240,7 @@ async fn start_openai(o: Arc) -> Endpoints { "rate_limit": { "allowed": true, "limit_reached": false, - "primary_window": {"used_percent": 21, "limit_window_seconds": 604800, "reset_after_seconds": 410907, "reset_at": 1790000000}, + "primary_window": {"used_percent": used, "limit_window_seconds": 604800, "reset_after_seconds": 410907, "reset_at": 1790000000}, "secondary_window": {"used_percent": 0, "limit_window_seconds": 0, "reset_after_seconds": 0, "reset_at": 0} }, "credits": {"has_credits": false, "unlimited": false, "balance": "0"}, @@ -959,12 +968,220 @@ async fn a_login_mode_that_is_not_understood_is_refused() { // ---------------------------------------------------------------- 用量与重置卡 +#[tokio::test] +async fn overview_and_menu_quota_reads_work_before_visiting_upstreams() { + let b = bed(|e| logged_in("chatgpt", e, "rt-cfg")).await; + let (st, quotas) = b.call("GET", "/quota", Value::Null).await; + assert_eq!(st, StatusCode::OK); + assert_eq!(quotas[0]["provider"], "chatgpt"); + assert_eq!(quotas[0]["windows"][0]["used_percent"], 21.0); + // Multiple quota views share the refresh; the account panel can still request a fresh read. + b.call("GET", "/quota", Value::Null).await; + assert_eq!(b.openai.backend.lock().unwrap().len(), 1); + b.call("GET", "/providers/chatgpt/chatgpt/usage", Value::Null) + .await; + assert_eq!(b.openai.backend.lock().unwrap().len(), 2); +} + +#[tokio::test] +async fn quota_polling_warms_and_refreshes_without_any_desktop_page() { + let mut b = bed(|e| logged_in("chatgpt", e, "rt-cfg")).await; + let task = tw_control::chatgpt::quotas::spawn(b.state.clone()); + async fn seen(b: &mut Bed) -> f64 { + tokio::time::timeout(Duration::from_secs(3), async { + loop { + if let Ok(tw_api::Event::QuotaSeen { windows, .. }) = b.events.recv().await { + return windows[0].used_percent; + } + } + }) + .await + .expect("no quota update event") + } + assert_eq!(seen(&mut b).await, 21.0); + *b.openai.usage_percent.lock().unwrap() = Some(78.0); + tokio::time::pause(); + tokio::time::advance(Duration::from_secs(66)).await; + tokio::time::resume(); + b.call("GET", "/quota", Value::Null).await; + assert_eq!( + b.openai.backend.lock().unwrap().len(), + 1, + "no minute polling" + ); + tokio::time::pause(); + tokio::time::advance(Duration::from_secs(15 * 60)).await; + tokio::time::resume(); + assert_eq!(seen(&mut b).await, 78.0); + task.abort(); + let _ = task.await; + assert_eq!( + b.state.gateway.quotas()["chatgpt"].windows[0].used_percent, + 78.0 + ); + assert_eq!(b.openai.backend.lock().unwrap().len(), 2); +} + +fn quota_from_traffic(b: &Bed, used_percent: f64, resets_at_ms: Option) { + // The data plane calls record_quota when a real response includes quota headers. + b.state.gateway.record_quota( + b.state.bus().next_id(), + "chatgpt", + tw_gateway::quota::Quota { + windows: vec![tw_gateway::quota::Window { + window: "weekly".into(), + used_percent, + resets_at_ms, + status: None, + credits: None, + }], + }, + ); +} + +#[tokio::test] +async fn fresh_traffic_keeps_the_menu_current_without_extra_quota_queries() { + let b = bed(|e| logged_in("chatgpt", e, "rt-cfg")).await; + b.call("GET", "/quota", Value::Null).await; + let task = tw_control::chatgpt::quotas::spawn(b.state.clone()); + tokio::time::pause(); + tokio::time::advance(Duration::from_secs(14 * 60)).await; + tokio::time::resume(); + quota_from_traffic(&b, 48.0, None); + tokio::task::yield_now().await; + tokio::time::pause(); + tokio::time::advance(Duration::from_secs(2 * 60)).await; + tokio::time::resume(); + let (_, q) = b.call("GET", "/quota", Value::Null).await; + assert_eq!(q[0]["windows"][0]["used_percent"], 48.0); + assert_eq!(b.openai.backend.lock().unwrap().len(), 1); + task.abort(); + let _ = task.await; +} + +#[tokio::test] +async fn a_quota_window_reset_refreshes_before_the_idle_deadline() { + let mut b = bed(|e| logged_in("chatgpt", e, "rt-cfg")).await; + b.call("GET", "/quota", Value::Null).await; + // Discard the startup event before waiting for the refresh following the reset. + while b.events.try_recv().is_ok() {} + let task = tw_control::chatgpt::quotas::spawn(b.state.clone()); + quota_from_traffic(&b, 100.0, Some(now_ms() + 60_000)); + tokio::task::yield_now().await; + *b.openai.usage_percent.lock().unwrap() = Some(0.0); + tokio::time::pause(); + tokio::time::advance(Duration::from_secs(66)).await; + tokio::time::resume(); + tokio::time::timeout(Duration::from_secs(3), async { + loop { + if let Ok(tw_api::Event::QuotaSeen { windows, .. }) = b.events.recv().await + && windows[0].used_percent == 0.0 + { + break; + } + } + }) + .await + .expect("no quota refresh after reset"); + assert_eq!(b.openai.backend.lock().unwrap().len(), 2); + task.abort(); + let _ = task.await; +} + +#[tokio::test] +async fn simultaneous_reads_and_a_timed_out_reader_share_a_detached_quota_read() { + let mut b = bed(|e| logged_in("chatgpt", e, "rt-cfg")).await; + *b.openai.usage_delay.lock().unwrap() = Duration::from_millis(100); + tw_control::chatgpt::quotas::refresh(&b.state, Duration::ZERO).await; + let (a, c, _) = tokio::join!( + b.call("GET", "/providers/chatgpt/chatgpt/usage", Value::Null), + b.call("GET", "/providers/chatgpt/chatgpt/usage", Value::Null), + b.call("GET", "/quota", Value::Null), + ); + assert_eq!(a.0, StatusCode::OK); + assert_eq!(c.0, StatusCode::OK); + assert_eq!(b.openai.backend.lock().unwrap().len(), 1); + assert!(matches!( + b.events.try_recv(), + Ok(tw_api::Event::QuotaSeen { .. }) + )); +} + +#[tokio::test] +async fn quota_polling_skips_disabled_accounts_and_preserves_the_last_value_on_failure() { + let b = bed(|e| { + format!( + "{}{}", + logged_in("chatgpt", e, "rt-cfg"), + logged_in("off", e, "rt-off").replace( + " protocol: chatgpt", + " disabled: true\n protocol: chatgpt" + ) + ) + }) + .await; + let (_, q) = b.call("GET", "/quota", Value::Null).await; + assert_eq!(q.as_array().unwrap().len(), 1); + assert_eq!(b.openai.backend.lock().unwrap().len(), 1); + *b.openai.usage_failed.lock().unwrap() = true; + tokio::time::pause(); + tokio::time::advance(Duration::from_secs(15 * 60 + 1)).await; + tokio::time::resume(); + let (_, q) = b.call("GET", "/quota", Value::Null).await; + assert_eq!(q[0]["windows"][0]["used_percent"], 21.0); + b.call("GET", "/quota", Value::Null).await; + assert_eq!( + b.openai.backend.lock().unwrap().len(), + 2, + "a failed read must back off" + ); +} + +#[tokio::test] +async fn an_account_disabled_during_a_read_does_not_publish_a_late_quota() { + let b = bed(|e| logged_in("chatgpt", e, "rt-cfg")).await; + *b.openai.usage_delay.lock().unwrap() = Duration::from_millis(150); + let change = async { + eventually("quota request started", || { + !b.openai.backend.lock().unwrap().is_empty() + }) + .await; + let mut config = (*b.state.config()).clone(); + config + .providers + .iter_mut() + .find(|p| p.name == "chatgpt") + .unwrap() + .disabled = true; + b.state.gateway.reload(config).unwrap(); + }; + let ((_, q), ()) = tokio::join!(b.call("GET", "/quota", Value::Null), change); + assert_eq!(q, json!([])); + assert!(b.state.gateway.quotas().is_empty()); +} + +#[tokio::test] +async fn stopping_the_quota_poller_cancels_its_pending_reads() { + let b = bed(|e| logged_in("chatgpt", e, "rt-cfg")).await; + *b.openai.usage_delay.lock().unwrap() = Duration::from_millis(150); + let task = tw_control::chatgpt::quotas::spawn(b.state.clone()); + eventually("quota request started", || { + !b.openai.backend.lock().unwrap().is_empty() + }) + .await; + task.abort(); + let _ = task.await; + // A new read can acquire the slot after handover/cancellation; no claim stays stuck. + let (_, q) = b.call("GET", "/quota", Value::Null).await; + assert_eq!(q[0]["windows"][0]["used_percent"], 21.0); + assert_eq!(b.openai.backend.lock().unwrap().len(), 2); +} + #[tokio::test] async fn usage_shows_the_limits_without_personal_details() { let b = bed(|e| logged_in("chatgpt", e, "rt-cfg")).await; // 还没有请求经过,额度就还不知道 - let (_, v) = b.call("GET", "/quota", Value::Null).await; - assert_eq!(v, json!([])); + assert!(b.state.gateway.quotas().is_empty()); let (st, v) = b .call("GET", "/providers/chatgpt/chatgpt/usage", Value::Null) .await; diff --git a/crates/tw-gateway/src/quota.rs b/crates/tw-gateway/src/quota.rs index 7729c44b..cd595292 100644 --- a/crates/tw-gateway/src/quota.rs +++ b/crates/tw-gateway/src/quota.rs @@ -7,10 +7,9 @@ //! **零成本**:不发额外请求、不要额外 scope、不占用户自己的配额 —— //! 顺着真实流量白捡。 //! -//! **只被动采样,不主动探测。**主动查会占掉用户自己的配额,还可能触发 -//! 上游的反滥用检测;而桌面用户手里就一两个账号,每一个都金贵。唯一的 -//! 例外是他在界面上手动点「立即刷新」—— 那是他明确的意图,而且他知道 -//! 代价。 +//! **优先被动采样,不用聊天请求探测额度。**ChatGPT 冷启动时由控制面查询用量接口, +//! 之后只在额度过期、窗口重置或用户手动刷新时补问;收到真实流量的额度头会延后补问。 +//! Anthropic 仍只读响应头。 //! //! GLM Coding Plan 是另一个例外:它的响应头里根本没有额度,只能去问账号的额度 //! 接口。那个接口不占用户的额度,问的节奏和退避见 [`crate::glm`]。 diff --git a/release-notes/0.89.1.md b/release-notes/0.89.1.md new file mode 100644 index 00000000..ff189267 --- /dev/null +++ b/release-notes/0.89.1.md @@ -0,0 +1,5 @@ +ChatGPT account quotas now load automatically at startup and when accounts are added, so Lite's overview and menu bar can display remaining quota without first opening the Upstreams page. + +Quota updates prefer the headers returned by real traffic. Background queries only fill a cold cache, refresh quota that has not been updated for 15 minutes, or check a window after its reported reset time. Manual refresh remains immediate. Concurrent readers share in-flight queries, with at most four account queries running at once; failed queries back off and preserve the last known quota. + +Disabled accounts and accounts that need to sign in again are excluded from automatic queries. No configuration changes are required. Updating an already open Lite overview also requires the accompanying Lite event-subscription fix.