From 6caf52d30f136447781b13a970e3e639e0a66bf0 Mon Sep 17 00:00:00 2001 From: fylorn <249551762+fylorn@users.noreply.github.com> Date: Thu, 24 Sep 2026 04:15:34 +0800 Subject: [PATCH] refactor!: tw-wire is usage only; quota and bodies go back to the desktop gateway MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit tw-wire was cut out to be shared with the server edition, and one of its three parts is: the usage sniffer. The other two only the desktop uses, and the server edition will not — its body capture is an audit pipeline with PII redaction, byte caps and S3 offload, a different thing from a bounded channel to a local store, and its quota is its own. A "shared" module with one user is a second place to change things, as tw-resil was. - `quota` → `tw_gateway::quota`, `bodies` → `tw_gateway::bodies`. - tw-wire keeps `usage` and depends on serde_json alone. - The crate-root re-exports of these types in tw-gateway had no users; callers name the module. BREAKING: tw_wire::{bodies, quota} are now in tw-gateway. Co-Authored-By: Claude Opus 5.5 --- Cargo.lock | 6 +---- bin/twcore/src/main.rs | 10 ++++---- crates/tw-control/src/chatgpt.rs | 6 ++--- crates/tw-gateway/Cargo.toml | 1 + crates/{tw-wire => tw-gateway}/src/bodies.rs | 0 crates/tw-gateway/src/ending.rs | 4 ++-- crates/tw-gateway/src/lib.rs | 3 ++- crates/{tw-wire => tw-gateway}/src/quota.rs | 0 crates/tw-gateway/src/server.rs | 24 ++++++++------------ crates/tw-wire/Cargo.toml | 14 +----------- crates/tw-wire/src/lib.rs | 22 ++++++++---------- 11 files changed, 34 insertions(+), 56 deletions(-) rename crates/{tw-wire => tw-gateway}/src/bodies.rs (100%) rename crates/{tw-wire => tw-gateway}/src/quota.rs (100%) diff --git a/Cargo.lock b/Cargo.lock index 2383051c..c8fd7815 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -2883,6 +2883,7 @@ dependencies = [ "bytes", "chrono", "futures", + "http 1.5.0", "http-body-util", "hyper", "hyper-util", @@ -3024,12 +3025,7 @@ dependencies = [ name = "tw-wire" version = "0.37.0" dependencies = [ - "bytes", - "chrono", - "http 1.5.0", - "serde", "serde_json", - "tokio", ] [[package]] diff --git a/bin/twcore/src/main.rs b/bin/twcore/src/main.rs index 9285b7e5..3a0bcd2e 100644 --- a/bin/twcore/src/main.rs +++ b/bin/twcore/src/main.rs @@ -748,7 +748,7 @@ fn cmd_serve(path: &Path, port: Option, safe: bool, parent: Option) -> // // body 的通道在这里建:**它是唯一同时看得见网关和存储的地方**, // 而两边各有各的同形结构,是为了不让「观测」挂到「转发」下面。 - let (body_tx, body_rx) = tokio::sync::mpsc::channel(tw_wire::bodies::CHANNEL_CAP); + let (body_tx, body_rx) = tokio::sync::mpsc::channel(tw_gateway::bodies::CHANNEL_CAP); let store = build_store(&dir, state.bus.clone(), state.pricing.clone(), body_rx); if store.is_some() { state.set_body_sink(body_tx); @@ -919,7 +919,7 @@ fn build_store( bus: tw_observe::EventBus, // **和网关同一份价格簿**,不是一份副本:改了价目表,下一个结束的请求就按新价算 pricing: tw_pricing::Shared, - bodies: tokio::sync::mpsc::Receiver, + bodies: tokio::sync::mpsc::Receiver, ) -> Option>> { let events = bus.subscribe(); let (db, blobs) = match tw_store::open(dir) { @@ -951,7 +951,7 @@ fn build_store( } // 两边的 body 结构在这里对接。**一次移动,不复制** —— `Bytes` 的 // 克隆是引用计数。 - let (tx, rx) = tokio::sync::mpsc::channel(tw_wire::bodies::CHANNEL_CAP); + let (tx, rx) = tokio::sync::mpsc::channel(tw_gateway::bodies::CHANNEL_CAP); let mut bodies = bodies; tokio::spawn(async move { while let Some(b) = bodies.recv().await { @@ -959,8 +959,8 @@ fn build_store( id: b.id, at_ms: b.at_ms, which: match b.kind { - tw_gateway::BodyKind::Request => tw_store::Which::Request, - tw_gateway::BodyKind::Response => tw_store::Which::Response, + tw_gateway::bodies::BodyKind::Request => tw_store::Which::Request, + tw_gateway::bodies::BodyKind::Response => tw_store::Which::Response, }, body: b.body, original_len: b.original_len, diff --git a/crates/tw-control/src/chatgpt.rs b/crates/tw-control/src/chatgpt.rs index c48aa075..da140a81 100644 --- a/crates/tw-control/src/chatgpt.rs +++ b/crates/tw-control/src/chatgpt.rs @@ -962,11 +962,11 @@ async fn usage( s.gateway.record_quota( s.bus().next_id(), &name, - tw_wire::quota::Quota { + tw_gateway::quota::Quota { windows: usage .windows .iter() - .map(|w| tw_wire::quota::Window { + .map(|w| tw_gateway::quota::Window { window: w.window.clone(), used_percent: w.used_percent, resets_at_ms: w.resets_at_ms, @@ -988,7 +988,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_wire::quota::codex_window(secs / 60), + window: tw_gateway::quota::codex_window(secs / 60), used_percent: used, resets_at_ms: w .get("reset_after_seconds") diff --git a/crates/tw-gateway/Cargo.toml b/crates/tw-gateway/Cargo.toml index 99b0ffeb..5740d272 100644 --- a/crates/tw-gateway/Cargo.toml +++ b/crates/tw-gateway/Cargo.toml @@ -18,6 +18,7 @@ tw-types = { workspace = true } arc-swap = { workspace = true } async-stream = { workspace = true } axum = { workspace = true } +http = "1" tokio-tungstenite = { workspace = true } bytes = { workspace = true } chrono = { workspace = true } diff --git a/crates/tw-wire/src/bodies.rs b/crates/tw-gateway/src/bodies.rs similarity index 100% rename from crates/tw-wire/src/bodies.rs rename to crates/tw-gateway/src/bodies.rs diff --git a/crates/tw-gateway/src/ending.rs b/crates/tw-gateway/src/ending.rs index b8d69658..67adb2f7 100644 --- a/crates/tw-gateway/src/ending.rs +++ b/crates/tw-gateway/src/ending.rs @@ -22,8 +22,8 @@ use std::time::Instant; +use crate::bodies::{BodyKind, BodyRecord, BodySender, ResponseTap}; use tw_types::{Msg, msg}; -use tw_wire::bodies::{BodyKind, BodyRecord, BodySender, ResponseTap}; use tw_wire::usage::{Sniffer, Usage}; /// 一个还欠着结局的请求。 @@ -136,7 +136,7 @@ impl Ending { self.told = true; let (recorded, original_len) = std::mem::take(&mut self.tap).finish(); if !recorded.is_empty() { - tw_wire::bodies::offer( + crate::bodies::offer( &self.sink, BodyRecord { id: self.id, diff --git a/crates/tw-gateway/src/lib.rs b/crates/tw-gateway/src/lib.rs index a5f2618a..5f336656 100644 --- a/crates/tw-gateway/src/lib.rs +++ b/crates/tw-gateway/src/lib.rs @@ -7,6 +7,7 @@ pub mod access; pub mod auth; +pub mod bodies; pub mod chatgpt; pub mod client_api; pub mod clientprobe; @@ -26,6 +27,7 @@ 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,7 +48,6 @@ pub use listen::{Listening, bind_failure, serve_at}; pub use probe::{ModelList, ProbeResult, probe}; pub use quote::Quote; pub use server::{AppState, Runtime, client_for_provider, router, serve}; -pub use tw_wire::{BodyKind, BodyRecord, BodySender, Quota, Sniffer, Usage, quota_from_headers}; /// 请求来自谁。**如实写 ThinkWatch** —— 我们从不把自己报成别的客户端。 pub const ORIGINATOR: &str = "thinkwatch"; diff --git a/crates/tw-wire/src/quota.rs b/crates/tw-gateway/src/quota.rs similarity index 100% rename from crates/tw-wire/src/quota.rs rename to crates/tw-gateway/src/quota.rs diff --git a/crates/tw-gateway/src/server.rs b/crates/tw-gateway/src/server.rs index 1d61dddb..7450585a 100644 --- a/crates/tw-gateway/src/server.rs +++ b/crates/tw-gateway/src/server.rs @@ -234,13 +234,13 @@ pub struct AppState { /// **有界通道,满了就丢。**直接调用意味着文件 I/O 跑在转发那条路上 /// —— 一次慢磁盘写就变成一次慢请求,而观测永远不该有这个权力。 /// `None` 表示观测层没起来,那时什么都不做。 - body_sink: Arc>>, + body_sink: Arc>>, /// 每个上游最近一次报的订阅额度。 /// /// **在内存里,不落库。**它是「现在还剩多少」,不是历史 —— 存一份 /// 五分钟前的百分比,价值几乎为零,而它会让「重启之后显示的是旧 /// 数字」变成一个要解释的问题。下一个请求回来就有新的了。 - quotas: Arc>>, + quotas: Arc>>, /// 监听地址变了。**这是「温」那一级**(三级热重载) —— /// 换端口不能只换配置:监听器是启动时建的,不重建的话新端口上什么 /// 都没有,而旧端口还在服务。那种「改了没反应」比报错难查得多。 @@ -696,16 +696,12 @@ impl AppState { /// **429 的那一跳也要读**:额度用完时上游回的正是 429,只读成功那一跳的话, /// 「用完了」这件事永远看不到。 pub(crate) fn note_quota(&self, id: u64, provider: &str, headers: &reqwest::header::HeaderMap) { - self.record_quota( - id, - provider, - tw_wire::quota::from_headers(headers, now_ms()), - ); + self.record_quota(id, provider, crate::quota::from_headers(headers, now_ms())); } /// 记下一份额度。**账号接口问来的也走这里**:额度只在内存里,冷启动之后要等第一次 /// 请求才有,而界面一打开就该看得见 - pub fn record_quota(&self, id: u64, provider: &str, quota: tw_wire::quota::Quota) { + pub fn record_quota(&self, id: u64, provider: &str, quota: crate::quota::Quota) { if quota.is_empty() { return; } @@ -828,7 +824,7 @@ impl AppState { /// 接上 body 的去处。**观测层起来之后才调** —— 在那之前 body 一律 /// 丢掉,而请求照常。 - pub fn set_body_sink(&self, tx: tw_wire::bodies::BodySender) { + pub fn set_body_sink(&self, tx: crate::bodies::BodySender) { if let Ok(mut g) = self.body_sink.lock() { *g = Some(tx); } @@ -875,12 +871,12 @@ impl AppState { } } - fn body_sink(&self) -> Option { + fn body_sink(&self) -> Option { self.body_sink.lock().ok().and_then(|g| g.clone()) } /// 每个上游最近一次报的订阅额度。 - pub fn quotas(&self) -> std::collections::HashMap { + pub fn quotas(&self) -> std::collections::HashMap { self.quotas.lock().map(|g| g.clone()).unwrap_or_default() } @@ -1690,12 +1686,12 @@ async fn pipeline( // 请求体交给观测层。**这时候它已经完整在内存里了**,所以这一步 // 除了一次 `Bytes` 的引用计数之外没有别的成本(说过入站是要 // 整个解析的,所以本来就在)。 - tw_wire::bodies::offer( + crate::bodies::offer( &sink, - tw_wire::bodies::BodyRecord { + crate::bodies::BodyRecord { id, at_ms, - kind: tw_wire::bodies::BodyKind::Request, + kind: crate::bodies::BodyKind::Request, body: body.clone(), original_len: body.len(), }, diff --git a/crates/tw-wire/Cargo.toml b/crates/tw-wire/Cargo.toml index b5c35c50..6dbec4a9 100644 --- a/crates/tw-wire/Cargo.toml +++ b/crates/tw-wire/Cargo.toml @@ -5,19 +5,7 @@ edition.workspace = true rust-version.workspace = true license.workspace = true repository.workspace = true -description = "Sideband readers for a streaming response: usage sniffing and body capture" +description = "Read the usage an upstream reports, alongside a response that keeps streaming" [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"] } - -[dev-dependencies] -tokio = { version = "1", features = ["rt", "macros"] } diff --git a/crates/tw-wire/src/lib.rs b/crates/tw-wire/src/lib.rs index aecbf544..7cbc9c31 100644 --- a/crates/tw-wire/src/lib.rs +++ b/crates/tw-wire/src/lib.rs @@ -1,20 +1,16 @@ -//! 响应流过时顺带做的两件事。 +//! 从响应里嗅出上游报的用量。 //! -//! 两者共享同一条纪律:**不缓冲**。响应是流着出去的,为了看一眼它而把 -//! 它整块攒下来,会把 SSE 变成一次性交付 —— 客户端看到的是「卡很久,然后 -//! 一下全出来」。所以这里的东西都是旁路的:字节照常流向客户端,同时喂 -//! 它们一份。 -//! -//! [`usage`] 嗅出上游报的用量,[`quota`] 从响应头白捡订阅额度,[`bodies`] -//! 留档请求和响应的正文。 +//! **不缓冲**。响应是流着出去的,为了看一眼它而把它整块攒下来,会把 SSE +//! 变成一次性交付 —— 客户端看到的是「卡很久,然后一下全出来」。所以这里 +//! 是旁路的:字节照常流向客户端,同时喂它一份。 //! //! 这一层刻意零业务依赖 —— 它不认识配置从哪来、数据存哪里、谁在调用, -//! 所以企业版和桌面版都能直接用。 +//! 所以企业版和桌面版都直接用它。 +//! +//! 以前这里还有订阅额度(`quota`)和正文留档(`bodies`)。两者只有桌面版 +//! 在用,已经搬回 tw-gateway:只有一方在用的「共用件」,是第二个要改的 +//! 地方,不是共用。 -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};