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
+105
View File
@@ -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()