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
44 changes: 22 additions & 22 deletions Cargo.lock

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

2 changes: 1 addition & 1 deletion Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -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 ───────────────────────────────────────────
Expand Down
15 changes: 11 additions & 4 deletions bin/twcore/src/background.rs
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
//! 后台事务:OAuth 写回、同步、价目表刷新、默认插件、模型目录、余额、日志回收。
//! 后台事务:OAuth 写回、同步、价目表刷新、默认插件、模型目录、额度、余额、日志回收。
//!
//! # 为什么放在一个单独的运行时上
//!
Expand All @@ -8,8 +8,8 @@
//! [`Background::stop`] 一次关掉整个运行时,任务连同它们派生的任务一起停下,转发那一边
//! (主运行时)不受影响。
//!
//! **模型目录、余额例外**,见 [`Background::start`] 里的说明:它们和转发共用连接池,
//! 不能跟着这个运行时一起关。
//! **模型目录、额度、余额例外**,见 [`Background::start`] 里的说明:它们和转发共用连接池,
//! 不能跟着这个运行时一起关。额度任务单独持有把手,交接时取消。
//!
//! **OAuth 写回例外地先收尾**:它手上那份新 refresh token 要是丢了,新 core 读到的就是一张
//! 已经作废的(见 [`tw_control::rotation::Rotation::settle`])。
Expand All @@ -28,12 +28,13 @@ const ROTATION_SETTLE: Duration = Duration::from_secs(5);
pub struct Background {
rt: Option<tokio::runtime::Runtime>,
rotation: Option<Arc<tw_control::rotation::Rotation>>,
quotas: Option<tokio::task::JoinHandle<()>>,
}

/// 起后台事务要的东西。
pub struct Start<'a> {
pub control: &'a tw_control::ControlState,
/// 安全模式:只起写回、同步(暂停着)、价目表;不起默认插件、模型目录、余额
/// 安全模式:只起写回、同步(暂停着)、价目表;不起默认插件、模型目录、额度、余额
pub safe: bool,
pub seeder: Option<tw_control::plugins::defaults::Seeder>,
pub store: Option<Store>,
Expand Down Expand Up @@ -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)
Expand All @@ -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();
Expand Down
2 changes: 1 addition & 1 deletion crates/tw-control/Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -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"] }
17 changes: 14 additions & 3 deletions crates/tw-control/src/chatgpt.rs
Original file line number Diff line number Diff line change
Expand Up @@ -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);
/// 设备码最快多久问一次「批准了没有」。服务端给的间隔比它还短就按它来 —— 问得再勤,
Expand Down Expand Up @@ -91,13 +93,15 @@ impl Default for Endpoints {
pub struct Accounts {
pub endpoints: Endpoints,
current: Mutex<Option<Current>>,
quotas: quotas::Cache,
}

impl Accounts {
pub fn new(endpoints: Endpoints) -> Self {
Self {
endpoints,
current: Mutex::new(None),
quotas: Default::default(),
}
}

Expand Down Expand Up @@ -997,13 +1001,21 @@ async fn usage(
State(s): State<ControlState>,
Path(name): Path<String>,
) -> Result<Json<tw_api::ChatgptUsage>, 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<tw_api::ChatgptUsage, Fail> {
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
Expand All @@ -1018,7 +1030,6 @@ async fn usage(
.collect(),
},
);
Ok(Json(usage))
}

/// `wham/usage` 的回答。**只取额度和重置卡**:同一份回答里的邮箱、套餐由上游视图从
Expand Down
Loading
Loading