From 3765b00b5214a361249bd1552935c63ba2e5b23e Mon Sep 17 00:00:00 2001 From: Vlad Gothbreach Date: Sat, 31 Oct 2026 11:23:33 +0300 Subject: [PATCH] Make legacy payment delivery retryable and keep gateway paths responsive --- README.md | 21 +- bot/config.example.json | 3 +- bot/grok_bot.py | 1024 ++++++++++++++++---- gateway/gateway_errors.py | 67 +- gateway/grok-web-skin.py | 275 ++++-- gateway/transparent_api.py | 31 +- tests/test_bot_stability_edges.py | 83 +- tests/test_gateway_error_classification.py | 105 ++ tests/test_legacy_payment_fulfillment.py | 718 ++++++++++++++ tests/test_relay_error_responsiveness.py | 197 ++++ tests/test_skin_live_catalogue.py | 456 +++++++++ tests/test_skin_tg_login_hardening.py | 168 ++++ tests/test_transparent_api.py | 9 +- 13 files changed, 2854 insertions(+), 303 deletions(-) create mode 100644 tests/test_legacy_payment_fulfillment.py create mode 100644 tests/test_relay_error_responsiveness.py create mode 100644 tests/test_skin_live_catalogue.py diff --git a/README.md b/README.md index f03a9e09..f895d50f 100644 --- a/README.md +++ b/README.md @@ -179,6 +179,7 @@ unit-файлов, но сам `.env` не загружает; окружени | Персистентный контекст чата | `IISHKO_MEMORY_OFF` | `1` (без памяти) | | Геолокация по IP (DB-IP) | файл `bot/geo/*.mmdb` | нет файла → функция выключена | | Платежи и покупки (CryptoPay / xRocket) | `commerce_offers` + `cryptopay_token` в `bot/config.json`, env `CRYPTOPAY_TOKEN` (имеет приоритет) | `commerce_offers: []` и пустой токен → покупки и создание платежей недоступны; дефолтных цен нет | +| Legacy-товары (покупка ранга, донат-безлимит) | `legacy_products` в `bot/config.json` | `false` → новые счета не создаются; `commerce_offers: []` выключает их даже при `true`. Доставка оплаченного работает всегда | | Community board (`/api/activities`) | — (переключателя нет) | маршруты включены; доступ ограничен auth/ban/admin-гейтами | | Чтение кошелька и grants | — (переключателя нет) | работает и при пустых офферах | | Премиум-эмодзи в рассылках | `IISHKO_BC_PREMIUM_AUTOFILL` | `0` (выкл.) | @@ -249,10 +250,24 @@ node --test tests/*.mjs # Node-тесты (Node 22), есл * **Docker-смоуков.** Никаких контейнерных прогонов здесь не выполнялось и не заявляется. * **Платежей из коробки.** Покупки и создание платежей недоступны, пока в `bot/config.json` не заданы `commerce_offers` и платёжный токен (`cryptopay_token`, - env `CRYPTOPAY_TOKEN` имеет приоритет). Дефолтных цен в коде нет. - **Enable-флагов у commerce нет**: `community_board` и `account_balances` не + env `CRYPTOPAY_TOKEN` имеет приоритет). У commerce-офферов нет дефолтных цен в коде. + **Legacy-товары** (покупка ранга `/buyrank`, донат-безлимит `/donate`) несут собственные + цены в коде, поэтому закрыты отдельным переключателем по умолчанию: `"legacy_products": false`. Без + явного `true` бот отказывает в создании нового счёта, а `commerce_offers: []` выключает их + даже при `legacy_products: true`. + **Оплаченное не теряется.** Гейт закрывает только создание новых счетов: проверка оплаты, + выдача и reconcile уже оплаченных счетов работают всегда — в том числе без платёжного токена + и без ограничения по возрасту счёта. Выдача идемпотентна: повторная проверка не продлевает + безлимит второй раз и не начисляет ранговый бонус повторно. Статус `paid` отделён от факта + доставки (`delivered`), поэтому сбой записи ранга или безлимита больше не выдаётся за + «✅ уже активировано» — обязательство остаётся в БД и довыдаётся поллером. API-безлимит + обещается пользователю только после фактической записи в шлюз; пока ключ не выпущен, + обязательство хранится как `api_state='pending'`, закрывается автоматически, а ответ честно + говорит «включим после выпуска ключа». + **Enable-флагов у board и кошелька нет**: `community_board` и `account_balances` не выключаются — board-маршруты отдаются, доступ ограничен auth/ban/admin-гейтами, - а пустые офферы отключают только покупки, не чтение кошелька и grants. + а пустые офферы и `legacy_products: false` отключают только продажи, не чтение кошелька + и grants. **Grace-окно счёта (180 с).** Если `createInvoice` завершился неоднозначно (сбой сети), строка счёта остаётся `uncertain` без `provider_invoice_id`; повтор с тем же `request_id` в пределах окна возвращает retryable `503 invoice_unconfirmed`, а после окна — терминальный diff --git a/bot/config.example.json b/bot/config.example.json index bbccbbd8..dc14210e 100644 --- a/bot/config.example.json +++ b/bot/config.example.json @@ -21,5 +21,6 @@ "cryptopay_token": "", "xrocket_token": "", "sticker_packs": [], - "commerce_offers": [] + "commerce_offers": [], + "legacy_products": false } diff --git a/bot/grok_bot.py b/bot/grok_bot.py index 1d93d49a..614067f0 100644 --- a/bot/grok_bot.py +++ b/bot/grok_bot.py @@ -10784,19 +10784,91 @@ async def _xr_alive(): _XR_ALIVE["ts"] = now; _XR_ALIVE["ok"] = ok return ok -def _rb_ensure_table(): - con = sqlite3.connect(BOT_DB, timeout=15) +_LEGACY_ON = ("1", "true", "yes", "on", "y", "да") + +def _legacy_sales_enabled(): + """[LEGACY-GATE] продажа legacy-продуктов (ранг/донат) только по явному opt-in. + commerce_offers=[] — жёсткий выключатель даже при legacy_products=true. + Доставку уже выставленных счетов гейт НЕ трогает.""" try: - con.execute("CREATE TABLE IF NOT EXISTS rank_purchases " - "(invoice_id INTEGER PRIMARY KEY, uid INTEGER, from_lvl INTEGER, to_lvl INTEGER, " - "amount_usd TEXT, status TEXT DEFAULT 'pending', created INTEGER, provider TEXT DEFAULT 'cp')") - cols = [r[1] for r in con.execute("PRAGMA table_info(rank_purchases)")] - if "provider" not in cols: - con.execute("ALTER TABLE rank_purchases ADD COLUMN provider TEXT DEFAULT 'cp'") + offs = CFG.get("commerce_offers", None) + if isinstance(offs, (list, tuple)) and len(offs) == 0: + return False + v = CFG.get("legacy_products", False) + except Exception: + return False + if isinstance(v, bool): + return v + if isinstance(v, str): + return v.strip().lower() in _LEGACY_ON + if isinstance(v, (int, float)): + return v != 0 + return False + +# [LEGACY-GATE] honest user-facing refusal; sales are opt-in, delivery never is. +_LEGACY_GATE_TEXT = { + "rank": "⚠️ Продажа рангов сейчас закрыта.", + "donate": "⚠️ Донаты сейчас закрыты.", +} +_LEGACY_GATE_LOG = {"ts": 0.0} + +def _legacy_gate_text(kind): + """[LEGACY-GATE] None when a NEW invoice may be created, otherwise the refusal line. + + Verification, delivery and reconciliation of already-issued invoices must not call + this: turning sales off cannot strand money that was already paid. + """ + if _legacy_sales_enabled(): + return None + now = time.time() + if now - _LEGACY_GATE_LOG["ts"] >= 300: + _LEGACY_GATE_LOG["ts"] = now + log.warning(f"[LEGACY-GATE] legacy sales disabled; refusing new invoice kind={kind}") + return _LEGACY_GATE_TEXT.get(kind, "⚠️ Покупки сейчас недоступны.") + +def _rb_ensure_table(): + """Additive migration under a write lock; concurrent callers must not race. + + PRAGMA is read after BEGIN IMMEDIATE, so a second thread (button + poller run in + worker threads) sees the columns the first one already added: no `duplicate column + name` failure and no second "fresh install" pass, which would mark a genuinely + undelivered paid invoice as delivered. + """ + con = sqlite3.connect(BOT_DB, timeout=15) + con.isolation_level = None + try: + con.execute("BEGIN IMMEDIATE") + try: + con.execute("CREATE TABLE IF NOT EXISTS rank_purchases " + "(invoice_id INTEGER PRIMARY KEY, uid INTEGER, from_lvl INTEGER, to_lvl INTEGER, " + "amount_usd TEXT, status TEXT DEFAULT 'pending', created INTEGER, provider TEXT DEFAULT 'cp')") cols = [r[1] for r in con.execute("PRAGMA table_info(rank_purchases)")] - if "inv_ext" not in cols: # [XRPAY 2010] строковый id инвойса Pay API - con.execute("ALTER TABLE rank_purchases ADD COLUMN inv_ext TEXT DEFAULT ''") - con.commit() + if "provider" not in cols: + con.execute("ALTER TABLE rank_purchases ADD COLUMN provider TEXT DEFAULT 'cp'") + cols = [r[1] for r in con.execute("PRAGMA table_info(rank_purchases)")] + if "inv_ext" not in cols: # [XRPAY 2010] строковый id инвойса Pay API + con.execute("ALTER TABLE rank_purchases ADD COLUMN inv_ext TEXT DEFAULT ''") + # [RB-FIX] paid != выдан: доставка учитывается отдельно, только аддитивные колонки + fresh = "delivered" not in cols + for _col, _ddl in (("delivered", "delivered INTEGER DEFAULT 0"), + ("delivered_at", "delivered_at INTEGER DEFAULT 0"), + ("bonus_state", "bonus_state TEXT DEFAULT 'none'"), + ("bonus_due", "bonus_due INTEGER DEFAULT 0")): + if _col not in cols: + con.execute("ALTER TABLE rank_purchases ADD COLUMN " + _ddl) + if fresh: + # [RB-MIGRATE] историю не перевыдаём: уже оплаченные строки считаем выданными + con.execute("UPDATE rank_purchases SET delivered=1, delivered_at=COALESCE(created,0) " + "WHERE status='paid' AND COALESCE(delivered,0)=0") + con.execute("UPDATE rank_purchases SET bonus_state='granted' " + "WHERE status='paid' AND COALESCE(bonus_state,'none')='none'") + con.execute("COMMIT") + except Exception: + try: + con.execute("ROLLBACK") + except Exception: + pass + raise finally: con.close() @@ -10819,74 +10891,274 @@ def _rb_pending_save(d): try: with open(_RB_PENDING_PATH, "w", encoding="utf-8") as f: json.dump(d, f) + return True except Exception as e: log.error(f"rb pending save: {e}") + return False -def _rb_pending_bonus(uid, bonus): - d = _rb_pending_load() - d[str(uid)] = max(int(d.get(str(uid), 0)), int(bonus)) - _rb_pending_save(d) - -def _rb_pending_flush(): - d = _rb_pending_load() - if not d: - return - changed = False - for uid_s, bonus in list(d.items()): - try: - con = sqlite3.connect(BOT_DB, timeout=15) - r = con.execute("SELECT token_name FROM users WHERE tg_id=?", (int(uid_s),)).fetchone() - con.close() - if r and r[0]: - _nc = sqlite3.connect(CFG["newapi_db"], timeout=15) - _nc.execute("UPDATE tokens SET remain_quota=MAX(remain_quota,?), " - "status=CASE WHEN status=4 THEN 1 ELSE status END " - "WHERE name=? AND deleted_at IS NULL", (int(bonus), r[0])) - _nc.commit(); _nc.close() - log.info(f"rankbuy pending bonus flushed uid={uid_s} ${int(bonus) // 500000}") - del d[uid_s] - changed = True - except Exception as e: - log.error(f"rb pending flush uid={uid_s}: {e}") - if changed: - _rb_pending_save(d) - -def _rb_apply(uid, to_lvl): - con = sqlite3.connect(BOT_DB, timeout=15) +def _rb_token_name(uid): + """[RB-FIX] трекнутый токен юзера (tg); None — ключ ещё не выпущен.""" try: - con.execute("UPDATE users SET badge_lock=?, badge_until=0 WHERE tg_id=?", (to_lvl, uid)) + con = sqlite3.connect(BOT_DB, timeout=15) + try: + r = con.execute("SELECT token_name FROM users WHERE tg_id=?", (int(uid),)).fetchone() + finally: + con.close() + except Exception as e: + log.error(f"rb token name uid={uid}: {e}") + return None + tn = (r or (None,))[0] + return (str(tn).strip() or None) if tn else None + +def _rb_token_bonus(tname, bonus): + """[RB-BONUS] бонус в квоту токена. True только при реально обновлённой строке.""" + if not tname or int(bonus) <= 0: + return False + try: + con = sqlite3.connect(Path(CFG["newapi_db"]).resolve().as_uri() + "?mode=rw", + uri=True, timeout=15) + except Exception as e: + log.error(f"rb bonus db: {e}") + return False + try: + cur = con.execute("UPDATE tokens SET remain_quota=MAX(COALESCE(remain_quota,0),?), " + "status=CASE WHEN status=4 THEN 1 ELSE status END " + "WHERE name=? AND deleted_at IS NULL", (int(bonus), tname)) con.commit() + return cur.rowcount >= 1 + except Exception as e: + log.error(f"rb bonus grant {tname}: {e}") + return False finally: con.close() - _RANK_SYNC.pop(uid, None) - sync_rank_limits(uid, ttl=0) - # [RANKPAY-BONUS 2010] ранговый бонус СРАЗУ при покупке (не ждать понедельника), MAX-семантика как weekly - try: - bonus = capped_bonus(uid, LOYALTY_BONUS.get(to_lvl, LOYALTY_BONUS[1])) - cc = sqlite3.connect(BOT_DB, timeout=15) - tn = cc.execute("SELECT token_name FROM users WHERE tg_id=?", (uid,)).fetchone() - cc.close() - if bonus and tn and tn[0]: - _nc = sqlite3.connect(CFG["newapi_db"], timeout=15) - _nc.execute("UPDATE tokens SET remain_quota=MAX(remain_quota,?), " - "status=CASE WHEN status=4 THEN 1 ELSE status END " - "WHERE name=? AND deleted_at IS NULL", (bonus, tn[0])) - _nc.commit(); _nc.close() - log.info(f"rankbuy bonus uid={uid} ${bonus // 500000}") - elif bonus: - _rb_pending_bonus(uid, bonus) # [RBPEND 2010] токен ещё не выпущен (keywait) — бонус не теряем - log.info(f"rankbuy bonus pending uid={uid} ${bonus // 500000}") - except Exception as e: - log.error(f"rankbuy bonus fail uid={uid}: {e}") - log.info(f"rankbuy applied uid={uid} to_lvl={to_lvl}") -async def _rb_confirm(bot, uid, to_lvl, paid_usd, provider="cp"): +def _rb_bonus_grant(uid, bonus): + """[RB-BONUS] выдать бонус, если есть куда. MAX-семантика: повтор не раздувает квоту.""" + tname = _rb_token_name(uid) + if not tname: + log.info(f"rankbuy bonus waiting uid={uid} ${int(bonus) // 500000}: ключ не выпущен") + return False + if not _rb_token_bonus(tname, bonus): + log.warning(f"rankbuy bonus keep uid={uid} token={tname}: строки нет/ошибка — обязательство сохранено") + return False + log.info(f"rankbuy bonus uid={uid} ${int(bonus) // 500000}") + return True + +def _rb_pending_flush(): + """[RBPEND] выдать отложенные бонусы. Ключ снимаем ТОЛЬКО когда бонус реально лёг в API.""" + d = _rb_pending_load() + if not d: + return 0 + left = {} + done = 0 + for uid_s, bonus in list(d.items()): + try: + uid = int(uid_s) + bonus = int(bonus) + except Exception: + continue + if bonus <= 0: + continue + if _rb_bonus_grant(uid, bonus): + done += 1 + else: + left[uid_s] = bonus + if left: + _rb_pending_save(left) + else: + try: + os.remove(_RB_PENDING_PATH) + except Exception as e: + if os.path.exists(_RB_PENDING_PATH): + log.error(f"rb pending rm: {e}") + return done + +def _rb_claim_paid(inv_id): + """[RB-FIX] pending->paid ровно один раз (rowcount-guard).""" + con = sqlite3.connect(BOT_DB, timeout=15) + try: + cur = con.execute("UPDATE rank_purchases SET status='paid' " + "WHERE invoice_id=? AND status='pending'", (int(inv_id),)) + con.commit() + return cur.rowcount == 1 + finally: + con.close() + +def _rb_bonus_granted(invoice_id): + """Выдан ли бонус по счёту (для честного текста подтверждения).""" + try: + con = sqlite3.connect(BOT_DB, timeout=15) + try: + row = con.execute("SELECT COALESCE(bonus_state,'none'), COALESCE(bonus_due,0) " + "FROM rank_purchases WHERE invoice_id=?", (int(invoice_id),)).fetchone() + finally: + con.close() + except Exception: + return False + st, due = (row or ("none", 0)) + return st == "granted" or int(due or 0) <= 0 + +def _rb_delivered(con, invoice_id): + """Доставлен ли счёт; читается внутри открытой транзакции вызывающего.""" + row = con.execute("SELECT COALESCE(delivered,0) FROM rank_purchases WHERE invoice_id=?", + (int(invoice_id),)).fetchone() + return bool(row) and int(row[0] or 0) == 1 + +def _rb_invoice_delivered(invoice_id): + """То же отдельным соединением — для путей без транзакции. Ошибка чтения = False.""" + try: + con = sqlite3.connect(BOT_DB, timeout=15) + try: + return _rb_delivered(con, invoice_id) + finally: + con.close() + except Exception as e: + log.error(f"rb delivered read inv={invoice_id}: {e}") + return False + +def _rb_apply(uid, to_lvl, invoice_id=None, claim=False): + """[RB-FIX] выдача ранга одной транзакцией вместе с отметкой доставки. + Бонус (чужая БД) — отдельным шагом после COMMIT. True = ранг записан, повтор безопасен. + + claim=True доставляет счёт только если он ещё не доставлен: проверка идёт в той же + BEGIN IMMEDIATE, поэтому гонка «кнопка + поллер» не может выдать два подтверждения + одному счёту. Уже доставленный счёт возвращает False (ранг при этом выдан), а + неудачная выдача откатывает отметку — обязательство остаётся в очереди reconcile. + """ + bonus = int(LOYALTY_BONUS.get(int(to_lvl), 0) or 0) + if bonus > 0: + try: + bonus = int(capped_bonus(uid, bonus)) + except Exception: + pass + already = False + con = sqlite3.connect(BOT_DB, timeout=15) + con.isolation_level = None + try: + con.execute("BEGIN IMMEDIATE") + try: + if claim and invoice_id is not None and _rb_delivered(con, invoice_id): + already = True + else: + cur = con.execute("UPDATE users SET badge_lock=MAX(COALESCE(badge_lock,0),?), badge_until=0 " + "WHERE tg_id=?", (int(to_lvl), uid)) + if cur.rowcount < 1: + raise RuntimeError(f"users row missing uid={uid}") + if invoice_id is not None: + row = con.execute("SELECT COALESCE(bonus_state,'none') FROM rank_purchases " + "WHERE invoice_id=?", (int(invoice_id),)).fetchone() + st = (row or ("none",))[0] or "none" + if st != "granted": + st = "pending" if bonus > 0 else st + con.execute("UPDATE rank_purchases SET delivered=1, delivered_at=?, " + "bonus_due=MAX(COALESCE(bonus_due,0),?), bonus_state=? WHERE invoice_id=?", + (int(time.time()), bonus, st, int(invoice_id))) + con.execute("ROLLBACK" if already else "COMMIT") + except Exception: + try: + con.execute("ROLLBACK") + except Exception: + pass + raise + except Exception as e: + log.error(f"rb apply fail uid={uid} to_lvl={to_lvl} inv={invoice_id}: {e}") + return False + finally: + con.close() + if already: + log.info(f"rankbuy already delivered uid={uid} inv={invoice_id}") + return False + try: + _RANK_SYNC.pop(uid, None) + sync_rank_limits(uid, ttl=0) + except Exception as e: + log.error(f"rb sync fail uid={uid}: {e}") + log.info(f"rankbuy applied uid={uid} to_lvl={to_lvl} inv={invoice_id}") + return True + +def _rb_bonus_settle(invoice_id=None): + """[RB-BONUS] добить бонусные обязательства ранга (MAX-семантика: повтор не раздувает квоту).""" + sql = ("SELECT invoice_id, uid, COALESCE(bonus_due,0) FROM rank_purchases " + "WHERE COALESCE(bonus_state,'none')='pending'") + args = () + if invoice_id is not None: + sql += " AND invoice_id=?" + args = (int(invoice_id),) + try: + con = sqlite3.connect(BOT_DB, timeout=15) + try: + rows = con.execute(sql, args).fetchall() + finally: + con.close() + except Exception as e: + log.error(f"rb bonus settle load: {e}") + return 0 + done = 0 + for inv, uid, bonus in rows: + bonus = int(bonus or 0) + if bonus <= 0: + continue + if not _rb_bonus_grant(uid, bonus): + continue + try: + con = sqlite3.connect(BOT_DB, timeout=15) + try: + con.execute("UPDATE rank_purchases SET bonus_state='granted' " + "WHERE invoice_id=? AND COALESCE(bonus_state,'none')='pending'", (inv,)) + con.commit() + finally: + con.close() + done += 1 + except Exception as e: + log.error(f"rb bonus mark inv={inv}: {e}") + return done + +def _rb_settle(uid, to_lvl, invoice_id=None, claim=False): + """[RB-FIX] единый путь доставки: ранг + бонус. Зовут и кнопка, и поллер. + claim=True — доставлять только недоставленный счёт (см. _rb_apply).""" + ok = _rb_apply(uid, to_lvl, invoice_id, claim=claim) + if ok and invoice_id is not None: + _rb_bonus_settle(invoice_id) + return ok + +def _rb_reconcile(): + """[RB-RECON] довыдать подтверждённые, но не доставленные покупки. Без сети, без фильтра возраста. + Возвращает [(uid, to_lvl, invoice_id, amount_usd, provider)] для уведомления.""" + out = [] + try: + _rb_ensure_table() + con = sqlite3.connect(BOT_DB, timeout=15) + try: + rows = con.execute("SELECT invoice_id, uid, to_lvl, COALESCE(amount_usd,''), " + "COALESCE(provider,'cp') FROM rank_purchases " + "WHERE status='paid' AND COALESCE(delivered,0)=0").fetchall() + finally: + con.close() + except Exception as e: + log.error(f"rb reconcile load: {e}") + return out + for inv, uid, to_lvl, amount, provider in rows: + # claim=True: если кнопку нажали между SELECT и выдачей, счёт уже доставлен — + # второе «Ранг куплен!» и второй алерт админам не отправляются. + if _rb_settle(int(uid), int(to_lvl), inv, claim=True): + out.append((int(uid), int(to_lvl), inv, amount, provider or "cp")) + try: + _rb_bonus_settle() + except Exception as e: + log.error(f"rb reconcile bonus: {e}") + return out + +async def _rb_confirm(bot, uid, to_lvl, paid_usd, provider="cp", bonus_ok=True): em, nm = BADGES[to_lvl][0], BADGES[to_lvl][1] src_name = "CryptoBot" if provider == "cp" else "xRocket" + bonus_usd = LOYALTY_BONUS.get(to_lvl, 0) // 500000 + # [RB-FIX] не врём про «уже начислен», если бонус ждёт выпуска ключа + tail = (f'💰 Бонус ранга ${bonus_usd} уже начислен на баланс.' if bonus_ok else + f'💰 Бонус ранга ${bonus_usd} начислим сразу после выпуска API-ключа — он не сгорит.') try: await bot.send_message(uid, f'🎉 Ранг куплен!\n\n{em} {nm} — навсегда (не сгорит).\n' f'Модели и лимиты уже открыты. Оплачено ${paid_usd} USDT через {src_name}.\n' - f'💰 Бонус ранга ${LOYALTY_BONUS.get(to_lvl, 0) // 500000} уже начислен на баланс.\n\n💖 Спасибо за поддержку иишко!') + f'{tail}\n\n💖 Спасибо за поддержку иишко!') except Exception: pass for a in list(ADMIN_IDS)[:3]: @@ -10913,6 +11185,9 @@ async def cb_buyrank_closed(c: CallbackQuery): async def cb_buyrank(c: CallbackQuery): """[RANKBUY-V2] меню покупки ранга.""" uid = c.from_user.id + gate = _legacy_gate_text("rank") + if gate: + return await c.answer(gate, show_alert=True) if not CRYPTOPAY_TOKEN and not XROCKET_TOKEN: return await c.answer("⚠️ Платежи временно недоступны", show_alert=True) lang = (db_get(uid) or {}).get("lang") or "ru" @@ -10958,6 +11233,9 @@ async def cb_brank_sel(c: CallbackQuery): return await c.answer("Недоступно для твоего ранга", show_alert=True) if to_lvl != cur + 1 and to_lvl != 4: return await c.answer("Можно +1 ранг или сразу Легенду", show_alert=True) + gate = _legacy_gate_text("rank") + if gate: + return await c.answer(gate, show_alert=True) price = _rb_price(cur, to_lvl) em, nm = BADGES[to_lvl][0], BADGES[to_lvl][1] xr_ok = await _xr_alive() @@ -10988,12 +11266,17 @@ async def cb_brp_pay(c: CallbackQuery): return await c.answer("Недоступно", show_alert=True) if to_lvl != cur + 1 and to_lvl != 4: return await c.answer("Можно +1 ранг или сразу Легенду", show_alert=True) + gate = _legacy_gate_text("rank") + if gate: + return await c.answer(gate, show_alert=True) price = _rb_price(cur, to_lvl) em, nm = BADGES[to_lvl][0], BADGES[to_lvl][1] inv_ext = "" # [XRPAY 2010] await c.answer() - _rb_ensure_table() try: + # [PERF] ensure держит BEGIN IMMEDIATE с busy-timeout 15 с: на event loop это + # вешало бы апдейты бота при database is locked и роняло handler без ответа. + await asyncio.to_thread(_rb_ensure_table) if prov == "cp": if not CRYPTOPAY_TOKEN: return await c.message.answer("⚠️ CryptoBot недоступен") @@ -11028,13 +11311,20 @@ async def cb_brp_pay(c: CallbackQuery): inv_ext = id_s pay_url = ((d.get("links") or {}).get("telegramBotLink")) or "" src_name = "xRocket" - con = sqlite3.connect(BOT_DB, timeout=15) - try: - con.execute("INSERT OR REPLACE INTO rank_purchases (invoice_id, uid, from_lvl, to_lvl, amount_usd, status, created, provider, inv_ext) VALUES (?,?,?,?,?,?,?,?,?)", - (inv_id, uid, cur, to_lvl, str(price), "pending", int(time.time()), prov, inv_ext)) - con.commit() - finally: - con.close() + # [RB-FIX] явный upsert: INSERT OR REPLACE стирал delivered/bonus_state у уже + # обработанного счёта и открывал путь к повторной выдаче; status не трогаем. + def _rb_record_invoice(): + con = sqlite3.connect(BOT_DB, timeout=15) + try: + con.execute("INSERT INTO rank_purchases (invoice_id, uid, from_lvl, to_lvl, amount_usd, status, created, provider, inv_ext) VALUES (?,?,?,?,?,?,?,?,?) " + "ON CONFLICT(invoice_id) DO UPDATE SET uid=excluded.uid, from_lvl=excluded.from_lvl, " + "to_lvl=excluded.to_lvl, amount_usd=excluded.amount_usd, created=excluded.created, " + "provider=excluded.provider, inv_ext=excluded.inv_ext WHERE COALESCE(delivered,0)=0", + (inv_id, uid, cur, to_lvl, str(price), "pending", int(time.time()), prov, inv_ext)) + con.commit() + finally: + con.close() + await asyncio.to_thread(_rb_record_invoice) kb = InlineKeyboardMarkup(inline_keyboard=[ [InlineKeyboardButton(text=f"💳 Оплатить ${price} USDT", url=pay_url)], [InlineKeyboardButton(text="✅ Я оплатил", callback_data=f"brchk_{inv_id}")], @@ -11055,39 +11345,46 @@ async def cb_brank_check(c: CallbackQuery): inv_id = int(c.data.split("_")[1]) except Exception: return await c.answer("ошибка", show_alert=True) - _rb_ensure_table() - con = sqlite3.connect(BOT_DB, timeout=15) - try: - row = con.execute("SELECT uid, to_lvl, status, amount_usd, provider, COALESCE(inv_ext,'') FROM rank_purchases WHERE invoice_id=?", (inv_id,)).fetchone() - finally: - con.close() + # [PERF] синхронный SQLite не должен блокировать event-loop бота: при database is + # locked таймаут до 15 с вешал бы обработку всех остальных апдейтов. + def _rb_check_row(): + _rb_ensure_table() + con = sqlite3.connect(BOT_DB, timeout=15) + try: + return con.execute("SELECT uid, to_lvl, status, amount_usd, provider, COALESCE(inv_ext,''), COALESCE(delivered,0) FROM rank_purchases WHERE invoice_id=?", (inv_id,)).fetchone() + finally: + con.close() + row = await asyncio.to_thread(_rb_check_row) if not row: return await c.answer("Счёт не найден", show_alert=True) - uid, to_lvl, status, amount, provider, inv_ext = row + uid, to_lvl, status, amount, provider, inv_ext, delivered = row provider = provider or "cp" - if status == "paid": + # [RB-FIX] чужой счёт: ни подтвердить, ни активировать + if int(uid) != int(getattr(c.from_user, "id", 0) or 0): + log.warning(f"rankbuy check: чужой счёт inv={inv_id} caller={getattr(c.from_user, 'id', None)}") + return await c.answer("Счёт не найден", show_alert=True) + if status == "paid" and delivered: return await c.answer("✅ Ранг уже активирован", show_alert=True) try: - if await _rb_inv_paid(provider, inv_id, inv_ext): - con = sqlite3.connect(BOT_DB, timeout=15) - try: - claim = con.execute("UPDATE rank_purchases SET status='paid' WHERE invoice_id=? AND status='pending'", (inv_id,)) - con.commit() - claimed = claim.rowcount == 1 - finally: - con.close() - if not claimed: + if status != "paid": + if not await _rb_inv_paid(provider, inv_id, inv_ext): + return await c.answer("⏳ Оплата ещё не прошла — подожди пару секунд и нажми снова", show_alert=True) + # [RB-FIX] сначала фиксируем оплату; выдача отдельно и идемпотентно + await asyncio.to_thread(_rb_claim_paid, inv_id) + if not await asyncio.to_thread(_rb_settle, uid, to_lvl, inv_id, True): + # claim не прошёл: либо поллер уже доставил счёт, либо выдача реально упала + if await asyncio.to_thread(_rb_invoice_delivered, inv_id): return await c.answer("✅ Ранг уже активирован", show_alert=True) - _rb_apply(uid, to_lvl) - await _rb_confirm(c.bot, uid, to_lvl, amount, provider) - em, nm = BADGES[to_lvl][0], BADGES[to_lvl][1] - await c.answer(f"🎉 Ранг {em} {nm} активирован навсегда!", show_alert=True) - try: - await c.message.edit_text((c.message.html_text or "") + "\n\n✅ ОПЛАЧЕНО — ранг активирован") - except Exception: - pass - else: - await c.answer("⏳ Оплата ещё не прошла — подожди пару секунд и нажми снова", show_alert=True) + log.error(f"rankbuy check: оплачен, но не выдан inv={inv_id} uid={uid}") + return await c.answer("✅ Оплата получена — ранг включим автоматически, нажми ещё раз через минуту", show_alert=True) + await _rb_confirm(c.bot, uid, to_lvl, amount, provider, + await asyncio.to_thread(_rb_bonus_granted, inv_id)) + em, nm = BADGES[to_lvl][0], BADGES[to_lvl][1] + await c.answer(f"🎉 Ранг {em} {nm} активирован навсегда!", show_alert=True) + try: + await c.message.edit_text((c.message.html_text or "") + "\n\n✅ ОПЛАЧЕНО — ранг активирован") + except Exception: + pass except Exception as e: log.error(f"rankbuy check fail: {e}") await c.answer("Не удалось проверить — попробуй позже", show_alert=True) @@ -11096,6 +11393,9 @@ async def cb_brank_check(c: CallbackQuery): async def cmd_buyrank(m: Message): """[RANKBUY-V2] команда покупки ранга.""" uid = m.from_user.id + gate = _legacy_gate_text("rank") + if gate: + return await m.answer(gate) xr_ok = await _xr_alive() if not CRYPTOPAY_TOKEN and not xr_ok: return await m.answer("⚠️ Платежи временно недоступны") @@ -11118,34 +11418,54 @@ async def cmd_buyrank(m: Message): reply_markup=InlineKeyboardMarkup(inline_keyboard=kb_rows)) async def rankbuy_poll_loop(bot: Bot): - """[RANKBUY-V2] поллинг неоплаченных инвойсов (cp+xr) раз в 15 сек [RBFAST 2010].""" + """[RANKBUY-V2] поллинг инвойсов (cp+xr) раз в 15 сек [RBFAST 2010]. + [RB-FIX] сначала довыдаём уже оплаченное (без сети, без токена, без срока давности).""" while True: try: await asyncio.sleep(15) + try: + # [PERF] _rb_reconcile готовит таблицу внутри рабочего потока: отдельный + # вызов на event loop держал бы апдейты до 15 с при database is locked. + for uid, to_lvl, inv_id, amount, provider in await asyncio.to_thread(_rb_reconcile): + try: + await _rb_confirm(bot, uid, to_lvl, amount, provider, + await asyncio.to_thread(_rb_bonus_granted, inv_id)) + except Exception as e: + log.error(f"rankbuy reconfirm uid={uid}: {e}") + except Exception as e: + log.error(f"rankbuy reconcile: {e}") + await asyncio.to_thread(_rb_pending_flush) # [RBPEND 2010] if not CRYPTOPAY_TOKEN and not XROCKET_TOKEN: continue - _rb_ensure_table() + # [PERF] строки читаем и сразу закрываем соединение: держать SQLite-блокировку + # на время HTTP-опроса провайдера — источник database is locked в логах. + def _rb_pending_rows(): + con = sqlite3.connect(BOT_DB, timeout=15) + try: + return con.execute("SELECT invoice_id, uid, to_lvl, amount_usd, provider, COALESCE(inv_ext,'') FROM rank_purchases " + "WHERE status='pending' AND created > ?", + (int(time.time()) - 604800,)).fetchall() + finally: + con.close() + rows = await asyncio.to_thread(_rb_pending_rows) paid_list = [] - con = sqlite3.connect(BOT_DB, timeout=15) - try: - rows = con.execute("SELECT invoice_id, uid, to_lvl, amount_usd, provider, COALESCE(inv_ext,'') FROM rank_purchases " - "WHERE status='pending' AND created > ?", - (int(time.time()) - 604800,)).fetchall() - for inv_id, uid, to_lvl, amount, provider, inv_ext in rows: - try: - if await _rb_inv_paid(provider or "cp", inv_id, inv_ext): - claim = con.execute("UPDATE rank_purchases SET status='paid' WHERE invoice_id=? AND status='pending'", (inv_id,)) - con.commit() - if claim.rowcount == 1: - paid_list.append((uid, to_lvl, amount, provider or "cp")) - except Exception: - continue - finally: - con.close() - for uid, to_lvl, amount, provider in paid_list: - _rb_apply(uid, to_lvl) - await _rb_confirm(bot, uid, to_lvl, amount, provider) - _rb_pending_flush() # [RBPEND 2010] + for inv_id, uid, to_lvl, amount, provider, inv_ext in rows: + try: + if await _rb_inv_paid(provider or "cp", inv_id, inv_ext): + if await asyncio.to_thread(_rb_claim_paid, inv_id): + paid_list.append((inv_id, uid, to_lvl, amount, provider or "cp")) + except asyncio.CancelledError: + raise + except Exception: + continue + for inv_id, uid, to_lvl, amount, provider in paid_list: + # [RB-FIX] выдача идемпотентна; упавший коммит остаётся в очереди reconcile. + # claim=True обязателен: между _rb_claim_paid и этим циклом пользователь мог + # нажать «Я оплатил» (status уже 'paid', delivered=0) и получить счёт сам — + # без claim поллер выдал бы второе «Ранг куплен!» и второй алерт админам. + if await asyncio.to_thread(_rb_settle, uid, to_lvl, inv_id, True): + await _rb_confirm(bot, uid, to_lvl, amount, provider, + await asyncio.to_thread(_rb_bonus_granted, inv_id)) except asyncio.CancelledError: raise except Exception as e: @@ -11161,17 +11481,307 @@ DONATE_PACKS = [ ] # (cb_id, usd, hours, asset) — $5=сутки, $10=3 суток безлимита+приоритета (изменено 09.10) def _prem_api_unlim(uid): + """[DON-FIX] True only when the gateway token really became unlimited. + + The previous helper swallowed every failure, so the caller promised an API key + unlimited quota that was never written (key not issued yet, row soft-deleted, + gateway DB locked). Returns bool so the caller can keep the obligation pending. + """ + uid = int(uid) try: - tname = f"tg{uid}" - con = sqlite3.connect(CFG["newapi_db"], timeout=15) - try: - con.execute("UPDATE tokens SET unlimited_quota=1, \"group\"='premium' WHERE name=? AND deleted_at IS NULL", (tname,)) - con.commit() - finally: - con.close() - log.info(f"prem on: uid={uid} api unlimited") + con = sqlite3.connect(Path(CFG["newapi_db"]).resolve().as_uri() + "?mode=rw", + uri=True, timeout=15) + except Exception as e: + log.error(f"prem api unlim db uid={uid}: {e}") + return False + try: + # [DON-NAME] Ключ аккаунта не обязан называться tg: account_limits + # допускает pm/sol и субключи -kN. Жёсткое имя давало 0 + # обновлённых строк и вечно 'pending' при реально оплаченном безлимите. + names = account_limits.account_token_names(con, uid) + tracked = _rb_token_name(uid) + if tracked and tracked not in names and account_limits.account_uid(tracked) == uid: + names = names + [tracked] + if not names: + log.warning(f"prem api keep uid={uid}: key not issued yet — entitlement stays pending") + return False + marks = ",".join("?" * len(names)) + cur = con.execute("UPDATE tokens SET unlimited_quota=1, \"group\"='premium' " + f"WHERE deleted_at IS NULL AND name IN ({marks})", names) + con.commit() + if cur.rowcount < 1: + log.warning(f"prem api keep uid={uid}: token row missing or inactive — entitlement stays pending") + return False + row = con.execute("SELECT COUNT(*) FROM tokens WHERE deleted_at IS NULL " + f"AND COALESCE(unlimited_quota,0)=1 AND name IN ({marks})", names).fetchone() + if not row or int(row[0]) < 1: + log.error(f"prem api readback uid={uid}: unlimited_quota not set") + return False + log.info(f"prem on: uid={uid} api unlimited keys={cur.rowcount}") + return True + except ValueError as e: + log.error(f"prem api bad uid={uid}: {e}") + return False except Exception as e: log.error(f"prem api unlim fail uid={uid}: {e}") + return False + finally: + con.close() + +# ─── [DON-FIX] durable donation entitlement: paid != delivered ────────────── +def _don_ensure_table(): + """Additive delivery columns only; already paid history is never re-granted. + + Runs under BEGIN IMMEDIATE for the same reason as _rb_ensure_table(): the button and + the poller both call it from worker threads, and a stale PRAGMA snapshot makes the + loser either fail on `duplicate column name` or rerun the fresh-install backfill. + """ + con = sqlite3.connect(BOT_DB, timeout=30) + con.isolation_level = None + try: + con.execute("BEGIN IMMEDIATE") + try: + con.execute("CREATE TABLE IF NOT EXISTS donations " + "(invoice_id INTEGER PRIMARY KEY, uid INTEGER, hours INTEGER, " + "status TEXT DEFAULT 'pending', created INTEGER)") + cols = [r[1] for r in con.execute("PRAGMA table_info(donations)")] + fresh = "delivered" not in cols + for _ddl in (("delivered INTEGER DEFAULT 0"), ("delivered_at INTEGER DEFAULT 0"), + ("until_ts INTEGER DEFAULT 0"), ("api_state TEXT DEFAULT 'none'")): + if _ddl.split()[0] not in cols: + con.execute("ALTER TABLE donations ADD COLUMN " + _ddl) + if fresh: + # [DON-MIGRATE] paid rows count as already delivered — no retroactive entitlement + con.execute("UPDATE donations SET delivered=1, delivered_at=COALESCE(created,0), " + "api_state='granted' WHERE status='paid' AND COALESCE(delivered,0)=0") + con.execute("COMMIT") + except Exception: + try: + con.execute("ROLLBACK") + except Exception: + pass + raise + finally: + con.close() + +def _don_row(inv_id): + """Delivery state of one invoice; connections close before any await upstream.""" + con = sqlite3.connect(BOT_DB, timeout=30) + try: + return con.execute("SELECT uid, hours, status, COALESCE(delivered,0), COALESCE(api_state,'none') " + "FROM donations WHERE invoice_id=?", (int(inv_id),)).fetchone() + finally: + con.close() + +def _don_pending_rows(max_age_s=604800): + """Recent unpaid invoices still worth asking the provider about.""" + con = sqlite3.connect(BOT_DB, timeout=30) + try: + return con.execute("SELECT invoice_id, uid, hours FROM donations " + "WHERE status='pending' AND created > ?", + (int(time.time()) - int(max_age_s),)).fetchall() + finally: + con.close() + +def _don_record_invoice(inv_id, uid, hours): + """[DON-FIX] pending invoice with an explicit column list. + + The old positional INSERT OR REPLACE wiped every row for a reused invoice_id and + had no place to store delivery state. + """ + _don_ensure_table() + con = sqlite3.connect(BOT_DB, timeout=30) + try: + con.execute( + "INSERT INTO donations (invoice_id, uid, hours, status, created) VALUES (?,?,?,?,?) " + "ON CONFLICT(invoice_id) DO UPDATE SET uid=excluded.uid, hours=excluded.hours, " + "created=excluded.created WHERE COALESCE(delivered,0)=0", + (int(inv_id), int(uid), int(hours), "pending", int(time.time()))) + con.commit() + finally: + con.close() + +def _don_claim_paid(inv_id): + """[DON-FIX] pending->paid exactly once (rowcount guard against double credit).""" + con = sqlite3.connect(BOT_DB, timeout=30) + try: + cur = con.execute("UPDATE donations SET status='paid' WHERE invoice_id=? AND status='pending'", (int(inv_id),)) + con.commit() + return cur.rowcount == 1 + finally: + con.close() + +def _don_fulfill(inv_id): + """[DON-FIX] single delivery path for the button and the poller. + + Chat premium plus the delivery mark are written in one transaction; the API + entitlement is verified separately and stays `pending` until it is really + granted. Idempotent: a retry never extends `unlim_until` a second time and never + re-promises an API key that does not exist. + Returns {"status": granted|pending_api|blocked|already|no_user|missing|error, + "until": int, "api": bool, "fresh": bool}. + """ + _don_ensure_table() + con = sqlite3.connect(BOT_DB, timeout=30) + con.isolation_level = None # explicit transaction; the gateway DB is written separately + try: + row = con.execute("SELECT uid, hours, COALESCE(delivered,0), COALESCE(until_ts,0), " + "COALESCE(api_state,'none') FROM donations WHERE invoice_id=?", (int(inv_id),)).fetchone() + if not row: + return {"status": "missing", "until": 0, "api": False, "fresh": False} + uid, hours, delivered, target, api_state = row + uid, hours, target = int(uid), int(hours or 0), int(target or 0) + fresh = False + if not delivered: + urow = con.execute("SELECT COALESCE(banned,0), COALESCE(api_blocked,0) FROM users WHERE tg_id=?", (uid,)).fetchone() + if urow is None: + return {"status": "no_user", "until": 0, "api": False, "fresh": False} + blocked = bool(int(urow[0]) or int(urow[1])) + con.execute("BEGIN IMMEDIATE") + try: + now = int(time.time()) + # [DON-RACE] Сначала заявка на доставку: guard `delivered=0` делает + # второй поток (кнопка + поллер) проигравшим, а не продлевает + # unlim_until дважды за одну оплату. + claim = con.execute("UPDATE donations SET delivered=1, delivered_at=? " + "WHERE invoice_id=? AND COALESCE(delivered,0)=0", + (now, int(inv_id))) + if claim.rowcount < 1: + con.execute("ROLLBACK") + rrow = con.execute("SELECT COALESCE(until_ts,0), COALESCE(api_state,'none') " + "FROM donations WHERE invoice_id=?", (int(inv_id),)).fetchone() + target = int((rrow or (0, "none"))[0] or 0) + api_state = (rrow or (0, "none"))[1] or "none" + else: + if blocked: + # money stays paid, entitlement is not issued for a restricted account + target = 0 + api_state = "blocked" + else: + cur_u = con.execute("SELECT COALESCE(unlim_until,0) FROM users WHERE tg_id=?", (uid,)).fetchone() + target = max(int((cur_u or (0,))[0] or 0), now) + hours * 3600 + api_state = "pending" + cur = con.execute("UPDATE users SET unlim_until=? WHERE tg_id=?", (target, uid)) + if cur.rowcount < 1: + raise RuntimeError(f"users row missing uid={uid}") + con.execute("UPDATE donations SET until_ts=?, api_state=? WHERE invoice_id=?", + (target, api_state, int(inv_id))) + con.execute("COMMIT") + fresh = True + except Exception: + try: + con.execute("ROLLBACK") + except Exception: + pass + raise + if not fresh: + if api_state == "granted": + return {"status": "already", "until": target, "api": True, "fresh": False} + if api_state == "blocked": + return {"status": "blocked", "until": 0, "api": False, "fresh": False} + if api_state == "blocked": + log.warning(f"[DON-FIX] uid={uid} restricted: payment kept, entitlement not issued inv={inv_id}") + return {"status": "blocked", "until": 0, "api": False, "fresh": fresh} + api_ok = _prem_api_unlim(uid) + con.execute("UPDATE donations SET api_state=? WHERE invoice_id=? AND COALESCE(api_state,'none')!='granted'", + ("granted" if api_ok else "pending", int(inv_id))) + return {"status": "granted" if api_ok else "pending_api", "until": target, + "api": api_ok, "fresh": fresh} + except Exception as e: + log.error(f"[DON-FIX] fulfill fail inv={inv_id}: {e}") + return {"status": "error", "until": 0, "api": False, "fresh": False} + finally: + con.close() + +def _don_pending_api(): + """[DON-FIX] retry API entitlements that are paid but not granted yet. + + No provider token and no invoice-age filter: the obligation lives in our DB, so a + missing CryptoBot token can never strand it. Returns [(uid, invoice_id)] newly granted. + """ + _don_ensure_table() + try: + con = sqlite3.connect(BOT_DB, timeout=30) + try: + rows = con.execute("SELECT invoice_id, uid FROM donations " + "WHERE COALESCE(api_state,'none')='pending'").fetchall() + finally: + con.close() + except Exception as e: + log.error(f"[DON-FIX] pending api load: {e}") + return [] + granted = [] + for inv_id, uid in rows: + if not _prem_api_unlim(int(uid)): + continue + try: + con = sqlite3.connect(BOT_DB, timeout=30) + try: + con.execute("UPDATE donations SET api_state='granted' WHERE invoice_id=? " + "AND COALESCE(api_state,'none')='pending'", (int(inv_id),)) + con.commit() + finally: + con.close() + granted.append((int(uid), int(inv_id))) + log.info(f"[DON-FIX] api unlimited granted late uid={uid} inv={inv_id}") + except Exception as e: + log.error(f"[DON-FIX] pending api mark inv={inv_id}: {e}") + return granted + +def _don_reconcile(): + """[DON-FIX] deliver paid-but-undelivered donations without network or age filter. + + Returns [(invoice_id, uid, hours, result)] only for deliveries performed now, so a + still-pending API entitlement never re-notifies the user every poll. + """ + out = [] + try: + _don_ensure_table() + con = sqlite3.connect(BOT_DB, timeout=30) + try: + rows = con.execute("SELECT invoice_id, uid, hours FROM donations " + "WHERE status='paid' AND COALESCE(delivered,0)=0").fetchall() + finally: + con.close() + except Exception as e: + log.error(f"[DON-FIX] reconcile load: {e}") + return out + for inv_id, uid, hours in rows: + res = _don_fulfill(inv_id) + if res["fresh"]: + out.append((int(inv_id), int(uid), int(hours or 0), res)) + return out + +def _don_answer_text(hours, res): + """Short callback-answer text (Telegram caps it at 200 chars).""" + st = (res or {}).get("status") + if st == "granted": + return f"✅ Прем на {hours}ч! Безлимит: чат, картинки и API-ключ" + if st == "pending_api": + return f"✅ Прем на {hours}ч: чат и картинки без лимита. API-безлимит включим автоматически после выпуска ключа" + if st == "blocked": + return "Оплата получена, но аккаунт ограничен — напиши в поддержку" + if st == "already": + return "✅ Уже активировано" + return "Не удалось подтвердить — попробуй позже" + +def _don_confirm_text(hours, res): + """Full confirmation message for the poller. Honest about the API part.""" + st = (res or {}).get("status") + until = int((res or {}).get("until") or 0) + if st == "blocked": + return ("🎉 Оплата получена\n\nАккаунт ограничен, поэтому безлимит не выдан. " + "Напиши в поддержку — решим вручную.") + api_line = ("✅ API-безлимит включён" if st == "granted" else + "🔓 API-безлимит включим автоматически, как только выпустится твой ключ — " + "он не сгорит и не потеряется") + when = time.strftime("%d.%m %H:%M", time.localtime(until)) if until else "" + line = f"⏱ Действует до: {when}\n\n" if when else "" + return (f"🎉 Оплата подтверждена!\n\n" + f"✅ Безлимит на {hours}ч активирован\n{line}" + f"{api_line}\n\n💖 Спасибо за поддержку!") +# ─── [DON-FIX] end ────────────────────────────────────────────────────────── + async def _cp_post(method, data): if not CRYPTOPAY_TOKEN: @@ -11189,6 +11799,9 @@ async def _cp_post(method, data): @router.callback_query(F.data == "donate") async def cb_donate(c: CallbackQuery): lang = (db_get(c.from_user.id) or {}).get("lang") or "ru" + gate = _legacy_gate_text("donate") + if gate: + return await c.answer(gate, show_alert=True) if not CRYPTOPAY_TOKEN: return await c.answer("⚠️ Донаты временно недоступны (настройка платежей)", show_alert=True) u = db_get(c.from_user.id) or {} @@ -11221,6 +11834,9 @@ async def cb_donate_pack(c: CallbackQuery): for cb_id, amt, hours, asset in DONATE_PACKS: if cb_id != c.data: continue + gate = _legacy_gate_text("donate") + if gate: + return await c.answer(gate, show_alert=True) await c.answer() try: pay_amount = amt @@ -11244,16 +11860,9 @@ async def cb_donate_pack(c: CallbackQuery): inv = d["result"] pay_url = inv.get("pay_url") or inv.get("bot_invoice_url") or "" # Сохранить инвойс для поллинга - con = sqlite3.connect(BOT_DB, timeout=30) - try: - con.execute("CREATE TABLE IF NOT EXISTS donations " - "(invoice_id INTEGER PRIMARY KEY, uid INTEGER, hours INTEGER, " - "status TEXT DEFAULT 'pending', created INTEGER)") - con.execute("INSERT OR REPLACE INTO donations VALUES (?,?,?,?,?)", - (inv["invoice_id"], uid, hours, "pending", int(time.time()))) - con.commit() - finally: - con.close() + # [DON-FIX] explicit columns: a positional INSERT OR REPLACE would wipe + # delivered/until_ts/api_state of an already fulfilled invoice. + await asyncio.to_thread(_don_record_invoice, inv["invoice_id"], uid, hours) kb = InlineKeyboardMarkup(inline_keyboard=[ [InlineKeyboardButton(text=f"💳 Оплатить {pay_amount} {asset}", url=pay_url)], [InlineKeyboardButton(text="✅ Я оплатил", callback_data=f"dchk_{inv['invoice_id']}")], @@ -11271,78 +11880,93 @@ async def cb_donate_pack(c: CallbackQuery): @router.callback_query(F.data.startswith("dchk_")) async def cb_donate_check(c: CallbackQuery): inv_id = int(c.data.split("_")[1]) - con = sqlite3.connect(BOT_DB, timeout=30) + await asyncio.to_thread(_don_ensure_table) + # [SLOW-LOOP] the row read goes to a worker thread: this callback is a hot path and a + # 30s SQLite timeout must never stall every other coroutine on the loop. + row = await asyncio.to_thread(_don_row, inv_id) + if not row: + await c.answer("Счёт не найден", show_alert=True); return + uid, hours, status, delivered, api_state = row + caller = int(getattr(c.from_user, "id", 0) or 0) + # [DON-FIX] чужой счёт нельзя ни подтвердить, ни активировать; анонимный callback + # (caller=0) тоже отклоняем — fail closed, как в rank-пути. + if int(uid) != caller: + log.warning(f"donate check: чужой счёт inv={inv_id} caller={caller} owner={uid}") + await c.answer("Счёт не найден", show_alert=True); return + hours = int(hours or 0) + if delivered and api_state in ("granted", "blocked"): + await c.answer(_don_answer_text(hours, {"status": "already" if api_state == "granted" else "blocked"}), show_alert=True) + return try: - row = con.execute("SELECT uid, hours, status FROM donations WHERE invoice_id=?", (inv_id,)).fetchone() - if not row: - await c.answer("Счёт не найден", show_alert=True); return - uid, hours, status = row - if status == "paid": - await c.answer("✅ Уже активировано", show_alert=True) + if status != "paid": + d = await _cp_post("getInvoices", {"invoice_ids": str(inv_id)}) + items = (d.get("result") or {}).get("items") or [] + if not (items and items[0].get("status") == "paid"): + await c.answer("⏳ Оплата ещё не прошла — подожди", show_alert=True) + return + await asyncio.to_thread(_don_claim_paid, inv_id) + # [DON-FIX] выдача отдельным шагом: если она не прошла, статус остаётся + # оплаченным-but-недоставленным, и поллер довыдаст без повторного списания. + res = await asyncio.to_thread(_don_fulfill, inv_id) + if res["status"] in ("error", "no_user", "missing"): + log.error(f"donate check: оплачен, но не выдан inv={inv_id} uid={uid} status={res['status']}") + await c.answer("✅ Оплата получена — безлимит включим автоматически, попробуй через минуту", show_alert=True) return - finally: - con.close() - # Проверить статус в CryptoPay - try: - d = await _cp_post("getInvoices", {"invoice_ids": str(inv_id)}) - items = (d.get("result") or {}).get("items") or [] - if items and items[0].get("status") == "paid": - con = sqlite3.connect(BOT_DB, timeout=30) - try: - claim = con.execute("UPDATE donations SET status='paid' WHERE invoice_id=? AND status='pending'", (inv_id,)) - if claim.rowcount != 1: - await c.answer("✅ Уже активировано", show_alert=True) - return - con.execute("UPDATE users SET unlim_until=MAX(COALESCE(unlim_until,0),CAST(strftime('%s','now') AS INTEGER))+? WHERE tg_id=?", (hours * 3600, uid)) - con.commit() - finally: - con.close() - _prem_api_unlim(uid) - await c.answer(f"✅ Прем на {hours}ч! Безлимит: чат, картинки и API-ключ", show_alert=True) - else: - await c.answer("⏳ Оплата ещё не прошла — подожди", show_alert=True) + await c.answer(_don_answer_text(hours, res), show_alert=True) except Exception as e: log.error(f"donate check fail: {e}") await c.answer("Не удалось проверить — попробуй позже", show_alert=True) async def donate_poll_loop(bot: Bot): - """Поллинг неоплаченных инвойсов раз в 60 сек.""" + """Поллинг инвойсов раз в 60 сек. + + [DON-FIX] сначала довыдаём уже оплаченное — без сети, без токена CryptoBot и без + срока давности: обязательство лежит в нашей БД, а не у провайдера. Соединения + закрываются до сетевых await, чтобы не держать SQLite-блокировку на время HTTP. + """ while True: try: await asyncio.sleep(60) - con = sqlite3.connect(BOT_DB, timeout=30) + await asyncio.to_thread(_don_ensure_table) try: - con.execute("CREATE TABLE IF NOT EXISTS donations " - "(invoice_id INTEGER PRIMARY KEY, uid INTEGER, hours INTEGER, " - "status TEXT DEFAULT 'pending', created INTEGER)") - rows = con.execute("SELECT invoice_id, uid, hours FROM donations " - "WHERE status='pending' AND created > ?", - (int(time.time()) - 604800,)).fetchall() - for inv_id, uid, hours in rows: + for inv_id, uid, hours, res in await asyncio.to_thread(_don_reconcile): try: - d = await _cp_post("getInvoices", {"invoice_ids": str(inv_id)}) - items = (d.get("result") or {}).get("items") or [] - if items and items[0].get("status") == "paid": - claim = con.execute("UPDATE donations SET status='paid' WHERE invoice_id=? AND status='pending'", (inv_id,)) - if claim.rowcount != 1: - continue - con.execute("UPDATE users SET unlim_until=MAX(COALESCE(unlim_until,0),CAST(strftime('%s','now') AS INTEGER))+? WHERE tg_id=?", (hours * 3600, uid)) - con.commit() - _prem_api_unlim(uid) - row_u = con.execute("SELECT unlim_until FROM users WHERE tg_id=?", (uid,)).fetchone() - until = (row_u or (0,))[0] or int(time.time()) - try: - msg2 = (f'🎉 Оплата подтверждена!\n\n' - f'✅ Безлимит на {hours}ч активирован\n' - f'⏱ До: {time.strftime("%d.%m %H:%M", time.localtime(until))} UTC\n\n' - f'💖 Спасибо за поддержку!') - await bot.send_message(uid, msg2) - except Exception: - pass - except Exception: + await bot.send_message(uid, _don_confirm_text(hours, res)) + except Exception as e: + log.error(f"donate reconfirm uid={uid}: {e}") + except Exception as e: + log.error(f"donate reconcile: {e}") + try: + for uid, inv_id in await asyncio.to_thread(_don_pending_api): + try: + await bot.send_message(uid, "🔓 API-безлимит включён — твой ключ теперь без лимита. Спасибо за поддержку! 💖") + except Exception as e: + log.error(f"donate api notify uid={uid}: {e}") + except Exception as e: + log.error(f"donate pending api: {e}") + if not CRYPTOPAY_TOKEN: + continue + rows = await asyncio.to_thread(_don_pending_rows) + for inv_id, uid, hours in rows: + try: + d = await _cp_post("getInvoices", {"invoice_ids": str(inv_id)}) + items = (d.get("result") or {}).get("items") or [] + if not (items and items[0].get("status") == "paid"): continue - finally: - con.close() + if not await asyncio.to_thread(_don_claim_paid, inv_id): + continue + res = await asyncio.to_thread(_don_fulfill, inv_id) + if res["status"] in ("granted", "pending_api", "blocked"): + try: + await bot.send_message(int(uid), _don_confirm_text(int(hours or 0), res)) + except Exception: + pass + else: + log.error(f"donate poll: оплачен, но не выдан inv={inv_id} uid={uid} status={res['status']}") + except asyncio.CancelledError: + raise + except Exception: + continue except asyncio.CancelledError: raise except Exception as e: diff --git a/gateway/gateway_errors.py b/gateway/gateway_errors.py index 3dd8a249..d3daf51b 100644 --- a/gateway/gateway_errors.py +++ b/gateway/gateway_errors.py @@ -8,7 +8,70 @@ _log = logging.getLogger("gwerr") import os as _os import sqlite3 as _sq -_NEWAPI_DB = _os.environ.get("GW_NEWAPI_DB", "/opt/grok-gateway/new-api/one-api.db") + +def _load_runtime_config(): + """runtime_config is the single source of truth for the effective paths. + + Importing it directly works for both real entrypoints; the file-based fallback keeps + gateway-only importers (and tests) from silently reverting to the legacy literal. + """ + try: + import runtime_config + return runtime_config + except ImportError: + pass + candidate = _os.path.join(_os.path.dirname(_os.path.dirname(_os.path.abspath(__file__))), + "bot", "runtime_config.py") + try: + import importlib.util as _iu + spec = _iu.spec_from_file_location("iishko_gateway_runtime_config", candidate) + if spec is None or spec.loader is None: + return None + module = _iu.module_from_spec(spec) + spec.loader.exec_module(module) + return module + except Exception: + return None + + +_runtime_config = _load_runtime_config() +_gateway_db_path = getattr(_runtime_config, "gateway_db_path", None) +_bot_config_path = getattr(_runtime_config, "bot_config_path", None) +_LEGACY_NEWAPI_DB = "/opt/grok-gateway/new-api/one-api.db" + + +def _config_newapi_db(): + """`newapi_db` from the bot config file, or "" when it names none. + + The skin resolves its gateway DB through effective_bot_config(), so a deployment + that sets the path only in bot/config.json must not leave 401 diagnostics reading + the legacy literal. An unreadable or malformed file means "no opinion": env aliases + and the legacy default still apply. + """ + if _bot_config_path is None: + return "" + try: + with open(_bot_config_path(), encoding="utf-8-sig") as fh: + cfg = json.load(fh) + except Exception: + return "" + value = cfg.get("newapi_db") if isinstance(cfg, dict) else None + value = str(value).strip() if value else "" + return value + + +def _newapi_db(): + """Effective gateway DB, resolved late on every call. + + Order: IISHKO_GW_DB > GATE_NEWAPI_DB (the shared resolver used by the skin, bot and + launcher) > GW_NEWAPI_DB (legacy units) > bot/config.json `newapi_db` (the value the + skin itself serves) > legacy literal. Previously this read a hardcoded legacy path + even when the process served a different effective database, so 401 diagnostics + classified keys against the wrong token table. + """ + legacy = _os.environ.get("GW_NEWAPI_DB") or _config_newapi_db() or _LEGACY_NEWAPI_DB + return _gateway_db_path(legacy) if _gateway_db_path else legacy + # [POLICYMSG 2810] Вердикт модерации апстрима детерминирован: тот же текст на том же # OpenAI «content_filter»). Прежняя формулировка «Повтори попытку или выбери другую @@ -42,7 +105,7 @@ def token_state(api_key): if not api_key: return None try: - con = _sq.connect("file:" + _NEWAPI_DB + "?mode=ro", uri=True, timeout=3) + con = _sq.connect("file:" + _newapi_db() + "?mode=ro", uri=True, timeout=3) try: row = con.execute( 'SELECT status, COALESCE(remain_quota,0), COALESCE(unlimited_quota,0) ' diff --git a/gateway/grok-web-skin.py b/gateway/grok-web-skin.py index 6e66b961..ef985ce6 100644 --- a/gateway/grok-web-skin.py +++ b/gateway/grok-web-skin.py @@ -527,35 +527,104 @@ PRICING_SHOWCASE = frozenset([ ]) # [PRICING-ALL 2026-10-20] витрина = ВСЕ живые модели шлюза (abilities enabled=1 -import sqlite3 as _sqlite3, threading as _threading -_LIVE_DB = "/opt/grok-gateway/new-api/one-api.db" -_live_lock = _threading.Lock() -_live_cache = {"ts": 0.0, "models": set()} +import threading as _threading +# [CATALOGUE-DB 2026-10-31] Витрина читает ту же БД, что и шлюз. Жёсткий литерал +# игнорировал env-переопределение (IISHKO_GW_DB/GATE_NEWAPI_DB) и показывал модели +# из посторонней/мёртвой базы, поэтому берём эффективный путь. +_LIVE_DB = GATE_NEWAPI_DB +_LIVE_TTL = 300.0 # успешный снимок (в том числе честно пустой) живёт 5 минут +_LIVE_RETRY = 30.0 # после сбоя БД не перечитываем её на каждом запросе +_LIVE_MAX_STALE = _LIVE_TTL + _LIVE_RETRY +_live_lock = _threading.Lock() # защищает только _live_cache +_live_fetch_lock = _threading.Lock() # single-flight: один читатель БД за раз +_live_cache = {"ts": 0.0, "models": frozenset(), "known": False, "err_ts": None} EXTRA_HIDE = frozenset({ "", " ", "all", "codex-auto-review", }) # [ALLMODELS 20.10] витрина = ВСЕ живые модели; скрыт только мусор -def get_live_models(): - import time as _t - with _live_lock: - if _t.time() - _live_cache["ts"] < 300 and _live_cache["models"]: - return _live_cache["models"] +def _live_now(): + """Indirection over monotonic clock so tests can drive TTL/retry without sleeping.""" + return time.monotonic() + +def _live_read(): + """Живые модели из БД шлюза: строго read-only и без создания файла базы.""" + con = sqlite3.connect(Path(_LIVE_DB).resolve().as_uri() + "?mode=ro", uri=True, timeout=5) try: - con = _sqlite3.connect(_LIVE_DB, timeout=5) con.execute("PRAGMA busy_timeout=5000") + con.execute("PRAGMA query_only=ON") rows = con.execute( "SELECT DISTINCT a.model FROM abilities a JOIN channels c ON c.id=a.channel_id " "WHERE a.enabled=1 AND c.status=1").fetchall() + finally: con.close() - models = {r[0] for r in rows if r[0] and r[0].strip()} - if models: - with _live_lock: - _live_cache["ts"] = _t.time(); _live_cache["models"] = models - return models - except Exception: - LOG.warning("live_models_db_fail", exc_info=True) + return frozenset(str(r[0]) for r in rows if r[0] and str(r[0]).strip()) + +def _live_cached(): + """A failed database cannot make an old availability snapshot permanent.""" + with _live_lock: + if _live_cache["known"] and _live_now() - _live_cache["ts"] < _LIVE_MAX_STALE: + return _live_cache["models"], True + return frozenset(), False + +def _live_note_failure(exc): + """Логируем сбой не чаще окна ретрая, и никогда не роняем запрос каталога.""" + now = _live_now() + with _live_lock: + quiet = _live_cache["err_ts"] is not None and now - _live_cache["err_ts"] < _LIVE_RETRY + _live_cache["err_ts"] = now + known = _live_cache["known"] and now - _live_cache["ts"] < _LIVE_MAX_STALE + cached = len(_live_cache["models"]) + if quiet: + return + # sqlite_errorname (3.11+) names the reason without leaking the DB path. + reason = getattr(exc, "sqlite_errorname", "") or "" + label = "%s/%s" % (type(exc).__name__, reason) if reason else type(exc).__name__ + if known: + LOG.warning("live_models_db_fail: %s — serving stale live set of %d models", + label, cached) + else: + LOG.warning("live_models_db_fail: %s — live set unknown, catalogue fail-closed", + label) + +def _live_snapshot(): + """(models, known). known=False значит «набор живых моделей неизвестен», а не «живут все».""" + now = _live_now() + with _live_lock: + models, known = _live_cache["models"], _live_cache["known"] + ts, err_ts = _live_cache["ts"], _live_cache["err_ts"] + if known and now - ts < _LIVE_TTL: + return models, True + if err_ts is not None and now - err_ts < _LIVE_RETRY: + return _live_cached() + # Известный снимок отдаём сразу (stale-on-error), не встаём в очередь за обновлением. + if not _live_fetch_lock.acquire(blocking=not known): + return _live_cached() + try: + now = _live_now() + with _live_lock: # снимок мог обновить поток, державший лок до нас + if _live_cache["known"] and now - _live_cache["ts"] < _LIVE_TTL: + return _live_cache["models"], True + quiet = _live_cache["err_ts"] is not None and now - _live_cache["err_ts"] < _LIVE_RETRY + if quiet: + return _live_cached() + try: + models = _live_read() + except Exception as exc: + _live_note_failure(exc) + return _live_cached() with _live_lock: - return _live_cache["models"] + _live_cache.update(ts=_live_now(), models=models, known=True, err_ts=None) + return models, True + finally: + _live_fetch_lock.release() + +def live_models_snapshot(): + """(models, known) для каталога: пустой known-набор честно пуст, неизвестный — fail-closed.""" + return _live_snapshot() + +def get_live_models(): + """Живые модели шлюза; неизменяемый набор, пустой при неизвестном состоянии БД.""" + return _live_snapshot()[0] def _hidden(nm): if nm in HIDE_MODEL_NAMES or nm in EXTRA_HIDE: @@ -581,22 +650,32 @@ def filter_pricing_body(raw): if '/' in s: s = s.rsplit('/', 1)[-1] return s.replace('-', '.') - _cand = {} - for r in rows: - if isinstance(r, dict) and r.get('model_name') is not None: - _cand.setdefault(_norm_key(r['model_name']), []).append(str(r['model_name'])) - _best = {k: min(v, key=lambda n: (0 if '.' in n else 1, 0 if n == n.lower() else 1, len(n))) - for k, v in _cand.items()} - live = get_live_models() + live, known = live_models_snapshot() + # [CATALOGUE-DB 2026-10-31] сначала скрытие и проверка живости, только потом + # дедуп: иначе победителем алиаса становится выключенная строка, и живая + # модель (например qwen-max) выпадает из каталога. + survivors = [] for row in rows: if isinstance(row, dict): nm = row.get('model_name') if _hidden(nm): changed = True continue - if live and nm not in live: + if not known or nm not in live: + # known=False: состав живых моделей неизвестен — не выдумываем + # доступность. known=True и nm не в live: модель выключена. changed = True continue + survivors.append(row) + _cand = {} + for r in survivors: + if isinstance(r, dict) and r.get('model_name') is not None: + _cand.setdefault(_norm_key(r['model_name']), []).append(str(r['model_name'])) + _best = {k: min(v, key=lambda n: (0 if '.' in n else 1, 0 if n == n.lower() else 1, len(n))) + for k, v in _cand.items()} + for row in survivors: + if isinstance(row, dict): + nm = row.get('model_name') if _best.get(_norm_key(nm)) != str(nm): changed = True continue @@ -628,8 +707,13 @@ def filter_pricing_body(raw): for f_ in ("model_ratio", "model_price"): v = row.get(f_) if isinstance(v, (int, float)) and v: - row[f_] = round(v / 2, 6) - changed = True + halved = round(v / 2, 6) + # [PRICING-PASS 2026-10-31] помечаем изменение только когда + # тариф действительно переписан: иначе любое тело с dict-строкой + # ре-сериализуется, хотя фильтр ничего не сделал. + if row.get(f_) != halved: + row[f_] = halved + changed = True if not changed: return raw envelope['data'] = kept @@ -646,7 +730,8 @@ def response_headers(headers): -def error_response(status, raw, path, headers=None, user_balance=None, from_upstream=False, api_key=None): +def _error_payload(status, raw, path, user_balance=None, from_upstream=False, api_key=None): + """Build the public error body. A 401 lookup touches the gateway SQLite DB.""" upstream_status = status status, payload = public_error(status, raw, path, user_balance=user_balance, from_upstream=from_upstream, api_key=api_key) @@ -655,12 +740,39 @@ def error_response(status, raw, path, headers=None, user_balance=None, from_upst payload["error"].setdefault("request_id", request_id) LOG.warning("client_error status=%s upstream_status=%s code=%s path=%s request_id=%s", status, upstream_status, payload["error"]["code"], path, request_id) + return status, payload, request_id + + +def _finish_error(status, payload, request_id, headers=None): safe_headers = CIMultiDict((k, v) for k, v in (headers or {}).items() if k.lower() == "retry-after") safe_headers["Cache-Control"] = "no-store" safe_headers["X-Request-ID"] = request_id return web.json_response(payload, status=status, headers=safe_headers, dumps=public_json_dumps) + +def error_response(status, raw, path, headers=None, user_balance=None, from_upstream=False, api_key=None): + """Synchronous wire form. Loop callers must use async_error_response().""" + return _finish_error(*_error_payload(status, raw, path, user_balance=user_balance, + from_upstream=from_upstream, api_key=api_key), headers=headers) + + +async def async_error_response(status, raw, path, headers=None, user_balance=None, from_upstream=False, api_key=None): + """Same wire form as error_response(), with the DB lookup off the event loop. + + Only a 401 classification reads the gateway SQLite token table, so other + statuses stay inline: during an upstream 5xx storm every reply would otherwise + pay an extra worker hop for nothing. + """ + if status == 401: + payload = await asyncio.to_thread(_error_payload, status, raw, path, + user_balance=user_balance, from_upstream=from_upstream, + api_key=api_key) + else: + payload = _error_payload(status, raw, path, user_balance=user_balance, + from_upstream=from_upstream, api_key=api_key) + return _finish_error(*payload, headers=headers) + def map_sse_frame(frame: bytes, path: str) -> bytes: """Pass through byte-exact; if a data: frame contains JSON {"error":...} -> map to event: error.""" if len(frame) > MAX_SSE_FRAME: @@ -735,7 +847,7 @@ async def relay(req, upstream): if (req.method == "GET" and req.path == "/api/pricing" and upstream.status == 200 and "json" in upstream.headers.get("Content-Type", "").lower()): raw = await upstream.read() - filtered = filter_pricing_body(raw) + filtered = await asyncio.to_thread(filter_pricing_body, raw) if filtered is not raw: LOG.info("pricing_dedup %d -> %d bytes", len(raw), len(filtered)) return web.Response(status=upstream.status, body=filtered, headers=headers) @@ -914,7 +1026,7 @@ async def proxy(req): LOG.warning("client_disconnect_read") return web.Response(status=499) except web.HTTPException as exc: - return error_response(exc.status, b"", req.path, api_key=key_from_headers(req.headers)) + return await async_error_response(exc.status, b"", req.path, api_key=key_from_headers(req.headers)) requested_model = None request_object = None if is_api and body: @@ -1029,7 +1141,7 @@ async def proxy(req): async def selected_failure(status, raw, outgoing): key = key_from_headers(headers) balance = await asyncio.to_thread(_key_balance_usd, key) - return error_response(status, raw, req.path, headers=outgoing, + return await async_error_response(status, raw, req.path, headers=outgoing, user_balance=balance, from_upstream=True, api_key=key) try: return await relay_selected(req, session, URL(UPSTREAM + req.raw_path, encoded=True), @@ -1060,9 +1172,9 @@ async def proxy(req): sse_include_usage=sse_include_usage) return await relay(req, upstream) except asyncio.TimeoutError: - return error_response(504, b"", req.path, api_key=key_from_headers(req.headers)) + return await async_error_response(504, b"", req.path, api_key=key_from_headers(req.headers)) except aiohttp.ClientError: - return error_response(503, b"", req.path, api_key=key_from_headers(req.headers)) + return await async_error_response(503, b"", req.path, api_key=key_from_headers(req.headers)) # ---------- [BRAND] custom logo/favicon replaces new-api defaults (owner, 2026-10-11) ---------- @@ -1398,6 +1510,27 @@ def _tg_store_conn(): return con +def _tg_store_password(tg_id): + """Stored password, with the connection closed before any network await.""" + con = _tg_store_conn() + try: + row = con.execute("SELECT password FROM tg_users WHERE tg_id=?", (tg_id,)).fetchone() + return row[0] if row else None + finally: + con.close() + + +def _tg_store_password_put(tg_id, username, password): + """Persist the provisioned password in its own short write transaction.""" + con = _tg_store_conn() + try: + con.execute("INSERT OR REPLACE INTO tg_users(tg_id, username, password, created)" + " VALUES(?,?,?,?)", (tg_id, username, password, int(time.time()))) + con.commit() + finally: + con.close() + + def _key_share_seize(user_id, attacker_name, owner_name, key): if attacker_name == owner_name: return 0 # same identity: no violation to punish (defensive) @@ -1802,47 +1935,43 @@ async def tg_login(req): LOG.error("tg_login_admin_token_unreadable") return web.json_response({"success": False, "error": "provision_unavailable"}, status=500) try: - con = _tg_store_conn() - try: - row = con.execute("SELECT password FROM tg_users WHERE tg_id=?", (tg_id,)).fetchone() - password = row[0] if row else None - if password is None: - password = secrets.token_urlsafe(24) + # Read the store in a worker and close it before provisioning: the previous + # version ran connect+schema DDL (with a 2s busy timeout) on the event loop and + # kept the connection open across up to four network round trips. + password = await asyncio.to_thread(_tg_store_password, tg_id) + if password is None: + password = secrets.token_urlsafe(24) + status, body, _ = await _newapi_call( + session, "POST", "/api/user/", bearer, + {"username": username, "password": password, "display_name": display}) + if not _json_ok(status, body): + # Create failed (user likely exists but store lost the password, + # e.g. crash during first login). Recovery in rc.40: fetch the FULL + # user object, resend it with a new password (admin UpdateUser by Id + # persists the whole struct - partial bodies are rejected). + _, search_body, _ = await _newapi_call( + session, "GET", "/api/user/search?keyword=" + username, bearer) + uid = _find_user_id(search_body, username) + if uid is None: + LOG.warning("tg_login_provision_failed status=%s", status) + return web.json_response({"success": False, "error": "provision_failed"}, status=502) + _, user_body, _ = await _newapi_call( + session, "GET", "/api/user/" + str(uid), bearer) + try: + user_obj = json.loads(user_body).get("data") + except Exception: + user_obj = None + if not isinstance(user_obj, dict) or "id" not in user_obj: + LOG.warning("tg_login_recovery_fetch_failed uid=%s", uid) + return web.json_response({"success": False, "error": "provision_failed"}, status=502) + user_obj["password"] = password status, body, _ = await _newapi_call( - session, "POST", "/api/user/", bearer, - {"username": username, "password": password, "display_name": display}) + session, "PUT", "/api/user/", bearer, user_obj) if not _json_ok(status, body): - # Create failed (user likely exists but store lost the password, - # e.g. crash during first login). Recovery in rc.40: fetch the FULL - # user object, resend it with a new password (admin UpdateUser by Id - # persists the whole struct - partial bodies are rejected). - _, search_body, _ = await _newapi_call( - session, "GET", "/api/user/search?keyword=" + username, bearer) - uid = _find_user_id(search_body, username) - if uid is None: - LOG.warning("tg_login_provision_failed status=%s", status) - return web.json_response({"success": False, "error": "provision_failed"}, status=502) - _, user_body, _ = await _newapi_call( - session, "GET", "/api/user/" + str(uid), bearer) - try: - user_obj = json.loads(user_body).get("data") - except Exception: - user_obj = None - if not isinstance(user_obj, dict) or "id" not in user_obj: - LOG.warning("tg_login_recovery_fetch_failed uid=%s", uid) - return web.json_response({"success": False, "error": "provision_failed"}, status=502) - user_obj["password"] = password - status, body, _ = await _newapi_call( - session, "PUT", "/api/user/", bearer, user_obj) - if not _json_ok(status, body): - LOG.warning("tg_login_recovery_put_failed uid=%s status=%s", uid, status) - return web.json_response({"success": False, "error": "provision_failed"}, status=502) - LOG.info("tg_login_recovered uid=%s", uid) - con.execute("INSERT OR REPLACE INTO tg_users(tg_id, username, password, created)" - " VALUES(?,?,?,?)", (tg_id, username, password, int(time.time()))) - con.commit() - finally: - con.close() + LOG.warning("tg_login_recovery_put_failed uid=%s status=%s", uid, status) + return web.json_response({"success": False, "error": "provision_failed"}, status=502) + LOG.info("tg_login_recovered uid=%s", uid) + await asyncio.to_thread(_tg_store_password_put, tg_id, username, password) await asyncio.to_thread(_tg_link_upsert, tg_id, username) status, body, hdrs = await _newapi_call( session, "POST", "/api/user/login", None, diff --git a/gateway/transparent_api.py b/gateway/transparent_api.py index fde6009e..3b308f60 100644 --- a/gateway/transparent_api.py +++ b/gateway/transparent_api.py @@ -38,6 +38,13 @@ _BUSY_PATHS = frozenset(("/v1/chat/completions", "/v1/completions", _BUSY_WAITERS = WeakKeyDictionary() +async def _upstream_error(status, raw, path, **context): + """Keep the optional SQLite token lookup off the relay's event loop.""" + if status == 401: + return await asyncio.to_thread(public_error, status, raw, path, **context) + return public_error(status, raw, path, **context) + + class _BusyWaiters: """Single-loop recovery work, not generation/connection leases or an auth queue.""" @@ -428,9 +435,10 @@ async def relay_api(request, upstream, *, user_balance=None, requested_model=Non raw = _decode(raw or b"", encoding) if len(raw) > MAX_ERROR_BODY: raw = b"" - status, payload = public_error(upstream.status, raw, request.path, - user_balance=user_balance, from_upstream=True, - api_key=key_from_headers(request.headers)) + status, payload = await _upstream_error(upstream.status, raw, request.path, + user_balance=user_balance, + from_upstream=True, + api_key=key_from_headers(request.headers)) payload["error"]["gateway_request_id"] = request_id safe_headers = {"X-Request-ID": request_id, "Cache-Control": "no-store"} retry_after = headers.get("Retry-After", "") @@ -465,9 +473,11 @@ async def relay_api(request, upstream, *, user_balance=None, requested_model=Non status = int(status) except (ValueError, TypeError): status = 502 - status, payload = public_error(status if 400 <= status <= 599 else 502, decoded, request.path, - user_balance=user_balance, from_upstream=True, - api_key=key_from_headers(request.headers)) + status, payload = await _upstream_error(status if 400 <= status <= 599 else 502, + decoded, request.path, + user_balance=user_balance, + from_upstream=True, + api_key=key_from_headers(request.headers)) return web.json_response(payload, status=status, headers={"X-Request-ID": request_id}, dumps=public_json_dumps) try: if not isinstance(obj.get("model"), str): @@ -508,10 +518,11 @@ async def relay_api(request, upstream, *, user_balance=None, requested_model=Non status = int(status) except (ValueError, TypeError): status = 502 - status, payload = public_error(status if 400 <= status <= 599 else 502, - _decode(raw, encoding), request.path, - user_balance=user_balance, from_upstream=True, - api_key=key_from_headers(request.headers)) + status, payload = await _upstream_error(status if 400 <= status <= 599 else 502, + _decode(raw, encoding), request.path, + user_balance=user_balance, + from_upstream=True, + api_key=key_from_headers(request.headers)) return web.json_response(payload, status=status, headers={"X-Request-ID": request_id}, dumps=public_json_dumps) except ModelIdentityError: return web.json_response(_identity_error(), status=503, headers={"X-Request-ID": request_id}, dumps=public_json_dumps) diff --git a/tests/test_bot_stability_edges.py b/tests/test_bot_stability_edges.py index b49da39c..5bc998b9 100644 --- a/tests/test_bot_stability_edges.py +++ b/tests/test_bot_stability_edges.py @@ -2,17 +2,55 @@ import ast import asyncio from concurrent.futures import ThreadPoolExecutor +from contextlib import contextmanager from pathlib import Path import sqlite3 import tempfile import threading import time +from types import SimpleNamespace import unittest +from unittest import mock from test_bot_stability import (BOT, Content, Response, Session, actual_gateway, adapter, frame, stability) +class FakeClock: + """Thread-safe monotonic clock that moves only when the test says so. + + Budget accounting can then be asserted exactly instead of hoped for: no real + sleep, thread warm-up or scheduling delay can shorten the window. + """ + + def __init__(self, start: float = 1000.0) -> None: + self.start = start + self._value = start + self._lock = threading.Lock() + + def monotonic(self) -> float: + with self._lock: + return self._value + + def advance(self, seconds: float) -> None: + with self._lock: + self._value += seconds + + +@contextmanager +def fake_timing(clock: FakeClock): + """Drive adapter deadline math *and* event-loop timers from one fake clock. + + The adapter reads ``bot_stability.time.monotonic``; the controller additionally + enforces its own deadline with ``loop.time()`` (``asyncio.timeout_at``). Both are + replaced, so expiry can only happen through ``clock.advance``. + """ + loop = asyncio.get_running_loop() + with mock.patch.object(adapter, "time", SimpleNamespace(monotonic=clock.monotonic)), \ + mock.patch.object(loop, "time", clock.monotonic): + yield + + class StreamEdges(unittest.IsolatedAsyncioTestCase): async def test_default_model_is_admitted_not_bypassed(self): session = Session([Response()]) @@ -229,23 +267,44 @@ class AdapterEdges(unittest.IsolatedAsyncioTestCase): self.assertFalse(gate._cap_pending) async def test_remaining_budget_recomputed_after_cap_and_success_is_not_refunded(self): - calls = [] + # The cap transaction consumes exactly half of the 125 ms budget, on a clock + # the test owns. A dispatch that kept the pre-cap budget (0.125) or that let + # real time eat the window cannot produce the asserted numbers. + budget, cap_cost = 0.125, 0.0625 + clock = FakeClock() + dispatched, reserved, refunds = [], [], [] + def reserve(uid, model): - time.sleep(.02) + clock.advance(cap_cost) + reserved.append((uid, model)) return True, 1, 10, "receipt" + + def release(key): + refunds.append(key) + return True + async def stream(messages, model, send, t=360, _deadline=None): - calls.append(t) - self.assertLess(t, .07) - self.assertGreater(t, 0) + dispatched.append((model, t, _deadline)) return "exact" - ns = {"BOT_DB": "unused.db", "gw_chat_stream": stream, "pm_cap_reserve": reserve, - "pm_cap_release": lambda key: self.fail("dispatched request must retain its unit")} - gate = adapter.BotStability(ns); gate.install_wrappers() - token = adapter.POLICY.set(adapter.RequestPolicy(7, 0, .08)) - try: self.assertEqual(await ns["gw_chat_stream"]([], "m", None), "exact") - finally: adapter.POLICY.reset(token) - self.assertEqual(len(calls), 1) + + ns = {"BOT_DB": "unused.db", "gw_chat_stream": stream, + "pm_cap_reserve": reserve, "pm_cap_release": release} + gate = adapter.BotStability( + ns, controller=stability.StabilityController(clock=clock.monotonic)) + gate.install_wrappers() + token = adapter.POLICY.set(adapter.RequestPolicy(7, 0, budget)) + try: + with fake_timing(clock): + self.assertEqual(await ns["gw_chat_stream"]([], "m", None), "exact") + finally: + adapter.POLICY.reset(token) + gate._cap_executor.shutdown(wait=False) + self.assertEqual(reserved, [(7, "m")]) + self.assertEqual(dispatched, [("m", budget - cap_cost, clock.start + budget)]) + self.assertEqual(refunds, []) self.assertFalse(gate._cleanup_tasks) + self.assertFalse(gate._cap_pending) + self.assertEqual(gate.controller.snapshot()["outcomes"]["success"], 1) async def test_auxiliary_call_keeps_its_shorter_explicit_timeout(self): calls = [] diff --git a/tests/test_gateway_error_classification.py b/tests/test_gateway_error_classification.py index 958ad0c0..45460b47 100644 --- a/tests/test_gateway_error_classification.py +++ b/tests/test_gateway_error_classification.py @@ -2,8 +2,12 @@ import ast import importlib.util import json +import os +from contextlib import closing from pathlib import Path import re +import sqlite3 +import tempfile import unittest SOURCE = Path(__file__).resolve().parents[1] / 'gateway/gateway_errors.py' @@ -294,5 +298,106 @@ class PolicyCodeClassificationTests(unittest.TestCase): self.assertEqual((status, body['error']['code']), (400, 'invalid_request')) +class TokenStateDatabaseTests(unittest.TestCase): + """A 401 diagnostic must read the effective gateway DB, not a legacy literal.""" + + ENV = ("GW_NEWAPI_DB", "IISHKO_GW_DB", "GATE_NEWAPI_DB", "GROK_BOT_CFG") + + def setUp(self): + self._saved = {name: os.environ.get(name) for name in self.ENV} + for name in self.ENV: + os.environ.pop(name, None) + tmp = tempfile.TemporaryDirectory() + self.addCleanup(tmp.cleanup) + self.dir = tmp.name + + def tearDown(self): + for name, value in self._saved.items(): + if value is None: + os.environ.pop(name, None) + else: + os.environ[name] = value + + def db(self, name, rows): + path = os.path.join(self.dir, name) + with closing(sqlite3.connect(path)) as con: + con.execute('CREATE TABLE tokens(id INTEGER PRIMARY KEY, "key" TEXT, status INTEGER,' + ' remain_quota INTEGER, unlimited_quota INTEGER, deleted_at INTEGER)') + con.executemany('INSERT INTO tokens("key", status, remain_quota, unlimited_quota,' + ' deleted_at) VALUES(?,?,?,?,?)', rows) + con.commit() + return path + + def auth_error(self, key): + return MOD.public_error(401, b'{"error":{"message":"Invalid token"}}', + '/v1/chat/completions', api_key=key) + + def write_config(self, newapi_db): + path = os.path.join(self.dir, 'config.json') + with open(path, 'w', encoding='utf-8-sig') as fh: + json.dump({'newapi_db': newapi_db, 'bot_token': 'x'}, fh) + os.environ['GROK_BOT_CFG'] = path + return path + + def test_shared_resolver_is_wired_and_resolves_late(self): + self.assertIsNotNone(MOD._gateway_db_path, + 'gateway_errors fell back to the hardcoded legacy DB path') + # behaviour, not module shape: an alias set after import must be honoured, + # which an import-time snapshot could never do + late = self.db('late.db', [('k', 1, 42, 0, None)]) + os.environ['IISHKO_GW_DB'] = late + self.assertEqual(MOD.token_state('k'), (1, 42, 0)) + + def test_config_json_gateway_db_beats_the_legacy_literal(self): + """A deployment that sets the path only in bot/config.json must not misread 401s.""" + self.db('legacy.db', [('k', 4, 0, 0, None)]) + configured = self.db('configured.db', [('k', 1, 7000, 0, None)]) + self.write_config(configured) + self.assertEqual(MOD.token_state('k'), (1, 7000, 0)) + # an explicit env alias still outvotes the config file + os.environ['IISHKO_GW_DB'] = self.db('effective.db', [('k', 2, 900, 0, None)]) + self.assertEqual(MOD.token_state('k'), (2, 900, 0)) + + def test_missing_or_bogus_config_path_falls_back_without_raising(self): + os.environ['GROK_BOT_CFG'] = os.path.join(self.dir, 'no-such-dir', 'config.json') + self.assertIsNone(MOD.token_state('k')) + broken = os.path.join(self.dir, 'broken.json') + with open(broken, 'w', encoding='utf-8-sig') as fh: + fh.write('{"newapi_db": ') + os.environ['GROK_BOT_CFG'] = broken + self.assertIsNone(MOD.token_state('k')) + # a config that names a nonexistent DB is not an error either: no key state + self.write_config(os.path.join(self.dir, 'absent.db')) + self.assertIsNone(MOD.token_state('k')) + + def test_env_precedence_decides_which_token_table_is_read(self): + stale = self.db('legacy.db', [('k', 4, 0, 0, None)]) + live = self.db('effective.db', [('k', 1, 5000, 0, None)]) + os.environ['GW_NEWAPI_DB'] = stale # legacy-only unit keeps working + self.assertEqual(MOD.token_state('k'), (4, 0, 0)) + # a stale legacy alias must not outvote the DB the rest of the stack serves + os.environ['GATE_NEWAPI_DB'] = live + self.assertEqual(MOD.token_state('k'), (1, 5000, 0)) + del os.environ['GATE_NEWAPI_DB'] + self.assertEqual(MOD.token_state('k'), (4, 0, 0)) + del os.environ['GW_NEWAPI_DB'] + os.environ['GATE_NEWAPI_DB'] = stale + os.environ['IISHKO_GW_DB'] = live # canonical name wins over GATE_NEWAPI_DB + self.assertEqual(MOD.token_state('k'), (1, 5000, 0)) + + def test_zero_balance_key_is_reported_as_empty_not_invalid(self): + os.environ['IISHKO_GW_DB'] = self.db('effective.db', [('deadbeef', 1, 0, 0, None)]) + status, body = self.auth_error('deadbeef') + self.assertEqual((status, body['error']['code']), (402, 'api_key_empty')) + + def test_foreign_database_never_makes_a_healthy_key_look_empty(self): + # The old hardcoded path belonged to another deployment: a drained key there + # must not change this gateway's verdict about its own healthy key. + self.db('legacy.db', [('healthy', 4, 0, 0, None)]) + os.environ['IISHKO_GW_DB'] = self.db('effective.db', [('healthy', 1, 900000, 0, None)]) + status, body = self.auth_error('healthy') + self.assertEqual((status, body['error']['code']), (401, 'invalid_api_key')) + + if __name__ == '__main__': unittest.main() diff --git a/tests/test_legacy_payment_fulfillment.py b/tests/test_legacy_payment_fulfillment.py new file mode 100644 index 00000000..a91863b8 --- /dev/null +++ b/tests/test_legacy_payment_fulfillment.py @@ -0,0 +1,718 @@ +"""Legacy rank/donation fulfillment: paid != delivered, honest API promises, opt-in sales. + +The helpers live in the ``bot/grok_bot.py`` monolith, so the exact functions and module +constants are extracted by name and executed against disposable SQLite databases. Every +assertion below runs the real code: no source-string matching. +""" +import ast +import asyncio +import json +import os +import sqlite3 +import sys +import tempfile +import threading +import time +import unittest +from contextlib import closing +from pathlib import Path + +ROOT = Path(__file__).resolve().parents[1] +BOT_SRC = ROOT / "bot" / "grok_bot.py" +# _prem_api_unlim resolves the account's gateway key names through the real helper; +# a stub would let the tests pass while production mis-resolves token names. +sys.path.insert(0, str(ROOT / "bot")) +import account_limits # noqa: E402 (path prepared just above) + +DONATION_FUNCS = ( + "_prem_api_unlim", "_don_ensure_table", "_don_record_invoice", "_don_claim_paid", + "_don_fulfill", "_don_pending_api", "_don_reconcile", "_don_answer_text", "_don_confirm_text", +) +RANK_FUNCS = ( + "_rb_ensure_table", "_rb_apply", "_rb_settle", "_rb_bonus_settle", "_rb_bonus_grant", + "_rb_token_bonus", "_rb_token_name", "_rb_reconcile", "_rb_claim_paid", "_rb_bonus_granted", + "_rb_pending_load", "_rb_pending_save", "_rb_pending_flush", + "_rb_delivered", "_rb_invoice_delivered", + "rankbuy_poll_loop", +) +GATE_FUNCS = ("_legacy_sales_enabled", "_legacy_gate_text") +CONSTS = ("_LEGACY_ON", "_LEGACY_GATE_TEXT", "_LEGACY_GATE_LOG") + +USERS_DDL = ("CREATE TABLE users(tg_id INTEGER PRIMARY KEY, token_name TEXT, banned INTEGER DEFAULT 0," + " api_blocked INTEGER DEFAULT 0, unlim_until INTEGER DEFAULT 0," + " badge_lock INTEGER DEFAULT 0, badge_until INTEGER DEFAULT 0)") +TOKENS_DDL = ('CREATE TABLE tokens(id INTEGER PRIMARY KEY, name TEXT, remain_quota INTEGER DEFAULT 0,' + ' unlimited_quota INTEGER DEFAULT 0, status INTEGER DEFAULT 1, deleted_at INTEGER,' + ' "group" TEXT DEFAULT \'t1\')') + +LOYALTY_BONUS = {2: 500000, 3: 1000000, 4: 2500000} + + +class _Log: + def __init__(self): + self.lines = [] + + def _add(self, level, msg, args): + self.lines.append((level, (msg % args) if args else str(msg))) + + def info(self, msg, *a): + self._add("info", msg, a) + + def warning(self, msg, *a): + self._add("warning", msg, a) + + def error(self, msg, *a): + self._add("error", msg, a) + + +def _extract(names, consts): + tree = ast.parse(BOT_SRC.read_text(encoding="utf-8")) + wanted, got = [], set() + for node in tree.body: + if isinstance(node, (ast.FunctionDef, ast.AsyncFunctionDef)) and node.name in names: + wanted.append(node) + got.add(node.name) + elif isinstance(node, ast.Assign): + for target in node.targets: + if isinstance(target, ast.Name) and target.id in consts: + wanted.append(node) + got.add(target.id) + missing = (set(names) | set(consts)) - got + if missing: + raise AssertionError(f"bot/grok_bot.py no longer defines: {sorted(missing)}") + return wanted + + +class LegacyFulfillmentCase(unittest.TestCase): + cryptopay_token = "" + xrocket_token = "" + commerce_offers = None + legacy_products = None + + def setUp(self): + temp = tempfile.TemporaryDirectory() + self.addCleanup(temp.cleanup) + self.dir = Path(temp.name) + self.bot_db = str(self.dir / "bot.db") + self.gw_db = str(self.dir / "api.db") + self.log = _Log() + with closing(sqlite3.connect(self.bot_db)) as con: + con.execute(USERS_DDL) + con.execute("INSERT INTO users(tg_id, token_name) VALUES(123, 'tg123')") + con.commit() + with closing(sqlite3.connect(self.gw_db)) as con: + con.execute(TOKENS_DDL) + con.commit() + cfg = {"newapi_db": self.gw_db, "bot_db": self.bot_db} + if self.commerce_offers is not None: + cfg["commerce_offers"] = self.commerce_offers + if self.legacy_products is not None: + cfg["legacy_products"] = self.legacy_products + self.ns = { + "sqlite3": sqlite3, "time": time, "json": json, "os": os, "Path": Path, + "account_limits": account_limits, + "log": self.log, "BOT_DB": self.bot_db, "GW_DB": self.gw_db, "CFG": cfg, + "CRYPTOPAY_TOKEN": self.cryptopay_token, "XROCKET_TOKEN": self.xrocket_token, + "LOYALTY_BONUS": LOYALTY_BONUS, "RANKBUY_PRICE": 10, + "RANKBUY_JUMP": {1: 25, 2: 18, 3: 10}, + "capped_bonus": lambda uid, bonus: bonus, + "_RANK_SYNC": {}, "sync_rank_limits": lambda uid, ttl=0: None, + "_RB_PENDING_PATH": str(self.dir / "rb_pending_bonus.json"), + # rankbuy_poll_loop is extracted for the race tests: its `bot: Bot` + # annotation is evaluated at exec time. + "Bot": object, "asyncio": asyncio, + } + body = _extract(DONATION_FUNCS + RANK_FUNCS + GATE_FUNCS, CONSTS) + exec(compile(ast.Module(body=body, type_ignores=[]), "legacy-fulfillment", "exec"), self.ns) + + # ── helpers ──────────────────────────────────────────────────────────── + def call(self, name, *args): + return self.ns[name](*args) + + def bot_sql(self, query, params=()): + with closing(sqlite3.connect(self.bot_db)) as con: + rows = con.execute(query, params).fetchall() + con.commit() + return rows + + def gw_sql(self, query, params=()): + with closing(sqlite3.connect(self.gw_db)) as con: + rows = con.execute(query, params).fetchall() + con.commit() + return rows + + def add_token(self, name="tg123", deleted_at=None, remain_quota=0, unlimited=0): + with closing(sqlite3.connect(self.gw_db)) as con: + con.execute("INSERT INTO tokens(name, remain_quota, unlimited_quota, deleted_at)" + " VALUES(?,?,?,?)", (name, remain_quota, unlimited, deleted_at)) + con.commit() + + def paid_donation(self, inv_id, uid=123, hours=24): + self.call("_don_record_invoice", inv_id, uid, hours) + self.assertTrue(self.call("_don_claim_paid", inv_id)) + + def paid_rank(self, inv_id, uid=123, to_lvl=2, amount="10", provider="cp"): + self.call("_rb_ensure_table") + with closing(sqlite3.connect(self.bot_db)) as con: + con.execute("INSERT INTO rank_purchases(invoice_id, uid, from_lvl, to_lvl, amount_usd," + " status, created, provider) VALUES(?,?,?,?,?, 'paid', ?, ?)", + (inv_id, uid, to_lvl - 1, to_lvl, amount, int(time.time()) - 60, provider)) + con.commit() + + +class DonationFulfillmentTests(LegacyFulfillmentCase): + def test_paid_donation_without_issued_key_keeps_api_obligation_pending(self): + """No gateway token yet: premium is issued, the API promise stays pending and honest.""" + self.paid_donation(9001) + before = int(self.bot_sql("SELECT COALESCE(unlim_until,0) FROM users WHERE tg_id=123")[0][0]) + self.assertEqual(before, 0) + started = int(time.time()) + res = self.call("_don_fulfill", 9001) + + self.assertEqual(res["status"], "pending_api") + self.assertFalse(res["api"]) + self.assertTrue(res["fresh"]) + # premium starts at payment time, never at the epoch, and is not shortened + self.assertGreaterEqual(int(res["until"]), started + 24 * 3600) + self.assertLess(int(res["until"]), started + 24 * 3600 + 120) + self.assertEqual(self.bot_sql("SELECT COALESCE(unlim_until,0) FROM users WHERE tg_id=123")[0][0], + int(res["until"])) + self.assertEqual(self.bot_sql("SELECT status, COALESCE(delivered,0), COALESCE(api_state,'none')" + " FROM donations WHERE invoice_id=9001")[0], + ("paid", 1, "pending")) + # the answer must not claim an API key that does not exist + answer = self.call("_don_answer_text", 24, res) + self.assertIn("API-безлимит включим автоматически", answer) + self.assertNotIn("и API-ключ", answer) + self.assertLessEqual(len(answer), 200) + self.assertIn("не сгорит", self.call("_don_confirm_text", 24, res)) + + def test_pending_api_entitlement_is_granted_once_the_key_exists(self): + self.paid_donation(9001) + first = self.call("_don_fulfill", 9001) + until_after_first = int(first["until"]) + self.add_token("tg123") + + granted = self.call("_don_pending_api") + self.assertEqual(granted, [(123, 9001)]) + self.assertEqual(self.gw_sql("SELECT unlimited_quota, \"group\" FROM tokens WHERE name='tg123'")[0], + (1, "premium")) + # a retry neither re-grants nor extends the paid premium a second time + self.assertEqual(self.call("_don_pending_api"), []) + again = self.call("_don_fulfill", 9001) + self.assertEqual(again["status"], "already") + self.assertTrue(again["api"]) + self.assertFalse(again["fresh"]) + self.assertEqual(int(self.bot_sql("SELECT COALESCE(unlim_until,0) FROM users WHERE tg_id=123")[0][0]), + until_after_first) + self.assertEqual(self.bot_sql("SELECT COALESCE(api_state,'none') FROM donations" + " WHERE invoice_id=9001")[0][0], "granted") + + def test_premium_hours_are_never_credited_twice(self): + self.paid_donation(9002, hours=72) + self.add_token("tg123") + first = self.call("_don_fulfill", 9002) + second = self.call("_don_fulfill", 9002) + self.assertEqual(first["status"], "granted") + self.assertEqual(second["status"], "already") + self.assertEqual(int(first["until"]), int(second["until"])) + self.assertEqual(self.bot_sql("SELECT COALESCE(until_ts,0) FROM donations WHERE invoice_id=9002")[0][0], + int(first["until"])) + self.assertEqual(self.call("_don_reconcile"), []) + + def test_blocked_account_keeps_the_payment_without_entitlement(self): + self.bot_sql("UPDATE users SET banned=1 WHERE tg_id=123") + self.paid_donation(9003) + res = self.call("_don_fulfill", 9003) + + self.assertEqual(res["status"], "blocked") + self.assertTrue(res["fresh"]) + self.assertEqual(self.bot_sql("SELECT COALESCE(unlim_until,0) FROM users WHERE tg_id=123")[0][0], 0) + self.assertEqual(self.bot_sql("SELECT status, COALESCE(delivered,0), COALESCE(api_state,'none')" + " FROM donations WHERE invoice_id=9003")[0], ("paid", 1, "blocked")) + self.add_token("tg123") + self.assertEqual(self.call("_don_pending_api"), []) + self.assertEqual(self.gw_sql("SELECT unlimited_quota FROM tokens WHERE name='tg123'")[0][0], 0) + # a second pass does not re-notify and does not issue anything + self.assertEqual(self.call("_don_fulfill", 9003)["status"], "blocked") + self.assertEqual(self.call("_don_reconcile"), []) + self.assertIn("ограничен", self.call("_don_answer_text", 24, res)) + + def test_reconcile_delivers_paid_rows_without_any_provider_token(self): + """A crash between provider confirmation and delivery is recovered offline.""" + self.call("_don_ensure_table") + with closing(sqlite3.connect(self.bot_db)) as con: + con.execute("INSERT INTO donations(invoice_id, uid, hours, status, created)" + " VALUES(9004, 123, 168, 'paid', ?)", (int(time.time()) - 999999,)) + con.commit() + self.add_token("tg123") + + rows = self.call("_don_reconcile") + self.assertEqual([r[:3] for r in rows], [(9004, 123, 168)]) + self.assertEqual(rows[0][3]["status"], "granted") + self.assertGreater(int(self.bot_sql("SELECT COALESCE(unlim_until,0) FROM users WHERE tg_id=123")[0][0]), + int(time.time())) + self.assertEqual(self.call("_don_reconcile"), []) + + def test_repeated_invoice_recording_preserves_delivery_state(self): + self.paid_donation(9005, hours=24) + self.add_token("tg123") + res = self.call("_don_fulfill", 9005) + until = int(res["until"]) + self.call("_don_record_invoice", 9005, 123, 24) + + self.assertEqual(self.bot_sql("SELECT status, COALESCE(delivered,0), COALESCE(api_state,'none')," + " COALESCE(until_ts,0) FROM donations WHERE invoice_id=9005")[0], + ("paid", 1, "granted", until)) + self.assertEqual(int(self.bot_sql("SELECT COALESCE(unlim_until,0) FROM users WHERE tg_id=123")[0][0]), + until) + self.assertEqual(self.call("_don_fulfill", 9005)["status"], "already") + + def test_legacy_paid_history_is_not_regranted_by_the_migration(self): + with closing(sqlite3.connect(self.bot_db)) as con: + con.execute("CREATE TABLE donations(invoice_id INTEGER PRIMARY KEY, uid INTEGER, hours INTEGER," + " status TEXT DEFAULT 'pending', created INTEGER)") + con.execute("INSERT INTO donations VALUES(9006, 123, 24, 'paid', 1700000000)") + con.execute("INSERT INTO donations VALUES(9007, 123, 24, 'pending', 1700000000)") + con.commit() + self.add_token("tg123") + self.call("_don_ensure_table") + + self.assertEqual(self.bot_sql("SELECT COALESCE(delivered,0), COALESCE(api_state,'none')" + " FROM donations WHERE invoice_id=9006")[0], (1, "granted")) + self.assertEqual(self.bot_sql("SELECT COALESCE(unlim_until,0) FROM users WHERE tg_id=123")[0][0], 0) + self.assertEqual(self.gw_sql("SELECT unlimited_quota FROM tokens WHERE name='tg123'")[0][0], 0) + self.assertEqual(self.call("_don_reconcile"), []) + # an old pending invoice is still deliverable: the age filter never applied here + self.call("_don_claim_paid", 9007) + self.assertEqual(self.call("_don_fulfill", 9007)["status"], "granted") + + def test_missing_gateway_database_is_reported_not_created(self): + self.ns["CFG"]["newapi_db"] = str(self.dir / "absent" / "one-api.db") + self.assertFalse(self.call("_prem_api_unlim", 123)) + self.assertFalse((self.dir / "absent").exists()) + self.assertTrue(any(level == "error" for level, _ in self.log.lines)) + + def test_api_unlim_tells_the_truth_about_deleted_and_live_tokens(self): + self.assertFalse(self.call("_prem_api_unlim", 123)) # no row at all + self.add_token("tg123", deleted_at=int(time.time())) + self.assertFalse(self.call("_prem_api_unlim", 123)) # soft-deleted row is not a grant + with closing(sqlite3.connect(self.gw_db)) as con: + con.execute("UPDATE tokens SET deleted_at=NULL WHERE name='tg123'") + con.commit() + self.assertTrue(self.call("_prem_api_unlim", 123)) + self.assertEqual(self.gw_sql("SELECT unlimited_quota, \"group\" FROM tokens WHERE name='tg123'")[0], + (1, "premium")) + + +class RankFulfillmentTests(LegacyFulfillmentCase): + def test_failed_grant_is_never_reported_as_activated_and_retry_finishes_it(self): + self.paid_rank(7001, to_lvl=2) + self.add_token("tg123") + with closing(sqlite3.connect(self.bot_db)) as con: + con.execute("CREATE TRIGGER fail_grant BEFORE UPDATE OF badge_lock ON users" + " BEGIN SELECT RAISE(ABORT, 'injected persistent grant write failure'); END") + con.commit() + + self.assertFalse(self.call("_rb_settle", 123, 2, 7001)) + self.assertEqual(self.bot_sql("SELECT status, COALESCE(delivered,0) FROM rank_purchases" + " WHERE invoice_id=7001")[0], ("paid", 0)) + self.assertEqual(self.bot_sql("SELECT COALESCE(badge_lock,0) FROM users WHERE tg_id=123")[0][0], 0) + # reconcile keeps retrying while the write fails, and reports nothing to the user + self.assertEqual(self.call("_rb_reconcile"), []) + self.assertEqual(self.gw_sql("SELECT remain_quota FROM tokens WHERE name='tg123'")[0][0], 0) + + with closing(sqlite3.connect(self.bot_db)) as con: + con.execute("DROP TRIGGER fail_grant") + con.commit() + rows = self.call("_rb_reconcile") + self.assertEqual([r[:3] for r in rows], [(123, 2, 7001)]) + self.assertEqual(self.bot_sql("SELECT status, COALESCE(delivered,0), COALESCE(bonus_state,'none')" + " FROM rank_purchases WHERE invoice_id=7001")[0], ("paid", 1, "granted")) + self.assertEqual(self.bot_sql("SELECT COALESCE(badge_lock,0) FROM users WHERE tg_id=123")[0][0], 2) + self.assertEqual(self.gw_sql("SELECT remain_quota FROM tokens WHERE name='tg123'")[0][0], + LOYALTY_BONUS[2]) + # exactly one delivery: no second badge write, no second bonus + self.assertEqual(self.call("_rb_reconcile"), []) + self.assertEqual(self.gw_sql("SELECT remain_quota FROM tokens WHERE name='tg123'")[0][0], + LOYALTY_BONUS[2]) + self.assertTrue(self.call("_rb_bonus_granted", 7001)) + + def test_bonus_obligation_survives_a_missing_then_deleted_token_row(self): + self.call("_rb_pending_save", {"123": LOYALTY_BONUS[3]}) + self.assertEqual(self.call("_rb_pending_flush"), 0) + self.assertEqual(self.call("_rb_pending_load"), {"123": LOYALTY_BONUS[3]}) + + self.add_token("tg123", deleted_at=int(time.time())) + self.assertEqual(self.call("_rb_pending_flush"), 0) + self.assertEqual(self.call("_rb_pending_load"), {"123": LOYALTY_BONUS[3]}) + self.assertEqual(self.gw_sql("SELECT remain_quota FROM tokens WHERE name='tg123'")[0][0], 0) + + with closing(sqlite3.connect(self.gw_db)) as con: + con.execute("UPDATE tokens SET deleted_at=NULL, remain_quota=10 WHERE name='tg123'") + con.commit() + self.assertEqual(self.call("_rb_pending_flush"), 1) + self.assertEqual(self.gw_sql("SELECT remain_quota FROM tokens WHERE name='tg123'")[0][0], + LOYALTY_BONUS[3]) + self.assertFalse(os.path.exists(self.ns["_RB_PENDING_PATH"])) + self.assertEqual(self.call("_rb_pending_flush"), 0) + + def test_bonus_quota_uses_max_semantics_and_never_accumulates(self): + """A retry must not pay the rank bonus twice or shrink an already larger balance.""" + self.add_token("tg123", remain_quota=0) + self.assertTrue(self.call("_rb_bonus_grant", 123, LOYALTY_BONUS[2])) + self.assertEqual(self.gw_sql("SELECT remain_quota FROM tokens WHERE name='tg123'")[0][0], + LOYALTY_BONUS[2]) + self.assertTrue(self.call("_rb_bonus_grant", 123, LOYALTY_BONUS[2])) + self.assertEqual(self.gw_sql("SELECT remain_quota FROM tokens WHERE name='tg123'")[0][0], + LOYALTY_BONUS[2]) + # a user who already has more quota keeps it + self.assertTrue(self.call("_rb_bonus_grant", 123, 10)) + self.assertEqual(self.gw_sql("SELECT remain_quota FROM tokens WHERE name='tg123'")[0][0], + LOYALTY_BONUS[2]) + # a disabled token is re-enabled, a deleted one is never resurrected + with closing(sqlite3.connect(self.gw_db)) as con: + con.execute("UPDATE tokens SET status=4 WHERE name='tg123'") + con.commit() + self.assertTrue(self.call("_rb_bonus_grant", 123, LOYALTY_BONUS[2])) + self.assertEqual(self.gw_sql("SELECT status FROM tokens WHERE name='tg123'")[0][0], 1) + self.assertFalse(self.call("_rb_bonus_grant", 456, LOYALTY_BONUS[2])) + + def test_button_delivery_wins_the_race_and_reconcile_stays_silent(self): + """One invoice = one delivery and one notification, whoever gets there first.""" + self.paid_rank(7003, to_lvl=2) + self.add_token("tg123") + self.assertTrue(self.call("_rb_settle", 123, 2, 7003, True)) + self.assertEqual(self.bot_sql("SELECT status, COALESCE(delivered,0), COALESCE(bonus_state,'none')" + " FROM rank_purchases WHERE invoice_id=7003")[0], + ("paid", 1, "granted")) + # the poller re-reads the same invoice and must neither re-deliver nor announce it + self.assertEqual(self.call("_rb_reconcile"), []) + self.assertFalse(self.call("_rb_settle", 123, 2, 7003, True)) + self.assertEqual(self.gw_sql("SELECT remain_quota FROM tokens WHERE name='tg123'")[0][0], + LOYALTY_BONUS[2]) + self.assertTrue(self.call("_rb_invoice_delivered", 7003)) + self.assertIn("rankbuy already delivered", " ".join(line for _, line in self.log.lines)) + + def test_poller_loses_the_button_race_and_does_not_confirm_twice(self): + """The paid_list sweep must claim too: the button can deliver mid-sweep.""" + self.call("_rb_ensure_table") + for inv in (7101, 7102): + with closing(sqlite3.connect(self.bot_db)) as con: + con.execute("INSERT INTO rank_purchases(invoice_id, uid, from_lvl, to_lvl," + " amount_usd, status, created, provider)" + " VALUES(?, 123, 1, 2, '10', 'pending', ?, 'cp')", + (inv, int(time.time()) - 60)) + con.commit() + self.add_token("tg123") + self.ns["CRYPTOPAY_TOKEN"] = "tok" + + confirms = [] + + async def _rb_confirm(bot, uid, to_lvl, amount, provider, bonus_ok): + confirms.append((uid, to_lvl, amount, provider, bonus_ok)) + + async def _rb_inv_paid(provider, inv_id, inv_ext): + if int(inv_id) == 7102: + # the sweep is still polling: meanwhile the user pressed «Я оплатил» for 7101 + # (status is already 'paid', delivered=0), which delivers and announces it. + if self.ns["_rb_settle"](123, 2, 7101, True): + await _rb_confirm(None, 123, 2, "10", "cp", + self.ns["_rb_bonus_granted"](7101)) + return False + return True + + class _Driver: + """One poll pass, then cancellation instead of a real 15s sleep.""" + + CancelledError = asyncio.CancelledError + to_thread = staticmethod(asyncio.to_thread) + + def __init__(self): + self.passes = 0 + + async def sleep(self, *_a): + self.passes += 1 + if self.passes > 1: + raise asyncio.CancelledError + + self.ns["_rb_confirm"] = _rb_confirm + self.ns["_rb_inv_paid"] = _rb_inv_paid + self.ns["asyncio"] = _Driver() + + with self.assertRaises(asyncio.CancelledError): + asyncio.run(self.ns["rankbuy_poll_loop"](None)) + + # exactly one announcement: the button's. The poller re-settling 7101 must be silent. + self.assertEqual(confirms, [(123, 2, "10", "cp", True)]) + self.assertEqual(self.bot_sql("SELECT status, COALESCE(delivered,0), COALESCE(bonus_state,'none')" + " FROM rank_purchases WHERE invoice_id=7101")[0], + ("paid", 1, "granted")) + # MAX semantics: the second settle attempt must not double the bonus quota + self.assertEqual(self.gw_sql("SELECT remain_quota FROM tokens WHERE name='tg123'")[0][0], + LOYALTY_BONUS[2]) + self.assertIn("rankbuy already delivered", " ".join(line for _, line in self.log.lines)) + + def test_claim_rolls_back_when_the_grant_fails_so_retry_can_finish_it(self): + self.paid_rank(7004, to_lvl=2) + self.add_token("tg123") + with closing(sqlite3.connect(self.bot_db)) as con: + con.execute("CREATE TRIGGER fail_grant BEFORE UPDATE OF badge_lock ON users" + " BEGIN SELECT RAISE(ABORT, 'injected persistent grant write failure'); END") + con.commit() + self.assertFalse(self.call("_rb_settle", 123, 2, 7004, True)) + self.assertEqual(self.bot_sql("SELECT COALESCE(delivered,0), COALESCE(bonus_state,'none')" + " FROM rank_purchases WHERE invoice_id=7004")[0][0], 0) + self.assertFalse(self.call("_rb_invoice_delivered", 7004)) + + with closing(sqlite3.connect(self.bot_db)) as con: + con.execute("DROP TRIGGER fail_grant") + con.commit() + self.assertEqual([r[:3] for r in self.call("_rb_reconcile")], [(123, 2, 7004)]) + self.assertTrue(self.call("_rb_invoice_delivered", 7004)) + self.assertEqual(self.bot_sql("SELECT COALESCE(badge_lock,0) FROM users WHERE tg_id=123")[0][0], 2) + self.assertEqual(self.gw_sql("SELECT remain_quota FROM tokens WHERE name='tg123'")[0][0], + LOYALTY_BONUS[2]) + + def test_delivered_probe_reports_false_on_a_broken_database(self): + """A dead DB must not turn into an exception on the callback path.""" + self.call("_rb_ensure_table") + self.assertFalse(self.call("_rb_invoice_delivered", 9999)) + self.ns["BOT_DB"] = str(self.dir / "no-such-dir" / "bot.db") + self.assertFalse(self.call("_rb_invoice_delivered", 9999)) + self.assertTrue(any(line.startswith("rb delivered read") for _, line in self.log.lines)) + + def test_claim_paid_is_a_one_shot_transition(self): + self.call("_rb_ensure_table") + with closing(sqlite3.connect(self.bot_db)) as con: + con.execute("INSERT INTO rank_purchases(invoice_id, uid, from_lvl, to_lvl, amount_usd," + " status, created, provider) VALUES(7002, 123, 1, 2, '10', 'pending', ?, 'cp')", + (int(time.time()),)) + con.commit() + self.assertTrue(self.call("_rb_claim_paid", 7002)) + self.assertFalse(self.call("_rb_claim_paid", 7002)) + self.assertEqual(self.bot_sql("SELECT status FROM rank_purchases WHERE invoice_id=7002")[0][0], "paid") + + +class LegacySalesGateTests(LegacyFulfillmentCase): + def test_empty_offer_list_is_a_hard_switch_even_with_opt_in(self): + self.ns["CFG"]["commerce_offers"] = [] + self.ns["CFG"]["legacy_products"] = True + self.assertFalse(self.call("_legacy_sales_enabled")) + self.assertTrue(self.call("_legacy_gate_text", "donate")) + self.assertTrue(self.call("_legacy_gate_text", "rank")) + self.assertIn("[LEGACY-GATE]", "\n".join(m for _, m in self.log.lines)) + + def test_legacy_products_are_off_by_default(self): + self.ns["CFG"]["commerce_offers"] = [{"id": "x"}] + self.assertFalse(self.call("_legacy_sales_enabled")) + self.assertTrue(self.call("_legacy_gate_text", "donate")) + self.assertTrue(self.call("_legacy_gate_text", "unknown-kind")) + + def test_explicit_opt_in_with_offers_reopens_sales(self): + self.ns["CFG"]["commerce_offers"] = [{"id": "x"}] + self.ns["CFG"]["legacy_products"] = "yes" + self.assertTrue(self.call("_legacy_sales_enabled")) + self.assertIsNone(self.call("_legacy_gate_text", "rank")) + + def test_gate_blocks_new_invoices_but_never_strands_paid_money(self): + self.ns["CFG"]["commerce_offers"] = [] + self.assertTrue(self.call("_legacy_gate_text", "donate")) + self.paid_donation(9100, hours=24) + res = self.call("_don_fulfill", 9100) + self.assertEqual(res["status"], "pending_api") + self.assertEqual(self.bot_sql("SELECT COALESCE(delivered,0) FROM donations WHERE invoice_id=9100")[0][0], 1) + self.paid_rank(7100, to_lvl=2) + self.assertTrue(self.call("_rb_settle", 123, 2, 7100)) + self.assertEqual(self.bot_sql("SELECT COALESCE(badge_lock,0) FROM users WHERE tg_id=123")[0][0], 2) + + +class DonationCallbackContractTests(LegacyFulfillmentCase): + """The button handler must answer honestly for every delivery outcome.""" + + def test_answer_texts_are_short_and_match_their_state(self): + cases = { + "granted": "✅ Прем на 24ч! Безлимит: чат, картинки и API-ключ", + "pending_api": "API-безлимит включим автоматически", + "blocked": "аккаунт ограничен", + "already": "Уже активировано", + "error": "Не удалось подтвердить", + } + for status, needle in cases.items(): + text = self.call("_don_answer_text", 24, {"status": status, "until": 0, "api": False}) + self.assertLessEqual(len(text), 200, status) + self.assertIn(needle, text) + + def test_confirm_text_reports_the_real_deadline(self): + until = int(time.time()) + 3600 + text = self.call("_don_confirm_text", 24, {"status": "granted", "until": until, "api": True}) + self.assertIn(time.strftime("%d.%m %H:%M", time.localtime(until)), text) + self.assertIn("24ч", text) + self.assertIn("API-безлимит включён", text) + pending = self.call("_don_confirm_text", 24, {"status": "pending_api", "until": until, "api": False}) + self.assertNotIn("API-безлимит включён", pending) + self.assertIn("как только выпустится твой ключ", pending) + + def test_donation_payload_is_json_serialisable_for_the_ui(self): + self.paid_donation(9200) + res = self.call("_don_fulfill", 9200) + self.assertEqual(json.loads(json.dumps(res)), res) + + +class _PausingConnection: + """Real sqlite3 connection whose schema probe can be frozen mid-transaction.""" + + def __init__(self, inner, on_pragma): + self._inner = inner + self._on_pragma = on_pragma + + def __getattr__(self, name): + return getattr(self._inner, name) + + @property + def isolation_level(self): + return self._inner.isolation_level + + @isolation_level.setter + def isolation_level(self, value): + self._inner.isolation_level = value + + def execute(self, sql, params=()): + if str(sql).lstrip().upper().startswith("PRAGMA TABLE_INFO"): + self._on_pragma() + return self._inner.execute(sql, params) + + +class _PausingSqlite3: + def __init__(self, real, on_pragma): + self._real = real + self._on_pragma = on_pragma + + def __getattr__(self, name): + return getattr(self._real, name) + + def connect(self, *args, **kwargs): + return _PausingConnection(self._real.connect(*args, **kwargs), self._on_pragma) + + +class MigrationWindowTests(LegacyFulfillmentCase): + """The additive migration holds a write lock for its whole read-modify-write span. + + A stale ``PRAGMA table_info`` snapshot is the classic money bug here: the caller that + read the old schema still runs the fresh-install backfill seconds later, and every + ``status='paid' AND delivered=0`` row that landed in between is marked delivered + without ever being granted. Serialising the migration closes that window. + """ + + def _assert_migration_blocks_concurrent_writes(self, ensure_fn, table, ddl, invoice): + paused, release = threading.Event(), threading.Event() + errors = [] + + with closing(sqlite3.connect(self.bot_db)) as con: + con.execute(ddl) + # already-paid history: the backfill must mark it delivered exactly once + con.execute(f"INSERT INTO {table}(invoice_id, uid, status, created)" + " VALUES(?, 123, 'paid', 1)", (invoice - 1,)) + con.commit() + + def migrate(): + try: + self.call(ensure_fn) + except BaseException as exc: # reported on the main thread + errors.append(exc) + + real_sqlite3 = self.ns["sqlite3"] + self.ns["sqlite3"] = _PausingSqlite3( + real_sqlite3, lambda: (paused.set(), release.wait(20))) + self.addCleanup(self.ns.__setitem__, "sqlite3", real_sqlite3) + migrator = threading.Thread(target=migrate, daemon=True) + migrator.start() + buyers = [] + + def _cleanup(): + # registered before the temp-dir cleanup, so it always runs first: a failing + # assertion must not leave a thread holding the SQLite file open on Windows + release.set() + migrator.join(20) + for t in buyers: + t.join(20) + + self.addCleanup(_cleanup) + self.assertTrue(paused.wait(20), f"{ensure_fn} never probed the schema") + + # a brand-new purchase arrives while the migration is between probe and backfill + landed = threading.Event() + + def buy(): + try: + with closing(real_sqlite3.connect(self.bot_db, timeout=20)) as con: + con.execute(f"INSERT INTO {table}(invoice_id, uid, status, created)" + " VALUES(?, 123, 'paid', 2)", (invoice,)) + con.commit() + landed.set() + except BaseException as exc: + errors.append(exc) + + buyer = threading.Thread(target=buy, daemon=True) + buyers.append(buyer) + buyer.start() + buyer.join(4) + self.assertFalse(landed.is_set(), + f"{ensure_fn}: a paid invoice landed inside the migration window") + + release.set() + migrator.join(20) + self.assertFalse(migrator.is_alive(), f"{ensure_fn} did not finish") + self.assertEqual(errors, []) + buyer.join(20) + self.assertTrue(landed.is_set(), "the new purchase never landed at all") + self.assertEqual(errors, []) + + delivered = dict(self.bot_sql(f"SELECT invoice_id, COALESCE(delivered,0) FROM {table}")) + self.assertEqual(delivered[invoice - 1], 1, + "already-paid history must not be re-granted by the poller") + self.assertEqual(delivered[invoice], 0, + "the new purchase was marked delivered without being granted") + + def test_rank_migration_holds_the_write_lock_until_the_backfill_committed(self): + self._assert_migration_blocks_concurrent_writes( + "_rb_ensure_table", "rank_purchases", + "CREATE TABLE rank_purchases(invoice_id INTEGER PRIMARY KEY, uid INTEGER," + " from_lvl INTEGER, to_lvl INTEGER, amount_usd TEXT," + " status TEXT DEFAULT 'pending', created INTEGER, provider TEXT DEFAULT 'cp')", + 901) + + def test_donation_migration_holds_the_write_lock_until_the_backfill_committed(self): + self._assert_migration_blocks_concurrent_writes( + "_don_ensure_table", "donations", + "CREATE TABLE donations(invoice_id INTEGER PRIMARY KEY, uid INTEGER," + " hours INTEGER, status TEXT DEFAULT 'pending', created INTEGER)", + 902) + + def test_parallel_migrations_do_not_fail_on_a_duplicate_column(self): + """Button and poller migrate at once: exactly one ALTER set wins, nobody raises.""" + failures = [] + start = threading.Barrier(6) + + def migrate(): + start.wait(10) + try: + self.call("_rb_ensure_table") + except BaseException as exc: + failures.append(repr(exc)) + + threads = [threading.Thread(target=migrate, daemon=True) for _ in range(6)] + for t in threads: + t.start() + for t in threads: + t.join(30) + self.assertFalse(t.is_alive(), "a migration thread hung") + self.assertEqual(failures, []) + cols = [r[1] for r in self.bot_sql("PRAGMA table_info(rank_purchases)")] + for expected in ("provider", "inv_ext", "delivered", "delivered_at", + "bonus_state", "bonus_due"): + self.assertEqual(cols.count(expected), 1, f"column {expected} malformed: {cols}") + + +if __name__ == "__main__": + unittest.main(verbosity=2) diff --git a/tests/test_relay_error_responsiveness.py b/tests/test_relay_error_responsiveness.py new file mode 100644 index 00000000..4e818bfe --- /dev/null +++ b/tests/test_relay_error_responsiveness.py @@ -0,0 +1,197 @@ +"""A blocked token lookup must not stall unrelated relay work on the event loop.""" +import ast +import asyncio +import importlib.util +import itertools +import json +import logging +from pathlib import Path +import sys +import threading +from types import SimpleNamespace +import unittest +from unittest.mock import patch + +ROOT = Path(__file__).resolve().parents[1] +sys.path.insert(0, str(ROOT / 'gateway')) +SPEC = importlib.util.spec_from_file_location('responsive_error_relay', ROOT / 'gateway/transparent_api.py') +if SPEC is None or SPEC.loader is None: + raise RuntimeError('Cannot load the relay under test') +RELAY = importlib.util.module_from_spec(SPEC) +SPEC.loader.exec_module(RELAY) + +SKIN = ROOT / 'gateway' / 'grok-web-skin.py' +SKIN_ERROR_FUNCS = ('_error_payload', '_finish_error', 'error_response', 'async_error_response') +_LOGGERS = itertools.count() + + +def _skin_error_ns(): + """Extract the real skin error-response functions (hyphenated module, import side effects).""" + from aiohttp import web + from multidict import CIMultiDict + import secrets + from gateway_errors import public_error, public_json_dumps + + tree = ast.parse(SKIN.read_text(encoding='utf-8')) + found = {n.name: n for n in tree.body + if isinstance(n, (ast.FunctionDef, ast.AsyncFunctionDef)) and n.name in SKIN_ERROR_FUNCS} + missing = [name for name in SKIN_ERROR_FUNCS if name not in found] + if missing: + raise AssertionError('skin error-response region changed shape; missing %s' % missing) + log = logging.getLogger('skin-error-%d' % next(_LOGGERS)) + log.setLevel(logging.CRITICAL) + log.propagate = False + ns = {'asyncio': asyncio, 'secrets': secrets, 'web': web, 'CIMultiDict': CIMultiDict, + 'public_error': public_error, 'public_json_dumps': public_json_dumps, 'LOG': log} + for name in SKIN_ERROR_FUNCS: + exec(compile(ast.Module(body=[found[name]], type_ignores=[]), str(SKIN), 'exec'), ns) + return ns + + +class ErrorResponsivenessTests(unittest.IsolatedAsyncioTestCase): + async def exercise(self, *, embedded=False): + loop = asyncio.get_running_loop() + started = asyncio.Event() + release = threading.Event() + owner = threading.get_ident() + called = [] + pending = None + + def mapper(status, raw, path, **context): + called.append((status, raw, path, context, threading.get_ident())) + loop.call_soon_threadsafe(started.set) + if not release.wait(2): + raise AssertionError('lookup blocked the relay event loop') + return 401, {'error': {'code': 'invalid_api_key', 'retryable': False}} + + class Content: + async def iter_chunked(self, size): + yield body + + body = json.dumps({'error': {'status': 401, 'message': 'invalid token'}}).encode() + upstream = SimpleNamespace(status=200 if embedded else 401, + headers={'Content-Type': 'application/json'}, content=Content()) + request = SimpleNamespace(path='/v1/chat/completions', headers={}) + try: + with patch.object(RELAY, 'public_error', side_effect=mapper): + pending = asyncio.create_task(RELAY.relay_api( + request, upstream, json_to_sse=embedded, user_balance=7)) + await asyncio.wait_for(started.wait(), 2) + # This coroutine runs while the mapper is still blocked in its worker. + self.assertFalse(pending.done()) + self.assertNotEqual(called[0][-1], owner) + release.set() + response = await asyncio.wait_for(pending, 2) + finally: + release.set() + if pending is not None and not pending.done(): + await asyncio.wait_for(asyncio.gather(pending, return_exceptions=True), 2) + self.assertEqual(response.status, 401) + payload = json.loads(response.body) + self.assertEqual(payload['error']['code'], 'invalid_api_key') + self.assertFalse(payload['error']['retryable']) + self.assertEqual(len(called), 1) + self.assertEqual(called[0][0], 401) + self.assertEqual(called[0][1], body) + self.assertEqual(called[0][2], request.path) + self.assertEqual(called[0][3]['user_balance'], 7) + self.assertTrue(called[0][3]['from_upstream']) + return payload + + async def test_http_401_token_lookup_does_not_stall_other_coroutines(self): + payload = await self.exercise() + self.assertTrue(payload['error']['gateway_request_id']) + + async def test_embedded_401_uses_the_same_nonblocking_lookup(self): + await self.exercise(embedded=True) + + async def test_other_statuses_keep_the_no_worker_fast_path(self): + result = (503, {'error': {'code': 'upstream_unavailable'}}) + with patch.object(RELAY, 'public_error', return_value=result) as mapper: + with patch.object(RELAY.asyncio, 'to_thread', side_effect=AssertionError('unexpected worker')): + actual = await RELAY._upstream_error(503, b'{}', '/v1/chat/completions', user_balance=5) + self.assertIs(actual, result) + mapper.assert_called_once_with(503, b'{}', '/v1/chat/completions', user_balance=5) + + +class SkinErrorResponseTests(unittest.IsolatedAsyncioTestCase): + """The skin shares the relay's rule: only a 401 pays for a worker hop.""" + + async def test_non_401_stays_inline_and_matches_the_sync_wire_form(self): + ns = _skin_error_ns() + owner = threading.get_ident() + threads = [] + real_payload = ns['_error_payload'] + + def recording(*args, **kwargs): + out = real_payload(*args, **kwargs) + threads.append(threading.get_ident()) + return out + + ns['_error_payload'] = recording + with patch.object(asyncio, 'to_thread', side_effect=AssertionError('unexpected worker hop')): + response = await ns['async_error_response'](503, b'{}', '/v1/chat/completions') + self.assertEqual(threads, [owner]) + self.assertEqual(response.status, 503) + payload = json.loads(response.body) + self.assertTrue(payload['error']['gateway_request_id']) + self.assertEqual(payload['error']['request_id'], payload['error']['gateway_request_id']) + self.assertEqual(response.headers['Cache-Control'], 'no-store') + self.assertEqual(response.headers['X-Request-ID'], payload['error']['gateway_request_id']) + # identical classification to the synchronous form, with a fresh request id + sync = json.loads(ns['error_response'](503, b'{}', '/v1/chat/completions').body) + self.assertEqual(payload['error']['code'], sync['error']['code']) + self.assertNotEqual(payload['error']['gateway_request_id'], sync['error']['gateway_request_id']) + + async def test_401_token_lookup_leaves_the_skin_event_loop(self): + ns = _skin_error_ns() + loop = asyncio.get_running_loop() + owner = threading.get_ident() + started = asyncio.Event() + release = threading.Event() + threads = [] + contexts = [] + + def mapper(status, raw, path, **context): + threads.append(threading.get_ident()) + contexts.append(context) + loop.call_soon_threadsafe(started.set) + if not release.wait(2): + raise AssertionError('blocked lookup stalled the test') + return status, {'error': {'code': 'invalid_api_key', 'retryable': False}} + + ns['public_error'] = mapper + ticks = 0 + + async def ticker(): + nonlocal ticks + while ticks < 5: + ticks += 1 + await asyncio.sleep(0) + + pending = None + try: + pending = asyncio.create_task(ns['async_error_response']( + 401, b'{}', '/v1/chat/completions', api_key='sk-under-test')) + await asyncio.wait_for(started.wait(), 2) + # unrelated coroutines keep running while the DB lookup is blocked + self.assertFalse(pending.done()) + await asyncio.wait_for(ticker(), 2) + release.set() + response = await asyncio.wait_for(pending, 2) + finally: + release.set() + if pending is not None and not pending.done(): + await asyncio.wait_for(asyncio.gather(pending, return_exceptions=True), 2) + self.assertNotEqual(threads, [owner]) + self.assertEqual(ticks, 5) + self.assertEqual(contexts[0]['api_key'], 'sk-under-test') + self.assertEqual(response.status, 401) + payload = json.loads(response.body) + self.assertEqual(payload['error']['code'], 'invalid_api_key') + self.assertTrue(payload['error']['gateway_request_id']) + self.assertEqual(response.headers['Cache-Control'], 'no-store') + + +if __name__ == '__main__': + unittest.main() diff --git a/tests/test_skin_live_catalogue.py b/tests/test_skin_live_catalogue.py new file mode 100644 index 00000000..c9221c08 --- /dev/null +++ b/tests/test_skin_live_catalogue.py @@ -0,0 +1,456 @@ +"""Live-model catalogue of gateway/grok-web-skin.py: effective DB, cache, fail-closed. + +These tests execute the real functions of the skin (top-level `ast` nodes) against a +real SQLite file, so DB path resolution, read-only access, caching, retry and alias +deduplication are exercised as behaviour rather than asserted against source text. +""" + +import ast +import asyncio +import json +import logging +import sqlite3 +import threading +import time +from pathlib import Path +from types import SimpleNamespace +from unittest import IsolatedAsyncioTestCase + +from aiohttp import web + +SKIN = Path(__file__).resolve().parents[1] / "gateway" / "grok-web-skin.py" + +ASSIGNS = ("_LIVE_DB", "_LIVE_TTL", "_LIVE_RETRY", "_LIVE_MAX_STALE", "_live_lock", "_live_fetch_lock", + "_live_cache", "EXTRA_HIDE") +FUNCS = ("_live_now", "_live_read", "_live_cached", "_live_note_failure", "_live_snapshot", + "live_models_snapshot", "get_live_models", "_hidden", "filter_pricing_body") + +_counter = iter(range(10000)) + + +def _nodes(): + tree = ast.parse(SKIN.read_text(encoding="utf-8")) + assigns, funcs = {}, {} + for node in tree.body: + if isinstance(node, (ast.FunctionDef, ast.AsyncFunctionDef)): + funcs[node.name] = node + elif isinstance(node, ast.Assign): + for target in node.targets: + if isinstance(target, ast.Name) and target.id in ASSIGNS: + assigns[target.id] = node + return assigns, funcs + + +def _logger(sink): + log = logging.getLogger("skin-catalogue-%d" % next(_counter)) + log.setLevel(logging.WARNING) + log.propagate = False + handler = logging.Handler() + handler.emit = sink.append + log.addHandler(handler) + return log + + +def _ns(db_path, hide=()): + """Namespace with the real catalogue assignments and functions of the skin.""" + source = SKIN.read_text(encoding="utf-8") + assigns, funcs = _nodes() + missing = [n for n in ASSIGNS if n not in assigns] + [n for n in FUNCS if n not in funcs] + assert not missing, "catalogue region changed shape: missing %s" % missing + sink = [] + ns = { + "json": json, "logging": logging, "time": time, "sqlite3": sqlite3, + "Path": Path, "_threading": threading, + "GATE_NEWAPI_DB": str(db_path), + "LOG": _logger(sink), + "HIDE_MODEL_NAMES": frozenset(hide), + "HIDDEN_GROUP": "vip", + "sink": sink, + "source": source, + } + for name in ASSIGNS: + exec(compile(ast.Module(body=[assigns[name]], type_ignores=[]), str(SKIN), "exec"), ns) + for name in FUNCS: + exec(compile(ast.Module(body=[funcs[name]], type_ignores=[]), str(SKIN), "exec"), ns) + return ns + + +def _make_db(path, live=(), disabled=()): + con = sqlite3.connect(path) + try: + con.execute("CREATE TABLE channels (id INTEGER PRIMARY KEY, status INTEGER NOT NULL)") + con.execute("CREATE TABLE abilities (id INTEGER PRIMARY KEY, model TEXT, channel_id INTEGER," + " enabled INTEGER NOT NULL)") + con.execute("INSERT INTO channels (id, status) VALUES (1, 1), (2, 2)") + con.executemany("INSERT INTO abilities (model, channel_id, enabled) VALUES (?, 1, 1)", + [(m,) for m in live]) + con.executemany("INSERT INTO abilities (model, channel_id, enabled) VALUES (?, 2, 1)", + [(m,) for m in disabled]) + con.commit() + finally: + con.close() + return path + + +def _pricing(*names, **extra): + rows = [{"model_name": name} for name in names] + body = {"object": "list", "data": rows} + body.update(extra) + return json.dumps(body).encode("utf-8") + + +def _kept(raw, ns): + filtered = ns["filter_pricing_body"](raw) + return [row["model_name"] for row in json.loads(filtered)["data"]] + + +def _counting_read(ns): + """Replace the DB reader with a wrapper that records every real attempt.""" + calls = [] + real = ns["_live_read"] + + def wrapped(): + calls.append(1) + return real() + + ns["_live_read"] = wrapped + return calls + + +# --- database selection --------------------------------------------------------------- + +def test_catalogue_follows_the_supplied_gateway_db(tmp_path): + """A hardcoded legacy path would ignore the effective DB, so both reads must differ.""" + first = _make_db(tmp_path / "first.db", live=["grok-4.6"]) + second = _make_db(tmp_path / "second.db", live=["grok-4.7"]) + + ns_a, ns_b = _ns(first), _ns(second) + + assert ns_a["_LIVE_DB"] == str(first) + assert ns_b["_LIVE_DB"] == str(second) + assert ns_a["get_live_models"]() == frozenset({"grok-4.6"}) + assert ns_b["get_live_models"]() == frozenset({"grok-4.7"}) + + +def test_catalogue_reads_effective_db_not_legacy(tmp_path): + effective = _make_db(tmp_path / "effective.db", live=["grok-4.6"]) + legacy = _make_db(tmp_path / "legacy.db", live=["legacy-only"]) + ns = _ns(effective) + + models = ns["get_live_models"]() + + assert models == frozenset({"grok-4.6"}) + assert ns["_LIVE_DB"] == str(effective) + assert ns["_LIVE_DB"] != str(legacy) + # the legacy file exists and holds other rows; none of them may surface + assert legacy.exists() + assert "legacy-only" not in models + + +def test_effective_env_path_overrides_config_file(tmp_path, monkeypatch): + """Regression guard for the mismatch: env path wins over the config-file value.""" + import runtime_config + + configured = _make_db(tmp_path / "configured.db", live=["legacy-only"]) + forced = _make_db(tmp_path / "forced.db", live=["grok-4.6"]) + monkeypatch.setenv("IISHKO_GW_DB", str(forced)) + monkeypatch.delenv("GATE_NEWAPI_DB", raising=False) + + cfg = runtime_config.effective_bot_config({"newapi_db": str(configured)}) + assert cfg["newapi_db"] == str(forced) + assert _ns(cfg["newapi_db"])["get_live_models"]() == frozenset({"grok-4.6"}) + + +# --- read-only access ---------------------------------------------------------------- + +def test_missing_db_is_not_created_and_state_is_unknown(tmp_path): + missing = tmp_path / "absent.db" + ns = _ns(missing) + + models, known = ns["live_models_snapshot"]() + + assert models == frozenset() + assert known is False + assert not missing.exists(), "catalogue must never create the gateway database" + + +def test_broken_db_never_reports_models(tmp_path): + broken = tmp_path / "broken.db" + broken.write_bytes(b"not a sqlite database") + ns = _ns(broken) + + models, known = ns["live_models_snapshot"]() + + assert models == frozenset() + assert known is False + assert broken.read_bytes() == b"not a sqlite database" + + +def test_empty_live_set_is_known_and_authoritative(tmp_path): + db = _make_db(tmp_path / "empty.db", live=(), disabled=["qwen-max"]) + ns = _ns(db) + + models, known = ns["live_models_snapshot"]() + + assert models == frozenset(), "disabled channels must not count as live" + assert known is True + + +# --- alias dedup after live/hidden filtering ----------------------------------------- + +def test_live_alias_survives_regardless_of_row_order(tmp_path): + """A disabled alias must not win the dedup and drop the live model.""" + db = _make_db(tmp_path / "live.db", live=["qwen-max"]) + ns = _ns(db) + + forward = _kept(_pricing("qwen/qwen.max", "qwen-max"), ns) + backward = _kept(_pricing("qwen-max", "qwen/qwen.max"), ns) + + assert forward == ["qwen-max"] + assert backward == ["qwen-max"] + + +def test_hidden_row_does_not_shadow_visible_alias(tmp_path): + db = _make_db(tmp_path / "live.db", live=["grok-4.6"]) + ns = _ns(db, hide=("grok-4.6",)) + + kept = _kept(_pricing("grok-4.6", "grok-4.6", "x-ai/grok-4.6"), ns) + + assert "grok-4.6" not in kept + assert kept == [] + + +def test_known_empty_catalogue_drops_every_row(tmp_path): + db = _make_db(tmp_path / "empty.db", live=()) + ns = _ns(db) + + kept = _kept(_pricing("grok-4.6", "qwen-max"), ns) + + assert kept == [], "a reachable DB with no live models must not advertise anything" + + +def test_unknown_state_does_not_invent_availability(tmp_path): + ns = _ns(tmp_path / "absent.db") + + kept = _kept(_pricing("grok-4.6", "qwen-max"), ns) + + assert kept == [], "unknown live set must fail closed, not pass every row through" + + +# --- cache, retry and logging -------------------------------------------------------- + +def test_repeated_calls_on_empty_db_read_once(tmp_path): + db = _make_db(tmp_path / "empty.db", live=()) + ns = _ns(db) + clock = [100.0] + ns["_live_now"] = lambda: clock[0] + calls = _counting_read(ns) + + for _ in range(25): + assert ns["get_live_models"]() == frozenset() + + assert len(calls) == 1 + assert ns["sink"] == [] + + clock[0] += ns["_LIVE_TTL"] + 1 + ns["get_live_models"]() + assert len(calls) == 2, "TTL expiry must refresh exactly once" + + +def test_failure_is_cached_with_bounded_retry(tmp_path): + db = _make_db(tmp_path / "live.db", live=["grok-4.6"]) + ns = _ns(db) + clock = [0.0] + ns["_live_now"] = lambda: clock[0] + calls = _counting_read(ns) + + assert ns["get_live_models"]() == frozenset({"grok-4.6"}) + db.unlink() + clock[0] += ns["_LIVE_TTL"] + 1 + + for _ in range(10): + assert ns["get_live_models"]() == frozenset({"grok-4.6"}), "stale set is served on error" + + assert len(calls) == 2, "a failed refresh must not re-hit the DB on every request" + assert len(ns["sink"]) == 1, "one warning per retry window, not per request" + + clock[0] = ns["_LIVE_MAX_STALE"] + assert ns["live_models_snapshot"]() == (frozenset(), False) + assert len(calls) == 2, "expiry must not bypass the failure retry window" + + clock[0] += ns["_LIVE_RETRY"] + 1 + assert ns["live_models_snapshot"]() == (frozenset(), False) + assert len(calls) == 3, "unavailable DB cannot keep advertising the stale set" + assert len(ns["sink"]) == 2 + + _make_db(db, live=["new-model"]) + clock[0] += ns["_LIVE_RETRY"] + 1 + assert ns["get_live_models"]() == frozenset({"new-model"}) + assert len(calls) == 4, "retry window must allow recovery" + + +def test_broken_db_stays_cached_between_requests(tmp_path): + broken = tmp_path / "broken.db" + broken.write_bytes(b"garbage") + ns = _ns(broken) + clock = [0.0] + ns["_live_now"] = lambda: clock[0] + calls = _counting_read(ns) + + for _ in range(30): + models, known = ns["live_models_snapshot"]() + assert models == frozenset() and known is False + + assert len(calls) == 1 + assert len(ns["sink"]) == 1 + + +def test_concurrent_refresh_runs_once(tmp_path): + db = _make_db(tmp_path / "live.db", live=["grok-4.6"]) + ns = _ns(db) + clock = [0.0] + ns["_live_now"] = lambda: clock[0] + calls = _counting_read(ns) + real = ns["_live_read"] + + def slow_read(): + time.sleep(0.15) + return real() + + ns["_live_read"] = slow_read + results = [] + barrier = threading.Barrier(8) + + def worker(): + barrier.wait() + results.append(ns["get_live_models"]()) + + threads = [threading.Thread(target=worker) for _ in range(8)] + for thread in threads: + thread.start() + for thread in threads: + thread.join(10) + + assert not any(thread.is_alive() for thread in threads) + assert len(results) == 8 + assert set(results) == {frozenset({"grok-4.6"})} + assert len(calls) == 1, "single-flight: one DB read for the whole burst" + + +def test_snapshot_is_immutable(tmp_path): + db = _make_db(tmp_path / "live.db", live=["grok-4.6"]) + ns = _ns(db) + + models = ns["get_live_models"]() + + assert isinstance(models, frozenset) + assert not hasattr(models, "add") + assert models is ns["live_models_snapshot"]()[0], "no per-request copy churn" + + +# --- pricing semantics unchanged ----------------------------------------------------- + +def test_pricing_body_preserves_billing_rules(tmp_path): + db = _make_db(tmp_path / "live.db", live=["grok-4.6", "kimi/kimi-k3.1-pro"]) + ns = _ns(db) + raw = json.dumps({"data": [ + {"model_name": "grok-4.6", "model_ratio": 4, "model_price": 0.5, + "enable_groups": ["default", "vip"]}, + {"model_name": "kimi/kimi-k3.1-pro", "model_ratio": 3}, + ], "group_ratio": {"default": 1, "vip": 2}, "usable_group": {"default": "x", "vip": "y"}} + ).encode("utf-8") + + body = json.loads(ns["filter_pricing_body"](raw)) + + grok, kimi = body["data"] + assert grok["model_ratio"] == 2 and grok["model_price"] == 0.25 + assert grok["enable_groups"] == ["default"] + assert kimi["model_ratio"] == 3, "explicit kimi tariffs must not be halved" + assert body["group_ratio"] == {"default": 1} + assert body["usable_group"] == {"default": "x"} + + +def test_unfiltered_body_returns_original_bytes(tmp_path): + ns = _ns(_make_db(tmp_path / "live.db", live=["grok-4.6"])) + raw = json.dumps({"data": ["not-a-model-row"]}).encode("utf-8") + + assert ns["filter_pricing_body"](raw) is raw + + +def test_real_rows_without_tariff_changes_return_original_bytes(tmp_path): + """Byte identity must hold for a genuine dict payload, not only a non-dict row. + + The billing pass used to flag every dict row as modified, so each pricing body + was re-serialized even when no tariff or group actually changed. + """ + ns = _ns(_make_db(tmp_path / "live.db", live=["grok-4.6", "kimi/kimi-k3.1-pro"])) + raw = json.dumps({"data": [ + {"model_name": "grok-4.6", "enable_groups": ["default"]}, + {"model_name": "kimi/kimi-k3.1-pro", "model_ratio": 3}, + ]}).encode("utf-8") + + assert ns["filter_pricing_body"](raw) is raw + + +def test_halved_tariff_still_marks_the_body_changed(tmp_path): + ns = _ns(_make_db(tmp_path / "live.db", live=["grok-4.6"])) + raw = json.dumps({"data": [{"model_name": "grok-4.6", "model_ratio": 4}]}).encode("utf-8") + + body = ns["filter_pricing_body"](raw) + + assert body is not raw + assert json.loads(body)["data"][0]["model_ratio"] == 2 + + +def test_empty_pricing_rows_skip_the_database_entirely(tmp_path): + db = _make_db(tmp_path / "live.db", live=["grok-4.6"]) + ns = _ns(db) + calls = _counting_read(ns) + raw = json.dumps({"data": []}).encode("utf-8") + + assert ns["filter_pricing_body"](raw) is raw + assert calls == [] + + +class PricingResponsivenessTests(IsolatedAsyncioTestCase): + async def test_cold_catalogue_lookup_keeps_the_relay_event_loop_responsive(self): + loop = asyncio.get_running_loop() + entered = asyncio.Event() + release = threading.Event() + owner = threading.get_ident() + callers = [] + raw = b'{"data":[{"model_name":"demo"}]}' + filtered = b'{"data":[]}' + + def filter_body(body): + callers.append((body, threading.get_ident())) + loop.call_soon_threadsafe(entered.set) + if not release.wait(3): + raise AssertionError("catalogue lookup blocked the event loop") + return filtered + + _, funcs = _nodes() + ns = {"asyncio": asyncio, "web": web, "SKIP": (), "LOG": logging.getLogger(__name__), + "response_headers": dict, "filter_pricing_body": filter_body} + exec(compile(ast.Module(body=[funcs["relay"]], type_ignores=[]), str(SKIN), "exec"), ns) + + async def read(): + return raw + + request = SimpleNamespace(path="/api/pricing", method="GET") + upstream = SimpleNamespace(status=200, headers={"Content-Type": "application/json"}, read=read) + pending = asyncio.create_task(ns["relay"](request, upstream)) + try: + await asyncio.wait_for(entered.wait(), 3) + self.assertFalse(pending.done()) + self.assertEqual(callers[0][0], raw) + self.assertNotEqual(callers[0][1], owner) + release.set() + response = await asyncio.wait_for(pending, 3) + finally: + release.set() + if not pending.done(): + await asyncio.wait_for(asyncio.gather(pending, return_exceptions=True), 3) + self.assertEqual(response.status, 200) + self.assertEqual(response.body, filtered) + self.assertEqual(response.headers["Content-Type"], "application/json") \ No newline at end of file diff --git a/tests/test_skin_tg_login_hardening.py b/tests/test_skin_tg_login_hardening.py index 35f8840c..662e3422 100644 --- a/tests/test_skin_tg_login_hardening.py +++ b/tests/test_skin_tg_login_hardening.py @@ -37,3 +37,171 @@ def test_tg_login_refuses_cross_site_origin(): resp = asyncio.run(ns["tg_login"](req)) assert resp.status == 403 assert json.loads(resp.body)["error"] == "bad_origin" + + +def test_tg_login_never_holds_the_store_open_across_provisioning(): + """connect+DDL must not run on the loop, and no connection may span a network await.""" + import asyncio + import logging + import os + import secrets + import sqlite3 + import tempfile + from contextlib import closing + + with tempfile.TemporaryDirectory() as tmp: + db = os.path.join(tmp, "tg-provision.db") + token_file = os.path.join(tmp, "admin.token") + with open(token_file, "w", encoding="utf-8") as fh: + fh.write("bearer-token\n") + + state = {"opened": 0, "closed": 0, "held": [], "links": []} + + class _Conn: + def __init__(self, con): + self._con = con + + def __getattr__(self, name): + return getattr(self._con, name) + + def close(self): + state["closed"] += 1 + self._con.close() + + class _Req: + headers = {"Origin": "https://example.com"} + host = "example.com" + app = {"sess": object()} + + async def text(self): + return json.dumps({"id": 123, "auth_date": str(int(time.time())), "hash": "0" * 64}) + + async def _newapi_call(session, method, path, bearer, body=None): + # the store must already be closed when the request goes out + state["held"].append(state["opened"] - state["closed"]) + if path == "/api/user/login": + return 200, b'{"success": false}', None + return 200, b'{"success": true, "data": {"id": 7}}', None + + ns = _load("tg_login", "_tg_store_conn", "_tg_store_password", "_tg_store_password_put", + sqlite3=sqlite3, os=os, secrets=secrets, asyncio=asyncio, + logging=logging, LOG=logging.getLogger("tg_login_store"), + TG_PROVISION_DB=db, _TG_SCHEMA_READY=False, TG_ADMIN_TOKEN_FILE=token_file, + CONTROL_SESSION_KEY="sess", _tg_normalize=lambda data: data, + _tg_check_hash=lambda data: True, _newapi_call=_newapi_call, + _json_ok=lambda status, body: status == 200 and json.loads(body).get("success") is True, + _tg_link_upsert=lambda *args: state["links"].append(args)) + real_conn = ns["_tg_store_conn"] + + def tracked_conn(): + state["opened"] += 1 + return _Conn(real_conn()) + + ns["_tg_store_conn"] = tracked_conn + + resp = asyncio.run(ns["tg_login"](_Req())) + + assert resp.status == 502 + assert json.loads(resp.body)["error"] == "login_failed" + # a read for the missing password plus a write once provisioning succeeded + assert state["opened"] >= 2 + assert state["held"] and set(state["held"]) == {0}, state["held"] + assert state["opened"] == state["closed"] + assert state["links"] == [(123, "tg123")] + # `with sqlite3.connect(...)` commits but does not close: on Windows the open + # handle would break TemporaryDirectory cleanup. + with closing(sqlite3.connect(db)) as con: + row = con.execute("SELECT username, length(password) FROM tg_users" + " WHERE tg_id=123").fetchone() + assert row[0] == "tg123" and row[1] >= 24 + + +def test_tg_login_provision_recovery_keeps_the_store_closed_across_awaits(): + """create->search->get->put recovery runs four round trips; no connection may span one.""" + import logging + import os + import secrets + import sqlite3 + import tempfile + from contextlib import closing + + with tempfile.TemporaryDirectory() as tmp: + db = os.path.join(tmp, "tg-provision.db") + token_file = os.path.join(tmp, "admin.token") + with open(token_file, "w", encoding="utf-8") as fh: + fh.write("bearer-token\n") + + state = {"opened": 0, "closed": 0, "held": [], "links": [], "calls": [], "put_body": None} + + class _Conn: + def __init__(self, con): + self._con = con + + def __getattr__(self, name): + return getattr(self._con, name) + + def close(self): + state["closed"] += 1 + self._con.close() + + class _Req: + headers = {"Origin": "https://example.com"} + host = "example.com" + app = {"sess": object()} + + async def text(self): + return json.dumps({"id": 123, "auth_date": str(int(time.time())), "hash": "0" * 64}) + + async def _newapi_call(session, method, path, bearer, body=None): + # the store must already be closed when each of the four requests goes out + state["held"].append(state["opened"] - state["closed"]) + state["calls"].append((method, path)) + if method == "POST" and path == "/api/user/": + return 200, b'{"success": false, "message": "username already exists"}', None + if method == "GET" and path.startswith("/api/user/search"): + return 200, b'{"success": true, "data": {"items": [{"id": 7, "username": "tg123"}]}}', None + if method == "GET" and path == "/api/user/7": + return 200, b'{"success": true, "data": {"id": 7, "username": "tg123", "display_name": "tg"}}', None + if method == "PUT" and path == "/api/user/": + state["put_body"] = body + return 200, b'{"success": true}', None + if path == "/api/user/login": + return 200, b'{"success": false}', None + return 404, b'{"success": false}', None + + ns = _load("tg_login", "_tg_store_conn", "_tg_store_password", "_tg_store_password_put", + "_find_user_id", "_json_ok", + sqlite3=sqlite3, os=os, secrets=secrets, asyncio=asyncio, + logging=logging, LOG=logging.getLogger("tg_login_recovery"), + TG_PROVISION_DB=db, _TG_SCHEMA_READY=False, TG_ADMIN_TOKEN_FILE=token_file, + CONTROL_SESSION_KEY="sess", _tg_normalize=lambda data: data, + _tg_check_hash=lambda data: True, _newapi_call=_newapi_call, + _tg_link_upsert=lambda *args: state["links"].append(args)) + real_conn = ns["_tg_store_conn"] + + def tracked_conn(): + state["opened"] += 1 + return _Conn(real_conn()) + + ns["_tg_store_conn"] = tracked_conn + + resp = asyncio.run(ns["tg_login"](_Req())) + + assert resp.status == 502 + assert json.loads(resp.body)["error"] == "login_failed" + # the whole recovery chain ran, in order, and the full user object was resent + assert state["calls"] == [("POST", "/api/user/"), + ("GET", "/api/user/search?keyword=tg123"), + ("GET", "/api/user/7"), + ("PUT", "/api/user/"), + ("POST", "/api/user/login")] + assert state["put_body"]["id"] == 7 and state["put_body"]["username"] == "tg123" + assert len(state["put_body"]["password"]) >= 24 + # no connection was open while a request was in flight, and none leaked + assert state["held"] and set(state["held"]) == {0}, state["held"] + assert state["opened"] == state["closed"] + assert state["links"] == [(123, "tg123")] + # the recovered password is what the store will serve on the next login + with closing(sqlite3.connect(db)) as con: + stored = con.execute("SELECT password FROM tg_users WHERE tg_id=123").fetchone()[0] + assert stored == state["put_body"]["password"] diff --git a/tests/test_transparent_api.py b/tests/test_transparent_api.py index 6c6f9026..c42ccdc0 100644 --- a/tests/test_transparent_api.py +++ b/tests/test_transparent_api.py @@ -78,6 +78,8 @@ class PublicTransparentTests(unittest.IsolatedAsyncioTestCase): 'TIMEOUT': aiohttp.ClientTimeout(total=5), 'SKIP': ('/v1/',), '_GEN_PATHS': {'/v1/chat/completions', '/v1/messages', '/v1/responses'}, 'LOG': logging.getLogger('transparent_test'), + 'public_error': public_error, 'public_json_dumps': public_json_dumps, + 'secrets': secrets, 'gate_check': AsyncMock(return_value=(False, '')), '_rl_check_sync': Mock(return_value=None), '_DEV_ROLE_INCOMPAT_PREFIXES': ("qwen", "glm", "deepseek", "kimi"), '_key_balance_usd': Mock(return_value=None), @@ -93,8 +95,11 @@ class PublicTransparentTests(unittest.IsolatedAsyncioTestCase): names = {'CONTROL_SESSION_KEY', 'GENERATION_CONNECTIONS', 'CONTROL_CONNECTIONS'} constants = [node for node in tree.body if isinstance(node, ast.Assign) and any(isinstance(target, ast.Name) and target.id in names for target in node.targets)] exec(compile(ast.Module(body=constants, type_ignores=[]), str(SKIN), 'exec'), self.ns) + # real error wire form: proxy's failure paths must exercise the offloaded + # mapping, not a stub, otherwise a reverted sync call would still pass. extract(SKIN, {'proxy', 'response_headers', '_dev_role_incompat_model', - '_normalize_developer_roles', '_open_upstream_sessions', '_close_upstream_sessions'}, self.ns) + '_normalize_developer_roles', '_open_upstream_sessions', '_close_upstream_sessions', + 'async_error_response', '_error_payload', '_finish_error'}, self.ns) self.app.router.add_route('*', '/{path:.*}', self.ns['proxy']) self.client = TestClient(TestServer(self.app)) await self.client.start_server() @@ -246,7 +251,7 @@ class PublicErrorWireTests(unittest.IsolatedAsyncioTestCase): 'public_error': public_error, 'public_json_dumps': public_json_dumps, 'LOG': logging.getLogger('error_wire_test'), } - extract(SKIN, {'error_response'}, namespace) + extract(SKIN, {'error_response', '_error_payload', '_finish_error'}, namespace) async def handler(request): return namespace['error_response'](