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

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

1 change: 1 addition & 0 deletions crates/tw-control/Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -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 }
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 @@ -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,
Expand All @@ -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")
Expand Down
4 changes: 1 addition & 3 deletions crates/tw-gateway/src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -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;
Expand All @@ -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";
Expand Down
8 changes: 4 additions & 4 deletions crates/tw-gateway/src/server.rs
Original file line number Diff line number Diff line change
Expand Up @@ -240,7 +240,7 @@ pub struct AppState {
/// **在内存里,不落库。**它是「现在还剩多少」,不是历史 —— 存一份
/// 五分钟前的百分比,价值几乎为零,而它会让「重启之后显示的是旧
/// 数字」变成一个要解释的问题。下一个请求回来就有新的了。
quotas: Arc<std::sync::Mutex<std::collections::HashMap<String, crate::quota::Quota>>>,
quotas: Arc<std::sync::Mutex<std::collections::HashMap<String, tw_wire::quota::Quota>>>,
/// 监听地址变了。**这是「温」那一级**(三级热重载) ——
/// 换端口不能只换配置:监听器是启动时建的,不重建的话新端口上什么
/// 都没有,而旧端口还在服务。那种「改了没反应」比报错难查得多。
Expand Down Expand Up @@ -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;
}
Expand Down Expand Up @@ -880,7 +880,7 @@ impl AppState {
}

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

Expand Down
5 changes: 5 additions & 0 deletions crates/tw-wire/Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -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"] }
Expand Down
5 changes: 4 additions & 1 deletion crates/tw-wire/src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -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};
21 changes: 2 additions & 19 deletions crates/tw-gateway/src/quota.rs → crates/tw-wire/src/quota.rs
Original file line number Diff line number Diff line change
Expand Up @@ -16,7 +16,7 @@
//! 直接显示,我们推断的要标成推断。理由和三态成本完全一样:
//! **一个编出来的精确数字,比一个诚实的「不知道」更有害。**

use axum::http::HeaderMap;
use http::HeaderMap;
use serde::{Deserialize, Serialize};

/// 一个额度窗口的状态。**每个字段都直接来自响应头,没有一个是推算的。**
Expand Down Expand Up @@ -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::*;
Expand All @@ -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(),
);
}
Expand Down
Loading