Initial public release. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
359 lines
14 KiB
Python
359 lines
14 KiB
Python
import copy
|
|
import hashlib
|
|
import os
|
|
import re
|
|
import sqlite3
|
|
import threading
|
|
import time
|
|
from contextlib import closing
|
|
from pathlib import Path
|
|
|
|
REF_NEW_ID_MIN = 9_000_000_000
|
|
MSK_OFFSET = 3 * 3600
|
|
DEFAULT_LIMIT = 20
|
|
MAX_LIMIT = 100
|
|
KINDS = ("referrals", "requests", "tokens", "models")
|
|
PERIODS = ("day", "week", "month", "all")
|
|
QUERY_DEADLINE = float(os.environ.get("IISHKO_RANK_QUERY_DEADLINE", "8"))
|
|
_ROLLING = {"week": 7 * 86400, "month": 30 * 86400}
|
|
_ACCOUNT_NAME = re.compile(r"(?:tg|pm|sol)([1-9][0-9]*)(?:-k[1-9][0-9]*)?\Z")
|
|
_GLOB_SCOPE = ("(token_name GLOB 'tg[0-9]*' OR token_name GLOB 'pm[0-9]*' "
|
|
"OR token_name GLOB 'sol[0-9]*')")
|
|
_SOURCES = {
|
|
"referrals": "bot.users.ref_awarded",
|
|
"requests": "gateway.logs(type=2)",
|
|
"tokens": "gateway.logs(type=2)",
|
|
"models": "gateway.logs(type=2).model_name",
|
|
}
|
|
_VALUES = {"referrals": "weighted_refs", "requests": "requests", "tokens": "tokens",
|
|
"models": "requests"}
|
|
|
|
_CACHE = {}
|
|
_CACHE_LOCK = threading.Lock()
|
|
_CACHE_TTL = 60.0
|
|
_CACHE_MAX = 64
|
|
|
|
|
|
# ---------------------------------------------------------------------------
|
|
# validation / windows / identity
|
|
|
|
def normalize_kind(kind):
|
|
value = "referrals" if kind is None else kind
|
|
if not isinstance(value, str):
|
|
raise ValueError("kind must be one of: " + ", ".join(KINDS))
|
|
value = value.strip().lower()
|
|
if value not in KINDS:
|
|
raise ValueError("kind must be one of: " + ", ".join(KINDS))
|
|
return value
|
|
|
|
|
|
def normalize_period(period, kind="referrals"):
|
|
"""Validate a period; omitted means lifetime for referrals, week for usage."""
|
|
if period is None:
|
|
return "all" if kind == "referrals" else "week"
|
|
if not isinstance(period, str):
|
|
raise ValueError("period must be one of: " + ", ".join(PERIODS))
|
|
value = period.strip().lower()
|
|
if value not in PERIODS:
|
|
raise ValueError("period must be one of: " + ", ".join(PERIODS))
|
|
if value == "all" and kind != "referrals":
|
|
raise ValueError("period all is supported for referrals only")
|
|
return value
|
|
|
|
|
|
def normalize_limit(limit):
|
|
if limit is None or limit == "":
|
|
return DEFAULT_LIMIT
|
|
if isinstance(limit, bool):
|
|
raise ValueError("limit must be an integer from 1 to %d" % MAX_LIMIT)
|
|
try:
|
|
value = int(limit)
|
|
except (TypeError, ValueError):
|
|
raise ValueError("limit must be an integer from 1 to %d" % MAX_LIMIT) from None
|
|
if not 1 <= value <= MAX_LIMIT:
|
|
raise ValueError("limit must be an integer from 1 to %d" % MAX_LIMIT)
|
|
return value
|
|
|
|
|
|
def window(period, now):
|
|
"""(start, end) unix seconds for a validated period; ``start`` is None for all."""
|
|
if type(now) is not int:
|
|
raise ValueError("now must be an integer unix timestamp")
|
|
if period == "all":
|
|
return None, now
|
|
if period == "day":
|
|
return (now + MSK_OFFSET) // 86400 * 86400 - MSK_OFFSET, now
|
|
return now - _ROLLING[period], now
|
|
|
|
|
|
def account_uid(name):
|
|
"""Canonical Telegram uid encoded in a credential name, or None.
|
|
|
|
Mirrors ``account_limits.account_uid``: only a full match counts, so
|
|
``tg1239``, ``tg123-k0`` and ``tg0123`` never belong to uid 123.
|
|
"""
|
|
if not isinstance(name, str):
|
|
return None
|
|
match = _ACCOUNT_NAME.fullmatch(name)
|
|
if match is None:
|
|
return None
|
|
uid = int(match.group(1))
|
|
return uid if uid <= 9223372036854775807 else None
|
|
|
|
|
|
def public_user(uid, username):
|
|
"""Public label only: ``@name`` or a stable pseudonym; never the uid."""
|
|
cleaned = (username or "").strip() if isinstance(username, str) else ""
|
|
if cleaned.startswith("@"):
|
|
cleaned = cleaned[1:].strip()
|
|
if cleaned:
|
|
return "@" + cleaned
|
|
digest = hashlib.sha256(("iishko-rank:%d" % int(uid)).encode("ascii")).hexdigest()
|
|
return "user-" + digest[:8]
|
|
|
|
|
|
# ---------------------------------------------------------------------------
|
|
# read-only database helpers
|
|
|
|
def _ro(path, timeout=8.0, deadline=None):
|
|
uri = Path(path).resolve().as_uri() + "?mode=ro"
|
|
con = sqlite3.connect(uri, uri=True, timeout=timeout)
|
|
con.row_factory = sqlite3.Row
|
|
con.execute("PRAGMA query_only=ON")
|
|
if deadline is not None:
|
|
# Bounded scan: abort instead of holding an HTTP worker on a huge window.
|
|
con.set_progress_handler(
|
|
lambda: 1 if time.monotonic() > deadline else 0, 10_000)
|
|
return con
|
|
|
|
|
|
def _columns(con, table):
|
|
return {row[1] for row in con.execute("PRAGMA table_info(" + table + ")")}
|
|
|
|
|
|
def _stamp(path):
|
|
try:
|
|
info = os.stat(path)
|
|
except OSError:
|
|
return None
|
|
return (info.st_mtime_ns, info.st_size)
|
|
|
|
|
|
def _cached(key, build):
|
|
now = time.monotonic()
|
|
with _CACHE_LOCK:
|
|
hit = _CACHE.get(key)
|
|
if hit is not None and hit[0] > now:
|
|
return copy.deepcopy(hit[1])
|
|
data = build()
|
|
with _CACHE_LOCK:
|
|
if len(_CACHE) >= _CACHE_MAX:
|
|
expired = [k for k, (expires, _) in _CACHE.items() if expires <= now]
|
|
for stale in (expired or list(_CACHE))[: max(1, _CACHE_MAX // 8)]:
|
|
_CACHE.pop(stale, None)
|
|
_CACHE[key] = (now + _CACHE_TTL, copy.deepcopy(data))
|
|
return data
|
|
|
|
|
|
# ---------------------------------------------------------------------------
|
|
# referrals
|
|
|
|
def _referral_rows(bot_db, start, end, limit, deadline=None):
|
|
con = _ro(bot_db, deadline=deadline)
|
|
try:
|
|
columns = _columns(con, "users")
|
|
required = {"tg_id", "username", "referred_by", "ref_awarded"}
|
|
if not required.issubset(columns):
|
|
raise sqlite3.OperationalError("users schema unavailable")
|
|
if start is not None and "ref_time" not in columns:
|
|
raise sqlite3.OperationalError("users.ref_time unavailable")
|
|
clean = []
|
|
for field in ("banned", "api_blocked"):
|
|
clean.append("COALESCE(u.%s,0)=0" % field if field in columns else "1=1")
|
|
sql = ("SELECT u.tg_id AS uid, u.username AS username, "
|
|
"SUM(CASE WHEN r.tg_id>=? THEN 0.5 ELSE 1.0 END) AS w, COUNT(*) AS n "
|
|
"FROM users AS r JOIN users AS u ON u.tg_id=r.referred_by "
|
|
"WHERE r.ref_awarded=1 AND r.referred_by IS NOT NULL AND " + " AND ".join(clean))
|
|
args = [REF_NEW_ID_MIN]
|
|
if start is not None:
|
|
sql += " AND r.ref_time>=? AND r.ref_time<=?"
|
|
args.extend((start, end))
|
|
count_sql = ("SELECT COUNT(*) FROM (SELECT 1 FROM users AS r JOIN users AS u "
|
|
"ON u.tg_id=r.referred_by WHERE r.ref_awarded=1 AND "
|
|
"r.referred_by IS NOT NULL AND " + " AND ".join(clean))
|
|
count_args = list(args[1:])
|
|
if start is not None:
|
|
count_sql += " AND r.ref_time>=? AND r.ref_time<=?"
|
|
count_sql += " GROUP BY u.tg_id)"
|
|
total = con.execute(count_sql, count_args).fetchone()[0]
|
|
sql += " GROUP BY u.tg_id, u.username ORDER BY w DESC, n DESC, u.tg_id ASC LIMIT ?"
|
|
args.append(limit)
|
|
rows = con.execute(sql, args).fetchall()
|
|
finally:
|
|
con.close()
|
|
out = []
|
|
for index, row in enumerate(rows):
|
|
refs = float(row["w"] or 0.0)
|
|
out.append({"pos": index + 1, "user": public_user(row["uid"], row["username"]),
|
|
"value": refs, "refs": refs, "count": int(row["n"] or 0)})
|
|
return out, int(total or 0)
|
|
|
|
|
|
# ---------------------------------------------------------------------------
|
|
# gateway usage (requests / tokens)
|
|
|
|
def _counter_sql(columns):
|
|
prompt = "prompt_tokens" if "prompt_tokens" in columns else "NULL"
|
|
completion = "completion_tokens" if "completion_tokens" in columns else "NULL"
|
|
bad = ("{p} IS NULL OR {c} IS NULL OR {p}<0 OR {c}<0".format(p=prompt, c=completion))
|
|
known = "CASE WHEN %s THEN 0 ELSE %s+%s END" % (bad, prompt, completion)
|
|
unknown = "CASE WHEN %s THEN 1 ELSE 0 END" % bad
|
|
return known, unknown
|
|
|
|
|
|
def _usage_by_token(gw_db, start, end, deadline=None):
|
|
con = _ro(gw_db, deadline=deadline)
|
|
try:
|
|
columns = _columns(con, "logs")
|
|
if not {"token_name", "created_at", "type"}.issubset(columns):
|
|
raise sqlite3.OperationalError("saved request logs unavailable")
|
|
known, unknown = _counter_sql(columns)
|
|
rows = con.execute(
|
|
"SELECT token_name, COUNT(*) AS requests, COALESCE(SUM(" + known + "),0) AS known_tokens, "
|
|
"COALESCE(SUM(" + unknown + "),0) AS unknown_requests "
|
|
"FROM logs WHERE type=2 AND created_at>=? AND created_at<=? AND " + _GLOB_SCOPE +
|
|
" GROUP BY token_name", (start, end)).fetchall()
|
|
finally:
|
|
con.close()
|
|
return rows
|
|
|
|
|
|
def _users_meta(bot_db, uids, deadline=None):
|
|
"""username/blocked flags for the ranked uids; missing rows mean no profile."""
|
|
meta = {}
|
|
if not uids:
|
|
return meta
|
|
con = _ro(bot_db, deadline=deadline)
|
|
try:
|
|
columns = _columns(con, "users")
|
|
if "tg_id" not in columns:
|
|
raise sqlite3.OperationalError("users schema unavailable")
|
|
banned = "COALESCE(banned,0)" if "banned" in columns else "0"
|
|
blocked = "COALESCE(api_blocked,0)" if "api_blocked" in columns else "0"
|
|
username = "username" if "username" in columns else "NULL"
|
|
ordered = sorted(uids)
|
|
for offset in range(0, len(ordered), 400):
|
|
chunk = ordered[offset:offset + 400]
|
|
rows = con.execute(
|
|
"SELECT tg_id, " + username + " AS username, " + banned + " AS banned, " +
|
|
blocked + " AS api_blocked FROM users WHERE tg_id IN (" +
|
|
",".join("?" for _ in chunk) + ")", chunk).fetchall()
|
|
for row in rows:
|
|
meta[int(row["tg_id"])] = (row["username"], bool(row["banned"]), bool(row["api_blocked"]))
|
|
finally:
|
|
con.close()
|
|
return meta
|
|
|
|
|
|
def _user_usage_rows(bot_db, gw_db, start, end, limit, order, deadline=None):
|
|
totals = {}
|
|
for row in _usage_by_token(gw_db, start, end, deadline=deadline):
|
|
uid = account_uid(row["token_name"])
|
|
if uid is None:
|
|
continue
|
|
slot = totals.setdefault(uid, [0, 0, 0]) # requests, known, unknown
|
|
slot[0] += int(row["requests"] or 0)
|
|
slot[1] += int(row["known_tokens"] or 0)
|
|
slot[2] += int(row["unknown_requests"] or 0)
|
|
meta = _users_meta(bot_db, list(totals), deadline=deadline)
|
|
ranked = []
|
|
for uid, (requests, known, unknown) in totals.items():
|
|
username, banned, blocked = meta.get(uid, (None, False, False))
|
|
if banned or blocked:
|
|
continue
|
|
ranked.append((uid, username, requests, known, unknown))
|
|
if order == "tokens":
|
|
ranked.sort(key=lambda item: (-item[3], -item[2], item[1] or "", item[0]))
|
|
else:
|
|
ranked.sort(key=lambda item: (-item[2], -item[3], item[1] or "", item[0]))
|
|
out = []
|
|
for index, (uid, username, requests, known, unknown) in enumerate(ranked[:limit]):
|
|
complete = unknown == 0
|
|
out.append({"pos": index + 1, "user": public_user(uid, username),
|
|
"value": requests if order == "requests" else known,
|
|
"requests": requests,
|
|
"tokens": known if complete else None,
|
|
"known_tokens": known,
|
|
"unknown_token_requests": unknown,
|
|
"tokens_complete": complete,
|
|
"value_kind": "exact" if complete else "lower_bound"})
|
|
return out, len(ranked)
|
|
|
|
|
|
# ---------------------------------------------------------------------------
|
|
# models
|
|
|
|
def _model_rows(gw_db, start, end, limit, deadline=None):
|
|
con = _ro(gw_db, deadline=deadline)
|
|
try:
|
|
columns = _columns(con, "logs")
|
|
if not {"model_name", "created_at", "type", "token_name"}.issubset(columns):
|
|
raise sqlite3.OperationalError("saved request logs unavailable")
|
|
known, unknown = _counter_sql(columns)
|
|
rows = con.execute(
|
|
"SELECT NULLIF(TRIM(model_name),'') AS model, COUNT(*) AS requests, "
|
|
"COALESCE(SUM(" + known + "),0) AS known_tokens, "
|
|
"COALESCE(SUM(" + unknown + "),0) AS unknown_requests "
|
|
"FROM logs WHERE type=2 AND created_at>=? AND created_at<=? AND " + _GLOB_SCOPE +
|
|
" GROUP BY model ORDER BY requests DESC, model IS NULL, model ASC LIMIT ?",
|
|
(start, end, limit)).fetchall()
|
|
finally:
|
|
con.close()
|
|
out = []
|
|
for index, row in enumerate(rows):
|
|
requests = int(row["requests"] or 0)
|
|
known = int(row["known_tokens"] or 0)
|
|
unknown = int(row["unknown_requests"] or 0)
|
|
complete = unknown == 0
|
|
out.append({"pos": index + 1, "model": row["model"], "value": requests,
|
|
"requests": requests,
|
|
"tokens": known if complete else None,
|
|
"known_tokens": known,
|
|
"unknown_token_requests": unknown,
|
|
"tokens_complete": complete,
|
|
"value_kind": "exact" if complete else "lower_bound"})
|
|
return out
|
|
|
|
|
|
# ---------------------------------------------------------------------------
|
|
# public entrypoint
|
|
|
|
def top(bot_db, gw_db, kind="referrals", period=None, now=None, limit=None):
|
|
"""Leaderboard payload; raises ValueError on bad input, sqlite3.Error on DB faults."""
|
|
kind = normalize_kind(kind)
|
|
period = normalize_period(period, kind)
|
|
limit = normalize_limit(limit)
|
|
now = int(time.time()) if now is None else now
|
|
if isinstance(now, bool) or not isinstance(now, int):
|
|
raise ValueError("now must be an integer unix timestamp")
|
|
start, end = window(period, now)
|
|
deadline = time.monotonic() + max(0.5, QUERY_DEADLINE)
|
|
|
|
cache_key = (kind, period, start, end // 60, limit, str(bot_db), str(gw_db),
|
|
_stamp(bot_db), _stamp(gw_db))
|
|
|
|
def build():
|
|
if kind == "referrals":
|
|
rows, ranked = _referral_rows(bot_db, start, end, limit, deadline)
|
|
elif kind == "models":
|
|
rows = _model_rows(gw_db, start, end, limit, deadline)
|
|
ranked = len(rows)
|
|
else:
|
|
rows, ranked = _user_usage_rows(bot_db, gw_db, start, end, limit, kind, deadline)
|
|
return {"top": rows, "kind": kind, "period": period, "source": _SOURCES[kind],
|
|
"from_ts": start, "to_ts": end, "as_of": end, "limit": limit,
|
|
"ranked": ranked, "truncated": ranked > len(rows),
|
|
"generated_at": int(time.time()), "timezone": "Europe/Moscow",
|
|
"value": _VALUES[kind]}
|
|
|
|
return _cached(cache_key, build) |