Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
60 changes: 57 additions & 3 deletions apps/gateway/src/anthropic/anthropic.ts
Original file line number Diff line number Diff line change
Expand Up @@ -785,6 +785,21 @@ anthropic.openapi(messages, async (c) => {
const reader = response.body.getReader();
const decoder = new TextDecoder();

// SSE keepalive to prevent proxy/load balancer and client idle
// timeouts from closing the connection during quiet gaps (slow
// time-to-first-token, long reasoning before output, slow tool-arg
// generation). Without this, coding clients see "The socket
// connection was closed unexpectedly". The inner
// /v1/chat/completions keepalive is consumed by this translator and
// never reaches the client, so we emit our own here. A `: ping`
// comment is part of the SSE spec and ignored by the Anthropic SDK.
const KEEPALIVE_INTERVAL_MS = 15000;
const keepaliveInterval = setInterval(() => {
stream.write(": ping\n").catch(() => {
// Stream likely closed; cleanup happens in finally.
});
}, KEEPALIVE_INTERVAL_MS);

let buffer = "";
let messageId = "";
let model = "";
Expand Down Expand Up @@ -1183,10 +1198,49 @@ anthropic.openapi(messages, async (c) => {
});
}
} catch (error) {
throw new HTTPException(500, {
message: `Streaming error: ${error instanceof Error ? error.message : String(error)}`,
});
// The 200 response and SSE headers are already sent, so throwing
// here cannot produce an HTTP error — it would abruptly tear down
// the socket and the client would see "The socket connection was
// closed unexpectedly". Instead, emit a well-formed Anthropic
// terminal sequence (error event + message_stop) so the client
// ends the stream cleanly. A client-side abort needs no write.
if (error instanceof Error && error.name === "AbortError") {
logger.info("Anthropic streaming request aborted by client", {
message: error.message,
path: c.req.path,
});
} else {
logger.error(
"Anthropic streaming error (mid-stream)",
toError(error),
{ path: c.req.path },
);
try {
await stream.writeSSE({
data: JSON.stringify(
buildAnthropicErrorEvent({
type: "error",
error: {
type: "api_error",
message: `Streaming error: ${error instanceof Error ? error.message : String(error)}`,
},
}),
),
event: "error",
});
await stream.writeSSE({
data: JSON.stringify({ type: "message_stop" }),
event: "message_stop",
});
} catch (sseError) {
logger.error(
"Failed to send Anthropic streaming error event",
toError(sseError),
);
}
}
} finally {
clearInterval(keepaliveInterval);
reader.releaseLock();
}
},
Expand Down
49 changes: 41 additions & 8 deletions apps/gateway/src/responses/responses.ts
Original file line number Diff line number Diff line change
Expand Up @@ -409,6 +409,21 @@ responses.post("/", async (c) => {
const decoder = new TextDecoder();
let buffer = "";

// SSE keepalive to prevent proxy/load balancer and client idle
// timeouts from closing the connection during quiet gaps (slow
// time-to-first-token, long reasoning before output, slow tool-arg
// generation). Without this, coding clients see "The socket
// connection was closed unexpectedly". The inner /v1/chat/completions
// keepalive is consumed by this translator and never reaches the
// client, so we emit our own here. A `: ping` comment is part of the
// SSE spec and ignored by the OpenAI SDK.
const KEEPALIVE_INTERVAL_MS = 15000;
const keepaliveInterval = setInterval(() => {
stream.write(": ping\n").catch(() => {
// Stream likely closed; cleanup happens in finally.
});
}, KEEPALIVE_INTERVAL_MS);
Comment on lines +421 to +425

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

P2 Badge Wrap the first SSE write in the cleanup path

If the client disconnects before or during the initial response.created write just below this block, that await stream.writeSSE(...) rejects before execution enters the try/finally that clears this interval. The new keepalive timer will then keep firing and swallowing failed writes for the lifetime of the process, so early-aborted /v1/responses streams can leak timers; start the interval inside the guarded section or include the initial write in the same try/finally.

Useful? React with 👍 / 👎.


// Send response.created
const createdEvent = createResponseCreatedEvent(state);
await stream.writeSSE({
Expand Down Expand Up @@ -501,15 +516,33 @@ responses.post("/", async (c) => {
await processLine(buffer);
}
} catch (error) {
logger.error("Error processing streaming response", {
error,
});
const failedEvent = createFailedEvent(state);
await stream.writeSSE({
event: failedEvent.event,
data: failedEvent.data,
});
// A client-side abort needs no terminal event — the socket is
// already gone, and writing would throw. For genuine errors, emit a
// well-formed response.failed event so the client ends the stream
// cleanly instead of seeing the socket close unexpectedly.
if (error instanceof Error && error.name === "AbortError") {
logger.info("Responses streaming request aborted by client", {
message: error.message,
path: c.req.path,
});
} else {
logger.error("Error processing streaming response", {
error,
});
try {
const failedEvent = createFailedEvent(state);
await stream.writeSSE({
event: failedEvent.event,
data: failedEvent.data,
});
} catch (sseError) {
logger.error("Failed to send response.failed event", {
error: sseError,
});
}
}
} finally {
clearInterval(keepaliveInterval);
reader.releaseLock();
}
});
Expand Down
Loading