#!/usr/bin/env python3 """Measure the real success rate of every outbound and write data/quality.json. Free Cloudflare-worker configs often pass a single health check but then answer 503 under load. This probe gives each outbound a dedicated inbound port and sends several requests through it, so the renderer can drop the flaky ones. """ import json import os import subprocess import time BASE = "/opt/proxy-lab" DATA = os.path.join(BASE, "data") BIN = os.path.join(BASE, "bin", "sing-box") SERVE = os.path.join(DATA, "serve.json") QUALITY = os.path.join(DATA, "quality.json") PORT_BASE = 22100 PROBES = 5 TARGET = "https://www.gstatic.com/generate_204" def key_of(o): return "%s|%s|%s|%s" % ( o.get("server"), o.get("server_port"), (o.get("tls") or {}).get("server_name"), (o.get("transport") or {}).get("path"), ) def main(): try: current = json.load(open(SERVE, encoding="utf-8")) except Exception as exc: # noqa: BLE001 print("cannot read serve.json:", exc) return 1 outs = [o for o in current.get("outbounds", []) if o.get("tag") != "auto"] if not outs: print("no outbounds to probe") return 1 cfg = { "log": {"level": "error"}, "dns": {"servers": [{"type": "local", "tag": "local"}]}, "inbounds": [], "outbounds": [{"type": "direct", "tag": "direct"}], "route": {"rules": [], "final": "direct", "default_domain_resolver": "local"}, } meta = [] for i, ob in enumerate(outs): ob = dict(ob) ob["tag"] = "o%d" % i cfg["outbounds"].append(ob) cfg["inbounds"].append( {"type": "mixed", "tag": "in%d" % i, "listen": "127.0.0.1", "listen_port": PORT_BASE + i} ) cfg["route"]["rules"].append({"inbound": ["in%d" % i], "outbound": "o%d" % i}) meta.append((i, ob)) tmp = os.path.join(DATA, ".quality_probe.json") with open(tmp, "w", encoding="utf-8") as fh: json.dump(cfg, fh) proc = subprocess.Popen( [BIN, "run", "-c", tmp], stdout=subprocess.DEVNULL, stderr=subprocess.DEVNULL, ) result = {} try: time.sleep(4) for i, ob in meta: ok = 0 times = [] for _ in range(PROBES): t0 = time.time() run = subprocess.run( ["curl", "-s", "-o", "/dev/null", "-w", "%{http_code}", "--max-time", "8", "-x", "http://127.0.0.1:%d" % (PORT_BASE + i), TARGET], capture_output=True, text=True, ) if (run.stdout or "").strip() == "204": ok += 1 times.append(time.time() - t0) result[key_of(ob)] = { "ok": ok, "total": PROBES, "avg_ms": round(1000 * sum(times) / len(times)) if times else None, } finally: proc.terminate() try: proc.wait(timeout=5) except Exception: # noqa: BLE001 proc.kill() if os.path.exists(tmp): os.unlink(tmp) with open(QUALITY, "w", encoding="utf-8") as fh: json.dump(result, fh, indent=1) print("quality (%d outbounds):" % len(result)) for k, v in sorted(result.items(), key=lambda kv: (-kv[1]["ok"], kv[1]["avg_ms"] or 99999)): print(" %d/%d %5sms %s" % (v["ok"], v["total"], v["avg_ms"], k[:70])) return 0 if __name__ == "__main__": raise SystemExit(main())