IISHKO: Telegram bot, Mini App and gateway
Initial public release. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
@@ -0,0 +1,114 @@
|
||||
#!/usr/bin/env python3
|
||||
import os
|
||||
import re
|
||||
import sqlite3
|
||||
import sys
|
||||
import time
|
||||
|
||||
GW_DB = os.environ.get("IISHKO_GW_DB", "/opt/grok-gateway/new-api/one-api.db")
|
||||
BOT_SRC = "/opt/grok-bot/iishko_bot.py" # [BOTFIX 2310] живой активный сервис
|
||||
BOT_SRC_FALLBACK = "/opt/grok-bot/grok_bot.py" # старое имя (legacy)
|
||||
TIER_GROUPS = ("t1", "t2", "t3", "t4")
|
||||
|
||||
LIVE_SQL = ("SELECT COUNT(*) FROM abilities a JOIN channels c ON c.id=a.channel_id "
|
||||
"WHERE a.model=? AND a.enabled=1 AND c.status=1 "
|
||||
"AND instr(',' || replace(c.models,' ','') || ',', ',' || a.model || ',')>0") # [FIX-2410] containment как в repair
|
||||
|
||||
|
||||
def _read_src(path):
|
||||
try:
|
||||
with open(path, encoding="utf-8") as f:
|
||||
return f.read()
|
||||
except OSError as e:
|
||||
print(time.strftime("%F %T"), "cannot read", path, str(e)[:120], flush=True)
|
||||
return ""
|
||||
|
||||
|
||||
def _parse_tiers(src):
|
||||
m = re.search(r"^TIER_MODELS\s*=\s*\{(.*?)^\s*\}", src, re.S | re.M)
|
||||
if not m:
|
||||
return {}
|
||||
body = re.sub(r"#[^\n]*", "", m.group(1))
|
||||
tiers = {}
|
||||
for tm in re.finditer(r"(\d+)\s*:\s*\[(.*?)\]", body, re.S):
|
||||
names = re.findall(r"""["']([A-Za-z0-9._/\-]+)["']""", tm.group(2))
|
||||
if names:
|
||||
tiers[int(tm.group(1))] = sorted(set(names))
|
||||
return tiers
|
||||
|
||||
|
||||
def catalog_tiers(path=None):
|
||||
"""Список тиров из исходника бота (без импорта бота).
|
||||
path=None: сначала живой iishko_bot.py (BOT_SRC), затем legacy grok_bot.py."""
|
||||
paths = (path,) if path else (BOT_SRC, BOT_SRC_FALLBACK)
|
||||
for p in paths:
|
||||
tiers = _parse_tiers(_read_src(p))
|
||||
if tiers:
|
||||
return tiers
|
||||
return {}
|
||||
|
||||
|
||||
def catalog_models(tiers):
|
||||
"""Union моделей каталога (для отчёта dark)."""
|
||||
return sorted({m for ms in tiers.values() for m in ms})
|
||||
|
||||
|
||||
def repair_abilities(con, tiers):
|
||||
if not tiers:
|
||||
return 0
|
||||
models = catalog_models(tiers)
|
||||
order = [n for n in sorted(tiers) if 1 <= n <= 4]
|
||||
if not models or not order:
|
||||
return 0
|
||||
|
||||
def ph(n):
|
||||
return ",".join(["?"] * n)
|
||||
|
||||
params = list(models) + list(TIER_GROUPS)
|
||||
gate_parts = ['abilities."group" NOT IN (' + ph(len(TIER_GROUPS)) + ')']
|
||||
for n in order:
|
||||
cum = [m for i in order if i <= n for m in tiers[i]]
|
||||
if not cum:
|
||||
continue
|
||||
gate_parts.append('(abilities."group"=? AND abilities.model IN ('
|
||||
+ ph(len(cum)) + '))')
|
||||
params.append("t" + str(n))
|
||||
params.extend(cum)
|
||||
# [FIX-2410] Нормализация containment: c.models может быть «m1, m2» с пробелами —
|
||||
sql = ("UPDATE abilities SET enabled=1 WHERE enabled=0 AND model IN ("
|
||||
+ ph(len(models)) + ") "
|
||||
+ "AND EXISTS (SELECT 1 FROM channels c WHERE c.id=abilities.channel_id "
|
||||
"AND c.status=1 AND instr(',' || replace(c.models,' ','') || ',', "
|
||||
"',' || abilities.model || ',')>0) "
|
||||
+ "AND (" + " OR ".join(gate_parts) + ")")
|
||||
return con.execute(sql, params).rowcount
|
||||
|
||||
|
||||
def main():
|
||||
tiers = catalog_tiers()
|
||||
if not tiers:
|
||||
print(time.strftime("%F %T"), "no catalog tiers parsed - refusing to touch abilities",
|
||||
flush=True)
|
||||
return 1
|
||||
models = catalog_models(tiers)
|
||||
con = sqlite3.connect(GW_DB, timeout=60)
|
||||
try:
|
||||
con.execute("PRAGMA busy_timeout=60000")
|
||||
fixed = repair_abilities(con, tiers)
|
||||
con.commit()
|
||||
dark = [m for m in models if not con.execute(LIVE_SQL, (m,)).fetchone()[0]]
|
||||
con.close()
|
||||
except Exception as e:
|
||||
print(time.strftime("%F %T"), "ERROR", str(e)[:200], flush=True)
|
||||
try:
|
||||
con.rollback()
|
||||
except Exception:
|
||||
pass
|
||||
return 2
|
||||
print(time.strftime("%F %T"), "catalog=%d re-enabled=%d dark=%s"
|
||||
% (len(models), fixed, ",".join(dark) if dark else "none"), flush=True)
|
||||
return 0
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
sys.exit(main())
|
||||
@@ -0,0 +1,336 @@
|
||||
from contextlib import closing
|
||||
import hashlib
|
||||
import json
|
||||
from pathlib import Path
|
||||
import sqlite3
|
||||
import time
|
||||
|
||||
from account_limits import account_uid, _name_scope
|
||||
|
||||
|
||||
PAUSE_PATH = "/opt/grok-bot/econ_cap_state.json"
|
||||
# Account-level locks that are not owned by a ban; unban must never clear them.
|
||||
INDEPENDENT_FLAGS = ("api_blocked", "key_locked", "chat_key_locked")
|
||||
|
||||
|
||||
class AdminError(Exception):
|
||||
pass
|
||||
|
||||
|
||||
def _uid(value):
|
||||
if type(value) is not int or not 0 < value <= 9223372036854775807:
|
||||
raise AdminError("Некорректный Telegram ID")
|
||||
return value
|
||||
|
||||
|
||||
def _connect(bot_db, gateway_db):
|
||||
con = sqlite3.connect(Path(gateway_db).resolve().as_uri() + "?mode=rw",
|
||||
uri=True, timeout=30, isolation_level=None)
|
||||
con.row_factory = sqlite3.Row
|
||||
try:
|
||||
con.execute("PRAGMA busy_timeout=30000")
|
||||
con.execute("ATTACH DATABASE ? AS bot", (Path(bot_db).resolve().as_uri() + "?mode=rw",))
|
||||
return con
|
||||
except BaseException:
|
||||
con.close()
|
||||
raise
|
||||
|
||||
|
||||
def _authorize(con, actor_uid, admin_ids):
|
||||
_uid(actor_uid)
|
||||
if actor_uid in admin_ids:
|
||||
return
|
||||
columns = {r[1] for r in con.execute("PRAGMA bot.table_info(users)")}
|
||||
row = con.execute("SELECT admin FROM bot.users WHERE tg_id=?", (actor_uid,)).fetchone() if "admin" in columns else None
|
||||
if not row or row[0] != 1:
|
||||
raise AdminError("Нет прав администратора")
|
||||
|
||||
|
||||
def _schema(con):
|
||||
con.execute("CREATE TABLE IF NOT EXISTS bot.wa_admin_bans ("
|
||||
"uid INTEGER PRIMARY KEY,actor INTEGER NOT NULL,started INTEGER NOT NULL,"
|
||||
"active INTEGER NOT NULL,site_status INTEGER)")
|
||||
columns = {r[1] for r in con.execute("PRAGMA bot.table_info(wa_admin_bans)")}
|
||||
if "site_status" not in columns:
|
||||
con.execute("ALTER TABLE bot.wa_admin_bans ADD COLUMN site_status INTEGER")
|
||||
con.execute("CREATE TABLE IF NOT EXISTS bot.wa_admin_ban_tokens ("
|
||||
"uid INTEGER NOT NULL,tid INTEGER NOT NULL,name TEXT NOT NULL,"
|
||||
"credential_hash TEXT NOT NULL,previous_status INTEGER NOT NULL,"
|
||||
"PRIMARY KEY(uid,tid))")
|
||||
con.execute("CREATE TABLE IF NOT EXISTS bot.ban_wl("
|
||||
"uid INTEGER PRIMARY KEY,ts INTEGER NOT NULL,note TEXT NOT NULL DEFAULT '')")
|
||||
|
||||
|
||||
def _fingerprint(value):
|
||||
return hashlib.sha256(str(value).encode("utf-8")).hexdigest()
|
||||
|
||||
|
||||
def _has_table(con, schema, name):
|
||||
return bool(con.execute("SELECT 1 FROM " + schema + ".sqlite_master WHERE type='table' AND name=?", (name,)).fetchone())
|
||||
|
||||
|
||||
def _pause_snapshot(path):
|
||||
try:
|
||||
data = json.loads(Path(path).read_text(encoding="utf-8"))
|
||||
if not isinstance(data, dict) or data.get("v", 2) != 2 or not isinstance(data.get("paused", {}), dict):
|
||||
return None
|
||||
return data.get("paused", {})
|
||||
except FileNotFoundError:
|
||||
return {}
|
||||
except (OSError, ValueError, TypeError):
|
||||
return None
|
||||
|
||||
|
||||
def _hold_reason(con, row, user, pause_state, now):
|
||||
if any(user.get(flag) for flag in ("api_blocked", "key_locked", "chat_key_locked")):
|
||||
return "independent_account_lock"
|
||||
if row["status"] != 2:
|
||||
return "status_changed"
|
||||
if row.get("expired_time", -1) not in (None, -1, 0) and int(row["expired_time"]) <= now:
|
||||
return "expired"
|
||||
for schema in ("main", "bot"):
|
||||
if _has_table(con, schema, "wa_key_locks"):
|
||||
if con.execute("SELECT 1 FROM " + schema + ".wa_key_locks WHERE tid=?", (row["id"],)).fetchone():
|
||||
return "self_or_manual_lock"
|
||||
if _has_table(con, schema, "wa_daily_cap_pauses"):
|
||||
if con.execute("SELECT 1 FROM " + schema + ".wa_daily_cap_pauses WHERE tid=? AND name=?", (row["id"], row["name"])).fetchone():
|
||||
return "limiter_pause"
|
||||
if pause_state is None:
|
||||
return "pause_state_unavailable"
|
||||
if row["name"] in pause_state:
|
||||
receipt = pause_state[row["name"]]
|
||||
if not isinstance(receipt, dict) or receipt.get("flag_only") is not True:
|
||||
return "limiter_pause"
|
||||
return ""
|
||||
|
||||
|
||||
def _site_account(con, uid):
|
||||
"""Return (status, readable) for the site account named tg<uid>.
|
||||
|
||||
readable is False when the gateway users table is absent or shaped
|
||||
differently, so callers report an honest hold reason instead of treating
|
||||
unknown state as an enabled account.
|
||||
"""
|
||||
if not _has_table(con, "main", "users"):
|
||||
return None, False
|
||||
columns = {r[1] for r in con.execute("PRAGMA main.table_info(users)")}
|
||||
if not {"username", "status"} <= columns:
|
||||
return None, False
|
||||
row = con.execute("SELECT status FROM main.users WHERE username=?", ("tg%d" % uid,)).fetchone()
|
||||
if row is not None and type(row[0]) is not int:
|
||||
return None, False
|
||||
return (None if row is None else row[0]), True
|
||||
|
||||
|
||||
def _site_ready(user):
|
||||
"""Site access is restored only when no independent account lock remains."""
|
||||
return not any(user.get(flag) for flag in INDEPENDENT_FLAGS + ("cap_paused",))
|
||||
|
||||
|
||||
def _site_disable(con, uid, fresh):
|
||||
"""Disable status 1 -> 2 for a new ban and return (preimage, hold reason).
|
||||
|
||||
The preimage is the raw pre-ban status. Only status 1 can be attributed to
|
||||
the ban, so a later unban restores just that case. A repeated ban never
|
||||
overwrites the original preimage; it only re-asserts a disable this ban
|
||||
already owns.
|
||||
"""
|
||||
status, readable = _site_account(con, uid)
|
||||
if not readable:
|
||||
return None, "site_unavailable"
|
||||
if status is None:
|
||||
return None, "site_missing"
|
||||
if not fresh:
|
||||
record = con.execute("SELECT site_status FROM bot.wa_admin_bans WHERE uid=?", (uid,)).fetchone()
|
||||
if record and record[0] == 1 and status == 1:
|
||||
con.execute("UPDATE main.users SET status=2 WHERE username=? AND status=1", ("tg%d" % uid,))
|
||||
return None, ""
|
||||
if status != 1:
|
||||
return status, "site_already_disabled"
|
||||
changed = con.execute("UPDATE main.users SET status=2 WHERE username=? AND status=1",
|
||||
("tg%d" % uid,)).rowcount
|
||||
if changed != 1:
|
||||
return None, "site_status_changed"
|
||||
return status, ""
|
||||
|
||||
|
||||
def _site_restore(con, uid, user, record, attributable):
|
||||
"""Restore only a site status this ban disabled; report why otherwise."""
|
||||
status, readable = _site_account(con, uid)
|
||||
if not readable:
|
||||
return False, "site_unavailable"
|
||||
if status is None:
|
||||
return False, "site_missing"
|
||||
if status == 1:
|
||||
return False, ""
|
||||
if not attributable:
|
||||
return False, "site_not_recorded"
|
||||
receipt = record["site_status"]
|
||||
if receipt is None:
|
||||
return False, "site_not_recorded"
|
||||
if receipt != 1:
|
||||
return False, "site_already_disabled"
|
||||
if status != 2:
|
||||
return False, "site_status_changed"
|
||||
if not _site_ready(user):
|
||||
return False, "independent_account_lock"
|
||||
changed = con.execute("UPDATE main.users SET status=1 WHERE username=? AND status=2",
|
||||
("tg%d" % uid,)).rowcount
|
||||
if changed != 1:
|
||||
return False, "site_status_changed"
|
||||
return True, ""
|
||||
|
||||
|
||||
def _clear_autoban_receipt(con, uid):
|
||||
for schema in ("main", "bot"):
|
||||
if not _has_table(con, schema, "entry_autoban_applied"):
|
||||
continue
|
||||
columns = {r[1] for r in con.execute("PRAGMA " + schema + ".table_info(entry_autoban_applied)")}
|
||||
if "uid" in columns:
|
||||
con.execute("DELETE FROM " + schema + ".entry_autoban_applied WHERE uid=?", (uid,))
|
||||
|
||||
|
||||
def _change(bot_db, gateway_db, target_uid, banned, *, actor_uid, admin_ids, pause_path, now):
|
||||
_uid(target_uid)
|
||||
if type(banned) is not bool:
|
||||
raise AdminError("Некорректное действие")
|
||||
now = int(time.time() if now is None else now)
|
||||
pause_state = None if banned else _pause_snapshot(pause_path)
|
||||
with closing(_connect(bot_db, gateway_db)) as con:
|
||||
try:
|
||||
con.execute("BEGIN IMMEDIATE")
|
||||
_authorize(con, actor_uid, admin_ids)
|
||||
required = {"tg_id", "banned", "api_blocked", "key_locked", "chat_key_locked", "cap_paused"}
|
||||
if not required <= {r[1] for r in con.execute("PRAGMA bot.table_info(users)")}:
|
||||
raise AdminError("Не удалось проверить независимые блокировки; изменений нет")
|
||||
found = con.execute("SELECT * FROM bot.users WHERE tg_id=?", (target_uid,)).fetchone()
|
||||
if not found:
|
||||
raise AdminError("Пользователь не найден")
|
||||
user = dict(found)
|
||||
_schema(con)
|
||||
record = con.execute("SELECT * FROM bot.wa_admin_bans WHERE uid=?", (target_uid,)).fetchone()
|
||||
scope, args = _name_scope("name", target_uid)
|
||||
tokens = [dict(r) for r in con.execute("SELECT * FROM tokens WHERE deleted_at IS NULL AND " + scope, args)
|
||||
if account_uid(r["name"]) == target_uid]
|
||||
report = {"uid": target_uid, "banned": banned, "restored": 0, "disabled": 0, "held": [],
|
||||
"site_restored": False, "site_held": ""}
|
||||
if banned:
|
||||
# Repeated bans must not replace the original pre-ban status image.
|
||||
fresh = not user["banned"] and not (record and record["active"])
|
||||
site_status, report["site_held"] = _site_disable(con, target_uid, fresh)
|
||||
if fresh:
|
||||
con.execute("DELETE FROM bot.wa_admin_ban_tokens WHERE uid=?", (target_uid,))
|
||||
con.execute("INSERT OR REPLACE INTO bot.wa_admin_bans VALUES(?,?,?,?,?)",
|
||||
(target_uid, actor_uid, now, 1, site_status))
|
||||
con.executemany("INSERT INTO bot.wa_admin_ban_tokens VALUES(?,?,?,?,?)", [
|
||||
(target_uid, row["id"], row["name"], _fingerprint(row["key"]), row["status"]) for row in tokens])
|
||||
con.execute("UPDATE bot.users SET banned=1 WHERE tg_id=?", (target_uid,))
|
||||
if _has_table(con, "bot", "ban_wl"):
|
||||
con.execute("DELETE FROM bot.ban_wl WHERE uid=?", (target_uid,))
|
||||
for row in tokens:
|
||||
if row["status"] == 1:
|
||||
con.execute("UPDATE tokens SET status=2 WHERE id=? AND name=? AND status=1", (row["id"], row["name"]))
|
||||
report["disabled"] += 1
|
||||
else:
|
||||
attributable = bool(user["banned"] and record and record["active"])
|
||||
receipts = {r["tid"]: dict(r) for r in con.execute("SELECT * FROM bot.wa_admin_ban_tokens WHERE uid=?", (target_uid,))}
|
||||
for row in tokens:
|
||||
if row["status"] != 2:
|
||||
continue
|
||||
previous = receipts.get(row["id"])
|
||||
reason = "legacy_or_manual_status"
|
||||
if attributable and previous:
|
||||
if previous["name"] != row["name"] or previous["credential_hash"] != _fingerprint(row["key"]):
|
||||
reason = "credential_changed"
|
||||
elif previous["previous_status"] != 1:
|
||||
reason = "preexisting_disabled"
|
||||
else:
|
||||
reason = _hold_reason(con, row, user, pause_state, now)
|
||||
if reason:
|
||||
report["held"].append({"name": row["name"], "reason": reason})
|
||||
else:
|
||||
changed = con.execute("UPDATE tokens SET status=1 WHERE id=? AND name=? AND status=2",
|
||||
(row["id"], row["name"])).rowcount
|
||||
if changed != 1:
|
||||
raise AdminError("Статус ключа изменился; разбан отменён")
|
||||
report["restored"] += changed
|
||||
report["site_restored"], report["site_held"] = _site_restore(
|
||||
con, target_uid, user, record, attributable)
|
||||
con.execute("UPDATE bot.users SET banned=0 WHERE tg_id=?", (target_uid,))
|
||||
con.execute("UPDATE bot.wa_admin_bans SET active=0 WHERE uid=?", (target_uid,))
|
||||
_clear_autoban_receipt(con, target_uid)
|
||||
# Preserve the live anti-reban policy in the BOT schema.
|
||||
if user["banned"]:
|
||||
con.execute("INSERT OR REPLACE INTO bot.ban_wl(uid,ts,note) VALUES(?,?,?)",
|
||||
(target_uid, now, "admin_unban"))
|
||||
con.commit()
|
||||
return report
|
||||
except BaseException:
|
||||
if con.in_transaction:
|
||||
con.rollback()
|
||||
raise
|
||||
|
||||
|
||||
def set_banned(bot_db, gateway_db, target_uid, banned, *, actor_uid, admin_ids,
|
||||
pause_path=PAUSE_PATH, now=None):
|
||||
return _change(bot_db, gateway_db, target_uid, banned, actor_uid=actor_uid,
|
||||
admin_ids=admin_ids, pause_path=pause_path, now=now)
|
||||
|
||||
|
||||
def unban_account(bot_db, gateway_db, target_uid, *, actor_uid, admin_ids,
|
||||
pause_path=PAUSE_PATH, now=None):
|
||||
return _change(bot_db, gateway_db, target_uid, False, actor_uid=actor_uid,
|
||||
admin_ids=admin_ids, pause_path=pause_path, now=now)
|
||||
|
||||
|
||||
def list_banned(bot_db, *, actor_uid, admin_ids, offset=0, limit=8):
|
||||
_uid(actor_uid)
|
||||
if type(offset) is not int or not 0 <= offset <= 1_000_000:
|
||||
raise AdminError("Некорректная страница")
|
||||
with closing(sqlite3.connect(Path(bot_db).resolve().as_uri() + "?mode=ro", uri=True, timeout=30)) as con:
|
||||
con.row_factory = sqlite3.Row
|
||||
if actor_uid not in admin_ids:
|
||||
cols = {r[1] for r in con.execute("PRAGMA table_info(users)")}
|
||||
admin = con.execute("SELECT admin FROM users WHERE tg_id=?", (actor_uid,)).fetchone() if "admin" in cols else None
|
||||
if not admin or admin[0] != 1:
|
||||
raise AdminError("Нет прав администратора")
|
||||
total = con.execute("SELECT COUNT(*) FROM users WHERE banned=1").fetchone()[0]
|
||||
rows = con.execute("SELECT tg_id,username FROM users WHERE banned=1 ORDER BY tg_id LIMIT ? OFFSET ?", (min(8, max(1, limit)), offset)).fetchall()
|
||||
return {"total": total, "users": [dict(r) for r in rows], "offset": offset}
|
||||
|
||||
|
||||
def summary(result):
|
||||
if result["banned"]:
|
||||
return "Бан установлен; балансы сохранены. Отключено ключей: %d" % result["disabled"]
|
||||
held = len(result["held"])
|
||||
text = "Бан снят; балансы без изменений. Включено ключей: %d" % result["restored"]
|
||||
if held:
|
||||
labels = {
|
||||
"legacy_or_manual_status": "нет подтверждения, что ключ отключён этим баном",
|
||||
"credential_changed": "ключ был перевыпущен",
|
||||
"preexisting_disabled": "ключ был отключён до бана",
|
||||
"independent_account_lock": "независимая блокировка аккаунта",
|
||||
"status_changed": "статус ключа изменён",
|
||||
"expired": "срок ключа истёк",
|
||||
"self_or_manual_lock": "самоблокировка или ручной лок",
|
||||
"limiter_pause": "активная пауза лимитера",
|
||||
"pause_state_unavailable": "состояние пауз недоступно",
|
||||
}
|
||||
text += ". Остались отключены: %d" % held
|
||||
for item in result["held"][:5]:
|
||||
text += "\n%s: %s" % (item["name"], labels.get(item["reason"], "неизвестная блокировка"))
|
||||
if held > 5:
|
||||
text += "\nИ ещё %d" % (held - 5)
|
||||
if result.get("site_restored"):
|
||||
text += "\nСайт: доступ восстановлен"
|
||||
elif result.get("site_held"):
|
||||
site_labels = {
|
||||
"site_not_recorded": "нет подтверждения, что доступ отключён этим баном",
|
||||
"site_already_disabled": "доступ был отключён до бана",
|
||||
"site_status_changed": "статус сайта изменён",
|
||||
"site_missing": "аккаунт сайта не найден",
|
||||
"site_unavailable": "состояние сайта недоступно",
|
||||
"independent_account_lock": "независимая блокировка аккаунта",
|
||||
}
|
||||
text += "\nСайт остался отключён: %s" % site_labels.get(result["site_held"], "неизвестное состояние")
|
||||
return text
|
||||
@@ -0,0 +1,37 @@
|
||||
from account_limits import account_uid, account_token_names
|
||||
|
||||
|
||||
def owned_rows(con, uid, user=None):
|
||||
user = dict(user or {})
|
||||
output, ambiguous, seen = [], [], set()
|
||||
for name in account_token_names(con, uid):
|
||||
rows = con.execute('SELECT * FROM tokens WHERE name=? AND deleted_at IS NULL ORDER BY id', (name,)).fetchall()
|
||||
if len(rows) != 1:
|
||||
canonical = [row for row in rows if name == 'tg%d' % uid and user.get('api_key')
|
||||
and row['key'] == user['api_key'].removeprefix('sk-')]
|
||||
if len(canonical) != 1:
|
||||
ambiguous.append(name)
|
||||
continue
|
||||
rows = canonical
|
||||
row = rows[0]
|
||||
if row['id'] in seen:
|
||||
continue
|
||||
duplicates = con.execute('SELECT name FROM tokens WHERE key=? AND deleted_at IS NULL', (row['key'],)).fetchall()
|
||||
if not row['key'] or len(duplicates) != 1 or any(account_uid(item['name']) != uid for item in duplicates):
|
||||
ambiguous.append(name)
|
||||
continue
|
||||
seen.add(row['id'])
|
||||
output.append(row)
|
||||
return output, ambiguous
|
||||
|
||||
|
||||
def snapshot(con, uid, user=None, quota_per_usd=500000):
|
||||
rows, ambiguous = owned_rows(con, uid, user)
|
||||
units = {'main': 0, 'extras': 0, 'promo': 0}
|
||||
for row in rows:
|
||||
kind = 'promo' if row['name'].startswith('pm') else ('extras' if '-k' in row['name'] else 'main')
|
||||
units[kind] += max(0, int(row['remain_quota'] or 0))
|
||||
return {**{kind+'_balance_usd': value / quota_per_usd for kind, value in units.items()},
|
||||
'total_balance_usd': sum(units.values()) / quota_per_usd,
|
||||
'balance_ambiguous_names': ambiguous,
|
||||
'balance_unlimited': any(bool(row['unlimited_quota']) for row in rows)}
|
||||
@@ -0,0 +1,139 @@
|
||||
from __future__ import annotations
|
||||
|
||||
import re
|
||||
import sqlite3
|
||||
from pathlib import Path
|
||||
|
||||
|
||||
MAIN_CONFIRMED = "confirmed"
|
||||
MAIN_PRESENT = "present"
|
||||
NO_MAIN = "none" # no canonical and no confirmed primary binding
|
||||
UNAVAILABLE = "unavailable" # DB/table/query failed; state is unknown
|
||||
|
||||
MAX_UID = (1 << 63) - 1
|
||||
_ACCOUNT_NAME = re.compile(r"(?:tg|pm|sol)([1-9][0-9]*)(?:-k[1-9][0-9]*)?\Z")
|
||||
|
||||
|
||||
def _account_uid(name: str) -> int | None:
|
||||
"""Exact account identity, mirrored from bot/account_limits.py."""
|
||||
if not isinstance(name, str):
|
||||
return None
|
||||
match = _ACCOUNT_NAME.fullmatch(name)
|
||||
if match is None:
|
||||
return None
|
||||
try:
|
||||
uid = int(match[1])
|
||||
except ValueError:
|
||||
return None
|
||||
return uid if uid <= MAX_UID else None
|
||||
|
||||
|
||||
def _main_name(name: str, uid: int) -> str | None:
|
||||
name = str(name or "")
|
||||
if not name or name.startswith(("pm", "sol")):
|
||||
return None
|
||||
if name.startswith("tg"):
|
||||
if _account_uid(name) != uid:
|
||||
return None
|
||||
return "tg%d" % uid
|
||||
return name
|
||||
|
||||
|
||||
def _normalise_key(value) -> str:
|
||||
if isinstance(value, bytes):
|
||||
value = value.decode("utf-8", "ignore")
|
||||
text = str(value or "").strip()
|
||||
return text[3:] if text.startswith("sk-") else text
|
||||
|
||||
|
||||
def _keys_match(stored, live) -> bool:
|
||||
stored = _normalise_key(stored)
|
||||
live = _normalise_key(live)
|
||||
return bool(stored and live and stored == live)
|
||||
|
||||
|
||||
def _readonly(path) -> sqlite3.Connection | None:
|
||||
"""Open an existing SQLite file read-only; never create a missing file."""
|
||||
try:
|
||||
resolved = Path(path).resolve(strict=True)
|
||||
except (OSError, RuntimeError):
|
||||
return None
|
||||
if not resolved.is_file():
|
||||
return None
|
||||
con = sqlite3.connect(resolved.as_uri() + "?mode=ro", uri=True, timeout=0.35)
|
||||
con.row_factory = sqlite3.Row
|
||||
con.execute("PRAGMA query_only=ON")
|
||||
con.execute("PRAGMA busy_timeout=350")
|
||||
return con
|
||||
|
||||
|
||||
def _chunks(values, size: int = 400):
|
||||
values = list(values)
|
||||
for start in range(0, len(values), size):
|
||||
yield values[start:start + size]
|
||||
|
||||
|
||||
def main_key_states(bot_db, gw_db, uids) -> dict[int, str]:
|
||||
try:
|
||||
wanted = sorted({int(uid) for uid in uids if 0 < int(uid) <= MAX_UID})
|
||||
except (TypeError, ValueError):
|
||||
return {}
|
||||
if not wanted:
|
||||
return {}
|
||||
|
||||
result = {uid: UNAVAILABLE for uid in wanted}
|
||||
bot_con = None
|
||||
gw_con = None
|
||||
try:
|
||||
bot_con = _readonly(bot_db)
|
||||
gw_con = _readonly(gw_db)
|
||||
if bot_con is None or gw_con is None:
|
||||
return result
|
||||
|
||||
bindings: dict[int, tuple] = {}
|
||||
for chunk in _chunks(wanted):
|
||||
marks = ",".join("?" for _ in chunk)
|
||||
rows = bot_con.execute(
|
||||
"SELECT tg_id,token_name,api_key FROM users WHERE tg_id IN (%s)" % marks,
|
||||
chunk,
|
||||
)
|
||||
for row in rows:
|
||||
bindings[int(row["tg_id"])] = (row["token_name"], row["api_key"])
|
||||
|
||||
names = set()
|
||||
for uid in wanted:
|
||||
names.add("tg%d" % uid)
|
||||
binding = bindings.get(uid)
|
||||
bound_name = _main_name(binding[0], uid) if binding else None
|
||||
if bound_name:
|
||||
names.add(bound_name)
|
||||
|
||||
live: dict[str, list] = {}
|
||||
for chunk in _chunks(sorted(names)):
|
||||
marks = ",".join("?" for _ in chunk)
|
||||
rows = gw_con.execute(
|
||||
"SELECT name,key FROM tokens WHERE deleted_at IS NULL "
|
||||
"AND status IN (1,2) AND name IN (%s)" % marks,
|
||||
chunk,
|
||||
)
|
||||
for row in rows:
|
||||
live.setdefault(str(row["name"]), []).append(row["key"])
|
||||
|
||||
for uid in wanted:
|
||||
canonical = "tg%d" % uid
|
||||
binding = bindings.get(uid)
|
||||
bound_name = _main_name(binding[0], uid) if binding else None
|
||||
if bound_name:
|
||||
rows = live.get(bound_name, [])
|
||||
if len(rows) == 1 and _keys_match(binding[1], rows[0]):
|
||||
result[uid] = MAIN_CONFIRMED
|
||||
continue
|
||||
result[uid] = MAIN_PRESENT if canonical in live else NO_MAIN
|
||||
return result
|
||||
except (sqlite3.Error, OSError, ValueError):
|
||||
return {uid: UNAVAILABLE for uid in wanted}
|
||||
finally:
|
||||
if bot_con is not None:
|
||||
bot_con.close()
|
||||
if gw_con is not None:
|
||||
gw_con.close()
|
||||
@@ -0,0 +1,76 @@
|
||||
"""Exact bot-account identity and read-only account-shared gateway usage."""
|
||||
import os
|
||||
from contextlib import closing
|
||||
from pathlib import Path
|
||||
import re
|
||||
import sqlite3
|
||||
|
||||
|
||||
DAILY_USD_CAP = {0: 100, 1: 100, 2: 200, 3: 500, 4: 1000}
|
||||
QUOTA_PER_USD = 500_000
|
||||
_owner_uid_raw = os.environ.get("IISHKO_OWNER_UID", "0").strip()
|
||||
# Operator identity is configuration. 0 = nobody holds owner privileges.
|
||||
OWNER_UID = int(_owner_uid_raw) if _owner_uid_raw.isdigit() else 0
|
||||
_ACCOUNT_NAME = re.compile(r"(?:tg|pm|sol)([1-9][0-9]*)(?:-k[1-9][0-9]*)?\Z")
|
||||
|
||||
|
||||
def account_uid(name: str) -> int | None:
|
||||
"""Return the canonical Telegram UID, never a prefix/substring match."""
|
||||
if not isinstance(name, str):
|
||||
return None
|
||||
match = _ACCOUNT_NAME.fullmatch(name)
|
||||
if match is None:
|
||||
return None
|
||||
try:
|
||||
uid = int(match[1])
|
||||
except ValueError:
|
||||
return None
|
||||
return uid if uid <= 9223372036854775807 else None
|
||||
|
||||
|
||||
def _name_scope(column, uid):
|
||||
if type(uid) is not int or not 0 < uid <= 9223372036854775807:
|
||||
raise ValueError("invalid account uid")
|
||||
# GLOB is only an indexed candidate selection. Every returned name must also
|
||||
# pass account_uid: '-k1foreign', Unicode digits and '-k01' are not credentials.
|
||||
bases = [prefix + str(uid) for prefix in ("tg", "pm", "sol")]
|
||||
terms, args = [], []
|
||||
for name in bases:
|
||||
terms.extend((column + "=?", column + " GLOB ?"))
|
||||
args.extend((name, name + "-k[0-9]*"))
|
||||
return "(" + " OR ".join(terms) + ")", args
|
||||
|
||||
|
||||
def account_token_names(con: sqlite3.Connection, uid: int) -> list[str]:
|
||||
"""Exact live names for this account; do not hide query/schema failures."""
|
||||
scope, args = _name_scope("name", uid)
|
||||
rows = con.execute("SELECT DISTINCT name FROM tokens WHERE deleted_at IS NULL AND " + scope,
|
||||
args).fetchall()
|
||||
return sorted(row[0] for row in rows if account_uid(row[0]) == uid)
|
||||
|
||||
|
||||
def daily_spent_units(gw_db, uid: int, day_start: int, day_end: int | None = None) -> int:
|
||||
scope, args = _name_scope("token_name", uid)
|
||||
if type(day_start) is not int or (day_end is not None and type(day_end) is not int):
|
||||
raise ValueError("invalid usage interval")
|
||||
if day_end is not None and day_end < day_start:
|
||||
raise ValueError("invalid usage interval")
|
||||
time_scope = "created_at>=?"
|
||||
times = [day_start]
|
||||
if day_end is not None:
|
||||
time_scope += " AND created_at<?"
|
||||
times.append(day_end)
|
||||
uri = Path(gw_db).resolve().as_uri() + "?mode=ro"
|
||||
with closing(sqlite3.connect(uri, uri=True, timeout=8)) as con:
|
||||
con.execute("PRAGMA query_only=ON")
|
||||
# Prefer account-name lookups over scanning every account's daily logs.
|
||||
# Keep the original plan on databases without the standard full index.
|
||||
full_index = any(row[1] == "idx_logs_token_name" and not row[4]
|
||||
for row in con.execute("PRAGMA index_list(logs)"))
|
||||
columns = con.execute("PRAGMA index_info(idx_logs_token_name)").fetchall()
|
||||
source = ("logs INDEXED BY idx_logs_token_name"
|
||||
if full_index and [row[2] for row in columns] == ["token_name"] else "logs")
|
||||
rows = con.execute(
|
||||
"SELECT token_name,COALESCE(SUM(quota),0) FROM " + source + " WHERE type=2 AND "
|
||||
+ time_scope + " AND " + scope + " GROUP BY token_name", times + args).fetchall()
|
||||
return sum(int(units) for name, units in rows if account_uid(name) == uid)
|
||||
@@ -0,0 +1,157 @@
|
||||
# -*- coding: utf-8 -*-
|
||||
import asyncio
|
||||
import json
|
||||
import os
|
||||
import time
|
||||
|
||||
import aiohttp
|
||||
|
||||
KEYS_FILE = os.environ.get("AFKEYS", "/opt/grok-bot/apiframe_keys.jsonl")
|
||||
API = "https://api.apiframe.ai"
|
||||
UA = ("Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 "
|
||||
"(KHTML, like Gecko) Chrome/131.0.0.0 Safari/537.36")
|
||||
|
||||
_dead = {}
|
||||
_sem = asyncio.Semaphore(2)
|
||||
|
||||
|
||||
def _load_keys():
|
||||
keys = []
|
||||
try:
|
||||
with open(KEYS_FILE, encoding="utf-8") as f:
|
||||
for line in f:
|
||||
line = line.strip()
|
||||
if not line:
|
||||
continue
|
||||
try:
|
||||
d = json.loads(line)
|
||||
k = d.get("key") or d.get("api_key")
|
||||
if isinstance(d, str):
|
||||
k = d
|
||||
if k and k.startswith("afk_"):
|
||||
keys.append(k)
|
||||
except Exception:
|
||||
if line.startswith("afk_"):
|
||||
keys.append(line)
|
||||
except FileNotFoundError:
|
||||
pass
|
||||
# dedupe, keep order
|
||||
seen, out = set(), []
|
||||
for k in keys:
|
||||
if k not in seen:
|
||||
seen.add(k)
|
||||
out.append(k)
|
||||
return out
|
||||
|
||||
|
||||
def _alive_keys():
|
||||
now = time.time()
|
||||
return [k for k in _load_keys() if now - _dead.get(k, 0) > 1800]
|
||||
|
||||
|
||||
def _headers(key):
|
||||
return {"X-API-Key": key, "User-Agent": UA,
|
||||
"Origin": "https://apiframe.ai", "Referer": "https://apiframe.ai/"}
|
||||
|
||||
|
||||
async def get_credits(session, key):
|
||||
try:
|
||||
async with session.get(API + "/v2/credits", headers=_headers(key),
|
||||
timeout=aiohttp.ClientTimeout(total=20)) as r:
|
||||
if r.status != 200:
|
||||
return None
|
||||
d = await r.json()
|
||||
return d.get("credits", d.get("balance"))
|
||||
except Exception:
|
||||
return None
|
||||
|
||||
|
||||
async def pool_status():
|
||||
"""[{key_tail, credits}] for admin."""
|
||||
out = []
|
||||
async with aiohttp.ClientSession() as s:
|
||||
for k in _load_keys():
|
||||
c = await get_credits(s, k)
|
||||
out.append({"key": k[:8] + "..." + k[-4:], "credits": c,
|
||||
"dead": (time.time() - _dead.get(k, 0)) < 1800})
|
||||
return out
|
||||
|
||||
|
||||
async def generate_music(prompt, title=None, style=None, instrumental=False,
|
||||
model_version="V5", timeout=420):
|
||||
"""Generate a Suno track. Returns dict:
|
||||
{ok, tracks:[{audioUrl,title,imageUrl}], error, key_tail}"""
|
||||
keys = _alive_keys()
|
||||
if not keys:
|
||||
return {"ok": False, "error": "POOL_EMPTY"}
|
||||
payload = {"model": "suno", "prompt": prompt}
|
||||
sp = {"model_version": model_version, "instrumental": bool(instrumental)}
|
||||
if title or style:
|
||||
sp["custom_mode"] = True
|
||||
if title:
|
||||
sp["title"] = title
|
||||
if style:
|
||||
sp["style"] = style
|
||||
sp["negative_tags"] = "instrumental, pop, slow" if not instrumental else "vocal"
|
||||
payload["sunoParams"] = sp
|
||||
|
||||
async with _sem:
|
||||
last_err = None
|
||||
for key in keys:
|
||||
try:
|
||||
async with aiohttp.ClientSession() as s:
|
||||
async with s.post(API + "/v2/music/generate", headers=_headers(key),
|
||||
json=payload, timeout=aiohttp.ClientTimeout(total=40)) as r:
|
||||
body = await r.text()
|
||||
if r.status == 402:
|
||||
_dead[key] = time.time()
|
||||
last_err = "NO_CREDITS"
|
||||
continue
|
||||
if r.status == 401 or r.status == 403:
|
||||
_dead[key] = time.time()
|
||||
last_err = "KEY_DEAD_%d" % r.status
|
||||
continue
|
||||
if r.status not in (200, 202):
|
||||
last_err = "HTTP_%d:%s" % (r.status, body[:120])
|
||||
continue
|
||||
try:
|
||||
d = json.loads(body)
|
||||
except Exception:
|
||||
last_err = "BAD_JSON"
|
||||
continue
|
||||
job = d.get("jobId") or d.get("job_id") or d.get("id")
|
||||
if not job:
|
||||
last_err = "NO_JOBID:%s" % body[:120]
|
||||
continue
|
||||
# poll
|
||||
t0 = time.time()
|
||||
while time.time() - t0 < timeout:
|
||||
await asyncio.sleep(8)
|
||||
async with aiohttp.ClientSession() as s2:
|
||||
async with s2.get(API + "/v2/jobs/" + job, headers=_headers(key),
|
||||
timeout=aiohttp.ClientTimeout(total=25)) as jr:
|
||||
try:
|
||||
jd = await jr.json()
|
||||
except Exception:
|
||||
continue
|
||||
st = str(jd.get("status", "")).lower()
|
||||
if st in ("done", "succeeded", "success", "completed"):
|
||||
res = jd.get("result") or {}
|
||||
tracks = res.get("tracks") or jd.get("tracks") or []
|
||||
out = [{"audioUrl": t.get("audioUrl") or t.get("audio_url"),
|
||||
"title": t.get("title") or title or "track",
|
||||
"imageUrl": t.get("imageUrl") or t.get("image_url")}
|
||||
for t in tracks if (t.get("audioUrl") or t.get("audio_url"))]
|
||||
return {"ok": bool(out), "tracks": out, "job": job,
|
||||
"key_tail": key[-6:], "error": None if out else "NO_TRACKS"}
|
||||
if st in ("failed", "error", "cancelled"):
|
||||
last_err = "JOB_FAILED:%s" % str(jd.get("error"))[:120]
|
||||
break
|
||||
else:
|
||||
last_err = "TIMEOUT"
|
||||
continue
|
||||
except asyncio.TimeoutError:
|
||||
last_err = "NET_TIMEOUT"
|
||||
except Exception as e:
|
||||
last_err = repr(e)[:150]
|
||||
return {"ok": False, "tracks": [], "error": last_err or "UNKNOWN"}
|
||||
@@ -0,0 +1,551 @@
|
||||
"""Stateless Mini App assistant: bounded caller context, original models, opt-in execution."""
|
||||
import asyncio
|
||||
from collections import OrderedDict
|
||||
from contextlib import closing
|
||||
from datetime import datetime, timezone
|
||||
import json
|
||||
import os
|
||||
import re
|
||||
import secrets
|
||||
import sqlite3
|
||||
import time
|
||||
|
||||
import aiohttp
|
||||
from model_identity import ModelIdentityError, check_response_model
|
||||
# Redaction of tool output before it goes to the model provider. High-signal patterns,
|
||||
# best effort: this is not an isolation boundary (the sandbox service still sees raw
|
||||
# output, and nothing here is a claim about what providers retain on their side).
|
||||
_SECRET_REDACTIONS = (
|
||||
(re.compile(r'(?s)-----BEGIN ((?:[A-Z0-9]+ )*)PRIVATE KEY-----.*?-----END (?:[A-Z0-9]+ )*PRIVATE KEY-----'),
|
||||
lambda m: ('[redacted %sprivate key]' % m.group(1)).lower()),
|
||||
(re.compile(r'(?s)-----BEGIN [A-Z0-9 ]*PRIVATE KEY-----.*'),
|
||||
'[redacted private key]'),
|
||||
(re.compile(r'eyJ[A-Za-z0-9_-]{10,}\.[A-Za-z0-9_-]{10,}\.[A-Za-z0-9_-]{10,}'), '[redacted jwt]'),
|
||||
(re.compile(r'\b(?:sk-[A-Za-z0-9_-]{16,}|AKIA[0-9A-Z]{16}|gh[pousr]_[A-Za-z0-9]{20,}|xox[baprs]-[A-Za-z0-9-]{10,})\b'),
|
||||
lambda m: m.group(0)[:6] + '…[redacted]'),
|
||||
(re.compile(r'(?i)\b(authorization)\b(["\']?\s*[:=]\s*["\']?\s*)(basic|bearer)\s+([A-Za-z0-9._~+/=-]+)'),
|
||||
lambda m: m.group(1) + m.group(2) + m.group(3) + ' [redacted]'),
|
||||
(re.compile(r'(?i)\b(bearer|authorization)\b(\s*[:=]?\s*)([A-Za-z0-9._~+/=-]{16,})'),
|
||||
lambda m: m.group(1) + m.group(2) + '[redacted]'),
|
||||
(re.compile(r'(?i)\b(password|passwd|pwd|secret|token|api[_-]?key|apikey|access[_-]?key|client[_-]?secret)\b'
|
||||
r'(\s*[:=]\s*)(["\']?)([^\s"\';,]{6,})(["\']?)'),
|
||||
lambda m: m.group(1) + m.group(2) + m.group(3) + '[redacted]' + (m.group(5) or '')),
|
||||
)
|
||||
|
||||
|
||||
def redact_secrets(text):
|
||||
for pattern, repl in _SECRET_REDACTIONS:
|
||||
text = pattern.sub(repl, text)
|
||||
return text
|
||||
|
||||
|
||||
def tool_result_for_model(result):
|
||||
"""Separate copy of a tool result for the upstream request: stdout/stderr redacted,
|
||||
cmd/exit_code/flags kept. The original stays in trace and in the client response."""
|
||||
if not isinstance(result, dict) or not isinstance(result.get('out'), str):
|
||||
return result
|
||||
copy = dict(result)
|
||||
copy['out'] = redact_secrets(copy['out'])
|
||||
return copy
|
||||
|
||||
|
||||
|
||||
class AssistantError(Exception):
|
||||
def __init__(self, status, code, message, **details):
|
||||
super().__init__(code)
|
||||
self.status, self.code, self.message = status, code, message
|
||||
self.details = details
|
||||
|
||||
|
||||
class UpstreamError(Exception):
|
||||
def __init__(self, status, reason=""):
|
||||
self.status, self.reason = status, reason
|
||||
super().__init__("upstream_%s" % status)
|
||||
|
||||
class _Operation:
|
||||
def __init__(self, uid, operation_id):
|
||||
self.uid, self.operation_id = uid, operation_id
|
||||
self.task = None
|
||||
self.cancel_requested = False
|
||||
self.side_effect_started = False
|
||||
self.uncertain = False
|
||||
self.trace, self.reminders = [], []
|
||||
|
||||
|
||||
|
||||
class AssistantRuntime:
|
||||
def __init__(self, bot_db, newapi_db, base_url, models, reminders, sandbox_path):
|
||||
self.bot_db, self.newapi_db = bot_db, newapi_db
|
||||
self.base_url, self.models = base_url.rstrip('/'), tuple(models)
|
||||
self.reminders, self.sandbox_path = reminders, sandbox_path
|
||||
self.busy, self.rate = set(), {}
|
||||
self.operations, self.finished = {}, OrderedDict()
|
||||
self.operation_ttl, self.operation_limit = 3600, 2048
|
||||
self.max_active, self.disconnect_interval = 128, 0.1
|
||||
|
||||
@staticmethod
|
||||
def operation_id(value, *, generate=False):
|
||||
if value is None and generate:
|
||||
return secrets.token_hex(16)
|
||||
if not isinstance(value, str) or not re.fullmatch(r'[A-Za-z0-9][A-Za-z0-9_.:-]{0,95}', value):
|
||||
raise AssistantError(400, 'invalid_operation_id', 'Некорректный идентификатор запроса.')
|
||||
return value
|
||||
|
||||
def _prune_operations(self):
|
||||
cutoff = time.monotonic() - self.operation_ttl
|
||||
while self.finished:
|
||||
key, record = next(iter(self.finished.items()))
|
||||
if len(self.finished) <= self.operation_limit and record['finished_at'] > cutoff:
|
||||
break
|
||||
self.finished.pop(key)
|
||||
|
||||
@staticmethod
|
||||
def _state(operation_id, state, uncertain=False):
|
||||
return {'ok': True, 'operation_id': operation_id, 'state': state, 'uncertain': bool(uncertain)}
|
||||
|
||||
def _finish_operation(self, operation, task):
|
||||
if self.operations.get(operation.uid) is not operation:
|
||||
return
|
||||
failed = task.cancelled() or task.exception() is not None
|
||||
# [STATE-TRUTH 2610] упавшая задача — failed, не completed: UI не показывает «готово» на обломе
|
||||
state = ('cancelled' if operation.cancel_requested or task.cancelled()
|
||||
else 'failed' if failed else 'completed')
|
||||
uncertain = operation.uncertain or (failed and operation.side_effect_started)
|
||||
record = self._state(operation.operation_id, state, uncertain)
|
||||
# [TERMINAL-TRUTH 2810] честный флаг для UI: «внешних действий не было» можно утверждать
|
||||
# только при side_effect_started=False, иначе Stop/ошибка не обещают отмену и не отменяют её.
|
||||
record['side_effect_started'] = bool(operation.side_effect_started)
|
||||
self.finished[(operation.uid, operation.operation_id)] = dict(record, finished_at=time.monotonic())
|
||||
self.operations.pop(operation.uid, None)
|
||||
self.busy.discard(operation.uid)
|
||||
self._prune_operations()
|
||||
|
||||
def cancel(self, uid, operation_id):
|
||||
self._prune_operations()
|
||||
# Legacy callers without an ID must never cancel whichever operation happens to be current.
|
||||
if operation_id is None:
|
||||
return self._state(None, 'not_found')
|
||||
operation_id = self.operation_id(operation_id)
|
||||
operation = self.operations.get(uid)
|
||||
if operation and operation.operation_id == operation_id:
|
||||
if operation.task.done():
|
||||
self._finish_operation(operation, operation.task)
|
||||
else:
|
||||
if not operation.cancel_requested:
|
||||
operation.cancel_requested = True
|
||||
operation.uncertain |= operation.side_effect_started
|
||||
operation.task.cancel()
|
||||
return self._state(operation_id, 'cancel_requested', operation.uncertain)
|
||||
record = self.finished.get((uid, operation_id))
|
||||
if record:
|
||||
receipt = {key: value for key, value in record.items() if key != 'finished_at'}
|
||||
if receipt.get('state') == 'failed':
|
||||
# [CANCEL-COMPAT 2810] Живой старый UI валидирует state ответа cancel по
|
||||
# whitelist completed/cancelled/cancel_requested/not_found и на 'failed'
|
||||
# бросает invalid_cancel_receipt. Отдаём legacy-состояние, но помечаем
|
||||
# провал явно: новый UI обязан показать ошибку, а не «уже завершилось».
|
||||
receipt['terminal_state'] = 'failed'
|
||||
receipt['failed'] = True
|
||||
receipt['state'] = 'completed'
|
||||
return receipt
|
||||
# [STOP-FIX 2610] not_found не записываем в finished: операция не найдена →
|
||||
# ничего не гасим, Stop возвращает честный ответ, не блокируем повторные стопы
|
||||
return self._state(operation_id, 'not_found')
|
||||
|
||||
@staticmethod
|
||||
async def _cleanup_await(awaitable):
|
||||
task = asyncio.create_task(awaitable)
|
||||
try:
|
||||
return await asyncio.shield(task)
|
||||
except asyncio.CancelledError:
|
||||
# A SQLite worker cannot be killed. Keep admission occupied until it actually closes.
|
||||
while not task.done():
|
||||
try:
|
||||
await asyncio.shield(task)
|
||||
except asyncio.CancelledError:
|
||||
continue
|
||||
except Exception:
|
||||
break
|
||||
if not task.cancelled():
|
||||
task.exception()
|
||||
raise
|
||||
|
||||
async def _drive_operation(self, operation, payload, history, alive):
|
||||
async def monitor():
|
||||
while True:
|
||||
if alive is not None and not alive():
|
||||
self.cancel(operation.uid, operation.operation_id)
|
||||
return
|
||||
await asyncio.sleep(self.disconnect_interval)
|
||||
|
||||
worker = asyncio.create_task(self._chat_work(operation.uid, payload, history, operation))
|
||||
watcher = asyncio.create_task(monitor()) if alive is not None else None
|
||||
try:
|
||||
return await worker
|
||||
finally:
|
||||
if watcher is not None:
|
||||
watcher.cancel()
|
||||
await asyncio.gather(watcher, return_exceptions=True)
|
||||
|
||||
async def close(self):
|
||||
pending = [operation.task for operation in list(self.operations.values())]
|
||||
for operation in list(self.operations.values()):
|
||||
self.cancel(operation.uid, operation.operation_id)
|
||||
if pending:
|
||||
await asyncio.gather(*pending, return_exceptions=True)
|
||||
|
||||
def connect(self, path):
|
||||
con = sqlite3.connect(str(path), timeout=5)
|
||||
con.row_factory = sqlite3.Row
|
||||
return con
|
||||
|
||||
def init_db(self):
|
||||
self.reminders.init_db(self.bot_db)
|
||||
|
||||
def history(self, uid):
|
||||
return [], 0
|
||||
|
||||
def clear_history(self, uid):
|
||||
"""Explicitly clear only this user's existing legacy row, if present."""
|
||||
with closing(self.connect(self.bot_db)) as con:
|
||||
exists = con.execute("SELECT 1 FROM sqlite_master WHERE type='table' AND name='wa_agent_history'").fetchone()
|
||||
if exists:
|
||||
con.execute("UPDATE wa_agent_history SET messages='[]',generation=generation+1,updated=? WHERE uid=?",
|
||||
(int(time.time()), uid))
|
||||
con.commit()
|
||||
|
||||
def save_history(self, uid, messages, generation):
|
||||
return False
|
||||
|
||||
def user(self, uid):
|
||||
with closing(self.connect(self.bot_db)) as con:
|
||||
user = con.execute("SELECT token_name,banned,api_blocked,key_locked FROM users WHERE tg_id=?", (uid,)).fetchone()
|
||||
if user is None:
|
||||
raise AssistantError(403, 'need_start', 'Сначала открой чат с ботом и нажми /start.')
|
||||
if user['banned'] or user['api_blocked']:
|
||||
raise AssistantError(403, 'access_blocked', 'Доступ ограничен. Проверь условия доступа в боте.')
|
||||
return user
|
||||
|
||||
def user_key(self, uid):
|
||||
user = self.user(uid)
|
||||
if user['key_locked']:
|
||||
raise AssistantError(403, 'key_locked', 'Твой ключ заблокирован тобой. Разблокируй его во вкладке «Ключи».')
|
||||
names = list(dict.fromkeys([user['token_name'], 'tg%d' % uid]))
|
||||
with closing(self.connect(self.newapi_db)) as con:
|
||||
for name in names:
|
||||
if not name:
|
||||
continue
|
||||
row = con.execute("SELECT key FROM tokens WHERE name=? AND status=1 AND deleted_at IS NULL "
|
||||
"ORDER BY remain_quota DESC LIMIT 1", (name,)).fetchone()
|
||||
if row and row['key']:
|
||||
key = row['key']
|
||||
return key if key.startswith('sk-') else 'sk-' + key
|
||||
raise AssistantError(403, 'need_key', 'Сначала создай активный API-ключ во вкладке «Ключи».')
|
||||
|
||||
def key_has_credit(self, key):
|
||||
plain = key[3:] if key.startswith('sk-') else key
|
||||
with closing(self.connect(self.newapi_db)) as con:
|
||||
row = con.execute(
|
||||
'SELECT t.remain_quota,t.unlimited_quota,u.quota FROM tokens t '
|
||||
'JOIN users u ON u.id=t.user_id WHERE t.key IN (?,?) AND t.deleted_at IS NULL',
|
||||
(plain, key)).fetchone()
|
||||
return bool(row and (row[1] or row[0] > 0) and row[2] > 0)
|
||||
|
||||
async def complete(self, model, messages, key, *, fast=False, max_tokens=2048):
|
||||
timeout = aiohttp.ClientTimeout(total=18 if fast else 85, connect=5)
|
||||
async with aiohttp.ClientSession(timeout=timeout) as session:
|
||||
async with session.post(self.base_url + '/chat/completions',
|
||||
headers={'Authorization': 'Bearer ' + key},
|
||||
json={'model': model, 'messages': messages, 'max_tokens': max_tokens}) as response:
|
||||
if response.status != 200:
|
||||
raw_error = (await response.content.read(16384)).decode('utf-8', 'replace').lower()
|
||||
try:
|
||||
decoded = json.loads(raw_error)
|
||||
detail = decoded.get('error', decoded) if isinstance(decoded, dict) else decoded
|
||||
raw_error = str(detail.get('message', '') if isinstance(detail, dict) else detail).lower()
|
||||
except (ValueError, TypeError):
|
||||
pass
|
||||
quota_markers = ('用户额度不足', '余额不足', '剩余额度', 'insufficient_quota',
|
||||
'insufficient balance', 'free quota', 'good standing', '请充值')
|
||||
reason = ''
|
||||
if any(marker in raw_error for marker in quota_markers):
|
||||
funded = await asyncio.to_thread(self.key_has_credit, key)
|
||||
reason = 'upstream_quota' if funded else 'local_quota'
|
||||
elif response.status == 401 and ('channel error' in raw_error or 'channel #' in raw_error):
|
||||
reason = 'upstream_auth'
|
||||
raise UpstreamError(response.status, reason)
|
||||
try:
|
||||
data = await response.json()
|
||||
except (ValueError, aiohttp.ContentTypeError):
|
||||
raise UpstreamError(502) from None
|
||||
if not isinstance(data, dict):
|
||||
raise UpstreamError(502)
|
||||
try:
|
||||
check_response_model(model, data)
|
||||
except ModelIdentityError:
|
||||
raise AssistantError(503, 'model_identity_mismatch', 'Выбранная модель сейчас недоступна. Повтори позже.') from None
|
||||
choices = data.get('choices')
|
||||
first = choices[0] if isinstance(choices, list) and choices else None
|
||||
message = first.get('message') if isinstance(first, dict) else None
|
||||
text = message.get('content') if isinstance(message, dict) else None
|
||||
if not isinstance(text, str) or not text.strip():
|
||||
raise UpstreamError(502)
|
||||
return text.strip()
|
||||
|
||||
async def execute(self, uid, command):
|
||||
if os.environ.get('IISHKO_SANDBOX_ENABLED') != '1':
|
||||
return {'error': 'sandbox_disabled', 'out': 'Выполнение команд отключено.', 'connected': False, 'uncertain': False}
|
||||
try:
|
||||
with open(self.sandbox_path, encoding='utf-8') as source:
|
||||
config = json.load(source)
|
||||
except (OSError, ValueError):
|
||||
return {'cmd': command, 'out': 'VM пока не настроена.', 'connected': False, 'uncertain': False}
|
||||
if not isinstance(config, dict):
|
||||
return {'cmd': command, 'out': 'Конфигурация VM некорректна.', 'connected': False, 'uncertain': False}
|
||||
if not config.get('url') or not config.get('key'):
|
||||
return {'cmd': command, 'out': 'VM пока не настроена.', 'connected': False, 'uncertain': False}
|
||||
# Isolation and resource limits are enforced by the existing sandbox service, not a substring filter.
|
||||
timeout = aiohttp.ClientTimeout(total=35, connect=5)
|
||||
try:
|
||||
async with aiohttp.ClientSession(timeout=timeout) as session:
|
||||
async with session.post(config['url'].rstrip('/') + '/exec',
|
||||
headers={'X-Sandbox-Key': config['key']},
|
||||
json={'uid': uid, 'cmd': command, 'timeout': 25}) as response:
|
||||
if response.status != 200:
|
||||
return {'cmd': command, 'out': 'VM временно недоступна (HTTP %s).' % response.status,
|
||||
'connected': False, 'uncertain': True}
|
||||
data = await response.json()
|
||||
if not isinstance(data, dict):
|
||||
return {'cmd': command, 'out': 'VM вернула некорректный ответ. Команда могла выполниться; проверь файлы.',
|
||||
'connected': False, 'uncertain': True}
|
||||
code = data.get('exit', data.get('exit_code'))
|
||||
if not isinstance(code, int) or isinstance(code, bool):
|
||||
return {'cmd': command, 'out': 'VM не подтвердила завершение. Проверь файлы перед повтором.',
|
||||
'connected': False, 'uncertain': True}
|
||||
output = str(data.get('stdout') or '')[:6000]
|
||||
if data.get('stderr'):
|
||||
output += '\n[stderr] ' + str(data['stderr'])[:2000]
|
||||
return {'cmd': command, 'out': output or '(нет вывода)', 'exit_code': code,
|
||||
'connected': True, 'uncertain': False, 'timed_out': bool(data.get('timed_out') or code == 124)}
|
||||
except (aiohttp.ClientError, asyncio.TimeoutError, ValueError) as error:
|
||||
return {'cmd': command, 'out': 'VM не ответила: %s. Команда могла завершиться; проверь файлы перед повтором.' %
|
||||
type(error).__name__, 'connected': False, 'uncertain': True}
|
||||
|
||||
def tool_reminder(self, uid, raw):
|
||||
data = json.loads(raw)
|
||||
if not isinstance(data, dict):
|
||||
raise ValueError('invalid_reminder')
|
||||
return self.reminders.create_reminder(self.bot_db, uid, data.get('text'), data.get('due_at'))
|
||||
|
||||
@staticmethod
|
||||
def public_upstream_error(error):
|
||||
status = getattr(error, 'status', 503)
|
||||
reason = getattr(error, 'reason', '')
|
||||
if reason in ('upstream_quota', 'upstream_auth'):
|
||||
return AssistantError(503, reason, 'Аккаунт провайдера этой модели не может обслужить запрос. Ваш ключ не отозван; выбранная модель не подменялась.')
|
||||
if reason == 'local_quota':
|
||||
return AssistantError(402, 'credit_required', 'На ключе закончился API-кредит. Проверь баланс во вкладке «Ключи».')
|
||||
if status == 403:
|
||||
return AssistantError(403, 'request_forbidden', 'Маршрут модели отклонил запрос. Это не отсутствие Telegram-авторизации; ключ не удалён.')
|
||||
if status == 401:
|
||||
return AssistantError(403, 'key_rejected', 'Шлюз не принял API-ключ. Проверь его во вкладке «Ключи»; ключ сохранён.')
|
||||
if status == 402:
|
||||
return AssistantError(402, 'credit_required', 'На ключе закончился API-кредит. Проверь баланс во вкладке «Ключи».')
|
||||
if status == 429:
|
||||
return AssistantError(429, 'model_busy', 'Модель перегружена. Попробуй позже или выбери другую модель.')
|
||||
return AssistantError(503, 'model_unavailable', 'Модель сейчас не ответила. Повтори позже.')
|
||||
|
||||
async def chat(self, uid, payload, alive=None):
|
||||
if not isinstance(payload, dict):
|
||||
raise AssistantError(400, 'invalid_body', 'Ожидается JSON-объект.')
|
||||
model = payload.get('model', 'auto')
|
||||
if not isinstance(model, str) or model not in ('auto', *self.models):
|
||||
raise AssistantError(400, 'invalid_model', 'Эта модель недоступна. Выбери модель из списка.')
|
||||
raw = payload.get('messages')
|
||||
if not isinstance(raw, list) or not raw or not isinstance(raw[-1], dict):
|
||||
raise AssistantError(400, 'invalid_messages', 'Напиши сообщение.')
|
||||
last = raw[-1]
|
||||
text = last.get('content')
|
||||
if last.get('role') != 'user' or not isinstance(text, str) or not text.strip() or len(text) > 12000:
|
||||
raise AssistantError(400, 'invalid_message', 'Сообщение должно содержать от 1 до 12 000 символов.')
|
||||
if len(raw) > 20:
|
||||
raise AssistantError(400, 'invalid_messages', 'Слишком длинный контекст: максимум 20 сообщений.')
|
||||
history = []
|
||||
total_chars = 0
|
||||
for item in raw:
|
||||
if not isinstance(item, dict) or item.get('role') not in ('user', 'assistant'):
|
||||
raise AssistantError(400, 'invalid_messages', 'Контекст может содержать только сообщения диалога.')
|
||||
content = item.get('content')
|
||||
if not isinstance(content, str) or not content.strip() or len(content) > 12000:
|
||||
raise AssistantError(400, 'invalid_messages', 'Некорректная длина сообщения контекста.')
|
||||
total_chars += len(content)
|
||||
if total_chars > 96000:
|
||||
raise AssistantError(400, 'invalid_messages', 'Слишком большой контекст диалога.')
|
||||
history.append({'role': item['role'], 'content': content})
|
||||
operation_id = self.operation_id(payload.get('operation_id'), generate=True)
|
||||
self._prune_operations()
|
||||
current = self.operations.get(uid)
|
||||
if current and current.task.done():
|
||||
self._finish_operation(current, current.task)
|
||||
current = None
|
||||
previous = self.finished.get((uid, operation_id))
|
||||
if previous:
|
||||
raise AssistantError(409, 'operation_replayed', 'Этот запрос уже завершён или остановлен. Проверь результат перед новым действием.',
|
||||
operation_id=operation_id, state=previous['state'], uncertain=previous['uncertain'])
|
||||
if current:
|
||||
same = current.operation_id == operation_id
|
||||
raise AssistantError(409, 'operation_in_progress' if same else 'agent_busy',
|
||||
'Предыдущий ответ ещё готовится.', operation_id=operation_id,
|
||||
state=('cancel_requested' if current.cancel_requested else 'running') if same else 'not_found',
|
||||
uncertain=current.uncertain if same else False)
|
||||
if len(self.operations) >= self.max_active:
|
||||
raise AssistantError(503, 'agent_capacity', 'Сервис занят. Попробуй позже.',
|
||||
operation_id=operation_id, state='not_found', uncertain=False)
|
||||
operation = _Operation(uid, operation_id)
|
||||
self.operations[uid] = operation
|
||||
self.busy.add(uid)
|
||||
task = asyncio.create_task(self._drive_operation(operation, payload, history, alive))
|
||||
operation.task = task
|
||||
task.add_done_callback(lambda done: self._finish_operation(operation, done))
|
||||
try:
|
||||
result = await asyncio.shield(task)
|
||||
return dict(result, operation_id=operation_id, state='completed', uncertain=operation.uncertain,
|
||||
side_effect_started=bool(operation.side_effect_started))
|
||||
except asyncio.CancelledError:
|
||||
if asyncio.current_task().cancelling():
|
||||
self.cancel(uid, operation_id)
|
||||
try:
|
||||
await asyncio.shield(task)
|
||||
except (asyncio.CancelledError, Exception):
|
||||
pass
|
||||
raise
|
||||
return dict(self._state(operation_id, 'cancelled', operation.uncertain),
|
||||
cancelled=True, partial=operation.side_effect_started,
|
||||
side_effect_started=bool(operation.side_effect_started),
|
||||
reply=('Ожидание остановлено. Команда или сохранение напоминания могли завершиться. '
|
||||
'Удалённая остановка не подтверждена; проверь результат перед повтором.'
|
||||
if operation.uncertain else 'Ожидание ответа остановлено.'),
|
||||
vm=operation.trace, reminders=operation.reminders, history_saved=False)
|
||||
except AssistantError as error:
|
||||
# [TERMINAL-TRUTH 2810] провайдерский отказ — failed, не completed: UI не рисует «готово»
|
||||
# и не утверждает, что внешних действий не было; флаг берём из самой операции.
|
||||
error.details.update(operation_id=operation_id, state='failed',
|
||||
uncertain=operation.uncertain or bool(operation.side_effect_started),
|
||||
side_effect_started=bool(operation.side_effect_started))
|
||||
raise
|
||||
|
||||
async def _chat_work(self, uid, payload, history, operation):
|
||||
model = payload.get('model', 'auto')
|
||||
sandbox_enabled = os.environ.get('IISHKO_SANDBOX_ENABLED') == '1'
|
||||
try:
|
||||
key = await self._cleanup_await(asyncio.to_thread(self.user_key, uid))
|
||||
# Operational tool contract only (no persona/policy): the loop below parses
|
||||
# <exec>/<reminder>, so the interface must be visible to the model. Exec is
|
||||
# advertised only while the sandbox flag is on; a stray tag then gets an honest
|
||||
# sandbox_disabled result instead of a fabricated action.
|
||||
system = ('Отвечай на языке пользователя. Не упоминай название провайдера или сервиса. '
|
||||
'Инструменты реальны, вызывай их тегом прямо в ответе, максимум 4 за запрос. '
|
||||
'Напоминание в Telegram: <reminder>{"text":"текст","due_at":UNIX_SECONDS}</reminder> '
|
||||
'(не меньше 30 секунд и не больше года вперёд). '
|
||||
'Текущее UTC-время: %s; Unix: %d. ')
|
||||
if sandbox_enabled:
|
||||
system += ('Linux-песочница (bash, python3, node, git): <exec>shell-команда</exec>; '
|
||||
'результат придёт сообщением «[Результат инструмента]» перед твоим итогом. ')
|
||||
system += ('О выполненном говори только по фактически пришедшему результату инструмента: '
|
||||
'не описывай действие или вывод, которых в результате нет.')
|
||||
conversation = [{'role': 'system', 'content': system % (datetime.now(timezone.utc).isoformat(), int(time.time()))}] + history
|
||||
trace, reminders, tool_cache = operation.trace, operation.reminders, {}
|
||||
selected_model = model
|
||||
|
||||
def check_alive():
|
||||
if operation.cancel_requested:
|
||||
raise asyncio.CancelledError()
|
||||
|
||||
async def run():
|
||||
nonlocal selected_model
|
||||
if model == 'auto':
|
||||
raw_candidates = payload.get('candidates')
|
||||
if isinstance(raw_candidates, list) and raw_candidates:
|
||||
candidates = [c for c in raw_candidates if isinstance(c, str) and c in self.models]
|
||||
else:
|
||||
candidates = list(self.models)
|
||||
if not candidates:
|
||||
candidates = [self.models[0] if self.models else '']
|
||||
else:
|
||||
candidates = [model]
|
||||
selected, answer, last_error = None, '', None
|
||||
for candidate in candidates:
|
||||
check_alive()
|
||||
try:
|
||||
answer = await self.complete(candidate, conversation, key, fast=model == 'auto')
|
||||
selected = candidate
|
||||
selected_model = candidate
|
||||
break
|
||||
except (UpstreamError, aiohttp.ClientError, asyncio.TimeoutError) as error:
|
||||
last_error = error
|
||||
if model != 'auto' or getattr(error, 'status', 503) in (401, 402) or getattr(error, 'reason', '') == 'local_quota':
|
||||
raise self.public_upstream_error(error) from None
|
||||
# auto: 403 (ранг/права на конкретную модель) и 5xx — пробуем следующего кандидата
|
||||
if selected is None:
|
||||
raise self.public_upstream_error(last_error) from None
|
||||
for step in range(5):
|
||||
check_alive()
|
||||
tool = re.search(r'<(exec|reminder)>(.*?)</\1>', answer, re.S)
|
||||
if not tool:
|
||||
return answer[:12000], selected, False
|
||||
if step == 4:
|
||||
return 'Достигнут лимит инструментов за один запрос. Выполненные действия и вывод сохранены; продолжим следующим сообщением.', selected, True
|
||||
kind, argument = tool.group(1), tool.group(2).strip()
|
||||
if len(argument) > 6000:
|
||||
result = {'error': 'tool_input_too_long'}
|
||||
elif (kind, argument) in tool_cache:
|
||||
result = tool_cache[(kind, argument)]
|
||||
elif kind == 'exec':
|
||||
operation.side_effect_started = True
|
||||
result = {'cmd': argument, 'out': 'Команда отправлена; завершение пока не подтверждено.',
|
||||
'connected': False, 'uncertain': True}
|
||||
trace.append(result)
|
||||
tool_cache[(kind, argument)] = result
|
||||
result.update(await self.execute(uid, argument))
|
||||
operation.uncertain |= bool(result.get('uncertain'))
|
||||
if result.get('uncertain'):
|
||||
return 'VM не подтвердила завершение команды. Автоматического повтора не будет. Проверь вывод и файлы перед новым действием.', selected, True
|
||||
else:
|
||||
async def save_reminder():
|
||||
row = await asyncio.to_thread(self.tool_reminder, uid, argument)
|
||||
reminders.append(row)
|
||||
tool_cache[(kind, argument)] = row
|
||||
return row
|
||||
|
||||
try:
|
||||
operation.side_effect_started = True
|
||||
result = await self._cleanup_await(save_reminder())
|
||||
except (ValueError, TypeError) as error:
|
||||
result = {'error': str(error)[:80]}
|
||||
# Only the upstream copy is redacted; trace, tool_cache and the client
|
||||
# response keep the original result.
|
||||
conversation.extend([{'role': 'assistant', 'content': answer},
|
||||
{'role': 'user', 'content': '[Результат инструмента]\n'
|
||||
+ json.dumps(tool_result_for_model(result), ensure_ascii=False)}])
|
||||
check_alive()
|
||||
try:
|
||||
answer = await self.complete(selected, conversation, key, fast=model == 'auto')
|
||||
except (UpstreamError, aiohttp.ClientError, asyncio.TimeoutError):
|
||||
return 'Инструмент завершил попытку, но модель не подготовила итог. Проверь вывод ниже и сохранённые напоминания. Не повторяй действие вслепую.', selected, True
|
||||
raise RuntimeError('unreachable_tool_loop')
|
||||
|
||||
try:
|
||||
answer, selected, partial = await asyncio.wait_for(run(), timeout=145)
|
||||
except asyncio.TimeoutError:
|
||||
operation.uncertain |= operation.side_effect_started
|
||||
if not trace and not reminders:
|
||||
raise AssistantError(504, 'agent_timeout', 'Истекло время ожидания. Попробуй более быструю модель.') from None
|
||||
answer, selected, partial = ('Время ожидания истекло после запуска инструмента. Проверь вывод и файлы перед повтором.', selected_model, True)
|
||||
return {'reply': answer, 'model': selected, 'vm': trace, 'reminders': reminders, 'partial': partial,
|
||||
'history_saved': False, 'workspace': ('/sandbox/users/%d' % uid) if sandbox_enabled else None}
|
||||
except asyncio.CancelledError:
|
||||
operation.uncertain |= operation.side_effect_started
|
||||
raise
|
||||
except Exception:
|
||||
operation.uncertain |= operation.side_effect_started
|
||||
raise
|
||||
@@ -0,0 +1,173 @@
|
||||
"""Strict, versioned migrations for the bot-owned SQLite database only.
|
||||
|
||||
Never opens New API, changes journal mode, or changes billing/ATTACH semantics.
|
||||
"""
|
||||
from __future__ import annotations
|
||||
|
||||
import logging
|
||||
import sqlite3
|
||||
import time
|
||||
|
||||
SCHEMA_VERSION = 2
|
||||
|
||||
TABLE_DDL = ('CREATE TABLE IF NOT EXISTS users(\n'
|
||||
' tg_id INTEGER PRIMARY KEY, username TEXT, token_name TEXT, api_key TEXT,\n'
|
||||
' created INTEGER, notified INTEGER DEFAULT 1,\n'
|
||||
' points INTEGER DEFAULT 0, referred_by INTEGER, ref_time INTEGER, ref_awarded INTEGER '
|
||||
'DEFAULT 0,\n'
|
||||
' lang TEXT, menu_style TEXT)',
|
||||
'CREATE TABLE IF NOT EXISTS group_log(chat_id INTEGER, uid INTEGER, username TEXT, text TEXT, ts '
|
||||
'INTEGER)',
|
||||
'CREATE TABLE IF NOT EXISTS sticker_cache(file_id TEXT PRIMARY KEY, emoji TEXT, set_name TEXT, '
|
||||
'added INTEGER)',
|
||||
'CREATE TABLE IF NOT EXISTS video_tasks(tid TEXT PRIMARY KEY, uid INTEGER, chat_id INTEGER, '
|
||||
'message_id INTEGER, prompt TEXT, key TEXT, ts INTEGER)')
|
||||
|
||||
USER_COLUMNS = (('points', 'INTEGER DEFAULT 0'),
|
||||
('referred_by', 'INTEGER'),
|
||||
('ref_time', 'INTEGER'),
|
||||
('ref_awarded', 'INTEGER DEFAULT 0'),
|
||||
('lang', 'TEXT'),
|
||||
('menu_style', 'TEXT'),
|
||||
('chat_mode', 'INTEGER DEFAULT 0'),
|
||||
('waiting_prompt', 'INTEGER DEFAULT 0'),
|
||||
('chat_count', 'INTEGER DEFAULT 0'),
|
||||
('img_count', 'INTEGER DEFAULT 0'),
|
||||
('quota_date', 'TEXT'),
|
||||
('chat_model', 'TEXT'),
|
||||
('img_model', 'TEXT'),
|
||||
('vip', 'INTEGER DEFAULT 0'),
|
||||
('last_checkin', 'TEXT'),
|
||||
('last_loyalty', 'INTEGER'),
|
||||
('admin', 'INTEGER DEFAULT 0'),
|
||||
('captcha_ok', 'INTEGER DEFAULT 0'),
|
||||
('banned', 'INTEGER DEFAULT 0'),
|
||||
('week_model', 'TEXT'),
|
||||
('week_key', 'TEXT'),
|
||||
('last_active', 'INTEGER'),
|
||||
('warned_at', 'INTEGER'),
|
||||
('ref_credit', 'INTEGER DEFAULT 0'),
|
||||
('key_locked', 'INTEGER DEFAULT 0'),
|
||||
('rep', 'INTEGER DEFAULT 0'),
|
||||
('quiz_last', 'INTEGER DEFAULT 0'),
|
||||
('dice_last', 'INTEGER DEFAULT 0'),
|
||||
('last_bonus_lvl', 'INTEGER DEFAULT 0'),
|
||||
('rep_last', 'INTEGER'),
|
||||
('badge_lock', 'INTEGER DEFAULT 0'),
|
||||
('last_bonus_ts', 'INTEGER'),
|
||||
('rank_cache', 'INTEGER DEFAULT 0'),
|
||||
('ref_notify', 'INTEGER DEFAULT 1'),
|
||||
('vid_model', 'TEXT'),
|
||||
('mus_model', 'TEXT'),
|
||||
('sub_penalized', 'INTEGER DEFAULT 0'),
|
||||
('rep_give_day', 'TEXT'),
|
||||
('rep_give_n', 'INTEGER DEFAULT 0'),
|
||||
('api_blocked', 'INTEGER DEFAULT 0'),
|
||||
('api_block_reason', 'TEXT'),
|
||||
('gate_member_ok', 'INTEGER'),
|
||||
('gate_member_ts', 'INTEGER DEFAULT 0'),
|
||||
('gate_warned_at', 'INTEGER DEFAULT 0'),
|
||||
('agent_model', 'TEXT'),
|
||||
('effort', "TEXT DEFAULT ''"),
|
||||
('prompt_on', 'INTEGER DEFAULT 0'),
|
||||
('badge_until', 'INTEGER DEFAULT 0'))
|
||||
|
||||
GROUP_LOG_INDEXES = {
|
||||
"idx_group_log_uid_ts": ("uid", "ts"),
|
||||
"idx_group_log_chat_ts_uid": ("chat_id", "ts", "uid"),
|
||||
"idx_group_log_ts": ("ts",),
|
||||
}
|
||||
|
||||
|
||||
class BotSchemaError(RuntimeError):
|
||||
"""Startup cannot safely continue with an incompatible bot schema."""
|
||||
|
||||
|
||||
def _columns(con, table):
|
||||
return {row[1]: row for row in con.execute(f'PRAGMA table_info("{table}")')}
|
||||
|
||||
|
||||
def _initial_schema(con):
|
||||
for ddl in TABLE_DDL:
|
||||
con.execute(ddl)
|
||||
columns = _columns(con, "users")
|
||||
for name, ddl in USER_COLUMNS:
|
||||
if name not in columns:
|
||||
con.execute(f'ALTER TABLE users ADD COLUMN "{name}" {ddl}')
|
||||
|
||||
|
||||
def _activity_indexes(con):
|
||||
for name, columns in GROUP_LOG_INDEXES.items():
|
||||
con.execute(f'CREATE INDEX IF NOT EXISTS "{name}" ON group_log ({", ".join(columns)})')
|
||||
|
||||
|
||||
def _validate(con):
|
||||
expected = {
|
||||
"users": {"tg_id", "username", "token_name", "api_key", "created", "notified"}
|
||||
| {name for name, _ in USER_COLUMNS},
|
||||
"group_log": {"chat_id", "uid", "username", "text", "ts"},
|
||||
"sticker_cache": {"file_id", "emoji", "set_name", "added"},
|
||||
"video_tasks": {"tid", "uid", "chat_id", "message_id", "prompt", "key", "ts"},
|
||||
}
|
||||
for table, required in expected.items():
|
||||
columns = _columns(con, table)
|
||||
if required - columns.keys():
|
||||
raise BotSchemaError(f"incomplete bot table: {table}")
|
||||
if table == "users" and (columns["tg_id"][2].upper() != "INTEGER" or columns["tg_id"][5] != 1):
|
||||
raise BotSchemaError("users.tg_id must remain an INTEGER PRIMARY KEY")
|
||||
indexes = {row[1] for row in con.execute('PRAGMA index_list("group_log")')}
|
||||
for name, expected_columns in GROUP_LOG_INDEXES.items():
|
||||
if name not in indexes:
|
||||
raise BotSchemaError(f"missing bot activity index: {name}")
|
||||
actual = tuple(row[2] for row in con.execute(f'PRAGMA index_info("{name}")'))
|
||||
if actual != expected_columns:
|
||||
raise BotSchemaError(f"incompatible bot activity index: {name}")
|
||||
|
||||
|
||||
def migrate_bot_schema(con):
|
||||
"""Apply all pending bot migrations atomically, or fail startup explicitly.
|
||||
|
||||
The caller owns the connection, not an active transaction. A legacy v0 DB is
|
||||
adopted by introspecting columns; duplicate columns are not exception flow.
|
||||
Future schema versions are refused rather than silently downgraded.
|
||||
"""
|
||||
if con.in_transaction:
|
||||
raise BotSchemaError("bot migration requires a connection outside a transaction")
|
||||
step = 0
|
||||
try:
|
||||
con.execute("BEGIN IMMEDIATE")
|
||||
# Inspect under the same write lock as DDL: another starter may have
|
||||
# migrated the file while this connection was waiting for admission.
|
||||
current = con.execute("PRAGMA user_version").fetchone()[0]
|
||||
if not 0 <= current <= SCHEMA_VERSION:
|
||||
raise BotSchemaError(f"unsupported bot schema version: {current}")
|
||||
for version, migrate in ((1, _initial_schema), (2, _activity_indexes)):
|
||||
if current < version:
|
||||
step = version
|
||||
migrate(con)
|
||||
con.execute(f"PRAGMA user_version={version}")
|
||||
_validate(con)
|
||||
con.commit()
|
||||
except BaseException as exc:
|
||||
if con.in_transaction:
|
||||
con.rollback()
|
||||
if isinstance(exc, sqlite3.Error):
|
||||
raise BotSchemaError(f"bot schema migration v{step} failed ({type(exc).__name__})") from exc
|
||||
raise
|
||||
return SCHEMA_VERSION
|
||||
|
||||
|
||||
def initialize_bot_db(path):
|
||||
"""Initialize only the bot-owned DB; keep its existing journal and timeout."""
|
||||
con = sqlite3.connect(path, timeout=30)
|
||||
try:
|
||||
migrate_bot_schema(con)
|
||||
# Cleanup remains best-effort, unlike a required schema migration.
|
||||
try:
|
||||
with con:
|
||||
con.execute("DELETE FROM group_log WHERE ts < ?", (int(time.time()) - 30 * 86400,))
|
||||
except sqlite3.Error as exc:
|
||||
logging.getLogger(__name__).warning(
|
||||
"bot log retention skipped (%s)", type(exc).__name__)
|
||||
finally:
|
||||
con.close()
|
||||
@@ -0,0 +1,368 @@
|
||||
"""Bot-only admission integration. No provider credentials, billing or content rewriting."""
|
||||
from __future__ import annotations
|
||||
|
||||
import asyncio
|
||||
from collections import OrderedDict
|
||||
from concurrent.futures import ThreadPoolExecutor
|
||||
from contextlib import closing
|
||||
from contextvars import ContextVar
|
||||
import contextvars
|
||||
from dataclasses import dataclass
|
||||
from functools import partial, wraps
|
||||
import inspect
|
||||
import logging
|
||||
from pathlib import Path
|
||||
import sqlite3
|
||||
import threading
|
||||
import time
|
||||
|
||||
from request_stability import DeadlineExceeded, QueueFull, StabilityController
|
||||
|
||||
log = logging.getLogger("bot-stability")
|
||||
WAIT_MODES = (60, 180, 360)
|
||||
|
||||
|
||||
@dataclass(frozen=True)
|
||||
class RequestPolicy:
|
||||
user_id: int = 0
|
||||
priority: int = 0
|
||||
wait_seconds: int = 180
|
||||
|
||||
|
||||
POLICY = ContextVar("iishko_stability_policy", default=RequestPolicy())
|
||||
_DEADLINE = ContextVar("iishko_stability_deadline", default=None)
|
||||
|
||||
class GenerationError(RuntimeError):
|
||||
terminal = True
|
||||
stability_code: str | None = None
|
||||
|
||||
def __init__(self, message, *, status=None, retry_safe=False, ambiguous=False):
|
||||
super().__init__(message)
|
||||
self.status = self.upstream_status = status
|
||||
self.retry_safe = retry_safe
|
||||
self.ambiguous = ambiguous
|
||||
self.dependency_failure = status is None or status in (429, 500, 502, 503, 504)
|
||||
self.stability_dependency_failure = self.dependency_failure
|
||||
|
||||
|
||||
class PartialReply(str):
|
||||
"""Raw content is unchanged; callers keep the incomplete marker when rendering."""
|
||||
incomplete = True
|
||||
stability_partial = True
|
||||
|
||||
|
||||
def generation_error(message, *, status=None, retry_safe=False, ambiguous=False):
|
||||
"""Typed transport evidence; never infer safety from provider text."""
|
||||
return GenerationError(message, status=status, retry_safe=retry_safe, ambiguous=ambiguous)
|
||||
|
||||
|
||||
|
||||
class WaitPreferences:
|
||||
"""A separate short-transaction preference store; never writes billing/bot DBs."""
|
||||
|
||||
def __init__(self, path):
|
||||
self.path = Path(path)
|
||||
self.cache = OrderedDict()
|
||||
self._lock = threading.RLock()
|
||||
|
||||
def get(self, uid):
|
||||
with self._lock:
|
||||
return self._get(uid)
|
||||
|
||||
def _get(self, uid):
|
||||
now = time.monotonic()
|
||||
cached = self.cache.get(uid)
|
||||
if cached and now - cached[1] < 30:
|
||||
self.cache.move_to_end(uid)
|
||||
return cached[0]
|
||||
value = 180
|
||||
if self.path.exists():
|
||||
uri = self.path.resolve().as_uri() + "?mode=ro"
|
||||
with closing(sqlite3.connect(uri, uri=True, timeout=0.15)) as con:
|
||||
row = con.execute("SELECT seconds FROM wait_preferences WHERE uid=?", (int(uid),)).fetchone()
|
||||
if row and row[0] in WAIT_MODES:
|
||||
value = row[0]
|
||||
self._remember(uid, value)
|
||||
return value
|
||||
|
||||
def _remember(self, uid, seconds):
|
||||
self.cache[uid] = (seconds, time.monotonic())
|
||||
self.cache.move_to_end(uid)
|
||||
while len(self.cache) > 4096:
|
||||
self.cache.popitem(last=False)
|
||||
|
||||
def set(self, uid, seconds):
|
||||
with self._lock:
|
||||
return self._set(uid, seconds)
|
||||
|
||||
def _set(self, uid, seconds):
|
||||
if isinstance(seconds, bool) or seconds not in WAIT_MODES:
|
||||
raise ValueError("unsupported wait mode")
|
||||
with closing(sqlite3.connect(str(self.path), timeout=0.15)) as con:
|
||||
with con:
|
||||
con.execute("CREATE TABLE IF NOT EXISTS wait_preferences(uid INTEGER PRIMARY KEY, seconds INTEGER NOT NULL)")
|
||||
con.execute("INSERT INTO wait_preferences(uid,seconds) VALUES(?,?) "
|
||||
"ON CONFLICT(uid) DO UPDATE SET seconds=excluded.seconds", (int(uid), seconds))
|
||||
actual = con.execute("SELECT seconds FROM wait_preferences WHERE uid=?", (int(uid),)).fetchone()[0]
|
||||
if actual != seconds:
|
||||
raise RuntimeError("wait preference not persisted")
|
||||
self._remember(uid, seconds)
|
||||
|
||||
|
||||
class BotStability:
|
||||
def __init__(self, namespace, controller=None, preferences=None):
|
||||
self.ns = namespace
|
||||
self.controller = controller or StabilityController()
|
||||
self.preferences = preferences or WaitPreferences(Path(namespace["BOT_DB"]).with_name("request-stability.db"))
|
||||
self.installed = False
|
||||
self._rank_cache = OrderedDict()
|
||||
self._rank_lock = threading.Lock()
|
||||
self._cleanup_tasks = set()
|
||||
self._cap_pending = set()
|
||||
# Cap transactions may wait out a short writer lock; the shared default
|
||||
# executor also serves per-event middleware and must not be starved here.
|
||||
self._cap_executor = ThreadPoolExecutor(max_workers=4, thread_name_prefix="iishko-cap")
|
||||
|
||||
async def _cap_operation(self, fn, *args):
|
||||
context = contextvars.copy_context()
|
||||
return await asyncio.get_running_loop().run_in_executor(
|
||||
self._cap_executor, partial(context.run, fn, *args))
|
||||
|
||||
def policy_for(self, uid):
|
||||
# Priority changes scheduling only. Existing handlers remain the access authority.
|
||||
now = time.monotonic()
|
||||
with self._rank_lock:
|
||||
cached = self._rank_cache.get(uid)
|
||||
if cached and now - cached[1] < 30:
|
||||
self._rank_cache.move_to_end(uid)
|
||||
rank = cached[0]
|
||||
else:
|
||||
rank = None
|
||||
if rank is None:
|
||||
rank = int(self.ns["tier_of"](uid))
|
||||
with self._rank_lock:
|
||||
self._rank_cache[uid] = (rank, time.monotonic())
|
||||
self._rank_cache.move_to_end(uid)
|
||||
while len(self._rank_cache) > 4096:
|
||||
self._rank_cache.popitem(last=False)
|
||||
return RequestPolicy(int(uid), max(0, min(3, rank - 1)), self.preferences.get(uid))
|
||||
|
||||
async def middleware(self, handler, event, data):
|
||||
policy = RequestPolicy()
|
||||
user = getattr(event, "from_user", None)
|
||||
if user is not None:
|
||||
try:
|
||||
policy = await asyncio.to_thread(self.policy_for, user.id)
|
||||
except Exception as exc:
|
||||
log.warning("request preference/rank unavailable (%s); using lowest priority", type(exc).__name__)
|
||||
policy = RequestPolicy(int(user.id))
|
||||
token = POLICY.set(policy)
|
||||
try:
|
||||
return await handler(event, data)
|
||||
finally:
|
||||
POLICY.reset(token)
|
||||
|
||||
def _cleanup(self, coro):
|
||||
task = asyncio.create_task(coro)
|
||||
self._cleanup_tasks.add(task)
|
||||
def done(finished):
|
||||
self._cleanup_tasks.discard(finished)
|
||||
try:
|
||||
finished.result()
|
||||
except BaseException as exc:
|
||||
log.error("premium cap cleanup failed (%s)", type(exc).__name__)
|
||||
task.add_done_callback(done)
|
||||
|
||||
async def _refund_cap(self, pending):
|
||||
try:
|
||||
receipt = await pending
|
||||
if receipt[0] and receipt[3] is not None:
|
||||
await self._cap_operation(self.ns["pm_cap_release"], receipt[3])
|
||||
finally:
|
||||
self._cap_pending.discard(pending)
|
||||
|
||||
async def _take_cap(self, uid, model):
|
||||
reserve, release = self.ns.get("pm_cap_reserve"), self.ns.get("pm_cap_release")
|
||||
if callable(reserve) and callable(release):
|
||||
if len(self._cap_pending) >= self.controller.global_limit:
|
||||
raise QueueFull()
|
||||
pending = asyncio.create_task(self._cap_operation(reserve, uid, model))
|
||||
self._cap_pending.add(pending)
|
||||
try:
|
||||
receipt = await asyncio.shield(pending)
|
||||
except BaseException:
|
||||
# Cancelling to_thread cannot cancel its transaction. Refund only
|
||||
# that attempt when the worker eventually returns its receipt.
|
||||
self._cleanup(self._refund_cap(pending))
|
||||
raise
|
||||
self._cap_pending.discard(pending)
|
||||
return receipt
|
||||
take = self.ns.get("pm_cap_take")
|
||||
if callable(take):
|
||||
return (*await asyncio.to_thread(take, uid, model), None)
|
||||
return True, 0, 0, None
|
||||
|
||||
def wrap(self, fn, kind):
|
||||
signature = inspect.signature(fn)
|
||||
|
||||
@wraps(fn)
|
||||
async def guarded(*args, **kwargs):
|
||||
bound = signature.bind(*args, **kwargs)
|
||||
bound.apply_defaults()
|
||||
if kind == "call" and bound.arguments.get("path") not in ("/chat/completions", "/responses"):
|
||||
return await fn(*args, **kwargs)
|
||||
payload = bound.arguments.get("payload") or {}
|
||||
model = bound.arguments.get("model") or payload.get("model")
|
||||
if not isinstance(model, str) or not model:
|
||||
raise generation_error("Для запроса не выбрана модель.", status=400)
|
||||
cap_model = model
|
||||
if callable(self.ns.get("_alias")):
|
||||
model = self.ns["_alias"](model)
|
||||
policy = POLICY.get()
|
||||
task = asyncio.current_task()
|
||||
inherited = _DEADLINE.get()
|
||||
nested = inherited is not None and inherited[0] is task
|
||||
deadline = inherited[1] if nested else time.monotonic() + policy.wait_seconds
|
||||
supplied_deadline = bound.arguments.get("_deadline")
|
||||
if supplied_deadline is not None:
|
||||
deadline = min(deadline, supplied_deadline)
|
||||
token = _DEADLINE.set((task, deadline))
|
||||
|
||||
async def invoke():
|
||||
remaining = deadline - time.monotonic()
|
||||
if remaining <= 0:
|
||||
raise DeadlineExceeded()
|
||||
receipt = None
|
||||
dispatched = False
|
||||
try:
|
||||
# The legacy caller used to spend this cap before waiting.
|
||||
# Rejected/expired queue entries must not consume model caps.
|
||||
if kind == "stream" and not nested and policy.user_id:
|
||||
receipt = await self._take_cap(policy.user_id, cap_model)
|
||||
ok, used, limit = receipt[:3]
|
||||
if not ok:
|
||||
exc = GenerationError(f"Дневной лимит модели исчерпан ({used}/{limit}). "
|
||||
"Обновится в 00:00 МСК. Выбор модели: /model",
|
||||
status=400)
|
||||
exc.stability_code = "model_daily_limit"
|
||||
raise exc
|
||||
remaining = deadline - time.monotonic()
|
||||
if remaining <= 0:
|
||||
raise DeadlineExceeded()
|
||||
if "t" in signature.parameters:
|
||||
bound.arguments["t"] = (min(bound.arguments["t"], remaining)
|
||||
if kind == "call" else remaining)
|
||||
if "_deadline" in signature.parameters:
|
||||
bound.arguments["_deadline"] = deadline
|
||||
dispatched = True
|
||||
return await fn(*bound.args, **bound.kwargs)
|
||||
except Exception as exc:
|
||||
# Prevent legacy callers from initiating another paid fallback.
|
||||
try:
|
||||
setattr(exc, "terminal", True)
|
||||
except (AttributeError, TypeError):
|
||||
pass
|
||||
raise
|
||||
finally:
|
||||
if receipt and receipt[0] and receipt[3] is not None and not dispatched:
|
||||
async def refund():
|
||||
await self._cap_operation(self.ns["pm_cap_release"], receipt[3])
|
||||
self._cleanup(refund())
|
||||
|
||||
try:
|
||||
remaining = deadline - time.monotonic()
|
||||
if remaining <= 0:
|
||||
raise DeadlineExceeded()
|
||||
return await self.controller.run(model, invoke, user_id=policy.user_id,
|
||||
priority=policy.priority, timeout=remaining)
|
||||
finally:
|
||||
_DEADLINE.reset(token)
|
||||
return guarded
|
||||
|
||||
def install_wrappers(self):
|
||||
if self.installed:
|
||||
return
|
||||
for name, kind in (("gw_chat_stream", "stream"), ("gw_call", "call"),
|
||||
("gw_chat", "chat"), ("gw_chat_tools", "tools")):
|
||||
if callable(self.ns.get(name)):
|
||||
self.ns[name] = self.wrap(self.ns[name], kind)
|
||||
self.installed = True
|
||||
|
||||
async def telemetry_worker(self):
|
||||
while True:
|
||||
try:
|
||||
snapshot = self.controller.snapshot()
|
||||
log.info("request_stability active=%d queued=%d models=%d limits=%s outcomes=%s rejects=%s",
|
||||
snapshot["active"], snapshot["queued"], snapshot["model_count"],
|
||||
snapshot["limits"], snapshot["outcomes"], snapshot["rejects"])
|
||||
except Exception as exc:
|
||||
log.error("request stability telemetry failed (%s)", type(exc).__name__)
|
||||
await asyncio.sleep(60)
|
||||
|
||||
def text(self, policy):
|
||||
snapshot = self.controller.snapshot()
|
||||
return ("Стабильность запросов\n\n"
|
||||
f"Общий бюджет ожидания: {policy.wait_seconds} с (очередь + генерация + инструменты).\n"
|
||||
f"Приоритет ранга: {policy.priority + 1}/4. Ожидающие запросы постепенно получают приоритет.\n"
|
||||
f"В работе: {snapshot.get('active', 0)} · в очереди: {snapshot.get('queued', 0)}.\n"
|
||||
"Не больше 1 одновременного запроса на пользователя. "
|
||||
"Перегрузка одной модели не блокирует остальные.\n"
|
||||
"После начала ответа запрос не запускается заново. "
|
||||
"Выбор ожидания не меняет модель, ранг, цену и лимит запросов.")
|
||||
|
||||
def register(self, router):
|
||||
from aiogram import F
|
||||
from aiogram.filters import Command
|
||||
from aiogram.types import InlineKeyboardButton, InlineKeyboardMarkup
|
||||
|
||||
def keyboard(seconds):
|
||||
return InlineKeyboardMarkup(inline_keyboard=[[
|
||||
InlineKeyboardButton(text=f"{s} с" + (" ✓" if s == seconds else ""),
|
||||
callback_data=f"stability_wait:{s}") for s in WAIT_MODES]])
|
||||
|
||||
async def command(message):
|
||||
if not message.from_user:
|
||||
return
|
||||
try:
|
||||
policy = await asyncio.to_thread(self.policy_for, message.from_user.id)
|
||||
except Exception:
|
||||
await message.answer("Настройки временно недоступны. Попробуй позже.", parse_mode=None)
|
||||
return
|
||||
await message.answer(self.text(policy), reply_markup=keyboard(policy.wait_seconds), parse_mode=None)
|
||||
|
||||
async def callback(query):
|
||||
if not query.from_user or not query.message:
|
||||
return
|
||||
# Do not let another group member change someone else's preference panel.
|
||||
chat = query.message.chat
|
||||
if chat.type != "private":
|
||||
await query.answer("Настрой ожидание в личном чате: /stability", show_alert=True)
|
||||
return
|
||||
try:
|
||||
seconds = int(query.data.split(":", 1)[1])
|
||||
if seconds not in WAIT_MODES:
|
||||
raise ValueError("invalid wait")
|
||||
await asyncio.to_thread(self.preferences.set, query.from_user.id, seconds)
|
||||
except (ValueError, sqlite3.Error, RuntimeError, OSError):
|
||||
await query.answer("Не удалось сохранить ожидание. Попробуй позже.", show_alert=True)
|
||||
return
|
||||
await query.answer(f"Общий бюджет: {seconds} с")
|
||||
policy = await asyncio.to_thread(self.policy_for, query.from_user.id)
|
||||
await query.message.edit_text(self.text(policy), reply_markup=keyboard(seconds), parse_mode=None)
|
||||
|
||||
router.message.middleware(self.middleware)
|
||||
router.callback_query.middleware(self.middleware)
|
||||
router.inline_query.middleware(self.middleware)
|
||||
router.message.register(command, Command(commands=["stability", "wait"]))
|
||||
router.callback_query.register(callback, F.data.startswith("stability_wait:"))
|
||||
|
||||
|
||||
def install(namespace, router):
|
||||
existing = namespace.get("_STABILITY_GATE")
|
||||
if existing is not None:
|
||||
return existing
|
||||
gate = BotStability(namespace)
|
||||
gate.install_wrappers()
|
||||
gate.register(router)
|
||||
namespace["_STABILITY_GATE"] = gate
|
||||
return gate
|
||||
+1030
File diff suppressed because it is too large
Load Diff
@@ -0,0 +1,150 @@
|
||||
"""Pure Telegram bounty parsing/rendering; no database, network or money mutations."""
|
||||
from decimal import Decimal
|
||||
import html
|
||||
import re
|
||||
import time
|
||||
|
||||
QUOTA_PER_USD = 500_000
|
||||
HELP = (
|
||||
"Создать: <code>/bounty описание $10 slots=3 ttl=7d work=48h</code>\n"
|
||||
"slots — число выполнений (1–100), ttl — общий срок (до 90d), "
|
||||
"work — срок одного исполнения (до 30d). По умолчанию: 1, 7d, 48h.\n"
|
||||
"Пополнить: <code>/btopup ID число</code>. Сдать: <code>/bdone ID пруф</code>.\n"
|
||||
"Выплата после принятия работы; комиссия 5%. Просроченный исполнитель повторно не берёт это баунти."
|
||||
)
|
||||
STATUSES = {"open": "открыто", "claimed": "в работе", "submitted": "на проверке",
|
||||
"disputed": "спор", "paid": "оплачено", "done": "выполнено",
|
||||
"cancelled": "отменено", "expired": "истекло", "refund_pending": "возврат удерживается",
|
||||
"legacy_review": "историческое эскроу: нужна проверка", "escrow_review": "эскроу: нужна проверка"}
|
||||
|
||||
|
||||
def escaped(value, limit=400):
|
||||
"""Bound escaped HTML, without splitting entities or accepting markup."""
|
||||
parts, size = [], 0
|
||||
for char in str(value or ""):
|
||||
part = html.escape(char)
|
||||
if size + len(part) > limit - 3:
|
||||
return "".join(parts) + "..."
|
||||
parts.append(part)
|
||||
size += len(part)
|
||||
return "".join(parts)
|
||||
|
||||
|
||||
def money(units):
|
||||
return format(Decimal(int(units or 0)) / QUOTA_PER_USD, ".2f")
|
||||
|
||||
|
||||
def deadline(value):
|
||||
return time.strftime("%d.%m %H:%M", time.gmtime(int(value) + 10800)) + " МСК" if value else "на проверке"
|
||||
|
||||
|
||||
def parse_create(text):
|
||||
"""Keep legacy '/bounty text $N', add bounded slots/ttl/work options."""
|
||||
body = str(text or "").split(maxsplit=1)
|
||||
if len(body) < 2 or re.fullmatch(r"[0-9]+", body[1]):
|
||||
return None
|
||||
body = body[1]
|
||||
options = {"slots": 1, "ttl": 7 * 86400, "claim_ttl": 48 * 3600}
|
||||
seen = set()
|
||||
def option(match):
|
||||
name, value = match.group(1), match.group(2)
|
||||
if name in seen:
|
||||
raise ValueError("Параметр повторяется: " + name)
|
||||
seen.add(name)
|
||||
if name == "slots":
|
||||
if not re.fullmatch(r"[1-9][0-9]*", value) or not 1 <= int(value) <= 100:
|
||||
raise ValueError("slots: целое число от 1 до 100")
|
||||
options["slots"] = int(value)
|
||||
else:
|
||||
duration = re.fullmatch(r"([1-9][0-9]*)([hd])", value)
|
||||
if duration is None:
|
||||
raise ValueError(name + ": укажи целые часы h или дни d")
|
||||
seconds = int(duration[1]) * (3600 if duration[2] == "h" else 86400)
|
||||
if seconds > (90 if name == "ttl" else 30) * 86400:
|
||||
raise ValueError("Срок слишком велик: " + name)
|
||||
options["ttl" if name == "ttl" else "claim_ttl"] = seconds
|
||||
return ""
|
||||
body = re.sub(r"(?<!\S)(slots|ttl|work)=([^\s]+)", option, body).strip()
|
||||
reward = re.search(r"\$([0-9]+(?:\.[0-9]{1,2})?)\s*$", body)
|
||||
if reward is None:
|
||||
raise ValueError("Нужны описание и цена за одно выполнение, например: /bounty сделать пост $10")
|
||||
description = body[:reward.start()].strip()
|
||||
amount = Decimal(reward[1])
|
||||
if not description or len(description) > 2000 or amount < 1:
|
||||
raise ValueError("Описание: 1–2000 символов, цена одного выполнения — минимум $1")
|
||||
units = int(amount * QUOTA_PER_USD)
|
||||
if units * options["slots"] > (1 << 63) - 1:
|
||||
raise ValueError("Сумма слишком велика")
|
||||
return dict(text=description, reward=units, **options)
|
||||
|
||||
|
||||
def render_list(data, viewer):
|
||||
page, pages = int(data.get("page", 0)), max(1, int(data.get("pages", 0)))
|
||||
lines = ["<b>Баунти</b> · страница %d/%d" % (page + 1, pages)]
|
||||
rows = []
|
||||
for item in data.get("items", []):
|
||||
lines.append("\n<b>#%d</b> %s\n$%s за выполнение · свободно %d · оплачено %d/%d\n%s" % (
|
||||
item["id"], escaped(item["text"], 180), money(item["unit_reward"]),
|
||||
item["available"], item["completed"], item["capacity"],
|
||||
escaped(STATUSES.get(item["status"], item["status"]), 100)))
|
||||
rows.append([("Открыть #%d" % item["id"], "bn:menu:%d" % item["id"])])
|
||||
if not data.get("items"):
|
||||
lines.append("\nБаунти пока нет.")
|
||||
nav = []
|
||||
if page:
|
||||
nav.append(("Назад", "bn:page:%d" % (page - 1)))
|
||||
if page + 1 < pages:
|
||||
nav.append(("Вперёд", "bn:page:%d" % (page + 1)))
|
||||
if nav:
|
||||
rows.append(nav)
|
||||
lines += ["\nЭскроу пополняется только подтверждёнными начислениями. Обычная API-квота не переводится.", "\n" + HELP]
|
||||
return "\n".join(lines), rows
|
||||
|
||||
|
||||
def render_detail(item, viewer, admin=False):
|
||||
bid = int(item["id"])
|
||||
owner = int(viewer) == int(item["creator"])
|
||||
attempts = item.get("assignments", [])
|
||||
lines = ["<b>Баунти #%d</b>" % bid, escaped(item["text"], 850),
|
||||
"$%s за выполнение · комиссия 5%%" % money(item["unit_reward"]),
|
||||
"Свободно: %d · в работе: %d · оплачено: %d/%d" % (item["available"], item["active"], item["completed"], item["capacity"]),
|
||||
"Общий срок: %s · на выполнение: %d ч" % (deadline(item["expires_at"]), int(item.get("claim_ttl") or 0) // 3600),
|
||||
"Статус: " + escaped(STATUSES.get(item["status"], item["status"]), 150)]
|
||||
rows = []
|
||||
held = item.get("legacy_review") or item.get("integrity_review")
|
||||
if held:
|
||||
lines.append("Средства сохранены в эскроу. Выплаты и возвраты — только после проверки происхождения; автосписания нет.")
|
||||
else:
|
||||
mine = next((a for a in attempts if a["worker"] == int(viewer)), None)
|
||||
if item["available"] and not owner and mine is None:
|
||||
rows.append([("Взять", "bn:claim:%d" % bid)])
|
||||
if mine:
|
||||
lines.append("Твоя попытка: %s · срок %s" % (escaped(STATUSES.get(mine["status"], mine["status"]), 80), deadline(mine["deadline"])))
|
||||
if mine["status"] == "claimed":
|
||||
lines.append("Сдать: <code>/bdone %d пруф</code>" % bid)
|
||||
if owner or admin:
|
||||
pending = [a for a in attempts if a["status"] in ("submitted", "disputed")]
|
||||
for attempt in pending[:10]:
|
||||
worker = int(attempt["worker"])
|
||||
lines.append("Работа u%d: %s" % (worker, STATUSES[attempt["status"]]))
|
||||
rows.append([("Пруф u%d" % worker, "bn:proof:%d:%d" % (bid, worker)),
|
||||
("Оплатить", "bn:ok:%d:%d" % (bid, worker)),
|
||||
("Спор", "bn:rej:%d:%d" % (bid, worker))])
|
||||
if len(pending) > 10:
|
||||
lines.append("Показаны первые 10 работ; следующие появятся после их проверки.")
|
||||
if owner and not item.get("closed_reason"):
|
||||
rows.append([("Закрыть", "bn:cancel:%d" % bid)])
|
||||
lines.append("Добавить выполнения: <code>/btopup %d число</code>" % bid)
|
||||
if item.get("refund_pending"):
|
||||
lines.append("Возврат $%s удерживается в эскроу до проверки ограничений/кошелька." % money(item["refund_pending"]))
|
||||
rows.append([("К списку", "bn:page:0")])
|
||||
return "\n".join(lines), rows
|
||||
|
||||
|
||||
def render_proof(item, viewer, worker, admin=False):
|
||||
if int(viewer) not in (int(item["creator"]), int(worker)) and not admin:
|
||||
raise ValueError("Пруф доступен только участникам работы")
|
||||
attempt = next((a for a in item.get("assignments", []) if a["worker"] == int(worker)), None)
|
||||
if attempt is None or "proof" not in attempt:
|
||||
raise ValueError("Пруф не найден или недоступен")
|
||||
return "<b>Баунти #%d · пруф u%d</b>\n%s" % (item["id"], worker, escaped(attempt["proof"], 3300))
|
||||
@@ -0,0 +1,146 @@
|
||||
import ast
|
||||
from contextlib import closing
|
||||
import os
|
||||
from pathlib import Path
|
||||
import sqlite3
|
||||
from threading import Lock
|
||||
import time
|
||||
|
||||
import gateway_commerce
|
||||
|
||||
_CACHE = {}
|
||||
_LOCK = Lock()
|
||||
_CONSTANTS = {'TIER_MODELS', 'IMG_MODELS', 'IMG_ALWAYS', 'VID_MODELS', 'MUS_MODELS',
|
||||
'MODEL_ALIASES', 'T4_ALIASES', 'MODEL_DESCS', 'BADGES', 'RANK_REFS',
|
||||
'BG_IMG_MODELS', 'REF_NEW_ID_MIN', 'PROMO_ACTIVE_UNTIL'}
|
||||
|
||||
|
||||
def _source():
|
||||
explicit = os.environ.get('IISHKO_BOT_SOURCE')
|
||||
if explicit:
|
||||
return Path(explicit)
|
||||
root = Path(os.environ.get('IISHKO_APP_ROOT', Path(__file__).resolve().parent))
|
||||
return root / 'grok_bot.py'
|
||||
|
||||
|
||||
def _literal(node, constants):
|
||||
if isinstance(node, ast.Name):
|
||||
if node.id not in constants:
|
||||
raise ValueError('unknown catalogue constant')
|
||||
return constants[node.id]
|
||||
if isinstance(node, ast.BinOp) and isinstance(node.op, ast.Add):
|
||||
left, right = _literal(node.left, constants), _literal(node.right, constants)
|
||||
if type(left) not in (list, tuple) or type(right) is not type(left):
|
||||
raise ValueError('invalid catalogue concatenation')
|
||||
return left + right
|
||||
return ast.literal_eval(node)
|
||||
|
||||
|
||||
def _catalogue():
|
||||
source = _source()
|
||||
stat = source.stat()
|
||||
key = (str(source.resolve()), stat.st_mtime_ns, stat.st_size)
|
||||
with _LOCK:
|
||||
if _CACHE.get('key') == key:
|
||||
return _CACHE['data']
|
||||
tree = ast.parse(source.read_text(encoding='utf-8'))
|
||||
result = {}
|
||||
for node in tree.body:
|
||||
if isinstance(node, ast.Assign):
|
||||
names = [target.id for target in node.targets
|
||||
if isinstance(target, ast.Name) and target.id in _CONSTANTS]
|
||||
if names:
|
||||
try:
|
||||
value = _literal(node.value, result)
|
||||
except (ValueError, TypeError):
|
||||
if any(name in {'TIER_MODELS', 'BADGES', 'RANK_REFS'} for name in names):
|
||||
raise
|
||||
continue
|
||||
for name in names:
|
||||
result[name] = value
|
||||
if not {'TIER_MODELS', 'BADGES', 'RANK_REFS'} <= result.keys():
|
||||
raise ValueError('trusted rank catalogue is unavailable')
|
||||
tiers = result['TIER_MODELS']
|
||||
if not isinstance(tiers, dict) or set(tiers) != {1, 2, 3, 4}:
|
||||
raise ValueError('invalid trusted rank catalogue')
|
||||
if any(not isinstance(models, (list, tuple)) or any(not isinstance(model, str) for model in models)
|
||||
for models in tiers.values()):
|
||||
raise ValueError('invalid trusted model catalogue')
|
||||
_CACHE.update(key=key, data=result)
|
||||
return result
|
||||
|
||||
|
||||
def _rank(con, uid, user, constants, now):
|
||||
env_admins = {int(value) for value in os.environ.get('IISHKO_ADMIN_IDS', '').split(',') if value.strip().isdigit()}
|
||||
if uid in env_admins or user.get('admin'):
|
||||
return 4
|
||||
days = max(0, (now - int(user.get('created') or 0)) // 86400) if user.get('created') else 0
|
||||
refs = con.execute('SELECT COALESCE(SUM(CASE WHEN tg_id>=? THEN 0.5 ELSE 1.0 END),0) '
|
||||
'FROM users WHERE referred_by=? AND ref_awarded=1',
|
||||
(constants.get('REF_NEW_ID_MIN', 9_000_000_000), uid)).fetchone()[0]
|
||||
rank = 1
|
||||
for level in (2, 3, 4):
|
||||
_, _, rep, age = constants['BADGES'][level]
|
||||
if days >= age and (refs >= constants['RANK_REFS'][level] or rep and (user.get('rep') or 0) >= rep):
|
||||
rank = level
|
||||
if rank < 2 and now < constants.get('PROMO_ACTIVE_UNTIL', 0):
|
||||
rank = 2
|
||||
floor, until = int(user.get('badge_lock') or 0), int(user.get('badge_until') or 0)
|
||||
if floor and (until == 0 or now < until):
|
||||
rank = max(rank, min(4, max(1, floor)))
|
||||
return rank
|
||||
|
||||
|
||||
def base_models(bot_db, uid):
|
||||
if type(uid) is not int or not 0 < uid <= 9223372036854775807:
|
||||
return []
|
||||
constants = _catalogue()
|
||||
uri = Path(bot_db).resolve().as_uri() + '?mode=ro'
|
||||
with closing(sqlite3.connect(uri, uri=True, timeout=8)) as con:
|
||||
con.row_factory = sqlite3.Row
|
||||
con.execute('PRAGMA query_only=ON')
|
||||
row = con.execute('SELECT * FROM users WHERE tg_id=?', (uid,)).fetchone()
|
||||
if row is None:
|
||||
return []
|
||||
user = dict(row)
|
||||
if user.get('banned') or user.get('api_blocked'):
|
||||
return []
|
||||
tier = _rank(con, uid, user, constants, int(time.time()))
|
||||
tiers = constants['TIER_MODELS']
|
||||
models = [model for level in range(1, tier + 1) for model in tiers[level]]
|
||||
images = list(constants.get('IMG_MODELS', ())) + list(constants.get('IMG_ALWAYS', ()))
|
||||
media = set(images + list(constants.get('VID_MODELS', ())) + list(constants.get('MUS_MODELS', ())))
|
||||
models += images
|
||||
for alias in constants.get('MODEL_ALIASES', ()):
|
||||
ranks = [level for level, names in tiers.items() if alias in names]
|
||||
if alias in media or ranks and min(ranks) <= tier:
|
||||
models.append(alias)
|
||||
if tier >= 4:
|
||||
models += list(constants.get('T4_ALIASES', ()))
|
||||
descriptions = constants.get('MODEL_DESCS', {})
|
||||
models += sorted({model.replace('.', '-') for model in models if '.' in model} & set(descriptions))
|
||||
return list(dict.fromkeys(models))
|
||||
|
||||
|
||||
def public_models():
|
||||
"""Current operator catalogue, independent of a user's rank or stale token."""
|
||||
constants = _catalogue()
|
||||
names = {name for models in constants['TIER_MODELS'].values() for name in models}
|
||||
for key in ('T4_ALIASES', 'IMG_MODELS', 'IMG_ALWAYS'):
|
||||
names.update(constants.get(key, ()))
|
||||
names.update(name.replace('.', '-') for name in tuple(names)
|
||||
if name.replace('.', '-') in constants.get('MODEL_DESCS', {}))
|
||||
return frozenset(names)
|
||||
|
||||
|
||||
def allowed(bot_db, uid, model, token_models, default_allowed):
|
||||
try:
|
||||
if model not in public_models():
|
||||
# Non-managed name: retain the existing token gate.
|
||||
return bool(default_allowed)
|
||||
# Managed catalogue model: re-derive from the authoritative rank catalogue
|
||||
# plus *active* passes. base_models/model_access read fresh state and raise
|
||||
# on any inconsistency, which the handler below turns into a rejection.
|
||||
return gateway_commerce.model_access(bot_db, uid, model, base_models(bot_db, uid))
|
||||
except (OSError, ValueError, TypeError, KeyError, sqlite3.Error, SyntaxError):
|
||||
return False
|
||||
@@ -0,0 +1,406 @@
|
||||
"""Private bug intake and moderated contributions; rewards are reputation only."""
|
||||
import hashlib
|
||||
import json
|
||||
import re
|
||||
import sqlite3
|
||||
import time
|
||||
from contextlib import closing
|
||||
from typing import NoReturn
|
||||
|
||||
ACTIVITY_CATEGORIES = ('creativity', 'docs', 'integration', 'tests')
|
||||
BUG_SEVERITIES = ('low', 'medium', 'high', 'critical')
|
||||
MAX_REWARD_REP = 40
|
||||
MAX_PENDING = 5
|
||||
DAILY_SUBMISSION_LIMIT = 10
|
||||
FEED_LIMIT = 50
|
||||
OWN_LIMIT = 100
|
||||
REVIEW_QUEUE_LIMIT = 100
|
||||
MAX_REQUEST_BYTES = 48_000
|
||||
TEXT_LIMITS = {
|
||||
'title': (5, 160),
|
||||
'description': (30, 6_000),
|
||||
'proof': (5, 2_000),
|
||||
'reason': (5, 1_000),
|
||||
}
|
||||
_ITEM_COLUMNS = ('id', 'kind', 'category', 'title', 'description', 'proof', 'status',
|
||||
'author_uid', 'reward_rep', 'created_at', 'review_reason')
|
||||
_SELECT_ITEMS = ','.join(_ITEM_COLUMNS)
|
||||
_REQUEST_ID = re.compile(r'[A-Za-z0-9:_-]{12,96}')
|
||||
# Reject common credential formats, not references to credentials or redacted examples.
|
||||
_SECRET = re.compile(
|
||||
r'-----BEGIN (?:[A-Z0-9 ]+ )?PRIVATE KEY-----'
|
||||
r'|\bBearer\s+(?!redacted\b)[A-Za-z0-9._~+/-]{12,}={0,2}'
|
||||
r'|\bsk-(?:proj-)?[A-Za-z0-9_-]{16,}'
|
||||
r'|\bgh[pousr]_[A-Za-z0-9]{20,}'
|
||||
r'|\bAIza[A-Za-z0-9_-]{30,}'
|
||||
r'|\b\d{6,12}:[A-Za-z0-9_-]{25,}'
|
||||
r'|\beyJ[A-Za-z0-9_-]{10,}\.eyJ[A-Za-z0-9_-]{10,}\.[A-Za-z0-9_-]{10,}'
|
||||
r'|\b(?:api[_ -]?key|access[_ -]?token|token|password|secret)\s*[=:]\s*'
|
||||
r'[\'\"]?(?!redacted\b)[A-Za-z0-9._~+/-]{16,}', re.IGNORECASE)
|
||||
|
||||
|
||||
class BoardError(ValueError):
|
||||
def __init__(self, status, code, message):
|
||||
super().__init__(message)
|
||||
self.status, self.code, self.message = status, code, message
|
||||
# Only a verified absent receipt plus successful rollback can set this true.
|
||||
self.operation_rejected = False
|
||||
|
||||
|
||||
def _fail(status, code, message) -> NoReturn:
|
||||
raise BoardError(status, code, message)
|
||||
|
||||
|
||||
def _connect(db):
|
||||
con = sqlite3.connect(str(db), timeout=10, isolation_level=None)
|
||||
con.row_factory = sqlite3.Row
|
||||
con.execute('PRAGMA foreign_keys=ON')
|
||||
return con
|
||||
|
||||
|
||||
def init_db(db):
|
||||
"""Create additive board tables; never create users or touch money/coin tables."""
|
||||
with closing(_connect(db)) as con:
|
||||
con.executescript('''
|
||||
CREATE TABLE IF NOT EXISTS community_board_submissions (
|
||||
id INTEGER PRIMARY KEY,
|
||||
author_uid INTEGER NOT NULL REFERENCES users(tg_id),
|
||||
kind TEXT NOT NULL CHECK(kind IN ('activity','bug')),
|
||||
category TEXT NOT NULL CHECK(
|
||||
(kind='activity' AND category IN ('creativity','docs','integration','tests')) OR
|
||||
(kind='bug' AND category IN ('low','medium','high','critical'))),
|
||||
title TEXT NOT NULL CHECK(length(title) BETWEEN 5 AND 160),
|
||||
description TEXT NOT NULL CHECK(length(description) BETWEEN 30 AND 6000),
|
||||
proof TEXT NOT NULL CHECK(length(proof) BETWEEN 5 AND 2000),
|
||||
status TEXT NOT NULL DEFAULT 'pending'
|
||||
CHECK(status IN ('pending','accepted','rejected','duplicate')),
|
||||
reward_rep INTEGER NOT NULL DEFAULT 0
|
||||
CHECK(typeof(reward_rep)='integer' AND reward_rep BETWEEN 0 AND 40),
|
||||
created_at INTEGER NOT NULL,
|
||||
reviewer_uid INTEGER REFERENCES users(tg_id),
|
||||
reviewed_at INTEGER,
|
||||
review_reason TEXT NOT NULL DEFAULT '',
|
||||
CHECK(reviewer_uid IS NULL OR reviewer_uid<>author_uid),
|
||||
CHECK(status='accepted' OR reward_rep=0),
|
||||
CHECK((status='pending' AND reviewer_uid IS NULL AND reviewed_at IS NULL
|
||||
AND review_reason='') OR
|
||||
(status<>'pending' AND reviewer_uid IS NOT NULL AND reviewed_at IS NOT NULL
|
||||
AND length(review_reason) BETWEEN 5 AND 1000)));
|
||||
CREATE TABLE IF NOT EXISTS community_board_reviews (
|
||||
id INTEGER PRIMARY KEY,
|
||||
submission_id INTEGER NOT NULL UNIQUE REFERENCES community_board_submissions(id),
|
||||
actor_uid INTEGER NOT NULL REFERENCES users(tg_id),
|
||||
author_uid INTEGER NOT NULL REFERENCES users(tg_id),
|
||||
decision TEXT NOT NULL CHECK(decision IN ('accepted','rejected','duplicate')),
|
||||
reward_rep INTEGER NOT NULL
|
||||
CHECK(typeof(reward_rep)='integer' AND reward_rep BETWEEN 0 AND 40),
|
||||
reason TEXT NOT NULL CHECK(length(reason) BETWEEN 5 AND 1000),
|
||||
request_id TEXT NOT NULL,
|
||||
digest TEXT NOT NULL,
|
||||
created_at INTEGER NOT NULL,
|
||||
UNIQUE(actor_uid,request_id),
|
||||
CHECK(actor_uid<>author_uid),
|
||||
CHECK(decision='accepted' OR reward_rep=0));
|
||||
CREATE TABLE IF NOT EXISTS community_board_operations (
|
||||
actor_uid INTEGER NOT NULL REFERENCES users(tg_id),
|
||||
request_id TEXT NOT NULL,
|
||||
digest TEXT NOT NULL,
|
||||
result TEXT NOT NULL,
|
||||
created_at INTEGER NOT NULL,
|
||||
PRIMARY KEY(actor_uid,request_id));
|
||||
CREATE INDEX IF NOT EXISTS community_board_author_status
|
||||
ON community_board_submissions(author_uid,status,created_at);
|
||||
CREATE INDEX IF NOT EXISTS community_board_public_feed
|
||||
ON community_board_submissions(kind,status,reviewed_at,id);
|
||||
CREATE INDEX IF NOT EXISTS community_board_pending
|
||||
ON community_board_submissions(status,id);
|
||||
CREATE TRIGGER IF NOT EXISTS community_board_reviewed_immutable
|
||||
BEFORE UPDATE ON community_board_submissions WHEN OLD.status<>'pending'
|
||||
BEGIN SELECT RAISE(ABORT,'reviewed submission is immutable'); END;
|
||||
CREATE TRIGGER IF NOT EXISTS community_board_submission_no_replace
|
||||
BEFORE INSERT ON community_board_submissions
|
||||
WHEN EXISTS (SELECT 1 FROM community_board_submissions WHERE id=NEW.id)
|
||||
BEGIN SELECT RAISE(ABORT,'submission history is immutable'); END;
|
||||
CREATE TRIGGER IF NOT EXISTS community_board_no_submission_delete
|
||||
BEFORE DELETE ON community_board_submissions
|
||||
BEGIN SELECT RAISE(ABORT,'submission history is immutable'); END;
|
||||
CREATE TRIGGER IF NOT EXISTS community_board_audit_matches
|
||||
BEFORE INSERT ON community_board_reviews
|
||||
WHEN NOT EXISTS (
|
||||
SELECT 1 FROM community_board_submissions s
|
||||
WHERE s.id=NEW.submission_id AND s.author_uid=NEW.author_uid
|
||||
AND s.reviewer_uid=NEW.actor_uid AND s.status=NEW.decision
|
||||
AND s.reward_rep=NEW.reward_rep AND s.review_reason=NEW.reason
|
||||
AND s.reviewed_at=NEW.created_at)
|
||||
BEGIN SELECT RAISE(ABORT,'audit does not match submission'); END;
|
||||
CREATE TRIGGER IF NOT EXISTS community_board_audit_no_update
|
||||
BEFORE UPDATE ON community_board_reviews
|
||||
BEGIN SELECT RAISE(ABORT,'review audit is immutable'); END;
|
||||
CREATE TRIGGER IF NOT EXISTS community_board_audit_no_delete
|
||||
BEFORE DELETE ON community_board_reviews
|
||||
BEGIN SELECT RAISE(ABORT,'review audit is immutable'); END;
|
||||
CREATE TRIGGER IF NOT EXISTS community_board_audit_no_replace
|
||||
BEFORE INSERT ON community_board_reviews
|
||||
WHEN EXISTS (SELECT 1 FROM community_board_reviews
|
||||
WHERE id=NEW.id OR submission_id=NEW.submission_id OR
|
||||
(actor_uid=NEW.actor_uid AND request_id=NEW.request_id))
|
||||
BEGIN SELECT RAISE(ABORT,'review audit is immutable'); END;
|
||||
CREATE TRIGGER IF NOT EXISTS community_board_receipt_no_update
|
||||
BEFORE UPDATE ON community_board_operations
|
||||
BEGIN SELECT RAISE(ABORT,'operation receipt is immutable'); END;
|
||||
CREATE TRIGGER IF NOT EXISTS community_board_receipt_no_delete
|
||||
BEFORE DELETE ON community_board_operations
|
||||
BEGIN SELECT RAISE(ABORT,'operation receipt is immutable'); END;
|
||||
CREATE TRIGGER IF NOT EXISTS community_board_receipt_no_replace
|
||||
BEFORE INSERT ON community_board_operations
|
||||
WHEN EXISTS (SELECT 1 FROM community_board_operations
|
||||
WHERE actor_uid=NEW.actor_uid AND request_id=NEW.request_id)
|
||||
BEGIN SELECT RAISE(ABORT,'operation receipt is immutable'); END;
|
||||
''')
|
||||
|
||||
|
||||
def _int(value, name, minimum=1, maximum=2**53-1):
|
||||
if type(value) is not int or not minimum <= value <= maximum:
|
||||
_fail(400, 'invalid_' + name, 'Некорректное поле: ' + name)
|
||||
return value
|
||||
|
||||
|
||||
def _text(value, name):
|
||||
minimum, maximum = TEXT_LIMITS[name]
|
||||
if (not isinstance(value, str) or len(value) > maximum
|
||||
or not minimum <= len(value.strip()) <= maximum
|
||||
or any(ord(char) < 32 and char not in '\n\r\t' for char in value)):
|
||||
_fail(400, 'invalid_' + name, f'{name}: от {minimum} до {maximum} символов.')
|
||||
if _SECRET.search(value):
|
||||
_fail(400, 'secrets_not_allowed', 'Удали ключи, токены, пароли и персональные данные из доказательств.')
|
||||
return value.strip()
|
||||
|
||||
|
||||
def _user(con, uid):
|
||||
_int(uid, 'user')
|
||||
try:
|
||||
row = con.execute('SELECT banned,api_blocked,rep FROM users WHERE tg_id=?', (uid,)).fetchone()
|
||||
except sqlite3.OperationalError:
|
||||
_fail(503, 'board_unavailable', 'Не удалось безопасно проверить доступ к сообществу.')
|
||||
if row is None:
|
||||
_fail(403, 'not_registered', 'Сначала открой бота и зарегистрируйся через /start.')
|
||||
# NULL, unknown flag values and missing columns must never bypass an account block.
|
||||
if row['banned'] != 0 or row['api_blocked'] != 0:
|
||||
_fail(403, 'blocked', 'Доступ к сообществу ограничен.')
|
||||
if row['rep'] is not None and type(row['rep']) is not int:
|
||||
_fail(503, 'board_unavailable', 'Не удалось безопасно проверить репутацию.')
|
||||
return row
|
||||
|
||||
|
||||
def _is_admin(uid, admins):
|
||||
return any(type(admin) is int and admin == uid for admin in admins)
|
||||
|
||||
|
||||
def _rules():
|
||||
# Fresh containers avoid a direct caller changing the policy returned to later users.
|
||||
examples = [
|
||||
('activity', 'creativity', 'Творчество', 'Оригинальный полезный материал с исходником и разрешением на использование.', 1, 5),
|
||||
('activity', 'docs', 'Документация', 'Проверенная инструкция с воспроизводимым примером и исправлением конкретного пробела.', 2, 10),
|
||||
('activity', 'integration', 'Интеграция', 'Рабочая интеграция с исходником, инструкцией и подтверждением результата.', 5, 20),
|
||||
('activity', 'tests', 'Тестирование', 'Воспроизводимый тест, который выявляет регрессию и проверяет исправление.', 2, 15),
|
||||
('bug', 'low', 'Низкая', 'Небольшой воспроизводимый дефект без доступа к чужим данным.', 1, 5),
|
||||
('bug', 'medium', 'Средняя', 'Существенно нарушенный сценарий с ограниченным влиянием.', 5, 15),
|
||||
('bug', 'high', 'Высокая', 'Подтверждённое серьёзное нарушение доступа или целостности.', 15, 30),
|
||||
('bug', 'critical', 'Критическая', 'Подтверждённое системное нарушение безопасности с широким влиянием; только безопасная проверка.', 25, 40),
|
||||
]
|
||||
return {
|
||||
'summary': 'Репутация — за полезный принятый результат, не за число сообщений. '
|
||||
'Независимый администратор проверяет вклад и объясняет решение. '
|
||||
'Самопроверка, повторные награды и награды за дубликаты запрещены. '
|
||||
'Заявки об ошибках видны только автору и администрации. '
|
||||
'Денежные выплаты, монеты и API-кредит не обещаются и не начисляются.',
|
||||
'activity_categories': list(ACTIVITY_CATEGORIES),
|
||||
'bug_severities': list(BUG_SEVERITIES),
|
||||
'rubric': [dict(kind=kind, category=category, label=label, example=example,
|
||||
suggested_rep=[low, high])
|
||||
for kind, category, label, example, low, high in examples],
|
||||
'submission_guide': {
|
||||
'activity': 'Опиши полезный результат, что изменилось и как проверить; приложи исходник или доказательство.',
|
||||
'bug': 'category — severity. В description укажи окружение, воспроизводимые шаги, '
|
||||
'ожидаемый и фактический результат. В proof приложи безопасное доказательство '
|
||||
'или request_id проблемного API-запроса. Не продолжай опасную проверку.',
|
||||
'proof': 'Удали API-ключи, Authorization, токены, пароли и чужие персональные данные. '
|
||||
'Автоматическая проверка распознаёт не все секреты; отправляй только обезличенные данные.',
|
||||
},
|
||||
'reward_rep': {'min': 0, 'max': MAX_REWARD_REP, 'after_review_only': True,
|
||||
'automatic_for_messages': False},
|
||||
'cash_bounty': False,
|
||||
'limits': {'pending': MAX_PENDING, 'per_day': DAILY_SUBMISSION_LIMIT,
|
||||
'day_timezone': 'UTC', 'title': list(TEXT_LIMITS['title']),
|
||||
'description': list(TEXT_LIMITS['description']),
|
||||
'proof': list(TEXT_LIMITS['proof']), 'reason': list(TEXT_LIMITS['reason']),
|
||||
'feed': FEED_LIMIT, 'own_submissions': OWN_LIMIT,
|
||||
'review_queue': REVIEW_QUEUE_LIMIT},
|
||||
}
|
||||
|
||||
|
||||
def snapshot(db, uid, admins=()):
|
||||
"""Return raw JSON text, never HTML. The UI must escape every user text field."""
|
||||
with closing(_connect(db)) as con:
|
||||
con.execute('BEGIN')
|
||||
user = _user(con, uid)
|
||||
is_admin = _is_admin(uid, admins)
|
||||
activities = con.execute(
|
||||
'SELECT ' + _SELECT_ITEMS + ' FROM community_board_submissions '
|
||||
"WHERE kind='activity' AND status='accepted' ORDER BY reviewed_at DESC,id DESC LIMIT ?",
|
||||
(FEED_LIMIT,)).fetchall()
|
||||
own = con.execute(
|
||||
'SELECT ' + _SELECT_ITEMS + ' FROM community_board_submissions '
|
||||
'WHERE author_uid=? ORDER BY id DESC LIMIT ?', (uid, OWN_LIMIT)).fetchall()
|
||||
queue = []
|
||||
if is_admin:
|
||||
queue = con.execute(
|
||||
'SELECT ' + _SELECT_ITEMS + ' FROM community_board_submissions '
|
||||
"WHERE status='pending' ORDER BY id LIMIT ?", (REVIEW_QUEUE_LIMIT,)).fetchall()
|
||||
result = {'uid': uid, 'is_admin': is_admin,
|
||||
'activities': [dict(row) for row in activities],
|
||||
'own_submissions': [dict(row) for row in own],
|
||||
'review_queue': [dict(row) for row in queue],
|
||||
'rules': _rules(), 'reputation': user['rep'] or 0}
|
||||
con.commit()
|
||||
return result
|
||||
|
||||
|
||||
def _submit(con, uid, body, now):
|
||||
required = {'action', 'request_id', 'kind', 'category', 'title', 'description', 'proof'}
|
||||
if set(body) != required:
|
||||
_fail(400, 'invalid_body', 'Нужны только поля action, request_id, kind, category, title, description, proof.')
|
||||
kind, category = body.get('kind'), body.get('category')
|
||||
if kind not in ('activity', 'bug'):
|
||||
_fail(400, 'invalid_kind', 'kind: activity или bug.')
|
||||
categories = ACTIVITY_CATEGORIES if kind == 'activity' else BUG_SEVERITIES
|
||||
if category not in categories:
|
||||
_fail(400, 'invalid_category', 'Выбери допустимую категорию вклада или severity ошибки.')
|
||||
title = _text(body.get('title'), 'title')
|
||||
description = _text(body.get('description'), 'description')
|
||||
proof = _text(body.get('proof'), 'proof')
|
||||
pending = con.execute(
|
||||
"SELECT COUNT(*) FROM community_board_submissions WHERE author_uid=? AND status='pending'",
|
||||
(uid,)).fetchone()[0]
|
||||
if pending >= MAX_PENDING:
|
||||
_fail(409, 'pending_limit', 'Сначала дождись проверки текущих заявок: максимум 5 ожидающих.')
|
||||
day_start = now // 86_400 * 86_400
|
||||
submitted = con.execute(
|
||||
'SELECT COUNT(*) FROM community_board_submissions WHERE author_uid=? AND created_at>=? AND created_at<?',
|
||||
(uid, day_start, day_start + 86_400)).fetchone()[0]
|
||||
if submitted >= DAILY_SUBMISSION_LIMIT:
|
||||
_fail(429, 'submission_day_limit', 'Дневной лимит заявок исчерпан. Обновление в 00:00 UTC.')
|
||||
cur = con.execute(
|
||||
'INSERT INTO community_board_submissions(author_uid,kind,category,title,description,proof,created_at) '
|
||||
'VALUES(?,?,?,?,?,?,?)', (uid, kind, category, title, description, proof, now))
|
||||
if cur.lastrowid is None:
|
||||
raise RuntimeError('SQLite did not return a submission id')
|
||||
return {'ok': True, 'action': 'submit', 'id': cur.lastrowid, 'status': 'pending', 'reward_rep': 0}
|
||||
|
||||
|
||||
def _review(con, uid, body, admins, now, digest):
|
||||
if not _is_admin(uid, admins):
|
||||
_fail(403, 'admin_only', 'Проверять заявки может только администрация.')
|
||||
required = {'action', 'request_id', 'id', 'decision', 'reward_rep', 'reason'}
|
||||
if set(body) != required:
|
||||
_fail(400, 'invalid_body', 'Нужны только поля action, request_id, id, decision, reward_rep, reason.')
|
||||
submission_id = _int(body.get('id'), 'id')
|
||||
decision = body.get('decision')
|
||||
if decision not in ('accepted', 'rejected', 'duplicate'):
|
||||
_fail(400, 'invalid_decision', 'decision: accepted, rejected или duplicate.')
|
||||
reward = _int(body.get('reward_rep'), 'reward_rep', minimum=0, maximum=MAX_REWARD_REP)
|
||||
if decision != 'accepted' and reward != 0:
|
||||
_fail(400, 'invalid_reward_rep', 'Отклонённая заявка или дубликат не получает репутацию.')
|
||||
reason = _text(body.get('reason'), 'reason')
|
||||
row = con.execute('SELECT * FROM community_board_submissions WHERE id=?', (submission_id,)).fetchone()
|
||||
if row is None:
|
||||
_fail(404, 'submission_not_found', 'Заявка не найдена.')
|
||||
if row['author_uid'] == uid:
|
||||
_fail(403, 'self_review', 'Нельзя проверять собственную заявку или награждать себя.')
|
||||
if row['status'] != 'pending':
|
||||
_fail(409, 'already_reviewed', 'Заявка уже проверена; повторная награда запрещена.')
|
||||
# Read the author WITHOUT failing on a block: the admin's decision must not
|
||||
# reputation credit is gated on eligibility, so a blocked author's submission can
|
||||
# still be rejected/duplicated (or accepted with zero reward) to clear the review
|
||||
# queue, while reputation is never credited to a blocked account.
|
||||
author = con.execute('SELECT banned,api_blocked,rep FROM users WHERE tg_id=?',
|
||||
(row['author_uid'],)).fetchone()
|
||||
if author is None:
|
||||
_fail(404, 'author_not_found', 'Аккаунт автора не найден.')
|
||||
author_blocked = bool(author['banned']) or bool(author['api_blocked'])
|
||||
if decision == 'accepted' and reward and author_blocked:
|
||||
_fail(409, 'author_ineligible',
|
||||
'Автор заблокирован: репутацию нельзя начислить. Отклони, отметь дубликат '
|
||||
'или прими с нулевой наградой, чтобы заявка не осталась в очереди.')
|
||||
if (author['rep'] or 0) > 2**63 - 1 - reward:
|
||||
_fail(409, 'reputation_limit', 'Начисление превысит допустимый целочисленный предел репутации.')
|
||||
updated = con.execute(
|
||||
'UPDATE community_board_submissions SET status=?,reward_rep=?,reviewer_uid=?,reviewed_at=?,review_reason=? '
|
||||
"WHERE id=? AND status='pending'", (decision, reward, uid, now, reason, submission_id))
|
||||
if updated.rowcount != 1:
|
||||
_fail(409, 'already_reviewed', 'Заявка уже проверена; повторная награда запрещена.')
|
||||
if decision == 'accepted' and reward:
|
||||
changed = con.execute(
|
||||
'UPDATE users SET rep=COALESCE(rep,0)+? WHERE tg_id=? AND banned=0 AND api_blocked=0',
|
||||
(reward, row['author_uid']))
|
||||
if changed.rowcount != 1:
|
||||
_fail(409, 'author_ineligible', 'Автор заблокирован; награда не начислена.')
|
||||
con.execute(
|
||||
'INSERT INTO community_board_reviews(submission_id,actor_uid,author_uid,decision,reward_rep,reason,'
|
||||
'request_id,digest,created_at) VALUES(?,?,?,?,?,?,?,?,?)',
|
||||
(submission_id, uid, row['author_uid'], decision, reward, reason, body['request_id'], digest, now))
|
||||
return {'ok': True, 'action': 'review', 'id': submission_id, 'status': decision,
|
||||
'reward_rep': reward, 'author_uid': row['author_uid']}
|
||||
|
||||
|
||||
def act(db, uid, body, admins=()):
|
||||
"""Mutate once per (uid, request_id, exact JSON digest) in one SQLite transaction."""
|
||||
_int(uid, 'user')
|
||||
if not isinstance(body, dict):
|
||||
_fail(400, 'invalid_body', 'Ожидается JSON-объект.')
|
||||
request_id = body.get('request_id')
|
||||
if not isinstance(request_id, str) or _REQUEST_ID.fullmatch(request_id) is None:
|
||||
_fail(400, 'request_id_required', 'Нужен request_id: 12–96 символов A–Z, a–z, 0–9, :, _, -.')
|
||||
try:
|
||||
encoded = json.dumps(body, sort_keys=True, ensure_ascii=False, separators=(',', ':'),
|
||||
allow_nan=False).encode('utf-8')
|
||||
except (TypeError, ValueError, UnicodeError, RecursionError):
|
||||
_fail(400, 'invalid_body', 'Некорректный JSON-объект.')
|
||||
if len(encoded) > MAX_REQUEST_BYTES:
|
||||
_fail(400, 'invalid_body', 'Слишком большой JSON-объект.')
|
||||
digest = hashlib.sha256(encoded).hexdigest()
|
||||
with closing(_connect(db)) as con:
|
||||
receipt_absent = False
|
||||
try:
|
||||
con.execute('BEGIN IMMEDIATE')
|
||||
_user(con, uid)
|
||||
previous = con.execute(
|
||||
'SELECT digest,result FROM community_board_operations WHERE actor_uid=? AND request_id=?',
|
||||
(uid, request_id)).fetchone()
|
||||
if previous:
|
||||
if previous['digest'] != digest:
|
||||
_fail(409, 'request_conflict', 'request_id уже использован для другого тела запроса.')
|
||||
if body.get('action') == 'review' and not _is_admin(uid, admins):
|
||||
_fail(403, 'admin_only', 'Проверять заявки может только администрация.')
|
||||
con.rollback()
|
||||
return json.loads(previous['result'])
|
||||
receipt_absent = True
|
||||
now = int(time.time())
|
||||
action = body.get('action')
|
||||
if action == 'submit':
|
||||
result = _submit(con, uid, body, now)
|
||||
elif action == 'review':
|
||||
result = _review(con, uid, body, admins, now, digest)
|
||||
else:
|
||||
_fail(400, 'unknown_action', 'Неизвестное действие; доступны submit и review.')
|
||||
con.execute(
|
||||
'INSERT INTO community_board_operations(actor_uid,request_id,digest,result,created_at) '
|
||||
'VALUES(?,?,?,?,?)',
|
||||
(uid, request_id, digest, json.dumps(result, ensure_ascii=False, separators=(',', ':')), now))
|
||||
con.commit()
|
||||
return result
|
||||
except Exception as exc:
|
||||
con.rollback()
|
||||
if receipt_absent and isinstance(exc, BoardError) and 400 <= exc.status < 500:
|
||||
exc.operation_rejected = True
|
||||
raise
|
||||
@@ -0,0 +1,238 @@
|
||||
import hashlib
|
||||
import json
|
||||
import re
|
||||
import sqlite3
|
||||
import time
|
||||
from contextlib import closing
|
||||
from typing import NoReturn
|
||||
|
||||
SUPPLY = 100_000
|
||||
DAILY_GRANT_LIMIT = 1_000
|
||||
MAX_AMOUNT = 10_000
|
||||
|
||||
|
||||
class EconomyError(ValueError):
|
||||
def __init__(self, status, code, message):
|
||||
super().__init__(message)
|
||||
self.status, self.code, self.message = status, code, message
|
||||
|
||||
|
||||
def _fail(status, code, message) -> NoReturn:
|
||||
raise EconomyError(status, code, message)
|
||||
|
||||
|
||||
def _connect(db):
|
||||
con = sqlite3.connect(str(db), timeout=10, isolation_level=None)
|
||||
con.row_factory = sqlite3.Row
|
||||
return con
|
||||
|
||||
|
||||
def init_db(db):
|
||||
with closing(_connect(db)) as con:
|
||||
con.executescript('''
|
||||
CREATE TABLE IF NOT EXISTS community_wallets (
|
||||
uid INTEGER PRIMARY KEY, balance INTEGER NOT NULL DEFAULT 0 CHECK(balance>=0));
|
||||
CREATE TABLE IF NOT EXISTS community_tasks (
|
||||
id INTEGER PRIMARY KEY, creator INTEGER NOT NULL, worker INTEGER,
|
||||
title TEXT NOT NULL, criteria TEXT NOT NULL, reward INTEGER NOT NULL CHECK(reward>0),
|
||||
status TEXT NOT NULL DEFAULT 'open', revision INTEGER NOT NULL DEFAULT 0,
|
||||
proof TEXT NOT NULL DEFAULT '', dispute TEXT NOT NULL DEFAULT '',
|
||||
resolution TEXT NOT NULL DEFAULT '', created INTEGER NOT NULL, updated INTEGER NOT NULL);
|
||||
CREATE TABLE IF NOT EXISTS community_ledger (
|
||||
id INTEGER PRIMARY KEY, actor INTEGER NOT NULL, src INTEGER NOT NULL, dst INTEGER NOT NULL,
|
||||
amount INTEGER NOT NULL CHECK(amount>0), kind TEXT NOT NULL,
|
||||
task_id INTEGER, reason TEXT NOT NULL, ts INTEGER NOT NULL);
|
||||
CREATE TABLE IF NOT EXISTS community_operations (
|
||||
actor INTEGER NOT NULL, request_id TEXT NOT NULL, digest TEXT NOT NULL,
|
||||
result TEXT NOT NULL, PRIMARY KEY(actor,request_id));
|
||||
CREATE INDEX IF NOT EXISTS community_tasks_status ON community_tasks(status,id);
|
||||
CREATE INDEX IF NOT EXISTS community_ledger_ts ON community_ledger(ts);
|
||||
''')
|
||||
# A finite non-cash reserve. Restarting never issues another reserve.
|
||||
con.execute('INSERT OR IGNORE INTO community_wallets(uid,balance) VALUES(0,?)', (SUPPLY,))
|
||||
|
||||
|
||||
def _int(value, name, minimum=1, maximum=MAX_AMOUNT):
|
||||
if type(value) is not int or not minimum <= value <= maximum:
|
||||
_fail(400, 'invalid_' + name, 'Некорректное поле: ' + name)
|
||||
return value
|
||||
|
||||
|
||||
def _text(value, name, minimum, maximum):
|
||||
if not isinstance(value, str) or not minimum <= len(value.strip()) <= maximum:
|
||||
_fail(400, 'invalid_' + name, f'{name}: от {minimum} до {maximum} символов.')
|
||||
return value.strip()
|
||||
|
||||
|
||||
def _user(con, uid):
|
||||
_int(uid, 'user', maximum=2**53-1)
|
||||
row = con.execute('SELECT banned,api_blocked FROM users WHERE tg_id=?', (uid,)).fetchone()
|
||||
if row is None:
|
||||
_fail(403, 'not_registered', 'Сначала открой бота и зарегистрируйся через /start.')
|
||||
if row['banned'] or row['api_blocked']:
|
||||
_fail(403, 'blocked', 'Доступ к экономике ограничен.')
|
||||
|
||||
|
||||
def _wallet(con, uid):
|
||||
con.execute('INSERT OR IGNORE INTO community_wallets(uid) VALUES(?)', (uid,))
|
||||
|
||||
|
||||
def _move(con, actor, src, dst, amount, kind, reason, now, task_id=None):
|
||||
_wallet(con, src)
|
||||
_wallet(con, dst)
|
||||
changed = con.execute('UPDATE community_wallets SET balance=balance-? WHERE uid=? AND balance>=?',
|
||||
(amount, src, amount)).rowcount
|
||||
if not changed:
|
||||
_fail(409, 'insufficient_coins', 'Недостаточно монет. API-баланс для этого не используется.')
|
||||
con.execute('UPDATE community_wallets SET balance=balance+? WHERE uid=?', (amount, dst))
|
||||
con.execute('INSERT INTO community_ledger(actor,src,dst,amount,kind,task_id,reason,ts) VALUES(?,?,?,?,?,?,?,?)',
|
||||
(actor, src, dst, amount, kind, task_id, reason, now))
|
||||
|
||||
|
||||
def snapshot(db, uid, admins=()):
|
||||
with closing(_connect(db)) as con:
|
||||
con.execute('BEGIN')
|
||||
_user(con, uid)
|
||||
row = con.execute('SELECT balance FROM community_wallets WHERE uid=?', (uid,)).fetchone()
|
||||
reserved = con.execute("SELECT COALESCE(SUM(reward),0) FROM community_tasks WHERE creator=? AND status IN ('open','claimed','submitted','disputed')", (uid,)).fetchone()[0]
|
||||
tasks = []
|
||||
# Personal work remains accessible even when the public board is busy.
|
||||
rows = con.execute('''SELECT * FROM community_tasks WHERE (creator=? OR worker=?)
|
||||
AND status IN ('open','claimed','submitted','disputed') ORDER BY id DESC''', (uid, uid)).fetchall()
|
||||
rows += con.execute('''SELECT * FROM community_tasks WHERE (creator=? OR worker=?)
|
||||
AND status IN ('done','cancelled') ORDER BY id DESC LIMIT 30''', (uid, uid)).fetchall()
|
||||
seen = {r['id'] for r in rows}
|
||||
rows += [r for r in con.execute("SELECT * FROM community_tasks WHERE status='open' ORDER BY id DESC LIMIT 50") if r['id'] not in seen]
|
||||
if uid in admins:
|
||||
seen = {r['id'] for r in rows}
|
||||
rows += [r for r in con.execute("SELECT * FROM community_tasks WHERE status='disputed' ORDER BY id DESC LIMIT 50") if r['id'] not in seen]
|
||||
for row_task in rows:
|
||||
task = dict(row_task)
|
||||
if uid not in (task['creator'], task['worker']) and uid not in admins:
|
||||
for field in ('proof', 'dispute', 'resolution'):
|
||||
task.pop(field, None)
|
||||
tasks.append(task)
|
||||
history = [dict(r) for r in con.execute('''SELECT id,src,dst,amount,kind,task_id,reason,ts
|
||||
FROM community_ledger WHERE src=? OR dst=? ORDER BY id DESC LIMIT 30''', (uid, uid))]
|
||||
reserve = con.execute('SELECT balance FROM community_wallets WHERE uid=0').fetchone()[0]
|
||||
granted = con.execute("SELECT COALESCE(SUM(amount),0) FROM community_ledger WHERE kind='grant' AND ts>=?", (int(time.time()) // 86400 * 86400,)).fetchone()[0]
|
||||
con.commit()
|
||||
return {'uid': uid, 'currency': 'coins', 'balance': row['balance'] if row else 0,
|
||||
'reserved': reserved, 'treasury': reserve, 'supply': SUPPLY,
|
||||
'grant_budget_left': max(0, DAILY_GRANT_LIMIT-granted),
|
||||
'is_admin': uid in admins, 'tasks': tasks, 'history': history,
|
||||
'rules': 'Монеты не деньги и не API-кредит. Оплата за принятый результат, не за сообщения. Обмена на деньги или AI-баланс нет.'}
|
||||
|
||||
|
||||
def act(db, uid, body, admins=()):
|
||||
if not isinstance(body, dict):
|
||||
_fail(400, 'invalid_body', 'Ожидается JSON-объект.')
|
||||
request_id = body.get('request_id')
|
||||
if not isinstance(request_id, str) or not re.fullmatch(r'[A-Za-z0-9:_-]{12,96}', request_id):
|
||||
_fail(400, 'request_id_required', 'Нужен уникальный идентификатор операции.')
|
||||
digest = hashlib.sha256(json.dumps(body, sort_keys=True, ensure_ascii=False).encode()).hexdigest()
|
||||
with closing(_connect(db)) as con:
|
||||
try:
|
||||
con.execute('BEGIN IMMEDIATE')
|
||||
now = int(time.time())
|
||||
previous = con.execute('SELECT digest,result FROM community_operations WHERE actor=? AND request_id=?', (uid, request_id)).fetchone()
|
||||
if previous:
|
||||
if previous['digest'] != digest:
|
||||
_fail(409, 'request_conflict', 'Идентификатор уже использован для другой операции.')
|
||||
con.rollback()
|
||||
return json.loads(previous['result'])
|
||||
_user(con, uid)
|
||||
action = body.get('action')
|
||||
result = {'ok': True, 'action': action}
|
||||
if action in ('grant', 'transfer'):
|
||||
amount = _int(body.get('amount'), 'amount')
|
||||
target = _int(body.get('target'), 'target', maximum=2**53-1)
|
||||
_user(con, target)
|
||||
reason = _text(body.get('reason'), 'Основание', 5, 500)
|
||||
if action == 'grant':
|
||||
if uid not in admins:
|
||||
_fail(403, 'admin_only', 'Начисление доступно только администрации.')
|
||||
spent = con.execute("SELECT COALESCE(SUM(amount),0) FROM community_ledger WHERE kind='grant' AND ts>=?", (now // 86400 * 86400,)).fetchone()[0]
|
||||
if spent + amount > DAILY_GRANT_LIMIT:
|
||||
_fail(409, 'grant_budget', 'Дневной фонд начислений исчерпан.')
|
||||
src = 0
|
||||
else:
|
||||
if target == uid:
|
||||
_fail(400, 'self_transfer', 'Нельзя перевести монеты самому себе.')
|
||||
src = uid
|
||||
_move(con, uid, src, target, amount, action, reason, now)
|
||||
elif action == 'create':
|
||||
title = _text(body.get('title'), 'Задание', 8, 300)
|
||||
criteria = _text(body.get('criteria'), 'Условия приёмки', 15, 1500)
|
||||
reward = _int(body.get('reward'), 'reward')
|
||||
count = con.execute("SELECT COUNT(*) FROM community_tasks WHERE creator=? AND status IN ('open','claimed','submitted','disputed')", (uid,)).fetchone()[0]
|
||||
if count >= 10:
|
||||
_fail(409, 'task_limit', 'Можно держать не более 10 незакрытых заданий.')
|
||||
cur = con.execute('INSERT INTO community_tasks(creator,title,criteria,reward,created,updated) VALUES(?,?,?,?,?,?)', (uid, title, criteria, reward, now, now))
|
||||
task_id = cur.lastrowid
|
||||
if task_id is None:
|
||||
raise RuntimeError('SQLite did not return a task id')
|
||||
_move(con, uid, uid, -task_id, reward, 'escrow', title, now, task_id)
|
||||
result['task_id'] = task_id
|
||||
elif action in ('claim', 'release', 'submit', 'accept', 'cancel', 'dispute', 'resolve'):
|
||||
task_id = _int(body.get('task_id'), 'task_id', maximum=2**53-1)
|
||||
revision = _int(body.get('revision'), 'revision', minimum=0, maximum=2**31-1)
|
||||
task = con.execute('SELECT * FROM community_tasks WHERE id=?', (task_id,)).fetchone()
|
||||
if task is None:
|
||||
_fail(404, 'task_not_found', 'Задание не найдено.')
|
||||
if task['revision'] != revision:
|
||||
_fail(409, 'stale_revision', 'Задание изменилось. Обнови список перед действием.')
|
||||
status, creator, worker = task['status'], task['creator'], task['worker']
|
||||
updates: dict[str, object] = {}
|
||||
if action == 'claim':
|
||||
if status != 'open' or uid == creator:
|
||||
_fail(409, 'not_claimable', 'Нельзя взять своё или занятое задание.')
|
||||
count = con.execute("SELECT COUNT(*) FROM community_tasks WHERE worker=? AND status IN ('claimed','submitted','disputed')", (uid,)).fetchone()[0]
|
||||
if count >= 5:
|
||||
_fail(409, 'worker_limit', 'Заверши текущие задания: максимум 5 в работе.')
|
||||
updates = {'worker': uid, 'status': 'claimed'}
|
||||
elif action == 'release':
|
||||
if uid != worker or status != 'claimed':
|
||||
_fail(403, 'not_releasable', 'Отказаться можно только от своего несданного задания.')
|
||||
updates = {'worker': None, 'status': 'open'}
|
||||
elif action == 'submit':
|
||||
if uid != worker or status != 'claimed':
|
||||
_fail(403, 'not_submittable', 'Сдать результат может только исполнитель задания в работе.')
|
||||
updates = {'proof': _text(body.get('proof'), 'Результат', 15, 3000), 'status': 'submitted'}
|
||||
elif action == 'accept':
|
||||
if uid != creator or status != 'submitted':
|
||||
_fail(403, 'not_acceptable', 'Заказчик принимает только сданную работу.')
|
||||
_move(con, uid, -task_id, worker, task['reward'], 'payout', task['title'], now, task_id)
|
||||
updates = {'status': 'done'}
|
||||
elif action == 'cancel':
|
||||
if uid != creator or status != 'open':
|
||||
_fail(403, 'not_cancellable', 'Отменить можно только своё ещё не взятое задание.')
|
||||
_move(con, uid, -task_id, creator, task['reward'], 'refund', task['title'], now, task_id)
|
||||
updates = {'status': 'cancelled'}
|
||||
elif action == 'dispute':
|
||||
if uid not in (creator, worker) or status not in ('claimed', 'submitted'):
|
||||
_fail(403, 'not_disputable', 'Спор доступен участникам незакрытого задания.')
|
||||
updates = {'status': 'disputed', 'dispute': _text(body.get('reason'), 'Причина спора', 15, 1500)}
|
||||
else:
|
||||
if uid not in admins:
|
||||
_fail(403, 'admin_only', 'Спор разрешает администрация.')
|
||||
if uid in (creator, worker):
|
||||
_fail(403, 'conflict_of_interest', 'Участник задания не может решать собственный спор.')
|
||||
if status != 'disputed' or body.get('decision') not in ('pay', 'refund'):
|
||||
_fail(409, 'invalid_resolution', 'Нужен открытый спор и решение pay или refund.')
|
||||
reason = _text(body.get('reason'), 'Решение', 15, 1500)
|
||||
pay = body['decision'] == 'pay'
|
||||
_move(con, uid, -task_id, worker if pay else creator, task['reward'], 'resolution', reason, now, task_id)
|
||||
updates = {'status': 'done' if pay else 'cancelled', 'resolution': reason}
|
||||
updates.update(revision=revision+1, updated=now)
|
||||
assignments = ','.join(key+'=?' for key in updates)
|
||||
con.execute('UPDATE community_tasks SET '+assignments+' WHERE id=?', (*updates.values(), task_id))
|
||||
result.update(task_id=task_id, revision=revision+1, status=updates['status'])
|
||||
else:
|
||||
_fail(400, 'unknown_action', 'Неизвестное действие экономики.')
|
||||
con.execute('INSERT INTO community_operations(actor,request_id,digest,result) VALUES(?,?,?,?)', (uid, request_id, digest, json.dumps(result)))
|
||||
con.commit()
|
||||
return result
|
||||
except Exception:
|
||||
con.rollback()
|
||||
raise
|
||||
@@ -0,0 +1,25 @@
|
||||
{
|
||||
"bot_token": "REPLACE_ME_TELEGRAM_BOT_TOKEN",
|
||||
"channel_username": "@your_channel",
|
||||
"channel_link": "https://t.me/your_channel",
|
||||
"channel_title": "Your channel",
|
||||
"support": "@your_support",
|
||||
"newapi_url": "http://127.0.0.1:48000",
|
||||
"newapi_user": "REPLACE_ME_NEWAPI_ADMIN_LOGIN",
|
||||
"newapi_pass": "REPLACE_ME_NEWAPI_ADMIN_PASSWORD",
|
||||
"newapi_db": "/opt/grok-gateway/new-api/data/one-api.db",
|
||||
"bot_db": "/opt/grok-bot/bot.db",
|
||||
"public_base": "http://127.0.0.1:8850",
|
||||
"user_quota": 500000000,
|
||||
"unlimited": false,
|
||||
"main_key": "REPLACE_ME_MASTER_GATEWAY_KEY",
|
||||
"chat_fallback_models": [],
|
||||
"chat_default_model": "deepseek-v4.1-flash-1017",
|
||||
"activity_chat_link": "",
|
||||
"activity_chat_id": 0,
|
||||
"gate_enforce_ts": 0,
|
||||
"cryptopay_token": "",
|
||||
"xrocket_token": "",
|
||||
"sticker_packs": [],
|
||||
"commerce_offers": []
|
||||
}
|
||||
@@ -0,0 +1,455 @@
|
||||
import logging
|
||||
import os
|
||||
import random
|
||||
import sqlite3
|
||||
import time
|
||||
from contextlib import closing
|
||||
|
||||
import econ_guard
|
||||
import quest_economy
|
||||
|
||||
log = logging.getLogger("daily_checkin")
|
||||
|
||||
QUOTA_PER_USD = 500_000
|
||||
FACES = (5_000_000, 8_000_000, 10_000_000, 12_000_000, 15_000_000, 20_000_000)
|
||||
# integer multipliers avoid float drift in money math
|
||||
RANK_MULT = {1: (1, 1), 2: (3, 2), 3: (2, 1), 4: (3, 1)}
|
||||
KIND_FACE = "ec_ddice:%d:%s"
|
||||
KIND_LEGACY = "ec_dice:%d:%s"
|
||||
KIND_WEB = "ec_web_checkin:%d:%s"
|
||||
REF_FMT = "daily:%d:%s"
|
||||
|
||||
|
||||
def _con(path, timeout=25):
|
||||
con = sqlite3.connect(path, timeout=timeout)
|
||||
con.row_factory = sqlite3.Row
|
||||
con.execute("PRAGMA busy_timeout=%d" % (timeout * 1000))
|
||||
return con
|
||||
|
||||
|
||||
def _now(now=None):
|
||||
if now is None:
|
||||
return int(time.time())
|
||||
if isinstance(now, (int, float)):
|
||||
return int(now)
|
||||
if hasattr(now, "timestamp"):
|
||||
return int(now.timestamp())
|
||||
raise ValueError("unsupported now")
|
||||
|
||||
|
||||
def _day(now=None):
|
||||
return quest_economy.today_iso(now)
|
||||
|
||||
|
||||
def multiplier(rank):
|
||||
num, den = RANK_MULT.get(int(rank), RANK_MULT[1])
|
||||
return num / float(den)
|
||||
|
||||
|
||||
def units_for(face, rank):
|
||||
face = int(face)
|
||||
if face < 1 or face > 6:
|
||||
raise ValueError("bad face")
|
||||
num, den = RANK_MULT.get(int(rank), RANK_MULT[1])
|
||||
return FACES[face - 1] * num // den
|
||||
|
||||
|
||||
def usd_for(units):
|
||||
return None if units is None else int(units) / float(QUOTA_PER_USD)
|
||||
|
||||
|
||||
def _faces_table(rank):
|
||||
return [{"face": i + 1, "units": units_for(i + 1, rank), "usd": usd_for(units_for(i + 1, rank))}
|
||||
for i in range(6)]
|
||||
|
||||
|
||||
# --------------------------------------------------------------------------- #
|
||||
# read side
|
||||
# --------------------------------------------------------------------------- #
|
||||
def schema_present(bot_db, gw_db):
|
||||
"""Read-only probe. Never opens a missing file, never creates a table."""
|
||||
for path in (bot_db, gw_db):
|
||||
if not path or not os.path.exists(path):
|
||||
return False
|
||||
try:
|
||||
with closing(_con(bot_db, timeout=5)) as b:
|
||||
names = {row[0] for row in b.execute(
|
||||
"SELECT name FROM sqlite_master WHERE type='table' AND name IN ('kv','users','econ_tx')")}
|
||||
if names != {"kv", "users", "econ_tx"}:
|
||||
return False
|
||||
if "wallet_id" not in {row[1] for row in b.execute("PRAGMA table_info(econ_tx)")}:
|
||||
return False
|
||||
with closing(_con(gw_db, timeout=5)) as g:
|
||||
if not g.execute("SELECT count(*) FROM sqlite_master WHERE type='table' "
|
||||
"AND name='econ_payouts'").fetchone()[0]:
|
||||
return False
|
||||
return True
|
||||
except sqlite3.Error:
|
||||
return False
|
||||
|
||||
|
||||
def _streak(con, uid):
|
||||
row = con.execute("SELECT v FROM kv WHERE k=?", ("ec_streak:%d" % int(uid),)).fetchone()
|
||||
try:
|
||||
return int(str(row[0]).split("|")[0]) if row else 0
|
||||
except (TypeError, ValueError, IndexError):
|
||||
return 0
|
||||
|
||||
|
||||
def _face_row(con, uid, day):
|
||||
row = con.execute("SELECT v FROM kv WHERE k=?", (KIND_FACE % (int(uid), day),)).fetchone()
|
||||
if not row:
|
||||
return None
|
||||
try:
|
||||
face, units, rank = str(row[0]).split("|")
|
||||
face, units, rank = int(face), int(units), int(rank)
|
||||
except (TypeError, ValueError):
|
||||
return None
|
||||
if not (1 <= face <= 6) or units <= 0 or rank not in (1, 2, 3, 4):
|
||||
return None
|
||||
return {"face": face, "units": units, "rank": rank}
|
||||
|
||||
|
||||
def _ledger_row(con, uid, day):
|
||||
row = con.execute("SELECT dst,units,type,ref,wallet_id FROM econ_tx "
|
||||
"WHERE type='daily' AND ref=?", (REF_FMT % (int(uid), day),)).fetchone()
|
||||
if not row:
|
||||
return None
|
||||
return {"dst": int(row[0]), "units": int(row[1]), "type": row[2],
|
||||
"ref": row[3], "wallet_id": row[4]}
|
||||
|
||||
|
||||
def _legacy_used(con, uid, day):
|
||||
return con.execute("SELECT 1 FROM kv WHERE k=?",
|
||||
(KIND_LEGACY % (int(uid), day),)).fetchone() is not None
|
||||
|
||||
|
||||
def _result(day=None, ok=True, error=None, claimed=False, paid=False, pending=False,
|
||||
face=None, units=None, rank=None, streak=0, already=False, resumed=False,
|
||||
credited_units=0, legacy=False, eligible=False, wallet=False, checked=None,
|
||||
faces=None):
|
||||
return {
|
||||
"ok": bool(ok),
|
||||
"error": error,
|
||||
"claimed": bool(claimed),
|
||||
"paid": bool(paid),
|
||||
"pending": bool(pending),
|
||||
"face": face,
|
||||
"value": face,
|
||||
"units": units,
|
||||
"usd": usd_for(units) if units is not None else None,
|
||||
"rank": rank,
|
||||
"multiplier": multiplier(rank) if rank else None,
|
||||
"streak": int(streak or 0),
|
||||
"already": bool(already),
|
||||
"resumed": bool(resumed),
|
||||
"credited_units": int(credited_units or 0),
|
||||
"legacy": bool(legacy),
|
||||
"eligible": bool(eligible),
|
||||
"wallet": bool(wallet),
|
||||
"day": day,
|
||||
"checkin": checked,
|
||||
"faces": faces if faces is not None else (_faces_table(rank) if rank else None),
|
||||
}
|
||||
|
||||
|
||||
def status(bot_db, gw_db, uid, now=None, rank=None):
|
||||
"""Read-only daily state. Performs no DDL and no writes whatsoever.
|
||||
|
||||
``rank`` is an optional display rank for the unclaimed preview; a persisted
|
||||
face always reports the rank it was actually paid at. Missing/unprepared
|
||||
economy schema yields ``ok=False, error="unavailable"`` (never creates it).
|
||||
"""
|
||||
day = _day(now)
|
||||
try:
|
||||
uid = int(uid)
|
||||
if uid <= 0:
|
||||
raise ValueError
|
||||
except (TypeError, ValueError):
|
||||
return _result(day=day, ok=False, error="user")
|
||||
preview = int(rank) if rank in (1, 2, 3, 4) else None
|
||||
if not schema_present(bot_db, gw_db):
|
||||
return _result(day=day, ok=False, error="unavailable", rank=preview)
|
||||
con = None
|
||||
try:
|
||||
con = _con(gw_db)
|
||||
con.execute("ATTACH DATABASE ? AS ledger", (bot_db,))
|
||||
user = con.execute("SELECT tg_id FROM ledger.users WHERE tg_id=?", (uid,)).fetchone()
|
||||
if not user:
|
||||
return _result(day=day, ok=False, error="user", rank=preview)
|
||||
eligible = econ_guard.account_eligible_con(con, uid, "ledger")
|
||||
streak = _streak(con, uid)
|
||||
face_row = _face_row(con, uid, day)
|
||||
ledger = _ledger_row(con, uid, day)
|
||||
legacy = _legacy_used(con, uid, day) and face_row is None and ledger is None
|
||||
wallet = econ_guard._resolve_wallet_con(con, uid) if eligible else None
|
||||
receipt = con.execute("SELECT token_id,units FROM econ_payouts WHERE ref=?",
|
||||
(REF_FMT % (uid, day),)).fetchone()
|
||||
except sqlite3.Error:
|
||||
log.exception("daily status read failed uid=%s", uid)
|
||||
return _result(day=day, ok=False, error="error", rank=preview)
|
||||
finally:
|
||||
if con is not None:
|
||||
con.close()
|
||||
if not eligible:
|
||||
return _result(day=day, ok=False, error="blocked", streak=streak, rank=preview)
|
||||
if legacy:
|
||||
# Ambiguous by definition: the pre-upgrade marker was written before its payout,
|
||||
# so it proves "consumed", not "credited". Never report a paid reward here.
|
||||
return _result(day=day, claimed=True, paid=False, pending=False, already=True,
|
||||
legacy=True, streak=streak, eligible=True, wallet=bool(wallet),
|
||||
rank=preview, faces=_faces_table(1))
|
||||
if face_row is None and ledger is None:
|
||||
return _result(day=day, claimed=False, paid=False, pending=False, rank=preview,
|
||||
streak=streak, eligible=True, wallet=bool(wallet))
|
||||
face = face_row or {"face": None, "units": int(ledger["units"]), "rank": None}
|
||||
paid = receipt is not None
|
||||
return _result(day=day, claimed=True, paid=paid, pending=not paid,
|
||||
face=face["face"], units=face["units"], rank=face["rank"] or preview,
|
||||
streak=streak, already=paid, resumed=not paid,
|
||||
eligible=True, wallet=bool(wallet))
|
||||
|
||||
|
||||
# --------------------------------------------------------------------------- #
|
||||
# payout
|
||||
# --------------------------------------------------------------------------- #
|
||||
def _credit_daily(gw_db, bot_db, uid, ref, wallet_id, units):
|
||||
"""Gateway-first payout of one daily ref. Never releases on ambiguity.
|
||||
|
||||
Returns ``(credited_units, result)`` with result in ok/already/blocked/wallet/error.
|
||||
"""
|
||||
if int(units) <= 0:
|
||||
return 0, "error"
|
||||
con = None
|
||||
try:
|
||||
con = _con(gw_db)
|
||||
con.execute("ATTACH DATABASE ? AS ledger", (bot_db,))
|
||||
con.execute("BEGIN IMMEDIATE")
|
||||
if not econ_guard.account_eligible_con(con, uid, "ledger"):
|
||||
con.rollback()
|
||||
return 0, "blocked"
|
||||
columns = {row[1] for row in con.execute("PRAGMA ledger.table_info(econ_tx)")}
|
||||
source = "bounty_source" if "bounty_source" in columns else "NULL AS bounty_source"
|
||||
rows = con.execute("SELECT dst,units,wallet_id,type,src,%s FROM ledger.econ_tx "
|
||||
"WHERE type='daily' AND ref=?" % source, (ref,)).fetchall()
|
||||
if (len(rows) != 1 or int(rows[0]["dst"]) != int(uid)
|
||||
or int(rows[0]["units"]) != int(units)
|
||||
or rows[0]["type"] != "daily" or int(rows[0]["src"] or 0) != 0
|
||||
or bool(rows[0]["bounty_source"])
|
||||
or (rows[0]["wallet_id"] is not None
|
||||
and int(rows[0]["wallet_id"]) != int(wallet_id))):
|
||||
con.rollback()
|
||||
log.error("daily ledger mismatch ref=%s", ref)
|
||||
return 0, "error"
|
||||
if not econ_guard._wallet_owned_con(con, uid, wallet_id):
|
||||
con.rollback()
|
||||
return 0, "wallet"
|
||||
existing = con.execute("SELECT token_id,units FROM econ_payouts WHERE ref=?", (ref,)).fetchone()
|
||||
if existing:
|
||||
if (int(existing["token_id"]) not in (0, int(wallet_id))
|
||||
or int(existing["units"]) != int(units)):
|
||||
con.rollback()
|
||||
log.error("daily payout ref conflict ref=%s", ref)
|
||||
return 0, "error"
|
||||
con.commit()
|
||||
return 0, "already"
|
||||
con.execute("INSERT INTO econ_payouts(ref,token_id,units,created) VALUES(?,?,?,?)",
|
||||
(ref, int(wallet_id), int(units), int(time.time())))
|
||||
updated = con.execute("UPDATE tokens SET remain_quota=remain_quota+? "
|
||||
"WHERE id=? AND status IN (1,2) AND deleted_at IS NULL",
|
||||
(int(units), int(wallet_id)))
|
||||
if updated.rowcount != 1:
|
||||
con.rollback()
|
||||
return 0, "wallet"
|
||||
con.commit()
|
||||
return int(units), "ok"
|
||||
except sqlite3.Error:
|
||||
log.exception("daily payout failed ref=%s", ref)
|
||||
if con is not None:
|
||||
con.rollback()
|
||||
return 0, "error"
|
||||
finally:
|
||||
if con is not None:
|
||||
con.close()
|
||||
|
||||
|
||||
# --------------------------------------------------------------------------- #
|
||||
# claim
|
||||
# --------------------------------------------------------------------------- #
|
||||
def _snapshot(bot_db, uid, day):
|
||||
with closing(_con(bot_db)) as con:
|
||||
if not econ_guard.account_eligible_con(con, uid):
|
||||
return {"error": "blocked"}
|
||||
face = _face_row(con, uid, day)
|
||||
ledger = _ledger_row(con, uid, day)
|
||||
return {"face": face, "ledger": ledger, "streak": _streak(con, uid),
|
||||
"legacy": (face is None and ledger is None and _legacy_used(con, uid, day))}
|
||||
|
||||
|
||||
def _persist_face(bot_db, uid, day, current, rank, face, units, wallet_id):
|
||||
"""Insert the face token and its ledger row atomically; adopt a concurrent winner."""
|
||||
con = _con(bot_db)
|
||||
try:
|
||||
con.execute("BEGIN IMMEDIATE")
|
||||
if not econ_guard.account_eligible_con(con, uid):
|
||||
con.rollback()
|
||||
return {"error": "blocked"}
|
||||
existing = _face_row(con, uid, day)
|
||||
ledger = _ledger_row(con, uid, day)
|
||||
if existing is not None or ledger is not None:
|
||||
con.rollback()
|
||||
return {"face": existing, "ledger": ledger, "won": False, "streak": _streak(con, uid)}
|
||||
won = con.execute("INSERT OR IGNORE INTO kv(k,v) VALUES(?,?)",
|
||||
(KIND_FACE % (uid, day), "%d|%d|%d" % (face, units, rank)))
|
||||
if won.rowcount == 1:
|
||||
con.execute("INSERT INTO econ_tx(src,dst,units,type,ts,ref,wallet_id) "
|
||||
"VALUES (?,?,?,?,?,?,?)",
|
||||
(0, uid, units, "daily", current, REF_FMT % (uid, day), int(wallet_id)))
|
||||
con.commit()
|
||||
return {"face": {"face": face, "units": units, "rank": rank}, "ledger": _ledger_row(
|
||||
con, uid, day), "won": True, "streak": _streak(con, uid)}
|
||||
con.rollback()
|
||||
return {"face": _face_row(con, uid, day), "ledger": _ledger_row(con, uid, day),
|
||||
"won": False, "streak": _streak(con, uid)}
|
||||
except sqlite3.IntegrityError:
|
||||
con.rollback()
|
||||
return {"face": _face_row(con, uid, day), "ledger": _ledger_row(con, uid, day),
|
||||
"won": False, "streak": _streak(con, uid)}
|
||||
finally:
|
||||
con.close()
|
||||
|
||||
|
||||
def claim(bot_db, gw_db, uid, rank, now=None, value=None, source="miniapp"):
|
||||
"""Roll (or resume) today's face and pay it exactly once.
|
||||
|
||||
``value`` is a dice face 1..6 from a trusted caller (a native Telegram dice);
|
||||
``None`` rolls a random face server-side. ``source`` is ``bot`` or ``miniapp``
|
||||
for the check-in calendar/streak side effect. Retries never roll again and
|
||||
never release a possibly-credited amount.
|
||||
"""
|
||||
day = _day(now)
|
||||
current = _now(now)
|
||||
try:
|
||||
uid = int(uid)
|
||||
if uid <= 0:
|
||||
raise ValueError
|
||||
except (TypeError, ValueError):
|
||||
return _result(day=day, ok=False, error="user")
|
||||
if rank not in (1, 2, 3, 4):
|
||||
return _result(day=day, ok=False, error="bad_input")
|
||||
rank = int(rank)
|
||||
if value is not None:
|
||||
try:
|
||||
value = int(value)
|
||||
except (TypeError, ValueError):
|
||||
return _result(day=day, ok=False, error="bad_input", rank=rank)
|
||||
if not 1 <= value <= 6:
|
||||
return _result(day=day, ok=False, error="bad_input", rank=rank)
|
||||
try:
|
||||
quest_economy.prepare(bot_db, gw_db)
|
||||
except sqlite3.Error:
|
||||
log.exception("daily prepare failed uid=%s", uid)
|
||||
return _result(day=day, ok=False, error="error", rank=rank)
|
||||
|
||||
try:
|
||||
snap = _snapshot(bot_db, uid, day)
|
||||
except sqlite3.Error:
|
||||
log.exception("daily snapshot failed uid=%s", uid)
|
||||
return _result(day=day, ok=False, error="error", rank=rank)
|
||||
if snap.get("error"):
|
||||
return _result(day=day, ok=False, error=snap["error"], rank=rank)
|
||||
if snap["legacy"]:
|
||||
return _result(day=day, claimed=True, paid=False, pending=False, already=True,
|
||||
legacy=True, rank=rank, streak=snap["streak"], eligible=True)
|
||||
if snap["face"] is not None or snap["ledger"] is not None:
|
||||
return _settle(bot_db, gw_db, uid, day, current, rank, snap["face"],
|
||||
snap["ledger"], snap["streak"], fresh=False)
|
||||
|
||||
wallet = econ_guard.resolve_wallet(gw_db, bot_db, uid)
|
||||
if not wallet:
|
||||
return _result(day=day, ok=False, error="wallet", rank=rank,
|
||||
streak=snap["streak"], eligible=True)
|
||||
checked = quest_economy.record_checkin(bot_db, gw_db, uid, current, source=source)
|
||||
if not checked.get("ok"):
|
||||
return _result(day=day, ok=False, error=checked.get("error", "error"), rank=rank,
|
||||
streak=snap["streak"], eligible=True, checked=checked)
|
||||
|
||||
face = int(value) if value is not None else random.randint(1, 6)
|
||||
units = units_for(face, rank)
|
||||
try:
|
||||
persisted = _persist_face(bot_db, uid, day, current, rank, face, units, wallet[0])
|
||||
except sqlite3.Error:
|
||||
log.exception("daily persist failed uid=%s", uid)
|
||||
return _result(day=day, ok=False, error="error", rank=rank, checked=checked)
|
||||
if persisted.get("error"):
|
||||
return _result(day=day, ok=False, error=persisted["error"], rank=rank,
|
||||
eligible=True, checked=checked)
|
||||
if persisted["face"] is None and persisted["ledger"] is None:
|
||||
log.error("daily face vanished uid=%s day=%s", uid, day)
|
||||
return _result(day=day, ok=False, error="error", rank=rank, checked=checked)
|
||||
return _settle(bot_db, gw_db, uid, day, current, rank, persisted["face"],
|
||||
persisted["ledger"], persisted["streak"], fresh=bool(persisted["won"]),
|
||||
checked=checked)
|
||||
|
||||
|
||||
def _settle(bot_db, gw_db, uid, day, current, rank, face_row, ledger, streak, fresh=False,
|
||||
checked=None):
|
||||
"""Phase 2: pay the persisted ref and report the stored values."""
|
||||
ref = REF_FMT % (uid, day)
|
||||
with closing(_con(bot_db)) as con:
|
||||
face_row = face_row or _face_row(con, uid, day)
|
||||
ledger = ledger or _ledger_row(con, uid, day)
|
||||
streak = _streak(con, uid) or streak
|
||||
if face_row is None and ledger is not None:
|
||||
face_row = {"face": None, "units": int(ledger["units"]), "rank": None}
|
||||
if face_row is None:
|
||||
log.error("daily claim row missing uid=%s day=%s", uid, day)
|
||||
return _result(day=day, ok=False, error="error", rank=rank, checked=checked)
|
||||
units = int(face_row["units"])
|
||||
out_rank = face_row["rank"] or rank
|
||||
if ledger is None:
|
||||
# Heal a half-written claim without changing face or amount.
|
||||
wallet = econ_guard.resolve_wallet(gw_db, bot_db, uid)
|
||||
if not wallet:
|
||||
return _result(day=day, ok=False, error="wallet", claimed=True, pending=True,
|
||||
face=face_row["face"], units=units, rank=out_rank,
|
||||
streak=streak, eligible=True, checked=checked)
|
||||
try:
|
||||
con = _con(bot_db)
|
||||
try:
|
||||
con.execute("BEGIN IMMEDIATE")
|
||||
if _ledger_row(con, uid, day) is None:
|
||||
con.execute("INSERT INTO econ_tx(src,dst,units,type,ts,ref,wallet_id) "
|
||||
"VALUES (?,?,?,?,?,?,?)",
|
||||
(0, uid, units, "daily", current, ref, int(wallet[0])))
|
||||
con.commit()
|
||||
finally:
|
||||
con.close()
|
||||
except sqlite3.Error:
|
||||
log.exception("daily ledger heal failed uid=%s", uid)
|
||||
return _result(day=day, ok=False, error="error", claimed=True, pending=True,
|
||||
face=face_row["face"], units=units, rank=out_rank,
|
||||
streak=streak, eligible=True, checked=checked)
|
||||
with closing(_con(bot_db)) as con:
|
||||
ledger = _ledger_row(con, uid, day)
|
||||
wallet_id = int(ledger["wallet_id"]) if ledger and ledger["wallet_id"] is not None else None
|
||||
if wallet_id is None:
|
||||
wallet = econ_guard.resolve_wallet(gw_db, bot_db, uid)
|
||||
if not wallet:
|
||||
return _result(day=day, ok=False, error="wallet", claimed=True, pending=True,
|
||||
face=face_row["face"], units=units, rank=out_rank,
|
||||
streak=streak, eligible=True, checked=checked)
|
||||
wallet_id = int(wallet[0])
|
||||
credited, result = _credit_daily(gw_db, bot_db, uid, ref, wallet_id, units)
|
||||
if result == "ok":
|
||||
return _result(day=day, claimed=True, paid=True, pending=False, face=face_row["face"],
|
||||
units=units, rank=out_rank, streak=streak, credited_units=credited,
|
||||
resumed=not fresh, eligible=True, wallet=True, checked=checked)
|
||||
if result == "already":
|
||||
return _result(day=day, claimed=True, paid=True, pending=False, face=face_row["face"],
|
||||
units=units, rank=out_rank, streak=streak, already=True, resumed=True,
|
||||
eligible=True, wallet=True, checked=checked)
|
||||
return _result(day=day, ok=False, error=result, claimed=True, pending=True,
|
||||
face=face_row["face"], units=units, rank=out_rank, streak=streak,
|
||||
resumed=not fresh, eligible=(result != "blocked"),
|
||||
wallet=(result != "wallet"), checked=checked)
|
||||
+165
@@ -0,0 +1,165 @@
|
||||
#!/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()
|
||||
@@ -0,0 +1,782 @@
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import logging
|
||||
import sqlite3
|
||||
import time
|
||||
from typing import Any, Dict, Optional, Tuple
|
||||
|
||||
log = logging.getLogger("econ_guard")
|
||||
|
||||
# Одноразовые награды: код извлекается из типа леджера.
|
||||
ONE_TIME_TYPES = ("firstweek",)
|
||||
ONE_TIME_PREFIXES = ("achv:", "streak:")
|
||||
|
||||
Wallet = Tuple[int, int]
|
||||
_WAL_WARNING_EMITTED = False
|
||||
REF_NEW_ID_MIN = 9_000_000_000
|
||||
REF_INVITER_UNITS = 25_000_000
|
||||
REF_INVITEE_UNITS = 10_000_000
|
||||
|
||||
|
||||
def _warn_wal_commit_window(con: sqlite3.Connection) -> None:
|
||||
global _WAL_WARNING_EMITTED
|
||||
if _WAL_WARNING_EMITTED:
|
||||
return
|
||||
modes = (con.execute("PRAGMA main.journal_mode").fetchone()[0],
|
||||
con.execute("PRAGMA ledger.journal_mode").fetchone()[0])
|
||||
if "wal" in modes:
|
||||
_WAL_WARNING_EMITTED = True
|
||||
log.warning("[ECONGUARD] WAL: ordinary SQL errors roll back both writes; "
|
||||
"power failure during COMMIT is not atomic across database files")
|
||||
|
||||
|
||||
# --------------------------------------------------------------------------- #
|
||||
# схема
|
||||
# --------------------------------------------------------------------------- #
|
||||
def ensure_schema(bot_db: str) -> None:
|
||||
con = sqlite3.connect(bot_db, timeout=30)
|
||||
try:
|
||||
con.execute("PRAGMA busy_timeout=30000")
|
||||
cols = {r[1] for r in con.execute("PRAGMA table_info(econ_tx)")}
|
||||
if "ref" not in cols:
|
||||
con.execute("ALTER TABLE econ_tx ADD COLUMN ref TEXT")
|
||||
# NULL в unique-индексе SQLite различимы -> исторические строки не мешают.
|
||||
con.execute("CREATE UNIQUE INDEX IF NOT EXISTS ux_econ_tx_ref ON econ_tx(type, ref)")
|
||||
con.execute("CREATE INDEX IF NOT EXISTS ix_econ_tx_dst_type_ts ON econ_tx(dst, type, ts)")
|
||||
con.execute("""CREATE TABLE IF NOT EXISTS econ_grants(
|
||||
uid INTEGER NOT NULL, code TEXT NOT NULL, units INTEGER NOT NULL,
|
||||
ts INTEGER NOT NULL, PRIMARY KEY(uid, code))""")
|
||||
con.execute("CREATE TABLE IF NOT EXISTS kv(k TEXT PRIMARY KEY, v TEXT)")
|
||||
con.execute("""CREATE TABLE IF NOT EXISTS referral_awards(
|
||||
invited_uid INTEGER PRIMARY KEY, inviter_uid INTEGER NOT NULL,
|
||||
awarded_at INTEGER NOT NULL, verified_at INTEGER NOT NULL,
|
||||
inviter_units INTEGER NOT NULL, invitee_units INTEGER NOT NULL)""")
|
||||
con.execute("CREATE INDEX IF NOT EXISTS ix_referral_awards_inviter_time "
|
||||
"ON referral_awards(inviter_uid,awarded_at)")
|
||||
con.commit()
|
||||
finally:
|
||||
con.close()
|
||||
|
||||
|
||||
def _con(path: str, timeout: int = 25) -> sqlite3.Connection:
|
||||
con = sqlite3.connect(path, timeout=timeout)
|
||||
con.execute("PRAGMA busy_timeout=%d" % (timeout * 1000))
|
||||
return con
|
||||
|
||||
|
||||
def account_eligible_con(con: sqlite3.Connection, uid: int, schema: str = "main") -> bool:
|
||||
"""Check canonical account flags on the caller's transaction; read errors never authorize."""
|
||||
if schema not in ("main", "ledger"):
|
||||
raise ValueError("invalid account schema")
|
||||
row = con.execute("SELECT COALESCE(banned,0),COALESCE(api_blocked,0) "
|
||||
"FROM %s.users WHERE tg_id=?" % schema, (int(uid),)).fetchone()
|
||||
return bool(row is not None and not row[0] and not row[1])
|
||||
|
||||
|
||||
def account_eligible(bot_db: str, uid: int) -> bool:
|
||||
"""Fail closed for missing accounts, either ban flag, or unreadable account state."""
|
||||
try:
|
||||
con = _con(bot_db, 15)
|
||||
try:
|
||||
return account_eligible_con(con, uid)
|
||||
finally:
|
||||
con.close()
|
||||
except sqlite3.Error:
|
||||
log.exception("[ECONGUARD] account eligibility read failed uid=%s", uid)
|
||||
return False
|
||||
|
||||
|
||||
def _account_name(name: str, uid: int, main_name: Optional[str] = None) -> bool:
|
||||
name = str(name or "")
|
||||
main = "tg%d" % int(uid)
|
||||
if name in (main, "pm%d" % int(uid), "sol%d" % int(uid)):
|
||||
return True
|
||||
prefix = main + "-k"
|
||||
if name.startswith(prefix):
|
||||
suffix = name[len(prefix):]
|
||||
return bool(suffix and suffix[0] != "0" and suffix.isascii() and suffix.isdigit())
|
||||
if name == main_name and not name.startswith(("tg", "pm", "sol")):
|
||||
return True
|
||||
return False
|
||||
|
||||
|
||||
def _wallet_owned_con(con: sqlite3.Connection, uid: int, token_id: int,
|
||||
schema: str = "ledger") -> bool:
|
||||
if schema not in ("main", "ledger"):
|
||||
raise ValueError("invalid account schema")
|
||||
user = con.execute("SELECT token_name FROM %s.users WHERE tg_id=?" % schema,
|
||||
(int(uid),)).fetchone()
|
||||
token = con.execute("SELECT name FROM tokens WHERE id=? AND deleted_at IS NULL",
|
||||
(int(token_id),)).fetchone()
|
||||
return bool(user and token and _account_name(token[0], uid, user[0]))
|
||||
|
||||
|
||||
def _resolve_wallet_con(con: sqlite3.Connection, uid: int) -> Optional[Wallet]:
|
||||
if not account_eligible_con(con, uid, "ledger"):
|
||||
return None
|
||||
user = con.execute("SELECT token_name FROM ledger.users WHERE tg_id=?", (int(uid),)).fetchone()
|
||||
names = []
|
||||
if user and user[0] and _account_name(user[0], uid, user[0]):
|
||||
names.append(user[0])
|
||||
default = "tg%d" % int(uid)
|
||||
if default not in names:
|
||||
names.append(default)
|
||||
for name in names:
|
||||
row = con.execute("SELECT id,remain_quota FROM tokens WHERE name=? "
|
||||
"AND status IN (1,2) AND deleted_at IS NULL "
|
||||
"ORDER BY remain_quota DESC,id LIMIT 1", (name,)).fetchone()
|
||||
if row:
|
||||
return int(row[0]), int(row[1])
|
||||
return None
|
||||
|
||||
|
||||
# --------------------------------------------------------------------------- #
|
||||
# леджер
|
||||
# --------------------------------------------------------------------------- #
|
||||
def ledger(bot_db: str, src: int, dst: int, units: int, type_: str,
|
||||
ref: Optional[str] = None) -> int:
|
||||
"""Записать строку леджера.
|
||||
|
||||
Возвращает rowid (>0), 0 - дубль по UNIQUE(type, ref), -1 - ошибка БД.
|
||||
"""
|
||||
con = _con(bot_db)
|
||||
try:
|
||||
cur = con.execute("INSERT INTO econ_tx (src,dst,units,type,ts,ref) VALUES (?,?,?,?,?,?)",
|
||||
(int(src), int(dst), int(units), type_, int(time.time()), ref))
|
||||
con.commit()
|
||||
return int(cur.lastrowid or 0)
|
||||
except sqlite3.IntegrityError:
|
||||
con.rollback()
|
||||
return 0
|
||||
except Exception:
|
||||
log.exception("[ECONGUARD] ledger insert failed type=%s ref=%s", type_, ref)
|
||||
try:
|
||||
con.rollback()
|
||||
except Exception:
|
||||
pass
|
||||
return -1
|
||||
finally:
|
||||
con.close()
|
||||
|
||||
|
||||
def undo_ledger(bot_db: str, rowid: int) -> None:
|
||||
"""Компенсация: убрать строку леджера, если деньги не двигались."""
|
||||
if not rowid or rowid <= 0:
|
||||
return
|
||||
con = _con(bot_db)
|
||||
try:
|
||||
con.execute("DELETE FROM econ_tx WHERE id=?", (int(rowid),))
|
||||
con.commit()
|
||||
except Exception:
|
||||
log.exception("[ECONGUARD] ledger undo failed id=%s", rowid)
|
||||
finally:
|
||||
con.close()
|
||||
|
||||
|
||||
# --------------------------------------------------------------------------- #
|
||||
# --------------------------------------------------------------------------- #
|
||||
def resolve_wallet(gw_db: str, bot_db: str, uid: int) -> Optional[Wallet]:
|
||||
"""Resolve an eligible account's live wallet in a gateway-first attached snapshot."""
|
||||
con = None
|
||||
try:
|
||||
con = _con(gw_db, 15)
|
||||
con.execute("ATTACH DATABASE ? AS ledger", (bot_db,))
|
||||
con.execute("BEGIN")
|
||||
# Establish the gateway read lock before reading attached account state.
|
||||
con.execute("SELECT id FROM tokens LIMIT 1").fetchone()
|
||||
wallet = _resolve_wallet_con(con, uid)
|
||||
con.commit()
|
||||
return wallet
|
||||
except sqlite3.Error:
|
||||
if con is not None:
|
||||
con.rollback()
|
||||
log.exception("[ECONGUARD] resolve_wallet failed uid=%s", uid)
|
||||
return None
|
||||
finally:
|
||||
if con is not None:
|
||||
con.close()
|
||||
|
||||
|
||||
def credit(gw_db: str, token_id: int, units: int) -> int:
|
||||
units = int(units)
|
||||
if units <= 0:
|
||||
return 0
|
||||
con = _con(gw_db)
|
||||
try:
|
||||
cur = con.execute("UPDATE tokens SET remain_quota=remain_quota+? "
|
||||
"WHERE id=? AND status IN (1,2) AND deleted_at IS NULL", # [FIX-2410] кап-пауза держит деньги
|
||||
(units, int(token_id)))
|
||||
con.commit()
|
||||
return units if cur.rowcount == 1 else 0
|
||||
except Exception:
|
||||
log.exception("[ECONGUARD] credit failed token=%s units=%s", token_id, units)
|
||||
try:
|
||||
con.rollback()
|
||||
except Exception:
|
||||
pass
|
||||
return 0
|
||||
finally:
|
||||
con.close()
|
||||
|
||||
|
||||
def debit(gw_db: str, token_id: int, units: int) -> int:
|
||||
units = int(units)
|
||||
if units <= 0:
|
||||
return 0
|
||||
con = _con(gw_db)
|
||||
try:
|
||||
cur = con.execute("UPDATE tokens SET remain_quota=remain_quota-? "
|
||||
"WHERE id=? AND remain_quota>=? AND status=1 AND deleted_at IS NULL", # [FIX-2410] пауза запрещает списание
|
||||
(units, int(token_id), units))
|
||||
con.commit()
|
||||
return units if cur.rowcount == 1 else 0
|
||||
except Exception:
|
||||
log.exception("[ECONGUARD] debit failed token=%s units=%s", token_id, units)
|
||||
try:
|
||||
con.rollback()
|
||||
except Exception:
|
||||
pass
|
||||
return 0
|
||||
finally:
|
||||
con.close()
|
||||
|
||||
|
||||
# --------------------------------------------------------------------------- #
|
||||
# mint / burn
|
||||
# --------------------------------------------------------------------------- #
|
||||
def mint(gw_db: str, bot_db: str, uid: int, units: int, type_: str,
|
||||
ref: Optional[str] = None, wallet: Optional[Wallet] = None) -> int:
|
||||
"""Казна -> пользователь: леджер и кредит в одной транзакции.
|
||||
|
||||
UNIQUE(type, ref) блокирует дубли; обычная ошибка SQLite или недоступный
|
||||
кошелёк откатывает обе записи. WAL не гарантирует power-failure atomicity.
|
||||
Возвращает реально зачислено, 0 — операция не применена.
|
||||
"""
|
||||
units = int(units)
|
||||
if units <= 0:
|
||||
return 0
|
||||
con = None
|
||||
try:
|
||||
# Do not trust a pre-resolved or explicit wallet across the account boundary.
|
||||
con = sqlite3.connect(gw_db, timeout=25)
|
||||
con.execute("PRAGMA busy_timeout=25000")
|
||||
# [FIX-2410] Один attached-транзакционный путь вместо credit/undo-компенсации:
|
||||
# обычные ошибки БД откатывают и леджер, и изменение кошелька.
|
||||
# Acquire gateway before bot.db, in the same order as mk_daemon.
|
||||
con.execute("ATTACH DATABASE ? AS ledger", (bot_db,))
|
||||
_warn_wal_commit_window(con)
|
||||
con.execute("BEGIN IMMEDIATE")
|
||||
if not account_eligible_con(con, uid, "ledger"):
|
||||
con.rollback()
|
||||
return 0
|
||||
w = wallet if wallet is not None else _resolve_wallet_con(con, uid)
|
||||
if not w or not _wallet_owned_con(con, uid, int(w[0])):
|
||||
con.rollback()
|
||||
return 0
|
||||
con.execute("INSERT INTO ledger.econ_tx (src,dst,units,type,ts,ref) VALUES (?,?,?,?,?,?)",
|
||||
(0, int(uid), units, type_, int(time.time()), ref))
|
||||
cur = con.execute("UPDATE tokens SET remain_quota=remain_quota+? "
|
||||
"WHERE id=? AND status IN (1,2) AND deleted_at IS NULL",
|
||||
(units, int(w[0])))
|
||||
if cur.rowcount != 1:
|
||||
con.rollback()
|
||||
log.warning("[ECONGUARD] mint rolled back, wallet unavailable uid=%s type=%s ref=%s",
|
||||
uid, type_, ref)
|
||||
return 0
|
||||
con.commit()
|
||||
return units
|
||||
except Exception as exc:
|
||||
if con is not None:
|
||||
try:
|
||||
con.rollback()
|
||||
except sqlite3.Error:
|
||||
log.exception("[ECONGUARD] mint rollback failed uid=%s type=%s ref=%s",
|
||||
uid, type_, ref)
|
||||
if isinstance(exc, sqlite3.IntegrityError):
|
||||
log.warning("[ECONGUARD] mint transaction rejected by constraint uid=%s type=%s ref=%s",
|
||||
uid, type_, ref)
|
||||
else:
|
||||
log.exception("[ECONGUARD] mint transaction failed uid=%s type=%s ref=%s",
|
||||
uid, type_, ref)
|
||||
return 0
|
||||
finally:
|
||||
if con is not None:
|
||||
con.close()
|
||||
|
||||
|
||||
def burn(gw_db: str, bot_db: str, uid: int, units: int, type_: str,
|
||||
ref: Optional[str] = None, wallet: Optional[Wallet] = None) -> int:
|
||||
units = int(units)
|
||||
if units <= 0:
|
||||
return 0
|
||||
con = None
|
||||
try:
|
||||
# Recheck flags and explicit wallet ownership after both database locks are held.
|
||||
con = sqlite3.connect(gw_db, timeout=25)
|
||||
con.execute("PRAGMA busy_timeout=25000")
|
||||
# [FIX-2410] UNIQUE проверяется вставкой под BEGIN IMMEDIATE, без ledger_seen
|
||||
# и отдельного refund: ошибки откатывают леджер и дебет вместе.
|
||||
con.execute("ATTACH DATABASE ? AS ledger", (bot_db,))
|
||||
_warn_wal_commit_window(con)
|
||||
con.execute("BEGIN IMMEDIATE")
|
||||
if not account_eligible_con(con, uid, "ledger"):
|
||||
con.rollback()
|
||||
return 0
|
||||
w = wallet if wallet is not None else _resolve_wallet_con(con, uid)
|
||||
if not w or not _wallet_owned_con(con, uid, int(w[0])):
|
||||
con.rollback()
|
||||
return 0
|
||||
con.execute("INSERT INTO ledger.econ_tx (src,dst,units,type,ts,ref) VALUES (?,?,?,?,?,?)",
|
||||
(int(uid), 0, units, type_, int(time.time()), ref))
|
||||
cur = con.execute("UPDATE tokens SET remain_quota=remain_quota-? "
|
||||
"WHERE id=? AND remain_quota>=? AND status=1 AND deleted_at IS NULL",
|
||||
(units, int(w[0]), units))
|
||||
if cur.rowcount != 1:
|
||||
con.rollback()
|
||||
log.warning("[ECONGUARD] burn rolled back (insufficient/locked) uid=%s type=%s ref=%s",
|
||||
uid, type_, ref)
|
||||
return 0
|
||||
con.commit()
|
||||
return units
|
||||
except Exception as exc:
|
||||
if con is not None:
|
||||
try:
|
||||
con.rollback()
|
||||
except sqlite3.Error:
|
||||
log.exception("[ECONGUARD] burn rollback failed uid=%s type=%s ref=%s",
|
||||
uid, type_, ref)
|
||||
if isinstance(exc, sqlite3.IntegrityError):
|
||||
log.warning("[ECONGUARD] burn transaction rejected by constraint uid=%s type=%s ref=%s",
|
||||
uid, type_, ref)
|
||||
else:
|
||||
log.exception("[ECONGUARD] burn transaction failed uid=%s type=%s ref=%s",
|
||||
uid, type_, ref)
|
||||
return 0
|
||||
finally:
|
||||
if con is not None:
|
||||
con.close()
|
||||
|
||||
|
||||
def refill_weekly(bot_db: str, gw_db: str, uid: int, target: int, week_start: int,
|
||||
level: int, now: Optional[int] = None) -> int:
|
||||
uid, target, week_start, level = int(uid), int(target), int(week_start), int(level)
|
||||
current = int(time.time() if now is None else now)
|
||||
if uid <= 0 or target < 0 or week_start <= 0 or current < week_start:
|
||||
return 0
|
||||
con = None
|
||||
try:
|
||||
con = _con(gw_db)
|
||||
con.execute("ATTACH DATABASE ? AS ledger", (bot_db,))
|
||||
_warn_wal_commit_window(con)
|
||||
con.execute("BEGIN IMMEDIATE")
|
||||
if not account_eligible_con(con, uid, "ledger"):
|
||||
con.rollback()
|
||||
return 0
|
||||
columns = {row[1] for row in con.execute("PRAGMA ledger.table_info(users)")}
|
||||
fields = ("token_name", "api_key", "created", "last_loyalty", "last_bonus_lvl",
|
||||
"key_locked", "chat_key_locked")
|
||||
user = con.execute("SELECT %s FROM ledger.users WHERE tg_id=?" % ",".join(fields),
|
||||
(uid,)).fetchone()
|
||||
info = dict(zip(fields, user))
|
||||
if (int(info["last_loyalty"] or 0) >= week_start
|
||||
or info["key_locked"] or info["chat_key_locked"]
|
||||
or not info["created"] or current - int(info["created"]) < 86400):
|
||||
con.rollback()
|
||||
return 0
|
||||
cap_paused = False
|
||||
if "cap_paused" in columns:
|
||||
cap_paused = bool(con.execute("SELECT cap_paused FROM ledger.users WHERE tg_id=?",
|
||||
(uid,)).fetchone()[0])
|
||||
main_name = str(info["token_name"] or "")
|
||||
if main_name.startswith("tg%d-k" % uid) and _account_name(main_name, uid):
|
||||
main_name = "tg%d" % uid
|
||||
if not main_name or not _account_name(main_name, uid, main_name):
|
||||
con.rollback()
|
||||
return 0
|
||||
saved = str(info["api_key"] or "").strip()
|
||||
has_saved_key = bool(saved)
|
||||
if saved.startswith("sk-"):
|
||||
saved = saved[3:]
|
||||
sql = ("SELECT id,remain_quota,status,unlimited_quota,expired_time FROM tokens "
|
||||
"WHERE name=? AND deleted_at IS NULL")
|
||||
params = [main_name]
|
||||
if has_saved_key:
|
||||
sql += " AND key=?"
|
||||
params.append(saved)
|
||||
wallets = con.execute(sql, params).fetchall()
|
||||
if len(wallets) != 1:
|
||||
con.rollback()
|
||||
return 0
|
||||
token_id, balance, status, unlimited, expires = wallets[0]
|
||||
if (status not in (1, 2, 4) or (status == 2 and not cap_paused)
|
||||
or unlimited or expires is None
|
||||
or not (int(expires) == -1 or int(expires) >= current)):
|
||||
con.rollback()
|
||||
return 0
|
||||
prefix = "tg%d-k" % uid
|
||||
rows = con.execute("SELECT name,remain_quota,unlimited_quota FROM tokens "
|
||||
"WHERE name IN (?,?,?,?) OR (name>=? AND name<?)",
|
||||
(main_name, "tg%d" % uid, "pm%d" % uid, "sol%d" % uid,
|
||||
prefix, "tg%d-l" % uid)).fetchall()
|
||||
# account-wide total exceed every rank target, so the weekly floor credited 0.
|
||||
total = sum(max(0, int(quota or 0)) for name, quota, unlimited in rows
|
||||
if not unlimited and _account_name(name, uid, main_name))
|
||||
delta = max(0, target - total)
|
||||
con.execute("INSERT INTO ledger.econ_tx(src,dst,units,type,ts,ref) VALUES(?,?,?,?,?,?)",
|
||||
(0, uid, delta, "loyalty:weekly", current, "weekly:%d:%d" % (uid, week_start)))
|
||||
credited = con.execute(
|
||||
"UPDATE tokens SET remain_quota=COALESCE(remain_quota,0)+?, "
|
||||
"status=CASE WHEN status=4 AND ?=0 AND COALESCE(remain_quota,0)+?>0 THEN 1 ELSE status END "
|
||||
"WHERE id=? AND deleted_at IS NULL AND status IN (1,2,4)",
|
||||
(delta, int(cap_paused), delta, int(token_id)))
|
||||
receipt = con.execute(
|
||||
"UPDATE ledger.users SET last_loyalty=?,last_bonus_lvl=MAX(COALESCE(last_bonus_lvl,0),?) "
|
||||
"WHERE tg_id=? AND COALESCE(last_loyalty,0)<? "
|
||||
"AND COALESCE(banned,0)=0 AND COALESCE(api_blocked,0)=0",
|
||||
(current, max(1, min(4, level)), uid, week_start))
|
||||
if credited.rowcount != 1 or receipt.rowcount != 1:
|
||||
con.rollback()
|
||||
return 0
|
||||
con.commit()
|
||||
return delta
|
||||
except Exception:
|
||||
if con is not None:
|
||||
con.rollback()
|
||||
log.exception("[ECONGUARD] weekly refill failed uid=%s week=%s", uid, week_start)
|
||||
return 0
|
||||
finally:
|
||||
if con is not None:
|
||||
con.close()
|
||||
|
||||
|
||||
def _referral_wallet_con(con: sqlite3.Connection, uid: int) -> Optional[Wallet]:
|
||||
user = con.execute("SELECT token_name,api_key FROM ledger.users WHERE tg_id=?",
|
||||
(int(uid),)).fetchone()
|
||||
if not user or not user[0] or not user[1]:
|
||||
return None
|
||||
name, saved = str(user[0]), str(user[1]).strip()
|
||||
if name.startswith("tg%d-k" % int(uid)) and _account_name(name, uid):
|
||||
name = "tg%d" % int(uid)
|
||||
if saved.startswith("sk-"):
|
||||
saved = saved[3:]
|
||||
if not saved or not _account_name(name, uid, name):
|
||||
return None
|
||||
rows = con.execute("SELECT id,remain_quota FROM tokens WHERE name=? AND key=? "
|
||||
"AND status IN (1,2) AND deleted_at IS NULL", (name, saved)).fetchall()
|
||||
if len(rows) != 1:
|
||||
return None
|
||||
return int(rows[0][0]), int(rows[0][1] or 0)
|
||||
|
||||
|
||||
def award_referral(bot_db: str, gw_db: str, uid: int, verified_at: int,
|
||||
now: Optional[int] = None) -> Dict[str, Any]:
|
||||
result = {"status": "pending", "inviter": 0, "inviter_units": 0, "invitee_units": 0}
|
||||
try:
|
||||
uid, verified = int(uid), int(verified_at)
|
||||
if isinstance(verified_at, bool) or verified_at != verified:
|
||||
return result
|
||||
current = int(time.time() if now is None else now)
|
||||
except (TypeError, ValueError, OverflowError):
|
||||
return result
|
||||
if uid <= 0:
|
||||
return result
|
||||
con = None
|
||||
try:
|
||||
con = _con(gw_db)
|
||||
con.execute("ATTACH DATABASE ? AS ledger", (bot_db,))
|
||||
_warn_wal_commit_window(con)
|
||||
con.execute("BEGIN IMMEDIATE")
|
||||
if now is None:
|
||||
current = int(time.time())
|
||||
user = con.execute("SELECT referred_by,ref_time,ref_awarded FROM ledger.users WHERE tg_id=?",
|
||||
(uid,)).fetchone()
|
||||
if not user:
|
||||
con.rollback()
|
||||
return result
|
||||
inviter = int(user[0] or 0)
|
||||
result["inviter"] = inviter
|
||||
if verified <= 0 or not 0 <= current - verified <= 30 or inviter <= 0 or inviter == uid:
|
||||
con.rollback()
|
||||
return result
|
||||
referrer = con.execute("SELECT referred_by FROM ledger.users WHERE tg_id=?",
|
||||
(inviter,)).fetchone()
|
||||
if not referrer or int(referrer[0] or 0) == uid:
|
||||
con.rollback()
|
||||
return result
|
||||
if not (account_eligible_con(con, uid, "ledger")
|
||||
and account_eligible_con(con, inviter, "ledger")):
|
||||
con.rollback()
|
||||
result["status"] = "blocked"
|
||||
return result
|
||||
existing = con.execute(
|
||||
"SELECT inviter_uid,inviter_units,invitee_units FROM ledger.referral_awards WHERE invited_uid=?",
|
||||
(uid,)).fetchone()
|
||||
if existing or user[2]:
|
||||
con.rollback()
|
||||
result["status"] = "already"
|
||||
if existing:
|
||||
result.update(inviter=int(existing[0]), inviter_units=int(existing[1]),
|
||||
invitee_units=int(existing[2]))
|
||||
return result
|
||||
ref_time = int(user[1] or 0)
|
||||
if ref_time <= 0 or current - ref_time < 86400:
|
||||
con.rollback()
|
||||
return result
|
||||
invitee_wallet = _referral_wallet_con(con, uid)
|
||||
inviter_wallet = _referral_wallet_con(con, inviter)
|
||||
if not invitee_wallet or not inviter_wallet:
|
||||
con.rollback()
|
||||
result["status"] = "no_wallet"
|
||||
return result
|
||||
# Mandatory invitee evidence: one successful (type=2) consumption log on the
|
||||
# exact stored main wallet, from referral time up to now. INDEXED BY is not
|
||||
# optional: unhinted SQLite prefers idx_logs_top24 and scans every user's
|
||||
# logs while this transaction already holds the writer lock. Read errors
|
||||
# (missing table/index/column) hit the except below: nothing is awarded.
|
||||
api_used = con.execute(
|
||||
"SELECT 1 FROM logs INDEXED BY idx_logs_token_id "
|
||||
"WHERE token_id=? AND type=2 AND created_at>=? AND created_at<=? "
|
||||
"AND (COALESCE(quota,0)>0 OR COALESCE(prompt_tokens,0)>0 "
|
||||
"OR COALESCE(completion_tokens,0)>0) LIMIT 1",
|
||||
(int(invitee_wallet[0]), ref_time, current)).fetchone()
|
||||
if not api_used:
|
||||
con.rollback()
|
||||
result["status"] = "no_api_request"
|
||||
return result
|
||||
awarded = con.execute(
|
||||
"SELECT COUNT(*) FROM ledger.referral_awards WHERE inviter_uid=? AND awarded_at>?",
|
||||
(inviter, current - 86400)).fetchone()[0]
|
||||
if int(awarded) >= 10:
|
||||
con.rollback()
|
||||
result["status"] = "cap"
|
||||
return result
|
||||
inviter_units = REF_INVITER_UNITS // 2 if uid >= REF_NEW_ID_MIN else REF_INVITER_UNITS
|
||||
claimed = con.execute(
|
||||
"UPDATE ledger.users SET ref_awarded=1 WHERE tg_id=? AND referred_by=? "
|
||||
"AND COALESCE(ref_awarded,0)=0 AND COALESCE(banned,0)=0 AND COALESCE(api_blocked,0)=0",
|
||||
(uid, inviter))
|
||||
if claimed.rowcount != 1:
|
||||
con.rollback()
|
||||
return result
|
||||
con.execute("INSERT INTO ledger.referral_awards"
|
||||
"(invited_uid,inviter_uid,awarded_at,verified_at,inviter_units,invitee_units) "
|
||||
"VALUES(?,?,?,?,?,?)",
|
||||
(uid, inviter, current, verified, inviter_units, REF_INVITEE_UNITS))
|
||||
for recipient, wallet, units, role in (
|
||||
(inviter, inviter_wallet, inviter_units, "inviter"),
|
||||
(uid, invitee_wallet, REF_INVITEE_UNITS, "invitee")):
|
||||
con.execute("INSERT INTO ledger.econ_tx(src,dst,units,type,ts,ref) VALUES(?,?,?,?,?,?)",
|
||||
(0, recipient, units, "referral", current, "referral:%d:%s" % (uid, role)))
|
||||
credited = con.execute("UPDATE tokens SET remain_quota=COALESCE(remain_quota,0)+? "
|
||||
"WHERE id=? AND status IN (1,2) AND deleted_at IS NULL",
|
||||
(units, wallet[0]))
|
||||
if credited.rowcount != 1:
|
||||
con.rollback()
|
||||
result["status"] = "no_wallet"
|
||||
return result
|
||||
immunity = con.execute(
|
||||
"UPDATE ledger.users SET ref_credit=MAX(COALESCE(ref_credit,0),?) WHERE tg_id=? "
|
||||
"AND COALESCE(banned,0)=0 AND COALESCE(api_blocked,0)=0",
|
||||
(current + 14 * 86400, inviter))
|
||||
if immunity.rowcount != 1:
|
||||
con.rollback()
|
||||
return result
|
||||
con.commit()
|
||||
result.update(status="awarded", inviter_units=inviter_units, invitee_units=REF_INVITEE_UNITS)
|
||||
return result
|
||||
except (sqlite3.Error, TypeError, ValueError, OverflowError):
|
||||
if con is not None:
|
||||
con.rollback()
|
||||
log.exception("[ECONGUARD] referral award failed uid=%s", uid)
|
||||
return result
|
||||
finally:
|
||||
if con is not None:
|
||||
con.close()
|
||||
|
||||
|
||||
def ledger_seen(bot_db: str, type_: str, ref: str) -> bool:
|
||||
"""Уже есть строка леджера с таким (type, ref)?"""
|
||||
con = _con(bot_db, 15)
|
||||
try:
|
||||
row = con.execute("SELECT 1 FROM econ_tx WHERE type=? AND ref=? LIMIT 1", (type_, ref)).fetchone()
|
||||
return bool(row)
|
||||
except Exception:
|
||||
log.exception("[ECONGUARD] ledger_seen failed type=%s ref=%s", type_, ref)
|
||||
return False
|
||||
finally:
|
||||
con.close()
|
||||
|
||||
|
||||
# --------------------------------------------------------------------------- #
|
||||
# заявки (claim-first)
|
||||
# --------------------------------------------------------------------------- #
|
||||
def claim(bot_db: str, sql: str, params: tuple = ()) -> bool:
|
||||
"""Атомарная заявка на смену состояния. True = мы первые.
|
||||
|
||||
Пример: ``claim(bot_db, "UPDATE duels SET status='done' WHERE id=? AND status='pending'", (did,))``
|
||||
"""
|
||||
con = _con(bot_db)
|
||||
try:
|
||||
cur = con.execute(sql, params)
|
||||
con.commit()
|
||||
return cur.rowcount > 0
|
||||
except Exception:
|
||||
log.exception("[ECONGUARD] claim failed sql=%s", sql)
|
||||
try:
|
||||
con.rollback()
|
||||
except Exception:
|
||||
pass
|
||||
return False
|
||||
finally:
|
||||
con.close()
|
||||
|
||||
|
||||
def grant_once(bot_db: str, gw_db: str, uid: int, code: str, units: int,
|
||||
type_: Optional[str] = None) -> int:
|
||||
units = int(units)
|
||||
if units <= 0:
|
||||
return 0
|
||||
con = _con(bot_db)
|
||||
try:
|
||||
cur = con.execute("INSERT OR IGNORE INTO econ_grants(uid,code,units,ts) VALUES (?,?,?,?)",
|
||||
(int(uid), code, units, int(time.time())))
|
||||
con.commit()
|
||||
claimed = cur.rowcount > 0
|
||||
except Exception:
|
||||
log.exception("[ECONGUARD] grant claim failed uid=%s code=%s", uid, code)
|
||||
return 0
|
||||
finally:
|
||||
con.close()
|
||||
if not claimed:
|
||||
return 0
|
||||
got = mint(gw_db, bot_db, uid, units, type_ or ("achv:%s" % code),
|
||||
ref="grant:%s:%s" % (code, uid))
|
||||
if got <= 0:
|
||||
release_grant(bot_db, uid, code)
|
||||
log.warning("[ECONGUARD] grant released after failed payout uid=%s code=%s", uid, code)
|
||||
return got
|
||||
|
||||
|
||||
def release_grant(bot_db: str, uid: int, code: str) -> None:
|
||||
con = _con(bot_db, 15)
|
||||
try:
|
||||
con.execute("DELETE FROM econ_grants WHERE uid=? AND code=?", (int(uid), code))
|
||||
con.commit()
|
||||
except Exception:
|
||||
log.exception("[ECONGUARD] release_grant failed uid=%s code=%s", uid, code)
|
||||
finally:
|
||||
con.close()
|
||||
|
||||
|
||||
def cooldown_take(bot_db: str, key: str, seconds: int, now: Optional[int] = None) -> bool:
|
||||
"""Атомарный кулдаун: True = взяли (прошлый истёк или не существовал)."""
|
||||
now = int(now if now is not None else time.time())
|
||||
seconds = int(seconds)
|
||||
con = _con(bot_db)
|
||||
try:
|
||||
cur = con.execute(
|
||||
"INSERT INTO kv(k,v) VALUES(?,?) ON CONFLICT(k) DO UPDATE SET v=excluded.v "
|
||||
"WHERE CAST(kv.v AS INTEGER) <= ?", (key, str(now), now - seconds))
|
||||
con.commit()
|
||||
return cur.rowcount > 0
|
||||
except Exception:
|
||||
log.exception("[ECONGUARD] cooldown_take failed key=%s", key)
|
||||
return False
|
||||
finally:
|
||||
con.close()
|
||||
|
||||
|
||||
# --------------------------------------------------------------------------- #
|
||||
# бэкфилл и аудит
|
||||
# --------------------------------------------------------------------------- #
|
||||
def grant_code(type_: str) -> Optional[str]:
|
||||
"""Код одноразовой награды из типа леджера ('achv:rich100' -> 'rich100')."""
|
||||
for p in ONE_TIME_PREFIXES:
|
||||
if type_.startswith(p):
|
||||
return type_[len(p):]
|
||||
return type_ if type_ in ONE_TIME_TYPES else None
|
||||
|
||||
|
||||
def backfill_grants(bot_db: str) -> Dict[str, int]:
|
||||
"""Отметить уже выданные одноразовые награды, чтобы фикс не выдал их повторно."""
|
||||
con = _con(bot_db)
|
||||
inserted = scanned = 0
|
||||
try:
|
||||
rows = con.execute(
|
||||
"SELECT DISTINCT dst, type, MAX(units) FROM econ_tx WHERE src=0 AND ("
|
||||
"type LIKE 'achv:%' OR type LIKE 'streak:%' OR type='firstweek') GROUP BY dst, type").fetchall()
|
||||
for uid, type_, units in rows:
|
||||
code = grant_code(type_)
|
||||
if not code:
|
||||
continue
|
||||
scanned += 1
|
||||
cur = con.execute("INSERT OR IGNORE INTO econ_grants(uid,code,units,ts) VALUES (?,?,?,?)",
|
||||
(int(uid), code, int(units or 0), int(time.time())))
|
||||
inserted += cur.rowcount
|
||||
con.commit()
|
||||
finally:
|
||||
con.close()
|
||||
return {"scanned": scanned, "inserted": inserted}
|
||||
|
||||
|
||||
def audit(bot_db: str, gw_db: Optional[str] = None, days: int = 7,
|
||||
top: int = 10) -> Dict[str, Any]:
|
||||
"""Сводка целостности: дубли начислений, повторные одноразовые, битые заявки.
|
||||
|
||||
Ничего не меняет - только читает.
|
||||
"""
|
||||
since = int(time.time()) - int(days) * 86400
|
||||
out: Dict[str, Any] = {"days": days, "since": since}
|
||||
con = _con(bot_db, 20)
|
||||
con.row_factory = sqlite3.Row
|
||||
try:
|
||||
has_ref = "ref" in {r[1] for r in con.execute("PRAGMA table_info(econ_tx)")}
|
||||
out["schema_ref"] = has_ref
|
||||
out["ledger_rows_window"] = con.execute(
|
||||
"SELECT COUNT(*) FROM econ_tx WHERE ts>=?", (since,)).fetchone()[0]
|
||||
# 1) Повтор одноразовых наград (achv/streak/firstweek) - всегда баг.
|
||||
out["one_time_repeats"] = [
|
||||
dict(r) for r in con.execute(
|
||||
"SELECT dst AS uid, type, COUNT(*) AS n, SUM(units) AS units FROM econ_tx "
|
||||
"WHERE src=0 AND (type LIKE 'achv:%' OR type LIKE 'streak:%' OR type='firstweek') "
|
||||
"GROUP BY dst, type HAVING COUNT(*)>1 ORDER BY n DESC LIMIT ?", (top,))]
|
||||
# 2) Начисления одному uid одним типом в одну секунду - признак гонки.
|
||||
out["same_second_mints"] = [
|
||||
dict(r) for r in con.execute(
|
||||
"SELECT dst AS uid, type, ts, COUNT(*) AS n, SUM(units) AS units FROM econ_tx "
|
||||
"WHERE src=0 AND dst!=0 AND ts>=? GROUP BY dst, type, ts HAVING COUNT(*)>1 "
|
||||
"ORDER BY n DESC LIMIT ?", (since, top))]
|
||||
# 3) Дубли по идемпотентному ref (после деплоя их быть не должно).
|
||||
out["duplicate_refs"] = [] if not has_ref else [
|
||||
dict(r) for r in con.execute(
|
||||
"SELECT type, ref, COUNT(*) AS n FROM econ_tx WHERE ref IS NOT NULL "
|
||||
"GROUP BY type, ref HAVING COUNT(*)>1 ORDER BY n DESC LIMIT ?", (top,))]
|
||||
# 4) Дуэли: несколько выплат на одну дуэль (по ref, если заполнен).
|
||||
if has_ref:
|
||||
out["duel_multi_payout"] = [
|
||||
dict(r) for r in con.execute(
|
||||
"SELECT ref, COUNT(*) AS n, SUM(units) AS units FROM econ_tx "
|
||||
"WHERE type LIKE 'duel:%' AND ref IS NOT NULL GROUP BY ref HAVING COUNT(*)>1 "
|
||||
"ORDER BY n DESC LIMIT ?", (top,))]
|
||||
out["grants_without_payout"] = con.execute(
|
||||
"SELECT COUNT(*) FROM econ_grants g WHERE NOT EXISTS ("
|
||||
"SELECT 1 FROM econ_tx t WHERE t.dst=g.uid AND t.src=0 AND ("
|
||||
"t.type='achv:'||g.code OR t.type='streak:'||g.code OR t.type=g.code))").fetchone()[0]
|
||||
out["grants_total"] = con.execute("SELECT COUNT(*) FROM econ_grants").fetchone()[0]
|
||||
out["mints_total_units_window"] = con.execute(
|
||||
"SELECT COALESCE(SUM(units),0) FROM econ_tx WHERE src=0 AND ts>=?", (since,)).fetchone()[0]
|
||||
out["burns_total_units_window"] = con.execute(
|
||||
"SELECT COALESCE(SUM(units),0) FROM econ_tx WHERE dst=0 AND src!=0 AND ts>=?", (since,)).fetchone()[0]
|
||||
stranded = [r[0] for r in con.execute(
|
||||
"SELECT DISTINCT dst FROM econ_tx WHERE src=0 AND ts>=? LIMIT 500", (since,))]
|
||||
finally:
|
||||
con.close()
|
||||
if gw_db and stranded:
|
||||
missing = []
|
||||
for uid in stranded:
|
||||
if resolve_wallet(gw_db, bot_db, uid) is None:
|
||||
missing.append(uid)
|
||||
out["wallet_missing_uids"] = missing[:top]
|
||||
out["wallet_missing_count"] = len(missing)
|
||||
return out
|
||||
@@ -0,0 +1,187 @@
|
||||
from contextlib import closing
|
||||
import os
|
||||
import sqlite3
|
||||
import time
|
||||
import unicodedata
|
||||
|
||||
BOT_DB = os.environ.get("IISHKO_BOT_DB", os.environ.get("GROK_BOT_DB", "/opt/grok-bot/bot.db"))
|
||||
WINDOW = 86400
|
||||
TAG_MAX = 48
|
||||
TAG_LIMIT = 12
|
||||
|
||||
|
||||
def _connect():
|
||||
con = sqlite3.connect(BOT_DB, timeout=10)
|
||||
con.row_factory = sqlite3.Row
|
||||
con.execute("PRAGMA busy_timeout=8000")
|
||||
return con
|
||||
|
||||
|
||||
def init_db():
|
||||
with closing(_connect()) as con:
|
||||
con.executescript("""
|
||||
CREATE TABLE IF NOT EXISTS wa_entry_tags (
|
||||
id INTEGER PRIMARY KEY AUTOINCREMENT,
|
||||
ip_hmac TEXT NOT NULL,
|
||||
tag TEXT NOT NULL,
|
||||
created_at INTEGER NOT NULL,
|
||||
by_uid INTEGER NOT NULL DEFAULT 0,
|
||||
UNIQUE(ip_hmac, tag)
|
||||
);
|
||||
CREATE INDEX IF NOT EXISTS wa_entry_tag_net ON wa_entry_tags(ip_hmac);
|
||||
CREATE TABLE IF NOT EXISTS wa_entry_tag_prompts (
|
||||
message_id INTEGER PRIMARY KEY,
|
||||
chat_id INTEGER NOT NULL,
|
||||
alert_id INTEGER NOT NULL,
|
||||
ip_hmac TEXT NOT NULL,
|
||||
alert_message_id INTEGER NOT NULL DEFAULT 0,
|
||||
admin_id INTEGER NOT NULL,
|
||||
created_at INTEGER NOT NULL
|
||||
);
|
||||
""")
|
||||
con.commit()
|
||||
return True
|
||||
|
||||
|
||||
def clean_tag(value):
|
||||
if not isinstance(value, str):
|
||||
return ""
|
||||
text = "".join(ch for ch in value[:TAG_MAX * 4]
|
||||
if not unicodedata.category(ch).startswith("C"))
|
||||
return " ".join(text.split())[:TAG_MAX]
|
||||
|
||||
|
||||
def alert(alert_id):
|
||||
try:
|
||||
alert_id = int(alert_id)
|
||||
except (TypeError, ValueError):
|
||||
return None
|
||||
with closing(_connect()) as con:
|
||||
row = con.execute("SELECT id,ip_hmac,created_at,accounts,country,city,geo_source "
|
||||
"FROM wa_entry_alerts WHERE id=?", (alert_id,)).fetchone()
|
||||
if row is None:
|
||||
return None
|
||||
data = dict(row)
|
||||
try:
|
||||
import json
|
||||
data["accounts"] = json.loads(data.get("accounts") or "[]")
|
||||
except ValueError:
|
||||
data["accounts"] = []
|
||||
data["uids"] = [int(item["uid"]) for item in data["accounts"]
|
||||
if isinstance(item, dict) and isinstance(item.get("uid"), int)]
|
||||
return data
|
||||
|
||||
|
||||
def recent_alerts(limit=5):
|
||||
limit = max(1, min(int(limit or 5), 20))
|
||||
with closing(_connect()) as con:
|
||||
rows = con.execute("SELECT id,ip_hmac,created_at,accounts,country,city "
|
||||
"FROM wa_entry_alerts ORDER BY id DESC LIMIT ?", (limit,)).fetchall()
|
||||
out = []
|
||||
for row in rows:
|
||||
item = dict(row)
|
||||
try:
|
||||
import json
|
||||
item["accounts"] = json.loads(item.get("accounts") or "[]")
|
||||
except ValueError:
|
||||
item["accounts"] = []
|
||||
out.append(item)
|
||||
return out
|
||||
|
||||
|
||||
def net_accounts(ip_hmac, window=WINDOW, limit=40):
|
||||
"""Every account that entered through this network inside the window."""
|
||||
now = int(time.time())
|
||||
with closing(_connect()) as con:
|
||||
rows = con.execute(
|
||||
"SELECT v.uid, u.username, COALESCE(u.banned,0) AS banned, COALESCE(u.admin,0) AS admin, "
|
||||
"v.last_visit, v.country, v.city FROM wa_entry_visits v "
|
||||
"LEFT JOIN users u ON u.tg_id=v.uid WHERE v.ip_hmac=? AND v.last_visit>? "
|
||||
"ORDER BY v.last_visit DESC LIMIT ?", (str(ip_hmac), now - int(window), limit)).fetchall()
|
||||
return [dict(row) for row in rows]
|
||||
|
||||
|
||||
def tags(ip_hmac):
|
||||
if not ip_hmac:
|
||||
return []
|
||||
with closing(_connect()) as con:
|
||||
rows = con.execute("SELECT tag FROM wa_entry_tags WHERE ip_hmac=? "
|
||||
"ORDER BY id LIMIT ?", (str(ip_hmac), TAG_LIMIT)).fetchall()
|
||||
return [row["tag"] for row in rows]
|
||||
|
||||
|
||||
def add_tag(ip_hmac, tag, by_uid=0):
|
||||
tag = clean_tag(tag)
|
||||
if not tag or not ip_hmac:
|
||||
return False
|
||||
with closing(_connect()) as con:
|
||||
count = con.execute("SELECT COUNT(*) FROM wa_entry_tags WHERE ip_hmac=?", (str(ip_hmac),)).fetchone()[0]
|
||||
exists = con.execute("SELECT 1 FROM wa_entry_tags WHERE ip_hmac=? AND tag=?",
|
||||
(str(ip_hmac), tag)).fetchone()
|
||||
if exists is None and count >= TAG_LIMIT:
|
||||
return False
|
||||
con.execute("INSERT OR IGNORE INTO wa_entry_tags(ip_hmac,tag,created_at,by_uid) VALUES(?,?,?,?)",
|
||||
(str(ip_hmac), tag, int(time.time()), int(by_uid or 0)))
|
||||
con.commit()
|
||||
return True
|
||||
|
||||
|
||||
def del_tag(ip_hmac, tag):
|
||||
tag = clean_tag(tag)
|
||||
if not tag or not ip_hmac:
|
||||
return False
|
||||
with closing(_connect()) as con:
|
||||
cur = con.execute("DELETE FROM wa_entry_tags WHERE ip_hmac=? AND tag=?",
|
||||
(str(ip_hmac), tag))
|
||||
con.commit()
|
||||
return cur.rowcount > 0
|
||||
|
||||
|
||||
def apply_tags(ip_hmac, raw, by_uid=0):
|
||||
"""Accepts 'a, b, c' or '-a' to drop a tag. Returns (added, removed, all_tags)."""
|
||||
added, removed = [], []
|
||||
for chunk in str(raw or "").replace(";", ",").split(",")[:8]:
|
||||
chunk = chunk.strip()
|
||||
if not chunk:
|
||||
continue
|
||||
if chunk.startswith("-"):
|
||||
if del_tag(ip_hmac, chunk[1:]):
|
||||
removed.append(clean_tag(chunk[1:]))
|
||||
elif add_tag(ip_hmac, chunk, by_uid):
|
||||
added.append(clean_tag(chunk))
|
||||
return added, removed, tags(ip_hmac)
|
||||
|
||||
|
||||
def save_prompt(message_id, chat_id, alert_id, ip_hmac, alert_message_id, admin_id):
|
||||
with closing(_connect()) as con:
|
||||
con.execute("DELETE FROM wa_entry_tag_prompts WHERE created_at<?",
|
||||
(int(time.time()) - 3 * WINDOW,))
|
||||
con.execute("INSERT OR REPLACE INTO wa_entry_tag_prompts"
|
||||
"(message_id,chat_id,alert_id,ip_hmac,alert_message_id,admin_id,created_at) "
|
||||
"VALUES(?,?,?,?,?,?,?)",
|
||||
(int(message_id), int(chat_id), int(alert_id), str(ip_hmac),
|
||||
int(alert_message_id or 0), int(admin_id), int(time.time())))
|
||||
con.commit()
|
||||
return True
|
||||
|
||||
|
||||
def has_prompt(message_id, admin_id):
|
||||
with closing(_connect()) as con:
|
||||
row = con.execute("SELECT 1 FROM wa_entry_tag_prompts WHERE message_id=? AND admin_id=?",
|
||||
(int(message_id), int(admin_id))).fetchone()
|
||||
return row is not None
|
||||
|
||||
|
||||
def take_prompt(message_id):
|
||||
with closing(_connect()) as con:
|
||||
row = con.execute("SELECT * FROM wa_entry_tag_prompts WHERE message_id=?",
|
||||
(int(message_id),)).fetchone()
|
||||
if row is None:
|
||||
return None
|
||||
con.execute("DELETE FROM wa_entry_tag_prompts WHERE message_id=?", (int(message_id),))
|
||||
con.commit()
|
||||
return dict(row)
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
print("init_db:", init_db())
|
||||
@@ -0,0 +1,268 @@
|
||||
import json
|
||||
import logging
|
||||
import os
|
||||
from pathlib import Path
|
||||
import re
|
||||
import sqlite3
|
||||
|
||||
log = logging.getLogger("entry_autoban")
|
||||
|
||||
BOT_DB = os.environ.get("IISHKO_BOT_DB", "/opt/grok-bot/bot.db")
|
||||
GW_DB = os.environ.get("IISHKO_GW_DB", "/opt/grok-gateway/new-api/one-api.db")
|
||||
SKIN_DB = os.environ.get("IISHKO_SKIN_DB", "/opt/grok-web-skin-tg.db")
|
||||
|
||||
PROTECT = tuple(int(v) for v in os.environ.get("IISHKO_PROTECTED_UIDS", "").replace(";", ",").split(",")
|
||||
if v.strip().isdigit())
|
||||
|
||||
|
||||
def enabled():
|
||||
return os.environ.get("IISHKO_ENTRY_AUTOBAN", "1").strip().lower() not in ("0", "off", "no", "false")
|
||||
|
||||
|
||||
def _connect(path):
|
||||
con = sqlite3.connect(Path(path).resolve().as_uri() + "?mode=rw", uri=True, timeout=10)
|
||||
try:
|
||||
con.row_factory = sqlite3.Row
|
||||
con.execute("PRAGMA synchronous=FULL")
|
||||
return con
|
||||
except BaseException:
|
||||
con.close()
|
||||
raise
|
||||
|
||||
|
||||
def _main_name(name, uid):
|
||||
"""Accept the exact stored main name, never another account's reserved name."""
|
||||
if not name:
|
||||
return None
|
||||
if name.startswith(("tg", "pm", "sol")):
|
||||
match = re.fullmatch(r"(?:tg|pm|sol)([1-9][0-9]*)(?:-k[1-9][0-9]*)?", name)
|
||||
if not match or int(match[1]) != uid:
|
||||
return None
|
||||
return name
|
||||
|
||||
|
||||
def _snapshot(con, uid, reason, tokens):
|
||||
"""Stage an append-only preimage; caller MUST commit before updating tokens."""
|
||||
con.execute("CREATE TABLE IF NOT EXISTS entry_autobans("
|
||||
"ts INTEGER NOT NULL, uid INTEGER NOT NULL, reason TEXT NOT NULL, "
|
||||
"tokens TEXT NOT NULL DEFAULT '', applied INTEGER NOT NULL DEFAULT 1)")
|
||||
cols = {r[1] for r in con.execute("PRAGMA table_info(entry_autobans)")}
|
||||
if "tokens" not in cols:
|
||||
con.execute("ALTER TABLE entry_autobans ADD COLUMN tokens TEXT NOT NULL DEFAULT ''")
|
||||
if "applied" not in cols:
|
||||
con.execute("ALTER TABLE entry_autobans ADD COLUMN applied INTEGER NOT NULL DEFAULT 1")
|
||||
payload = json.dumps(tokens, ensure_ascii=False, separators=(",", ":"), allow_nan=False)
|
||||
# A failed apply can retry only the identical preimage. Never overwrite history.
|
||||
previous = con.execute("SELECT rowid,tokens,applied FROM entry_autobans "
|
||||
"WHERE uid=? ORDER BY rowid DESC LIMIT 1", (uid,)).fetchone()
|
||||
if previous and not previous["applied"] and previous["tokens"] == payload:
|
||||
return previous["rowid"], payload
|
||||
cur = con.execute("INSERT INTO entry_autobans(ts,uid,reason,tokens,applied) "
|
||||
"VALUES(strftime('%s','now'),?,?,?,0)", (uid, str(reason)[:120], payload))
|
||||
return cur.lastrowid, payload
|
||||
|
||||
|
||||
def _processed(g, con, uid, was_banned):
|
||||
g.execute("CREATE TABLE IF NOT EXISTS entry_autoban_applied("
|
||||
"uid INTEGER PRIMARY KEY,tokens TEXT NOT NULL)")
|
||||
row = g.execute("SELECT tokens FROM entry_autoban_applied WHERE uid=?", (uid,)).fetchone()
|
||||
if not was_banned:
|
||||
return set()
|
||||
legacy = False
|
||||
if row is None and con.execute(
|
||||
"SELECT 1 FROM sqlite_master WHERE type='table' AND name='entry_autobans'").fetchone():
|
||||
cols = {r[1] for r in con.execute("PRAGMA table_info(entry_autobans)")}
|
||||
if "tokens" in cols:
|
||||
# Older cluster bans recorded the original preimage after applying.
|
||||
# Do not burn those same credentials again while migrating receipts.
|
||||
applied = " AND applied=1" if "applied" in cols else ""
|
||||
row = con.execute("SELECT tokens FROM entry_autobans WHERE uid=?" + applied
|
||||
+ " ORDER BY rowid DESC LIMIT 1", (uid,)).fetchone()
|
||||
legacy = True
|
||||
if row is None or (legacy and not row["tokens"]):
|
||||
return set()
|
||||
data = json.loads(row["tokens"])
|
||||
if legacy:
|
||||
if not isinstance(data, list) or any(not isinstance(item, dict) for item in data):
|
||||
raise ValueError("invalid autoban recovery record")
|
||||
data = [[item.get("id"), item.get("name")] for item in data]
|
||||
if not isinstance(data, list) or any(
|
||||
not isinstance(item, list) or len(item) != 2 or type(item[0]) is not int
|
||||
or not isinstance(item[1], str) for item in data):
|
||||
raise ValueError("invalid autoban apply receipt")
|
||||
return {tuple(item) for item in data}
|
||||
|
||||
|
||||
def ban_user(uid, reason="entry_ip_collision", taken=None):
|
||||
uid = int(uid)
|
||||
if uid in PROTECT:
|
||||
return False
|
||||
g = _connect(GW_DB)
|
||||
saved = None
|
||||
try:
|
||||
# Same acquisition order as econ_guard/account_admin: gateway, then bot.
|
||||
# Keep the gateway write reservation through the separate durable audit
|
||||
g.execute("BEGIN IMMEDIATE")
|
||||
con = _connect(BOT_DB)
|
||||
try:
|
||||
con.execute("BEGIN IMMEDIATE")
|
||||
if (con.execute("SELECT 1 FROM sqlite_master WHERE type='table' AND name='ban_wl'").fetchone()
|
||||
and con.execute("SELECT 1 FROM ban_wl WHERE uid=?", (uid,)).fetchone()):
|
||||
return False
|
||||
account = con.execute("SELECT token_name,admin,banned FROM users WHERE tg_id=?",
|
||||
(uid,)).fetchone()
|
||||
if account is not None and account["admin"]:
|
||||
return False
|
||||
tname = _main_name(account["token_name"], uid) if account is not None else None
|
||||
was_banned = bool(account["banned"]) if account is not None else False
|
||||
if tname and con.execute("SELECT 1 FROM users WHERE token_name=? AND tg_id!=? LIMIT 1",
|
||||
(tname, uid)).fetchone():
|
||||
raise ValueError("ambiguous autoban main ownership")
|
||||
names = list(dict.fromkeys(n for n in (tname, "pm%d" % uid, "sol%d" % uid) if n))
|
||||
tokens = []
|
||||
for name in names:
|
||||
tokens.extend(g.execute(
|
||||
"SELECT id,name,status,remain_quota,unlimited_quota FROM tokens "
|
||||
"WHERE name=? AND deleted_at IS NULL ORDER BY id", (name,)).fetchall())
|
||||
finite = [row for row in tokens if not row["unlimited_quota"]]
|
||||
if any(type(row["remain_quota"]) is not int for row in finite):
|
||||
raise ValueError("invalid autoban quota")
|
||||
processed = _processed(g, con, uid, was_banned)
|
||||
pending = [row for row in finite if (row["id"], row["name"]) not in processed]
|
||||
if any(row["remain_quota"] > 0 for row in pending):
|
||||
saved = _snapshot(con, uid, reason, [
|
||||
{"id": row["id"], "name": row["name"], "status": row["status"],
|
||||
"quota": row["remain_quota"], "unlimited_quota": row["unlimited_quota"]}
|
||||
for row in pending])
|
||||
con.commit() # FULL synchronous audit, before any token UPDATE.
|
||||
finally:
|
||||
con.close()
|
||||
|
||||
# Financial preimage is already durable. Attach only now, otherwise
|
||||
# BEGIN IMMEDIATE would lock bot.db against the independent audit commit.
|
||||
g.execute("ATTACH DATABASE ? AS bot", (Path(BOT_DB).resolve().as_uri() + "?mode=rw",))
|
||||
current = g.execute("SELECT token_name,admin,banned FROM bot.users WHERE tg_id=?",
|
||||
(uid,)).fetchone()
|
||||
if (tuple(current) if current is not None else None) != (
|
||||
tuple(account) if account is not None else None):
|
||||
raise ValueError("autoban account changed; retry")
|
||||
if account is None:
|
||||
if g.execute("INSERT INTO bot.users(tg_id,username,banned) VALUES(?,'',1)", (uid,)).rowcount != 1:
|
||||
raise RuntimeError("autoban account insert failed")
|
||||
elif g.execute("UPDATE bot.users SET banned=1 WHERE tg_id=?", (uid,)).rowcount != 1:
|
||||
raise RuntimeError("autoban account update failed")
|
||||
if tname and g.execute("SELECT 1 FROM bot.users WHERE token_name=? AND tg_id!=? LIMIT 1",
|
||||
(tname, uid)).fetchone():
|
||||
raise ValueError("ambiguous autoban main ownership")
|
||||
if saved and g.execute(
|
||||
"UPDATE bot.entry_autobans SET applied=1 "
|
||||
"WHERE rowid=? AND uid=? AND tokens=? AND applied=0",
|
||||
(saved[0], uid, saved[1])).rowcount != 1:
|
||||
raise RuntimeError("autoban recovery record changed")
|
||||
for row in finite:
|
||||
identity = (row["id"], row["name"])
|
||||
quota = row["remain_quota"] if identity in processed else min(row["remain_quota"], 0)
|
||||
status = 2 if row["status"] == 1 else row["status"]
|
||||
if quota != row["remain_quota"] or status != row["status"]:
|
||||
cur = g.execute(
|
||||
"UPDATE tokens SET status=?,remain_quota=? WHERE id=? AND name=? "
|
||||
"AND deleted_at IS NULL AND remain_quota=? AND status IS ? "
|
||||
"AND NOT COALESCE(unlimited_quota,0)",
|
||||
(status, quota, row["id"], row["name"], row["remain_quota"], row["status"]))
|
||||
if cur.rowcount != 1:
|
||||
raise RuntimeError("autoban token update failed")
|
||||
processed.add(identity)
|
||||
g.execute("UPDATE users SET status=2 WHERE username=? AND status=1", ("tg%d" % uid,))
|
||||
if g.execute("INSERT OR REPLACE INTO entry_autoban_applied(uid,tokens) VALUES(?,?)",
|
||||
(uid, json.dumps(sorted(processed), ensure_ascii=False, separators=(",", ":")))).rowcount != 1:
|
||||
raise RuntimeError("autoban apply receipt failed")
|
||||
# roll back bot flags; WAL cannot promise cross-file crash atomicity.
|
||||
g.commit()
|
||||
except BaseException:
|
||||
g.rollback()
|
||||
raise
|
||||
finally:
|
||||
g.close()
|
||||
if tname:
|
||||
con = _connect(SKIN_DB)
|
||||
try:
|
||||
con.execute("DELETE FROM ip_claims WHERE token_name=?", (tname,))
|
||||
con.commit()
|
||||
finally:
|
||||
con.close()
|
||||
if taken is not None and saved:
|
||||
taken[uid] = saved[1]
|
||||
log.warning("[ENTRY-AUTOBAN] enforced uid=%s", uid)
|
||||
return not was_banned
|
||||
|
||||
|
||||
def ban_cluster(uids, reason="entry_ip_collision"):
|
||||
uids = [int(u) for u in uids]
|
||||
if not enabled():
|
||||
log.warning("[ENTRY-AUTOBAN] disabled")
|
||||
return []
|
||||
out = []
|
||||
for uid in dict.fromkeys(uids):
|
||||
try:
|
||||
if ban_user(uid, reason):
|
||||
out.append(uid)
|
||||
except Exception as exc:
|
||||
log.error("entry_autoban failed uid=%s error=%s", uid, type(exc).__name__)
|
||||
return out
|
||||
|
||||
|
||||
def _gw_exec(sql, params=()):
|
||||
con = sqlite3.connect(GW_DB, timeout=10)
|
||||
try:
|
||||
con.execute(sql, params)
|
||||
con.commit()
|
||||
finally:
|
||||
con.close()
|
||||
|
||||
|
||||
def _last_snapshot(uid):
|
||||
"""Pre-ban token state written by _snapshot(), newest first."""
|
||||
try:
|
||||
con = sqlite3.connect(BOT_DB, timeout=10)
|
||||
try:
|
||||
con.execute("CREATE TABLE IF NOT EXISTS entry_autobans("
|
||||
"ts INTEGER NOT NULL, uid INTEGER NOT NULL, reason TEXT NOT NULL, "
|
||||
"tokens TEXT NOT NULL DEFAULT '')")
|
||||
row = con.execute("SELECT tokens FROM entry_autobans WHERE uid=? "
|
||||
"ORDER BY ts DESC, rowid DESC LIMIT 1",
|
||||
(int(uid),)).fetchone()
|
||||
finally:
|
||||
con.close()
|
||||
except Exception:
|
||||
log.exception("entry_unban snapshot read uid=%s", uid)
|
||||
return []
|
||||
if not row or not row[0]:
|
||||
return []
|
||||
try:
|
||||
data = json.loads(row[0])
|
||||
except ValueError:
|
||||
return []
|
||||
seen, clean = set(), []
|
||||
for item in data if isinstance(data, list) else []:
|
||||
if not isinstance(item, dict) or "id" not in item or item["id"] in seen:
|
||||
continue
|
||||
seen.add(item["id"])
|
||||
clean.append(item)
|
||||
return clean
|
||||
|
||||
|
||||
def unban_user(uid, *, restore_tokens=True, reason="admin_button",
|
||||
actor_uid=None, admin_ids=()):
|
||||
import account_admin
|
||||
account_admin.unban_account(BOT_DB, GW_DB, uid, actor_uid=actor_uid,
|
||||
admin_ids=admin_ids)
|
||||
return True
|
||||
|
||||
|
||||
def unban_cluster(uids, reason="admin_button", *, actor_uid=None, admin_ids=()):
|
||||
"""Compatibility entry point; each target uses the same authorized unban."""
|
||||
out = []
|
||||
for uid in dict.fromkeys(uids):
|
||||
if unban_user(uid, reason=reason, actor_uid=actor_uid, admin_ids=admin_ids):
|
||||
out.append(uid)
|
||||
return out
|
||||
@@ -0,0 +1,275 @@
|
||||
"""Approximate country/city from a fixed, integrity-pinned local DB-IP database.
|
||||
|
||||
The caller must enforce existing privacy consent and run this synchronous helper
|
||||
outside the event loop. Import does not open data. There are no network calls,
|
||||
DNS lookups, environment overrides, updates, input/result caches or log messages.
|
||||
A missing/changed/broken asset disables lookups until process restart. The data
|
||||
file must be deployed read-only and replaced only while the service is stopped.
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import atexit
|
||||
from contextlib import suppress
|
||||
import hashlib
|
||||
import ipaddress
|
||||
import mmap
|
||||
import os
|
||||
import stat
|
||||
import threading
|
||||
from pathlib import Path
|
||||
|
||||
ATTRIBUTION_TEXT = "IP Geolocation by DB-IP"
|
||||
ATTRIBUTION_URL = "https://db-ip.com"
|
||||
LICENSE_URL = "https://creativecommons.org/licenses/by/4.0/"
|
||||
SOURCE = "DB-IP Lite 2026-10 (https://db-ip.com)"
|
||||
|
||||
_DATA_PATH = Path(__file__).absolute().parent / "geo" / "dbip-city-lite-2026-10.mmdb"
|
||||
_EXPECTED_SIZE = 126998165
|
||||
_EXPECTED_SHA256 = "9e250f02722d1ad1780f88192f0e908af285478a33e76b88b349c9181ae9d0f5"
|
||||
_HASH_CHUNK_SIZE = 1024 * 1024
|
||||
_UNINITIALIZED = object()
|
||||
_STATE = _UNINITIALIZED
|
||||
_LOCK = threading.Lock()
|
||||
|
||||
# Conservative, explicit special-purpose exclusions also close classification
|
||||
# differences between the Python 3.11 and 3.14 ipaddress registries. IPv6 is
|
||||
# limited to allocated global unicast; mapped IPv4 is classified as IPv4 first.
|
||||
_SPECIAL_V4 = tuple(
|
||||
ipaddress.ip_network(network)
|
||||
for network in ("192.0.0.0/24", "192.88.99.0/24")
|
||||
)
|
||||
_GLOBAL_V6 = ipaddress.ip_network("2000::/3")
|
||||
_SPECIAL_V6 = tuple(
|
||||
ipaddress.ip_network(network)
|
||||
for network in ("2001::/23", "2001:db8::/32", "2002::/16", "3fff::/20")
|
||||
)
|
||||
|
||||
__all__ = ["lookup_ip", "ATTRIBUTION_TEXT", "ATTRIBUTION_URL", "LICENSE_URL", "SOURCE"]
|
||||
|
||||
|
||||
class _ReaderState:
|
||||
__slots__ = ("path", "reader", "buffer", "signature")
|
||||
|
||||
def __init__(self, path, reader, buffer, signature):
|
||||
self.path = path
|
||||
self.reader = reader
|
||||
self.buffer = buffer
|
||||
self.signature = signature
|
||||
|
||||
|
||||
def _canonical_public_ip(value):
|
||||
if not isinstance(value, str) or not value or len(value) > 45 or "%" in value:
|
||||
return None
|
||||
try:
|
||||
address = ipaddress.ip_address(value)
|
||||
except ValueError:
|
||||
return None
|
||||
if isinstance(address, ipaddress.IPv6Address) and address.ipv4_mapped is not None:
|
||||
address = address.ipv4_mapped
|
||||
if (
|
||||
not address.is_global
|
||||
or address.is_private
|
||||
or address.is_reserved
|
||||
or address.is_loopback
|
||||
or address.is_link_local
|
||||
or address.is_multicast
|
||||
or address.is_unspecified
|
||||
):
|
||||
return None
|
||||
if isinstance(address, ipaddress.IPv4Address):
|
||||
if any(address in network for network in _SPECIAL_V4):
|
||||
return None
|
||||
elif address not in _GLOBAL_V6 or any(address in network for network in _SPECIAL_V6):
|
||||
return None
|
||||
return str(address)
|
||||
|
||||
|
||||
def _signature(info):
|
||||
return (info.st_dev, info.st_ino, info.st_size, info.st_mtime_ns, info.st_ctime_ns)
|
||||
|
||||
|
||||
def _regular_file_info(path):
|
||||
info = path.stat(follow_symlinks=False)
|
||||
if not stat.S_ISREG(info.st_mode):
|
||||
raise ValueError("Geo data is not a regular file")
|
||||
if getattr(info, "st_file_attributes", 0) & getattr(stat, "FILE_ATTRIBUTE_REPARSE_POINT", 0x400):
|
||||
raise ValueError("Geo data reparse points are not supported")
|
||||
if info.st_size != _EXPECTED_SIZE:
|
||||
raise ValueError("Geo data size does not match pin")
|
||||
return info
|
||||
|
||||
|
||||
def _local_path():
|
||||
text = os.fspath(_DATA_PATH)
|
||||
# A path override is not a supported interface. Keep even accidental local
|
||||
# configuration changes from opening URLs, UNC shares or Windows devices.
|
||||
if (
|
||||
not isinstance(text, str)
|
||||
or not text
|
||||
or "\x00" in text
|
||||
or "://" in text
|
||||
or text.startswith(("\\", "//"))
|
||||
or ":" in text[2:]
|
||||
):
|
||||
raise ValueError("Geo data must use a local absolute path")
|
||||
path = Path(text)
|
||||
if not path.is_absolute():
|
||||
raise ValueError("Geo data path is not absolute")
|
||||
return path
|
||||
|
||||
|
||||
def _new_reader(buffer):
|
||||
# Use only the inspected pure-Python implementation, not an installed
|
||||
# package/extension. Feed the verified mapping directly to the pinned
|
||||
# reader, avoiding a pathname re-open between verification and decode.
|
||||
from vendor_entry_geo.reader import Reader
|
||||
|
||||
class _VerifiedMappedReader(Reader):
|
||||
def _load_buffer(self, database, mode=0):
|
||||
self._buffer = database
|
||||
self._buffer_size = len(database)
|
||||
return "verified offline DB-IP"
|
||||
|
||||
return _VerifiedMappedReader(buffer)
|
||||
|
||||
|
||||
def _open_state():
|
||||
path = _local_path()
|
||||
expected_signature = _signature(_regular_file_info(path))
|
||||
flags = os.O_RDONLY | getattr(os, "O_BINARY", 0) | getattr(os, "O_NOFOLLOW", 0) | getattr(os, "O_NONBLOCK", 0)
|
||||
buffer = None
|
||||
reader = None
|
||||
try:
|
||||
with os.fdopen(os.open(path, flags), "rb") as handle:
|
||||
info = os.fstat(handle.fileno())
|
||||
if not stat.S_ISREG(info.st_mode) or _signature(info) != expected_signature:
|
||||
raise ValueError("Geo data changed while opening")
|
||||
buffer = mmap.mmap(handle.fileno(), 0, access=mmap.ACCESS_READ)
|
||||
if len(buffer) != _EXPECTED_SIZE or buffer.size() != _EXPECTED_SIZE:
|
||||
raise ValueError("Geo mapping size does not match pin")
|
||||
digest = hashlib.sha256()
|
||||
for offset in range(0, _EXPECTED_SIZE, _HASH_CHUNK_SIZE):
|
||||
digest.update(buffer[offset : offset + _HASH_CHUNK_SIZE])
|
||||
if digest.hexdigest() != _EXPECTED_SHA256:
|
||||
raise ValueError("Geo data integrity check failed")
|
||||
if (
|
||||
_signature(os.fstat(handle.fileno())) != expected_signature
|
||||
or _signature(_regular_file_info(path)) != expected_signature
|
||||
):
|
||||
raise ValueError("Geo data changed while verifying")
|
||||
reader = _new_reader(buffer)
|
||||
metadata = reader.metadata()
|
||||
if (
|
||||
metadata.database_type != "DBIP-City-Lite"
|
||||
or metadata.binary_format_major_version != 2
|
||||
or metadata.ip_version != 6
|
||||
):
|
||||
raise ValueError("Unexpected geo database metadata")
|
||||
state = _ReaderState(path, reader, buffer, expected_signature)
|
||||
if not _still_current(state):
|
||||
raise ValueError("Geo data changed while initializing")
|
||||
return state
|
||||
except Exception:
|
||||
if reader is not None:
|
||||
with suppress(Exception):
|
||||
reader.close()
|
||||
if buffer is not None:
|
||||
with suppress(Exception):
|
||||
buffer.close()
|
||||
raise
|
||||
|
||||
|
||||
def _still_current(state):
|
||||
return (
|
||||
_signature(_regular_file_info(state.path)) == state.signature
|
||||
and state.buffer.size() == _EXPECTED_SIZE
|
||||
)
|
||||
|
||||
|
||||
def _name(value):
|
||||
if not isinstance(value, str) or len(value) > 160 or any(not char.isprintable() for char in value):
|
||||
return None
|
||||
return value.strip()
|
||||
|
||||
|
||||
def _approximate_record(record):
|
||||
if not isinstance(record, dict):
|
||||
return None
|
||||
country = record.get("country")
|
||||
city = record.get("city", {})
|
||||
if not isinstance(country, dict) or not isinstance(city, dict):
|
||||
return None
|
||||
iso_code = country.get("iso_code")
|
||||
if (
|
||||
not isinstance(iso_code, str)
|
||||
or len(iso_code) != 2
|
||||
or not iso_code.isascii()
|
||||
or not iso_code.isalpha()
|
||||
or not iso_code.isupper()
|
||||
or iso_code in ("ZZ", "XX", "EU", "AP")
|
||||
):
|
||||
return None
|
||||
country_names = country.get("names", {})
|
||||
city_names = city.get("names", {})
|
||||
if not isinstance(country_names, dict) or not isinstance(city_names, dict):
|
||||
return None
|
||||
country_name = _name(country_names.get("en", ""))
|
||||
city_name = _name(city_names.get("en", ""))
|
||||
if country_name is None or city_name is None:
|
||||
return None
|
||||
# A missing city stays unknown (empty string); do not synthesize one from
|
||||
# coordinates, subdivisions, a resolver, registered country or the input.
|
||||
return {"country": country_name or iso_code, "city": city_name, "source": SOURCE}
|
||||
|
||||
|
||||
def _disable_locked():
|
||||
global _STATE
|
||||
state = _STATE
|
||||
_STATE = None
|
||||
if isinstance(state, _ReaderState):
|
||||
with suppress(Exception):
|
||||
state.reader.close()
|
||||
with suppress(Exception):
|
||||
state.buffer.close()
|
||||
|
||||
|
||||
def _close():
|
||||
with _LOCK:
|
||||
_disable_locked()
|
||||
|
||||
|
||||
def lookup_ip(ip: str) -> dict[str, str] | None:
|
||||
"""Return only approximate country/city/source for a public literal, or None.
|
||||
|
||||
IPv4-mapped IPv6 is canonicalized to IPv4. Non-public and ambiguous inputs
|
||||
never initialize the reader. All file/integrity/reader failures are silent
|
||||
unknown results, with no raw IP in logs, storage or outbound requests.
|
||||
"""
|
||||
global _STATE
|
||||
canonical = _canonical_public_ip(ip)
|
||||
if canonical is None:
|
||||
return None
|
||||
with _LOCK:
|
||||
try:
|
||||
if _STATE is _UNINITIALIZED:
|
||||
_STATE = _open_state()
|
||||
if _STATE is None:
|
||||
return None
|
||||
state = _STATE
|
||||
if not _still_current(state):
|
||||
_disable_locked()
|
||||
return None
|
||||
record = state.reader.get(canonical)
|
||||
if not _still_current(state):
|
||||
_disable_locked()
|
||||
return None
|
||||
return _approximate_record(record)
|
||||
except Exception:
|
||||
# Deliberately do not log exception text: third-party reader errors
|
||||
# may include the lookup address. Fail once, closed, until restart.
|
||||
_disable_locked()
|
||||
return None
|
||||
|
||||
|
||||
atexit.register(_close)
|
||||
@@ -0,0 +1,372 @@
|
||||
"""Private Mini App network audit. Network matches are signals, never identity or bans."""
|
||||
import asyncio
|
||||
from collections import OrderedDict
|
||||
from contextlib import closing
|
||||
import hashlib
|
||||
import hmac
|
||||
import ipaddress
|
||||
import json
|
||||
import math
|
||||
import os
|
||||
from pathlib import Path
|
||||
import re
|
||||
import secrets
|
||||
import sqlite3
|
||||
import threading
|
||||
import time
|
||||
import unicodedata
|
||||
import logging
|
||||
|
||||
log = logging.getLogger("entry_telemetry")
|
||||
|
||||
from support_store import NotificationError
|
||||
|
||||
WINDOW = 86400
|
||||
# Known shared reverse-proxy/WARP networks; operators may add their own NAT/relay ranges.
|
||||
# Source: https://www.cloudflare.com/ips/ . This is suppression, not an IP blocklist.
|
||||
SHARED_EGRESS = (
|
||||
"103.21.244.0/22", "103.22.200.0/22", "103.31.4.0/22", "104.16.0.0/13",
|
||||
"104.24.0.0/14", "108.162.192.0/18", "131.0.72.0/22", "141.101.64.0/18",
|
||||
"162.158.0.0/15", "172.64.0.0/13", "173.245.48.0/20", "188.114.96.0/20",
|
||||
"190.93.240.0/20", "197.234.240.0/22", "198.41.128.0/17", "2400:cb00::/32",
|
||||
"2606:4700::/32", "2803:f800::/32", "2405:b500::/32", "2405:8100::/32",
|
||||
"2a06:98c0::/29", "2c0f:f248::/32",
|
||||
)
|
||||
|
||||
|
||||
class EntryError(Exception):
|
||||
def __init__(self, status=503, code="entry_unavailable", message="Не удалось сохранить вход. Попробуй позже."):
|
||||
super().__init__(code)
|
||||
self.status, self.code, self.message = status, code, message
|
||||
|
||||
|
||||
def canonical_ip(value):
|
||||
if not isinstance(value, str) or not value or len(value) > 64 or "%" in value:
|
||||
return None
|
||||
try:
|
||||
address = ipaddress.ip_address(value)
|
||||
except ValueError:
|
||||
return None
|
||||
if isinstance(address, ipaddress.IPv6Address) and address.ipv4_mapped is not None:
|
||||
address = address.ipv4_mapped
|
||||
return str(address)
|
||||
|
||||
|
||||
def trusted_ip(remote, headers):
|
||||
"""Only a loopback socket may carry Caddy's overwritten X-Real-IP. Never use XFF."""
|
||||
peer = canonical_ip(remote)
|
||||
if peer is None:
|
||||
return None
|
||||
if ipaddress.ip_address(peer).is_loopback:
|
||||
return canonical_ip(headers.get("X-Real-IP", "")) or peer
|
||||
return peer
|
||||
|
||||
|
||||
def public_ip(value):
|
||||
canonical = canonical_ip(value)
|
||||
if canonical is None:
|
||||
return None
|
||||
address = ipaddress.ip_address(canonical)
|
||||
if not address.is_global or any((address.is_multicast, address.is_reserved,
|
||||
address.is_unspecified, address.is_loopback,
|
||||
address.is_link_local, address.is_private)):
|
||||
return None
|
||||
return canonical
|
||||
|
||||
|
||||
def delivery_enabled():
|
||||
# The existing support switch is also a hard entry-delivery kill switch for old fixtures.
|
||||
return all(os.environ.get(name, "1") != "0" for name in (
|
||||
"IISHKO_NOTIFICATIONS_ENABLED", "IISHKO_SUPPORT_DELIVERY_ENABLED", "IISHKO_ENTRY_DELIVERY_ENABLED"))
|
||||
|
||||
|
||||
def _label(value, length):
|
||||
if not isinstance(value, str):
|
||||
return ""
|
||||
return "".join(char for char in value[:length * 4] if not unicodedata.category(char).startswith("C")).strip()[:length]
|
||||
|
||||
|
||||
def _username(value):
|
||||
return "@" + value if isinstance(value, str) and re.fullmatch(r"[A-Za-z0-9_]{1,32}", value) else "без username"
|
||||
|
||||
|
||||
def _networks(extra):
|
||||
values = list(SHARED_EGRESS) + list(extra)
|
||||
if len(values) > len(SHARED_EGRESS) + 64:
|
||||
raise ValueError("entry_shared_ranges_limit")
|
||||
result = []
|
||||
for value in values:
|
||||
network = ipaddress.ip_network(value, strict=False)
|
||||
if network.version == 6 and network.prefixlen >= 96 and network.network_address.ipv4_mapped is not None:
|
||||
network = ipaddress.ip_network(str(network.network_address.ipv4_mapped) + "/" + str(network.prefixlen - 96))
|
||||
result.append(network)
|
||||
return tuple(result)
|
||||
|
||||
|
||||
class EntryTelemetry:
|
||||
def __init__(self, path, secret, owners, *, lookup=None, clock=time.time,
|
||||
retention=3 * WINDOW, max_visits=20000, max_user_ips=32, max_alerts=2000,
|
||||
shared_cidrs=(), geo_cache_size=512, geo_cache_ttl=300,
|
||||
lease_seconds=60, max_attempts=3):
|
||||
if isinstance(secret, str):
|
||||
secret = secret.encode("utf-8")
|
||||
if not isinstance(secret, bytes) or not secret or len(secret) > 4096:
|
||||
raise ValueError("entry_hmac_key_invalid")
|
||||
self.key = hmac.new(secret, b"iishko-entry-audit-v1", hashlib.sha256).digest()
|
||||
self.path, self.clock, self.lookup = str(path), clock, lookup
|
||||
self.owners = tuple(sorted({uid for uid in owners if type(uid) is int and 0 < uid <= 2**63 - 1}))
|
||||
if len(self.owners) > 64:
|
||||
raise ValueError("entry_owners_limit")
|
||||
self.retention = max(WINDOW, min(int(retention), 7 * WINDOW))
|
||||
self.max_visits, self.max_user_ips, self.max_alerts = max_visits, max_user_ips, max_alerts
|
||||
self.shared_ranges = _networks(shared_cidrs)
|
||||
self.geo_cache_size, self.geo_cache_ttl = max(1, geo_cache_size), max(1, geo_cache_ttl)
|
||||
self.geo_cache, self.geo_lock = OrderedDict(), threading.Lock()
|
||||
self.lease_seconds, self.max_attempts = lease_seconds, max_attempts
|
||||
|
||||
def connect(self):
|
||||
con = sqlite3.connect(Path(self.path).resolve().as_uri() + "?mode=rw", uri=True, timeout=0.5)
|
||||
con.row_factory = sqlite3.Row
|
||||
con.execute("PRAGMA foreign_keys=ON")
|
||||
con.execute("PRAGMA secure_delete=ON")
|
||||
return con
|
||||
|
||||
def init_db(self):
|
||||
with closing(self.connect()) as con:
|
||||
con.executescript("""
|
||||
CREATE TABLE IF NOT EXISTS wa_entry_visits (
|
||||
ip_hmac TEXT NOT NULL, uid INTEGER NOT NULL,
|
||||
first_visit INTEGER NOT NULL, last_visit INTEGER NOT NULL,
|
||||
country TEXT NOT NULL, city TEXT NOT NULL, geo_source TEXT NOT NULL,
|
||||
shared_egress INTEGER NOT NULL, PRIMARY KEY(ip_hmac,uid)
|
||||
);
|
||||
CREATE INDEX IF NOT EXISTS wa_entry_ip_time ON wa_entry_visits(ip_hmac,last_visit);
|
||||
CREATE INDEX IF NOT EXISTS wa_entry_uid_time ON wa_entry_visits(uid,last_visit);
|
||||
CREATE TABLE IF NOT EXISTS wa_entry_alerts (
|
||||
id INTEGER PRIMARY KEY AUTOINCREMENT, ip_hmac TEXT NOT NULL,
|
||||
created_at INTEGER NOT NULL, accounts TEXT NOT NULL,
|
||||
country TEXT NOT NULL, city TEXT NOT NULL, geo_source TEXT NOT NULL
|
||||
);
|
||||
CREATE INDEX IF NOT EXISTS wa_entry_alert_ip_time ON wa_entry_alerts(ip_hmac,created_at);
|
||||
CREATE TABLE IF NOT EXISTS wa_entry_outbox (
|
||||
alert_id INTEGER NOT NULL REFERENCES wa_entry_alerts(id) ON DELETE CASCADE,
|
||||
owner_id INTEGER NOT NULL, status TEXT NOT NULL DEFAULT 'pending',
|
||||
attempts INTEGER NOT NULL DEFAULT 0, next_attempt REAL NOT NULL DEFAULT 0,
|
||||
lease_until REAL NOT NULL DEFAULT 0, claim_token TEXT NOT NULL DEFAULT '',
|
||||
PRIMARY KEY(alert_id,owner_id)
|
||||
);
|
||||
CREATE INDEX IF NOT EXISTS wa_entry_pending ON wa_entry_outbox(status,next_attempt);
|
||||
""")
|
||||
self._prune(con, self.clock())
|
||||
con.commit()
|
||||
|
||||
def ip_tag(self, ip):
|
||||
return hmac.new(self.key, ("ip:" + ip).encode("ascii"), hashlib.sha256).hexdigest()
|
||||
|
||||
def _prune(self, con, now):
|
||||
con.execute("DELETE FROM wa_entry_visits WHERE last_visit<=?", (now - self.retention,))
|
||||
con.execute("DELETE FROM wa_entry_alerts WHERE created_at<=?", (now - self.retention,))
|
||||
# A lost claim may have reached Telegram. Expiry is NOT permission to resend.
|
||||
con.execute("UPDATE wa_entry_outbox SET status='uncertain',lease_until=0,claim_token='' "
|
||||
"WHERE status='sending' AND lease_until<=?", (now,))
|
||||
|
||||
def prune(self):
|
||||
with closing(self.connect()) as con:
|
||||
self._prune(con, self.clock())
|
||||
con.commit()
|
||||
|
||||
@staticmethod
|
||||
def _eligible(con, uid):
|
||||
row = con.execute("SELECT tg_id,username,banned,privacy_ok FROM users WHERE tg_id=?", (uid,)).fetchone()
|
||||
if row is None or row["banned"] or row["privacy_ok"] != 1:
|
||||
raise EntryError(403, "entry_forbidden", "Для входа нужен зарегистрированный аккаунт и согласие на приватность.")
|
||||
return row
|
||||
|
||||
def _geo(self, ip, tag, now):
|
||||
with self.geo_lock:
|
||||
cached = self.geo_cache.get(tag)
|
||||
if cached is not None and cached[0] > now:
|
||||
self.geo_cache.move_to_end(tag)
|
||||
return dict(cached[1])
|
||||
value = None
|
||||
if self.lookup is not None:
|
||||
try:
|
||||
value = self.lookup(ip)
|
||||
except Exception:
|
||||
pass # Missing/broken offline data is unknown, never a network fallback.
|
||||
geo = {"country": "", "city": "", "source": "unknown"}
|
||||
if isinstance(value, dict):
|
||||
geo = {"country": _label(value.get("country"), 64),
|
||||
"city": _label(value.get("city"), 96),
|
||||
"source": _label(value.get("source"), 64) or "unknown"}
|
||||
self.geo_cache[tag] = (now + self.geo_cache_ttl, dict(geo))
|
||||
self.geo_cache.move_to_end(tag)
|
||||
while len(self.geo_cache) > self.geo_cache_size:
|
||||
self.geo_cache.popitem(last=False)
|
||||
return geo
|
||||
|
||||
def record(self, uid, ip):
|
||||
if type(uid) is not int or not 0 < uid <= 2**63 - 1:
|
||||
raise EntryError(403, "entry_forbidden", "Не удалось подтвердить аккаунт.")
|
||||
now = int(self.clock())
|
||||
ban_uids = []
|
||||
with closing(self.connect()) as con:
|
||||
self._eligible(con, uid)
|
||||
ip = public_ip(ip)
|
||||
if ip is None:
|
||||
return
|
||||
tag = self.ip_tag(ip)
|
||||
shared = any(ipaddress.ip_address(ip) in network for network in self.shared_ranges)
|
||||
geo = self._geo(ip, tag, now)
|
||||
con.execute("BEGIN IMMEDIATE")
|
||||
self._eligible(con, uid) # Consent/ban changes cannot race the audit commit.
|
||||
self._prune(con, now)
|
||||
existing = con.execute("SELECT 1 FROM wa_entry_visits WHERE ip_hmac=? AND uid=?", (tag, uid)).fetchone()
|
||||
if existing is None:
|
||||
total = con.execute("SELECT COUNT(*) FROM wa_entry_visits").fetchone()[0]
|
||||
own = con.execute("SELECT COUNT(*) FROM wa_entry_visits WHERE uid=?", (uid,)).fetchone()[0]
|
||||
if total >= self.max_visits or own >= self.max_user_ips:
|
||||
raise EntryError()
|
||||
con.execute("INSERT INTO wa_entry_visits VALUES(?,?,?,?,?,?,?,?) "
|
||||
"ON CONFLICT(ip_hmac,uid) DO UPDATE SET last_visit=excluded.last_visit,"
|
||||
"country=excluded.country,city=excluded.city,geo_source=excluded.geo_source,"
|
||||
"shared_egress=excluded.shared_egress",
|
||||
(tag, uid, now, now, geo["country"], geo["city"], geo["source"], int(shared)))
|
||||
recent = con.execute("SELECT 1 FROM wa_entry_alerts WHERE ip_hmac=? AND created_at>? LIMIT 1",
|
||||
(tag, now - WINDOW)).fetchone()
|
||||
if not shared and recent is None:
|
||||
accounts = con.execute("SELECT v.uid,u.username FROM wa_entry_visits v JOIN users u ON u.tg_id=v.uid "
|
||||
"WHERE v.ip_hmac=? AND v.last_visit>? AND COALESCE(u.banned,0)=0 "
|
||||
"AND u.privacy_ok=1 ORDER BY v.first_visit,v.uid LIMIT 8", (tag, now - WINDOW)).fetchall()
|
||||
if len(accounts) >= 2 and con.execute("SELECT COUNT(*) FROM wa_entry_alerts").fetchone()[0] < self.max_alerts:
|
||||
payload = json.dumps([{"uid": row["uid"], "username": _username(row["username"])} for row in accounts],
|
||||
ensure_ascii=False, separators=(",", ":"))
|
||||
alert = con.execute("INSERT INTO wa_entry_alerts(ip_hmac,created_at,accounts,country,city,geo_source) "
|
||||
"VALUES(?,?,?,?,?,?)", (tag, now, payload, geo["country"], geo["city"], geo["source"]))
|
||||
con.executemany("INSERT INTO wa_entry_outbox(alert_id,owner_id) VALUES(?,?)",
|
||||
[(alert.lastrowid, owner) for owner in self.owners])
|
||||
ban_uids = [row["uid"] for row in accounts]
|
||||
con.commit()
|
||||
if ban_uids:
|
||||
try:
|
||||
import entry_autoban
|
||||
entry_autoban.ban_cluster(ban_uids, reason="entry_ip_collision")
|
||||
except Exception:
|
||||
log.exception("entry autoban failed")
|
||||
|
||||
def claim(self):
|
||||
now = self.clock()
|
||||
with closing(self.connect()) as con:
|
||||
con.execute("BEGIN IMMEDIATE")
|
||||
self._prune(con, now)
|
||||
if not self.owners:
|
||||
con.commit()
|
||||
return None
|
||||
slots = ",".join("?" for _ in self.owners)
|
||||
row = con.execute("SELECT o.*,a.ip_hmac,a.created_at,a.accounts,a.country,a.city,a.geo_source "
|
||||
"FROM wa_entry_outbox o JOIN wa_entry_alerts a ON a.id=o.alert_id "
|
||||
"WHERE o.status='pending' AND o.next_attempt<=? AND o.attempts<? "
|
||||
"AND o.owner_id IN (" + slots + ") ORDER BY a.created_at,o.alert_id,o.owner_id LIMIT 1",
|
||||
(now, self.max_attempts, *self.owners)).fetchone()
|
||||
if row is None:
|
||||
con.commit()
|
||||
return None
|
||||
token = secrets.token_hex(16)
|
||||
con.execute("UPDATE wa_entry_outbox SET status='sending',attempts=attempts+1,lease_until=?,claim_token=? "
|
||||
"WHERE alert_id=? AND owner_id=?", (now + self.lease_seconds, token, row["alert_id"], row["owner_id"]))
|
||||
con.commit()
|
||||
return dict(row, attempts=row["attempts"] + 1, claim_token=token)
|
||||
|
||||
def finish(self, claim, status, *, retry_after=0):
|
||||
if status not in ("sent", "failed", "uncertain", "pending"):
|
||||
raise ValueError("entry_delivery_status_invalid")
|
||||
delay = 0
|
||||
if status == "pending":
|
||||
if claim["attempts"] >= self.max_attempts:
|
||||
status = "failed"
|
||||
else:
|
||||
retry = retry_after if type(retry_after) in (int, float) and math.isfinite(retry_after) else 0
|
||||
delay = max(15 * 2 ** (claim["attempts"] - 1), min(self.retention, retry))
|
||||
with closing(self.connect()) as con:
|
||||
con.execute("UPDATE wa_entry_outbox SET status=?,next_attempt=?,lease_until=0,claim_token='' "
|
||||
"WHERE alert_id=? AND owner_id=? AND status='sending' AND claim_token=?",
|
||||
(status, self.clock() + delay, claim["alert_id"], claim["owner_id"], claim["claim_token"]))
|
||||
con.commit()
|
||||
|
||||
|
||||
def notification_text(claim, tags=()):
|
||||
accounts = json.loads(claim["accounts"])
|
||||
users = "\n".join("• UID %d · %s" % (row["uid"], row["username"]) for row in accounts[:8])
|
||||
place = ", ".join(value for value in (claim["country"], claim["city"]) if value) or "неизвестно"
|
||||
source = claim["geo_source"] or "unknown"
|
||||
observed = time.strftime("%Y-%m-%d %H:%M UTC", time.gmtime(claim["created_at"]))
|
||||
text = ("Mini App: совпадение сети за 24 часа\nНаблюдение: %s\n%s\nПримерный регион: %s\nИсточник: %s\n"
|
||||
"Сеть #%s. Совпадение IP не доказывает общего владельца: возможны Wi-Fi, NAT, VPN или relay. "
|
||||
"Автобан применён автоматически (все аккаунты сети, кроме админов).\nГеоданные: IP Geolocation by DB-IP, CC BY 4.0 — https://db-ip.com" %
|
||||
(observed, users, place, source, claim["ip_hmac"][:12]))[:3000]
|
||||
# Operator tags always survive truncation: they are the fastest way to recognise a network.
|
||||
marks = " · ".join(str(tag) for tag in list(tags or ())[:12] if tag)
|
||||
if marks:
|
||||
text += "\nТеги: " + marks
|
||||
return text[:3400]
|
||||
|
||||
|
||||
class EntryOutbox:
|
||||
def __init__(self, store, sender, *, enabled=delivery_enabled, interval=5, batch=4, tags=None):
|
||||
self.store, self.sender, self.enabled = store, sender, enabled
|
||||
self.tag_source = tags
|
||||
self.interval, self.batch = interval, max(1, min(int(batch), 16))
|
||||
self.wake, self.stopping = asyncio.Event(), False
|
||||
|
||||
def _text(self, claim):
|
||||
marks = ()
|
||||
if self.tag_source is not None:
|
||||
try:
|
||||
marks = self.tag_source(claim["ip_hmac"]) or ()
|
||||
except Exception:
|
||||
log.exception("entry tags unavailable")
|
||||
marks = ()
|
||||
return notification_text(claim, marks)
|
||||
|
||||
def stop(self):
|
||||
self.stopping = True
|
||||
self.wake.set()
|
||||
|
||||
async def run_once(self):
|
||||
for _ in range(self.batch):
|
||||
if self.stopping or not self.enabled():
|
||||
break
|
||||
claim = await asyncio.to_thread(self.store.claim)
|
||||
if claim is None:
|
||||
break
|
||||
if not self.enabled():
|
||||
# No sender was entered; putting this exact claim back is safe.
|
||||
await asyncio.to_thread(self.store.finish, claim, "pending")
|
||||
break
|
||||
try:
|
||||
await self.sender(claim["owner_id"], self._text(claim), claim)
|
||||
except asyncio.CancelledError:
|
||||
await asyncio.shield(asyncio.to_thread(self.store.finish, claim, "uncertain"))
|
||||
raise
|
||||
except NotificationError as error:
|
||||
status = "failed" if not error.retryable else (
|
||||
"pending" if getattr(error, "delivery_rejected", False) else "uncertain")
|
||||
await asyncio.to_thread(self.store.finish, claim, status, retry_after=error.retry_after)
|
||||
except Exception:
|
||||
await asyncio.to_thread(self.store.finish, claim, "uncertain")
|
||||
else:
|
||||
await asyncio.to_thread(self.store.finish, claim, "sent")
|
||||
|
||||
async def run(self):
|
||||
while not self.stopping:
|
||||
self.wake.clear()
|
||||
try:
|
||||
await self.run_once()
|
||||
except (sqlite3.Error, OSError, ValueError):
|
||||
pass # Never log token-bearing exception text or an entry payload.
|
||||
if self.stopping:
|
||||
break
|
||||
try:
|
||||
await asyncio.wait_for(self.wake.wait(), self.interval)
|
||||
except asyncio.TimeoutError:
|
||||
pass
|
||||
@@ -0,0 +1,260 @@
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import io
|
||||
import re
|
||||
import zipfile
|
||||
from dataclasses import dataclass, field
|
||||
from html import unescape
|
||||
|
||||
MAX_FILE_BYTES = 8 * 1024 * 1024
|
||||
TEXT_BUDGET = 24000
|
||||
_MAX_PDF_PAGES = 60
|
||||
_MAX_XLSX_ROWS = 400
|
||||
_MAX_ZIP_ENTRIES = 200
|
||||
|
||||
TEXT_EXTS = {
|
||||
".txt", ".md", ".markdown", ".rst", ".log", ".csv", ".tsv", ".json", ".jsonl",
|
||||
".ndjson", ".yaml", ".yml", ".toml", ".ini", ".cfg", ".conf", ".env", ".sh",
|
||||
".bash", ".zsh", ".ps1", ".bat", ".py", ".pyi", ".js", ".mjs", ".cjs", ".ts",
|
||||
".tsx", ".jsx", ".java", ".kt", ".kts", ".c", ".h", ".cpp", ".hpp", ".cc",
|
||||
".cs", ".go", ".rs", ".rb", ".php", ".swift", ".m", ".mm", ".sql", ".html",
|
||||
".htm", ".xml", ".css", ".scss", ".less", ".vue", ".svelte", ".gitignore",
|
||||
".dockerfile", ".makefile", ".patch", ".diff", ".srt", ".vtt", ".tex",
|
||||
}
|
||||
|
||||
_OFFICE_EXTS = {".docx", ".xlsx", ".xlsm", ".pptx", ".odt"}
|
||||
_TAG_RE = re.compile(r"<[^>]+>")
|
||||
_CTRL_RE = re.compile(r"[\x00-\x08\x0b\x0c\x0e-\x1f]")
|
||||
|
||||
|
||||
@dataclass
|
||||
class ExtractResult:
|
||||
ok: bool
|
||||
kind: str = ""
|
||||
text: str = ""
|
||||
reason: str = ""
|
||||
chars: int = 0
|
||||
truncated: bool = False
|
||||
warnings: list = field(default_factory=list)
|
||||
|
||||
|
||||
def _num(name: str) -> int:
|
||||
"""Порядковый номер из имени вида sheet3.xml / slide12.xml; 0 если цифр нет."""
|
||||
m = re.search(r"(\d+)", name)
|
||||
return int(m.group(1)) if m else 0
|
||||
|
||||
|
||||
def _too_big(size: int) -> ExtractResult | None:
|
||||
if size > MAX_FILE_BYTES:
|
||||
return ExtractResult(
|
||||
ok=False,
|
||||
reason=f"файл {size / 1048576:.1f} МБ — предел {MAX_FILE_BYTES // 1048576} МБ",
|
||||
)
|
||||
if size == 0:
|
||||
return ExtractResult(ok=False, reason="файл пустой")
|
||||
return None
|
||||
|
||||
|
||||
def _decode(data: bytes) -> str | None:
|
||||
"""Текстовая декодировка: BOM-кодировки, затем utf-8, cp1251, koi8-r, latin-1.
|
||||
|
||||
utf-16 пробуется ТОЛЬКО при наличии BOM: вслепую он успешно «декодирует»
|
||||
cp1251-байты чётной длины в CJK-мусор, и русский файл приезжал иероглифами.
|
||||
"""
|
||||
if data[:2] in (b"\xff\xfe", b"\xfe\xff") or data[:3] == b"\xef\xbb\xbf":
|
||||
for enc in ("utf-8-sig", "utf-16"):
|
||||
try:
|
||||
return data.decode(enc)
|
||||
except (UnicodeDecodeError, UnicodeError):
|
||||
continue
|
||||
for enc in ("utf-8", "cp1251", "koi8-r", "latin-1"):
|
||||
try:
|
||||
return data.decode(enc)
|
||||
except (UnicodeDecodeError, UnicodeError):
|
||||
continue
|
||||
return None
|
||||
|
||||
|
||||
def _looks_binary(text: str) -> bool:
|
||||
sample = text[:8192]
|
||||
if not sample:
|
||||
return True
|
||||
return len(_CTRL_RE.findall(sample)) / len(sample) > 0.02
|
||||
|
||||
|
||||
def _finish(text: str, kind: str, warnings: list | None = None) -> ExtractResult:
|
||||
clean = text.replace("\r\n", "\n").replace("\r", "\n")
|
||||
clean = re.sub(r"\n{3,}", "\n\n", clean).strip()
|
||||
truncated = len(clean) > TEXT_BUDGET
|
||||
if truncated:
|
||||
clean = clean[:TEXT_BUDGET]
|
||||
warnings = list(warnings or [])
|
||||
warnings.append(f"показаны первые {TEXT_BUDGET} символов")
|
||||
if not clean:
|
||||
return ExtractResult(ok=False, kind=kind, reason="в файле нет извлекаемого текста")
|
||||
return ExtractResult(
|
||||
ok=True, kind=kind, text=clean, chars=len(clean),
|
||||
truncated=truncated, warnings=list(warnings or []),
|
||||
)
|
||||
|
||||
|
||||
def _read_entry(zf: zipfile.ZipFile, name: str) -> str:
|
||||
info = zf.getinfo(name)
|
||||
if info.file_size > 32 * 1024 * 1024:
|
||||
raise RuntimeError(f"entry {name} распаковывается в {info.file_size // 1048576} МБ — слишком много")
|
||||
return zf.read(name).decode("utf-8", "replace")
|
||||
|
||||
|
||||
def _from_docx(zf: zipfile.ZipFile) -> str:
|
||||
xml = _read_entry(zf, "word/document.xml")
|
||||
xml = xml.replace("</w:p>", "\n").replace("<w:tab/>", "\t").replace("<w:br/>", "\n")
|
||||
return unescape(_TAG_RE.sub("", xml))
|
||||
|
||||
|
||||
def _from_pptx(zf: zipfile.ZipFile) -> str:
|
||||
slides = sorted(
|
||||
(n for n in zf.namelist() if re.fullmatch(r"ppt/slides/slide\d+\.xml", n)),
|
||||
key=lambda n: _num(n),
|
||||
)
|
||||
out = []
|
||||
for n in slides:
|
||||
xml = _read_entry(zf, n)
|
||||
xml = xml.replace("</a:p>", "\n")
|
||||
out.append(f"--- {n.rsplit('/', 1)[-1]} ---\n" + unescape(_TAG_RE.sub("", xml)))
|
||||
return "\n".join(out)
|
||||
|
||||
|
||||
def _from_xlsx(zf: zipfile.ZipFile) -> str:
|
||||
shared: list[str] = []
|
||||
if "xl/sharedStrings.xml" in zf.namelist():
|
||||
ss = _read_entry(zf, "xl/sharedStrings.xml")
|
||||
shared = [unescape(_TAG_RE.sub("", m)) for m in re.findall(r"<si>(.*?)</si>", ss, re.S)]
|
||||
sheets = [n for n in zf.namelist() if re.fullmatch(r"xl/worksheets/sheet\d+\.xml", n)]
|
||||
sheets.sort(key=lambda n: _num(n.rsplit("/", 1)[-1]))
|
||||
out: list[str] = []
|
||||
for sheet in sheets[:3]:
|
||||
xml = _read_entry(zf, sheet)
|
||||
rows = []
|
||||
for row in re.findall(r"<row[^>]*>(.*?)</row>", xml, re.S)[:_MAX_XLSX_ROWS]:
|
||||
cells = []
|
||||
for m in re.finditer(r"<c([^>]*)(?:/>|>(.*?)</c>)", row, re.S):
|
||||
attrs, body = m.group(1) or "", m.group(2) or ""
|
||||
val = ""
|
||||
vm = re.search(r"<v>(.*?)</v>", body, re.S)
|
||||
if vm:
|
||||
val = unescape(vm.group(1))
|
||||
if 't="s"' in attrs and val.isdigit() and int(val) < len(shared):
|
||||
val = shared[int(val)]
|
||||
else:
|
||||
im = re.search(r"<t[^>]*>(.*?)</t>", body, re.S)
|
||||
if im:
|
||||
val = unescape(im.group(1))
|
||||
cells.append(val.replace("\t", " ").replace("\n", " "))
|
||||
if any(c.strip() for c in cells):
|
||||
rows.append("\t".join(cells))
|
||||
if rows:
|
||||
out.append(f"--- {sheet.rsplit('/', 1)[-1]} ---\n" + "\n".join(rows))
|
||||
return "\n".join(out)
|
||||
|
||||
|
||||
def _from_odt(zf: zipfile.ZipFile) -> str:
|
||||
xml = _read_entry(zf, "content.xml")
|
||||
xml = re.sub(r"</text:(p|h|list-item)>", "\n", xml)
|
||||
return unescape(_TAG_RE.sub("", xml))
|
||||
|
||||
|
||||
def _from_office(data: bytes, ext: str) -> ExtractResult:
|
||||
try:
|
||||
with zipfile.ZipFile(io.BytesIO(data)) as zf:
|
||||
names = set(zf.namelist())
|
||||
if ext == ".docx" and "word/document.xml" in names:
|
||||
return _finish(_from_docx(zf), "docx")
|
||||
if ext == ".pptx" and any(n.startswith("ppt/slides/slide") for n in names):
|
||||
return _finish(_from_pptx(zf), "pptx")
|
||||
if ext in (".xlsx", ".xlsm") and any(n.startswith("xl/worksheets/") for n in names):
|
||||
return _finish(_from_xlsx(zf), "xlsx")
|
||||
if ext == ".odt" and "content.xml" in names:
|
||||
return _finish(_from_odt(zf), "odt")
|
||||
except (zipfile.BadZipFile, KeyError, ValueError, IndexError, RuntimeError) as exc:
|
||||
return ExtractResult(ok=False, reason=f"{ext} повреждён или слишком большой внутри: {type(exc).__name__}")
|
||||
return ExtractResult(ok=False, reason=f"{ext} без ожидаемой структуры — возможно, старый формат (.doc/.xls/.ppt)")
|
||||
|
||||
|
||||
def _from_pdf(data: bytes) -> ExtractResult:
|
||||
try:
|
||||
from pypdf import PdfReader # type: ignore[import-not-found]
|
||||
except ImportError:
|
||||
return ExtractResult(ok=False, reason="PDF-ридер не установлен на сервере (pypdf)")
|
||||
try:
|
||||
reader = PdfReader(io.BytesIO(data))
|
||||
pages = reader.pages[:_MAX_PDF_PAGES]
|
||||
parts = []
|
||||
for i, page in enumerate(pages, 1):
|
||||
try:
|
||||
parts.append((page.extract_text() or "").strip())
|
||||
except Exception as exc: # битая страница не должна ронять весь файл
|
||||
parts.append(f"[страница {i} не читается: {type(exc).__name__}]")
|
||||
text = "\n".join(p for p in parts if p)
|
||||
warns = []
|
||||
if len(reader.pages) > _MAX_PDF_PAGES:
|
||||
warns.append(f"прочитаны первые {_MAX_PDF_PAGES} из {len(reader.pages)} страниц")
|
||||
if not text.strip():
|
||||
return ExtractResult(
|
||||
ok=False,
|
||||
reason="PDF без текстового слоя (скан) — нужно распознавание, его на сервере нет",
|
||||
)
|
||||
return _finish(text, "pdf", warns)
|
||||
except Exception as exc:
|
||||
return ExtractResult(ok=False, reason=f"PDF не читается: {type(exc).__name__}")
|
||||
|
||||
|
||||
def _from_zip_listing(zf: zipfile.ZipFile) -> ExtractResult:
|
||||
infos = zf.infolist()[:_MAX_ZIP_ENTRIES]
|
||||
lines = [f"{i.file_size:>10} {i.filename}" for i in infos if not i.is_dir()]
|
||||
body = "\n".join(lines) or "(архив пуст)"
|
||||
more = f"\n…и ещё {len(zf.infolist()) - len(infos)}" if len(zf.infolist()) > len(infos) else ""
|
||||
return _finish(f"Содержимое архива:\n{body}{more}", "zip-listing")
|
||||
|
||||
|
||||
def extract(name: str, data: bytes) -> ExtractResult:
|
||||
name = str(name or "").strip()
|
||||
guard = _too_big(len(data or b""))
|
||||
if guard:
|
||||
return guard
|
||||
ext = ("." + name.rsplit(".", 1)[-1].lower()) if "." in name else ""
|
||||
if ext in _OFFICE_EXTS:
|
||||
return _from_office(data, ext)
|
||||
if ext == ".pdf":
|
||||
return _from_pdf(data)
|
||||
if ext in (".zip", ".apk", ".whl", ".jar", ".epub"):
|
||||
try:
|
||||
with zipfile.ZipFile(io.BytesIO(data)) as zf:
|
||||
return _from_zip_listing(zf)
|
||||
except zipfile.BadZipFile:
|
||||
return ExtractResult(ok=False, reason="архив повреждён")
|
||||
if ext in (".doc", ".xls", ".ppt", ".rtf"):
|
||||
return ExtractResult(
|
||||
ok=False,
|
||||
reason=f"{ext} — старый бинарный формат, конвертера на сервере нет. Пересохрани как "
|
||||
f"{'docx' if ext == '.doc' else 'xlsx' if ext == '.xls' else 'pdf'} или .txt",
|
||||
)
|
||||
if ext in {".png", ".jpg", ".jpeg", ".webp", ".gif", ".mp3", ".ogg", ".mp4", ".wav", ".webm"}:
|
||||
return ExtractResult(ok=False, reason="это медиа, а не документ — пришли фото отдельно, оно уходит в vision-модель")
|
||||
|
||||
text = _decode(data)
|
||||
if text is None or _looks_binary(text):
|
||||
return ExtractResult(
|
||||
ok=False,
|
||||
reason=f"бинарный файл{f' {ext}' if ext else ''} — текстового содержимого нет",
|
||||
)
|
||||
kind = ext.lstrip(".") or "text"
|
||||
return _finish(text, kind if kind in TEXT_EXTS or ext else "text")
|
||||
|
||||
|
||||
def describe(name: str, res: ExtractResult) -> str:
|
||||
"""Короткое честное описание результата для сообщения юзеру (без HTML-разметки)."""
|
||||
if res.ok:
|
||||
extra = f", {res.warnings[0]}" if res.warnings else ""
|
||||
return f"{name}: {res.kind}, {res.chars} символов{extra}"
|
||||
return f"{name}: не прочитан — {res.reason}"
|
||||
@@ -0,0 +1,271 @@
|
||||
"""Telegram forum setup with persistent topic and panel identifiers.
|
||||
|
||||
Bot API cannot create a group or enable forum mode. This module verifies both the
|
||||
chat and the bot permission before creating anything. Re-running setup reuses topic
|
||||
IDs and edits existing panels instead of posting duplicates.
|
||||
"""
|
||||
from __future__ import annotations
|
||||
|
||||
import asyncio
|
||||
from contextlib import closing
|
||||
import html
|
||||
import logging
|
||||
import sqlite3
|
||||
import time
|
||||
|
||||
from aiogram import types
|
||||
|
||||
log = logging.getLogger("forum-panels")
|
||||
|
||||
TOPICS = (
|
||||
("ann", "📢 Объявления"),
|
||||
("econ", "💰 Экономика"),
|
||||
("quests", "📜 Квесты и баунти"),
|
||||
("top", "🏆 Топ и дуэли"),
|
||||
("moder", "🛠 Модерация"),
|
||||
)
|
||||
_SETUP_LOCKS = {}
|
||||
|
||||
|
||||
def _setup_lock():
|
||||
loop = asyncio.get_running_loop()
|
||||
lock = _SETUP_LOCKS.get(loop)
|
||||
if lock is None:
|
||||
lock = asyncio.Lock()
|
||||
_SETUP_LOCKS[loop] = lock
|
||||
return lock
|
||||
|
||||
|
||||
def ensure_schema(bot_db):
|
||||
with closing(sqlite3.connect(bot_db, timeout=20)) as con:
|
||||
con.execute("""CREATE TABLE IF NOT EXISTS forum_topics(
|
||||
chat_id INTEGER NOT NULL, kind TEXT NOT NULL, thread_id INTEGER NOT NULL,
|
||||
title TEXT NOT NULL, panel_message_id INTEGER, created INTEGER NOT NULL,
|
||||
PRIMARY KEY(chat_id,kind), UNIQUE(chat_id,thread_id))""")
|
||||
con.commit()
|
||||
|
||||
|
||||
def topic_rows(bot_db, chat_id):
|
||||
ensure_schema(bot_db)
|
||||
with closing(sqlite3.connect(bot_db, timeout=20)) as con:
|
||||
con.row_factory = sqlite3.Row
|
||||
return con.execute("SELECT * FROM forum_topics WHERE chat_id=?", (int(chat_id),)).fetchall()
|
||||
|
||||
|
||||
def panel_keyboard(buttons):
|
||||
if not buttons:
|
||||
return None
|
||||
rows = [[types.InlineKeyboardButton(text=text, callback_data=data) for text, data in buttons[i:i + 3]]
|
||||
for i in range(0, len(buttons), 3)]
|
||||
return types.InlineKeyboardMarkup(inline_keyboard=rows)
|
||||
|
||||
|
||||
async def status(bot_db, bot, chat_id):
|
||||
try:
|
||||
chat = await bot.get_chat(chat_id)
|
||||
except Exception:
|
||||
log.warning("forum status get_chat failed chat=%s", chat_id, exc_info=True)
|
||||
return "💬 <b>Форум ИИШКО</b>\n\nНе удалось получить чат через Telegram. Проверь доступ бота и попробуй снова."
|
||||
if getattr(chat, "type", "") == "private":
|
||||
return ("💬 <b>Форум ИИШКО</b>\n\nФорум живёт в групповом чате сообщества: объявления, "
|
||||
"экономика, квесты и баунти, топ и дуэли. Открой чат ИИШКО и выбери тему; "
|
||||
"настройка тем доступна администратору группы.")
|
||||
is_forum = bool(getattr(chat, "is_forum", False))
|
||||
title = html.escape(str(getattr(chat, "title", None) or chat_id))
|
||||
rows = []
|
||||
if getattr(chat, "type", "") in ("group", "supergroup"):
|
||||
try:
|
||||
rows = await asyncio.to_thread(topic_rows, bot_db, chat_id)
|
||||
except sqlite3.Error:
|
||||
log.exception("forum status db failed chat=%s", chat_id)
|
||||
return ("💬 <b>Форум ИИШКО</b>\n\nСостояние тем сейчас недоступно. "
|
||||
"Повтори позже; настройка не менялась.")
|
||||
lines = ["💬 <b>Форум ИИШКО</b>", f"Чат: <b>{title}</b>",
|
||||
"Темы Telegram: <b>%s</b>" % ("включены" if is_forum else "выключены")]
|
||||
if not is_forum:
|
||||
lines += ["", "Bot API не может создать группу или включить темы.",
|
||||
"Администратор группы: <b>Управление группой → Темы</b>. Затем в группе: /forum setup"]
|
||||
if rows:
|
||||
lines.append("Сохранённых записей о темах: %d (live-проверка не выполнялась)." % len(rows))
|
||||
return "\n".join(lines)
|
||||
by_kind = {row["kind"]: row for row in rows}
|
||||
lines.append("Сохранено в БД: тем <b>%d/%d</b> · панелей <b>%d</b> "
|
||||
"(live-проверка не выполнялась)" % (
|
||||
len(rows), len(TOPICS), sum(bool(row["panel_message_id"]) for row in rows)))
|
||||
for kind, topic_title in TOPICS:
|
||||
row = by_kind.get(kind)
|
||||
lines.append(("✅ " if row else "▫️ ") + html.escape(topic_title) +
|
||||
(f" · ID {row['thread_id']}" if row else ""))
|
||||
if len(rows) < len(TOPICS):
|
||||
lines += ["", "Администратор: /forum setup"]
|
||||
return "\n".join(lines)
|
||||
|
||||
|
||||
def _admin_can_manage_topics(member):
|
||||
value = getattr(member, "status", None)
|
||||
status = getattr(value, "value", value)
|
||||
return status == "administrator" and bool(getattr(member, "can_manage_topics", False))
|
||||
|
||||
|
||||
def _not_modified(error):
|
||||
return "message is not modified" in str(error).lower()
|
||||
|
||||
|
||||
def _missing_message(error):
|
||||
text = str(error).lower()
|
||||
return "message to edit not found" in text or "message_id_invalid" in text or "message not found" in text
|
||||
|
||||
|
||||
def _missing_thread(error):
|
||||
text = str(error).lower()
|
||||
return ("message thread not found" in text or "topic_deleted" in text
|
||||
or "topic_id_invalid" in text or "thread not found" in text)
|
||||
|
||||
|
||||
def _store_topic(bot_db, chat_id, kind, thread_id, title):
|
||||
with closing(sqlite3.connect(bot_db, timeout=20)) as con:
|
||||
con.execute("DELETE FROM forum_topics WHERE chat_id=? AND kind=?", (int(chat_id), kind))
|
||||
con.execute("INSERT INTO forum_topics(chat_id,kind,thread_id,title,panel_message_id,created) "
|
||||
"VALUES(?,?,?,?,NULL,?)", (int(chat_id), kind, int(thread_id), title, int(time.time())))
|
||||
con.commit()
|
||||
|
||||
|
||||
def _drop_topic(bot_db, chat_id, kind):
|
||||
with closing(sqlite3.connect(bot_db, timeout=20)) as con:
|
||||
con.execute("DELETE FROM forum_topics WHERE chat_id=? AND kind=?", (int(chat_id), kind))
|
||||
con.commit()
|
||||
|
||||
|
||||
async def _create_topic(bot_db, bot, chat_id, kind, title, created):
|
||||
topic = await bot.create_forum_topic(chat_id=chat_id, name=title)
|
||||
thread_id = int(topic.message_thread_id)
|
||||
_store_topic(bot_db, chat_id, kind, thread_id, title)
|
||||
created.append("%s · ID %d" % (title, thread_id))
|
||||
return {"kind": kind, "thread_id": thread_id, "panel_message_id": None}
|
||||
|
||||
|
||||
async def _send_panel(bot_db, bot, chat_id, kind, title, row, text, keyboard, created):
|
||||
"""Send into a topic; recreate the topic once when Telegram says it is gone."""
|
||||
try:
|
||||
return await bot.send_message(chat_id, text, reply_markup=keyboard,
|
||||
message_thread_id=int(row["thread_id"]), parse_mode="HTML")
|
||||
except Exception as error:
|
||||
if not _missing_thread(error):
|
||||
raise
|
||||
log.warning("forum topic missing chat=%s kind=%s; recreating", chat_id, kind)
|
||||
_drop_topic(bot_db, chat_id, kind)
|
||||
fresh = await _create_topic(bot_db, bot, chat_id, kind, title, created)
|
||||
return await bot.send_message(chat_id, text, reply_markup=keyboard,
|
||||
message_thread_id=int(fresh["thread_id"]), parse_mode="HTML")
|
||||
|
||||
|
||||
CASINO_DISABLED_TEXT = ("🎰 <b>Казино</b>\n\n"
|
||||
"Ставки и платные игры отключены навсегда. "
|
||||
"Бесплатные игры: /quiz, /dice, /pair, /roast.")
|
||||
|
||||
|
||||
def _casino_rows(bot_db):
|
||||
ensure_schema(bot_db)
|
||||
with closing(sqlite3.connect(bot_db, timeout=20)) as con:
|
||||
con.row_factory = sqlite3.Row
|
||||
return con.execute("SELECT * FROM forum_topics WHERE kind='casino'").fetchall()
|
||||
|
||||
|
||||
async def retire_casino_panels(bot_db, bot, chat_id=None):
|
||||
rows = [r for r in _casino_rows(bot_db)
|
||||
if chat_id is None or int(r["chat_id"]) == int(chat_id)]
|
||||
retired, kept, failed = 0, 0, 0
|
||||
for row in rows:
|
||||
cid = int(row["chat_id"])
|
||||
pid = int(row["panel_message_id"] or 0)
|
||||
if pid:
|
||||
try:
|
||||
await bot.edit_message_text(text=CASINO_DISABLED_TEXT, chat_id=cid, message_id=pid,
|
||||
reply_markup=None, parse_mode="HTML")
|
||||
except Exception as error:
|
||||
if not (_not_modified(error) or _missing_message(error) or _missing_thread(error)):
|
||||
failed += 1
|
||||
log.warning("casino panel retire failed chat=%s msg=%s", cid, pid, exc_info=True)
|
||||
continue
|
||||
_drop_topic(bot_db, cid, "casino")
|
||||
retired += 1
|
||||
if rows:
|
||||
log.info("casino panels retired=%s failed=%s kept=%s", retired, failed, kept)
|
||||
return {"found": len(rows), "retired": retired, "failed": failed}
|
||||
|
||||
|
||||
async def _setup(bot_db, bot, chat_id, panels):
|
||||
chat = await bot.get_chat(chat_id)
|
||||
if getattr(chat, "type", "") != "supergroup" or not bool(getattr(chat, "is_forum", False)):
|
||||
return {"ok": False, "created": 0, "panels": 0, "errors": ["not_forum"],
|
||||
"text": "❌ Здесь нельзя настроить форум: нужен супергрупповой чат с включёнными «Темами». "
|
||||
"Включи их в настройках группы и повтори /forum setup."}
|
||||
me = await bot.get_me()
|
||||
member = await bot.get_chat_member(chat_id, me.id)
|
||||
if not _admin_can_manage_topics(member):
|
||||
return {"ok": False, "created": 0, "panels": 0, "errors": ["can_manage_topics"],
|
||||
"text": "❌ Нет права управления темами. Сделай бота администратором с правом "
|
||||
"<b>Manage Topics / Управление темами</b> и повтори /forum setup."}
|
||||
ensure_schema(bot_db)
|
||||
try:
|
||||
await retire_casino_panels(bot_db, bot, chat_id) # [NO-PAID-CASINO] стухшая панель казино
|
||||
except Exception:
|
||||
log.warning("casino panel retire skipped chat=%s", chat_id, exc_info=True)
|
||||
created, ready, errors = [], 0, []
|
||||
rows = {row["kind"]: row for row in topic_rows(bot_db, chat_id)}
|
||||
for kind, title in TOPICS:
|
||||
try:
|
||||
row = rows.get(kind)
|
||||
if row is None:
|
||||
row = await _create_topic(bot_db, bot, chat_id, kind, title, created)
|
||||
rows[kind] = row
|
||||
text, buttons = panels[kind]
|
||||
keyboard = panel_keyboard(buttons)
|
||||
panel_id = row["panel_message_id"]
|
||||
if panel_id:
|
||||
try:
|
||||
await bot.edit_message_text(text=text, chat_id=chat_id, message_id=panel_id,
|
||||
reply_markup=keyboard, parse_mode="HTML")
|
||||
except Exception as error:
|
||||
if _not_modified(error):
|
||||
pass
|
||||
elif _missing_message(error):
|
||||
sent = await _send_panel(bot_db, bot, chat_id, kind, title, row,
|
||||
text, keyboard, created)
|
||||
panel_id = sent.message_id
|
||||
else:
|
||||
raise
|
||||
else:
|
||||
sent = await _send_panel(bot_db, bot, chat_id, kind, title, row,
|
||||
text, keyboard, created)
|
||||
panel_id = sent.message_id
|
||||
if int(panel_id) != int(row["panel_message_id"] or 0):
|
||||
with closing(sqlite3.connect(bot_db, timeout=20)) as con:
|
||||
con.execute("UPDATE forum_topics SET panel_message_id=? WHERE chat_id=? AND kind=?",
|
||||
(int(panel_id), int(chat_id), kind))
|
||||
con.commit()
|
||||
ready += 1
|
||||
except Exception as error:
|
||||
log.warning("forum setup item failed chat=%s kind=%s", chat_id, kind, exc_info=True)
|
||||
errors.append("%s: %s" % (title, html.escape(str(error)[:100])))
|
||||
lines = []
|
||||
if created:
|
||||
lines.append("✅ Созданы темы:\n" + "\n".join(created))
|
||||
else:
|
||||
lines.append("✅ Новых тем не потребовалось: использую сохранённые ID.")
|
||||
lines.append("Панелей готово: <b>%d/%d</b>." % (ready, len(TOPICS)))
|
||||
if errors:
|
||||
lines.append("⚠️ Ошибки:\n" + "\n".join(errors))
|
||||
lines.append("Повторный /forum setup обновит панели без создания дублей.")
|
||||
return {"ok": not errors and ready == len(TOPICS), "created": len(created),
|
||||
"panels": ready, "errors": errors, "text": "\n\n".join(lines)}
|
||||
|
||||
|
||||
async def setup(bot_db, bot, chat_id, panels):
|
||||
async with _setup_lock():
|
||||
try:
|
||||
return await _setup(bot_db, bot, chat_id, panels)
|
||||
except Exception:
|
||||
log.exception("forum setup failed chat=%s", chat_id)
|
||||
return {"ok": False, "created": 0, "panels": 0, "errors": ["setup_failed"],
|
||||
"text": "❌ Настройка не завершена. Проверь права бота и логи; повтор безопасен."}
|
||||
@@ -0,0 +1,533 @@
|
||||
import asyncio
|
||||
from contextlib import closing
|
||||
from decimal import Decimal, InvalidOperation
|
||||
import hashlib
|
||||
import json
|
||||
import re
|
||||
import secrets
|
||||
import sqlite3
|
||||
import time
|
||||
from urllib.parse import urlsplit
|
||||
|
||||
import aiohttp
|
||||
|
||||
CURRENCY = 'USD'
|
||||
MAX_CENTS = 1_000_000_000
|
||||
MAX_REQUESTS = 10_000_000
|
||||
CP_BASE = 'https://pay.crypt.bot/api'
|
||||
# A createInvoice call whose outcome is unknown (network failure) is terminalised
|
||||
# after this grace window. It must exceed aiohttp ClientTimeout(total=20) by a wide
|
||||
# margin so a same-request_id retry cannot race an in-flight create and expose a
|
||||
# second remote invoice for one request_id.
|
||||
AMBIGUITY_GRACE = 180
|
||||
_REQUEST = re.compile(r'[A-Za-z0-9:_-]{12,96}\Z')
|
||||
_ID = re.compile(r'[A-Za-z0-9_-]{1,64}\Z')
|
||||
_MODEL = re.compile(r'[A-Za-z0-9][A-Za-z0-9._:/-]{0,127}\Z')
|
||||
|
||||
|
||||
class CommerceError(ValueError):
|
||||
def __init__(self, status, code, message):
|
||||
super().__init__(message)
|
||||
self.status, self.code, self.message = status, code, message
|
||||
self.operation_rejected = status < 500 and code in {
|
||||
'invalid_body', 'request_id_required', 'unknown_action', 'invalid_offer_id',
|
||||
'invalid_invoice_id', 'offer_unavailable', 'insufficient_funds',
|
||||
'entitlement_limit', 'payment_mismatch', 'invoice_not_found', 'wallet_limit',
|
||||
'invoice_abandoned'}
|
||||
|
||||
|
||||
def _fail(status, code, message):
|
||||
raise CommerceError(status, code, message)
|
||||
|
||||
|
||||
def _connect(db):
|
||||
con = sqlite3.connect(str(db), timeout=15, isolation_level=None)
|
||||
con.row_factory = sqlite3.Row
|
||||
con.execute('PRAGMA busy_timeout=15000')
|
||||
return con
|
||||
|
||||
|
||||
def init_db(db):
|
||||
with closing(_connect(db)) as con:
|
||||
con.executescript('''
|
||||
CREATE TABLE IF NOT EXISTS commerce_wallets (
|
||||
uid INTEGER PRIMARY KEY, balance_cents INTEGER NOT NULL DEFAULT 0
|
||||
CHECK(balance_cents>=0 AND balance_cents<=1000000000));
|
||||
CREATE TABLE IF NOT EXISTS commerce_operations (
|
||||
uid INTEGER NOT NULL, request_id TEXT NOT NULL, digest TEXT NOT NULL,
|
||||
result TEXT NOT NULL, PRIMARY KEY(uid,request_id));
|
||||
CREATE TABLE IF NOT EXISTS commerce_invoices (
|
||||
id TEXT PRIMARY KEY, uid INTEGER NOT NULL, request_id TEXT NOT NULL,
|
||||
digest TEXT NOT NULL, offer_id TEXT NOT NULL, amount_cents INTEGER NOT NULL
|
||||
CHECK(amount_cents>0), currency TEXT NOT NULL CHECK(currency='USD'),
|
||||
provider_invoice_id INTEGER UNIQUE, payload TEXT NOT NULL UNIQUE,
|
||||
status TEXT NOT NULL, pay_url TEXT NOT NULL DEFAULT '',
|
||||
created INTEGER NOT NULL, updated INTEGER NOT NULL, credited_at INTEGER,
|
||||
UNIQUE(uid,request_id));
|
||||
CREATE TABLE IF NOT EXISTS commerce_ledger (
|
||||
id INTEGER PRIMARY KEY, uid INTEGER NOT NULL, delta_cents INTEGER NOT NULL,
|
||||
kind TEXT NOT NULL, offer_id TEXT, invoice_id TEXT, request_id TEXT NOT NULL,
|
||||
ts INTEGER NOT NULL);
|
||||
CREATE UNIQUE INDEX IF NOT EXISTS commerce_payment_once
|
||||
ON commerce_ledger(invoice_id) WHERE kind='payment';
|
||||
CREATE TABLE IF NOT EXISTS commerce_grants (
|
||||
id INTEGER PRIMARY KEY, uid INTEGER NOT NULL, kind TEXT NOT NULL,
|
||||
requests INTEGER NOT NULL DEFAULT 0, model TEXT NOT NULL DEFAULT '',
|
||||
expires_at INTEGER NOT NULL, base_granted INTEGER NOT NULL DEFAULT 0,
|
||||
request_id TEXT NOT NULL, created INTEGER NOT NULL, UNIQUE(uid,request_id));
|
||||
CREATE INDEX IF NOT EXISTS commerce_grants_uid ON commerce_grants(uid,expires_at);
|
||||
CREATE INDEX IF NOT EXISTS commerce_ledger_uid ON commerce_ledger(uid,id);
|
||||
CREATE INDEX IF NOT EXISTS commerce_invoices_uid ON commerce_invoices(uid,created);
|
||||
''')
|
||||
|
||||
|
||||
def _now(now):
|
||||
return int(time.time()) if now is None else int(now)
|
||||
|
||||
|
||||
def _user(con, uid):
|
||||
if type(uid) is not int or not 0 < uid <= 9223372036854775807:
|
||||
_fail(400, 'invalid_user', 'Некорректный пользователь.')
|
||||
row = con.execute('SELECT * FROM users WHERE tg_id=?', (uid,)).fetchone()
|
||||
if row is None:
|
||||
_fail(403, 'not_registered', 'Сначала открой бота и зарегистрируйся.')
|
||||
user = dict(row)
|
||||
if user.get('banned') or user.get('api_blocked'):
|
||||
_fail(403, 'blocked', 'Доступ к покупкам ограничен.')
|
||||
return user
|
||||
|
||||
|
||||
def configured_offers(offers=()):
|
||||
"""Validate only operator-owned configuration. No default prices or products."""
|
||||
if offers is None:
|
||||
offers = []
|
||||
if not isinstance(offers, (list, tuple)) or len(offers) > 100:
|
||||
_fail(503, 'commerce_config_invalid', 'Конфигурация магазина недоступна.')
|
||||
result, seen = [], set()
|
||||
for item in offers:
|
||||
if not isinstance(item, dict):
|
||||
_fail(503, 'commerce_config_invalid', 'Конфигурация магазина недоступна.')
|
||||
identity, kind, price = item.get('id'), item.get('kind'), item.get('price_cents')
|
||||
if (not isinstance(identity, str) or not _ID.fullmatch(identity) or identity in seen
|
||||
or kind not in ('wallet_topup', 'extra_requests', 'model_pass')
|
||||
or type(price) is not int or not 0 < price <= MAX_CENTS):
|
||||
_fail(503, 'commerce_config_invalid', 'Конфигурация магазина недоступна.')
|
||||
offer = {'id': identity, 'kind': kind, 'price_cents': price, 'currency': CURRENCY,
|
||||
'title': str(item.get('title') or identity)[:160]}
|
||||
if kind == 'extra_requests':
|
||||
requests = item.get('requests')
|
||||
if type(requests) is not int or not 0 < requests <= MAX_REQUESTS:
|
||||
_fail(503, 'commerce_config_invalid', 'Конфигурация магазина недоступна.')
|
||||
offer.update(requests=requests, duration='msk_day')
|
||||
elif kind == 'model_pass':
|
||||
model = item.get('model')
|
||||
if not isinstance(model, str) or not _MODEL.fullmatch(model):
|
||||
_fail(503, 'commerce_config_invalid', 'Конфигурация магазина недоступна.')
|
||||
offer.update(model=model, duration_seconds=86400)
|
||||
seen.add(identity)
|
||||
result.append(offer)
|
||||
return result
|
||||
|
||||
|
||||
def _offer(offers, identity, kinds):
|
||||
available = configured_offers(offers)
|
||||
if not available:
|
||||
_fail(503, 'commerce_unavailable', 'Покупки пока не настроены.')
|
||||
offer = next((item for item in available if item['id'] == identity), None)
|
||||
if offer is None or offer['kind'] not in kinds:
|
||||
_fail(400, 'offer_unavailable', 'Такое предложение недоступно.')
|
||||
return offer
|
||||
|
||||
|
||||
def _empty_entitlements():
|
||||
return {'extra_requests': 0, 'models': [], 'expires_at': None}
|
||||
|
||||
|
||||
def _has_grants(con):
|
||||
return bool(con.execute("SELECT 1 FROM sqlite_master WHERE type='table' AND name='commerce_grants'").fetchone())
|
||||
|
||||
|
||||
def _entitlements(con, uid, now):
|
||||
if not _has_grants(con):
|
||||
return _empty_entitlements()
|
||||
rows = con.execute('SELECT kind,requests,model,expires_at FROM commerce_grants '
|
||||
'WHERE uid=? AND expires_at>?', (uid, now)).fetchall()
|
||||
return {'extra_requests': sum(int(row['requests']) for row in rows if row['kind'] == 'extra_requests'),
|
||||
'models': sorted({row['model'] for row in rows if row['kind'] == 'model_pass'}),
|
||||
'expires_at': min((int(row['expires_at']) for row in rows), default=None)}
|
||||
|
||||
|
||||
def entitlements(db, uid, now=None):
|
||||
with closing(_connect(db)) as con:
|
||||
try:
|
||||
_user(con, uid)
|
||||
except CommerceError as error:
|
||||
if error.code in ('blocked', 'not_registered'):
|
||||
return _empty_entitlements()
|
||||
raise
|
||||
return _entitlements(con, uid, _now(now))
|
||||
|
||||
|
||||
def managed_model_passes(db, uid, now=None):
|
||||
stamp = _now(now)
|
||||
with closing(_connect(db)) as con:
|
||||
if not _has_grants(con):
|
||||
return []
|
||||
rows = con.execute("SELECT model,MAX(expires_at) AS expires_at,MAX(base_granted) AS base_granted "
|
||||
"FROM commerce_grants WHERE uid=? AND kind='model_pass' GROUP BY model ORDER BY model",
|
||||
(uid,)).fetchall()
|
||||
return [{'model': row['model'], 'expires_at': int(row['expires_at']),
|
||||
'active': int(row['expires_at']) > stamp, 'base_granted': bool(row['base_granted'])}
|
||||
for row in rows]
|
||||
|
||||
|
||||
def token_model_scope(db, uid, base_models, now=None):
|
||||
"""Union for upstream model_limits; safe ONLY with a per-request expiry gate."""
|
||||
return list(dict.fromkeys(list(base_models) + entitlements(db, uid, now)['models']))
|
||||
|
||||
|
||||
def model_access(db, uid, model, base_models, now=None):
|
||||
"""A model gate, not an auth/ban/subscription override."""
|
||||
with closing(_connect(db)) as con:
|
||||
try:
|
||||
_user(con, uid)
|
||||
except CommerceError:
|
||||
return False
|
||||
return model in base_models or model in _entitlements(con, uid, _now(now))['models']
|
||||
|
||||
|
||||
def _body(body):
|
||||
if not isinstance(body, dict):
|
||||
_fail(400, 'invalid_body', 'Ожидается JSON-объект.')
|
||||
request_id = body.get('request_id')
|
||||
if not isinstance(request_id, str) or not _REQUEST.fullmatch(request_id):
|
||||
_fail(400, 'request_id_required', 'Нужен уникальный идентификатор операции.')
|
||||
action = body.get('action')
|
||||
if action == 'buy':
|
||||
action = 'purchase'
|
||||
fields = {'purchase': 'offer_id', 'create_invoice': 'offer_id', 'check_invoice': 'invoice_id'}
|
||||
if action not in fields:
|
||||
_fail(400, 'unknown_action', 'Неизвестное действие магазина.')
|
||||
selector = fields[action]
|
||||
# Amount, paid and target identity never cross the trusted settlement boundary.
|
||||
if set(body) - {'action', 'request_id', selector}:
|
||||
_fail(400, 'invalid_body', 'Переданы неподдерживаемые поля операции.')
|
||||
value = body.get(selector)
|
||||
if not isinstance(value, str) or not _ID.fullmatch(value):
|
||||
_fail(400, 'invalid_' + selector, 'Некорректный идентификатор операции.')
|
||||
normalized = {'action': action, 'request_id': request_id, selector: value}
|
||||
digest = hashlib.sha256(json.dumps(normalized, sort_keys=True).encode()).hexdigest()
|
||||
return normalized, digest
|
||||
|
||||
|
||||
def _receipt(con, uid, request_id, digest):
|
||||
row = con.execute('SELECT digest,result FROM commerce_operations WHERE uid=? AND request_id=?',
|
||||
(uid, request_id)).fetchone()
|
||||
if row is None:
|
||||
pending = con.execute('SELECT digest FROM commerce_invoices WHERE uid=? AND request_id=?',
|
||||
(uid, request_id)).fetchone()
|
||||
if pending is not None and pending['digest'] != digest:
|
||||
_fail(409, 'request_conflict', 'Идентификатор уже использован другой операцией.')
|
||||
return None
|
||||
if row['digest'] != digest:
|
||||
_fail(409, 'request_conflict', 'Идентификатор уже использован другой операцией.')
|
||||
return json.loads(row['result'])
|
||||
|
||||
|
||||
def _save_receipt(con, uid, body, digest, result):
|
||||
con.execute('INSERT INTO commerce_operations(uid,request_id,digest,result) VALUES(?,?,?,?)',
|
||||
(uid, body['request_id'], digest, json.dumps(result)))
|
||||
|
||||
|
||||
def _invoice_public(row):
|
||||
return {'id': row['id'], 'amount_cents': int(row['amount_cents']), 'currency': row['currency'],
|
||||
'status': row['status'], 'pay_url': row['pay_url'], 'created': int(row['created'])}
|
||||
|
||||
|
||||
def _token(token):
|
||||
if not isinstance(token, str) or not token.strip():
|
||||
_fail(503, 'payment_unavailable', 'Платежи пока не настроены.')
|
||||
return token.strip()
|
||||
|
||||
|
||||
def snapshot(db, uid, offers=(), cryptopay_token='', now=None):
|
||||
available = configured_offers(offers)
|
||||
with closing(_connect(db)) as con:
|
||||
con.execute('BEGIN')
|
||||
_user(con, uid)
|
||||
row = con.execute('SELECT balance_cents FROM commerce_wallets WHERE uid=?', (uid,)).fetchone()
|
||||
history = [dict(item) for item in con.execute(
|
||||
'SELECT id,delta_cents,kind,offer_id,invoice_id,ts FROM commerce_ledger '
|
||||
'WHERE uid=? ORDER BY id DESC LIMIT 50', (uid,))]
|
||||
invoices = [_invoice_public(item) for item in con.execute(
|
||||
'SELECT * FROM commerce_invoices WHERE uid=? ORDER BY created DESC,id DESC LIMIT 30', (uid,))]
|
||||
result = {'uid': uid, 'wallet_cents': int(row[0]) if row else 0, 'currency': CURRENCY, 'offers': available,
|
||||
'entitlements': _entitlements(con, uid, _now(now)), 'history': history, 'invoices': invoices,
|
||||
'payment_enabled': bool(isinstance(cryptopay_token, str) and cryptopay_token.strip()
|
||||
and any(item['kind'] == 'wallet_topup' for item in available))}
|
||||
if not available:
|
||||
result['unavailable_reason'] = 'commerce_unavailable'
|
||||
elif not result['payment_enabled']:
|
||||
result['unavailable_reason'] = 'payment_unavailable'
|
||||
con.commit()
|
||||
return result
|
||||
|
||||
|
||||
def purchase(db, uid, body, offers=(), now=None, base_models=(), available_models=None):
|
||||
body, digest = _body(body)
|
||||
if body['action'] != 'purchase':
|
||||
_fail(400, 'unknown_action', 'Ожидалась покупка предложения.')
|
||||
stamp = _now(now)
|
||||
with closing(_connect(db)) as con:
|
||||
try:
|
||||
con.execute('BEGIN IMMEDIATE')
|
||||
_user(con, uid)
|
||||
previous = _receipt(con, uid, body['request_id'], digest)
|
||||
if previous is not None:
|
||||
con.rollback()
|
||||
return dict(previous, replayed=True)
|
||||
offer = _offer(offers, body['offer_id'], ('extra_requests', 'model_pass'))
|
||||
if (offer["kind"] == "model_pass" and available_models is not None
|
||||
and offer["model"] not in available_models):
|
||||
_fail(503, "model_offer_unavailable", "Предложение модели недоступно. Средства не списаны.")
|
||||
price = offer['price_cents']
|
||||
con.execute('INSERT OR IGNORE INTO commerce_wallets(uid) VALUES(?)', (uid,))
|
||||
if not con.execute('UPDATE commerce_wallets SET balance_cents=balance_cents-? '
|
||||
'WHERE uid=? AND balance_cents>=?', (price, uid, price)).rowcount:
|
||||
_fail(409, 'insufficient_funds', 'Недостаточно средств в денежном кошельке.')
|
||||
expires = stamp - ((stamp + 10800) % 86400) + 86400 if offer['kind'] == 'extra_requests' else stamp + 86400
|
||||
if offer['kind'] == 'extra_requests' and _entitlements(con, uid, stamp)['extra_requests'] + offer['requests'] > MAX_REQUESTS:
|
||||
_fail(409, 'entitlement_limit', 'Достигнут максимальный дополнительный лимит.')
|
||||
con.execute('INSERT INTO commerce_grants(uid,kind,requests,model,expires_at,base_granted,request_id,created) '
|
||||
'VALUES(?,?,?,?,?,?,?,?)',
|
||||
(uid, offer['kind'], offer.get('requests', 0), offer.get('model', ''), expires,
|
||||
int(offer.get('model') in base_models), body['request_id'], stamp))
|
||||
con.execute('INSERT INTO commerce_ledger(uid,delta_cents,kind,offer_id,request_id,ts) VALUES(?,?,?,?,?,?)',
|
||||
(uid, -price, 'purchase', offer['id'], body['request_id'], stamp))
|
||||
result = {'ok': True, 'action': 'purchase', 'offer_id': offer['id'], 'expires_at': expires,
|
||||
'charged_cents': price}
|
||||
_save_receipt(con, uid, body, digest, result)
|
||||
con.commit()
|
||||
return result
|
||||
except BaseException:
|
||||
con.rollback()
|
||||
raise
|
||||
|
||||
|
||||
async def _cp_post(token, method, data):
|
||||
token = _token(token)
|
||||
try:
|
||||
async with aiohttp.ClientSession(timeout=aiohttp.ClientTimeout(total=20)) as session:
|
||||
async with session.post(CP_BASE + '/' + method, json=data,
|
||||
headers={'Crypto-Pay-API-Token': token}, allow_redirects=False) as response:
|
||||
if response.status != 200:
|
||||
_fail(503, 'payment_provider_unavailable', 'Платёжный сервис временно недоступен.')
|
||||
result = await response.json()
|
||||
except CommerceError:
|
||||
# A provider-status failure already carries an exact message; do not let the
|
||||
# broad ValueError net (CommerceError subclasses ValueError) swallow it.
|
||||
raise
|
||||
except (aiohttp.ClientError, asyncio.TimeoutError, ValueError):
|
||||
_fail(503, 'payment_provider_unavailable', 'Не удалось подтвердить ответ платёжного сервиса.')
|
||||
if not isinstance(result, dict) or result.get('ok') is not True:
|
||||
_fail(503, 'payment_provider_unavailable', 'Платёжный сервис временно недоступен.')
|
||||
return result.get('result')
|
||||
|
||||
|
||||
def _invoice_matches(remote, local, paid=False):
|
||||
if not isinstance(remote, dict):
|
||||
_fail(409, 'payment_mismatch', 'Параметры счёта не подтверждены платёжным сервисом.')
|
||||
try:
|
||||
amount = Decimal(str(remote.get('amount')))
|
||||
valid_amount = amount.is_finite() and amount == Decimal(local['amount_cents']) / 100
|
||||
except (InvalidOperation, ValueError, TypeError):
|
||||
valid_amount = False
|
||||
valid = (type(remote.get('invoice_id')) is int and remote['invoice_id'] > 0 and valid_amount
|
||||
and remote.get('currency_type') == 'fiat' and remote.get('fiat') == local['currency']
|
||||
and remote.get('payload') == local['payload'])
|
||||
if local['provider_invoice_id'] is not None:
|
||||
valid = valid and remote.get('invoice_id') == local['provider_invoice_id']
|
||||
if not valid or paid and remote.get('status') != 'paid':
|
||||
_fail(409, 'payment_mismatch', 'Параметры счёта не подтверждены платёжным сервисом.')
|
||||
|
||||
|
||||
def _reserve_invoice(db, uid, body, digest, offers, stamp):
|
||||
with closing(_connect(db)) as con:
|
||||
try:
|
||||
con.execute('BEGIN IMMEDIATE')
|
||||
_user(con, uid)
|
||||
previous = _receipt(con, uid, body['request_id'], digest)
|
||||
if previous is not None:
|
||||
con.rollback()
|
||||
return None, dict(previous, replayed=True)
|
||||
row = con.execute('SELECT * FROM commerce_invoices WHERE uid=? AND request_id=?',
|
||||
(uid, body['request_id'])).fetchone()
|
||||
if row:
|
||||
if row['digest'] != digest:
|
||||
_fail(409, 'request_conflict', 'Идентификатор уже использован другой операцией.')
|
||||
# No provider idempotency guarantee: never create a second remote invoice.
|
||||
if row['provider_invoice_id'] is not None:
|
||||
_fail(409, 'request_conflict', 'Счёт уже создан; повтор с тем же номером недоступен.')
|
||||
if stamp - int(row['created']) < AMBIGUITY_GRACE:
|
||||
# A concurrent create for this request_id may still commit; retryable.
|
||||
_fail(503, 'invoice_unconfirmed',
|
||||
'Создание счёта не подтверждено. Повтори проверку с тем же номером.')
|
||||
# Past the grace window no create can still be in flight and this row
|
||||
# never exposed a pay_url, so it is inert. Terminalise the retry so the
|
||||
# client mints a new request_id instead of looping on 503 forever.
|
||||
_fail(409, 'invoice_abandoned',
|
||||
'Создание счёта не подтверждено и истекло. Создай новый счёт с новым номером операции.')
|
||||
offer = _offer(offers, body['offer_id'], ('wallet_topup',))
|
||||
identity, payload = secrets.token_hex(16), secrets.token_hex(24)
|
||||
con.execute('INSERT INTO commerce_invoices(id,uid,request_id,digest,offer_id,amount_cents,currency,'
|
||||
'payload,status,created,updated) VALUES(?,?,?,?,?,?,?,?,?,?,?)',
|
||||
(identity, uid, body['request_id'], digest, offer['id'], offer['price_cents'],
|
||||
CURRENCY, payload, 'creating', stamp, stamp))
|
||||
row = dict(con.execute('SELECT * FROM commerce_invoices WHERE id=?', (identity,)).fetchone())
|
||||
con.commit()
|
||||
return row, None
|
||||
except BaseException:
|
||||
con.rollback()
|
||||
raise
|
||||
|
||||
|
||||
def _mark_uncertain(db, identity, stamp):
|
||||
with closing(_connect(db)) as con:
|
||||
con.execute("UPDATE commerce_invoices SET status='uncertain',updated=? WHERE id=? AND status='creating'",
|
||||
(stamp, identity))
|
||||
|
||||
|
||||
def _save_invoice(db, uid, body, digest, local, remote, stamp):
|
||||
_invoice_matches(remote, local)
|
||||
pay_url = remote.get('bot_invoice_url') or remote.get('mini_app_invoice_url') or remote.get('pay_url')
|
||||
if not isinstance(pay_url, str):
|
||||
_fail(503, 'invoice_unconfirmed', 'Ссылка на оплату не подтверждена.')
|
||||
parsed = urlsplit(pay_url)
|
||||
if (parsed.scheme != 'https' or parsed.hostname not in ('t.me', 'pay.crypt.bot', 'crypt.bot')
|
||||
or parsed.username or parsed.password):
|
||||
_fail(503, 'invoice_unconfirmed', 'Ссылка на оплату не подтверждена.')
|
||||
with closing(_connect(db)) as con:
|
||||
try:
|
||||
con.execute('BEGIN IMMEDIATE')
|
||||
_user(con, uid)
|
||||
duplicate = con.execute('SELECT id FROM commerce_invoices WHERE provider_invoice_id=? AND id!=?',
|
||||
(remote['invoice_id'], local['id'])).fetchone()
|
||||
if duplicate is not None:
|
||||
_fail(409, 'payment_mismatch', 'Платёжный сервис вернул ранее использованный счёт.')
|
||||
con.execute("UPDATE commerce_invoices SET provider_invoice_id=?,status='pending',pay_url=?,updated=? "
|
||||
"WHERE id=? AND uid=? AND status='creating'", (remote['invoice_id'], pay_url, stamp, local['id'], uid))
|
||||
row = con.execute('SELECT * FROM commerce_invoices WHERE id=? AND uid=?', (local['id'], uid)).fetchone()
|
||||
if row['provider_invoice_id'] != remote['invoice_id']:
|
||||
_fail(503, 'invoice_unconfirmed', 'Счёт ожидает проверки поддержки.')
|
||||
result = {'ok': True, 'action': 'create_invoice', 'invoice': _invoice_public(row)}
|
||||
_save_receipt(con, uid, body, digest, result)
|
||||
con.commit()
|
||||
return result
|
||||
except BaseException:
|
||||
con.rollback()
|
||||
raise
|
||||
|
||||
|
||||
def _load_invoice(db, uid, body, digest):
|
||||
with closing(_connect(db)) as con:
|
||||
_user(con, uid)
|
||||
previous = _receipt(con, uid, body['request_id'], digest)
|
||||
if previous is not None:
|
||||
return None, dict(previous, replayed=True)
|
||||
row = con.execute('SELECT * FROM commerce_invoices WHERE id=? AND uid=?',
|
||||
(body['invoice_id'], uid)).fetchone()
|
||||
if row is None:
|
||||
_fail(404, 'invoice_not_found', 'Счёт не найден.')
|
||||
if row['provider_invoice_id'] is None:
|
||||
_fail(503, 'invoice_unconfirmed', 'Счёт ожидает проверки поддержки.')
|
||||
return dict(row), None
|
||||
|
||||
|
||||
def _settle_invoice(db, uid, body, digest, local, remote, stamp):
|
||||
_invoice_matches(remote, local)
|
||||
if remote.get('status') not in ('active', 'paid', 'expired'):
|
||||
_fail(503, 'payment_provider_unavailable', 'Статус оплаты не подтверждён.')
|
||||
with closing(_connect(db)) as con:
|
||||
try:
|
||||
con.execute('BEGIN IMMEDIATE')
|
||||
_user(con, uid)
|
||||
previous = _receipt(con, uid, body['request_id'], digest)
|
||||
if previous is not None:
|
||||
con.rollback()
|
||||
return dict(previous, replayed=True)
|
||||
row = con.execute('SELECT * FROM commerce_invoices WHERE id=? AND uid=?', (local['id'], uid)).fetchone()
|
||||
if row is None or row['provider_invoice_id'] != remote['invoice_id']:
|
||||
_fail(409, 'payment_mismatch', 'Счёт не соответствует ожидаемому платежу.')
|
||||
_invoice_matches(remote, row)
|
||||
credited = row['credited_at'] is not None
|
||||
if remote['status'] == 'paid' and not credited:
|
||||
con.execute('INSERT OR IGNORE INTO commerce_wallets(uid) VALUES(?)', (uid,))
|
||||
if not con.execute('UPDATE commerce_wallets SET balance_cents=balance_cents+? '
|
||||
'WHERE uid=? AND balance_cents<=?',
|
||||
(row['amount_cents'], uid, MAX_CENTS-row['amount_cents'])).rowcount:
|
||||
_fail(409, 'wallet_limit', 'Лимит кошелька превышен. Обратись в поддержку.')
|
||||
con.execute('INSERT INTO commerce_ledger(uid,delta_cents,kind,offer_id,invoice_id,request_id,ts) '
|
||||
"VALUES(?,?,'payment',?,?,?,?)",
|
||||
(uid, row['amount_cents'], row['offer_id'], row['id'], body['request_id'], stamp))
|
||||
con.execute("UPDATE commerce_invoices SET status='credited',credited_at=?,updated=? WHERE id=?",
|
||||
(stamp, stamp, row['id']))
|
||||
credited = True
|
||||
elif not credited:
|
||||
con.execute('UPDATE commerce_invoices SET status=?,updated=? WHERE id=?',
|
||||
('expired' if remote['status'] == 'expired' else 'pending', stamp, row['id']))
|
||||
row = con.execute('SELECT * FROM commerce_invoices WHERE id=?', (row['id'],)).fetchone()
|
||||
result = {'ok': True, 'action': 'check_invoice', 'paid': credited,
|
||||
'credited_cents': int(row['amount_cents']) if credited else 0,
|
||||
'invoice': _invoice_public(row)}
|
||||
_save_receipt(con, uid, body, digest, result)
|
||||
con.commit()
|
||||
return result
|
||||
except BaseException:
|
||||
con.rollback()
|
||||
raise
|
||||
|
||||
|
||||
async def act(db, uid, body, offers=(), cryptopay_token='', now=None, base_models=(), available_models=None):
|
||||
"""Authenticated UID and offers/token must come from the server, not the body.
|
||||
|
||||
Each SQLite phase is a short transaction on a worker thread. No network I/O
|
||||
occurs in a transaction. A failed/ambiguous create cannot mint a second invoice.
|
||||
A confirmed pending check is a completed receipt; polling uses a new request_id.
|
||||
"""
|
||||
body, digest = _body(body)
|
||||
stamp = _now(now)
|
||||
if body['action'] == 'purchase':
|
||||
result = await asyncio.to_thread(purchase, db, uid, body, offers, stamp, base_models, available_models)
|
||||
elif body['action'] == 'create_invoice':
|
||||
_token(cryptopay_token)
|
||||
local, result = await asyncio.to_thread(_reserve_invoice, db, uid, body, digest, offers, stamp)
|
||||
if result is None:
|
||||
try:
|
||||
remote = await _cp_post(cryptopay_token, 'createInvoice', {
|
||||
'currency_type': 'fiat', 'fiat': local['currency'],
|
||||
'amount': format(Decimal(local['amount_cents']) / 100, '.2f'),
|
||||
'payload': local['payload'], 'description': 'IISHKO USD wallet',
|
||||
'allow_comments': False, 'allow_anonymous': False, 'expires_in': 3600})
|
||||
result = await asyncio.to_thread(_save_invoice, db, uid, body, digest, local, remote, stamp)
|
||||
except BaseException as error:
|
||||
await asyncio.to_thread(_mark_uncertain, db, local['id'], stamp)
|
||||
if isinstance(error, CommerceError):
|
||||
error.operation_rejected = False # A remote invoice may already exist.
|
||||
raise
|
||||
else:
|
||||
# Local receipts are safe to replay even when a payment token is later disabled.
|
||||
local, result = await asyncio.to_thread(_load_invoice, db, uid, body, digest)
|
||||
if result is None:
|
||||
_token(cryptopay_token)
|
||||
response = await _cp_post(cryptopay_token, 'getInvoices', {'invoice_ids': str(local['provider_invoice_id'])})
|
||||
items = response.get('items') if isinstance(response, dict) else None
|
||||
if not isinstance(items, list) or len(items) != 1:
|
||||
_fail(409, 'payment_mismatch', 'Платёжный сервис не подтвердил единственный ожидаемый счёт.')
|
||||
result = await asyncio.to_thread(_settle_invoice, db, uid, body, digest, local, items[0], stamp)
|
||||
try:
|
||||
result['state'] = await asyncio.to_thread(snapshot, db, uid, offers, cryptopay_token, stamp)
|
||||
except (CommerceError, sqlite3.Error, OSError, ValueError, TypeError, KeyError):
|
||||
# The mutation already committed above; a best-effort state refresh must not
|
||||
# mask a committed purchase/settle with a false error. The receipt stands.
|
||||
result['state'] = None
|
||||
return result
|
||||
@@ -0,0 +1,396 @@
|
||||
Attribution 4.0 International
|
||||
|
||||
=======================================================================
|
||||
|
||||
Creative Commons Corporation ("Creative Commons") is not a law firm and
|
||||
does not provide legal services or legal advice. Distribution of
|
||||
Creative Commons public licenses does not create a lawyer-client or
|
||||
other relationship. Creative Commons makes its licenses and related
|
||||
information available on an "as-is" basis. Creative Commons gives no
|
||||
warranties regarding its licenses, any material licensed under their
|
||||
terms and conditions, or any related information. Creative Commons
|
||||
disclaims all liability for damages resulting from their use to the
|
||||
fullest extent possible.
|
||||
|
||||
Using Creative Commons Public Licenses
|
||||
|
||||
Creative Commons public licenses provide a standard set of terms and
|
||||
conditions that creators and other rights holders may use to share
|
||||
original works of authorship and other material subject to copyright
|
||||
and certain other rights specified in the public license below. The
|
||||
following considerations are for informational purposes only, are not
|
||||
exhaustive, and do not form part of our licenses.
|
||||
|
||||
Considerations for licensors: Our public licenses are
|
||||
intended for use by those authorized to give the public
|
||||
permission to use material in ways otherwise restricted by
|
||||
copyright and certain other rights. Our licenses are
|
||||
irrevocable. Licensors should read and understand the terms
|
||||
and conditions of the license they choose before applying it.
|
||||
Licensors should also secure all rights necessary before
|
||||
applying our licenses so that the public can reuse the
|
||||
material as expected. Licensors should clearly mark any
|
||||
material not subject to the license. This includes other CC-
|
||||
licensed material, or material used under an exception or
|
||||
limitation to copyright. More considerations for licensors:
|
||||
wiki.creativecommons.org/Considerations_for_licensors
|
||||
|
||||
Considerations for the public: By using one of our public
|
||||
licenses, a licensor grants the public permission to use the
|
||||
licensed material under specified terms and conditions. If
|
||||
the licensor's permission is not necessary for any reason--for
|
||||
example, because of any applicable exception or limitation to
|
||||
copyright--then that use is not regulated by the license. Our
|
||||
licenses grant only permissions under copyright and certain
|
||||
other rights that a licensor has authority to grant. Use of
|
||||
the licensed material may still be restricted for other
|
||||
reasons, including because others have copyright or other
|
||||
rights in the material. A licensor may make special requests,
|
||||
such as asking that all changes be marked or described.
|
||||
Although not required by our licenses, you are encouraged to
|
||||
respect those requests where reasonable. More considerations
|
||||
for the public:
|
||||
wiki.creativecommons.org/Considerations_for_licensees
|
||||
|
||||
=======================================================================
|
||||
|
||||
Creative Commons Attribution 4.0 International Public License
|
||||
|
||||
By exercising the Licensed Rights (defined below), You accept and agree
|
||||
to be bound by the terms and conditions of this Creative Commons
|
||||
Attribution 4.0 International Public License ("Public License"). To the
|
||||
extent this Public License may be interpreted as a contract, You are
|
||||
granted the Licensed Rights in consideration of Your acceptance of
|
||||
these terms and conditions, and the Licensor grants You such rights in
|
||||
consideration of benefits the Licensor receives from making the
|
||||
Licensed Material available under these terms and conditions.
|
||||
|
||||
|
||||
Section 1 -- Definitions.
|
||||
|
||||
a. Adapted Material means material subject to Copyright and Similar
|
||||
Rights that is derived from or based upon the Licensed Material
|
||||
and in which the Licensed Material is translated, altered,
|
||||
arranged, transformed, or otherwise modified in a manner requiring
|
||||
permission under the Copyright and Similar Rights held by the
|
||||
Licensor. For purposes of this Public License, where the Licensed
|
||||
Material is a musical work, performance, or sound recording,
|
||||
Adapted Material is always produced where the Licensed Material is
|
||||
synched in timed relation with a moving image.
|
||||
|
||||
b. Adapter's License means the license You apply to Your Copyright
|
||||
and Similar Rights in Your contributions to Adapted Material in
|
||||
accordance with the terms and conditions of this Public License.
|
||||
|
||||
c. Copyright and Similar Rights means copyright and/or similar rights
|
||||
closely related to copyright including, without limitation,
|
||||
performance, broadcast, sound recording, and Sui Generis Database
|
||||
Rights, without regard to how the rights are labeled or
|
||||
categorized. For purposes of this Public License, the rights
|
||||
specified in Section 2(b)(1)-(2) are not Copyright and Similar
|
||||
Rights.
|
||||
|
||||
d. Effective Technological Measures means those measures that, in the
|
||||
absence of proper authority, may not be circumvented under laws
|
||||
fulfilling obligations under Article 11 of the WIPO Copyright
|
||||
Treaty adopted on December 20, 1996, and/or similar international
|
||||
agreements.
|
||||
|
||||
e. Exceptions and Limitations means fair use, fair dealing, and/or
|
||||
any other exception or limitation to Copyright and Similar Rights
|
||||
that applies to Your use of the Licensed Material.
|
||||
|
||||
f. Licensed Material means the artistic or literary work, database,
|
||||
or other material to which the Licensor applied this Public
|
||||
License.
|
||||
|
||||
g. Licensed Rights means the rights granted to You subject to the
|
||||
terms and conditions of this Public License, which are limited to
|
||||
all Copyright and Similar Rights that apply to Your use of the
|
||||
Licensed Material and that the Licensor has authority to license.
|
||||
|
||||
h. Licensor means the individual(s) or entity(ies) granting rights
|
||||
under this Public License.
|
||||
|
||||
i. Share means to provide material to the public by any means or
|
||||
process that requires permission under the Licensed Rights, such
|
||||
as reproduction, public display, public performance, distribution,
|
||||
dissemination, communication, or importation, and to make material
|
||||
available to the public including in ways that members of the
|
||||
public may access the material from a place and at a time
|
||||
individually chosen by them.
|
||||
|
||||
j. Sui Generis Database Rights means rights other than copyright
|
||||
resulting from Directive 96/9/EC of the European Parliament and of
|
||||
the Council of 11 March 1996 on the legal protection of databases,
|
||||
as amended and/or succeeded, as well as other essentially
|
||||
equivalent rights anywhere in the world.
|
||||
|
||||
k. You means the individual or entity exercising the Licensed Rights
|
||||
under this Public License. Your has a corresponding meaning.
|
||||
|
||||
|
||||
Section 2 -- Scope.
|
||||
|
||||
a. License grant.
|
||||
|
||||
1. Subject to the terms and conditions of this Public License,
|
||||
the Licensor hereby grants You a worldwide, royalty-free,
|
||||
non-sublicensable, non-exclusive, irrevocable license to
|
||||
exercise the Licensed Rights in the Licensed Material to:
|
||||
|
||||
a. reproduce and Share the Licensed Material, in whole or
|
||||
in part; and
|
||||
|
||||
b. produce, reproduce, and Share Adapted Material.
|
||||
|
||||
2. Exceptions and Limitations. For the avoidance of doubt, where
|
||||
Exceptions and Limitations apply to Your use, this Public
|
||||
License does not apply, and You do not need to comply with
|
||||
its terms and conditions.
|
||||
|
||||
3. Term. The term of this Public License is specified in Section
|
||||
6(a).
|
||||
|
||||
4. Media and formats; technical modifications allowed. The
|
||||
Licensor authorizes You to exercise the Licensed Rights in
|
||||
all media and formats whether now known or hereafter created,
|
||||
and to make technical modifications necessary to do so. The
|
||||
Licensor waives and/or agrees not to assert any right or
|
||||
authority to forbid You from making technical modifications
|
||||
necessary to exercise the Licensed Rights, including
|
||||
technical modifications necessary to circumvent Effective
|
||||
Technological Measures. For purposes of this Public License,
|
||||
simply making modifications authorized by this Section 2(a)
|
||||
(4) never produces Adapted Material.
|
||||
|
||||
5. Downstream recipients.
|
||||
|
||||
a. Offer from the Licensor -- Licensed Material. Every
|
||||
recipient of the Licensed Material automatically
|
||||
receives an offer from the Licensor to exercise the
|
||||
Licensed Rights under the terms and conditions of this
|
||||
Public License.
|
||||
|
||||
b. No downstream restrictions. You may not offer or impose
|
||||
any additional or different terms or conditions on, or
|
||||
apply any Effective Technological Measures to, the
|
||||
Licensed Material if doing so restricts exercise of the
|
||||
Licensed Rights by any recipient of the Licensed
|
||||
Material.
|
||||
|
||||
6. No endorsement. Nothing in this Public License constitutes or
|
||||
may be construed as permission to assert or imply that You
|
||||
are, or that Your use of the Licensed Material is, connected
|
||||
with, or sponsored, endorsed, or granted official status by,
|
||||
the Licensor or others designated to receive attribution as
|
||||
provided in Section 3(a)(1)(A)(i).
|
||||
|
||||
b. Other rights.
|
||||
|
||||
1. Moral rights, such as the right of integrity, are not
|
||||
licensed under this Public License, nor are publicity,
|
||||
privacy, and/or other similar personality rights; however, to
|
||||
the extent possible, the Licensor waives and/or agrees not to
|
||||
assert any such rights held by the Licensor to the limited
|
||||
extent necessary to allow You to exercise the Licensed
|
||||
Rights, but not otherwise.
|
||||
|
||||
2. Patent and trademark rights are not licensed under this
|
||||
Public License.
|
||||
|
||||
3. To the extent possible, the Licensor waives any right to
|
||||
collect royalties from You for the exercise of the Licensed
|
||||
Rights, whether directly or through a collecting society
|
||||
under any voluntary or waivable statutory or compulsory
|
||||
licensing scheme. In all other cases the Licensor expressly
|
||||
reserves any right to collect such royalties.
|
||||
|
||||
|
||||
Section 3 -- License Conditions.
|
||||
|
||||
Your exercise of the Licensed Rights is expressly made subject to the
|
||||
following conditions.
|
||||
|
||||
a. Attribution.
|
||||
|
||||
1. If You Share the Licensed Material (including in modified
|
||||
form), You must:
|
||||
|
||||
a. retain the following if it is supplied by the Licensor
|
||||
with the Licensed Material:
|
||||
|
||||
i. identification of the creator(s) of the Licensed
|
||||
Material and any others designated to receive
|
||||
attribution, in any reasonable manner requested by
|
||||
the Licensor (including by pseudonym if
|
||||
designated);
|
||||
|
||||
ii. a copyright notice;
|
||||
|
||||
iii. a notice that refers to this Public License;
|
||||
|
||||
iv. a notice that refers to the disclaimer of
|
||||
warranties;
|
||||
|
||||
v. a URI or hyperlink to the Licensed Material to the
|
||||
extent reasonably practicable;
|
||||
|
||||
b. indicate if You modified the Licensed Material and
|
||||
retain an indication of any previous modifications; and
|
||||
|
||||
c. indicate the Licensed Material is licensed under this
|
||||
Public License, and include the text of, or the URI or
|
||||
hyperlink to, this Public License.
|
||||
|
||||
2. You may satisfy the conditions in Section 3(a)(1) in any
|
||||
reasonable manner based on the medium, means, and context in
|
||||
which You Share the Licensed Material. For example, it may be
|
||||
reasonable to satisfy the conditions by providing a URI or
|
||||
hyperlink to a resource that includes the required
|
||||
information.
|
||||
|
||||
3. If requested by the Licensor, You must remove any of the
|
||||
information required by Section 3(a)(1)(A) to the extent
|
||||
reasonably practicable.
|
||||
|
||||
4. If You Share Adapted Material You produce, the Adapter's
|
||||
License You apply must not prevent recipients of the Adapted
|
||||
Material from complying with this Public License.
|
||||
|
||||
|
||||
Section 4 -- Sui Generis Database Rights.
|
||||
|
||||
Where the Licensed Rights include Sui Generis Database Rights that
|
||||
apply to Your use of the Licensed Material:
|
||||
|
||||
a. for the avoidance of doubt, Section 2(a)(1) grants You the right
|
||||
to extract, reuse, reproduce, and Share all or a substantial
|
||||
portion of the contents of the database;
|
||||
|
||||
b. if You include all or a substantial portion of the database
|
||||
contents in a database in which You have Sui Generis Database
|
||||
Rights, then the database in which You have Sui Generis Database
|
||||
Rights (but not its individual contents) is Adapted Material; and
|
||||
|
||||
c. You must comply with the conditions in Section 3(a) if You Share
|
||||
all or a substantial portion of the contents of the database.
|
||||
|
||||
For the avoidance of doubt, this Section 4 supplements and does not
|
||||
replace Your obligations under this Public License where the Licensed
|
||||
Rights include other Copyright and Similar Rights.
|
||||
|
||||
|
||||
Section 5 -- Disclaimer of Warranties and Limitation of Liability.
|
||||
|
||||
a. UNLESS OTHERWISE SEPARATELY UNDERTAKEN BY THE LICENSOR, TO THE
|
||||
EXTENT POSSIBLE, THE LICENSOR OFFERS THE LICENSED MATERIAL AS-IS
|
||||
AND AS-AVAILABLE, AND MAKES NO REPRESENTATIONS OR WARRANTIES OF
|
||||
ANY KIND CONCERNING THE LICENSED MATERIAL, WHETHER EXPRESS,
|
||||
IMPLIED, STATUTORY, OR OTHER. THIS INCLUDES, WITHOUT LIMITATION,
|
||||
WARRANTIES OF TITLE, MERCHANTABILITY, FITNESS FOR A PARTICULAR
|
||||
PURPOSE, NON-INFRINGEMENT, ABSENCE OF LATENT OR OTHER DEFECTS,
|
||||
ACCURACY, OR THE PRESENCE OR ABSENCE OF ERRORS, WHETHER OR NOT
|
||||
KNOWN OR DISCOVERABLE. WHERE DISCLAIMERS OF WARRANTIES ARE NOT
|
||||
ALLOWED IN FULL OR IN PART, THIS DISCLAIMER MAY NOT APPLY TO YOU.
|
||||
|
||||
b. TO THE EXTENT POSSIBLE, IN NO EVENT WILL THE LICENSOR BE LIABLE
|
||||
TO YOU ON ANY LEGAL THEORY (INCLUDING, WITHOUT LIMITATION,
|
||||
NEGLIGENCE) OR OTHERWISE FOR ANY DIRECT, SPECIAL, INDIRECT,
|
||||
INCIDENTAL, CONSEQUENTIAL, PUNITIVE, EXEMPLARY, OR OTHER LOSSES,
|
||||
COSTS, EXPENSES, OR DAMAGES ARISING OUT OF THIS PUBLIC LICENSE OR
|
||||
USE OF THE LICENSED MATERIAL, EVEN IF THE LICENSOR HAS BEEN
|
||||
ADVISED OF THE POSSIBILITY OF SUCH LOSSES, COSTS, EXPENSES, OR
|
||||
DAMAGES. WHERE A LIMITATION OF LIABILITY IS NOT ALLOWED IN FULL OR
|
||||
IN PART, THIS LIMITATION MAY NOT APPLY TO YOU.
|
||||
|
||||
c. The disclaimer of warranties and limitation of liability provided
|
||||
above shall be interpreted in a manner that, to the extent
|
||||
possible, most closely approximates an absolute disclaimer and
|
||||
waiver of all liability.
|
||||
|
||||
|
||||
Section 6 -- Term and Termination.
|
||||
|
||||
a. This Public License applies for the term of the Copyright and
|
||||
Similar Rights licensed here. However, if You fail to comply with
|
||||
this Public License, then Your rights under this Public License
|
||||
terminate automatically.
|
||||
|
||||
b. Where Your right to use the Licensed Material has terminated under
|
||||
Section 6(a), it reinstates:
|
||||
|
||||
1. automatically as of the date the violation is cured, provided
|
||||
it is cured within 30 days of Your discovery of the
|
||||
violation; or
|
||||
|
||||
2. upon express reinstatement by the Licensor.
|
||||
|
||||
For the avoidance of doubt, this Section 6(b) does not affect any
|
||||
right the Licensor may have to seek remedies for Your violations
|
||||
of this Public License.
|
||||
|
||||
c. For the avoidance of doubt, the Licensor may also offer the
|
||||
Licensed Material under separate terms or conditions or stop
|
||||
distributing the Licensed Material at any time; however, doing so
|
||||
will not terminate this Public License.
|
||||
|
||||
d. Sections 1, 5, 6, 7, and 8 survive termination of this Public
|
||||
License.
|
||||
|
||||
|
||||
Section 7 -- Other Terms and Conditions.
|
||||
|
||||
a. The Licensor shall not be bound by any additional or different
|
||||
terms or conditions communicated by You unless expressly agreed.
|
||||
|
||||
b. Any arrangements, understandings, or agreements regarding the
|
||||
Licensed Material not stated herein are separate from and
|
||||
independent of the terms and conditions of this Public License.
|
||||
|
||||
|
||||
Section 8 -- Interpretation.
|
||||
|
||||
a. For the avoidance of doubt, this Public License does not, and
|
||||
shall not be interpreted to, reduce, limit, restrict, or impose
|
||||
conditions on any use of the Licensed Material that could lawfully
|
||||
be made without permission under this Public License.
|
||||
|
||||
b. To the extent possible, if any provision of this Public License is
|
||||
deemed unenforceable, it shall be automatically reformed to the
|
||||
minimum extent necessary to make it enforceable. If the provision
|
||||
cannot be reformed, it shall be severed from this Public License
|
||||
without affecting the enforceability of the remaining terms and
|
||||
conditions.
|
||||
|
||||
c. No term or condition of this Public License will be waived and no
|
||||
failure to comply consented to unless expressly agreed to by the
|
||||
Licensor.
|
||||
|
||||
d. Nothing in this Public License constitutes or may be interpreted
|
||||
as a limitation upon, or waiver of, any privileges and immunities
|
||||
that apply to the Licensor or You, including from the legal
|
||||
processes of any jurisdiction or authority.
|
||||
|
||||
|
||||
=======================================================================
|
||||
|
||||
Creative Commons is not a party to its public
|
||||
licenses. Notwithstanding, Creative Commons may elect to apply one of
|
||||
its public licenses to material it publishes and in those instances
|
||||
will be considered the “Licensor.” The text of the Creative Commons
|
||||
public licenses is dedicated to the public domain under the CC0 Public
|
||||
Domain Dedication. Except for the limited purpose of indicating that
|
||||
material is shared under a Creative Commons public license or as
|
||||
otherwise permitted by the Creative Commons policies published at
|
||||
creativecommons.org/policies, Creative Commons does not authorize the
|
||||
use of the trademark "Creative Commons" or any other trademark or logo
|
||||
of Creative Commons without its prior written consent including,
|
||||
without limitation, in connection with any unauthorized modifications
|
||||
to any of its public licenses or any other arrangements,
|
||||
understandings, or agreements concerning use of licensed material. For
|
||||
the avoidance of doubt, this paragraph does not form part of the
|
||||
public licenses.
|
||||
|
||||
Creative Commons may be contacted at creativecommons.org.
|
||||
|
||||
@@ -0,0 +1,55 @@
|
||||
{
|
||||
"schema_version": 1,
|
||||
"provider": "DB-IP",
|
||||
"dataset": "DB-IP IP to City Lite",
|
||||
"release": "2026-10",
|
||||
"release_date": "2026-10-01",
|
||||
"retrieved_at_utc": "2026-10-25",
|
||||
"download_page_url": "https://db-ip.com/db/download/ip-to-city-lite",
|
||||
"download_page_sha256": "184fe5ab257a5b0beb6003a9ad531924c12c6ed4c9527ac50e89a95a416c1d71",
|
||||
"schema_url": "https://db-ip.com/db/format/ip-to-city-lite/mmdb.html",
|
||||
"source_url": "https://download.db-ip.com/free/dbip-city-lite-2026-10.mmdb.gz",
|
||||
"license": "CC-BY-4.0",
|
||||
"license_url": "https://creativecommons.org/licenses/by/4.0/",
|
||||
"license_text_url": "https://creativecommons.org/licenses/by/4.0/legalcode.txt",
|
||||
"license_file": "DB-IP-CC-BY-4.0-LICENSE.txt",
|
||||
"license_sha256": "9ba9550ad48438d0836ddab3da480b3b69ffa0aac7b7878b5a0039e7ab429411",
|
||||
"attribution": {
|
||||
"text": "IP Geolocation by DB-IP",
|
||||
"url": "https://db-ip.com",
|
||||
"html": "<a href='https://db-ip.com'>IP Geolocation by DB-IP</a>",
|
||||
"required_display": "Include a clickable DB-IP attribution link in owner alert messages displaying results and in the existing privacy policy surface; do not expose audit results to ordinary users."
|
||||
},
|
||||
"modifications": "Unmodified original MMDB; gzip decompression only. No data edits. Application returns only country/city and static source, never location coordinates.",
|
||||
"official_checksums": {
|
||||
"md5": "5966907981d3e82f338e823d1b83e002",
|
||||
"sha1": "df17bd24390108ed1d24dcb7718dc60f6b9abd4f",
|
||||
"representation": "uncompressed_mmdb",
|
||||
"verification": "Downloaded official gzip over HTTPS, independently hashed both compressed and uncompressed representations; BOTH official values match only the decompressed MMDB."
|
||||
},
|
||||
"runtime_asset": {
|
||||
"file": "dbip-city-lite-2026-10.mmdb",
|
||||
"size_bytes": 126998165,
|
||||
"md5": "5966907981d3e82f338e823d1b83e002",
|
||||
"sha1": "df17bd24390108ed1d24dcb7718dc60f6b9abd4f",
|
||||
"sha256": "9e250f02722d1ad1780f88192f0e908af285478a33e76b88b349c9181ae9d0f5"
|
||||
},
|
||||
"build_only_archive": {
|
||||
"file": "../../geo-downloads/dbip-city-lite-2026-10.mmdb.gz",
|
||||
"deployed": false,
|
||||
"size_bytes": 60193321,
|
||||
"md5": "cea73c8fa0400c8751763c8993c6e116",
|
||||
"sha1": "71dd7ad3448ebbe8ff86e390f4a8b5276c195284",
|
||||
"sha256": "c839d407f85a1e0bddba354cef16b2c398182d1c34ed8d985555dce134b36b14"
|
||||
},
|
||||
"runtime": {
|
||||
"network": false,
|
||||
"automatic_downloads": false,
|
||||
"automatic_updates": false,
|
||||
"path": "Fixed geo/dbip-city-lite-2026-10.mmdb adjacent to entry_geo.py; no environment override",
|
||||
"integrity": "Hardcoded exact size and SHA256 verified once before decoder use; unchanged regular-file identity checked on every lookup; changes/read failures disable geo until process restart",
|
||||
"resources": "One read-only mmap per process; 1 MiB transient hash chunks; upstream per-decode limits 65536 values,512 levels,2 MiB payload; serialized initialization and reads",
|
||||
"accuracy": "Approximate IP country/city only; reduced accuracy/free dataset, VPN/carrier/shared-egress may not represent physical user location",
|
||||
"consent": "Caller must enforce existing privacy consent before calling; entry_geo does not persist inputs or results"
|
||||
}
|
||||
}
|
||||
+14784
File diff suppressed because it is too large
Load Diff
+437
@@ -0,0 +1,437 @@
|
||||
{
|
||||
"✈️": "6028346797368283073",
|
||||
"🍏": "5775870512127283512",
|
||||
"⭐️": "6028338546736107668",
|
||||
"🎁": "5773677501825945508",
|
||||
"🔣": "6035162669948867129",
|
||||
"🖥": "5942734685976138521",
|
||||
"⚙️": "5904258298764334001",
|
||||
"⚙": "6032742198179532882",
|
||||
"🎛": "5776424837786374634",
|
||||
"📰": "5895519358871932592",
|
||||
"📝": "5920046907782074235",
|
||||
"🗂": "5766994197705921104",
|
||||
"↔️": "5893316448670978477",
|
||||
"⬅️": "5960671702059848143",
|
||||
"🔁": "6030657343744644592",
|
||||
"⏫": "5938437708635443119",
|
||||
"✏️": "6039779802741739617",
|
||||
"✏": "6039614175917903752",
|
||||
"❌": "6030757850274336631",
|
||||
"⌨": "6039404727542747508",
|
||||
"📎": "6039451237743595514",
|
||||
"🔧": "5962952497197748583",
|
||||
"🔨": "5940433880585605708",
|
||||
"🚪": "6035130900075777681",
|
||||
"🔎": "6032850693348399258",
|
||||
"🏷": "5888620056551625531",
|
||||
"↩️": "5895507195524550741",
|
||||
"➡️": "5895383238473421210",
|
||||
"📺": "6039391078136681499",
|
||||
"🔗": "6028171274939797252",
|
||||
"➕": "6032924188828767321",
|
||||
"ℹ": "6028435952299413210",
|
||||
"❓": "6030848053177486888",
|
||||
"❗️": "6030563507299160824",
|
||||
"▶️": "5773626993010546707",
|
||||
"✅": "5774022692642492953",
|
||||
"⬆️": "6028205772117118673",
|
||||
"🔓": "6037496202990194718",
|
||||
"🔒": "6037249452824072506",
|
||||
"🖼": "6030466823290360017",
|
||||
"🤖": "6030400221232501136",
|
||||
"📁": "6037475557082403885",
|
||||
"📄": "6034969813032374911",
|
||||
"🗑": "6039522349517115015",
|
||||
"🎶": "6037364759811068375",
|
||||
"👁": "6037397706505195857",
|
||||
"⬇️": "6037157012242960559",
|
||||
"☁": "6028115612163641653",
|
||||
"📤": "6039573425268201570",
|
||||
"🛡": "6030537007350944596",
|
||||
"📂": "6039630677182254664",
|
||||
"📥": "6041730074376410123",
|
||||
"📢": "6021418126061605425",
|
||||
"📣": "6039450962865688331",
|
||||
"🔊": "6039454987250044861",
|
||||
"🔇": "6039505337151655702",
|
||||
"🔈": "6039853100653612987",
|
||||
"🔔": "6039486778597970865",
|
||||
"🔕": "6039569594157371705",
|
||||
"📷": "6030506650522096180",
|
||||
"🎞": "5944777041709633960",
|
||||
"❤️": "6037533152593842454",
|
||||
"📖": "6037286673010660132",
|
||||
"5️⃣": "6035231690073314447",
|
||||
"2️⃣": "6034847960515219908",
|
||||
"⏰": "5850317551090800862",
|
||||
"🕓": "5775896410780079073",
|
||||
"👣": "5843679481566335204",
|
||||
"✅️": "5843596438373667352",
|
||||
"⏲️": "6037268453759389862",
|
||||
"⏰️": "5983150113483134607",
|
||||
"🥇": "6037428784888549034",
|
||||
"1️⃣": "5940515192906456099",
|
||||
"🎥": "5886579539064132088",
|
||||
"🎤": "6030722571412967168",
|
||||
"🎙": "6030467682283818947",
|
||||
"📞": "6039605143601680423",
|
||||
"☎️": "6039398100408209720",
|
||||
"💬": "6030784887093464891",
|
||||
"💡": "5891120964468480450",
|
||||
"💭": "5904248647972820334",
|
||||
"💤": "5983401171501454028",
|
||||
"🔞": "5922610170034132416",
|
||||
"📍": "6030399199030284183",
|
||||
"👤": "6032994772321309200",
|
||||
"🗣": "6032653721853234759",
|
||||
"👥": "6032609071373226027",
|
||||
"🎯": "6032949275732742941",
|
||||
"🎭": "6032625495328165724",
|
||||
"🙂": "5774034804450267485",
|
||||
"🙁": "5778197572652897847",
|
||||
"😀": "6043996047582170909",
|
||||
"😝": "6043847274210005137",
|
||||
"🤔": "6043960760130868895",
|
||||
"😐": "6041748912102968702",
|
||||
"😨": "6043973168291384891",
|
||||
"☹️": "6042029429301973188",
|
||||
"😡": "6044118213631938928",
|
||||
"🐻": "6044004057696177711",
|
||||
"🎉": "6041731551845159060",
|
||||
"👋": "6041921818896372382",
|
||||
"👍": "6041720006973067267",
|
||||
"👎": "6041716699848249286",
|
||||
"👆": "5886676966102274844",
|
||||
"✋️": "5891184096192763888",
|
||||
"🚫": "5938215362473496448",
|
||||
"👏": "5994417835630137549",
|
||||
"🍔": "6041874690220233085",
|
||||
"🎂": "5922305158636639117",
|
||||
"🛁": "6041963669057703997",
|
||||
"🏳️": "6041923781696426657",
|
||||
"🪧": "6042098561095570207",
|
||||
"⛱️": "6041933986538721961",
|
||||
"🗺": "5904650558127478452",
|
||||
"🏠": "6042137469204303531",
|
||||
"🏡": "5938537205847822613",
|
||||
"💼": "5938492039971737551",
|
||||
"🎓": "5938195768832692153",
|
||||
"👓": "5882223295469722324",
|
||||
"🔫": "5767356727305441799",
|
||||
"🎮": "5938413566624272793",
|
||||
"⚽️": "6042069608721027027",
|
||||
"⚪️": "5884332803016891855",
|
||||
"⬜️": "5884089033558070257",
|
||||
"☁️": "5884330496619450755",
|
||||
"📸": "5881806211195605908",
|
||||
"⚡": "5884428842780594914",
|
||||
"⚡️": "5920515922505765329",
|
||||
"🔄": "5769248574499983619",
|
||||
"#️⃣": "5924498929147189381",
|
||||
"☀️": "5938525265838739643",
|
||||
"🌝": "5938342819922973434",
|
||||
"🪟": "6035353688619356485",
|
||||
"📌": "6043896193887506430",
|
||||
"⭕️": "5776428312414917091",
|
||||
"✨": "5778226250149532337",
|
||||
"📦": "5778672437122045013",
|
||||
"🌙": "5769143090103193926",
|
||||
"♾": "6048407885233263063",
|
||||
"🛜": "6048723247501938454",
|
||||
"💊": "6050677620830376838",
|
||||
"💧": "6050632433479455053",
|
||||
"🖍": "5771798621137670637",
|
||||
"🖌": "6050679691004612757",
|
||||
"🧽": "5811966564039135541",
|
||||
"🫥": "5812150667812280629",
|
||||
"🪄": "6021792097454002931",
|
||||
"👩🎨": "5769635757211784031",
|
||||
"🔃": "5767310088255576068",
|
||||
"🔡": "5771851822897566479",
|
||||
"🅰": "6030710030108463274",
|
||||
"✂️": "5771880672192893347",
|
||||
"📈": "5938539885907415367",
|
||||
"📊": "5936143551854285132",
|
||||
"🌐": "5776233299424843260",
|
||||
"🏧": "5879814368572478751",
|
||||
"💰": "5778421276024509124",
|
||||
"🪙": "5778613750688911681",
|
||||
"💎": "5776023601941582822",
|
||||
"🤑": "5902206159095339799",
|
||||
"🏪": "5920332557466997677",
|
||||
"📟": "5776118099812028333",
|
||||
"🌀": "6050588788021793070",
|
||||
"🔳": "5771652845652677093",
|
||||
"📅": "5890937706803894250",
|
||||
"⌛️": "5891211339170326418",
|
||||
"👛": "5769126056262898415",
|
||||
"⏲": "6030537810509828330",
|
||||
"🕶": "5962882510705660145",
|
||||
"🧠": "5864019342873598613",
|
||||
"🧭": "6030687898141987254",
|
||||
"🆕": "5895669571058142797",
|
||||
"🪐": "5891156376473836675",
|
||||
"1⃣": "5794164805065514131",
|
||||
"2⃣": "5794085322400733645",
|
||||
"3⃣": "5794280000383358988",
|
||||
"4⃣": "5794241397217304511",
|
||||
"5⃣": "5793985348446984682",
|
||||
"6⃣": "5794324702402976226",
|
||||
"7⃣": "5793942849745591465",
|
||||
"8⃣": "5793926687783655907",
|
||||
"9⃣": "5793979472931723221",
|
||||
"👑": "5805553606635559688",
|
||||
"🌟": "5805331990618053402",
|
||||
"🧩": "5837069325034331827",
|
||||
"📱": "6021839011381778328",
|
||||
"⌚️": "6026262844876526729",
|
||||
"💻": "6021472143865289128",
|
||||
"🥽": "6023601507046267425",
|
||||
"⚠️": "6032636958595880929",
|
||||
"🖱": "6019471960415672536",
|
||||
"🕹": "6019166128679425474",
|
||||
"🎧": "6019261863500454521",
|
||||
"📻": "6019151667524539757",
|
||||
"🧑": "6021344660646009373",
|
||||
"☝️": "6019161984035986674",
|
||||
"🔐": "6019568309417023812",
|
||||
"🔑": "6019290828759898301",
|
||||
"🔌": "6023820193896077912",
|
||||
"🪫": "6023714391671708259",
|
||||
"🔋": "6019603137306827592",
|
||||
"👻": "6019605624092891862",
|
||||
"📡": "6019336759140165949",
|
||||
"⛓️": "6021452855167164269",
|
||||
"⛓️💥": "6019455841403411231",
|
||||
"📩": "6019263620142078168",
|
||||
"📹": "6019542324864882867",
|
||||
"🆘": "6021798595739523148",
|
||||
"🪪": "6021367625836140615",
|
||||
"🔉": "6021712185292495630",
|
||||
"🏁": "6021591694279973430",
|
||||
"💾": "6021741567163767583",
|
||||
"📨": "6021777395780950709",
|
||||
"🗃": "6021524310538065865",
|
||||
"ℹ️": "6021620268697393273",
|
||||
"📑": "6021745995275048956",
|
||||
"📃": "6021547434641987535",
|
||||
"📋": "6021435576513730578",
|
||||
"📜": "6023985764885338464",
|
||||
"🛠": "6021401276904905698",
|
||||
"🪛": "6023804147898260512",
|
||||
"🗝": "6030597532030081221",
|
||||
"📏": "6021717197519329757",
|
||||
"💿": "6024086962904766974",
|
||||
"☂️": "6021700962542950030",
|
||||
"🌂": "6021600232674957741",
|
||||
"🧯": "6021710192427669344",
|
||||
"🔭": "6021517653338758334",
|
||||
"👒": "6023979485643153732",
|
||||
"🪖": "6026341352583731546",
|
||||
"👟": "6023877759342746998",
|
||||
"🧢": "6023803044091665206",
|
||||
"👜": "6030355815565629428",
|
||||
"🎒": "6021621630202027944",
|
||||
"👕": "6026164962571852521",
|
||||
"🧥": "6025881627874301385",
|
||||
"👔": "6026108771514717874",
|
||||
"🧸": "6023725614421253091",
|
||||
"🪮": "6021525946920605883",
|
||||
"🎸": "6024044902290037236",
|
||||
"🏆": "6021644067111180663",
|
||||
"🎹": "6023572795189893997",
|
||||
"🎲": "6021391505854306270",
|
||||
"🎟": "6021617983774791539",
|
||||
"🏸": "6021337110093503238",
|
||||
"⛷": "6023589781785550249",
|
||||
"🏂": "6021779491724990056",
|
||||
"🏄♀️": "6021667440323204753",
|
||||
"🛹": "6021401049271640030",
|
||||
"⚾️": "6021757930989164684",
|
||||
"🏀": "6021765958283040902",
|
||||
"🏐": "6021616184183494682",
|
||||
"🏈": "6023908309445121643",
|
||||
"🏋️♀️": "6030747692676684614",
|
||||
"🧍": "6023669354644649609",
|
||||
"🧍♀️": "6021829047057652150",
|
||||
"🧍♂️": "6021423280022361212",
|
||||
"👬": "6030385004163374105",
|
||||
"🧑🧑🧒": "6030522189713775231",
|
||||
"🧑🧒": "6030603282991290307",
|
||||
"👶": "6032895232159257958",
|
||||
"♿️": "6024071041461000329",
|
||||
"👩🦽": "6021396500901271559",
|
||||
"🚴♂️": "6030562266053613403",
|
||||
"🙋♀️": "6021393275380832234",
|
||||
"🚶♀️": "6021522330558142880",
|
||||
"🏃♀️": "6023934809393338431",
|
||||
"🧘♀️": "6030526497565974276",
|
||||
"🤸♂️": "6030371779959068597",
|
||||
"💃": "6030644566216940396",
|
||||
"🤸♀️": "6030502110741667106",
|
||||
"🩰": "6030842401000527867",
|
||||
"⛸": "6030784543496083388",
|
||||
"🕺": "6030432296048269602",
|
||||
"🏓": "6030817357046225176",
|
||||
"🎾": "6030703634902161922",
|
||||
"🥏": "6030542079707322185",
|
||||
"🏹": "6030845248563844581",
|
||||
"🥊": "6030388830979233667",
|
||||
"🏑": "6030644531857201063",
|
||||
"🏒": "6030770932744724657",
|
||||
"🥌": "6030694782974564876",
|
||||
"🧗♀️": "6030671912273713900",
|
||||
"🧗♂️": "6030462837560711027",
|
||||
"🚴♀️": "6030579282714041411",
|
||||
"🐟": "6030796543634708454",
|
||||
"🏊♂️": "6030736195049231815",
|
||||
"👇": "6023566962624306038",
|
||||
"👈": "6021510515103111203",
|
||||
"👉": "6021623107670776267",
|
||||
"🤏": "6023776913510636026",
|
||||
"🤚": "6021665327199295814",
|
||||
"👀": "6021517988346206310",
|
||||
"👃": "6021466951249828045",
|
||||
"👄": "6023717831940511994",
|
||||
"🥸": "6021471302051698463",
|
||||
"👂": "6023885885420871319",
|
||||
"🫁": "6023745835127282619",
|
||||
"🩷": "6023852792697854544",
|
||||
"🫀": "6021556170605467328",
|
||||
"🫧": "6023581015757297605",
|
||||
"🦠": "6021348985678075808",
|
||||
"🚑": "6024074004988435387",
|
||||
"🩹": "6021401418638825347",
|
||||
"🌬": "6023823969172332666",
|
||||
"😷": "6021460598993197745",
|
||||
"💉": "6021835657012320577",
|
||||
"🩺": "6023704302793528745",
|
||||
"🧪": "6021696766359902854",
|
||||
"🐈": "6024034628728264585",
|
||||
"🐕": "6023772227701315562",
|
||||
"🐾": "6021787076637235622",
|
||||
"🐇": "6024048192234985393",
|
||||
"🐢": "6024014352187661296",
|
||||
"🐦⬛️": "6021780612711454761",
|
||||
"🐞": "6021595332117272254",
|
||||
"🐜": "6021417310017821454",
|
||||
"🦎": "6021803960153676091",
|
||||
"🐚": "6023921434865178936",
|
||||
"🥕": "6024046929514600832",
|
||||
"🌳": "6021522931853564301",
|
||||
"🌱": "6021851325053015552",
|
||||
"🌷": "6021452545929518743",
|
||||
"🍃": "6021522072860105215",
|
||||
"♻️": "6021772508108167860",
|
||||
"🪨": "6021345012833326278",
|
||||
"🌎": "6021458653373013164",
|
||||
"☢️": "6023564935399741395",
|
||||
"🌈": "6023962610716645351",
|
||||
"🌫️": "6030444377791272815",
|
||||
"🌧": "6021711515277599911",
|
||||
"🌩": "6023920889404332279",
|
||||
"🌨": "6024124629767953975",
|
||||
"⛅️": "6023775272833128433",
|
||||
"🌦": "6021372599408270968",
|
||||
"🌡": "6023936084998624686",
|
||||
"❄️": "6023884760139439190",
|
||||
"🔥": "6021384767050618542",
|
||||
"🌊": "6021789086681930128",
|
||||
"🌪": "6021597741593925661",
|
||||
"💨": "6023619893801261729",
|
||||
"🏢": "6026377494733528465",
|
||||
"🛋": "6024118728482888047",
|
||||
"🛏": "6023652943574604375",
|
||||
"🗄": "6021745419749431396",
|
||||
"🪑": "6023915963076843700",
|
||||
"🚽": "6021752626704553775",
|
||||
"🚿": "6023956649302038305",
|
||||
"🚰": "6021469030013999565",
|
||||
"♨️": "6023985343978543841",
|
||||
"🍽": "6024035015275322530",
|
||||
"🚨": "6023782836270536399",
|
||||
"🎈": "6023848484845656936",
|
||||
"🎇": "6024106766998968511",
|
||||
"💥": "6024010375047944401",
|
||||
"🍳": "6023971415399601811",
|
||||
"☕️": "6026256776087738391",
|
||||
"🥛": "6023622028400009740",
|
||||
"🍷": "6025935869016283321",
|
||||
"🥄": "6023643833948968918",
|
||||
"🍴": "6023885924075576491",
|
||||
"🥤": "6021326003308074821",
|
||||
"🍿": "6021326050552715519",
|
||||
"⛺️": "6023704736585227810",
|
||||
"🚗": "6026034764933241171",
|
||||
"🚛": "6023694913995020551",
|
||||
"🚌": "6023754699939781369",
|
||||
"🚊": "6026273006769149547",
|
||||
"🚇": "6024030612933844303",
|
||||
"🚢": "6026253589222004503",
|
||||
"⛵️": "6023568418618218922",
|
||||
"🛫": "6026282172229359229",
|
||||
"🎫": "6026064314308236812",
|
||||
"🏍": "6023750933253462508",
|
||||
"🛵": "6025834443363587986",
|
||||
"🚲": "6023805822935504200",
|
||||
"🛴": "6023762323506730705",
|
||||
"⛽️": "6023687646910356322",
|
||||
"📯": "6026091449911613733",
|
||||
"🅿️": "6025845867976597604",
|
||||
"🪢": "6026008475438422714",
|
||||
"✨️": "6026090681112467208",
|
||||
"🖋": "6025959826343861881",
|
||||
"🪣": "6026137564975471762",
|
||||
"🎨": "6021435456254646075",
|
||||
"↕️": "6026324700995525399",
|
||||
"⤵️": "6026095302497279226",
|
||||
"📐": "6025973462865024477",
|
||||
"☯": "6025891721047447607",
|
||||
"🎚": "6026270240810211206",
|
||||
"🔠": "6026269596565117758",
|
||||
"🔢": "6026201306585110323",
|
||||
"🅱": "6025906315346320098",
|
||||
"🛑": "6028583295447472629",
|
||||
"🔸": "6028549648673675429",
|
||||
"🔺": "6028560600840280115",
|
||||
"🛒": "6030664675253820292",
|
||||
"🛍": "6030573613357209704",
|
||||
"💵": "6030352469786105758",
|
||||
"💳": "6030602393933060595",
|
||||
"✍": "6030433657552903637",
|
||||
"0️⃣": "6033119468106816326",
|
||||
"3️⃣": "6035205087045884098",
|
||||
"4️⃣": "6033086216470010273",
|
||||
"⏱": "6034973034257848185",
|
||||
"6️⃣": "6035270203045057886",
|
||||
"7️⃣": "6032821320067062559",
|
||||
"8️⃣": "6034994461849691426",
|
||||
"9️⃣": "6035360556272064664",
|
||||
"🔟": "6035261763434322126",
|
||||
"↘️": "5807535965970898326",
|
||||
"↙️": "5807830592137467875",
|
||||
"↖️": "5805642976315054775",
|
||||
"⏪": "5805587360783539509",
|
||||
"⏏️": "5805296827720800660",
|
||||
"⏩": "5807527002374151568",
|
||||
"➗": "5807945628541525223",
|
||||
"🟰": "5807539539383688298",
|
||||
"↗️": "5807926412857841573",
|
||||
"🔀": "5807880911974308745",
|
||||
"⏹": "5807622114424924272",
|
||||
"⏸": "5807945302124012062",
|
||||
"⏺": "5807844031090137566",
|
||||
"🔂": "5807810169567976104",
|
||||
"➖": "5807405618008433289",
|
||||
"✖️": "5807692706507399432",
|
||||
"🔘": "5944754888268323234",
|
||||
"🌼": "5945137514019824091",
|
||||
"🩸": "5945191033607297698",
|
||||
"🧲": "5852684851165011254",
|
||||
"🍕": "5855226776019540768",
|
||||
"🎙️": "5854991218538191981",
|
||||
"🎬": "5886579539064132088",
|
||||
"💖": "6023852792697854544",
|
||||
"🛡️": "6030537007350944596"
|
||||
}
|
||||
@@ -0,0 +1,13 @@
|
||||
#!/usr/bin/env python3
|
||||
"""Compatibility launcher for the canonical bot module.
|
||||
|
||||
Deployed systemd units and helper imports use the historical name
|
||||
``iishko_bot.py``; the real implementation lives in ``grok_bot.py``.
|
||||
This file only forwards execution so both module names stay importable.
|
||||
"""
|
||||
import runpy
|
||||
import sys
|
||||
|
||||
if __name__ == "__main__":
|
||||
sys.argv[0] = "grok_bot.py"
|
||||
runpy.run_module("grok_bot", run_name="__main__")
|
||||
@@ -0,0 +1,110 @@
|
||||
"""Issuance throttles, not account bans. Client installation IDs are resettable signals.
|
||||
|
||||
Device claims are resettable too: they cap issuance velocity per installation, never prove
|
||||
a person and never stand in for hardware attestation.
|
||||
"""
|
||||
from contextlib import closing
|
||||
import hashlib
|
||||
import hmac
|
||||
import ipaddress
|
||||
import re
|
||||
import sqlite3
|
||||
import time
|
||||
|
||||
# Shared networks are allowed; an IP is never treated as a unique person. Only the
|
||||
# account and the client installation ID throttle issuance — NAT is never a reason to reject.
|
||||
LIMITS = (('uid', 8, 600), ('device', 12, 600))
|
||||
DEVICE_UID_LIMIT = 3
|
||||
DEVICE_UID_WINDOW = 14 * 86400
|
||||
|
||||
|
||||
def client_ip(remote, headers):
|
||||
try:
|
||||
peer = ipaddress.ip_address(remote or '')
|
||||
except ValueError:
|
||||
return 'unknown'
|
||||
# Caddy overwrites X-Real-IP. Public peers must never supply a trusted value.
|
||||
if peer.is_loopback:
|
||||
try:
|
||||
return str(ipaddress.ip_address(headers.get('X-Real-IP', '')))
|
||||
except ValueError:
|
||||
pass
|
||||
return str(peer)
|
||||
|
||||
|
||||
def opaque(secret, purpose, value):
|
||||
return hmac.new(secret.encode(), (purpose + ':' + str(value)).encode(), hashlib.sha256).hexdigest()
|
||||
|
||||
|
||||
def context(secret, uid, device, remote, headers):
|
||||
if not isinstance(device, str) or not re.fullmatch(r'[a-f0-9]{32}', device):
|
||||
return None
|
||||
return {'uid': opaque(secret, 'key-uid', uid),
|
||||
'device': opaque(secret, 'key-device', device),
|
||||
'ip': opaque(secret, 'key-ip', client_ip(remote, headers))}
|
||||
|
||||
|
||||
def attempt(db_path, signals, now=None):
|
||||
"""Atomically allow/count an attempt, returning seconds until a rejected attempt may retry."""
|
||||
now = int(time.time() if now is None else now)
|
||||
with closing(sqlite3.connect(db_path, timeout=15)) as con:
|
||||
con.execute('PRAGMA busy_timeout=15000')
|
||||
con.execute('CREATE TABLE IF NOT EXISTS wa_issue_attempts(kind TEXT NOT NULL, signal TEXT NOT NULL, ts INTEGER NOT NULL)')
|
||||
con.execute('CREATE INDEX IF NOT EXISTS wa_issue_attempts_lookup ON wa_issue_attempts(kind,signal,ts)')
|
||||
con.execute('BEGIN IMMEDIATE')
|
||||
try:
|
||||
con.execute('DELETE FROM wa_issue_attempts WHERE ts<=?', (now-86400,))
|
||||
retry = 0
|
||||
for kind, limit, window in LIMITS:
|
||||
count, oldest = con.execute('SELECT COUNT(*),MIN(ts) FROM wa_issue_attempts WHERE kind=? AND signal=? AND ts>?', (kind, signals[kind], now-window)).fetchone()
|
||||
if count >= limit:
|
||||
retry = max(retry, int(oldest) + window - now + 1)
|
||||
if not retry:
|
||||
con.executemany('INSERT INTO wa_issue_attempts VALUES (?,?,?)', [(kind, signals[kind], now) for kind, _, _ in LIMITS])
|
||||
con.commit()
|
||||
return retry
|
||||
except BaseException:
|
||||
con.rollback()
|
||||
raise
|
||||
|
||||
|
||||
def bind_beneficiary(con, uid, device_hash, now):
|
||||
"""Called inside the daemon issuance transaction, before a first welcome allocation."""
|
||||
if not isinstance(device_hash, str) or not re.fullmatch(r'[a-f0-9]{64}', device_hash):
|
||||
raise ValueError('Для выдачи ключа открой Mini App заново и разреши хранение данных')
|
||||
con.execute('CREATE TABLE IF NOT EXISTS bot.wa_issue_beneficiaries(device TEXT PRIMARY KEY, uid INTEGER NOT NULL, created INTEGER NOT NULL)')
|
||||
row = con.execute('SELECT uid FROM bot.wa_issue_beneficiaries WHERE device=?', (device_hash,)).fetchone()
|
||||
if row and row[0] != uid:
|
||||
raise ValueError('На этой установке Mini App стартовый ключ уже получал другой аккаунт. Поддержка: @your-handle')
|
||||
con.execute('INSERT OR IGNORE INTO bot.wa_issue_beneficiaries VALUES (?,?,?)', (device_hash, uid, now))
|
||||
|
||||
|
||||
def ensure_device_table(con):
|
||||
con.execute('CREATE TABLE IF NOT EXISTS bot.wa_key_dev(name TEXT PRIMARY KEY, uid INTEGER, '
|
||||
'device TEXT, created INTEGER)')
|
||||
con.execute('CREATE INDEX IF NOT EXISTS bot.wa_key_dev_device ON wa_key_dev(device,created)')
|
||||
|
||||
|
||||
def _device_hash(device_hash):
|
||||
if not isinstance(device_hash, str) or not re.fullmatch(r'[a-f0-9]{64}', device_hash):
|
||||
raise ValueError('Для выдачи ключа открой Mini App заново и разреши хранение данных')
|
||||
return device_hash
|
||||
|
||||
|
||||
def check_device(con, uid, device_hash, now):
|
||||
device_hash = _device_hash(device_hash)
|
||||
ensure_device_table(con)
|
||||
others = con.execute('SELECT COUNT(DISTINCT uid) FROM bot.wa_key_dev '
|
||||
'WHERE device=? AND uid<>? AND created>=?',
|
||||
(device_hash, uid, int(now) - DEVICE_UID_WINDOW)).fetchone()[0]
|
||||
if others >= DEVICE_UID_LIMIT:
|
||||
raise ValueError('С этой установки Mini App уже выдавались ключи другим аккаунтам. Поддержка: @your-handle')
|
||||
|
||||
|
||||
def record_device(con, uid, device_hash, name, now):
|
||||
device_hash = _device_hash(device_hash)
|
||||
if not isinstance(name, str) or not name:
|
||||
raise ValueError('Не удалось подтвердить ключ операции')
|
||||
ensure_device_table(con)
|
||||
con.execute('INSERT OR REPLACE INTO bot.wa_key_dev(name,uid,device,created) VALUES (?,?,?,?)',
|
||||
(name, uid, device_hash, int(now)))
|
||||
@@ -0,0 +1,495 @@
|
||||
import argparse
|
||||
import asyncio
|
||||
from contextlib import closing
|
||||
import datetime
|
||||
import json
|
||||
import logging
|
||||
import math
|
||||
import os
|
||||
from pathlib import Path
|
||||
import secrets
|
||||
import sqlite3
|
||||
import time
|
||||
from urllib.parse import urlsplit, urlunsplit
|
||||
|
||||
|
||||
log = logging.getLogger("key-notifications")
|
||||
KINDS = ("policy", "elapsed")
|
||||
STATES = ("pending", "sending", "sent", "covered", "uncertain", "terminal", "suppressed")
|
||||
ENABLE_ENV = "IISHKO_KEY_NOTIFICATIONS_ENABLED"
|
||||
|
||||
|
||||
def ledger_path(bot_db):
|
||||
return os.environ.get("IISHKO_KEY_NOTIFICATIONS_DB") or str(Path(bot_db).with_name("key_notifications.sqlite3"))
|
||||
|
||||
|
||||
def enable_path(bot_db):
|
||||
return os.environ.get("IISHKO_KEY_NOTIFICATIONS_ENABLE_FILE") or str(Path(bot_db).with_name("key_notifications.enabled"))
|
||||
|
||||
|
||||
def delivery_enabled(bot_db):
|
||||
if ENABLE_ENV in os.environ:
|
||||
return os.environ[ENABLE_ENV] == "1"
|
||||
try:
|
||||
with open(enable_path(bot_db), encoding="ascii") as marker:
|
||||
content = marker.read(17)
|
||||
return len(content) <= 16 and content.strip() == "1"
|
||||
except (OSError, UnicodeError):
|
||||
return False
|
||||
|
||||
|
||||
def keys_url(url):
|
||||
parts = urlsplit(url)
|
||||
if parts.scheme != "https" or not parts.netloc:
|
||||
raise ValueError("invalid_webapp_url")
|
||||
return urlunsplit(parts._replace(fragment="keys"))
|
||||
|
||||
|
||||
def wait_duration(wait_seconds, lang="ru"):
|
||||
if wait_seconds % 3600 == 0:
|
||||
return "%d %s" % (wait_seconds // 3600, "h" if lang == "en" else "ч")
|
||||
return "%d %s" % (wait_seconds, "s" if lang == "en" else "с")
|
||||
|
||||
|
||||
def policy_summary(wait_seconds, lang="ru"):
|
||||
duration = wait_duration(wait_seconds, lang)
|
||||
if lang == "en":
|
||||
return ("Create your first API key after %s from registration. "
|
||||
"The timer is in Mini App → Keys. The key is not sent automatically." % duration)
|
||||
return ("Первый API-ключ можно создать через %s после регистрации. "
|
||||
"Таймер — в Mini App → «Ключи». Ключ не придёт автоматически: создай его там." % duration)
|
||||
|
||||
|
||||
def notification_text(claim, wait_seconds, now):
|
||||
en = claim["lang"] == "en"
|
||||
elapsed = now >= claim["deadline"]
|
||||
if claim["kind"] == "elapsed" or elapsed:
|
||||
heading = "Your first-key waiting period has elapsed" if en else "Период ожидания первого ключа истёк"
|
||||
timing = ("Your waiting period has already elapsed; no new waiting period starts with this notice." if en else
|
||||
"Твой период ожидания уже истёк; новое ожидание с этого сообщения не начинается.")
|
||||
else:
|
||||
heading = "First API key: waiting period" if en else "Первый API-ключ: период ожидания"
|
||||
deadline = datetime.datetime.fromtimestamp(claim["deadline"], datetime.timezone.utc).strftime("%d.%m.%Y %H:%M:%S UTC")
|
||||
timing = ("Your registration-based deadline is <b>%s</b>." if en else
|
||||
"Твой срок по дате регистрации закончится <b>%s</b>.") % deadline
|
||||
summary = policy_summary(wait_seconds, claim["lang"]) + "\n\n" if claim["kind"] == "policy" else ""
|
||||
ending = ("Open Mini App → Keys to check your account conditions and create a main key if you still need one. "
|
||||
"No key has been issued automatically. Elapsed waiting time does not guarantee model or provider availability." if en else
|
||||
"Открой Mini App → «Ключи», чтобы проверить условия аккаунта и создать основной ключ, если он ещё нужен. "
|
||||
"Ключ автоматически не выдан. Истечение срока не гарантирует доступность моделей или провайдеров.")
|
||||
return "<b>%s</b>\n\n%s%s\n\n%s" % (heading, summary, timing, ending), elapsed
|
||||
|
||||
|
||||
def _readonly(path):
|
||||
con = sqlite3.connect(Path(path).resolve().as_uri() + "?mode=ro", uri=True, timeout=2)
|
||||
con.row_factory = sqlite3.Row
|
||||
con.execute("PRAGMA query_only=ON")
|
||||
return con
|
||||
|
||||
|
||||
def _eligible(row, now):
|
||||
return (row is not None and type(row["tg_id"]) is int and row["tg_id"] > 0
|
||||
and type(row["created"]) in (int, float) and math.isfinite(row["created"])
|
||||
and 0 < row["created"] <= now and row["privacy_ok"] == 1 and not row["banned"])
|
||||
|
||||
|
||||
class LostClaim(RuntimeError):
|
||||
pass
|
||||
|
||||
|
||||
class DeliveryRejected(Exception):
|
||||
"""Telegram explicitly rejected the request; retry only an explicit flood delay."""
|
||||
def __init__(self, code, *, retry_after=None):
|
||||
super().__init__(code)
|
||||
self.code, self.retry_after = code, retry_after
|
||||
|
||||
|
||||
class DeliveryUncertain(Exception):
|
||||
pass
|
||||
|
||||
|
||||
class KeyNotificationStore:
|
||||
def __init__(self, bot_db, path=None, *, wait_seconds, clock=time.time, max_attempts=5,
|
||||
lease_seconds=90, pace_seconds=0.2):
|
||||
if type(wait_seconds) is not int or wait_seconds < 0:
|
||||
raise ValueError("invalid_wait_seconds")
|
||||
self.bot_db, self.path = str(bot_db), str(path or ledger_path(bot_db))
|
||||
if Path(self.path).resolve() == Path(self.bot_db).resolve():
|
||||
raise ValueError("notification_ledger_must_be_separate")
|
||||
self.wait_seconds, self.clock = wait_seconds, clock
|
||||
self.max_attempts, self.lease_seconds, self.pace_seconds = max_attempts, lease_seconds, pace_seconds
|
||||
|
||||
def connect(self):
|
||||
con = sqlite3.connect(self.path, timeout=2)
|
||||
con.row_factory = sqlite3.Row
|
||||
con.execute("PRAGMA synchronous=FULL")
|
||||
return con
|
||||
|
||||
def init_db(self):
|
||||
with closing(self.connect()) as con:
|
||||
con.execute("PRAGMA journal_mode=WAL")
|
||||
con.executescript("""
|
||||
CREATE TABLE IF NOT EXISTS key_notifications (
|
||||
uid INTEGER NOT NULL, kind TEXT NOT NULL CHECK(kind IN ('policy','elapsed')),
|
||||
registered_at REAL NOT NULL, deadline REAL NOT NULL,
|
||||
state TEXT NOT NULL DEFAULT 'pending'
|
||||
CHECK(state IN ('pending','sending','sent','covered','uncertain','terminal','suppressed')),
|
||||
attempts INTEGER NOT NULL DEFAULT 0, next_attempt REAL NOT NULL DEFAULT 0,
|
||||
claim_token TEXT, lease_until REAL NOT NULL DEFAULT 0,
|
||||
sent_at REAL, error_code TEXT, PRIMARY KEY(uid,kind)
|
||||
);
|
||||
CREATE INDEX IF NOT EXISTS key_notifications_due
|
||||
ON key_notifications(state,next_attempt,deadline);
|
||||
CREATE TABLE IF NOT EXISTS key_notification_meta (name TEXT PRIMARY KEY, value REAL NOT NULL);
|
||||
""")
|
||||
con.commit()
|
||||
|
||||
@staticmethod
|
||||
def _meta(con, name):
|
||||
row = con.execute("SELECT value FROM key_notification_meta WHERE name=?", (name,)).fetchone()
|
||||
return row[0] if row else 0
|
||||
|
||||
@staticmethod
|
||||
def _set_meta(con, name, value):
|
||||
con.execute("INSERT INTO key_notification_meta(name,value) VALUES(?,?) "
|
||||
"ON CONFLICT(name) DO UPDATE SET value=excluded.value", (name, value))
|
||||
|
||||
def discover(self, limit=250):
|
||||
"""A wrapping keyset scan includes old users and newly consented registrations."""
|
||||
limit, now = max(1, min(int(limit), 1000)), self.clock()
|
||||
with closing(self.connect()) as con, closing(_readonly(self.bot_db)) as source:
|
||||
con.execute("BEGIN IMMEDIATE")
|
||||
cursor = int(self._meta(con, "scan_cursor"))
|
||||
query = "SELECT tg_id,created,privacy_ok,banned,lang FROM users WHERE tg_id>? ORDER BY tg_id LIMIT ?"
|
||||
rows = source.execute(query, (cursor, limit)).fetchall()
|
||||
wrapped = len(rows) < limit
|
||||
if not rows and cursor:
|
||||
rows = source.execute(query, (0, limit)).fetchall()
|
||||
wrapped = True
|
||||
accepted = 0
|
||||
for row in rows:
|
||||
if not _eligible(row, now):
|
||||
continue
|
||||
accepted += 1
|
||||
for kind in KINDS:
|
||||
con.execute("INSERT OR IGNORE INTO key_notifications(uid,kind,registered_at,deadline) VALUES(?,?,?,?)",
|
||||
(row["tg_id"], kind, row["created"], row["created"] + self.wait_seconds))
|
||||
con.execute("UPDATE key_notifications SET registered_at=?,deadline=?,state='pending',error_code=NULL "
|
||||
"WHERE uid=? AND kind=? AND state IN ('pending','suppressed')",
|
||||
(row["created"], row["created"] + self.wait_seconds, row["tg_id"], kind))
|
||||
self._set_meta(con, "scan_cursor", rows[-1]["tg_id"] if rows and not wrapped else 0)
|
||||
con.commit()
|
||||
return {"scanned": len(rows), "eligible": accepted, "scan_pending": not wrapped}
|
||||
|
||||
def _live(self, source, uid, now):
|
||||
row = source.execute("SELECT tg_id,created,privacy_ok,banned,lang FROM users WHERE tg_id=?", (uid,)).fetchone()
|
||||
return dict(row) if _eligible(row, now) else None
|
||||
|
||||
@staticmethod
|
||||
def _suppress(con, uid):
|
||||
con.execute("UPDATE key_notifications SET state='suppressed',claim_token=NULL,lease_until=0,error_code='ineligible' "
|
||||
"WHERE uid=? AND state IN ('pending','sending')", (uid,))
|
||||
|
||||
def claim(self):
|
||||
now = self.clock()
|
||||
with closing(self.connect()) as con, closing(_readonly(self.bot_db)) as source:
|
||||
con.execute("BEGIN IMMEDIATE")
|
||||
# An expired claim is an unknown outcome, not permission to resend.
|
||||
con.execute("UPDATE key_notifications SET state='uncertain',error_code='expired_claim' "
|
||||
"WHERE state='sending' AND lease_until<=?", (now,))
|
||||
if max(self._meta(con, "pause_until"), self._meta(con, "send_after")) > now:
|
||||
con.commit()
|
||||
return None
|
||||
rows = con.execute("""SELECT n.* FROM key_notifications n WHERE n.state='pending'
|
||||
AND n.attempts<? AND n.next_attempt<=? AND (n.kind='policy' OR
|
||||
(n.deadline<=? AND EXISTS(SELECT 1 FROM key_notifications p
|
||||
WHERE p.uid=n.uid AND p.kind='policy' AND p.state='sent')))
|
||||
ORDER BY n.next_attempt,n.deadline,n.uid,n.kind LIMIT 100""",
|
||||
(self.max_attempts, now, now)).fetchall()
|
||||
for row in rows:
|
||||
live = self._live(source, row["uid"], now)
|
||||
if not live:
|
||||
self._suppress(con, row["uid"])
|
||||
continue
|
||||
deadline = live["created"] + self.wait_seconds
|
||||
con.execute("UPDATE key_notifications SET registered_at=?,deadline=? WHERE uid=? AND state='pending'",
|
||||
(live["created"], deadline, row["uid"]))
|
||||
if row["kind"] == "elapsed" and deadline > now:
|
||||
continue
|
||||
token = secrets.token_hex(16)
|
||||
con.execute("UPDATE key_notifications SET state='sending',attempts=attempts+1,claim_token=?,lease_until=? "
|
||||
"WHERE uid=? AND kind=? AND state='pending'",
|
||||
(token, now + self.lease_seconds, row["uid"], row["kind"]))
|
||||
self._set_meta(con, "send_after", now + self.pace_seconds)
|
||||
con.commit()
|
||||
return {**dict(row), "deadline": deadline, "lang": "en" if live["lang"] == "en" else "ru",
|
||||
"claim_token": token, "attempts": row["attempts"] + 1}
|
||||
con.commit()
|
||||
return None
|
||||
|
||||
def prepare(self, claim):
|
||||
"""Recheck consent/ban/deadline immediately before the one transport call."""
|
||||
now = self.clock()
|
||||
with closing(self.connect()) as con, closing(_readonly(self.bot_db)) as source:
|
||||
con.execute("BEGIN IMMEDIATE")
|
||||
row = con.execute("SELECT * FROM key_notifications WHERE uid=? AND kind=? AND state='sending' "
|
||||
"AND claim_token=? AND lease_until>?",
|
||||
(claim["uid"], claim["kind"], claim["claim_token"], now)).fetchone()
|
||||
if row is None:
|
||||
con.commit()
|
||||
return None
|
||||
live = self._live(source, claim["uid"], now)
|
||||
if not live:
|
||||
self._suppress(con, claim["uid"])
|
||||
con.commit()
|
||||
return None
|
||||
deadline = live["created"] + self.wait_seconds
|
||||
if claim["kind"] == "elapsed" and deadline > now:
|
||||
self._release(con, claim)
|
||||
con.commit()
|
||||
return None
|
||||
con.execute("UPDATE key_notifications SET registered_at=?,deadline=?,lease_until=? WHERE uid=? AND kind=?",
|
||||
(live["created"], deadline, now + self.lease_seconds, claim["uid"], claim["kind"]))
|
||||
con.commit()
|
||||
return {**claim, "deadline": deadline, "lang": "en" if live["lang"] == "en" else "ru"}
|
||||
|
||||
@staticmethod
|
||||
def _release(con, claim):
|
||||
con.execute("UPDATE key_notifications SET state='pending',attempts=MAX(0,attempts-1),claim_token=NULL,lease_until=0 "
|
||||
"WHERE uid=? AND kind=? AND state='sending' AND claim_token=?",
|
||||
(claim["uid"], claim["kind"], claim["claim_token"]))
|
||||
|
||||
def release_unsent(self, claim):
|
||||
with closing(self.connect()) as con:
|
||||
con.execute("BEGIN IMMEDIATE")
|
||||
self._release(con, claim)
|
||||
con.commit()
|
||||
|
||||
def finish(self, claim, state, *, covers_elapsed=False, error_code=None, retry_after=None):
|
||||
if state not in ("sent", "pending", "terminal", "uncertain"):
|
||||
raise ValueError("invalid_delivery_state")
|
||||
now = self.clock()
|
||||
if state == "pending":
|
||||
if retry_after is None or not math.isfinite(retry_after) or retry_after < 0:
|
||||
raise ValueError("retry_requires_known_rejection_delay")
|
||||
if claim["attempts"] >= self.max_attempts:
|
||||
state = "terminal"
|
||||
delay = max(1, retry_after) if retry_after is not None else 0
|
||||
with closing(self.connect()) as con:
|
||||
con.execute("BEGIN IMMEDIATE")
|
||||
changed = con.execute("UPDATE key_notifications SET state=?,next_attempt=?,lease_until=0,sent_at=?,error_code=? "
|
||||
"WHERE uid=? AND kind=? AND claim_token=? AND attempts=? AND state IN ('sending','uncertain')",
|
||||
(state, now + delay, now if state == "sent" else None, error_code,
|
||||
claim["uid"], claim["kind"], claim["claim_token"], claim["attempts"]))
|
||||
if changed.rowcount != 1:
|
||||
raise LostClaim("notification_claim_lost")
|
||||
if retry_after is not None:
|
||||
self._set_meta(con, "pause_until", max(self._meta(con, "pause_until"), now + delay))
|
||||
if state == "sent" and claim["kind"] == "policy" and covers_elapsed:
|
||||
con.execute("UPDATE key_notifications SET state='covered',sent_at=?,error_code=NULL "
|
||||
"WHERE uid=? AND kind='elapsed' AND state IN ('pending','suppressed')",
|
||||
(now, claim["uid"]))
|
||||
if state == "terminal" and (error_code == "unreachable" or claim["kind"] == "policy"):
|
||||
con.execute("UPDATE key_notifications SET state='terminal',error_code=? "
|
||||
"WHERE uid=? AND state IN ('pending','suppressed')", (error_code, claim["uid"]))
|
||||
con.commit()
|
||||
|
||||
def status(self):
|
||||
result = {"enabled": delivery_enabled(self.bot_db), "counts": {kind: {state: 0 for state in STATES} for kind in KINDS},
|
||||
"pause_until": 0, "send_after": 0}
|
||||
if not Path(self.path).exists():
|
||||
return result
|
||||
with closing(_readonly(self.path)) as con:
|
||||
for row in con.execute("SELECT kind,state,COUNT(*) AS n FROM key_notifications GROUP BY kind,state"):
|
||||
result["counts"][row["kind"]][row["state"]] = row["n"]
|
||||
result["pause_until"] = self._meta(con, "pause_until")
|
||||
result["send_after"] = self._meta(con, "send_after")
|
||||
return result
|
||||
|
||||
def dry_run(self):
|
||||
"""Read-only aggregate plan; never creates a ledger, changes claims or lists IDs."""
|
||||
now, cursor = self.clock(), 0
|
||||
plan = {key: 0 for key in ("eligible", "waiting", "elapsed", "policy_waiting_due", "policy_combined_due",
|
||||
"elapsed_due", "elapsed_scheduled", "held", "ineligible")}
|
||||
ledger = _readonly(self.path) if Path(self.path).exists() else None
|
||||
try:
|
||||
with closing(_readonly(self.bot_db)) as source:
|
||||
plan["ineligible"] = source.execute("SELECT COUNT(*) FROM users WHERE tg_id<=0").fetchone()[0]
|
||||
while True:
|
||||
rows = source.execute("SELECT tg_id,created,privacy_ok,banned,lang FROM users "
|
||||
"WHERE tg_id>? ORDER BY tg_id LIMIT 500", (cursor,)).fetchall()
|
||||
if not rows:
|
||||
break
|
||||
for row in rows:
|
||||
if not _eligible(row, now):
|
||||
plan["ineligible"] += 1
|
||||
continue
|
||||
plan["eligible"] += 1
|
||||
elapsed = row["created"] + self.wait_seconds <= now
|
||||
plan["elapsed" if elapsed else "waiting"] += 1
|
||||
states = {item["kind"]: dict(item) for item in ledger.execute(
|
||||
"SELECT kind,state,next_attempt FROM key_notifications WHERE uid=?", (row["tg_id"],))} if ledger else {}
|
||||
policy, notice = states.get("policy", {}), states.get("elapsed", {})
|
||||
if policy.get("state", "pending") in ("pending", "suppressed"):
|
||||
if policy.get("next_attempt", 0) <= now:
|
||||
plan["policy_combined_due" if elapsed else "policy_waiting_due"] += 1
|
||||
else:
|
||||
plan["held"] += 1
|
||||
elif policy["state"] == "sent" and notice.get("state", "pending") in ("pending", "suppressed"):
|
||||
plan["elapsed_due" if elapsed and notice.get("next_attempt", 0) <= now else "elapsed_scheduled"] += 1
|
||||
elif policy["state"] in ("sending", "uncertain", "terminal"):
|
||||
plan["held"] += 1
|
||||
cursor = rows[-1]["tg_id"]
|
||||
finally:
|
||||
if ledger:
|
||||
ledger.close()
|
||||
return {"now": now, "wait_seconds": self.wait_seconds, "plan": plan, "status": self.status()}
|
||||
|
||||
def cleanup_orphans(self, limit=250):
|
||||
"""Bounded reconciliation of an existing ledger; live leases defer deletion."""
|
||||
empty = {"scanned": 0, "removed": 0, "scan_pending": False}
|
||||
if not Path(self.path).is_file():
|
||||
return empty
|
||||
limit, now = max(1, min(int(limit), 500)), self.clock()
|
||||
# mode=rw cannot create a ledger if it disappears after the existence check.
|
||||
uri = Path(self.path).resolve().as_uri() + "?mode=rw"
|
||||
with closing(sqlite3.connect(uri, uri=True, timeout=2)) as con, closing(_readonly(self.bot_db)) as source:
|
||||
con.row_factory = sqlite3.Row
|
||||
tables = {row["name"] for row in con.execute("SELECT name FROM sqlite_master WHERE type='table'")}
|
||||
if not {"key_notifications", "key_notification_meta"}.issubset(tables):
|
||||
return empty
|
||||
con.execute("PRAGMA synchronous=FULL")
|
||||
con.execute("BEGIN IMMEDIATE")
|
||||
cursor = int(self._meta(con, "cleanup_cursor"))
|
||||
query = "SELECT DISTINCT uid FROM key_notifications WHERE uid>? ORDER BY uid LIMIT ?"
|
||||
rows = con.execute(query, (cursor, limit)).fetchall()
|
||||
wrapped = len(rows) < limit
|
||||
if not rows and cursor:
|
||||
rows = con.execute(query, (0, limit)).fetchall()
|
||||
wrapped = True
|
||||
removed = 0
|
||||
if rows:
|
||||
recipients = [row["uid"] for row in rows]
|
||||
slots = ",".join("?" for _ in recipients)
|
||||
existing = {row["tg_id"] for row in source.execute(
|
||||
"SELECT tg_id FROM users WHERE tg_id IN (" + slots + ")", recipients)}
|
||||
for uid in recipients:
|
||||
if uid in existing:
|
||||
continue
|
||||
deleted = con.execute(
|
||||
"DELETE FROM key_notifications WHERE uid=? AND NOT EXISTS("
|
||||
"SELECT 1 FROM key_notifications live WHERE live.uid=? "
|
||||
"AND live.state='sending' AND live.lease_until>?)", (uid, uid, now))
|
||||
removed += deleted.rowcount
|
||||
self._set_meta(con, "cleanup_cursor", rows[-1]["uid"] if rows and not wrapped else 0)
|
||||
con.commit()
|
||||
return {"scanned": len(rows), "removed": removed, "scan_pending": not wrapped}
|
||||
|
||||
|
||||
async def telegram_send(bot, claim, text, url):
|
||||
from aiogram.exceptions import (TelegramBadRequest, TelegramForbiddenError, TelegramNetworkError,
|
||||
TelegramRetryAfter, TelegramServerError)
|
||||
from aiogram.types import InlineKeyboardButton, InlineKeyboardMarkup, WebAppInfo
|
||||
label = "Keys in Mini App" if claim["lang"] == "en" else "Ключи в Mini App"
|
||||
keyboard = InlineKeyboardMarkup(inline_keyboard=[[
|
||||
InlineKeyboardButton(text=label, web_app=WebAppInfo(url=url))]])
|
||||
try:
|
||||
await bot.send_message(claim["uid"], text, parse_mode="HTML", reply_markup=keyboard, request_timeout=20)
|
||||
except TelegramRetryAfter as error:
|
||||
raise DeliveryRejected("rate_limited", retry_after=error.retry_after) from None
|
||||
except TelegramForbiddenError:
|
||||
raise DeliveryRejected("unreachable") from None
|
||||
except TelegramBadRequest as error:
|
||||
unreachable = any(part in str(error).lower() for part in
|
||||
("chat not found", "user is deactivated", "chat_id is empty", "chat_id is invalid"))
|
||||
raise DeliveryRejected("unreachable" if unreachable else "bad_request") from None
|
||||
except (TelegramNetworkError, TelegramServerError):
|
||||
raise DeliveryUncertain("telegram_transport") from None
|
||||
|
||||
|
||||
class KeyNotificationWorker:
|
||||
def __init__(self, store, sender, webapp_url, *, enabled=None, batch=25, scan_batch=250, interval=30,
|
||||
timeout=25, sleep=asyncio.sleep):
|
||||
self.store, self.sender, self.url = store, sender, keys_url(webapp_url)
|
||||
self.enabled = enabled or (lambda: delivery_enabled(store.bot_db))
|
||||
self.batch, self.scan_batch, self.interval = batch, scan_batch, interval
|
||||
self.timeout, self.sleep, self.initialized = timeout, sleep, False
|
||||
|
||||
async def run_once(self):
|
||||
counts = {"sent": 0, "uncertain": 0, "rejected": 0, "scan_pending": 0}
|
||||
cleanup = await asyncio.to_thread(self.store.cleanup_orphans, self.scan_batch)
|
||||
counts["orphan_removed"] = cleanup["removed"]
|
||||
counts["cleanup_pending"] = int(cleanup["scan_pending"])
|
||||
if not await asyncio.to_thread(self.enabled):
|
||||
return counts
|
||||
if not self.initialized:
|
||||
await asyncio.to_thread(self.store.init_db)
|
||||
self.initialized = True
|
||||
scan = await asyncio.to_thread(self.store.discover, self.scan_batch)
|
||||
counts["scan_pending"] = int(scan["scan_pending"])
|
||||
for _ in range(self.batch):
|
||||
if not await asyncio.to_thread(self.enabled):
|
||||
break
|
||||
claim = await asyncio.to_thread(self.store.claim)
|
||||
if claim is None:
|
||||
break
|
||||
claim = await asyncio.to_thread(self.store.prepare, claim)
|
||||
if claim is None:
|
||||
continue
|
||||
if not await asyncio.to_thread(self.enabled):
|
||||
await asyncio.to_thread(self.store.release_unsent, claim)
|
||||
break
|
||||
text, covers_elapsed = notification_text(claim, self.store.wait_seconds, self.store.clock())
|
||||
try:
|
||||
await asyncio.wait_for(self.sender(claim, text, self.url), timeout=self.timeout)
|
||||
except asyncio.CancelledError:
|
||||
try:
|
||||
await asyncio.shield(asyncio.to_thread(self.store.finish, claim, "uncertain", error_code="cancelled"))
|
||||
except (sqlite3.Error, OSError):
|
||||
log.error("key notification cancellation state unavailable; claim remains quarantinable")
|
||||
raise
|
||||
except DeliveryRejected as error:
|
||||
await asyncio.to_thread(self.store.finish, claim, "pending" if error.retry_after is not None else "terminal",
|
||||
error_code=error.code, retry_after=error.retry_after)
|
||||
counts["rejected"] += 1
|
||||
if error.retry_after is not None:
|
||||
break
|
||||
except (DeliveryUncertain, TimeoutError, OSError) as error:
|
||||
await asyncio.to_thread(self.store.finish, claim, "uncertain", error_code=type(error).__name__)
|
||||
counts["uncertain"] += 1
|
||||
except Exception:
|
||||
# Preserve the original programming failure; the attempted delivery must not be replayed.
|
||||
await asyncio.to_thread(self.store.finish, claim, "uncertain", error_code="unexpected_failure")
|
||||
raise
|
||||
else:
|
||||
await asyncio.to_thread(self.store.finish, claim, "sent", covers_elapsed=covers_elapsed)
|
||||
counts["sent"] += 1
|
||||
await self.sleep(self.store.pace_seconds)
|
||||
return counts
|
||||
|
||||
async def run(self):
|
||||
while True:
|
||||
try:
|
||||
counts = await self.run_once()
|
||||
except (sqlite3.Error, OSError) as error:
|
||||
counts = {"storage_error": 0}
|
||||
# Do not log exception text, recipient IDs, SQL values or token-bearing URLs.
|
||||
log.error("key notification worker storage failure: %s", type(error).__name__)
|
||||
await self.sleep(0 if sum(counts.values()) else self.interval)
|
||||
|
||||
|
||||
def main():
|
||||
parser = argparse.ArgumentParser(description="Read-only first-key notification aggregates; this CLI never sends.")
|
||||
parser.add_argument("action", choices=("dry-run", "status"))
|
||||
parser.add_argument("--bot-db", default=os.environ.get("GROK_BOT_DB", "/opt/grok-bot/bot.db"))
|
||||
parser.add_argument("--ledger")
|
||||
parser.add_argument("--config", default=os.environ.get("GROK_BOT_CFG", "/opt/grok-bot/config.json"))
|
||||
args = parser.parse_args()
|
||||
with open(args.config, encoding="utf-8") as config:
|
||||
wait_seconds = int(json.load(config).get("key_wait_hours", 24)) * 3600
|
||||
store = KeyNotificationStore(args.bot_db, args.ledger, wait_seconds=wait_seconds)
|
||||
print(json.dumps(store.dry_run() if args.action == "dry-run" else store.status(), ensure_ascii=False, sort_keys=True))
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
main()
|
||||
@@ -0,0 +1,178 @@
|
||||
import json
|
||||
import os
|
||||
import threading
|
||||
import time
|
||||
import urllib.error
|
||||
import urllib.request
|
||||
|
||||
BASE = "https://api.kie.ai"
|
||||
POOL = os.environ.get("KIE_POOL", "/opt/grok-bot/kie_keys.jsonl")
|
||||
DEAD = os.environ.get("KIE_DEAD", "/opt/grok-bot/kie_keys_dead.jsonl")
|
||||
UA = ("Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 "
|
||||
"(KHTML, like Gecko) Chrome/141.0.0.0 Safari/537.36")
|
||||
|
||||
IMG_MODEL = os.environ.get("KIE_IMG_MODEL", "qwen2/text-to-image") # ~0.03 кредита
|
||||
IMG_MODEL_HI = os.environ.get("KIE_IMG_MODEL_HI", "z-image") # ~0.8 кредита
|
||||
VID_MODEL = os.environ.get("KIE_VID_MODEL", "hailuo/02-text-to-video-standard")
|
||||
|
||||
_lock = threading.Lock()
|
||||
_keys = []
|
||||
_rr = [0]
|
||||
|
||||
|
||||
def _load():
|
||||
global _keys
|
||||
with _lock:
|
||||
if _keys:
|
||||
return _keys
|
||||
out, seen = [], set()
|
||||
try:
|
||||
with open(POOL, encoding="utf-8", errors="replace") as f:
|
||||
for line in f:
|
||||
line = line.strip()
|
||||
if not line:
|
||||
continue
|
||||
try:
|
||||
d = json.loads(line)
|
||||
k = (d.get("apiKey") or d.get("key") or d.get("api_key") or "").strip()
|
||||
except Exception:
|
||||
k = line
|
||||
if k and k not in seen:
|
||||
seen.add(k)
|
||||
out.append({"apiKey": k})
|
||||
except FileNotFoundError:
|
||||
pass
|
||||
_keys = out
|
||||
return _keys
|
||||
|
||||
|
||||
def reload_pool():
|
||||
global _keys
|
||||
with _lock:
|
||||
_keys = []
|
||||
return len(_load())
|
||||
|
||||
|
||||
def _kill(key):
|
||||
global _keys
|
||||
with _lock:
|
||||
try:
|
||||
with open(DEAD, "a", encoding="utf-8") as f:
|
||||
f.write(json.dumps({"apiKey": key, "ts": int(time.time())}) + "\n")
|
||||
except Exception:
|
||||
pass
|
||||
_keys = [x for x in _keys if x.get("apiKey") != key]
|
||||
|
||||
|
||||
def _next_key():
|
||||
ks = _load()
|
||||
if not ks:
|
||||
raise RuntimeError("kie pool empty")
|
||||
with _lock:
|
||||
_rr[0] = (_rr[0] + 1) % len(ks)
|
||||
i = _rr[0]
|
||||
return ks[i]["apiKey"]
|
||||
|
||||
|
||||
def _req(key, path, body=None, timeout=45):
|
||||
h = {"User-Agent": UA, "Content-Type": "application/json",
|
||||
"Authorization": "Bearer " + key}
|
||||
data = json.dumps(body).encode() if body is not None else None
|
||||
req = urllib.request.Request(BASE + path, data=data, headers=h)
|
||||
try:
|
||||
return json.loads(urllib.request.urlopen(req, timeout=timeout).read().decode())
|
||||
except urllib.error.HTTPError as e:
|
||||
try:
|
||||
return json.loads(e.read().decode())
|
||||
except Exception:
|
||||
return {"code": e.code, "msg": "http"}
|
||||
except Exception as e:
|
||||
return {"code": -1, "msg": str(e)[:120]}
|
||||
|
||||
|
||||
def _create(model, inp):
|
||||
last = ""
|
||||
for _ in range(8):
|
||||
key = _next_key()
|
||||
r = _req(key, "/api/v1/jobs/createTask", {"model": model, "input": inp})
|
||||
if r.get("code") == 200:
|
||||
d = r.get("data") or {}
|
||||
tid = d.get("taskId") or d.get("recordId")
|
||||
if tid:
|
||||
return tid, key
|
||||
msg = str(r.get("msg") or "")
|
||||
last = msg
|
||||
low = msg.lower()
|
||||
if r.get("code") == 402 or "credit" in low or "balance" in low or "квот" in low:
|
||||
_kill(key)
|
||||
continue
|
||||
time.sleep(2)
|
||||
raise RuntimeError("kie create: " + (last[:140] or "fail"))
|
||||
|
||||
|
||||
def _poll(tid, key, tmo=420):
|
||||
t0 = time.time()
|
||||
while time.time() - t0 < tmo:
|
||||
r = _req(key, "/api/v1/jobs/recordInfo?taskId=" + str(tid))
|
||||
d = r.get("data") or {}
|
||||
st = d.get("state")
|
||||
if st == "success":
|
||||
rj = d.get("resultJson") or "{}"
|
||||
if isinstance(rj, str):
|
||||
try:
|
||||
rj = json.loads(rj)
|
||||
except Exception:
|
||||
rj = {}
|
||||
urls = rj.get("resultUrls") or rj.get("result_urls") or rj.get("urls") or []
|
||||
return urls[0] if urls else None
|
||||
if st in ("fail", "failed"):
|
||||
raise RuntimeError("kie task fail: " + str(d.get("failMsg"))[:120])
|
||||
time.sleep(6)
|
||||
raise RuntimeError("kie poll timeout")
|
||||
|
||||
|
||||
def _dl(url):
|
||||
req = urllib.request.Request(url, headers={"User-Agent": UA})
|
||||
return urllib.request.urlopen(req, timeout=120).read()
|
||||
|
||||
|
||||
def kie_image_sync(prompt, aspect="1:1", hi=False):
|
||||
"""-> bytes (jpeg/png/webp как отдал апстрим)."""
|
||||
model = IMG_MODEL_HI if hi else IMG_MODEL
|
||||
tid, key = _create(model, {"prompt": (prompt or "")[:900], "aspect_ratio": aspect})
|
||||
url = _poll(tid, key, 300)
|
||||
if not url:
|
||||
raise RuntimeError("kie image: no url")
|
||||
return _dl(url)
|
||||
|
||||
|
||||
def kie_image_url(prompt, aspect="1:1", hi=False):
|
||||
model = IMG_MODEL_HI if hi else IMG_MODEL
|
||||
tid, key = _create(model, {"prompt": (prompt or "")[:900], "aspect_ratio": aspect})
|
||||
return _poll(tid, key, 300)
|
||||
|
||||
|
||||
def kie_video_url(prompt, aspect="16:9", seconds=6):
|
||||
"""hailuo/02 standard: ~5 кредитов/сек. Возвращает URL mp4."""
|
||||
sec = max(6, min(int(seconds or 6), 10))
|
||||
inp = {"prompt": (prompt or "")[:600], "duration": str(sec)}
|
||||
# часть моделей требует aspect_ratio/resolution — hailuo игнорирует лишнее, но не любит пустое
|
||||
inp["aspect_ratio"] = aspect
|
||||
tid, key = _create(VID_MODEL, inp)
|
||||
return _poll(tid, key, 600)
|
||||
|
||||
|
||||
def kie_video_sync(prompt, aspect="16:9", seconds=6, model=None):
|
||||
"""Совместимость с патчем бота: -> (url, taskId-хвост)."""
|
||||
u = kie_video_url(prompt, aspect, seconds)
|
||||
return u, ""
|
||||
|
||||
|
||||
def status():
|
||||
ks = _load()
|
||||
dead = 0
|
||||
try:
|
||||
dead = sum(1 for _ in open(DEAD, encoding="utf-8", errors="replace"))
|
||||
except Exception:
|
||||
pass
|
||||
return {"keys": len(ks), "dead": dead, "img": IMG_MODEL, "vid": VID_MODEL}
|
||||
@@ -0,0 +1,125 @@
|
||||
"""In-process UID throttles. Device IDs, forwarding headers and query strings are not identities."""
|
||||
from collections import OrderedDict
|
||||
import hashlib
|
||||
import hmac
|
||||
import math
|
||||
import time
|
||||
|
||||
from aiohttp import web
|
||||
|
||||
POLICIES = {"read": (180, 60), "write": (30, 60), "chat": (12, 60),
|
||||
"files": (3, 60), "support": (12, 60), "captcha": (6, 60),
|
||||
"control": (120, 60)}
|
||||
CONTROL = {"/api/agent_cancel", "/api/agent_history", "/api/agent_history/clear", "/api/reminders/cancel"}
|
||||
CHAT = {"/api/agent_chat", "/api/neurolab/talk"}
|
||||
|
||||
|
||||
def families(method, path):
|
||||
# aiohttp Request.path is decoded and excludes the query; also protect direct callers.
|
||||
path = path.split("?", 1)[0]
|
||||
if path in CONTROL:
|
||||
return ("control",)
|
||||
if method in ("GET", "HEAD"):
|
||||
return ("captcha",) if path == "/api/captcha" else ("read",)
|
||||
if path in CHAT:
|
||||
return ("chat",)
|
||||
if path == "/api/support":
|
||||
return ("write", "support")
|
||||
return ("write",)
|
||||
|
||||
|
||||
def rate_response(retry_after, *, operation_id=None):
|
||||
retry = max(1, min(86400, int(math.ceil(retry_after))))
|
||||
message = "Слишком много запросов. Подожди немного и повтори вручную."
|
||||
body = {"error": "miniapp_rate", "msg": message, "message": message,
|
||||
"retry_after": retry, "operation_rejected": True}
|
||||
# No state/uncertain claim: this request did not enter the handler, but an earlier
|
||||
# request with the same unknown operation ID might still be running/completed.
|
||||
if operation_id is not None:
|
||||
body["operation_id"] = operation_id
|
||||
return web.json_response(body, status=429, headers={"Retry-After": str(retry)})
|
||||
|
||||
|
||||
class MiniappGuard:
|
||||
def __init__(self, secret, *, policies=None, clock=time.monotonic,
|
||||
max_users=10000, max_peers=2048, idle_ttl=900, auth_limit=30):
|
||||
self.clock = clock
|
||||
self.policies = dict(POLICIES if policies is None else policies)
|
||||
if not self.policies or any(type(limit) is not int or limit <= 0 or
|
||||
not isinstance(window, (int, float)) or not math.isfinite(window) or window <= 0
|
||||
for limit, window in self.policies.values()):
|
||||
raise ValueError("miniapp_rate_policy_invalid")
|
||||
self.max_users, self.max_peers = max(1, max_users), max(1, max_peers)
|
||||
self.idle_ttl = max(idle_ttl, max(window for _, window in self.policies.values()), 60)
|
||||
self.auth_limit = max(1, auth_limit)
|
||||
self.users, self.peers = OrderedDict(), OrderedDict()
|
||||
self.secret = str(secret).encode("utf-8")
|
||||
self.global_auth = (float(self.auth_limit * 20), self.clock())
|
||||
|
||||
def _prune(self, records, now):
|
||||
while records:
|
||||
key, record = next(iter(records.items()))
|
||||
if now - record["last"] < self.idle_ttl:
|
||||
break
|
||||
records.pop(key)
|
||||
|
||||
@staticmethod
|
||||
def _available(bucket, limit, window, now):
|
||||
tokens, updated = bucket if bucket is not None else (float(limit), now)
|
||||
available = min(float(limit), tokens + max(0, now - updated) * limit / window)
|
||||
return available, max(0, int(math.ceil((1 - available) * window / limit)))
|
||||
|
||||
def take(self, uid, *requested):
|
||||
if type(uid) is not int or not 0 < uid <= 2**63 - 1:
|
||||
return 60
|
||||
now = self.clock()
|
||||
self._prune(self.users, now)
|
||||
record = self.users.get(uid)
|
||||
if record is None:
|
||||
if len(self.users) >= self.max_users:
|
||||
oldest = next(iter(self.users.values()))
|
||||
return max(1, int(math.ceil(oldest["last"] + self.idle_ttl - now)))
|
||||
record = {"last": now, "buckets": {}}
|
||||
self.users[uid] = record
|
||||
record["last"] = now
|
||||
self.users.move_to_end(uid)
|
||||
pending, retry = {}, 0
|
||||
for family in set(requested):
|
||||
limit, window = self.policies[family]
|
||||
available, wait = self._available(record["buckets"].get(family), limit, window, now)
|
||||
pending[family] = available
|
||||
retry = max(retry, wait)
|
||||
if not retry:
|
||||
for family, available in pending.items():
|
||||
record["buckets"][family] = (available - 1, now)
|
||||
return retry
|
||||
|
||||
def check(self, uid, method, path):
|
||||
return self.take(uid, *families(method, path))
|
||||
|
||||
def reject_auth(self, remote):
|
||||
"""Only invalid signatures spend this inexpensive bounded budget; valid users are not IP-throttled."""
|
||||
now = self.clock()
|
||||
self._prune(self.peers, now)
|
||||
remote = remote if isinstance(remote, str) and len(remote) <= 64 else "unknown"
|
||||
peer = hmac.new(self.secret, ("auth-peer:" + remote).encode("utf-8"), hashlib.sha256).hexdigest()
|
||||
record = self.peers.get(peer)
|
||||
if record is None:
|
||||
if len(self.peers) >= self.max_peers:
|
||||
oldest = next(iter(self.peers.values()))
|
||||
return max(1, int(math.ceil(oldest["last"] + self.idle_ttl - now)))
|
||||
record = {"last": now, "bucket": None}
|
||||
self.peers[peer] = record
|
||||
record["last"] = now
|
||||
self.peers.move_to_end(peer)
|
||||
tokens, wait = self._available(record["bucket"], self.auth_limit, 60, now)
|
||||
global_tokens, global_wait = self._available(self.global_auth, self.auth_limit * 20, 60, now)
|
||||
retry = max(wait, global_wait)
|
||||
if not retry:
|
||||
record["bucket"] = (tokens - 1, now)
|
||||
self.global_auth = (global_tokens - 1, now)
|
||||
return retry
|
||||
|
||||
@staticmethod
|
||||
def response(retry_after, *, operation_id=None):
|
||||
return rate_response(retry_after, operation_id=operation_id)
|
||||
@@ -0,0 +1,202 @@
|
||||
"""Единый каталог моделей ИИШКО для бота и Mini App.
|
||||
|
||||
Module is stdlib-only, has no I/O and no credentials: importing it never
|
||||
contacts the gateway, databases or providers, and carries no availability
|
||||
claims (availability is probed at runtime by the gateway).
|
||||
|
||||
Sources of truth:
|
||||
* ``TIER_MODELS`` — exact per-tier lists. Tier N opens models of tiers 1..N
|
||||
(the bot builds the cumulative union at runtime); a lower-tier name repeated
|
||||
inside a higher tier is intentional and must stay, because unlock weeks and
|
||||
the tool picker order depend on it.
|
||||
* ``MODEL_DESCS`` — display metadata for every catalogue id, every public
|
||||
spelling alias, and the media/routing identities that are not rank-gated.
|
||||
* ``ALIASES`` — alternate API spellings of catalogue ids (dots vs dashes).
|
||||
Metadata only: an alias never adds a model and never changes a rank.
|
||||
* ``ROUTING_ALIASES`` — legacy request names resolved by the bot gateway
|
||||
layer. Metadata only, never offered in menus.
|
||||
|
||||
``bot/grok_bot.py`` keeps a literal projection of ``TIER_MODELS`` and
|
||||
``MODEL_DESCS`` because ``commerce_access.py``/``abilities_guard.py`` read the
|
||||
trusted catalogue from source without importing the bot. Edit this module, then
|
||||
regenerate the projection; ``tests/test_model_catalogue.py`` fails on drift.
|
||||
"""
|
||||
|
||||
# Ranks: 1 Новичок, 2 Актив, 3 Профи, 4 Легенда.
|
||||
TIER_MODELS = {1: ['glm-5.3',
|
||||
'glm-5.3-prime',
|
||||
'qwen-plus',
|
||||
'qwen-max',
|
||||
'qwen3.8-flash',
|
||||
'qwen3.8-27b',
|
||||
'qwen3.8-max',
|
||||
'qwen3.8-max-0902',
|
||||
'deepseek-v4.1-flash-1017',
|
||||
'kimi-k3',
|
||||
'qwen3-vl-plus'],
|
||||
2: ['deepseek-v4-pro',
|
||||
'qwen3.7-max',
|
||||
'gpt-5.6-luna',
|
||||
'gpt-5.6-terra',
|
||||
'gpt-6-luna',
|
||||
'grok-4.6',
|
||||
'grok-4.7',
|
||||
'grok-composer-2.5-fast',
|
||||
'MiniMax-M2.7-highspeed',
|
||||
'gemini-auto',
|
||||
'LongCat-2.0',
|
||||
'cx/gpt-6-luna',
|
||||
'Atria-Dawn-Preview',
|
||||
'Qwen3.8-Flash-Next',
|
||||
'SenseNova-6.8-Flash-Lite',
|
||||
'claude-sonnet-4.5'],
|
||||
3: ['kimi/kimi-k3.1-pro',
|
||||
'kimi/kimi-k3.1-pro-highspeed',
|
||||
'gpt-5.6-sol',
|
||||
'gpt-6-astra',
|
||||
'kimi-k2.7-code',
|
||||
'MiniMax-M2.7-highspeed',
|
||||
'gemini-auto',
|
||||
'LongCat-2.0',
|
||||
'cx/gpt-6-luna',
|
||||
'Atria-Dawn-Preview',
|
||||
'Qwen3.8-Flash-Next',
|
||||
'SenseNova-6.8-Flash-Lite',
|
||||
'gpt-6-luna',
|
||||
'grok-4.6',
|
||||
'grok-4.7',
|
||||
'claude-sonnet-4.5'],
|
||||
4: ['claude-opus-5.5',
|
||||
'claude-opus-5',
|
||||
'claude-opus-4-5-token',
|
||||
'claude-fable-5.1',
|
||||
'gpt-5.5',
|
||||
'claude-opus-4-6',
|
||||
'MiniMax-M2.7-highspeed',
|
||||
'gemini-auto',
|
||||
'LongCat-2.0',
|
||||
'cx/gpt-6-luna',
|
||||
'Atria-Dawn-Preview',
|
||||
'Qwen3.8-Flash-Next',
|
||||
'SenseNova-6.8-Flash-Lite',
|
||||
'gpt-6-luna',
|
||||
'grok-4.6',
|
||||
'grok-4.7',
|
||||
'claude-sonnet-4.5']}
|
||||
TIER_TITLES = {1: ('🥉', 'Новичок'), 2: ('🥈', 'Актив'), 3: ('🥇', 'Профи'), 4: ('💎', 'Легенда')}
|
||||
TIER_UNLOCK = {1: 1, 2: 2, 3: 3, 4: 4}
|
||||
MODEL_DESCS = {'glm-5.3': 'GLM 5.3 · диалоги, редактура и задачи по коду',
|
||||
'qwen3.7-max': 'Qwen 3.7 Max · анализ задач, тексты и код',
|
||||
'glm-5.3-prime': 'GLM 5.3 Prime · разбор задач и составление инструкций',
|
||||
'deepseek-v4-pro': 'DeepSeek V4 Pro · разбор решений, анализ и код',
|
||||
'glm-5.3-flash': 'GLM 5.3 Flash · вопросы, диалоги и черновики',
|
||||
'qwen3.8-max-0902': 'Qwen 3.8 Max 0902 · разбор задач, тексты и код',
|
||||
'qwen3.8-27b': 'Qwen 3.8 27B · вопросы, планы и черновики',
|
||||
'qwen-plus': 'Qwen Plus · диалоги, тексты и объяснения',
|
||||
'qwen3.8-flash': 'Qwen 3.8 Flash · повседневные вопросы и редактура',
|
||||
'qwen-max': 'Qwen Max · анализ задач, тексты и код',
|
||||
'qwen3-vl-plus': 'Qwen VL Plus · вопросы, описания и объяснения',
|
||||
'deepseek-v4.1-flash-1017': 'DeepSeek V4.1 Flash 1017 · разбор кода и анализ задач',
|
||||
'deepseek-v4-flash': 'DeepSeek V4 Flash · вопросы, объяснения и код',
|
||||
'qwen3.8-max': 'Qwen 3.8 Max · анализ задач, тексты и код',
|
||||
'kimi-k3': 'Kimi K3 · работа с текстом, планы и код',
|
||||
'kimi/kimi-k3.1-pro': 'Kimi K3.1 Pro · анализ текста, планы и разбор кода',
|
||||
'kimi/kimi-k3.1-pro-highspeed': 'Kimi K3.1 Pro Highspeed · анализ текста, планы и разбор кода',
|
||||
'grok-4.6': 'Grok 4.6 · диалоги, идеи и задачи по коду',
|
||||
'grok-4.7': 'Grok 4.7 · обсуждение идей, тексты и код',
|
||||
'grok-composer-2.5-fast': 'Grok Composer 2.5 Fast · написание и редактирование текстов',
|
||||
'claude-opus-5-5': 'Claude Opus 5.5 · разбор задач, инструкции и код',
|
||||
'claude-opus-4-6': 'Claude Opus 4.6 · разбор задач, инструкции и код',
|
||||
'claude-fable-5-1': 'Claude Fable 5.1 · тексты, сценарии и редактура',
|
||||
'gpt-5.6-luna': 'GPT-5.6 Luna · диалоги, редактура и задачи по коду',
|
||||
'gpt-6-luna': 'GPT-6 Luna · диалоги, редактура и код',
|
||||
'gpt-5.6-terra': 'GPT-5.6 Terra · диалоги, объяснения и задачи по коду',
|
||||
'gpt-5.6-sol': 'GPT-5.6 Sol · анализ задач, тексты и код',
|
||||
'gpt-6.1-sol': 'GPT-6.1 Sol · разбор решений, тексты и код',
|
||||
'gpt-5.5': 'GPT-5.5 · диалоги, тексты и задачи по коду',
|
||||
'wanx2.1-t2i-turbo': 'Wanx 2.1 Turbo · изображения по текстовому описанию',
|
||||
'wan2.2-t2i-flash': 'Wan 2.2 Flash · изображения по текстовому описанию',
|
||||
'wan2.6-t2v': 'Wan 2.6 · видео по текстовому описанию',
|
||||
'grok-imagine-image': 'Grok Imagine · изображения по текстовому описанию',
|
||||
'grok-imagine-image-2.0': 'Grok Imagine 2.0 · изображения по текстовому описанию',
|
||||
'gpt-image-2.5': 'GPT Image 2.5 · изображения по текстовому описанию',
|
||||
'kimi-k2.7-code': 'Kimi K2.7 Code · генерация и правка кода',
|
||||
'MiniMax-M2.7-highspeed': 'MiniMax 2.7 Highspeed · быстрые диалоги и код',
|
||||
'gemini-auto': 'Gemini Auto · авто-выбор канала, диалоги и тексты',
|
||||
'LongCat-2.0': 'LongCat 2.0 · диалоги, пересказ и черновики',
|
||||
'cx/gpt-6-luna': 'GPT-6 Luna (канал cx) · тексты, разбор и код',
|
||||
'Atria-Dawn-Preview': 'Atria Dawn Preview · экспериментальные диалоги',
|
||||
'Qwen3.8-Flash-Next': 'Qwen 3.8 Flash Next · быстрые ответы и код',
|
||||
'SenseNova-6.8-Flash-Lite': 'SenseNova 6.8 Flash Lite · лёгкие быстрые ответы',
|
||||
'claude-sonnet-4.5': 'Claude Sonnet 4.5 · диалоги, тексты и код',
|
||||
'claude-opus-5': 'Claude Opus 5 · сложные задачи и код',
|
||||
'claude-opus-5.5': 'Claude Opus 5.5 · разбор задач, инструкции и код',
|
||||
'claude-opus-4-5-token': 'Claude Opus 4.5 (token-канал) · длинные задачи и код',
|
||||
'claude-fable-5.1': 'Claude Fable 5.1 · тексты, сценарии и редактура',
|
||||
'gpt-6-astra': 'GPT-6 Astra · сложные диалоги, разбор и код'}
|
||||
ALIASES = {'claude-opus-5-5': 'claude-opus-5.5', 'claude-fable-5-1': 'claude-fable-5.1'}
|
||||
ROUTING_ALIASES = {'deepseek-v4-flash': 'deepseek-v4.1-flash-1017', 'claude-sonnet-5': 'claude-opus-4-6'}
|
||||
|
||||
CATALOGUE_MODELS = tuple(dict.fromkeys(model for rank in sorted(TIER_MODELS) for model in TIER_MODELS[rank]))
|
||||
MIN_RANKS = {model: next(rank for rank in sorted(TIER_MODELS) if model in TIER_MODELS[rank]) for model in CATALOGUE_MODELS}
|
||||
_LOOKUP = {model.lower(): model for model in CATALOGUE_MODELS}
|
||||
|
||||
|
||||
def canonical(name):
|
||||
"""Canonical catalogue id for a public alias; unknown names are kept verbatim."""
|
||||
return ALIASES.get(name) or _LOOKUP.get(str(name).lower()) or name
|
||||
|
||||
|
||||
def min_rank(name):
|
||||
"""Lowest rank that opens ``name``; ``None`` when the id is outside the rank catalogue."""
|
||||
return MIN_RANKS.get(canonical(name))
|
||||
|
||||
|
||||
def describe(name):
|
||||
"""Display description for a catalogue id or alias, falling back to the raw id."""
|
||||
return MODEL_DESCS.get(name) or MODEL_DESCS.get(canonical(name)) or str(name)
|
||||
|
||||
|
||||
def model_label(name):
|
||||
"""Short button label (the text before the `` · `` separator)."""
|
||||
return describe(name).partition(" · ")[0]
|
||||
|
||||
|
||||
def model_count():
|
||||
return len(CATALOGUE_MODELS)
|
||||
|
||||
|
||||
def tier_models(rank):
|
||||
return tuple(TIER_MODELS.get(rank, ()))
|
||||
|
||||
|
||||
def api_ids(name):
|
||||
"""Accepted API spellings for a catalogue id, canonical first."""
|
||||
canonical_name = canonical(name)
|
||||
return (canonical_name,) + tuple(alias for alias, target in ALIASES.items() if target == canonical_name)
|
||||
|
||||
|
||||
def problems():
|
||||
"""Structural invariants; returns a list of human-readable problems."""
|
||||
found = []
|
||||
for rank in sorted(TIER_MODELS):
|
||||
if not TIER_MODELS[rank]:
|
||||
found.append("tier %s is empty" % rank)
|
||||
for model in TIER_MODELS[rank]:
|
||||
if model not in MODEL_DESCS:
|
||||
found.append("no display description for %s (tier %s)" % (model, rank))
|
||||
for alias, model in ALIASES.items():
|
||||
if model not in MIN_RANKS:
|
||||
found.append("alias %s points outside the catalogue" % alias)
|
||||
if alias in MIN_RANKS:
|
||||
found.append("alias %s shadows a catalogue id" % alias)
|
||||
if alias not in MODEL_DESCS:
|
||||
found.append("alias %s has no display description" % alias)
|
||||
for alias, model in ROUTING_ALIASES.items():
|
||||
if model not in MIN_RANKS:
|
||||
found.append("routing alias %s targets a model outside the catalogue" % alias)
|
||||
return found
|
||||
|
||||
|
||||
if problems(): # pragma: no cover - guard against a malformed edit at import time
|
||||
raise AssertionError("model catalogue is inconsistent: %s" % "; ".join(problems()))
|
||||
@@ -0,0 +1,132 @@
|
||||
{
|
||||
"schema": 1,
|
||||
"scope": "vendor_reference",
|
||||
"gateway_verified": false,
|
||||
"source": "https://openrouter.ai/api/v1/models",
|
||||
"source_model_field": "id",
|
||||
"field_sources": {
|
||||
"context_window": "model.context_length",
|
||||
"max_output_tokens": "top_provider.max_completion_tokens",
|
||||
"max_input_tokens": "not published by the vendor as a separate limit; always null, never inferred from context_window",
|
||||
"top_provider_context_window": "top_provider.context_length, present only when the routed provider window is narrower than model.context_length"
|
||||
},
|
||||
"notes": [
|
||||
"Static vendor catalogue reference. The numbers describe what the model vendor advertises; they are NOT proof of what this gateway or the current provider route honours. gateway_verified is false for every entry.",
|
||||
"Keys are the model ids this app serves. source_model is the exact vendor catalogue id; only single-prefix vendor spellings are mapped, nothing is guessed.",
|
||||
"A model id absent from this file is reported as unknown with null limits; the loader never interpolates or rounds numbers."
|
||||
],
|
||||
"bot_output_budget": {
|
||||
"scope": "bot_runtime_local",
|
||||
"not_a_vendor_limit": true,
|
||||
"normal": 8000,
|
||||
"max": 16000,
|
||||
"source": "bot/grok_bot.py:1711"
|
||||
},
|
||||
"models": {
|
||||
"glm-5.3": {
|
||||
"source_model": "z-ai/glm-5.3",
|
||||
"context_window": 1048576,
|
||||
"max_input_tokens": null,
|
||||
"max_output_tokens": 943718
|
||||
},
|
||||
"glm-5.3-flash": {
|
||||
"source_model": "z-ai/glm-5.3-flash",
|
||||
"context_window": 1048576,
|
||||
"max_input_tokens": null,
|
||||
"max_output_tokens": 943717,
|
||||
"top_provider_context_window": 1048575
|
||||
},
|
||||
"glm-5.3-prime": {
|
||||
"source_model": "z-ai/glm-5.3-prime",
|
||||
"context_window": 1000000,
|
||||
"max_input_tokens": null,
|
||||
"max_output_tokens": 131072
|
||||
},
|
||||
"kimi-k3": {
|
||||
"source_model": "moonshotai/kimi-k3",
|
||||
"context_window": 1048576,
|
||||
"max_input_tokens": null,
|
||||
"max_output_tokens": 943718
|
||||
},
|
||||
"kimi/kimi-k3.1-pro": {
|
||||
"source_model": "moonshotai/kimi-k3.1-pro",
|
||||
"context_window": 1048576,
|
||||
"max_input_tokens": null,
|
||||
"max_output_tokens": 943718
|
||||
},
|
||||
"deepseek-v4.1-flash": {
|
||||
"source_model": "deepseek/deepseek-v4.1-flash",
|
||||
"context_window": 1048576,
|
||||
"max_input_tokens": null,
|
||||
"max_output_tokens": 131072
|
||||
},
|
||||
"deepseek-v4.1-flash-1017": {
|
||||
"source_model": "deepseek/deepseek-v4.1-flash-1017",
|
||||
"context_window": 1048576,
|
||||
"max_input_tokens": null,
|
||||
"max_output_tokens": 393216
|
||||
},
|
||||
"deepseek-v4-flash": {
|
||||
"source_model": "deepseek/deepseek-v4-flash",
|
||||
"context_window": 1048576,
|
||||
"max_input_tokens": null,
|
||||
"max_output_tokens": 131072
|
||||
},
|
||||
"deepseek-v4-pro": {
|
||||
"source_model": "deepseek/deepseek-v4-pro",
|
||||
"context_window": 1048576,
|
||||
"max_input_tokens": null,
|
||||
"max_output_tokens": 384000,
|
||||
"top_provider_context_window": 1024000
|
||||
},
|
||||
"qwen3.8-flash": {
|
||||
"source_model": "qwen/qwen3.8-flash",
|
||||
"context_window": 1000000,
|
||||
"max_input_tokens": null,
|
||||
"max_output_tokens": 131072
|
||||
},
|
||||
"qwen3.8-27b": {
|
||||
"source_model": "qwen/qwen3.8-27b",
|
||||
"context_window": 1000000,
|
||||
"max_input_tokens": null,
|
||||
"max_output_tokens": 235929,
|
||||
"top_provider_context_window": 262144
|
||||
},
|
||||
"qwen3.8-max-0902": {
|
||||
"source_model": "qwen/qwen3.8-max-0902",
|
||||
"context_window": 1000000,
|
||||
"max_input_tokens": null,
|
||||
"max_output_tokens": 131072
|
||||
},
|
||||
"grok-4.6": {
|
||||
"source_model": "x-ai/grok-4.6",
|
||||
"context_window": 500000,
|
||||
"max_input_tokens": null,
|
||||
"max_output_tokens": 450000
|
||||
},
|
||||
"grok-4.7": {
|
||||
"source_model": "x-ai/grok-4.7",
|
||||
"context_window": 500000,
|
||||
"max_input_tokens": null,
|
||||
"max_output_tokens": 450000
|
||||
},
|
||||
"gpt-5.6-luna": {
|
||||
"source_model": "openai/gpt-5.6-luna",
|
||||
"context_window": 1050000,
|
||||
"max_input_tokens": null,
|
||||
"max_output_tokens": 128000
|
||||
},
|
||||
"gpt-5.6-terra": {
|
||||
"source_model": "openai/gpt-5.6-terra",
|
||||
"context_window": 1050000,
|
||||
"max_input_tokens": null,
|
||||
"max_output_tokens": 128000
|
||||
},
|
||||
"gpt-5.6-sol": {
|
||||
"source_model": "openai/gpt-5.6-sol",
|
||||
"context_window": 1050000,
|
||||
"max_input_tokens": null,
|
||||
"max_output_tokens": 128000
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,211 @@
|
||||
"""Model uptime history: stores real probe results, never probes by itself.
|
||||
|
||||
Stdlib-only SQLite store fed by the existing ``_ms_loop`` probe results in
|
||||
``webapp/server.py`` (``_MS["data"]`` dict ``model -> probe``). Probe schema:
|
||||
``{"up": 1|0|None, "status": "up"|"down"|"busy"|"unknown", "ms": int?,
|
||||
"http_status": int?, "checked_at": int}``.
|
||||
|
||||
Semantics:
|
||||
* only terminal ``up``/``down`` observations count towards uptime;
|
||||
* ``busy`` (429/5xx after retry) is *degraded*, not down;
|
||||
* ``unknown`` (timeouts, empty answers) and missing hours are ``no_data``;
|
||||
* nothing before the first real observation is invented (``observed_since``).
|
||||
"""
|
||||
from __future__ import annotations
|
||||
|
||||
import sqlite3
|
||||
import math
|
||||
import time
|
||||
from typing import Any, Iterable, Mapping
|
||||
|
||||
RETENTION_DAYS = 30
|
||||
WINDOW_HOURS = 24
|
||||
BUCKET_SECONDS = 3600
|
||||
MAX_ROWS = 200_000 # hard storage bound on top of retention
|
||||
MAX_MODELS = 500 # per batch / per history call
|
||||
MAX_MODEL_LEN = 128
|
||||
MAX_LATENCY_MS = 600_000
|
||||
FUTURE_SKEW = 300 # tolerated clock skew for checked_at, seconds
|
||||
STATUSES = ("up", "down", "busy", "unknown")
|
||||
|
||||
_SCHEMA = (
|
||||
"CREATE TABLE IF NOT EXISTS model_probe ("
|
||||
" ts INTEGER NOT NULL, model TEXT NOT NULL, status TEXT NOT NULL,"
|
||||
" latency_ms INTEGER, http_status INTEGER, PRIMARY KEY (model, ts))",
|
||||
"CREATE INDEX IF NOT EXISTS model_probe_ts ON model_probe (ts)",
|
||||
)
|
||||
|
||||
|
||||
def _connect(db_path: str) -> sqlite3.Connection:
|
||||
con = sqlite3.connect(db_path, timeout=15, isolation_level=None)
|
||||
con.execute("PRAGMA busy_timeout=15000")
|
||||
return con
|
||||
|
||||
|
||||
def init(db_path: str) -> None:
|
||||
"""Create schema (idempotent) and switch the file to WAL for concurrent readers."""
|
||||
con = _connect(db_path)
|
||||
try:
|
||||
try:
|
||||
con.execute("PRAGMA journal_mode=WAL")
|
||||
except sqlite3.OperationalError:
|
||||
pass # e.g. locked by another writer; DELETE journal still works
|
||||
for stmt in _SCHEMA:
|
||||
con.execute(stmt)
|
||||
finally:
|
||||
con.close()
|
||||
|
||||
|
||||
def _int_or_none(value: Any, lo: int, hi: int) -> int | None:
|
||||
if isinstance(value, bool) or not isinstance(value, (int, float)) or not math.isfinite(value):
|
||||
return None
|
||||
value = int(value)
|
||||
return value if lo <= value <= hi else None
|
||||
|
||||
|
||||
def _normalize(model: Any, probe: Any, now: int, cutoff: int) -> tuple | None:
|
||||
if not isinstance(model, str) or not model or len(model) > MAX_MODEL_LEN:
|
||||
return None
|
||||
if not isinstance(probe, Mapping):
|
||||
return None
|
||||
status = probe.get("status")
|
||||
if status not in STATUSES:
|
||||
up = probe.get("up")
|
||||
status = ("unknown" if isinstance(up, bool) or up is None
|
||||
else "up" if up == 1 else "down" if up == 0 else "unknown")
|
||||
ts = _int_or_none(probe.get("checked_at"), 1, now + FUTURE_SKEW)
|
||||
ts = min(ts, now) if ts is not None else now
|
||||
if ts < cutoff:
|
||||
return None
|
||||
latency = _int_or_none(probe.get("ms"), 0, MAX_LATENCY_MS) if status == "up" else None
|
||||
http_status = _int_or_none(probe.get("http_status"), 100, 599)
|
||||
return ts, model, status, latency, http_status
|
||||
|
||||
|
||||
def record_batch(db_path: str, status_dict: Mapping[str, Any], now: float | None = None,
|
||||
retention_days: int = RETENTION_DAYS) -> int:
|
||||
now_i = int(time.time() if now is None else now)
|
||||
cutoff = now_i - int(retention_days) * 86400
|
||||
rows = []
|
||||
if isinstance(status_dict, Mapping):
|
||||
for model, probe in list(status_dict.items())[:MAX_MODELS]:
|
||||
row = _normalize(model, probe, now_i, cutoff)
|
||||
if row:
|
||||
rows.append(row)
|
||||
init(db_path)
|
||||
con = _connect(db_path)
|
||||
try:
|
||||
con.execute("BEGIN IMMEDIATE")
|
||||
try:
|
||||
before = con.total_changes
|
||||
con.executemany("INSERT OR IGNORE INTO model_probe (ts, model, status, latency_ms, http_status)"
|
||||
" VALUES (?,?,?,?,?)", rows)
|
||||
inserted = con.total_changes - before
|
||||
con.execute("DELETE FROM model_probe WHERE ts < ?", (cutoff,))
|
||||
excess = con.execute("SELECT COUNT(*) FROM model_probe").fetchone()[0] - MAX_ROWS
|
||||
if excess > 0:
|
||||
con.execute("DELETE FROM model_probe WHERE rowid IN"
|
||||
" (SELECT rowid FROM model_probe ORDER BY ts LIMIT ?)", (excess,))
|
||||
con.execute("COMMIT")
|
||||
except BaseException:
|
||||
con.execute("ROLLBACK")
|
||||
raise
|
||||
finally:
|
||||
con.close()
|
||||
return inserted
|
||||
|
||||
|
||||
def _bucket_state(c: Mapping[str, int]) -> str:
|
||||
if c["up"] and c["down"]:
|
||||
return "partial"
|
||||
if c["down"]:
|
||||
return "down"
|
||||
if c["up"] and not c["busy"]:
|
||||
return "up"
|
||||
if c["up"] or c["busy"]:
|
||||
return "degraded"
|
||||
return "no_data" # only unknown samples or nothing at all
|
||||
|
||||
|
||||
def _empty_model(buckets: list[dict]) -> dict:
|
||||
return {"data_state": "no_data", "uptime_pct": None, "sample_count": 0,
|
||||
"observed_count": 0, "counts": dict.fromkeys(STATUSES, 0),
|
||||
"observed_since": None, "last_checked": None, "last_status": None,
|
||||
"latency_ms": None, "latency_avg_ms": None, "coverage_pct": 0.0,
|
||||
"buckets": [dict(b, state="no_data", samples=0, **dict.fromkeys(STATUSES, 0))
|
||||
for b in buckets]}
|
||||
|
||||
|
||||
def history(db_path: str, models: Iterable[str], now: float | None = None,
|
||||
hours: int = WINDOW_HOURS) -> dict:
|
||||
"""Per-model timeline of the last ``hours`` one-hour buckets (hour-aligned, UTC).
|
||||
|
||||
The last bucket is the current, still running hour. ``uptime_pct`` is
|
||||
``up / (up + down)`` over the window or ``None`` without terminal samples.
|
||||
``data_state``: ``no_data`` (no samples in window), ``partial`` (history
|
||||
starts inside the window or hours are missing) or ``complete``.
|
||||
"""
|
||||
now_i = int(time.time() if now is None else now)
|
||||
hours = max(1, min(int(hours), 24 * RETENTION_DAYS))
|
||||
end = (now_i // BUCKET_SECONDS + 1) * BUCKET_SECONDS
|
||||
start = end - hours * BUCKET_SECONDS
|
||||
frame = [{"start": start + i * BUCKET_SECONDS, "end": start + (i + 1) * BUCKET_SECONDS}
|
||||
for i in range(hours)]
|
||||
names = [m for m in dict.fromkeys(models) if isinstance(m, str) and m][:MAX_MODELS]
|
||||
out = {m: _empty_model(frame) for m in names}
|
||||
meta = {"generated_at": now_i, "window_start": start, "window_end": end, "hours": hours,
|
||||
"bucket_seconds": BUCKET_SECONDS, "retention_days": RETENTION_DAYS,
|
||||
"uptime_basis": "up/(up+down); busy=degraded; unknown/no probe=no_data"}
|
||||
if not names:
|
||||
return {**meta, "models": out}
|
||||
init(db_path)
|
||||
con = _connect(db_path)
|
||||
try:
|
||||
marks = ",".join("?" * len(names))
|
||||
firsts = dict(con.execute(f"SELECT model, MIN(ts) FROM model_probe WHERE model IN ({marks})"
|
||||
" GROUP BY model", names).fetchall())
|
||||
lasts = {m: (ts, st, lat) for m, ts, st, lat in con.execute(
|
||||
f"SELECT model, ts, status, latency_ms FROM model_probe p WHERE model IN ({marks})"
|
||||
" AND ts = (SELECT MAX(ts) FROM model_probe WHERE model = p.model)", names)}
|
||||
rows = con.execute(f"SELECT model, ts, status, latency_ms FROM model_probe"
|
||||
f" WHERE model IN ({marks}) AND ts >= ? AND ts < ?",
|
||||
(*names, start, end)).fetchall()
|
||||
finally:
|
||||
con.close()
|
||||
lat_sum: dict[str, list[int]] = {}
|
||||
for model, ts, status, latency in rows:
|
||||
if status not in STATUSES:
|
||||
continue
|
||||
item = out[model]
|
||||
bucket = item["buckets"][(ts - start) // BUCKET_SECONDS]
|
||||
bucket[status] += 1
|
||||
bucket["samples"] += 1
|
||||
item["counts"][status] += 1
|
||||
item["sample_count"] += 1
|
||||
if status == "up" and latency is not None:
|
||||
lat_sum.setdefault(model, []).append(latency)
|
||||
for model, item in out.items():
|
||||
for bucket in item["buckets"]:
|
||||
bucket["state"] = _bucket_state(bucket)
|
||||
c = item["counts"]
|
||||
terminal = c["up"] + c["down"]
|
||||
item["observed_count"] = terminal
|
||||
item["uptime_pct"] = round(100.0 * c["up"] / terminal, 2) if terminal else None
|
||||
item["observed_since"] = firsts.get(model)
|
||||
if model in lasts:
|
||||
ts, status, latency = lasts[model]
|
||||
item["last_checked"], item["last_status"] = ts, status
|
||||
item["latency_ms"] = latency if status == "up" else None
|
||||
if model in lat_sum:
|
||||
item["latency_avg_ms"] = round(sum(lat_sum[model]) / len(lat_sum[model]))
|
||||
covered = sum(1 for b in item["buckets"] if b["state"] != "no_data")
|
||||
# the running hour may simply not have been probed yet (loop sleeps 30 min)
|
||||
due = hours if item["buckets"][-1]["state"] != "no_data" else hours - 1
|
||||
item["coverage_pct"] = round(100.0 * covered / max(due, 1), 1)
|
||||
if item["sample_count"] == 0:
|
||||
item["data_state"] = "no_data"
|
||||
elif item["observed_since"] > start or covered < due:
|
||||
item["data_state"] = "partial"
|
||||
else:
|
||||
item["data_state"] = "complete"
|
||||
return {**meta, "models": out}
|
||||
File diff suppressed because it is too large
Load Diff
+1195
File diff suppressed because it is too large
Load Diff
@@ -0,0 +1,124 @@
|
||||
import asyncio, json, os, time
|
||||
import aiohttp
|
||||
|
||||
KEYS_FILE = os.environ.get("PIKEYS", "/opt/grok-bot/piapi_keys.jsonl")
|
||||
API = "https://api.piapi.ai"
|
||||
_sem = asyncio.Semaphore(2)
|
||||
_dead = {}
|
||||
|
||||
|
||||
def _load_keys():
|
||||
keys = []
|
||||
try:
|
||||
with open(KEYS_FILE, encoding="utf-8") as f:
|
||||
for line in f:
|
||||
line = line.strip()
|
||||
if not line:
|
||||
continue
|
||||
try:
|
||||
rec = json.loads(line)
|
||||
except Exception:
|
||||
continue
|
||||
k = rec.get("key")
|
||||
if k and k not in keys:
|
||||
keys.append(k)
|
||||
except FileNotFoundError:
|
||||
pass
|
||||
return keys
|
||||
|
||||
|
||||
def _alive_keys():
|
||||
now = time.time()
|
||||
return [k for k in _load_keys() if now - _dead.get(k, 0) > 3600]
|
||||
|
||||
|
||||
def _headers(key):
|
||||
return {"x-api-key": key, "Content-Type": "application/json",
|
||||
"User-Agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 Chrome/131.0.0.0 Safari/537.36"}
|
||||
|
||||
|
||||
async def pool_status():
|
||||
keys = _load_keys()
|
||||
alive = _alive_keys()
|
||||
return {"backend": "piapi-udio", "total": len(keys), "alive": len(alive), "dead": len(keys) - len(alive)}
|
||||
|
||||
|
||||
async def generate_music(prompt, title=None, style=None, instrumental=False,
|
||||
model_version=None, timeout=480):
|
||||
keys = _alive_keys()
|
||||
if not keys:
|
||||
return {"ok": False, "error": "POOL_EMPTY", "tracks": [], "key_tail": ""}
|
||||
desc = prompt
|
||||
if style:
|
||||
desc = "%s, %s" % (style, prompt) if prompt != style else style
|
||||
if title:
|
||||
desc = "%s (%s)" % (desc, title)
|
||||
inp = {"gpt_description_prompt": desc[:1000], "negative_tags": "",
|
||||
"lyrics_type": "instrumental" if instrumental else "generate", "seed": -1}
|
||||
body = {"model": "music-u", "task_type": "generate_music", "input": inp,
|
||||
"config": {"service_mode": "public", "webhook_config": {"endpoint": "", "secret": ""}}}
|
||||
|
||||
async with _sem:
|
||||
last_err = None
|
||||
for key in keys:
|
||||
try:
|
||||
async with aiohttp.ClientSession() as s:
|
||||
async with s.post(API + "/api/v1/task", headers=_headers(key), json=body,
|
||||
timeout=aiohttp.ClientTimeout(total=40)) as r:
|
||||
txt = await r.text()
|
||||
if r.status in (401, 403):
|
||||
_dead[key] = time.time()
|
||||
last_err = "KEY_DEAD_%d" % r.status
|
||||
continue
|
||||
try:
|
||||
d = json.loads(txt)
|
||||
except Exception:
|
||||
last_err = "BAD_JSON"
|
||||
continue
|
||||
if r.status != 200:
|
||||
msg = str(d.get("message") or d.get("error") or txt)[:150].lower()
|
||||
if "balance" in msg or "credit" in msg or "insufficient" in msg or "point" in msg:
|
||||
_dead[key] = time.time()
|
||||
last_err = "NO_CREDITS"
|
||||
else:
|
||||
last_err = "HTTP_%d:%s" % (r.status, txt[:120])
|
||||
continue
|
||||
tid = (d.get("data") or {}).get("task_id")
|
||||
if not tid:
|
||||
last_err = "NO_TASKID:%s" % txt[:120]
|
||||
continue
|
||||
t0 = time.time()
|
||||
while time.time() - t0 < timeout:
|
||||
await asyncio.sleep(10)
|
||||
try:
|
||||
async with aiohttp.ClientSession() as s2:
|
||||
async with s2.get(API + "/api/v1/task/" + str(tid),
|
||||
headers=_headers(key),
|
||||
timeout=aiohttp.ClientTimeout(total=25)) as gr:
|
||||
gd = await gr.json()
|
||||
except Exception:
|
||||
continue
|
||||
dd = gd.get("data") or {}
|
||||
st = str(dd.get("status", "")).lower()
|
||||
if st == "completed":
|
||||
songs = ((dd.get("output") or {}).get("songs")) or []
|
||||
out = [{"audioUrl": s.get("song_path") or s.get("hosted_audio_url"),
|
||||
"title": s.get("title") or title or "track",
|
||||
"imageUrl": s.get("image_path")}
|
||||
for s in songs if (s.get("song_path") or s.get("hosted_audio_url"))]
|
||||
return {"ok": bool(out), "tracks": out, "job": tid,
|
||||
"key_tail": key[-6:], "error": None if out else "NO_TRACKS"}
|
||||
if st in ("failed", "failure", "error", "cancelled"):
|
||||
err = (dd.get("error") or {}).get("message") if isinstance(dd.get("error"), dict) else str(dd.get("error"))
|
||||
err = (err or "")[:150].lower()
|
||||
if "balance" in err or "credit" in err or "insufficient" in err:
|
||||
_dead[key] = time.time()
|
||||
last_err = "NO_CREDITS"
|
||||
else:
|
||||
last_err = "TASK_FAILED:%s" % (err or st)
|
||||
break
|
||||
else:
|
||||
last_err = "TIMEOUT"
|
||||
except Exception as e:
|
||||
last_err = "EXC:%s" % str(e)[:100]
|
||||
return {"ok": False, "error": last_err or "UNKNOWN", "tracks": [], "key_tail": keys[-1][-6:] if keys else ""}
|
||||
@@ -0,0 +1,530 @@
|
||||
"""Shared daily quests and check-ins for the bot and Mini App.
|
||||
|
||||
The ledger/claim is committed in bot.db before money moves. The gateway credit and
|
||||
its unique payout ref are committed in one gateway.db transaction. A retry checks
|
||||
that payout ref and completes an interrupted claim instead of paying twice or
|
||||
returning a false "already". This avoids relying on cross-file WAL atomicity.
|
||||
"""
|
||||
from __future__ import annotations
|
||||
|
||||
import calendar
|
||||
from contextlib import closing
|
||||
import datetime
|
||||
import logging
|
||||
import sqlite3
|
||||
import threading
|
||||
import time
|
||||
|
||||
import econ_guard
|
||||
|
||||
log = logging.getLogger("quest-economy")
|
||||
|
||||
QUOTA_PER_USD = 500_000
|
||||
QUEST_BUDGET = 250_000_000
|
||||
PAYOUT_TYPES = ("quest", "streak:7", "streak:30", "streak:100")
|
||||
QUESTS = {
|
||||
0: [("msgs", 10, 100), ("checkin", 1, 100)],
|
||||
1: [("msgs", 10, 100), ("quiz", 1, 100), ("checkin", 1, 100)],
|
||||
2: [("msgs", 15, 200), ("quiz", 1, 150), ("checkin", 1, 150)],
|
||||
3: [("msgs", 20, 300), ("quiz", 1, 250), ("checkin", 1, 250)],
|
||||
4: [("msgs", 25, 400), ("quiz", 1, 350), ("checkin", 1, 350)],
|
||||
}
|
||||
TITLES = {
|
||||
"msgs": "Сообщения в группе",
|
||||
"quiz": "Правильный ответ в квизе",
|
||||
"checkin": "Ежедневный чек-ин",
|
||||
}
|
||||
MSK = 3 * 3600
|
||||
_PREPARED = set()
|
||||
_PREPARE_LOCK = threading.Lock()
|
||||
|
||||
|
||||
def _now(value=None):
|
||||
return int(time.time() if value is None else value)
|
||||
|
||||
|
||||
def today(now=None):
|
||||
return time.strftime("%Y%m%d", time.gmtime(_now(now) + MSK))
|
||||
|
||||
|
||||
def today_iso(now=None):
|
||||
return time.strftime("%Y-%m-%d", time.gmtime(_now(now) + MSK))
|
||||
|
||||
|
||||
def day_start(now=None):
|
||||
msk = time.gmtime(_now(now) + MSK)
|
||||
return calendar.timegm((msk.tm_year, msk.tm_mon, msk.tm_mday, 0, 0, 0)) - MSK
|
||||
|
||||
|
||||
def week_key(now=None):
|
||||
return time.strftime("%G%V", time.gmtime(_now(now) + MSK))
|
||||
|
||||
|
||||
def week_start(now=None):
|
||||
msk = datetime.datetime.fromtimestamp(_now(now) + MSK, datetime.timezone.utc)
|
||||
monday = (msk.replace(hour=0, minute=0, second=0, microsecond=0) -
|
||||
datetime.timedelta(days=msk.weekday()))
|
||||
return calendar.timegm(monday.timetuple()) - MSK
|
||||
|
||||
|
||||
def is_today(value, now=None):
|
||||
if value in (None, "", 0, "0"):
|
||||
return False
|
||||
text = str(value)
|
||||
if len(text) == 8 and text.isdigit():
|
||||
return text == today(now)
|
||||
try:
|
||||
return float(value) >= day_start(now)
|
||||
except (TypeError, ValueError):
|
||||
return text.replace("-", "") == today(now)
|
||||
|
||||
|
||||
def _con(path):
|
||||
con = sqlite3.connect(path, timeout=25)
|
||||
con.row_factory = sqlite3.Row
|
||||
con.execute("PRAGMA busy_timeout=25000")
|
||||
return con
|
||||
|
||||
|
||||
def ensure_schema(bot_db, gw_db):
|
||||
econ_guard.ensure_schema(bot_db)
|
||||
with closing(_con(bot_db)) as con:
|
||||
columns = {row[1] for row in con.execute("PRAGMA table_info(econ_tx)")}
|
||||
if "wallet_id" not in columns:
|
||||
try:
|
||||
con.execute("ALTER TABLE econ_tx ADD COLUMN wallet_id INTEGER")
|
||||
except sqlite3.OperationalError as exc:
|
||||
if "duplicate column" not in str(exc).lower():
|
||||
raise
|
||||
con.commit()
|
||||
with closing(_con(gw_db)) as con:
|
||||
con.execute("""CREATE TABLE IF NOT EXISTS econ_payouts(
|
||||
ref TEXT PRIMARY KEY, token_id INTEGER NOT NULL,
|
||||
units INTEGER NOT NULL, created INTEGER NOT NULL)""")
|
||||
con.commit()
|
||||
|
||||
|
||||
def _migrate_legacy(bot_db, gw_db):
|
||||
"""Mark pre-upgrade ledger refs as paid exactly once, before any new claim."""
|
||||
con = _con(gw_db)
|
||||
try:
|
||||
con.execute("ATTACH DATABASE ? AS ledger", (bot_db,))
|
||||
con.execute("BEGIN IMMEDIATE")
|
||||
if con.execute("SELECT v FROM ledger.kv WHERE k='quest_credits:v1'").fetchone():
|
||||
con.commit()
|
||||
return
|
||||
rows = con.execute("SELECT ref,units FROM ledger.econ_tx "
|
||||
"WHERE ref IS NOT NULL AND ref!=''").fetchall()
|
||||
con.executemany("INSERT OR IGNORE INTO econ_payouts(ref,token_id,units,created) VALUES(?,0,?,0)",
|
||||
[(row["ref"], int(row["units"])) for row in rows])
|
||||
con.execute("INSERT INTO ledger.kv(k,v) VALUES('quest_credits:v1','1')")
|
||||
con.commit()
|
||||
except Exception:
|
||||
con.rollback()
|
||||
raise
|
||||
finally:
|
||||
con.close()
|
||||
|
||||
|
||||
def prepare(bot_db, gw_db):
|
||||
key = (bot_db, gw_db)
|
||||
if key in _PREPARED:
|
||||
return
|
||||
with _PREPARE_LOCK:
|
||||
if key in _PREPARED:
|
||||
return
|
||||
ensure_schema(bot_db, gw_db)
|
||||
_migrate_legacy(bot_db, gw_db)
|
||||
_PREPARED.add(key)
|
||||
|
||||
|
||||
def multiplier(bot_db, uid, now=None):
|
||||
current = _now(now)
|
||||
with closing(_con(bot_db)) as con:
|
||||
row = con.execute("SELECT v FROM kv WHERE k=?", ("ec_x2:%d" % int(uid),)).fetchone()
|
||||
if not row or not row[0]:
|
||||
return 1
|
||||
try:
|
||||
value = str(row[0])
|
||||
if "|" in value:
|
||||
until, mult = value.split("|", 1)
|
||||
return int(mult) if float(until) > current else 1
|
||||
return 2 if float(value) > current else 1
|
||||
except (TypeError, ValueError):
|
||||
return 1
|
||||
|
||||
|
||||
def _progress_con(con, uid, now=None):
|
||||
user = con.execute("SELECT quiz_last,last_checkin FROM users WHERE tg_id=?", (int(uid),)).fetchone()
|
||||
msgs = con.execute("SELECT COUNT(*) FROM group_log WHERE uid=? AND ts>=?",
|
||||
(int(uid), day_start(now))).fetchone()[0]
|
||||
return {
|
||||
"msgs": int(msgs or 0),
|
||||
"quiz": int(is_today(user["quiz_last"] if user else None, now)),
|
||||
"checkin": int(is_today(user["last_checkin"] if user else None, now)),
|
||||
}
|
||||
|
||||
|
||||
def progress(bot_db, uid, now=None):
|
||||
with closing(_con(bot_db)) as con:
|
||||
return _progress_con(con, uid, now)
|
||||
|
||||
|
||||
def earned_rank(bot_db, uid, badges, rank_refs, ref_new_id_min=9_000_000_000, now=None):
|
||||
"""Payout rank: formula plus badge_lock floor, without the admin display override."""
|
||||
current = _now(now)
|
||||
with closing(_con(bot_db)) as con:
|
||||
user = con.execute("SELECT rep,created,badge_lock,badge_until FROM users WHERE tg_id=?",
|
||||
(int(uid),)).fetchone()
|
||||
refs = con.execute(
|
||||
"SELECT COALESCE(SUM(CASE WHEN tg_id>=? THEN 0.5 ELSE 1.0 END),0) "
|
||||
"FROM users WHERE referred_by=? AND ref_awarded=1", (ref_new_id_min, int(uid))).fetchone()[0]
|
||||
if not user:
|
||||
return 1
|
||||
rep, created, badge_lock, badge_until = user
|
||||
days = max(0, (current - int(created or 0)) // 86400) if created else 0
|
||||
lvl = 1
|
||||
for candidate in (2, 3, 4):
|
||||
rep_req, days_req = badges[candidate][2], badges[candidate][3]
|
||||
if days >= days_req and (refs >= rank_refs[candidate] or (rep_req and (rep or 0) >= rep_req)):
|
||||
lvl = candidate
|
||||
lock = int(badge_lock or 0)
|
||||
until = int(badge_until or 0)
|
||||
if lock and (until == 0 or current < until):
|
||||
lvl = max(lvl, min(4, max(1, lock)))
|
||||
return lvl
|
||||
|
||||
|
||||
def _credit_once(gw_db, ref, wallet_id, units, bot_db=None, uid=None):
|
||||
if bot_db is None or uid is None:
|
||||
return 0, "user"
|
||||
if int(units) <= 0:
|
||||
return 0, "error"
|
||||
con = None
|
||||
try:
|
||||
con = _con(gw_db)
|
||||
con.execute("ATTACH DATABASE ? AS ledger", (bot_db,))
|
||||
con.execute("BEGIN IMMEDIATE")
|
||||
if not econ_guard.account_eligible_con(con, uid, "ledger"):
|
||||
con.rollback()
|
||||
return 0, "blocked"
|
||||
columns = {row[1] for row in con.execute("PRAGMA ledger.table_info(econ_tx)")}
|
||||
source = "bounty_source" if "bounty_source" in columns else "NULL AS bounty_source"
|
||||
receipts = con.execute("SELECT dst,units,wallet_id,type,src,%s "
|
||||
"FROM ledger.econ_tx WHERE ref=? AND type IN (?,?,?,?)" % source,
|
||||
(ref, *PAYOUT_TYPES)).fetchall()
|
||||
if (len(receipts) != 1 or int(receipts[0]["dst"]) != int(uid)
|
||||
or int(receipts[0]["units"]) != int(units)
|
||||
or receipts[0]["type"] not in PAYOUT_TYPES or receipts[0]["src"] != 0
|
||||
or bool(receipts[0]["bounty_source"])
|
||||
or (receipts[0]["wallet_id"] is not None
|
||||
and int(receipts[0]["wallet_id"]) != int(wallet_id))):
|
||||
con.rollback()
|
||||
return 0, "error"
|
||||
if not econ_guard._wallet_owned_con(con, uid, wallet_id):
|
||||
con.rollback()
|
||||
return 0, "wallet"
|
||||
existing = con.execute("SELECT token_id,units FROM econ_payouts WHERE ref=?", (ref,)).fetchone()
|
||||
if existing:
|
||||
token_matches = int(existing["token_id"]) in (0, int(wallet_id))
|
||||
if not token_matches or int(existing["units"]) != int(units):
|
||||
con.rollback()
|
||||
log.error("payout ref conflict ref=%s", ref)
|
||||
return 0, "error"
|
||||
con.commit()
|
||||
return 0, "already"
|
||||
con.execute("INSERT INTO econ_payouts(ref,token_id,units,created) VALUES(?,?,?,?)",
|
||||
(ref, int(wallet_id), int(units), int(time.time())))
|
||||
credited = con.execute("UPDATE tokens SET remain_quota=remain_quota+? "
|
||||
"WHERE id=? AND status IN (1,2) AND deleted_at IS NULL",
|
||||
(int(units), int(wallet_id)))
|
||||
if credited.rowcount != 1:
|
||||
con.rollback()
|
||||
return 0, "wallet"
|
||||
con.commit()
|
||||
return int(units), "ok"
|
||||
except sqlite3.Error:
|
||||
log.exception("gateway payout failed ref=%s", ref)
|
||||
if con:
|
||||
con.rollback()
|
||||
return 0, "error"
|
||||
finally:
|
||||
if con:
|
||||
con.close()
|
||||
|
||||
|
||||
def _credit_ledger_row(bot_db, gw_db, row):
|
||||
if not econ_guard.account_eligible(bot_db, int(row["dst"])):
|
||||
return 0, "blocked"
|
||||
wallet_id = row["wallet_id"]
|
||||
if wallet_id is None:
|
||||
wallet = econ_guard.resolve_wallet(gw_db, bot_db, int(row["dst"]))
|
||||
if not wallet:
|
||||
return 0, "wallet"
|
||||
wallet_id = wallet[0]
|
||||
return _credit_once(gw_db, row["ref"], int(wallet_id), int(row["units"]),
|
||||
bot_db=bot_db, uid=int(row["dst"]))
|
||||
|
||||
|
||||
def reconcile_pending(bot_db, gw_db, uid=None):
|
||||
"""Complete this module's two-phase quest/streak claims, never atomic bounty receipts."""
|
||||
prepare(bot_db, gw_db)
|
||||
sql = ("SELECT dst,units,type,ref,wallet_id FROM econ_tx WHERE wallet_id IS NOT NULL "
|
||||
"AND type IN (?,?,?,?)")
|
||||
params = list(PAYOUT_TYPES)
|
||||
if uid is not None:
|
||||
sql += " AND dst=?"
|
||||
params.append(int(uid))
|
||||
with closing(_con(bot_db)) as con:
|
||||
columns = {row[1] for row in con.execute("PRAGMA table_info(econ_tx)")}
|
||||
if "bounty_source" in columns:
|
||||
sql += " AND COALESCE(bounty_source,'')=''"
|
||||
rows = con.execute(sql, params).fetchall()
|
||||
with closing(_con(gw_db)) as gw:
|
||||
paid = {r[0] for r in gw.execute("SELECT ref FROM econ_payouts").fetchall()}
|
||||
results = {}
|
||||
for row in rows:
|
||||
if row["ref"] in paid:
|
||||
results["already"] = results.get("already", 0) + 1
|
||||
continue
|
||||
_, result = _credit_ledger_row(bot_db, gw_db, row)
|
||||
results[result] = results.get(result, 0) + 1
|
||||
return results
|
||||
|
||||
|
||||
def _ledger_row(bot_db, type_, ref):
|
||||
with closing(_con(bot_db)) as con:
|
||||
return con.execute("SELECT dst,units,type,ref,wallet_id FROM econ_tx WHERE type=? AND ref=?",
|
||||
(type_, ref)).fetchone()
|
||||
|
||||
|
||||
def claim_daily(bot_db, gw_db, uid, qid, lvl, progress_map=None, mult=None, now=None,
|
||||
allow_checkin=False):
|
||||
"""Claim once and self-heal interrupted payouts; progress_map is only a caller prefilter."""
|
||||
uid = int(uid)
|
||||
current = _now(now)
|
||||
definition = next((item for item in QUESTS.get(int(lvl), QUESTS[1]) if item[0] == qid), None)
|
||||
if not definition:
|
||||
return 0, "unknown_quest"
|
||||
_, need, reward = definition
|
||||
prepare(bot_db, gw_db)
|
||||
if not econ_guard.account_eligible(bot_db, uid):
|
||||
return 0, "blocked"
|
||||
if qid == "checkin" and allow_checkin:
|
||||
checked = record_checkin(bot_db, gw_db, uid, current, source="miniapp")
|
||||
if not checked.get("ok"):
|
||||
return 0, checked.get("error", "user")
|
||||
mult = multiplier(bot_db, uid, current) if mult is None else int(mult)
|
||||
units = reward * QUOTA_PER_USD * mult
|
||||
day = today(current)
|
||||
marker = "ec_q:%d:%s:%s" % (uid, day, qid)
|
||||
ref = "quest:%d:%s:%s" % (uid, day, qid)
|
||||
existing = _ledger_row(bot_db, "quest", ref)
|
||||
wallet = None if existing else econ_guard.resolve_wallet(gw_db, bot_db, uid)
|
||||
if not existing and not wallet:
|
||||
return 0, "wallet"
|
||||
con = _con(bot_db)
|
||||
try:
|
||||
con.execute("BEGIN IMMEDIATE")
|
||||
if not econ_guard.account_eligible_con(con, uid):
|
||||
con.rollback()
|
||||
return 0, "blocked"
|
||||
row = con.execute("SELECT dst,units,type,ref,wallet_id FROM econ_tx WHERE type='quest' AND ref=?",
|
||||
(ref,)).fetchone()
|
||||
if row is None:
|
||||
if con.execute("SELECT 1 FROM kv WHERE k=?", (marker,)).fetchone():
|
||||
con.commit()
|
||||
return 0, "already"
|
||||
prog = _progress_con(con, uid, current)
|
||||
if prog.get(qid, 0) < need:
|
||||
con.rollback()
|
||||
return 0, "progress"
|
||||
spent = int(con.execute("SELECT COALESCE(SUM(units),0) FROM econ_tx WHERE type='quest' AND ts>=?",
|
||||
(day_start(current),)).fetchone()[0] or 0)
|
||||
if spent + units > QUEST_BUDGET:
|
||||
con.rollback()
|
||||
return 0, "budget"
|
||||
if not wallet:
|
||||
con.rollback()
|
||||
return 0, "wallet"
|
||||
claimed = con.execute("INSERT OR IGNORE INTO kv(k,v) VALUES (?,'1')", (marker,))
|
||||
if claimed.rowcount != 1:
|
||||
con.rollback()
|
||||
return 0, "already"
|
||||
con.execute("INSERT INTO econ_tx(src,dst,units,type,ts,ref,wallet_id) VALUES (?,?,?,?,?,?,?)",
|
||||
(0, uid, units, "quest", current, ref, int(wallet[0])))
|
||||
row = con.execute("SELECT dst,units,type,ref,wallet_id FROM econ_tx WHERE type='quest' AND ref=?",
|
||||
(ref,)).fetchone()
|
||||
con.commit()
|
||||
except sqlite3.IntegrityError:
|
||||
con.rollback()
|
||||
return 0, "already"
|
||||
except sqlite3.Error:
|
||||
log.exception("daily quest ledger failed uid=%s quest=%s", uid, qid)
|
||||
con.rollback()
|
||||
return 0, "error"
|
||||
finally:
|
||||
con.close()
|
||||
return _credit_ledger_row(bot_db, gw_db, row)
|
||||
|
||||
|
||||
def _kv_set(con, key, value):
|
||||
con.execute("INSERT INTO kv(k,v) VALUES(?,?) ON CONFLICT(k) DO UPDATE SET v=excluded.v",
|
||||
(key, str(value)))
|
||||
|
||||
|
||||
def _streak_milestone(bot_db, gw_db, uid, days, reward_usd, now):
|
||||
prepare(bot_db, gw_db)
|
||||
if not econ_guard.account_eligible(bot_db, uid):
|
||||
return 0, "blocked"
|
||||
type_ = "streak:%d" % days
|
||||
ref = "grant:%d:%d" % (days, int(uid))
|
||||
units = int(reward_usd) * QUOTA_PER_USD
|
||||
existing = _ledger_row(bot_db, type_, ref)
|
||||
wallet = None if existing else econ_guard.resolve_wallet(gw_db, bot_db, uid)
|
||||
if not existing and not wallet:
|
||||
return 0, "wallet"
|
||||
con = _con(bot_db)
|
||||
try:
|
||||
con.execute("BEGIN IMMEDIATE")
|
||||
if not econ_guard.account_eligible_con(con, uid):
|
||||
con.rollback()
|
||||
return 0, "blocked"
|
||||
row = con.execute("SELECT dst,units,type,ref,wallet_id FROM econ_tx WHERE type=? AND ref=?",
|
||||
(type_, ref)).fetchone()
|
||||
if row is None:
|
||||
if con.execute("SELECT 1 FROM econ_grants WHERE uid=? AND code=?",
|
||||
(int(uid), str(days))).fetchone():
|
||||
con.commit()
|
||||
return 0, "already"
|
||||
granted = con.execute("INSERT OR IGNORE INTO econ_grants(uid,code,units,ts) VALUES(?,?,?,?)",
|
||||
(int(uid), str(days), units, _now(now)))
|
||||
if granted.rowcount != 1:
|
||||
con.rollback()
|
||||
return 0, "already"
|
||||
if not wallet:
|
||||
con.rollback()
|
||||
return 0, "wallet"
|
||||
con.execute("INSERT INTO econ_tx(src,dst,units,type,ts,ref,wallet_id) VALUES(?,?,?,?,?,?,?)",
|
||||
(0, int(uid), units, type_, _now(now), ref, int(wallet[0])))
|
||||
_kv_set(con, "ec_streak_aw:%d:%d" % (int(uid), days), "1")
|
||||
row = con.execute("SELECT dst,units,type,ref,wallet_id FROM econ_tx WHERE type=? AND ref=?",
|
||||
(type_, ref)).fetchone()
|
||||
con.commit()
|
||||
except sqlite3.Error:
|
||||
log.exception("streak milestone ledger failed uid=%s days=%s", uid, days)
|
||||
con.rollback()
|
||||
return 0, "error"
|
||||
finally:
|
||||
con.close()
|
||||
return _credit_ledger_row(bot_db, gw_db, row)
|
||||
|
||||
|
||||
def record_checkin(bot_db, gw_db, uid, now=None, source="miniapp"):
|
||||
"""Idempotently apply calendar, streak, weekly and gate effects of one check-in."""
|
||||
uid = int(uid)
|
||||
prepare(bot_db, gw_db)
|
||||
current = _now(now)
|
||||
day = today_iso(current)
|
||||
yesterday = time.strftime("%Y-%m-%d", time.gmtime(current - 86400 + MSK))
|
||||
con = _con(bot_db)
|
||||
milestone = None
|
||||
try:
|
||||
con.execute("BEGIN IMMEDIATE")
|
||||
user = con.execute("SELECT last_checkin FROM users WHERE tg_id=?", (uid,)).fetchone()
|
||||
if not user:
|
||||
con.rollback()
|
||||
con.close()
|
||||
return {"ok": False, "error": "user", "streak": 0}
|
||||
if not econ_guard.account_eligible_con(con, uid):
|
||||
con.rollback()
|
||||
con.close()
|
||||
return {"ok": False, "error": "blocked", "streak": 0}
|
||||
new_calendar = not is_today(user["last_checkin"], current)
|
||||
con.execute("UPDATE users SET last_checkin=?,gate_member_ok=NULL,gate_member_ts=0 "
|
||||
"WHERE tg_id=?", (day, uid))
|
||||
streak_row = con.execute("SELECT v FROM kv WHERE k=?", ("ec_streak:%d" % uid,)).fetchone()
|
||||
try:
|
||||
n, last = str(streak_row[0]).split("|") if streak_row else (0, "")
|
||||
n = int(n)
|
||||
except (TypeError, ValueError):
|
||||
n, last = 0, ""
|
||||
fx_key = "ec_checkin_fx:%d:%s" % (uid, day)
|
||||
fresh_fx = con.execute("INSERT OR IGNORE INTO kv(k,v) VALUES(?,'1')", (fx_key,)).rowcount == 1
|
||||
last_compact = str(last).replace("-", "")
|
||||
day_compact = day.replace("-", "")
|
||||
yesterday_compact = yesterday.replace("-", "")
|
||||
if fresh_fx and last_compact != day_compact:
|
||||
n = n + 1 if last_compact == yesterday_compact else 1
|
||||
_kv_set(con, "ec_streak:%d" % uid, "%d|%s" % (n, day))
|
||||
week = week_key(current)
|
||||
wk_key = "ec_wcin:%d:%s" % (uid, week)
|
||||
wk_row = con.execute("SELECT v FROM kv WHERE k=?", (wk_key,)).fetchone()
|
||||
try:
|
||||
wcin = int(float(wk_row[0])) if wk_row else 0
|
||||
except (TypeError, ValueError):
|
||||
wcin = 0
|
||||
_kv_set(con, wk_key, wcin + 1)
|
||||
milestone = n if n in (7, 30, 100) else None
|
||||
if source == "miniapp":
|
||||
_kv_set(con, "ec_web_checkin:%d:%s" % (uid, day), "1")
|
||||
if fresh_fx and last_compact == day_compact:
|
||||
# A pre-upgrade bot /daily already used its dice; do not offer a second one.
|
||||
_kv_set(con, "ec_dice:%d:%s" % (uid, day), "1")
|
||||
con.commit()
|
||||
except sqlite3.Error:
|
||||
log.exception("checkin state failed uid=%s", uid)
|
||||
con.rollback()
|
||||
con.close()
|
||||
return {"ok": False, "error": "error", "streak": 0}
|
||||
else:
|
||||
con.close()
|
||||
milestone_result = None
|
||||
if milestone:
|
||||
reward = {7: 50, 30: 200, 100: 1000}[milestone]
|
||||
milestone_result = _streak_milestone(bot_db, gw_db, uid, milestone, reward, current)
|
||||
return {"ok": True, "new_calendar": new_calendar, "streak": n,
|
||||
"milestone": milestone, "milestone_result": milestone_result}
|
||||
|
||||
|
||||
def snapshot(bot_db, gw_db, uid, lvl, now=None):
|
||||
current = _now(now)
|
||||
prepare(bot_db, gw_db)
|
||||
day = today(current)
|
||||
mult = multiplier(bot_db, uid, current)
|
||||
with closing(_con(bot_db)) as con:
|
||||
prog = _progress_con(con, uid, current)
|
||||
spent = int(con.execute("SELECT COALESCE(SUM(units),0) FROM econ_tx WHERE type='quest' AND ts>=?",
|
||||
(day_start(current),)).fetchone()[0] or 0)
|
||||
markers = {row[0] for row in con.execute("SELECT k FROM kv WHERE k LIKE ?",
|
||||
("ec_q:%d:%s:%%" % (int(uid), day),)).fetchall()}
|
||||
refs = ["quest:%d:%s:%s" % (int(uid), day, qid) for qid, _, _ in QUESTS.get(int(lvl), QUESTS[1])]
|
||||
ledger = set()
|
||||
if refs:
|
||||
ledger = {row[0] for row in con.execute(
|
||||
"SELECT ref FROM econ_tx WHERE type='quest' AND ref IN (%s)" % ",".join("?" * len(refs)), refs)}
|
||||
payouts = set()
|
||||
if ledger:
|
||||
with closing(_con(gw_db)) as con:
|
||||
payouts = {row[0] for row in con.execute(
|
||||
"SELECT ref FROM econ_payouts WHERE ref IN (%s)" % ",".join("?" * len(ledger)), list(ledger))}
|
||||
quests = []
|
||||
for qid, need, reward in QUESTS.get(int(lvl), QUESTS[1]):
|
||||
marker = "ec_q:%d:%s:%s" % (int(uid), day, qid)
|
||||
ref = "quest:%d:%s:%s" % (int(uid), day, qid)
|
||||
has_ledger = ref in ledger
|
||||
pending = has_ledger and ref not in payouts
|
||||
done = (marker in markers and not has_ledger) or (has_ledger and not pending)
|
||||
units = reward * QUOTA_PER_USD * mult
|
||||
complete = qid == "checkin" or prog.get(qid, 0) >= need
|
||||
quests.append({
|
||||
"id": qid, "title": TITLES[qid], "target": need,
|
||||
"progress": prog.get(qid, 0), "done": done, "pending": pending,
|
||||
"base_reward_usd": reward, "reward_usd": units / QUOTA_PER_USD,
|
||||
"claimable": not done and complete and (pending or spent + units <= QUEST_BUDGET),
|
||||
})
|
||||
return {
|
||||
"day": day, "rank": int(lvl), "multiplier": mult, "quests": quests,
|
||||
"budget_usd": QUEST_BUDGET / QUOTA_PER_USD,
|
||||
"budget_left_usd": max(0, QUEST_BUDGET - spent) / QUOTA_PER_USD,
|
||||
}
|
||||
+359
@@ -0,0 +1,359 @@
|
||||
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)
|
||||
@@ -0,0 +1,129 @@
|
||||
"""Persistent, per-user Telegram reminders shared by bot and Mini App."""
|
||||
from contextlib import closing
|
||||
import math
|
||||
import sqlite3
|
||||
import time
|
||||
from typing import Any
|
||||
import uuid
|
||||
|
||||
|
||||
MAX_PENDING = 100
|
||||
MAX_ATTEMPTS = 5
|
||||
PUBLIC_FIELDS = ("id", "text", "due_at", "status", "created_at", "sent_at", "last_error")
|
||||
|
||||
|
||||
def _connect(db_path):
|
||||
con = sqlite3.connect(db_path, timeout=10)
|
||||
con.row_factory = sqlite3.Row
|
||||
return con
|
||||
|
||||
|
||||
def init_db(db_path):
|
||||
with closing(_connect(db_path)) as con:
|
||||
con.execute("""CREATE TABLE IF NOT EXISTS wa_reminders (
|
||||
id INTEGER PRIMARY KEY AUTOINCREMENT,
|
||||
uid INTEGER NOT NULL,
|
||||
text TEXT NOT NULL,
|
||||
due_at INTEGER NOT NULL,
|
||||
status TEXT NOT NULL DEFAULT 'pending',
|
||||
created_at INTEGER NOT NULL,
|
||||
sent_at INTEGER,
|
||||
last_error TEXT,
|
||||
attempts INTEGER NOT NULL DEFAULT 0,
|
||||
lease_until INTEGER NOT NULL DEFAULT 0,
|
||||
claim_token TEXT
|
||||
)""")
|
||||
con.execute("CREATE INDEX IF NOT EXISTS wa_reminders_due ON wa_reminders(status, due_at)")
|
||||
con.execute("CREATE INDEX IF NOT EXISTS wa_reminders_owner ON wa_reminders(uid, created_at)")
|
||||
con.commit()
|
||||
|
||||
|
||||
def _public(row) -> dict[str, Any]:
|
||||
return {key: row[key] for key in PUBLIC_FIELDS}
|
||||
|
||||
|
||||
def create_reminder(db_path, uid, text, due_at, now=None):
|
||||
now = int(time.time() if now is None else now)
|
||||
if not isinstance(uid, int) or isinstance(uid, bool) or uid <= 0:
|
||||
raise ValueError("invalid_user")
|
||||
if not isinstance(text, str) or not text.strip() or len(text.strip()) > 1000:
|
||||
raise ValueError("invalid_text")
|
||||
if isinstance(due_at, bool) or not isinstance(due_at, (int, float)) or not math.isfinite(due_at):
|
||||
raise ValueError("invalid_due")
|
||||
due_at = int(due_at)
|
||||
if not now + 30 <= due_at <= now + 366 * 86400:
|
||||
raise ValueError("invalid_due")
|
||||
with closing(_connect(db_path)) as con:
|
||||
con.execute("BEGIN IMMEDIATE")
|
||||
count = con.execute("SELECT COUNT(*) FROM wa_reminders WHERE uid=? AND status IN ('pending','sending')", (uid,)).fetchone()[0]
|
||||
if count >= MAX_PENDING:
|
||||
raise ValueError("too_many")
|
||||
cur = con.execute("INSERT INTO wa_reminders(uid,text,due_at,created_at) VALUES (?,?,?,?)",
|
||||
(uid, text.strip(), due_at, now))
|
||||
row = con.execute("SELECT * FROM wa_reminders WHERE id=?", (cur.lastrowid,)).fetchone()
|
||||
con.commit()
|
||||
return _public(row)
|
||||
|
||||
|
||||
def list_reminders(db_path, uid, limit=50):
|
||||
limit = max(1, min(100, int(limit)))
|
||||
with closing(_connect(db_path)) as con:
|
||||
rows = con.execute("SELECT * FROM wa_reminders WHERE uid=? ORDER BY "
|
||||
"CASE WHEN status IN ('pending','sending') THEN 0 ELSE 1 END, "
|
||||
"CASE WHEN status IN ('pending','sending') THEN due_at ELSE -created_at END, id DESC LIMIT ?",
|
||||
(uid, limit)).fetchall()
|
||||
return [_public(row) for row in rows]
|
||||
|
||||
|
||||
def cancel_reminder(db_path, uid, reminder_id):
|
||||
if not isinstance(reminder_id, int) or isinstance(reminder_id, bool) or reminder_id <= 0:
|
||||
raise ValueError("invalid_id")
|
||||
with closing(_connect(db_path)) as con:
|
||||
changed = con.execute("UPDATE wa_reminders SET status='cancelled' WHERE id=? AND uid=? AND status='pending'",
|
||||
(reminder_id, uid)).rowcount
|
||||
con.commit()
|
||||
return changed == 1
|
||||
|
||||
|
||||
def claim_due(db_path, now=None, limit=20, lease_seconds=120):
|
||||
"""Claim due work atomically; expired leases recover after process restarts."""
|
||||
now = int(time.time() if now is None else now)
|
||||
limit = max(1, min(20, int(limit)))
|
||||
with closing(_connect(db_path)) as con:
|
||||
con.execute("BEGIN IMMEDIATE")
|
||||
con.execute("UPDATE wa_reminders SET status=CASE WHEN attempts>=? THEN 'failed' ELSE 'pending' END, "
|
||||
"claim_token=NULL, lease_until=0, last_error='delivery_interrupted' "
|
||||
"WHERE status='sending' AND lease_until<=?", (MAX_ATTEMPTS, now))
|
||||
rows = con.execute("SELECT * FROM wa_reminders WHERE status='pending' AND due_at<=? "
|
||||
"AND attempts<? ORDER BY due_at,id LIMIT ?", (now, MAX_ATTEMPTS, limit)).fetchall()
|
||||
result = []
|
||||
for row in rows:
|
||||
token = uuid.uuid4().hex
|
||||
con.execute("UPDATE wa_reminders SET status='sending', attempts=attempts+1, lease_until=?, claim_token=? WHERE id=?",
|
||||
(now + max(30, int(lease_seconds)), token, row["id"]))
|
||||
result.append({**dict(row), "status": "sending", "attempts": row["attempts"] + 1, "claim_token": token})
|
||||
con.commit()
|
||||
return result
|
||||
|
||||
|
||||
def finish_delivery(db_path, reminder_id, claim_token, *, error=None, permanent=False, retry_after=None, now=None):
|
||||
"""Only the current delivery lease may complete or reschedule a reminder."""
|
||||
now = int(time.time() if now is None else now)
|
||||
with closing(_connect(db_path)) as con:
|
||||
con.execute("BEGIN IMMEDIATE")
|
||||
row = con.execute("SELECT attempts FROM wa_reminders WHERE id=? AND status='sending' AND claim_token=?",
|
||||
(reminder_id, claim_token)).fetchone()
|
||||
if row is None:
|
||||
return False
|
||||
if error is None:
|
||||
con.execute("UPDATE wa_reminders SET status='sent',sent_at=?,last_error=NULL,lease_until=0,claim_token=NULL WHERE id=?",
|
||||
(now, reminder_id))
|
||||
else:
|
||||
failed = permanent or row["attempts"] >= MAX_ATTEMPTS
|
||||
delay = min(3600, max(15, int(retry_after or (30 * 2 ** row["attempts"]))))
|
||||
# Store error classes/codes, never exception bodies (which can contain credentials).
|
||||
code = ''.join(c for c in str(error) if c.isalnum() or c == '_')[:80] or 'delivery_failed'
|
||||
con.execute("UPDATE wa_reminders SET status=?,due_at=?,last_error=?,lease_until=0,claim_token=NULL WHERE id=?",
|
||||
('failed' if failed else 'pending', now + delay, code, reminder_id))
|
||||
con.commit()
|
||||
return True
|
||||
@@ -0,0 +1,696 @@
|
||||
"""Bounded admission and model health for existing async request factories.
|
||||
|
||||
This module never retries, spawns a worker, or changes a factory's result/error.
|
||||
Use one controller on one event loop; factories must cooperate with cancellation.
|
||||
Model names must be trusted, nonsecret identifiers. External reports inside an
|
||||
owned lease are coalesced into that run's outcome, including returned partials.
|
||||
|
||||
Priority 3 is highest. Waiting requests gain one priority level per aging period;
|
||||
FIFO breaks ties. A queued request survives a subsequently opened circuit without
|
||||
holding a permit. New requests fail fast while the circuit is open/probing.
|
||||
"""
|
||||
from __future__ import annotations
|
||||
|
||||
import asyncio
|
||||
import math
|
||||
import time
|
||||
from collections import OrderedDict, deque
|
||||
from contextvars import ContextVar
|
||||
from dataclasses import dataclass, field
|
||||
from typing import Awaitable, Callable, TypeVar
|
||||
|
||||
__all__ = (
|
||||
"StabilityError", "QueueFull", "DeadlineExceeded", "CircuitOpen",
|
||||
"StabilityController",
|
||||
)
|
||||
|
||||
T = TypeVar("T")
|
||||
_MAX_MODELS = 128
|
||||
_MAX_QUEUE = 64
|
||||
_MAX_USER_QUEUE = 2
|
||||
_MAX_MODEL_LENGTH = 128
|
||||
_RECENT_LIMIT = 128
|
||||
_RECOVERY_SUCCESSES = 8
|
||||
_FAILURE_STATUSES = frozenset((429, 500, 502, 503, 504))
|
||||
_OUTCOMES = ("success", "partial", "error", "dependency_failure", "deadline_exceeded", "cancelled")
|
||||
_REJECTS = ("queue_full", "circuit_open")
|
||||
|
||||
|
||||
class StabilityError(RuntimeError):
|
||||
"""A terminal admission/deadline error, safe to display without its cause."""
|
||||
|
||||
terminal = True
|
||||
stability_code = "stability_error"
|
||||
public_message = "Не удалось выполнить запрос. Попробуйте позже."
|
||||
|
||||
def __init__(self) -> None:
|
||||
super().__init__(self.public_message)
|
||||
|
||||
|
||||
class QueueFull(StabilityError):
|
||||
stability_code = "queue_full"
|
||||
public_message = "Сейчас слишком много запросов. Попробуйте позже."
|
||||
|
||||
|
||||
class DeadlineExceeded(StabilityError):
|
||||
stability_code = "deadline_exceeded"
|
||||
public_message = "Время ожидания запроса истекло. Попробуйте позже."
|
||||
|
||||
|
||||
class CircuitOpen(StabilityError):
|
||||
stability_code = "circuit_open"
|
||||
public_message = "Модель временно недоступна. Попробуйте позже."
|
||||
|
||||
|
||||
def _counts(keys: tuple[str, ...]) -> dict[str, int]:
|
||||
return dict.fromkeys(keys, 0)
|
||||
|
||||
|
||||
def _positive_int(name: str, value: int, maximum: int | None = None) -> int:
|
||||
if isinstance(value, bool) or not isinstance(value, int) or value <= 0:
|
||||
raise ValueError(f"{name} must be a positive integer")
|
||||
if maximum is not None and value > maximum:
|
||||
raise ValueError(f"{name} must not exceed {maximum}")
|
||||
return value
|
||||
|
||||
|
||||
def _positive_seconds(name: str, value: float) -> float:
|
||||
if isinstance(value, bool) or not isinstance(value, (int, float)):
|
||||
raise ValueError(f"{name} must be finite and positive")
|
||||
try:
|
||||
result = float(value)
|
||||
except (OverflowError, ValueError) as exc:
|
||||
raise ValueError(f"{name} must be finite and positive") from exc
|
||||
if not math.isfinite(result) or result <= 0:
|
||||
raise ValueError(f"{name} must be finite and positive")
|
||||
return result
|
||||
|
||||
|
||||
def _model_name(model: str) -> str:
|
||||
if (not isinstance(model, str) or not model or len(model) > _MAX_MODEL_LENGTH
|
||||
or model.isspace() or any(ord(char) < 32 for char in model)):
|
||||
raise ValueError("model must be a nonempty identifier of at most 128 characters")
|
||||
return model
|
||||
|
||||
|
||||
def _dependency_failure(error: BaseException) -> bool:
|
||||
"""Only explicit upstream evidence, never a local or delivery timeout."""
|
||||
if isinstance(error, StabilityError):
|
||||
return False
|
||||
try:
|
||||
status = getattr(error, "upstream_status", None)
|
||||
if status is not None:
|
||||
# A definite auth/input/billing/identity status wins over a marker.
|
||||
return (not isinstance(status, bool) and isinstance(status, int)
|
||||
and status in _FAILURE_STATUSES)
|
||||
return getattr(error, "stability_dependency_failure", False) is True
|
||||
except Exception:
|
||||
# A broken exception attribute must never replace the original error.
|
||||
return False
|
||||
|
||||
|
||||
@dataclass(slots=True)
|
||||
class _Sample:
|
||||
queue_seconds: float
|
||||
latency_seconds: float | None
|
||||
|
||||
|
||||
@dataclass(slots=True)
|
||||
class _Model:
|
||||
name: str
|
||||
limit: int
|
||||
active: int = 0
|
||||
queued: int = 0
|
||||
circuit_until: float | None = None
|
||||
probe_active: bool = False
|
||||
epoch: int = 0
|
||||
success_streak: int = 0
|
||||
outcomes: dict[str, int] = field(default_factory=lambda: _counts(_OUTCOMES))
|
||||
rejects: dict[str, int] = field(default_factory=lambda: _counts(_REJECTS))
|
||||
recent: deque[_Sample] = field(default_factory=lambda: deque(maxlen=_RECENT_LIMIT))
|
||||
|
||||
|
||||
@dataclass(slots=True)
|
||||
class _Lease:
|
||||
controller: StabilityController
|
||||
state: _Model
|
||||
owner: asyncio.Task
|
||||
user_id: int
|
||||
deadline: float
|
||||
loop_deadline: float
|
||||
epoch: int
|
||||
probe: bool
|
||||
started_at: float | None = None
|
||||
released: bool = False
|
||||
deadline_failure: bool = False
|
||||
reported_outcome: str | None = None
|
||||
timeout_scope: asyncio.Timeout | None = None
|
||||
|
||||
|
||||
@dataclass(slots=True, eq=False)
|
||||
class _Request:
|
||||
state: _Model
|
||||
owner: asyncio.Task
|
||||
user_id: int
|
||||
priority: int
|
||||
sequence: int
|
||||
enqueued_at: float
|
||||
deadline: float
|
||||
loop_deadline: float
|
||||
future: asyncio.Future[_Lease]
|
||||
queued: bool = False
|
||||
lease: _Lease | None = None
|
||||
finished: bool = False
|
||||
|
||||
|
||||
# Context is inherited by child tasks, but every lookup ALSO checks task identity.
|
||||
_LEASES: ContextVar[tuple[_Lease, ...]] = ContextVar("request_stability_leases", default=())
|
||||
|
||||
|
||||
def _timings(samples: deque[_Sample]) -> dict[str, float | int | None]:
|
||||
queues = sorted(sample.queue_seconds for sample in samples)
|
||||
latencies = sorted(sample.latency_seconds for sample in samples
|
||||
if sample.latency_seconds is not None)
|
||||
|
||||
def percentile(values: list[float], fraction: float) -> float | None:
|
||||
# Nearest-rank percentiles; no synthetic observations when empty.
|
||||
return values[max(0, math.ceil(len(values) * fraction) - 1)] if values else None
|
||||
|
||||
return {
|
||||
"recent_samples": len(samples),
|
||||
"latency_p50_seconds": percentile(latencies, 0.50),
|
||||
"latency_p95_seconds": percentile(latencies, 0.95),
|
||||
"queue_p50_seconds": percentile(queues, 0.50),
|
||||
"queue_p95_seconds": percentile(queues, 0.95),
|
||||
}
|
||||
|
||||
|
||||
class StabilityController:
|
||||
"""Single-event-loop scheduler; all state transitions are synchronous.
|
||||
|
||||
There is deliberately no admission lock held over an await. Background user
|
||||
0 is exempt from both user caps, but not global/model capacity or global queue.
|
||||
Nested calls in the same task/model reuse one lease and can shorten, never
|
||||
extend, its deadline. Different-model nesting needs a separate permit.
|
||||
"""
|
||||
|
||||
def __init__(self, global_limit: int = 24, model_limit: int = 4,
|
||||
user_limit: int = 1, queue_limit: int = 64,
|
||||
aging_seconds: float = 15.0, circuit_seconds: float = 20.0,
|
||||
clock: Callable[[], float] = time.monotonic) -> None:
|
||||
self.global_limit = _positive_int("global_limit", global_limit)
|
||||
self.model_limit = _positive_int("model_limit", model_limit)
|
||||
self.user_limit = _positive_int("user_limit", user_limit)
|
||||
self.queue_limit = _positive_int("queue_limit", queue_limit, _MAX_QUEUE)
|
||||
self.aging_seconds = _positive_seconds("aging_seconds", aging_seconds)
|
||||
self.circuit_seconds = _positive_seconds("circuit_seconds", circuit_seconds)
|
||||
if not callable(clock):
|
||||
raise ValueError("clock must be callable")
|
||||
self._clock = clock
|
||||
self._now() # Reject an invalid clock before any admission is possible.
|
||||
self._loop: asyncio.AbstractEventLoop | None = None
|
||||
self._wakeup: asyncio.TimerHandle | None = None
|
||||
self._models: OrderedDict[str, _Model] = OrderedDict()
|
||||
self._waiting: list[_Request] = []
|
||||
self._active = 0
|
||||
self._users_active: dict[int, int] = {}
|
||||
self._users_queued: dict[int, int] = {}
|
||||
self._sequence = 0
|
||||
self._outcomes = _counts(_OUTCOMES)
|
||||
self._rejects = _counts(_REJECTS)
|
||||
# Report paths run inside exception handlers; they must never raise.
|
||||
self._dropped_reports = 0
|
||||
self._recent: deque[_Sample] = deque(maxlen=_RECENT_LIMIT)
|
||||
|
||||
def _now(self) -> float:
|
||||
value = self._clock()
|
||||
if isinstance(value, bool) or not isinstance(value, (int, float)):
|
||||
raise ValueError("clock must return a finite monotonic number")
|
||||
try:
|
||||
value = float(value)
|
||||
except (OverflowError, ValueError) as exc:
|
||||
raise ValueError("clock must return a finite monotonic number") from exc
|
||||
if not math.isfinite(value):
|
||||
raise ValueError("clock must return a finite monotonic number")
|
||||
return value
|
||||
|
||||
def _check_loop(self) -> None:
|
||||
if self._loop is not None:
|
||||
try:
|
||||
loop = asyncio.get_running_loop()
|
||||
except RuntimeError as exc:
|
||||
raise RuntimeError("controller must be used on its owning event loop") from exc
|
||||
if loop is not self._loop:
|
||||
raise RuntimeError("controller cannot be shared across event loops")
|
||||
|
||||
def _bind_loop(self) -> asyncio.AbstractEventLoop:
|
||||
self._check_loop()
|
||||
loop = asyncio.get_running_loop()
|
||||
if self._loop is None:
|
||||
self._loop = loop
|
||||
return loop
|
||||
|
||||
def _reject(self, code: str, state: _Model | None = None) -> None:
|
||||
self._rejects[code] += 1
|
||||
if state is not None:
|
||||
state.rejects[code] += 1
|
||||
raise QueueFull() if code == "queue_full" else CircuitOpen()
|
||||
|
||||
def _state(self, model: str, now: float) -> _Model:
|
||||
state = self._models.get(model)
|
||||
if state is not None:
|
||||
self._models.move_to_end(model)
|
||||
return state
|
||||
if len(self._models) >= _MAX_MODELS:
|
||||
# In-flight/queued states and unexpired protection cannot be evicted.
|
||||
victim = next((name for name, item in self._models.items()
|
||||
if item.active == 0 and item.queued == 0
|
||||
and (item.circuit_until is None or item.circuit_until <= now)), None)
|
||||
if victim is None:
|
||||
self._reject("queue_full")
|
||||
del self._models[victim]
|
||||
state = _Model(model, self.model_limit)
|
||||
self._models[model] = state
|
||||
return state
|
||||
|
||||
def _report_state(self, model: str, now: float) -> _Model | None:
|
||||
"""Reports are called from exception handlers; a full table drops the sample."""
|
||||
try:
|
||||
return self._state(model, now)
|
||||
except QueueFull:
|
||||
self._dropped_reports += 1
|
||||
return None
|
||||
|
||||
def _expired(self, deadline: float, loop_deadline: float, now: float) -> bool:
|
||||
return now >= deadline or self._loop.time() >= loop_deadline
|
||||
|
||||
def _ready(self, state: _Model, user_id: int, now: float) -> bool:
|
||||
if self._active >= self.global_limit or state.active >= state.limit:
|
||||
return False
|
||||
if user_id != 0 and self._users_active.get(user_id, 0) >= self.user_limit:
|
||||
return False
|
||||
if state.circuit_until is not None:
|
||||
return (now >= state.circuit_until and not state.probe_active
|
||||
and state.active == 0)
|
||||
return True
|
||||
|
||||
def _unqueue(self, request: _Request) -> None:
|
||||
if not request.queued:
|
||||
return
|
||||
request.queued = False
|
||||
self._waiting.remove(request)
|
||||
request.state.queued -= 1
|
||||
count = self._users_queued[request.user_id] - 1
|
||||
if count:
|
||||
self._users_queued[request.user_id] = count
|
||||
else:
|
||||
del self._users_queued[request.user_id]
|
||||
|
||||
def _grant(self, request: _Request) -> None:
|
||||
state = request.state
|
||||
self._unqueue(request)
|
||||
probe = state.circuit_until is not None
|
||||
if probe:
|
||||
state.probe_active = True
|
||||
lease = _Lease(self, state, request.owner, request.user_id,
|
||||
request.deadline, request.loop_deadline, state.epoch, probe)
|
||||
request.lease = lease
|
||||
self._active += 1
|
||||
state.active += 1
|
||||
if request.user_id != 0:
|
||||
self._users_active[request.user_id] = self._users_active.get(request.user_id, 0) + 1
|
||||
request.future.set_result(lease)
|
||||
|
||||
def _rank(self, request: _Request, now: float) -> tuple[int, int]:
|
||||
elapsed = max(0.0, now - request.enqueued_at)
|
||||
# Saturate before division, including for tiny valid aging periods.
|
||||
age = 3 if elapsed >= 3 * self.aging_seconds else int(elapsed / self.aging_seconds)
|
||||
return -min(3, request.priority + age), request.sequence
|
||||
|
||||
def _dispatch(self, now: float) -> None:
|
||||
# Removing every expired waiter first prevents it consuming a released slot.
|
||||
for request in tuple(self._waiting):
|
||||
if request.future.done():
|
||||
self._unqueue(request)
|
||||
elif self._expired(request.deadline, request.loop_deadline, now):
|
||||
self._unqueue(request)
|
||||
request.future.set_exception(DeadlineExceeded())
|
||||
while self._active < self.global_limit:
|
||||
ready = (request for request in self._waiting
|
||||
if self._ready(request.state, request.user_id, now))
|
||||
request = min(ready, key=lambda item: self._rank(item, now), default=None)
|
||||
if request is None:
|
||||
break
|
||||
self._grant(request)
|
||||
self._schedule_wakeup(now)
|
||||
|
||||
def _schedule_wakeup(self, now: float) -> None:
|
||||
if self._wakeup is not None:
|
||||
self._wakeup.cancel()
|
||||
self._wakeup = None
|
||||
if self._loop is None or not self._waiting:
|
||||
return
|
||||
times = [request.state.circuit_until for request in self._waiting
|
||||
if request.state.circuit_until is not None
|
||||
and request.state.circuit_until > now]
|
||||
if times:
|
||||
# A timer is needed only for existing cooldown waiters, never while idle.
|
||||
self._wakeup = self._loop.call_later(min(times) - now, self._on_wakeup)
|
||||
|
||||
def _on_wakeup(self) -> None:
|
||||
self._wakeup = None
|
||||
self._dispatch(self._now())
|
||||
|
||||
def _submit(self, model: str, owner: asyncio.Task, user_id: int, priority: int,
|
||||
deadline: float, loop_deadline: float, now: float) -> _Request:
|
||||
self._dispatch(now)
|
||||
state = self._state(model, now)
|
||||
if state.circuit_until is not None and (now < state.circuit_until or state.probe_active):
|
||||
self._reject("circuit_open", state)
|
||||
self._sequence += 1
|
||||
request = _Request(state, owner, user_id, priority, self._sequence, now,
|
||||
deadline, loop_deadline, self._loop.create_future())
|
||||
if self._expired(deadline, loop_deadline, now):
|
||||
request.future.set_exception(DeadlineExceeded())
|
||||
elif self._ready(state, user_id, now):
|
||||
self._grant(request)
|
||||
else:
|
||||
if (len(self._waiting) >= self.queue_limit
|
||||
or (user_id != 0 and self._users_queued.get(user_id, 0) >= _MAX_USER_QUEUE)):
|
||||
self._reject("queue_full", state)
|
||||
request.queued = True
|
||||
self._waiting.append(request)
|
||||
state.queued += 1
|
||||
self._users_queued[user_id] = self._users_queued.get(user_id, 0) + 1
|
||||
self._schedule_wakeup(now)
|
||||
return request
|
||||
|
||||
def _owned_lease(self, model: str) -> _Lease | None:
|
||||
try:
|
||||
owner = asyncio.current_task()
|
||||
except RuntimeError:
|
||||
return None
|
||||
return next((lease for lease in reversed(_LEASES.get())
|
||||
if lease.controller is self and lease.owner is owner
|
||||
and lease.state.name == model and not lease.released), None)
|
||||
|
||||
|
||||
def _health_failure(self, state: _Model, now: float) -> None:
|
||||
state.epoch += 1
|
||||
state.circuit_until = now + self.circuit_seconds
|
||||
state.probe_active = False
|
||||
state.success_streak = 0
|
||||
state.limit = max(1, state.limit // 2)
|
||||
|
||||
def _health_success(self, state: _Model, lease: _Lease | None = None) -> None:
|
||||
if lease is not None:
|
||||
# An older in-flight success cannot undo a newer confirmed failure.
|
||||
if lease.epoch != state.epoch:
|
||||
return
|
||||
if state.circuit_until is not None and not lease.probe:
|
||||
return
|
||||
state.circuit_until = None
|
||||
state.probe_active = False
|
||||
if state.limit < self.model_limit:
|
||||
state.success_streak += 1
|
||||
if state.success_streak >= _RECOVERY_SUCCESSES:
|
||||
state.limit += 1
|
||||
state.success_streak = 0
|
||||
else:
|
||||
state.success_streak = 0
|
||||
|
||||
def _finish(self, request: _Request, outcome: str, dependency_failure: bool) -> None:
|
||||
if request.finished:
|
||||
return
|
||||
request.finished = True
|
||||
now = self._now()
|
||||
self._unqueue(request)
|
||||
if not request.future.done():
|
||||
request.future.cancel()
|
||||
elif not request.future.cancelled():
|
||||
request.future.exception()
|
||||
lease = request.lease
|
||||
state = request.state
|
||||
if lease is not None and lease.reported_outcome == "dependency_failure":
|
||||
# The explicit report already opened/reduced health exactly once.
|
||||
dependency_failure = False
|
||||
if outcome in ("success", "error", "dependency_failure"):
|
||||
outcome = "dependency_failure"
|
||||
elif lease is not None and lease.reported_outcome == "partial" and outcome in ("success", "error"):
|
||||
outcome = "partial"
|
||||
elif lease is not None and lease.reported_outcome == "error" and outcome == "success":
|
||||
outcome = "error"
|
||||
if lease is not None and not lease.released:
|
||||
lease.released = True
|
||||
self._active -= 1
|
||||
state.active -= 1
|
||||
if lease.user_id != 0:
|
||||
count = self._users_active[lease.user_id] - 1
|
||||
if count:
|
||||
self._users_active[lease.user_id] = count
|
||||
else:
|
||||
del self._users_active[lease.user_id]
|
||||
if lease.probe and lease.epoch == state.epoch:
|
||||
state.probe_active = False
|
||||
if dependency_failure:
|
||||
self._health_failure(state, now)
|
||||
elif outcome == "success":
|
||||
self._health_success(state, lease)
|
||||
elif outcome in ("error", "partial"):
|
||||
state.success_streak = 0
|
||||
self._outcomes[outcome] += 1
|
||||
state.outcomes[outcome] += 1
|
||||
started = lease.started_at if lease is not None else None
|
||||
sample = _Sample(max(0.0, (started if started is not None else now) - request.enqueued_at),
|
||||
max(0.0, now - started) if started is not None else None)
|
||||
state.recent.append(sample)
|
||||
self._recent.append(sample)
|
||||
self._dispatch(now)
|
||||
|
||||
async def _nested(self, lease: _Lease, factory: Callable[[], Awaitable[T]],
|
||||
deadline: float, loop_deadline: float) -> T:
|
||||
# A shorter nested budget constrains the whole lease, not just its wrapper.
|
||||
lease.deadline = min(lease.deadline, deadline)
|
||||
lease.loop_deadline = min(lease.loop_deadline, loop_deadline)
|
||||
if (lease.timeout_scope.expired()
|
||||
or self._expired(lease.deadline, lease.loop_deadline, self._now())):
|
||||
lease.deadline_failure = True
|
||||
raise DeadlineExceeded()
|
||||
lease.timeout_scope.reschedule(lease.loop_deadline)
|
||||
scope = asyncio.timeout_at(lease.loop_deadline)
|
||||
try:
|
||||
async with scope:
|
||||
if self._expired(lease.deadline, lease.loop_deadline, self._now()):
|
||||
lease.deadline_failure = True
|
||||
raise DeadlineExceeded()
|
||||
result = await factory()
|
||||
if scope.expired() or self._expired(lease.deadline, lease.loop_deadline, self._now()):
|
||||
lease.deadline_failure = True
|
||||
if (getattr(result, "stability_partial", False) is True
|
||||
and lease.reported_outcome in ("partial", "dependency_failure")):
|
||||
return result
|
||||
raise DeadlineExceeded()
|
||||
return result
|
||||
except TimeoutError as exc:
|
||||
if scope.expired():
|
||||
lease.deadline_failure = True
|
||||
raise DeadlineExceeded() from exc
|
||||
raise
|
||||
|
||||
async def run(self, model: str, factory: Callable[[], Awaitable[T]], *,
|
||||
user_id: int = 0, priority: int = 0, timeout: float = 180.0) -> T:
|
||||
"""Run exactly once within one queue+execution monotonic deadline.
|
||||
|
||||
Only this method's own deadline becomes DeadlineExceeded. Factory-raised
|
||||
exceptions retain their identity; upstream_status and the explicit
|
||||
stability_dependency_failure marker control health classification.
|
||||
"""
|
||||
model = _model_name(model)
|
||||
timeout = _positive_seconds("timeout", timeout)
|
||||
if not callable(factory):
|
||||
raise ValueError("factory must be callable")
|
||||
if isinstance(user_id, bool) or not isinstance(user_id, int):
|
||||
raise ValueError("user_id must be an integer")
|
||||
if isinstance(priority, bool) or not isinstance(priority, int):
|
||||
raise ValueError("priority must be an integer")
|
||||
priority = min(3, max(0, priority))
|
||||
loop = self._bind_loop()
|
||||
owner = asyncio.current_task()
|
||||
now = self._now()
|
||||
deadline, loop_deadline = now + timeout, loop.time() + timeout
|
||||
if not math.isfinite(deadline) or not math.isfinite(loop_deadline):
|
||||
raise ValueError("timeout produces a nonfinite deadline")
|
||||
owned = tuple(lease for lease in _LEASES.get()
|
||||
if lease.controller is self and lease.owner is owner and not lease.released)
|
||||
for lease in owned:
|
||||
deadline = min(deadline, lease.deadline)
|
||||
loop_deadline = min(loop_deadline, lease.loop_deadline)
|
||||
same = next((lease for lease in reversed(owned) if lease.state.name == model), None)
|
||||
if same is not None:
|
||||
return await self._nested(same, factory, deadline, loop_deadline)
|
||||
if (user_id != 0
|
||||
and sum(lease.user_id == user_id for lease in owned) >= self.user_limit):
|
||||
# Waiting on our own user slot can never make progress.
|
||||
self._reject("queue_full", self._models.get(model))
|
||||
|
||||
request: _Request | None = None
|
||||
outcome = "error"
|
||||
dependency_failure = False
|
||||
scope = asyncio.timeout_at(loop_deadline)
|
||||
try:
|
||||
async with scope:
|
||||
request = self._submit(model, owner, user_id, priority,
|
||||
deadline, loop_deadline, now)
|
||||
lease = await asyncio.shield(request.future)
|
||||
if owner.cancelling():
|
||||
raise asyncio.CancelledError()
|
||||
if self._expired(lease.deadline, lease.loop_deadline, self._now()):
|
||||
raise DeadlineExceeded()
|
||||
lease.started_at = self._now()
|
||||
lease.timeout_scope = scope
|
||||
# Do not accumulate inherited parent-task leases in descendants.
|
||||
current = tuple(item for item in _LEASES.get()
|
||||
if item.owner is owner and not item.released)
|
||||
token = _LEASES.set(current + (lease,))
|
||||
try:
|
||||
result = await factory()
|
||||
if scope.expired() or self._expired(lease.deadline, lease.loop_deadline, self._now()):
|
||||
lease.deadline_failure = True
|
||||
if (getattr(result, "stability_partial", False) is True
|
||||
and lease.reported_outcome in ("partial", "dependency_failure")):
|
||||
outcome = "success"
|
||||
return result
|
||||
raise DeadlineExceeded()
|
||||
outcome = "success"
|
||||
return result
|
||||
finally:
|
||||
_LEASES.reset(token)
|
||||
except TimeoutError as exc:
|
||||
if scope.expired():
|
||||
outcome = "deadline_exceeded"
|
||||
dependency_failure = False
|
||||
raise DeadlineExceeded() from exc
|
||||
dependency_failure = _dependency_failure(exc)
|
||||
outcome = "dependency_failure" if dependency_failure else "error"
|
||||
raise
|
||||
except DeadlineExceeded:
|
||||
outcome = "deadline_exceeded"
|
||||
dependency_failure = False
|
||||
raise
|
||||
except asyncio.CancelledError:
|
||||
outcome = "cancelled"
|
||||
raise
|
||||
except BaseException as exc:
|
||||
dependency_failure = _dependency_failure(exc)
|
||||
outcome = "dependency_failure" if dependency_failure else "error"
|
||||
raise
|
||||
finally:
|
||||
if request is not None:
|
||||
self._finish(request, outcome, dependency_failure)
|
||||
|
||||
def report_partial(self, model: str) -> None:
|
||||
"""Record incomplete delivery without inventing an upstream health failure."""
|
||||
self._check_loop()
|
||||
model = _model_name(model)
|
||||
state = self._report_state(model, self._now())
|
||||
if state is None:
|
||||
return
|
||||
lease = self._owned_lease(model)
|
||||
if lease is not None:
|
||||
if lease.reported_outcome != "dependency_failure":
|
||||
lease.reported_outcome = "partial"
|
||||
else:
|
||||
state.outcomes["partial"] += 1
|
||||
self._outcomes["partial"] += 1
|
||||
state.success_streak = 0
|
||||
|
||||
def report_failure(self, model: str, status: int | None = None) -> None:
|
||||
"""Record a confirmed observation; None means dependency/transport failure.
|
||||
|
||||
An owner-task/model report is coalesced into the lease's final outcome;
|
||||
confirmed failures affect health immediately, without counting twice.
|
||||
Outside a lease, reports add an outcome but no invented latency sample.
|
||||
Nonfailure HTTP statuses never open a circuit.
|
||||
"""
|
||||
self._check_loop()
|
||||
model = _model_name(model)
|
||||
if status is not None and (isinstance(status, bool) or not isinstance(status, int)
|
||||
or not 100 <= status <= 599):
|
||||
raise ValueError("status must be an HTTP status integer or None")
|
||||
now = self._now()
|
||||
state = self._report_state(model, now)
|
||||
if state is None:
|
||||
return
|
||||
confirmed = status is None or status in _FAILURE_STATUSES
|
||||
outcome = "dependency_failure" if confirmed else "error"
|
||||
lease = self._owned_lease(model)
|
||||
if lease is not None:
|
||||
if confirmed and lease.reported_outcome != "dependency_failure":
|
||||
lease.reported_outcome = "dependency_failure"
|
||||
self._health_failure(state, now)
|
||||
elif not confirmed and lease.reported_outcome is None:
|
||||
lease.reported_outcome = "error"
|
||||
state.success_streak = 0
|
||||
self._dispatch(now)
|
||||
return
|
||||
state.outcomes[outcome] += 1
|
||||
self._outcomes[outcome] += 1
|
||||
if confirmed:
|
||||
self._health_failure(state, now)
|
||||
else:
|
||||
state.success_streak = 0
|
||||
self._dispatch(now)
|
||||
|
||||
def report_success(self, model: str) -> None:
|
||||
"""Record external success; owner-lease success is accounted on completion."""
|
||||
self._check_loop()
|
||||
model = _model_name(model)
|
||||
if self._owned_lease(model) is not None:
|
||||
# In particular, never undo an explicitly reported partial failure.
|
||||
return
|
||||
now = self._now()
|
||||
state = self._report_state(model, now)
|
||||
if state is None:
|
||||
return
|
||||
state.outcomes["success"] += 1
|
||||
self._outcomes["success"] += 1
|
||||
# An unowned report cannot bypass cooldown or the exclusive recovery probe.
|
||||
if state.circuit_until is None:
|
||||
self._health_success(state)
|
||||
self._dispatch(now)
|
||||
|
||||
def snapshot(self) -> dict:
|
||||
"""Return detached, bounded nonsecret aggregates (seconds; no TPS estimate)."""
|
||||
self._check_loop()
|
||||
now = self._now()
|
||||
models = {}
|
||||
for name, state in self._models.items():
|
||||
circuit = ("closed" if state.circuit_until is None else
|
||||
"open" if now < state.circuit_until else "half_open")
|
||||
models[name] = {
|
||||
"active": state.active,
|
||||
"queued": state.queued,
|
||||
"limit": state.limit,
|
||||
"hard_limit": self.model_limit,
|
||||
"circuit": circuit,
|
||||
"probe_active": state.probe_active,
|
||||
"retry_after_seconds": max(0.0, state.circuit_until - now)
|
||||
if state.circuit_until is not None else 0.0,
|
||||
"outcomes": dict(state.outcomes),
|
||||
"rejects": dict(state.rejects),
|
||||
**_timings(state.recent),
|
||||
}
|
||||
return {
|
||||
"active": self._active,
|
||||
"queued": len(self._waiting),
|
||||
"model_count": len(self._models),
|
||||
"limits": {"global": self.global_limit, "model": self.model_limit,
|
||||
"user": self.user_limit, "queue": self.queue_limit,
|
||||
"user_queue": _MAX_USER_QUEUE, "models": _MAX_MODELS,
|
||||
"recent": _RECENT_LIMIT},
|
||||
"outcomes": dict(self._outcomes),
|
||||
"rejects": dict(self._rejects),
|
||||
"dropped_reports": self._dropped_reports,
|
||||
**_timings(self._recent),
|
||||
"models": models,
|
||||
}
|
||||
@@ -0,0 +1,106 @@
|
||||
"""Short-lived chat context. No filesystem, database or network access."""
|
||||
import time
|
||||
|
||||
CHAT_MEMORY_LIMIT = 10
|
||||
MEM_CHAR_BUDGET = 24000
|
||||
_CHAT_MEMORY = {}
|
||||
_CHAT_MEMORY_TTL = 3600
|
||||
_CHAT_MEMORY_USERS = 1000
|
||||
|
||||
# [FILES 2310] прикреплённый файл живёт в том же коротком in-memory контексте:
|
||||
# без БД и файловой системы, умирает вместе с процессом и по TTL.
|
||||
FILE_CHAR_BUDGET = 16000
|
||||
_FILE_TTL = 3600
|
||||
_FILE_USERS = 500
|
||||
_FILES = {} # uid -> (ts, name, kind, text)
|
||||
|
||||
|
||||
def _memory_expire():
|
||||
now = time.monotonic()
|
||||
for uid, (ts, _) in list(_CHAT_MEMORY.items()):
|
||||
if now - ts >= _CHAT_MEMORY_TTL:
|
||||
_CHAT_MEMORY.pop(uid, None)
|
||||
|
||||
|
||||
def mem_add(uid, role, content):
|
||||
if role not in ("user", "assistant") or not isinstance(content, str) or not content.strip():
|
||||
return
|
||||
_memory_expire()
|
||||
if uid not in _CHAT_MEMORY and len(_CHAT_MEMORY) >= _CHAT_MEMORY_USERS:
|
||||
_CHAT_MEMORY.pop(min(_CHAT_MEMORY, key=lambda key: _CHAT_MEMORY[key][0]))
|
||||
messages = _CHAT_MEMORY.get(uid, (0, []))[1]
|
||||
messages.append({"role": role, "content": content[:4000]})
|
||||
del messages[:-CHAT_MEMORY_LIMIT]
|
||||
_CHAT_MEMORY[uid] = (time.monotonic(), messages)
|
||||
|
||||
|
||||
def mem_load(uid, n=CHAT_MEMORY_LIMIT, budget=MEM_CHAR_BUDGET):
|
||||
_memory_expire()
|
||||
if n <= 0:
|
||||
return []
|
||||
messages = _CHAT_MEMORY.get(uid, (0, []))[1][-min(n, CHAT_MEMORY_LIMIT):]
|
||||
result, total = [], 0
|
||||
for message in reversed(messages):
|
||||
size = len(message["content"])
|
||||
if budget is not None and total + size > budget:
|
||||
break
|
||||
result.append(dict(message))
|
||||
total += size
|
||||
return list(reversed(result))
|
||||
|
||||
|
||||
def _file_expire():
|
||||
now = time.monotonic()
|
||||
for uid, entry in list(_FILES.items()):
|
||||
if now - entry[0] >= _FILE_TTL:
|
||||
_FILES.pop(uid, None)
|
||||
|
||||
|
||||
def file_attach(uid, name, kind, text):
|
||||
"""Положить извлечённый текст файла в контекст юзера. Пустой текст игнорируется."""
|
||||
if not isinstance(text, str) or not text.strip():
|
||||
return False
|
||||
_file_expire()
|
||||
if uid not in _FILES and len(_FILES) >= _FILE_USERS:
|
||||
_FILES.pop(min(_FILES, key=lambda key: _FILES[key][0]))
|
||||
body = text.strip()
|
||||
truncated = len(body) > FILE_CHAR_BUDGET
|
||||
if truncated:
|
||||
body = body[:FILE_CHAR_BUDGET].rstrip() + "\n[…обрезано по бюджету контекста]"
|
||||
_FILES[uid] = (time.monotonic(), str(name)[:120], str(kind)[:20], body)
|
||||
return True
|
||||
|
||||
|
||||
def file_context(uid):
|
||||
"""Сообщение с содержимым файла для вставки в msgs, либо пустой список."""
|
||||
_file_expire()
|
||||
entry = _FILES.get(uid)
|
||||
if not entry:
|
||||
return []
|
||||
_, name, kind, body = entry
|
||||
head = f"[Прикреплённый файл {name} ({kind or 'текст'}) — учитывай его содержимое в ответе]"
|
||||
return [{"role": "user", "content": f"{head}\n{body}"}]
|
||||
|
||||
|
||||
def file_info(uid):
|
||||
"""Сведения о прикреплённом файле: name/kind/chars/age_sec, либо None."""
|
||||
_file_expire()
|
||||
entry = _FILES.get(uid)
|
||||
if not entry:
|
||||
return None
|
||||
ts, name, kind, body = entry
|
||||
return {"name": name, "kind": kind, "chars": len(body),
|
||||
"age_sec": int(time.monotonic() - ts)}
|
||||
|
||||
|
||||
def file_clear(uid):
|
||||
_FILES.pop(uid, None)
|
||||
|
||||
|
||||
def mem_count(uid):
|
||||
return len(mem_load(uid, budget=None))
|
||||
|
||||
|
||||
def clear_memory(uid):
|
||||
_CHAT_MEMORY.pop(uid, None)
|
||||
file_clear(uid)
|
||||
@@ -0,0 +1,340 @@
|
||||
"""Bounded support receipts and an at-least-once, secret-safe notification outbox."""
|
||||
import asyncio
|
||||
from contextlib import closing
|
||||
import hashlib
|
||||
import html
|
||||
import json
|
||||
import re
|
||||
import secrets
|
||||
import sqlite3
|
||||
import time
|
||||
from urllib.parse import unquote, urlsplit, urlunsplit
|
||||
|
||||
from assistant_runtime import redact_secrets
|
||||
|
||||
|
||||
IDENTIFIER = re.compile(r'[A-Za-z0-9][A-Za-z0-9_.:-]{0,95}\Z')
|
||||
CONTEXT_LIMITS = {'screen': 64, 'model': 128, 'error_code': 64,
|
||||
'request_id': 96, 'operation_id': 96}
|
||||
_SECRET_FIELD = r'(?:password|passwd|pwd|secret|token|api[_-]?key|apikey|access[_-]?key|client[_-]?secret|bot[_-]?token|access[_-]?token|refresh[_-]?token|session[_-]?id|signature)'
|
||||
_QUOTED_SECRET = re.compile(r'(?i)(["\']?\b' + _SECRET_FIELD + r'\b["\']?\s*[:=]\s*)(["\'])(.*?)\2')
|
||||
_PLAIN_SECRET = re.compile(r'(?i)(\b' + _SECRET_FIELD + r'\b\s*[:=]\s*)(?!\[redacted\])[^\s,;&}\]]+')
|
||||
_AUTH = re.compile(r'(?im)(["\']?\b(?:authorization|proxy-authorization|cookie|set-cookie)\b["\']?\s*[:=]\s*)(?:"[^"\r\n]*"|\'[^\'\r\n]*\'|[^\r\n]*)')
|
||||
_INIT = re.compile(r'(?im)(\b(?:init[_-]?data|tgWebAppData|X-Init-Data)\b["\']?\s*[:=]\s*)[^\r\n]*')
|
||||
_TELEGRAM_DATA = re.compile(r'(?i)(?:auth_date|query_id|chat_instance|user)=[^\s]*&(?:[^\s]*&)?(?:hash|signature)=[^\s]+|hash=[^\s]*&[^\s]*auth_date=[^\s]+')
|
||||
_BOT_TOKEN = re.compile(r'\b\d{5,16}:[A-Za-z0-9_-]{20,}\b')
|
||||
_BARE_AUTH = re.compile(r'(?i)\b(?:bearer|basic)\s+[A-Za-z0-9._~+/=-]+')
|
||||
_URL = re.compile(r'https?://[^\s<>"\']+', re.I)
|
||||
_KEY_TOKEN = re.compile(r'\b(?:sk-[A-Za-z0-9_-]{16,}|AKIA[0-9A-Z]{16}|gh[pousr]_[A-Za-z0-9]{20,}|xox[baprs]-[A-Za-z0-9-]{10,})\b')
|
||||
|
||||
|
||||
class SupportError(Exception):
|
||||
def __init__(self, status, code, message):
|
||||
super().__init__(code)
|
||||
self.status, self.code, self.message = status, code, message
|
||||
|
||||
|
||||
class NotificationError(Exception):
|
||||
def __init__(self, *, retryable=True, retry_after=0):
|
||||
super().__init__('notification_failed')
|
||||
self.retryable = retryable
|
||||
self.retry_after = retry_after if isinstance(retry_after, (int, float)) else 0
|
||||
|
||||
|
||||
def identifier(value):
|
||||
return isinstance(value, str) and IDENTIFIER.fullmatch(value) is not None
|
||||
|
||||
|
||||
def redact_text(value):
|
||||
text = html.unescape(value)
|
||||
for _ in range(2):
|
||||
decoded = unquote(text)
|
||||
if decoded == text:
|
||||
break
|
||||
text = decoded
|
||||
text = ''.join(c for c in text if c in '\n\t' or (ord(c) >= 32 and ord(c) != 127))
|
||||
text = _INIT.sub(lambda m: m.group(1) + '[redacted]', text)
|
||||
text = _TELEGRAM_DATA.sub('[redacted Telegram auth]', text)
|
||||
text = _AUTH.sub(lambda m: m.group(1) + '[redacted]', text)
|
||||
text = _QUOTED_SECRET.sub(lambda m: m.group(1) + '"[redacted]"', text)
|
||||
text = _PLAIN_SECRET.sub(lambda m: m.group(1) + '[redacted]', text)
|
||||
text = _BARE_AUTH.sub('[redacted authorization]', text)
|
||||
text = _BOT_TOKEN.sub('[redacted bot token]', text)
|
||||
text = _KEY_TOKEN.sub('[redacted key]', text)
|
||||
text = redact_secrets(text)
|
||||
|
||||
def safe_url(match):
|
||||
try:
|
||||
url = urlsplit(match.group(0))
|
||||
host = url.netloc.rsplit('@', 1)[-1]
|
||||
return urlunsplit((url.scheme, host, url.path, '[redacted]' if url.query else '', ''))
|
||||
except ValueError:
|
||||
return '[redacted URL]'
|
||||
|
||||
return _URL.sub(safe_url, text)
|
||||
|
||||
|
||||
def safe_request_id(value):
|
||||
if identifier(value) and redact_text(value) == value:
|
||||
return value
|
||||
return secrets.token_hex(16)
|
||||
|
||||
|
||||
def clean_submission(message, context):
|
||||
if (not isinstance(message, str) or not message.strip() or len(message) > 4000
|
||||
or any(0xD800 <= ord(c) <= 0xDFFF for c in message)):
|
||||
raise SupportError(400, 'invalid_support_message', 'Опиши проблему: от 1 до 4000 символов.')
|
||||
if context is None:
|
||||
context = {}
|
||||
if not isinstance(context, dict):
|
||||
raise SupportError(400, 'invalid_support_context', 'Контекст должен быть JSON-объектом.')
|
||||
cleaned = {}
|
||||
for field, limit in CONTEXT_LIMITS.items():
|
||||
if field not in context:
|
||||
continue
|
||||
value = context[field]
|
||||
if (not isinstance(value, str) or len(value) > limit
|
||||
or any(0xD800 <= ord(c) <= 0xDFFF for c in value)):
|
||||
raise SupportError(400, 'invalid_support_context', 'Некорректный диагностический контекст.')
|
||||
if field in ('request_id', 'operation_id'):
|
||||
if not value:
|
||||
continue
|
||||
if not identifier(value) or redact_text(value) != value:
|
||||
raise SupportError(400, 'invalid_support_context', 'Некорректный идентификатор диагностики.')
|
||||
cleaned[field] = value
|
||||
continue
|
||||
value = redact_text(value).strip()
|
||||
if field == 'screen':
|
||||
if '://' in value:
|
||||
try:
|
||||
value = urlsplit(value).path
|
||||
except ValueError:
|
||||
value = ''
|
||||
value = value.split('?', 1)[0].split('#', 1)[0]
|
||||
value = re.sub(r'[^A-Za-z0-9_./:-]', '', value)
|
||||
if value:
|
||||
cleaned[field] = value[:limit]
|
||||
return redact_text(message.strip())[:4000], cleaned
|
||||
|
||||
|
||||
class SupportStore:
|
||||
def __init__(self, path, *, clock=time.time, retention=30 * 86400, pending_retention=7 * 86400,
|
||||
max_tickets=2000, max_user_tickets=50, hourly_limit=5, daily_limit=20,
|
||||
max_attempts=5, retry_base=15, retry_max=3600, lease_seconds=60):
|
||||
self.path, self.clock = str(path), clock
|
||||
self.retention, self.pending_retention = retention, pending_retention
|
||||
self.max_tickets, self.max_user_tickets = max_tickets, max_user_tickets
|
||||
self.hourly_limit, self.daily_limit = hourly_limit, daily_limit
|
||||
self.max_attempts, self.retry_base, self.retry_max = max_attempts, retry_base, retry_max
|
||||
self.lease_seconds = lease_seconds
|
||||
|
||||
def connect(self):
|
||||
con = sqlite3.connect(self.path, timeout=2)
|
||||
con.row_factory = sqlite3.Row
|
||||
con.execute('PRAGMA foreign_keys=ON')
|
||||
con.execute('PRAGMA secure_delete=ON')
|
||||
return con
|
||||
|
||||
def init_db(self):
|
||||
with closing(self.connect()) as con:
|
||||
con.execute('PRAGMA journal_mode=WAL')
|
||||
con.executescript('''
|
||||
CREATE TABLE IF NOT EXISTS support_tickets (
|
||||
id TEXT PRIMARY KEY, uid INTEGER NOT NULL, request_id TEXT NOT NULL,
|
||||
message TEXT NOT NULL, context TEXT NOT NULL, created_at INTEGER NOT NULL,
|
||||
notification_status TEXT NOT NULL DEFAULT 'pending', UNIQUE(uid, request_id)
|
||||
);
|
||||
CREATE INDEX IF NOT EXISTS support_user_created ON support_tickets(uid, created_at);
|
||||
CREATE TABLE IF NOT EXISTS support_outbox (
|
||||
ticket_id TEXT NOT NULL REFERENCES support_tickets(id) ON DELETE CASCADE,
|
||||
admin_id INTEGER NOT NULL, status TEXT NOT NULL DEFAULT 'pending',
|
||||
attempts INTEGER NOT NULL DEFAULT 0, next_attempt REAL NOT NULL DEFAULT 0,
|
||||
lease_until REAL NOT NULL DEFAULT 0, PRIMARY KEY(ticket_id, admin_id)
|
||||
);
|
||||
CREATE INDEX IF NOT EXISTS support_delivery_due ON support_outbox(status, next_attempt);
|
||||
''')
|
||||
con.commit()
|
||||
|
||||
@staticmethod
|
||||
def receipt(row):
|
||||
return {'id': row['id'], 'status': 'received', 'notification_status': row['notification_status'],
|
||||
'created_at': row['created_at']}
|
||||
|
||||
def _prune(self, con, now):
|
||||
con.execute('DELETE FROM support_tickets WHERE created_at<=?', (now - self.retention,))
|
||||
con.execute("UPDATE support_outbox SET status='failed',lease_until=0 WHERE ticket_id IN "
|
||||
"(SELECT id FROM support_tickets WHERE notification_status='pending' AND created_at<=?)",
|
||||
(now - self.pending_retention,))
|
||||
con.execute("UPDATE support_tickets SET notification_status='failed' "
|
||||
"WHERE notification_status='pending' AND created_at<=?", (now - self.pending_retention,))
|
||||
|
||||
def prune(self):
|
||||
with closing(self.connect()) as con:
|
||||
con.execute('BEGIN IMMEDIATE')
|
||||
self._prune(con, self.clock())
|
||||
con.commit()
|
||||
|
||||
def submit(self, uid, request_id, message, context=None):
|
||||
if not identifier(request_id):
|
||||
raise SupportError(400, 'invalid_request_id', 'Обнови экран и отправь обращение заново.')
|
||||
message, context = clean_submission(message, context)
|
||||
# Only a digest of the caller's deduplication ID is retained; it may itself be a pasted secret.
|
||||
request_key = hashlib.sha256(request_id.encode('utf-8')).hexdigest()
|
||||
now = self.clock()
|
||||
with closing(self.connect()) as con:
|
||||
con.execute('BEGIN IMMEDIATE')
|
||||
self._prune(con, now)
|
||||
row = con.execute('SELECT * FROM support_tickets WHERE uid=? AND request_id=?',
|
||||
(uid, request_key)).fetchone()
|
||||
if row:
|
||||
con.commit()
|
||||
return self.receipt(row)
|
||||
recent = con.execute('SELECT COUNT(*),COALESCE(SUM(created_at>?),0) FROM support_tickets '
|
||||
'WHERE uid=? AND created_at>?', (now - 3600, uid, now - 86400)).fetchone()
|
||||
if recent[0] >= self.daily_limit or recent[1] >= self.hourly_limit:
|
||||
raise SupportError(429, 'support_rate_limited', 'Обращения сохранены. Попробуй отправить новое позже.')
|
||||
user_count = con.execute('SELECT COUNT(*) FROM support_tickets WHERE uid=?', (uid,)).fetchone()[0]
|
||||
if user_count >= self.max_user_tickets:
|
||||
raise SupportError(429, 'support_intake_full', 'Лимит сохранённых обращений достигнут. Попробуй позже.')
|
||||
count = con.execute('SELECT COUNT(*) FROM support_tickets').fetchone()[0]
|
||||
if count >= self.max_tickets:
|
||||
raise SupportError(503, 'support_intake_full', 'Поддержка временно занята. Попробуй позже.')
|
||||
ticket_id = secrets.token_hex(12)
|
||||
con.execute('INSERT INTO support_tickets(id,uid,request_id,message,context,created_at) VALUES(?,?,?,?,?,?)',
|
||||
(ticket_id, uid, request_key, message, json.dumps(context, ensure_ascii=False), int(now)))
|
||||
row = con.execute('SELECT * FROM support_tickets WHERE id=?', (ticket_id,)).fetchone()
|
||||
con.commit()
|
||||
return self.receipt(row)
|
||||
|
||||
def list_receipts(self, uid, limit=20):
|
||||
limit = max(1, min(int(limit), 50))
|
||||
with closing(self.connect()) as con:
|
||||
con.execute('BEGIN IMMEDIATE')
|
||||
self._prune(con, self.clock())
|
||||
rows = con.execute('SELECT * FROM support_tickets WHERE uid=? ORDER BY created_at DESC,id DESC LIMIT ?',
|
||||
(uid, limit)).fetchall()
|
||||
con.commit()
|
||||
return [self.receipt(row) for row in rows]
|
||||
|
||||
@staticmethod
|
||||
def _refresh(con):
|
||||
con.execute('''UPDATE support_tickets SET notification_status=CASE
|
||||
WHEN EXISTS(SELECT 1 FROM support_outbox o WHERE o.ticket_id=support_tickets.id
|
||||
AND o.status IN ('pending','sending')) THEN 'pending'
|
||||
WHEN EXISTS(SELECT 1 FROM support_outbox o WHERE o.ticket_id=support_tickets.id
|
||||
AND o.status='failed') THEN 'failed'
|
||||
WHEN EXISTS(SELECT 1 FROM support_outbox o WHERE o.ticket_id=support_tickets.id) THEN 'sent'
|
||||
ELSE 'pending' END WHERE notification_status='pending' ''')
|
||||
|
||||
def claim(self, admin_ids):
|
||||
admins = sorted({uid for uid in admin_ids if isinstance(uid, int) and not isinstance(uid, bool) and uid > 0})
|
||||
if len(admins) > 64:
|
||||
raise ValueError('too_many_support_admins')
|
||||
now = self.clock()
|
||||
with closing(self.connect()) as con:
|
||||
con.execute('BEGIN IMMEDIATE')
|
||||
self._prune(con, now)
|
||||
if not admins:
|
||||
con.commit()
|
||||
return None
|
||||
slots = ','.join('?' for _ in admins)
|
||||
con.execute("DELETE FROM support_outbox WHERE ticket_id IN "
|
||||
"(SELECT id FROM support_tickets WHERE notification_status='pending') "
|
||||
'AND admin_id NOT IN (' + slots + ')', admins)
|
||||
for admin in admins:
|
||||
con.execute('INSERT OR IGNORE INTO support_outbox(ticket_id,admin_id) '
|
||||
"SELECT id,? FROM support_tickets WHERE notification_status='pending'", (admin,))
|
||||
con.execute("UPDATE support_outbox SET status='failed',lease_until=0 "
|
||||
"WHERE status IN ('pending','sending') AND attempts>=? AND lease_until<=?",
|
||||
(self.max_attempts, now))
|
||||
self._refresh(con)
|
||||
row = con.execute('''SELECT o.*,t.uid,t.message,t.context,t.created_at FROM support_outbox o
|
||||
JOIN support_tickets t ON t.id=o.ticket_id WHERE t.notification_status='pending'
|
||||
AND o.admin_id IN (''' + slots + ''') AND o.attempts<? AND
|
||||
((o.status='pending' AND o.next_attempt<=?) OR (o.status='sending' AND o.lease_until<=?))
|
||||
ORDER BY o.next_attempt,t.created_at,o.ticket_id,o.admin_id LIMIT 1''',
|
||||
(*admins, self.max_attempts, now, now)).fetchone()
|
||||
if row is None:
|
||||
con.commit()
|
||||
return None
|
||||
con.execute("UPDATE support_outbox SET status='sending',attempts=attempts+1,lease_until=? "
|
||||
'WHERE ticket_id=? AND admin_id=?', (now + self.lease_seconds, row['ticket_id'], row['admin_id']))
|
||||
con.commit()
|
||||
claimed = dict(row)
|
||||
claimed['attempts'] += 1
|
||||
return claimed
|
||||
|
||||
def finish(self, claim, *, sent=False, retryable=True, retry_after=0):
|
||||
attempts = claim['attempts']
|
||||
if sent:
|
||||
state, delay = 'sent', 0
|
||||
elif not retryable or attempts >= self.max_attempts:
|
||||
state, delay = 'failed', 0
|
||||
else:
|
||||
state = 'pending'
|
||||
retry_after = retry_after if isinstance(retry_after, (int, float)) else 0
|
||||
delay = min(self.retry_max, max(self.retry_base * 2 ** (attempts - 1), retry_after))
|
||||
with closing(self.connect()) as con:
|
||||
con.execute('BEGIN IMMEDIATE')
|
||||
con.execute("UPDATE support_outbox SET status=?,next_attempt=?,lease_until=0 "
|
||||
"WHERE ticket_id=? AND admin_id=? AND attempts=? AND status='sending'",
|
||||
(state, self.clock() + delay, claim['ticket_id'], claim['admin_id'], attempts))
|
||||
self._refresh(con)
|
||||
con.commit()
|
||||
|
||||
|
||||
def notification_text(claim):
|
||||
context = json.loads(claim['context'])
|
||||
details = '\n'.join('%s: %s' % (key, value) for key, value in context.items())
|
||||
message = claim['message'][:3000]
|
||||
if len(claim['message']) > len(message):
|
||||
message += '\n[Текст сокращён в уведомлении]'
|
||||
return ('Обращение #%s\nПользователь: %s\n%s\n%s' %
|
||||
(claim['ticket_id'], claim['uid'], message, details))[:4000]
|
||||
|
||||
|
||||
class SupportOutbox:
|
||||
def __init__(self, store, admin_ids, sender, *, interval=5, batch=8):
|
||||
self.store, self.admin_ids, self.sender = store, admin_ids, sender
|
||||
self.interval, self.batch = interval, batch
|
||||
self.wake = asyncio.Event()
|
||||
self.stopping = False
|
||||
|
||||
def stop(self):
|
||||
self.stopping = True
|
||||
self.wake.set()
|
||||
|
||||
async def run_once(self):
|
||||
for _ in range(self.batch):
|
||||
if self.stopping:
|
||||
break
|
||||
claim = await asyncio.to_thread(self.store.claim, self.admin_ids())
|
||||
if claim is None:
|
||||
break
|
||||
try:
|
||||
await self.sender(claim['admin_id'], notification_text(claim))
|
||||
except asyncio.CancelledError:
|
||||
# A crashed/cancelled delivery remains leased and is recoverable after restart.
|
||||
raise
|
||||
except NotificationError as error:
|
||||
await asyncio.to_thread(self.store.finish, claim, retryable=error.retryable,
|
||||
retry_after=error.retry_after)
|
||||
except Exception:
|
||||
await asyncio.to_thread(self.store.finish, claim, retryable=True)
|
||||
else:
|
||||
await asyncio.to_thread(self.store.finish, claim, sent=True)
|
||||
|
||||
async def run(self):
|
||||
while not self.stopping:
|
||||
self.wake.clear()
|
||||
try:
|
||||
await self.run_once()
|
||||
except (sqlite3.Error, OSError, ValueError):
|
||||
# No exception text: HTTP exceptions may contain a token-bearing Telegram URL.
|
||||
pass
|
||||
if self.stopping:
|
||||
break
|
||||
try:
|
||||
await asyncio.wait_for(self.wake.wait(), timeout=self.interval)
|
||||
except asyncio.TimeoutError:
|
||||
pass
|
||||
@@ -0,0 +1,202 @@
|
||||
|
||||
Apache License
|
||||
Version 2.0, January 2004
|
||||
http://www.apache.org/licenses/
|
||||
|
||||
TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
|
||||
|
||||
1. Definitions.
|
||||
|
||||
"License" shall mean the terms and conditions for use, reproduction,
|
||||
and distribution as defined by Sections 1 through 9 of this document.
|
||||
|
||||
"Licensor" shall mean the copyright owner or entity authorized by
|
||||
the copyright owner that is granting the License.
|
||||
|
||||
"Legal Entity" shall mean the union of the acting entity and all
|
||||
other entities that control, are controlled by, or are under common
|
||||
control with that entity. For the purposes of this definition,
|
||||
"control" means (i) the power, direct or indirect, to cause the
|
||||
direction or management of such entity, whether by contract or
|
||||
otherwise, or (ii) ownership of fifty percent (50%) or more of the
|
||||
outstanding shares, or (iii) beneficial ownership of such entity.
|
||||
|
||||
"You" (or "Your") shall mean an individual or Legal Entity
|
||||
exercising permissions granted by this License.
|
||||
|
||||
"Source" form shall mean the preferred form for making modifications,
|
||||
including but not limited to software source code, documentation
|
||||
source, and configuration files.
|
||||
|
||||
"Object" form shall mean any form resulting from mechanical
|
||||
transformation or translation of a Source form, including but
|
||||
not limited to compiled object code, generated documentation,
|
||||
and conversions to other media types.
|
||||
|
||||
"Work" shall mean the work of authorship, whether in Source or
|
||||
Object form, made available under the License, as indicated by a
|
||||
copyright notice that is included in or attached to the work
|
||||
(an example is provided in the Appendix below).
|
||||
|
||||
"Derivative Works" shall mean any work, whether in Source or Object
|
||||
form, that is based on (or derived from) the Work and for which the
|
||||
editorial revisions, annotations, elaborations, or other modifications
|
||||
represent, as a whole, an original work of authorship. For the purposes
|
||||
of this License, Derivative Works shall not include works that remain
|
||||
separable from, or merely link (or bind by name) to the interfaces of,
|
||||
the Work and Derivative Works thereof.
|
||||
|
||||
"Contribution" shall mean any work of authorship, including
|
||||
the original version of the Work and any modifications or additions
|
||||
to that Work or Derivative Works thereof, that is intentionally
|
||||
submitted to Licensor for inclusion in the Work by the copyright owner
|
||||
or by an individual or Legal Entity authorized to submit on behalf of
|
||||
the copyright owner. For the purposes of this definition, "submitted"
|
||||
means any form of electronic, verbal, or written communication sent
|
||||
to the Licensor or its representatives, including but not limited to
|
||||
communication on electronic mailing lists, source code control systems,
|
||||
and issue tracking systems that are managed by, or on behalf of, the
|
||||
Licensor for the purpose of discussing and improving the Work, but
|
||||
excluding communication that is conspicuously marked or otherwise
|
||||
designated in writing by the copyright owner as "Not a Contribution."
|
||||
|
||||
"Contributor" shall mean Licensor and any individual or Legal Entity
|
||||
on behalf of whom a Contribution has been received by Licensor and
|
||||
subsequently incorporated within the Work.
|
||||
|
||||
2. Grant of Copyright License. Subject to the terms and conditions of
|
||||
this License, each Contributor hereby grants to You a perpetual,
|
||||
worldwide, non-exclusive, no-charge, royalty-free, irrevocable
|
||||
copyright license to reproduce, prepare Derivative Works of,
|
||||
publicly display, publicly perform, sublicense, and distribute the
|
||||
Work and such Derivative Works in Source or Object form.
|
||||
|
||||
3. Grant of Patent License. Subject to the terms and conditions of
|
||||
this License, each Contributor hereby grants to You a perpetual,
|
||||
worldwide, non-exclusive, no-charge, royalty-free, irrevocable
|
||||
(except as stated in this section) patent license to make, have made,
|
||||
use, offer to sell, sell, import, and otherwise transfer the Work,
|
||||
where such license applies only to those patent claims licensable
|
||||
by such Contributor that are necessarily infringed by their
|
||||
Contribution(s) alone or by combination of their Contribution(s)
|
||||
with the Work to which such Contribution(s) was submitted. If You
|
||||
institute patent litigation against any entity (including a
|
||||
cross-claim or counterclaim in a lawsuit) alleging that the Work
|
||||
or a Contribution incorporated within the Work constitutes direct
|
||||
or contributory patent infringement, then any patent licenses
|
||||
granted to You under this License for that Work shall terminate
|
||||
as of the date such litigation is filed.
|
||||
|
||||
4. Redistribution. You may reproduce and distribute copies of the
|
||||
Work or Derivative Works thereof in any medium, with or without
|
||||
modifications, and in Source or Object form, provided that You
|
||||
meet the following conditions:
|
||||
|
||||
(a) You must give any other recipients of the Work or
|
||||
Derivative Works a copy of this License; and
|
||||
|
||||
(b) You must cause any modified files to carry prominent notices
|
||||
stating that You changed the files; and
|
||||
|
||||
(c) You must retain, in the Source form of any Derivative Works
|
||||
that You distribute, all copyright, patent, trademark, and
|
||||
attribution notices from the Source form of the Work,
|
||||
excluding those notices that do not pertain to any part of
|
||||
the Derivative Works; and
|
||||
|
||||
(d) If the Work includes a "NOTICE" text file as part of its
|
||||
distribution, then any Derivative Works that You distribute must
|
||||
include a readable copy of the attribution notices contained
|
||||
within such NOTICE file, excluding those notices that do not
|
||||
pertain to any part of the Derivative Works, in at least one
|
||||
of the following places: within a NOTICE text file distributed
|
||||
as part of the Derivative Works; within the Source form or
|
||||
documentation, if provided along with the Derivative Works; or,
|
||||
within a display generated by the Derivative Works, if and
|
||||
wherever such third-party notices normally appear. The contents
|
||||
of the NOTICE file are for informational purposes only and
|
||||
do not modify the License. You may add Your own attribution
|
||||
notices within Derivative Works that You distribute, alongside
|
||||
or as an addendum to the NOTICE text from the Work, provided
|
||||
that such additional attribution notices cannot be construed
|
||||
as modifying the License.
|
||||
|
||||
You may add Your own copyright statement to Your modifications and
|
||||
may provide additional or different license terms and conditions
|
||||
for use, reproduction, or distribution of Your modifications, or
|
||||
for any such Derivative Works as a whole, provided Your use,
|
||||
reproduction, and distribution of the Work otherwise complies with
|
||||
the conditions stated in this License.
|
||||
|
||||
5. Submission of Contributions. Unless You explicitly state otherwise,
|
||||
any Contribution intentionally submitted for inclusion in the Work
|
||||
by You to the Licensor shall be under the terms and conditions of
|
||||
this License, without any additional terms or conditions.
|
||||
Notwithstanding the above, nothing herein shall supersede or modify
|
||||
the terms of any separate license agreement you may have executed
|
||||
with Licensor regarding such Contributions.
|
||||
|
||||
6. Trademarks. This License does not grant permission to use the trade
|
||||
names, trademarks, service marks, or product names of the Licensor,
|
||||
except as required for reasonable and customary use in describing the
|
||||
origin of the Work and reproducing the content of the NOTICE file.
|
||||
|
||||
7. Disclaimer of Warranty. Unless required by applicable law or
|
||||
agreed to in writing, Licensor provides the Work (and each
|
||||
Contributor provides its Contributions) on an "AS IS" BASIS,
|
||||
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
|
||||
implied, including, without limitation, any warranties or conditions
|
||||
of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
|
||||
PARTICULAR PURPOSE. You are solely responsible for determining the
|
||||
appropriateness of using or redistributing the Work and assume any
|
||||
risks associated with Your exercise of permissions under this License.
|
||||
|
||||
8. Limitation of Liability. In no event and under no legal theory,
|
||||
whether in tort (including negligence), contract, or otherwise,
|
||||
unless required by applicable law (such as deliberate and grossly
|
||||
negligent acts) or agreed to in writing, shall any Contributor be
|
||||
liable to You for damages, including any direct, indirect, special,
|
||||
incidental, or consequential damages of any character arising as a
|
||||
result of this License or out of the use or inability to use the
|
||||
Work (including but not limited to damages for loss of goodwill,
|
||||
work stoppage, computer failure or malfunction, or any and all
|
||||
other commercial damages or losses), even if such Contributor
|
||||
has been advised of the possibility of such damages.
|
||||
|
||||
9. Accepting Warranty or Additional Liability. While redistributing
|
||||
the Work or Derivative Works thereof, You may choose to offer,
|
||||
and charge a fee for, acceptance of support, warranty, indemnity,
|
||||
or other liability obligations and/or rights consistent with this
|
||||
License. However, in accepting such obligations, You may act only
|
||||
on Your own behalf and on Your sole responsibility, not on behalf
|
||||
of any other Contributor, and only if You agree to indemnify,
|
||||
defend, and hold each Contributor harmless for any liability
|
||||
incurred by, or claims asserted against, such Contributor by reason
|
||||
of your accepting any such warranty or additional liability.
|
||||
|
||||
END OF TERMS AND CONDITIONS
|
||||
|
||||
APPENDIX: How to apply the Apache License to your work.
|
||||
|
||||
To apply the Apache License to your work, attach the following
|
||||
boilerplate notice, with the fields enclosed by brackets "[]"
|
||||
replaced with your own identifying information. (Don't include
|
||||
the brackets!) The text should be enclosed in the appropriate
|
||||
comment syntax for the file format. We also recommend that a
|
||||
file or class name and description of purpose be included on the
|
||||
same "printed page" as the copyright notice for easier
|
||||
identification within third-party archives.
|
||||
|
||||
Copyright [yyyy] [name of copyright owner]
|
||||
|
||||
Licensed under the Apache License, Version 2.0 (the "License");
|
||||
you may not use this file except in compliance with the License.
|
||||
You may obtain a copy of the License at
|
||||
|
||||
http://www.apache.org/licenses/LICENSE-2.0
|
||||
|
||||
Unless required by applicable law or agreed to in writing, software
|
||||
distributed under the License is distributed on an "AS IS" BASIS,
|
||||
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
||||
See the License for the specific language governing permissions and
|
||||
limitations under the License.
|
||||
@@ -0,0 +1 @@
|
||||
"""Pinned Apache-2.0 MaxMind pure-Python reader; no extension or API loader."""
|
||||
@@ -0,0 +1,47 @@
|
||||
"""Constants used in the API."""
|
||||
|
||||
from enum import IntEnum
|
||||
|
||||
|
||||
class Mode(IntEnum):
|
||||
"""Database open modes.
|
||||
|
||||
These modes control how the MaxMind DB file is opened and read.
|
||||
"""
|
||||
|
||||
AUTO = 0
|
||||
"""Try MODE_MMAP_EXT, MODE_MMAP, MODE_FILE in that order. Default mode."""
|
||||
|
||||
MMAP_EXT = 1
|
||||
"""Use the C extension with memory map."""
|
||||
|
||||
MMAP = 2
|
||||
"""Read from memory map. Pure Python."""
|
||||
|
||||
FILE = 4
|
||||
"""Read database as standard file. Pure Python."""
|
||||
|
||||
MEMORY = 8
|
||||
"""Load database into memory. Pure Python."""
|
||||
|
||||
FD = 16
|
||||
"""Database is a file descriptor, not a path. This mode implies MODE_MEMORY."""
|
||||
|
||||
|
||||
# Backward compatibility: export both enum members and old-style constants
|
||||
MODE_AUTO = Mode.AUTO
|
||||
MODE_MMAP_EXT = Mode.MMAP_EXT
|
||||
MODE_MMAP = Mode.MMAP
|
||||
MODE_FILE = Mode.FILE
|
||||
MODE_MEMORY = Mode.MEMORY
|
||||
MODE_FD = Mode.FD
|
||||
|
||||
__all__ = [
|
||||
"MODE_AUTO",
|
||||
"MODE_FD",
|
||||
"MODE_FILE",
|
||||
"MODE_MEMORY",
|
||||
"MODE_MMAP",
|
||||
"MODE_MMAP_EXT",
|
||||
"Mode",
|
||||
]
|
||||
@@ -0,0 +1,356 @@
|
||||
# Vendored from MaxMind-DB-Reader-python v3.2.0 (Apache-2.0).
|
||||
# ENI modification: package imports made relative; reader/decoder behavior unchanged.
|
||||
"""Decoder for the MaxMind DB data section."""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import struct
|
||||
from dataclasses import dataclass
|
||||
from typing import TYPE_CHECKING
|
||||
|
||||
try:
|
||||
import mmap
|
||||
except ImportError:
|
||||
mmap = None # type: ignore[assignment]
|
||||
|
||||
from .errors import InvalidDatabaseError
|
||||
|
||||
if TYPE_CHECKING:
|
||||
from .file import FileBuffer
|
||||
from .types import Record
|
||||
|
||||
|
||||
# Per-lookup value limit recommended by the MaxMind DB specification. It stops
|
||||
# pointer fan-out, where nested containers share targets that would otherwise
|
||||
# cost 2**depth decode operations. The root costs one value. Arrays charge each
|
||||
# Real records decode a few hundred values, leaving a wide margin.
|
||||
# An explicit depth limit catches container cycles and overly nested data.
|
||||
# Python's recursion limit may fire first, which decode converts to the same
|
||||
# error. The explicit limit also applies when callers raise Python's limit.
|
||||
_MAX_VALUES = 1 << 16
|
||||
_MAX_DEPTH = 512
|
||||
# Per-lookup limit on the total string and bytes payload materialized, matching
|
||||
# libmaxminddb and the Go reader. It stops a payload amplification, where many
|
||||
# pointers to one large value would otherwise materialize N * size bytes from a
|
||||
# small file. Each string or bytes value is charged its length wherever it is
|
||||
# decoded, so re-decoding a shared target through another pointer recharges.
|
||||
_MAX_PAYLOAD_BYTES = 1 << 21
|
||||
# The widest fixed-width integer the format defines is the 16-byte uint128; a
|
||||
# declared size past that is malformed and could copy attacker-controlled bytes.
|
||||
_MAX_UINT_BYTES = 16
|
||||
_MAX_INT32_BYTES = 4
|
||||
# Added to a pointer value, by pointer size. A 4-byte pointer adds nothing.
|
||||
_POINTER_VALUE_OFFSETS = (0, 0, 2048, 526336)
|
||||
_TOO_MANY_VALUES = (
|
||||
"The MaxMind DB file's data section exceeds the maximum number of values"
|
||||
)
|
||||
_TOO_DEEP = "The MaxMind DB file's data section exceeds the maximum depth"
|
||||
_TOO_LARGE = "The MaxMind DB file's data section exceeds the maximum payload size"
|
||||
_BAD_DATA = (
|
||||
"The MaxMind DB file's data section contains bad data "
|
||||
"(unknown data type or corrupt data)"
|
||||
)
|
||||
|
||||
|
||||
@dataclass
|
||||
class _DecodeBudget:
|
||||
"""Shared counters for one record or metadata decode."""
|
||||
|
||||
values_left: int
|
||||
depth: int
|
||||
payload_left: int
|
||||
|
||||
|
||||
class Decoder:
|
||||
"""Decoder for the data section of the MaxMind DB."""
|
||||
|
||||
def __init__(
|
||||
self,
|
||||
database_buffer: FileBuffer | mmap.mmap | bytes,
|
||||
pointer_base: int = 0,
|
||||
pointer_test: bool = False, # noqa: FBT001, FBT002
|
||||
) -> None:
|
||||
"""Create a Decoder for a MaxMind DB.
|
||||
|
||||
Arguments:
|
||||
database_buffer: an mmap'd MaxMind DB file.
|
||||
pointer_base: the base number to use when decoding a pointer
|
||||
pointer_test: used for internal unit testing of pointer code
|
||||
|
||||
"""
|
||||
self._pointer_test = pointer_test
|
||||
self._buffer = database_buffer
|
||||
self._pointer_base = pointer_base
|
||||
|
||||
def _decode_array(
|
||||
self,
|
||||
size: int,
|
||||
offset: int,
|
||||
budget: _DecodeBudget,
|
||||
) -> tuple[list[Record], int]:
|
||||
remaining = budget.values_left - size
|
||||
if remaining < 0:
|
||||
raise InvalidDatabaseError(_TOO_MANY_VALUES)
|
||||
budget.values_left = remaining
|
||||
depth = budget.depth + 1
|
||||
if depth > _MAX_DEPTH:
|
||||
raise InvalidDatabaseError(_TOO_DEEP)
|
||||
budget.depth = depth
|
||||
array = []
|
||||
decode = self._decode
|
||||
for _ in range(size):
|
||||
(value, offset) = decode(offset, budget, False) # noqa: FBT003
|
||||
array.append(value)
|
||||
budget.depth -= 1
|
||||
return array, offset
|
||||
|
||||
def _decode_boolean(
|
||||
self,
|
||||
size: int,
|
||||
offset: int,
|
||||
_budget: _DecodeBudget,
|
||||
) -> tuple[bool, int]:
|
||||
return size != 0, offset
|
||||
|
||||
def _decode_bytes(
|
||||
self,
|
||||
size: int,
|
||||
offset: int,
|
||||
budget: _DecodeBudget,
|
||||
) -> tuple[bytes, int]:
|
||||
# Charge the payload before copying so a crafted size cannot force a
|
||||
# large allocation, and so pointers reusing one target recharge.
|
||||
remaining = budget.payload_left - size
|
||||
if remaining < 0:
|
||||
raise InvalidDatabaseError(_TOO_LARGE)
|
||||
budget.payload_left = remaining
|
||||
new_offset = offset + size
|
||||
return self._buffer[offset:new_offset], new_offset
|
||||
|
||||
def _decode_double(
|
||||
self,
|
||||
size: int,
|
||||
offset: int,
|
||||
_budget: _DecodeBudget,
|
||||
) -> tuple[float, int]:
|
||||
self._verify_size(size, 8)
|
||||
new_offset = offset + size
|
||||
packed_bytes = self._buffer[offset:new_offset]
|
||||
(value,) = struct.unpack(b"!d", packed_bytes)
|
||||
return value, new_offset
|
||||
|
||||
def _decode_float(
|
||||
self,
|
||||
size: int,
|
||||
offset: int,
|
||||
_budget: _DecodeBudget,
|
||||
) -> tuple[float, int]:
|
||||
self._verify_size(size, 4)
|
||||
new_offset = offset + size
|
||||
packed_bytes = self._buffer[offset:new_offset]
|
||||
(value,) = struct.unpack(b"!f", packed_bytes)
|
||||
return value, new_offset
|
||||
|
||||
def _decode_int32(
|
||||
self,
|
||||
size: int,
|
||||
offset: int,
|
||||
_budget: _DecodeBudget,
|
||||
) -> tuple[int, int]:
|
||||
if size > _MAX_INT32_BYTES:
|
||||
raise InvalidDatabaseError(_BAD_DATA)
|
||||
if size == 0:
|
||||
return 0, offset
|
||||
new_offset = offset + size
|
||||
packed_bytes = self._buffer[offset:new_offset]
|
||||
|
||||
if size != 4:
|
||||
packed_bytes = packed_bytes.rjust(4, b"\x00")
|
||||
(value,) = struct.unpack(b"!i", packed_bytes)
|
||||
return value, new_offset
|
||||
|
||||
def _decode_map(
|
||||
self,
|
||||
size: int,
|
||||
offset: int,
|
||||
budget: _DecodeBudget,
|
||||
) -> tuple[dict[str, Record], int]:
|
||||
remaining = budget.values_left - size * 2
|
||||
if remaining < 0:
|
||||
raise InvalidDatabaseError(_TOO_MANY_VALUES)
|
||||
budget.values_left = remaining
|
||||
depth = budget.depth + 1
|
||||
if depth > _MAX_DEPTH:
|
||||
raise InvalidDatabaseError(_TOO_DEEP)
|
||||
budget.depth = depth
|
||||
container: dict[str, Record] = {}
|
||||
decode = self._decode
|
||||
for _ in range(size):
|
||||
(key, offset) = decode(offset, budget, False) # noqa: FBT003
|
||||
(value, offset) = decode(offset, budget, False) # noqa: FBT003
|
||||
container[key] = value # type: ignore[index]
|
||||
budget.depth -= 1
|
||||
return container, offset
|
||||
|
||||
def _decode_pointer(
|
||||
self,
|
||||
size: int,
|
||||
offset: int,
|
||||
budget: _DecodeBudget,
|
||||
) -> tuple[Record, int]:
|
||||
pointer_size = (size >> 3) + 1
|
||||
new_offset = offset + pointer_size
|
||||
pointer_bytes = self._buffer[offset:new_offset]
|
||||
if len(pointer_bytes) != pointer_size:
|
||||
raise InvalidDatabaseError(_BAD_DATA)
|
||||
pointer = int.from_bytes(pointer_bytes, "big")
|
||||
if pointer_size < 4:
|
||||
# The low three bits of the ctrl byte are the high bits of the
|
||||
# pointer, and sizes 2 and 3 add a fixed offset.
|
||||
pointer |= (size & 0x7) << (pointer_size << 3)
|
||||
pointer += _POINTER_VALUE_OFFSETS[pointer_size]
|
||||
pointer += self._pointer_base
|
||||
|
||||
if self._pointer_test:
|
||||
return pointer, new_offset
|
||||
|
||||
# The value at the pointer's position was charged by its containing
|
||||
# array or map, so the target costs nothing more. Only the depth changes.
|
||||
depth = budget.depth + 1
|
||||
if depth > _MAX_DEPTH:
|
||||
raise InvalidDatabaseError(_TOO_DEEP)
|
||||
budget.depth = depth
|
||||
(value, _) = self._decode(pointer, budget, True) # noqa: FBT003
|
||||
budget.depth -= 1
|
||||
return value, new_offset
|
||||
|
||||
def _decode_uint(
|
||||
self,
|
||||
size: int,
|
||||
offset: int,
|
||||
_budget: _DecodeBudget,
|
||||
) -> tuple[int, int]:
|
||||
# Reject a declared size past the widest defined unsigned integer before
|
||||
# copying, so a crafted size cannot force a large allocation.
|
||||
if size > _MAX_UINT_BYTES:
|
||||
raise InvalidDatabaseError(_BAD_DATA)
|
||||
new_offset = offset + size
|
||||
uint_bytes = self._buffer[offset:new_offset]
|
||||
return int.from_bytes(uint_bytes, "big"), new_offset
|
||||
|
||||
def decode(self, offset: int) -> tuple[Record, int]:
|
||||
"""Decode a section of the data section starting at offset.
|
||||
|
||||
Arguments:
|
||||
offset: the location of the data structure to decode
|
||||
|
||||
"""
|
||||
# Each call gets its own budget, shared by recursive calls. Charge the
|
||||
# root here.
|
||||
try:
|
||||
return self._decode(
|
||||
offset,
|
||||
_DecodeBudget(_MAX_VALUES - 1, 0, _MAX_PAYLOAD_BYTES),
|
||||
False, # noqa: FBT003
|
||||
)
|
||||
except RecursionError as ex:
|
||||
raise InvalidDatabaseError(_TOO_DEEP) from ex
|
||||
except (IndexError, struct.error) as ex:
|
||||
# Convert failed buffer indexing and fixed-width unpacking.
|
||||
raise InvalidDatabaseError(_BAD_DATA) from ex
|
||||
|
||||
# Keep type dispatch inline to avoid another call for every decoded value.
|
||||
# The positional booleans are intentional: keywords and omitted defaults
|
||||
# prevented CPython from using its fastest call path in our benchmarks.
|
||||
# pointer_target rejects pointers to other pointers.
|
||||
def _decode( # noqa: C901, PLR0911, PLR0912
|
||||
self,
|
||||
offset: int,
|
||||
budget: _DecodeBudget,
|
||||
pointer_target: bool, # noqa: FBT001
|
||||
) -> tuple[Record, int]:
|
||||
new_offset = offset + 1
|
||||
ctrl_byte = self._buffer[offset]
|
||||
type_num = ctrl_byte >> 5
|
||||
# Extended type
|
||||
if not type_num:
|
||||
(type_num, new_offset) = self._read_extended(new_offset)
|
||||
|
||||
size = ctrl_byte & 0x1F
|
||||
# Sizes under 29 are stored in the ctrl byte, and a pointer's size bits
|
||||
# are not a size. Skip the call for that common case.
|
||||
if size >= 29 and type_num != 1:
|
||||
(size, new_offset) = self._size_from_ctrl_byte(size, new_offset)
|
||||
# Put common types first to reduce comparisons during real lookups.
|
||||
match type_num:
|
||||
case 2:
|
||||
# Strings are most of the values in a real database. Decode them
|
||||
# here to save a method call.
|
||||
# Charge the payload before copying so a crafted size cannot force
|
||||
# a large allocation, and so pointers reusing one target recharge.
|
||||
remaining = budget.payload_left - size
|
||||
if remaining < 0:
|
||||
raise InvalidDatabaseError(_TOO_LARGE)
|
||||
budget.payload_left = remaining
|
||||
end = new_offset + size
|
||||
return self._buffer[new_offset:end].decode("utf-8"), end
|
||||
case 1:
|
||||
if pointer_target:
|
||||
raise InvalidDatabaseError(_BAD_DATA)
|
||||
return self._decode_pointer(size, new_offset, budget)
|
||||
case 7:
|
||||
return self._decode_map(size, new_offset, budget)
|
||||
case 6 | 5 | 9 | 10: # uint32, uint16, uint64, uint128
|
||||
return self._decode_uint(size, new_offset, budget)
|
||||
case 11:
|
||||
return self._decode_array(size, new_offset, budget)
|
||||
case 3:
|
||||
return self._decode_double(size, new_offset, budget)
|
||||
case 4:
|
||||
return self._decode_bytes(size, new_offset, budget)
|
||||
case 8:
|
||||
return self._decode_int32(size, new_offset, budget)
|
||||
case 14:
|
||||
return self._decode_boolean(size, new_offset, budget)
|
||||
case 15:
|
||||
return self._decode_float(size, new_offset, budget)
|
||||
case _:
|
||||
msg = f"Unexpected type number ({type_num}) encountered"
|
||||
raise InvalidDatabaseError(msg)
|
||||
|
||||
def _read_extended(self, offset: int) -> tuple[int, int]:
|
||||
next_byte = self._buffer[offset]
|
||||
type_num = next_byte + 7
|
||||
if type_num < 7:
|
||||
msg = (
|
||||
"Something went horribly wrong in the decoder. An "
|
||||
f"extended type resolved to a type number < 8 ({type_num})"
|
||||
)
|
||||
raise InvalidDatabaseError(
|
||||
msg,
|
||||
)
|
||||
return type_num, offset + 1
|
||||
|
||||
@staticmethod
|
||||
def _verify_size(expected: int, actual: int) -> None:
|
||||
if expected != actual:
|
||||
raise InvalidDatabaseError(_BAD_DATA)
|
||||
|
||||
def _size_from_ctrl_byte(self, size: int, offset: int) -> tuple[int, int]:
|
||||
# Called only for size codes 29 to 31, which are followed by size bytes.
|
||||
if size == 29:
|
||||
size = 29 + self._buffer[offset]
|
||||
return size, offset + 1
|
||||
|
||||
# Using unpack rather than int_from_bytes as it is faster
|
||||
# here and below.
|
||||
if size == 30:
|
||||
new_offset = offset + 2
|
||||
size_bytes = self._buffer[offset:new_offset]
|
||||
size = 285 + struct.unpack(b"!H", size_bytes)[0]
|
||||
return size, new_offset
|
||||
|
||||
new_offset = offset + 3
|
||||
size_bytes = self._buffer[offset:new_offset]
|
||||
size = struct.unpack(b"!I", b"\x00" + size_bytes)[0] + 65821
|
||||
return size, new_offset
|
||||
@@ -0,0 +1,5 @@
|
||||
"""Typed errors thrown by this library."""
|
||||
|
||||
|
||||
class InvalidDatabaseError(RuntimeError):
|
||||
"""An error thrown when unexpected data is found in the database."""
|
||||
@@ -0,0 +1,74 @@
|
||||
"""For internal use only. It provides a slice-like file reader."""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import os
|
||||
from typing import overload
|
||||
|
||||
try:
|
||||
from multiprocessing import Lock
|
||||
except ImportError:
|
||||
from threading import Lock # type: ignore[assignment]
|
||||
|
||||
|
||||
class FileBuffer:
|
||||
"""A slice-able file reader."""
|
||||
|
||||
def __init__(self, database: str) -> None:
|
||||
"""Create FileBuffer."""
|
||||
self._handle = open(database, "rb") # noqa: SIM115
|
||||
self._size = os.fstat(self._handle.fileno()).st_size
|
||||
if not hasattr(os, "pread"):
|
||||
self._lock = Lock()
|
||||
|
||||
@overload
|
||||
def __getitem__(self, index: int) -> int: ...
|
||||
|
||||
@overload
|
||||
def __getitem__(self, index: slice) -> bytes: ...
|
||||
|
||||
def __getitem__(self, index: slice | int) -> bytes | int:
|
||||
"""Get item by index."""
|
||||
if isinstance(index, slice):
|
||||
return self._read(index.stop - index.start, index.start)
|
||||
if isinstance(index, int):
|
||||
return self._read(1, index)[0]
|
||||
msg = "Invalid argument type."
|
||||
raise TypeError(msg)
|
||||
|
||||
def rfind(self, needle: bytes, start: int) -> int:
|
||||
"""Reverse find needle from start."""
|
||||
pos = self._read(self._size - start - 1, start).rfind(needle)
|
||||
if pos == -1:
|
||||
return pos
|
||||
return start + pos
|
||||
|
||||
def size(self) -> int:
|
||||
"""Size of file."""
|
||||
return self._size
|
||||
|
||||
def close(self) -> None:
|
||||
"""Close file."""
|
||||
self._handle.close()
|
||||
|
||||
if hasattr(os, "pread"): # type: ignore[attr-defined]
|
||||
|
||||
def _read(self, buffersize: int, offset: int) -> bytes:
|
||||
"""Read that uses pread."""
|
||||
return os.pread(self._handle.fileno(), buffersize, offset) # type: ignore[attr-defined]
|
||||
|
||||
else:
|
||||
|
||||
def _read(self, buffersize: int, offset: int) -> bytes:
|
||||
"""Read with a lock.
|
||||
|
||||
This lock is necessary as after a fork, the different processes
|
||||
will share the same file table entry, even if we dup the fd, and
|
||||
as such the same offsets. There does not appear to be a way to
|
||||
duplicate the file table entry and we cannot re-open based on the
|
||||
original path as that file may have replaced with another or
|
||||
unlinked.
|
||||
"""
|
||||
with self._lock:
|
||||
self._handle.seek(offset)
|
||||
return self._handle.read(buffersize)
|
||||
@@ -0,0 +1,98 @@
|
||||
{
|
||||
"schema_version": 1,
|
||||
"project": "MaxMind-DB-Reader-python",
|
||||
"repository": "https://github.com/maxmind/MaxMind-DB-Reader-python",
|
||||
"release": "v3.2.0",
|
||||
"release_url": "https://github.com/maxmind/MaxMind-DB-Reader-python/releases/tag/v3.2.0",
|
||||
"release_published_at": "2026-09-10T22:11:26Z",
|
||||
"commit": "b6885a05eb5a4729bd213e760a2619c34e4184d2",
|
||||
"license": "Apache-2.0",
|
||||
"license_file": "LICENSE",
|
||||
"retrieved_at_utc": "2026-10-25",
|
||||
"python_requires": ">=3.10",
|
||||
"python_3_11_and_3_14_supported_upstream": true,
|
||||
"runtime_dependencies": "Python standard library only; typing_extensions is inside TYPE_CHECKING guards only",
|
||||
"source_inspection": "Inspected all included module imports, reader mmap/cleanup paths, decoder budgets and all dispatch branches before use. No HTTP, DNS, socket, pickle, subprocess, telemetry, updater or install hooks in included runtime source. FileBuffer fallback is included solely to satisfy upstream imports; application adapter only supplies a verified read-only mmap.",
|
||||
"included_modules": [
|
||||
"__init__.py",
|
||||
"const.py",
|
||||
"decoder.py",
|
||||
"errors.py",
|
||||
"file.py",
|
||||
"reader.py",
|
||||
"types.py"
|
||||
],
|
||||
"excluded": "No C extension, build/install files, tests, docs, API clients, downloaded executable or upstream package __init__ loader.",
|
||||
"local_adapter": "entry_geo._new_reader subclasses only _load_buffer to accept the already SHA256-verified mmap; no path re-open or alternate memory/file/network mode.",
|
||||
"files": {
|
||||
"const.py": {
|
||||
"upstream_url": "https://raw.githubusercontent.com/maxmind/MaxMind-DB-Reader-python/b6885a05eb5a4729bd213e760a2619c34e4184d2/maxminddb/const.py",
|
||||
"upstream_git_blob_sha1": "0f7e9826c510ab41da67fcb5dd69275f2ef43fd7",
|
||||
"upstream_sha256": "44e3afd67f2dd1932b962cb797fed53b76e9758dd78107829d9ca34c78f7de6c",
|
||||
"upstream_size_bytes": 986,
|
||||
"vendored_size_bytes": 986,
|
||||
"vendored_sha256": "44e3afd67f2dd1932b962cb797fed53b76e9758dd78107829d9ca34c78f7de6c",
|
||||
"modifications": []
|
||||
},
|
||||
"decoder.py": {
|
||||
"upstream_url": "https://raw.githubusercontent.com/maxmind/MaxMind-DB-Reader-python/b6885a05eb5a4729bd213e760a2619c34e4184d2/maxminddb/decoder.py",
|
||||
"upstream_git_blob_sha1": "9ef985abd276d14b42d8a46f4e2c21ae574b3cfb",
|
||||
"upstream_sha256": "cd05d6b9cac680b30636ce12036f884abc7654f741279a49700ac5d91bac6ddc",
|
||||
"upstream_size_bytes": 13289,
|
||||
"vendored_size_bytes": 13410,
|
||||
"vendored_sha256": "4d4171bcf373b4a051964b09109739e0f58a972534c825ea7604dd7808c85585",
|
||||
"modifications": [
|
||||
"Added prominent vendoring/modification notice",
|
||||
"Changed maxminddb.* imports to relative imports for isolated vendor_entry_geo package"
|
||||
]
|
||||
},
|
||||
"errors.py": {
|
||||
"upstream_url": "https://raw.githubusercontent.com/maxmind/MaxMind-DB-Reader-python/b6885a05eb5a4729bd213e760a2619c34e4184d2/maxminddb/errors.py",
|
||||
"upstream_git_blob_sha1": "b87bc8d4face8d5e906ae4a45b1d4f7accc42060",
|
||||
"upstream_sha256": "4422ad335e76e52420498e27733b5ff2d5ef790257e27274573038b9a20045eb",
|
||||
"upstream_size_bytes": 160,
|
||||
"vendored_size_bytes": 160,
|
||||
"vendored_sha256": "4422ad335e76e52420498e27733b5ff2d5ef790257e27274573038b9a20045eb",
|
||||
"modifications": []
|
||||
},
|
||||
"file.py": {
|
||||
"upstream_url": "https://raw.githubusercontent.com/maxmind/MaxMind-DB-Reader-python/b6885a05eb5a4729bd213e760a2619c34e4184d2/maxminddb/file.py",
|
||||
"upstream_git_blob_sha1": "1901d9ba6f6b2806080f3dfce30564f7ee95f26c",
|
||||
"upstream_sha256": "f233f4c8ce6ae854a9464530f14d6734951ca4962762981408d520bcfeb1a829",
|
||||
"upstream_size_bytes": 2401,
|
||||
"vendored_size_bytes": 2401,
|
||||
"vendored_sha256": "f233f4c8ce6ae854a9464530f14d6734951ca4962762981408d520bcfeb1a829",
|
||||
"modifications": []
|
||||
},
|
||||
"reader.py": {
|
||||
"upstream_url": "https://raw.githubusercontent.com/maxmind/MaxMind-DB-Reader-python/b6885a05eb5a4729bd213e760a2619c34e4184d2/maxminddb/reader.py",
|
||||
"upstream_git_blob_sha1": "32fe961b7ca8ee019cfa32457ffbcb3b71e51863",
|
||||
"upstream_sha256": "043b409c31dd18d205ec002cbeade355e065d1c29bb1e07382bfd2a3d5aaa87b",
|
||||
"upstream_size_bytes": 13578,
|
||||
"vendored_size_bytes": 13681,
|
||||
"vendored_sha256": "b04dd6ba6f0144f77d201adb0d305758b24cadaa6e8c5ca92a5259fcfe3bfc2e",
|
||||
"modifications": [
|
||||
"Added prominent vendoring/modification notice",
|
||||
"Changed maxminddb.* imports to relative imports for isolated vendor_entry_geo package"
|
||||
]
|
||||
},
|
||||
"types.py": {
|
||||
"upstream_url": "https://raw.githubusercontent.com/maxmind/MaxMind-DB-Reader-python/b6885a05eb5a4729bd213e760a2619c34e4184d2/maxminddb/types.py",
|
||||
"upstream_git_blob_sha1": "fa14eefa6416f5b2cefc2f861caa5069a4d41a5c",
|
||||
"upstream_sha256": "28d1737da3b3176f002187c3b3c0a9a9eb6e137361f4940dfa250e7d14ecf65a",
|
||||
"upstream_size_bytes": 429,
|
||||
"vendored_size_bytes": 429,
|
||||
"vendored_sha256": "28d1737da3b3176f002187c3b3c0a9a9eb6e137361f4940dfa250e7d14ecf65a",
|
||||
"modifications": []
|
||||
},
|
||||
"LICENSE": {
|
||||
"upstream_url": "https://raw.githubusercontent.com/maxmind/MaxMind-DB-Reader-python/b6885a05eb5a4729bd213e760a2619c34e4184d2/LICENSE",
|
||||
"upstream_git_blob_sha1": "d645695673349e3947e8e5ae42332d0ac3164cd7",
|
||||
"upstream_sha256": "cfc7749b96f63bd31c3c42b5c471bf756814053e847c10f3eb003417bc523d30",
|
||||
"upstream_size_bytes": 11358,
|
||||
"vendored_size_bytes": 11358,
|
||||
"vendored_sha256": "cfc7749b96f63bd31c3c42b5c471bf756814053e847c10f3eb003417bc523d30",
|
||||
"modifications": []
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,385 @@
|
||||
# Vendored from MaxMind-DB-Reader-python v3.2.0 (Apache-2.0).
|
||||
# ENI modification: package imports made relative; reader/decoder behavior unchanged.
|
||||
"""Pure-Python reader for the MaxMind DB file format."""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
try:
|
||||
import mmap
|
||||
except ImportError:
|
||||
mmap = None # type: ignore[assignment]
|
||||
|
||||
import contextlib
|
||||
import ipaddress
|
||||
from dataclasses import dataclass
|
||||
from ipaddress import IPv4Address, IPv6Address
|
||||
from typing import IO, TYPE_CHECKING, Any, AnyStr
|
||||
|
||||
from .const import MODE_AUTO, MODE_FD, MODE_FILE, MODE_MEMORY, MODE_MMAP
|
||||
from .decoder import Decoder
|
||||
from .errors import InvalidDatabaseError
|
||||
from .file import FileBuffer
|
||||
|
||||
if TYPE_CHECKING:
|
||||
from collections.abc import Iterator
|
||||
from os import PathLike
|
||||
|
||||
from typing_extensions import Self
|
||||
|
||||
from .types import Record
|
||||
|
||||
_IPV4_MAX_NUM = 2**32
|
||||
|
||||
|
||||
class Reader:
|
||||
"""A pure Python implementation of a reader for the MaxMind DB format.
|
||||
|
||||
IP addresses can be looked up using the ``get`` method.
|
||||
"""
|
||||
|
||||
_DATA_SECTION_SEPARATOR_SIZE = 16
|
||||
_METADATA_START_MARKER = b"\xab\xcd\xefMaxMind.com"
|
||||
|
||||
_buffer: bytes | FileBuffer | "mmap.mmap" # noqa: UP037
|
||||
_buffer_size: int
|
||||
closed: bool
|
||||
_decoder: Decoder
|
||||
_metadata: Metadata
|
||||
_record_size: int
|
||||
_ipv4_start: int
|
||||
|
||||
def __init__(
|
||||
self,
|
||||
database: AnyStr | int | PathLike | IO,
|
||||
mode: int = MODE_AUTO,
|
||||
) -> None:
|
||||
"""Reader for the MaxMind DB file format.
|
||||
|
||||
Arguments:
|
||||
database: A path to a valid MaxMind DB file such as a GeoIP database
|
||||
file, or a file descriptor in the case of MODE_FD.
|
||||
mode: mode to open the database with. Valid mode are:
|
||||
* MODE_MMAP - read from memory map.
|
||||
* MODE_FILE - read database as standard file.
|
||||
* MODE_MEMORY - load database into memory.
|
||||
* MODE_AUTO - tries MODE_MMAP and then MODE_FILE. Default.
|
||||
* MODE_FD - the param passed via database is a file descriptor, not
|
||||
a path. This mode implies MODE_MEMORY.
|
||||
|
||||
"""
|
||||
filename = self._load_buffer(database, mode)
|
||||
|
||||
# Include validation errors in this cleanup scope. TRY301 is suppressed
|
||||
# because the handler only closes the buffer and re-raises the error.
|
||||
try:
|
||||
metadata_start = self._buffer.rfind(
|
||||
self._METADATA_START_MARKER,
|
||||
max(0, self._buffer_size - 128 * 1024),
|
||||
)
|
||||
|
||||
if metadata_start == -1:
|
||||
msg = (
|
||||
f"Error opening database file ({filename}). "
|
||||
"Is this a valid MaxMind DB file?"
|
||||
)
|
||||
raise InvalidDatabaseError( # noqa: TRY301
|
||||
msg,
|
||||
)
|
||||
|
||||
metadata_start += len(self._METADATA_START_MARKER)
|
||||
metadata_decoder = Decoder(self._buffer, metadata_start)
|
||||
(metadata, _) = metadata_decoder.decode(metadata_start)
|
||||
|
||||
if not isinstance(metadata, dict):
|
||||
msg = f"Error reading metadata in database file ({filename})."
|
||||
raise InvalidDatabaseError( # noqa: TRY301
|
||||
msg,
|
||||
)
|
||||
|
||||
self._metadata = Metadata(**metadata)
|
||||
self._record_size = self._metadata.record_size
|
||||
if self._record_size not in (24, 28, 32):
|
||||
msg = f"Unknown record size: {self._record_size}"
|
||||
raise InvalidDatabaseError(msg) # noqa: TRY301
|
||||
if self._metadata.node_count < 0:
|
||||
msg = f"Invalid node count: {self._metadata.node_count}"
|
||||
raise InvalidDatabaseError(msg) # noqa: TRY301
|
||||
|
||||
# Traversal reads nodes below node_count. Once the tree fits, those
|
||||
# reads need no length checks of their own.
|
||||
tree_end = (
|
||||
self._metadata.search_tree_size + self._DATA_SECTION_SEPARATOR_SIZE
|
||||
)
|
||||
if tree_end > self._buffer_size:
|
||||
msg = (
|
||||
f"Error opening database file ({filename}). The search tree "
|
||||
"extends past the end of the file."
|
||||
)
|
||||
raise InvalidDatabaseError(msg) # noqa: TRY301
|
||||
|
||||
self._decoder = Decoder(
|
||||
self._buffer,
|
||||
self._metadata.search_tree_size + self._DATA_SECTION_SEPARATOR_SIZE,
|
||||
)
|
||||
self.closed = False
|
||||
|
||||
ipv4_start = 0
|
||||
if self._metadata.ip_version == 6:
|
||||
# We store the IPv4 starting node as an optimization for IPv4 lookups
|
||||
# in IPv6 trees. This allows us to skip over the first 96 nodes in
|
||||
# this case.
|
||||
node = 0
|
||||
for _ in range(96):
|
||||
if node >= self._metadata.node_count:
|
||||
break
|
||||
node = self._read_node(node, 0)
|
||||
ipv4_start = node
|
||||
self._ipv4_start = ipv4_start
|
||||
except BaseException:
|
||||
# Release the buffer on any initialization failure.
|
||||
self.close()
|
||||
raise
|
||||
|
||||
def metadata(self) -> Metadata:
|
||||
"""Return the metadata associated with the MaxMind DB file."""
|
||||
return self._metadata
|
||||
|
||||
def get(self, ip_address: str | IPv6Address | IPv4Address) -> Record | None:
|
||||
"""Return the record for the ip_address in the MaxMind DB.
|
||||
|
||||
Arguments:
|
||||
ip_address: an IP address in the standard string notation
|
||||
|
||||
"""
|
||||
(record, _) = self.get_with_prefix_len(ip_address)
|
||||
return record
|
||||
|
||||
def get_with_prefix_len(
|
||||
self,
|
||||
ip_address: str | IPv6Address | IPv4Address,
|
||||
) -> tuple[Record | None, int]:
|
||||
"""Return a tuple with the record and the associated prefix length.
|
||||
|
||||
Arguments:
|
||||
ip_address: an IP address in the standard string notation
|
||||
|
||||
"""
|
||||
if isinstance(ip_address, str):
|
||||
address = ipaddress.ip_address(ip_address)
|
||||
else:
|
||||
address = ip_address
|
||||
|
||||
try:
|
||||
packed_address = bytearray(address.packed)
|
||||
except AttributeError as ex:
|
||||
msg = "argument 1 must be a string or ipaddress object"
|
||||
raise TypeError(msg) from ex
|
||||
|
||||
if address.version == 6 and self._metadata.ip_version == 4:
|
||||
msg = (
|
||||
f"Error looking up {ip_address}. You attempted to look up "
|
||||
"an IPv6 address in an IPv4-only database."
|
||||
)
|
||||
raise ValueError(
|
||||
msg,
|
||||
)
|
||||
|
||||
(pointer, prefix_len) = self._find_address_in_tree(packed_address)
|
||||
|
||||
if pointer:
|
||||
return self._resolve_data_pointer(pointer), prefix_len
|
||||
return None, prefix_len
|
||||
|
||||
def __iter__(self) -> Iterator:
|
||||
return self._generate_children(0, 0, 0)
|
||||
|
||||
def _generate_children(self, node: int, depth: int, ip_acc: int) -> Iterator:
|
||||
if ip_acc != 0 and node == self._ipv4_start:
|
||||
# Skip nodes aliased to IPv4
|
||||
return
|
||||
|
||||
node_count = self._metadata.node_count
|
||||
if node > node_count:
|
||||
bits = 128 if self._metadata.ip_version == 6 else 32
|
||||
ip_acc <<= bits - depth
|
||||
if ip_acc <= _IPV4_MAX_NUM and bits == 128:
|
||||
depth -= 96
|
||||
yield (
|
||||
ipaddress.ip_network((ip_acc, depth)),
|
||||
self._resolve_data_pointer(
|
||||
node,
|
||||
),
|
||||
)
|
||||
elif node < node_count:
|
||||
left = self._read_node(node, 0)
|
||||
ip_acc <<= 1
|
||||
depth += 1
|
||||
yield from self._generate_children(left, depth, ip_acc)
|
||||
right = self._read_node(node, 1)
|
||||
yield from self._generate_children(right, depth, ip_acc | 1)
|
||||
|
||||
def _find_address_in_tree(self, packed: bytearray) -> tuple[int, int]:
|
||||
bit_count = len(packed) * 8
|
||||
node = self._start_node(bit_count)
|
||||
node_count = self._metadata.node_count
|
||||
|
||||
i = 0
|
||||
while i < bit_count and node < node_count:
|
||||
bit = 1 & (packed[i >> 3] >> 7 - (i % 8))
|
||||
node = self._read_node(node, bit)
|
||||
i = i + 1
|
||||
|
||||
if node == node_count:
|
||||
# Record is empty
|
||||
return 0, i
|
||||
if node > node_count:
|
||||
return node, i
|
||||
|
||||
msg = "Invalid node in search tree"
|
||||
raise InvalidDatabaseError(msg)
|
||||
|
||||
def _start_node(self, length: int) -> int:
|
||||
if self._metadata.ip_version == 6 and length == 32:
|
||||
return self._ipv4_start
|
||||
return 0
|
||||
|
||||
def _read_node(self, node_number: int, index: int) -> int:
|
||||
record_size = self._record_size
|
||||
if record_size == 28:
|
||||
# Two 28-bit records share the middle byte: its high nibble
|
||||
# belongs to the left record and its low nibble to the right.
|
||||
base_offset = node_number * 7
|
||||
if index:
|
||||
offset = base_offset + 3
|
||||
record = int.from_bytes(self._buffer[offset : offset + 4], "big")
|
||||
return record & 0x0FFFFFFF
|
||||
record = int.from_bytes(self._buffer[base_offset : base_offset + 4], "big")
|
||||
return (record >> 8) | ((record & 0xF0) << 20)
|
||||
if record_size == 24:
|
||||
offset = node_number * 6 + index * 3
|
||||
return int.from_bytes(self._buffer[offset : offset + 3], "big")
|
||||
if record_size == 32:
|
||||
offset = node_number * 8 + index * 4
|
||||
return int.from_bytes(self._buffer[offset : offset + 4], "big")
|
||||
msg = f"Unknown record size: {record_size}"
|
||||
raise InvalidDatabaseError(msg)
|
||||
|
||||
def _resolve_data_pointer(self, pointer: int) -> Record:
|
||||
resolved = pointer - self._metadata.node_count + self._metadata.search_tree_size
|
||||
|
||||
if resolved >= self._buffer_size:
|
||||
msg = "The MaxMind DB file's search tree is corrupt"
|
||||
raise InvalidDatabaseError(msg)
|
||||
|
||||
(data, _) = self._decoder.decode(resolved)
|
||||
return data
|
||||
|
||||
def _load_buffer(
|
||||
self, database: AnyStr | int | PathLike | IO, mode: int = MODE_AUTO
|
||||
) -> str:
|
||||
filename: Any
|
||||
if (mode == MODE_AUTO and mmap) or mode == MODE_MMAP:
|
||||
with open(database, "rb") as db_file: # type: ignore[arg-type]
|
||||
self._buffer = mmap.mmap(db_file.fileno(), 0, access=mmap.ACCESS_READ)
|
||||
self._buffer_size = self._buffer.size()
|
||||
filename = database
|
||||
elif mode in (MODE_AUTO, MODE_FILE):
|
||||
self._buffer = FileBuffer(database) # type: ignore[arg-type]
|
||||
self._buffer_size = self._buffer.size()
|
||||
filename = database
|
||||
elif mode == MODE_MEMORY:
|
||||
with open(database, "rb") as db_file: # type: ignore[arg-type]
|
||||
buf = db_file.read()
|
||||
self._buffer = buf
|
||||
self._buffer_size = len(buf)
|
||||
filename = database
|
||||
elif mode == MODE_FD:
|
||||
self._buffer = database.read() # type: ignore[union-attr]
|
||||
self._buffer_size = len(self._buffer) # type: ignore[arg-type]
|
||||
# io buffers are not guaranteed to have a name attribute
|
||||
if hasattr(database, "name"):
|
||||
filename = database.name # type: ignore[union-attr]
|
||||
else:
|
||||
filename = f"<{type(database)}>"
|
||||
else:
|
||||
msg = (
|
||||
f"Unsupported open mode ({mode}). Only MODE_AUTO, MODE_FILE, "
|
||||
"MODE_MEMORY and MODE_FD are supported by the pure Python "
|
||||
"Reader"
|
||||
)
|
||||
raise ValueError(
|
||||
msg,
|
||||
)
|
||||
|
||||
return filename
|
||||
|
||||
def close(self) -> None:
|
||||
"""Close the MaxMind DB file and returns the resources to the system.
|
||||
|
||||
Calling this method while reads are in progress may cause exceptions.
|
||||
"""
|
||||
with contextlib.suppress(AttributeError):
|
||||
self._buffer.close() # type: ignore[union-attr]
|
||||
|
||||
self.closed = True
|
||||
|
||||
def __exit__(self, *_) -> None: # noqa: ANN002
|
||||
self.close()
|
||||
|
||||
def __enter__(self) -> Self:
|
||||
if self.closed:
|
||||
msg = "Attempt to reopen a closed MaxMind DB"
|
||||
raise ValueError(msg)
|
||||
return self
|
||||
|
||||
|
||||
@dataclass(kw_only=True, frozen=True)
|
||||
class Metadata:
|
||||
"""Metadata for the MaxMind DB reader."""
|
||||
|
||||
binary_format_major_version: int
|
||||
"""
|
||||
The major version number of the binary format used when creating the
|
||||
database.
|
||||
"""
|
||||
|
||||
binary_format_minor_version: int
|
||||
"""
|
||||
The minor version number of the binary format used when creating the
|
||||
database.
|
||||
"""
|
||||
|
||||
build_epoch: int
|
||||
"""The Unix epoch for the build time of the database."""
|
||||
|
||||
database_type: str
|
||||
"""A string identifying the database type, e.g., "GeoIP2-City"."""
|
||||
|
||||
description: dict[str, str]
|
||||
"""A map from locales to text descriptions of the database."""
|
||||
|
||||
ip_version: int
|
||||
"""
|
||||
The IP version of the data in a database. A value of "4" means the
|
||||
database only supports IPv4. A database with a value of "6" may support
|
||||
both IPv4 and IPv6 lookups.
|
||||
"""
|
||||
|
||||
languages: list[str]
|
||||
"""A list of locale codes supported by the database."""
|
||||
|
||||
node_count: int
|
||||
"""The number of nodes in the database."""
|
||||
|
||||
record_size: int
|
||||
"""The bit size of a record in the search tree."""
|
||||
|
||||
@property
|
||||
def node_byte_size(self) -> int:
|
||||
"""The size of a node in bytes."""
|
||||
return self.record_size // 4
|
||||
|
||||
@property
|
||||
def search_tree_size(self) -> int:
|
||||
"""The size of the search tree."""
|
||||
return self.node_count * self.node_byte_size
|
||||
@@ -0,0 +1,15 @@
|
||||
"""Types representing database records."""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
from typing import AnyStr, TypeAlias
|
||||
|
||||
Primitive: TypeAlias = AnyStr | bool | float | int
|
||||
|
||||
RecordList: TypeAlias = list["Record"]
|
||||
"""RecordList is a type for lists in a database record."""
|
||||
|
||||
RecordDict: TypeAlias = dict[str, "Record"]
|
||||
"""RecordDict is a type for dicts in a database record."""
|
||||
|
||||
Record: TypeAlias = Primitive | RecordList | RecordDict
|
||||
@@ -0,0 +1,490 @@
|
||||
# -*- coding: utf-8 -*-
|
||||
import asyncio
|
||||
from contextlib import closing
|
||||
from pathlib import Path
|
||||
import hashlib
|
||||
import json
|
||||
import math
|
||||
import os
|
||||
import re
|
||||
import secrets
|
||||
import sqlite3
|
||||
import sys
|
||||
import time
|
||||
|
||||
os.chdir(os.path.dirname(os.path.abspath(__file__)))
|
||||
sys.path[:0] = os.environ.get("IISHKO_RUNTIME_PATHS", os.environ.get("IISHKO_APP_ROOT", str(Path(__file__).resolve().parent.parent))).split(os.pathsep)
|
||||
import key_issue_guard
|
||||
from account_limits import account_uid, account_token_names
|
||||
import account_balances
|
||||
_so = sys.stdout
|
||||
sys.stdout = sys.stderr
|
||||
try:
|
||||
import grok_bot as g
|
||||
finally:
|
||||
sys.stdout = _so
|
||||
BOT_DB = os.environ.get("IISHKO_BOT_DB") or os.environ.get("GROK_BOT_DB", "/opt/grok-bot/bot.db")
|
||||
GW_DB = g.CFG['newapi_db']
|
||||
Q = g.QUOTA_PER_UNIT
|
||||
|
||||
|
||||
class KeyErrorSafe(ValueError):
|
||||
pass
|
||||
|
||||
|
||||
def _fail(message):
|
||||
raise KeyErrorSafe(message)
|
||||
|
||||
|
||||
def _connect():
|
||||
con = sqlite3.connect(Path(GW_DB).resolve().as_uri() + '?mode=rw',
|
||||
uri=True, timeout=20, isolation_level=None)
|
||||
con.row_factory = sqlite3.Row
|
||||
con.execute('PRAGMA busy_timeout=20000')
|
||||
try:
|
||||
con.execute('ATTACH DATABASE ? AS bot', (Path(BOT_DB).resolve().as_uri() + '?mode=rw',))
|
||||
con.execute('CREATE TABLE IF NOT EXISTS wa_key_operations ('
|
||||
'uid INTEGER NOT NULL, request_id TEXT NOT NULL,digest TEXT NOT NULL,'
|
||||
'result TEXT NOT NULL,PRIMARY KEY(uid,request_id))')
|
||||
con.execute('CREATE TABLE IF NOT EXISTS wa_key_locks ('
|
||||
'tid INTEGER PRIMARY KEY,uid INTEGER NOT NULL,name TEXT NOT NULL)')
|
||||
return con
|
||||
except Exception:
|
||||
con.close()
|
||||
raise
|
||||
|
||||
|
||||
def _user(con, uid):
|
||||
if type(uid) is not int or not 0 < uid <= 9223372036854775807:
|
||||
_fail('Некорректный пользователь')
|
||||
row = con.execute('SELECT * FROM bot.users WHERE tg_id=?', (uid,)).fetchone()
|
||||
if not row:
|
||||
_fail('Сначала открой бота и зарегистрируйся')
|
||||
u = dict(row)
|
||||
if u['banned'] or u['api_blocked']:
|
||||
_fail('Доступ к API заблокирован. Поддержка: @your-handle')
|
||||
if u.get('token_name') and account_uid(u['token_name']) != uid:
|
||||
_fail('Ключ не принадлежит аккаунту. Нужна проверка поддержки')
|
||||
if u.get('api_key'):
|
||||
if not isinstance(u['api_key'], str):
|
||||
_fail('Не удалось подтвердить ключ аккаунта')
|
||||
owners = con.execute('SELECT name FROM tokens WHERE key=?',
|
||||
(u['api_key'].removeprefix('sk-'),)).fetchall()
|
||||
if any(account_uid(r['name']) != uid for r in owners):
|
||||
_fail('Ключ не принадлежит аккаунту. Нужна проверка поддержки')
|
||||
return u
|
||||
|
||||
|
||||
def _name(uid, n, promo=False):
|
||||
if type(n) is not int or n < (-1 if promo else 0) or n > 1000000:
|
||||
_fail('Некорректный номер ключа')
|
||||
return 'pm%d' % uid if n == -1 else ('tg%d' % uid if n == 0 else 'tg%d-k%d' % (uid, n))
|
||||
|
||||
|
||||
def _row(con, uid, n, u, required=True):
|
||||
name = _name(uid, n, promo=True)
|
||||
rows = con.execute('SELECT * FROM tokens WHERE name=? AND deleted_at IS NULL ORDER BY id', (name,)).fetchall()
|
||||
if n == 0 and u.get('api_key'):
|
||||
raw = u['api_key'].removeprefix('sk-')
|
||||
canonical = [r for r in rows if r['key'] == raw]
|
||||
if len(canonical) == 1:
|
||||
return canonical[0]
|
||||
if len(rows) > 1:
|
||||
_fail('Найдены дубли ключа. Нужна проверка поддержки; баланс сохранён')
|
||||
if not rows and required:
|
||||
_fail('Ключ не найден')
|
||||
return rows[0] if rows else None
|
||||
|
||||
|
||||
def _rows(con, uid, u):
|
||||
out = []
|
||||
for name in account_token_names(con, uid):
|
||||
match = re.fullmatch(r'tg%d-k([1-9][0-9]*)' % uid, name)
|
||||
if name == 'tg%d' % uid or match:
|
||||
n = int(match[1]) if match else 0
|
||||
out.append((n, _row(con, uid, n, u)))
|
||||
return sorted(out, key=lambda item: item[0])
|
||||
|
||||
|
||||
def _digest(action, params):
|
||||
return hashlib.sha256(json.dumps([action, params], sort_keys=True, allow_nan=False).encode()).hexdigest()
|
||||
|
||||
|
||||
def _request(request_id):
|
||||
if not isinstance(request_id, str) or not re.fullmatch(r'[A-Za-z0-9_-]{12,96}', request_id):
|
||||
_fail('Нужен уникальный идентификатор операции. Обнови Mini App')
|
||||
|
||||
|
||||
def _receipt(con, uid, request_id, digest):
|
||||
row = con.execute('SELECT digest,result FROM wa_key_operations WHERE uid=? AND request_id=?',
|
||||
(uid, request_id)).fetchone()
|
||||
if not row:
|
||||
return None
|
||||
if row['digest'] != digest:
|
||||
_fail('Этот номер уже использован другой операцией')
|
||||
result = json.loads(row['result'])
|
||||
if result.get('name') and account_uid(result['name']) != uid:
|
||||
_fail('Не удалось подтвердить владельца операции')
|
||||
if result.get('token_id') is not None:
|
||||
tid = result['token_id']
|
||||
if type(tid) is not int or tid <= 0:
|
||||
_fail('Не удалось подтвердить ключ операции')
|
||||
token = con.execute('SELECT key,name FROM tokens WHERE id=? AND deleted_at IS NULL',
|
||||
(tid,)).fetchone()
|
||||
if token:
|
||||
if account_uid(token['name']) != uid or result.get('name', token['name']) != token['name']:
|
||||
_fail('Не удалось подтвердить владельца операции')
|
||||
result['key'] = 'sk-' + token['key']
|
||||
return result
|
||||
|
||||
|
||||
async def _subscribed(uid):
|
||||
bot = g.Bot(token=g.CFG['bot_token'])
|
||||
try:
|
||||
return await g.is_subscribed(bot, uid)
|
||||
finally:
|
||||
await bot.session.close()
|
||||
|
||||
|
||||
def _owned_history(con, uid):
|
||||
terms, args = [], []
|
||||
for prefix in ('tg', 'pm', 'sol'):
|
||||
name = prefix + str(uid)
|
||||
terms.extend(('name=?', 'name GLOB ?'))
|
||||
args.extend((name, name + '-k[0-9]*'))
|
||||
rows = con.execute('SELECT * FROM tokens WHERE ' + ' OR '.join(terms), args).fetchall()
|
||||
return [row for row in rows if account_uid(row['name']) == uid]
|
||||
|
||||
|
||||
def _create(con, uid, u, now, issue_device=None):
|
||||
if not isinstance(issue_device, str) or not re.fullmatch(r'[a-f0-9]{64}', issue_device):
|
||||
_fail('Обнови Mini App и разреши хранение данных для выдачи ключа')
|
||||
main = _row(con, uid, 0, u, required=False)
|
||||
rows = _rows(con, uid, u)
|
||||
if not main:
|
||||
wait = int(u.get('created') or 0) + g.KEY_WAIT_SEC
|
||||
if wait > now and int(u.get('unlim_until') or 0) <= now:
|
||||
_fail('Основной ключ доступен через %s после регистрации' %
|
||||
('24 часа' if g.KEY_WAIT_SEC == 86400 else '%d ч' % (g.KEY_WAIT_SEC // 3600)))
|
||||
if len(rows) >= g.MK_CAP.get(g.badge_of(uid), 2):
|
||||
_fail('Достигнут лимит ключей ранга (включая основной)')
|
||||
history = _owned_history(con, uid)
|
||||
recent = max((int(row['created_time'] or 0) for row in history), default=0)
|
||||
if recent and now - int(recent) < 45:
|
||||
_fail('Подожди минуту перед созданием следующего ключа')
|
||||
# [device issuance] Installation-wide cap on distinct accounts; checked inside the same
|
||||
# transaction and before allocation, so NAT/account gates stay untouched.
|
||||
try:
|
||||
key_issue_guard.check_device(con, uid, issue_device, now)
|
||||
except ValueError as error:
|
||||
_fail(str(error))
|
||||
if main:
|
||||
n = 1
|
||||
occupied = {item[0] for item in rows}
|
||||
while n in occupied:
|
||||
n += 1
|
||||
quota, unlimited = 0, 0
|
||||
else:
|
||||
n = 0
|
||||
beneficiary_table = con.execute(
|
||||
"SELECT 1 FROM bot.sqlite_master WHERE type='table' AND name='wa_issue_beneficiaries'"
|
||||
).fetchone()
|
||||
prior_grant = bool(beneficiary_table and con.execute(
|
||||
'SELECT 1 FROM bot.wa_issue_beneficiaries WHERE uid=? LIMIT 1', (uid,)).fetchone())
|
||||
prior_create = any(json.loads(row[0]).get('n') == 0 for row in con.execute(
|
||||
'SELECT result FROM wa_key_operations WHERE uid=?', (uid,)))
|
||||
first = (not history and not u.get('api_key') and not u.get('token_name') and
|
||||
not prior_grant and not prior_create and
|
||||
not u.get('key_locked') and not u.get('chat_key_locked'))
|
||||
# All account families/history share one first issuance; never a new bucket.
|
||||
if first:
|
||||
try:
|
||||
key_issue_guard.bind_beneficiary(con, uid, issue_device, now)
|
||||
except ValueError as error:
|
||||
_fail(str(error))
|
||||
quota = g.first_mint_bonus(uid, g.CFG['user_quota']) if first else 0
|
||||
unlimited = int(bool(g.CFG['unlimited'])) if first else 0
|
||||
name, raw = _name(uid, n), secrets.token_hex(24)
|
||||
previous_main = main
|
||||
status, expires = 1, -1
|
||||
if previous_main is not None:
|
||||
status = int(previous_main['status'])
|
||||
expires = -1 if previous_main['expired_time'] is None else int(previous_main['expired_time'])
|
||||
if u.get('key_locked') or u.get('chat_key_locked'):
|
||||
status = 2
|
||||
cursor = con.execute('INSERT INTO tokens (user_id,key,name,status,created_time,accessed_time,expired_time,'
|
||||
'remain_quota,unlimited_quota,model_limits_enabled,model_limits,allow_ips,used_quota,"group",deleted_at) '
|
||||
'VALUES (?,?,?,?,?,?,?, ?,?,1,?,\'\',0,?,NULL)',
|
||||
(g.newapi_user_id(GW_DB), raw, name, status, now, now, expires, quota, unlimited,
|
||||
','.join(g.rank_models(uid)), 't%d' % g.tier_of(uid)))
|
||||
if status == 2 and (u.get('key_locked') or u.get('chat_key_locked') or
|
||||
previous_main is not None and con.execute(
|
||||
'SELECT 1 FROM wa_key_locks WHERE tid=? AND uid=? AND name=?',
|
||||
(previous_main['id'], uid, previous_main['name'])).fetchone()):
|
||||
con.execute('INSERT INTO wa_key_locks VALUES (?,?,?)', (cursor.lastrowid, uid, name))
|
||||
if n == 0:
|
||||
con.execute('UPDATE bot.users SET token_name=?,api_key=? WHERE tg_id=?', (name, 'sk-' + raw, uid))
|
||||
# [device issuance] Same transaction as the token insert: a rollback unbinds the name.
|
||||
try:
|
||||
key_issue_guard.record_device(con, uid, issue_device, name, now)
|
||||
except ValueError as error:
|
||||
_fail(str(error))
|
||||
return {'ok': True, 'n': n, 'name': name, 'key': 'sk-' + raw, 'token_id': cursor.lastrowid}
|
||||
|
||||
|
||||
def _move(con, src, dst, amount=None):
|
||||
if int(src['unlimited_quota'] or 0) or int(dst['unlimited_quota'] or 0):
|
||||
_fail('Переводы безлимитных ключей не поддерживаются')
|
||||
available = max(0, int(src['remain_quota'] or 0))
|
||||
amount = available if amount is None else amount
|
||||
if amount < 0 or amount > available:
|
||||
_fail('Недостаточно API-кредита')
|
||||
uid = account_uid(src['name'])
|
||||
if uid is None or account_uid(dst['name']) != uid:
|
||||
_fail('Ключ не принадлежит аккаунту. Баланс сохранён')
|
||||
user = _user(con, uid)
|
||||
if user.get('cap_paused') or user.get('key_locked'):
|
||||
_fail('Доступ к API приостановлен для аккаунта; баланс сохранён')
|
||||
now = int(time.time())
|
||||
for row in (src, dst):
|
||||
status = int(row['status'] or 0)
|
||||
expired = row['expired_time'] is not None and 0 <= int(row['expired_time']) <= now
|
||||
if status not in (1, 4) or expired or row['deleted_at'] is not None:
|
||||
_fail('Ключ приостановлен или истёк; перевод недоступен, баланс сохранён')
|
||||
if status == 4:
|
||||
# Exhaustion is not an admin pause. Preserve even legacy lock evidence.
|
||||
locked = con.execute('SELECT 1 FROM wa_key_locks WHERE tid=?', (row['id'],)).fetchone()
|
||||
has_pauses = con.execute(
|
||||
"SELECT 1 FROM sqlite_master WHERE type='table' AND name='wa_daily_cap_pauses'"
|
||||
).fetchone()
|
||||
paused = has_pauses and con.execute(
|
||||
'SELECT 1 FROM wa_daily_cap_pauses WHERE tid=?', (row['id'],)).fetchone()
|
||||
if locked or paused:
|
||||
_fail('Не удалось подтвердить причину ограничения ключа; баланс сохранён')
|
||||
if amount:
|
||||
for row, sign in ((src, '-'), (dst, '+')):
|
||||
changed = con.execute(
|
||||
'UPDATE tokens SET remain_quota=COALESCE(remain_quota,0)' + sign + '?,'
|
||||
'status=CASE WHEN status=4 AND COALESCE(remain_quota,0)' + sign + '?>0 '
|
||||
'THEN 1 ELSE status END WHERE id=? AND deleted_at IS NULL AND status IN (1,4)',
|
||||
(amount, amount, row['id']))
|
||||
if changed.rowcount != 1:
|
||||
_fail('Состояние ключа изменилось; баланс сохранён')
|
||||
return amount
|
||||
|
||||
|
||||
def mutate(action, uid, request_id, issue_device=None, **params):
|
||||
_request(request_id)
|
||||
digest = _digest(action, params)
|
||||
# External check happens outside the write transaction and follows existing bot policy.
|
||||
if action == 'create':
|
||||
with closing(_connect()) as con:
|
||||
_user(con, uid)
|
||||
previous = _receipt(con, uid, request_id, digest)
|
||||
if previous:
|
||||
return previous
|
||||
if not asyncio.run(_subscribed(uid)):
|
||||
_fail('Подпишись на канал бота, затем повтори получение ключа в Mini App')
|
||||
# [FIX-2410] чтение econ_cap_state.json ДО BEGIN IMMEDIATE — не держим write-lock ради файлового I/O
|
||||
pause_state = _read_pause_state() if action == 'lock' else None
|
||||
with closing(_connect()) as con:
|
||||
try:
|
||||
con.execute('BEGIN IMMEDIATE')
|
||||
u = _user(con, uid)
|
||||
previous = _receipt(con, uid, request_id, digest)
|
||||
if previous:
|
||||
con.rollback()
|
||||
return previous
|
||||
now = int(time.time())
|
||||
if action == 'create':
|
||||
result = _create(con, uid, u, now, issue_device=issue_device)
|
||||
elif action == 'return_all':
|
||||
if params:
|
||||
_fail('Возврат всех остатков не принимает параметры ключа или суммы')
|
||||
main = _row(con, uid, 0, u)
|
||||
trusted, ambiguous = account_balances.owned_rows(con, uid, u)
|
||||
sources = [row for row in trusted if '-k' in row['name'] and not row['name'].startswith('pm')]
|
||||
trusted_ids = {row['id'] for row in trusted}
|
||||
if ambiguous or main['id'] not in trusted_ids or any(row['id'] not in trusted_ids for row in sources):
|
||||
_fail('Нельзя подтвердить владельца всех ключей. Баланс сохранён')
|
||||
moved = sum(_move(con, row, main) for row in sources)
|
||||
con.execute('INSERT INTO bot.econ_tx(src,dst,units,type,ts) VALUES(?,?,?,?,?)',
|
||||
(uid, uid, moved, 'web:key_return_all', now))
|
||||
result = {'ok': True, 'moved_usd': moved / Q, 'returned_keys': len(sources),
|
||||
**account_balances.snapshot(con, uid, u, Q)}
|
||||
else:
|
||||
n = params.get('n')
|
||||
_name(uid, n)
|
||||
row = _row(con, uid, n, u)
|
||||
if action == 'lock':
|
||||
if _daily_pause_info(con, row, u, state=pause_state).get('daily_paused'):
|
||||
_fail('Достигнут дневной лимит API. Доступ возобновится после 00:00 МСК при следующей проверке; баланс сохранён')
|
||||
current = int(row['status'])
|
||||
own_lock = con.execute('SELECT 1 FROM wa_key_locks WHERE tid=? AND uid=? AND name=?',
|
||||
(row['id'], uid, row['name'])).fetchone()
|
||||
if current == 1:
|
||||
status = 2
|
||||
con.execute('INSERT OR REPLACE INTO wa_key_locks VALUES (?,?,?)',
|
||||
(row['id'], uid, row['name']))
|
||||
elif current == 2 and (own_lock or n == 0 and u.get('key_locked')):
|
||||
status = 1
|
||||
con.execute('DELETE FROM wa_key_locks WHERE tid=?', (row['id'],))
|
||||
else:
|
||||
_fail('Ключ ограничен администратором или истёк; самостоятельная разблокировка недоступна')
|
||||
con.execute('UPDATE tokens SET status=? WHERE id=?', (status, row['id']))
|
||||
if n == 0:
|
||||
con.execute('UPDATE bot.users SET key_locked=? WHERE tg_id=?', (int(status == 2), uid))
|
||||
result = {'ok': True, 'status': status}
|
||||
elif action in ('transfer', 'del'):
|
||||
if n < 1:
|
||||
_fail('Эта операция доступна только для дополнительного ключа')
|
||||
main = _row(con, uid, 0, u)
|
||||
if action == 'del':
|
||||
moved = _move(con, row, main)
|
||||
con.execute('UPDATE tokens SET status=2,deleted_at=? WHERE id=?', (now, row['id']))
|
||||
else:
|
||||
usd, direction = params.get('usd'), params.get('direction')
|
||||
if type(usd) not in (int, float) or not math.isfinite(usd) or direction not in ('to', 'from'):
|
||||
_fail('Проверь сумму и направление перевода')
|
||||
if not (1 <= usd <= 1000 or usd == 0 and direction == 'from'):
|
||||
_fail('Сумма перевода: от 1 до 1000; возврат всего остатка: 0')
|
||||
units = int(round(usd * Q)) if usd else None
|
||||
moved = _move(con, row if direction == 'from' else main, main if direction == 'from' else row, units)
|
||||
con.execute('INSERT INTO bot.econ_tx(src,dst,units,type,ts) VALUES (?,?,?,?,?)',
|
||||
(uid, uid, moved, 'web:key_' + action, now))
|
||||
result = {'ok': True, 'moved_usd': moved / Q}
|
||||
else:
|
||||
_fail('Неизвестная операция')
|
||||
receipt = {k: v for k, v in result.items() if k != 'key'}
|
||||
con.execute('INSERT INTO wa_key_operations VALUES (?,?,?,?)', (uid, request_id, digest, json.dumps(receipt)))
|
||||
con.commit()
|
||||
return result
|
||||
except BaseException:
|
||||
con.rollback()
|
||||
raise
|
||||
|
||||
|
||||
def cmd_replay(uid, action, request_id, **params):
|
||||
_request(request_id)
|
||||
with closing(_connect()) as con:
|
||||
_user(con, uid)
|
||||
result = _receipt(con, uid, request_id, _digest(action, params))
|
||||
return result if result is not None else {'ok': True, 'found': False}
|
||||
|
||||
|
||||
def cmd_reveal(uid, n):
|
||||
with closing(_connect()) as con:
|
||||
u = _user(con, uid)
|
||||
r = _row(con, uid, n, u)
|
||||
return {'ok': True, 'key': 'sk-' + r['key'], 'name': r['name']}
|
||||
|
||||
|
||||
def _read_pause_state(state_path='/opt/grok-bot/econ_cap_state.json'):
|
||||
# [FIX-2410] чтение JSON-состояния вынесено из BEGIN IMMEDIATE-транзакции
|
||||
try:
|
||||
with open(state_path, encoding='utf-8') as fh:
|
||||
state = json.load(fh)
|
||||
return state if isinstance(state, dict) else {}
|
||||
except (OSError, ValueError):
|
||||
return {}
|
||||
|
||||
|
||||
def _daily_pause_info(con, row, user, state=None, state_path='/opt/grok-bot/econ_cap_state.json'):
|
||||
if int(row['status']) != 2 or user.get('key_locked'):
|
||||
return {}
|
||||
try:
|
||||
durable = con.execute(
|
||||
"SELECT 1 FROM sqlite_master WHERE type='table' AND name='wa_daily_cap_pauses'"
|
||||
).fetchone()
|
||||
if durable:
|
||||
record = con.execute(
|
||||
'SELECT tid,name,ts,prev_status FROM wa_daily_cap_pauses WHERE tid=? AND name=?',
|
||||
(row['id'], row['name'])).fetchone()
|
||||
pause = dict(record) if record else None
|
||||
else:
|
||||
# [FIX-2410] файл читается вызывающей стороной до BEGIN IMMEDIATE; ленивое чтение — только fallback
|
||||
if state is None:
|
||||
state = _read_pause_state(state_path)
|
||||
pause = state.get('paused', {}).get(row['name']) if state and state.get('v', 2) == 2 else None
|
||||
if not isinstance(pause, dict) or pause.get('tid') != row['id']:
|
||||
return {}
|
||||
if pause.get('flag_only'):
|
||||
return {}
|
||||
if pause.get('prev_status') != 1:
|
||||
return {}
|
||||
stamp = int(pause['ts'])
|
||||
if stamp <= 0:
|
||||
return {}
|
||||
retry_at = stamp - ((stamp + 3 * 3600) % 86400) + 86400
|
||||
return {'daily_paused': True, 'retry_at': retry_at,
|
||||
'status_reason': 'Дневной лимит API; баланс сохранён'}
|
||||
except (OSError, ValueError, TypeError, KeyError, AttributeError, sqlite3.Error):
|
||||
# Unknown or invalid ownership evidence remains unclassified.
|
||||
return {}
|
||||
|
||||
|
||||
def cmd_list(uid):
|
||||
with closing(_connect()) as con:
|
||||
u = _user(con, uid)
|
||||
rows = _rows(con, uid, u)
|
||||
# Recover a lost bot pointer from an unambiguous existing main, never mint a duplicate.
|
||||
main = next((r for n, r in rows if n == 0), None)
|
||||
if main is not None and (u.get('api_key') != 'sk-' + main['key'] or u.get('token_name') != main['name']):
|
||||
con.execute('UPDATE bot.users SET token_name=?,api_key=? WHERE tg_id=?', (main['name'], 'sk-' + main['key'], uid))
|
||||
promo = _row(con, uid, -1, u, required=False)
|
||||
output = []
|
||||
# [FIX-2410] состояние читаем один раз до цикла (не в каждой строке, не внутри write-контекста)
|
||||
pause_state = _read_pause_state()
|
||||
for n, r in rows + ([(-1, promo)] if promo else []):
|
||||
raw = r['key']
|
||||
output.append({'n': n, 'main': n == 0, 'promo': n == -1, 'name': r['name'],
|
||||
'masked': raw[:6] + '…' + raw[-4:], 'status': r['status'],
|
||||
'remain_usd': (r['remain_quota'] or 0) / Q, 'used_usd': (r['used_quota'] or 0) / Q,
|
||||
'unlimited': r['unlimited_quota'], 'models_n': len((r['model_limits'] or '').split(',')),
|
||||
'group': r['group'], 'created': r['created_time']})
|
||||
output[-1].update(_daily_pause_info(con, r, u, state=pause_state))
|
||||
cap = g.MK_CAP.get(g.badge_of(uid), 2)
|
||||
now = time.time()
|
||||
wait_until = int(u.get('created') or 0) + g.KEY_WAIT_SEC if not main and int(u.get('unlim_until') or 0) <= now else 0
|
||||
can_create = len(rows) < cap and wait_until <= now
|
||||
return {'ok': True, 'uid': uid, 'keys': output, 'cap': cap, 'has_main': main is not None,
|
||||
'can_create': can_create, 'wait_until': wait_until, 'wait_seconds': g.KEY_WAIT_SEC, 'server_now': now,
|
||||
'create_reason': ('Ключ доступен через %s после регистрации' %
|
||||
('24 часа' if g.KEY_WAIT_SEC == 86400 else '%d ч' % (g.KEY_WAIT_SEC // 3600))) if wait_until > now else 'Лимит ключей ранга',
|
||||
'extras': sum(n > 0 for n, _ in rows), **account_balances.snapshot(con, uid, u, Q)}
|
||||
|
||||
|
||||
def dispatch(req):
|
||||
try:
|
||||
if not isinstance(req, dict):
|
||||
_fail('Ожидается JSON-объект')
|
||||
req = dict(req)
|
||||
cmd = req.pop('cmd', '')
|
||||
if cmd == 'ping':
|
||||
return {'ok': True, 'v': 4}
|
||||
if cmd == 'list':
|
||||
return cmd_list(**req)
|
||||
if cmd == 'replay':
|
||||
return cmd_replay(**req)
|
||||
if cmd == 'reveal':
|
||||
return cmd_reveal(**req)
|
||||
return mutate(cmd, **req)
|
||||
except KeyErrorSafe as error:
|
||||
return {'ok': False, 'err': str(error), 'operation_rejected': True}
|
||||
except Exception as error:
|
||||
sys.stderr.write('key operation failed: %s\n' % type(error).__name__)
|
||||
return {'ok': False, 'err': 'Статус операции не подтверждён. Повтори проверку с тем же номером', 'uncertain': True}
|
||||
|
||||
|
||||
def main():
|
||||
for line in sys.stdin:
|
||||
try:
|
||||
response = dispatch(json.loads(line))
|
||||
except (ValueError, TypeError):
|
||||
response = {'ok': False, 'err': 'Некорректный JSON', 'operation_rejected': True}
|
||||
_so.write(json.dumps(response, ensure_ascii=False) + '\n')
|
||||
_so.flush()
|
||||
|
||||
|
||||
if __name__ == '__main__':
|
||||
main()
|
||||
File diff suppressed because it is too large
Load Diff
File diff suppressed because it is too large
Load Diff
Reference in New Issue
Block a user