File size: 7,845 Bytes
5b14aa2 | 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 | """
API Key Pool Manager for DocStrange.
Manages a pool of Nanonets API keys with automatic rotation on rate limit (429).
"""
import os
import json
import time
import threading
from pathlib import Path
from typing import Optional, List, Dict, Any
import logging
logger = logging.getLogger(__name__)
class KeyStatus:
ACTIVE = "active"
RATE_LIMITED = "rate_limited"
EXPIRED = "expired"
class ApiKeyEntry:
"""Represents a single API key in the pool with its state."""
def __init__(self, key: str, source: str = "manual"):
self.key = key
self.source = source # "manual", "env", "config", "credentials"
self.status = KeyStatus.ACTIVE
self.rate_limited_at = None
self.reset_at = None # When the rate limit resets (epoch time)
self.requests_made = 0
self.last_used = None
def mark_rate_limited(self, reset_after_seconds: int = 3600):
"""Mark this key as rate-limited."""
self.status = KeyStatus.RATE_LIMITED
self.rate_limited_at = time.time()
self.reset_at = time.time() + reset_after_seconds
logger.warning(f"API key {self.key[:8]}... rate limited, resets at {self.reset_at}")
def is_available(self) -> bool:
"""Check if this key is available for use."""
if self.status == KeyStatus.ACTIVE:
return True
if self.status == KeyStatus.RATE_LIMITED and self.reset_at:
if time.time() >= self.reset_at:
self.status = KeyStatus.ACTIVE
self.rate_limited_at = None
self.reset_at = None
return True
return False
def record_use(self):
"""Record that this key was used."""
self.requests_made += 1
self.last_used = time.time()
class ApiKeyPool:
"""
Manages a pool of API keys with automatic rotation.
When a key hits rate limit (429), it's marked as unavailable and the next
key in the pool is tried. When all keys are exhausted, signals fallback.
"""
_instance = None
_lock = threading.Lock()
def __init__(self):
self._keys: List[ApiKeyEntry] = []
self._current_index = 0
self._lock_pool = threading.Lock()
self._config_path = Path.home() / ".docstrange" / "api_keys.json"
self._load_config()
@classmethod
def get_instance(cls) -> "ApiKeyPool":
"""Get singleton instance."""
if cls._instance is None:
with cls._lock:
if cls._instance is None:
cls._instance = cls()
return cls._instance
def _load_config(self):
"""Load API keys from config file."""
try:
if self._config_path.exists():
with open(self._config_path, 'r') as f:
config = json.load(f)
keys = config.get("api_keys", [])
for key_entry in keys:
if isinstance(key_entry, str):
self.add_key(key_entry, source="config")
elif isinstance(key_entry, dict) and "key" in key_entry:
self.add_key(key_entry["key"], source=key_entry.get("source", "config"))
logger.info(f"Loaded {len(self._keys)} API keys from config")
except Exception as e:
logger.warning(f"Failed to load API key config: {e}")
# Also check environment variable for a comma-separated list of keys
env_keys = os.environ.get('NANONETS_API_KEYS', '')
if env_keys:
for key in env_keys.split(','):
key = key.strip()
if key:
self.add_key(key, source="env")
def save_config(self):
"""Save API keys to config file."""
try:
config_dir = self._config_path.parent
config_dir.mkdir(exist_ok=True)
keys_data = []
for entry in self._keys:
keys_data.append({
"key": entry.key,
"source": entry.source
})
with open(self._config_path, 'w') as f:
json.dump({"api_keys": keys_data}, f, indent=2)
os.chmod(self._config_path, 0o600)
logger.info(f"Saved {len(keys_data)} API keys to config")
except Exception as e:
logger.error(f"Failed to save API key config: {e}")
def add_key(self, key: str, source: str = "manual") -> bool:
"""Add an API key to the pool."""
with self._lock_pool:
# Check for duplicates
for entry in self._keys:
if entry.key == key:
return False
self._keys.append(ApiKeyEntry(key, source))
logger.info(f"Added API key from {source} to pool (total: {len(self._keys)})")
return True
def remove_key(self, key: str) -> bool:
"""Remove an API key from the pool."""
with self._lock_pool:
for i, entry in enumerate(self._keys):
if entry.key == key:
self._keys.pop(i)
return True
return False
def get_next_key(self) -> Optional[str]:
"""
Get the next available API key.
Returns None if all keys are rate-limited.
"""
with self._lock_pool:
if not self._keys:
return None
# Try to find an available key starting from current index
total_keys = len(self._keys)
for i in range(total_keys):
idx = (self._current_index + i) % total_keys
if self._keys[idx].is_available():
self._current_index = idx
self._keys[idx].record_use()
return self._keys[idx].key
return None
def mark_key_rate_limited(self, key: str, reset_after_seconds: int = 3600):
"""Mark a specific key as rate-limited."""
with self._lock_pool:
for entry in self._keys:
if entry.key == key:
entry.mark_rate_limited(reset_after_seconds)
break
def has_available_keys(self) -> bool:
"""Check if any API keys are available."""
with self._lock_pool:
return any(k.is_available() for k in self._keys)
def get_pool_stats(self) -> Dict[str, Any]:
"""Get statistics about the key pool."""
with self._lock_pool:
stats = {
"total_keys": len(self._keys),
"available": 0,
"rate_limited": 0,
"total_requests": 0
}
for key in self._keys:
if key.is_available():
stats["available"] += 1
else:
stats["rate_limited"] += 1
stats["total_requests"] += key.requests_made
return stats
def get_all_keys(self) -> List[str]:
"""Get all API keys (masked for display)."""
with self._lock_pool:
return [f"{k.key[:8]}...{k.key[-4:]}" if len(k.key) > 12 else "***" for k in self._keys]
# Convenience functions
def get_pool() -> ApiKeyPool:
"""Get the API key pool singleton."""
return ApiKeyPool.get_instance()
def add_api_key(key: str):
"""Add an API key to the pool."""
pool = get_pool()
pool.add_key(key)
pool.save_config()
def remove_api_key(key: str):
"""Remove an API key from the pool."""
pool = get_pool()
pool.remove_key(key)
pool.save_config()
def list_api_keys() -> List[str]:
"""List all API keys (masked)."""
pool = get_pool()
return pool.get_all_keys()
def get_available_key() -> Optional[str]:
"""Get the next available API key."""
return get_pool().get_next_key()
|