@splashcodex/api-key-manager 4.1.0 → 5.0.0

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.
package/src/index.ts CHANGED
@@ -1,13 +1,31 @@
1
1
  /**
2
- * Universal ApiKeyManager v4.0 — Mastermind Edition
2
+ * Universal ApiKeyManager v5.0 — Ecosystem Edition
3
3
  * Implements: Rotation, Circuit Breaker, Persistence, Exponential Backoff, Strategies,
4
4
  * Event Emitter, Fallback, execute(), Timeout, Auto-Retry, Provider Tags,
5
5
  * Health Checks, Bulkhead/Concurrency
6
+ * NEW in v5.0: Provider Presets (GeminiManager, OpenAIManager, MultiManager),
7
+ * Built-in Persistence (FileStorage, MemoryStorage)
6
8
  * Gemini-Specific: finishReason handling, Safety blocks, RECITATION detection
7
9
  */
8
10
 
9
11
  import { EventEmitter } from 'events';
10
12
 
13
+ // ─── Re-exports: Persistence ─────────────────────────────────────────────────
14
+ // Persistence adapters can be imported from root or via subpath
15
+ export { FileStorage } from './persistence/file';
16
+ export type { FileStorageOptions } from './persistence/file';
17
+ export { MemoryStorage } from './persistence/memory';
18
+
19
+ // ─── Presets ─────────────────────────────────────────────────────────────────
20
+ // Presets are available via subpath imports to avoid circular dependencies:
21
+ // import { GeminiManager } from '@splashcodex/api-key-manager/presets/gemini';
22
+ // import { OpenAIManager } from '@splashcodex/api-key-manager/presets/openai';
23
+ // import { MultiManager } from '@splashcodex/api-key-manager/presets/multi';
24
+ // Or import all at once:
25
+ // import { GeminiManager, OpenAIManager, MultiManager } from '@splashcodex/api-key-manager/presets';
26
+
27
+
28
+
11
29
  // ─── Interfaces & Types ──────────────────────────────────────────────────────
12
30
 
13
31
  export interface KeyState {
@@ -185,12 +203,15 @@ export class WeightedStrategy implements LoadBalancingStrategy {
185
203
  }
186
204
 
187
205
  /**
188
- * Latency Strategy: Pick lowest average latency
206
+ * Latency Strategy: Pick lowest average latency with LRU tie-break
189
207
  */
190
208
  export class LatencyStrategy implements LoadBalancingStrategy {
191
209
  next(candidates: KeyState[]): KeyState | null {
192
210
  if (candidates.length === 0) return null;
193
- candidates.sort((a, b) => a.averageLatency - b.averageLatency);
211
+ candidates.sort((a, b) => {
212
+ if (a.averageLatency !== b.averageLatency) return a.averageLatency - b.averageLatency;
213
+ return a.lastUsed - b.lastUsed; // LRU tie-break
214
+ });
194
215
  return candidates[0];
195
216
  }
196
217
  }
@@ -0,0 +1,89 @@
1
+ /**
2
+ * File-Based Storage Adapter
3
+ *
4
+ * Persists API key state to a JSON file on disk.
5
+ * Survives process restarts so keys don't reset to CLOSED
6
+ * when an app reboots.
7
+ *
8
+ * Extracted from the proven WhatsDeX adapter pattern.
9
+ *
10
+ * @module persistence/file
11
+ */
12
+
13
+ import { writeFileSync, readFileSync, existsSync, mkdirSync, unlinkSync } from 'fs';
14
+ import { dirname, join } from 'path';
15
+ import { tmpdir } from 'os';
16
+
17
+ export interface FileStorageOptions {
18
+ /** Full path to the state file. Defaults to `os.tmpdir()/codedex_api_key_state.json` */
19
+ filePath?: string;
20
+ /** If true, clears any existing state file on construction (fresh start). Default: true */
21
+ clearOnInit?: boolean;
22
+ }
23
+
24
+ /**
25
+ * File-based storage adapter for ApiKeyManager.
26
+ *
27
+ * @example
28
+ * ```ts
29
+ * import { ApiKeyManager } from '@splashcodex/api-key-manager';
30
+ * import { FileStorage } from '@splashcodex/api-key-manager/persistence/file';
31
+ *
32
+ * const manager = new ApiKeyManager(keys, {
33
+ * storage: new FileStorage({ filePath: './state.json' })
34
+ * });
35
+ * ```
36
+ */
37
+ export class FileStorage {
38
+ private filePath: string;
39
+
40
+ constructor(options: FileStorageOptions = {}) {
41
+ this.filePath = options.filePath || join(tmpdir(), 'codedex_api_key_state.json');
42
+
43
+ if (options.clearOnInit !== false) {
44
+ this.clear();
45
+ }
46
+ }
47
+
48
+ getItem(_key: string): string | null {
49
+ try {
50
+ if (existsSync(this.filePath)) {
51
+ return readFileSync(this.filePath, 'utf-8');
52
+ }
53
+ } catch {
54
+ // Silently fail — state will be rebuilt from scratch
55
+ }
56
+ return null;
57
+ }
58
+
59
+ setItem(_key: string, value: string): void {
60
+ try {
61
+ const dir = dirname(this.filePath);
62
+ if (!existsSync(dir)) {
63
+ mkdirSync(dir, { recursive: true });
64
+ }
65
+ writeFileSync(this.filePath, value, 'utf-8');
66
+ } catch {
67
+ // Silently fail — state will be lost on restart
68
+ }
69
+ }
70
+
71
+ /**
72
+ * Delete the persisted state file.
73
+ * Useful for clearing stale dead-key states from a previous session.
74
+ */
75
+ clear(): void {
76
+ try {
77
+ if (existsSync(this.filePath)) {
78
+ unlinkSync(this.filePath);
79
+ }
80
+ } catch {
81
+ // Silently fail
82
+ }
83
+ }
84
+
85
+ /** Get the path to the state file (for debugging/logging) */
86
+ getFilePath(): string {
87
+ return this.filePath;
88
+ }
89
+ }
@@ -0,0 +1,7 @@
1
+ /**
2
+ * Persistence Adapters
3
+ * @module persistence
4
+ */
5
+ export { FileStorage } from './file';
6
+ export type { FileStorageOptions } from './file';
7
+ export { MemoryStorage } from './memory';
@@ -0,0 +1,43 @@
1
+ /**
2
+ * In-Memory Storage Adapter
3
+ *
4
+ * Simple key-value storage that lives only for the process lifetime.
5
+ * Useful for testing, serverless functions, or when persistence isn't needed.
6
+ *
7
+ * @module persistence/memory
8
+ */
9
+
10
+ /**
11
+ * In-memory storage adapter for ApiKeyManager.
12
+ *
13
+ * @example
14
+ * ```ts
15
+ * import { ApiKeyManager } from '@splashcodex/api-key-manager';
16
+ * import { MemoryStorage } from '@splashcodex/api-key-manager/persistence/memory';
17
+ *
18
+ * const manager = new ApiKeyManager(keys, {
19
+ * storage: new MemoryStorage()
20
+ * });
21
+ * ```
22
+ */
23
+ export class MemoryStorage {
24
+ private store: Map<string, string> = new Map();
25
+
26
+ getItem(key: string): string | null {
27
+ return this.store.get(key) ?? null;
28
+ }
29
+
30
+ setItem(key: string, value: string): void {
31
+ this.store.set(key, value);
32
+ }
33
+
34
+ /** Clear all stored state */
35
+ clear(): void {
36
+ this.store.clear();
37
+ }
38
+
39
+ /** Get the number of stored entries */
40
+ get size(): number {
41
+ return this.store.size;
42
+ }
43
+ }
@@ -0,0 +1,323 @@
1
+ /**
2
+ * BasePreset — Shared foundation for all provider presets
3
+ *
4
+ * Provides the "batteries included" pattern:
5
+ * - Singleton lifecycle management
6
+ * - Environment variable parsing (single key or JSON array)
7
+ * - File-based persistence (survives restarts)
8
+ * - Event-to-logger wiring
9
+ * - Health check scheduling
10
+ * - Result<T> pattern for safe initialization
11
+ *
12
+ * @module presets/base
13
+ */
14
+
15
+ import {
16
+ ApiKeyManager,
17
+ LatencyStrategy,
18
+ ExecuteOptions,
19
+ ApiKeyManagerOptions,
20
+ LoadBalancingStrategy,
21
+ } from '../index';
22
+ import { FileStorage } from '../persistence/file';
23
+ import { join } from 'path';
24
+ import { tmpdir } from 'os';
25
+
26
+ // ─── Result Type ─────────────────────────────────────────────────────────────
27
+
28
+ /**
29
+ * A discriminated union for safe error handling without exceptions.
30
+ * Used by `getInstance()` to avoid crashing on missing env vars.
31
+ */
32
+ export type Result<T> =
33
+ | { success: true; data: T }
34
+ | { success: false; error: Error };
35
+
36
+ // ─── Configuration ──────────────────────────────────────────────────────────
37
+
38
+ export interface PresetOptions {
39
+ /** Environment variable name(s) to read API keys from. */
40
+ envKeys: string[];
41
+ /** Provider name for logging and file state isolation. Default: 'default' */
42
+ provider?: string;
43
+ /** Load balancing strategy. Default: LatencyStrategy */
44
+ strategy?: LoadBalancingStrategy;
45
+ /** Max concurrent execute() calls. Default: 20 */
46
+ concurrency?: number;
47
+ /** Health check interval in ms. Set to 0 to disable. Default: 300_000 (5 min) */
48
+ healthCheckIntervalMs?: number;
49
+ /** Custom health check function. If not set, health checks are disabled. */
50
+ healthCheckFn?: (key: string) => Promise<boolean>;
51
+ /** Semantic cache config. Optional. */
52
+ semanticCache?: ApiKeyManagerOptions['semanticCache'];
53
+ /** Custom logger. Defaults to console. */
54
+ logger?: PresetLogger;
55
+ /** Fallback function when all keys are exhausted. */
56
+ fallbackFn?: () => any;
57
+ /** Custom state file path. Defaults to `os.tmpdir()/codedex_{provider}_state.json` */
58
+ stateFilePath?: string;
59
+ }
60
+
61
+ export interface PresetLogger {
62
+ info(message: string, ...args: any[]): void;
63
+ warn(message: string, ...args: any[]): void;
64
+ error(message: string, ...args: any[]): void;
65
+ }
66
+
67
+ // ─── Base Preset Class ──────────────────────────────────────────────────────
68
+
69
+ /**
70
+ * Abstract base class for provider presets.
71
+ * Subclasses only need to define `getDefaultOptions()` with provider-specific
72
+ * defaults (env var name, health check function, etc.).
73
+ *
74
+ * @example
75
+ * ```ts
76
+ * // Creating a custom preset:
77
+ * class MyProviderPreset extends BasePreset {
78
+ * protected static getDefaultOptions(): Partial<PresetOptions> {
79
+ * return {
80
+ * envKeys: ['MY_PROVIDER_API_KEY'],
81
+ * provider: 'my-provider',
82
+ * };
83
+ * }
84
+ * }
85
+ * ```
86
+ */
87
+ export abstract class BasePreset {
88
+ private static instances: Map<string, BasePreset> = new Map();
89
+
90
+ protected manager: ApiKeyManager;
91
+ protected logger: PresetLogger;
92
+ protected options: Required<Pick<PresetOptions, 'provider' | 'concurrency' | 'healthCheckIntervalMs'>> & PresetOptions;
93
+
94
+ protected constructor(apiKeys: string[], options: PresetOptions) {
95
+ this.logger = options.logger || console;
96
+
97
+ this.options = {
98
+ provider: options.provider || 'default',
99
+ concurrency: options.concurrency ?? 20,
100
+ healthCheckIntervalMs: options.healthCheckIntervalMs ?? 300_000,
101
+ ...options,
102
+ };
103
+
104
+ const stateFile = this.options.stateFilePath ||
105
+ join(tmpdir(), `codedex_${this.options.provider}_state.json`);
106
+
107
+ const storage = new FileStorage({
108
+ filePath: stateFile,
109
+ clearOnInit: true, // Fresh start each session to clear stale DEAD keys
110
+ });
111
+
112
+ this.manager = new ApiKeyManager(apiKeys, {
113
+ storage,
114
+ strategy: this.options.strategy || new LatencyStrategy(),
115
+ fallbackFn: this.options.fallbackFn,
116
+ concurrency: this.options.concurrency,
117
+ semanticCache: this.options.semanticCache,
118
+ });
119
+
120
+ this.wireEvents();
121
+
122
+ if (this.options.healthCheckFn && this.options.healthCheckIntervalMs > 0) {
123
+ this.manager.setHealthCheck(this.options.healthCheckFn);
124
+ this.manager.startHealthChecks(this.options.healthCheckIntervalMs);
125
+ }
126
+
127
+ this.logger.info(
128
+ `[${this.options.provider}] ApiKeyManager initialized with ${apiKeys.length} keys ` +
129
+ `(Strategy: ${this.options.strategy?.constructor.name || 'LatencyStrategy'}, ` +
130
+ `Concurrency: ${this.options.concurrency}, ` +
131
+ `HealthChecks: ${this.options.healthCheckIntervalMs > 0 ? `every ${this.options.healthCheckIntervalMs / 1000}s` : 'disabled'})`
132
+ );
133
+ }
134
+
135
+ /**
136
+ * Wire all manager events to the logger.
137
+ */
138
+ private wireEvents(): void {
139
+ const tag = this.options.provider;
140
+ this.manager.on('keyDead', (key) =>
141
+ this.logger.error(`[${tag}] Key PERMANENTLY DEAD: ...${key.slice(-4)}`));
142
+ this.manager.on('circuitOpen', (key) =>
143
+ this.logger.warn(`[${tag}] Circuit OPEN (cooldown): ...${key.slice(-4)}`));
144
+ this.manager.on('keyRecovered', (key) =>
145
+ this.logger.info(`[${tag}] Key RECOVERED: ...${key.slice(-4)}`));
146
+ this.manager.on('retry', (key, attempt, delay) =>
147
+ this.logger.info(`[${tag}] Retry with ...${key.slice(-4)} (Attempt ${attempt}, Delay ${delay}ms)`));
148
+ this.manager.on('fallback', (reason) =>
149
+ this.logger.warn(`[${tag}] Triggering FALLBACK: ${reason}`));
150
+ this.manager.on('allKeysExhausted', () =>
151
+ this.logger.error(`[${tag}] ALL KEYS EXHAUSTED! No fallback available.`));
152
+ this.manager.on('bulkheadRejected', () =>
153
+ this.logger.warn(`[${tag}] Bulkhead rejected request (concurrency limit reached)`));
154
+ this.manager.on('healthCheckPassed', (key) =>
155
+ this.logger.info(`[${tag}] Health check PASSED: ...${key.slice(-4)}`));
156
+ this.manager.on('healthCheckFailed', (key) =>
157
+ this.logger.warn(`[${tag}] Health check FAILED: ...${key.slice(-4)}`));
158
+ }
159
+
160
+ // ─── Public API ─────────────────────────────────────────────────────────
161
+
162
+ /**
163
+ * Execute a function with automatic key rotation, retries, timeout, and caching.
164
+ */
165
+ async execute<T>(
166
+ fn: (key: string, signal?: AbortSignal) => Promise<T>,
167
+ options?: ExecuteOptions & { prompt?: string }
168
+ ): Promise<T> {
169
+ return this.manager.execute(fn, options);
170
+ }
171
+
172
+ /**
173
+ * Execute a streaming function with retry on initial connection failure.
174
+ */
175
+ async *executeStream<T>(
176
+ fn: (key: string, signal?: AbortSignal) => AsyncGenerator<T, any, unknown>,
177
+ options?: ExecuteOptions & { prompt?: string }
178
+ ): AsyncGenerator<T, any, unknown> {
179
+ yield* this.manager.executeStream(fn, options);
180
+ }
181
+
182
+ /**
183
+ * Get the best available API key directly (low-level).
184
+ */
185
+ getKey(): string | null {
186
+ return this.manager.getKey();
187
+ }
188
+
189
+ /**
190
+ * Get the number of non-dead keys.
191
+ */
192
+ getKeyCount(): number {
193
+ return this.manager.getKeyCount();
194
+ }
195
+
196
+ /**
197
+ * Get pool health statistics.
198
+ */
199
+ getStats() {
200
+ return this.manager.getStats();
201
+ }
202
+
203
+ /**
204
+ * Get the underlying ApiKeyManager instance for advanced use.
205
+ */
206
+ getManager(): ApiKeyManager {
207
+ return this.manager;
208
+ }
209
+
210
+ /**
211
+ * Stop health checks and clean up. Call when shutting down.
212
+ */
213
+ destroy(): void {
214
+ this.manager.stopHealthChecks();
215
+ }
216
+
217
+ // ─── Static Factory ─────────────────────────────────────────────────────
218
+
219
+ /**
220
+ * Parse API keys from environment variables.
221
+ * Supports:
222
+ * - Single key: `"AIza..."`
223
+ * - JSON array: `'["AIza...", "AIzb..."]'`
224
+ * - Comma-separated: `"AIza...,AIzb..."`
225
+ */
226
+ protected static parseKeysFromEnv(envKeys: string[]): string[] {
227
+ const keys: string[] = [];
228
+
229
+ for (const envName of envKeys) {
230
+ const envValue = process.env[envName];
231
+ if (!envValue) continue;
232
+
233
+ const trimmed = envValue.trim();
234
+ if (!trimmed) continue;
235
+
236
+ // Try JSON array
237
+ if (trimmed.startsWith('[')) {
238
+ try {
239
+ const parsed = JSON.parse(trimmed);
240
+ if (Array.isArray(parsed)) {
241
+ keys.push(...parsed.filter((k: any) => typeof k === 'string' && k.trim()));
242
+ continue;
243
+ }
244
+ } catch {
245
+ // Not valid JSON, fall through to comma split
246
+ }
247
+ }
248
+
249
+ // Comma-separated or single key
250
+ keys.push(...trimmed.split(',').map(k => k.trim()).filter(k => k.length > 0));
251
+ }
252
+
253
+ return [...new Set(keys)]; // Deduplicate
254
+ }
255
+
256
+ /**
257
+ * Get or create the singleton instance for a preset.
258
+ * This is the core factory used by all preset subclasses.
259
+ *
260
+ * @param PresetClass - The preset class to instantiate
261
+ * @param overrides - Optional overrides for preset options
262
+ * @returns Result<T> — either `{ success: true, data: instance }` or `{ success: false, error }`
263
+ */
264
+ protected static createInstance<T extends BasePreset>(
265
+ PresetClass: new (keys: string[], options: PresetOptions) => T,
266
+ defaultOptions: Partial<PresetOptions>,
267
+ overrides?: Partial<PresetOptions>
268
+ ): Result<T> {
269
+ const mergedOptions = { ...defaultOptions, ...overrides } as PresetOptions;
270
+ const instanceKey = mergedOptions.provider || PresetClass.name;
271
+
272
+ // Return existing singleton
273
+ const existing = BasePreset.instances.get(instanceKey);
274
+ if (existing) {
275
+ return { success: true, data: existing as T };
276
+ }
277
+
278
+ // Parse keys
279
+ const envKeys = mergedOptions.envKeys || [];
280
+ const keys = BasePreset.parseKeysFromEnv(envKeys);
281
+
282
+ if (keys.length === 0) {
283
+ const logger = mergedOptions.logger || console;
284
+ logger.warn(
285
+ `[${instanceKey}] No API keys found in env vars: ${envKeys.join(', ')}. ` +
286
+ `AI features will be disabled.`
287
+ );
288
+ // Still create the instance with empty keys — allows graceful degradation
289
+ }
290
+
291
+ try {
292
+ const instance = new PresetClass(keys, mergedOptions);
293
+ BasePreset.instances.set(instanceKey, instance);
294
+ return { success: true, data: instance };
295
+ } catch (error) {
296
+ return {
297
+ success: false,
298
+ error: error instanceof Error ? error : new Error(String(error)),
299
+ };
300
+ }
301
+ }
302
+
303
+ /**
304
+ * Reset a singleton instance (primarily for testing).
305
+ */
306
+ protected static resetInstance(provider: string): void {
307
+ const existing = BasePreset.instances.get(provider);
308
+ if (existing) {
309
+ existing.destroy();
310
+ BasePreset.instances.delete(provider);
311
+ }
312
+ }
313
+
314
+ /**
315
+ * Reset ALL singleton instances (primarily for testing).
316
+ */
317
+ static resetAll(): void {
318
+ for (const [, instance] of BasePreset.instances) {
319
+ instance.destroy();
320
+ }
321
+ BasePreset.instances.clear();
322
+ }
323
+ }
@@ -0,0 +1,84 @@
1
+ /**
2
+ * Gemini Preset — One-line Gemini API key management
3
+ *
4
+ * Pre-configured singleton with:
5
+ * - Reads `GOOGLE_GEMINI_API_KEY` or `GEMINI_API_KEY` from env
6
+ * - LatencyStrategy for optimal key selection
7
+ * - File persistence (survives restarts)
8
+ * - Health checks every 5 minutes
9
+ * - Concurrency limit of 20
10
+ *
11
+ * @module presets/gemini
12
+ *
13
+ * @example
14
+ * ```ts
15
+ * import { GeminiManager } from '@splashcodex/api-key-manager/presets/gemini';
16
+ *
17
+ * // Initialize once (reads keys from process.env automatically)
18
+ * const result = GeminiManager.getInstance();
19
+ * if (!result.success) throw result.error;
20
+ * const gemini = result.data;
21
+ *
22
+ * // Use the execute() wrapper for automatic key rotation + retries
23
+ * const response = await gemini.execute(async (key) => {
24
+ * const genAI = new GoogleGenerativeAI(key);
25
+ * const model = genAI.getGenerativeModel({ model: 'gemini-2.0-flash' });
26
+ * const res = await model.generateContent('Hello, world!');
27
+ * return res.response.text();
28
+ * }, { maxRetries: 3, timeoutMs: 30000 });
29
+ * ```
30
+ */
31
+
32
+ import { BasePreset, PresetOptions, Result } from './base';
33
+
34
+ export class GeminiManager extends BasePreset {
35
+ private static readonly PROVIDER = 'gemini';
36
+
37
+ private constructor(keys: string[], options: PresetOptions) {
38
+ super(keys, options);
39
+ }
40
+
41
+ /**
42
+ * Default configuration for Gemini presets.
43
+ */
44
+ private static getDefaultOptions(): Partial<PresetOptions> {
45
+ return {
46
+ envKeys: ['GOOGLE_GEMINI_API_KEY', 'GEMINI_API_KEY'],
47
+ provider: GeminiManager.PROVIDER,
48
+ concurrency: 20,
49
+ healthCheckIntervalMs: 300_000, // 5 minutes
50
+ };
51
+ }
52
+
53
+ /**
54
+ * Get or create the singleton GeminiManager instance.
55
+ *
56
+ * @param overrides - Optional configuration overrides
57
+ * @returns Result<GeminiManager> — safely check `.success` before using `.data`
58
+ *
59
+ * @example
60
+ * ```ts
61
+ * const result = GeminiManager.getInstance();
62
+ * if (result.success) {
63
+ * const gemini = result.data;
64
+ * const text = await gemini.execute(apiCall, { maxRetries: 3 });
65
+ * }
66
+ * ```
67
+ */
68
+ static getInstance(overrides?: Partial<PresetOptions>): Result<GeminiManager> {
69
+ return BasePreset.createInstance(
70
+ GeminiManager as unknown as new (keys: string[], options: PresetOptions) => GeminiManager,
71
+ GeminiManager.getDefaultOptions(),
72
+ overrides
73
+ ) as Result<GeminiManager>;
74
+ }
75
+
76
+ /**
77
+ * Reset the singleton instance. Primarily for testing.
78
+ */
79
+ static reset(): void {
80
+ BasePreset.resetInstance(GeminiManager.PROVIDER);
81
+ }
82
+ }
83
+
84
+ export { Result } from './base';
@@ -0,0 +1,10 @@
1
+ /**
2
+ * Presets — Batteries-included provider managers
3
+ * @module presets
4
+ */
5
+ export { BasePreset } from './base';
6
+ export type { PresetOptions, PresetLogger, Result } from './base';
7
+ export { GeminiManager } from './gemini';
8
+ export { OpenAIManager } from './openai';
9
+ export { MultiManager } from './multi';
10
+ export type { ProviderConfig, MultiManagerOptions } from './multi';