From 0e832337156eea2bcbf2c6266ccc98d5300df98d Mon Sep 17 00:00:00 2001 From: tyuXX Date: Tue, 3 Nov 2026 17:55:26 +0000 Subject: [PATCH] feat(timeout): prevent Cloudflare 524 timeouts on long generations via SSE heartbeats and chunked keep-alives --- .env.example | 11 +++ README.md | 17 ++++ package.json | 2 +- src/config.ts | 7 +- src/revolverEngine.ts | 168 ++++++++++++++++++++++++++----- src/routes.ts | 2 + test-timeout-keepalive.ts | 203 ++++++++++++++++++++++++++++++++++++++ 7 files changed, 385 insertions(+), 25 deletions(-) create mode 100644 test-timeout-keepalive.ts diff --git a/.env.example b/.env.example index c641dbd..9e081e3 100644 --- a/.env.example +++ b/.env.example @@ -16,6 +16,17 @@ LOG_DIR=./logs # Rate limit configuration (duration in milliseconds) RATE_LIMIT_DURATION_MS=60000 +# Cloudflare Anti-Timeout Configuration +# Interval (in ms) to send SSE comment heartbeats during streaming (: keep-alive) +# KEEPALIVE_INTERVAL_MS=15000 + +# Enable chunked whitespace keep-alives for non-streaming requests exceeding delay +# ENABLE_NON_STREAMING_KEEPALIVE=true +# NON_STREAMING_KEEPALIVE_DELAY_MS=20000 + +# Candidate timeout per provider attempt before rotating (in ms) +# CANDIDATE_TIMEOUT_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/README.md b/README.md index 1736485..283f298 100644 --- a/README.md +++ b/README.md @@ -16,6 +16,7 @@ An OpenAI v1 compatible API endpoint that rotates Gemini API keys to avoid rate - ๐Ÿงช **Live Playground & Key Verifier** - Test individual provider keys and inspect step-by-step trace metadata directly from the Admin console - ๐Ÿณ **Docker support** - Containerized deployment with Docker and Docker Compose - ๐ŸŒ **Cloudflare Tunnel integration** - Securely expose your API via Cloudflare tunnel +- โฑ๏ธ **Cloudflare 524 Anti-Timeout Engine** - Prevents Cloudflare Free/Pro/Biz 100s proxy timeouts on long generations via immediate SSE header flushing, periodic `: keep-alive` comment heartbeats, and RFC 8259 chunked whitespace keep-alives for non-streaming requests ## Setup @@ -126,6 +127,22 @@ With Cloudflare tunnel running, your API will be accessible at: Use the same authentication method with your configured `API_PASSWORD`. +### Cloudflare 524 Timeout Prevention (Free Plan Compatible) + +Cloudflare Free, Pro, and Business plans enforce a non-configurable **100-second idle proxy timeout** (Error 524). Long LLM generations (thinking models, large prompts, or slow outputs) can exceed this limit. GeminiRevolver solves this at the application level: + +1. **Streaming Requests (`stream: true`)**: + - HTTP response headers and `X-Accel-Buffering: no` are flushed immediately upon initiation. + - Periodic SSE comment pings (`: keep-alive\n\n`) are transmitted every 15 seconds. These reset Cloudflare's 100-second timer continuously while being silently ignored by SSE client parsers per the W3C spec. +2. **Non-Streaming Requests (`stream: false`)**: + - If generation takes longer than 20 seconds, chunked transfer encoding (`Transfer-Encoding: chunked`) is activated, and periodic whitespace keep-alives (` `) are emitted. + - Standard JSON parsers (RFC 8259) automatically ignore leading whitespace when parsing the final JSON payload. +3. **Configurable Settings (`.env`)**: + - `KEEPALIVE_INTERVAL_MS` (default: `15000`): Interval between SSE comment heartbeats. + - `ENABLE_NON_STREAMING_KEEPALIVE` (default: `true`): Enables chunked whitespace keep-alives for non-streaming calls. + - `NON_STREAMING_KEEPALIVE_DELAY_MS` (default: `20000`): Wait time before activating non-streaming keep-alives. + - `CANDIDATE_TIMEOUT_MS` (default: `60000`): Timeout per individual key/provider before triggering automatic failover. + ## Admin Console & Model Revolver Navigate to `http://localhost:3000/admin` in your web browser. diff --git a/package.json b/package.json index 2427635..9a1add4 100644 --- a/package.json +++ b/package.json @@ -8,7 +8,7 @@ "start": "node dist/index.js", "dev": "ts-node src/index.ts", "watch": "tsc --watch", - "test": "API_PASSWORD=test_password ts-node test-revolver.ts && API_PASSWORD=test_password ts-node test-integration.ts" + "test": "API_PASSWORD=test_password ts-node test-revolver.ts && API_PASSWORD=test_password ts-node test-integration.ts && API_PASSWORD=test_password ts-node test-timeout-keepalive.ts" }, "keywords": ["openai", "gemini", "api", "rotation"], "author": "", diff --git a/src/config.ts b/src/config.ts index 87c3858..95f9c3b 100644 --- a/src/config.ts +++ b/src/config.ts @@ -10,7 +10,12 @@ export const config = { logDir: process.env.LOG_DIR || './logs', configFilePath: process.env.CONFIG_FILE || path.join(process.cwd(), 'data', 'revolver-config.json'), model: 'gemini-flash-lite-latest', - rateLimitDurationMs: parseInt(process.env.RATE_LIMIT_DURATION_MS || '60000', 10) + rateLimitDurationMs: parseInt(process.env.RATE_LIMIT_DURATION_MS || '60000', 10), + // Cloudflare Anti-Timeout & Keep-Alive settings + keepAliveIntervalMs: parseInt(process.env.KEEPALIVE_INTERVAL_MS || '15000', 10), + enableNonStreamingKeepAlive: process.env.ENABLE_NON_STREAMING_KEEPALIVE !== 'false', + nonStreamingKeepAliveDelayMs: parseInt(process.env.NON_STREAMING_KEEPALIVE_DELAY_MS || '20000', 10), + candidateTimeoutMs: parseInt(process.env.CANDIDATE_TIMEOUT_MS || '60000', 10) }; if (!config.apiPassword) { diff --git a/src/revolverEngine.ts b/src/revolverEngine.ts index b0579b8..e0194b7 100644 --- a/src/revolverEngine.ts +++ b/src/revolverEngine.ts @@ -220,17 +220,75 @@ export class RevolverEngine { let streamStarted = false; let isCancelled = false; + let keepAliveTimer: NodeJS.Timeout | null = null; + let nonStreamingTimer: NodeJS.Timeout | null = null; + + const cleanupTimers = () => { + if (keepAliveTimer) { + clearInterval(keepAliveTimer); + keepAliveTimer = null; + } + if (nonStreamingTimer) { + clearInterval(nonStreamingTimer); + nonStreamingTimer = null; + } + }; res.on('close', () => { + cleanupTimers(); if (!res.writableEnded) { isCancelled = true; if (onCancelled) onCancelled(); } }); + if (isStreaming) { + // Send SSE headers immediately to establish connection with Cloudflare and prevent 524 timeouts + if (!res.headersSent) { + res.setHeader('Content-Type', 'text/event-stream; charset=utf-8'); + res.setHeader('Cache-Control', 'no-cache, no-transform'); + res.setHeader('Connection', 'keep-alive'); + res.setHeader('X-Accel-Buffering', 'no'); + if (typeof res.flushHeaders === 'function') { + res.flushHeaders(); + } + } + + // Immediately transmit an initial SSE comment ping so Cloudflare Edge receives response bytes instantly + if (!res.destroyed && !res.writableEnded) { + res.write(': keep-alive\n\n'); + } + + // Keep connection active with periodic SSE comments while waiting for model thinking / generation + keepAliveTimer = setInterval(() => { + if (!res.destroyed && !res.writableEnded) { + res.write(': keep-alive\n\n'); + } + }, config.keepAliveIntervalMs); + } else if (config.enableNonStreamingKeepAlive) { + // For non-streaming requests: start emitting whitespace chunks if request takes longer than nonStreamingKeepAliveDelayMs + nonStreamingTimer = setInterval(() => { + if (res.destroyed || res.writableEnded) { + cleanupTimers(); + return; + } + if (!res.headersSent) { + res.setHeader('Content-Type', 'application/json; charset=utf-8'); + res.setHeader('Transfer-Encoding', 'chunked'); + res.setHeader('Cache-Control', 'no-cache, no-transform'); + res.setHeader('X-Accel-Buffering', 'no'); + if (typeof res.flushHeaders === 'function') { + res.flushHeaders(); + } + } + res.write(' '); + }, config.nonStreamingKeepAliveDelayMs); + } + // Sort tiers by tierIndex const sortedTiers = [...customModel.tiers].sort((a, b) => a.tierIndex - b.tierIndex); if (sortedTiers.length === 0) { + cleanupTimers(); throw new Error(`Custom model '${customModel.name}' has no fallback tiers defined.`); } @@ -248,7 +306,10 @@ export class RevolverEngine { // Try candidates in this tier for (const candidate of candidates) { - if (isCancelled || res.destroyed) return; + if (isCancelled || res.destroyed) { + cleanupTimers(); + return; + } try { console.log(`[REVOLVER] Routing to Provider '${candidate.provider.name}' (${candidate.provider.type}) with model '${candidate.target.model}' [Key ${candidate.keyIndex + 1}/${candidate.provider.keys.length}]`); @@ -265,6 +326,7 @@ export class RevolverEngine { }, onSuccess }); + cleanupTimers(); // If stream finished successfully, return return; } else { @@ -275,6 +337,7 @@ export class RevolverEngine { requestId }); + cleanupTimers(); if (isCancelled || res.destroyed) return; // Success! Update stats @@ -289,16 +352,34 @@ export class RevolverEngine { onSuccess({ input: promptTokens, output: completionTokens }); } - res.json(responseData); + if (res.headersSent) { + // Chunked keep-alive headers were already emitted + res.write(JSON.stringify(responseData)); + res.end(); + } else { + res.json(responseData); + } return; } } catch (err: any) { lastError = err; console.error(`[REVOLVER] Candidate failed (Provider: '${candidate.provider.name}', Model: '${candidate.target.model}'):`, err.message); - // If stream has already started sending bytes to the client, we cannot fail over cleanly + // If stream has already started sending content bytes to the client, we cannot fail over cleanly if (streamStarted) { + cleanupTimers(); if (onFailure) onFailure('stream_interrupted'); + if (!res.destroyed && !res.writableEnded) { + res.write(`data: ${JSON.stringify({ + error: { + message: err.message || 'Stream interrupted', + type: 'server_error', + code: 'stream_interrupted' + } + })}\n\n`); + res.write('data: [DONE]\n\n'); + res.end(); + } throw err; } @@ -327,15 +408,42 @@ export class RevolverEngine { } // If we reached here, all tiers and all candidates failed + cleanupTimers(); if (onFailure) onFailure('all_tiers_exhausted'); const finalErrorMessage = lastError ? lastError.message : 'All model tiers and provider keys are exhausted or rate-limited.'; - res.status(503).json({ - error: { - message: `[Revolver Fallback Error]: ${finalErrorMessage}`, - type: 'revolver_exhausted_error', - code: 'all_tiers_exhausted' + + if (isStreaming) { + if (!res.destroyed && !res.writableEnded) { + res.write(`data: ${JSON.stringify({ + error: { + message: `[Revolver Fallback Error]: ${finalErrorMessage}`, + type: 'revolver_exhausted_error', + code: 'all_tiers_exhausted' + } + })}\n\n`); + res.write('data: [DONE]\n\n'); + res.end(); } - }); + } else { + if (res.headersSent) { + res.write(JSON.stringify({ + error: { + message: `[Revolver Fallback Error]: ${finalErrorMessage}`, + type: 'revolver_exhausted_error', + code: 'all_tiers_exhausted' + } + })); + res.end(); + } else { + res.status(503).json({ + error: { + message: `[Revolver Fallback Error]: ${finalErrorMessage}`, + type: 'revolver_exhausted_error', + code: 'all_tiers_exhausted' + } + }); + } + } } private async executeNonStreaming(params: { @@ -377,7 +485,7 @@ export class RevolverEngine { const modelInstance = genAI.getGenerativeModel({ model: candidate.target.model, systemInstruction: systemInstruction || undefined - }); + }, { timeout: config.candidateTimeoutMs }); const lastMessage = geminiMessages[geminiMessages.length - 1]; if (!lastMessage || lastMessage.role !== 'user') { @@ -447,7 +555,8 @@ export class RevolverEngine { 'Content-Type': 'application/json', 'Authorization': `Bearer ${candidate.keyConfig.key}` }, - body: JSON.stringify(forwardedBody) + body: JSON.stringify(forwardedBody), + signal: AbortSignal.timeout(config.candidateTimeoutMs) }); if (!response.ok) { @@ -522,7 +631,7 @@ export class RevolverEngine { const modelInstance = genAI.getGenerativeModel({ model: candidate.target.model, systemInstruction: systemInstruction || undefined - }); + }, { timeout: config.candidateTimeoutMs }); const lastMessage = geminiMessages[geminiMessages.length - 1]; if (!lastMessage || lastMessage.role !== 'user') { @@ -541,11 +650,16 @@ export class RevolverEngine { // Start streaming from Gemini const result = await chat.sendMessageStream(lastMessage.parts[0].text); - // If we got here without throwing, commit headers to client - onStreamStart(); - res.setHeader('Content-Type', 'text/event-stream'); - res.setHeader('Cache-Control', 'no-cache'); - res.setHeader('Connection', 'keep-alive'); + // If headers haven't been committed, commit them now + if (!res.headersSent) { + res.setHeader('Content-Type', 'text/event-stream; charset=utf-8'); + res.setHeader('Cache-Control', 'no-cache, no-transform'); + res.setHeader('Connection', 'keep-alive'); + res.setHeader('X-Accel-Buffering', 'no'); + if (typeof res.flushHeaders === 'function') { + res.flushHeaders(); + } + } let fullContent = ''; let promptTokens = 0; @@ -555,6 +669,7 @@ export class RevolverEngine { if (res.destroyed) break; const text = chunk.text(); fullContent += text; + onStreamStart(); const chunkResponse = { id: `chatcmpl-${requestId}`, @@ -640,7 +755,8 @@ export class RevolverEngine { 'Content-Type': 'application/json', 'Authorization': `Bearer ${candidate.keyConfig.key}` }, - body: JSON.stringify(forwardedBody) + body: JSON.stringify(forwardedBody), + signal: AbortSignal.timeout(config.candidateTimeoutMs) }); if (!response.ok) { @@ -659,11 +775,16 @@ export class RevolverEngine { throw new Error('Response body is null from provider stream.'); } - // Stream started successfully! - onStreamStart(); - res.setHeader('Content-Type', 'text/event-stream'); - res.setHeader('Cache-Control', 'no-cache'); - res.setHeader('Connection', 'keep-alive'); + // If headers haven't been committed, commit them now + if (!res.headersSent) { + res.setHeader('Content-Type', 'text/event-stream; charset=utf-8'); + res.setHeader('Cache-Control', 'no-cache, no-transform'); + res.setHeader('Connection', 'keep-alive'); + res.setHeader('X-Accel-Buffering', 'no'); + if (typeof res.flushHeaders === 'function') { + res.flushHeaders(); + } + } const reader = response.body.getReader(); const decoder = new TextDecoder(); @@ -700,6 +821,7 @@ export class RevolverEngine { const parsed = JSON.parse(dataStr); parsed.model = requestedModelName; if (parsed.choices?.[0]?.delta?.content) { + onStreamStart(); totalOutputChars += parsed.choices[0].delta.content.length; } res.write(`data: ${JSON.stringify(parsed)}\n\n`); diff --git a/src/routes.ts b/src/routes.ts index 3fd9af7..2fdb130 100644 --- a/src/routes.ts +++ b/src/routes.ts @@ -121,6 +121,8 @@ router.post('/v1/chat/completions', async (req: Request, res: Response) => { code: 'internal_error' } }); + } else if (!res.writableEnded) { + res.end(); } } }); diff --git a/test-timeout-keepalive.ts b/test-timeout-keepalive.ts new file mode 100644 index 0000000..dd9ab3f --- /dev/null +++ b/test-timeout-keepalive.ts @@ -0,0 +1,203 @@ +import http from 'http'; +import assert from 'assert'; +import app from './src/index'; +import { config } from './src/config'; +import { configStore } from './src/configStore'; + +async function runKeepAliveTests() { + console.log('๐Ÿงช Starting Cloudflare Anti-Timeout & Keep-Alive Tests...\n'); + + // Set short delays for testing + config.keepAliveIntervalMs = 100; + config.nonStreamingKeepAliveDelayMs = 80; + + // 1. Create a mock upstream OpenAI-compatible server + let mockStreamDelay = 250; + let mockNonStreamDelay = 250; + + const mockUpstream = http.createServer((req, res) => { + let body = ''; + req.on('data', chunk => (body += chunk)); + req.on('end', () => { + const parsed = JSON.parse(body || '{}'); + if (parsed.stream) { + setTimeout(() => { + res.writeHead(200, { + 'Content-Type': 'text/event-stream', + 'Cache-Control': 'no-cache' + }); + res.write('data: {"choices":[{"delta":{"content":"Chunk 1"}}]}\n\n'); + setTimeout(() => { + res.write('data: {"choices":[{"delta":{"content":"Chunk 2"}}]}\n\n'); + res.write('data: [DONE]\n\n'); + res.end(); + }, 50); + }, mockStreamDelay); + } else { + setTimeout(() => { + res.writeHead(200, { 'Content-Type': 'application/json' }); + res.end( + JSON.stringify({ + id: 'chatcmpl-mock', + choices: [{ message: { role: 'assistant', content: 'Mock non-streaming answer' } }], + usage: { prompt_tokens: 5, completion_tokens: 5, total_tokens: 10 } + }) + ); + }, mockNonStreamDelay); + } + }); + }); + + await new Promise(resolve => mockUpstream.listen(0, resolve)); + const upstreamPort = (mockUpstream.address() as any).port; + const upstreamBaseUrl = `http://localhost:${upstreamPort}`; + + // 2. Start the GeminiRevolver server + const server = http.createServer(app); + await new Promise(resolve => server.listen(0, resolve)); + const port = (server.address() as any).port; + const baseUrl = `http://localhost:${port}`; + const validKey = config.apiPassword!; + + // 3. Register a test provider & custom model pointing to mock upstream + const testProv = configStore.saveProvider({ + name: 'Mock Upstream Provider', + type: 'custom', + baseUrl: upstreamBaseUrl, + keys: ['mock-api-key-123'] + }); + + const testModel = configStore.saveCustomModel({ + name: 'test-keepalive-model', + description: 'Testing anti-timeout features', + isDefault: false, + tiers: [ + { + tierIndex: 0, + name: 'Tier 0', + targets: [{ providerId: testProv.id, model: 'mock-model-v1' }] + } + ] + }); + + try { + // TEST 1: Streaming Keep-Alive & Anti-Buffering Headers + console.log('1. Testing SSE Headers & Keep-Alive Comments during slow TTFT...'); + const streamStart = Date.now(); + const streamResp = await fetch(`${baseUrl}/v1/chat/completions`, { + method: 'POST', + headers: { + 'Authorization': `Bearer ${validKey}`, + 'Content-Type': 'application/json' + }, + body: JSON.stringify({ + model: 'test-keepalive-model', + stream: true, + messages: [{ role: 'user', content: 'Hello slow stream' }] + }) + }); + + assert.strictEqual(streamResp.status, 200); + assert.strictEqual(streamResp.headers.get('content-type'), 'text/event-stream; charset=utf-8'); + assert.strictEqual(streamResp.headers.get('cache-control'), 'no-cache, no-transform'); + assert.strictEqual(streamResp.headers.get('connection'), 'keep-alive'); + assert.strictEqual(streamResp.headers.get('x-accel-buffering'), 'no'); + + const reader = streamResp.body!.getReader(); + const decoder = new TextDecoder(); + let streamChunks: string[] = []; + let receivedContent = ''; + + while (true) { + const { done, value } = await reader.read(); + if (done) break; + const text = decoder.decode(value); + streamChunks.push(text); + + const lines = text.split('\n'); + for (const line of lines) { + if (line.startsWith('data: ') && !line.includes('[DONE]')) { + try { + const parsed = JSON.parse(line.slice(6)); + if (parsed.choices?.[0]?.delta?.content) { + receivedContent += parsed.choices[0].delta.content; + } + } catch {} + } + } + } + + const fullRawStream = streamChunks.join(''); + assert.ok( + fullRawStream.includes(': keep-alive'), + 'Stream should contain SSE keep-alive comments before or between chunks' + ); + assert.strictEqual(receivedContent, 'Chunk 1Chunk 2', 'Stream content should be parsed accurately'); + console.log(' โœ“ SSE headers flushed immediately and : keep-alive heartbeats verified.'); + + // TEST 2: Non-Streaming Keep-Alive with Chunked Whitespace + console.log('\n2. Testing Non-Streaming Keep-Alive with chunked whitespace...'); + const nonStreamResp = await fetch(`${baseUrl}/v1/chat/completions`, { + method: 'POST', + headers: { + 'Authorization': `Bearer ${validKey}`, + 'Content-Type': 'application/json' + }, + body: JSON.stringify({ + model: 'test-keepalive-model', + stream: false, + messages: [{ role: 'user', content: 'Hello slow non-stream' }] + }) + }); + + assert.strictEqual(nonStreamResp.status, 200); + assert.strictEqual(nonStreamResp.headers.get('transfer-encoding'), 'chunked'); + assert.strictEqual(nonStreamResp.headers.get('x-accel-buffering'), 'no'); + + const nonStreamData = (await nonStreamResp.json()) as any; + assert.ok(nonStreamData.choices?.[0]?.message?.content); + assert.strictEqual( + nonStreamData.choices[0].message.content, + 'Mock non-streaming answer', + 'JSON should be parsed cleanly despite leading whitespace keep-alives' + ); + console.log(' โœ“ Non-streaming chunked whitespace keep-alive and RFC 8259 client parsing verified.'); + + // TEST 3: Fast Non-Streaming (< threshold) sends regular JSON + console.log('\n3. Testing Fast Non-Streaming (< delay threshold) preserves standard JSON...'); + mockNonStreamDelay = 10; // finish in 10ms (less than 80ms threshold) + const fastResp = await fetch(`${baseUrl}/v1/chat/completions`, { + method: 'POST', + headers: { + 'Authorization': `Bearer ${validKey}`, + 'Content-Type': 'application/json' + }, + body: JSON.stringify({ + model: 'test-keepalive-model', + stream: false, + messages: [{ role: 'user', content: 'Fast query' }] + }) + }); + + assert.strictEqual(fastResp.status, 200); + // Standard response without chunked transfer + assert.strictEqual(fastResp.headers.get('content-type'), 'application/json; charset=utf-8'); + const fastData = (await fastResp.json()) as any; + assert.strictEqual(fastData.choices[0].message.content, 'Mock non-streaming answer'); + console.log(' โœ“ Fast requests preserve standard non-chunked JSON responses.'); + + } finally { + // Cleanup + configStore.deleteCustomModel(testModel.id); + configStore.deleteProvider(testProv.id); + await new Promise(resolve => server.close(resolve)); + await new Promise(resolve => mockUpstream.close(resolve)); + } + + console.log('\n๐ŸŽ‰ ALL CLOUDFLARE ANTI-TIMEOUT TESTS PASSED SUCCESSFULLY!\n'); +} + +runKeepAliveTests().catch(err => { + console.error('โŒ Test failed:', err); + process.exit(1); +});