diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml index 72403713..f0d7a1d7 100644 --- a/.github/workflows/ci.yml +++ b/.github/workflows/ci.yml @@ -44,3 +44,99 @@ jobs: # 脚本自己会 build,这一步只是跑它。 - name: Smoke (real binary, real socket, real data plane) run: ./scripts/smoke.sh + + # **这台机器上没有 unix socket,也没有信号。**core 在这两件事上各有一套 + # 平台实现,而在这个任务出现之前,Windows 那一半从来没有被编译过 —— + # 一个 `#[cfg(windows)]` 模块「检查通过」和「根本没人看过它」长得一模一样。 + # + # 不重复跑 `cargo fmt`:格式和平台无关,跑两遍只是慢一倍。 + windows: + runs-on: windows-latest + steps: + - uses: actions/checkout@v4 + - uses: dtolnay/rust-toolchain@stable + with: + components: clippy + - uses: Swatinem/rust-cache@v2 + with: + # **失败也存。**这个 action 默认只在任务成功时保存缓存,而一个 + # 刚立起来、还在逐条修的任务恰恰一次都不会成功 —— 于是「红 → + # 不存缓存 → 从零编译 → 还是红」自己维持住了,每一轮都要把 + # rusqlite 的 SQLite 和 aws-lc-sys 重编一遍。 + # + # cargo 自己按指纹判断哪些要重编,所以缓存下一个失败构建的 + # target 目录是安全的,它只是省掉那些与失败无关的部分。 + cache-on-failure: true + + - name: clippy + run: cargo clippy --workspace --all-targets -- -D warnings + + - name: Test + run: cargo test --workspace + + - name: Build + run: cargo build --release -p twcore + + # macOS 那边的 smoke 脚本在这里跑不了(`stat -f`、`curl --unix-socket`、 + # 一堆 BSD 的写法),移植它是另一件事。但**至少要证明这个二进制真的 + # 起得来、控制面真的应答** —— 那两样恰恰是这个平台上和 unix 完全不同的 + # 实现:回环端口换掉了 socket,凭据是唯一的门。 + # + # 不验这个的话,Windows 上的失败模式是「CI 全绿,而用户装上之后界面 + # 永远停在连接页」。 + - name: It starts, and the control plane answers only with the token + shell: pwsh + run: | + $ErrorActionPreference = "Stop" + $home_ = Join-Path $env:RUNNER_TEMP "tw" + New-Item -ItemType Directory -Force -Path $home_ | Out-Null + $env:THINKWATCH_HOME = $home_ + $cfg = Join-Path $home_ "config.yaml" + $proc = Start-Process -FilePath "target\release\twcore.exe" ` + -ArgumentList "serve","--config",$cfg,"--port","18999" ` + -PassThru -NoNewWindow ` + -RedirectStandardOutput (Join-Path $home_ "out.log") ` + -RedirectStandardError (Join-Path $home_ "err.log") + + # 端口是 core 绑到之后才写出来的,所以它出现就等于「听起来了」 + $portFile = Join-Path $home_ "control.port" + $deadline = (Get-Date).AddSeconds(60) + while (-not (Test-Path $portFile)) { + if ($proc.HasExited) { + Get-Content (Join-Path $home_ "err.log") -ErrorAction SilentlyContinue + throw "core exited before it started listening (code $($proc.ExitCode))" + } + if ((Get-Date) -gt $deadline) { + Get-Content (Join-Path $home_ "err.log") -ErrorAction SilentlyContinue + throw "core never wrote $portFile" + } + Start-Sleep -Milliseconds 200 + } + $port = (Get-Content $portFile -Raw).Trim() + $token = (Get-Content (Join-Path $home_ "control.token") -Raw).Trim() + $url = "http://127.0.0.1:$port/status" + Write-Host "control plane on $port" + + try { + $no = Invoke-WebRequest -Uri $url -SkipHttpErrorCheck -TimeoutSec 10 + if ($no.StatusCode -ne 401) { throw "without a token the control plane answered $($no.StatusCode), not 401" } + + $yes = Invoke-WebRequest -Uri $url -TimeoutSec 10 -Headers @{ Authorization = "Bearer $token" } + if ($yes.StatusCode -ne 200) { throw "with the token it answered $($yes.StatusCode)" } + $status = $yes.Content | ConvertFrom-Json + if (-not $status.version) { throw "the status carried no version: $($yes.Content)" } + Write-Host "gateway $($status.version), api $($status.api_version)" + # **请它退出,它就该退。**这条路在这个平台上没有替代品: + # 没有 SIGTERM,而桌面端要靠它在改完配置后重启 core、在装更新 + # 之前停掉它。只能强杀意味着 WAL 不收尾、在途请求断在半路。 + $bye = Invoke-WebRequest -Uri "http://127.0.0.1:$port/shutdown" -Method Post ` + -TimeoutSec 10 -Headers @{ Authorization = "Bearer $token" } + if ($bye.StatusCode -ne 202) { throw "asking it to exit answered $($bye.StatusCode)" } + # 等**进程**没了,不是等端口没了 —— 一个卡住的进程也可能丢掉监听 + if (-not $proc.WaitForExit(10000)) { + throw "it was asked to exit and is still running after 10s" + } + Write-Host "it exited on request" + } finally { + Stop-Process -Id $proc.Id -Force -ErrorAction SilentlyContinue + } diff --git a/bin/twcore/src/lockfile.rs b/bin/twcore/src/lockfile.rs index a141afc1..c046489c 100644 --- a/bin/twcore/src/lockfile.rs +++ b/bin/twcore/src/lockfile.rs @@ -66,7 +66,8 @@ mod tests { fn a_stale_lock_from_a_dead_process_is_taken_over() { // 「上次没退干净」是最常见的情况,不该需要用户手动删文件。 let d = tempfile::tempdir().unwrap(); - // pid 1 之外挑一个几乎肯定不存在的 + // 挑一个几乎肯定不存在的。Windows 的 pid 都是 4 的倍数,所以 + // 999999 在那里根本不可能是一个 pid;macOS 的 pid_max 是 99998。 std::fs::write(d.path().join("twcore.lock"), "999999").unwrap(); assert!(matches!( LockFile::acquire(d.path()).unwrap(), @@ -84,13 +85,40 @@ mod tests { )); } + /// 一个会活一会儿的子进程。 + /// + /// **不借用 pid 1。**那在 unix 上是 init/launchd,而 Windows 上根本没有 + /// 这个 pid —— 这条测试要的只是「一个确实活着、又不是我们自己的 pid」, + /// 起一个就是了,不必挑一个碰巧存在的。 + fn sleeping_child() -> std::process::Child { + #[cfg(windows)] + // `timeout` 要一个控制台,测试进程里没有;`ping` 不要 + let mut c = std::process::Command::new("ping"); + #[cfg(windows)] + c.args(["-n", "60", "127.0.0.1"]); + #[cfg(not(windows))] + let mut c = std::process::Command::new("sleep"); + #[cfg(not(windows))] + c.arg("60"); + c.stdout(std::process::Stdio::null()) + .stderr(std::process::Stdio::null()) + .spawn() + .expect("起一个会活一会儿的子进程") + } + #[test] fn a_live_pid_blocks_and_reports_who() { let d = tempfile::tempdir().unwrap(); - // 用 pid 1(init/launchd),它一定活着且不是我们 - std::fs::write(d.path().join("twcore.lock"), "1").unwrap(); - match LockFile::acquire(d.path()).unwrap() { - LockOutcome::AlreadyRunning { pid } => assert_eq!(pid, 1), + let mut child = sleeping_child(); + let alive = child.id(); + std::fs::write(d.path().join("twcore.lock"), alive.to_string()).unwrap(); + let got = LockFile::acquire(d.path()); + // **先收尸再断言** —— 断言失败会 panic,而 panic 之后这个子进程 + // 就留在那儿活满六十秒 + let _ = child.kill(); + let _ = child.wait(); + match got.unwrap() { + LockOutcome::AlreadyRunning { pid } => assert_eq!(pid, alive), other => panic!("应该被挡住,实际 {other:?}"), } } diff --git a/bin/twcore/tests/copy.rs b/bin/twcore/tests/copy.rs index 44a76cd6..58180961 100644 --- a/bin/twcore/tests/copy.rs +++ b/bin/twcore/tests/copy.rs @@ -224,11 +224,19 @@ fn product_text_is_written_not_spoken() { let mut found = Vec::new(); for f in &files { - let rel = f.strip_prefix(&root).unwrap_or(f).display().to_string(); - // 集成测试和这个文件自己都不查 - if rel.contains("/tests/") { + let rel_path = f.strip_prefix(&root).unwrap_or(f); + // 集成测试和这个文件自己都不查。 + // + // **按路径的组成部分判断,不在字符串里找斜杠。**Windows 上分隔符是 + // `\`,`contains("/tests/")` 在那里恒为 false —— 于是这个测试开始扫 + // 测试文件,而第一个撞上的就是它自己那张禁用词表。 + if rel_path + .components() + .any(|c| c.as_os_str().eq_ignore_ascii_case("tests")) + { continue; } + let rel = rel_path.display().to_string(); let src = std::fs::read_to_string(f).unwrap(); // 看的是产品代码那一半(测试模块在文件末尾) let product = src.split("#[cfg(test)]").next().unwrap(); diff --git a/crates/tw-adopt/src/foreign.rs b/crates/tw-adopt/src/foreign.rs index c9a8edff..d7ced737 100644 --- a/crates/tw-adopt/src/foreign.rs +++ b/crates/tw-adopt/src/foreign.rs @@ -387,7 +387,6 @@ pub fn apply( #[cfg(test)] mod tests { use super::*; - use std::io::Write as _; fn ok(_: &str) -> Result<(), String> { Ok(()) @@ -422,6 +421,10 @@ mod tests { assert!(strays.is_empty(), "留下了临时文件:{strays:?}"); } + // **unix 专有。**Windows 上建符号链接要特权,跟随的语义也不一样 —— + // `resolve` 在那边走的是另一条分支(见 `cfg(not(unix))`),而那条分支 + // 眼下没有测试覆盖,要等接管整体支持 Windows 时一起补。 + #[cfg(unix)] #[test] fn a_symlink_is_written_through_to_its_target() { // cc-switch #6785:直接 rename 会把 dotfile 管理器的软链换成 @@ -612,10 +615,14 @@ mod tests { assert_eq!(std::fs::read_to_string(&p).unwrap(), "{}"); } + // **unix 专有。**Windows 没有 mode 位,「这个文件对别人也可读」那条 + // 判断在那边是 ACL 的事,是另一套。 + #[cfg(unix)] #[test] fn the_original_permissions_are_kept_and_a_loose_one_is_reported() { // 不擅自 chmod:那超出了「只改 endpoint 和 key 字段」的边界。 // 报告是我们的职责,修改是他的权利。 + use std::io::Write as _; use std::os::unix::fs::PermissionsExt; let (d, root) = dirs(); let p = d.path().join("c.json"); @@ -643,6 +650,7 @@ mod tests { ); } + #[cfg(unix)] #[test] fn a_tight_file_carrying_a_secret_gets_no_warning() { use std::os::unix::fs::PermissionsExt; @@ -664,6 +672,7 @@ mod tests { assert!(a.warnings.is_empty(), "{:?}", a.warnings); } + #[cfg(unix)] #[test] fn a_symlink_loop_is_refused_instead_of_hanging() { let d = tempfile::tempdir().unwrap(); @@ -674,6 +683,7 @@ mod tests { assert!(matches!(resolve(&a), Err(ForeignError::LinkLoop { .. }))); } + #[cfg(unix)] #[test] fn a_relative_symlink_resolves_against_its_own_directory() { let d = tempfile::tempdir().unwrap(); diff --git a/crates/tw-config/src/nics.rs b/crates/tw-config/src/nics.rs index 7045db5a..08acc852 100644 --- a/crates/tw-config/src/nics.rs +++ b/crates/tw-config/src/nics.rs @@ -154,13 +154,16 @@ mod windows { GAA_FLAG_SKIP_ANYCAST, GAA_FLAG_SKIP_DNS_SERVER, GAA_FLAG_SKIP_MULTICAST, GetAdaptersAddresses, IP_ADAPTER_ADDRESSES_LH, }; + use windows_sys::Win32::NetworkManagement::Ndis::IF_OPER_STATUS; use windows_sys::Win32::Networking::WinSock::{ AF_INET, AF_INET6, AF_UNSPEC, SOCKADDR_IN, SOCKADDR_IN6, }; /// `IfOperStatusUp`。**只认「up」这一档**,和 unix 那边的 `IFF_UP` 对齐: /// 「正在连」「已断开」的网卡绑不上去。 - const OPER_STATUS_UP: i32 = 1; + /// + /// 类型跟着 `IF_OPER_STATUS` 走(就是 `i32`),这样比较的时候不用转换。 + const OPER_STATUS_UP: IF_OPER_STATUS = 1; /// 一张网卡上我们关心的东西。 struct Adapter { @@ -271,7 +274,7 @@ mod windows { } out.push(Adapter { name, - up: a.OperStatus as i32 == OPER_STATUS_UP, + up: a.OperStatus == OPER_STATUS_UP, addrs, }); } diff --git a/crates/tw-control/Cargo.toml b/crates/tw-control/Cargo.toml index b100c8e6..22048e61 100644 --- a/crates/tw-control/Cargo.toml +++ b/crates/tw-control/Cargo.toml @@ -52,4 +52,6 @@ tempfile = "3" tw-observe = { workspace = true } tw-api = { workspace = true } tw-types = { workspace = true } +# 网卡那条断言要对着本机真实的清单比,不写死某个平台的名字 +tw-config = { workspace = true } tokio = { workspace = true, features = ["rt", "macros"] } diff --git a/crates/tw-control/tests/listen.rs b/crates/tw-control/tests/listen.rs index acaa4ca4..592cae68 100644 --- a/crates/tw-control/tests/listen.rs +++ b/crates/tw-control/tests/listen.rs @@ -175,11 +175,18 @@ async fn an_interface_that_is_not_there_is_refused_by_name() { assert_eq!(st, StatusCode::CONFLICT, "{v}"); assert_eq!(v["code"], "gw.listen.no_such_nic"); assert_eq!(v["args"]["name"], "en97"); - // 真有哪些网卡一并说出来,用户不必再去跑一次 ifconfig - assert!( - v["args"]["available"].as_str().unwrap().contains("lo0"), - "{v}" - ); + // 真有哪些网卡一并说出来,用户不必再去跑一次 ifconfig。 + // + // **不写死任何一个名字。**原来这里断言的是 `lo0`,而那是这台机器的 + // 名字,不是这条断言要说的事 —— Windows 上回环叫「Loopback + // Pseudo-Interface 1」,网卡叫「Ethernet 3」。改成对着本机真实的清单 + // 比,反而比原来强:它要求**每一张**都列出来了,不是碰巧有一张。 + let listed = v["args"]["available"].as_str().unwrap(); + let here = tw_config::nics::by_name(); + assert!(!here.is_empty(), "本机一张网卡都没有?"); + for n in &here { + assert!(listed.contains(&n.name), "{} 不在「{listed}」里", n.name); + } assert_eq!(b.file(), before); // 写法本身不对的,按配置文件的那套规则说