"""API Key Manager — Stealth Rotator for Multi-Key Quota Multiplication.""" import asyncio import threading import random import time from typing import List, Optional from loguru import logger class APIKeyManager: def __init__(self, keys: List[str]): self.keys = [{"key": k, "status": "ready", "last_used": 0.0, "fail_count": 0} for k in keys] self.current_index = 0 self._lock = None self._thread_lock = threading.Lock() @property def lock(self): if self._lock is None: self._lock = asyncio.Lock() return self._lock async def get_key(self) -> Optional[str]: """Returns the next available API key using Round-Robin logic with health checks.""" if not self.keys: return None # Jitter: Add a tiny random delay to avoid robotic simultaneous requests await asyncio.sleep(random.uniform(0.1, 0.5)) async with self.lock: with self._thread_lock: for _ in range(len(self.keys)): key_data = self.keys[self.current_index] self.current_index = (self.current_index + 1) % len(self.keys) now = time.time() if key_data["status"] == "ready": key_data["last_used"] = now return key_data["key"] # Reset cooled down keys with exponential backoff (base 1 minute) if key_data["status"] == "cooldown": fail_count = max(1, key_data["fail_count"]) cooldown_duration = 60.0 * (2.0 ** (fail_count - 1)) # Limit maximum cooldown duration to 1 hour (3600 seconds) cooldown_duration = min(cooldown_duration, 3600.0) if now - key_data["last_used"] > cooldown_duration: key_data["status"] = "ready" key_data["last_used"] = now return key_data["key"] return None def mark_failed(self, key: str, reason: str = "429"): """Marks a key as rate-limited or failed.""" with self._thread_lock: for k in self.keys: if k["key"] == key: k["status"] = "cooldown" k["last_used"] = time.time() k["fail_count"] += 1 logger.warning(f"[KeyManager] Key {key[:8]}... put on cooldown (fail_count={k['fail_count']}). Reason: {reason}") break def mark_success(self, key: str): """Marks a key as successful, resetting fail count and setting status to ready.""" with self._thread_lock: for k in self.keys: if k["key"] == key: k["status"] = "ready" k["fail_count"] = 0 logger.info(f"[KeyManager] Key {key[:8]}... marked as successful. Reset fail_count.") break def get_random_user_agent(self) -> str: """Variation to make requests from the same server look organic.""" agents = [ "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/124.0.0.0 Safari/537.36", "Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_7) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/123.0.0.0 Safari/537.36", "Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/124.0.0.0 Safari/537.36", "Brigawan-AI-Core/2.5 (Enterprise-Agentic-System)", "Google-Cloud-Function/Python-3.12" ] return random.choice(agents)