leindex 1.0.0__py3-none-any.whl
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- leindex/__init__.py +6 -0
- leindex/__main__.py +6 -0
- leindex/api_key_manager.py +646 -0
- leindex/async_indexer.py +698 -0
- leindex/async_task_queue.py +895 -0
- leindex/cli.py +477 -0
- leindex/config_manager.py +457 -0
- leindex/constants.py +361 -0
- leindex/content_extractor.py +197 -0
- leindex/core_engine/__init__.py +28 -0
- leindex/core_engine/consolidated_tools.py +990 -0
- leindex/core_engine/engine.py +676 -0
- leindex/core_engine/interfaces.py +269 -0
- leindex/core_engine/leann_backend.py +3147 -0
- leindex/core_engine/leann_backend_enhanced.py +762 -0
- leindex/core_engine/local_vector_backend.py +1861 -0
- leindex/core_engine/logger_config.py +19 -0
- leindex/core_engine/test_engine.py +68 -0
- leindex/core_engine/test_local_vector_backend.py +243 -0
- leindex/core_engine/tool_routers.py +1409 -0
- leindex/core_engine/types.py +107 -0
- leindex/elasticsearch_config.py +275 -0
- leindex/elasticsearch_installer.py +527 -0
- leindex/error_handling.py +241 -0
- leindex/file_change_tracker.py +1029 -0
- leindex/file_reader.py +758 -0
- leindex/global_config_manager.py +64 -0
- leindex/ignore_patterns.py +248 -0
- leindex/incremental_indexer.py +579 -0
- leindex/lazy_loader.py +570 -0
- leindex/logger_config.py +77 -0
- leindex/lru_cache.py +375 -0
- leindex/memory_profiler.py +718 -0
- leindex/monitoring.py +131 -0
- leindex/optimized_project_settings.py +625 -0
- leindex/parallel_processor.py +264 -0
- leindex/performance_monitor.py +918 -0
- leindex/progress_tracker.py +561 -0
- leindex/project_settings.py +654 -0
- leindex/realtime_indexer.py +1368 -0
- leindex/registry/__init__.py +79 -0
- leindex/registry/backup_scheduler.py +255 -0
- leindex/registry/directories.py +229 -0
- leindex/registry/index_migrator.py +709 -0
- leindex/registry/msgpack_serializer.py +454 -0
- leindex/registry/orphan_detector.py +561 -0
- leindex/registry/project_registry.py +674 -0
- leindex/registry/registration_integrator.py +393 -0
- leindex/registry/registry_backup.py +812 -0
- leindex/registry/startup_migration.py +389 -0
- leindex/repositories/__init__.py +65 -0
- leindex/repositories/base.py +397 -0
- leindex/repositories/file_repository.py +435 -0
- leindex/repositories/index_repository.py +350 -0
- leindex/repositories/quality_metrics_repository.py +799 -0
- leindex/repositories/repository_factory.py +159 -0
- leindex/repositories/search_repository.py +338 -0
- leindex/retry.py +382 -0
- leindex/search/__init__.py +21 -0
- leindex/search/ag.py +89 -0
- leindex/search/async_search.py +390 -0
- leindex/search/base.py +303 -0
- leindex/search/basic.py +123 -0
- leindex/search/grep.py +90 -0
- leindex/search/ranking.py +572 -0
- leindex/search/result_merger.py +711 -0
- leindex/search/ripgrep.py +83 -0
- leindex/search/ugrep.py +80 -0
- leindex/search/zoekt.py +978 -0
- leindex/search_utils.py +834 -0
- leindex/server.py +7841 -0
- leindex/stats_dashboard.py +520 -0
- leindex/storage/__init__.py +12 -0
- leindex/storage/dal_factory.py +715 -0
- leindex/storage/duckdb_storage.py +753 -0
- leindex/storage/elasticsearch_storage.py +831 -0
- leindex/storage/postgresql_storage.py +929 -0
- leindex/storage/sqlite_storage.py +1260 -0
- leindex/storage/storage_interface.py +728 -0
- leindex/storage/tantivy_storage.py +1200 -0
- leindex/storage/trie_index.py +166 -0
- leindex/system_utils.py +681 -0
- leindex/tantivy_config.py +258 -0
- leindex-1.0.0.dist-info/METADATA +513 -0
- leindex-1.0.0.dist-info/RECORD +91 -0
- leindex-1.0.0.dist-info/WHEEL +5 -0
- leindex-1.0.0.dist-info/entry_points.txt +3 -0
- leindex-1.0.0.dist-info/licenses/LICENSE +21 -0
- leindex-1.0.0.dist-info/top_level.txt +2 -0
- scripts/etl_script.py +559 -0
- scripts/install_agent.py +78 -0
leindex/__init__.py
ADDED
leindex/__main__.py
ADDED
|
@@ -0,0 +1,646 @@
|
|
|
1
|
+
"""
|
|
2
|
+
API Key Management with rotation and quota tracking.
|
|
3
|
+
|
|
4
|
+
PRODUCT.MD ALIGNMENT:
|
|
5
|
+
---------------------
|
|
6
|
+
"Multi-key rotation and quota management for API keys"
|
|
7
|
+
|
|
8
|
+
This module provides comprehensive API key management:
|
|
9
|
+
- Multiple key rotation strategies
|
|
10
|
+
- Per-key quota tracking and limits
|
|
11
|
+
- Automatic key switching on quota exhaustion
|
|
12
|
+
- Persistent storage of key usage statistics
|
|
13
|
+
- Health monitoring and alerting
|
|
14
|
+
"""
|
|
15
|
+
|
|
16
|
+
import os
|
|
17
|
+
import json
|
|
18
|
+
import time
|
|
19
|
+
import hashlib
|
|
20
|
+
import threading
|
|
21
|
+
from dataclasses import dataclass, field, asdict
|
|
22
|
+
from datetime import datetime
|
|
23
|
+
from enum import Enum
|
|
24
|
+
from typing import Dict, List, Optional, Any, Set, Callable
|
|
25
|
+
from pathlib import Path
|
|
26
|
+
import logging
|
|
27
|
+
|
|
28
|
+
logger = logging.getLogger(__name__)
|
|
29
|
+
|
|
30
|
+
|
|
31
|
+
class KeyRotationStrategy(Enum):
|
|
32
|
+
"""
|
|
33
|
+
Strategy for rotating between multiple API keys.
|
|
34
|
+
"""
|
|
35
|
+
ROUND_ROBIN = "round_robin" # Rotate keys in order
|
|
36
|
+
LEAST_RECENTLY_USED = "lru" # Use least recently used key
|
|
37
|
+
LEAST_QUOTA_REMAINING = "lqr" # Prefer keys with more quota
|
|
38
|
+
RANDOM = "random" # Random selection
|
|
39
|
+
|
|
40
|
+
|
|
41
|
+
class QuotaPeriod(Enum):
|
|
42
|
+
"""
|
|
43
|
+
Time periods for quota enforcement.
|
|
44
|
+
"""
|
|
45
|
+
MINUTE = "minute"
|
|
46
|
+
HOUR = "hour"
|
|
47
|
+
DAY = "day"
|
|
48
|
+
MONTH = "month"
|
|
49
|
+
FOREVER = "forever" # No reset
|
|
50
|
+
|
|
51
|
+
|
|
52
|
+
@dataclass
|
|
53
|
+
class KeyUsageStats:
|
|
54
|
+
"""
|
|
55
|
+
Usage statistics for a single API key.
|
|
56
|
+
"""
|
|
57
|
+
key_id: str
|
|
58
|
+
key_name: str
|
|
59
|
+
request_count: int = 0
|
|
60
|
+
last_used: Optional[str] = None
|
|
61
|
+
last_error: Optional[str] = None
|
|
62
|
+
error_count: int = 0
|
|
63
|
+
quota_used: int = 0
|
|
64
|
+
quota_limit: Optional[int] = None
|
|
65
|
+
quota_reset_at: Optional[str] = None
|
|
66
|
+
is_active: bool = True
|
|
67
|
+
created_at: str = field(default_factory=lambda: datetime.now().isoformat())
|
|
68
|
+
|
|
69
|
+
def to_dict(self) -> Dict[str, Any]:
|
|
70
|
+
"""Convert to dictionary for serialization."""
|
|
71
|
+
return asdict(self)
|
|
72
|
+
|
|
73
|
+
@classmethod
|
|
74
|
+
def from_dict(cls, data: Dict[str, Any]) -> 'KeyUsageStats':
|
|
75
|
+
"""Create from dictionary."""
|
|
76
|
+
return cls(**data)
|
|
77
|
+
|
|
78
|
+
def get_quota_remaining(self) -> Optional[int]:
|
|
79
|
+
"""Get remaining quota for this key."""
|
|
80
|
+
if self.quota_limit is None:
|
|
81
|
+
return None
|
|
82
|
+
return max(0, self.quota_limit - self.quota_used)
|
|
83
|
+
|
|
84
|
+
def is_quota_exceeded(self) -> bool:
|
|
85
|
+
"""Check if quota has been exceeded."""
|
|
86
|
+
if self.quota_limit is None:
|
|
87
|
+
return False
|
|
88
|
+
return self.quota_used >= self.quota_limit
|
|
89
|
+
|
|
90
|
+
def should_reset_quota(self) -> bool:
|
|
91
|
+
"""Check if quota should be reset based on time."""
|
|
92
|
+
if self.quota_reset_at is None:
|
|
93
|
+
return False
|
|
94
|
+
|
|
95
|
+
reset_time = datetime.fromisoformat(self.quota_reset_at)
|
|
96
|
+
return datetime.now() >= reset_time
|
|
97
|
+
|
|
98
|
+
def reset_quota(self):
|
|
99
|
+
"""Reset quota counter."""
|
|
100
|
+
self.quota_used = 0
|
|
101
|
+
|
|
102
|
+
|
|
103
|
+
@dataclass
|
|
104
|
+
class APIKey:
|
|
105
|
+
"""
|
|
106
|
+
Represents a single API key configuration.
|
|
107
|
+
"""
|
|
108
|
+
key_id: str # Unique identifier
|
|
109
|
+
key_value: str # The actual API key
|
|
110
|
+
key_name: str # Human-readable name
|
|
111
|
+
quota_limit: Optional[int] = None # Requests per period (None = unlimited)
|
|
112
|
+
quota_period: QuotaPeriod = QuotaPeriod.FOREVER
|
|
113
|
+
priority: int = 0 # Higher priority keys preferred
|
|
114
|
+
tags: Set[str] = field(default_factory=set)
|
|
115
|
+
is_active: bool = True
|
|
116
|
+
metadata: Dict[str, Any] = field(default_factory=dict)
|
|
117
|
+
|
|
118
|
+
def __post_init__(self):
|
|
119
|
+
"""Convert tags to set if it's a list."""
|
|
120
|
+
if isinstance(self.tags, list):
|
|
121
|
+
self.tags = set(self.tags)
|
|
122
|
+
|
|
123
|
+
def to_dict(self, redact: bool = True) -> Dict[str, Any]:
|
|
124
|
+
"""Convert to dictionary, optionally redacting the key value."""
|
|
125
|
+
data = asdict(self)
|
|
126
|
+
data['tags'] = list(self.tags) # Convert set to list
|
|
127
|
+
if redact and self.key_value:
|
|
128
|
+
# Show only first 4 and last 4 characters
|
|
129
|
+
if len(self.key_value) > 8:
|
|
130
|
+
data['key_value'] = f"{self.key_value[:4]}...{self.key_value[-4:]}"
|
|
131
|
+
else:
|
|
132
|
+
data['key_value'] = "***"
|
|
133
|
+
return data
|
|
134
|
+
|
|
135
|
+
@classmethod
|
|
136
|
+
def from_dict(cls, data: Dict[str, Any]) -> 'APIKey':
|
|
137
|
+
"""Create from dictionary."""
|
|
138
|
+
if 'tags' in data and isinstance(data['tags'], list):
|
|
139
|
+
data['tags'] = set(data['tags'])
|
|
140
|
+
return cls(**data)
|
|
141
|
+
|
|
142
|
+
def get_hash(self) -> str:
|
|
143
|
+
"""Get a hash of the key value for identification."""
|
|
144
|
+
return hashlib.sha256(self.key_value.encode()).hexdigest()[:16]
|
|
145
|
+
|
|
146
|
+
|
|
147
|
+
class APIKeyManager:
|
|
148
|
+
"""
|
|
149
|
+
Manages multiple API keys with rotation and quota tracking.
|
|
150
|
+
|
|
151
|
+
PRODUCT.MD ALIGNMENT:
|
|
152
|
+
---------------------
|
|
153
|
+
"Multi-key rotation and quota management"
|
|
154
|
+
|
|
155
|
+
Features:
|
|
156
|
+
- Multiple key rotation strategies
|
|
157
|
+
- Per-key quota tracking
|
|
158
|
+
- Automatic key switching
|
|
159
|
+
- Persistent usage statistics
|
|
160
|
+
- Health monitoring
|
|
161
|
+
"""
|
|
162
|
+
|
|
163
|
+
def __init__(
|
|
164
|
+
self,
|
|
165
|
+
storage_path: Optional[str] = None,
|
|
166
|
+
rotation_strategy: KeyRotationStrategy = KeyRotationStrategy.LEAST_QUOTA_REMAINING,
|
|
167
|
+
auto_save: bool = True,
|
|
168
|
+
save_interval: int = 60
|
|
169
|
+
):
|
|
170
|
+
"""
|
|
171
|
+
Initialize the API key manager.
|
|
172
|
+
|
|
173
|
+
Args:
|
|
174
|
+
storage_path: Path to persist usage statistics (JSON file)
|
|
175
|
+
rotation_strategy: Strategy for rotating between keys
|
|
176
|
+
auto_save: Whether to automatically save statistics
|
|
177
|
+
save_interval: Seconds between auto-saves
|
|
178
|
+
"""
|
|
179
|
+
self.storage_path = storage_path
|
|
180
|
+
self.rotation_strategy = rotation_strategy
|
|
181
|
+
self.auto_save = auto_save
|
|
182
|
+
self.save_interval = save_interval
|
|
183
|
+
|
|
184
|
+
self._keys: Dict[str, APIKey] = {}
|
|
185
|
+
self._usage_stats: Dict[str, KeyUsageStats] = {}
|
|
186
|
+
self._current_key_index = 0
|
|
187
|
+
self._lock = threading.RLock()
|
|
188
|
+
self._last_save_time = 0
|
|
189
|
+
self._callbacks: Dict[str, List[Callable]] = {
|
|
190
|
+
'on_key_selected': [],
|
|
191
|
+
'on_quota_exceeded': [],
|
|
192
|
+
'on_key_error': [],
|
|
193
|
+
'on_key_rotated': [],
|
|
194
|
+
}
|
|
195
|
+
|
|
196
|
+
# Load existing data if storage path provided
|
|
197
|
+
if self.storage_path:
|
|
198
|
+
self._load_from_storage()
|
|
199
|
+
|
|
200
|
+
# Start auto-save thread if enabled
|
|
201
|
+
if self.auto_save:
|
|
202
|
+
self._start_auto_save()
|
|
203
|
+
|
|
204
|
+
def add_key(
|
|
205
|
+
self,
|
|
206
|
+
key_id: str,
|
|
207
|
+
key_value: str,
|
|
208
|
+
key_name: str,
|
|
209
|
+
quota_limit: Optional[int] = None,
|
|
210
|
+
quota_period: QuotaPeriod = QuotaPeriod.FOREVER,
|
|
211
|
+
priority: int = 0,
|
|
212
|
+
tags: Optional[Set[str]] = None,
|
|
213
|
+
metadata: Optional[Dict[str, Any]] = None
|
|
214
|
+
) -> bool:
|
|
215
|
+
"""
|
|
216
|
+
Add a new API key.
|
|
217
|
+
|
|
218
|
+
Args:
|
|
219
|
+
key_id: Unique identifier for the key
|
|
220
|
+
key_value: The actual API key
|
|
221
|
+
key_name: Human-readable name
|
|
222
|
+
quota_limit: Requests per period (None = unlimited)
|
|
223
|
+
quota_period: Time period for quota
|
|
224
|
+
priority: Higher priority keys preferred
|
|
225
|
+
tags: Tags for grouping keys
|
|
226
|
+
metadata: Additional metadata
|
|
227
|
+
|
|
228
|
+
Returns:
|
|
229
|
+
True if key was added, False if key_id already exists
|
|
230
|
+
"""
|
|
231
|
+
with self._lock:
|
|
232
|
+
if key_id in self._keys:
|
|
233
|
+
logger.warning(f"Key {key_id} already exists, skipping")
|
|
234
|
+
return False
|
|
235
|
+
|
|
236
|
+
api_key = APIKey(
|
|
237
|
+
key_id=key_id,
|
|
238
|
+
key_value=key_value,
|
|
239
|
+
key_name=key_name,
|
|
240
|
+
quota_limit=quota_limit,
|
|
241
|
+
quota_period=quota_period,
|
|
242
|
+
priority=priority,
|
|
243
|
+
tags=tags or set(),
|
|
244
|
+
metadata=metadata or {}
|
|
245
|
+
)
|
|
246
|
+
|
|
247
|
+
self._keys[key_id] = api_key
|
|
248
|
+
self._usage_stats[key_id] = KeyUsageStats(
|
|
249
|
+
key_id=key_id,
|
|
250
|
+
key_name=key_name,
|
|
251
|
+
quota_limit=quota_limit
|
|
252
|
+
)
|
|
253
|
+
|
|
254
|
+
logger.info(f"Added API key: {key_name} ({key_id})")
|
|
255
|
+
self._save_if_needed()
|
|
256
|
+
|
|
257
|
+
return True
|
|
258
|
+
|
|
259
|
+
def remove_key(self, key_id: str) -> bool:
|
|
260
|
+
"""
|
|
261
|
+
Remove an API key.
|
|
262
|
+
|
|
263
|
+
Args:
|
|
264
|
+
key_id: Key identifier to remove
|
|
265
|
+
|
|
266
|
+
Returns:
|
|
267
|
+
True if key was removed, False if not found
|
|
268
|
+
"""
|
|
269
|
+
with self._lock:
|
|
270
|
+
if key_id not in self._keys:
|
|
271
|
+
return False
|
|
272
|
+
|
|
273
|
+
key_name = self._keys[key_id].key_name
|
|
274
|
+
del self._keys[key_id]
|
|
275
|
+
del self._usage_stats[key_id]
|
|
276
|
+
|
|
277
|
+
logger.info(f"Removed API key: {key_name} ({key_id})")
|
|
278
|
+
self._save_if_needed()
|
|
279
|
+
|
|
280
|
+
return True
|
|
281
|
+
|
|
282
|
+
def get_key(self, key_id: str) -> Optional[APIKey]:
|
|
283
|
+
"""Get an API key by ID (without the value)."""
|
|
284
|
+
with self._lock:
|
|
285
|
+
return self._keys.get(key_id)
|
|
286
|
+
|
|
287
|
+
def list_keys(self, include_inactive: bool = False) -> List[Dict[str, Any]]:
|
|
288
|
+
"""
|
|
289
|
+
List all API keys.
|
|
290
|
+
|
|
291
|
+
Args:
|
|
292
|
+
include_inactive: Whether to include inactive keys
|
|
293
|
+
|
|
294
|
+
Returns:
|
|
295
|
+
List of key dictionaries (values redacted)
|
|
296
|
+
"""
|
|
297
|
+
with self._lock:
|
|
298
|
+
result = []
|
|
299
|
+
for key in self._keys.values():
|
|
300
|
+
if not include_inactive and not key.is_active:
|
|
301
|
+
continue
|
|
302
|
+
result.append(key.to_dict(redact=True))
|
|
303
|
+
return result
|
|
304
|
+
|
|
305
|
+
def select_key(self, tags: Optional[Set[str]] = None) -> Optional[str]:
|
|
306
|
+
"""
|
|
307
|
+
Select the best available API key based on rotation strategy.
|
|
308
|
+
|
|
309
|
+
Args:
|
|
310
|
+
tags: Optional tags to filter keys
|
|
311
|
+
|
|
312
|
+
Returns:
|
|
313
|
+
Selected key ID or None if no keys available
|
|
314
|
+
"""
|
|
315
|
+
with self._lock:
|
|
316
|
+
# Filter available keys
|
|
317
|
+
available_keys = []
|
|
318
|
+
for key_id, key in self._keys.items():
|
|
319
|
+
if not key.is_active:
|
|
320
|
+
continue
|
|
321
|
+
|
|
322
|
+
# Check tags if specified
|
|
323
|
+
if tags and not tags.intersection(key.tags):
|
|
324
|
+
continue
|
|
325
|
+
|
|
326
|
+
# Check quota
|
|
327
|
+
stats = self._usage_stats.get(key_id)
|
|
328
|
+
if stats and stats.is_quota_exceeded():
|
|
329
|
+
# Check if quota should be reset
|
|
330
|
+
if stats.should_reset_quota():
|
|
331
|
+
stats.reset_quota()
|
|
332
|
+
else:
|
|
333
|
+
continue
|
|
334
|
+
|
|
335
|
+
available_keys.append((key_id, key, stats))
|
|
336
|
+
|
|
337
|
+
if not available_keys:
|
|
338
|
+
logger.warning("No available API keys")
|
|
339
|
+
return None
|
|
340
|
+
|
|
341
|
+
# Select based on strategy
|
|
342
|
+
selected_key_id = None
|
|
343
|
+
|
|
344
|
+
if self.rotation_strategy == KeyRotationStrategy.ROUND_ROBIN:
|
|
345
|
+
selected_key_id = self._round_robin_select(available_keys)
|
|
346
|
+
|
|
347
|
+
elif self.rotation_strategy == KeyRotationStrategy.LEAST_RECENTLY_USED:
|
|
348
|
+
selected_key_id = self._lru_select(available_keys)
|
|
349
|
+
|
|
350
|
+
elif self.rotation_strategy == KeyRotationStrategy.LEAST_QUOTA_REMAINING:
|
|
351
|
+
selected_key_id = self._lqr_select(available_keys)
|
|
352
|
+
|
|
353
|
+
elif self.rotation_strategy == KeyRotationStrategy.RANDOM:
|
|
354
|
+
import random
|
|
355
|
+
selected_key_id, _, _ = random.choice(available_keys)
|
|
356
|
+
|
|
357
|
+
# Fire callback
|
|
358
|
+
if selected_key_id:
|
|
359
|
+
self._fire_callback('on_key_selected', selected_key_id)
|
|
360
|
+
|
|
361
|
+
return selected_key_id
|
|
362
|
+
|
|
363
|
+
def get_key_value(self, key_id: str) -> Optional[str]:
|
|
364
|
+
"""
|
|
365
|
+
Get the actual value of an API key.
|
|
366
|
+
|
|
367
|
+
Args:
|
|
368
|
+
key_id: Key identifier
|
|
369
|
+
|
|
370
|
+
Returns:
|
|
371
|
+
Key value or None if not found
|
|
372
|
+
"""
|
|
373
|
+
with self._lock:
|
|
374
|
+
key = self._keys.get(key_id)
|
|
375
|
+
if key and key.is_active:
|
|
376
|
+
return key.key_value
|
|
377
|
+
return None
|
|
378
|
+
|
|
379
|
+
def record_usage(
|
|
380
|
+
self,
|
|
381
|
+
key_id: str,
|
|
382
|
+
success: bool = True,
|
|
383
|
+
error_message: Optional[str] = None
|
|
384
|
+
):
|
|
385
|
+
"""
|
|
386
|
+
Record API usage for a key.
|
|
387
|
+
|
|
388
|
+
Args:
|
|
389
|
+
key_id: Key that was used
|
|
390
|
+
success: Whether the request was successful
|
|
391
|
+
error_message: Error message if unsuccessful
|
|
392
|
+
"""
|
|
393
|
+
with self._lock:
|
|
394
|
+
stats = self._usage_stats.get(key_id)
|
|
395
|
+
if not stats:
|
|
396
|
+
logger.warning(f"No stats found for key {key_id}")
|
|
397
|
+
return
|
|
398
|
+
|
|
399
|
+
now = datetime.now().isoformat()
|
|
400
|
+
stats.request_count += 1
|
|
401
|
+
stats.last_used = now
|
|
402
|
+
|
|
403
|
+
if success:
|
|
404
|
+
stats.quota_used += 1
|
|
405
|
+
if stats.is_quota_exceeded():
|
|
406
|
+
logger.warning(f"Quota exceeded for key {key_id}")
|
|
407
|
+
self._fire_callback('on_quota_exceeded', key_id)
|
|
408
|
+
else:
|
|
409
|
+
stats.error_count += 1
|
|
410
|
+
stats.last_error = error_message
|
|
411
|
+
self._fire_callback('on_key_error', key_id, error_message)
|
|
412
|
+
|
|
413
|
+
self._save_if_needed()
|
|
414
|
+
|
|
415
|
+
def get_usage_stats(self, key_id: Optional[str] = None) -> Dict[str, Any]:
|
|
416
|
+
"""
|
|
417
|
+
Get usage statistics.
|
|
418
|
+
|
|
419
|
+
Args:
|
|
420
|
+
key_id: Specific key to get stats for, or None for all keys
|
|
421
|
+
|
|
422
|
+
Returns:
|
|
423
|
+
Dictionary of usage statistics
|
|
424
|
+
"""
|
|
425
|
+
with self._lock:
|
|
426
|
+
if key_id:
|
|
427
|
+
stats = self._usage_stats.get(key_id)
|
|
428
|
+
return stats.to_dict() if stats else {}
|
|
429
|
+
|
|
430
|
+
return {
|
|
431
|
+
kid: stats.to_dict()
|
|
432
|
+
for kid, stats in self._usage_stats.items()
|
|
433
|
+
}
|
|
434
|
+
|
|
435
|
+
def reset_quota(self, key_id: str):
|
|
436
|
+
"""Reset quota for a specific key."""
|
|
437
|
+
with self._lock:
|
|
438
|
+
stats = self._usage_stats.get(key_id)
|
|
439
|
+
if stats:
|
|
440
|
+
stats.reset_quota()
|
|
441
|
+
logger.info(f"Reset quota for key {key_id}")
|
|
442
|
+
self._save_if_needed()
|
|
443
|
+
|
|
444
|
+
def set_rotation_strategy(self, strategy: KeyRotationStrategy):
|
|
445
|
+
"""Change the rotation strategy."""
|
|
446
|
+
with self._lock:
|
|
447
|
+
self.rotation_strategy = strategy
|
|
448
|
+
logger.info(f"Changed rotation strategy to {strategy.value}")
|
|
449
|
+
|
|
450
|
+
def register_callback(self, event: str, callback: Callable):
|
|
451
|
+
"""
|
|
452
|
+
Register a callback for an event.
|
|
453
|
+
|
|
454
|
+
Events:
|
|
455
|
+
- on_key_selected: Called when a key is selected (args: key_id)
|
|
456
|
+
- on_quota_exceeded: Called when quota is exceeded (args: key_id)
|
|
457
|
+
- on_key_error: Called on error (args: key_id, error_message)
|
|
458
|
+
- on_key_rotated: Called when key is rotated (args: old_key_id, new_key_id)
|
|
459
|
+
"""
|
|
460
|
+
if event in self._callbacks:
|
|
461
|
+
self._callbacks[event].append(callback)
|
|
462
|
+
|
|
463
|
+
def _round_robin_select(self, available: List[tuple]) -> str:
|
|
464
|
+
"""Select key using round-robin strategy."""
|
|
465
|
+
# Sort by priority first
|
|
466
|
+
available.sort(key=lambda x: x[1].priority, reverse=True)
|
|
467
|
+
|
|
468
|
+
# Get highest priority group
|
|
469
|
+
if available:
|
|
470
|
+
max_priority = available[0][1].priority
|
|
471
|
+
high_priority = [k for k in available if k[1].priority == max_priority]
|
|
472
|
+
|
|
473
|
+
# Select from high priority group using index
|
|
474
|
+
key_id = high_priority[self._current_key_index % len(high_priority)][0]
|
|
475
|
+
self._current_key_index += 1
|
|
476
|
+
return key_id
|
|
477
|
+
|
|
478
|
+
return available[0][0]
|
|
479
|
+
|
|
480
|
+
def _lru_select(self, available: List[tuple]) -> str:
|
|
481
|
+
"""Select key using least recently used strategy."""
|
|
482
|
+
# Sort by last_used (oldest first)
|
|
483
|
+
available.sort(key=lambda x: x[2].last_used or '0')
|
|
484
|
+
return available[0][0]
|
|
485
|
+
|
|
486
|
+
def _lqr_select(self, available: List[tuple]) -> str:
|
|
487
|
+
"""Select key with most quota remaining."""
|
|
488
|
+
def quota_remaining(item):
|
|
489
|
+
stats = item[2]
|
|
490
|
+
if stats.quota_limit is None:
|
|
491
|
+
return float('inf')
|
|
492
|
+
return stats.quota_limit - stats.quota_used
|
|
493
|
+
|
|
494
|
+
available.sort(key=quota_remaining, reverse=True)
|
|
495
|
+
return available[0][0]
|
|
496
|
+
|
|
497
|
+
def _fire_callback(self, event: str, *args):
|
|
498
|
+
"""Fire all callbacks for an event."""
|
|
499
|
+
for callback in self._callbacks.get(event, []):
|
|
500
|
+
try:
|
|
501
|
+
callback(*args)
|
|
502
|
+
except Exception as e:
|
|
503
|
+
logger.error(f"Error in callback for {event}: {e}")
|
|
504
|
+
|
|
505
|
+
def _save_if_needed(self):
|
|
506
|
+
"""Save statistics if auto-save is enabled."""
|
|
507
|
+
if not self.auto_save or not self.storage_path:
|
|
508
|
+
return
|
|
509
|
+
|
|
510
|
+
now = time.time()
|
|
511
|
+
if now - self._last_save_time >= self.save_interval:
|
|
512
|
+
self._save_to_storage()
|
|
513
|
+
self._last_save_time = now
|
|
514
|
+
|
|
515
|
+
def _save_to_storage(self):
|
|
516
|
+
"""Save statistics to storage file."""
|
|
517
|
+
if not self.storage_path:
|
|
518
|
+
return
|
|
519
|
+
|
|
520
|
+
try:
|
|
521
|
+
data = {
|
|
522
|
+
'usage_stats': {
|
|
523
|
+
kid: stats.to_dict()
|
|
524
|
+
for kid, stats in self._usage_stats.items()
|
|
525
|
+
},
|
|
526
|
+
'rotation_strategy': self.rotation_strategy.value,
|
|
527
|
+
'saved_at': datetime.now().isoformat()
|
|
528
|
+
}
|
|
529
|
+
|
|
530
|
+
path = Path(self.storage_path)
|
|
531
|
+
path.parent.mkdir(parents=True, exist_ok=True)
|
|
532
|
+
|
|
533
|
+
with open(path, 'w') as f:
|
|
534
|
+
json.dump(data, f, indent=2)
|
|
535
|
+
|
|
536
|
+
logger.debug(f"Saved usage statistics to {self.storage_path}")
|
|
537
|
+
|
|
538
|
+
except Exception as e:
|
|
539
|
+
logger.error(f"Error saving to storage: {e}")
|
|
540
|
+
|
|
541
|
+
def _load_from_storage(self):
|
|
542
|
+
"""Load statistics from storage file."""
|
|
543
|
+
if not self.storage_path:
|
|
544
|
+
return
|
|
545
|
+
|
|
546
|
+
path = Path(self.storage_path)
|
|
547
|
+
if not path.exists():
|
|
548
|
+
return
|
|
549
|
+
|
|
550
|
+
try:
|
|
551
|
+
with open(path, 'r') as f:
|
|
552
|
+
data = json.load(f)
|
|
553
|
+
|
|
554
|
+
# Load usage stats
|
|
555
|
+
for kid, stats_data in data.get('usage_stats', {}).items():
|
|
556
|
+
self._usage_stats[kid] = KeyUsageStats.from_dict(stats_data)
|
|
557
|
+
|
|
558
|
+
# Load rotation strategy
|
|
559
|
+
strategy_str = data.get('rotation_strategy')
|
|
560
|
+
if strategy_str:
|
|
561
|
+
try:
|
|
562
|
+
self.rotation_strategy = KeyRotationStrategy(strategy_str)
|
|
563
|
+
except ValueError:
|
|
564
|
+
pass
|
|
565
|
+
|
|
566
|
+
logger.debug(f"Loaded usage statistics from {self.storage_path}")
|
|
567
|
+
|
|
568
|
+
except Exception as e:
|
|
569
|
+
logger.error(f"Error loading from storage: {e}")
|
|
570
|
+
|
|
571
|
+
def _start_auto_save(self):
|
|
572
|
+
"""Start background thread for auto-saving."""
|
|
573
|
+
def auto_save_worker():
|
|
574
|
+
while True:
|
|
575
|
+
time.sleep(self.save_interval)
|
|
576
|
+
with self._lock:
|
|
577
|
+
self._save_to_storage()
|
|
578
|
+
|
|
579
|
+
thread = threading.Thread(target=auto_save_worker, daemon=True)
|
|
580
|
+
thread.start()
|
|
581
|
+
logger.debug("Started auto-save thread")
|
|
582
|
+
|
|
583
|
+
def shutdown(self):
|
|
584
|
+
"""Shutdown and save final state."""
|
|
585
|
+
with self._lock:
|
|
586
|
+
self._save_to_storage()
|
|
587
|
+
logger.info("API key manager shutdown complete")
|
|
588
|
+
|
|
589
|
+
|
|
590
|
+
def create_manager_from_env(
|
|
591
|
+
prefix: str = "API_KEY_",
|
|
592
|
+
default_quota: Optional[int] = None,
|
|
593
|
+
storage_path: Optional[str] = None
|
|
594
|
+
) -> APIKeyManager:
|
|
595
|
+
"""
|
|
596
|
+
Create an API key manager from environment variables.
|
|
597
|
+
|
|
598
|
+
Environment variables should be named like:
|
|
599
|
+
- API_KEY_1=value
|
|
600
|
+
- API_KEY_1_NAME=My Key
|
|
601
|
+
- API_KEY_1_QUOTA=1000
|
|
602
|
+
- API_KEY_1_PRIORITY=10
|
|
603
|
+
|
|
604
|
+
Args:
|
|
605
|
+
prefix: Environment variable prefix
|
|
606
|
+
default_quota: Default quota limit if not specified
|
|
607
|
+
storage_path: Path for persistent storage
|
|
608
|
+
|
|
609
|
+
Returns:
|
|
610
|
+
Configured APIKeyManager
|
|
611
|
+
"""
|
|
612
|
+
manager = APIKeyManager(storage_path=storage_path)
|
|
613
|
+
|
|
614
|
+
# Find all API_KEY_* variables
|
|
615
|
+
api_keys = set()
|
|
616
|
+
for key in os.environ:
|
|
617
|
+
if key.startswith(prefix) and key.endswith('_1') or \
|
|
618
|
+
any(key.startswith(f"{prefix}{i}_") for i in range(2, 100)):
|
|
619
|
+
# Extract the index
|
|
620
|
+
parts = key[len(prefix):].split('_')
|
|
621
|
+
if parts and parts[0].isdigit():
|
|
622
|
+
api_keys.add(parts[0])
|
|
623
|
+
|
|
624
|
+
# Load each key
|
|
625
|
+
for idx in sorted(api_keys):
|
|
626
|
+
base = f"{prefix}{idx}"
|
|
627
|
+
|
|
628
|
+
value = os.environ.get(base)
|
|
629
|
+
if not value:
|
|
630
|
+
continue
|
|
631
|
+
|
|
632
|
+
key_id = os.environ.get(f"{base}_ID", f"key_{idx}")
|
|
633
|
+
name = os.environ.get(f"{base}_NAME", f"API Key {idx}")
|
|
634
|
+
quota = int(os.environ.get(f"{base}_QUOTA", default_quota or 0)) or None
|
|
635
|
+
priority = int(os.environ.get(f"{base}_PRIORITY", 0))
|
|
636
|
+
|
|
637
|
+
manager.add_key(
|
|
638
|
+
key_id=key_id,
|
|
639
|
+
key_value=value,
|
|
640
|
+
key_name=name,
|
|
641
|
+
quota_limit=quota,
|
|
642
|
+
priority=priority
|
|
643
|
+
)
|
|
644
|
+
|
|
645
|
+
logger.info(f"Loaded {len(api_keys)} API keys from environment")
|
|
646
|
+
return manager
|