feat(timeout): prevent Cloudflare 524 timeouts on long generations via SSE heartbeats and chunked keep-alives
This commit is contained in:
parent
ba57e3e394
commit
0e83233715
7 changed files with 385 additions and 25 deletions
|
|
@ -220,17 +220,75 @@ export class RevolverEngine {
|
|||
|
||||
let streamStarted = false;
|
||||
let isCancelled = false;
|
||||
let keepAliveTimer: NodeJS.Timeout | null = null;
|
||||
let nonStreamingTimer: NodeJS.Timeout | null = null;
|
||||
|
||||
const cleanupTimers = () => {
|
||||
if (keepAliveTimer) {
|
||||
clearInterval(keepAliveTimer);
|
||||
keepAliveTimer = null;
|
||||
}
|
||||
if (nonStreamingTimer) {
|
||||
clearInterval(nonStreamingTimer);
|
||||
nonStreamingTimer = null;
|
||||
}
|
||||
};
|
||||
|
||||
res.on('close', () => {
|
||||
cleanupTimers();
|
||||
if (!res.writableEnded) {
|
||||
isCancelled = true;
|
||||
if (onCancelled) onCancelled();
|
||||
}
|
||||
});
|
||||
|
||||
if (isStreaming) {
|
||||
// Send SSE headers immediately to establish connection with Cloudflare and prevent 524 timeouts
|
||||
if (!res.headersSent) {
|
||||
res.setHeader('Content-Type', 'text/event-stream; charset=utf-8');
|
||||
res.setHeader('Cache-Control', 'no-cache, no-transform');
|
||||
res.setHeader('Connection', 'keep-alive');
|
||||
res.setHeader('X-Accel-Buffering', 'no');
|
||||
if (typeof res.flushHeaders === 'function') {
|
||||
res.flushHeaders();
|
||||
}
|
||||
}
|
||||
|
||||
// Immediately transmit an initial SSE comment ping so Cloudflare Edge receives response bytes instantly
|
||||
if (!res.destroyed && !res.writableEnded) {
|
||||
res.write(': keep-alive\n\n');
|
||||
}
|
||||
|
||||
// Keep connection active with periodic SSE comments while waiting for model thinking / generation
|
||||
keepAliveTimer = setInterval(() => {
|
||||
if (!res.destroyed && !res.writableEnded) {
|
||||
res.write(': keep-alive\n\n');
|
||||
}
|
||||
}, config.keepAliveIntervalMs);
|
||||
} else if (config.enableNonStreamingKeepAlive) {
|
||||
// For non-streaming requests: start emitting whitespace chunks if request takes longer than nonStreamingKeepAliveDelayMs
|
||||
nonStreamingTimer = setInterval(() => {
|
||||
if (res.destroyed || res.writableEnded) {
|
||||
cleanupTimers();
|
||||
return;
|
||||
}
|
||||
if (!res.headersSent) {
|
||||
res.setHeader('Content-Type', 'application/json; charset=utf-8');
|
||||
res.setHeader('Transfer-Encoding', 'chunked');
|
||||
res.setHeader('Cache-Control', 'no-cache, no-transform');
|
||||
res.setHeader('X-Accel-Buffering', 'no');
|
||||
if (typeof res.flushHeaders === 'function') {
|
||||
res.flushHeaders();
|
||||
}
|
||||
}
|
||||
res.write(' ');
|
||||
}, config.nonStreamingKeepAliveDelayMs);
|
||||
}
|
||||
|
||||
// Sort tiers by tierIndex
|
||||
const sortedTiers = [...customModel.tiers].sort((a, b) => a.tierIndex - b.tierIndex);
|
||||
if (sortedTiers.length === 0) {
|
||||
cleanupTimers();
|
||||
throw new Error(`Custom model '${customModel.name}' has no fallback tiers defined.`);
|
||||
}
|
||||
|
||||
|
|
@ -248,7 +306,10 @@ export class RevolverEngine {
|
|||
|
||||
// Try candidates in this tier
|
||||
for (const candidate of candidates) {
|
||||
if (isCancelled || res.destroyed) return;
|
||||
if (isCancelled || res.destroyed) {
|
||||
cleanupTimers();
|
||||
return;
|
||||
}
|
||||
|
||||
try {
|
||||
console.log(`[REVOLVER] Routing to Provider '${candidate.provider.name}' (${candidate.provider.type}) with model '${candidate.target.model}' [Key ${candidate.keyIndex + 1}/${candidate.provider.keys.length}]`);
|
||||
|
|
@ -265,6 +326,7 @@ export class RevolverEngine {
|
|||
},
|
||||
onSuccess
|
||||
});
|
||||
cleanupTimers();
|
||||
// If stream finished successfully, return
|
||||
return;
|
||||
} else {
|
||||
|
|
@ -275,6 +337,7 @@ export class RevolverEngine {
|
|||
requestId
|
||||
});
|
||||
|
||||
cleanupTimers();
|
||||
if (isCancelled || res.destroyed) return;
|
||||
|
||||
// Success! Update stats
|
||||
|
|
@ -289,16 +352,34 @@ export class RevolverEngine {
|
|||
onSuccess({ input: promptTokens, output: completionTokens });
|
||||
}
|
||||
|
||||
res.json(responseData);
|
||||
if (res.headersSent) {
|
||||
// Chunked keep-alive headers were already emitted
|
||||
res.write(JSON.stringify(responseData));
|
||||
res.end();
|
||||
} else {
|
||||
res.json(responseData);
|
||||
}
|
||||
return;
|
||||
}
|
||||
} catch (err: any) {
|
||||
lastError = err;
|
||||
console.error(`[REVOLVER] Candidate failed (Provider: '${candidate.provider.name}', Model: '${candidate.target.model}'):`, err.message);
|
||||
|
||||
// If stream has already started sending bytes to the client, we cannot fail over cleanly
|
||||
// If stream has already started sending content bytes to the client, we cannot fail over cleanly
|
||||
if (streamStarted) {
|
||||
cleanupTimers();
|
||||
if (onFailure) onFailure('stream_interrupted');
|
||||
if (!res.destroyed && !res.writableEnded) {
|
||||
res.write(`data: ${JSON.stringify({
|
||||
error: {
|
||||
message: err.message || 'Stream interrupted',
|
||||
type: 'server_error',
|
||||
code: 'stream_interrupted'
|
||||
}
|
||||
})}\n\n`);
|
||||
res.write('data: [DONE]\n\n');
|
||||
res.end();
|
||||
}
|
||||
throw err;
|
||||
}
|
||||
|
||||
|
|
@ -327,15 +408,42 @@ export class RevolverEngine {
|
|||
}
|
||||
|
||||
// If we reached here, all tiers and all candidates failed
|
||||
cleanupTimers();
|
||||
if (onFailure) onFailure('all_tiers_exhausted');
|
||||
const finalErrorMessage = lastError ? lastError.message : 'All model tiers and provider keys are exhausted or rate-limited.';
|
||||
res.status(503).json({
|
||||
error: {
|
||||
message: `[Revolver Fallback Error]: ${finalErrorMessage}`,
|
||||
type: 'revolver_exhausted_error',
|
||||
code: 'all_tiers_exhausted'
|
||||
|
||||
if (isStreaming) {
|
||||
if (!res.destroyed && !res.writableEnded) {
|
||||
res.write(`data: ${JSON.stringify({
|
||||
error: {
|
||||
message: `[Revolver Fallback Error]: ${finalErrorMessage}`,
|
||||
type: 'revolver_exhausted_error',
|
||||
code: 'all_tiers_exhausted'
|
||||
}
|
||||
})}\n\n`);
|
||||
res.write('data: [DONE]\n\n');
|
||||
res.end();
|
||||
}
|
||||
});
|
||||
} else {
|
||||
if (res.headersSent) {
|
||||
res.write(JSON.stringify({
|
||||
error: {
|
||||
message: `[Revolver Fallback Error]: ${finalErrorMessage}`,
|
||||
type: 'revolver_exhausted_error',
|
||||
code: 'all_tiers_exhausted'
|
||||
}
|
||||
}));
|
||||
res.end();
|
||||
} else {
|
||||
res.status(503).json({
|
||||
error: {
|
||||
message: `[Revolver Fallback Error]: ${finalErrorMessage}`,
|
||||
type: 'revolver_exhausted_error',
|
||||
code: 'all_tiers_exhausted'
|
||||
}
|
||||
});
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
private async executeNonStreaming(params: {
|
||||
|
|
@ -377,7 +485,7 @@ export class RevolverEngine {
|
|||
const modelInstance = genAI.getGenerativeModel({
|
||||
model: candidate.target.model,
|
||||
systemInstruction: systemInstruction || undefined
|
||||
});
|
||||
}, { timeout: config.candidateTimeoutMs });
|
||||
|
||||
const lastMessage = geminiMessages[geminiMessages.length - 1];
|
||||
if (!lastMessage || lastMessage.role !== 'user') {
|
||||
|
|
@ -447,7 +555,8 @@ export class RevolverEngine {
|
|||
'Content-Type': 'application/json',
|
||||
'Authorization': `Bearer ${candidate.keyConfig.key}`
|
||||
},
|
||||
body: JSON.stringify(forwardedBody)
|
||||
body: JSON.stringify(forwardedBody),
|
||||
signal: AbortSignal.timeout(config.candidateTimeoutMs)
|
||||
});
|
||||
|
||||
if (!response.ok) {
|
||||
|
|
@ -522,7 +631,7 @@ export class RevolverEngine {
|
|||
const modelInstance = genAI.getGenerativeModel({
|
||||
model: candidate.target.model,
|
||||
systemInstruction: systemInstruction || undefined
|
||||
});
|
||||
}, { timeout: config.candidateTimeoutMs });
|
||||
|
||||
const lastMessage = geminiMessages[geminiMessages.length - 1];
|
||||
if (!lastMessage || lastMessage.role !== 'user') {
|
||||
|
|
@ -541,11 +650,16 @@ export class RevolverEngine {
|
|||
// Start streaming from Gemini
|
||||
const result = await chat.sendMessageStream(lastMessage.parts[0].text);
|
||||
|
||||
// If we got here without throwing, commit headers to client
|
||||
onStreamStart();
|
||||
res.setHeader('Content-Type', 'text/event-stream');
|
||||
res.setHeader('Cache-Control', 'no-cache');
|
||||
res.setHeader('Connection', 'keep-alive');
|
||||
// If headers haven't been committed, commit them now
|
||||
if (!res.headersSent) {
|
||||
res.setHeader('Content-Type', 'text/event-stream; charset=utf-8');
|
||||
res.setHeader('Cache-Control', 'no-cache, no-transform');
|
||||
res.setHeader('Connection', 'keep-alive');
|
||||
res.setHeader('X-Accel-Buffering', 'no');
|
||||
if (typeof res.flushHeaders === 'function') {
|
||||
res.flushHeaders();
|
||||
}
|
||||
}
|
||||
|
||||
let fullContent = '';
|
||||
let promptTokens = 0;
|
||||
|
|
@ -555,6 +669,7 @@ export class RevolverEngine {
|
|||
if (res.destroyed) break;
|
||||
const text = chunk.text();
|
||||
fullContent += text;
|
||||
onStreamStart();
|
||||
|
||||
const chunkResponse = {
|
||||
id: `chatcmpl-${requestId}`,
|
||||
|
|
@ -640,7 +755,8 @@ export class RevolverEngine {
|
|||
'Content-Type': 'application/json',
|
||||
'Authorization': `Bearer ${candidate.keyConfig.key}`
|
||||
},
|
||||
body: JSON.stringify(forwardedBody)
|
||||
body: JSON.stringify(forwardedBody),
|
||||
signal: AbortSignal.timeout(config.candidateTimeoutMs)
|
||||
});
|
||||
|
||||
if (!response.ok) {
|
||||
|
|
@ -659,11 +775,16 @@ export class RevolverEngine {
|
|||
throw new Error('Response body is null from provider stream.');
|
||||
}
|
||||
|
||||
// Stream started successfully!
|
||||
onStreamStart();
|
||||
res.setHeader('Content-Type', 'text/event-stream');
|
||||
res.setHeader('Cache-Control', 'no-cache');
|
||||
res.setHeader('Connection', 'keep-alive');
|
||||
// If headers haven't been committed, commit them now
|
||||
if (!res.headersSent) {
|
||||
res.setHeader('Content-Type', 'text/event-stream; charset=utf-8');
|
||||
res.setHeader('Cache-Control', 'no-cache, no-transform');
|
||||
res.setHeader('Connection', 'keep-alive');
|
||||
res.setHeader('X-Accel-Buffering', 'no');
|
||||
if (typeof res.flushHeaders === 'function') {
|
||||
res.flushHeaders();
|
||||
}
|
||||
}
|
||||
|
||||
const reader = response.body.getReader();
|
||||
const decoder = new TextDecoder();
|
||||
|
|
@ -700,6 +821,7 @@ export class RevolverEngine {
|
|||
const parsed = JSON.parse(dataStr);
|
||||
parsed.model = requestedModelName;
|
||||
if (parsed.choices?.[0]?.delta?.content) {
|
||||
onStreamStart();
|
||||
totalOutputChars += parsed.choices[0].delta.content.length;
|
||||
}
|
||||
res.write(`data: ${JSON.stringify(parsed)}\n\n`);
|
||||
|
|
|
|||
Loading…
Add table
Add a link
Reference in a new issue