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
19 changes: 15 additions & 4 deletions bin/twcore/src/main.rs
Original file line number Diff line number Diff line change
Expand Up @@ -728,6 +728,9 @@ fn cmd_serve(path: &Path, port: Option<u16>, safe: bool, parent: Option<u32>) ->
// **在起任何东西之前问**。等到 bind 失败时,网关已经在监听、客户端
// 可能已经连上来了,而这条错误当时只会进日志。
tw_control::endpoint_usable(&endpoint)?;
// 「该退了」的开关。**在起任何东西之前建好** —— 控制面和主循环各拿
// 一份,而控制面可能在主循环开始等之前就收到那条请求。
let shutdown = tw_control::Shutdown::default();
// 控制面的凭据,同样在起任何东西之前拿到:桌面端从环境变量交过来,
// 手工启动时生成一个写进配置目录。取不到就停在这儿 —— 一个装不上门的
// 控制面不该先起来再说。
Expand Down Expand Up @@ -810,6 +813,7 @@ fn cmd_serve(path: &Path, port: Option<u16>, safe: bool, parent: Option<u32>) ->
// 控制面无论如何都要起来 —— **网关挂了的时候,用户最需要的恰恰
// 是能改配置**。安全模式就是「只有这一半」。
let control = tw_control::ControlState {
shutdown: shutdown.clone(),
home: tw_control::home_dir(),
started: std::time::Instant::now(),
gateway: state.clone(),
Expand Down Expand Up @@ -878,7 +882,7 @@ fn cmd_serve(path: &Path, port: Option<u16>, safe: bool, parent: Option<u32>) ->
msg = control_dead => {
anyhow::bail!("{}", msg.unwrap_or_else(|_| "the control plane stopped".into()))
}
_ = shutdown_signal() => {}
_ = shutdown_requested(&shutdown) => {}
}
return Ok(());
}
Expand All @@ -895,7 +899,7 @@ fn cmd_serve(path: &Path, port: Option<u16>, safe: bool, parent: Option<u32>) ->
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(())
}
Expand Down Expand Up @@ -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();
};
Expand All @@ -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() => {} }
}
9 changes: 8 additions & 1 deletion crates/tw-api/src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -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 {
Expand Down
25 changes: 25 additions & 0 deletions crates/tw-control/src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -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)]
Expand All @@ -58,6 +60,8 @@ pub struct ControlState {
/// Z.ai / BigModel 账号的登录。**同一时刻也只有一次** —— 理由不是端口,是
/// 「一次登录」在界面上就是一件正在进行的事,两件同时进行没人说得清哪件成了
pub zai: Arc<zai::Accounts>,
/// 请网关退出的那个开关。控制面上的 `POST /shutdown` 扳它,主循环等它。
pub shutdown: Shutdown,
/// 用户的 home。接管要顺着它去找各客户端的配置。
///
/// **是个字段,不是每次现读 `$HOME`。**进程级的环境变量是全局可变
Expand Down Expand Up @@ -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())
Expand Down Expand Up @@ -187,6 +192,26 @@ async fn interfaces() -> Json<Vec<tw_api::NicView>> {
)
}

/// 请网关退出。
///
/// 理由见 [`shutdown`] 那个模块:Windows 上没有 SIGTERM,而桌面端要在改完
/// 配置之后重启 core、在装更新之前停掉它并且等它真的退出。
async fn ask_shutdown(State(s): State<ControlState>) -> (StatusCode, Json<Msg>) {
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<ControlState>) -> Json<tw_api::Status> {
let cfg = s.config();
let listening = s.gateway.listening();
Expand Down
69 changes: 69 additions & 0 deletions crates/tw-control/src/shutdown.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,69 @@
//! 请网关退出。
//!
//! # 为什么这是控制面上的一条请求,而不是一个信号
//!
//! **Windows 上没有 SIGTERM。**而桌面端有两件事非做不可:改完配置之后重启
//! core,以及装更新之前停掉它并且**等它真的退出**(不等的话,新起来的那个
//! 会撞上旧的还没放开的锁)。那个平台上能用的只剩强杀,而强杀意味着 SQLite
//! 的 WAL 没有收尾、在途的请求直接断在半路。
//!
//! 所以做成一条请求。它比信号还好一点:**有应答**,桌面端因此知道对方收到了,
//! 而不是发完信号去猜。
//!
//! 两个平台都走它。只在一个平台上生效的路径,是没人日常测的路径。

use std::sync::Arc;

/// 一个「该退了」的开关。
#[derive(Clone, Default)]
pub struct Shutdown(Arc<tokio::sync::Notify>);

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("先到的那次请求被丢了");
}
}
1 change: 1 addition & 0 deletions crates/tw-control/tests/adopt.rs
Original file line number Diff line number Diff line change
Expand Up @@ -34,6 +34,7 @@ fn bed_with_store(store: Option<std::sync::Arc<tokio::sync::Mutex<tw_store::Reco
let home = d.path().join("home");
std::fs::create_dir_all(home.join(".claude")).unwrap();
let state = ControlState {
shutdown: Default::default(),
cfg: Arc::new(ConfigManager::new(p, gw.clone(), bus)),
gateway: gw,
store,
Expand Down
1 change: 1 addition & 0 deletions crates/tw-control/tests/chatgpt.rs
Original file line number Diff line number Diff line change
Expand Up @@ -348,6 +348,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,
Expand Down
1 change: 1 addition & 0 deletions crates/tw-control/tests/dryrun.rs
Original file line number Diff line number Diff line change
Expand Up @@ -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,
Expand Down
1 change: 1 addition & 0 deletions crates/tw-control/tests/in_flight.rs
Original file line number Diff line number Diff line change
Expand Up @@ -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,
Expand Down
1 change: 1 addition & 0 deletions crates/tw-control/tests/keys.rs
Original file line number Diff line number Diff line change
Expand Up @@ -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,
Expand Down
1 change: 1 addition & 0 deletions crates/tw-control/tests/listen.rs
Original file line number Diff line number Diff line change
Expand Up @@ -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,
Expand Down
1 change: 1 addition & 0 deletions crates/tw-control/tests/live_state.rs
Original file line number Diff line number Diff line change
Expand Up @@ -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,
Expand Down
1 change: 1 addition & 0 deletions crates/tw-control/tests/m4_acceptance.rs
Original file line number Diff line number Diff line change
Expand Up @@ -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,
Expand Down
1 change: 1 addition & 0 deletions crates/tw-control/tests/models.rs
Original file line number Diff line number Diff line change
Expand Up @@ -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,
Expand Down
1 change: 1 addition & 0 deletions crates/tw-control/tests/pricing.rs
Original file line number Diff line number Diff line change
Expand Up @@ -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,
Expand Down
1 change: 1 addition & 0 deletions crates/tw-control/tests/resources.rs
Original file line number Diff line number Diff line change
Expand Up @@ -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,
Expand Down
1 change: 1 addition & 0 deletions crates/tw-control/tests/routes.rs
Original file line number Diff line number Diff line change
Expand Up @@ -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,
Expand Down
1 change: 1 addition & 0 deletions crates/tw-control/tests/security.rs
Original file line number Diff line number Diff line change
Expand Up @@ -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))),
Expand Down
1 change: 1 addition & 0 deletions crates/tw-control/tests/sessions.rs
Original file line number Diff line number Diff line change
Expand Up @@ -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))),
Expand Down
1 change: 1 addition & 0 deletions crates/tw-control/tests/speed.rs
Original file line number Diff line number Diff line change
Expand Up @@ -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,
Expand Down
1 change: 1 addition & 0 deletions crates/tw-control/tests/zai.rs
Original file line number Diff line number Diff line change
Expand Up @@ -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,
Expand Down
28 changes: 28 additions & 0 deletions scripts/smoke.sh
Original file line number Diff line number Diff line change
Expand Up @@ -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"
Expand Down
Loading