diff --git a/crates/tw-api/src/lib.rs b/crates/tw-api/src/lib.rs index fd889ae1..fd0ee6a2 100644 --- a/crates/tw-api/src/lib.rs +++ b/crates/tw-api/src/lib.rs @@ -205,6 +205,28 @@ pub enum Event { alerts: Vec, at_ms: u64, }, + /// 客户端配置面上的文件动了 —— **不管改了什么**。 + /// + /// 和 `ScanAlert` 是两件事。那条说的是「出现了可疑内容」,值得打断 + /// 用户;这条只说「磁盘上那几个文件变了」,界面据此重读一遍接管 + /// 状态。用户在编辑器里把 `ANTHROPIC_BASE_URL` 改回原样,一点都不 + /// 可疑,但界面必须跟上 —— 没有这条,那一页只能每五秒重扫一次磁盘。 + ClientsChanged { id: u64, at_ms: u64 }, + /// 某家上游的熔断器开了或者合上了。 + /// + /// **这是少数几个不挂在任何一次请求上的状态变化。**熔断是攒够三次 + /// 连续失败之后的判断,而恢复更彻底 —— 「冷却到点了」纯粹是时间 + /// 走到,没有任何调用触发它。 + /// + /// 没有这条事件,界面想知道「哪家被熔断了」就只能轮询 `/overview`, + /// 而那是在一条本来完全空闲的连接上每两秒问一次同样的问题。 + HealthChanged { + id: u64, + provider: String, + /// `open` = 熔断中,不进候选链;`closed` = 可以用 + state: String, + at_ms: u64, + }, /// 上游在响应头里报了订阅额度。 /// /// **零成本**:不发额外请求,顺着真实流量白捡。按量付费的账号没有 @@ -316,6 +338,8 @@ impl Event { | Event::QuotaSeen { id, .. } | Event::LeakSeen { id, .. } | Event::ScanAlert { id, .. } + | Event::ClientsChanged { id, .. } + | Event::HealthChanged { id, .. } | Event::Redacted { id, .. } | Event::ToolCallFlagged { id, .. } | Event::ResponseInspected { id, .. } diff --git a/crates/tw-control/src/scan.rs b/crates/tw-control/src/scan.rs index 1e2359ff..d03c8aee 100644 --- a/crates/tw-control/src/scan.rs +++ b/crates/tw-control/src/scan.rs @@ -17,6 +17,13 @@ use serde::Deserialize; use crate::ControlState; +fn now_ms() -> u64 { + std::time::SystemTime::now() + .duration_since(std::time::UNIX_EPOCH) + .map(|d| d.as_millis() as u64) + .unwrap_or(0) +} + /// 把一条发现变成给界面看的样子。 pub fn finding_view(f: &tw_scan::report::Finding) -> tw_api::ScanFinding { tw_api::ScanFinding { @@ -152,6 +159,16 @@ pub fn spawn_watcher( seen.diff(&scan_now(&home).findings); while rx.recv().await.is_some() { + // **文件动了本身就是一条消息,和「可疑不可疑」无关。**接管 + // 状态读的就是这几个文件(`ANTHROPIC_BASE_URL` 指向哪儿), + // 用户在编辑器里把它改回去一点都不可疑,但界面必须跟上。 + // 没有这条,客户端那一页只能每五秒重扫一次磁盘。 + let id = bus.next_id(); + bus.emit(tw_api::Event::ClientsChanged { + id, + at_ms: now_ms(), + }); + // **每次重新枚举来源**:用户可能刚加了一个 skill, // 而那个文件在启动时还不存在 let fresh = seen.diff(&scan_now(&home).findings); @@ -163,10 +180,7 @@ pub fn spawn_watcher( bus.emit(tw_api::Event::ScanAlert { id, alerts: fresh.iter().map(finding_view).collect(), - at_ms: std::time::SystemTime::now() - .duration_since(std::time::UNIX_EPOCH) - .map(|d| d.as_millis() as u64) - .unwrap_or(0), + at_ms: now_ms(), }); } }); diff --git a/crates/tw-gateway/src/health.rs b/crates/tw-gateway/src/health.rs index a985e51f..66529179 100644 --- a/crates/tw-gateway/src/health.rs +++ b/crates/tw-gateway/src/health.rs @@ -35,6 +35,15 @@ struct Entry { opened_at: Option, } +/// 这一条现在算什么状态。**时间也是输入** —— 冷却到点就自动算合上, +/// 下一个请求自然成为探测。 +fn effective(e: &Entry) -> State { + match e.opened_at { + Some(t) if t.elapsed() < COOLDOWN => State::Open, + _ => State::Closed, + } +} + /// 每个 provider 的健康状态。 /// /// **不持久化**。桌面应用重启频繁,把「这家挂了」的判断带过重启 @@ -60,30 +69,48 @@ impl Health { pub fn state(&self, name: &str) -> State { let g = self.inner.lock().unwrap(); - let Some(e) = g.get(name) else { - return State::Closed; - }; - match e.opened_at { - Some(t) if t.elapsed() < COOLDOWN => State::Open, - // 冷却到点了就当成 Closed —— 下一个请求自然成为探测。 - _ => State::Closed, - } + g.get(name).map_or(State::Closed, effective) } - pub fn record_success(&self, name: &str) { + /// 记一次成功。**返回的是状态变化,没变就是 `None`。** + /// + /// 调用方要拿它去发事件:熔断开合是界面上看得见的状态,而看得见的 + /// 状态必须能被推出去 —— 否则界面只能轮询。 + pub fn record_success(&self, name: &str) -> Option { let mut g = self.inner.lock().unwrap(); let e = g.entry(name.to_string()).or_default(); + let before = effective(e); e.consecutive_failures = 0; e.opened_at = None; + (before != State::Closed).then_some(State::Closed) } - pub fn record_failure(&self, name: &str) { + /// 记一次失败,同样返回状态变化。 + /// + /// 冷却到点之后那次探测又失败时,这里会再报一次 `Open` —— **那不是 + /// 重复**:中间确实经过了一段「可以再试」的时间,而它又被关上了。 + pub fn record_failure(&self, name: &str) -> Option { let mut g = self.inner.lock().unwrap(); let e = g.entry(name.to_string()).or_default(); + let before = effective(e); e.consecutive_failures += 1; if e.consecutive_failures >= FAILURE_THRESHOLD { e.opened_at = Some(Instant::now()); } + let after = effective(e); + (before != after).then_some(after) + } + + /// 这家的冷却刚好走完了吗。 + /// + /// **专门给「报一条恢复」用的**,所以判据比 `state()` 严:要求那次 + /// 熔断**还在**(`opened_at` 没被成功清掉,也没有被一次新的失败 + /// 顶成更晚的时刻)。中途成功过的话 `record_success` 已经报过了, + /// 再报一条就是同一件事说两遍;重新熔断的话,那次自己带着定时器。 + pub fn just_cooled_down(&self, name: &str) -> bool { + let g = self.inner.lock().unwrap(); + g.get(name) + .is_some_and(|e| e.opened_at.is_some_and(|t| t.elapsed() >= COOLDOWN)) } /// 从候选里挑出还能用的,**并说明是不是 fail-open**。 @@ -122,6 +149,42 @@ mod tests { assert_eq!(h.state("a"), State::Closed); } + #[test] + fn only_the_failure_that_flips_it_reports_a_change() { + // 每次失败都报一条的话,这个事件就退化成了另一个请求流 —— + // 而订阅它的那一页要的是「什么时候变了」,不是「又失败了一次」。 + let h = Health::new(); + assert_eq!(h.record_failure("a"), None); + assert_eq!(h.record_failure("a"), None); + assert_eq!(h.record_failure("a"), Some(State::Open), "第三次才是变化"); + assert_eq!(h.record_failure("a"), None, "已经开着了,不是新的变化"); + } + + #[test] + fn a_success_reports_the_close_only_when_it_was_open() { + let h = Health::new(); + assert_eq!(h.record_success("a"), None, "本来就是好的"); + for _ in 0..3 { + h.record_failure("a"); + } + assert_eq!(h.record_success("a"), Some(State::Closed)); + assert_eq!(h.record_success("a"), None); + } + + /// 刚熔断的那一刻冷却还没走完 —— 这条守的是「别把恢复报两遍」: + /// 开的时候排下的那个定时器到点会拿它再确认一次。 + #[test] + fn a_fresh_open_has_not_cooled_down_yet() { + let h = Health::new(); + for _ in 0..3 { + h.record_failure("a"); + } + assert!(!h.just_cooled_down("a")); + // 成功之后那次熔断就不存在了,定时器到点也不该再报一条 + h.record_success("a"); + assert!(!h.just_cooled_down("a")); + } + #[test] fn it_takes_three_consecutive_failures_to_open() { let h = Health::new(); diff --git a/crates/tw-gateway/src/server.rs b/crates/tw-gateway/src/server.rs index baf40a67..7ec6a262 100644 --- a/crates/tw-gateway/src/server.rs +++ b/crates/tw-gateway/src/server.rs @@ -767,6 +767,45 @@ async fn passthrough( .map_err(|e| e.in_dialect(dialect)) } +/// 熔断状态变了就报一条,没变什么都不做。 +/// +/// **用自己的 id,不用这次请求的。**挂上请求的 id 会让存储层把它当成 +/// 那次请求的一部分 —— 而熔断说的是「这家上游现在什么情况」,和触发它 +/// 的那一次请求已经没关系了。 +/// +/// 开的时候顺手排一个定时器:**冷却到点本身就是一次状态变化**,而它 +/// 不由任何调用触发。不报的话,界面会一直显示「熔断中」,直到碰巧又有 +/// 一个请求打到这家为止。 +fn note_health( + bus: &tw_observe::EventBus, + health: &Arc, + provider: &str, + change: Option, +) { + let Some(next) = change else { return }; + let say = |bus: &tw_observe::EventBus, name: String, open: bool| { + let id = bus.next_id(); + bus.emit(tw_api::Event::HealthChanged { + id, + provider: name, + state: if open { "open" } else { "closed" }.into(), + at_ms: now_ms(), + }); + }; + let open = next == crate::health::State::Open; + say(bus, provider.to_string(), open); + if !open { + return; + } + let (bus, health, name) = (bus.clone(), health.clone(), provider.to_string()); + tokio::spawn(async move { + tokio::time::sleep(crate::health::COOLDOWN).await; + if health.just_cooled_down(&name) { + say(&bus, name, false); + } + }); +} + #[allow(clippy::too_many_arguments)] async fn pipeline( state: AppState, @@ -1116,7 +1155,12 @@ async fn pipeline( // 密钥取不到是这一家的问题(环境变量没设、token 端点 // 连不上),换下一家是合理的 —— 而且**必须**换:不换的话 // 一家 OAuth 上游的 token 端点抽风会让整个网关不可用。 - state.health.record_failure(&provider.name); + note_health( + &state.bus, + &state.health, + &provider.name, + state.health.record_failure(&provider.name), + ); chain.push(hop(&provider.name, format!("密钥取不到:{e}"), hop_started)); last_err = Some(GatewayError::config(format!( "provider `{}` 的密钥取不到:{e}", @@ -1170,7 +1214,12 @@ async fn pipeline( // 5xx 和限流:换一家有意义,那边可能有不同的额度或地域。 // **4xx 不换**(除了 429)—— 请求本身有问题的话,换一家 // 也一样被拒,还会白白污染那家的健康度。 - state.health.record_failure(&provider.name); + note_health( + &state.bus, + &state.health, + &provider.name, + state.health.record_failure(&provider.name), + ); chain.push(hop(&provider.name, format!("{}", r.status()), hop_started)); // **429 要保住 429。**塌成 502 的话,客户端会当成「服务器 // 坏了」而不是「该退避了」,而它们该做的事完全不同。 @@ -1182,7 +1231,12 @@ async fn pipeline( continue; } Ok(r) => { - state.health.record_success(&provider.name); + note_health( + &state.bus, + &state.health, + &provider.name, + state.health.record_success(&provider.name), + ); chain.push(hop(&provider.name, "成功".to_string(), hop_started)); upstream = Some(r); used = Some(provider); @@ -1191,7 +1245,12 @@ async fn pipeline( break; } Err(e) => { - state.health.record_failure(&provider.name); + note_health( + &state.bus, + &state.health, + &provider.name, + state.health.record_failure(&provider.name), + ); let err = forward::map_reqwest_error(e); chain.push(hop(&provider.name, err.message.clone(), hop_started)); last_err = Some(err); diff --git a/crates/tw-gateway/tests/hotreload.rs b/crates/tw-gateway/tests/hotreload.rs index 6cd9cf52..9b56cd03 100644 --- a/crates/tw-gateway/tests/hotreload.rs +++ b/crates/tw-gateway/tests/hotreload.rs @@ -154,6 +154,56 @@ async fn a_reload_that_cannot_build_leaves_the_old_config_serving() { assert!(ask(gw).await.contains("\"a\""), "旧配置没能继续服务"); } +#[tokio::test] +async fn opening_the_breaker_is_announced_on_the_bus() { + // **熔断是界面上看得见的状态,所以它必须能被推出去。**没有这条 + // 事件,界面想知道「哪家被熔断了」就只能定时去问 `/overview` —— + // 而那是在一条完全空闲的连接上反复问同一个问题。 + let dead = { + let app = Router::new().fallback(any(|| async { + axum::http::StatusCode::SERVICE_UNAVAILABLE + })); + let l = tokio::net::TcpListener::bind("127.0.0.1:0").await.unwrap(); + let a = l.local_addr().unwrap(); + tokio::spawn(async move { axum::serve(l, app).await.unwrap() }); + a + }; + let (good, _) = counting_upstream("good").await; + let c = cfg(vec![provider("dead", dead), provider("good", good)], vec![]); + let state = tw_gateway::AppState::new(c).unwrap(); + let mut rx = state.bus.subscribe(); + let gw = serve(state.clone()).await; + + for _ in 0..6 { + ask(gw).await; + } + assert!(!state.health.is_available("dead"), "dead 没被熔断"); + + let mut opened = Vec::new(); + while let Ok(ev) = rx.try_recv() { + if let tw_api::Event::HealthChanged { + provider, state, .. + } = ev + { + opened.push((provider, state)); + } + } + assert_eq!( + opened + .iter() + .filter(|(p, s)| p == "dead" && s == "open") + .count(), + 1, + "dead 熔断了却没报,或者报了不止一次:{opened:?}" + ); + // **成功的那家不报。**没变化的状态不该产生事件 —— 每次成功都报一条 + // 的话,这个事件就退化成了另一个请求流。 + assert!( + !opened.iter().any(|(p, _)| p == "good"), + "good 一直是好的,不该有状态变化:{opened:?}" + ); +} + #[tokio::test] async fn the_circuit_breaker_state_survives_a_reload() { // **一家刚被熔断的上游,不该因为你改了条规则就立刻又被试一遍**。 diff --git a/crates/tw-store/src/recorder.rs b/crates/tw-store/src/recorder.rs index 3fcbd012..374b4bd9 100644 --- a/crates/tw-store/src/recorder.rs +++ b/crates/tw-store/src/recorder.rs @@ -391,7 +391,11 @@ impl Recorder { | Event::ToolCallFlagged { .. } | Event::Translated { .. } // 凭据轮换说的是配置文件该改了,跟哪一次请求无关 - | Event::CredentialRotated { .. } => {} + | Event::CredentialRotated { .. } + // 客户端配置面变了、某家上游熔断了 —— 都是「现在什么情况」, + // 不是「刚才发生过什么」。这张表只装后者。 + | Event::ClientsChanged { .. } + | Event::HealthChanged { .. } => {} Event::ResponseInspected { id, tool_calls,