288 lines
11 KiB
TypeScript
288 lines
11 KiB
TypeScript
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;
|
|
let mockLongStreamMode = false;
|
|
|
|
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 && mockLongStreamMode) {
|
|
setTimeout(() => {
|
|
res.writeHead(200, {
|
|
'Content-Type': 'text/event-stream',
|
|
'Cache-Control': 'no-cache'
|
|
});
|
|
res.write('data: {"choices":[{"delta":{"reasoning_content":"Thinking..."}}]}\n\n');
|
|
|
|
let count = 0;
|
|
const interval = setInterval(() => {
|
|
count++;
|
|
res.write(`data: {"choices":[{"delta":{"content":"Part ${count}"}}]}\n\n`);
|
|
if (count >= 5) {
|
|
clearInterval(interval);
|
|
res.write('data: [DONE]\n\n');
|
|
res.end();
|
|
}
|
|
}, 80);
|
|
}, 50);
|
|
} else 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<void>(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<void>(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.');
|
|
|
|
// TEST 4: Long streaming generation exceeding candidateTimeoutMs succeeds
|
|
console.log('\n4. Testing Long Streaming Generation exceeding candidateTimeoutMs...');
|
|
const origCandidateTimeoutMs = config.candidateTimeoutMs;
|
|
const origStreamFirstTokenTimeoutMs = config.streamFirstTokenTimeoutMs;
|
|
config.candidateTimeoutMs = 200;
|
|
config.streamFirstTokenTimeoutMs = 150;
|
|
mockLongStreamMode = true;
|
|
|
|
try {
|
|
const longStart = Date.now();
|
|
const longResp = 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: 'Long high-token stream' }]
|
|
})
|
|
});
|
|
|
|
assert.strictEqual(longResp.status, 200);
|
|
const longReader = longResp.body!.getReader();
|
|
const longDecoder = new TextDecoder();
|
|
let receivedReasoning = '';
|
|
let receivedLongContent = '';
|
|
let sawDone = false;
|
|
|
|
while (true) {
|
|
const { done, value } = await longReader.read();
|
|
if (done) break;
|
|
const text = longDecoder.decode(value, { stream: true });
|
|
for (const line of text.split('\n')) {
|
|
const trimmed = line.trim();
|
|
if (!trimmed.startsWith('data: ')) continue;
|
|
const payload = trimmed.slice(6);
|
|
if (payload === '[DONE]') {
|
|
sawDone = true;
|
|
continue;
|
|
}
|
|
const parsed = JSON.parse(payload);
|
|
assert.ok(!parsed.error, `Stream should not emit error: ${JSON.stringify(parsed.error)}`);
|
|
if (parsed.choices?.[0]?.delta?.reasoning_content) {
|
|
receivedReasoning += parsed.choices[0].delta.reasoning_content;
|
|
}
|
|
if (parsed.choices?.[0]?.delta?.content) {
|
|
receivedLongContent += parsed.choices[0].delta.content;
|
|
}
|
|
}
|
|
}
|
|
|
|
const longDuration = Date.now() - longStart;
|
|
assert.ok(longDuration > config.candidateTimeoutMs, `Expected stream duration (${longDuration}ms) > candidateTimeoutMs (${config.candidateTimeoutMs}ms)`);
|
|
assert.strictEqual(receivedReasoning, 'Thinking...');
|
|
assert.strictEqual(receivedLongContent, 'Part 1Part 2Part 3Part 4Part 5');
|
|
assert.strictEqual(sawDone, true, 'Long stream should complete cleanly with [DONE]');
|
|
console.log(` ✓ Long streaming generation (${longDuration}ms > ${config.candidateTimeoutMs}ms) completed with reasoning and all content chunks.`);
|
|
} finally {
|
|
mockLongStreamMode = false;
|
|
config.candidateTimeoutMs = origCandidateTimeoutMs;
|
|
config.streamFirstTokenTimeoutMs = origStreamFirstTokenTimeoutMs;
|
|
}
|
|
|
|
} 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);
|
|
});
|