fix(engine): handle Content-Length mismatch, socket drops, and stream failover resilience
This commit is contained in:
parent
299c5f4c9e
commit
f558ef4c88
4 changed files with 526 additions and 61 deletions
|
|
@ -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 && API_PASSWORD=test_password ts-node test-timeout-keepalive.ts && API_PASSWORD=test_password ts-node test-live-watcher.ts && API_PASSWORD=test_password ts-node test-telemetry-fallback.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 && API_PASSWORD=test_password ts-node test-live-watcher.ts && API_PASSWORD=test_password ts-node test-telemetry-fallback.ts && API_PASSWORD=test_password ts-node test-content-length-resilience.ts"
|
||||
},
|
||||
"keywords": ["openai", "gemini", "api", "rotation"],
|
||||
"author": "",
|
||||
|
|
|
|||
|
|
@ -197,14 +197,47 @@ export class RevolverEngine {
|
|||
}
|
||||
|
||||
private isServerError(error: any): boolean {
|
||||
if (!error) return false;
|
||||
|
||||
const status = error?.status || error?.statusCode || error?.code;
|
||||
if (typeof status === 'number' && status >= 500 && status < 600) {
|
||||
return true;
|
||||
}
|
||||
|
||||
const networkCodes = [
|
||||
'ECONNRESET',
|
||||
'ETIMEDOUT',
|
||||
'ECONNREFUSED',
|
||||
'EPIPE',
|
||||
'ENOTFOUND',
|
||||
'EAI_AGAIN',
|
||||
'UND_ERR_SOCKET',
|
||||
'UND_ERR_RES_CONTENT_LENGTH_MISMATCH',
|
||||
'UND_ERR_REQ_CONTENT_LENGTH_MISMATCH',
|
||||
'UND_ERR_BODY_TIMEOUT',
|
||||
'UND_ERR_HEADERS_TIMEOUT',
|
||||
'UND_ERR_CONNECT_TIMEOUT'
|
||||
];
|
||||
|
||||
const errCode = error?.code || error?.cause?.code;
|
||||
if (errCode && networkCodes.includes(errCode)) {
|
||||
return true;
|
||||
}
|
||||
|
||||
const errName = error?.name || error?.cause?.name;
|
||||
if (errName === 'ResponseContentLengthMismatchError' || errName === 'SocketError') {
|
||||
return true;
|
||||
}
|
||||
|
||||
const msg = `${error?.message || ''} ${error?.cause?.message || ''}`.toLowerCase();
|
||||
return (
|
||||
status === 500 ||
|
||||
status === 502 ||
|
||||
status === 503 ||
|
||||
status === 504 ||
|
||||
status === 'ECONNRESET' ||
|
||||
status === 'ETIMEDOUT'
|
||||
msg.includes('content-length') ||
|
||||
msg.includes('fetch failed') ||
|
||||
msg.includes('terminated') ||
|
||||
msg.includes('other side closed') ||
|
||||
msg.includes('socket hung up') ||
|
||||
msg.includes('premature close') ||
|
||||
msg.includes('network error')
|
||||
);
|
||||
}
|
||||
|
||||
|
|
@ -485,13 +518,15 @@ export class RevolverEngine {
|
|||
res.write(JSON.stringify(responseData));
|
||||
res.end();
|
||||
} else {
|
||||
res.setHeader('Cache-Control', 'no-cache, no-transform');
|
||||
res.json(responseData);
|
||||
}
|
||||
return;
|
||||
}
|
||||
} catch (err: any) {
|
||||
lastError = err;
|
||||
console.error(`[REVOLVER] Candidate failed (Provider: '${candidate.provider.name}', Model: '${candidate.target.model}'):`, err.message);
|
||||
const detailedErrorMessage = err.cause?.message ? `${err.message}: ${err.cause.message}` : (err.message || 'Unknown candidate error');
|
||||
console.error(`[REVOLVER] Candidate failed (Provider: '${candidate.provider.name}', Model: '${candidate.target.model}'):`, detailedErrorMessage);
|
||||
|
||||
const stepDuration = Date.now() - candidateStart;
|
||||
const isRateLimit = this.isRateLimitOrQuotaError(err);
|
||||
|
|
@ -521,8 +556,8 @@ export class RevolverEngine {
|
|||
maskedKey: this.store.maskKey(candidate.keyConfig.key),
|
||||
durationMs: stepDuration,
|
||||
status: statusType,
|
||||
statusCode: err.status || (isRateLimit ? 429 : 500),
|
||||
errorMessage: err.message,
|
||||
statusCode: err.status || (isRateLimit ? 429 : (isServerErr ? 502 : 500)),
|
||||
errorMessage: detailedErrorMessage,
|
||||
rateLimitedUntil: cooldown ? Date.now() + cooldown : null,
|
||||
cooldownSeconds: cooldown ? Math.ceil(cooldown / 1000) : undefined,
|
||||
nextAction
|
||||
|
|
@ -557,7 +592,7 @@ export class RevolverEngine {
|
|||
if (!res.destroyed && !res.writableEnded) {
|
||||
res.write(`data: ${JSON.stringify({
|
||||
error: {
|
||||
message: err.message || 'Stream interrupted',
|
||||
message: detailedErrorMessage,
|
||||
type: 'server_error',
|
||||
code: 'stream_interrupted'
|
||||
}
|
||||
|
|
@ -756,14 +791,20 @@ export class RevolverEngine {
|
|||
method: 'POST',
|
||||
headers: {
|
||||
'Content-Type': 'application/json',
|
||||
'Authorization': `Bearer ${candidate.keyConfig.key}`
|
||||
'Authorization': `Bearer ${candidate.keyConfig.key}`,
|
||||
'Accept-Encoding': 'identity'
|
||||
},
|
||||
body: JSON.stringify(forwardedBody),
|
||||
signal: AbortSignal.timeout(config.candidateTimeoutMs)
|
||||
});
|
||||
|
||||
if (!response.ok) {
|
||||
const errBody = await response.text();
|
||||
let errBody = '';
|
||||
try {
|
||||
errBody = await response.text();
|
||||
} catch (readErr: any) {
|
||||
errBody = readErr.message || 'Failed to read error response';
|
||||
}
|
||||
let errorDetails = errBody;
|
||||
try {
|
||||
const parsed = JSON.parse(errBody);
|
||||
|
|
@ -774,7 +815,46 @@ export class RevolverEngine {
|
|||
throw err;
|
||||
}
|
||||
|
||||
const json = (await response.json()) as OpenAIChatResponse;
|
||||
if (!response.body) {
|
||||
throw new Error('Response body is null from provider.');
|
||||
}
|
||||
|
||||
// Safely consume response stream to handle premature connection termination or Content-Length mismatches gracefully
|
||||
let rawText = '';
|
||||
const reader = response.body.getReader();
|
||||
const decoder = new TextDecoder();
|
||||
let streamReadError: any = null;
|
||||
|
||||
try {
|
||||
while (true) {
|
||||
const { done, value } = await reader.read();
|
||||
if (done) break;
|
||||
if (value) {
|
||||
rawText += decoder.decode(value, { stream: true });
|
||||
}
|
||||
}
|
||||
rawText += decoder.decode();
|
||||
} catch (readErr: any) {
|
||||
streamReadError = readErr;
|
||||
}
|
||||
|
||||
let json: OpenAIChatResponse | null = null;
|
||||
if (rawText.trim()) {
|
||||
try {
|
||||
json = JSON.parse(rawText.trim()) as OpenAIChatResponse;
|
||||
} catch (parseErr) {
|
||||
// If JSON parsing fails and stream had a read error, re-throw the stream read error
|
||||
if (streamReadError) {
|
||||
throw streamReadError;
|
||||
}
|
||||
throw new Error(`Invalid JSON received from provider: ${parseErr instanceof Error ? parseErr.message : String(parseErr)}`);
|
||||
}
|
||||
} else if (streamReadError) {
|
||||
throw streamReadError;
|
||||
} else {
|
||||
throw new Error('Empty response body received from provider.');
|
||||
}
|
||||
|
||||
// Overwrite returned model with requestedModelName for client fidelity
|
||||
json.model = requestedModelName;
|
||||
if (!json.id) {
|
||||
|
|
@ -963,14 +1043,20 @@ export class RevolverEngine {
|
|||
method: 'POST',
|
||||
headers: {
|
||||
'Content-Type': 'application/json',
|
||||
'Authorization': `Bearer ${candidate.keyConfig.key}`
|
||||
'Authorization': `Bearer ${candidate.keyConfig.key}`,
|
||||
'Accept-Encoding': 'identity'
|
||||
},
|
||||
body: JSON.stringify(forwardedBody),
|
||||
signal: AbortSignal.timeout(config.candidateTimeoutMs)
|
||||
});
|
||||
|
||||
if (!response.ok) {
|
||||
const errBody = await response.text();
|
||||
let errBody = '';
|
||||
try {
|
||||
errBody = await response.text();
|
||||
} catch (readErr: any) {
|
||||
errBody = readErr.message || 'Failed to read error response';
|
||||
}
|
||||
let errorDetails = errBody;
|
||||
try {
|
||||
const parsed = JSON.parse(errBody);
|
||||
|
|
@ -1001,54 +1087,52 @@ export class RevolverEngine {
|
|||
let buffer = '';
|
||||
let totalOutputChars = 0;
|
||||
|
||||
try {
|
||||
while (true) {
|
||||
if (res.destroyed) break;
|
||||
const { done, value } = await reader.read();
|
||||
if (done) break;
|
||||
while (true) {
|
||||
if (res.destroyed) break;
|
||||
const { done, value } = await reader.read();
|
||||
if (done) break;
|
||||
|
||||
const text = decoder.decode(value, { stream: true });
|
||||
buffer += text;
|
||||
const text = decoder.decode(value, { stream: true });
|
||||
buffer += text;
|
||||
|
||||
const lines = buffer.split('\n');
|
||||
buffer = lines.pop() || '';
|
||||
const lines = buffer.split('\n');
|
||||
buffer = lines.pop() || '';
|
||||
|
||||
for (const line of lines) {
|
||||
const trimmed = line.trim();
|
||||
if (!trimmed) {
|
||||
res.write('\n');
|
||||
for (const line of lines) {
|
||||
const trimmed = line.trim();
|
||||
if (!trimmed) {
|
||||
res.write('\n');
|
||||
continue;
|
||||
}
|
||||
|
||||
if (trimmed.startsWith('data: ')) {
|
||||
const dataStr = trimmed.slice(6);
|
||||
if (dataStr === '[DONE]') {
|
||||
res.write('data: [DONE]\n\n');
|
||||
continue;
|
||||
}
|
||||
|
||||
if (trimmed.startsWith('data: ')) {
|
||||
const dataStr = trimmed.slice(6);
|
||||
if (dataStr === '[DONE]') {
|
||||
res.write('data: [DONE]\n\n');
|
||||
continue;
|
||||
try {
|
||||
const parsed = JSON.parse(dataStr);
|
||||
parsed.model = requestedModelName;
|
||||
if (parsed.choices?.[0]?.delta?.content) {
|
||||
onStreamStart();
|
||||
const delta = parsed.choices[0].delta.content;
|
||||
totalOutputChars += delta.length;
|
||||
liveWatcher.appendStreamChunk(requestId, delta);
|
||||
}
|
||||
|
||||
try {
|
||||
const parsed = JSON.parse(dataStr);
|
||||
parsed.model = requestedModelName;
|
||||
if (parsed.choices?.[0]?.delta?.content) {
|
||||
onStreamStart();
|
||||
const delta = parsed.choices[0].delta.content;
|
||||
totalOutputChars += delta.length;
|
||||
liveWatcher.appendStreamChunk(requestId, delta);
|
||||
}
|
||||
res.write(`data: ${JSON.stringify(parsed)}\n\n`);
|
||||
} catch {
|
||||
res.write(`${line}\n`);
|
||||
}
|
||||
} else {
|
||||
res.write(`data: ${JSON.stringify(parsed)}\n\n`);
|
||||
} catch {
|
||||
res.write(`${line}\n`);
|
||||
}
|
||||
} else {
|
||||
res.write(`${line}\n`);
|
||||
}
|
||||
}
|
||||
} finally {
|
||||
if (!res.destroyed) {
|
||||
res.end();
|
||||
}
|
||||
}
|
||||
|
||||
if (!res.destroyed && !res.writableEnded) {
|
||||
res.end();
|
||||
}
|
||||
|
||||
const estimatedInput = Math.ceil(JSON.stringify(requestBody.messages).length / 4);
|
||||
|
|
@ -1145,9 +1229,10 @@ export class RevolverEngine {
|
|||
} catch (err: any) {
|
||||
lastError = err;
|
||||
const isRateLimit = this.isRateLimitOrQuotaError(err);
|
||||
if (isRateLimit) {
|
||||
const isServerErr = this.isServerError(err);
|
||||
if (isRateLimit || isServerErr) {
|
||||
this.store.updateKeyStats(candidate.provider.id, candidate.keyConfig.key, {
|
||||
rateLimitedUntil: Date.now() + config.rateLimitDurationMs,
|
||||
rateLimitedUntil: Date.now() + (isRateLimit ? config.rateLimitDurationMs : 15000),
|
||||
incrementError: true
|
||||
});
|
||||
}
|
||||
|
|
@ -1190,7 +1275,8 @@ export class RevolverEngine {
|
|||
method: 'POST',
|
||||
headers: {
|
||||
'Content-Type': 'application/json',
|
||||
'Authorization': `Bearer ${params.key}`
|
||||
'Authorization': `Bearer ${params.key}`,
|
||||
'Accept-Encoding': 'identity'
|
||||
},
|
||||
body: JSON.stringify({
|
||||
model,
|
||||
|
|
@ -1200,11 +1286,16 @@ export class RevolverEngine {
|
|||
});
|
||||
|
||||
if (!res.ok) {
|
||||
const body = await res.text();
|
||||
let errText = body;
|
||||
let errBody = '';
|
||||
try {
|
||||
const parsed = JSON.parse(body);
|
||||
errText = parsed.error?.message || body;
|
||||
errBody = await res.text();
|
||||
} catch (readErr: any) {
|
||||
errBody = readErr.message || 'Failed to read error response';
|
||||
}
|
||||
let errText = errBody;
|
||||
try {
|
||||
const parsed = JSON.parse(errBody);
|
||||
errText = parsed.error?.message || errBody;
|
||||
} catch {}
|
||||
return {
|
||||
success: false,
|
||||
|
|
@ -1222,10 +1313,11 @@ export class RevolverEngine {
|
|||
};
|
||||
}
|
||||
} catch (err: any) {
|
||||
const detailedMsg = err.cause?.message ? `${err.message}: ${err.cause.message}` : (err.message || 'Connection failed');
|
||||
return {
|
||||
success: false,
|
||||
latencyMs: Date.now() - start,
|
||||
message: err.message || 'Connection failed'
|
||||
message: detailedMsg
|
||||
};
|
||||
}
|
||||
}
|
||||
|
|
|
|||
|
|
@ -136,6 +136,7 @@ router.post('/v1/chat/completions', async (req: Request, res: Response) => {
|
|||
});
|
||||
|
||||
if (!res.headersSent) {
|
||||
res.setHeader('Cache-Control', 'no-cache, no-transform');
|
||||
res.status(error.status || 500).json({
|
||||
error: {
|
||||
message: error.message || 'Internal server error',
|
||||
|
|
@ -144,6 +145,13 @@ router.post('/v1/chat/completions', async (req: Request, res: Response) => {
|
|||
}
|
||||
});
|
||||
} else if (!res.writableEnded) {
|
||||
res.write(JSON.stringify({
|
||||
error: {
|
||||
message: error.message || 'Internal server error',
|
||||
type: 'server_error',
|
||||
code: 'internal_error'
|
||||
}
|
||||
}));
|
||||
res.end();
|
||||
}
|
||||
}
|
||||
|
|
|
|||
365
test-content-length-resilience.ts
Normal file
365
test-content-length-resilience.ts
Normal file
|
|
@ -0,0 +1,365 @@
|
|||
import http from 'http';
|
||||
import assert from 'assert';
|
||||
import app from './src/index';
|
||||
import { revolverEngine } from './src/revolverEngine';
|
||||
import { configStore } from './src/configStore';
|
||||
import { telemetryTracker } from './src/telemetryTracker';
|
||||
|
||||
const PORT = 3999;
|
||||
const API_KEY = 'test_password';
|
||||
|
||||
console.log('🧪 Starting Content-Length Resilience & Upstream Failover Test Suite...\n');
|
||||
|
||||
async function runTests() {
|
||||
const server = http.createServer(app);
|
||||
await new Promise<void>((resolve) => server.listen(PORT, resolve));
|
||||
|
||||
const createdModelIds: string[] = [];
|
||||
const createdProviderIds: string[] = [];
|
||||
|
||||
try {
|
||||
// =========================================================================
|
||||
// Test 1: Unit Test isServerError() logic via revolverEngine private access
|
||||
// =========================================================================
|
||||
console.log('1. Testing isServerError detection across all Content-Length and socket error variants...');
|
||||
|
||||
const isServerErrorFn = (revolverEngine as any).isServerError.bind(revolverEngine);
|
||||
|
||||
// 1.1 HTTP 5xx codes
|
||||
assert.strictEqual(isServerErrorFn({ status: 500 }), true, '500 should be server error');
|
||||
assert.strictEqual(isServerErrorFn({ status: 502 }), true, '502 should be server error');
|
||||
assert.strictEqual(isServerErrorFn({ status: 503 }), true, '503 should be server error');
|
||||
assert.strictEqual(isServerErrorFn({ statusCode: 504 }), true, '504 should be server error');
|
||||
|
||||
// 1.2 Undici Content-Length Mismatch Errors
|
||||
const undiciContentLengthErr = new TypeError('fetch failed');
|
||||
(undiciContentLengthErr as any).cause = {
|
||||
name: 'ResponseContentLengthMismatchError',
|
||||
code: 'UND_ERR_RES_CONTENT_LENGTH_MISMATCH',
|
||||
message: 'Response body length does not match content-length header'
|
||||
};
|
||||
assert.strictEqual(isServerErrorFn(undiciContentLengthErr), true, 'UND_ERR_RES_CONTENT_LENGTH_MISMATCH must be server error');
|
||||
|
||||
// 1.3 Exact string from prompt: Content-Length header of network response exceeds response Body.
|
||||
const exactPromptErr = new TypeError('fetch failed');
|
||||
(exactPromptErr as any).cause = new Error('Content-Length header of network response exceeds response Body.');
|
||||
assert.strictEqual(isServerErrorFn(exactPromptErr), true, 'Exact Content-Length mismatch string must be server error');
|
||||
|
||||
// 1.4 Socket closed prematurely (UND_ERR_SOCKET / other side closed)
|
||||
const undiciSocketErr = new TypeError('fetch failed');
|
||||
(undiciSocketErr as any).cause = {
|
||||
name: 'SocketError',
|
||||
code: 'UND_ERR_SOCKET',
|
||||
message: 'other side closed'
|
||||
};
|
||||
assert.strictEqual(isServerErrorFn(undiciSocketErr), true, 'UND_ERR_SOCKET other side closed must be server error');
|
||||
|
||||
// 1.5 Node standard network errors
|
||||
assert.strictEqual(isServerErrorFn({ code: 'ECONNRESET' }), true, 'ECONNRESET must be server error');
|
||||
assert.strictEqual(isServerErrorFn({ code: 'ETIMEDOUT' }), true, 'ETIMEDOUT must be server error');
|
||||
assert.strictEqual(isServerErrorFn({ code: 'ECONNREFUSED' }), true, 'ECONNREFUSED must be server error');
|
||||
|
||||
// 1.6 Client errors that should NOT be server error
|
||||
assert.strictEqual(isServerErrorFn({ status: 400 }), false, '400 must NOT be server error');
|
||||
assert.strictEqual(isServerErrorFn({ status: 401 }), false, '401 must NOT be server error');
|
||||
assert.strictEqual(isServerErrorFn({ status: 404 }), false, '404 must NOT be server error');
|
||||
assert.strictEqual(isServerErrorFn({ status: 429 }), false, '429 must NOT be server error (handled as rate limit)');
|
||||
|
||||
console.log(' ✓ isServerError accurately identifies undici/network/Content-Length mismatch errors.\n');
|
||||
|
||||
// =========================================================================
|
||||
// Test 2: Non-Streaming: Recovery of valid JSON when upstream claims inflated Content-Length
|
||||
// =========================================================================
|
||||
console.log('2. Testing Non-Streaming recovery when upstream returns valid JSON but terminates with Content-Length mismatch...');
|
||||
|
||||
const validJsonPayload = {
|
||||
id: 'chatcmpl-recovered-123',
|
||||
object: 'chat.completion',
|
||||
created: Math.floor(Date.now() / 1000),
|
||||
model: 'resilient-model',
|
||||
choices: [
|
||||
{
|
||||
index: 0,
|
||||
message: { role: 'assistant', content: 'Successfully parsed even with Content-Length header mismatch!' },
|
||||
finish_reason: 'stop'
|
||||
}
|
||||
],
|
||||
usage: { prompt_tokens: 10, completion_tokens: 12, total_tokens: 22 }
|
||||
};
|
||||
const validJsonStr = JSON.stringify(validJsonPayload);
|
||||
|
||||
// Mock server returns Content-Length: 5000, writes only ~250 bytes, then abruptly closes
|
||||
const mockMismatchedServer = http.createServer((req, res) => {
|
||||
res.writeHead(200, {
|
||||
'Content-Type': 'application/json',
|
||||
'Content-Length': '5000' // Inflated Content-Length
|
||||
});
|
||||
res.write(validJsonStr);
|
||||
// Abruptly destroy socket to trigger Content-Length mismatch on standard client
|
||||
setTimeout(() => {
|
||||
res.destroy();
|
||||
}, 50);
|
||||
});
|
||||
await new Promise<void>((resolve) => mockMismatchedServer.listen(0, resolve));
|
||||
const mismatchPort = (mockMismatchedServer.address() as any).port;
|
||||
|
||||
// Create provider with the mock server URL
|
||||
const p1 = configStore.saveProvider({
|
||||
name: 'Mismatched Content-Length Provider',
|
||||
type: 'custom',
|
||||
baseUrl: `http://localhost:${mismatchPort}`,
|
||||
keys: ['mock-key-1']
|
||||
});
|
||||
createdProviderIds.push(p1.id);
|
||||
|
||||
const m1 = configStore.saveCustomModel({
|
||||
name: 'model-mismatch-recovery',
|
||||
tiers: [
|
||||
{
|
||||
tierIndex: 0,
|
||||
name: 'Tier 0',
|
||||
targets: [{ providerId: p1.id, model: 'mismatch-model' }]
|
||||
}
|
||||
]
|
||||
});
|
||||
createdModelIds.push(m1.id);
|
||||
|
||||
// Make non-streaming request to Revolver
|
||||
const req1 = await fetch(`http://localhost:${PORT}/v1/chat/completions`, {
|
||||
method: 'POST',
|
||||
headers: {
|
||||
'Content-Type': 'application/json',
|
||||
'Authorization': `Bearer ${API_KEY}`
|
||||
},
|
||||
body: JSON.stringify({
|
||||
model: 'model-mismatch-recovery',
|
||||
messages: [{ role: 'user', content: 'Test prompt' }],
|
||||
stream: false
|
||||
})
|
||||
});
|
||||
|
||||
assert.strictEqual(req1.status, 200, `Expected 200 OK, got ${req1.status}`);
|
||||
const data1 = (await req1.json()) as any;
|
||||
assert.strictEqual(data1.choices[0].message.content, 'Successfully parsed even with Content-Length header mismatch!');
|
||||
console.log(' ✓ Revolver recovered full valid JSON payload despite upstream Content-Length mismatch.\n');
|
||||
|
||||
mockMismatchedServer.close();
|
||||
|
||||
// =========================================================================
|
||||
// Test 3: Non-Streaming: Failover to Candidate 2 when upstream terminates with truly corrupted/truncated JSON
|
||||
// =========================================================================
|
||||
console.log('3. Testing Non-Streaming failover to Candidate 2 when Candidate 1 drops with truncated broken JSON...');
|
||||
|
||||
// Server 1 returns truncated broken JSON and closes socket
|
||||
const mockCorruptedServer = http.createServer((req, res) => {
|
||||
res.writeHead(200, {
|
||||
'Content-Type': 'application/json',
|
||||
'Content-Length': '500'
|
||||
});
|
||||
res.write('{"choices": [{"message": {"content": "Truncated cut-off');
|
||||
setTimeout(() => {
|
||||
res.destroy();
|
||||
}, 30);
|
||||
});
|
||||
await new Promise<void>((resolve) => mockCorruptedServer.listen(0, resolve));
|
||||
const corruptPort = (mockCorruptedServer.address() as any).port;
|
||||
|
||||
// Server 2 returns valid 200 response
|
||||
const mockHealthyServer = http.createServer((req, res) => {
|
||||
res.writeHead(200, { 'Content-Type': 'application/json' });
|
||||
res.end(JSON.stringify({
|
||||
id: 'chatcmpl-healthy-candidate',
|
||||
object: 'chat.completion',
|
||||
created: Math.floor(Date.now() / 1000),
|
||||
model: 'healthy-model',
|
||||
choices: [
|
||||
{
|
||||
index: 0,
|
||||
message: { role: 'assistant', content: 'Candidate 2 saved the day!' },
|
||||
finish_reason: 'stop'
|
||||
}
|
||||
],
|
||||
usage: { prompt_tokens: 5, completion_tokens: 8, total_tokens: 13 }
|
||||
}));
|
||||
});
|
||||
await new Promise<void>((resolve) => mockHealthyServer.listen(0, resolve));
|
||||
const healthyPort = (mockHealthyServer.address() as any).port;
|
||||
|
||||
const pCorrupt = configStore.saveProvider({
|
||||
name: 'Corrupted Provider',
|
||||
type: 'custom',
|
||||
baseUrl: `http://localhost:${corruptPort}`,
|
||||
keys: ['corrupt-key']
|
||||
});
|
||||
createdProviderIds.push(pCorrupt.id);
|
||||
|
||||
const pHealthy = configStore.saveProvider({
|
||||
name: 'Healthy Provider',
|
||||
type: 'custom',
|
||||
baseUrl: `http://localhost:${healthyPort}`,
|
||||
keys: ['healthy-key']
|
||||
});
|
||||
createdProviderIds.push(pHealthy.id);
|
||||
|
||||
const mFailover = configStore.saveCustomModel({
|
||||
name: 'model-failover-test',
|
||||
tiers: [
|
||||
{
|
||||
tierIndex: 0,
|
||||
name: 'Tier 0',
|
||||
targets: [
|
||||
{ providerId: pCorrupt.id, model: 'corrupt-model' },
|
||||
{ providerId: pHealthy.id, model: 'healthy-model' }
|
||||
]
|
||||
}
|
||||
]
|
||||
});
|
||||
createdModelIds.push(mFailover.id);
|
||||
|
||||
const req2 = await fetch(`http://localhost:${PORT}/v1/chat/completions`, {
|
||||
method: 'POST',
|
||||
headers: {
|
||||
'Content-Type': 'application/json',
|
||||
'Authorization': `Bearer ${API_KEY}`
|
||||
},
|
||||
body: JSON.stringify({
|
||||
model: 'model-failover-test',
|
||||
messages: [{ role: 'user', content: 'Failover please' }],
|
||||
stream: false
|
||||
})
|
||||
});
|
||||
|
||||
assert.strictEqual(req2.status, 200, `Expected 200 OK after failover, got ${req2.status}`);
|
||||
const data2 = (await req2.json()) as any;
|
||||
assert.strictEqual(data2.choices[0].message.content, 'Candidate 2 saved the day!');
|
||||
|
||||
// Verify Telemetry Tracker recorded candidate 1 failure and candidate 2 success
|
||||
const latestJourneys = telemetryTracker.getRecentJourneys(1);
|
||||
assert.strictEqual(latestJourneys.length, 1);
|
||||
const j = latestJourneys[0];
|
||||
assert.strictEqual(j.finalStatus, 'success_fallback');
|
||||
assert.strictEqual(j.steps.length, 2);
|
||||
assert.strictEqual(j.steps[0].status, 'server_error');
|
||||
assert.strictEqual(j.steps[1].status, 'success');
|
||||
console.log(' ✓ Revolver detected socket truncation, marked candidate 1 with server_error, and served via candidate 2.\n');
|
||||
|
||||
mockCorruptedServer.close();
|
||||
mockHealthyServer.close();
|
||||
|
||||
// =========================================================================
|
||||
// Test 4: Streaming: Failover to Candidate 2 when Candidate 1 drops stream before first token
|
||||
// =========================================================================
|
||||
console.log('4. Testing Streaming failover to Candidate 2 when Candidate 1 terminates stream prematurely...');
|
||||
|
||||
// Stream Server 1: Sends SSE 200 OK headers, but immediately destroys socket before data
|
||||
const mockStreamCorrupt = http.createServer((req, res) => {
|
||||
res.writeHead(200, {
|
||||
'Content-Type': 'text/event-stream',
|
||||
'Cache-Control': 'no-cache',
|
||||
'Connection': 'keep-alive'
|
||||
});
|
||||
setTimeout(() => {
|
||||
res.destroy();
|
||||
}, 30);
|
||||
});
|
||||
await new Promise<void>((resolve) => mockStreamCorrupt.listen(0, resolve));
|
||||
const streamCorruptPort = (mockStreamCorrupt.address() as any).port;
|
||||
|
||||
// Stream Server 2: Sends proper SSE chunks and [DONE]
|
||||
const mockStreamHealthy = http.createServer((req, res) => {
|
||||
res.writeHead(200, {
|
||||
'Content-Type': 'text/event-stream',
|
||||
'Cache-Control': 'no-cache',
|
||||
'Connection': 'keep-alive'
|
||||
});
|
||||
res.write(`data: ${JSON.stringify({
|
||||
id: 'chatcmpl-stream-healthy',
|
||||
object: 'chat.completion.chunk',
|
||||
created: Math.floor(Date.now() / 1000),
|
||||
model: 'healthy-stream-model',
|
||||
choices: [{ index: 0, delta: { content: 'Streaming seamless failover succeeded!' }, finish_reason: null }]
|
||||
})}\n\n`);
|
||||
res.write('data: [DONE]\n\n');
|
||||
res.end();
|
||||
});
|
||||
await new Promise<void>((resolve) => mockStreamHealthy.listen(0, resolve));
|
||||
const streamHealthyPort = (mockStreamHealthy.address() as any).port;
|
||||
|
||||
const pStreamCorrupt = configStore.saveProvider({
|
||||
name: 'Stream Corrupt Provider',
|
||||
type: 'custom',
|
||||
baseUrl: `http://localhost:${streamCorruptPort}`,
|
||||
keys: ['stream-key-1']
|
||||
});
|
||||
createdProviderIds.push(pStreamCorrupt.id);
|
||||
|
||||
const pStreamHealthy = configStore.saveProvider({
|
||||
name: 'Stream Healthy Provider',
|
||||
type: 'custom',
|
||||
baseUrl: `http://localhost:${streamHealthyPort}`,
|
||||
keys: ['stream-key-2']
|
||||
});
|
||||
createdProviderIds.push(pStreamHealthy.id);
|
||||
|
||||
const mStreamFailover = configStore.saveCustomModel({
|
||||
name: 'model-stream-failover-test',
|
||||
tiers: [
|
||||
{
|
||||
tierIndex: 0,
|
||||
name: 'Tier 0',
|
||||
targets: [
|
||||
{ providerId: pStreamCorrupt.id, model: 'corrupt-stream' },
|
||||
{ providerId: pStreamHealthy.id, model: 'healthy-stream' }
|
||||
]
|
||||
}
|
||||
]
|
||||
});
|
||||
createdModelIds.push(mStreamFailover.id);
|
||||
|
||||
const req3 = await fetch(`http://localhost:${PORT}/v1/chat/completions`, {
|
||||
method: 'POST',
|
||||
headers: {
|
||||
'Content-Type': 'application/json',
|
||||
'Authorization': `Bearer ${API_KEY}`
|
||||
},
|
||||
body: JSON.stringify({
|
||||
model: 'model-stream-failover-test',
|
||||
messages: [{ role: 'user', content: 'Stream failover please' }],
|
||||
stream: true
|
||||
})
|
||||
});
|
||||
|
||||
assert.strictEqual(req3.status, 200, `Expected 200 OK for stream, got ${req3.status}`);
|
||||
const streamBody = await req3.text();
|
||||
assert.ok(streamBody.includes('Streaming seamless failover succeeded!'), 'Stream body must contain content from Candidate 2');
|
||||
assert.ok(streamBody.includes('[DONE]'), 'Stream body must end with [DONE]');
|
||||
console.log(' ✓ Revolver caught stream drop on candidate 1 and cleanly streamed candidate 2 to client.\n');
|
||||
|
||||
mockStreamCorrupt.close();
|
||||
mockStreamHealthy.close();
|
||||
|
||||
// =========================================================================
|
||||
// Test 5: Verify Cache-Control: no-cache, no-transform header is sent downstream
|
||||
// =========================================================================
|
||||
console.log('5. Testing downstream Cache-Control: no-cache, no-transform headers...');
|
||||
const cacheHeader = req1.headers.get('cache-control');
|
||||
assert.ok(cacheHeader && cacheHeader.includes('no-transform'), 'Downstream response must include no-transform to prevent proxy compression mismatches');
|
||||
console.log(' ✓ Cache-Control: no-cache, no-transform verified on downstream responses.\n');
|
||||
|
||||
console.log('🎉 ALL CONTENT-LENGTH RESILIENCE & FAILOVER TESTS PASSED SUCCESSFULLY!\n');
|
||||
|
||||
} finally {
|
||||
for (const mId of createdModelIds) {
|
||||
try { configStore.deleteCustomModel(mId); } catch {}
|
||||
}
|
||||
for (const pId of createdProviderIds) {
|
||||
try { configStore.deleteProvider(pId); } catch {}
|
||||
}
|
||||
server.close();
|
||||
}
|
||||
}
|
||||
|
||||
runTests().catch((err) => {
|
||||
console.error('❌ Test suite failed:', err);
|
||||
process.exit(1);
|
||||
});
|
||||
Loading…
Add table
Add a link
Reference in a new issue