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
32 changes: 31 additions & 1 deletion crates/tw-api/src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -482,7 +482,11 @@ pub const MSG_CODES: &str = include_str!("../msg-codes.txt");
///
/// **16 把最后几处原因也换成了 [`Msg`]**:`KeySyncFailed.error`、`PricingStatus.error`、
/// `TurnView.error`。照 15 写的界面会把它们画成一个对象。
pub const CONTROL_API_VERSION: u32 = 16;
///
/// **17 起「此刻有什么不对」都能问到**,不必从事件流开头听起:`Status.config_rejected`
/// (磁盘上那份配置没通过校验、旧的还在服务)和 `ProviderView.writeback_failed`
/// (换发的凭据没能写回配置)。半路才连上的一方(桌面端的提醒)按它们对账。
pub const CONTROL_API_VERSION: u32 = 17;

#[derive(Debug, Clone, Serialize, Deserialize)]
#[cfg_attr(feature = "ts", derive(ts_rs::TS))]
Expand All @@ -501,6 +505,11 @@ pub struct Status {
/// 旧的地址还在服务**,也就是 `gateway_addr` 说的那个
#[serde(default, skip_serializing_if = "Option::is_none")]
pub listen_error: Option<Msg>,
/// 磁盘上的配置文件最近一次改动没通过校验:**旧的那一版还在服务**。
/// 下一次换入成功(改好了、或者界面写了一版)就没有了。和 `ConfigRejected`
/// 事件说的是同一件事 —— 事件是那一刻,这里是现在
#[serde(default, skip_serializing_if = "Option::is_none")]
pub config_rejected: Option<ConfigRejection>,
pub config_path: String,
pub clients: usize,
pub providers: usize,
Expand Down Expand Up @@ -1160,6 +1169,22 @@ pub struct RunningView {
pub at_ms: u64,
}

/// 配置文件没通过校验的那一次。字段和 [`Event::ConfigRejected`] 一样。
///
/// **只记外部改动**(在编辑器里改的、命令行写的):界面自己写坏的根本没落盘,
/// 那是一次保存失败,保存那条路当场就说了。
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
#[cfg_attr(feature = "ts", derive(ts_rs::TS))]
pub struct ConfigRejection {
pub stage: ConfigStage,
pub message: Msg,
/// 1 起。语义错误没有
pub line: Option<usize>,
/// 出错那一行的原文,**已脱敏**
pub excerpt: Option<String>,
pub at_ms: u64,
}

/// 界面要显示的配置概览。
///
/// **不是配置文件本身**:密钥一律只给来源描述,不给值(统一脱敏)。
Expand Down Expand Up @@ -1353,6 +1378,10 @@ pub struct ProviderView {
/// 上游永远不会熔断。和 `AuthChanged` 说的是同一件事:一个是现状,一个是变化
#[serde(default, skip_serializing_if = "Option::is_none")]
pub auth_rejected: Option<u16>,
/// token 端点换发的新凭据**没能写回配置**的原因。这时新凭据只在内存里,旧的
/// 已经作废:网关一重启,这家上游就要重新登录。写回成功就没有了
#[serde(default, skip_serializing_if = "Option::is_none")]
pub writeback_failed: Option<Msg>,
/// 计费方式:`per-token`(按价目表算,订阅账号也是)/ `free`(记 $0)
pub billing: Billing,
/// 谁在引用它。**删之前要知道**,改名时它们会跟着改
Expand Down Expand Up @@ -4355,6 +4384,7 @@ mod tests {
pid: 1,
gateway_addr: Some("127.0.0.1:8788".into()),
listen_error: None,
config_rejected: None,
config_path: "/x/config.yaml".into(),
clients: 1,
providers: 1,
Expand Down
41 changes: 40 additions & 1 deletion crates/tw-control/src/config.rs
Original file line number Diff line number Diff line change
Expand Up @@ -22,6 +22,9 @@ pub struct ConfigManager {
/// 上一次**我们自己**写下去的样子。文件事件来了先和它比 ——
/// 一样就是自己写的,直接忽略,否则会形成回环。
seen: Mutex<Option<Fingerprint>>,
/// 磁盘上那份最近一次外部改动没通过校验(`Status.config_rejected`)。**是现状,不是
/// 那一刻**:半路才连上的界面按它补上那条提醒;换入成功就清掉
rejected: std::sync::Mutex<Option<tw_api::ConfigRejection>>,
}

/// 一次配置改动没成的原因。
Expand Down Expand Up @@ -86,6 +89,18 @@ impl ConfigManager {
gateway,
bus,
seen: Mutex::new(seen),
rejected: std::sync::Mutex::new(None),
}
}

/// 磁盘上那份配置此刻是不是没通过校验、旧的还在服务
pub fn rejected(&self) -> Option<tw_api::ConfigRejection> {
self.rejected.lock().ok().and_then(|g| g.clone())
}

fn set_rejected(&self, r: Option<tw_api::ConfigRejection>) {
if let Ok(mut g) = self.rejected.lock() {
*g = r;
}
}

Expand All @@ -110,6 +125,18 @@ impl ConfigManager {
{
// **这是回环的唯一出口。**没有它,我们写一次文件,监听
// 响一次,我们再重载一次,严重时是个循环。
//
// 写坏之后又改回了在服务的那一版:文件和现状又对上了,被拒那件事
// 就过去了 —— 要说一声,否则界面上那条「未通过校验」一直挂着
if self.rejected().is_some() {
self.set_rejected(None);
self.bus.emit(tw_api::Event::ConfigReloaded {
id: self.bus.next_id(),
version: store::version_of(&loaded.text),
origin: Origin::External.into(),
at_ms: now_ms(),
});
}
return Ok(None);
}
}
Expand All @@ -126,14 +153,25 @@ impl ConfigManager {
// **先告诉界面,再返回错误。**这条路径最常见的调用方是文件
// 监听,而它的错误没有人接 —— 不发事件的话,用户在编辑器里
// 写错一个字,界面上什么都不会发生。
let at_ms = now_ms();
// 只有外部改动会留在盘上:界面自己写坏的根本没落盘
if origin == Origin::External {
self.set_rejected(Some(tw_api::ConfigRejection {
stage: r.stage.into(),
message: (*r.message).clone(),
line: r.line,
excerpt: r.excerpt.clone(),
at_ms,
}));
}
self.bus.emit(tw_api::Event::ConfigRejected {
id: self.bus.next_id(),
stage: r.stage.into(),
message: (*r.message).clone(),
line: r.line,
excerpt: r.excerpt.clone(),
origin: origin.into(),
at_ms: now_ms(),
at_ms,
});
tracing::warn!(
"the configuration did not validate; staying on the previous version: {r}"
Expand All @@ -146,6 +184,7 @@ impl ConfigManager {
// 存刚刚生效的这一版。加上写入路径在写之前存的那一次,去重
// 之后的效果是「每个存在过的版本各一条」,最新那条就是现在跑
// 着的 —— 于是「回到上一版」在列表上就是第二条,不用数。
self.set_rejected(None);
let _ = tw_config::history::snapshot(&self.path, text, origin);
let version = store::version_of(text);
tracing::info!(%version, origin = origin.slug(), "the configuration is in effect");
Expand Down
2 changes: 2 additions & 0 deletions crates/tw-control/src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -223,6 +223,7 @@ async fn status(State(s): State<ControlState>) -> Json<tw_api::Status> {
// 这里自然是 None
gateway_addr: listening.primary().map(|a| a.to_string()),
listen_error: listening.error,
config_rejected: s.cfg.rejected(),
config_path: s.config_path().display().to_string(),
clients: cfg.clients.len(),
providers: cfg.providers.len(),
Expand Down Expand Up @@ -484,6 +485,7 @@ fn provider_view(
tw_gateway::health::State::Open => tw_api::Health::Open,
},
auth_rejected: s.gateway.auth_rejected(&p.name),
writeback_failed: s.gateway.writeback_failed(&p.name),
billing: p.billing.into(),
references: tw_config::refs::provider_refs(cfg, &p.name)
.iter()
Expand Down
76 changes: 76 additions & 0 deletions crates/tw-control/tests/sync.rs
Original file line number Diff line number Diff line change
Expand Up @@ -213,3 +213,79 @@ async fn an_external_edit_also_lands_in_history_so_it_can_be_undone() {
"外部改动没进历史"
);
}

/// 被拒是**现状**,不只是那一刻的事件:半路才连上的一方问得到;改好了就没有了
#[tokio::test]
async fn a_rejected_file_stays_visible_until_the_next_good_one() {
let (_d, mgr, bus) = setup();
let mut rx = bus.subscribe();
let _w = tw_control::spawn_watcher(mgr.clone()).unwrap();
assert!(mgr.rejected().is_none());

std::fs::write(
mgr.path(),
"version: 1\nclients:\n - name: c\n kye: tw-k\n",
)
.unwrap();
assert!(matches!(
next_config_event(&mut rx).await,
tw_api::Event::ConfigRejected { .. }
));
let r = mgr.rejected().expect("被拒要留着");
assert_eq!(r.stage, tw_api::ConfigStage::Schema);
assert_eq!(r.line, Some(4));

let good = format!("{BASE}providers: []\n");
std::fs::write(mgr.path(), &good).unwrap();
assert!(matches!(
next_config_event(&mut rx).await,
tw_api::Event::ConfigReloaded { .. }
));
assert!(mgr.rejected().is_none(), "改好了就不该还挂着");
}

/// 写坏之后又原样改回在服务的那一版:文件内容和现状一致,**被拒那件事过去了**,
/// 要说一声(不然界面上的那条一直挂着),也不该重载一遍
#[tokio::test]
async fn reverting_a_rejected_edit_clears_the_rejection() {
let (_d, mgr, bus) = setup();
let mut rx = bus.subscribe();
let _w = tw_control::spawn_watcher(mgr.clone()).unwrap();

std::fs::write(
mgr.path(),
"version: 1\nclients:\n - name: c\n kye: tw-k\n",
)
.unwrap();
assert!(matches!(
next_config_event(&mut rx).await,
tw_api::Event::ConfigRejected { .. }
));
std::fs::write(mgr.path(), BASE).unwrap();
match next_config_event(&mut rx).await {
tw_api::Event::ConfigReloaded {
origin, version, ..
} => {
assert_eq!(origin, tw_api::ConfigOrigin::External);
assert_eq!(version, mgr.current().unwrap().version());
}
other => panic!("{other:?}"),
}
assert!(mgr.rejected().is_none());
}

/// 界面自己写坏的根本没落盘:**不算现状**,保存那条路当场就报了
#[tokio::test]
async fn a_rejected_write_from_the_interface_is_not_a_standing_rejection() {
let (_d, mgr, _bus) = setup();
let e = mgr
.write(
"version: 1\nclients:\n - name: c\n kye: tw-k\n",
None,
Origin::Ui,
)
.await
.unwrap_err();
assert!(matches!(e, ApplyError::Rejected(_)), "{e:?}");
assert!(mgr.rejected().is_none());
}
4 changes: 4 additions & 0 deletions crates/tw-gateway/src/state.rs
Original file line number Diff line number Diff line change
Expand Up @@ -189,6 +189,9 @@ pub struct AppState {
/// 忽略通知,包括那些真该看的。失败不一样:它要一直挂着,
/// 而且从成功变成失败是**状态变了**,必须重新说。
rotation_told: Arc<std::sync::Mutex<std::collections::HashSet<String>>>,
/// 换发的凭据没能写回的那几家,和最后一次的原因。**是现状**:半路才连上的界面按它
/// 补上那条提醒(`ProviderView.writeback_failed`);写回成功就清掉
writeback_failed: Arc<std::sync::Mutex<std::collections::HashMap<String, tw_types::Msg>>>,
/// 已经报过「凭据失效」的上游。**只在失效的那一刻报一次**,恢复之后清掉
expired_told: Arc<std::sync::Mutex<std::collections::HashSet<String>>>,
/// 已经报过「用完」的额度窗口:(上游, 窗口)。**窗口恢复之后清掉**,再用完会重新报
Expand Down Expand Up @@ -240,6 +243,7 @@ impl AppState {
)),
renewal_sink: Arc::new(std::sync::Mutex::new(None)),
rotation_told: Arc::new(std::sync::Mutex::new(Default::default())),
writeback_failed: Arc::new(std::sync::Mutex::new(Default::default())),
expired_told: Arc::new(std::sync::Mutex::new(Default::default())),
exhausted: Arc::new(std::sync::Mutex::new(Default::default())),
rejected: Arc::new(std::sync::Mutex::new(Default::default())),
Expand Down
15 changes: 15 additions & 0 deletions crates/tw-gateway/src/state/credentials.rs
Original file line number Diff line number Diff line change
Expand Up @@ -154,12 +154,27 @@ impl AppState {
});
}

/// 这一家换发的凭据没能写回的话,最后一次的原因(见 [`AppState::report_rotation`])
pub fn writeback_failed(&self, provider: &str) -> Option<Msg> {
self.writeback_failed
.lock()
.ok()
.and_then(|g| g.get(provider).cloned())
}

/// 凭据轮换的结果报给界面。
///
/// **写成功也要报一次。**用户的 config.yaml 被我们改了 —— 哪怕改得
/// 完全正确,不说一声也是不对的:他的编辑器会弹「文件已在磁盘上更改」,
/// 而那时他应该已经知道原因。
pub fn report_rotation(&self, provider: &str, persisted: bool, detail: Msg) {
if let Ok(mut g) = self.writeback_failed.lock() {
if persisted {
g.remove(provider);
} else {
g.insert(provider.to_string(), detail.clone());
}
}
{
let mut told = self.rotation_told.lock().expect("lock not poisoned");
if persisted {
Expand Down
5 changes: 5 additions & 0 deletions crates/tw-gateway/tests/oauth.rs
Original file line number Diff line number Diff line change
Expand Up @@ -428,6 +428,11 @@ async fn without_a_config_manager_the_rotation_is_reported_as_not_persisted() {
}
// 事件里一个 token 都不能有
assert!(!seen.iter().any(|s| s.2.text.contains("rt-")), "{seen:?}");
// **没写回是现状**:半路才连上的界面问得到(`ProviderView.writeback_failed`)
let now = state.writeback_failed("p").expect("没写回要留着");
assert!(now.text.contains("not written back"), "{now}");
state.report_rotation("p", true, seen[0].2.clone());
assert!(state.writeback_failed("p").is_none(), "写回成功就清掉");
}

/// 用户在 config.yaml 里换了 refresh token 之后,**缓存不能盖住这个修改**。
Expand Down
Loading