shim: persistent 6h cooldown on 402 (cool.json), available counter in healthz; add qw_limits.sql (iishko gates)

This commit is contained in:
ENI
2026-11-21 17:34:48 +02:00
parent 370858c0df
commit 7db35a4ec1
4 changed files with 65 additions and 3 deletions
+44 -3
View File
@@ -60,8 +60,30 @@ MODES = {
_lock = threading.Lock()
_cursor = [0]
_accounts = []
_pool_mtime = 0.0
COOL_FILE = os.environ.get("QW_COOL_FILE", "/opt/qw-shim/cool.json")
_cool = {} # email -> unix ts until which the account is skipped
def load_cool():
try:
d = json.load(open(COOL_FILE, encoding="utf-8"))
now = time.time()
for k, v in d.items():
if isinstance(v, (int, float)) and v > now:
_cool[k] = float(v)
except Exception:
pass
def save_cool():
try:
now = time.time()
d = {k: v for k, v in _cool.items() if v > now}
tmp = COOL_FILE + ".tmp"
json.dump(d, open(tmp, "w", encoding="utf-8"))
os.replace(tmp, COOL_FILE)
except Exception:
pass
class QWError(Exception):
def __init__(self, code, msg):
@@ -71,9 +93,13 @@ class QWError(Exception):
def load_pool():
global _accounts
global _accounts, _pool_mtime
acc = []
if os.path.exists(POOL_PATH):
try:
_pool_mtime = os.path.getmtime(POOL_PATH)
except OSError:
_pool_mtime = 0.0
for line in open(POOL_PATH, encoding="utf-8"):
line = line.strip()
if not line:
@@ -85,9 +111,20 @@ def load_pool():
if d.get("jwt"):
acc.append(d)
_accounts = acc
load_cool()
return len(acc)
def maybe_reload():
"""Pick up accounts appended by the farm without a service restart."""
try:
mt = os.path.getmtime(POOL_PATH)
except OSError:
return
if mt != _pool_mtime:
load_pool()
def pick(skip=None):
with _lock:
n = len(_accounts)
@@ -219,9 +256,11 @@ class H(BaseHTTPRequestHandler):
self.wfile.write(b)
def do_GET(self):
maybe_reload()
if self.path.startswith("/healthz"):
return self._json(200, {"ok": True, "accounts": len(_accounts), "models": len(MODES),
"cooling": len([1 for v in _cool.values() if v > time.time()])})
"cooling": len([1 for v in _cool.values() if v > time.time()]),
"available": sum(1 for a in _accounts if _cool.get(a["email"], 0) <= time.time())})
if self.path.startswith("/v1/models"):
return self._json(200, {"object": "list", "data": [
{"id": k, "object": "model", "owned_by": "qwenwork"} for k in MODES]})
@@ -236,6 +275,7 @@ class H(BaseHTTPRequestHandler):
except Exception:
return self._json(400, {"error": {"message": "bad json"}})
maybe_reload()
model = req.get("model") or "qw-flash"
mode = MODES.get(model)
if not mode:
@@ -262,7 +302,8 @@ class H(BaseHTTPRequestHandler):
last_err = e
tried.add(acc["email"])
if last_err.code in (401, 402, 403):
_cool[acc["email"]] = time.time() + COOLDOWN
_cool[acc["email"]] = time.time() + (COOLDOWN if last_err.code != 402 else int(os.environ.get("QW_COOL_402", "21600")))
save_cool()
acc = pick(skip=tried)
if not acc:
break