Repository navigation
Expand file tree
/
Copy pathvalidator.py
More file actions
3247 lines (2896 loc) · 166 KB
/
Copy pathvalidator.py
File metadata and controls
3247 lines (2896 loc) · 166 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
"""
Модуль валидатора - Асинхронная проверка API Key + глубокая оценка стоимости
Основные функции:
1. AsyncIO + aiohttp высокопроизводительная проверка (100 одновременных запросов)
2. Глубокая оценка стоимости (определение GPT-4, проверка баланса, анализ RPM)
3. Детализация состояний (valid, invalid, quota_exceeded, connection_error)
4. Интеграция с UI-панелью
Публичный API: AsyncValidator, start_validators, ValidationResult, CircuitBreaker.
"""
import asyncio
import json
import ssl
import re
from typing import Tuple, Optional, Dict, Any, List
from datetime import datetime
from dataclasses import dataclass
import aiohttp
from aiohttp import ClientTimeout, TCPConnector
from loguru import logger
from config import (
config,
PROTECTED_DOMAINS,
SAFE_HTTP_STATUS_CODES,
CIRCUIT_BREAKER_HTTP_CODES,
CIRCUIT_BREAKER_FAILURE_THRESHOLD,
CIRCUIT_BREAKER_RECOVERY_TIMEOUT,
CIRCUIT_BREAKER_HALF_OPEN_REQUESTS
)
# Модуль config целиком — для доступа к EXTRA_PROVIDERS / REGEX_PATTERNS
# (config-экземпляр dataclass выше перекрывает имя, поэтому отдельный алиас).
from config import EXTRA_PROVIDERS as _EXTRA_PROVIDERS
from database import Database, LeakedKey, KeyStatus
# ============================================================================
# Константы и конфигурация
# ============================================================================
# Максимальное количество одновременных запросов
MAX_CONCURRENCY = 100
# Тайм-аут запроса (config.request_timeout может переопределить)
_req_timeout_total = getattr(config, 'request_timeout', 15) or 15
REQUEST_TIMEOUT = ClientTimeout(total=_req_timeout_total, connect=10)
# Список высокостоимостных моделей
HIGH_VALUE_MODELS = ['gpt-4', 'gpt-4-turbo', 'gpt-4o', 'gpt-4-32k', 'claude-3-opus']
# Пороговые значения RPM
RPM_ENTERPRISE_THRESHOLD = 3000 # >= 3000 - корпоративный уровень
RPM_FREE_TRIAL_THRESHOLD = 20 # <= 20 - бесплатный пробный период
# ============================================================================
# Прерыватель цепи (Circuit Breaker) - защита от ложных срабатываний
# ============================================================================
from enum import Enum
from urllib.parse import urlparse
import time
import threading
import random
from collections import OrderedDict
def _math_challenge() -> tuple:
"""Генерирует арифметическую задачу и ожидаемый ответ.
Случайные большие числа → провайдер не может захардкодить ответ, и мусорные
ответы (китайские «余额不足»/квота, заглушки) не совпадут с результатом.
Возвращает (prompt_text, answer_str).
"""
a = random.randint(10000, 99999)
b = random.randint(10000, 99999)
answer = str(a + b)
prompt = (f"Calculate {a}+{b}, and reply with the result only.")
return prompt, answer
def _content_has_answer(content: str, answer: str) -> bool:
"""Проверить, что ответ содержит правильную сумму (строго).
Отсекает мусор: китайские сообщения о квоте, заглушки, ошибки — они не
содержат правильное число. Учитывает форматирование (пробелы/запятые).
"""
if not content:
return False
# Очистка: убрать пробелы/неразрывные/разделители тысяч
cleaned = re.sub(r"[\s ,']", "", str(content))
# Матч с границами числа: ответ-сумма не должен быть подстрокой
# более длинного числа (180245 содержит 80245 → ложный CONFIRMED).
return bool(re.search(r'(?<!\d)' + re.escape(answer) + r'(?!\d)', cleaned))
# Модульный кеш нормализации base_url (чистая функция, потокобезопасен через GIL
# для dict-операций). Ограничен LRU-политикой (4096), чтобы на длинных прогонах
# по произвольным URL не расти без памяти.
_NORMALIZE_CACHE_MAX = 4096
_NORMALIZE_CACHE: "OrderedDict[str, str]" = OrderedDict()
def _cache_get(key: str):
val = _NORMALIZE_CACHE.get(key)
if val is not None:
_NORMALIZE_CACHE.move_to_end(key)
return val
def _cache_put(key: str, val: str) -> None:
_NORMALIZE_CACHE[key] = val
_NORMALIZE_CACHE.move_to_end(key)
while len(_NORMALIZE_CACHE) > _NORMALIZE_CACHE_MAX:
_NORMALIZE_CACHE.popitem(last=False)
class CircuitState(Enum):
"""Состояние прерывателя цепи"""
CLOSED = "closed" # Нормальный режим, запросы разрешены
OPEN = "open" # Прерывание, запросы отклоняются
HALF_OPEN = "half_open" # Полуоткрытый режим, разрешены тестовые запросы
class CircuitBreaker:
"""
Прерыватель цепи для доменов - с защитой от ложных срабатываний
Основная логика безопасности:
1. Белый список защищенных доменов - никогда не прерывать
2. Строгая классификация ошибок - только ошибки уровня соединения активируют прерыватель
"""
def __init__(self):
# Домен -> информация о состоянии
self._domain_states: Dict[str, dict] = {}
self._lock = threading.Lock() # Потокобезопасность
@staticmethod
def _extract_domain(url: str) -> str:
"""Извлечь домен из URL"""
try:
parsed = urlparse(url)
return parsed.netloc.lower().split(':')[0] # Удалить номер порта
except Exception:
return ""
@staticmethod
def _is_protected_domain(domain: str) -> bool:
"""
Проверить, защищен ли домен
Поддерживает суффиксное сопоставление, например my-resource.openai.azure.com совпадет с openai.azure.com
"""
if not domain:
return True # Пустой домен по умолчанию защищен
# Точное совпадение
if domain in PROTECTED_DOMAINS:
return True
# Суффиксное сопоставление (для динамических поддоменов Azure и т.д.)
for protected in PROTECTED_DOMAINS:
if domain.endswith('.' + protected) or domain.endswith(protected):
return True
return False
@staticmethod
def _is_network_error(error: Exception = None, http_status: int = None) -> bool:
"""
Определить, является ли ошибкой уровня сети (должна активировать прерыватель)
Ошибки уровня сети:
- Отказ в соединении / ошибка DNS (ClientConnectorError)
- Тайм-аут (TimeoutError)
- Ошибка шлюза 502/503/504
Ошибки уровня приложения (не активируют прерыватель):
- 401/403/429 и другие бизнес-ошибки
"""
# Проверить тип исключения
if error is not None:
if isinstance(error, (aiohttp.ClientConnectorError, asyncio.TimeoutError)):
return True
# ServerDisconnectedError и другие также считаются ошибками сети
if isinstance(error, aiohttp.ServerDisconnectedError):
return True
# Проверить HTTP-статус код
if http_status is not None:
if http_status in CIRCUIT_BREAKER_HTTP_CODES:
return True
# Ошибки уровня приложения не активируют прерыватель
if http_status in SAFE_HTTP_STATUS_CODES:
return False
return False
async def get_state(self, url: str) -> CircuitState:
"""Получить состояние прерывателя цепи для домена"""
domain = self._extract_domain(url)
# Защищенные домены всегда возвращают CLOSED
if self._is_protected_domain(domain):
return CircuitState.CLOSED
with self._lock:
if domain not in self._domain_states:
return CircuitState.CLOSED
state_info = self._domain_states[domain]
current_state = state_info.get('state', CircuitState.CLOSED)
# Проверить, следует ли перейти из OPEN в HALF_OPEN
if current_state == CircuitState.OPEN:
open_time = state_info.get('open_time', 0)
if time.time() - open_time >= CIRCUIT_BREAKER_RECOVERY_TIMEOUT:
state_info['state'] = CircuitState.HALF_OPEN
state_info['half_open_requests'] = 0
return CircuitState.HALF_OPEN
return current_state
async def is_allowed(self, url: str) -> bool:
"""Проверить, разрешен ли запрос"""
state = await self.get_state(url)
if state == CircuitState.CLOSED:
return True
elif state == CircuitState.OPEN:
return False
else: # HALF_OPEN
domain = self._extract_domain(url)
with self._lock:
state_info = self._domain_states.get(domain, {})
half_open_requests = state_info.get('half_open_requests', 0)
if half_open_requests < CIRCUIT_BREAKER_HALF_OPEN_REQUESTS:
state_info['half_open_requests'] = half_open_requests + 1
return True
return False
async def record_success(self, url: str):
"""Записать успешный запрос"""
domain = self._extract_domain(url)
if self._is_protected_domain(domain):
return
with self._lock:
if domain in self._domain_states:
# Сбросить состояние после успеха
self._domain_states[domain] = {
'state': CircuitState.CLOSED,
'failure_count': 0
}
async def record_failure(
self,
url: str,
error: Exception = None,
http_status: int = None
):
"""
Записать неудачный запрос - с защитой от ложных срабатываний
Args:
url: URL запроса
error: Объект исключения
http_status: HTTP статус код
"""
domain = self._extract_domain(url)
# ========== Проверка безопасности 1: Защищенные домены ==========
if self._is_protected_domain(domain):
return # Игнорировать, не записывать неудачу
# ========== Проверка безопасности 2: Ошибки уровня приложения ==========
if not self._is_network_error(error, http_status):
return # Бизнес-ошибки не активируют прерыватель
# ========== Запись ошибок уровня сети ==========
with self._lock:
if domain not in self._domain_states:
self._domain_states[domain] = {
'state': CircuitState.CLOSED,
'failure_count': 0
}
state_info = self._domain_states[domain]
state_info['failure_count'] = state_info.get('failure_count', 0) + 1
# Проверить, активировался ли прерыватель
if state_info['failure_count'] >= CIRCUIT_BREAKER_FAILURE_THRESHOLD:
state_info['state'] = CircuitState.OPEN
state_info['open_time'] = time.time()
async def get_stats(self) -> Dict[str, Any]:
"""Получить статистику прерывателя цепи"""
with self._lock:
stats = {}
for domain, info in self._domain_states.items():
stats[domain] = {
'state': info.get('state', CircuitState.CLOSED).value,
'failure_count': info.get('failure_count', 0)
}
return stats
def reset(self):
"""Сбросить все состояния доменов (для повторной валидации)"""
with self._lock:
self._domain_states.clear()
# Глобальный экземпляр прерывателя цепи
circuit_breaker = CircuitBreaker()
def mask_key(key: str) -> str:
"""Маскировать среднюю часть API Key"""
if len(key) <= 12:
return key[:4] + "..." + key[-4:]
return key[:8] + "..." + key[-4:]
@dataclass
class ValidationResult:
"""Класс данных результата валидации"""
status: KeyStatus
info: str
model_tier: str = ""
rpm: int = 0
balance_usd: float = 0.0
is_high_value: bool = False
models: list = None # список идентификаторов моделей из /models
def __post_init__(self):
if self.models is None:
self.models = []
class AsyncValidator:
"""Асинхронный валидатор API Key - с интеграцией прерывателя цепи"""
def __init__(self, db: Database, dashboard=None):
self.db = db
self.dashboard = dashboard
self.semaphore = asyncio.Semaphore(MAX_CONCURRENCY)
self._session: Optional[aiohttp.ClientSession] = None
self._circuit_breaker = circuit_breaker # Использовать глобальный прерыватель
# Заголовки последнего ответа провайдера (org/tier/rate-limit).
# Читаются в _probe_openai_billing; без инициализации давал
# AttributeError, который _save_key_metadata молча глотал —
# метаданные (tpd/concurrency/balance/org_plan) не сохранялись.
self._last_headers: Dict[str, str] = {}
async def _get_session(self) -> aiohttp.ClientSession:
"""Получить или создать aiohttp сессию"""
if self._session is None or self._session.closed:
# Настроить прокси
# ThreadedResolver — использует системный DNS резолвер в потоке,
# исправляет ClientConnectorDNSError на Windows
connector = TCPConnector(
limit=MAX_CONCURRENCY,
limit_per_host=50,
ssl=ssl.create_default_context(),
force_close=False,
use_dns_cache=True,
ttl_dns_cache=600,
keepalive_timeout=60,
enable_cleanup_closed=True,
resolver=aiohttp.resolver.ThreadedResolver(),
)
self._session = aiohttp.ClientSession(
connector=connector,
timeout=REQUEST_TIMEOUT,
trust_env=True # Поддержка прокси из переменных окружения
)
return self._session
async def close(self):
"""Закрыть сессию"""
if self._session and not self._session.closed:
await self._session.close()
def _get_proxy(self) -> Optional[str]:
"""Получить URL прокси"""
return config.proxy_url if config.proxy_url else None
def _log(self, message: str, level: str = "INFO"):
"""Вывести лог"""
if self.dashboard:
self.dashboard.add_log(message, level)
def _normalize_base_url(self, base_url: str) -> str:
"""
Привести base_url к API-корню, отбросив хвостовые сегменты эндпоинтов.
Функция чистая от входной строки — результат кешируется в модульный
dict _NORMALIZE_CACHE: на горячем gemini-дрейне один и тот же base_url
(generativelanguage.googleapis.com/v1beta) нормализуется тысячи раз.
См. _normalize_base_url_uncached для фактических правил/примеров.
"""
if not base_url:
return base_url
cached = _cache_get(base_url)
if cached is not None:
return cached
result = self._normalize_base_url_uncached(base_url)
_cache_put(base_url, result)
return result
def _normalize_base_url_uncached(self, base_url: str) -> str:
"""
Привести base_url к API-корню, отбросив хвостовые сегменты эндпоинтов.
Сканер извлекает URL «по соседству с ключом», поэтому base_url часто
содержит полный путь вызова, например:
https://api.siliconflow.cn/v1/chat/completions
Если такой URL напрямую склеить с /models, получится мусорный адрес
…/v1/chat/completions/models, и валидация заведомо провалится.
Правила:
1. Оставить scheme://host[:port].
2. Из пути удалить известные суффиксы эндпоинтов
(chat/completions, completions, embeddings, models, messages…).
3. Сохранить префикс версии (v1, v1beta, openai/v1 и т.п.),
отбросив всё после него.
Примеры:
https://api.siliconflow.cn/v1/chat/completions
-> https://api.siliconflow.cn/v1
https://relay.com/openai/v1/models -> https://relay.com/openai/v1
https://api.openai.com -> https://api.openai.com
"""
if not base_url:
return base_url
from urllib.parse import urlparse
try:
parsed = urlparse(base_url.strip())
except ValueError:
return base_url
if not parsed.scheme or not parsed.netloc:
return base_url
host = f"{parsed.scheme}://{parsed.netloc}"
segments = [s for s in parsed.path.split('/') if s]
# Известные имена сегментов эндпоинтов (OpenAI-совместимые + Gemini)
ENDPOINT_SEGMENTS = {
'chat', 'completions', 'embeddings', 'models', 'messages',
'audio', 'transcriptions', 'translations', 'images',
'generations', 'files', 'fine_tunes', 'fine-tunes',
'moderations', 'responses', 'edits', 'invitations',
}
# 1. Удалить хвостовые сегменты-эндпоинты
while segments and segments[-1] in ENDPOINT_SEGMENTS:
segments.pop()
# 2. Найти сегмент-версию (v1, v1beta, v2, v1openai …) и обрезать после него
import re as _re
cut = None
for idx, seg in enumerate(segments):
if _re.fullmatch(r'v\d\w*', seg, _re.IGNORECASE):
cut = idx + 1
break
if cut is not None:
segments = segments[:cut]
if segments:
return host + '/' + '/'.join(segments)
return host
def _is_likely_valid_relay(self, url: str) -> bool:
"""Проверить, что URL может быть API-эндпоинтом + защита от SSRF.
Проверки:
1. Исключить documentation/settings/guide pages
2. Заблокировать частные IP (RFC1918, loopback, link-local)
3. Заблокировать опасные суффиксы (.local/.internal/.corp)
4. Черный список documentation доменов
"""
if not url or not url.startswith('http'):
return False
url_lower = url.lower()
# Документация/settings
doc_indicators = ['docs', 'settings', 'guide', 'tutorial', 'help',
'/ref/', '/docs/', '/guide']
if any(ind in url_lower for ind in doc_indicators):
return False
# Черный список documentation доменов
invalid_domains = [
'docs.djangoproject.com', 'docs.python.org',
'developer.mozilla.org', 'stackoverflow.com',
'themoviedb.org', 'prisma.io', 'pris.ly',
'every.to', 'makersuite.google.com',
]
for inv in invalid_domains:
if inv in url_lower:
return False
# SSRF: блокировка частных IP и локальных суффиксов
try:
parsed = urlparse(url)
host = parsed.hostname or ''
import ipaddress
try:
ip = ipaddress.ip_address(host)
if (ip.is_private or ip.is_loopback
or ip.is_link_local or ip.is_reserved):
return False
except ValueError:
pass
for suffix in ('.local', '.internal', '.corp', '.lan', '.home'):
if host.endswith(suffix):
return False
path = parsed.path.strip('/')
if path and '/' in path and len(path) > 40:
return False
except Exception:
pass
return True
def _try_url_variants(self, base_url: str, path: str) -> list:
"""
Сгенерировать варианты URL для эндпоинта.
Сначала base_url нормализуется к API-корню (см. _normalize_base_url),
затем перебираются варианты с/без префикса /v1, чтобы попасть в
правильный эндпоинт независимо от того, как именно был записан URL
в исходном коде.
"""
base = self._normalize_base_url(base_url).rstrip('/')
path = path.lstrip('/')
variants = [f"{base}/{path}"]
# Если в нормализованном URL нет /v1 — попробовать с /v1
if '/v1' not in base:
variants.append(f"{base}/v1/{path}")
# Если /v1 есть — попробовать и без него (некоторые реле держат модели
# прямо в корне), но аккуратно: вырезаем только суффикс /v1 из пути
if base.endswith('/v1'):
variants.append(f"{base[:-3].rstrip('/')}/{path}")
# Дедупликация с сохранением порядка
seen = set()
uniq = []
for v in variants:
if v not in seen:
seen.add(v)
uniq.append(v)
return uniq
# ========================================================================
# Методы интеграции прерывателя цепи
# ========================================================================
async def _check_circuit_breaker(self, base_url: str) -> Optional[ValidationResult]:
"""
Проверить состояние прерывателя цепи
Returns:
Если прерыватель активен, возвращает результат CONNECTION_ERROR; иначе None
"""
if not config.circuit_breaker_enabled:
return None
if not await self._circuit_breaker.is_allowed(base_url):
self._log(f"Прерывание: {base_url[:30]}...", "WARN")
return ValidationResult(KeyStatus.CONNECTION_ERROR, "Домен прерван")
return None
async def _record_circuit_result(
self,
url: str,
success: bool = False,
error: Exception = None,
http_status: int = None
):
"""Записать результат запроса в прерыватель"""
if not config.circuit_breaker_enabled:
return
if success:
await self._circuit_breaker.record_success(url)
else:
await self._circuit_breaker.record_failure(url, error, http_status)
# ========================================================================
# Универсальный HTTP-запрос с повторными попытками (retry)
# ========================================================================
# Ранее один тайм-аут/ошибка соединения навсегда помечали ключ как
# connection_error. Теперь транзитные ошибки (тайм-аут, обрыв соединения,
# 502/503/504) повторяются с экспоненциальным backoff, и лишь после
# исчерпания попыток ключ считается connection_error.
def _retry_cfg(self) -> Tuple[int, float]:
# Config-driven: validator_max_retries (default 3), validator_retry_backoff (default 1.5)
# Hardcoded fallback (2, 0.8) если config не задан
retries = getattr(config, 'validator_max_retries', None) or 2
backoff = getattr(config, 'validator_retry_backoff', None) or 0.8
return (retries, backoff)
@staticmethod
def _is_transient_error(exc: Optional[Exception],
status: Optional[int]) -> bool:
"""Транзитная ошибка = стоит повторить (сеть/тайм-аут/шлюз)."""
if status is not None:
if status in (502, 503, 504):
return True
return False
if exc is None:
return False
# Тайм-ауты и обрывы соединения — транзитные
if isinstance(exc, (asyncio.TimeoutError,)):
return True
name = type(exc).__name__
transient = ("Timeout", "ConnectorError", "ClientConnectorError",
"ClientOSError", "ClientPayloadError", "ServerDisconnectedError",
"ConnectionError", "OSError")
return any(t in name for t in transient)
@staticmethod
def _classify_status(status: int) -> KeyStatus:
"""Сопоставить HTTP-код со статусом ключа.
200 → VALID, 401/403 → INVALID (отказ auth — ключ отвергнут),
429/402 → QUOTA/оплата, 5xx/3xx → CONNECTION_ERROR (транзитная),
405/410 → UNVERIFIED (endpoint ответил, но метод/ресурс недоступен),
400/404/422 → INVALID (бизнес-ошибка по умолчанию; валидаторы
могут переопределить на UNVERIFIED, если контекст не подтверждает
невалидность ключа), прочие → UNVERIFIED (безопаснее, чем INVALID).
"""
if 200 <= status < 300:
return KeyStatus.VALID
if status in (401, 403):
return KeyStatus.INVALID
if status in (429, 402):
return KeyStatus.QUOTA_EXCEEDED
if status >= 500 or 300 <= status < 400:
return KeyStatus.CONNECTION_ERROR
if status in (405, 410):
return KeyStatus.UNVERIFIED
if status in (400, 404, 422):
return KeyStatus.INVALID
return KeyStatus.UNVERIFIED
async def _fetch_with_retry(
self,
method: str,
url: str,
headers: Optional[Dict[str, str]] = None,
json_body: Optional[Dict[str, Any]] = None,
parse_json: bool = True,
) -> Tuple[Optional[int], Any, int, Dict]:
"""
Выполнить HTTP-запрос с повторными попытками.
Returns:
(status_code, json_data, rpm, headers) — при успехе.
(None, None, 0, {}) — если все попытки провалились транзитной ошибкой.
"""
retries, backoff = self._retry_cfg()
proxy = self._get_proxy()
session = await self._get_session()
last_exc: Optional[Exception] = None
for attempt in range(retries):
try:
if method.upper() == "GET":
ctx = session.get(url, headers=headers, proxy=proxy)
else:
ctx = session.post(url, headers=headers,
json=json_body, proxy=proxy)
async with ctx as resp:
status = resp.status
rpm = 0
try:
rpm = int(resp.headers.get('x-ratelimit-limit-requests', 0))
except (ValueError, TypeError):
rpm = 0
# Транзитный статус шлюза → повторить
if status in (502, 503, 504) and attempt < retries - 1:
await self._record_circuit_result(url, http_status=status)
delay = backoff * (2 ** attempt) + random.uniform(0, backoff * 0.5)
await asyncio.sleep(delay)
continue
data = None
if parse_json:
try:
data = await resp.json(content_type=None)
except Exception:
data = None
# Записать результат в прерыватель цепи
if status < 500:
await self._record_circuit_result(
url, success=(200 <= status < 400), http_status=status)
else:
await self._record_circuit_result(url, http_status=status)
return status, data, rpm, dict(resp.headers)
except asyncio.TimeoutError as e:
last_exc = e
await self._record_circuit_result(url, error=e)
if attempt < retries - 1:
delay = backoff * (2 ** attempt) + random.uniform(0, backoff * 0.5)
await asyncio.sleep(delay)
continue
except aiohttp.ClientConnectorError as e:
last_exc = e
await self._record_circuit_result(url, error=e)
if attempt < retries - 1:
delay = backoff * (2 ** attempt) + random.uniform(0, backoff * 0.5)
await asyncio.sleep(delay)
continue
except aiohttp.ClientError as e:
last_exc = e
# Прочие клиентские ошибки — транзитные, повторить
if self._is_transient_error(e, None) and attempt < retries - 1:
await self._record_circuit_result(url, error=e)
delay = backoff * (2 ** attempt) + random.uniform(0, backoff * 0.5)
await asyncio.sleep(delay)
continue
logger.debug(f"HTTP ошибка ({type(e).__name__}): {e}")
break
except Exception as e:
last_exc = e
logger.debug(f"Неожиданная ошибка запроса: {type(e).__name__}: {e}")
break
# Все попытки исчерпаны транзитной ошибкой
if last_exc:
await self._record_circuit_result(url, error=last_exc)
return None, None, 0, {}
# ---------- rate-limit / billing / org metadata ----------
def _extract_rate_limits(self, headers: Dict[str, str]) -> Dict[str, Any]:
"""Извлечь rate-limit данные из HTTP headers."""
result: Dict[str, Any] = {
"rpm": 0, "tpd": 0, "concurrency_limit": 0,
"rate_tier": "", "rate_headers": "",
}
# Нормализуем ключи headers в lowercase
hl = {k.lower(): v for k, v in headers.items()} if headers else {}
# RPM (requests per minute) — ищем по множеству вариантов
rpm_keys = [
"x-ratelimit-limit-requests", "x-ratelimit-limit",
"x-ratelimit-limit-minute", "ratelimit-limit-requests",
"ratelimit-limit", "x-ratelimit-requests-limit",
"x-rl-limit-requests", "x-quota-limit",
]
for key in rpm_keys:
if key in hl:
try:
result["rpm"] = int(hl[key])
except (ValueError, TypeError):
pass
break
# TPD (tokens per day) / TPM (tokens per minute)
tpd_keys = [
"x-ratelimit-limit-tokens", "x-ratelimit-limit-tokens-day",
"x-ratelimit-limit-token", "ratelimit-limit-tokens",
"ratelimit-limit-token", "x-ratelimit-tokens-limit",
"x-rl-limit-tokens", "x-quota-tokens",
]
for key in tpd_keys:
if key in hl:
try:
result["tpd"] = int(hl[key])
except (ValueError, TypeError):
pass
break
# Concurrency / parallel requests
conc_keys = [
"x-ratelimit-limit-concurrent", "x-concurrent-limit",
"x-ratelimit-limit-parallel", "x-parallel-limit",
"x-ratelimit-concurrent", "x-concurrency-limit",
]
for key in conc_keys:
if key in hl:
try:
result["concurrency_limit"] = int(hl[key])
except (ValueError, TypeError):
pass
break
# Rate tier
tier_keys = [
"x-openai-tier", "x-rate-tier", "x-ratelimit-tier",
"x-openai-ratelist-tier", "x-tier", "x-plan-tier",
]
for key in tier_keys:
if key in hl:
result["rate_tier"] = str(hl[key])
break
# Сохранить все rate-limit headers как JSON
rate_headers = {k: v for k, v in hl.items()
if "ratelimit" in k or "rate-limit" in k
or "tier" in k or "limit" in k or "quota" in k
or "remaining" in k or "reset" in k}
if rate_headers:
result["rate_headers"] = json.dumps(rate_headers, ensure_ascii=False)
# Если нет limit, но есть remaining — используем remaining как оценку
if not result["rpm"]:
for key in ("x-ratelimit-remaining-requests", "ratelimit-remaining",
"x-ratelimit-remaining"):
if key in hl:
try:
result["rpm"] = int(hl[key])
except (ValueError, TypeError):
pass
break
return result
async def _probe_openai_billing(self, api_key: str, base_url: str) -> Dict[str, Any]:
"""Получить баланс и org plan для OpenAI ключа.
Returns:
{"balance_usd": float, "org_plan": str}
"""
result: Dict[str, Any] = {"balance_usd": -1, "org_plan": ""}
headers = {"Authorization": f"Bearer {api_key}"}
session = await self._get_session()
proxy = self._get_proxy()
# 0) Проверить org info из headers последнего ответа (chat completion)
if self._last_headers:
hl = {k.lower(): v for k, v in self._last_headers.items()}
for key in ("x-openai-organization", "openai-organization",
"x-openai-org", "x-org-id"):
if key in hl:
result["org_plan"] = f"org:{hl[key]}"
break
for key in ("x-openai-tier", "x-rate-tier", "x-openai-ratelist-tier"):
if key in hl:
if not result.get("rate_tier"):
result["rate_tier"] = str(hl[key])
# 1) Billing balance — пробуем несколько endpoint'ов
billing_urls = [
"https://api.openai.com/v1/organization/costs?start_time=0&limit=1",
"https://api.openai.com/dashboard/billing/credit_grants",
"https://api.openai.com/v1/organization/usage",
"https://api.openai.com/dashboard/billing/subscription",
]
for burl in billing_urls:
try:
async with session.get(burl, headers=headers, proxy=proxy) as resp:
if resp.status == 200:
data = await resp.json(content_type=None)
if isinstance(data, dict):
for field in ("total_granted_amount", "total_available",
"balance", "hard_limit_usd",
"soft_limit_usd", "account_balance"):
val = data.get(field)
if val is not None:
try:
result["balance_usd"] = float(val)
break
except (ValueError, TypeError):
pass
total = data.get("total_granted_amount")
used = data.get("total_used_amount")
if total is not None and used is not None:
try:
result["balance_usd"] = float(total) - float(used)
except (ValueError, TypeError):
pass
break
except Exception:
continue
# 2) Org plan из /organization endpoint
if not result["org_plan"]:
try:
org_url = "https://api.openai.com/v1/organization"
async with session.get(org_url, headers=headers, proxy=proxy) as resp:
if resp.status == 200:
data = await resp.json(content_type=None)
if isinstance(data, dict):
_plan = data.get("plan", {})
plan = _plan.get("title") if isinstance(_plan, dict) else str(_plan)
if not plan:
plan = data.get("plan")
if plan:
result["org_plan"] = str(plan)
except Exception:
pass
return result
async def _save_key_metadata(self, api_key: str, platform: str,
base_url: str,
headers: Optional[Dict] = None) -> None:
"""Собрать и сохранить расширенные метаданные ключа."""
try:
rate = self._extract_rate_limits(headers or {})
billing = {"balance_usd": -1, "org_plan": ""}
if platform in ("openai", "relay"):
billing = await self._probe_openai_billing(api_key, base_url)
self.db.update_key_meta(
api_key,
tpd=rate.get("tpd", 0),
concurrency_limit=rate.get("concurrency_limit", 0),
balance_usd=billing.get("balance_usd", -1),
org_plan=billing.get("org_plan", ""),
rate_tier=rate.get("rate_tier", ""),
rate_headers=rate.get("rate_headers", ""),
)
except Exception as e:
logger.debug(f"Ошибка сохранения метаданных ключа: {e}")
async def _validate_models_endpoint(
self,
platform_name: str,
api_key: str,
base_url: str,
default_url: str,
) -> ValidationResult:
"""
Универсальная проверка OpenAI-совместимых провайдеров через GET /models.
Используется для groq/deepseek/cohere/mistral/together/perplexity/
fireworks/xai/openrouter/cerebras и т.п. — все они принимают
Authorization: Bearer <key> и отдают список моделей на /models.
"""
if not base_url:
base_url = default_url
if not self._is_likely_valid_relay(base_url):
return ValidationResult(KeyStatus.INVALID, "base_url недействителен")
circuit_result = await self._check_circuit_breaker(base_url)
if circuit_result:
return circuit_result
headers = {"Authorization": f"Bearer {api_key}"}
# Пробуем /models и варианты с/без /v1
urls = self._try_url_variants(base_url, "models")
last_status: Optional[int] = None
# Отслеживаем, был ли явный отказ аутентификации (401/403)
auth_rejected = False
for url in urls:
status, data, _, _ = await self._fetch_with_retry("GET", url, headers=headers)
if status is None:
# Транзитная ошибка на этом URL — пробуем следующий вариант
continue
last_status = status
if status == 200:
models_count = 0
models_list: List[str] = []
if isinstance(data, dict):
models = data.get("data") or data.get("models") or []
if isinstance(models, list):
models_count = len(models)
for m in models:
mid = m.get("id") if isinstance(m, dict) else str(m)
if mid:
models_list.append(mid)
return ValidationResult(
KeyStatus.VALID,
f"{platform_name} действителен ({models_count} моделей)",
models=models_list)
if status == 429:
return ValidationResult(KeyStatus.QUOTA_EXCEEDED, "Квота исчерпана")
if status in (401, 403):
# Явный отказ аутентификации — ключ невалиден
auth_rejected = True
break
# 404/400/422 — endpoint может отсутствовать на этом relay;
# пробуем следующий вариант URL, не делаем вывод о невалидности ключа
# Если был явный отказ auth — ключ невалиден
if auth_rejected:
return ValidationResult(KeyStatus.INVALID, "Недействителен")
# Fallback: POST /chat/completions (некоторые relay не отдают /models)
chat_body = {"model": "gpt-3.5-turbo",
"messages": [{"role": "user", "content": "Hi"}],
"max_tokens": 1}
for url in self._try_url_variants(base_url, "chat/completions"):
status, data, _, _ = await self._fetch_with_retry(
"POST", url, headers=headers, json_body=chat_body)
if status is None:
continue
last_status = status
if status == 200:
return ValidationResult(KeyStatus.VALID,
f"{platform_name} действителен (chat)")