#!/usr/bin/env python3 """Probe every harvested outbound against the endpoints that actually matter. Two problems with the previous version: 1. It probed the outbounds found in serve.json. serve.json only ever holds the members the renderer already picked, so the pool could never grow: 1 member in -> 1 member probed -> 1 member rendered, forever. This version probes healthy.json, i.e. the whole harvested pool. 2. It only asked gstatic/204. A worker proxy can answer that and still fail OpenRouter or Google Generative Language, which is the "Connection error" the apps were seeing while the watchdog reported "healthy". Writes data/quality.json with per-target counters. """ 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") HEALTHY = os.path.join(DATA, "healthy.json") QUALITY = os.path.join(DATA, "quality.json") PORT_BASE = 22100 PROBES = 2 MAX_TIME = "6" MAX_PROBE = 16 # bound the runtime on a 2-core box # name, url, accepted http codes, extra headers TARGETS = [ ("base", "https://www.gstatic.com/generate_204", {"204"}, []), ("openrouter", "https://openrouter.ai/api/v1/models", {"200", "401"}, []), ("gemini", "https://generativelanguage.googleapis.com/v1beta/models", {"400"}, ["x-goog-api-key: dummy"]), ] 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 load_candidates(): with open(HEALTHY, encoding="utf-8") as fh: entries = json.load(fh) seen, out = set(), [] for entry in sorted(entries, key=lambda e: e.get("latency_ms") or 10 ** 9): ob = entry.get("outbound") if not isinstance(ob, dict) or "type" not in ob or "server" not in ob: continue key = key_of(ob) if key in seen: continue seen.add(key) out.append(ob) return out[:MAX_PROBE] def probe(port, url, accept, headers): cmd = [ "curl", "-s", "-o", "/dev/null", "-w", "%{http_code}", "--max-time", MAX_TIME, "-x", "http://127.0.0.1:%d" % port, ] for h in headers: cmd += ["-H", h] cmd.append(url) run = subprocess.run(cmd, capture_output=True, text=True) return (run.stdout or "").strip() in accept def main(): try: outs = load_candidates() except Exception as exc: # noqa: BLE001 print("cannot read healthy.json:", exc) return 1 if not outs: print("no candidates in healthy.json") 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: port = PORT_BASE + i stats = {name: 0 for name, _, _, _ in TARGETS} times = [] for _ in range(PROBES): t0 = time.time() if probe(port, TARGETS[0][1], TARGETS[0][2], TARGETS[0][3]): stats["base"] += 1 times.append(time.time() - t0) if stats["base"] == 0: continue for name, url, accept, headers in TARGETS[1:]: if probe(port, url, accept, headers): stats[name] += 1 result[key_of(ob)] = { "ok": stats["base"], "total": PROBES, "avg_ms": round(1000 * sum(times) / len(times)) if times else None, "targets": stats, } 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, %d probes/target):" % (len(result), PROBES)) for k, v in sorted(result.items(), key=lambda kv: (-kv[1]["ok"], kv[1]["avg_ms"] or 99999)): t = v.get("targets", {}) print(" base %d/%d openrouter %d gemini %d %5sms %s" % ( v["ok"], v["total"], t.get("openrouter", -1), t.get("gemini", -1), v["avg_ms"], k[:60])) return 0 if __name__ == "__main__": raise SystemExit(main())