From 032f81b75d9866322a4513a14f7158fdb1e60481 Mon Sep 17 00:00:00 2001 From: fylorn <249551762+fylorn@users.noreply.github.com> Date: Thu, 24 Sep 2026 09:47:26 +0800 Subject: [PATCH] feat!: tw-breaker, one circuit-breaker state machine for both gateways; hidden-text scan in tw-guard MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit The desktop's upstream health, the server edition's route health and its MCP breaker each carried their own state machine. Their premises differ — one user in one process that fails open, versus replicas sharing Redis that filter a tripped route out — but the machine is the same: closed, open, half-open once the cooldown is over, and a probe deciding. tw-breaker is that machine and nothing else: - `Breaker` is plain, serialisable data; transitions are pure functions of it, a `Policy` and a time the caller supplies. Where it lives — a mutex, a Redis key — is the caller's business. `Breakers` is the in-process keyed set. - A `Trip` is either N consecutive failures or an error rate over a window; the window is counted by whoever stores the samples. - A cooled breaker reads as half-open with nobody nudging it. The server edition moved a route from open to half-open only when a request on that route completed, and an open route is never picked — it stayed open until its Redis key expired. - Half-open admits; `probes` successes close it, one failure reopens it. A late result while open still counts. The desktop's `health` runs on it with the same policy (3 failures, 60 s, one probe) and keeps its own rules on top: fail open when every candidate is down, bypass a single candidate. A half-open provider still reads "ok" on the upstreams page. `hidden` (invisible and look-alike characters) moves from tw-scan into tw-guard, for the server edition to scan requests with. `Kind::smuggles` names the two kinds with no legitimate use in any text — tag characters and bidi overrides; zero-width joiners make emoji and Cyrillic is Russian. The config scan grades by it too. BREAKING: tw_gateway::health::State is tw_breaker::State (adds HalfOpen); tw_scan::hidden is tw_guard::hidden. Co-Authored-By: Claude Opus 5.5 --- Cargo.lock | 9 + Cargo.toml | 2 + crates/tw-breaker/Cargo.toml | 14 + crates/tw-breaker/src/lib.rs | 448 +++++++++++++++++++++ crates/tw-control/src/lib.rs | 3 +- crates/tw-gateway/Cargo.toml | 1 + crates/tw-gateway/src/health.rs | 121 +++--- crates/{tw-scan => tw-guard}/src/hidden.rs | 20 + crates/tw-guard/src/lib.rs | 3 +- crates/tw-scan/src/lib.rs | 1 - crates/tw-scan/src/report.rs | 11 +- crates/tw-scan/tests/scan.rs | 2 +- 12 files changed, 565 insertions(+), 70 deletions(-) create mode 100644 crates/tw-breaker/Cargo.toml create mode 100644 crates/tw-breaker/src/lib.rs rename crates/{tw-scan => tw-guard}/src/hidden.rs (92%) diff --git a/Cargo.lock b/Cargo.lock index 28d75ebd..79fdeb9e 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -2774,6 +2774,14 @@ dependencies = [ "tw-types", ] +[[package]] +name = "tw-breaker" +version = "0.39.0" +dependencies = [ + "serde", + "serde_json", +] + [[package]] name = "tw-config" version = "0.39.0" @@ -2903,6 +2911,7 @@ dependencies = [ "tower", "tracing", "tw-api", + "tw-breaker", "tw-config", "tw-dialect", "tw-engine", diff --git a/Cargo.toml b/Cargo.toml index cf95ab66..9c6d074b 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -16,6 +16,7 @@ members = [ "crates/tw-adopt", "crates/tw-scan", "crates/tw-guard", + "crates/tw-breaker", "crates/tw-dialect", "crates/tw-engine", "crates/tw-observe", @@ -56,6 +57,7 @@ tw-pricing = { path = "crates/tw-pricing" } tw-adopt = { path = "crates/tw-adopt" } tw-scan = { path = "crates/tw-scan" } tw-guard = { path = "crates/tw-guard" } +tw-breaker = { path = "crates/tw-breaker" } tw-dialect = { path = "crates/tw-dialect" } # ── 版本与企业版 workspace 对齐,便于反向依赖时不打架 ──── diff --git a/crates/tw-breaker/Cargo.toml b/crates/tw-breaker/Cargo.toml new file mode 100644 index 00000000..0e3c8b47 --- /dev/null +++ b/crates/tw-breaker/Cargo.toml @@ -0,0 +1,14 @@ +[package] +name = "tw-breaker" +version.workspace = true +edition.workspace = true +rust-version.workspace = true +license.workspace = true +repository.workspace = true +description = "The circuit-breaker state machine both gateways run: pure data and pure transitions, stored wherever the caller keeps it" + +[dependencies] +serde = { workspace = true } + +[dev-dependencies] +serde_json = { workspace = true } diff --git a/crates/tw-breaker/src/lib.rs b/crates/tw-breaker/src/lib.rs new file mode 100644 index 00000000..b3be8dac --- /dev/null +++ b/crates/tw-breaker/src/lib.rs @@ -0,0 +1,448 @@ +//! 熔断的状态机。 +//! +//! 三处在用:桌面版的上游健康、企业版的路由健康、企业版的 MCP 服务器。 +//! 三处的**前提**不一样 —— 桌面版一个用户、进程内、全部熔断时照样放行; +//! 企业版多副本共享 Redis、按错误率判断、熔断了就把路由过滤掉 —— 但状态机 +//! 本身是同一个:闭合、打开、冷却到点之后半开、半开时的结果决定开合。 +//! +//! 所以这里只放状态机,不放前提: +//! +//! - **状态是纯数据**([`Breaker`],可以序列化),**转换是纯函数**,时间由 +//! 调用方给。放在一把锁后面([`Breakers`])还是放进 Redis,由调用方定。 +//! - **触发条件二选一**([`Trip`]):连续失败 N 次,或者窗口里的错误率。 +//! 窗口怎么统计是存储那边的事,这里只要统计结果([`Tally`])。 +//! - 「全部熔断了怎么办」「只有一个候选时要不要熔断」是调用方的策略,不在 +//! 这里。 +//! +//! # 三条规则,对所有调用方一样 +//! +//! 1. **冷却到点就是半开**,不需要谁来「推」它一下。以前企业版要等一个请求 +//! 落在这条路由上才会从打开变半开,而打开的路由根本选不到 —— 它就一直 +//! 开着,直到存储里那个键过期。 +//! 2. **半开时放行,结果决定开合**:成功够 `probes` 次就闭合,失败一次就 +//! 重新打开。 +//! 3. **打开期间收到的结果也算数**:熔断之前就发出去的请求晚到了。成功按 +//! 一次探测记,失败则把冷却重新计起 —— 它说明上游还是坏的。 + +use std::collections::HashMap; +use std::hash::Hash; +use std::sync::{Arc, Mutex}; +use std::time::Duration; + +use serde::{Deserialize, Serialize}; + +#[derive(Debug, Clone, Copy, Default, PartialEq, Eq, Hash, Serialize, Deserialize)] +#[serde(rename_all = "snake_case")] +pub enum State { + #[default] + Closed, + /// 熔断中,不放行 + Open, + /// 冷却到点了,放行,下一个结果决定开合 + HalfOpen, +} + +/// 什么时候打开。 +#[derive(Debug, Clone, Copy, PartialEq, Eq)] +pub enum Trip { + /// 连续失败这么多次 + Consecutive(u32), + /// 窗口里至少有 `min_samples` 个结果,且错误占比达到 `percent` + ErrorRate { percent: u32, min_samples: u32 }, +} + +/// 一个熔断器的规矩。 +#[derive(Debug, Clone, Copy, PartialEq, Eq)] +pub struct Policy { + pub trip: Trip, + /// 打开之后多久变半开 + pub cooldown: Duration, + /// 半开时要成功多少次才闭合。至少 1 + pub probes: u32, +} + +/// 窗口里的统计,**包含这一次结果在内**。按错误率触发时要它;按连续失败 +/// 触发时给默认值就行。 +#[derive(Debug, Clone, Copy, Default, PartialEq, Eq)] +pub struct Tally { + pub total: u32, + pub errors: u32, +} + +/// 一个熔断器知道的全部东西。 +/// +/// **是纯数据**:放在锁后面,或者整个写进 Redis,都行。存储里读不出来的 +/// (键过期了、格式不认识)就当 `Default` —— 闭合、什么都不记得,那是最 +/// 保守的起点。 +#[derive(Debug, Clone, Copy, Default, PartialEq, Eq, Serialize, Deserialize)] +pub struct Breaker { + #[serde(default)] + pub state: State, + /// 最近一次打开的时刻,Unix 毫秒。只在打开 / 半开时有意义 + #[serde(default)] + pub opened_at_ms: i64, + /// 连续失败了几次 + #[serde(default)] + pub failures: u32, + /// 半开以来成功了几次 + #[serde(default)] + pub probe_successes: u32, +} + +impl Breaker { + /// 此刻是什么状态。**冷却到点的打开就是半开**,不改任何东西 —— 选路时 + /// 用它,不必为了看一眼状态去写存储。 + pub fn state_at(&self, p: &Policy, now_ms: i64) -> State { + match self.state { + State::Open if self.cooled(p, now_ms) => State::HalfOpen, + s => s, + } + } + + /// 现在放不放行。 + pub fn admits(&self, p: &Policy, now_ms: i64) -> bool { + self.state_at(p, now_ms) != State::Open + } + + /// 放一个请求过去,**并把「冷却到点」落成半开**。状态变了就返回新状态。 + /// + /// 要把半开这一步报出去的调用方用它(企业版的 MCP 熔断把它推给仪表盘); + /// 只想知道能不能放的用 [`Self::admits`]。 + pub fn admit(&mut self, p: &Policy, now_ms: i64) -> (bool, Option) { + if self.state == State::Open && self.cooled(p, now_ms) { + self.state = State::HalfOpen; + self.probe_successes = 0; + return (true, Some(State::HalfOpen)); + } + (self.state != State::Open, None) + } + + /// 还要等多久才半开。 + /// + /// `None`:不在打开状态。`Some(0)`:冷却走完了,下一个请求就是探测。 + /// 要按时报「恢复」的定时器靠它分清「到点了」和「中途又失败、冷却被 + /// 顶到更晚了」。 + pub fn cooldown_left(&self, p: &Policy, now_ms: i64) -> Option { + if self.state != State::Open { + return None; + } + let elapsed = u64::try_from(now_ms.saturating_sub(self.opened_at_ms)).unwrap_or(0); + Some(p.cooldown.saturating_sub(Duration::from_millis(elapsed))) + } + + /// 记一次结果。**返回的是状态变化,没变就是 `None`** —— 调用方拿它去发 + /// 事件,而一个每次失败都报一条的事件就退化成了另一个请求流。 + /// + /// 比较的是此刻的状态([`Self::state_at`]):冷却到点之后那次探测又失败, + /// 会再报一次 `Open` —— 中间确实经过了一段「可以再试」的时间。 + pub fn record(&mut self, ok: bool, tally: Tally, p: &Policy, now_ms: i64) -> Option { + let before = self.state_at(p, now_ms); + match (before, ok) { + (State::Closed, true) => self.failures = 0, + (State::Closed, false) => { + self.failures += 1; + if trips(p.trip, self.failures, tally) { + self.open(now_ms); + } + } + (State::HalfOpen | State::Open, true) => { + self.probe_successes += 1; + if self.probe_successes >= p.probes.max(1) { + *self = Breaker::default(); + } else { + self.state = State::HalfOpen; + } + } + (State::HalfOpen | State::Open, false) => { + self.failures += 1; + self.open(now_ms); + } + } + let after = self.state_at(p, now_ms); + (after != before).then_some(after) + } + + fn open(&mut self, now_ms: i64) { + self.state = State::Open; + self.opened_at_ms = now_ms; + self.probe_successes = 0; + } + + fn cooled(&self, p: &Policy, now_ms: i64) -> bool { + let cooldown = i64::try_from(p.cooldown.as_millis()).unwrap_or(i64::MAX); + now_ms.saturating_sub(self.opened_at_ms) >= cooldown + } +} + +fn trips(t: Trip, failures: u32, tally: Tally) -> bool { + match t { + Trip::Consecutive(n) => failures >= n.max(1), + Trip::ErrorRate { + percent, + min_samples, + } => { + tally.total >= min_samples.max(1) + && u64::from(tally.errors) * 100 >= u64::from(percent) * u64::from(tally.total) + } + } +} + +/// 现在是 Unix 毫秒几。 +pub fn now_ms() -> i64 { + std::time::SystemTime::now() + .duration_since(std::time::UNIX_EPOCH) + .map_or(0, |d| i64::try_from(d.as_millis()).unwrap_or(i64::MAX)) +} + +type Clock = Arc i64 + Send + Sync>; + +/// 一组放在进程内存里的熔断器,按 `K` 区分。 +/// +/// **不持久化。**进程内的熔断器活多久就记多久;要跨副本共享的调用方 +/// 把 [`Breaker`] 自己存到别处。 +/// +/// 只用于按连续失败触发的熔断器 —— 按错误率触发要一个窗口,而窗口怎么统计 +/// 是存储的事。 +pub struct Breakers { + policy: Policy, + map: Mutex>, + clock: Clock, +} + +impl Breakers { + pub fn new(policy: Policy) -> Self { + Self::with_clock(policy, Arc::new(now_ms)) + } + + /// 时间由调用方给。测试用它把时间拨快,不必真等冷却。 + pub fn with_clock(policy: Policy, clock: Clock) -> Self { + Self { + policy, + map: Mutex::new(HashMap::new()), + clock, + } + } + + pub fn policy(&self) -> &Policy { + &self.policy + } + + fn with(&self, key: &K, f: impl FnOnce(&mut Breaker, &Policy, i64) -> R) -> R { + let now = (self.clock)(); + let mut map = self.map.lock().unwrap_or_else(|e| e.into_inner()); + let b = map.entry(key.clone()).or_default(); + f(b, &self.policy, now) + } + + pub fn state(&self, key: &K) -> State { + let now = (self.clock)(); + let map = self.map.lock().unwrap_or_else(|e| e.into_inner()); + map.get(key) + .map_or(State::Closed, |b| b.state_at(&self.policy, now)) + } + + pub fn admits(&self, key: &K) -> bool { + self.state(key) != State::Open + } + + /// 见 [`Breaker::admit`]。 + pub fn admit(&self, key: &K) -> (bool, Option) { + self.with(key, |b, p, now| b.admit(p, now)) + } + + pub fn record(&self, key: &K, ok: bool) -> Option { + self.with(key, |b, p, now| b.record(ok, Tally::default(), p, now)) + } + + pub fn cooldown_left(&self, key: &K) -> Option { + let now = (self.clock)(); + let map = self.map.lock().unwrap_or_else(|e| e.into_inner()); + map.get(key)?.cooldown_left(&self.policy, now) + } +} + +#[cfg(test)] +mod tests { + use super::*; + use std::sync::atomic::{AtomicI64, Ordering}; + + const SEC: i64 = 1000; + + fn consecutive(n: u32, probes: u32) -> Policy { + Policy { + trip: Trip::Consecutive(n), + cooldown: Duration::from_secs(60), + probes, + } + } + + fn rate() -> Policy { + Policy { + trip: Trip::ErrorRate { + percent: 50, + min_samples: 4, + }, + cooldown: Duration::from_secs(30), + probes: 1, + } + } + + fn fail(b: &mut Breaker, p: &Policy, now: i64) -> Option { + b.record(false, Tally::default(), p, now) + } + + #[test] + fn only_the_failure_that_flips_it_reports_a_change() { + let p = consecutive(3, 1); + let mut b = Breaker::default(); + assert_eq!(fail(&mut b, &p, 0), None); + assert_eq!(fail(&mut b, &p, 0), None); + assert_eq!(fail(&mut b, &p, 0), Some(State::Open), "第三次才是变化"); + assert_eq!(fail(&mut b, &p, 1), None, "已经开着了"); + } + + #[test] + fn one_success_wipes_the_streak() { + // 「连续」是关键词。断续的失败说明是偶发 + let p = consecutive(3, 1); + let mut b = Breaker::default(); + fail(&mut b, &p, 0); + fail(&mut b, &p, 0); + b.record(true, Tally::default(), &p, 0); + fail(&mut b, &p, 0); + assert!(b.admits(&p, 0)); + } + + #[test] + fn a_cooled_breaker_is_half_open_without_anyone_touching_it() { + // 以前企业版要等一个请求落在这条路由上才半开,而打开的路由选不到 + let p = consecutive(1, 1); + let mut b = Breaker::default(); + fail(&mut b, &p, 0); + assert_eq!(b.state_at(&p, 59 * SEC), State::Open); + assert_eq!(b.state_at(&p, 60 * SEC), State::HalfOpen); + assert!(b.admits(&p, 60 * SEC)); + } + + #[test] + fn a_probe_decides() { + let p = consecutive(1, 1); + let mut b = Breaker::default(); + fail(&mut b, &p, 0); + // 探测失败:重新打开,这是一次变化(中间确实可以再试过) + assert_eq!(fail(&mut b, &p, 60 * SEC), Some(State::Open)); + assert_eq!(b.cooldown_left(&p, 60 * SEC), Some(Duration::from_secs(60))); + // 探测成功:闭合 + assert_eq!( + b.record(true, Tally::default(), &p, 120 * SEC), + Some(State::Closed) + ); + assert_eq!(b, Breaker::default()); + } + + #[test] + fn several_probes_can_be_required() { + let p = consecutive(1, 3); + let mut b = Breaker::default(); + fail(&mut b, &p, 0); + let ok = |b: &mut Breaker| b.record(true, Tally::default(), &p, 60 * SEC); + assert_eq!(ok(&mut b), None, "还是半开"); + assert_eq!(b.state, State::HalfOpen, "半开落进了状态里"); + assert_eq!(ok(&mut b), None); + assert_eq!(ok(&mut b), Some(State::Closed)); + } + + #[test] + fn a_late_failure_while_open_restarts_the_cooldown() { + // 熔断之前发出去的请求晚到了,又失败 —— 上游还是坏的 + let p = consecutive(1, 1); + let mut b = Breaker::default(); + fail(&mut b, &p, 0); + assert_eq!(fail(&mut b, &p, 30 * SEC), None); + assert_eq!(b.cooldown_left(&p, 30 * SEC), Some(Duration::from_secs(60))); + } + + #[test] + fn a_late_success_while_open_counts_as_a_probe() { + let p = consecutive(1, 1); + let mut b = Breaker::default(); + fail(&mut b, &p, 0); + assert_eq!( + b.record(true, Tally::default(), &p, SEC), + Some(State::Closed) + ); + } + + #[test] + fn admit_lands_the_half_open_step_once() { + let p = consecutive(1, 2); + let mut b = Breaker::default(); + fail(&mut b, &p, 0); + assert_eq!(b.admit(&p, SEC), (false, None)); + assert_eq!(b.admit(&p, 60 * SEC), (true, Some(State::HalfOpen))); + assert_eq!(b.admit(&p, 61 * SEC), (true, None)); + } + + #[test] + fn an_error_rate_needs_enough_samples() { + let p = rate(); + let mut b = Breaker::default(); + let t = |total, errors| Tally { total, errors }; + assert_eq!(b.record(false, t(3, 3), &p, 0), None, "样本不够"); + assert_eq!(b.record(false, t(4, 2), &p, 0), Some(State::Open)); + } + + #[test] + fn an_error_rate_below_the_line_stays_closed() { + let p = rate(); + let mut b = Breaker::default(); + assert_eq!( + b.record( + false, + Tally { + total: 10, + errors: 4 + }, + &p, + 0 + ), + None + ); + assert_eq!(b.state, State::Closed); + } + + #[test] + fn it_round_trips_through_json_and_forgets_on_garbage() { + let p = consecutive(1, 1); + let mut b = Breaker::default(); + fail(&mut b, &p, 5); + let back: Breaker = serde_json::from_str(&serde_json::to_string(&b).unwrap()).unwrap(); + assert_eq!(back, b); + // 状态名是 snake_case,和企业版界面读到的一样 + assert_eq!( + serde_json::to_string(&State::HalfOpen).unwrap(), + "\"half_open\"" + ); + // 缺字段就是默认 + let empty: Breaker = serde_json::from_str("{}").unwrap(); + assert_eq!(empty, Breaker::default()); + } + + #[test] + fn breakers_keep_one_per_key_on_a_clock_the_caller_controls() { + let now = Arc::new(AtomicI64::new(0)); + let clock = { + let now = now.clone(); + Arc::new(move || now.load(Ordering::SeqCst)) + }; + let bs = Breakers::with_clock(consecutive(2, 1), clock); + assert_eq!(bs.record(&"a", false), None); + assert_eq!(bs.record(&"a", false), Some(State::Open)); + assert!(!bs.admits(&"a")); + assert!(bs.admits(&"b"), "一个键一个"); + now.store(60 * SEC, Ordering::SeqCst); + assert_eq!(bs.state(&"a"), State::HalfOpen); + assert_eq!(bs.admit(&"a"), (true, Some(State::HalfOpen))); + assert_eq!(bs.record(&"a", true), Some(State::Closed)); + } +} diff --git a/crates/tw-control/src/lib.rs b/crates/tw-control/src/lib.rs index bf36eba9..fa38ddb9 100644 --- a/crates/tw-control/src/lib.rs +++ b/crates/tw-control/src/lib.rs @@ -468,7 +468,8 @@ fn provider_view( model_count: s.gateway.catalog.load().count_for(&p.name), disabled: p.disabled, health: match s.health().state(&p.name) { - tw_gateway::health::State::Closed => "ok".into(), + // 冷却到点的半开照常放行,界面上和闭合一样是「正常」 + tw_gateway::health::State::Closed | tw_gateway::health::State::HalfOpen => "ok".into(), tw_gateway::health::State::Open => "open".into(), }, auth_rejected: s.gateway.auth_rejected(&p.name), diff --git a/crates/tw-gateway/Cargo.toml b/crates/tw-gateway/Cargo.toml index 5740d272..d4c09d13 100644 --- a/crates/tw-gateway/Cargo.toml +++ b/crates/tw-gateway/Cargo.toml @@ -10,6 +10,7 @@ description = "Data-plane HTTP server" [dependencies] tw-api = { workspace = true } tw-config = { workspace = true } +tw-breaker = { workspace = true } tw-engine = { workspace = true } tw-observe = { workspace = true } tw-secret = { workspace = true } diff --git a/crates/tw-gateway/src/health.rs b/crates/tw-gateway/src/health.rs index 1611c8ca..fb5ebd47 100644 --- a/crates/tw-gateway/src/health.rs +++ b/crates/tw-gateway/src/health.rs @@ -1,5 +1,8 @@ //! 上游健康与熔断。 //! +//! 状态机是共用的(`tw-breaker`,企业版的路由和 MCP 熔断跑的是同一个), +//! 这里是桌面版的**规矩**: +//! //! **只有两个旋钮**:连续失败阈值和冷却时长。cc-switch //! 那套有五个,其中「错误率 + 最小请求数」这条路径在单用户场景下几乎永远 //! 打不满 —— 要先攒够十几个请求才生效,而那时用户早就自己发现了。 @@ -12,9 +15,10 @@ //! 2. **只有一个候选时完全旁路熔断器。**否则唯一的上游一旦被自己熔断, //! 就把用户锁死了,熔断纯粹是自伤。 -use std::collections::HashMap; -use std::sync::Mutex; -use std::time::{Duration, Instant}; +use std::time::Duration; + +pub use tw_breaker::State; +use tw_breaker::{Breakers, Policy, Trip}; /// 连续失败多少次算坏。 pub const FAILURE_THRESHOLD: u32 = 3; @@ -22,54 +26,52 @@ pub const FAILURE_THRESHOLD: u32 = 3; /// 熔断之后多久放一个探测过去。 pub const COOLDOWN: Duration = Duration::from_secs(60); -#[derive(Debug, Clone, Copy, PartialEq, Eq)] -pub enum State { - Closed, - /// 熔断中。到点之后第一个请求会被放过去探路(半开) - Open, -} - -#[derive(Debug, Default)] -struct Entry { - consecutive_failures: u32, - opened_at: Option, -} - -/// 这一条现在算什么状态。**时间也是输入** —— 冷却到点就自动算合上, -/// 下一个请求自然成为探测。 -fn effective(e: &Entry) -> State { - match e.opened_at { - Some(t) if t.elapsed() < COOLDOWN => State::Open, - _ => State::Closed, - } -} +/// 桌面版的规矩:连续失败 3 次打开,冷却 60 秒,一次成功就闭合。 +pub const POLICY: Policy = Policy { + trip: Trip::Consecutive(FAILURE_THRESHOLD), + cooldown: COOLDOWN, + probes: 1, +}; /// 每个 provider 的健康状态。 /// /// **不持久化**。桌面应用重启频繁,把「这家挂了」的判断带过重启 /// 意味着用户重启后第一个请求还在被上一次的故障惩罚 —— 而重启本身往往 /// 就是他为了解决问题做的事。 -#[derive(Default)] pub struct Health { - inner: Mutex>, + breakers: Breakers, +} + +impl Default for Health { + fn default() -> Self { + Self::new() + } } impl Health { pub fn new() -> Self { - Self::default() + Self { + breakers: Breakers::new(POLICY), + } + } + + #[cfg(test)] + fn with_clock(clock: std::sync::Arc i64 + Send + Sync>) -> Self { + Self { + breakers: Breakers::with_clock(POLICY, clock), + } } - /// 这家现在能进候选链吗。 + /// 这家现在能进候选链吗。冷却到点的算半开,放行。 /// - /// **和「能不能收一个探测请求」是两件事**,所以是两个方法。合成一个 - /// 的话,光是排候选顺序就会把半开状态的唯一探测机会用掉。 + /// **和「能不能收一个探测请求」是两件事**:只看不改,光是排候选顺序 + /// 不该把半开状态的探测机会用掉。 pub fn is_available(&self, name: &str) -> bool { - self.state(name) == State::Closed + self.breakers.admits(&name.to_string()) } pub fn state(&self, name: &str) -> State { - let g = self.inner.lock().unwrap(); - g.get(name).map_or(State::Closed, effective) + self.breakers.state(&name.to_string()) } /// 记一次成功。**返回的是状态变化,没变就是 `None`。** @@ -77,42 +79,19 @@ impl Health { /// 调用方要拿它去发事件:熔断开合是界面上看得见的状态,而看得见的 /// 状态必须能被推出去 —— 否则界面只能轮询。 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) + self.breakers.record(&name.to_string(), true) } /// 记一次失败,同样返回状态变化。 - /// - /// 冷却到点之后那次探测又失败时,这里会再报一次 `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) + self.breakers.record(&name.to_string(), false) } - /// 这家还要等多久才轮到探测。 + /// 这家还要等多久才轮到探测。见 [`tw_breaker::Breaker::cooldown_left`]。 /// - /// `None` = 根本不在熔断态(成功过,或者从来没熔断过)。 - /// `Some(0)` = 冷却走完了,下一个请求就是那次探测。 - /// - /// **专门给「报一条恢复」的定时器用。**它必须能分清「到点了」和 - /// 「中途又失败、冷却被顶到更晚了」—— 后者返回的是新的剩余时间, - /// 定时器据此接着等,而不是现在就宣布恢复。 + /// **专门给「报一条恢复」的定时器用。** pub fn cooldown_left(&self, name: &str) -> Option { - let g = self.inner.lock().unwrap(); - let t = g.get(name)?.opened_at?; - Some(COOLDOWN.saturating_sub(t.elapsed())) + self.breakers.cooldown_left(&name.to_string()) } /// 从候选里挑出还能用的,**并说明是不是 fail-open**。 @@ -284,4 +263,24 @@ mod tests { assert!(!h.is_available("a")); assert!(h.is_available("b")); } + + #[test] + fn after_the_cooldown_the_next_request_is_a_probe() { + use std::sync::atomic::{AtomicI64, Ordering}; + let now = std::sync::Arc::new(AtomicI64::new(0)); + let h = Health::with_clock({ + let now = now.clone(); + std::sync::Arc::new(move || now.load(Ordering::SeqCst)) + }); + for _ in 0..3 { + h.record_failure("a"); + } + assert!(!h.is_available("a")); + now.store(COOLDOWN.as_millis() as i64, Ordering::SeqCst); + assert!(h.is_available("a"), "冷却到点就放一个过去"); + assert_eq!(h.cooldown_left("a"), Some(Duration::ZERO)); + // 探测又失败:再报一次打开 + assert_eq!(h.record_failure("a"), Some(State::Open)); + assert!(!h.is_available("a")); + } } diff --git a/crates/tw-scan/src/hidden.rs b/crates/tw-guard/src/hidden.rs similarity index 92% rename from crates/tw-scan/src/hidden.rs rename to crates/tw-guard/src/hidden.rs index d1a70ea3..8ed1463e 100644 --- a/crates/tw-scan/src/hidden.rs +++ b/crates/tw-guard/src/hidden.rs @@ -38,6 +38,15 @@ impl Kind { Kind::PrivateUse => "private_use", } } + /// 在**任何**正文里都没有正当用途的两种:标签字符和双向覆盖。 + /// + /// 其余几种只在指令文件里可疑:对话正文里零宽连接符组成表情(👨‍👩‍👧), + /// 波斯文要零宽不连字,俄文就是西里尔字母。扫用户消息、工具结果这类 + /// 正文时只看这两种;扫配置文件时它们是最高那一档。 + pub fn smuggles(&self) -> bool { + matches!(self, Kind::Tag | Kind::Bidi) + } + /// 一句给人看的话。**说清「它能干什么」,不是「它是什么」** —— /// 「U+200B ZWSP」对绝大多数人不构成信息。 pub fn why(&self) -> &'static str { @@ -250,6 +259,17 @@ pub fn scan(text: &str) -> Vec { #[cfg(test)] mod tests { + #[test] + fn only_tags_and_bidi_overrides_smuggle() { + // 表情里的零宽连接符、俄文的西里尔字母在对话里是正常的 + let smuggles = |s: &str| scan(s).iter().any(|h| h.kind.smuggles()); + assert!(smuggles("hi\u{E0049}\u{E0067}"), "标签字符"); + assert!(smuggles("abc\u{202E}fed"), "双向覆盖"); + assert!(!smuggles("👨\u{200D}👩\u{200D}👧"), "表情"); + assert!(!smuggles("Привет, как дела?"), "俄文"); + assert!(!smuggles("مرحبا"), "阿拉伯文本身不带覆盖符"); + } + use super::*; #[test] diff --git a/crates/tw-guard/src/lib.rs b/crates/tw-guard/src/lib.rs index 39aa04bb..5d847e5f 100644 --- a/crates/tw-guard/src/lib.rs +++ b/crates/tw-guard/src/lib.rs @@ -1,10 +1,11 @@ -//! 防护:出站脱敏,和对上游返回的工具调用的审查。 +//! 防护:出站脱敏、对上游返回的工具调用的审查,和藏在文本里的不可见字符。 //! //! **引擎在这里,规则集和配置各带各的。**桌面版脱的是开发者自己的 API key, //! 企业版脱的是客户的身份证号和手机号;桌面版的规则写在 `config.yaml`,企业版 //! 的在系统设置里。两边共用的是「怎么找、怎么换、怎么在流里换回来、怎么审查 //! 一个工具调用」—— 这些和规则是什么、从哪来无关。 +pub mod hidden; pub mod redact; pub mod tools; diff --git a/crates/tw-scan/src/lib.rs b/crates/tw-scan/src/lib.rs index 94f3cc48..9b6e9ed6 100644 --- a/crates/tw-scan/src/lib.rs +++ b/crates/tw-scan/src/lib.rs @@ -1,4 +1,3 @@ -pub mod hidden; pub mod report; pub mod sources; pub mod watch; diff --git a/crates/tw-scan/src/report.rs b/crates/tw-scan/src/report.rs index 26d9ccc3..b75935bc 100644 --- a/crates/tw-scan/src/report.rs +++ b/crates/tw-scan/src/report.rs @@ -20,8 +20,8 @@ use std::path::PathBuf; use tw_adopt::json::Val; use tw_types::{Msg, msg}; -use crate::hidden; use crate::sources::{self, Source}; +use tw_guard::hidden; use tw_guard::tools::rules::Rules; #[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord)] @@ -301,10 +301,11 @@ pub fn scan(sources: &[Source], rules: &Rules) -> Report { // 一、藏起来的东西。**每一份都扫**,配置文件也不例外 for h in hidden::scan(&text) { - let level = match h.kind { - // 标签字符和双向控制符在指令文件里没有任何正当用途 - hidden::Kind::Tag | hidden::Kind::Bidi => Level::High, - _ => Level::Medium, + // 标签字符和双向控制符在任何文本里都没有正当用途 + let level = if h.kind.smuggles() { + Level::High + } else { + Level::Medium }; r.findings.push(Finding { level, diff --git a/crates/tw-scan/tests/scan.rs b/crates/tw-scan/tests/scan.rs index 72b276e9..cf866958 100644 --- a/crates/tw-scan/tests/scan.rs +++ b/crates/tw-scan/tests/scan.rs @@ -253,7 +253,7 @@ fn the_source_code_itself_contains_no_way_to_delete_anything() { // 一个安全扫描器长出删除能力的那天,会是从某个「顺手」的 PR 开始的。 for f in [ "src/report.rs", - "src/hidden.rs", + "../tw-guard/src/hidden.rs", "src/sources.rs", // 规则引擎住在 tw-guard,扫描器用的也是它 "../tw-guard/src/tools/rules.rs",