From 930af8d9e9d7eaae39f68f04eed9512118bcf670 Mon Sep 17 00:00:00 2001 From: tyuXX Date: Sun, 27 Sep 2026 15:58:16 +0300 Subject: [PATCH] Up --- .env.example | 3 +++ src/config.ts | 9 +++++---- src/keyRotation.ts | 11 +++++++---- src/logger.ts | 2 +- src/routes.ts | 17 +++++++++++++++-- 5 files changed, 31 insertions(+), 11 deletions(-) diff --git a/.env.example b/.env.example index 6eddcad..1665da9 100644 --- a/.env.example +++ b/.env.example @@ -10,6 +10,9 @@ PORT=3000 # Logging configuration LOG_DIR=./logs +# Rate limit configuration (duration in milliseconds) +RATE_LIMIT_DURATION_MS=60000 + # Cloudflare Tunnel configuration (for Docker deployment) # Get your tunnel token from: https://dash.cloudflare.com/ CLOUDFLARE_TUNNEL_TOKEN=your_cloudflare_tunnel_token_here diff --git a/src/config.ts b/src/config.ts index 1494875..9ae92c8 100644 --- a/src/config.ts +++ b/src/config.ts @@ -3,15 +3,16 @@ import dotenv from 'dotenv'; dotenv.config(); export const config = { - apiPassword: process.env.API_PASSWORD || 'default_password', + apiPassword: process.env.API_PASSWORD, geminiApiKeys: (process.env.GEMINI_API_KEYS || '').split(',').filter(key => key.trim()), port: parseInt(process.env.PORT || '3000', 10), logDir: process.env.LOG_DIR || './logs', - model: 'gemini-flash-lite-latest' + model: 'gemini-flash-lite-latest', + rateLimitDurationMs: parseInt(process.env.RATE_LIMIT_DURATION_MS || '60000', 10) }; -if (!config.apiPassword || config.apiPassword === 'default_password') { - console.warn('WARNING: Using default API password. Please set API_PASSWORD in .env file'); +if (!config.apiPassword) { + throw new Error('API_PASSWORD is required. Please set it in .env file'); } if (config.geminiApiKeys.length === 0) { diff --git a/src/keyRotation.ts b/src/keyRotation.ts index 7269732..6107c07 100644 --- a/src/keyRotation.ts +++ b/src/keyRotation.ts @@ -29,8 +29,8 @@ class KeyRotationManager { return Date.now() < keyUsage.rateLimitedUntil; } - private markRateLimited(keyUsage: KeyUsage, durationMs: number = 60000): void { - keyUsage.rateLimitedUntil = Date.now() + durationMs; + private markRateLimited(keyUsage: KeyUsage, durationMs?: number): void { + keyUsage.rateLimitedUntil = Date.now() + (durationMs || config.rateLimitDurationMs); } getNextAvailableKey(): string { @@ -71,9 +71,12 @@ class KeyRotationManager { return [...this.keys]; } - createGenerativeAI(): GoogleGenerativeAI { + createGenerativeAI(): { client: GoogleGenerativeAI; apiKey: string } { const apiKey = this.getNextAvailableKey(); - return new GoogleGenerativeAI(apiKey); + return { + client: new GoogleGenerativeAI(apiKey), + apiKey + }; } } diff --git a/src/logger.ts b/src/logger.ts index 9b4a17e..a7314e7 100644 --- a/src/logger.ts +++ b/src/logger.ts @@ -79,7 +79,7 @@ class RequestLogger { } generateRequestId(): string { - return `req_${Date.now()}_${Math.random().toString(36).substr(2, 9)}`; + return `req_${Date.now()}_${Math.random().toString(36).substring(2, 11)}`; } } diff --git a/src/routes.ts b/src/routes.ts index 490ed4a..9149ea2 100644 --- a/src/routes.ts +++ b/src/routes.ts @@ -51,6 +51,7 @@ function convertToOpenAIResponse(geminiResponse: any, model: string, requestId: // POST /v1/chat/completions router.post('/v1/chat/completions', async (req: Request, res: Response) => { const requestId = requestLogger.generateRequestId(); + let apiKey = ''; try { const body: OpenAIChatRequest = req.body; @@ -68,7 +69,8 @@ router.post('/v1/chat/completions', async (req: Request, res: Response) => { } // Get Gemini client with rotated key - const genAI = keyRotationManager.createGenerativeAI(); + const { client: genAI, apiKey: currentApiKey } = keyRotationManager.createGenerativeAI(); + apiKey = currentApiKey; const model = genAI.getGenerativeModel({ model: config.model }); // Convert messages @@ -115,7 +117,18 @@ router.post('/v1/chat/completions', async (req: Request, res: Response) => { }); // Check if it's a rate limit error - if (error.message?.includes('RATE_LIMIT_EXCEEDED') || error.status === 429) { + const isRateLimitError = + error.status === 429 || + error.message?.includes('RATE_LIMIT_EXCEEDED') || + error.message?.includes('quota') || + error.message?.includes('limit') || + error.code === 429 || + error.statusCode === 429; + + if (isRateLimitError) { + // Mark the key as rate limited + keyRotationManager.markKeyAsRateLimited(apiKey); + res.status(429).json({ error: { message: 'Rate limit exceeded. Please try again later.',