From 804f51def14ebc375a14399d923ec04f07088dc6 Mon Sep 17 00:00:00 2001 From: fylorn <249551762+fylorn@users.noreply.github.com> Date: Thu, 24 Sep 2026 15:45:05 +0800 Subject: [PATCH] refactor: one debounced watcher for config and scan; core counts the menubar's live numbers tw-watch: watch a set of directories without recursing, keep create/modify/ remove events whose path passes a filter, debounce a burst into one signal and drop signals while one is pending. tw-config's config-file watch and tw-scan's client-surface watch now differ only in which directories and which paths count; notify is a dependency of tw-watch alone. GET /live: the running requests (the same set as /in-flight, as small views sorted by start) and the generation rate over the last minute (output tokens over time after the first byte, weighted by tokens; null when nothing finished). The event bus already tracked what is in flight; it now also keeps first-byte times and recent finishes, so the desktop's menubar can stop counting requests itself. Co-Authored-By: Claude Opus 5.5 --- Cargo.lock | 15 +- Cargo.toml | 4 +- README.md | 8 +- README.zh-CN.md | 8 +- crates/tw-api/src/ep.rs | 2 + crates/tw-api/src/lib.rs | 30 ++++ crates/tw-config/Cargo.toml | 2 +- crates/tw-config/src/watch.rs | 96 ++--------- crates/tw-control/src/lib.rs | 7 + crates/tw-control/tests/in_flight.rs | 51 ++++++ crates/tw-observe/src/bus.rs | 241 +++++++++++++++++++++++++-- crates/tw-scan/Cargo.toml | 3 +- crates/tw-scan/src/watch.rs | 79 +-------- crates/tw-watch/Cargo.toml | 17 ++ crates/tw-watch/src/lib.rs | 191 +++++++++++++++++++++ 15 files changed, 574 insertions(+), 180 deletions(-) create mode 100644 crates/tw-watch/Cargo.toml create mode 100644 crates/tw-watch/src/lib.rs diff --git a/Cargo.lock b/Cargo.lock index 76ee024e..652ff4e0 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -2442,7 +2442,6 @@ version = "0.42.0" dependencies = [ "blake3", "libc", - "notify", "rand 0.10.2", "regex", "serde", @@ -2456,6 +2455,7 @@ dependencies = [ "tw-pricing", "tw-secret", "tw-types", + "tw-watch", "tw-yaml", "windows-sys 0.61.2", ] @@ -2604,19 +2604,18 @@ dependencies = [ name = "tw-scan" version = "0.42.0" dependencies = [ - "notify", "regex", "serde", "serde_json", "serde_yaml_ng", "tempfile", - "thiserror", "tokio", "tracing", "tw-adopt", "tw-config", "tw-guard", "tw-types", + "tw-watch", ] [[package]] @@ -2652,6 +2651,16 @@ dependencies = [ "ts-rs", ] +[[package]] +name = "tw-watch" +version = "0.42.0" +dependencies = [ + "notify", + "tempfile", + "thiserror", + "tokio", +] + [[package]] name = "tw-yaml" version = "0.42.0" diff --git a/Cargo.toml b/Cargo.toml index 9d5c6512..af95df70 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -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", @@ -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" } @@ -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"] } diff --git a/README.md b/README.md index 0e87930b..550e5d86 100644 --- a/README.md +++ b/README.md @@ -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 diff --git a/README.zh-CN.md b/README.zh-CN.md index d63675af..7b8ba5ef 100644 --- a/README.zh-CN.md +++ b/README.zh-CN.md @@ -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)、脱敏与工具调用 diff --git a/crates/tw-api/src/ep.rs b/crates/tw-api/src/ep.rs index a6f184dc..65eb7e45 100644 --- a/crates/tw-api/src/ep.rs +++ b/crates/tw-api/src/ep.rs @@ -18,6 +18,8 @@ endpoints! { Events: GET "/events", () => api::Event, events; /// 此刻还没结束的请求,按开始事件的样子给 InFlight: GET "/in-flight", () => Vec; + /// 此刻的实时读数:在跑的请求、最近一分钟的生成速率 + Live: GET "/live", () => api::LiveView; Overview: GET "/overview", () => api::Overview; /// 连通性分段测速 L1: POST "/l1", api::L1Request => Vec; diff --git a/crates/tw-api/src/lib.rs b/crates/tw-api/src/lib.rs index fbcb906b..6f18e23f 100644 --- a/crates/tw-api/src/lib.rs +++ b/crates/tw-api/src/lib.rs @@ -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, + /// 最近一分钟跑完的请求平均每秒生成多少 token:**每个请求的输出除以它生成用的 + /// 时间**(总耗时减去首字节),按 token 加权。这一分钟里没有跑完的是空,不是 0 + pub tokens_per_sec: Option, +} + +/// 一个在跑的请求。 +#[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, + pub model: String, + /// 开始时的首选上游 + pub provider: String, + pub at_ms: u64, +} + /// 界面要显示的配置概览。 /// /// **不是配置文件本身**:密钥一律只给来源描述,不给值(统一脱敏)。 diff --git a/crates/tw-config/Cargo.toml b/crates/tw-config/Cargo.toml index 27fdbd30..f037b21d 100644 --- a/crates/tw-config/Cargo.toml +++ b/crates/tw-config/Cargo.toml @@ -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 } diff --git a/crates/tw-config/src/watch.rs b/crates/tw-config/src/watch.rs index 96d88a73..ea10526a 100644 --- a/crates/tw-config/src/watch.rs +++ b/crates/tw-config/src/watch.rs @@ -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| { - 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)] diff --git a/crates/tw-control/src/lib.rs b/crates/tw-control/src/lib.rs index f8e5324f..77433b26 100644 --- a/crates/tw-control/src/lib.rs +++ b/crates/tw-control/src/lib.rs @@ -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) @@ -253,6 +254,12 @@ async fn in_flight(State(s): State) -> Json> { Json(s.bus().in_flight()) } +/// 在跑的请求和最近的生成速率(见 `EventBus::live`)。菜单栏每次重收都问它, +/// 不必自己听事件去数。 +async fn live(State(s): State) -> Json { + Json(s.bus().live()) +} + /// 事件流编码成 SSE。 fn async_stream_from( rx: broadcast::Receiver, diff --git a/crates/tw-control/tests/in_flight.rs b/crates/tw-control/tests/in_flight.rs index c88d1aa5..b275e920 100644 --- a/crates/tw-control/tests/in_flight.rs +++ b/crates/tw-control/tests/in_flight.rs @@ -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); +} diff --git a/crates/tw-observe/src/bus.rs b/crates/tw-observe/src/bus.rs index 79394039..d2e55c3c 100644 --- a/crates/tw-observe/src/bus.rs +++ b/crates/tw-observe/src/bus.rs @@ -8,20 +8,47 @@ //! 注意这条豁免**不适用于成本记账**:那类数据丢了账单永久对不 //! 上,必须走别的路径。这里只走「丢了只是图上少个点」的东西。 -use std::collections::BTreeMap; +use std::collections::{BTreeMap, HashMap, VecDeque}; use std::sync::atomic::{AtomicU64, Ordering}; use std::sync::{Arc, Mutex}; +use std::time::{Duration, Instant}; use tokio::sync::broadcast; const CAPACITY: usize = 1024; +/// 生成速率看最近这么久里跑完的请求 +pub const RATE_WINDOW: Duration = Duration::from_secs(60); + #[derive(Clone)] pub struct EventBus { tx: broadcast::Sender, next_id: Arc, - /// 开始了、还没有结局的请求:它们的开始事件,按 id。见 [`EventBus::in_flight`] - open: Arc>>, + /// 在跑的和最近跑完的。见 [`EventBus::in_flight`]、[`EventBus::live`] + tally: Arc>, +} + +/// 按事件数出来的现状。 +#[derive(Default)] +struct Tally { + /// 开始了、还没有结局的请求:它们的开始事件,按 id + open: BTreeMap, + /// 在跑的请求首字节用了多久,毫秒。生成用时要从总耗时里减掉它 + ttfb: HashMap, + /// 最近跑完的:(什么时候结束的,输出了多少 token,生成用了多少毫秒) + done: VecDeque<(Instant, u64, u64)>, +} + +impl Tally { + fn forget(&mut self, now: Instant) { + while self + .done + .front() + .is_some_and(|(at, _, _)| now.saturating_duration_since(*at) > RATE_WINDOW) + { + self.done.pop_front(); + } + } } impl Default for EventBus { @@ -36,7 +63,7 @@ impl EventBus { Self { tx, next_id: Arc::new(AtomicU64::new(1)), - open: Arc::default(), + tally: Arc::default(), } } @@ -82,16 +109,42 @@ impl EventBus { /// 正处在一次 unwind 里 —— 再 panic 一次,整个进程就没了。锁中毒了也照样 /// 拿里面的表:少记一笔的快照,好过一个没了的网关。 fn track(&self, ev: &tw_api::Event) { + self.track_at(ev, Instant::now()); + } + + fn track_at(&self, ev: &tw_api::Event, now: Instant) { use tw_api::Event as E; - let mut open = self.open.lock().unwrap_or_else(|p| p.into_inner()); + let mut t = self.tally.lock().unwrap_or_else(|p| p.into_inner()); match ev { E::RequestStarted { id, .. } => { - open.insert(*id, ev.clone()); + t.open.insert(*id, ev.clone()); + } + E::RequestHeaders { id, ttfb_ms, .. } => { + if t.open.contains_key(id) { + t.ttfb.insert(*id, *ttfb_ms); + } + } + E::RequestFinished { + id, + duration_ms, + usage, + .. + } => { + t.open.remove(id); + let ttfb = t.ttfb.remove(id); + // **只数跑完了的。**取消的、断掉的输出不全,拿来算速率只会偏低; + // 没有响应头的(WebSocket)不知道生成用了多久,不瞎算 + if let (Some(u), Some(ttfb)) = (usage, ttfb) { + let gen_ms = duration_ms.saturating_sub(ttfb); + if u.output > 0 && gen_ms > 0 { + t.done.push_back((now, u.output, gen_ms)); + } + } + t.forget(now); } - E::RequestFinished { id, .. } - | E::RequestFailed { id, .. } - | E::RequestCancelled { id, .. } => { - open.remove(id); + E::RequestFailed { id, .. } | E::RequestCancelled { id, .. } => { + t.open.remove(id); + t.ttfb.remove(id); } _ => {} } @@ -111,14 +164,66 @@ impl EventBus { /// /// 表不会只进不出:每个开始事件都欠着恰好一个结局,由 `Ending` 保证。 pub fn in_flight(&self) -> Vec { - self.open + self.tally .lock() .unwrap_or_else(|p| p.into_inner()) + .open .values() .cloned() .collect() } + /// 此刻的实时读数:在跑的请求(和 [`EventBus::in_flight`] 同一批),和最近 + /// 一分钟跑完的请求平均每秒生成多少 token。 + /// + /// **量的是生成的快慢**:每个请求的输出除以它生成用的时间(总耗时减去首字节), + /// 按 token 加权。拿「一分钟里输出了多少」去除以六十的话,一个跑了一分钟才 + /// 结束的长请求,要等它结束之后才把速率一次性摊进来,数字跟着请求的长短忽高 + /// 忽低。 + pub fn live(&self) -> tw_api::LiveView { + self.live_at(Instant::now()) + } + + fn live_at(&self, now: Instant) -> tw_api::LiveView { + let mut t = self.tally.lock().unwrap_or_else(|p| p.into_inner()); + t.forget(now); + let (tokens, ms) = t + .done + .iter() + .fold((0u64, 0u64), |(tok, ms), (_, out, gen_ms)| { + (tok + out, ms + gen_ms) + }); + let mut running: Vec = t + .open + .values() + .filter_map(|e| match e { + tw_api::Event::RequestStarted { + id, + client, + client_hint, + model, + provider, + at_ms, + .. + } => Some(tw_api::RunningView { + id: *id, + client: client.clone(), + client_hint: client_hint.clone(), + model: model.clone(), + provider: provider.clone(), + at_ms: *at_ms, + }), + _ => None, + }) + .collect(); + running.sort_by_key(|r| (r.at_ms, r.id)); + tw_api::LiveView { + running, + tokens_per_sec: (ms > 0) + .then(|| (tokens.saturating_mul(1000) / ms).min(u32::MAX as u64) as u32), + } + } + pub fn subscribe(&self) -> broadcast::Receiver { self.tx.subscribe() } @@ -216,6 +321,120 @@ mod tests { ); } + fn headers(id: u64, ttfb_ms: u64) -> tw_api::Event { + tw_api::Event::RequestHeaders { + id, + status: 200, + ttfb_ms, + } + } + + fn finished(id: u64, duration_ms: u64, output: u64) -> tw_api::Event { + tw_api::Event::RequestFinished { + id, + model: "m".into(), + status: 200, + bytes: 1, + duration_ms, + usage: Some(tw_api::UsageView { + input: 10, + output, + ..Default::default() + }), + } + } + + /// **量的是生成的快慢**:首字节之前那一段不算,几个请求按 token 加权。 + #[test] + fn the_rate_is_output_over_generation_time() { + let b = EventBus::new(); + let now = Instant::now(); + // 首字节 1 秒,之后 2 秒生成了 100 个 + b.track_at(&started(1), now); + b.track_at(&headers(1, 1_000), now); + b.track_at(&finished(1, 3_000, 100), now); + assert_eq!(b.live_at(now).tokens_per_sec, Some(50)); + // 又一个:1 秒生成了 50 个。合起来 150 个 / 3 秒 + b.track_at(&started(2), now); + b.track_at(&headers(2, 500), now); + b.track_at(&finished(2, 1_500, 50), now); + assert_eq!(b.live_at(now).tokens_per_sec, Some(50)); + } + + /// 一分钟之前跑完的不算;**没有就是没有**,不是 0 + #[test] + fn an_idle_minute_has_no_rate() { + let b = EventBus::new(); + let then = Instant::now(); + assert_eq!(b.live_at(then).tokens_per_sec, None); + b.track_at(&started(1), then); + b.track_at(&headers(1, 100), then); + b.track_at(&finished(1, 1_100, 40), then); + assert_eq!(b.live_at(then).tokens_per_sec, Some(40)); + let later = then + RATE_WINDOW + Duration::from_secs(1); + assert_eq!(b.live_at(later).tokens_per_sec, None); + } + + /// 没有响应头的(WebSocket)、失败和取消的,都不拿来算速率 + #[test] + fn only_finished_requests_with_their_headers_make_a_rate() { + let b = EventBus::new(); + let now = Instant::now(); + b.track_at(&started(1), now); + b.track_at(&finished(1, 2_000, 100), now); + b.track_at(&started(2), now); + b.track_at(&headers(2, 100), now); + b.track_at( + &tw_api::Event::RequestCancelled { + id: 2, + model: "m".into(), + status: Some(200), + bytes: 1, + duration_ms: 2_000, + usage: Some(tw_api::UsageView { + output: 100, + ..Default::default() + }), + }, + now, + ); + let live = b.live_at(now); + assert_eq!(live.tokens_per_sec, None); + assert!(live.running.is_empty()); + } + + /// 菜单的「进行中」要知道是谁、用什么模型、跑了多久;开始得早的在前 + #[test] + fn the_running_list_says_who_what_and_since_when() { + let b = EventBus::new(); + let mut ev = started(7); + if let tw_api::Event::RequestStarted { + client_hint, at_ms, .. + } = &mut ev + { + *client_hint = Some("codex".into()); + *at_ms = 900; + } + b.emit(started(3)); + b.emit(ev); + let live = b.live(); + assert_eq!( + live.running.iter().map(|r| r.id).collect::>(), + [7, 3] + ); + assert_eq!( + live.running[0], + tw_api::RunningView { + id: 7, + client: "c".into(), + client_hint: Some("codex".into()), + model: "m".into(), + provider: "p".into(), + at_ms: 900, + } + ); + } + #[test] fn ids_resume_after_the_number_the_store_already_has() { let b = EventBus::new(); diff --git a/crates/tw-scan/Cargo.toml b/crates/tw-scan/Cargo.toml index 091b875c..3f19874d 100644 --- a/crates/tw-scan/Cargo.toml +++ b/crates/tw-scan/Cargo.toml @@ -16,9 +16,8 @@ tw-adopt = { workspace = true } tw-config = { workspace = true } tw-types = { workspace = true } tw-guard = { workspace = true } -notify = { workspace = true } +tw-watch = { workspace = true } tokio = { workspace = true } -thiserror = { workspace = true } tracing = { workspace = true } [dev-dependencies] diff --git a/crates/tw-scan/src/watch.rs b/crates/tw-scan/src/watch.rs index 2015fabc..df546734 100644 --- a/crates/tw-scan/src/watch.rs +++ b/crates/tw-scan/src/watch.rs @@ -16,9 +16,7 @@ //! 监听的目录集合就是 [`crate::sources`] 划定的那一批,一个不多。无界的 //! FSEvents 监听既是性能问题,也和「空闲时接近零」的目标冲突。 //! -//! **盯目录不盯文件**(和 tw-config 的监听同一条理由):编辑器保存是 -//! 「写临时文件再 rename」,盯着文件的监听会在第一次保存之后永久失效, -//! 而且不报任何错。 +//! **盯目录不盯文件、不递归、去抖**,和配置文件的监听是同一份([`tw_watch`])。 use std::collections::HashSet; use std::path::{Path, PathBuf}; @@ -27,19 +25,7 @@ use std::time::Duration; /// 聚合窗口。一次保存会触发好几个事件(建临时文件、rename、改属性)。 pub const DEBOUNCE: Duration = Duration::from_millis(300); -#[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, -} +pub use tw_watch::{Watch, WatchError}; /// 要盯的目录集合。 /// @@ -78,64 +64,13 @@ fn interesting(p: &Path) -> bool { .is_some_and(|e| INTERESTING.iter().any(|x| x.eq_ignore_ascii_case(e))) } -/// 盯住这些目录,聚合出的每一次改动发一个信号。 +/// 盯住这些目录,聚合出的每一次改动发一个信号(见 [`tw_watch::watch`])。 /// -/// 发的是「有事发生了」而不是「文件现在长这样」:**读文件是调用方的 -/// 事** —— 事件到达时写入可能还没完成。 +/// **只有我们关心的那几种文件算数。这一条撑着「空闲接近零」** —— `$HOME` 在 +/// 监听集合里(`~/.claude.json` 的父目录就是它)。我们自己写的备份和旁文件也 +/// 不算:接管一次会触发一轮扫描,那一轮又什么都发现不了。 pub fn watch(dirs: &[PathBuf]) -> Result<(Watch, tokio::sync::mpsc::Receiver<()>), WatchError> { - use notify::{EventKind, RecursiveMode, Watcher as _}; - - let (tx, rx) = tokio::sync::mpsc::channel(4); - let (raw_tx, raw_rx) = std::sync::mpsc::channel::<()>(); - - let mut w = notify::recommended_watcher(move |ev: notify::Result| { - let Ok(ev) = ev else { return }; - // 只关心内容和存在性。**访问时间之类的不算** —— 备份和索引工具 - // 会大量产生它们,而那会让「空闲时接近零」变成一句空话。 - if !matches!( - ev.kind, - EventKind::Create(_) | EventKind::Modify(_) | EventKind::Remove(_) - ) { - return; - } - // 只有我们关心的那几种文件算数。**这一条撑着「空闲接近零」** —— - // `$HOME` 在监听集合里(`~/.claude.json` 的父目录就是它)。 - // - // 我们自己写的备份和旁文件也不算:接管一次会触发一轮扫描, - // 那一轮又什么都发现不了。 - if !ev.paths.iter().any(|p| interesting(p) && !is_ours(p)) { - return; - } - let _ = raw_tx.send(()); - }) - .map_err(|source| WatchError::Start { - path: PathBuf::new(), - source, - })?; - - for d in dirs { - w.watch(d, RecursiveMode::NonRecursive) - .map_err(|source| WatchError::Start { - path: d.clone(), - source, - })?; - } - - 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(dirs, DEBOUNCE, |p| interesting(p) && !is_ours(p)) } /// 这个路径是我们自己写的吗。 diff --git a/crates/tw-watch/Cargo.toml b/crates/tw-watch/Cargo.toml new file mode 100644 index 00000000..1f78ee48 --- /dev/null +++ b/crates/tw-watch/Cargo.toml @@ -0,0 +1,17 @@ +[package] +name = "tw-watch" +version.workspace = true +edition.workspace = true +rust-version.workspace = true +license.workspace = true +repository.workspace = true +description = "Debounced directory watching: one signal per burst of changes" + +[dependencies] +notify = { workspace = true } +tokio = { workspace = true } +thiserror = { workspace = true } + +[dev-dependencies] +tempfile = "3" +tokio = { workspace = true, features = ["macros", "rt-multi-thread", "time"] } diff --git a/crates/tw-watch/src/lib.rs b/crates/tw-watch/src/lib.rs new file mode 100644 index 00000000..6f474b7b --- /dev/null +++ b/crates/tw-watch/src/lib.rs @@ -0,0 +1,191 @@ +//! 盯几个目录,一阵改动聚合成一个信号。 +//! +//! 配置文件的热重载(tw-config)和客户端配置面的变更扫描(tw-scan)要的是同一件 +//! 事,**只写一遍**:两份各写各的,去抖、事件种类、通道满了怎么办迟早长得不一样, +//! 而那种不一致的表现是「这边改了会重载、那边改了没反应」。各自不同的只有两样: +//! 盯哪几个目录、哪些路径算数([`watch`] 的 `relevant`)。 +//! +//! 三个非做不可的细节: +//! +//! **一、盯目录,不盯文件。**编辑器保存不是「往原文件写」,而是「写一个临时文件 +//! 再 rename 过去」。rename 之后原来那个 inode 就没人指了 —— 盯着文件的监听会在 +//! 第一次保存之后**永久失效**,而且不报任何错。 +//! +//! **二、不递归。**配置旁边就是历史目录;`~/.claude/` 底下有每分钟都在变的东西。 +//! 递归盯它们等于给自己找一个永不停歇的事件源。 +//! +//! **三、去抖。**一次保存常常触发好几个事件(建临时文件、rename、改属性、改 +//! mtime)。不聚合的话,一次保存会触发好几轮重读。 + +use std::path::{Path, PathBuf}; +use std::time::Duration; + +#[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, +} + +/// 盯住 `dirs`(不递归),改动涉及的路径里有一个让 `relevant` 说是的,就算一次; +/// 一次之后 `debounce` 之内的都并进去,然后往通道里发**一个**信号。 +/// +/// 发的是「有事发生了」而不是「文件现在长这样」:**读文件是调用方的事** —— 只有 +/// 它知道要不要读(比如上一次是自己刚写的),而事件到达时写入可能还没完成。 +/// +/// 只看内容和存在性的变化(建、改、删)。**访问时间之类的不算** —— 备份和索引 +/// 工具会大量产生它们。 +/// +/// 通道里最多攒一个信号:满了就丢。信号的意思是「去看一眼」,攒两个和攒一个是 +/// 一回事。 +pub fn watch( + dirs: &[PathBuf], + debounce: Duration, + relevant: impl Fn(&Path) -> bool + Send + 'static, +) -> Result<(Watch, tokio::sync::mpsc::Receiver<()>), WatchError> { + use notify::{EventKind, RecursiveMode, Watcher as _}; + + let (tx, rx) = tokio::sync::mpsc::channel(1); + let (raw_tx, raw_rx) = std::sync::mpsc::channel::<()>(); + let mut w = notify::recommended_watcher(move |ev: notify::Result| { + let Ok(ev) = ev else { return }; + if !matches!( + ev.kind, + EventKind::Create(_) | EventKind::Modify(_) | EventKind::Remove(_) + ) { + return; + } + if ev.paths.iter().any(|p| relevant(p)) { + let _ = raw_tx.send(()); + } + }) + .map_err(|source| WatchError::Start { + path: dirs.first().cloned().unwrap_or_default(), + source, + })?; + for d in dirs { + w.watch(d, RecursiveMode::NonRecursive) + .map_err(|source| WatchError::Start { + path: d.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)) +} + +#[cfg(test)] +mod tests { + use super::*; + + const WINDOW: Duration = Duration::from_millis(200); + + /// 等一个信号,**区分三种结果**:收到了、窗口内没动静、通道关了(监听线程 + /// 没了之后永远不会再有信号 —— 不分开的话它和「收到了」分不清)。 + #[derive(Debug, PartialEq)] + enum Signal { + Got, + Quiet, + Closed, + } + + async fn recv(rx: &mut tokio::sync::mpsc::Receiver<()>, within: Duration) -> Signal { + match tokio::time::timeout(within, rx.recv()).await { + Ok(Some(())) => Signal::Got, + Ok(None) => Signal::Closed, + Err(_) => Signal::Quiet, + } + } + + fn only_md(p: &Path) -> bool { + p.extension().is_some_and(|e| e == "md") + } + + #[tokio::test] + async fn a_burst_of_writes_is_one_signal() { + let d = tempfile::tempdir().unwrap(); + let (_w, mut rx) = watch(&[d.path().to_path_buf()], WINDOW, only_md).unwrap(); + for i in 0..10 { + std::fs::write(d.path().join("a.md"), format!("{i}\n")).unwrap(); + std::thread::sleep(Duration::from_millis(10)); + } + assert_eq!(recv(&mut rx, Duration::from_secs(3)).await, Signal::Got); + assert_eq!( + recv(&mut rx, Duration::from_millis(600)).await, + Signal::Quiet, + "连写十次产生了不止一个信号" + ); + } + + #[tokio::test] + async fn what_the_filter_turns_down_stays_quiet() { + let d = tempfile::tempdir().unwrap(); + let (_w, mut rx) = watch(&[d.path().to_path_buf()], WINDOW, only_md).unwrap(); + std::fs::write(d.path().join("x.log"), "x\n").unwrap(); + assert_eq!( + recv(&mut rx, Duration::from_millis(800)).await, + Signal::Quiet + ); + std::fs::write(d.path().join("x.md"), "x\n").unwrap(); + assert_eq!(recv(&mut rx, Duration::from_secs(3)).await, Signal::Got); + } + + #[tokio::test] + async fn a_subdirectory_is_not_watched() { + let d = tempfile::tempdir().unwrap(); + std::fs::create_dir_all(d.path().join("history")).unwrap(); + let (_w, mut rx) = watch(&[d.path().to_path_buf()], WINDOW, only_md).unwrap(); + std::fs::write(d.path().join("history/1.md"), "x\n").unwrap(); + assert_eq!( + recv(&mut rx, Duration::from_millis(800)).await, + Signal::Quiet, + "递归了" + ); + } + + #[tokio::test] + async fn several_directories_are_watched_at_once() { + let d = tempfile::tempdir().unwrap(); + let (a, b) = (d.path().join("a"), d.path().join("b")); + std::fs::create_dir_all(&a).unwrap(); + std::fs::create_dir_all(&b).unwrap(); + let (_w, mut rx) = watch(&[a, b.clone()], WINDOW, only_md).unwrap(); + std::fs::write(b.join("x.md"), "x\n").unwrap(); + assert_eq!(recv(&mut rx, Duration::from_secs(3)).await, Signal::Got); + } + + #[test] + fn a_directory_that_does_not_exist_is_an_error_that_names_it() { + let d = tempfile::tempdir().unwrap(); + let missing = d.path().join("nope"); + let Err(WatchError::Start { path, .. }) = + watch(std::slice::from_ref(&missing), WINDOW, only_md) + else { + panic!("盯一个不存在的目录没报错"); + }; + assert_eq!(path, missing); + } +}