From 4a4e74a54e1ca3bca7b74cbe188b7c4999811fb6 Mon Sep 17 00:00:00 2001 From: fylorn <249551762+fylorn@users.noreply.github.com> Date: Wed, 23 Sep 2026 15:17:21 +0800 Subject: [PATCH 1/2] refactor: lift the two sideband readers out of the gateway MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit `usage` and `bodies` sit in tw-gateway, but neither knows anything about this gateway. Zero `crate::` references between them and the rest, zero users outside tw-gateway, and one external dependency each — serde_json and bytes. They are general wire-format machinery filed under a binary that happens to have been written first. The enterprise gateway needs both and has neither. Its token counter is 106 lines of `latin/4 + cjk/2` character estimation, and it reads streaming usage off whatever the provider adapter left on a chat chunk, so anything the adapter dropped is simply gone. `usage` here reads the upstream's own numbers across all four formats in both modes, and subtracts cache hits where the vendor folds them into the input count — OpenAI and Gemini do, Anthropic does not. Billing off the estimate charges the cached prefix at input price a second time. So they move to `tw-wire`, which either side can depend on. Both files move unchanged; only the paths that referenced them changed. tokio is declared here rather than taken from the workspace: the workspace copy carries net, signal and timers, and a crate meant to be pulled in from outside should decide for itself what it drags along. A single `mpsc::Sender` needs `sync`. Co-Authored-By: Claude Opus 5 --- Cargo.lock | 11 +++++++++++ Cargo.toml | 2 ++ bin/twcore/Cargo.toml | 1 + bin/twcore/src/main.rs | 4 ++-- crates/tw-gateway/Cargo.toml | 1 + crates/tw-gateway/src/ending.rs | 6 +++--- crates/tw-gateway/src/fixture.rs | 2 +- crates/tw-gateway/src/lib.rs | 5 +---- crates/tw-gateway/src/server.rs | 12 ++++++------ crates/tw-wire/Cargo.toml | 18 ++++++++++++++++++ crates/{tw-gateway => tw-wire}/src/bodies.rs | 0 crates/tw-wire/src/lib.rs | 17 +++++++++++++++++ crates/{tw-gateway => tw-wire}/src/usage.rs | 0 13 files changed, 63 insertions(+), 16 deletions(-) create mode 100644 crates/tw-wire/Cargo.toml rename crates/{tw-gateway => tw-wire}/src/bodies.rs (100%) create mode 100644 crates/tw-wire/src/lib.rs rename crates/{tw-gateway => tw-wire}/src/usage.rs (100%) diff --git a/Cargo.lock b/Cargo.lock index 436e2db4..e1659303 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -2932,6 +2932,7 @@ dependencies = [ "tw-scan", "tw-secret", "tw-types", + "tw-wire", "uuid", ] @@ -3069,6 +3070,15 @@ dependencies = [ "thiserror", ] +[[package]] +name = "tw-wire" +version = "0.29.0" +dependencies = [ + "bytes", + "serde_json", + "tokio", +] + [[package]] name = "tw-yaml" version = "0.29.0" @@ -3101,6 +3111,7 @@ dependencies = [ "tw-scan", "tw-secret", "tw-store", + "tw-wire", "tw-yaml", "windows-sys 0.61.2", ] diff --git a/Cargo.toml b/Cargo.toml index fcc39163..e9db2a24 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -3,6 +3,7 @@ resolver = "2" members = [ # ── 第一层 · 共用协议层(企业版也依赖)──────────────── "crates/tw-types", + "crates/tw-wire", "crates/tw-protocol", "crates/tw-provider", "crates/tw-resil", @@ -43,6 +44,7 @@ version = "0.29.0" [workspace.dependencies] # ── 内部 crate ─────────────────────────────────────────── tw-types = { path = "crates/tw-types" } +tw-wire = { path = "crates/tw-wire" } tw-protocol = { path = "crates/tw-protocol" } tw-provider = { path = "crates/tw-provider" } tw-resil = { path = "crates/tw-resil" } diff --git a/bin/twcore/Cargo.toml b/bin/twcore/Cargo.toml index 83101b55..16b92cb7 100644 --- a/bin/twcore/Cargo.toml +++ b/bin/twcore/Cargo.toml @@ -22,6 +22,7 @@ anyhow = { workspace = true } clap = { workspace = true } tw-adopt = { workspace = true } tw-scan = { workspace = true } +tw-wire = { workspace = true } serde_yaml_ng = { workspace = true } tokio = { workspace = true } tracing = { workspace = true } diff --git a/bin/twcore/src/main.rs b/bin/twcore/src/main.rs index 4e6e4a68..b2807b61 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_gateway::bodies::CHANNEL_CAP); + let (body_tx, body_rx) = tokio::sync::mpsc::channel(tw_wire::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); @@ -951,7 +951,7 @@ fn build_store( } // 两边的 body 结构在这里对接。**一次移动,不复制** —— `Bytes` 的 // 克隆是引用计数。 - let (tx, rx) = tokio::sync::mpsc::channel(tw_gateway::bodies::CHANNEL_CAP); + let (tx, rx) = tokio::sync::mpsc::channel(tw_wire::bodies::CHANNEL_CAP); let mut bodies = bodies; tokio::spawn(async move { while let Some(b) = bodies.recv().await { diff --git a/crates/tw-gateway/Cargo.toml b/crates/tw-gateway/Cargo.toml index 3a992654..2662f987 100644 --- a/crates/tw-gateway/Cargo.toml +++ b/crates/tw-gateway/Cargo.toml @@ -36,6 +36,7 @@ rand = { workspace = true } uuid = { workspace = true } tw-redact = { workspace = true } tw-dialect = { workspace = true } +tw-wire = { workspace = true } tw-scan = { workspace = true } thiserror = { workspace = true } tokio = { workspace = true } diff --git a/crates/tw-gateway/src/ending.rs b/crates/tw-gateway/src/ending.rs index 69f57cbe..ea72776a 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 crate::usage::{Sniffer, Usage}; +use tw_wire::bodies::{BodyKind, BodyRecord, BodySender, ResponseTap}; +use tw_wire::usage::{Sniffer, Usage}; use tw_types::{Msg, msg}; /// 一个还欠着结局的请求。 @@ -136,7 +136,7 @@ impl Ending { self.told = true; let (recorded, original_len) = std::mem::take(&mut self.tap).finish(); if !recorded.is_empty() { - crate::bodies::offer( + tw_wire::bodies::offer( &self.sink, BodyRecord { id: self.id, diff --git a/crates/tw-gateway/src/fixture.rs b/crates/tw-gateway/src/fixture.rs index 50718031..01320a8f 100644 --- a/crates/tw-gateway/src/fixture.rs +++ b/crates/tw-gateway/src/fixture.rs @@ -112,7 +112,7 @@ pub fn extract(request: &Recorded, response: &Recorded) -> Extracted { } // ---- 响应侧:同样复用线上那个嗅探器 - let mut sniffer = crate::usage::Sniffer::new(); + let mut sniffer = tw_wire::usage::Sniffer::new(); sniffer.feed(response.body.as_bytes()); out.usage = sniffer .finish() diff --git a/crates/tw-gateway/src/lib.rs b/crates/tw-gateway/src/lib.rs index c1ba63e6..cbfe8f89 100644 --- a/crates/tw-gateway/src/lib.rs +++ b/crates/tw-gateway/src/lib.rs @@ -7,7 +7,6 @@ pub mod access; pub mod auth; -pub mod bodies; pub mod chatgpt; pub mod client_api; pub mod clientprobe; @@ -33,11 +32,10 @@ pub mod server; pub mod session; pub mod toolwall; pub mod translate; -pub mod usage; pub mod ws; pub use access::{AllowList, Cidr}; -pub use bodies::{BodyKind, BodyRecord, BodySender}; +pub use tw_wire::{BodyKind, BodyRecord, BodySender, Sniffer, Usage}; pub use clientprobe::{ProbeKind, classify}; pub use error::GatewayError; pub use health::Health; @@ -52,7 +50,6 @@ 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 usage::{Sniffer, Usage}; /// 请求来自谁。**如实写 ThinkWatch** —— 我们从不把自己报成别的客户端。 pub const ORIGINATOR: &str = "thinkwatch"; diff --git a/crates/tw-gateway/src/server.rs b/crates/tw-gateway/src/server.rs index 9d5b517d..ca7513ec 100644 --- a/crates/tw-gateway/src/server.rs +++ b/crates/tw-gateway/src/server.rs @@ -234,7 +234,7 @@ pub struct AppState { /// **有界通道,满了就丢。**直接调用意味着文件 I/O 跑在转发那条路上 /// —— 一次慢磁盘写就变成一次慢请求,而观测永远不该有这个权力。 /// `None` 表示观测层没起来,那时什么都不做。 - body_sink: Arc>>, + body_sink: Arc>>, /// 每个上游最近一次报的订阅额度。 /// /// **在内存里,不落库。**它是「现在还剩多少」,不是历史 —— 存一份 @@ -828,7 +828,7 @@ impl AppState { /// 接上 body 的去处。**观测层起来之后才调** —— 在那之前 body 一律 /// 丢掉,而请求照常。 - pub fn set_body_sink(&self, tx: crate::bodies::BodySender) { + pub fn set_body_sink(&self, tx: tw_wire::bodies::BodySender) { if let Ok(mut g) = self.body_sink.lock() { *g = Some(tx); } @@ -875,7 +875,7 @@ impl AppState { } } - fn body_sink(&self) -> Option { + fn body_sink(&self) -> Option { self.body_sink.lock().ok().and_then(|g| g.clone()) } @@ -1690,12 +1690,12 @@ async fn pipeline( // 请求体交给观测层。**这时候它已经完整在内存里了**,所以这一步 // 除了一次 `Bytes` 的引用计数之外没有别的成本(说过入站是要 // 整个解析的,所以本来就在)。 - crate::bodies::offer( + tw_wire::bodies::offer( &sink, - crate::bodies::BodyRecord { + tw_wire::bodies::BodyRecord { id, at_ms, - kind: crate::bodies::BodyKind::Request, + kind: tw_wire::bodies::BodyKind::Request, body: body.clone(), original_len: body.len(), }, diff --git a/crates/tw-wire/Cargo.toml b/crates/tw-wire/Cargo.toml new file mode 100644 index 00000000..eec0819a --- /dev/null +++ b/crates/tw-wire/Cargo.toml @@ -0,0 +1,18 @@ +[package] +name = "tw-wire" +version.workspace = true +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" + +[dependencies] +bytes = { workspace = true } +serde_json = { workspace = true } +# 只要一个 mpsc 发送端。**不用 workspace 那份** —— 那份带着网络、信号、 +# 计时器,而这个 crate 要能被企业版直接依赖,背什么进去是它说了算 +tokio = { version = "1", default-features = false, features = ["sync"] } + +[dev-dependencies] +tokio = { version = "1", features = ["rt", "macros"] } diff --git a/crates/tw-gateway/src/bodies.rs b/crates/tw-wire/src/bodies.rs similarity index 100% rename from crates/tw-gateway/src/bodies.rs rename to crates/tw-wire/src/bodies.rs diff --git a/crates/tw-wire/src/lib.rs b/crates/tw-wire/src/lib.rs new file mode 100644 index 00000000..36e38e37 --- /dev/null +++ b/crates/tw-wire/src/lib.rs @@ -0,0 +1,17 @@ +//! 响应流过时顺带做的两件事。 +//! +//! 两者共享同一条纪律:**不缓冲**。响应是流着出去的,为了看一眼它而把 +//! 它整块攒下来,会把 SSE 变成一次性交付 —— 客户端看到的是「卡很久,然后 +//! 一下全出来」。所以这里的东西都是旁路的:字节照常流向客户端,同时喂 +//! 它们一份。 +//! +//! [`usage`] 嗅出上游报的用量,[`bodies`] 留档请求和响应的正文。 +//! +//! 这一层刻意零业务依赖 —— 它不认识配置从哪来、数据存哪里、谁在调用, +//! 所以企业版和桌面版都能直接用。 + +pub mod bodies; +pub mod usage; + +pub use bodies::{BodyKind, BodyRecord, BodySender, ResponseTap}; +pub use usage::{Sniffer, Usage}; diff --git a/crates/tw-gateway/src/usage.rs b/crates/tw-wire/src/usage.rs similarity index 100% rename from crates/tw-gateway/src/usage.rs rename to crates/tw-wire/src/usage.rs From d2cc90da6116d44dbbc17b4c787620ba08ee595b Mon Sep 17 00:00:00 2001 From: fylorn <249551762+fylorn@users.noreply.github.com> Date: Wed, 23 Sep 2026 15:19:55 +0800 Subject: [PATCH 2/2] style: sort the imports rustfmt's way Co-Authored-By: Claude Opus 5 --- crates/tw-gateway/src/ending.rs | 2 +- crates/tw-gateway/src/lib.rs | 2 +- 2 files changed, 2 insertions(+), 2 deletions(-) diff --git a/crates/tw-gateway/src/ending.rs b/crates/tw-gateway/src/ending.rs index ea72776a..b8d69658 100644 --- a/crates/tw-gateway/src/ending.rs +++ b/crates/tw-gateway/src/ending.rs @@ -22,9 +22,9 @@ use std::time::Instant; +use tw_types::{Msg, msg}; use tw_wire::bodies::{BodyKind, BodyRecord, BodySender, ResponseTap}; use tw_wire::usage::{Sniffer, Usage}; -use tw_types::{Msg, msg}; /// 一个还欠着结局的请求。 /// diff --git a/crates/tw-gateway/src/lib.rs b/crates/tw-gateway/src/lib.rs index cbfe8f89..f672e9d1 100644 --- a/crates/tw-gateway/src/lib.rs +++ b/crates/tw-gateway/src/lib.rs @@ -35,7 +35,6 @@ pub mod translate; pub mod ws; pub use access::{AllowList, Cidr}; -pub use tw_wire::{BodyKind, BodyRecord, BodySender, Sniffer, Usage}; pub use clientprobe::{ProbeKind, classify}; pub use error::GatewayError; pub use health::Health; @@ -50,6 +49,7 @@ 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}; /// 请求来自谁。**如实写 ThinkWatch** —— 我们从不把自己报成别的客户端。 pub const ORIGINATOR: &str = "thinkwatch";