Files
coarena-autoreg/coa_sync.py
T

107 lines
3.8 KiB
Python

#!/usr/bin/env python3
"""Keep a budgeted key pool honest in iishko/new-api.
Probes GET /api/v1/limits per channel key (spends no budget), parks channels whose
remaining daily USD is exhausted and revives them after the 00:00 UTC reset.
Dry run by default; writes nothing to the gateway without --apply.
Usage (on the prod host):
python3 coa_sync.py # dry run: prints park/revive/keep counts
python3 coa_sync.py --apply # writes channels/abilities + purges guard_hold
Cron:
*/15 * * * * root cd /root && /usr/bin/python3 coa_sync.py --apply >> /var/log/coa_sync.log 2>&1
"""
import json
import subprocess
import sys
import time
import urllib.request
from concurrent.futures import ThreadPoolExecutor
LIMITS = "https://coarena.ai/api/v1/limits"
LOG = "/var/log/coa_sync.log"
NAME_LIKE = "coarena-%"
FLOOR = 0.05
APPLY = "--apply" in sys.argv
def sh(sql_text):
"""Run SQL as postgres via a uniquely named file (a foreign /tmp/*.sql may execute instead)."""
path = "/tmp/coa_sync_q_%d.sql" % time.time_ns()
with open(path, "w") as fh:
fh.write(sql_text)
subprocess.run(["chmod", "644", path], capture_output=True)
p = subprocess.run(["su", "postgres", "-c", "psql -d newapi -At -F '|' -f " + path],
capture_output=True, text=True, timeout=180)
return p.stdout.strip(), p.stderr.strip()
out, err = sh("select id, name, key, status from channels where name like '%s' order by id;" % NAME_LIKE)
rows = []
for line in out.splitlines():
parts = line.split("|")
if len(parts) >= 4:
rows.append({"id": int(parts[0]), "name": parts[1], "key": parts[2], "status": int(parts[3])})
print("channels", len(rows), flush=True)
if err:
print("psql warn", err[:160], flush=True)
def limits(row):
req = urllib.request.Request(LIMITS, headers={"Authorization": "Bearer " + row["key"],
"User-Agent": "Mozilla/5.0"})
try:
with urllib.request.urlopen(req, timeout=25) as x:
d = json.loads(x.read())["data"]
used = (d.get("today") or {}).get("used_usd") or 0
cap = d.get("usd_per_day") or 0
return row, round(cap - used, 3)
except Exception as e:
return row, "err:" + type(e).__name__
res = []
with ThreadPoolExecutor(max_workers=8) as ex:
for row, left in ex.map(limits, rows):
res.append((row, left))
park, revive, keep, unknown = [], [], 0, 0
for row, left in res:
if isinstance(left, str):
unknown += 1
continue
if left <= FLOOR:
if row["status"] == 1:
park.append(row)
elif row["status"] != 1:
revive.append(row)
else:
keep += 1
print("park", len(park), "revive", len(revive), "keep", keep, "unknown", unknown, flush=True)
stmts = []
for row in park:
stmts.append("update channels set status=2 where id=%d;" % row["id"])
stmts.append("update abilities set enabled=false where channel_id=%d;" % row["id"])
for row in revive:
stmts.append("update channels set status=1 where id=%d;" % row["id"])
stmts.append("update abilities set enabled=true where channel_id=%d;" % row["id"])
stmts.append("delete from guard_hold where channel_id in (select id from channels where name like '%s');" % NAME_LIKE)
if APPLY and stmts:
o, e = sh("\n".join(stmts) + "\n")
print("applied", len(stmts), "stmts", (o or "")[-90:], (e or "")[:90], flush=True)
# new-api caches abilities ~60s; restart only when the live set actually changed.
if park or revive:
subprocess.run(["systemctl", "restart", "new-api.service"], capture_output=True)
line = "%s park=%d revive=%d keep=%d unknown=%d apply=%s" % (
time.strftime("%Y-%m-%d %H:%M:%S"), len(park), len(revive), keep, unknown, APPLY)
try:
with open(LOG, "a") as fh:
fh.write(line + "\n")
except Exception:
pass
print(line)