From cc5891e6d0aa1f074d10811d0359dd2576989982 Mon Sep 17 00:00:00 2001 From: xmz7891 Date: Wed, 7 Oct 2026 18:20:57 +0800 Subject: [PATCH] =?UTF-8?q?=E4=BF=AE=E5=B1=80=E5=9F=9F=E7=BD=91/=E4=B8=AD?= =?UTF-8?q?=E8=BD=AC=E5=AF=B9=E6=AF=94=E5=9F=BA=E5=87=86=EF=BC=9A=E5=AE=83?= =?UTF-8?q?=E8=87=AA=E5=B7=B1=E6=9C=89=E4=B8=A4=E4=B8=AA=20bug=EF=BC=8C?= =?UTF-8?q?=E5=AE=B3=E4=BA=A7=E5=93=81=E8=83=8C=E4=BA=86=E9=BB=91=E9=94=85?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit 这个基准一直是红的(中转那条路报「连接阶段失败: timed out」), 而且报告里写着"这是中转链路的产品 bug"。**查下来不是产品的问题。** == bug 1:两条路用了同一个配对码 == 基准为了排除互相干扰,给两条路**各起一台全新被控端**(设计是对的), 但两台都用了写死的 code="246813"。 中转有「一个配对码只属于一台设备」的规则: 第 1 台(跑局域网)注册成功 -> stop_agent 杀掉进程,但**中转还以为它在线**(last_seen 没过期) 第 2 台(跑中转)用同一个码注册 -> **被拒** 中转日志:配对码 246813 已被 ... 占用,拒绝 ... 而 start_agent 只检查"有没有设备在线" —— 第 1 台僵尸还挂着, 于是**以为新的一台登记成功了** -> 没有任何进程在回包 -> 超时 对照实验(新增 _build/verify_code_reuse.py): 场景 A 同一个码 -> **不通** 场景 B 各用不同码 -> 通 修法:两条路各用不同码;start_agent 的判据从"有没有在线设备" 改成"有没有**配对码正好是这一台要用的码**的在线设备"。 == bug 2:attach 用的还是旧码(我第一版补丁也漏了这处)== relay_connect() 里 `client.attach(code)` 用的还是局域网那个码 —— attach 到一台已经死掉、但中转以为在线的设备上,pair 自然没人回。 修成 `attach(relay_code)`。 == 顺带更新一段过时注释 == 原文写着「当前版本经中转只稳定支撑前 1~2 次交互……这是中转链路的 产品 bug」,并据此把中转的轮数调小、超时调短。 那个 bug **已经修好了**(根因:一条 HTTP/1.1 连接被长轮询和发命令 两个线程同时用,撞状态机抛 CannotSendRequest("Idle"), 异常冒到 _client_loop 外面把 client-relay 线程打死)。 注释不更新会误导后人以为产品还有这个问题。 == 修好之后的实测(本地中转,30 次/路)== 局域网 握手 16ms 成功 30/30 (100%) 中位 0ms P90 0ms 最大 1ms 中转 握手 46ms 成功 30/30 (100%) 中位 15ms P90 29ms 最大 32ms 这是本地中转,量的是**协议本身的开销**(长轮询往返 vs 直连 TCP); 真实跨网络那条腿的 1.0~1.5 秒来自隧道和 4G,是另一回事。 结论:局域网确实是"毫秒级、不耗流量"的那条根本路径 —— 中位 0ms vs 15ms,而且不走任何外网。 踩坑记录:这两处都是"看起来像产品 bug、实际是测试自己的 bug"。 先怀疑测量工具,比先怀疑产品更省时间 —— 上一次(管理页缓存头)也是我拿 curl -I 测 GET 白查了半天。 --- _build/_cmsg5.txt | 57 +++++++++ _build/accept_final.sh | 75 +++++++++++ _build/diag_relay_bench.py | 241 +++++++++++++++++++++++++++++++++++ _build/drb.txt | 28 ++++ _build/fix_bench_code.py | 178 ++++++++++++++++++++++++++ _build/insert_stub_checks.py | 63 +++++++++ _build/inspect_pathtest.sh | 27 ++++ _build/lanbench.txt | 19 +++ _build/lanbench2.txt | 19 +++ _build/lanbench3.txt | 19 +++ _build/lanbench4.txt | 20 +++ _build/rp_pc_long.tsv | 23 ++++ _build/test_deploy_sh.sh | 24 ++++ _build/vcr.txt | 23 ++++ _build/verify_code_reuse.py | 225 ++++++++++++++++++++++++++++++++ _tests/bench_lan_vs_relay.py | 63 ++++++--- 16 files changed, 1088 insertions(+), 16 deletions(-) create mode 100644 _build/_cmsg5.txt create mode 100644 _build/accept_final.sh create mode 100644 _build/diag_relay_bench.py create mode 100644 _build/drb.txt create mode 100644 _build/fix_bench_code.py create mode 100644 _build/insert_stub_checks.py create mode 100644 _build/inspect_pathtest.sh create mode 100644 _build/lanbench.txt create mode 100644 _build/lanbench2.txt create mode 100644 _build/lanbench3.txt create mode 100644 _build/lanbench4.txt create mode 100644 _build/vcr.txt create mode 100644 _build/verify_code_reuse.py diff --git a/_build/_cmsg5.txt b/_build/_cmsg5.txt new file mode 100644 index 0000000..57b3afd --- /dev/null +++ b/_build/_cmsg5.txt @@ -0,0 +1,57 @@ +修局域网/中转对比基准:它自己有两个 bug,害产品背了黑锅 + +这个基准一直是红的(中转那条路报「连接阶段失败: timed out」), +而且报告里写着"这是中转链路的产品 bug"。**查下来不是产品的问题。** + +== bug 1:两条路用了同一个配对码 == + +基准为了排除互相干扰,给两条路**各起一台全新被控端**(设计是对的), +但两台都用了写死的 code="246813"。 + +中转有「一个配对码只属于一台设备」的规则: + 第 1 台(跑局域网)注册成功 + -> stop_agent 杀掉进程,但**中转还以为它在线**(last_seen 没过期) + 第 2 台(跑中转)用同一个码注册 -> **被拒** + 中转日志:配对码 246813 已被 ... 占用,拒绝 ... + 而 start_agent 只检查"有没有设备在线" —— 第 1 台僵尸还挂着, + 于是**以为新的一台登记成功了** + -> 没有任何进程在回包 -> 超时 + +对照实验(新增 _build/verify_code_reuse.py): + 场景 A 同一个码 -> **不通** + 场景 B 各用不同码 -> 通 + +修法:两条路各用不同码;start_agent 的判据从"有没有在线设备" + 改成"有没有**配对码正好是这一台要用的码**的在线设备"。 + +== bug 2:attach 用的还是旧码(我第一版补丁也漏了这处)== + +relay_connect() 里 `client.attach(code)` 用的还是局域网那个码 —— +attach 到一台已经死掉、但中转以为在线的设备上,pair 自然没人回。 + +修成 `attach(relay_code)`。 + +== 顺带更新一段过时注释 == + +原文写着「当前版本经中转只稳定支撑前 1~2 次交互……这是中转链路的 +产品 bug」,并据此把中转的轮数调小、超时调短。 + +那个 bug **已经修好了**(根因:一条 HTTP/1.1 连接被长轮询和发命令 +两个线程同时用,撞状态机抛 CannotSendRequest("Idle"), +异常冒到 _client_loop 外面把 client-relay 线程打死)。 +注释不更新会误导后人以为产品还有这个问题。 + +== 修好之后的实测(本地中转,30 次/路)== + + 局域网 握手 16ms 成功 30/30 (100%) 中位 0ms P90 0ms 最大 1ms + 中转 握手 46ms 成功 30/30 (100%) 中位 15ms P90 29ms 最大 32ms + +这是本地中转,量的是**协议本身的开销**(长轮询往返 vs 直连 TCP); +真实跨网络那条腿的 1.0~1.5 秒来自隧道和 4G,是另一回事。 + +结论:局域网确实是"毫秒级、不耗流量"的那条根本路径 —— +中位 0ms vs 15ms,而且不走任何外网。 + +踩坑记录:这两处都是"看起来像产品 bug、实际是测试自己的 bug"。 +先怀疑测量工具,比先怀疑产品更省时间 —— +上一次(管理页缓存头)也是我拿 curl -I 测 GET 白查了半天。 diff --git a/_build/accept_final.sh b/_build/accept_final.sh new file mode 100644 index 0000000..d47c4e9 --- /dev/null +++ b/_build/accept_final.sh @@ -0,0 +1,75 @@ +#!/bin/bash +# 1.8.2 最终验收(在设备上跑) +set -u + +BASE=https://relay.xxmxxs.top +UA='LanRemote/1.8.2' + +echo "════════ 1. 官网和三个成品(走公网,看缓存)════════" +for p in / /download/ykxmz-setup-1.8.2.exe /download/ykxmz-server-1.8.2.zip /download/ykxmz-watch-1.8.2.apk; do + hdr=$(curl -s -D - -o /dev/null --max-time 45 -H "User-Agent: $UA" "$BASE$p" 2>/dev/null | tr -d '\r') + code=$(echo "$hdr" | head -1 | awk '{print $2}') + len=$(echo "$hdr" | grep -i '^content-length' | awk '{print $2}') + cf=$(echo "$hdr" | grep -i '^cf-cache-status' | awk '{print $2}') + cc=$(echo "$hdr" | grep -i '^cache-control' | cut -d' ' -f2-) + printf " %-38s HTTP %-4s %10s cf=%-6s %s\n" "$p" "$code" "$len" "${cf:-无}" "${cc:-无}" +done + +echo +echo "════════ 2. 对外清洁度(官网不能有管理页字眼)════════" +curl -s --max-time 30 -H "User-Agent: $UA" "$BASE/" -o /tmp/site.html +n=$(grep -cE 'zhongzhuanzhan|管理后台|管理页|管理入口|管理面板' /tmp/site.html || true) +echo " 官网里管理页字眼: $n 处(应为 0)" +echo " 官网大小: $(wc -c < /tmp/site.html) 字节" +echo " 下载按钮:" +grep -o 'href="/download/[^"]*"' /tmp/site.html | sort -u | sed 's/^/ /' + +echo +echo "════════ 3. 管理页两个新功能 ════════" +if [ -f /root/taf.py ]; then + python3 /root/taf.py 2>&1 | tail -16 | sed 's/^/ /' +else + echo " (测试脚本不在设备上)" +fi + +echo +echo "════════ 4. 中转核心功能(长轮询 + 注册)════════" +STAMP=$(date +%s) +DEV="acc-$STAMP" +CODE=$(printf "%06d" $(( STAMP % 1000000 ))) +REG=$(curl -s --max-time 30 -X POST "$BASE/v1/agent/register" \ + -H 'Content-Type: application/json' -H "User-Agent: $UA" \ + -d "{\"deviceId\":\"$DEV\",\"code\":\"$CODE\",\"name\":\"验收\",\"version\":\"1.8.2\"}") +TOKEN=$(echo "$REG" | python3 -c "import sys,json; print(json.load(sys.stdin).get('token',''))" 2>/dev/null) +echo " 注册: $([ -n "$TOKEN" ] && echo 成功 || echo 失败)" +if [ -n "$TOKEN" ]; then + for i in 1 2; do + out=$(curl -s -o /dev/null -w '%{http_code} %{time_total}' --max-time 200 \ + -X POST "$BASE/v1/agent/poll" -H "X-Token: $TOKEN" -H "User-Agent: $UA") + printf " 长轮询 %d: 码 %s 耗时 %.1fs(应约 61 秒)\n" \ + "$i" "$(echo "$out" | awk '{print $1}')" "$(echo "$out" | awk '{print $2}')" + done + KEY=$(cat /root/lanremote-relay/data/admin_key.txt 2>/dev/null) + curl -s --max-time 20 -X POST "http://127.0.0.1:8080/v1/admin/delete" \ + -H "X-Admin: $KEY" -H 'Content-Type: application/json' \ + -d "{\"deviceId\":\"$DEV\"}" > /dev/null 2>&1 + echo " 探针已清理" +fi + +echo +echo "════════ 5. 公网可用率(20 次)════════" +ok=0 +for i in $(seq 1 20); do + c=$(curl -s -o /dev/null -w '%{http_code}' --max-time 20 -H "User-Agent: $UA" "$BASE/v1/health") + [ "$c" = "200" ] && ok=$((ok + 1)) + sleep 1 +done +echo " 可用 $ok/20 = $((ok * 5))%" + +echo +echo "════════ 6. 隧道和错误 ════════" +for s in lanremote-relay lanremote-tunnel lanremote-tunnel-h2; do + printf " %-24s %s\n" "$s" "$(systemctl is-active $s)" +done +echo " 中转错误行数(近 10 分钟): $(journalctl -u lanremote-relay --since '10 minutes ago' --no-pager 2>/dev/null | grep -icE 'traceback|nameerror|typeerror|AttributeError' || echo 0)" +echo " 连接数: 20241=$(curl -s --max-time 4 http://127.0.0.1:20241/metrics 2>/dev/null | grep '^cloudflared_tunnel_ha_connections' | awk '{print $2}') 20242=$(curl -s --max-time 4 http://127.0.0.1:20242/metrics 2>/dev/null | grep '^cloudflared_tunnel_ha_connections' | awk '{print $2}')" diff --git a/_build/diag_relay_bench.py b/_build/diag_relay_bench.py new file mode 100644 index 0000000..b801a4a --- /dev/null +++ b/_build/diag_relay_bench.py @@ -0,0 +1,241 @@ +# -*- coding: utf-8 -*- +r'''复刻 bench_lan_vs_relay 的中转那一半,抓被控端日志。 + +我自己那个 ins_relay_flow.py 是中转 4/4 通过的, +但 bench_lan_vs_relay.py 的中转那半报"连接阶段失败: timed out"。 +差异一定在设置里,所以要逐项对齐 bench 的写法: + * RELAY_POLL=2(我那边是 5) + * 用 YKXMZ_DATA 指到临时目录 + --silent(我那边直接写 windows/data) + * 每条路起**一台全新的**被控端 + * 先 attach 再 pair(bench 的 relay_connect 就是这么做的) + +把每一步的耗时和被控端日志都打出来。 +''' +from __future__ import annotations + +import json +import os +import socket +import subprocess +import sys +import tempfile +import time +import urllib.error +import urllib.request +from pathlib import Path + +ROOT = Path(__file__).resolve().parent.parent +WINDOWS = ROOT / "windows" +UA = {"User-Agent": "LanRemote/1.8.2"} +CODE = "975310" + + +def free_port() -> int: + s = socket.socket() + s.bind(("127.0.0.1", 0)) + p = s.getsockname()[1] + s.close() + return p + + +def post(base, path, body=b"", headers=None, timeout=20.0): + h = dict(UA) + h.update(headers or {}) + req = urllib.request.Request(base + path, data=body, headers=h, + method="POST") + try: + with urllib.request.urlopen(req, timeout=timeout) as resp: + return resp.status, resp.read() + except urllib.error.HTTPError as exc: + return exc.code, exc.read() + except Exception as exc: # noqa: BLE001 + return 0, str(exc).encode() + + +def get(base, path, timeout=5.0): + req = urllib.request.Request(base + path, headers=UA) + try: + with urllib.request.urlopen(req, timeout=timeout) as resp: + return resp.status, resp.read() + except Exception as exc: # noqa: BLE001 + return 0, str(exc).encode() + + +def main() -> int: + work = Path(tempfile.mkdtemp(prefix="benchdiag_")) + relay_port = free_port() + agent_port = free_port() + base = "http://127.0.0.1:%d" % relay_port + relay_proc = agent_proc = None + relay_log = agent_log = None + try: + print(" 中转端口 %d 被控端端口 %d" % (relay_port, agent_port)) + + # ---- 1. 本地中转(对齐 bench:RELAY_POLL=2)---- + rdata = work / "r" + rdata.mkdir(parents=True, exist_ok=True) + env = dict(os.environ) + env.update({"RELAY_PORT": str(relay_port), "RELAY_BIND": "127.0.0.1", + "RELAY_DATA": str(rdata), "RELAY_POLL": "2", + "PYTHONIOENCODING": "utf-8", "PYTHONUNBUFFERED": "1"}) + relay_log = open(work / "relay.log", "wb") + relay_proc = subprocess.Popen( + [sys.executable, "-u", str(ROOT / "relay" / "relay.py")], env=env, + stdout=relay_log, stderr=subprocess.STDOUT) + for _ in range(60): + time.sleep(0.5) + if get(base, "/v1/health")[0] == 200: + break + print(" 中转就绪") + + # ---- 2. 被控端(对齐 bench:YKXMZ_DATA + --silent + 独立锁端口)---- + sys.path.insert(0, str(WINDOWS)) + from lanremote.config import Store + adata = work / "a" + adata.mkdir(parents=True, exist_ok=True) + store = Store(adata) + store.set_pairing_code(CODE) + store.set("setup_done", True) + store.set("allow_new_pairing", True) + store.set("close_pair_after_first", False) + store.set("server_name", "基准测试电脑") + store.set("relay_url", base) + store.set("port", agent_port) + + aenv = dict(os.environ) + aenv.update({"YKXMZ_DATA": str(adata), + "YKXMZ_LOCK_PORT": str(free_port()), + "PYTHONIOENCODING": "utf-8", "PYTHONUNBUFFERED": "1"}) + agent_log = open(work / "agent.log", "wb") + agent_proc = subprocess.Popen( + [sys.executable, "-u", str(WINDOWS / "run_agent.py"), + "--silent", "--port", str(agent_port)], + cwd=str(WINDOWS), env=aenv, + stdout=agent_log, stderr=subprocess.STDOUT) + + online = False + for _ in range(45): + time.sleep(1.0) + if agent_proc.poll() is not None: + print(" ✗ 被控端启动即退出,返回码 %s" % agent_proc.returncode) + break + st, body = get(base, "/v1/health", timeout=4) + if st == 200: + snap = json.loads(body.decode()) + if any(d.get("online") for d in snap.get("devices", [])): + online = True + break + print(" 被控端登记: %s" % ("成功" if online else "**失败**")) + if not online: + return 1 + + # ---- 3. 完全照 bench 的 relay_connect 做 ---- + print() + print(" ── 照 bench 的顺序:attach -> pair ──") + t0 = time.time() + st, body = post(base, "/v1/client/attach", json.dumps( + {"code": CODE, "name": "基准测试手表"}).encode(), + {"Content-Type": "application/json"}) + att = json.loads(body.decode()) + session = att.get("session", "") + print(" attach: %dms ok=%s session=%s" + % (int((time.time() - t0) * 1000), att.get("ok"), + session[:8] if session else "无")) + + payload = (json.dumps({"cmd": "pair", "deviceId": "bench-relay", + "deviceName": "基准测试手表", + "code": CODE}, ensure_ascii=False) + + "\n").encode() + t0 = time.time() + st, _ = post(base, "/v1/client/send", payload, {"X-Session": session}) + print(" send pair: %dms status=%s" % (int((time.time() - t0) * 1000), st)) + + # 轮询等回复,每轮都打点 + buf = b"" + deadline = time.time() + 40 + got = None + round_no = 0 + while time.time() < deadline: + round_no += 1 + remaining = deadline - time.time() + t0 = time.time() + st, chunk = post(base, "/v1/client/poll", b"", + {"X-Session": session}, min(10.0, remaining)) + buf += chunk + print(" poll#%d: %dms status=%s 收到 %d 字节" + % (round_no, int((time.time() - t0) * 1000), st, len(chunk))) + while b"\n" in buf: + line, _, buf = buf.partition(b"\n") + if not line.strip(): + continue + msg = json.loads(line.decode()) + if "event" in msg: + continue + got = msg + break + if got is not None: + break + + if got is None: + print(" ✗ 40 秒内没等到 pair 的回复") + else: + print(" ✓ pair 回复: %s" % json.dumps(got, ensure_ascii=False)[:120]) + + # ---- 4. 再来几次 ping ---- + if got is not None: + for i in range(5): + payload = (json.dumps({"cmd": "ping"}) + "\n").encode() + post(base, "/v1/client/send", payload, {"X-Session": session}) + deadline = time.time() + 15 + ok = False + while time.time() < deadline: + st, chunk = post(base, "/v1/client/poll", b"", + {"X-Session": session}, 8.0) + buf += chunk + while b"\n" in buf: + line, _, buf = buf.partition(b"\n") + if not line.strip(): + continue + msg = json.loads(line.decode()) + if "event" in msg: + continue + ok = True + break + if ok: + break + print(" ping#%d: %s" % (i + 1, "OK" if ok else "**超时**")) + + # ---- 5. 被控端日志 ---- + print() + print(" ════ 被控端日志(最后 25 行)════") + agent_log.flush() + for line in (work / "agent.log").read_text( + encoding="utf-8", errors="replace").splitlines()[-25:]: + print(" " + line[:120]) + print() + print(" ════ 进程还活着吗 ════") + print(" agent poll = %s" % agent_proc.poll()) + print() + print(" ════ 中转日志(最后 10 行)════") + relay_log.flush() + for line in (work / "relay.log").read_text( + encoding="utf-8", errors="replace").splitlines()[-10:]: + print(" " + line[:120]) + return 0 + finally: + for p in (agent_proc, relay_proc): + if p is not None: + try: + p.terminate() + p.wait(timeout=6) + except Exception: # noqa: BLE001 + try: + p.kill() + except Exception: # noqa: BLE001 + pass + import shutil + shutil.rmtree(work, ignore_errors=True) + + +if __name__ == "__main__": + sys.exit(main()) diff --git a/_build/drb.txt b/_build/drb.txt new file mode 100644 index 0000000..3c0cfb9 --- /dev/null +++ b/_build/drb.txt @@ -0,0 +1,28 @@ + 中转端口 59913 被控端端口 59914 + 中转就绪 + 被控端登记: 成功 + + ── 照 bench 的顺序:attach -> pair ── + attach: 0ms ok=True session=223aadf1 + send pair: 1ms status=200 + poll#1: 17ms status=200 收到 102 字节 + ✓ pair 回复: {"ok": true, "token": "83dbc727003b9fb32c896b4a1a6fd55b", "serverName": "基准测试电脑", "protocol": 1} + ping#1: OK + ping#2: OK + ping#3: OK + ping#4: OK + ping#5: OK + + ════ 被控端日志(最后 25 行)════ + + ════ 进程还活着吗 ════ + agent poll = None + + ════ 中转日志(最后 10 行)════ + [10-07 18:18:24] 中转服务器 v1.8.2 启动,监听 127.0.0.1:59913 + [10-07 18:18:24] 长轮询 2 秒 · 队列上限 2048 KB · 数据目录 C:\Users\shu\AppData\Local\Temp\benchdiag_v6uvedpl\r + [10-07 18:18:24] 管理页:http://<本机>:59913/?key=lMvZ9w12vLnidllvR41PFZWg + [10-07 18:18:24] (钥匙也在 C:\Users\shu\AppData\Local\Temp\benchdiag_v6uvedpl\r\admin_key.txt) + [10-07 18:18:25] 被控端上线:基准测试电脑 码 975310 (基准测试电脑-f308c…) + [10-07 18:18:25] 注册请求 -> ok=True + [10-07 18:18:25] 手表接入:基准测试手表 (127.0.0.1) -> 基准测试电脑 diff --git a/_build/fix_bench_code.py b/_build/fix_bench_code.py new file mode 100644 index 0000000..d26f21e --- /dev/null +++ b/_build/fix_bench_code.py @@ -0,0 +1,178 @@ +# -*- coding: utf-8 -*- +r'''修 bench_lan_vs_relay.py:两条路用了同一个配对码。 + +== 问题 == + +这个基准为了排除互相干扰,给"局域网"和"中转"两条路**各起一台全新被控端** +(这个设计本身是对的)。但两台都用了写死的 `code = "246813"`。 + +中转有「一个配对码只能属于一台设备」的规则,于是: + + 第 1 台(跑局域网)用 246813 注册成功 + -> stop_agent 杀掉进程,但**中转还以为它在线**(last_seen 没过期) + 第 2 台(跑中转)也用 246813 注册 + -> **被拒**(码被占),中转日志:配对码 246813 已被 ... 占用,拒绝 ... + 而 start_agent 只检查"有没有设备在线" —— 第 1 台还挂着,于是**以为成功了** + -> 接下来 attach 成功(码还绑在第 1 台那个 deviceId 上), + 但**没有任何进程在回包** -> "连接阶段失败: timed out" + +实测对照(_build/verify_code_reuse.py): + 场景 A 同一个码 -> **不通** + 场景 B 各用不同码 -> 通 + +**所以产品是好的,是这个基准脚本在"公正对比"这个目标上自己绊了自己。** + +== 顺带修掉两处 == + +1. 那段「当前版本经中转只稳定支撑前 1~2 次交互」的注释是**过时的** —— + 那个 bug 已经修好了(根因是一条 HTTP/1.1 连接被长轮询和发命令 + 两个线程同时用,撞状态机抛 "Idle" 把 client-relay 线程打死)。 + 注释要更新,否则会误导后人以为产品还有这个问题。 + +2. start_agent 只判断"有没有设备在线"太松 —— 会被上一台僵尸设备骗过。 + 加一个更硬的判据:看 deviceId 是不是**这一台**新生成的。 +''' +from __future__ import annotations + +import sys +from pathlib import Path + +ROOT = Path(r"C:\Users\shu\Desktop\deepseekagent\LanRemote") +SRC = ROOT / "_tests" / "bench_lan_vs_relay.py" + + +def patch(text, old, new, label): + if old not in text: + print(" ✗ 没找到:%s" % label) + return text, False + if text.count(old) != 1: + print(" ! 出现 %d 次:%s" % (text.count(old), label)) + return text, False + print(" ✓ %s" % label) + return text.replace(old, new, 1), True + + +def main() -> int: + text = SRC.read_text(encoding="utf-8") + ok_all = True + + # ------------------------------------------------ 1. 两个码 + text, ok = patch( + text, + ' code = "246813"', + ''' # ⚠ 两条路必须用**不同的**配对码。 + # 中转有「一个码只属于一台设备」的规则,而这个基准给每条路 + # 各起一台全新被控端(为了排除互相干扰,设计是对的)。 + # 要是两台共用一个码,第 2 台的注册会被拒,而第 1 台虽然 + # 进程被杀了、中转还以为它在线 —— 于是"看着登记成功、 + # 实际没人回包",表现为连接阶段超时。 + # 实测对照见 _build/verify_code_reuse.py:同码不通、不同码通。 + code = "246813" # 局域网那条路 + relay_code = "975310" # 中转那条路,必须不同''', + "两条路用不同的配对码") + ok_all = ok_all and ok + + # ------------------------------------------------ 2. relay_connect 用 relay_code + text, ok = patch( + text, + ''' reply = client.call({"cmd": "pair", "deviceId": "bench-relay", + "deviceName": "基准测试手表", "code": code}, + args.relay_timeout)''', + ''' reply = client.call({"cmd": "pair", "deviceId": "bench-relay", + "deviceName": "基准测试手表", + "code": relay_code}, + args.relay_timeout)''', + "relay_connect 用 relay_code") + ok_all = ok_all and ok + + # ------------------------------------------------ 3. 第二个 start_agent 传码 + text, ok = patch( + text, + """ agent_proc, _data = start_agent() + + # attach 只是"接入中转",协议层还得 pair 一次才算鉴权完成 ——""", + """ agent_proc, _data = start_agent(relay_code) + + # attach 只是"接入中转",协议层还得 pair 一次才算鉴权完成 ——""", + "第二台用 relay_code") + ok_all = ok_all and ok + + # ------------------------------------------------ 4. start_agent 接受码 + 硬判据 + text, ok = patch( + text, + """ def start_agent(): + data = Path(tempfile.mkdtemp(prefix="bench_agent_", dir=str(work))) + store = Store(data) + store.set_pairing_code(code)""", + """ def start_agent(agent_code=None): + agent_code = agent_code or code + data = Path(tempfile.mkdtemp(prefix="bench_agent_", dir=str(work))) + store = Store(data) + store.set_pairing_code(agent_code)""", + "start_agent 接受码参数") + ok_all = ok_all and ok + + # 只判断"有没有在线设备"太松:上一台僵尸还挂着就会骗过它。 + # 改成看有没有**在线且没被别的码占用**的设备,并且记录 deviceId 做比对。 + text, ok = patch( + text, + """ if any(d.get("online") for d in snap.get("devices", [])): + return proc, data + raise RuntimeError("被控端 45 秒内没登记到中转")""", + """ # ⚠ 不能只看"有没有设备在线" —— + # 上一台被控端虽然进程被杀,中转还没超时清理它, + # 于是这里会被僵尸设备骗过,以为新的一台登记成功了。 + # 要求:存在一台在线、且配对码正好是**这一台要用的码** + # 的设备。 + live = [d for d in snap.get("devices", []) + if d.get("online") and d.get("code") == agent_code] + if live: + return proc, data + raise RuntimeError( + "被控端 45 秒内没登记到中转(码 %s)" % agent_code)""", + "start_agent 的判据改硬") + ok_all = ok_all and ok + + # ------------------------------------------------ 5. 更新过时注释 + text, ok = patch( + text, + """ # ⚠ 这里的轮数**故意比局域网少**,而且超时给得短。 + # 原因:当前版本经中转只稳定支撑前 1~2 次交互,之后被控端 + # 就不再回包(详见 _build/diag_relay_leg.py 的时间线: + # attach/pair/ping#1 全 0ms 返回,ping#2 开始 relay 一直回 0 字节)。 + # 这是中转链路的**产品 bug**,不是本测试的毛病 —— + # 仓库现成的 _tests/test_relay_local.py 也是同样形状。 + # 所以这里只做**有界**测量:拿得到就打点,拿不到就如实报错, + # 绝不让整个基准卡死。""", + """ # 【历史】这里原来写着"经中转只稳定支撑前 1~2 次交互", + # 并据此把轮数调小、超时调短。那个产品 bug **已经修好了**: + # + # 根因是一条 HTTP/1.1 连接被两个线程同时用 —— + # relay-link 线程的 /v1/agent/poll 要挂 180 秒(长轮询), + # client-relay 线程同时 POST /v1/agent/send 发命令, + # HTTP/1.1 一条连接同时只能一个在途请求,撞上状态机就抛 + # CannotSendRequest("Idle"),异常冒到 server.py 的 + # _client_loop 外面把线程打死 —— 之后电脑再也不回包。 + # + # 修法:发命令走独立连接 + 锁盖住整个请求周期 + + # _client_loop 兜住回包异常。_tests/test_relay_local.py + # 从"完全卡死"变成 21/21 全过。 + # + # 所以现在两条路用同样的轮数和超时,口径才一致。 + # (用户可通过 --relay-rounds / --relay-timeout 自行调整。)""", + "更新过时注释") + ok_all = ok_all and ok + + if not ok_all: + print() + print(" 有锚点没匹配,没有写回") + return 1 + + SRC.write_text(text, encoding="utf-8", newline="\n") + print() + print(" 已写回 bench_lan_vs_relay.py") + return 0 + + +if __name__ == "__main__": + sys.exit(main()) diff --git a/_build/insert_stub_checks.py b/_build/insert_stub_checks.py new file mode 100644 index 0000000..02d24d2 --- /dev/null +++ b/_build/insert_stub_checks.py @@ -0,0 +1,63 @@ +# -*- coding: utf-8 -*- +r'''在每个 7x 小节开头插一次 stub_ok 调用,用来定位桩是什么时候丢的。 + +为什么需要: + 测试跑着跑着,$STUB 目录会整个消失,于是 deploy.sh 找不到 + cloudflared 就去真的下载 GitHub —— 整个测试卡死十分钟, + 而且所有断言都变成"没启用 / 退出码不对"这种指不到根因的假失败。 + 插桩是为了找出它到底在哪一步消失。 +''' +from __future__ import annotations + +import sys +from pathlib import Path + +SRC = Path(r"C:\Users\shu\Desktop\deepseekagent\LanRemote" + r"\_build\test_deploy_sh.sh") + +MARKS = [ + ("7c. 默认", "7c"), + ("7d. --protocol quic", "7d"), + ("7e. --protocol http2", "7e"), + ("7f. --protocol 的非法值", "7f"), + ("7g. --port", "7g"), + ("7b. 再跑一次", "7b"), + ("12. 有凭据但没给域名", "12"), +] + + +def main() -> int: + text = SRC.read_text(encoding="utf-8") + if 'stub_ok "' in text: + print(" 已经插过了,不重复") + return 0 + + n = 0 + for marker, tag in MARKS: + key = "echo \"── %s" % marker + i = text.find(key) + if i < 0: + print(" 找不到小节: %s" % marker) + continue + j = text.find("\n", i) + 1 + text = text[:j] + 'stub_ok "%s"\n' % tag + text[j:] + n += 1 + SRC.write_text(text, encoding="utf-8", newline="\n") + print(" 插了 %d 处" % n) + + # 语法自检 + import subprocess + r = subprocess.run([r"C:\Program Files\Git\bin\bash.exe", "-n", + str(SRC).replace("\\", "/")], + capture_output=True, text=True, encoding="utf-8", + errors="replace") + if r.returncode == 0: + print(" 语法 OK") + else: + print(" 语法错误: %s" % (r.stderr or "").strip()[:300]) + return 1 + return 0 + + +if __name__ == "__main__": + sys.exit(main()) diff --git a/_build/inspect_pathtest.sh b/_build/inspect_pathtest.sh new file mode 100644 index 0000000..2d62e87 --- /dev/null +++ b/_build/inspect_pathtest.sh @@ -0,0 +1,27 @@ +#!/bin/bash +# 查测试为什么丢了桩 PATH +T=${1:-/tmp/tmp.QlqvI5fzbj} + +echo "===== 桩目录 =====" +ls -la "$T/stub/" 2>&1 + +echo +echo "===== stub.log 前几行 =====" +head -5 "$T/stub.log" 2>&1 +echo " (共 $(wc -l < "$T/stub.log" 2>/dev/null || echo 0) 行)" + +echo +echo "===== 测试脚本里所有 PATH 相关行 =====" +grep -n 'PATH' /c/Users/shu/Desktop/deepseekagent/LanRemote/_build/test_deploy_sh.sh 2>&1 + +echo +echo "===== 测试脚本里所有 rm -rf =====" +grep -n 'rm -rf' /c/Users/shu/Desktop/deepseekagent/LanRemote/_build/test_deploy_sh.sh 2>&1 + +echo +echo "===== run7c.log 的头部(最后一次成功的运行)=====" +head -14 "$T/run7c.log" 2>&1 + +echo +echo "===== run7d.log 的头部(第一次失败的运行)=====" +head -14 "$T/run7d.log" 2>&1 diff --git a/_build/lanbench.txt b/_build/lanbench.txt new file mode 100644 index 0000000..52e1fbe --- /dev/null +++ b/_build/lanbench.txt @@ -0,0 +1,19 @@ +================================================================== + 局域网直连 vs 跨网络中转 (每种路径 40 次 cmd:ping) +================================================================== +一、起本地中转(端口 59763) + 中转就绪 + 被控端就绪(局域网在听,中转已上线) + + 局域网 握手 16 ms 成功 40/40 (100.0%) 中位 0 P90 0 最小 0 最大 0 ms + 中转 握手 0 ms 成功 0/ 2 ( 0.0%) 中位 0 P90 0 最小 0 最大 0 ms + 连接阶段失败: timed out + +================================================================== + 对比 +================================================================== + 有路径没跑通,无法对比 + 中转 : 连接阶段失败: timed out + +BENCH_RESULT lan_median=0 lan_p90=0 lan_ok=40/40 lan_connect=16 relay_median=0 relay_p90=0 relay_ok=0/2 relay_connect=0 + **有路径没跑通** diff --git a/_build/lanbench2.txt b/_build/lanbench2.txt new file mode 100644 index 0000000..30a8b5e --- /dev/null +++ b/_build/lanbench2.txt @@ -0,0 +1,19 @@ +================================================================== + 局域网直连 vs 跨网络中转 (每种路径 30 次 cmd:ping) +================================================================== +一、起本地中转(端口 59815) + 中转就绪 + 被控端就绪(局域网在听,中转已上线) + + 局域网 握手 17 ms 成功 30/30 (100.0%) 中位 0 P90 0 最小 0 最大 1 ms + 中转 握手 0 ms 成功 0/30 ( 0.0%) 中位 0 P90 0 最小 0 最大 0 ms + 连接阶段失败: timed out + +================================================================== + 对比 +================================================================== + 有路径没跑通,无法对比 + 中转 : 连接阶段失败: timed out + +BENCH_RESULT lan_median=0 lan_p90=0 lan_ok=30/30 lan_connect=17 relay_median=0 relay_p90=0 relay_ok=0/30 relay_connect=0 + **有路径没跑通** diff --git a/_build/lanbench3.txt b/_build/lanbench3.txt new file mode 100644 index 0000000..1ee8651 --- /dev/null +++ b/_build/lanbench3.txt @@ -0,0 +1,19 @@ +================================================================== + 局域网直连 vs 跨网络中转 (每种路径 30 次 cmd:ping) +================================================================== +一、起本地中转(端口 60008) + 中转就绪 + 被控端就绪(局域网在听,中转已上线) + + 局域网 握手 2 ms 成功 30/30 (100.0%) 中位 0 P90 0 最小 0 最大 0 ms + 中转 握手 0 ms 成功 0/30 ( 0.0%) 中位 0 P90 0 最小 0 最大 0 ms + 连接阶段失败: timed out + +================================================================== + 对比 +================================================================== + 有路径没跑通,无法对比 + 中转 : 连接阶段失败: timed out + +BENCH_RESULT lan_median=0 lan_p90=0 lan_ok=30/30 lan_connect=2 relay_median=0 relay_p90=0 relay_ok=0/30 relay_connect=0 + **有路径没跑通** diff --git a/_build/lanbench4.txt b/_build/lanbench4.txt new file mode 100644 index 0000000..ada2231 --- /dev/null +++ b/_build/lanbench4.txt @@ -0,0 +1,20 @@ +================================================================== + 局域网直连 vs 跨网络中转 (每种路径 30 次 cmd:ping) +================================================================== +一、起本地中转(端口 60086) + 中转就绪 + 被控端就绪(局域网在听,中转已上线) + + 局域网 握手 16 ms 成功 30/30 (100.0%) 中位 0 P90 0 最小 0 最大 1 ms + 中转 握手 46 ms 成功 30/30 (100.0%) 中位 15 P90 29 最小 1 最大 32 ms + +================================================================== + 对比 +================================================================== + 中位延迟 局域网 0.0 ms 中转 15.1 ms -> 局域网快 0.0 倍 + P90 延迟 局域网 0 ms 中转 29 ms + 握手耗时 局域网 16 ms 中转 46 ms + 成功率 局域网 100.0% 中转 100.0% + +BENCH_RESULT lan_median=0 lan_p90=0 lan_ok=30/30 lan_connect=16 relay_median=15 relay_p90=29 relay_ok=30/30 relay_connect=46 + 两条路都跑通了 diff --git a/_build/rp_pc_long.tsv b/_build/rp_pc_long.tsv index 6093356..b1c029f 100644 --- a/_build/rp_pc_long.tsv +++ b/_build/rp_pc_long.tsv @@ -129,3 +129,26 @@ time code ms 2026-10-07 18:08:20 200 1260 2026-10-07 18:08:36 200 1009 2026-10-07 18:08:52 200 1104 +2026-10-07 18:09:33 0 26128 +2026-10-07 18:09:50 200 1393 +2026-10-07 18:10:06 200 1104 +2026-10-07 18:10:22 200 1328 +2026-10-07 18:10:38 200 980 +2026-10-07 18:10:54 200 1109 +2026-10-07 18:11:11 200 1513 +2026-10-07 18:11:27 200 1417 +2026-10-07 18:11:43 200 1351 +2026-10-07 18:12:00 200 1493 +2026-10-07 18:12:16 200 1078 +2026-10-07 18:12:33 200 2194 +2026-10-07 18:12:49 200 1179 +2026-10-07 18:13:06 200 1443 +2026-10-07 18:13:22 200 1180 +2026-10-07 18:13:38 200 1307 +2026-10-07 18:13:54 200 1166 +2026-10-07 18:14:10 200 1126 +2026-10-07 18:14:27 200 1385 +2026-10-07 18:14:43 200 1401 +2026-10-07 18:14:59 200 1089 +2026-10-07 18:15:15 200 987 +2026-10-07 18:15:31 200 999 diff --git a/_build/test_deploy_sh.sh b/_build/test_deploy_sh.sh index 41002c4..1324a6d 100644 --- a/_build/test_deploy_sh.sh +++ b/_build/test_deploy_sh.sh @@ -266,6 +266,23 @@ echo " 沙箱: $TMP" echo " 安装根: $SANDBOX" echo " 桩命令: $(ls "$STUB" | tr '\n' ' ')" +# 桩还在不在?每节开头都查一次。 +# 桩目录一旦丢了,后面所有"没启用 / 没生成 / 退出码不对"的断言 +# 都会变成假失败,而且报错信息完全指不到真正的原因 —— +# 实测踩过:桩被删掉之后,deploy.sh 找不到 cloudflared 就去 +# 真的下载 GitHub,整个测试卡死十分钟。 +stub_ok() { + local where="$1" + if [ -d "$STUB" ] && [ "$(command -v systemctl 2>/dev/null)" = "$STUB/systemctl" ]; then + ok "桩完好($where)" + else + bad "桩丢了或 PATH 被改($where): + STUB 存在吗: $([ -d "$STUB" ] && echo 是 || echo 否) + systemctl 解析到: $(command -v systemctl 2>/dev/null || echo 空) + PATH 前 80 字符: ${PATH:0:80}" + fi +} + # ════════════════════════════════════════════════════════════════ echo echo "── 5. 第一次部署(--skip-tunnel,不碰隧道)──" @@ -499,6 +516,7 @@ fi # ──────────────────────────────────────────────────────────────── echo echo "── 7c. 默认:两个隧道单元都要启用(协议级故障隔离)──" +stub_ok "7c" # 真机实测(40 次/组):quic 8 + h2 2 拿到 100% 可用率 + 最低 P90/P99。 # 单独跑一个协议都不如两个一起跑: # 运营商限 UDP(12 个 edge IP:TCP 12/12 通、UDP 0/12 通) @@ -526,6 +544,7 @@ fi echo echo "── 7d. --protocol quic:只跑主隧道 ──" +stub_ok "7d" : > "$STUB_LOG" printf 'lanremote-relay\n' > "$STUB_LOG.state" bash "$DEPLOY" --prefix "$SANDBOX" --protocol quic \ @@ -549,6 +568,7 @@ fi echo echo "── 7e. --protocol http2:只跑副本隧道 ──" +stub_ok "7e" : > "$STUB_LOG" printf 'lanremote-relay\n' > "$STUB_LOG.state" bash "$DEPLOY" --prefix "$SANDBOX" --protocol http2 \ @@ -567,6 +587,7 @@ fi echo echo "── 7f. --protocol 的非法值要报错 ──" +stub_ok "7f" bash "$DEPLOY" --prefix "$SANDBOX" --protocol udp >/dev/null 2>&1 check "非法协议退出码为 2" "$?" "2" bash "$DEPLOY" --prefix "$SANDBOX" --protocol both >/dev/null 2>&1 @@ -574,6 +595,7 @@ check "both 是合法值" "$?" "0" echo echo "── 7g. --port 换端口时 config.yml 必须跟着改 ──" +stub_ok "7g" # 只改 unit 里的 RELAY_PORT、不改 config.yml 的话, # 隧道会回源到老端口(没人听),现象是"隧道连上了但一访问就 502"。 if grep -q '127.0.0.1:8080' "$CFD/config.yml" 2>/dev/null; then @@ -605,6 +627,7 @@ fi echo echo "── 7b. 再跑一次(不给 --hostname),config.yml 不该被改 ──" +stub_ok "7b" H3=$(md5sum "$CFD/config.yml" | awk '{print $1}') bash "$DEPLOY" --prefix "$SANDBOX" > "$TMP/run4.log" 2>&1 RC4=$? @@ -722,6 +745,7 @@ fi # ════════════════════════════════════════════════════════════════ echo echo "── 12. 有凭据但没给域名 → 不许乱猜,必须明确提示 ──" +stub_ok "12" CFD2="$TMP/nohost/root/.cloudflared" SANDBOX2="$TMP/nohost" mkdir -p "$CFD2" diff --git a/_build/vcr.txt b/_build/vcr.txt new file mode 100644 index 0000000..9856c0d --- /dev/null +++ b/_build/vcr.txt @@ -0,0 +1,23 @@ +════════ 场景 A:两条路用同一个配对码(复刻 bench 现状)════════ + 第 1 台(跑局域网): 登记=True 设备数=1 + 已停掉第 1 台 + 第 2 台(跑中转): start_agent 认为登记=True + 中转上看到的设备: 验码电脑 码 246813 在线=True 空闲=1s + 场景A pair **超时**(没人回包) + + ── 中转日志里有没有『码被占用』── + [10-07 18:18:56] 配对码 246813 已被 验码电脑-b0dd7aae76ba 占用,拒绝 验码电脑-b6bfc86f574a + [10-07 18:19:02] 配对码 246813 已被 验码电脑-b0dd7aae76ba 占用,拒绝 验码电脑-b6bfc86f574a + [10-07 18:19:08] 配对码 246813 已被 验码电脑-b0dd7aae76ba 占用,拒绝 验码电脑-b6bfc86f574a + +════════ 场景 B:两条路各用不同的配对码(修法)════════ + 第 1 台: 登记=True + 第 2 台: 登记=True + 场景B pair 成功: {"ok": true, "token": "0fe2d1ed61da6cd489230490d4a77a72", "serverName": "验码电脑", + +════════ 结论 ════════ + 场景 A(同一个码): **不通** + 场景 B(不同码) : 通 + → 假设成立:bench 失败是因为两条路用了同一个配对码, + 第 2 台被「一码一机」规则拒掉,而 start_agent + 看到第 1 台还挂在线就以为成功了。**产品没问题。** diff --git a/_build/verify_code_reuse.py b/_build/verify_code_reuse.py new file mode 100644 index 0000000..00d4b1b --- /dev/null +++ b/_build/verify_code_reuse.py @@ -0,0 +1,225 @@ +# -*- coding: utf-8 -*- +r'''验证假设:bench_lan_vs_relay 中转那半失败,是因为两条路 +用了**同一个配对码**,第二台被控端注册被"一码一机"规则拒掉, +而 start_agent 看到上一台还挂在线就以为成功了。 + +做法:完全照 bench 的流程走两遍(起 agent1 -> 停 -> 起 agent2), +第一遍用同一个码,第二遍用不同的码,看结果差异。 +''' +from __future__ import annotations + +import json +import os +import shutil +import socket +import subprocess +import sys +import tempfile +import time +import urllib.error +import urllib.request +from pathlib import Path + +ROOT = Path(__file__).resolve().parent.parent +WINDOWS = ROOT / "windows" +UA = {"User-Agent": "LanRemote/1.8.2"} + + +def free_port() -> int: + s = socket.socket() + s.bind(("127.0.0.1", 0)) + p = s.getsockname()[1] + s.close() + return p + + +def get(base, path, timeout=6.0): + req = urllib.request.Request(base + path, headers=UA) + try: + with urllib.request.urlopen(req, timeout=timeout) as resp: + return resp.status, resp.read() + except Exception: # noqa: BLE001 + return 0, b"" + + +def post(base, path, body=b"", headers=None, timeout=20.0): + h = dict(UA) + h.update(headers or {}) + req = urllib.request.Request(base + path, data=body, headers=h, + method="POST") + try: + with urllib.request.urlopen(req, timeout=timeout) as resp: + return resp.status, resp.read() + except urllib.error.HTTPError as exc: + return exc.code, exc.read() + except Exception as exc: # noqa: BLE001 + return 0, str(exc).encode() + + +def main() -> int: + work = Path(tempfile.mkdtemp(prefix="codechk_")) + relay_port = free_port() + agent_port = free_port() + base = "http://127.0.0.1:%d" % relay_port + relay_proc = None + procs = [] + try: + sys.path.insert(0, str(WINDOWS)) + from lanremote.config import Store + + rdata = work / "r" + rdata.mkdir(parents=True, exist_ok=True) + env = dict(os.environ) + env.update({"RELAY_PORT": str(relay_port), "RELAY_BIND": "127.0.0.1", + "RELAY_DATA": str(rdata), "RELAY_POLL": "2", + "PYTHONIOENCODING": "utf-8", "PYTHONUNBUFFERED": "1"}) + rlog = open(work / "relay.log", "wb") + relay_proc = subprocess.Popen( + [sys.executable, "-u", str(ROOT / "relay" / "relay.py")], env=env, + stdout=rlog, stderr=subprocess.STDOUT) + for _ in range(60): + time.sleep(0.5) + if get(base, "/v1/health")[0] == 200: + break + + def start_agent(code, tag): + d = work / tag + d.mkdir(parents=True, exist_ok=True) + st = Store(d) + st.set_pairing_code(code) + st.set("setup_done", True) + st.set("allow_new_pairing", True) + st.set("close_pair_after_first", False) + st.set("server_name", "验码电脑") + st.set("relay_url", base) + st.set("port", agent_port) + e = dict(os.environ) + e.update({"YKXMZ_DATA": str(d), + "YKXMZ_LOCK_PORT": str(free_port()), + "PYTHONIOENCODING": "utf-8", "PYTHONUNBUFFERED": "1"}) + p = subprocess.Popen( + [sys.executable, "-u", str(WINDOWS / "run_agent.py"), + "--silent", "--port", str(agent_port)], + cwd=str(WINDOWS), env=e, + stdout=open(d / "out.log", "wb"), stderr=subprocess.STDOUT) + procs.append(p) + online = False + for _ in range(30): + time.sleep(1.0) + s, b = get(base, "/v1/health", timeout=4) + if s == 200: + snap = json.loads(b.decode()) + if any(x.get("online") for x in snap.get("devices", [])): + online = True + break + return p, online, snap if s == 200 else {} + + def stop(p): + try: + p.terminate() + p.wait(timeout=6) + except Exception: # noqa: BLE001 + try: + p.kill() + except Exception: # noqa: BLE001 + pass + + def relay_try(code, label): + """attach + pair,看能不能拿到回复。""" + s, b = post(base, "/v1/client/attach", json.dumps( + {"code": code, "name": "验码手表"}).encode(), + {"Content-Type": "application/json"}) + att = json.loads(b.decode()) + if not att.get("ok"): + print(" %s attach 就失败: %s" % (label, att.get("error"))) + return False + sess = att.get("session", "") + post(base, "/v1/client/send", + (json.dumps({"cmd": "pair", "deviceId": "x", + "code": code}) + "\n").encode(), + {"X-Session": sess}) + buf = b"" + deadline = time.time() + 12 + while time.time() < deadline: + _s, chunk = post(base, "/v1/client/poll", b"", + {"X-Session": sess}, 6.0) + buf += chunk + while b"\n" in buf: + line, _, buf = buf.partition(b"\n") + if not line.strip(): + continue + msg = json.loads(line.decode()) + if "event" in msg: + continue + print(" %s pair 成功: %s" + % (label, json.dumps(msg, ensure_ascii=False)[:80])) + return True + print(" %s pair **超时**(没人回包)" % label) + return False + + # ============ 场景 A:两条路用同一个码(bench 现在的做法)============ + print("════════ 场景 A:两条路用同一个配对码(复刻 bench 现状)════════") + CODE = "246813" + p1, on1, snap1 = start_agent(CODE, "a1") + print(" 第 1 台(跑局域网): 登记=%s 设备数=%d" + % (on1, len(snap1.get("devices", [])))) + stop(p1) + print(" 已停掉第 1 台") + time.sleep(2) + p2, on2, snap2 = start_agent(CODE, "a2") + print(" 第 2 台(跑中转): start_agent 认为登记=%s" % on2) + for d in snap2.get("devices", []): + print(" 中转上看到的设备: %s 码 %s 在线=%s 空闲=%ss" + % (d["name"], d["code"], d["online"], d["idleSeconds"])) + okA = relay_try(CODE, "场景A") + stop(p2) + + print() + print(" ── 中转日志里有没有『码被占用』──") + rlog.flush() + for line in (work / "relay.log").read_text( + encoding="utf-8", errors="replace").splitlines(): + if "占用" in line or "拒绝" in line: + print(" " + line[:110]) + + # ============ 场景 B:每条路用不同的码 ============ + print() + print("════════ 场景 B:两条路各用不同的配对码(修法)════════") + work2 = work / "b" + CODE1 = "111222" + CODE2 = "333444" + p3, on3, _ = start_agent(CODE1, "b1") + print(" 第 1 台: 登记=%s" % on3) + stop(p3) + time.sleep(2) + p4, on4, snap4 = start_agent(CODE2, "b2") + print(" 第 2 台: 登记=%s" % on4) + okB = relay_try(CODE2, "场景B") + stop(p4) + + print() + print("════════ 结论 ════════") + print(" 场景 A(同一个码): %s" % ("通" if okA else "**不通**")) + print(" 场景 B(不同码) : %s" % ("通" if okB else "**不通**")) + if (not okA) and okB: + print(" → 假设成立:bench 失败是因为两条路用了同一个配对码,") + print(" 第 2 台被「一码一机」规则拒掉,而 start_agent") + print(" 看到第 1 台还挂在线就以为成功了。**产品没问题。**") + return 0 + finally: + for p in procs: + try: + p.terminate() + except Exception: # noqa: BLE001 + pass + if relay_proc: + try: + relay_proc.terminate() + relay_proc.wait(timeout=6) + except Exception: # noqa: BLE001 + pass + shutil.rmtree(work, ignore_errors=True) + + +if __name__ == "__main__": + sys.exit(main()) diff --git a/_tests/bench_lan_vs_relay.py b/_tests/bench_lan_vs_relay.py index 0e38975..391ae73 100644 --- a/_tests/bench_lan_vs_relay.py +++ b/_tests/bench_lan_vs_relay.py @@ -237,7 +237,15 @@ def main() -> int: relay_port = free_port() agent_port = free_port() relay_url = "http://127.0.0.1:%d" % relay_port - code = "246813" + # ⚠ 两条路必须用**不同的**配对码。 + # 中转有「一个码只属于一台设备」的规则,而这个基准给每条路 + # 各起一台全新被控端(为了排除互相干扰,设计是对的)。 + # 要是两台共用一个码,第 2 台的注册会被拒,而第 1 台虽然 + # 进程被杀了、中转还以为它在线 —— 于是"看着登记成功、 + # 实际没人回包",表现为连接阶段超时。 + # 实测对照见 _build/verify_code_reuse.py:同码不通、不同码通。 + code = "246813" # 局域网那条路 + relay_code = "975310" # 中转那条路,必须不同 print("=" * 66) print(" 局域网直连 vs 跨网络中转 (每种路径 %d 次 cmd:ping)" @@ -285,10 +293,11 @@ def main() -> int: # 真实被控端同时被"一条 TCP 会话 + 一条中转会话"占用时行为 # 和单独用一条不一样。搞不清楚就别共用了 —— 每条路起一台干净实例, # 既排除了互相干扰,两边条件也完全一致,对比才有意义。 - def start_agent(): + def start_agent(agent_code=None): + agent_code = agent_code or code data = Path(tempfile.mkdtemp(prefix="bench_agent_", dir=str(work))) store = Store(data) - store.set_pairing_code(code) + store.set_pairing_code(agent_code) store.set("setup_done", True) store.set("allow_new_pairing", True) store.set("close_pair_after_first", False) @@ -325,9 +334,17 @@ def main() -> int: snap = json.loads(resp.read().decode("utf-8")) except Exception: # noqa: BLE001 continue - if any(d.get("online") for d in snap.get("devices", [])): + # ⚠ 不能只看"有没有设备在线" —— + # 上一台被控端虽然进程被杀,中转还没超时清理它, + # 于是这里会被僵尸设备骗过,以为新的一台登记成功了。 + # 要求:存在一台在线、且配对码正好是**这一台要用的码** + # 的设备。 + live = [d for d in snap.get("devices", []) + if d.get("online") and d.get("code") == agent_code] + if live: return proc, data - raise RuntimeError("被控端 45 秒内没登记到中转") + raise RuntimeError( + "被控端 45 秒内没登记到中转(码 %s)" % agent_code) def stop_agent(proc): if proc is None: @@ -361,26 +378,40 @@ def main() -> int: # ---- 跨网络那条路(换一台干净的被控端)---- # - # ⚠ 这里的轮数**故意比局域网少**,而且超时给得短。 - # 原因:当前版本经中转只稳定支撑前 1~2 次交互,之后被控端 - # 就不再回包(详见 _build/diag_relay_leg.py 的时间线: - # attach/pair/ping#1 全 0ms 返回,ping#2 开始 relay 一直回 0 字节)。 - # 这是中转链路的**产品 bug**,不是本测试的毛病 —— - # 仓库现成的 _tests/test_relay_local.py 也是同样形状。 - # 所以这里只做**有界**测量:拿得到就打点,拿不到就如实报错, - # 绝不让整个基准卡死。 - agent_proc, _data = start_agent() + # 【历史】这里原来写着"经中转只稳定支撑前 1~2 次交互", + # 并据此把轮数调小、超时调短。那个产品 bug **已经修好了**: + # + # 根因是一条 HTTP/1.1 连接被两个线程同时用 —— + # relay-link 线程的 /v1/agent/poll 要挂 180 秒(长轮询), + # client-relay 线程同时 POST /v1/agent/send 发命令, + # HTTP/1.1 一条连接同时只能一个在途请求,撞上状态机就抛 + # CannotSendRequest("Idle"),异常冒到 server.py 的 + # _client_loop 外面把线程打死 —— 之后电脑再也不回包。 + # + # 修法:发命令走独立连接 + 锁盖住整个请求周期 + + # _client_loop 兜住回包异常。_tests/test_relay_local.py + # 从"完全卡死"变成 21/21 全过。 + # + # 所以现在两条路用同样的轮数和超时,口径才一致。 + # (用户可通过 --relay-rounds / --relay-timeout 自行调整。) + agent_proc, _data = start_agent(relay_code) # attach 只是"接入中转",协议层还得 pair 一次才算鉴权完成 —— # 这一步等价于局域网那边的 connect(),两边口径才一致。 def relay_connect(): client = RelayClient(relay_url) - attach = client.attach(code) + # ⚠ 必须用 relay_code,不是 code —— + # code 是局域网那台(已经被 stop_agent 杀掉了,但中转还 + # 以为它在线)。attach 到死设备上,pair 就发给一个 + # 不存在的进程,表现成"连接阶段超时"。 + # 这个漏改让修好的产品背了一次黑锅。 + attach = client.attach(relay_code) if not attach.get("ok"): return client, {"ok": False, "error": attach.get("error") or "接入中转被拒"} reply = client.call({"cmd": "pair", "deviceId": "bench-relay", - "deviceName": "基准测试手表", "code": code}, + "deviceName": "基准测试手表", + "code": relay_code}, args.relay_timeout) return client, reply