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
15 changes: 12 additions & 3 deletions Cargo.lock

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

4 changes: 3 additions & 1 deletion Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -19,6 +19,7 @@ members = [
"crates/tw-pricing",
"crates/tw-adopt",
"crates/tw-scan",
"crates/tw-watch",
"crates/tw-engine",
"crates/tw-observe",
"crates/tw-gateway",
Expand Down Expand Up @@ -54,6 +55,7 @@ tw-store = { path = "crates/tw-store" }
tw-pricing = { path = "crates/tw-pricing" }
tw-adopt = { path = "crates/tw-adopt" }
tw-scan = { path = "crates/tw-scan" }
tw-watch = { path = "crates/tw-watch" }
tw-guard = { path = "crates/tw-guard" }
tw-breaker = { path = "crates/tw-breaker" }
tw-dialect = { path = "crates/tw-dialect" }
Expand All @@ -70,7 +72,7 @@ bytes = "1"
serde = { version = "1", features = ["derive"] }
serde_json = "1"
serde_yaml_ng = "0.10"
# 文件监听。盯配置文件那一份
# 文件监听,只有 tw-watch 直接用
notify = "8"
# 请求历史。bundled 是刻意的:零外部依赖,用户不必装 sqlite
rusqlite = { version = "0.40", features = ["bundled"] }
Expand Down
8 changes: 4 additions & 4 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -43,10 +43,10 @@ Point a client (Claude Code, Codex, and friends) at a local port, and:
## Crate layers

```
tw-dialect · tw-guard · tw-breaker ← shared with the server edition
tw-types · tw-engine · tw-pricing · tw-yaml · tw-secret ← domain logic
tw-config · tw-store · tw-scan · tw-adopt · tw-observe ← assembly
tw-gateway · tw-control ← data plane / control plane
tw-dialect · tw-guard · tw-breaker ← shared with the server edition
tw-types · tw-engine · tw-pricing · tw-yaml · tw-secret · tw-watch ← domain logic
tw-config · tw-store · tw-scan · tw-adopt · tw-observe ← assembly
tw-gateway · tw-control ← data plane / control plane
```

The server edition depends on the top layer and nothing else: format
Expand Down
8 changes: 4 additions & 4 deletions README.zh-CN.md
Original file line number Diff line number Diff line change
Expand Up @@ -38,10 +38,10 @@ cargo run -p twcore -- serve # 起网关和控制面
## crate 分层

```
tw-dialect · tw-guard · tw-breaker ← 与服务端版本共用
tw-types · tw-engine · tw-pricing · tw-yaml · tw-secret ← 领域逻辑
tw-config · tw-store · tw-scan · tw-adopt · tw-observe ← 装配
tw-gateway · tw-control ← 数据面 / 控制面
tw-dialect · tw-guard · tw-breaker ← 与服务端版本共用
tw-types · tw-engine · tw-pricing · tw-yaml · tw-secret · tw-watch ← 领域逻辑
tw-config · tw-store · tw-scan · tw-adopt · tw-observe ← 装配
tw-gateway · tw-control ← 数据面 / 控制面
```

服务端版本只依赖最上面一层:格式转换与用量解析(tw-dialect)、脱敏与工具调用
Expand Down
2 changes: 2 additions & 0 deletions crates/tw-api/src/ep.rs
Original file line number Diff line number Diff line change
Expand Up @@ -18,6 +18,8 @@ endpoints! {
Events: GET "/events", () => api::Event, events;
/// 此刻还没结束的请求,按开始事件的样子给
InFlight: GET "/in-flight", () => Vec<api::Event>;
/// 此刻的实时读数:在跑的请求、最近一分钟的生成速率
Live: GET "/live", () => api::LiveView;
Overview: GET "/overview", () => api::Overview;
/// 连通性分段测速
L1: POST "/l1", api::L1Request => Vec<api::L1Result>;
Expand Down
30 changes: 30 additions & 0 deletions crates/tw-api/src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -727,6 +727,36 @@ impl Event {
}
}

/// 此刻的实时读数(`GET /live`):在跑的请求,和最近跑完的请求生成得多快。
///
/// **按事件数出来的,core 里只数一份。**以前菜单栏自己听事件流、自己记在跑的和
/// 跑完的:半路才开始听的那一段要拿 `/in-flight` 对账,丢过事件要重对,而这些
/// core 的事件总线本来就在记。
#[derive(Debug, Clone, Default, PartialEq, Serialize, Deserialize)]
#[cfg_attr(feature = "ts", derive(ts_rs::TS))]
pub struct LiveView {
/// 开始了、还没有结局的请求,开始得早的在前。和 `/in-flight` 是同一批
pub running: Vec<RunningView>,
/// 最近一分钟跑完的请求平均每秒生成多少 token:**每个请求的输出除以它生成用的
/// 时间**(总耗时减去首字节),按 token 加权。这一分钟里没有跑完的是空,不是 0
pub tokens_per_sec: Option<u32>,
}

/// 一个在跑的请求。
#[derive(Debug, Clone, Default, PartialEq, Serialize, Deserialize)]
#[cfg_attr(feature = "ts", derive(ts_rs::TS))]
pub struct RunningView {
pub id: u64,
/// 网关密钥的名字
pub client: String,
/// 按请求头推测的应用。**可以伪造**,只用来显示
pub client_hint: Option<String>,
pub model: String,
/// 开始时的首选上游
pub provider: String,
pub at_ms: u64,
}

/// 界面要显示的配置概览。
///
/// **不是配置文件本身**:密钥一律只给来源描述,不给值(统一脱敏)。
Expand Down
2 changes: 1 addition & 1 deletion crates/tw-config/Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -25,7 +25,7 @@ serde_yaml_ng = { workspace = true }
thiserror = { workspace = true }
rand = { workspace = true }
blake3 = { workspace = true }
notify = { workspace = true }
tw-watch = { workspace = true }
# 网卡枚举:`bind` 认网卡名,要问系统它现在是哪个地址。
# getifaddrs 一共不到五十行,不值得引第三方 crate
libc = { workspace = true }
Expand Down
96 changes: 14 additions & 82 deletions crates/tw-config/src/watch.rs
Original file line number Diff line number Diff line change
@@ -1,103 +1,35 @@
//! 盯着配置文件。
//!
//! 两个非做不可的细节,少哪个都会表现成「有时候能自动重载,有时候不能」:
//!
//! **一、盯目录,不盯文件。**编辑器保存不是「往原文件写」,而是「写一个
//! 临时文件再 rename 过去」。rename 之后原来那个 inode 就没人指了 ——
//! 盯着文件的监听会在第一次保存之后**永久失效**,而且不报任何错。
//!
//! **二、去抖。**一次保存常常触发好几个事件(建临时文件、rename、改
//! 属性、改 mtime)。不聚合的话,一次保存会触发好几轮重载。
//! 盯目录不盯文件、去抖,这两件少哪个都会表现成「有时候能自动重载,有时候
//! 不能」—— 都在 [`tw_watch`] 里,和客户端配置面的监听是同一份。

use std::path::{Path, PathBuf};
use std::time::Duration;

pub use tw_watch::{Watch, WatchError};

/// 聚合窗口。**200ms 是照着编辑器保存的节奏定的** —— 那一串事件通常
/// 在几十毫秒内发完,而人对「改完文件到界面反应」这件事的耐心是秒级的
/// (M2 的验收标准写的是三秒)。
pub const DEBOUNCE: Duration = Duration::from_millis(200);

#[derive(Debug, thiserror::Error)]
pub enum WatchError {
#[error("changes to {path} could not be watched: {source}")]
Start {
path: PathBuf,
source: notify::Error,
},
}

/// 一个活着的监听。**扔掉它就停止监听** —— 所以调用方必须留着它。
pub struct Watch {
_inner: notify::RecommendedWatcher,
}

/// 盯住 `path`,每聚合出一次改动就往 channel 里发一个信号。
/// 盯住 `path`,每聚合出一次改动就往 channel 里发一个信号(见 [`tw_watch::watch`])。
///
/// 发的是「有事发生了」而不是「文件现在长这样」:**读文件是调用方的
/// 事**,因为只有它知道要不要读(比如上一次自己刚写过)。而在这里读
/// 会引入一个更糟的问题 —— 事件到达时写入可能还没完成。
/// 盯的是它所在的目录,只认这一个文件名:同目录下的其他文件(历史目录、我们
/// 自己的临时文件)不算。
pub fn watch(path: &Path) -> Result<(Watch, tokio::sync::mpsc::Receiver<()>), WatchError> {
use notify::{EventKind, RecursiveMode, Watcher as _};

let (tx, rx) = tokio::sync::mpsc::channel(8);
let target = path.to_path_buf();
let file_name = target.file_name().map(|s| s.to_os_string());
let file_name = path.file_name().map(|s| s.to_os_string());
// 目录不存在时盯不住 —— 但配置文件的目录在这一步之前已经建好了。
let dir = target
let dir = path
.parent()
.filter(|d| !d.as_os_str().is_empty())
.map(PathBuf::from)
.unwrap_or_else(|| PathBuf::from("."));

let (raw_tx, raw_rx) = std::sync::mpsc::channel::<()>();
let mut w = notify::recommended_watcher(move |ev: notify::Result<notify::Event>| {
let Ok(ev) = ev else { return };
// 只关心内容/存在性的变化。**访问时间之类的不算** —— 有些工具
// (备份、索引)会大量产生它们。
if !matches!(
ev.kind,
EventKind::Create(_) | EventKind::Modify(_) | EventKind::Remove(_)
) {
return;
}
// 同目录下的其他文件(历史目录、我们自己的临时文件)不算
let hit = ev.paths.iter().any(|p| match (&file_name, p.file_name()) {
(Some(want), Some(got)) => want == got,
_ => false,
});
if hit {
let _ = raw_tx.send(());
}
})
.map_err(|source| WatchError::Start {
path: dir.clone(),
source,
})?;
// 非递归:历史目录就在旁边,递归会把每一次快照都当成一次改动。
w.watch(&dir, RecursiveMode::NonRecursive)
.map_err(|source| WatchError::Start {
path: dir.clone(),
source,
})?;

// notify 的回调跑在它自己的线程上,这里把它接到 tokio 上并去抖。
std::thread::spawn(move || {
while raw_rx.recv().is_ok() {
// 收到一个之后,把窗口内后续的全部吞掉 —— 一次保存的那一串
// 事件因此只产生一个信号。
loop {
match raw_rx.recv_timeout(DEBOUNCE) {
Ok(()) => continue,
Err(std::sync::mpsc::RecvTimeoutError::Timeout) => break,
Err(std::sync::mpsc::RecvTimeoutError::Disconnected) => return,
}
}
// 满了就丢:信号是「去看一眼」,堆积两个和堆积一个是一回事。
let _ = tx.try_send(());
}
});

Ok((Watch { _inner: w }, rx))
tw_watch::watch(
&[dir],
DEBOUNCE,
move |p| matches!((&file_name, p.file_name()), (Some(want), Some(got)) if want == got),
)
}

#[cfg(test)]
Expand Down
7 changes: 7 additions & 0 deletions crates/tw-control/src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -122,6 +122,7 @@ pub fn router(state: ControlState) -> Router {
.merge(listen::router())
.at(ep::Events, events)
.at(ep::InFlight, in_flight)
.at(ep::Live, live)
.at(ep::Overview, overview)
.at(ep::L1, l1)
.at(ep::GetConfig, get_config)
Expand Down Expand Up @@ -253,6 +254,12 @@ async fn in_flight(State(s): State<ControlState>) -> Json<Vec<tw_api::Event>> {
Json(s.bus().in_flight())
}

/// 在跑的请求和最近的生成速率(见 `EventBus::live`)。菜单栏每次重收都问它,
/// 不必自己听事件去数。
async fn live(State(s): State<ControlState>) -> Json<tw_api::LiveView> {
Json(s.bus().live())
}

/// 事件流编码成 SSE。
fn async_stream_from(
rx: broadcast::Receiver<tw_api::Event>,
Expand Down
51 changes: 51 additions & 0 deletions crates/tw-control/tests/in_flight.rs
Original file line number Diff line number Diff line change
Expand Up @@ -93,3 +93,54 @@ async fn nothing_running_is_an_empty_list() {
let (_d, _bus, router) = app();
assert!(get(router).await.is_empty());
}

async fn live(router: axum::Router) -> serde_json::Value {
let resp = router
.oneshot(Request::get("/live").body(Body::empty()).unwrap())
.await
.unwrap();
assert_eq!(resp.status(), StatusCode::OK);
let body = axum::body::to_bytes(resp.into_body(), usize::MAX)
.await
.unwrap();
serde_json::from_slice(&body).unwrap()
}

/// `/live`:菜单栏要的在跑的请求和生成速率,由 core 数好。
#[tokio::test]
async fn live_gives_the_running_requests_and_the_generation_rate() {
let (_d, bus, router) = app();
let idle = live(router.clone()).await;
assert_eq!(idle["running"], serde_json::json!([]));
// 这一分钟里没有跑完的:是空,不是 0
assert!(idle["tokens_per_sec"].is_null(), "{idle}");

bus.emit(started(1, "claude-sonnet-5"));
bus.emit(tw_api::Event::RequestHeaders {
id: 1,
status: 200,
ttfb_ms: 1_000,
});
bus.emit(tw_api::Event::RequestFinished {
id: 1,
model: "claude-sonnet-5".into(),
status: 200,
bytes: 10,
duration_ms: 3_000,
usage: Some(tw_api::UsageView {
output: 100,
..Default::default()
}),
});
bus.emit(started(2, "gpt-5.5"));

let v = live(router).await;
assert_eq!(v["tokens_per_sec"], 50, "{v}");
assert_eq!(v["running"].as_array().unwrap().len(), 1);
let r = &v["running"][0];
assert_eq!(r["id"], 2);
assert_eq!(r["client"], "我");
assert_eq!(r["client_hint"], "claude-code");
assert_eq!(r["model"], "gpt-5.5");
assert_eq!(r["at_ms"], 1_002);
}
Loading
Loading