# -*- coding: utf-8 -*- r'''稳定性观测:连续打公网,统计可用率。 用途:验证 2.1.2 的隧道加固(协议 auto + 重试拉大)真的有效。 2.1.1 之前是"过一阵就 530",所以只看一次 200 说明不了问题, 要**连续观测一段时间**。 用法: python _build/watch_stability.py # 默认 20 次、间隔 15 秒 python _build/watch_stability.py 40 20 # 40 次、间隔 20 秒 ''' from __future__ import annotations import sys import time import urllib.error import urllib.request URL = "https://relay.xxmxxs.top/v1/health" def once(timeout: float = 15.0) -> tuple: """返回 (状态码文本, 耗时秒)。""" t0 = time.time() try: req = urllib.request.Request( URL, headers={"Cache-Control": "no-cache", "User-Agent": "ykxmz-watch"}) with urllib.request.urlopen(req, timeout=timeout) as resp: resp.read(64) return str(resp.status), time.time() - t0 except urllib.error.HTTPError as exc: try: exc.read(64) except Exception: # noqa: BLE001 pass return str(exc.code), time.time() - t0 except Exception as exc: # noqa: BLE001 return "无响应(%s)" % type(exc).__name__, time.time() - t0 def main() -> int: times = int(sys.argv[1]) if len(sys.argv) > 1 else 20 gap = float(sys.argv[2]) if len(sys.argv) > 2 else 15.0 print("=" * 58) print(" 公网稳定性观测:%d 次,间隔 %.0f 秒(约 %.0f 分钟)" % (times, gap, times * gap / 60)) print("=" * 58) codes = [] durs = [] for i in range(1, times + 1): code, dur = once() codes.append(code) durs.append(dur) mark = "✓" if code == "200" else "✗" print(" %s 第 %2d 次: %-8s %.2fs" % (mark, i, code, dur)) if i < times: time.sleep(gap) ok = sum(1 for c in codes if c == "200") print() print("=" * 58) print(" 200 的次数: %d / %d" % (ok, times)) print(" 可用率: %.1f%%" % (100.0 * ok / max(1, times))) if durs: sd = sorted(durs) print(" 延迟 中位: %.2fs P90: %.2fs 最大: %.2fs" % (sd[len(sd) // 2], sd[min(len(sd) - 1, int(len(sd) * 0.9))], sd[-1])) print() if ok == times: print(" ✅ 全程 200 —— 加固有效") elif ok >= times * 0.9: print(" ⚠ 偶尔失败(%d 次)—— 比加固前好,但还没完全稳" % (times - ok)) else: print(" ❌ 可用率偏低(%d 次失败)—— 还要继续查" % (times - ok)) return 0 if __name__ == "__main__": sys.exit(main())