diff --git a/crates/tw-api/msg-codes.txt b/crates/tw-api/msg-codes.txt index 5be2f14a..92a67122 100644 --- a/crates/tw-api/msg-codes.txt +++ b/crates/tw-api/msg-codes.txt @@ -58,6 +58,7 @@ config.edit.self_check config.edit.unwritable config.empty_key config.empty_models_only +config.failover_range config.name_collision config.no_clients config.output_limit_range @@ -286,6 +287,7 @@ gw.upstream.sign_failed gw.upstream.status gw.upstream.stream_error gw.upstream.stream_exception +gw.upstream.stream_opening_error gw.upstream.timeout gw.upstream.unreachable gw.ws.bad_header diff --git a/crates/tw-api/src/lib.rs b/crates/tw-api/src/lib.rs index 13f0ee37..4e175a55 100644 --- a/crates/tw-api/src/lib.rs +++ b/crates/tw-api/src/lib.rs @@ -651,6 +651,9 @@ pub const MSG_CODES: &str = include_str!("../msg-codes.txt"); /// `:countTokens` 路由到别的格式的上游、或者上游回 404 / 405 时,网关自己估一个数回去。 /// 尝试链多一种结果 [`AttemptOutcome::Estimated`],那一行是 `local`、费用 0。照 29 写的 /// 界面不认这个词。 +/// +/// 30 起概览还带 [`Overview::failover`]([`FailoverView`]:上游失败之后停用多久、流开头 +/// 最多等多久)。照 29 写的界面读不出这一项,也就改不了它。 pub const CONTROL_API_VERSION: u32 = 30; #[derive(Debug, Clone, Serialize, Deserialize)] @@ -1581,6 +1584,8 @@ pub struct Overview { pub client_probes: Vec, /// 日志留多久 pub retention: RetentionView, + /// 上游失败之后停用多久、流开头最多等多久 + pub failover: FailoverView, /// 自定义价目表。默认价目表不在这里 —— 它的状态看 `/pricing` pub price_sheets: Vec, } @@ -1662,6 +1667,27 @@ pub struct RetentionView { pub body_bytes_now: u64, } +/// 上游失败之后停用多久、流开头最多等多久。和配置的 `failover` 一一对应, +/// 没写的是默认值 —— **界面显示的就是真在用的数**,不是「空 = 默认」。 +#[derive(Debug, Clone, Default, Serialize, Deserialize)] +#[cfg_attr(feature = "ts", derive(ts_rs::TS))] +pub struct FailoverView { + /// 说不出原因的失败连续几次之后停用 + pub failures_to_pause: u32, + /// 这类失败第一次停用多少秒,之后每次翻倍 + pub pause_secs: u64, + /// 翻倍的上限,秒 + pub max_pause_secs: u64, + /// 余额不足时停用多少秒 + pub no_balance_pause_secs: u64, + /// 额度用完、上游没说什么时候重置时停用多少秒 + pub quota_pause_secs: u64, + /// 限流时按 `Retry-After` 停用,最多多少秒 + pub rate_limit_max_pause_secs: u64, + /// 流式回答的开头最多等多少秒 + pub stream_start_wait_secs: u64, +} + /// 每项防护各在哪一档:`off` / `observe` / `enforce`。 /// /// **「拦截」在各项上做的事不一样**:脱敏是替换成占位符,工具调用审查和输出长度 diff --git a/crates/tw-config/src/failover.rs b/crates/tw-config/src/failover.rs new file mode 100644 index 00000000..1213f029 --- /dev/null +++ b/crates/tw-config/src/failover.rs @@ -0,0 +1,126 @@ +//! 故障转移:一家上游失败之后停用多久、流开头最多等多久。 + +use serde::{Deserialize, Serialize}; + +/// 一家上游失败之后停用多久。 +/// +/// **按失败的原因分开算**,因为上游说出来的原因差别很大:余额不足要等用户去 +/// 充值,额度用完要等到上游说的重置时刻,限流通常几十秒就过去 —— 一律「冷却 +/// 60 秒」的话,前两种每分钟白试一次,最后一种又停得太久。 +/// +/// 只有一家候选的请求不受这些影响:没有别的家可切,停用它只会把用户锁死 +/// (见 `tw_gateway::health`)。 +#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)] +#[serde(deny_unknown_fields)] +pub struct Failover { + /// 说不出原因的失败(5xx、连不上)连续几次之后停用 + #[serde(default = "d_failures_to_pause")] + pub failures_to_pause: u32, + /// 这类失败第一次停用多少秒。**之后每再停一次翻一倍**,直到 + /// [`Self::max_pause_secs`];成功一次就回到这个数 + #[serde(default = "d_pause_secs")] + pub pause_secs: u64, + /// 翻倍的上限,秒 + #[serde(default = "d_max_pause_secs")] + pub max_pause_secs: u64, + /// 上游说余额不足时停用多少秒 + #[serde(default = "d_no_balance_pause_secs")] + pub no_balance_pause_secs: u64, + /// 上游说额度用完、又没说什么时候重置时,停用多少秒。说了的就停到那一刻 + #[serde(default = "d_quota_pause_secs")] + pub quota_pause_secs: u64, + /// 限流时按上游给的 `Retry-After` 停用,**最多停多少秒**。没给就当作说不出 + /// 原因的失败 + #[serde(default = "d_rate_limit_max_pause_secs")] + pub rate_limit_max_pause_secs: u64, + /// 流式回答开头最多等多少秒。在第一段内容到达之前,上游报的错误照样换下一家; + /// 等过这么久还没有内容,就不再等,把已经收到的交给客户端 + #[serde(default = "d_stream_start_wait_secs")] + pub stream_start_wait_secs: u64, +} + +fn d_failures_to_pause() -> u32 { + 3 +} +fn d_pause_secs() -> u64 { + 60 +} +fn d_max_pause_secs() -> u64 { + 600 +} +fn d_no_balance_pause_secs() -> u64 { + 1800 +} +fn d_quota_pause_secs() -> u64 { + 3600 +} +fn d_rate_limit_max_pause_secs() -> u64 { + 3600 +} +fn d_stream_start_wait_secs() -> u64 { + 15 +} + +impl Default for Failover { + fn default() -> Self { + Self { + failures_to_pause: d_failures_to_pause(), + pause_secs: d_pause_secs(), + max_pause_secs: d_max_pause_secs(), + no_balance_pause_secs: d_no_balance_pause_secs(), + quota_pause_secs: d_quota_pause_secs(), + rate_limit_max_pause_secs: d_rate_limit_max_pause_secs(), + stream_start_wait_secs: d_stream_start_wait_secs(), + } + } +} + +/// 停用时长最多写多少秒:一周。**额度用完停到重置时刻不受它限制** —— 那是上游 +/// 说的时刻,周额度本来就可能在七天之后 +pub const MAX_PAUSE_SECS: u64 = 7 * 24 * 3600; + +/// 流开头最多等多少秒。再长的话,一家卡在半路的上游会让客户端先超时 +pub const MAX_STREAM_START_WAIT_SECS: u64 = 120; + +impl Failover { + /// 不在允许范围里的第一项:字段名、写的值、下限、上限。 + pub(crate) fn out_of_range(&self) -> Option<(&'static str, u64, u64, u64)> { + let fields: [(&'static str, u64, u64, u64); 7] = [ + ( + "failures_to_pause", + u64::from(self.failures_to_pause), + 1, + 100, + ), + ("pause_secs", self.pause_secs, 1, MAX_PAUSE_SECS), + ( + "max_pause_secs", + self.max_pause_secs, + self.pause_secs.max(1), + MAX_PAUSE_SECS, + ), + ( + "no_balance_pause_secs", + self.no_balance_pause_secs, + 1, + MAX_PAUSE_SECS, + ), + ("quota_pause_secs", self.quota_pause_secs, 1, MAX_PAUSE_SECS), + ( + "rate_limit_max_pause_secs", + self.rate_limit_max_pause_secs, + 1, + MAX_PAUSE_SECS, + ), + ( + "stream_start_wait_secs", + self.stream_start_wait_secs, + 1, + MAX_STREAM_START_WAIT_SECS, + ), + ]; + fields + .into_iter() + .find(|(_, v, min, max)| v < min || v > max) + } +} diff --git a/crates/tw-config/src/lib.rs b/crates/tw-config/src/lib.rs index bb456fef..70bf42c5 100644 --- a/crates/tw-config/src/lib.rs +++ b/crates/tw-config/src/lib.rs @@ -11,6 +11,7 @@ pub mod chatgpt; pub mod control_key; pub mod credential; pub mod edit; +mod failover; pub mod history; mod init; pub mod nics; @@ -88,6 +89,9 @@ pub struct Config { /// 日志留多久。不写就是默认值。 #[serde(default, skip_serializing_if = "is_default")] pub retention: Retention, + /// 一家上游失败之后停用多久、流开头最多等多久。不写就是默认值。 + #[serde(default, skip_serializing_if = "is_default")] + pub failover: Failover, #[serde(default, skip_serializing_if = "Vec::is_empty")] pub groups: Vec, /// 路由。一条路由是一组按顺序求值的规则。 @@ -126,6 +130,7 @@ impl Default for Config { client_probes: ClientProbes::default(), security: Security::default(), retention: Retention::default(), + failover: Failover::default(), groups: Vec::new(), routes: Vec::new(), default_route: None, @@ -1143,6 +1148,7 @@ pub fn write(path: &Path, cfg: &Config) -> Result<(), WriteError> { Ok(()) } +pub use failover::{Failover, MAX_PAUSE_SECS, MAX_STREAM_START_WAIT_SECS}; pub use probes::{ClientProbes, ProbeAction}; pub use reload::{Rejected, Stage, try_parse}; pub use retention::Retention; diff --git a/crates/tw-config/src/validate.rs b/crates/tw-config/src/validate.rs index 72f987f0..045bff80 100644 --- a/crates/tw-config/src/validate.rs +++ b/crates/tw-config/src/validate.rs @@ -71,6 +71,13 @@ pub enum ValidationError { #[error("{}", self.msg())] OutputLimitRange { max: usize, ceiling: usize }, #[error("{}", self.msg())] + FailoverRange { + field: &'static str, + value: u64, + min: u64, + max: u64, + }, + #[error("{}", self.msg())] ControlKeyMissing, #[error("{}", self.msg())] ControlKeyInvalid, @@ -203,6 +210,15 @@ impl ValidationError { "config.output_limit_range", max = max, ceiling = ceiling => "security.output_limit.max_chars is {max}; it has to be between 1 and {ceiling}" ), + FailoverRange { + field, + value, + min, + max, + } => msg!( + "config.failover_range", field = field, value = value, min = min, max = max => + "failover.{field} is {value}; it has to be between {min} and {max}" + ), ControlKeyMissing => msg!( "config.control_key_missing" => "the configuration has no listen.control.key, the key the desktop app connects \ @@ -429,6 +445,14 @@ pub fn validate(cfg: &Config) -> Result<(), ValidationError> { ceiling: crate::MAX_CHARS_CEILING, }); } + if let Some((field, value, min, max)) = cfg.failover.out_of_range() { + return Err(ValidationError::FailoverRange { + field, + value, + min, + max, + }); + } // 按 id 开关、改处置的内置规则得真的存在。**写错一个 id 和写错一个字段名 // 是同一种错**:跳过它,用户停用的那条会照样在报 if let Some((guard, id)) = cfg.security.unknown_rule() { @@ -876,6 +900,34 @@ mod tests { assert!(validate(&x).is_ok()); } + /// 停用时长写成 0 等于没有停用,上限比起点还小等于翻倍从一开始就封顶 —— + /// 都是写错了,说出是哪一项 + #[test] + fn failover_numbers_have_to_be_in_range() { + let base = with_rules(&[], &[]); + assert!(validate(&base).is_ok()); + type Bend = fn(&mut crate::Failover); + let cases: [(&str, Bend); 4] = [ + ("failures_to_pause", |f| f.failures_to_pause = 0), + ("pause_secs", |f| f.pause_secs = 0), + ("max_pause_secs", |f| { + f.pause_secs = 120; + f.max_pause_secs = 60; + }), + ("stream_start_wait_secs", |f| { + f.stream_start_wait_secs = crate::MAX_STREAM_START_WAIT_SECS + 1 + }), + ]; + for (want, bend) in cases { + let mut x = base.clone(); + bend(&mut x.failover); + match validate(&x) { + Err(ValidationError::FailoverRange { field, .. }) => assert_eq!(field, want), + other => panic!("{want} 该被拒,实际 {other:?}"), + } + } + } + /// 按 id 写到的内置规则得真的存在:写错的 id 和写错的字段名一样拒绝, /// 说出是哪一项下的哪个 id。 #[test] diff --git a/crates/tw-config/tests/manual/schema.rs b/crates/tw-config/tests/manual/schema.rs index 482c9de9..13b19b43 100644 --- a/crates/tw-config/tests/manual/schema.rs +++ b/crates/tw-config/tests/manual/schema.rs @@ -171,6 +171,15 @@ pub fn sections() -> Vec
{ Def::Section, t("How long request logs are kept.", "请求日志保留多久。"), ), + row( + "failover", + Kind::Obj("failover"), + Def::Section, + t( + "How long an upstream is set aside after it fails, and how long the start of a stream is awaited.", + "上游失败后停用多久,以及流式回答的开头最多等多久。", + ), + ), row( "groups", Kind::Objs("groups[]"), @@ -1164,6 +1173,76 @@ pub fn sections() -> Vec
{ ), ], }, + // ── failover ────────────────────────────────────────── + Section { + path: "failover", + ty: checked!(Failover, "{}"), + rows: vec![ + row( + "failures_to_pause", + Kind::Int, + Def::Is("3"), + t( + "Consecutive failures without a stated reason (5xx, connection errors) before the upstream is set aside. From 1 to 100.", + "没有说明原因的失败(5xx、连接失败)连续几次后停用这家上游,取值 1 到 100。", + ), + ), + row( + "pause_secs", + Kind::Int, + Def::Is("60"), + t( + "Seconds the first such pause lasts. Each further pause doubles it, up to `max_pause_secs`; one success resets it.", + "这类失败第一次停用的秒数。之后每停用一次翻一倍,直到 `max_pause_secs`;成功一次后回到这个值。", + ), + ), + row( + "max_pause_secs", + Kind::Int, + Def::Is("600"), + t( + "Upper bound on the doubled pause, in seconds; not less than `pause_secs`.", + "翻倍后的停用上限,单位秒,不小于 `pause_secs`。", + ), + ), + row( + "no_balance_pause_secs", + Kind::Int, + Def::Is("1800"), + t( + "Seconds to set aside an upstream that reports an insufficient balance.", + "上游报告余额不足时停用的秒数。", + ), + ), + row( + "quota_pause_secs", + Kind::Int, + Def::Is("3600"), + t( + "Seconds to set aside an upstream whose quota is used up when it does not say when the quota resets. When it does, the upstream is set aside until then.", + "上游报告额度用完、但没有给出重置时间时停用的秒数。给出了重置时间的,停用到那一刻。", + ), + ), + row( + "rate_limit_max_pause_secs", + Kind::Int, + Def::Is("3600"), + t( + "A rate-limited upstream is set aside for the time its `Retry-After` gives, at most this many seconds. Without `Retry-After` it counts as a failure without a stated reason.", + "被限流的上游按它给的 `Retry-After` 停用,最多这么多秒。没有 `Retry-After` 的按没有说明原因的失败计。", + ), + ), + row( + "stream_start_wait_secs", + Kind::Int, + Def::Is("15"), + t( + "Seconds to hold a streamed answer until its first content arrives. An error before then moves the request to the next upstream; after this long, what has arrived is passed on. From 1 to 120.", + "流式回答在第一段内容到达前最多暂存的秒数。在此之前上游报错,请求换到下一家;超过这个时间,已收到的部分照常交给客户端。取值 1 到 120。", + ), + ), + ], + }, // ── groups / routes ─────────────────────────────────── Section { path: "groups[]", diff --git a/crates/tw-control/src/lib.rs b/crates/tw-control/src/lib.rs index 36b133f7..1e2b95a6 100644 --- a/crates/tw-control/src/lib.rs +++ b/crates/tw-control/src/lib.rs @@ -391,6 +391,18 @@ async fn overview(State(s): State) -> Json { // 判断松还是紧,除非同时看得见现在占了多少 body_bytes_now, }, + failover: { + let f = &cfg.failover; + tw_api::FailoverView { + failures_to_pause: f.failures_to_pause, + pause_secs: f.pause_secs, + max_pause_secs: f.max_pause_secs, + no_balance_pause_secs: f.no_balance_pause_secs, + quota_pause_secs: f.quota_pause_secs, + rate_limit_max_pause_secs: f.rate_limit_max_pause_secs, + stream_start_wait_secs: f.stream_start_wait_secs, + } + }, listen: tw_api::ListenView { // **`Display` 不是 `Debug`。**`{:?}` 对 `Loopback` / `All` // 碰巧给出正确的小写词,对 `Addr(192.168.1.5)` 给的是 diff --git a/crates/tw-control/tests/resources.rs b/crates/tw-control/tests/resources.rs index 80caf7bd..905610cc 100644 --- a/crates/tw-control/tests/resources.rs +++ b/crates/tw-control/tests/resources.rs @@ -170,6 +170,47 @@ async fn the_overview_carries_the_version_an_edit_is_based_on() { assert_eq!(st, StatusCode::BAD_REQUEST, "{body}"); } +/// 故障转移那一节不写就是默认值,概览照样给出真在用的数;改一项就只写那一项, +/// 写错的数被拒 +#[tokio::test] +async fn failover_settings_show_their_defaults_and_take_an_edit() { + let b = bed(BASE); + let (_, body) = call(&b.app, "GET", "/overview", serde_json::Value::Null).await; + let f = &json(&body)["failover"]; + assert_eq!(f["failures_to_pause"], 3, "{body}"); + assert_eq!(f["pause_secs"], 60); + assert_eq!(f["stream_start_wait_secs"], 15); + + let (st, body) = call( + &b.app, + "PATCH", + "/config", + serde_json::json!({ + "ops": [{ "op": "replace", "path": "/failover/no_balance_pause_secs", "value": 900 }], + }), + ) + .await; + assert_eq!(st, StatusCode::OK, "{body}"); + assert_eq!(b.parsed().failover.no_balance_pause_secs, 900); + assert!( + !b.file().contains("pause_secs: 60"), + "没改的默认值不写进文件:{}", + b.file() + ); + + let (st, body) = call( + &b.app, + "PATCH", + "/config", + serde_json::json!({ + "ops": [{ "op": "replace", "path": "/failover/stream_start_wait_secs", "value": 0 }], + }), + ) + .await; + assert_eq!(st, StatusCode::BAD_REQUEST, "{body}"); + assert!(body.contains("config.failover_range"), "{body}"); +} + // ─────────────────────────────────────────────────────────── 上游 #[tokio::test] diff --git a/crates/tw-gateway/src/failure.rs b/crates/tw-gateway/src/failure.rs new file mode 100644 index 00000000..1006769d --- /dev/null +++ b/crates/tw-gateway/src/failure.rs @@ -0,0 +1,359 @@ +//! 上游失败的原因:该不该换下一家,这家停用多久。 +//! +//! **上游多半说了原因**,在状态码、`Retry-After`、额度头或错误正文里。读出来 +//! 之后两件事就定了: +//! +//! - **换不换。**5xx 和限流换,这不用说;401、403(凭据被拒)、402(没钱了)、 +//! 404(这家没有这个模型)也换 —— 下一家用的是另一把密钥、另一个账户,很可能 +//! 答得了。400、422 多半是请求本身的问题,换了也一样被拒,**只有正文说的是 +//! 余额、额度或者模型不可用时才换**。 +//! - **停多久**(见 [`crate::health`])。余额不足要等充值,额度用完要等到重置 +//! 时刻,限流按 `Retry-After`;说不出原因的才走「连续几次、冷却翻倍」。 +//! +//! 流式回答开头在流里报的错误(Anthropic 的 `overloaded_error`、Codex 的 +//! `response.failed`)也走这里:[`crate::server`] 的流开头判断把它换算成对应的 +//! 状态码和正文,再交给 [`classify`]。 + +use std::time::Duration; + +use http::HeaderMap; + +/// 一家上游这一次为什么没答上来。 +#[derive(Debug, Clone, Copy, PartialEq, Eq)] +pub enum Cause { + /// 余额不足、欠费 + NoBalance, + /// 订阅额度用完了。上游说了什么时候重置的,是那一刻(Unix 毫秒) + QuotaUsedUp { resets_at_ms: Option }, + /// 被限流。上游说了多久之后再来的,是那么久 + RateLimited { retry_after: Option }, + /// 这家没有这个模型,或者不支持。**换下一家,不算这家坏了** —— 它对别的 + /// 模型照样好好的 + ModelUnavailable, + /// 凭据被拒 + AuthRejected, + /// 说不出原因的失败:5xx、过载、连接断了 + Unexplained, +} + +/// 这个回答该怎么办。 +#[derive(Debug, Clone, Copy, PartialEq, Eq)] +pub enum Verdict { + /// 这家没答上来,换下一家 + Failed(Cause), + /// 请求本身的问题:原样交给客户端,不换、不记这家的账 + ClientError, +} + +/// 错误正文最多看多少字节。错误都很短,读太多只是在等一个不是错误的东西 +pub const BODY_PEEK: usize = 64 * 1024; + +/// 看一个非 2xx 的回答。`body` 是正文的开头(最多 [`BODY_PEEK`])。 +pub fn classify(status: u16, headers: &HeaderMap, body: &[u8], now_ms: u64) -> Verdict { + let text = String::from_utf8_lossy(body).to_lowercase(); + // **正文说的原因优先于状态码**:没钱了有人回 402,有人回 429、400、403, + // 甚至 500;额度用完有人回 429,有人回 403 + if says(&text, NO_BALANCE) { + return Verdict::Failed(Cause::NoBalance); + } + let used_up = used_up_reset(headers, now_ms); + if says(&text, QUOTA_USED_UP) || (status == 429 && used_up.is_some()) { + return Verdict::Failed(Cause::QuotaUsedUp { + resets_at_ms: used_up.flatten().or_else(|| reset_in_body(body, now_ms)), + }); + } + match status { + 429 => Verdict::Failed(Cause::RateLimited { + retry_after: retry_after(headers, now_ms).or_else(|| retry_delay_in_body(body)), + }), + 402 => Verdict::Failed(Cause::NoBalance), + 401 | 403 => Verdict::Failed(Cause::AuthRejected), + 404 => Verdict::Failed(Cause::ModelUnavailable), + 400 | 422 if says(&text, MODEL_UNAVAILABLE) => Verdict::Failed(Cause::ModelUnavailable), + s if s >= 500 => Verdict::Failed(Cause::Unexplained), + _ => Verdict::ClientError, + } +} + +/// 余额不足。**要具体到不会误伤**:只写「quota」的话,Gemini 每分钟的限流 +/// (`Quota exceeded for metric …`)也会被当成没钱了 +const NO_BALANCE: &[&str] = &[ + "insufficient_quota", + "exceeded your current quota", + "insufficient balance", + "insufficient_balance", + "insufficient account balance", + "credit balance is too low", + "balance is too low", + "payment required", + "billing_hard_limit", + "arrearage", + "余额不足", + "欠费", +]; + +/// 订阅额度用完。和限流的区别是**要等到重置时刻**,不是几十秒 +const QUOTA_USED_UP: &[&str] = &[ + "usage_limit_reached", + "usage limit reached", + "usage limit has been reached", + "hit your usage limit", + "reached your usage limit", + "使用上限", + "额度已用完", + "额度已用尽", +]; + +/// 这家没有这个模型、不支持它 +const MODEL_UNAVAILABLE: &[&str] = &[ + "model_not_found", + "model not found", + "no such model", + "unknown model", + "unsupported model", + "model is not supported", + "model not supported", + "is not a valid model", + "invalid model", + "模型不存在", + "不支持该模型", + "不支持的模型", +]; + +fn says(text: &str, words: &[&str]) -> bool { + words.iter().any(|w| text.contains(w)) +} + +/// 额度头说用完了没有:`None` 是没说用完,`Some(None)` 是说用完了、没说什么时候 +/// 重置,`Some(Some(t))` 是在 `t` 重置。 +/// +/// 好几个窗口都满了的时候取**最晚**的那个:早的那个重置了,晚的还满着,照样用不了 +fn used_up_reset(headers: &HeaderMap, now_ms: u64) -> Option> { + let q = crate::quota::from_headers(headers, now_ms); + let full: Vec<_> = q + .windows + .iter() + .filter(|w| w.rejected() || w.used_percent >= 100.0) + .collect(); + if full.is_empty() { + return None; + } + Some(full.iter().filter_map(|w| w.resets_at_ms).max()) +} + +/// `Retry-After`:秒数,或者一个 HTTP 日期。 +pub fn retry_after(headers: &HeaderMap, now_ms: u64) -> Option { + let v = headers + .get(http::header::RETRY_AFTER)? + .to_str() + .ok()? + .trim(); + if let Ok(secs) = v.parse::() { + return Some(Duration::from_secs(secs)); + } + let at = chrono::DateTime::parse_from_rfc2822(v) + .ok()? + .timestamp_millis(); + let left = u64::try_from(at).ok()?.checked_sub(now_ms)?; + Some(Duration::from_millis(left)) +} + +/// Gemini 把「多久之后再来」写在正文里:`"retryDelay": "33s"`。 +fn retry_delay_in_body(body: &[u8]) -> Option { + let v: serde_json::Value = serde_json::from_slice(body).ok()?; + let details = v.pointer("/error/details")?.as_array()?; + details.iter().find_map(|d| { + let s = d.get("retryDelay")?.as_str()?; + let secs: f64 = s.strip_suffix('s')?.parse().ok()?; + (secs.is_finite() && secs >= 0.0).then(|| Duration::from_secs_f64(secs)) + }) +} + +/// 正文里的重置时刻。Codex 的 `usage_limit_reached` 带 `resets_at`(Unix 秒)或 +/// `resets_in_seconds`,有时在 `error` 里面。**已经过去的不算** +fn reset_in_body(body: &[u8], now_ms: u64) -> Option { + let v: serde_json::Value = serde_json::from_slice(body).ok()?; + let scopes = [Some(&v), v.get("error")]; + let at = scopes.into_iter().flatten().find_map(|o| { + if let Some(s) = o.get("resets_at").and_then(serde_json::Value::as_u64) { + return Some(s.saturating_mul(1000)); + } + o.get("resets_in_seconds") + .and_then(serde_json::Value::as_u64) + .map(|s| now_ms.saturating_add(s.saturating_mul(1000))) + })?; + (at > now_ms).then_some(at) +} + +#[cfg(test)] +mod tests { + use super::*; + + const NOW: u64 = 1_800_000_000_000; + + fn verdict(status: u16, body: &str) -> Verdict { + classify(status, &HeaderMap::new(), body.as_bytes(), NOW) + } + + fn headers(pairs: &[(&'static str, &str)]) -> HeaderMap { + let mut h = HeaderMap::new(); + for (k, v) in pairs { + h.insert(*k, v.parse().unwrap()); + } + h + } + + #[test] + fn a_plain_bad_request_goes_back_to_the_client() { + // 请求本身有问题,换一家也一样被拒,还白白记在那家账上 + assert_eq!( + verdict( + 400, + r#"{"error":{"type":"invalid_request_error","message":"max_tokens: must be positive"}}"# + ), + Verdict::ClientError + ); + assert_eq!(verdict(413, "too large"), Verdict::ClientError); + } + + #[test] + fn a_missing_balance_is_recognised_whatever_the_status() { + for (status, body) in [ + ( + 400, + r#"{"type":"error","error":{"type":"invalid_request_error","message":"Your credit balance is too low to access the Anthropic API."}}"#, + ), + ( + 429, + r#"{"error":{"code":"insufficient_quota","message":"You exceeded your current quota"}}"#, + ), + (402, r#"{"error":{"message":"Insufficient Balance"}}"#), + (403, r#"{"error":{"code":"Arrearage"}}"#), + ( + 429, + r#"{"error":{"code":"1113","message":"余额不足或无可用资源包"}}"#, + ), + ] { + assert_eq!( + verdict(status, body), + Verdict::Failed(Cause::NoBalance), + "{body}" + ); + } + } + + #[test] + fn a_used_up_quota_waits_for_the_reset_the_upstream_names() { + let body = format!( + r#"{{"error":{{"type":"usage_limit_reached","message":"The usage limit has been reached","resets_at":{}}}}}"#, + NOW / 1000 + 3600 + ); + assert_eq!( + verdict(429, &body), + Verdict::Failed(Cause::QuotaUsedUp { + resets_at_ms: Some(NOW + 3_600_000) + }) + ); + // 只说了还有多少秒 + assert_eq!( + verdict( + 429, + r#"{"error":{"type":"usage_limit_reached","resets_in_seconds":60}}"# + ), + Verdict::Failed(Cause::QuotaUsedUp { + resets_at_ms: Some(NOW + 60_000) + }) + ); + } + + #[test] + fn a_429_with_a_rejected_subscription_window_is_a_used_up_quota() { + // Claude 订阅:正文只说 rate_limit_error,额度头说 5 小时窗口满了 + let h = headers(&[ + ("anthropic-ratelimit-unified-5h-status", "rejected"), + ("anthropic-ratelimit-unified-5h-utilization", "1.0"), + ("anthropic-ratelimit-unified-5h-reset", "7200"), + ]); + assert_eq!( + classify( + 429, + &h, + br#"{"type":"error","error":{"type":"rate_limit_error"}}"#, + NOW + ), + Verdict::Failed(Cause::QuotaUsedUp { + resets_at_ms: Some(NOW + 7_200_000) + }) + ); + } + + #[test] + fn a_rate_limit_takes_retry_after_from_the_header_or_the_body() { + let h = headers(&[("retry-after", "30")]); + assert_eq!( + classify(429, &h, b"{}", NOW), + Verdict::Failed(Cause::RateLimited { + retry_after: Some(Duration::from_secs(30)) + }) + ); + // Gemini 的每分钟限流写着「Quota exceeded」,**不是没钱了** + let gemini = r#"{"error":{"code":429,"message":"Quota exceeded for metric: generate_content_free_tier_requests","status":"RESOURCE_EXHAUSTED","details":[{"@type":"type.googleapis.com/google.rpc.RetryInfo","retryDelay":"33s"}]}}"#; + assert_eq!( + verdict(429, gemini), + Verdict::Failed(Cause::RateLimited { + retry_after: Some(Duration::from_secs(33)) + }) + ); + assert_eq!( + verdict(429, "slow down"), + Verdict::Failed(Cause::RateLimited { retry_after: None }) + ); + } + + #[test] + fn credentials_and_missing_models_move_on() { + assert_eq!( + verdict(401, "invalid x-api-key"), + Verdict::Failed(Cause::AuthRejected) + ); + assert_eq!( + verdict(403, "forbidden"), + Verdict::Failed(Cause::AuthRejected) + ); + assert_eq!(verdict(404, ""), Verdict::Failed(Cause::ModelUnavailable)); + assert_eq!( + verdict( + 400, + r#"{"error":{"code":"model_not_found","message":"The model `x` does not exist"}}"# + ), + Verdict::Failed(Cause::ModelUnavailable) + ); + assert_eq!( + verdict(422, r#"{"detail":"Unsupported model: foo"}"#), + Verdict::Failed(Cause::ModelUnavailable) + ); + } + + #[test] + fn server_errors_are_unexplained_unless_the_body_says_more() { + assert_eq!(verdict(503, "busy"), Verdict::Failed(Cause::Unexplained)); + assert_eq!( + verdict(529, "overloaded"), + Verdict::Failed(Cause::Unexplained) + ); + assert_eq!( + verdict(500, "余额不足"), + Verdict::Failed(Cause::NoBalance), + "有的中转把没钱了报成 500" + ); + } + + #[test] + fn retry_after_reads_an_http_date() { + let at = chrono::DateTime::from_timestamp_millis((NOW + 90_000) as i64) + .unwrap() + .to_rfc2822(); + let h = headers(&[("retry-after", &at)]); + assert_eq!(retry_after(&h, NOW), Some(Duration::from_secs(90))); + } +} diff --git a/crates/tw-gateway/src/health.rs b/crates/tw-gateway/src/health.rs index fb5ebd47..5cdbfe45 100644 --- a/crates/tw-gateway/src/health.rs +++ b/crates/tw-gateway/src/health.rs @@ -3,9 +3,10 @@ //! 状态机是共用的(`tw-breaker`,企业版的路由和 MCP 熔断跑的是同一个), //! 这里是桌面版的**规矩**: //! -//! **只有两个旋钮**:连续失败阈值和冷却时长。cc-switch -//! 那套有五个,其中「错误率 + 最小请求数」这条路径在单用户场景下几乎永远 -//! 打不满 —— 要先攒够十几个请求才生效,而那时用户早就自己发现了。 +//! **停用多久看失败的原因**(见 [`crate::failure`])。上游说了原因的 —— 余额 +//! 不足、额度用完、限流并给了 `Retry-After` —— 一次就停用,停到那个原因该过去 +//! 的时候;说不出原因的(5xx、连不上)连续几次才停,停的时长每次翻倍,成功一次 +//! 就回到起点。几个数都在配置的 `failover` 里。 //! //! 两条硬边界,它们比参数重要得多: //! @@ -15,23 +16,28 @@ //! 2. **只有一个候选时完全旁路熔断器。**否则唯一的上游一旦被自己熔断, //! 就把用户锁死了,熔断纯粹是自伤。 +use std::collections::HashMap; +use std::sync::{Arc, Mutex}; use std::time::Duration; pub use tw_breaker::State; -use tw_breaker::{Breakers, Policy, Trip}; +use tw_breaker::{Breaker, Policy, Tally, Trip}; -/// 连续失败多少次算坏。 -pub const FAILURE_THRESHOLD: u32 = 3; +use crate::failure::Cause; -/// 熔断之后多久放一个探测过去。 -pub const COOLDOWN: Duration = Duration::from_secs(60); +type Clock = Arc i64 + Send + Sync>; -/// 桌面版的规矩:连续失败 3 次打开,冷却 60 秒,一次成功就闭合。 -pub const POLICY: Policy = Policy { - trip: Trip::Consecutive(FAILURE_THRESHOLD), - cooldown: COOLDOWN, - probes: 1, -}; +/// 一家上游记着的东西。 +#[derive(Debug, Clone, Copy, Default)] +struct Entry { + /// 说不出原因的失败走它:连续几次打开,冷却到点放一个探测过去 + breaker: Breaker, + /// 它打开过几次(中间没有成功过)。冷却按它翻倍 + trips: u32, + /// 上游说了原因的停用,到这一刻为止(Unix 毫秒)。**到点了也留着**, + /// 直到下一次成功 —— 报「恢复」的定时器要靠它知道这家曾经停过 + held_until_ms: Option, +} /// 每个 provider 的健康状态。 /// @@ -39,7 +45,10 @@ pub const POLICY: Policy = Policy { /// 意味着用户重启后第一个请求还在被上一次的故障惩罚 —— 而重启本身往往 /// 就是他为了解决问题做的事。 pub struct Health { - breakers: Breakers, + map: Mutex>, + /// 配置里的 `failover`。**跟着配置换**([`Self::configure`]),状态不丢 + settings: Mutex, + clock: Clock, } impl Default for Health { @@ -50,16 +59,69 @@ impl Default for Health { impl Health { pub fn new() -> Self { + Self::with_clock(Arc::new(tw_breaker::now_ms)) + } + + fn with_clock(clock: Clock) -> Self { Self { - breakers: Breakers::new(POLICY), + map: Mutex::new(HashMap::new()), + settings: Mutex::new(tw_config::Failover::default()), + clock, } } - #[cfg(test)] - fn with_clock(clock: std::sync::Arc i64 + Send + Sync>) -> Self { - Self { - breakers: Breakers::with_clock(POLICY, clock), + /// 换一份 `failover` 设置。已经停用着的照旧停着;之后的判断按新的算 + pub fn configure(&self, settings: &tw_config::Failover) { + if let Ok(mut s) = self.settings.lock() { + *s = settings.clone(); + } + } + + fn settings(&self) -> tw_config::Failover { + self.settings.lock().map(|s| s.clone()).unwrap_or_default() + } + + /// 这家此刻的熔断规矩:冷却随它打开过的次数翻倍 + fn policy(settings: &tw_config::Failover, trips: u32) -> Policy { + let doubled = settings + .pause_secs + .saturating_mul(1u64 << trips.saturating_sub(1).min(20)); + Policy { + trip: Trip::Consecutive(settings.failures_to_pause), + cooldown: Duration::from_secs(doubled.min(settings.max_pause_secs)), + probes: 1, + } + } + + fn state_of(e: &Entry, settings: &tw_config::Failover, now: i64) -> State { + if e.held_until_ms.is_some_and(|t| now < t) { + return State::Open; } + e.breaker.state_at(&Self::policy(settings, e.trips), now) + } + + fn entry(&self, name: &str) -> Entry { + self.map + .lock() + .ok() + .and_then(|m| m.get(name).copied()) + .unwrap_or_default() + } + + /// 改一家的记录,返回状态变化(没变是 `None`)。 + fn update( + &self, + name: &str, + f: impl FnOnce(&mut Entry, &tw_config::Failover, i64), + ) -> Option { + let settings = self.settings(); + let now = (self.clock)(); + let mut map = self.map.lock().ok()?; + let e = map.entry(name.to_string()).or_default(); + let before = Self::state_of(e, &settings, now); + f(e, &settings, now); + let after = Self::state_of(e, &settings, now); + (after != before).then_some(after) } /// 这家现在能进候选链吗。冷却到点的算半开,放行。 @@ -67,11 +129,11 @@ impl Health { /// **和「能不能收一个探测请求」是两件事**:只看不改,光是排候选顺序 /// 不该把半开状态的探测机会用掉。 pub fn is_available(&self, name: &str) -> bool { - self.breakers.admits(&name.to_string()) + self.state(name) != State::Open } pub fn state(&self, name: &str) -> State { - self.breakers.state(&name.to_string()) + Self::state_of(&self.entry(name), &self.settings(), (self.clock)()) } /// 记一次成功。**返回的是状态变化,没变就是 `None`。** @@ -79,19 +141,71 @@ impl Health { /// 调用方要拿它去发事件:熔断开合是界面上看得见的状态,而看得见的 /// 状态必须能被推出去 —— 否则界面只能轮询。 pub fn record_success(&self, name: &str) -> Option { - self.breakers.record(&name.to_string(), true) + self.update(name, |e, s, now| { + e.breaker + .record(true, Tally::default(), &Self::policy(s, e.trips), now); + e.trips = 0; + e.held_until_ms = None; + }) } - /// 记一次失败,同样返回状态变化。 + /// 记一次说不出原因的失败,同样返回状态变化。 pub fn record_failure(&self, name: &str) -> Option { - self.breakers.record(&name.to_string(), false) + self.update(name, |e, s, now| { + let policy = Self::policy(s, e.trips); + let before = e.breaker.state_at(&policy, now); + e.breaker.record(false, Tally::default(), &policy, now); + // 这一次打开了(或者探测失败又打开了):下一段冷却翻倍。 + // 已经开着、冷却还没到时又失败的(只有一家候选时会这样)不算新的一次 + if before != State::Open && e.breaker.state == State::Open { + e.trips = e.trips.saturating_add(1); + } + }) + } + + /// 记一次失败,按原因停用。返回状态变化。 + pub fn record_cause(&self, name: &str, cause: Cause) -> Option { + let s = self.settings(); + let now = (self.clock)(); + let secs = + |n: u64| now.saturating_add(i64::try_from(n.saturating_mul(1000)).unwrap_or(i64::MAX)); + let until = match cause { + Cause::ModelUnavailable => return None, + Cause::NoBalance => secs(s.no_balance_pause_secs), + Cause::QuotaUsedUp { resets_at_ms } => resets_at_ms + .and_then(|t| i64::try_from(t).ok()) + .filter(|t| *t > now) + .unwrap_or_else(|| secs(s.quota_pause_secs)), + Cause::RateLimited { + retry_after: Some(d), + } if !d.is_zero() => secs(d.as_secs().max(1).min(s.rate_limit_max_pause_secs)), + Cause::RateLimited { .. } | Cause::AuthRejected | Cause::Unexplained => { + return self.record_failure(name); + } + }; + self.update(name, |e, _, _| { + e.held_until_ms = Some(e.held_until_ms.map_or(until, |t| t.max(until))); + }) } - /// 这家还要等多久才轮到探测。见 [`tw_breaker::Breaker::cooldown_left`]。 + /// 这家还要等多久才轮到探测。 + /// + /// `None`:没停用过(或者停用之后已经成功过)。`Some(0)`:到点了。 /// /// **专门给「报一条恢复」的定时器用。** pub fn cooldown_left(&self, name: &str) -> Option { - self.breakers.cooldown_left(&name.to_string()) + let e = self.entry(name); + let now = (self.clock)(); + let held = e + .held_until_ms + .map(|t| Duration::from_millis(u64::try_from(t.saturating_sub(now)).unwrap_or(0))); + let breaker = e + .breaker + .cooldown_left(&Self::policy(&self.settings(), e.trips), now); + match (held, breaker) { + (Some(a), Some(b)) => Some(a.max(b)), + (a, b) => a.or(b), + } } /// 从候选里挑出还能用的,**并说明是不是 fail-open**。 @@ -276,11 +390,119 @@ mod tests { h.record_failure("a"); } assert!(!h.is_available("a")); - now.store(COOLDOWN.as_millis() as i64, Ordering::SeqCst); + now.store(60_000, 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")); } + + fn clocked() -> (Health, std::sync::Arc) { + let now = std::sync::Arc::new(std::sync::atomic::AtomicI64::new(1_000_000)); + let h = Health::with_clock({ + let now = now.clone(); + std::sync::Arc::new(move || now.load(std::sync::atomic::Ordering::SeqCst)) + }); + (h, now) + } + + fn advance(now: &std::sync::atomic::AtomicI64, ms: i64) { + now.fetch_add(ms, std::sync::atomic::Ordering::SeqCst); + } + + #[test] + fn each_further_pause_doubles_until_the_ceiling_and_a_success_resets_it() { + let (h, now) = clocked(); + for _ in 0..3 { + h.record_failure("a"); + } + assert_eq!(h.cooldown_left("a"), Some(Duration::from_secs(60))); + // 探测又失败:第二段 120 秒 + advance(&now, 60_000); + assert_eq!(h.record_failure("a"), Some(State::Open)); + assert_eq!(h.cooldown_left("a"), Some(Duration::from_secs(120))); + advance(&now, 120_000); + h.record_failure("a"); + assert_eq!(h.cooldown_left("a"), Some(Duration::from_secs(240))); + advance(&now, 240_000); + h.record_failure("a"); + advance(&now, 480_000); + h.record_failure("a"); + assert_eq!( + h.cooldown_left("a"), + Some(Duration::from_secs(600)), + "封顶在 max_pause_secs" + ); + // 成功一次,下次打开又从 60 秒起 + advance(&now, 600_000); + h.record_success("a"); + for _ in 0..3 { + h.record_failure("a"); + } + assert_eq!(h.cooldown_left("a"), Some(Duration::from_secs(60))); + } + + #[test] + fn a_stated_reason_sets_the_upstream_aside_at_once_for_as_long_as_it_says() { + let (h, now) = clocked(); + assert_eq!(h.record_cause("a", Cause::NoBalance), Some(State::Open)); + assert_eq!(h.cooldown_left("a"), Some(Duration::from_secs(1800))); + + let reset = 1_000_000 + 5 * 3_600_000; + h.record_cause( + "b", + Cause::QuotaUsedUp { + resets_at_ms: Some(reset as u64), + }, + ); + assert_eq!(h.cooldown_left("b"), Some(Duration::from_secs(5 * 3600))); + h.record_cause("c", Cause::QuotaUsedUp { resets_at_ms: None }); + assert_eq!(h.cooldown_left("c"), Some(Duration::from_secs(3600))); + + // Retry-After 太长的按上限 + h.record_cause( + "d", + Cause::RateLimited { + retry_after: Some(Duration::from_secs(99_999)), + }, + ); + assert_eq!(h.cooldown_left("d"), Some(Duration::from_secs(3600))); + + // 到点了:能用,定时器看到 0;成功之后什么都不记得 + advance(&now, 1_800_000); + assert!(h.is_available("a")); + assert_eq!(h.cooldown_left("a"), Some(Duration::ZERO)); + h.record_success("a"); + assert_eq!(h.cooldown_left("a"), None); + } + + #[test] + fn a_missing_model_or_an_unstated_rate_limit_does_not_set_it_aside_at_once() { + let (h, _) = clocked(); + assert_eq!(h.record_cause("a", Cause::ModelUnavailable), None); + assert!(h.is_available("a")); + // 没说多久的限流按说不出原因的失败算:连续三次才停 + for _ in 0..2 { + h.record_cause("b", Cause::RateLimited { retry_after: None }); + } + assert!(h.is_available("b")); + h.record_cause("b", Cause::Unexplained); + assert!(!h.is_available("b")); + } + + #[test] + fn the_settings_come_from_the_configuration() { + let (h, _) = clocked(); + h.configure(&tw_config::Failover { + failures_to_pause: 1, + pause_secs: 5, + no_balance_pause_secs: 7, + ..Default::default() + }); + assert_eq!(h.record_failure("a"), Some(State::Open), "一次就停"); + assert_eq!(h.cooldown_left("a"), Some(Duration::from_secs(5))); + h.record_cause("b", Cause::NoBalance); + assert_eq!(h.cooldown_left("b"), Some(Duration::from_secs(7))); + } } diff --git a/crates/tw-gateway/src/lib.rs b/crates/tw-gateway/src/lib.rs index f7b25860..d39d3220 100644 --- a/crates/tw-gateway/src/lib.rs +++ b/crates/tw-gateway/src/lib.rs @@ -17,6 +17,7 @@ pub mod count; pub mod egress; pub mod ending; pub mod error; +pub mod failure; pub mod fixture; pub mod forward; pub mod glm; diff --git a/crates/tw-gateway/src/server.rs b/crates/tw-gateway/src/server.rs index 0f5cc226..8234bf8c 100644 --- a/crates/tw-gateway/src/server.rs +++ b/crates/tw-gateway/src/server.rs @@ -229,7 +229,7 @@ fn note_health( } let (bus, health, name) = (bus.clone(), health.clone(), provider.to_string()); tokio::spawn(async move { - let mut left = crate::health::COOLDOWN; + let mut left = health.cooldown_left(&name).unwrap_or_default(); loop { tokio::time::sleep(left).await; match health.cooldown_left(&name) { diff --git a/crates/tw-gateway/src/server/pipeline.rs b/crates/tw-gateway/src/server/pipeline.rs index 17725304..fd79ee61 100644 --- a/crates/tw-gateway/src/server/pipeline.rs +++ b/crates/tw-gateway/src/server/pipeline.rs @@ -21,6 +21,7 @@ use crate::state::{AppState, Runtime}; use tw_types::msg; mod hop; +mod opening; mod relay; /// 256 MiB。大到能装下几张 4K 图的 base64(膨胀 33%),小到失控的 diff --git a/crates/tw-gateway/src/server/pipeline/hop.rs b/crates/tw-gateway/src/server/pipeline/hop.rs index a927a243..2af55cb4 100644 --- a/crates/tw-gateway/src/server/pipeline/hop.rs +++ b/crates/tw-gateway/src/server/pipeline/hop.rs @@ -10,6 +10,7 @@ use bytes::Bytes; use super::{Inbound, Started}; use crate::error::GatewayError; +use crate::failure::{Cause, Verdict}; use crate::forward; use crate::server::{hop, hop_failed, note_health}; use crate::state::{AppState, Runtime}; @@ -82,7 +83,9 @@ pub(super) async fn try_upstreams<'a>( // 不再试下一家的原因:第二阶段拒绝了,或者规则求不了值。**路由事件照样要发** let mut halt: Option = None; - for name in &started.alive { + for (i, name) in started.alive.iter().enumerate() { + // 后面没有别的候选了 + let last = i + 1 == started.alive.len(); let Some(provider) = rt.config.providers.iter().find(|p| &p.name == name) else { // 校验时挡过一次,能到这儿说明配置在运行中被换过。 last_err = Some(GatewayError::config(msg!( @@ -288,53 +291,185 @@ pub(super) async fn try_upstreams<'a>( Err(e) => Err(e), }; match sent { - 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)—— 请求本身有问题的话,换一家 - // 也一样被拒,还会白白污染那家的健康度。 - note_health( - &state.bus, - &state.health, - &provider.name, - state.health.record_failure(&provider.name), - ); - chain.push(hop( - &provider.name, - model.clone(), - tw_api::AttemptOutcome::Status, - r.status().as_u16(), - hop_started, - )); - // **429 要保住 429。**塌成 502 的话,客户端会当成「服务器 - // 坏了」而不是「该退避了」,而它们该做的事完全不同。 - last_err = Some(if r.status() == 429 { - GatewayError::rate_limited(msg!( - "gw.upstream.rate_limited", upstream = provider.name.clone() => - "Upstream `{upstream}` rate-limited the request." - )) - } else { - GatewayError::upstream(msg!( - "gw.upstream.status", upstream = provider.name.clone(), status = r.status().as_u16() => - "Upstream `{upstream}` answered {status}." - )) - }); + Ok(r) if !r.status().is_success() => { + let status = r.status().as_u16(); + // 同格式的上游没实现数 token(不少中转只做了生成回答):网关自己估。 + // **在判断换不换之前**:404 平时是「这家没有这个模型」,要换下一家 + if counting && crate::count::unsupported(status) { + note_health( + &state.bus, + &state.health, + &provider.name, + state.health.record_success(&provider.name), + ); + chain.push(estimated_hop( + provider, + model.clone(), + Some(status), + hop_started, + )); + estimated = Some(provider); + break; + } + let headers = r.headers().clone(); + let (head, r) = peek_body(r).await; // GLM Coding Plan 的额度用完不在响应头里,在 429 的 body 里 - if r.status() == 429 { - state.note_glm_429(id, provider, r).await; + if status == 429 { + state.note_glm_429_body(id, provider, &head); + } + let verdict = crate::failure::classify(status, &headers, &head, now_ms()); + // **最后一家的 4xx 交给客户端**:没有下一家可换了,上游自己的原话 + // (「invalid x-api-key」)比我们转述的一句「回了 401」有用得多。 + // 5xx 和 429 照旧报我们的话,带着尝试链 + let hand_on = last && status < 500 && status != 429; + match verdict { + Verdict::Failed(cause) if !hand_on => { + // 5xx、限流、没钱了、额度用完、凭据被拒、没有这个模型:换一家有 + // 意义,那边是另一把密钥、另一个账户。停用多久看原因。 + // + // 交给客户端的那一跳,下面这几样由回程(`relay`)去记 + // + // 额度用完时上游回的正是 429,这一跳的额度头也要读 + state.note_quota(id, &provider.name, &headers); + // 上游回了话,说明代理是通的 + state.note_proxy_ok(&provider.proxy); + state.glm_traffic(provider); + // 凭据被拒是要让用户知道的状态,**换了下一家也一样** + state.note_auth(&provider.name, status); + let cause = known_reset(state, &provider.name, cause); + note_health( + &state.bus, + &state.health, + &provider.name, + state.health.record_cause(&provider.name, cause), + ); + chain.push(hop( + &provider.name, + model.clone(), + tw_api::AttemptOutcome::Status, + status, + hop_started, + )); + // **429 要保住 429。**塌成 502 的话,客户端会当成「服务器 + // 坏了」而不是「该退避了」,而它们该做的事完全不同。 + last_err = Some(if status == 429 { + GatewayError::rate_limited(msg!( + "gw.upstream.rate_limited", upstream = provider.name.clone() => + "Upstream `{upstream}` rate-limited the request." + )) + } else { + GatewayError::upstream(msg!( + "gw.upstream.status", upstream = provider.name.clone(), status = status => + "Upstream `{upstream}` answered {status}." + )) + }); + continue; + } + verdict => { + // 请求本身的问题(换一家也一样被拒),或者最后一家的 4xx:原样交出去 + let change = match verdict { + Verdict::Failed(cause) => state.health.record_cause( + &provider.name, + known_reset(state, &provider.name, cause), + ), + Verdict::ClientError => state.health.record_success(&provider.name), + }; + note_health(&state.bus, &state.health, &provider.name, change); + // Bedrock 拒绝凭证时的原话会点名账号和 IAM 身份:换成我们自己的话再交出去 + let r = if provider.is_bedrock() && matches!(status, 401 | 403) { + bedrock_refusal(provider, r).await + } else { + r + }; + chain.push(hop( + &provider.name, + model.clone(), + tw_api::AttemptOutcome::Served, + status, + hop_started, + )); + served = Some(Served { + upstream: r, + provider, + ledger, + session: out.session, + }); + break; + } } - state.glm_traffic(provider); - continue; } Ok(r) => { - // Bedrock 拒绝凭证时的原话会点名账号和 IAM 身份:换成我们自己的话再交出去 - let r = if provider.is_bedrock() && matches!(r.status().as_u16(), 401 | 403) { - bedrock_refusal(provider, r).await - } else { - r + // 流式回答:**第一段内容到之前**上游在流里报的错,照样换下一家(见 + // `opening`)。最后一家不等 —— 没有下一家可换,等只会让客户端晚一点 + // 看到同一个错误 + let r = match opening_of(req, provider, &out, &r).filter(|_| !last) { + None => r, + Some((dialect, eventstream)) => { + let wait = std::time::Duration::from_secs( + rt.config.failover.stream_start_wait_secs, + ); + match super::opening::watch(r, dialect, eventstream, wait).await { + super::opening::Opening::Go(r) => r, + super::opening::Opening::Failed { + status, + headers, + body, + kind, + message, + response, + } => { + match crate::failure::classify(status, &headers, &body, now_ms()) { + Verdict::ClientError => response, + Verdict::Failed(cause) => { + state.note_quota(id, &provider.name, &headers); + state.note_proxy_ok(&provider.proxy); + let cause = known_reset(state, &provider.name, cause); + note_health( + &state.bus, + &state.health, + &provider.name, + state.health.record_cause(&provider.name, cause), + ); + let said = msg!( + "gw.upstream.stream_opening_error", + upstream = provider.name.clone(), kind = kind, message = message => + "Upstream `{upstream}` started the answer and reported an error \ + before any content ({kind}): {message}" + ); + let err = if status == 429 { + GatewayError::rate_limited(said) + } else { + GatewayError::upstream(said) + }; + chain.push(hop_failed( + &provider.name, + model.clone(), + err.detail.clone(), + hop_started, + )); + last_err = Some(err); + continue; + } + } + } + super::opening::Opening::Broken(err) => { + note_health( + &state.bus, + &state.health, + &provider.name, + state.health.record_failure(&provider.name), + ); + chain.push(hop_failed( + &provider.name, + model.clone(), + err.detail.clone(), + hop_started, + )); + last_err = Some(err); + continue; + } + } + } }; note_health( &state.bus, @@ -342,17 +477,6 @@ pub(super) async fn try_upstreams<'a>( &provider.name, state.health.record_success(&provider.name), ); - // 同格式的上游没实现数 token(不少中转只做了生成回答):网关自己估 - if counting && crate::count::unsupported(r.status().as_u16()) { - chain.push(estimated_hop( - provider, - model.clone(), - Some(r.status().as_u16()), - hop_started, - )); - estimated = Some(provider); - break; - } chain.push(hop( &provider.name, model.clone(), @@ -1080,3 +1204,80 @@ async fn bedrock_refusal( ); reqwest::Response::from(resp) } + +/// 读错误响应的开头(最多 [`crate::failure::BODY_PEEK`]),交回读到的和一个照旧能从头 +/// 读起的响应 —— 这一跳可能还是要原样交给客户端的。 +async fn peek_body(r: reqwest::Response) -> (Bytes, reqwest::Response) { + use futures::StreamExt; + let status = r.status(); + let headers = r.headers().clone(); + let mut stream = r.bytes_stream(); + let mut held: Vec = Vec::new(); + let mut size = 0usize; + // 错误正文都很短。**读不完就算了**:这一跳多半已经失败了,读它只为认出原因, + // 不能因此拖住下一家 + let deadline = tokio::time::Instant::now() + std::time::Duration::from_secs(2); + while size < crate::failure::BODY_PEEK { + match tokio::time::timeout_at(deadline, stream.next()).await { + Ok(Some(Ok(chunk))) => { + size += chunk.len(); + held.push(chunk); + } + _ => break, + } + } + let head: Vec = held.iter().flat_map(|c| c.iter().copied()).collect(); + let replay = futures::stream::iter(held.into_iter().map(Ok::<_, reqwest::Error>)); + let mut resp = http::Response::new(reqwest::Body::wrap_stream(replay.chain(stream))); + *resp.status_mut() = status; + *resp.headers_mut() = headers; + let head = Bytes::from(head); + (head, reqwest::Response::from(resp)) +} + +/// 额度用完、这一跳又没说什么时候重置的:看这家最近报的额度窗口(GLM 的在 429 的 +/// 正文里读过了,别家的在响应头里)。满了的窗口里取**最晚**重置的那个 +fn known_reset(state: &AppState, provider: &str, cause: Cause) -> Cause { + let Cause::QuotaUsedUp { resets_at_ms: None } = cause else { + return cause; + }; + let now = now_ms(); + let resets_at_ms = state.quotas().get(provider).and_then(|q| { + q.windows + .iter() + .filter(|w| w.rejected() || w.used_percent >= 100.0) + .filter_map(|w| w.resets_at_ms) + .filter(|t| *t > now) + .max() + }); + Cause::QuotaUsedUp { resets_at_ms } +} + +/// 这个回答要不要等开头:生成回答的流式响应才等。等的话,上游说的是哪种格式、 +/// 是不是 Bedrock 的二进制帧 +fn opening_of( + req: &Inbound, + provider: &tw_config::Provider, + out: &Outbound, + r: &reqwest::Response, +) -> Option<(tw_dialect::ir::Dialect, bool)> { + if !r.status().is_success() { + return None; + } + let ct = r + .headers() + .get(http::header::CONTENT_TYPE) + .and_then(|v| v.to_str().ok()) + .unwrap_or_default(); + let eventstream = + provider.is_bedrock() && ct.starts_with(tw_bedrock::eventstream::CONTENT_TYPE); + if !(eventstream || ct.starts_with("text/event-stream")) { + return None; + } + let dialect = out.target.or_else(|| req.api.map(|a| a.dialect()))?; + Some((dialect, eventstream)) +} + +fn now_ms() -> u64 { + u64::try_from(tw_breaker::now_ms()).unwrap_or(0) +} diff --git a/crates/tw-gateway/src/server/pipeline/opening.rs b/crates/tw-gateway/src/server/pipeline/opening.rs new file mode 100644 index 00000000..f8cd4ae3 --- /dev/null +++ b/crates/tw-gateway/src/server/pipeline/opening.rs @@ -0,0 +1,473 @@ +//! 流式回答的开头:**第一段内容到达之前,上游在流里报的错误照样换下一家。** +//! +//! 上游回了 200、流也开了,之后第一个事件却是错误 —— Anthropic 过载时的 +//! `overloaded_error`、Codex 额度用完时的 `response.failed`、Bedrock 的 +//! `throttlingException`。这时客户端还什么都没收到,换一家它完全无感;等到 +//! 错误帧写给了客户端,就只能让它自己重试了。 +//! +//! 所以响应头到手之后先不转发:把流读到第一段内容为止,读到的字节原样留着。 +//! 期间是错误就换下一家;是内容,就把留着的字节和后面的流接在一起交出去 —— +//! 客户端收到的和直接转发一个字节都不差。 +//! +//! 等待有上限(配置的 `failover.stream_start_wait_secs`,以及 [`HOLD_LIMIT`]): +//! 上游迟迟不出内容时不能一直压着,那样客户端看到的就是一个卡住的请求。 + +use std::time::Duration; + +use bytes::Bytes; +use futures::StreamExt; + +use crate::error::GatewayError; +use tw_dialect::ir::Dialect; + +/// 开头最多压多少字节。前导事件都很小,攒到这么多还没有内容,就不是在等开头了 +pub(super) const HOLD_LIMIT: usize = 1024 * 1024; + +/// 流开头的结论。 +pub(super) enum Opening { + /// 内容来了(或者等够了、流结束了):交给客户端。读过的字节已经接回去了 + Go(reqwest::Response), + /// 第一段内容之前上游报了错。`status` 是这个错误对应的状态码,`body` 是 + /// 上游的原话,交给 [`crate::failure::classify`] 判断换不换。 + /// + /// **读过的字节也还在 `response` 里**:判断下来是请求本身的问题(换一家也一样 + /// 被拒)时,照常把它交给客户端 + Failed { + status: u16, + headers: http::HeaderMap, + body: Bytes, + kind: String, + message: String, + response: reqwest::Response, + }, + /// 流在第一段内容之前断了 + Broken(GatewayError), +} + +/// 读到第一段内容为止。`dialect` 是上游说的格式,`eventstream` 表示流是 Bedrock +/// 的二进制帧。 +pub(super) async fn watch( + r: reqwest::Response, + dialect: Dialect, + eventstream: bool, + wait: Duration, +) -> Opening { + let status = r.status(); + let headers = r.headers().clone(); + let mut stream = r.bytes_stream(); + let mut held: Vec = Vec::new(); + let mut size = 0usize; + let mut sse = Sse::default(); + let mut unframe = eventstream.then(tw_bedrock::eventstream::Transcoder::new); + let deadline = tokio::time::Instant::now() + wait; + + let verdict = loop { + let next = match tokio::time::timeout_at(deadline, stream.next()).await { + Ok(next) => next, + Err(_) => break Judge::Content, + }; + let chunk = match next { + None => break Judge::Content, + Some(Ok(c)) => c, + Some(Err(e)) => { + return Opening::Broken(crate::forward::map_reqwest_error(e)); + } + }; + size += chunk.len(); + held.push(chunk.clone()); + let text = match unframe.as_mut() { + None => chunk.to_vec(), + Some(t) => match t.feed(&chunk) { + Ok(sse) => sse, + Err(tw_bedrock::eventstream::StreamError::Upstream { kind, message }) => { + break bedrock_exception(kind, message); + } + // 帧坏了:交给转发那一边照常报 + Err(_) => break Judge::Content, + }, + }; + let judged = sse + .feed(&text) + .into_iter() + .map(|(event, data)| judge(dialect, event.as_deref(), &data)) + .find(|j| !matches!(j, Judge::Preamble)); + if let Some(j) = judged { + break j; + } + if size >= HOLD_LIMIT { + break Judge::Content; + } + }; + + // 读过的字节接回流的前面,交出去的和上游发的一个字节都不差 + let replay = futures::stream::iter(held.into_iter().map(Ok::<_, reqwest::Error>)); + let mut resp = http::Response::new(reqwest::Body::wrap_stream(replay.chain(stream))); + *resp.status_mut() = status; + *resp.headers_mut() = headers.clone(); + let response = reqwest::Response::from(resp); + match verdict { + Judge::Error { + status, + body, + kind, + message, + } => Opening::Failed { + status, + headers, + body, + kind, + message, + response, + }, + Judge::Content | Judge::Preamble => Opening::Go(response), + } +} + +/// 一个事件是什么。 +#[derive(Debug, PartialEq)] +enum Judge { + /// 开头的例行事件(`message_start`、`response.created`、心跳):接着等 + Preamble, + /// 内容,或者认不出来的东西:**认不出来的一律当内容** —— 放行最多是没能 + /// 换一家,拦错了却会把好好的回答扔掉 + Content, + Error { + status: u16, + body: Bytes, + kind: String, + message: String, + }, +} + +/// 看一个 SSE 事件。 +fn judge(dialect: Dialect, event: Option<&str>, data: &str) -> Judge { + let data = data.trim(); + if data.is_empty() { + return Judge::Preamble; + } + if data == "[DONE]" { + return Judge::Content; + } + let Ok(v) = serde_json::from_str::(data) else { + return Judge::Content; + }; + let ty = event + .map(str::to_string) + .or_else(|| v.get("type").and_then(|t| t.as_str()).map(str::to_string)) + .unwrap_or_default(); + match dialect { + Dialect::Anthropic => match ty.as_str() { + "message_start" | "ping" => Judge::Preamble, + "error" => { + let e = v.get("error").unwrap_or(&v); + let kind = text_of(e, "type"); + error(anthropic_status(&kind), data, kind, text_of(e, "message")) + } + _ => Judge::Content, + }, + Dialect::Responses => match ty.as_str() { + "response.created" | "response.in_progress" | "response.queued" => Judge::Preamble, + // Codex 后端在开头报一次额度,不是回答 + t if t.starts_with("codex.") => Judge::Preamble, + "response.failed" => { + let e = v.pointer("/response/error").unwrap_or(&v); + let kind = text_of(e, "code"); + error(openai_status(&kind), data, kind, text_of(e, "message")) + } + "error" => { + let e = v.get("error").unwrap_or(&v); + let kind = Some(text_of(e, "code")) + .filter(|c| !c.is_empty()) + .unwrap_or_else(|| text_of(e, "type")); + error(openai_status(&kind), data, kind, text_of(e, "message")) + } + _ => Judge::Content, + }, + Dialect::Chat => { + if let Some(e) = v.get("error") { + let kind = Some(text_of(e, "code")) + .filter(|c| !c.is_empty()) + .unwrap_or_else(|| text_of(e, "type")); + let status = e + .get("code") + .and_then(|c| c.as_u64()) + .and_then(|c| u16::try_from(c).ok()) + .filter(|c| (400..600).contains(c)) + .unwrap_or_else(|| openai_status(&kind)); + return error(status, data, kind, text_of(e, "message")); + } + // 只有角色、没有内容的第一块(多数兼容接口都先发这么一块)还不算内容 + let delta = v.pointer("/choices/0/delta"); + let finished = v + .pointer("/choices/0/finish_reason") + .is_some_and(|f| !f.is_null()); + let said = delta.is_some_and(|d| { + ["content", "reasoning_content", "reasoning", "tool_calls"] + .iter() + .any(|k| d.get(*k).is_some_and(|x| !x.is_null() && x != "")) + }); + let usage_only = v.get("usage").is_some_and(|u| !u.is_null()) + && v.get("choices") + .and_then(|c| c.as_array()) + .is_none_or(|c| c.is_empty()); + if said || finished || usage_only { + Judge::Content + } else { + Judge::Preamble + } + } + Dialect::Gemini => match v.get("error") { + Some(e) => { + let status = e + .get("code") + .and_then(|c| c.as_u64()) + .and_then(|c| u16::try_from(c).ok()) + .unwrap_or(500); + error(status, data, text_of(e, "status"), text_of(e, "message")) + } + None => Judge::Content, + }, + Dialect::Bedrock => match ty.as_str() { + "messageStart" => Judge::Preamble, + _ => Judge::Content, + }, + } +} + +fn error(status: u16, data: &str, kind: String, message: String) -> Judge { + Judge::Error { + status, + body: Bytes::copy_from_slice(data.as_bytes()), + kind, + message, + } +} + +fn text_of(v: &serde_json::Value, key: &str) -> String { + v.get(key) + .and_then(|x| x.as_str()) + .unwrap_or_default() + .to_string() +} + +/// Anthropic 错误类型对应的状态码(它的文档里一一对应) +fn anthropic_status(kind: &str) -> u16 { + match kind { + "invalid_request_error" => 400, + "authentication_error" => 401, + "billing_error" => 402, + "permission_error" => 403, + "not_found_error" => 404, + "request_too_large" => 413, + "rate_limit_error" => 429, + "timeout_error" => 504, + "overloaded_error" => 529, + _ => 500, + } +} + +/// OpenAI 在流里报的错误码对应的状态码 +fn openai_status(code: &str) -> u16 { + match code { + "rate_limit_exceeded" | "insufficient_quota" | "usage_limit_reached" => 429, + "invalid_prompt" | "context_length_exceeded" | "invalid_request_error" => 400, + "server_is_overloaded" | "slow_down" => 503, + _ => 500, + } +} + +fn bedrock_exception(kind: String, message: String) -> Judge { + let status = match kind.as_str() { + "throttlingException" => 429, + "serviceUnavailableException" => 503, + "validationException" => 400, + "accessDeniedException" => 403, + "modelTimeoutException" => 504, + _ => 500, + }; + let body = serde_json::json!({ "message": message }).to_string(); + Judge::Error { + status, + body: Bytes::from(body), + kind, + message, + } +} + +/// 从字节里拆 SSE 事件:`(event 名, data)`。一个事件没收齐时留着等下一块。 +#[derive(Default)] +struct Sse { + buf: String, +} + +impl Sse { + fn feed(&mut self, bytes: &[u8]) -> Vec<(Option, String)> { + self.buf.push_str(&String::from_utf8_lossy(bytes)); + let mut out = Vec::new(); + loop { + let normalized = self.buf.replace("\r\n", "\n"); + let Some(end) = normalized.find("\n\n") else { + self.buf = normalized; + break; + }; + let block = normalized[..end].to_string(); + self.buf = normalized[end + 2..].to_string(); + let mut event = None; + let mut data = Vec::new(); + for line in block.lines() { + if let Some(v) = line.strip_prefix("event:") { + event = Some(v.trim().to_string()); + } else if let Some(v) = line.strip_prefix("data:") { + data.push(v.strip_prefix(' ').unwrap_or(v).to_string()); + } + } + // 只有注释(`: keep-alive`)的块什么都不是 + if event.is_some() || !data.is_empty() { + out.push((event, data.join("\n"))); + } + } + out + } +} + +#[cfg(test)] +mod tests { + use super::*; + + fn events(text: &str) -> Vec<(Option, String)> { + Sse::default().feed(text.as_bytes()) + } + + fn first_verdict(dialect: Dialect, text: &str) -> Option { + events(text) + .into_iter() + .map(|(e, d)| judge(dialect, e.as_deref(), &d)) + .find(|j| !matches!(j, Judge::Preamble)) + } + + #[test] + fn events_split_across_chunks_are_put_back_together() { + let mut sse = Sse::default(); + assert!(sse.feed(b"event: ping\ndata: {\"ty").is_empty()); + let got = sse.feed(b"pe\":\"ping\"}\r\n\r\n: keep-alive\n\n"); + assert_eq!( + got, + vec![(Some("ping".into()), r#"{"type":"ping"}"#.into())] + ); + } + + #[test] + fn anthropic_overloaded_before_content_is_a_529() { + let text = "event: message_start\ndata: {\"type\":\"message_start\",\"message\":{}}\n\n\ + event: ping\ndata: {\"type\":\"ping\"}\n\n\ + event: error\ndata: {\"type\":\"error\",\"error\":{\"type\":\"overloaded_error\",\"message\":\"Overloaded\"}}\n\n"; + match first_verdict(Dialect::Anthropic, text) { + Some(Judge::Error { + status, + kind, + message, + .. + }) => { + assert_eq!(status, 529); + assert_eq!(kind, "overloaded_error"); + assert_eq!(message, "Overloaded"); + } + other => panic!("{other:?}"), + } + } + + #[test] + fn anthropic_content_ends_the_wait() { + let text = "event: message_start\ndata: {\"type\":\"message_start\"}\n\n\ + event: content_block_start\ndata: {\"type\":\"content_block_start\"}\n\n"; + assert_eq!( + first_verdict(Dialect::Anthropic, text), + Some(Judge::Content) + ); + } + + #[test] + fn codex_usage_limit_in_the_stream_is_a_429() { + let text = "event: response.created\ndata: {\"type\":\"response.created\"}\n\n\ + event: codex.rate_limits\ndata: {\"type\":\"codex.rate_limits\"}\n\n\ + event: response.failed\ndata: {\"type\":\"response.failed\",\"response\":{\"error\":{\"code\":\"usage_limit_reached\",\"message\":\"The usage limit has been reached\"}}}\n\n"; + match first_verdict(Dialect::Responses, text) { + Some(Judge::Error { status, kind, .. }) => { + assert_eq!(status, 429); + assert_eq!(kind, "usage_limit_reached"); + } + other => panic!("{other:?}"), + } + } + + #[test] + fn a_chat_role_chunk_is_not_content_but_text_is() { + let role = + "data: {\"choices\":[{\"delta\":{\"role\":\"assistant\",\"content\":\"\"}}]}\n\n"; + assert_eq!(first_verdict(Dialect::Chat, role), None); + let text = "data: {\"choices\":[{\"delta\":{\"content\":\"Hi\"}}]}\n\n"; + assert_eq!(first_verdict(Dialect::Chat, text), Some(Judge::Content)); + let err = "data: {\"error\":{\"code\":429,\"message\":\"busy\"}}\n\n"; + assert!(matches!( + first_verdict(Dialect::Chat, err), + Some(Judge::Error { status: 429, .. }) + )); + } + + #[test] + fn a_gemini_error_carries_its_http_code() { + let err = "data: {\"error\":{\"code\":503,\"status\":\"UNAVAILABLE\",\"message\":\"overloaded\"}}\n\n"; + assert!(matches!( + first_verdict(Dialect::Gemini, err), + Some(Judge::Error { status: 503, .. }) + )); + } + + #[test] + fn something_unrecognised_counts_as_content() { + assert_eq!( + first_verdict(Dialect::Anthropic, "data: not json\n\n"), + Some(Judge::Content) + ); + } + + async fn served(body: &'static str) -> reqwest::Response { + let mut resp = http::Response::new(reqwest::Body::from(body)); + resp.headers_mut().insert( + http::header::CONTENT_TYPE, + http::HeaderValue::from_static("text/event-stream"), + ); + reqwest::Response::from(resp) + } + + #[tokio::test] + async fn what_was_read_is_handed_on_byte_for_byte() { + let body = "event: message_start\ndata: {\"type\":\"message_start\"}\n\n\ + event: content_block_delta\ndata: {\"type\":\"content_block_delta\"}\n\n\ + event: message_stop\ndata: {\"type\":\"message_stop\"}\n\n"; + let r = served(body).await; + match watch(r, Dialect::Anthropic, false, Duration::from_secs(5)).await { + Opening::Go(r) => { + assert_eq!(r.headers()[http::header::CONTENT_TYPE], "text/event-stream"); + assert_eq!(r.text().await.unwrap(), body); + } + _ => panic!("该放行"), + } + } + + #[tokio::test] + async fn an_error_before_content_is_reported_not_handed_on() { + let body = "event: error\ndata: {\"type\":\"error\",\"error\":{\"type\":\"rate_limit_error\",\"message\":\"slow\"}}\n\n"; + match watch( + served(body).await, + Dialect::Anthropic, + false, + Duration::from_secs(5), + ) + .await + { + Opening::Failed { status, .. } => assert_eq!(status, 429), + _ => panic!("该报失败"), + } + } +} diff --git a/crates/tw-gateway/src/state.rs b/crates/tw-gateway/src/state.rs index 3f27290b..82278eac 100644 --- a/crates/tw-gateway/src/state.rs +++ b/crates/tw-gateway/src/state.rs @@ -231,12 +231,14 @@ impl AppState { let models = Arc::new(crate::models::Directory::default()); models.reconcile(&config); let rt = Runtime::build(config, None)?; + let health = Arc::new(Health::new()); + health.configure(&rt.config.failover); let state = Self { rt: Arc::new(arc_swap::ArcSwap::from_pointee(rt)), gate: Default::default(), http, bus: tw_observe::EventBus::new(), - health: Arc::new(Health::new()), + health, catalog: Arc::new(arc_swap::ArcSwap::from_pointee(Default::default())), models, body_sink: Arc::new(std::sync::Mutex::new(None)), @@ -381,6 +383,7 @@ impl AppState { let (sheets, assign) = (next.config.pricing.clone(), next.config.price_assign()); self.pricing .rcu(|book| book.with_config(sheets.clone(), assign.clone())); + self.health.configure(&next.config.failover); self.rt.store(Arc::new(next)); // 模型汇总马上按新配置重算:删掉、停用的上游的模型必须立刻消失(列表 // 即承诺),改了范围的立刻生效。新加的、地址凭据变了的在后台补问 diff --git a/crates/tw-gateway/src/state/glm.rs b/crates/tw-gateway/src/state/glm.rs index 5bf1fbb6..dbbf61a3 100644 --- a/crates/tw-gateway/src/state/glm.rs +++ b/crates/tw-gateway/src/state/glm.rs @@ -9,11 +9,6 @@ use crate::server::now_ms; /// 问一次额度接口最多等多久 const ASK_TIMEOUT: Duration = Duration::from_secs(15); -/// 429 的 body 最多读多少、等多久。**这一跳已经失败了**,读它只为认出额度用完, -/// 不能因此拖住下一家 -const BODY_LIMIT: usize = 16 * 1024; -const BODY_TIMEOUT: Duration = Duration::from_secs(2); - impl AppState { /// 额度接口换成别的地址。**给测试用**:平时就是 Z.ai 和 BigModel 自己的 pub fn set_glm_sites(&self, sites: glm::Sites) { @@ -116,22 +111,14 @@ impl AppState { } /// 一个 GLM 上游回了 429:body 里说额度用完了的话,**那一刻就记成用完**,报一次 - /// `QuotaExhausted`。 + /// `QuotaExhausted`。`body` 是这个 429 正文的开头(转发那一边已经读过了)。 /// /// 重置时刻以额度接口问来的为准;还没问到过,才用消息里说的 - pub(crate) async fn note_glm_429( - &self, - id: u64, - p: &tw_config::Provider, - r: reqwest::Response, - ) { + pub(crate) fn note_glm_429_body(&self, id: u64, p: &tw_config::Provider, body: &[u8]) { if self.glm_target(p).is_none() { return; } - let Some(body) = read_capped(r).await else { - return; - }; - self.note_glm_exhausted(id, &p.name, &body); + self.note_glm_exhausted(id, &p.name, body); } /// 读出来的 429 body 说额度用完了的话,记下来。 @@ -172,21 +159,6 @@ impl AppState { } } -/// 读 body,最多 [`BODY_LIMIT`] 字节、[`BODY_TIMEOUT`]。读不完就算了 -async fn read_capped(mut r: reqwest::Response) -> Option> { - let read = async { - let mut out = Vec::new(); - while let Some(chunk) = r.chunk().await.ok()? { - out.extend_from_slice(&chunk); - if out.len() > BODY_LIMIT { - return None; - } - } - Some(out) - }; - tokio::time::timeout(BODY_TIMEOUT, read).await.ok()? -} - #[cfg(test)] mod tests { use super::*; diff --git a/crates/tw-gateway/tests/passthrough.rs b/crates/tw-gateway/tests/passthrough.rs index 6aaa0c99..e5ebb2e1 100644 --- a/crates/tw-gateway/tests/passthrough.rs +++ b/crates/tw-gateway/tests/passthrough.rs @@ -67,6 +67,7 @@ async fn start_upstream(sse: bool) -> (SocketAddr, Arc>) { async fn start_gateway(upstream: SocketAddr) -> SocketAddr { let cfg = Config { retention: Default::default(), + failover: Default::default(), default_route: None, default_key: None, version: 1, @@ -238,6 +239,7 @@ async fn a_request_emits_the_four_lifecycle_events_in_order() { let (up, _) = start_upstream(true).await; let cfg = Config { retention: Default::default(), + failover: Default::default(), default_route: None, default_key: None, version: 1, @@ -343,6 +345,7 @@ async fn an_unreachable_upstream_emits_a_failure_event_and_a_502() { let dead_port = spare_port(); let cfg = Config { retention: Default::default(), + failover: Default::default(), default_route: None, default_key: None, version: 1, @@ -407,6 +410,7 @@ async fn a_rule_sends_opus_to_one_upstream_and_everything_else_to_another() { let cfg = Config { retention: Default::default(), + failover: Default::default(), default_route: None, default_key: None, version: 1, @@ -509,6 +513,7 @@ async fn with_no_routes_at_all_requests_still_go_somewhere() { let (up, seen) = start_upstream(false).await; let cfg = Config { retention: Default::default(), + failover: Default::default(), default_route: None, default_key: None, version: 1, @@ -681,6 +686,162 @@ async fn rate_limiting_does_fail_over_because_another_account_may_have_quota() { assert!(!seen.lock().unwrap().body.is_empty()); } +/// 回一个固定的状态码、类型和正文的上游,并数它被打了几次。 +async fn start_answering_upstream( + status: u16, + content_type: &'static str, + body: &'static str, +) -> (SocketAddr, Arc) { + let hits = Arc::new(AtomicUsize::new(0)); + let counted = hits.clone(); + let app = Router::new().fallback(axum::routing::any(move || { + let counted = counted.clone(); + async move { + counted.fetch_add(1, Ordering::SeqCst); + axum::response::Response::builder() + .status(status) + .header("content-type", content_type) + .body(axum::body::Body::from(body)) + .unwrap() + } + })); + 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, hits) +} + +fn two(first: SocketAddr, second: SocketAddr) -> Config { + cfg_with( + vec![ + Provider { + name: "first".into(), + base_url: format!("http://{first}"), + key: Some("k".into()), + ..Default::default() + }, + Provider { + name: "second".into(), + base_url: format!("http://{second}"), + key: Some("k".into()), + ..Default::default() + }, + ], + vec![], + ) +} + +#[tokio::test] +async fn an_error_at_the_start_of_a_stream_moves_the_request_to_the_next_upstream() { + // 上游回了 200、开了流,第一个事件却是过载。客户端这时什么都还没收到, + // 换一家它完全无感;错误帧写给了它,就只能自己重试了 + let (overloaded, _) = start_answering_upstream( + 200, + "text/event-stream", + "event: message_start\ndata: {\"type\":\"message_start\",\"message\":{}}\n\n\ + event: error\ndata: {\"type\":\"error\",\"error\":{\"type\":\"overloaded_error\",\"message\":\"Overloaded\"}}\n\n", + ) + .await; + let (good, hits) = start_answering_upstream( + 200, + "text/event-stream", + "event: message_start\ndata: {\"type\":\"message_start\",\"message\":{}}\n\n\ + event: content_block_delta\ndata: {\"type\":\"content_block_delta\",\"delta\":{\"text\":\"answer\"}}\n\n", + ) + .await; + let gw = serve_cfg(two(overloaded, good)).await; + let text = reqwest::Client::new() + .post(format!("http://{gw}/v1/messages")) + .header("x-api-key", "tw-k") + .body(r#"{"model":"claude-sonnet-4-5","stream":true}"#) + .send() + .await + .unwrap() + .text() + .await + .unwrap(); + assert_eq!(hits.load(Ordering::SeqCst), 1, "第二家接下了"); + assert!(text.contains("answer"), "{text}"); + assert!( + !text.contains("overloaded_error"), + "第一家的错误不该到客户端:{text}" + ); +} + +#[tokio::test] +async fn an_error_after_content_has_started_is_not_retried() { + // 内容已经交给客户端了,再换一家就是把同一段回答说两遍 + let (broken, _) = start_answering_upstream( + 200, + "text/event-stream", + "event: content_block_delta\ndata: {\"type\":\"content_block_delta\",\"delta\":{\"text\":\"half\"}}\n\n\ + event: error\ndata: {\"type\":\"error\",\"error\":{\"type\":\"overloaded_error\",\"message\":\"Overloaded\"}}\n\n", + ) + .await; + let (good, hits) = start_answering_upstream(200, "text/event-stream", "").await; + let gw = serve_cfg(two(broken, good)).await; + let text = reqwest::Client::new() + .post(format!("http://{gw}/v1/messages")) + .header("x-api-key", "tw-k") + .body(r#"{"model":"claude-sonnet-4-5","stream":true}"#) + .send() + .await + .unwrap() + .text() + .await + .unwrap(); + assert_eq!(hits.load(Ordering::SeqCst), 0); + assert!( + text.contains("half") && text.contains("overloaded_error"), + "{text}" + ); +} + +#[tokio::test] +async fn a_missing_balance_moves_on_and_sets_the_upstream_aside() { + let (broke, broke_hits) = start_answering_upstream( + 402, + "application/json", + r#"{"error":{"message":"Insufficient Balance"}}"#, + ) + .await; + let (good, hits) = start_upstream(false).await; + let state = tw_gateway::AppState::new(two(broke, good)).unwrap(); + let health = state.health.clone(); + let gw = tw_gateway::serve(state, ([127, 0, 0, 1], 0).into()) + .await + .unwrap(); + tokio::time::sleep(Duration::from_millis(50)).await; + assert_eq!(send_to(gw).await.status(), 200); + assert!(!hits.lock().unwrap().body.is_empty()); + // **一次就停用**:上游说了原因,不必再撞两次 + assert!(!health.is_available("first")); + assert_eq!(send_to(gw).await.status(), 200); + assert_eq!(broke_hits.load(Ordering::SeqCst), 1, "停用着的不再去试"); +} + +#[tokio::test] +async fn the_last_upstreams_own_refusal_reaches_the_client() { + // 没有下一家可换了:上游自己的原话比「回了 401」有用 + let (bad_key, _) = start_answering_upstream( + 401, + "application/json", + r#"{"type":"error","error":{"type":"authentication_error","message":"invalid x-api-key"}}"#, + ) + .await; + let (also_bad, _) = start_answering_upstream( + 401, + "application/json", + r#"{"type":"error","error":{"type":"authentication_error","message":"invalid x-api-key"}}"#, + ) + .await; + let gw = serve_cfg(two(bad_key, also_bad)).await; + let r = send_to(gw).await; + assert_eq!(r.status(), 401); + assert_eq!(r.headers().get("x-thinkwatch-upstream").unwrap(), "second"); + assert!(r.text().await.unwrap().contains("invalid x-api-key")); +} + #[tokio::test] async fn the_only_provider_keeps_being_tried_no_matter_how_broken() { // 唯一的上游被自己熔断就把用户锁死了。没有别的家可切的时候, diff --git a/docs/config.md b/docs/config.md index 4e1bfa8b..655d04d9 100644 --- a/docs/config.md +++ b/docs/config.md @@ -152,6 +152,7 @@ means. | `client_probes` | object, [`client_probes`](#cfg-client_probes) | — | What happens to the helper requests clients send on their own (health checks, warm-ups, titles). | | `security` | object, [`security`](#cfg-security) | — | The five guards. All of them start in `observe` or `off`, so out of the box nothing is changed or blocked. | | `retention` | object, [`retention`](#cfg-retention) | — | How long request logs are kept. | +| `failover` | object, [`failover`](#cfg-failover) | — | How long an upstream is set aside after it fails, and how long the start of a stream is awaited. | | `groups` | list of [`groups[]`](#cfg-groups) | `[]` | Strategy groups: several upstreams behind one name, with a way to pick among them. | | `routes` | list of [`routes[]`](#cfg-routes) | `[]` | Routes. Without any, requests fail over across all upstreams in the order they are declared. | | `default_route` | string | — | The route for keys that do not name one. Unset: the route named `default`, or the built-in failover when there is none. | @@ -816,6 +817,32 @@ a few hundred bytes. The byte limit covers bursts. | `body_max_bytes` | integer | `2147483648` | Upper bound on the bytes bodies may take; beyond it the oldest days go first. The default is 2 GiB. | +### `failover` + +An upstream that fails is set aside for a while, so that the next requests +go straight to the next candidate. How long depends on the reason the +upstream gives: an insufficient balance waits for a top-up, a used-up quota +waits until the moment the upstream says it resets, and a rate limit usually +passes within seconds. A request with a single candidate is never affected. + +Before the first content of a streamed answer reaches the client, an error +the upstream sends in the stream moves the request to the next candidate, +the same as an error status would. + + + + +| Field | Type | Default | Description | +|---|---|---|---| +| `failures_to_pause` | integer | `3` | Consecutive failures without a stated reason (5xx, connection errors) before the upstream is set aside. From 1 to 100. | +| `pause_secs` | integer | `60` | Seconds the first such pause lasts. Each further pause doubles it, up to `max_pause_secs`; one success resets it. | +| `max_pause_secs` | integer | `600` | Upper bound on the doubled pause, in seconds; not less than `pause_secs`. | +| `no_balance_pause_secs` | integer | `1800` | Seconds to set aside an upstream that reports an insufficient balance. | +| `quota_pause_secs` | integer | `3600` | Seconds to set aside an upstream whose quota is used up when it does not say when the quota resets. When it does, the upstream is set aside until then. | +| `rate_limit_max_pause_secs` | integer | `3600` | A rate-limited upstream is set aside for the time its `Retry-After` gives, at most this many seconds. Without `Retry-After` it counts as a failure without a stated reason. | +| `stream_start_wait_secs` | integer | `15` | Seconds to hold a streamed answer until its first content arrives. An error before then moves the request to the next upstream; after this long, what has arrived is passed on. From 1 to 120. | + + ### `groups` A group puts several upstreams behind one name. Rules send requests to a diff --git a/docs/config.zh-CN.md b/docs/config.zh-CN.md index 1116041c..38093a1e 100644 --- a/docs/config.zh-CN.md +++ b/docs/config.zh-CN.md @@ -101,6 +101,7 @@ twcore config set /listen/gateway/port 8790 --int | `client_probes` | 对象,见 [`client_probes`](#cfg-client_probes) | — | 客户端自行发出的辅助请求(连通性检查、预热、起标题)如何处理。 | | `security` | 对象,见 [`security`](#cfg-security) | — | 五项防护。出厂时都处在 `observe` 或 `off`,不改变、不拦截任何请求。 | | `retention` | 对象,见 [`retention`](#cfg-retention) | — | 请求日志保留多久。 | +| `failover` | 对象,见 [`failover`](#cfg-failover) | — | 上游失败后停用多久,以及流式回答的开头最多等多久。 | | `groups` | 对象列表,见 [`groups[]`](#cfg-groups) | `[]` | 策略组:多个上游合用一个名字,并规定如何在其中选择。 | | `routes` | 对象列表,见 [`routes[]`](#cfg-routes) | `[]` | 路由。一条都不写时,请求按上游的声明顺序故障转移。 | | `default_route` | 字符串 | — | 未指定路由的密钥走哪条路由。不写:名为 `default` 的路由;没有这条路由时走内置的故障转移。 | @@ -686,6 +687,29 @@ security: | `body_max_bytes` | 整数 | `2147483648` | 正文最多占用的字节数,超出时从最早的日期开始删除。默认 2 GiB。 | +### `failover` + +上游失败后会停用一段时间,接下来的请求直接交给下一个候选。停用多久取决于上游 +给出的原因:余额不足要等充值,额度用完要等到上游说的重置时刻,限流通常几秒钟就 +过去。只有一个候选的请求不受影响。 + +流式回答在第一段内容交给客户端之前,上游在流里报的错误和错误状态码一样,会把 +请求换到下一个候选。 + + + + +| 字段 | 类型 | 默认值 | 说明 | +|---|---|---|---| +| `failures_to_pause` | 整数 | `3` | 没有说明原因的失败(5xx、连接失败)连续几次后停用这家上游,取值 1 到 100。 | +| `pause_secs` | 整数 | `60` | 这类失败第一次停用的秒数。之后每停用一次翻一倍,直到 `max_pause_secs`;成功一次后回到这个值。 | +| `max_pause_secs` | 整数 | `600` | 翻倍后的停用上限,单位秒,不小于 `pause_secs`。 | +| `no_balance_pause_secs` | 整数 | `1800` | 上游报告余额不足时停用的秒数。 | +| `quota_pause_secs` | 整数 | `3600` | 上游报告额度用完、但没有给出重置时间时停用的秒数。给出了重置时间的,停用到那一刻。 | +| `rate_limit_max_pause_secs` | 整数 | `3600` | 被限流的上游按它给的 `Retry-After` 停用,最多这么多秒。没有 `Retry-After` 的按没有说明原因的失败计。 | +| `stream_start_wait_secs` | 整数 | `15` | 流式回答在第一段内容到达前最多暂存的秒数。在此之前上游报错,请求换到下一家;超过这个时间,已收到的部分照常交给客户端。取值 1 到 120。 | + + ### `groups` 策略组让多个上游合用一个名字。规则用 `to` 把请求交给策略组。 diff --git a/scripts/smoke.sh b/scripts/smoke.sh index af0e8b1e..c5ffc6ec 100755 --- a/scripts/smoke.sh +++ b/scripts/smoke.sh @@ -124,12 +124,18 @@ class H(http.server.BaseHTTPRequestHandler): "usage": {"inputTokens": 30, "outputTokens": 2, "totalTokens": 32}}).encode()) saw = "yes" if b"sk-ant-api03-SMOKEKEY" in body else "no" if b"SLOWSTREAM" in body: - # 先吐第一帧(输入用量就在里面),然后长时间「思考」—— 客户端 + # 先吐开头(输入用量在 message_start 里),然后长时间「思考」—— 客户端 # 会在这期间走掉。不给 content-length,读到连接关闭为止。 + # + # **思考块的开头也要发**:网关在第一段内容到达之前不转发(开头报错还能 + # 换一家),只有 message_start 的话客户端一个字节都收不到。真实上游 + # 开始思考时也是马上发这一帧 self.send_response(200); self.send_header('content-type','text/event-stream') self.send_header('connection','close'); self.end_headers() self.wfile.write(b'event: message_start\ndata: {"type":"message_start",' - b'"message":{"usage":{"input_tokens":4321,"output_tokens":1}}}\n\n') + b'"message":{"usage":{"input_tokens":4321,"output_tokens":1}}}\n\n' + b'event: content_block_start\ndata: {"type":"content_block_start",' + b'"index":0,"content_block":{"type":"thinking","thinking":""}}\n\n') self.wfile.flush() time.sleep(30) return