From 183af4bb14c8af46b3e512413bb1469f1c0edf2d Mon Sep 17 00:00:00 2001 From: fylorn <249551762+fylorn@users.noreply.github.com> Date: Wed, 23 Sep 2026 15:36:12 +0800 Subject: [PATCH] refactor: move the quota reader to tw-wire, and stop rebuilding header maps MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit `quota` reads the subscription window straight out of response headers — Anthropic puts it on every response, Codex has the same shape in another set. It costs nothing: no extra request, no extra scope, no spending the user's own quota. It has no `tw-*` dependency and nothing about it is specific to this gateway, so it belongs next to the other sideband readers. The enterprise gateway has no equivalent and needs one as soon as it fronts a subscription account. `from_headers_reqwest` goes away. It rebuilt the entire header map entry by entry on the premise that "reqwest and axum each have their own HeaderMap" — which has not been true for some time. reqwest 0.13 and axum 0.8 both re-export http 1.5.0, so the two arguments were already the same type and every response paid for a copy that changed nothing. (The one http 0.2 in the tree comes in under aws-sigv4, i.e. the Bedrock provider.) Calling `from_headers` directly compiles, which is the proof. The crate now depends on `http` rather than reaching through axum: a shared layer should not dictate which HTTP framework its consumers run. Co-Authored-By: Claude Opus 5 --- Cargo.lock | 4 ++++ crates/tw-control/Cargo.toml | 1 + crates/tw-control/src/chatgpt.rs | 6 +++--- crates/tw-gateway/src/lib.rs | 4 +--- crates/tw-gateway/src/server.rs | 8 ++++---- crates/tw-wire/Cargo.toml | 5 +++++ crates/tw-wire/src/lib.rs | 5 ++++- crates/{tw-gateway => tw-wire}/src/quota.rs | 21 ++------------------- 8 files changed, 24 insertions(+), 30 deletions(-) rename crates/{tw-gateway => tw-wire}/src/quota.rs (96%) diff --git a/Cargo.lock b/Cargo.lock index e1659303..52ac031e 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -2857,6 +2857,7 @@ dependencies = [ "tw-secret", "tw-store", "tw-types", + "tw-wire", "tw-yaml", ] @@ -3075,6 +3076,9 @@ name = "tw-wire" version = "0.29.0" dependencies = [ "bytes", + "chrono", + "http 1.5.0", + "serde", "serde_json", "tokio", ] diff --git a/crates/tw-control/Cargo.toml b/crates/tw-control/Cargo.toml index 8193552c..b100c8e6 100644 --- a/crates/tw-control/Cargo.toml +++ b/crates/tw-control/Cargo.toml @@ -21,6 +21,7 @@ tw-redact = { workspace = true } bytes = { workspace = true } tw-engine = { workspace = true } tw-gateway = { workspace = true } +tw-wire = { workspace = true } tw-observe = { workspace = true } tw-secret = { workspace = true } tw-store = { workspace = true } diff --git a/crates/tw-control/src/chatgpt.rs b/crates/tw-control/src/chatgpt.rs index 8f6deae7..d8fef6ee 100644 --- a/crates/tw-control/src/chatgpt.rs +++ b/crates/tw-control/src/chatgpt.rs @@ -965,11 +965,11 @@ async fn usage( s.gateway.record_quota( s.bus().next_id(), &name, - tw_gateway::quota::Quota { + tw_wire::quota::Quota { windows: usage .windows .iter() - .map(|w| tw_gateway::quota::Window { + .map(|w| tw_wire::quota::Window { window: w.window.clone(), used_percent: w.used_percent, resets_at_ms: w.resets_at_ms, @@ -991,7 +991,7 @@ fn parse_usage(v: &Value, now_ms: u64) -> tw_api::ChatgptUsage { let secs = w.get("limit_window_seconds")?.as_u64().filter(|s| *s > 0)?; let used = w.get("used_percent")?.as_f64()?.clamp(0.0, 100.0); Some(tw_api::QuotaWindow { - window: tw_gateway::quota::codex_window(secs / 60), + window: tw_wire::quota::codex_window(secs / 60), used_percent: used, resets_at_ms: w .get("reset_after_seconds") diff --git a/crates/tw-gateway/src/lib.rs b/crates/tw-gateway/src/lib.rs index f672e9d1..d89bd6e8 100644 --- a/crates/tw-gateway/src/lib.rs +++ b/crates/tw-gateway/src/lib.rs @@ -26,7 +26,6 @@ pub mod live; pub mod models; pub mod oauth; pub mod probe; -pub mod quota; pub mod quote; pub mod server; pub mod session; @@ -46,10 +45,9 @@ pub use l3::{Estimate, L3Result}; pub use limits::Gate; pub use listen::{Listening, bind_failure, serve_at}; pub use probe::{ModelList, ProbeResult, probe}; -pub use quota::{Quota, from_headers as quota_from_headers}; pub use quote::Quote; pub use server::{AppState, Runtime, client_for_provider, router, serve}; -pub use tw_wire::{BodyKind, BodyRecord, BodySender, Sniffer, Usage}; +pub use tw_wire::{BodyKind, BodyRecord, BodySender, Quota, Sniffer, Usage, quota_from_headers}; /// 请求来自谁。**如实写 ThinkWatch** —— 我们从不把自己报成别的客户端。 pub const ORIGINATOR: &str = "thinkwatch"; diff --git a/crates/tw-gateway/src/server.rs b/crates/tw-gateway/src/server.rs index ca7513ec..81393e04 100644 --- a/crates/tw-gateway/src/server.rs +++ b/crates/tw-gateway/src/server.rs @@ -240,7 +240,7 @@ pub struct AppState { /// **在内存里,不落库。**它是「现在还剩多少」,不是历史 —— 存一份 /// 五分钟前的百分比,价值几乎为零,而它会让「重启之后显示的是旧 /// 数字」变成一个要解释的问题。下一个请求回来就有新的了。 - quotas: Arc>>, + quotas: Arc>>, /// 监听地址变了。**这是「温」那一级**(三级热重载) —— /// 换端口不能只换配置:监听器是启动时建的,不重建的话新端口上什么 /// 都没有,而旧端口还在服务。那种「改了没反应」比报错难查得多。 @@ -699,13 +699,13 @@ impl AppState { self.record_quota( id, provider, - crate::quota::from_headers_reqwest(headers, now_ms()), + tw_wire::quota::from_headers(headers, now_ms()), ); } /// 记下一份额度。**账号接口问来的也走这里**:额度只在内存里,冷启动之后要等第一次 /// 请求才有,而界面一打开就该看得见 - pub fn record_quota(&self, id: u64, provider: &str, quota: crate::quota::Quota) { + pub fn record_quota(&self, id: u64, provider: &str, quota: tw_wire::quota::Quota) { if quota.is_empty() { return; } @@ -880,7 +880,7 @@ impl AppState { } /// 每个上游最近一次报的订阅额度。 - pub fn quotas(&self) -> std::collections::HashMap { + pub fn quotas(&self) -> std::collections::HashMap { self.quotas.lock().map(|g| g.clone()).unwrap_or_default() } diff --git a/crates/tw-wire/Cargo.toml b/crates/tw-wire/Cargo.toml index eec0819a..b5c35c50 100644 --- a/crates/tw-wire/Cargo.toml +++ b/crates/tw-wire/Cargo.toml @@ -9,7 +9,12 @@ description = "Sideband readers for a streaming response: usage sniffing and bod [dependencies] bytes = { workspace = true } +chrono = { workspace = true } +serde = { workspace = true } serde_json = { workspace = true } +# 只要 HeaderMap。**不要 axum 也不要 reqwest** —— 共享层不该规定下游用哪个 +# HTTP 框架,而两者的 HeaderMap 本来就都是这个 crate 的类型 +http = "1" # 只要一个 mpsc 发送端。**不用 workspace 那份** —— 那份带着网络、信号、 # 计时器,而这个 crate 要能被企业版直接依赖,背什么进去是它说了算 tokio = { version = "1", default-features = false, features = ["sync"] } diff --git a/crates/tw-wire/src/lib.rs b/crates/tw-wire/src/lib.rs index 36e38e37..aecbf544 100644 --- a/crates/tw-wire/src/lib.rs +++ b/crates/tw-wire/src/lib.rs @@ -5,13 +5,16 @@ //! 一下全出来」。所以这里的东西都是旁路的:字节照常流向客户端,同时喂 //! 它们一份。 //! -//! [`usage`] 嗅出上游报的用量,[`bodies`] 留档请求和响应的正文。 +//! [`usage`] 嗅出上游报的用量,[`quota`] 从响应头白捡订阅额度,[`bodies`] +//! 留档请求和响应的正文。 //! //! 这一层刻意零业务依赖 —— 它不认识配置从哪来、数据存哪里、谁在调用, //! 所以企业版和桌面版都能直接用。 pub mod bodies; +pub mod quota; pub mod usage; pub use bodies::{BodyKind, BodyRecord, BodySender, ResponseTap}; +pub use quota::{Quota, from_headers as quota_from_headers}; pub use usage::{Sniffer, Usage}; diff --git a/crates/tw-gateway/src/quota.rs b/crates/tw-wire/src/quota.rs similarity index 96% rename from crates/tw-gateway/src/quota.rs rename to crates/tw-wire/src/quota.rs index 597699f5..a9b61802 100644 --- a/crates/tw-gateway/src/quota.rs +++ b/crates/tw-wire/src/quota.rs @@ -16,7 +16,7 @@ //! 直接显示,我们推断的要标成推断。理由和三态成本完全一样: //! **一个编出来的精确数字,比一个诚实的「不知道」更有害。** -use axum::http::HeaderMap; +use http::HeaderMap; use serde::{Deserialize, Serialize}; /// 一个额度窗口的状态。**每个字段都直接来自响应头,没有一个是推算的。** @@ -197,23 +197,6 @@ fn after(now_ms: u64, secs: u64) -> u64 { now_ms.saturating_add(secs.saturating_mul(1000)) } -/// 从 reqwest 的响应头读。 -/// -/// **两个 HeaderMap 类型,一段逻辑。**reqwest 和 axum 各有各的 -/// `HeaderMap`,而把解析抄两遍必然会漂移出两套行为。 -pub fn from_headers_reqwest(h: &reqwest::header::HeaderMap, now_ms: u64) -> Quota { - let mut axum_map = HeaderMap::new(); - for (k, v) in h.iter() { - if let (Ok(name), Ok(val)) = ( - axum::http::HeaderName::from_bytes(k.as_ref()), - axum::http::HeaderValue::from_bytes(v.as_bytes()), - ) { - axum_map.insert(name, val); - } - } - from_headers(&axum_map, now_ms) -} - #[cfg(test)] mod tests { use super::*; @@ -225,7 +208,7 @@ mod tests { let mut h = HeaderMap::new(); for (k, v) in pairs { h.insert( - axum::http::HeaderName::from_bytes(k.as_bytes()).unwrap(), + http::HeaderName::from_bytes(k.as_bytes()).unwrap(), v.parse().unwrap(), ); }