From 88a551907ee3b70d29718bb03dc9edb3f61bf718 Mon Sep 17 00:00:00 2001 From: fylorn <249551762+fylorn@users.noreply.github.com> Date: Fri, 18 Sep 2026 02:58:19 +0800 Subject: [PATCH] feat: report the state changes worth interrupting a user for The desktop app decides whether to raise a system notification, so what it needs from core is state transitions, each reported once and again when it recovers. Three signals were missing, and the reason they were missing is the same in every case: nothing in core was in a position to notice. - ProxyChanged: a request that cannot connect through a named proxy now checks that proxy once (the L1 handshake, not a poll), and a failure is reported against the proxy rather than against every upstream behind it. Re-checks are spaced 30s apart and a success through the proxy reports that it is back. - AuthChanged: a 401 or 403 from an upstream is not a failure for the circuit breaker (retrying elsewhere would be rejected too), so a stale key never trips it and never reaches the user. It is reported on the transition, and again when the upstream accepts the credential. - StorageChanged: the disk level already changed the recorder's behaviour and only wrote a log. A request with no body is otherwise indistinguishable from a bug. ConfigRejected now carries the origin, so the interface can tell a typo in the user's editor from a write it just made itself. Co-Authored-By: Claude Opus 5 --- crates/tw-api/src/lib.rs | 47 ++++++ crates/tw-control/src/config.rs | 1 + crates/tw-control/tests/sync.rs | 3 + crates/tw-gateway/src/server.rs | 190 ++++++++++++++++++++++ crates/tw-gateway/tests/notices.rs | 242 +++++++++++++++++++++++++++++ crates/tw-store/src/recorder.rs | 70 +++++++-- 6 files changed, 543 insertions(+), 10 deletions(-) create mode 100644 crates/tw-gateway/tests/notices.rs diff --git a/crates/tw-api/src/lib.rs b/crates/tw-api/src/lib.rs index 19c8ef57..d4cf4ae7 100644 --- a/crates/tw-api/src/lib.rs +++ b/crates/tw-api/src/lib.rs @@ -330,6 +330,45 @@ pub enum Event { state: String, at_ms: u64, }, + /// 某个代理通不通变了(只在变化那一刻发一次)。 + /// + /// **没有它,代理挂了看起来就是「好几家上游同时不通」** —— 而那两件事 + /// 要做的处理完全不同。转发失败时顺手检一次那个代理,不做定时探测。 + ProxyChanged { + id: u64, + proxy: String, + /// `unreachable` = 刚刚检查不通;`reachable` = 又通了 + state: String, + /// 不通时卡在哪一步,已脱敏。通了没有 + #[serde(default, skip_serializing_if = "Option::is_none")] + detail: Option, + at_ms: u64, + }, + /// 上游拒绝了我们的凭据(401/403),或者重新接受了。 + /// + /// **熔断器看不见这件事**:4xx 不算失败,所以一个凭据坏掉的上游永远不会 + /// 被熔断,也就永远不会有 `HealthChanged`。而它要用户去改配置。 + AuthChanged { + id: u64, + provider: String, + /// `rejected` = 上游拒绝了凭据;`accepted` = 又能用了 + state: String, + /// 被拒时上游给的状态码 + #[serde(default, skip_serializing_if = "Option::is_none")] + status: Option, + at_ms: u64, + }, + /// 磁盘空间的档位变了,记录随之减少或停止。 + /// + /// **用户点开一个请求发现没有正文时,得知道那不是 bug。** + StorageChanged { + id: u64, + /// `ok` = 全记;`metadata_only` = 不再存正文;`stopped` = 连记录也停了 + level: String, + /// 还剩多少可用空间 + free_bytes: u64, + at_ms: u64, + }, /// 上游在响应头里报了订阅额度。 /// /// **零成本**:不发额外请求,顺着真实流量白捡。按量付费的账号没有 @@ -380,6 +419,11 @@ pub enum Event { line: Option, /// 出错那一行的原文,**已脱敏** excerpt: Option, + /// 这一版是谁写的:`ui` / `cli` / `external` / `rollback` / `rotation`。 + /// + /// **界面靠它区分「用户在编辑器里写错了」和「界面自己刚写坏了」** —— + /// 前者要提醒,后者是保存失败,那条路自己会报。 + origin: String, at_ms: u64, }, /// 客户端的辅助请求被本地应答了,一个字节都没发给上游。 @@ -472,6 +516,9 @@ impl Event { | Event::RequestPriced { id, .. } | Event::ClientsChanged { id, .. } | Event::HealthChanged { id, .. } + | Event::ProxyChanged { id, .. } + | Event::AuthChanged { id, .. } + | Event::StorageChanged { id, .. } | Event::Redacted { id, .. } | Event::ToolCallFlagged { id, .. } | Event::ResponseInspected { id, .. } diff --git a/crates/tw-control/src/config.rs b/crates/tw-control/src/config.rs index 0ad26470..15e00eb1 100644 --- a/crates/tw-control/src/config.rs +++ b/crates/tw-control/src/config.rs @@ -101,6 +101,7 @@ impl ConfigManager { message: r.message.clone(), line: r.line, excerpt: r.excerpt.clone(), + origin: origin.slug().to_string(), at_ms: now_ms(), }); tracing::warn!("配置未通过校验,继续使用上一版本:{r}"); diff --git a/crates/tw-control/tests/sync.rs b/crates/tw-control/tests/sync.rs index 864cd552..48bf0fb8 100644 --- a/crates/tw-control/tests/sync.rs +++ b/crates/tw-control/tests/sync.rs @@ -101,11 +101,14 @@ async fn a_broken_file_keeps_the_old_config_serving_and_says_where() { stage, line, message, + origin, .. } => { assert_eq!(stage, "schema"); assert_eq!(line, Some(4), "得指到那一行"); assert!(message.contains("kye"), "{message}"); + // **谁写的也要说**:编辑器里写错了要提醒,界面自己写坏了那条路自己会报 + assert_eq!(origin, "external"); } other => panic!("{other:?}"), } diff --git a/crates/tw-gateway/src/server.rs b/crates/tw-gateway/src/server.rs index 0b447455..1bdde1c9 100644 --- a/crates/tw-gateway/src/server.rs +++ b/crates/tw-gateway/src/server.rs @@ -265,10 +265,34 @@ pub struct AppState { expired_told: Arc>>, /// 已经报过「用完」的额度窗口:(上游, 窗口)。**窗口恢复之后清掉**,再用完会重新报 exhausted: Arc>>, + /// 凭据正被上游拒绝的那几家。**进入和恢复各报一次** + rejected: Arc>>, + /// 每个代理最近一次检查的结果。见 [`AppState::check_proxy`] + proxies: Arc>>, /// 正在服务中的请求数。见 [`crate::live`]。 pub live: crate::live::Live, } +/// 这个出站设置是配置里定义的代理吗。`direct` 和 `system` 不是: +/// 前者没有代理,后者的地址在 reqwest 建连时才去环境里查,我们没有它可以握手 +fn named_proxy(proxy: &str) -> bool { + !proxy.is_empty() && proxy != tw_config::DIRECT && proxy != tw_config::SYSTEM +} + +/// 一个代理最近一次检查的结果。 +/// +/// **只在转发失败之后才检查**,而且同一个代理隔一会儿才检一次 —— 一条打不通的 +/// 链路上每个请求都去检一遍,等于把一次故障放大成一串握手。 +struct ProxyState { + reachable: bool, + checked_at: std::time::Instant, + /// 正在检查。并发的失败只触发一次 + checking: bool, +} + +/// 同一个代理两次检查之间至少隔多久 +const PROXY_RECHECK: std::time::Duration = std::time::Duration::from_secs(30); + impl AppState { pub fn new(config: tw_config::Config) -> Result { let http = base_client_builder() @@ -309,6 +333,8 @@ impl AppState { rotation_told: Arc::new(std::sync::Mutex::new(Default::default())), expired_told: Arc::new(std::sync::Mutex::new(Default::default())), exhausted: Arc::new(std::sync::Mutex::new(Default::default())), + rejected: Arc::new(std::sync::Mutex::new(Default::default())), + proxies: Arc::new(std::sync::Mutex::new(Default::default())), live: crate::live::Live::default(), }; // 手写的清单马上可用;向上游问是后台的事,不挡启动 @@ -433,6 +459,163 @@ impl AppState { Ok(token) } + /// 上游对凭据的态度变了没有。**进入被拒和恢复各报一次**。 + /// + /// 熔断器看不见这件事:4xx 不算失败(换一家也一样被拒),所以一个凭据坏掉的 + /// 上游永远不会被熔断,也就永远不会有 `HealthChanged`。而这件事要用户去改配置。 + pub(crate) fn note_auth(&self, provider: &str, status: u16) { + let rejected = status == 401 || status == 403; + // 别的失败(500、429、超时)什么都不说明:凭据可能好好的 + if !rejected && !(200..300).contains(&status) { + return; + } + let changed = self + .rejected + .lock() + .map(|mut g| { + if rejected { + g.insert(provider.to_string()) + } else { + g.remove(provider) + } + }) + .unwrap_or(false); + if !changed { + return; + } + if rejected { + tracing::warn!(provider, status, "上游拒绝了凭据"); + } + self.bus.emit(tw_api::Event::AuthChanged { + id: self.bus.next_id(), + provider: provider.to_string(), + state: if rejected { "rejected" } else { "accepted" }.into(), + status: rejected.then_some(status), + at_ms: now_ms(), + }); + } + + /// 经这个代理的请求成功了:它之前要是被判成不通,现在说一声通了。 + pub(crate) fn note_proxy_ok(&self, proxy: &str) { + if !named_proxy(proxy) { + return; + } + let recovered = self + .proxies + .lock() + .map(|mut g| match g.get_mut(proxy) { + Some(st) if !st.reachable => { + st.reachable = true; + st.checked_at = std::time::Instant::now(); + true + } + _ => false, + }) + .unwrap_or(false); + if recovered { + self.bus.emit(tw_api::Event::ProxyChanged { + id: self.bus.next_id(), + proxy: proxy.to_string(), + state: "reachable".into(), + detail: None, + at_ms: now_ms(), + }); + } + } + + /// 经这个代理的请求连不上了:检一次代理本身。 + /// + /// **不做定时探测**,只在转发失败之后顺手检一次 —— 没有它,代理挂掉在界面上 + /// 看起来是「好几家上游同时不通」,而那两件事要做的处理完全不同。 + pub(crate) fn check_proxy(&self, proxy: &str) { + if !named_proxy(proxy) { + return; + } + let due = self + .proxies + .lock() + .map(|mut g| { + let st = g.entry(proxy.to_string()).or_insert(ProxyState { + reachable: true, + // 第一次就该检:把时间放到足够早 + checked_at: std::time::Instant::now() - PROXY_RECHECK, + checking: false, + }); + let due = !st.checking && st.checked_at.elapsed() >= PROXY_RECHECK; + if due { + st.checking = true; + } + due + }) + .unwrap_or(false); + if !due { + return; + } + let state = self.clone(); + let name = proxy.to_string(); + tokio::spawn(async move { + let cfg = state.config(); + let result = match cfg.proxies.iter().find(|p| p.name == name) { + Some(px) => match crate::l1::hop_of(px) { + Ok(hop) => { + let (host, port) = crate::l1::proxy_target(&cfg, &name); + let r = crate::l1::l1_proxy(&hop, &host, port).await; + if r.ok { + None + } else { + // 卡在哪一步 + 为什么。**两个都要**:一句「TCP 握手失败」 + // 说不出是地址错了还是代理没起来 + let step = r.failed.map(|f| f.label()).unwrap_or_default(); + let why = r.error.unwrap_or_else(|| "无法连接".into()); + Some(if step.is_empty() { + why + } else { + format!("{step}:{why}") + }) + } + } + Err(e) => Some(e), + }, + // 配置刚好在这中间改了,代理没了:不报 + None => None, + }; + let changed = state + .proxies + .lock() + .map(|mut g| match g.get_mut(&name) { + Some(st) => { + st.checking = false; + st.checked_at = std::time::Instant::now(); + let reachable = result.is_none(); + let changed = st.reachable != reachable; + st.reachable = reachable; + changed + } + None => false, + }) + .unwrap_or(false); + if !changed { + return; + } + match &result { + Some(why) => tracing::warn!(proxy = %name, "代理不通:{why}"), + None => tracing::info!(proxy = %name, "代理又通了"), + } + state.bus.emit(tw_api::Event::ProxyChanged { + id: state.bus.next_id(), + proxy: name, + state: if result.is_some() { + "unreachable" + } else { + "reachable" + } + .into(), + detail: result, + at_ms: now_ms(), + }); + }); + } + /// 凭据失效报给界面。**同一家只报一次**,直到它恢复。 fn report_expired(&self, provider: &str, e: &crate::oauth::OauthError) { let first = self @@ -1723,6 +1906,8 @@ async fn pipeline( Ok(r) if r.status().is_server_error() || r.status() == 429 => { // 额度用完时上游回的正是 429,这一跳的额度头也要读 state.note_quota(id, &provider.name, r.headers()); + // 上游回了话,说明代理是通的 + state.note_proxy_ok(&provider.proxy); // 5xx 和限流:换一家有意义,那边可能有不同的额度或地域。 // **4xx 不换**(除了 429)—— 请求本身有问题的话,换一家 // 也一样被拒,还会白白污染那家的健康度。 @@ -1773,6 +1958,8 @@ async fn pipeline( &provider.name, state.health.record_failure(&provider.name), ); + // 连不上的可能是代理而不是上游 —— 检一次那个代理,说清是哪一件事 + state.check_proxy(&provider.proxy); let err = forward::map_reqwest_error(e); chain.push(hop_failed(&provider.name, err.message.clone(), hop_started)); last_err = Some(err); @@ -1840,6 +2027,9 @@ async fn pipeline( // 订阅额度。**零成本** —— 这些头本来就在响应里,读一下 // 就有了。按量付费的账号没有它们,那时什么都不发。 state.note_quota(id, &provider.name, upstream.headers()); + // 上游收不收我们的凭据、经过的代理通不通:**都是状态变化,各只报一次** + state.note_auth(&provider.name, status.as_u16()); + state.note_proxy_ok(&provider.proxy); let mut out_headers = forward::response_headers(upstream.headers()); // **哪一家服务的,写在头上。**错误契约要求上游的错误原样透传、不加 diff --git a/crates/tw-gateway/tests/notices.rs b/crates/tw-gateway/tests/notices.rs new file mode 100644 index 00000000..0c326743 --- /dev/null +++ b/crates/tw-gateway/tests/notices.rs @@ -0,0 +1,242 @@ +//! 要发通知的那几件事,在数据面这一侧。 +//! +//! 桌面版据此决定弹不弹系统通知,所以每一条的要求都一样:**只在状态变化那一刻发一次**, +//! 恢复也要说。这里验的是两件熔断器看不见的事 —— +//! +//! - 上游拒绝凭据(401/403):4xx 不算失败,那样的上游永远不会被熔断 +//! - 代理不通:不检查的话,界面上看到的是「好几家上游同时不通」 + +use std::net::SocketAddr; +use std::sync::Arc; +use std::sync::atomic::{AtomicBool, AtomicUsize, Ordering}; +use std::time::Duration; + +use serde_json::json; +use tokio::io::{AsyncReadExt, AsyncWriteExt}; +use tw_config::{Client, Config, Listen, Provider}; + +// ---------------------------------------------------------------- 假上游 + +/// 先回 `reject` 次 401,之后回 200 +async fn upstream(reject: usize) -> SocketAddr { + let left = Arc::new(AtomicUsize::new(reject)); + let app = axum::Router::new() + .route( + "/v1/messages", + axum::routing::post(|axum::extract::State(left): axum::extract::State>| async move { + if left.load(Ordering::SeqCst) > 0 { + left.fetch_sub(1, Ordering::SeqCst); + return ( + axum::http::StatusCode::UNAUTHORIZED, + axum::Json(json!({"type": "error", "error": {"type": "authentication_error", "message": "invalid x-api-key"}})), + ); + } + ( + axum::http::StatusCode::OK, + axum::Json(json!({ + "id": "msg_1", + "type": "message", + "role": "assistant", + "model": "claude-sonnet-4-5", + "content": [{"type": "text", "text": "ok"}], + "stop_reason": "end_turn", + "usage": {"input_tokens": 5, "output_tokens": 2} + })), + ) + }), + ) + .with_state(left); + let l = tokio::net::TcpListener::bind("127.0.0.1:0").await.unwrap(); + let addr = l.local_addr().unwrap(); + tokio::spawn(async move { axum::serve(l, app).await.unwrap() }); + addr +} + +// ---------------------------------------------------------------- 假代理 + +/// 一个能坏掉的 HTTP 代理:认 `CONNECT`,也认绝对形式的请求。 +/// +/// **两种都要认**:转发走的是绝对形式,而代理检查走的是 `CONNECT`。坏掉的时候 +/// 连上就断,这正是代理进程没了的样子。 +async fn proxy(broken: Arc) -> SocketAddr { + let l = tokio::net::TcpListener::bind("127.0.0.1:0").await.unwrap(); + let addr = l.local_addr().unwrap(); + tokio::spawn(async move { + loop { + let Ok((mut down, _)) = l.accept().await else { + return; + }; + if broken.load(Ordering::SeqCst) { + let _ = down.shutdown().await; + continue; + } + tokio::spawn(async move { + let mut head = Vec::new(); + let mut byte = [0u8; 1]; + while !head.ends_with(b"\r\n\r\n") { + match down.read(&mut byte).await { + Ok(1) => head.push(byte[0]), + _ => return, + } + } + let text = String::from_utf8_lossy(&head).to_string(); + let mut parts = text.split_whitespace(); + let (method, target) = (parts.next().unwrap_or(""), parts.next().unwrap_or("")); + let (host, rest) = if method == "CONNECT" { + (target.to_string(), None) + } else { + // `POST http://127.0.0.1:1234/v1/messages HTTP/1.1` + let after = target.strip_prefix("http://").unwrap_or(target); + let (h, path) = after.split_once('/').unwrap_or((after, "")); + (h.to_string(), Some(format!("/{path}"))) + }; + let Ok(mut up) = tokio::net::TcpStream::connect(&host).await else { + return; + }; + match rest { + None => { + let _ = down + .write_all(b"HTTP/1.1 200 Connection Established\r\n\r\n") + .await; + } + Some(path) => { + let head = text.replacen(target, &path, 1); + let _ = up.write_all(head.as_bytes()).await; + } + } + let _ = tokio::io::copy_bidirectional(&mut down, &mut up).await; + }); + } + }); + addr +} + +// ---------------------------------------------------------------- 网关 + +fn config(p: Provider) -> Config { + Config { + version: 1, + listen: Listen::default(), + clients: vec![Client { + name: "c".into(), + key: "tw-k".into(), + ..Default::default() + }], + providers: vec![p], + ..Default::default() + } +} + +async fn serve(cfg: Config) -> (SocketAddr, tokio::sync::broadcast::Receiver) { + let state = tw_gateway::AppState::new(cfg).unwrap(); + let rx = state.bus.subscribe(); + let addr = { + let l = tokio::net::TcpListener::bind("127.0.0.1:0").await.unwrap(); + l.local_addr().unwrap() + }; + tokio::spawn(async move { tw_gateway::serve(state, addr).await.unwrap() }); + tokio::time::sleep(Duration::from_millis(60)).await; + (addr, rx) +} + +async fn ask(gw: SocketAddr) -> u16 { + reqwest::Client::builder() + .no_proxy() + .build() + .unwrap() + .post(format!("http://{gw}/v1/messages")) + .header("content-type", "application/json") + .header("x-api-key", "tw-k") + .body(json!({"model": "claude-sonnet-4-5", "max_tokens": 16, "messages": [{"role": "user", "content": "hi"}]}).to_string()) + .send() + .await + .unwrap() + .status() + .as_u16() +} + +/// 等一条自己关心的事件。**别的事件要跳过**:一次请求会发好几条 +async fn next_change( + rx: &mut tokio::sync::broadcast::Receiver, + want: &str, +) -> (String, Option) { + let want = want.to_string(); + tokio::time::timeout(Duration::from_secs(10), async { + loop { + match rx.recv().await.unwrap() { + tw_api::Event::AuthChanged { + provider, state, .. + } if want == "auth" => return (state, Some(provider)), + tw_api::Event::ProxyChanged { + proxy, + state, + detail, + .. + } if want == "proxy" => { + assert_eq!(proxy, "代理一"); + return (state, detail); + } + _ => {} + } + } + }) + .await + .unwrap_or_else(|_| panic!("10 秒内没有等到 {want} 的状态变化")) +} + +// ---------------------------------------------------------------- 用例 + +#[tokio::test] +async fn an_upstream_that_rejects_the_credential_is_reported_once_and_again_when_it_recovers() { + let up = upstream(2).await; + let (gw, mut rx) = serve(config(Provider { + name: "relay".into(), + base_url: format!("http://{up}"), + key: Some(tw_config::Secret::new("sk-stale")), + ..Default::default() + })) + .await; + + assert_eq!(ask(gw).await, 401); + assert_eq!(next_change(&mut rx, "auth").await.0, "rejected"); + // 第二次还是 401:**同一件事不再说第二遍** + assert_eq!(ask(gw).await, 401); + // 凭据又被接受了 + assert_eq!(ask(gw).await, 200); + let (state, provider) = next_change(&mut rx, "auth").await; + assert_eq!( + (state.as_str(), provider.as_deref()), + ("accepted", Some("relay")) + ); +} + +#[tokio::test] +async fn a_dead_proxy_is_named_as_the_cause_and_reported_again_when_it_comes_back() { + let up = upstream(0).await; + let broken = Arc::new(AtomicBool::new(true)); + let px = proxy(broken.clone()).await; + let mut cfg = config(Provider { + name: "relay".into(), + base_url: format!("http://{up}"), + key: Some(tw_config::Secret::new("sk-good")), + proxy: "代理一".into(), + ..Default::default() + }); + cfg.proxies = vec![tw_config::Proxy { + name: "代理一".into(), + kind: tw_config::ProxyKind::Http, + addr: px.to_string(), + auth: None, + }]; + let (gw, mut rx) = serve(cfg).await; + + // 代理连上就断:请求失败,而失败的是代理不是上游 + assert_ne!(ask(gw).await, 200); + let (state, detail) = next_change(&mut rx, "proxy").await; + assert_eq!(state, "unreachable"); + assert!(detail.is_some_and(|d| !d.is_empty()), "要说清卡在哪一步"); + + broken.store(false, Ordering::SeqCst); + assert_eq!(ask(gw).await, 200); + assert_eq!(next_change(&mut rx, "proxy").await.0, "reachable"); +} diff --git a/crates/tw-store/src/recorder.rs b/crates/tw-store/src/recorder.rs index 515b8164..2444cd37 100644 --- a/crates/tw-store/src/recorder.rs +++ b/crates/tw-store/src/recorder.rs @@ -448,6 +448,9 @@ impl Recorder { // 不是「刚才发生过什么」。这张表只装后者。 | Event::ClientsChanged { .. } | Event::HealthChanged { .. } + | Event::ProxyChanged { .. } + | Event::AuthChanged { .. } + | Event::StorageChanged { .. } // 自己刚报出去的那条。**不能再处理一遍** —— 那是一个回路 | Event::RequestPriced { .. } => {} Event::ResponseInspected { @@ -604,16 +607,28 @@ impl Recorder { let Some(free) = disk::free_bytes(self.blobs.root()) else { return; }; - let next = disk::level_for(free); - if next != self.level { - // 级别变了要说出来 —— 用户点开一个请求发现没有 body, - // 得知道那不是 bug。 - tracing::warn!( - free_mb = free / 1024 / 1024, - "磁盘状态已变化:{}", - next.label() - ); - self.level = next; + self.set_level(disk::level_for(free), free, now); + } + + /// 换一档。**只在真的变了的时候说一次** —— 用户点开一个请求发现没有正文时, + /// 得知道那不是 bug,而这是唯一会发生这件事的地方。 + fn set_level(&mut self, next: DiskLevel, free: u64, now: i64) { + if next == self.level { + return; + } + tracing::warn!( + free_mb = free / 1024 / 1024, + "磁盘状态已变化:{}", + next.label() + ); + self.level = next; + if let Some(bus) = &self.bus { + bus.emit(Event::StorageChanged { + id: bus.next_id(), + level: next.slug().to_string(), + free_bytes: free, + at_ms: now as u64, + }); } } @@ -957,6 +972,41 @@ mod tests { ); } + #[test] + fn a_change_of_disk_level_is_announced_once() { + let (_d, mut r) = rec(); + let bus = tw_observe::EventBus::new(); + let mut rx = bus.subscribe(); + r = r.reporting_to(bus); + r.set_level( + DiskLevel::MetadataOnly, + 500 * 1024 * 1024, + 1_700_000_000_000, + ); + match rx.try_recv().unwrap() { + Event::StorageChanged { + level, free_bytes, .. + } => { + assert_eq!(level, "metadata_only"); + assert_eq!(free_bytes, 500 * 1024 * 1024); + } + other => panic!("{other:?}"), + } + // 还是这一档:不再说第二遍 + r.set_level( + DiskLevel::MetadataOnly, + 400 * 1024 * 1024, + 1_700_000_001_000, + ); + assert!(rx.try_recv().is_err()); + // 回到正常也要说 —— 界面上那条提示该撤掉了 + r.set_level(DiskLevel::Ok, 40 * 1024 * 1024 * 1024, 1_700_000_002_000); + assert!(matches!( + rx.try_recv().unwrap(), + Event::StorageChanged { level, .. } if level == "ok" + )); + } + #[test] fn nothing_is_written_when_the_disk_is_full() { // **但请求照样通** —— 这一层根本不参与转发。