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
6 changes: 1 addition & 5 deletions Cargo.lock

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

10 changes: 5 additions & 5 deletions bin/twcore/src/main.rs
Original file line number Diff line number Diff line change
Expand Up @@ -748,7 +748,7 @@ fn cmd_serve(path: &Path, port: Option<u16>, safe: bool, parent: Option<u32>) ->
//
// 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);
Expand Down Expand Up @@ -919,7 +919,7 @@ fn build_store(
bus: tw_observe::EventBus,
// **和网关同一份价格簿**,不是一份副本:改了价目表,下一个结束的请求就按新价算
pricing: tw_pricing::Shared,
bodies: tokio::sync::mpsc::Receiver<tw_gateway::BodyRecord>,
bodies: tokio::sync::mpsc::Receiver<tw_gateway::bodies::BodyRecord>,
) -> Option<std::sync::Arc<tokio::sync::Mutex<tw_store::Recorder>>> {
let events = bus.subscribe();
let (db, blobs) = match tw_store::open(dir) {
Expand Down Expand Up @@ -951,16 +951,16 @@ 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 {
let mapped = tw_store::StoredBody {
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,
Expand Down
6 changes: 3 additions & 3 deletions crates/tw-control/src/chatgpt.rs
Original file line number Diff line number Diff line change
Expand Up @@ -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,
Expand All @@ -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")
Expand Down
1 change: 1 addition & 0 deletions crates/tw-gateway/Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -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 }
Expand Down
File renamed without changes.
4 changes: 2 additions & 2 deletions crates/tw-gateway/src/ending.rs
Original file line number Diff line number Diff line change
Expand Up @@ -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};

/// 一个还欠着结局的请求。
Expand Down Expand Up @@ -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,
Expand Down
3 changes: 2 additions & 1 deletion crates/tw-gateway/src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -7,6 +7,7 @@

pub mod access;
pub mod auth;
pub mod bodies;
pub mod chatgpt;
pub mod client_api;
pub mod clientprobe;
Expand All @@ -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;
Expand All @@ -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";
Expand Down
File renamed without changes.
24 changes: 10 additions & 14 deletions crates/tw-gateway/src/server.rs
Original file line number Diff line number Diff line change
Expand Up @@ -234,13 +234,13 @@ pub struct AppState {
/// **有界通道,满了就丢。**直接调用意味着文件 I/O 跑在转发那条路上
/// —— 一次慢磁盘写就变成一次慢请求,而观测永远不该有这个权力。
/// `None` 表示观测层没起来,那时什么都不做。
body_sink: Arc<std::sync::Mutex<Option<tw_wire::bodies::BodySender>>>,
body_sink: Arc<std::sync::Mutex<Option<crate::bodies::BodySender>>>,
/// 每个上游最近一次报的订阅额度。
///
/// **在内存里,不落库。**它是「现在还剩多少」,不是历史 —— 存一份
/// 五分钟前的百分比,价值几乎为零,而它会让「重启之后显示的是旧
/// 数字」变成一个要解释的问题。下一个请求回来就有新的了。
quotas: Arc<std::sync::Mutex<std::collections::HashMap<String, tw_wire::quota::Quota>>>,
quotas: Arc<std::sync::Mutex<std::collections::HashMap<String, crate::quota::Quota>>>,
/// 监听地址变了。**这是「温」那一级**(三级热重载) ——
/// 换端口不能只换配置:监听器是启动时建的,不重建的话新端口上什么
/// 都没有,而旧端口还在服务。那种「改了没反应」比报错难查得多。
Expand Down Expand Up @@ -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;
}
Expand Down Expand Up @@ -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);
}
Expand Down Expand Up @@ -875,12 +871,12 @@ impl AppState {
}
}

fn body_sink(&self) -> Option<tw_wire::bodies::BodySender> {
fn body_sink(&self) -> Option<crate::bodies::BodySender> {
self.body_sink.lock().ok().and_then(|g| g.clone())
}

/// 每个上游最近一次报的订阅额度。
pub fn quotas(&self) -> std::collections::HashMap<String, tw_wire::quota::Quota> {
pub fn quotas(&self) -> std::collections::HashMap<String, crate::quota::Quota> {
self.quotas.lock().map(|g| g.clone()).unwrap_or_default()
}

Expand Down Expand Up @@ -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(),
},
Expand Down
14 changes: 1 addition & 13 deletions crates/tw-wire/Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -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"] }
22 changes: 9 additions & 13 deletions crates/tw-wire/src/lib.rs
Original file line number Diff line number Diff line change
@@ -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};
Loading