Make legacy payment delivery retryable and keep gateway paths responsive
checks / pytest (push) Has been cancelled
checks / moderation (push) Has been cancelled
checks / node (push) Has been cancelled

This commit is contained in:
Vlad Gothbreach
2026-10-31 11:23:33 +03:00
parent 97d125122c
commit 3765b00b52
13 changed files with 2854 additions and 303 deletions
+65 -2
View File
@@ -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) '
+202 -73
View File
@@ -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,
+21 -10
View File
@@ -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)