Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
2 changes: 2 additions & 0 deletions crates/tw-api/msg-codes.txt
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down Expand Up @@ -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
Expand Down
26 changes: 26 additions & 0 deletions crates/tw-api/src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -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)]
Expand Down Expand Up @@ -1581,6 +1584,8 @@ pub struct Overview {
pub client_probes: Vec<ProbeView>,
/// 日志留多久
pub retention: RetentionView,
/// 上游失败之后停用多久、流开头最多等多久
pub failover: FailoverView,
/// 自定义价目表。默认价目表不在这里 —— 它的状态看 `/pricing`
pub price_sheets: Vec<PriceSheetView>,
}
Expand Down Expand Up @@ -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`。
///
/// **「拦截」在各项上做的事不一样**:脱敏是替换成占位符,工具调用审查和输出长度
Expand Down
126 changes: 126 additions & 0 deletions crates/tw-config/src/failover.rs
Original file line number Diff line number Diff line change
@@ -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)
}
}
6 changes: 6 additions & 0 deletions crates/tw-config/src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -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;
Expand Down Expand Up @@ -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<tw_engine::Group>,
/// 路由。一条路由是一组按顺序求值的规则。
Expand Down Expand Up @@ -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,
Expand Down Expand Up @@ -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;
Expand Down
52 changes: 52 additions & 0 deletions crates/tw-config/src/validate.rs
Original file line number Diff line number Diff line change
Expand Up @@ -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,
Expand Down Expand Up @@ -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 \
Expand Down Expand Up @@ -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() {
Expand Down Expand Up @@ -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]
Expand Down
79 changes: 79 additions & 0 deletions crates/tw-config/tests/manual/schema.rs
Original file line number Diff line number Diff line change
Expand Up @@ -171,6 +171,15 @@ pub fn sections() -> Vec<Section> {
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[]"),
Expand Down Expand Up @@ -1164,6 +1173,76 @@ pub fn sections() -> Vec<Section> {
),
],
},
// ── 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[]",
Expand Down
Loading
Loading