From e59e0d45344a79136c15213b1541bfa3087715fb Mon Sep 17 00:00:00 2001 From: fylorn <249551762+fylorn@users.noreply.github.com> Date: Thu, 24 Sep 2026 16:17:26 +0800 Subject: [PATCH 1/2] feat: Linux twcore release builds, Linux CI, and a NIC list that skips unplugged and virtual-first interfaces - release.yml: build twcore natively for x86_64-unknown-linux-gnu (ubuntu-22.04) and aarch64-unknown-linux-gnu (ubuntu-22.04-arm); check the architecture with `file`, the version against the tag, and fail if the binary needs a glibc newer than 2.35. Same asset and .sha256 naming as the other platforms. glibc, not musl: the desktop app needs glibc 2.35 anyway. - ci.yml: an ubuntu-22.04 job running clippy, the workspace tests and the smoke script. smoke.sh now asks GNU stat first (BSD `stat -f` means something else on GNU and still exits 0) and honours CARGO_TARGET_DIR. - nics: list only interfaces that are up *and* running (IFF_RUNNING), so an unplugged NIC or an idle docker0/br-* no longer shows up; on Linux, interfaces backed by a device (/sys/class/net//device) sort before virtual ones. exists() is unchanged. - A bound interface that is present but unusable now reports gw.listen.nic_offline ("is not connected right now") instead of gw.listen.nic_no_addr: a disconnected interface often still has an address. - lockfile test no longer assumes pid 999999 cannot exist (Linux pid_max is 4194304 under systemd); the --parent watcher comment covers systemd --user as the subreaper. Co-Authored-By: Claude Opus 5.5 --- .github/workflows/ci.yml | 27 +++++ .github/workflows/release.yml | 97 ++++++++++++++++++ bin/twcore/src/lockfile.rs | 16 ++- bin/twcore/src/main.rs | 7 +- crates/tw-api/msg-codes.txt | 2 +- crates/tw-config/src/lib.rs | 12 ++- crates/tw-config/src/nics.rs | 168 +++++++++++++++++++++++++++++--- crates/tw-control/src/token.rs | 2 +- crates/tw-gateway/src/listen.rs | 8 +- scripts/smoke.sh | 14 ++- 10 files changed, 319 insertions(+), 34 deletions(-) diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml index 98d0e401..a376c995 100644 --- a/.github/workflows/ci.yml +++ b/.github/workflows/ci.yml @@ -128,6 +128,33 @@ jobs: working-directory: enterprise run: cargo check --workspace --all-targets + # **同是 unix,不等于和 macOS 一样。**`getifaddrs` 给的标志、sysfs 里有 + # 没有 `device`、pid 的上限、`stat` 的参数,这些在 macOS 上测过不说明 + # 任何事 —— 而桌面版要在 22.04 上跑,所以就在 22.04 上测。 + # + # 不重复跑 `cargo fmt`:格式和平台无关。 + linux: + runs-on: ubuntu-22.04 + steps: + - uses: actions/checkout@v4 + - uses: dtolnay/rust-toolchain@stable + with: + components: clippy + - uses: Swatinem/rust-cache@v2 + with: + # 理由见下面 windows 那一段 + cache-on-failure: true + + - name: clippy + run: cargo clippy --workspace --all-targets -- -D warnings + + - name: Test + run: cargo test --workspace + + # 真二进制、真 socket、真数据面,和 macOS 那一步是同一个脚本 + - name: Smoke (real binary, real socket, real data plane) + run: ./scripts/smoke.sh + # **这台机器上没有 unix socket,也没有信号。**core 在这两件事上各有一套 # 平台实现,而在这个任务出现之前,Windows 那一半从来没有被编译过 —— # 一个 `#[cfg(windows)]` 模块「检查通过」和「根本没人看过它」长得一模一样。 diff --git a/.github/workflows/release.yml b/.github/workflows/release.yml index 7993f02d..79be20ee 100644 --- a/.github/workflows/release.yml +++ b/.github/workflows/release.yml @@ -173,3 +173,100 @@ jobs: dist/twcore-aarch64-pc-windows-msvc.exe dist/twcore-aarch64-pc-windows-msvc.exe.sha256 generate_release_notes: true + + twcore-linux: + name: twcore (${{ matrix.target }}) + # **两个架构都原生编**,各在自己架构的 runner 上 —— 交叉编 aarch64 要 + # 一套 aarch64 的 glibc sysroot 和链接器,而 GitHub 给公开仓库提供了 + # arm64 的 Linux runner(`ubuntu-22.04-arm`),原生编还能顺手把产物 + # 跑一遍,交叉编的跑不了。 + # + # **两个都是 22.04,不是 24.04。**glibc 只向后兼容:在 2.39(24.04)上 + # 链出来的二进制,拿到 2.35(22.04)上会报 `GLIBC_2.38 not found` 起不来。 + # 桌面版在 Linux 上的底线就是 22.04(WebKitGTK 4.1),core 跟它对齐。 + # + # **不用 musl 静态编。**它能摆脱 glibc 版本,但桌面版本体反正要 glibc + # 2.35+,core 单独摆脱它换不来什么;而 musl 的内存分配器在多线程下慢得 + # 多、DNS 解析的行为和 glibc 不同 —— 用户机器上出了问题,排查的是一个 + # 和系统里其他程序都不一样的运行时。同一个 glibc 底线,排查也简单。 + strategy: + fail-fast: false + matrix: + include: + - target: x86_64-unknown-linux-gnu + runner: ubuntu-22.04 + file_arch: x86-64 + - target: aarch64-unknown-linux-gnu + runner: ubuntu-22.04-arm + file_arch: ARM aarch64 + runs-on: ${{ matrix.runner }} + steps: + - uses: actions/checkout@v4 + - uses: dtolnay/rust-toolchain@stable + with: + targets: ${{ matrix.target }} + - uses: Swatinem/rust-cache@v2 + with: + key: ${{ matrix.target }} + + - name: Build + run: cargo build --release -p twcore --target ${{ matrix.target }} + + # **产物自检。**一个编得过但起不来的二进制,从文件列表上看不出任何 + # 问题 —— 而它会一路发到用户手里。 + # + # 比 macOS 那段多一条 glibc 的上限:runner 的镜像哪天换了、或者有人把 + # 上面的 22.04 改成了 latest,产物就会悄悄要求一个更新的 glibc,而在 + # 构建机上它照样跑得起来 —— 只有用户的 22.04 上起不来。 + - name: It runs, it is the version on the tag, and it needs glibc 2.35 at most + env: + FILE_ARCH: ${{ matrix.file_arch }} + run: | + set -euo pipefail + BIN=target/${{ matrix.target }}/release/twcore + file "$BIN" + file "$BIN" | grep -q "$FILE_ARCH" + + MAX_GLIBC=2.35 + NEED=$(objdump -T "$BIN" | grep -o 'GLIBC_[0-9][0-9.]*' | sed 's/GLIBC_//' | sort -uV | tail -n 1) + if [ -z "$NEED" ]; then + echo "objdump found no GLIBC_ symbol versions in $BIN" >&2 + exit 1 + fi + echo "needs glibc $NEED (limit $MAX_GLIBC)" + if [ "$(printf '%s\n%s\n' "$NEED" "$MAX_GLIBC" | sort -V | tail -n 1)" != "$MAX_GLIBC" ]; then + echo "twcore needs glibc $NEED, newer than $MAX_GLIBC (Ubuntu 22.04)" >&2 + exit 1 + fi + + GOT=$("$BIN" --version | awk '{print $2}') + # 排练时没有 tag 可对,只把版本打出来 + if [ "$GITHUB_REF_TYPE" = tag ]; then + WANT="${GITHUB_REF_NAME#v}" + if [ "$GOT" != "$WANT" ]; then + echo "the tag says $WANT but the binary reports $GOT -- Cargo.toml did not keep up" >&2 + exit 1 + fi + else + echo "rehearsal: the binary reports $GOT" + fi + "$BIN" --help > /dev/null + + - name: Package + run: | + set -euo pipefail + mkdir -p dist + cp target/${{ matrix.target }}/release/twcore dist/twcore-${{ matrix.target }} + cd dist + # 和另外两个平台同一种校验文件:` <文件名>` + sha256sum twcore-${{ matrix.target }} > twcore-${{ matrix.target }}.sha256 + cat twcore-${{ matrix.target }}.sha256 + + - uses: softprops/action-gh-release@v2 + # 排练不发布。 + if: github.ref_type == 'tag' + with: + files: | + dist/twcore-${{ matrix.target }} + dist/twcore-${{ matrix.target }}.sha256 + generate_release_notes: true diff --git a/bin/twcore/src/lockfile.rs b/bin/twcore/src/lockfile.rs index c046489c..ce67c03c 100644 --- a/bin/twcore/src/lockfile.rs +++ b/bin/twcore/src/lockfile.rs @@ -66,9 +66,19 @@ mod tests { fn a_stale_lock_from_a_dead_process_is_taken_over() { // 「上次没退干净」是最常见的情况,不该需要用户手动删文件。 let d = tempfile::tempdir().unwrap(); - // 挑一个几乎肯定不存在的。Windows 的 pid 都是 4 的倍数,所以 - // 999999 在那里根本不可能是一个 pid;macOS 的 pid_max 是 99998。 - std::fs::write(d.path().join("twcore.lock"), "999999").unwrap(); + // **不编一个 pid。**以前这里写死 999999,理由是 macOS 的 pid_max + // 是 99998、Windows 的 pid 都是 4 的倍数 —— 而 Linux 上 systemd 把 + // pid_max 设成 4194304,999999 完全可能是一个活着的进程。起一个、 + // 等它退干净,拿它的号:这个号此刻一定没人用(除非刚好被回收, + // 那个窗口比编一个号小得多)。 + let pid = { + let mut c = sleeping_child(); + let pid = c.id(); + c.kill().unwrap(); + c.wait().unwrap(); + pid + }; + std::fs::write(d.path().join("twcore.lock"), pid.to_string()).unwrap(); assert!(matches!( LockFile::acquire(d.path()).unwrap(), LockOutcome::Acquired(_) diff --git a/bin/twcore/src/main.rs b/bin/twcore/src/main.rs index 9dd161dc..c760e914 100644 --- a/bin/twcore/src/main.rs +++ b/bin/twcore/src/main.rs @@ -861,8 +861,11 @@ fn cmd_serve(path: &Path, port: Option, safe: bool, parent: Option) -> if let Some(ppid) = parent { // 父进程守望:GUI 没了我们跟着退。轮询而不是用 kqueue,是因为 - // 这段代码要能在被 launchd 重新 parent 之后仍然正确 —— 那时 - // getppid() 会变成 1,而我们要看的是原来那个 pid 还在不在。 + // 这段代码要能在被重新 parent 之后仍然正确 —— macOS 上收养我们的 + // 是 launchd(getppid() 变成 1),Linux 桌面会话里多半是 + // `systemd --user`(它是 subreaper,getppid() 变成它的 pid,不是 1)。 + // 所以**不看 getppid()**,只看原来那个 pid 还在不在,哪个平台、 + // 谁来收养都一样。 tokio::spawn(async move { loop { tokio::time::sleep(std::time::Duration::from_secs(2)).await; diff --git a/crates/tw-api/msg-codes.txt b/crates/tw-api/msg-codes.txt index 556324a2..32875b99 100644 --- a/crates/tw-api/msg-codes.txt +++ b/crates/tw-api/msg-codes.txt @@ -300,7 +300,7 @@ gw.internal gw.listen.addr_unavailable gw.listen.bind_failed gw.listen.denied -gw.listen.nic_no_addr +gw.listen.nic_offline gw.listen.no_such_nic gw.listen.port_taken gw.model.no_upstream diff --git a/crates/tw-config/src/lib.rs b/crates/tw-config/src/lib.rs index 85598666..4cc4b70c 100644 --- a/crates/tw-config/src/lib.rs +++ b/crates/tw-config/src/lib.rs @@ -343,9 +343,13 @@ pub enum BindError { name: String, available: Vec, }, - /// 网卡在,但此刻没有地址:网线拔了、Wi-Fi 没连上、还没拿到 DHCP。 - #[error("interface `{name}` currently has no address")] - NicHasNoAddr { name: String }, + /// 网卡在,但此刻用不了:网线拔了、Wi-Fi 没连上、还没拿到 DHCP。 + /// + /// **不说「没有地址」。**没连上的网卡常常还挂着地址(静态配的、或者 + /// 一个没有容器接着的 `docker0`),[`nics::list`] 按「连着没有」把它们 + /// 筛掉了 —— 这时说「没有地址」是错的,而用户要做的事两种情况一样。 + #[error("interface `{name}` is not connected right now")] + NicOffline { name: String }, } impl Bind { @@ -361,7 +365,7 @@ impl Bind { // 界面上的选单列的也是它,选单上写的就是真要监听的那个 Bind::Nic(name) => match nics::by_name().into_iter().find(|n| n.name == *name) { Some(n) => Ok(n.addr), - None if nics::exists(name) => Err(BindError::NicHasNoAddr { name: name.clone() }), + None if nics::exists(name) => Err(BindError::NicOffline { name: name.clone() }), None => Err(BindError::NoSuchNic { name: name.clone(), available: nics::by_name().into_iter().map(|n| n.name).collect(), diff --git a/crates/tw-config/src/nics.rs b/crates/tw-config/src/nics.rs index 08acc852..2e243db2 100644 --- a/crates/tw-config/src/nics.rs +++ b/crates/tw-config/src/nics.rs @@ -34,21 +34,42 @@ fn is_link_local_v6(a: &Ipv6Addr) -> bool { a.segments()[0] & 0xffc0 == 0xfe80 } -/// 列出所有已配好地址、并且已经 up 的网卡。 +/// 列出所有已配好地址、已经 up 并且连着的网卡。 /// -/// **跳过没有地址的和没 up 的** —— 一张插着网线但没拿到 IP 的网卡绑不 -/// 上去,列在选单里只会让人选了之后发现起不来。 +/// **跳过没有地址的、没 up 的、没连上的** —— 一张插着网线但没拿到 IP 的 +/// 网卡绑不上去,列在选单里只会让人选了之后发现起不来。 +/// +/// 「连着」在 unix 上是 `IFF_RUNNING`:网线拔了、Wi-Fi 断了,或者一个没有 +/// 容器接着的 `docker0`/`br-*`,它们往往还挂着地址、也是 up 的,但局域网里 +/// 谁都连不到那个地址上。Windows 那边的「up」(`IfOperStatusUp`)本来就是 +/// 这个意思。 pub fn list() -> Vec { let mut out = imp::list(); - // 回环排最后:它在选单里对应的是「仅本机」那一档,不该混在 - // 「选一张网卡」的候选里排在前面。 - // - // **排序在这里,不在各自的平台实现里** —— 它是一条界面上的规矩, - // 和系统怎么把网卡交给我们没有关系。 - out.sort_by_key(|n| (n.addr.is_loopback(), n.name.clone(), n.addr.to_string())); + order(&mut out, imp::is_physical); out } +/// 选单里的顺序。 +/// +/// - **回环排最后**:它在选单里对应的是「仅本机」那一档,不该混在「选一张 +/// 网卡」的候选里排在前面。 +/// - **物理网卡排在虚拟网卡前面**:装了 Docker 的 Linux 上,`br-1a2b3c`、 +/// `docker0` 按字母排会压在 `enp3s0`、`wlp2s0` 前面,而局域网里别的机器 +/// 要连的几乎总是后者。虚拟的仍然列出来 —— 有人就是要绑 `tailscale0`。 +/// +/// **排序在这里,不在各自的平台实现里** —— 它是一条界面上的规矩,和系统 +/// 怎么把网卡交给我们没有关系。平台只回答「这张是不是物理的」。 +fn order(nics: &mut [Nic], physical: impl Fn(&str) -> bool) { + nics.sort_by_cached_key(|n| { + ( + n.addr.is_loopback(), + !physical(&n.name), + n.name.clone(), + n.addr.to_string(), + ) + }); +} + /// 每张网卡一行,地址是按名字绑它时真正监听的那一个。 /// /// **同一张网卡只出现一次。**配置里按名字存(`bind: en0`),一张网卡的 @@ -73,10 +94,10 @@ fn one_per_name(all: Vec) -> Vec { out } -/// 系统里有没有叫这个名字的网卡,**有没有地址都算**。 +/// 系统里有没有叫这个名字的网卡,**有没有地址、连没连上都算**。 /// -/// [`list`] 只列有地址的:网线拔了、Wi-Fi 断了的网卡不在里面。「没有这张 -/// 网卡」和「这张网卡此刻没有地址」要分开说 —— 前者多半是拼错了,后者 +/// [`list`] 只列有地址、连着的:网线拔了、Wi-Fi 断了的网卡不在里面。「没有 +/// 这张网卡」和「这张网卡此刻没连上」要分开说 —— 前者多半是拼错了,后者 /// 插上网线就好。 pub fn exists(name: &str) -> bool { imp::exists(name) @@ -106,7 +127,11 @@ mod unix { while !cur.is_null() { let e = &*cur; cur = e.ifa_next; - if e.ifa_addr.is_null() || e.ifa_flags & libc::IFF_UP as u32 == 0 { + // 要 up,也要 running(连着)。glibc 和 macOS 的 getifaddrs + // 给每个地址条目带的都是**所属网卡**的标志,所以这里按地址 + // 逐条判就等于按网卡判。 + let want = (libc::IFF_UP | libc::IFF_RUNNING) as u32; + if e.ifa_addr.is_null() || e.ifa_flags & want != want { continue; } let name = match CStr::from_ptr(e.ifa_name).to_str() { @@ -135,6 +160,29 @@ mod unix { out } + /// Linux 上,**背后有一个设备的**是物理网卡:内核给它在 sysfs 里建一个 + /// `device` 链接,指向 PCI/USB 上那块硬件。`docker0`、`br-*`、`veth*`、 + /// `virbr0`、`tailscale0`、`wg0`、`tun0`、`lo` 都没有。 + /// + /// 读不到 sysfs(容器里没挂、权限不够)时算虚拟 —— 那样只影响排序, + /// 不影响列不列。 + #[cfg(target_os = "linux")] + pub fn is_physical(name: &str) -> bool { + // 名字是内核给的短名,不会含 `/`;含了就不是一张网卡,别拿它拼路径 + !name.contains('/') + && std::path::Path::new("/sys/class/net") + .join(name) + .join("device") + .exists() + } + + /// 其他 unix(macOS)上不分:一律当物理网卡,于是顺序和以前一样只按 + /// 名字排。 + #[cfg(not(target_os = "linux"))] + pub fn is_physical(_name: &str) -> bool { + true + } + pub fn exists(name: &str) -> bool { let Ok(c) = std::ffi::CString::new(name) else { return false; @@ -159,7 +207,8 @@ mod windows { AF_INET, AF_INET6, AF_UNSPEC, SOCKADDR_IN, SOCKADDR_IN6, }; - /// `IfOperStatusUp`。**只认「up」这一档**,和 unix 那边的 `IFF_UP` 对齐: + /// `IfOperStatusUp`。**只认「up」这一档**,和 unix 那边的 + /// `IFF_UP | IFF_RUNNING` 对齐: /// 「正在连」「已断开」的网卡绑不上去。 /// /// 类型跟着 `IF_OPER_STATUS` 走(就是 `i32`),这样比较的时候不用转换。 @@ -317,6 +366,13 @@ mod windows { .collect() } + /// 不分物理和虚拟:Windows 的虚拟网卡(Hyper-V 的 `vEthernet`、VPN) + /// 没有一个像 sysfs `device` 那样可靠的判据,而按名字猜会猜错中文系统 + /// 上的显示名。顺序照旧只按名字排。 + pub fn is_physical(_name: &str) -> bool { + true + } + /// **不看 up、也不看有没有地址** —— 见 [`super::exists`] 上那段。 pub fn exists(name: &str) -> bool { !name.is_empty() && adapters().iter().any(|a| a.name == name) @@ -374,6 +430,90 @@ mod tests { ); } + /// 装了 Docker 的 Linux:按字母排的话 `br-*`、`docker0` 压在真网卡前面。 + #[test] + fn physical_interfaces_come_before_virtual_ones_and_loopback_is_last() { + let nic = |name: &str, addr: &str| Nic { + name: name.into(), + addr: addr.parse().unwrap(), + }; + let mut rows = vec![ + nic("lo", "127.0.0.1"), + nic("br-1a2b3c", "172.18.0.1"), + nic("wlp2s0", "192.168.1.9"), + nic("docker0", "172.17.0.1"), + nic("enp3s0", "fd00::5"), + nic("enp3s0", "192.168.1.5"), + nic("tailscale0", "100.64.0.2"), + ]; + order(&mut rows, |n| n.starts_with("enp") || n.starts_with("wlp")); + let names: Vec<&str> = rows.iter().map(|n| n.name.as_str()).collect(); + assert_eq!( + names, + [ + "enp3s0", + "enp3s0", + "wlp2s0", + "br-1a2b3c", + "docker0", + "tailscale0", + "lo" + ] + ); + // 排完再按名字并成一行一张,挑的仍是 IPv4,顺序不变 + let one: Vec = one_per_name(rows) + .into_iter() + .map(|n| format!("{} {}", n.name, n.addr)) + .collect(); + assert_eq!( + one, + [ + "enp3s0 192.168.1.5", + "wlp2s0 192.168.1.9", + "br-1a2b3c 172.18.0.1", + "docker0 172.17.0.1", + "tailscale0 100.64.0.2", + "lo 127.0.0.1" + ] + ); + } + + /// 一个平台不分物理虚拟(macOS、Windows)时,顺序就是原来那样:名字, + /// 回环最后。 + #[test] + fn without_a_physical_signal_the_order_is_by_name_with_loopback_last() { + let nic = |name: &str, addr: &str| Nic { + name: name.into(), + addr: addr.parse().unwrap(), + }; + let mut rows = vec![ + nic("lo0", "::1"), + nic("utun3", "fd00::2"), + nic("lo0", "127.0.0.1"), + nic("en0", "10.0.3.7"), + ]; + order(&mut rows, |_| true); + assert_eq!( + rows, + vec![ + nic("en0", "10.0.3.7"), + nic("utun3", "fd00::2"), + nic("lo0", "127.0.0.1"), + nic("lo0", "::1"), + ] + ); + } + + /// Linux 上回环背后没有设备,算虚拟 —— 它排最后靠的是「是不是回环」 + /// 那一键,不是这一键。编出来的名字、带路径的名字都不算物理。 + #[cfg(target_os = "linux")] + #[test] + fn on_linux_loopback_is_not_physical_and_a_made_up_name_is_not_either() { + assert!(!imp::is_physical("lo")); + assert!(!imp::is_physical("tw-no-such0")); + assert!(!imp::is_physical("../lo")); + } + /// 名字里可以有空格和中文 —— Windows 上「以太网」「Wi-Fi 2」都是常见的。 #[test] fn a_name_with_spaces_or_non_ascii_is_still_one_row() { diff --git a/crates/tw-control/src/token.rs b/crates/tw-control/src/token.rs index a060d08d..97a85541 100644 --- a/crates/tw-control/src/token.rs +++ b/crates/tw-control/src/token.rs @@ -2,7 +2,7 @@ //! //! # 为什么 socket 之外还要一道门 //! -//! unix socket 那一套(`0700` 的文件,只有属主连得上)在 macOS 上够用,但它 +//! unix socket 那一套(`0700` 的文件,只有属主连得上)在 macOS、Linux 上够用,但它 //! **是文件系统给的保证,不是我们给的**。Windows 上没有对等物:控制面在那里 //! 只能落在 `127.0.0.1` 的 TCP 上,而本机任意进程都连得上一个回环端口,连上 //! 之后也问不出对端是谁 —— unix socket 问得出(`SO_PEERCRED`),TCP 问不出。 diff --git a/crates/tw-gateway/src/listen.rs b/crates/tw-gateway/src/listen.rs index 8c1ececc..b1fce9ba 100644 --- a/crates/tw-gateway/src/listen.rs +++ b/crates/tw-gateway/src/listen.rs @@ -61,16 +61,16 @@ pub fn bind_failure(addr: SocketAddr, e: &std::io::Error) -> Msg { } /// 网卡解析不出地址的原因,说给人听。**两种情况要做的事不同**:名字不对要 -/// 改设置,网卡没地址要去插网线、连 Wi-Fi。 +/// 改设置,网卡没连上要去插网线、连 Wi-Fi。 pub fn unresolved(e: &tw_config::BindError) -> Msg { match e { tw_config::BindError::NoSuchNic { name, available } => msg!( "gw.listen.no_such_nic", name = name, available = available.join(", ") => "This machine has no interface named {name}; it has {available}." ), - tw_config::BindError::NicHasNoAddr { name } => msg!( - "gw.listen.nic_no_addr", name = name => - "Interface {name} currently has no address. Check the cable or the Wi-Fi connection." + tw_config::BindError::NicOffline { name } => msg!( + "gw.listen.nic_offline", name = name => + "Interface {name} is not connected right now. Check the cable or the Wi-Fi connection." ), } } diff --git a/scripts/smoke.sh b/scripts/smoke.sh index e1aa47fc..86f0c316 100755 --- a/scripts/smoke.sh +++ b/scripts/smoke.sh @@ -37,6 +37,10 @@ bad() { FAIL=$((FAIL+1)); printf ' ✗ %s\n' "$1"; [ $# -gt 1 ] && printf ' # 两个都会让人停止看这一行。 warn() { WARN=$((WARN+1)); printf ' ⚠ %s\n' "$1"; [ $# -gt 1 ] && printf ' %s\n' "$2"; } step() { printf '\n== %s\n' "$1"; } +# 权限位、修改时间 + 大小。**GNU 先问**:BSD 的 `stat -f` 在 GNU 上是「查文件 +# 系统」,同一串参数照样返回 0、吐出一行不相干的东西,而不是失败退到下一种。 +mode_of() { stat -c '%a' "$1" 2>/dev/null || stat -f '%Lp' "$1" 2>/dev/null; } +mtime_size() { stat -c '%Y %s' "$1" 2>/dev/null || stat -f '%m %z' "$1" 2>/dev/null; } cleanup() { [ -n "${CORE_PID:-}" ] && kill "$CORE_PID" 2>/dev/null @@ -114,7 +118,7 @@ step "构建" if cargo build --release -p twcore --manifest-path "$ROOT/Cargo.toml" 2>&1 | grep -q '^error'; then bad "构建失败"; exit 1 fi -BIN="$ROOT/target/release/twcore" +BIN="${CARGO_TARGET_DIR:-$ROOT/target}/release/twcore" ok "twcore 构建好了" # ---------------------------------------------------------------- init @@ -123,7 +127,7 @@ CFG="$THINKWATCH_HOME/config.yaml" "$BIN" --config "$CFG" init >/dev/null 2>&1 [ -f "$CFG" ] && ok "init 生成了配置" || bad "init 没生成配置" # **明文密钥的文件必须是 0600** -MODE=$(stat -f '%Lp' "$CFG" 2>/dev/null || stat -c '%a' "$CFG") +MODE=$(mode_of "$CFG") [ "$MODE" = "600" ] && ok "config.yaml 是 0600" || bad "config.yaml 权限是 $MODE,该是 600" python3 - "$CFG" "$UPPORT" "$PORT" <<'PY' @@ -189,7 +193,7 @@ CORE_PID=$! for _ in $(seq 1 40); do [ -S "$SOCK" ] && break; sleep 0.25; done [ -S "$SOCK" ] && ok "控制面 socket 起来了" || { bad "socket 没出现" "$(tail -3 "$TMP/core.log")"; exit 1; } -MODE=$(stat -f '%Lp' "$THINKWATCH_HOME/data.db" 2>/dev/null || echo -) +MODE=$(mode_of "$THINKWATCH_HOME/data.db" || echo -) [ "$MODE" = "600" ] && ok "data.db 是 0600" || bad "data.db 权限是 $MODE" # ---------------------------------------------------------------- 数据面 @@ -396,9 +400,9 @@ fi # 空闲时不写盘(最后一条)。**没有请求就不该有任何写入** —— # 一个常驻进程每秒摸一次磁盘,在笔记本上就是电量 -DB_BEFORE=$(stat -f '%m %z' "$THINKWATCH_HOME/data.db" 2>/dev/null || echo "0 0") +DB_BEFORE=$(mtime_size "$THINKWATCH_HOME/data.db" || echo "0 0") sleep 3 -DB_AFTER=$(stat -f '%m %z' "$THINKWATCH_HOME/data.db" 2>/dev/null || echo "1 1") +DB_AFTER=$(mtime_size "$THINKWATCH_HOME/data.db" || echo "1 1") [ "$DB_BEFORE" = "$DB_AFTER" ] && ok "空闲 3 秒没有写盘" \ || bad "空闲时还在写盘" "before=$DB_BEFORE after=$DB_AFTER" From 449fcf0bab400ffdbb469ec6c45f3735536b3e1e Mon Sep 17 00:00:00 2001 From: fylorn <249551762+fylorn@users.noreply.github.com> Date: Thu, 24 Sep 2026 16:48:36 +0800 Subject: [PATCH 2/2] smoke: disable Nagle in the fake upstream Its handler writes the headers and the body in two small sends; with Nagle the body waits for the ACK of the headers, and Linux delays that ACK by 40ms on a pooled connection, so every request through the gateway looked 40ms slower on the Linux runner. Co-Authored-By: Claude Opus 5.5 --- scripts/smoke.sh | 6 ++++++ 1 file changed, 6 insertions(+) diff --git a/scripts/smoke.sh b/scripts/smoke.sh index 86f0c316..4d13dedc 100755 --- a/scripts/smoke.sh +++ b/scripts/smoke.sh @@ -54,6 +54,12 @@ trap cleanup EXIT cat > "$TMP/upstream.py" <<'PY' import http.server, json, sys, time class H(http.server.BaseHTTPRequestHandler): + # **关掉 Nagle。**这个处理器先写响应头、再单独写正文,两次小写。开着 + # Nagle 的话,正文要等对端确认了响应头才发;而 core 用的是池里的旧 + # 连接,Linux 在旧连接上会把确认攒 40ms 再发 —— 于是每条请求平白多出 + # 40ms,下面那条「转发的额外延迟」在 Linux 上就这么红过。真正的上游 + # 不会这样一次响应拆成两段小写,这是假上游自己的毛病。 + disable_nagle_algorithm = True # **默认是 HTTP/1.0,每条响应之后关连接。**core 那边是带连接池的 # 客户端,会拿一条它以为还活着的连接去发下一个请求。配上 1.1 才是 # 这个假上游该模拟的形状。