Merge branch 'main' into fix_fallback_timeout_latency
This commit is contained in:
commit
e860faba14
5 changed files with 499 additions and 28 deletions
|
|
@ -8,7 +8,7 @@
|
||||||
"start": "node dist/index.js",
|
"start": "node dist/index.js",
|
||||||
"dev": "ts-node src/index.ts",
|
"dev": "ts-node src/index.ts",
|
||||||
"watch": "tsc --watch",
|
"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 && API_PASSWORD=test_password ts-node test-circuit-breaker-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 && API_PASSWORD=test_password ts-node test-circuit-breaker-fallback.ts"
|
||||||
},
|
},
|
||||||
"keywords": ["openai", "gemini", "api", "rotation"],
|
"keywords": ["openai", "gemini", "api", "rotation"],
|
||||||
"author": "",
|
"author": "",
|
||||||
|
|
|
||||||
|
|
@ -391,7 +391,7 @@ export class LiveWatcher {
|
||||||
}): void {
|
}): void {
|
||||||
if (!this.isWatcherActive) return;
|
if (!this.isWatcherActive) return;
|
||||||
const entry = this.buffer.find(e => e.id === params.requestId);
|
const entry = this.buffer.find(e => e.id === params.requestId);
|
||||||
if (!entry) return;
|
if (!entry || (entry.endTime !== undefined && entry.status === 'completed')) return;
|
||||||
|
|
||||||
entry.endTime = Date.now();
|
entry.endTime = Date.now();
|
||||||
entry.durationMs = entry.endTime - entry.startTime;
|
entry.durationMs = entry.endTime - entry.startTime;
|
||||||
|
|
@ -426,7 +426,7 @@ export class LiveWatcher {
|
||||||
public cancelRequest(requestId: string): void {
|
public cancelRequest(requestId: string): void {
|
||||||
if (!this.isWatcherActive) return;
|
if (!this.isWatcherActive) return;
|
||||||
const entry = this.buffer.find(e => e.id === requestId);
|
const entry = this.buffer.find(e => e.id === requestId);
|
||||||
if (!entry) return;
|
if (!entry || entry.endTime !== undefined) return;
|
||||||
|
|
||||||
entry.endTime = Date.now();
|
entry.endTime = Date.now();
|
||||||
entry.durationMs = entry.endTime - entry.startTime;
|
entry.durationMs = entry.endTime - entry.startTime;
|
||||||
|
|
|
||||||
|
|
@ -80,7 +80,7 @@ export class RevolverEngine {
|
||||||
return Date.now() < keyConfig.rateLimitedUntil;
|
return Date.now() < keyConfig.rateLimitedUntil;
|
||||||
}
|
}
|
||||||
|
|
||||||
public getCandidatesForTier(tier: FallbackTier, modelId: string, allowCooldownProbes = false): CandidateExecution[] {
|
public getCandidatesForTier(tier: FallbackTier, modelId: string, allowCooldownProbes = false, advancePointer = true): CandidateExecution[] {
|
||||||
const candidates: CandidateExecution[] = [];
|
const candidates: CandidateExecution[] = [];
|
||||||
|
|
||||||
for (const target of tier.targets) {
|
for (const target of tier.targets) {
|
||||||
|
|
@ -114,7 +114,9 @@ export class RevolverEngine {
|
||||||
if (available.length > 0) {
|
if (available.length > 0) {
|
||||||
// Rotate starting from pointer
|
// Rotate starting from pointer
|
||||||
const startIdx = pointer % available.length;
|
const startIdx = pointer % available.length;
|
||||||
this.roundRobinPointers.set(tierKey, (startIdx + 1) % available.length);
|
if (advancePointer) {
|
||||||
|
this.roundRobinPointers.set(tierKey, (startIdx + 1) % available.length);
|
||||||
|
}
|
||||||
return [
|
return [
|
||||||
...available.slice(startIdx),
|
...available.slice(startIdx),
|
||||||
...available.slice(0, startIdx)
|
...available.slice(0, startIdx)
|
||||||
|
|
@ -203,14 +205,47 @@ export class RevolverEngine {
|
||||||
}
|
}
|
||||||
|
|
||||||
private isServerError(error: any): boolean {
|
private isServerError(error: any): boolean {
|
||||||
|
if (!error) return false;
|
||||||
|
|
||||||
const status = error?.status || error?.statusCode || error?.code;
|
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 (
|
return (
|
||||||
status === 500 ||
|
msg.includes('content-length') ||
|
||||||
status === 502 ||
|
msg.includes('fetch failed') ||
|
||||||
status === 503 ||
|
msg.includes('terminated') ||
|
||||||
status === 504 ||
|
msg.includes('other side closed') ||
|
||||||
status === 'ECONNRESET' ||
|
msg.includes('socket hung up') ||
|
||||||
status === 'ETIMEDOUT'
|
msg.includes('premature close') ||
|
||||||
|
msg.includes('network error')
|
||||||
);
|
);
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|
@ -328,7 +363,7 @@ export class RevolverEngine {
|
||||||
// Check if any healthy candidates exist across all tiers (or if all targets are in cooldown)
|
// Check if any healthy candidates exist across all tiers (or if all targets are in cooldown)
|
||||||
let hasAvailableCandidateAcrossTiers = false;
|
let hasAvailableCandidateAcrossTiers = false;
|
||||||
for (const t of sortedTiers) {
|
for (const t of sortedTiers) {
|
||||||
if (this.getCandidatesForTier(t, customModel.id, false).length > 0) {
|
if (this.getCandidatesForTier(t, customModel.id, false, false).length > 0) {
|
||||||
hasAvailableCandidateAcrossTiers = true;
|
hasAvailableCandidateAcrossTiers = true;
|
||||||
break;
|
break;
|
||||||
}
|
}
|
||||||
|
|
@ -522,13 +557,15 @@ export class RevolverEngine {
|
||||||
res.write(JSON.stringify(responseData));
|
res.write(JSON.stringify(responseData));
|
||||||
res.end();
|
res.end();
|
||||||
} else {
|
} else {
|
||||||
|
res.setHeader('Cache-Control', 'no-cache, no-transform');
|
||||||
res.json(responseData);
|
res.json(responseData);
|
||||||
}
|
}
|
||||||
return;
|
return;
|
||||||
}
|
}
|
||||||
} catch (err: any) {
|
} catch (err: any) {
|
||||||
lastError = err;
|
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 stepDuration = Date.now() - candidateStart;
|
||||||
const isRateLimit = this.isRateLimitOrQuotaError(err);
|
const isRateLimit = this.isRateLimitOrQuotaError(err);
|
||||||
|
|
@ -602,8 +639,8 @@ export class RevolverEngine {
|
||||||
maskedKey: this.store.maskKey(candidate.keyConfig.key),
|
maskedKey: this.store.maskKey(candidate.keyConfig.key),
|
||||||
durationMs: stepDuration,
|
durationMs: stepDuration,
|
||||||
status: statusType,
|
status: statusType,
|
||||||
statusCode: err.status || (isRateLimit ? 429 : (isTimeout ? 504 : 500)),
|
statusCode: err.status || (isRateLimit ? 429 : (isTimeout ? 504 : (isServerErr ? 502 : 500))),
|
||||||
errorMessage: err.message,
|
errorMessage: detailedErrorMessage,
|
||||||
rateLimitedUntil: isRateLimit ? Date.now() + config.rateLimitDurationMs : null,
|
rateLimitedUntil: isRateLimit ? Date.now() + config.rateLimitDurationMs : null,
|
||||||
cooldownSeconds: cooldownSecs,
|
cooldownSeconds: cooldownSecs,
|
||||||
nextAction
|
nextAction
|
||||||
|
|
@ -638,7 +675,7 @@ export class RevolverEngine {
|
||||||
if (!res.destroyed && !res.writableEnded) {
|
if (!res.destroyed && !res.writableEnded) {
|
||||||
res.write(`data: ${JSON.stringify({
|
res.write(`data: ${JSON.stringify({
|
||||||
error: {
|
error: {
|
||||||
message: err.message || 'Stream interrupted',
|
message: detailedErrorMessage,
|
||||||
type: 'server_error',
|
type: 'server_error',
|
||||||
code: 'stream_interrupted'
|
code: 'stream_interrupted'
|
||||||
}
|
}
|
||||||
|
|
@ -674,7 +711,9 @@ export class RevolverEngine {
|
||||||
// If we reached here, all tiers and all candidates failed
|
// If we reached here, all tiers and all candidates failed
|
||||||
cleanupTimers();
|
cleanupTimers();
|
||||||
if (onFailure) onFailure('all_tiers_exhausted');
|
if (onFailure) onFailure('all_tiers_exhausted');
|
||||||
const finalErrorMessage = lastError ? lastError.message : 'All model tiers and provider keys are exhausted or rate-limited.';
|
const finalErrorMessage = lastError?.cause?.message
|
||||||
|
? `${lastError.message}: ${lastError.cause.message}`
|
||||||
|
: (lastError ? lastError.message : 'All model tiers and provider keys are exhausted or rate-limited.');
|
||||||
|
|
||||||
const journey: RequestFallbackJourney = {
|
const journey: RequestFallbackJourney = {
|
||||||
requestId,
|
requestId,
|
||||||
|
|
@ -720,6 +759,7 @@ export class RevolverEngine {
|
||||||
}));
|
}));
|
||||||
res.end();
|
res.end();
|
||||||
} else {
|
} else {
|
||||||
|
res.setHeader('Cache-Control', 'no-cache, no-transform');
|
||||||
res.status(503).json({
|
res.status(503).json({
|
||||||
error: {
|
error: {
|
||||||
message: `[Revolver Fallback Error]: ${finalErrorMessage}`,
|
message: `[Revolver Fallback Error]: ${finalErrorMessage}`,
|
||||||
|
|
@ -838,14 +878,20 @@ export class RevolverEngine {
|
||||||
method: 'POST',
|
method: 'POST',
|
||||||
headers: {
|
headers: {
|
||||||
'Content-Type': 'application/json',
|
'Content-Type': 'application/json',
|
||||||
'Authorization': `Bearer ${candidate.keyConfig.key}`
|
'Authorization': `Bearer ${candidate.keyConfig.key}`,
|
||||||
|
'Accept-Encoding': 'identity'
|
||||||
},
|
},
|
||||||
body: JSON.stringify(forwardedBody),
|
body: JSON.stringify(forwardedBody),
|
||||||
signal: AbortSignal.timeout(config.candidateTimeoutMs)
|
signal: AbortSignal.timeout(config.candidateTimeoutMs)
|
||||||
});
|
});
|
||||||
|
|
||||||
if (!response.ok) {
|
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;
|
let errorDetails = errBody;
|
||||||
try {
|
try {
|
||||||
const parsed = JSON.parse(errBody);
|
const parsed = JSON.parse(errBody);
|
||||||
|
|
@ -856,7 +902,46 @@ export class RevolverEngine {
|
||||||
throw err;
|
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
|
// Overwrite returned model with requestedModelName for client fidelity
|
||||||
json.model = requestedModelName;
|
json.model = requestedModelName;
|
||||||
if (!json.id) {
|
if (!json.id) {
|
||||||
|
|
@ -1096,14 +1181,20 @@ export class RevolverEngine {
|
||||||
method: 'POST',
|
method: 'POST',
|
||||||
headers: {
|
headers: {
|
||||||
'Content-Type': 'application/json',
|
'Content-Type': 'application/json',
|
||||||
'Authorization': `Bearer ${candidate.keyConfig.key}`
|
'Authorization': `Bearer ${candidate.keyConfig.key}`,
|
||||||
|
'Accept-Encoding': 'identity'
|
||||||
},
|
},
|
||||||
body: JSON.stringify(forwardedBody),
|
body: JSON.stringify(forwardedBody),
|
||||||
signal: AbortSignal.timeout(config.candidateTimeoutMs)
|
signal: AbortSignal.timeout(config.candidateTimeoutMs)
|
||||||
});
|
});
|
||||||
|
|
||||||
if (!response.ok) {
|
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;
|
let errorDetails = errBody;
|
||||||
try {
|
try {
|
||||||
const parsed = JSON.parse(errBody);
|
const parsed = JSON.parse(errBody);
|
||||||
|
|
@ -1367,7 +1458,8 @@ export class RevolverEngine {
|
||||||
method: 'POST',
|
method: 'POST',
|
||||||
headers: {
|
headers: {
|
||||||
'Content-Type': 'application/json',
|
'Content-Type': 'application/json',
|
||||||
'Authorization': `Bearer ${params.key}`
|
'Authorization': `Bearer ${params.key}`,
|
||||||
|
'Accept-Encoding': 'identity'
|
||||||
},
|
},
|
||||||
body: JSON.stringify({
|
body: JSON.stringify({
|
||||||
model,
|
model,
|
||||||
|
|
@ -1377,11 +1469,16 @@ export class RevolverEngine {
|
||||||
});
|
});
|
||||||
|
|
||||||
if (!res.ok) {
|
if (!res.ok) {
|
||||||
const body = await res.text();
|
let errBody = '';
|
||||||
let errText = body;
|
|
||||||
try {
|
try {
|
||||||
const parsed = JSON.parse(body);
|
errBody = await res.text();
|
||||||
errText = parsed.error?.message || body;
|
} 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 {}
|
} catch {}
|
||||||
return {
|
return {
|
||||||
success: false,
|
success: false,
|
||||||
|
|
@ -1399,10 +1496,11 @@ export class RevolverEngine {
|
||||||
};
|
};
|
||||||
}
|
}
|
||||||
} catch (err: any) {
|
} catch (err: any) {
|
||||||
|
const detailedMsg = err.cause?.message ? `${err.message}: ${err.cause.message}` : (err.message || 'Connection failed');
|
||||||
return {
|
return {
|
||||||
success: false,
|
success: false,
|
||||||
latencyMs: Date.now() - start,
|
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) {
|
if (!res.headersSent) {
|
||||||
|
res.setHeader('Cache-Control', 'no-cache, no-transform');
|
||||||
res.status(error.status || 500).json({
|
res.status(error.status || 500).json({
|
||||||
error: {
|
error: {
|
||||||
message: error.message || 'Internal server 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) {
|
} else if (!res.writableEnded) {
|
||||||
|
res.write(JSON.stringify({
|
||||||
|
error: {
|
||||||
|
message: error.message || 'Internal server error',
|
||||||
|
type: 'server_error',
|
||||||
|
code: 'internal_error'
|
||||||
|
}
|
||||||
|
}));
|
||||||
res.end();
|
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