#!/usr/bin/env python3 """Render a sing-box config from proxylab's healthy.json. Two tiers so that "only healthy members serve traffic" does not turn into "one member and no failover": trusted : passed base + openrouter + gemini probes backup : passed the base probe only (reachable, but flaky / partial) urltest only ever dials a member that answers its own probe, so a dead entry costs one probe interval, not a 30s hang. The backup tier is appended only when the trusted tier cannot fail over on its own, which keeps the earlier lesson intact: adding fast-but-flaky members to a healthy pool makes urltest prefer them. Writes atomically to data/serve.json and validates with `sing-box check`. Exit codes: 0 ok, 1 no usable config (file untouched), 2 validation failed. """ import json import os import subprocess import sys import tempfile import time BASE = "/opt/proxy-lab" DATA = os.path.join(BASE, "data") HEALTHY = os.path.join(DATA, "healthy.json") SERVE = os.path.join(DATA, "serve.json") QUALITY = os.path.join(DATA, "quality.json") BIN = os.path.join(BASE, "bin", "sing-box") PORT = int(os.environ.get("SERVE_PORT", "20808")) MAX_OUT = int(os.environ.get("MAX_OUTBOUNDS", "8")) LISTEN = ["127.0.0.1", "172.19.0.1", "172.17.0.1"] TEST_URL = "https://www.gstatic.com/generate_204" TRUSTED_BASE = 0.9 # of the base probes TRUSTED_REAL = 0.5 # of the openrouter / gemini probes BACKUP_BASE = 0.5 WANT_MEMBERS = 3 # below this the backup tier is appended QUALITY_MAX_AGE = 3 * 3600 def key_of(ob): return "%s|%s|%s|%s" % ( ob.get("server"), ob.get("server_port"), (ob.get("tls") or {}).get("server_name"), (ob.get("transport") or {}).get("path"), ) def load_quality(): try: if time.time() - os.path.getmtime(QUALITY) > QUALITY_MAX_AGE: print("quality.json is stale, ignoring it") return {} with open(QUALITY, encoding="utf-8") as fh: return json.load(fh) except Exception: # noqa: BLE001 return {} def candidates(entries): seen = set() out = [] 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((key, ob)) return out def ratio(quality, key, name=None): q = quality.get(key) or {} if name is None: total = q.get("total") or 1 return (q.get("ok", 0) / total) targets = q.get("targets") or {} if name not in targets: return None total = q.get("total") or 1 return targets.get(name, 0) / total def classify(cands, quality): """Split candidates into trusted / backup, preserving latency order.""" trusted, backup = [], [] for key, ob in cands: if not quality: backup.append((key, ob)) continue base = ratio(quality, key) real = [r for r in (ratio(quality, key, "openrouter"), ratio(quality, key, "gemini")) if r is not None] if base >= TRUSTED_BASE and real and min(real) >= TRUSTED_REAL: trusted.append((key, ob)) elif base >= BACKUP_BASE: backup.append((key, ob)) else: # not even the base probe: keep it out of the pool entirely continue print("tiers: trusted=%d backup=%d (of %d candidates)" % (len(trusted), len(backup), len(cands))) return trusted, backup def select(trusted, backup): if len(trusted) >= WANT_MEMBERS: chosen = trusted[:MAX_OUT] else: chosen = (trusted + backup)[:MAX_OUT] if trusted: print("trusted tier has %d member(s); appended backup to reach %d" % (len(trusted), len(chosen))) return chosen def build(entries, quality): cands = candidates(entries) trusted, backup = classify(cands, quality) chosen = select(trusted, backup) if not chosen: # quality data missing for everything (fresh pool): use what we have chosen = cands[:WANT_MEMBERS] print("no classified members; falling back to first %d candidates" % len(chosen)) outs = [] for _, ob in chosen: ob = dict(ob) ob["tag"] = "p%d" % len(outs) outs.append(ob) if not outs: return None tags = [o["tag"] for o in outs] return { "log": {"level": "warn"}, "dns": {"servers": [{"type": "local", "tag": "local"}]}, "inbounds": [ {"type": "mixed", "tag": "in-%d" % i, "listen": addr, "listen_port": PORT} for i, addr in enumerate(LISTEN) ], "outbounds": outs + [ { "type": "urltest", "tag": "auto", "outbounds": tags, "url": TEST_URL, "interval": "45s", "tolerance": 50, "idle_timeout": "5m", "interrupt_exist_connections": False, } ], "route": {"final": "auto", "default_domain_resolver": "local"}, } def main(): try: with open(HEALTHY, encoding="utf-8") as fh: entries = json.load(fh) except Exception as exc: # noqa: BLE001 print("cannot read %s: %s" % (HEALTHY, exc)) return 1 config = build(entries, load_quality()) if config is None: print("no usable outbound in healthy.json; keeping current config") return 1 fd, tmp = tempfile.mkstemp(dir=DATA, prefix=".serve-", suffix=".json") try: with os.fdopen(fd, "w", encoding="utf-8") as fh: json.dump(config, fh, ensure_ascii=False) os.chmod(tmp, 0o600) check = subprocess.run([BIN, "check", "-c", tmp], capture_output=True, text=True) if check.returncode != 0: print("sing-box check failed:\n%s" % (check.stderr or check.stdout)[:600]) return 2 os.replace(tmp, SERVE) finally: if os.path.exists(tmp): os.unlink(tmp) best = config["outbounds"][0] print("rendered %d outbound(s) best=%s:%s -> %s" % ( len(config["outbounds"]) - 1, best.get("server"), best.get("server_port"), SERVE)) return 0 if __name__ == "__main__": sys.exit(main())