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); });