From 0f35362b8271068ff6d9ba0ade100a7bb6e48c95 Mon Sep 17 00:00:00 2001 From: fylorn <249551762+fylorn@users.noreply.github.com> Date: Wed, 23 Sep 2026 13:59:19 +0800 Subject: [PATCH] feat(control): let the gateway be asked to exit, and record the token break Windows has no SIGTERM, and the desktop app has two things it must do: restart core after a configuration change, and stop core before installing an update and *wait for it to be gone* -- without that wait the new one collides with the lock the old one has not released yet. On that platform the only thing left is a hard kill, which means SQLite's WAL gets no chance to settle and in-flight requests are cut mid-response. So it is a request rather than a signal, and it is slightly better than one: it is acknowledged. The desktop app knows it was received instead of firing and guessing. Both platforms use it. A path that only runs on one platform is a path nobody exercises. The handler answers before the switch is thrown. Throwing it immediately risks the process being gone before the response is written, and what the client sees then is a reset connection -- indistinguishable from core crashing, on the one exit it asked for itself. The switch stores a request that arrives before anyone is waiting (`notify_one`, not `notify_waiters`). During the first milliseconds of startup the control plane can be answering before the main loop reaches its select, and dropping that request leaves a process that never exits. The protocol version goes to 12, which #114 should have done: a request without `Authorization: Bearer` now gets 401 for everything, `/status` included. A client written against 11 never sees the bump -- it hits the 401 first -- but that line is this protocol's change history, and "when did a credential become required" is something a reader has to be able to find. The smoke script now asks core to exit and waits for the process to be gone. That is the only end-to-end check of the chain: an HTTP request throws the switch, the main loop's select wakes, the process leaves. Unit tests can show the switch flips; they cannot show it is wired to the main loop -- and the shape of getting that wrong is a 202 and a gateway that keeps running. Co-Authored-By: Claude Opus 5 --- bin/twcore/src/main.rs | 19 +++++-- crates/tw-api/src/lib.rs | 9 +++- crates/tw-control/src/lib.rs | 25 +++++++++ crates/tw-control/src/shutdown.rs | 69 ++++++++++++++++++++++++ crates/tw-control/tests/adopt.rs | 1 + crates/tw-control/tests/chatgpt.rs | 1 + crates/tw-control/tests/dryrun.rs | 1 + crates/tw-control/tests/in_flight.rs | 1 + crates/tw-control/tests/keys.rs | 1 + crates/tw-control/tests/listen.rs | 1 + crates/tw-control/tests/live_state.rs | 1 + crates/tw-control/tests/m4_acceptance.rs | 1 + crates/tw-control/tests/models.rs | 1 + crates/tw-control/tests/pricing.rs | 1 + crates/tw-control/tests/resources.rs | 1 + crates/tw-control/tests/routes.rs | 1 + crates/tw-control/tests/security.rs | 1 + crates/tw-control/tests/sessions.rs | 1 + crates/tw-control/tests/speed.rs | 1 + crates/tw-control/tests/zai.rs | 1 + scripts/smoke.sh | 28 ++++++++++ 21 files changed, 161 insertions(+), 5 deletions(-) create mode 100644 crates/tw-control/src/shutdown.rs diff --git a/bin/twcore/src/main.rs b/bin/twcore/src/main.rs index 09135b70..4e6e4a68 100644 --- a/bin/twcore/src/main.rs +++ b/bin/twcore/src/main.rs @@ -728,6 +728,9 @@ fn cmd_serve(path: &Path, port: Option, safe: bool, parent: Option) -> // **在起任何东西之前问**。等到 bind 失败时,网关已经在监听、客户端 // 可能已经连上来了,而这条错误当时只会进日志。 tw_control::endpoint_usable(&endpoint)?; + // 「该退了」的开关。**在起任何东西之前建好** —— 控制面和主循环各拿 + // 一份,而控制面可能在主循环开始等之前就收到那条请求。 + let shutdown = tw_control::Shutdown::default(); // 控制面的凭据,同样在起任何东西之前拿到:桌面端从环境变量交过来, // 手工启动时生成一个写进配置目录。取不到就停在这儿 —— 一个装不上门的 // 控制面不该先起来再说。 @@ -810,6 +813,7 @@ fn cmd_serve(path: &Path, port: Option, safe: bool, parent: Option) -> // 控制面无论如何都要起来 —— **网关挂了的时候,用户最需要的恰恰 // 是能改配置**。安全模式就是「只有这一半」。 let control = tw_control::ControlState { + shutdown: shutdown.clone(), home: tw_control::home_dir(), started: std::time::Instant::now(), gateway: state.clone(), @@ -878,7 +882,7 @@ fn cmd_serve(path: &Path, port: Option, safe: bool, parent: Option) -> msg = control_dead => { anyhow::bail!("{}", msg.unwrap_or_else(|_| "the control plane stopped".into())) } - _ = shutdown_signal() => {} + _ = shutdown_requested(&shutdown) => {} } return Ok(()); } @@ -895,7 +899,7 @@ fn cmd_serve(path: &Path, port: Option, safe: bool, parent: Option) -> msg = control_dead => { anyhow::bail!("{}", msg.unwrap_or_else(|_| "the control plane stopped".into())) } - _ = shutdown_signal() => { + _ = shutdown_requested(&shutdown) => { tracing::info!("got a shutdown signal"); Ok(()) } @@ -975,7 +979,14 @@ fn build_store( )) } -async fn shutdown_signal() { +/// 等一个「该退了」。 +/// +/// 三个来源:Ctrl-C、SIGTERM,以及控制面上的那条请求。 +/// +/// **第三个不是锦上添花。**Windows 上根本没有 SIGTERM,而桌面端要在改完配置 +/// 之后重启 core、装更新之前停掉它 —— 那个平台上剩下的只有强杀,而强杀意味着 +/// WAL 没收尾、在途请求断在半路。见 `tw_control::shutdown`。 +async fn shutdown_requested(asked: &tw_control::Shutdown) { let ctrl_c = async { tokio::signal::ctrl_c().await.ok(); }; @@ -988,5 +999,5 @@ async fn shutdown_signal() { }; #[cfg(not(unix))] let term = std::future::pending::<()>(); - tokio::select! { _ = ctrl_c => {}, _ = term => {} } + tokio::select! { _ = ctrl_c => {}, _ = term => {}, _ = asked.asked() => {} } } diff --git a/crates/tw-api/src/lib.rs b/crates/tw-api/src/lib.rs index 0c87db18..1b2846b2 100644 --- a/crates/tw-api/src/lib.rs +++ b/crates/tw-api/src/lib.rs @@ -59,7 +59,14 @@ pub use tw_types::Msg; /// **11 推理测速的错误是 [`Msg`]、输出上限可以是空。**ChatGPT 账号那种上游不接受 /// 输出上限,报价里的上限和金额都是空的;错误原来是一句英文字符串,中文界面上 /// 只能原样显示。照 10 写的界面会把错误画成一个对象。 -pub const CONTROL_API_VERSION: u32 = 11; +/// +/// **12 起控制面要凭据。**没带 `Authorization: Bearer` 的请求一律 401, +/// 连 `/status` 都读不到 —— 所以照 11 写的客户端**看不到这次跳号**,它先 +/// 撞上的是 401。跳号在这里仍然要记,因为这一行是这个协议的变更史,而 +/// 「什么时候开始要凭据」是读它的人必须查得到的一件事。 +/// +/// 同一版加了 `POST /shutdown`。新增端点本身不破坏什么,它跟着这次走。 +pub const CONTROL_API_VERSION: u32 = 12; #[derive(Debug, Clone, Serialize, Deserialize)] pub struct Status { diff --git a/crates/tw-control/src/lib.rs b/crates/tw-control/src/lib.rs index c3e39ebc..46de149e 100644 --- a/crates/tw-control/src/lib.rs +++ b/crates/tw-control/src/lib.rs @@ -33,9 +33,11 @@ pub mod rotation; pub mod routes; pub mod scan; pub mod security; +pub mod shutdown; pub mod token; pub mod zai; pub use config::{ApplyError, ConfigManager, resolve_path, spawn_watcher}; +pub use shutdown::Shutdown; pub use tw_observe::EventBus; #[derive(Clone)] @@ -58,6 +60,8 @@ pub struct ControlState { /// Z.ai / BigModel 账号的登录。**同一时刻也只有一次** —— 理由不是端口,是 /// 「一次登录」在界面上就是一件正在进行的事,两件同时进行没人说得清哪件成了 pub zai: Arc, + /// 请网关退出的那个开关。控制面上的 `POST /shutdown` 扳它,主循环等它。 + pub shutdown: Shutdown, /// 用户的 home。接管要顺着它去找各客户端的配置。 /// /// **是个字段,不是每次现读 `$HOME`。**进程级的环境变量是全局可变 @@ -109,6 +113,7 @@ impl ControlState { pub fn router(state: ControlState) -> Router { Router::new() .route("/status", get(status)) + .route("/shutdown", post(ask_shutdown)) .route("/interfaces", get(interfaces)) .merge(keys::router()) .merge(listen::router()) @@ -187,6 +192,26 @@ async fn interfaces() -> Json> { ) } +/// 请网关退出。 +/// +/// 理由见 [`shutdown`] 那个模块:Windows 上没有 SIGTERM,而桌面端要在改完 +/// 配置之后重启 core、在装更新之前停掉它并且等它真的退出。 +async fn ask_shutdown(State(s): State) -> (StatusCode, Json) { + tracing::info!("asked to shut down over the control plane"); + // **先把话说完再退。**立刻扳开关的话,这条响应可能还没写出去进程就没了, + // 而客户端看到的是连接被重置 —— 和「core 崩了」长得一模一样,偏偏这是 + // 它自己要求的那一次退出。 + let sw = s.shutdown.clone(); + tokio::spawn(async move { + tokio::time::sleep(std::time::Duration::from_millis(100)).await; + sw.ask(); + }); + ( + StatusCode::ACCEPTED, + Json(msg!("control.shutdown" => "The gateway is shutting down.")), + ) +} + async fn status(State(s): State) -> Json { let cfg = s.config(); let listening = s.gateway.listening(); diff --git a/crates/tw-control/src/shutdown.rs b/crates/tw-control/src/shutdown.rs new file mode 100644 index 00000000..46099c67 --- /dev/null +++ b/crates/tw-control/src/shutdown.rs @@ -0,0 +1,69 @@ +//! 请网关退出。 +//! +//! # 为什么这是控制面上的一条请求,而不是一个信号 +//! +//! **Windows 上没有 SIGTERM。**而桌面端有两件事非做不可:改完配置之后重启 +//! core,以及装更新之前停掉它并且**等它真的退出**(不等的话,新起来的那个 +//! 会撞上旧的还没放开的锁)。那个平台上能用的只剩强杀,而强杀意味着 SQLite +//! 的 WAL 没有收尾、在途的请求直接断在半路。 +//! +//! 所以做成一条请求。它比信号还好一点:**有应答**,桌面端因此知道对方收到了, +//! 而不是发完信号去猜。 +//! +//! 两个平台都走它。只在一个平台上生效的路径,是没人日常测的路径。 + +use std::sync::Arc; + +/// 一个「该退了」的开关。 +#[derive(Clone, Default)] +pub struct Shutdown(Arc); + +impl Shutdown { + /// 请它退出。 + /// + /// **用 `notify_one` 而不是 `notify_waiters`。**前者在还没有人等的时候 + /// 会把这一次记下来,后者直接丢掉 —— 而「请求先到、主循环才开始等」 + /// 这个顺序在启动那几毫秒里是可能的,丢掉的后果是一个永远不退的进程。 + pub fn ask(&self) { + self.0.notify_one(); + } + + /// 等到有人请它退出。 + pub async fn asked(&self) { + self.0.notified().await; + } +} + +impl std::fmt::Debug for Shutdown { + fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { + f.write_str("Shutdown") + } +} + +#[cfg(test)] +mod tests { + use super::*; + + #[tokio::test] + async fn asking_wakes_the_waiter() { + let s = Shutdown::default(); + let w = s.clone(); + let h = tokio::spawn(async move { w.asked().await }); + s.ask(); + tokio::time::timeout(std::time::Duration::from_secs(5), h) + .await + .expect("请求没把等的人叫醒") + .unwrap(); + } + + /// 请求先到、主循环后开始等 —— 启动那几毫秒里真的可能这样。 + /// 丢掉这一次的后果是一个永远不退的进程。 + #[tokio::test] + async fn a_request_that_arrives_before_anyone_waits_is_not_lost() { + let s = Shutdown::default(); + s.ask(); + tokio::time::timeout(std::time::Duration::from_secs(5), s.asked()) + .await + .expect("先到的那次请求被丢了"); + } +} diff --git a/crates/tw-control/tests/adopt.rs b/crates/tw-control/tests/adopt.rs index e58d97e4..87da31ea 100644 --- a/crates/tw-control/tests/adopt.rs +++ b/crates/tw-control/tests/adopt.rs @@ -34,6 +34,7 @@ fn bed_with_store(store: Option String) -> Bed { let bus = gw.bus.clone(); let events = bus.subscribe(); let state = ControlState { + shutdown: Default::default(), cfg: Arc::new(ConfigManager::new(p, gw.clone(), bus)), gateway: gw, store: None, diff --git a/crates/tw-control/tests/dryrun.rs b/crates/tw-control/tests/dryrun.rs index 51734104..63849fce 100644 --- a/crates/tw-control/tests/dryrun.rs +++ b/crates/tw-control/tests/dryrun.rs @@ -57,6 +57,7 @@ fn app_with(text: &str) -> (tempfile::TempDir, axum::Router) { let gw = tw_gateway::AppState::new(cfg).unwrap(); let bus = gw.bus.clone(); let state = ControlState { + shutdown: Default::default(), cfg: Arc::new(ConfigManager::new(p, gw.clone(), bus)), gateway: gw, store: None, diff --git a/crates/tw-control/tests/in_flight.rs b/crates/tw-control/tests/in_flight.rs index d061b656..c88d1aa5 100644 --- a/crates/tw-control/tests/in_flight.rs +++ b/crates/tw-control/tests/in_flight.rs @@ -20,6 +20,7 @@ fn app() -> (tempfile::TempDir, tw_observe::EventBus, axum::Router) { let gw = tw_gateway::AppState::new(cfg).unwrap(); let bus = gw.bus.clone(); let state = ControlState { + shutdown: Default::default(), cfg: Arc::new(ConfigManager::new(p, gw.clone(), bus.clone())), gateway: gw, store: None, diff --git a/crates/tw-control/tests/keys.rs b/crates/tw-control/tests/keys.rs index c8aca52d..3059a02e 100644 --- a/crates/tw-control/tests/keys.rs +++ b/crates/tw-control/tests/keys.rs @@ -54,6 +54,7 @@ fn bed(yaml: &str) -> Bed { let gw = tw_gateway::AppState::new(cfg).unwrap(); let bus = gw.bus.clone(); let state = ControlState { + shutdown: Default::default(), cfg: Arc::new(ConfigManager::new(p, gw.clone(), bus)), gateway: gw, store: None, diff --git a/crates/tw-control/tests/listen.rs b/crates/tw-control/tests/listen.rs index fdea3198..acaa4ca4 100644 --- a/crates/tw-control/tests/listen.rs +++ b/crates/tw-control/tests/listen.rs @@ -34,6 +34,7 @@ fn bed(yaml: &str) -> Bed { let gw = tw_gateway::AppState::new(cfg).unwrap(); let bus = gw.bus.clone(); let state = ControlState { + shutdown: Default::default(), cfg: Arc::new(ConfigManager::new(p, gw.clone(), bus)), gateway: gw.clone(), store: None, diff --git a/crates/tw-control/tests/live_state.rs b/crates/tw-control/tests/live_state.rs index 901338ba..2d663f20 100644 --- a/crates/tw-control/tests/live_state.rs +++ b/crates/tw-control/tests/live_state.rs @@ -24,6 +24,7 @@ fn control( let gw = tw_gateway::AppState::new(cfg).unwrap(); let bus = gw.bus.clone(); let state = ControlState { + shutdown: Default::default(), cfg: Arc::new(ConfigManager::new(p, gw.clone(), bus)), gateway: gw.clone(), store, diff --git a/crates/tw-control/tests/m4_acceptance.rs b/crates/tw-control/tests/m4_acceptance.rs index bea06d1a..dc2d8e9c 100644 --- a/crates/tw-control/tests/m4_acceptance.rs +++ b/crates/tw-control/tests/m4_acceptance.rs @@ -37,6 +37,7 @@ fn bed() -> Bed { let bus = gw.bus.clone(); let home = d.path().join("home"); let state = ControlState { + shutdown: Default::default(), cfg: Arc::new(ConfigManager::new(p, gw.clone(), bus)), gateway: gw, store: None, diff --git a/crates/tw-control/tests/models.rs b/crates/tw-control/tests/models.rs index 47f86f9d..499f489d 100644 --- a/crates/tw-control/tests/models.rs +++ b/crates/tw-control/tests/models.rs @@ -30,6 +30,7 @@ fn bed(yaml: &str) -> Bed { let bus = gw.bus.clone(); let events = bus.subscribe(); let state = ControlState { + shutdown: Default::default(), cfg: Arc::new(ConfigManager::new(p, gw.clone(), bus)), gateway: gw, store: None, diff --git a/crates/tw-control/tests/pricing.rs b/crates/tw-control/tests/pricing.rs index 9f202704..250ef697 100644 --- a/crates/tw-control/tests/pricing.rs +++ b/crates/tw-control/tests/pricing.rs @@ -52,6 +52,7 @@ fn bed_with(yaml: &str, updater: Updater) -> Bed { let gw = tw_gateway::AppState::new(cfg).unwrap(); let bus = gw.bus.clone(); let state = ControlState { + shutdown: Default::default(), cfg: Arc::new(ConfigManager::new(p, gw.clone(), bus)), gateway: gw, store: None, diff --git a/crates/tw-control/tests/resources.rs b/crates/tw-control/tests/resources.rs index aa51663e..55dbabcd 100644 --- a/crates/tw-control/tests/resources.rs +++ b/crates/tw-control/tests/resources.rs @@ -53,6 +53,7 @@ fn bed(yaml: &str) -> Bed { let gw = tw_gateway::AppState::new(cfg).unwrap(); let bus = gw.bus.clone(); let state = ControlState { + shutdown: Default::default(), cfg: Arc::new(ConfigManager::new(p, gw.clone(), bus)), gateway: gw, store: None, diff --git a/crates/tw-control/tests/routes.rs b/crates/tw-control/tests/routes.rs index 3cd47dcc..f1a85b8a 100644 --- a/crates/tw-control/tests/routes.rs +++ b/crates/tw-control/tests/routes.rs @@ -82,6 +82,7 @@ fn bed(yaml: &str) -> Bed { let gw = tw_gateway::AppState::new(cfg).unwrap(); let bus = gw.bus.clone(); let state = ControlState { + shutdown: Default::default(), cfg: Arc::new(ConfigManager::new(p, gw.clone(), bus)), gateway: gw, store: None, diff --git a/crates/tw-control/tests/security.rs b/crates/tw-control/tests/security.rs index b88199f9..efb85ce7 100644 --- a/crates/tw-control/tests/security.rs +++ b/crates/tw-control/tests/security.rs @@ -110,6 +110,7 @@ fn bed_with(yaml: &str, seed: impl FnOnce(&tw_store::Db)) -> Bed { let gw = tw_gateway::AppState::new(cfg).unwrap(); let bus = gw.bus.clone(); let state = ControlState { + shutdown: Default::default(), cfg: Arc::new(ConfigManager::new(p, gw.clone(), bus)), gateway: gw, store: Some(Arc::new(tokio::sync::Mutex::new(rec))), diff --git a/crates/tw-control/tests/sessions.rs b/crates/tw-control/tests/sessions.rs index b3e28224..24a02dca 100644 --- a/crates/tw-control/tests/sessions.rs +++ b/crates/tw-control/tests/sessions.rs @@ -64,6 +64,7 @@ fn app(rows: &[tw_store::db::RequestRow]) -> (tempfile::TempDir, axum::Router) { let gw = tw_gateway::AppState::new(cfg).unwrap(); let bus = gw.bus.clone(); let state = ControlState { + shutdown: Default::default(), cfg: Arc::new(ConfigManager::new(p, gw.clone(), bus)), gateway: gw, store: Some(Arc::new(tokio::sync::Mutex::new(rec))), diff --git a/crates/tw-control/tests/speed.rs b/crates/tw-control/tests/speed.rs index 9f1b7762..9679dc02 100644 --- a/crates/tw-control/tests/speed.rs +++ b/crates/tw-control/tests/speed.rs @@ -24,6 +24,7 @@ fn bed(yaml: &str) -> Bed { let gw = tw_gateway::AppState::new(cfg).unwrap(); let bus = gw.bus.clone(); let state = ControlState { + shutdown: Default::default(), cfg: Arc::new(ConfigManager::new(p, gw.clone(), bus)), gateway: gw, store: None, diff --git a/crates/tw-control/tests/zai.rs b/crates/tw-control/tests/zai.rs index 087eae8d..1aa50352 100644 --- a/crates/tw-control/tests/zai.rs +++ b/crates/tw-control/tests/zai.rs @@ -278,6 +278,7 @@ async fn bed(extra: impl FnOnce(&Endpoints) -> String) -> Bed { let bus = gw.bus.clone(); let events = bus.subscribe(); let state = ControlState { + shutdown: Default::default(), cfg: Arc::new(ConfigManager::new(p, gw.clone(), bus)), gateway: gw, store: None, diff --git a/scripts/smoke.sh b/scripts/smoke.sh index e3401fe7..463ea80d 100755 --- a/scripts/smoke.sh +++ b/scripts/smoke.sh @@ -434,6 +434,34 @@ else bad "经过网关多花了 ${OVER}ms,目标是解析加路由 < 2ms、中继 < 1ms" fi +# ---------------------------------------------------------------- 请它退出 +# +# **放在最后**:这一条真的会把 core 停掉,后面就没有控制面可用了。 +# +# 这是整条链唯一被端到端验证的地方 —— 一条 HTTP 请求扳开关、主循环的 +# select 醒过来、进程自己退出。单元测试能证明开关会被扳动,证明不了它 +# 接在主循环上;而接错的样子是请求返回 202、进程稳稳地继续跑。 +step "请它退出,它就退" +CODE=$(curl -s -o "$TMP/out" -w '%{http_code}' --unix-socket "$SOCK" "${AUTH[@]}" \ + -XPOST http://localhost/shutdown) +if [ "$CODE" = 202 ]; then + ok "控制面收下了这条请求" +else + bad "请它退出返回 $CODE" "$(cat "$TMP/out")" +fi +# 给它几秒真正退出。**等的是进程没了,不是 socket 没了** —— 后者在 +# 一个卡住的进程上也可能发生。 +GONE=0 +for _ in $(seq 1 50); do + kill -0 "$CORE_PID" 2>/dev/null || { GONE=1; break; } + sleep 0.2 +done +if [ "$GONE" = 1 ]; then + ok "进程在几秒内自己退了" +else + bad "请过它退出之后,进程还在跑(pid $CORE_PID)" +fi + # ---------------------------------------------------------------- 收尾 step "结果" printf '通过 %d,失败 %d,超标但没回归 %d\n' "$PASS" "$FAIL" "$WARN"