Initial public release. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
166 lines
6.5 KiB
Python
166 lines
6.5 KiB
Python
#!/usr/bin/env python3
|
|
import json
|
|
import os
|
|
import sqlite3
|
|
import sys
|
|
import time
|
|
from pathlib import Path
|
|
from contextlib import closing
|
|
|
|
from account_limits import account_uid
|
|
|
|
BOT_DB = '/opt/grok-bot/bot.db'
|
|
NA_DB = '/opt/grok-gateway/new-api/one-api.db'
|
|
STATE = '/opt/grok-bot/econ_cap_state.json'
|
|
# Keep this literal compatible with the Mini App's read-only policy parser.
|
|
DAILY_USD_CAP = {0: 100, 1: 100, 2: 200, 3: 500, 4: 1000}
|
|
QUOTA_PER_USD = 500000
|
|
OWNER_UID = os.environ.get("IISHKO_OWNER_UID", "0").strip() or "0" # owner identity from config; "0" = no owner privilege
|
|
ST_ENABLED, ST_PAUSED, ST_EXPIRED, ST_EXHAUSTED = 1, 2, 3, 4
|
|
|
|
|
|
def load_state(archive=True):
|
|
if not os.path.exists(STATE):
|
|
return {}, 0
|
|
try:
|
|
with open(STATE, encoding='utf-8') as fh:
|
|
raw = json.load(fh)
|
|
except Exception:
|
|
return {}, 0
|
|
if not isinstance(raw, dict):
|
|
return {}, 0
|
|
if 'paused' in raw:
|
|
p = raw.get('paused') or {}
|
|
return ({k: v for k, v in p.items() if isinstance(v, dict)}, 0)
|
|
if raw:
|
|
if archive:
|
|
try:
|
|
with open(STATE + '.v1.bak-%d' % int(time.time()), 'w', encoding='utf-8') as fh:
|
|
json.dump(raw, fh)
|
|
except Exception:
|
|
pass
|
|
return {}, len(raw)
|
|
return {}, 0
|
|
|
|
|
|
def _levels(now):
|
|
"""Read ranks and all deny flags; a broken/incomplete policy must raise."""
|
|
lvl, nogo = {}, set()
|
|
uri = Path(BOT_DB).resolve().as_uri() + '?mode=ro'
|
|
with closing(sqlite3.connect(uri, uri=True, timeout=30)) as bot:
|
|
rows = bot.execute(
|
|
'SELECT tg_id,badge_lock,badge_until,rank_cache,'
|
|
'COALESCE(banned,0),COALESCE(key_locked,0),COALESCE(api_blocked,0) FROM users'
|
|
).fetchall()
|
|
for uid, lock, until, rank, banned, key_locked, api_blocked in rows:
|
|
effective = int(lock or 0) if not until or int(until) > now else 0
|
|
lvl[str(uid)] = min(4, max(0, effective, int(rank or 0)))
|
|
if banned or api_blocked or key_locked:
|
|
nogo.add(str(uid))
|
|
return lvl, nogo
|
|
|
|
|
|
def _sync_cap_flag(paused, dry):
|
|
"""Only the daily access flag is mutable; never infer a token unlock."""
|
|
want = {uid for name in paused if (uid := account_uid(name)) is not None}
|
|
set_on = set_off = 0
|
|
uri = Path(BOT_DB).resolve().as_uri() + ('?mode=ro' if dry else '?mode=rw')
|
|
with closing(sqlite3.connect(uri, uri=True, timeout=30)) as bot:
|
|
bot.execute('PRAGMA busy_timeout=30000')
|
|
if not dry:
|
|
bot.execute('BEGIN IMMEDIATE')
|
|
try:
|
|
cols = {r[1] for r in bot.execute('PRAGMA table_info(users)')}
|
|
if 'cap_paused' not in cols:
|
|
if dry:
|
|
return len(want), 0
|
|
bot.execute('ALTER TABLE users ADD COLUMN cap_paused INTEGER DEFAULT 0')
|
|
have = {int(t): int(c or 0) for t, c in
|
|
bot.execute('SELECT tg_id,COALESCE(cap_paused,0) FROM users')}
|
|
for uid, current in have.items():
|
|
desired = int(uid in want)
|
|
if current == desired:
|
|
continue
|
|
if desired:
|
|
set_on += 1
|
|
elif current:
|
|
set_off += 1
|
|
if not dry:
|
|
bot.execute('UPDATE users SET cap_paused=? WHERE tg_id=?', (desired, uid))
|
|
if not dry:
|
|
bot.commit()
|
|
except BaseException:
|
|
if not dry:
|
|
bot.rollback()
|
|
raise
|
|
return set_on, set_off
|
|
|
|
|
|
def main(argv=None):
|
|
argv = sys.argv[1:] if argv is None else argv
|
|
dry = '--dry-run' in argv
|
|
now = int(time.time())
|
|
msk0 = now - ((now + 3 * 3600) % 86400)
|
|
previous, migrated_v1 = load_state(archive=not dry)
|
|
lvl, nogo = _levels(now)
|
|
uri = Path(NA_DB).resolve().as_uri() + '?mode=ro'
|
|
with closing(sqlite3.connect(uri, uri=True, timeout=60)) as na:
|
|
na.execute('BEGIN')
|
|
spent_uid = {}
|
|
for name, quota in na.execute(
|
|
'SELECT token_name,COALESCE(SUM(quota),0) FROM logs '
|
|
'WHERE type=2 AND created_at>=? AND created_at<? GROUP BY token_name',
|
|
(msk0, msk0 + 86400)):
|
|
uid = account_uid(name)
|
|
if uid is not None:
|
|
spent_uid[uid] = spent_uid.get(uid, 0) + int(quota)
|
|
tokens = na.execute(
|
|
'SELECT id,name,remain_quota,status FROM tokens WHERE deleted_at IS NULL'
|
|
).fetchall()
|
|
paused, live = {}, set()
|
|
newly = stale = 0
|
|
for tid, name, remain, status in tokens:
|
|
uid = account_uid(name)
|
|
if uid is None:
|
|
continue
|
|
live.add(name)
|
|
old = previous.get(name)
|
|
if old and int(old.get('tid') or 0) != int(tid):
|
|
stale += 1
|
|
old = None
|
|
if str(uid) == OWNER_UID or str(uid) not in lvl or str(uid) in nogo:
|
|
continue
|
|
cap = DAILY_USD_CAP[lvl[str(uid)]]
|
|
if spent_uid.get(uid, 0) < cap * QUOTA_PER_USD:
|
|
continue
|
|
# A flag receipt is never evidence that we own status=2 or may resume it.
|
|
paused[name] = {'ts': now, 'tid': tid, 'flag_only': True,
|
|
'spent': round(spent_uid.get(uid, 0) / QUOTA_PER_USD, 2),
|
|
'prev_status': status}
|
|
if old is None:
|
|
newly += 1
|
|
pruned = sum(name not in live for name in previous)
|
|
resumed = sum(name in live and name not in paused for name in previous)
|
|
# Complete all reads before clearing or setting any access flag. A read error
|
|
# propagates and leaves the previous durable flags and financial state intact.
|
|
flag_on, flag_off = _sync_cap_flag(paused, dry)
|
|
if not dry:
|
|
tmp = STATE + '.tmp'
|
|
with open(tmp, 'w', encoding='utf-8') as fh:
|
|
json.dump({'v': 2, 'paused': paused, 'updated': now}, fh)
|
|
os.replace(tmp, STATE)
|
|
print('%s econ_cap2%s: tokens=%d flagged_now=%d released_flags=%d '
|
|
'in_state=%d stale_tid=%d pruned=%d migrated_v1=%d cap_flag=+%d/-%d'
|
|
% (time.strftime('%F %T'), ' (DRY RUN)' if dry else '', len(tokens), newly,
|
|
resumed, len(paused), stale, pruned, migrated_v1, flag_on, flag_off))
|
|
return {'dry': dry, 'tokens': len(tokens), 'paused_now': newly,
|
|
'resumed_now': resumed, 'healed_exhausted': 0,
|
|
'adopted': 0, 'orphan_resumed': 0, 'repaused': 0,
|
|
'stale_tid': stale, 'pruned': pruned,
|
|
'in_state': len(paused), 'migrated_v1': migrated_v1,
|
|
'cap_flag_on': flag_on, 'cap_flag_off': flag_off}
|
|
|
|
|
|
if __name__ == '__main__':
|
|
main()
|