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
|
|
@ -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();
|
||||
}
|
||||
}
|
||||
|
|
|
|||
Loading…
Add table
Add a link
Reference in a new issue