Never stop coding. Free MIT AI gateway: one endpoint, 375 providers (150+ free), 1,400+ models Kimi, Claude, GPT, Gemini, GLM, DeepSeek, MiniMax. Works with Claude Code, Codex, Cursor, OpenCode, Cline & Copilot. Quota-aware auto-fallback, RTK+Caveman compression saves 15-95% tokens, MCP/A2A, Desktop/PWA. Built by 900+ contributors
TypeScript a2aai-agentsai-gatewayanthropicclaudeclaude-codeclinecodexcopilotcursordeepseekfree-aigeminikimillm-gatewaymcpopenaiopenai-proxyqwentoken-saver
fix: add body-read timeout to prevent stuck pending requests (#1680)
clousky2020cc07e5f7f611
diff --git a/open-sse/config/constants.ts b/open-sse/config/constants.tsindex 25fef8f32a..421c62722e 100644--- a/open-sse/config/constants.ts+++ b/open-sse/config/constants.ts@@ -16,6 +16,11 @@ export const FETCH_TIMEOUT_MS = upstreamTimeouts.fetchTimeoutMs;// Extended-thinking models rarely pause >90s between chunks. Override with STREAM_IDLE_TIMEOUT_MS env var.export const STREAM_IDLE_TIMEOUT_MS = upstreamTimeouts.streamIdleTimeoutMs;+// Timeout for reading the full response body after headers arrive (ms).+// Prevents indefinite hangs when the upstream sends headers but stalls on the body.+// Defaults to FETCH_TIMEOUT_MS. Override with FETCH_BODY_TIMEOUT_MS env var.+export const FETCH_BODY_TIMEOUT_MS = upstreamTimeouts.fetchBodyTimeoutMs;+// Provider configurations// OAuth credentials read from env vars with hardcoded fallbacks for backward compatibility.// Use provider-credentials.json or env vars to override in production.diff --git a/open-sse/handlers/chatCore.ts b/open-sse/handlers/chatCore.tsindex bebb01f5e2..b32ee29255 100644--- a/open-sse/handlers/chatCore.ts+++ b/open-sse/handlers/chatCore.ts@@ -6,6 +6,7 @@ import {createSSETransformStreamWithLogger,createPassthroughStreamWithLogger,COLORS,+ withBodyTimeout,} from "../utils/stream.ts";import { createStreamController, pipeWithDisconnect } from "../utils/streamHandler.ts";import { addBufferToUsage, filterUsageForFormat, estimateUsage } from "../utils/usageTracking.ts";@@ -2174,7 +2175,7 @@ export async function handleChatCore({const status = rawResult.response.status;const statusText = rawResult.response.statusText;const headers = Array.from(rawResult.response.headers.entries()) as [string, string][];- const payload = await rawResult.response.text();+ const payload = await withBodyTimeout<string>(rawResult.response.text());acquireAccountSemaphoreRelease();return {@@ -2286,7 +2287,7 @@ export async function handleChatCore({const failureStatus =error.name === "AbortError"? 499- : error.name === "TimeoutError"+ : error.name === "TimeoutError" || error.name === "BodyTimeoutError"? HTTP_STATUS.GATEWAY_TIMEOUT: HTTP_STATUS.BAD_GATEWAY;const failureMessage =@@ -2777,7 +2778,7 @@ export async function handleChatCore({const contentType = (providerResponse.headers.get("content-type") || "").toLowerCase();let responseBody;let responsePayloadFormat = targetFormat;- const rawBody = await providerResponse.text();+ const rawBody = await withBodyTimeout<string>(providerResponse.text());const normalizedProviderPayload = normalizePayloadForLog(rawBody);const looksLikeSSE =contentType.includes("text/event-stream") ||@@ -2872,7 +2873,7 @@ export async function handleChatCore({try {const fallbackResult = await executeProviderRequest(nextModel, false);if (fallbackResult.response.ok) {- const fallbackRaw = await fallbackResult.response.text();+ const fallbackRaw = await withBodyTimeout<string>(fallbackResult.response.text());try {responseBody = fallbackRaw ? JSON.parse(fallbackRaw) : {};providerUrl = fallbackResult.url;diff --git a/open-sse/utils/stream.ts b/open-sse/utils/stream.tsindex 7cfb4074ff..7675ef04e3 100644--- a/open-sse/utils/stream.ts+++ b/open-sse/utils/stream.ts@@ -23,13 +23,33 @@ import {createStructuredSSECollector,buildStreamSummaryFromEvents,} from "./streamPayloadCollector.ts";-import { STREAM_IDLE_TIMEOUT_MS, HTTP_STATUS } from "../config/constants.ts";+import { STREAM_IDLE_TIMEOUT_MS, FETCH_BODY_TIMEOUT_MS, HTTP_STATUS } from "../config/constants.ts";import {sanitizeStreamingChunk,extractThinkingFromContent,} from "../handlers/responseSanitizer.ts";import { buildErrorBody } from "./error.ts";+/**+ * Race a response body read against a timeout.+ * Prevents indefinite hangs when the upstream sends headers but stalls on the body.+ */+export function withBodyTimeout<T>(+ promise: Promise<T>,+ timeoutMs: number = FETCH_BODY_TIMEOUT_MS+): Promise<T> {+ if (timeoutMs <= 0) return promise;+ let timer: ReturnType<typeof setTimeout>;+ const timeout = new Promise<never>((_, reject) => {+ timer = setTimeout(() => {+ const err = new Error(`Response body read timeout after ${timeoutMs}ms`);+ err.name = "BodyTimeoutError";+ reject(err);+ }, timeoutMs);+ });+ return Promise.race([promise, timeout]).finally(() => clearTimeout(timer)) as Promise<T>;+}+export { COLORS, formatSSE };type JsonRecord = Record<string, unknown>;diff --git a/src/app/api/logs/active/route.ts b/src/app/api/logs/active/route.tsindex f8117ed32a..77b5c462d0 100644--- a/src/app/api/logs/active/route.ts+++ b/src/app/api/logs/active/route.ts@@ -1,7 +1,7 @@import { NextResponse } from "next/server";import { requireManagementAuth } from "@/lib/api/requireManagementAuth";import { getProviderConnections } from "@/lib/localDb";-import { getPendingRequests } from "@/lib/usage/usageHistory";+import { getPendingRequests, clearPendingRequests } from "@/lib/usage/usageHistory";export async function GET(request: Request) {const authError = await requireManagementAuth(request);@@ -45,3 +45,11 @@ export async function GET(request: Request) {return NextResponse.json({ error: "Failed to load active requests" }, { status: 500 });}}++export async function DELETE(request: Request) {+ const authError = await requireManagementAuth(request);+ if (authError) return authError;++ clearPendingRequests();+ return NextResponse.json({ success: true, message: "Pending request counts cleared" });+}diff --git a/src/lib/usage/usageHistory.ts b/src/lib/usage/usageHistory.tsindex eae88174a2..c644cf0612 100644--- a/src/lib/usage/usageHistory.ts+++ b/src/lib/usage/usageHistory.ts@@ -226,6 +226,19 @@ export function getPendingRequests() {return pendingRequests;}+/**+ * Clear all pending request counts.+ * Used for admin reset when counts leak due to uncaught timeouts or process-level errors.+ */+export function clearPendingRequests() {+ pendingRequests.byModel = Object.create(null) as Record<string, number>;+ pendingRequests.byAccount = Object.create(null) as Record<string, Record<string, number>>;+ pendingRequests.details = Object.create(null) as Record<+ string,+ Record<string, PendingRequestDetail>+ >;+}+// ──────────────── getUsageDb Shim (backward compat) ────────────────/**diff --git a/tests/unit/body-read-timeout.test.ts b/tests/unit/body-read-timeout.test.tsnew file mode 100644index 0000000000..a96f3b0802--- /dev/null+++ b/tests/unit/body-read-timeout.test.ts@@ -0,0 +1,54 @@+import test from "node:test";+import assert from "node:assert/strict";++import { withBodyTimeout } from "../../open-sse/utils/stream.ts";++test("withBodyTimeout resolves with the value when the promise completes before timeout", async () => {+ const result = await withBodyTimeout(Promise.resolve("hello"), 5000);+ assert.equal(result, "hello");+});++test("withBodyTimeout rejects with BodyTimeoutError when the promise exceeds the timeout", async () => {+ const neverResolves = new Promise<string>(() => {});+ await assert.rejects(withBodyTimeout(neverResolves, 50), (error) => {+ assert.ok(error instanceof Error);+ assert.equal(error.name, "BodyTimeoutError");+ assert.match(error.message, /body read timeout after 50ms/);+ return true;+ });+});++test("withBodyTimeout forwards the original rejection when the promise rejects before timeout", async () => {+ const originalError = new Error("network failure");+ const rejects = Promise.reject(originalError);+ await assert.rejects(withBodyTimeout(rejects, 5000), (error) => {+ assert.equal(error, originalError);+ return true;+ });+});++test("withBodyTimeout with timeoutMs=0 skips timeout and passes through directly", async () => {+ // A promise that would timeout with any positive timeout+ const slow = new Promise((resolve) => setTimeout(() => resolve("late"), 200));+ // With timeoutMs=0, it should wait for the promise naturally+ const result = await withBodyTimeout(slow, 0);+ assert.equal(result, "late");+});++test("withBodyTimeout cleans up the timer after successful resolution", async () => {+ const result = await withBodyTimeout(Promise.resolve(42), 100);+ assert.equal(result, 42);+ // If the timer wasn't cleaned up, the process might hang or throw later.+ // Wait a bit to confirm no stray timer fires.+ await new Promise((resolve) => setTimeout(resolve, 150));+});++test("withBodyTimeout cleans up the timer after rejection", async () => {+ const originalError = new Error("fail");+ await assert.rejects(+ withBodyTimeout(Promise.reject(originalError), 100),+ (error) => error === originalError+ );+ // Wait to confirm no stray timer+ await new Promise((resolve) => setTimeout(resolve, 150));+});diff --git a/tests/unit/body-timeout-integration.test.ts b/tests/unit/body-timeout-integration.test.tsnew file mode 100644index 0000000000..d2bcc849aa--- /dev/null+++ b/tests/unit/body-timeout-integration.test.ts@@ -0,0 +1,155 @@+import test from "node:test";+import assert from "node:assert/strict";+import fs from "node:fs";+import os from "node:os";+import path from "node:path";++// ── 1. FETCH_BODY_TIMEOUT_MS constant export validation ──────────────────++test("FETCH_BODY_TIMEOUT_MS is exported from open-sse/config/constants and is a positive number", async () => {+ const constants = await import("../../open-sse/config/constants.ts");+ assert.ok("FETCH_BODY_TIMEOUT_MS" in constants, "FETCH_BODY_TIMEOUT_MS should be exported");+ assert.equal(typeof constants.FETCH_BODY_TIMEOUT_MS, "number");+ assert.ok(constants.FETCH_BODY_TIMEOUT_MS > 0, "should be a positive number");+});++test("FETCH_BODY_TIMEOUT_MS defaults to FETCH_TIMEOUT_MS when no env override", async () => {+ const constants = await import("../../open-sse/config/constants.ts");+ assert.equal(+ constants.FETCH_BODY_TIMEOUT_MS,+ constants.FETCH_TIMEOUT_MS,+ "FETCH_BODY_TIMEOUT_MS should default to FETCH_TIMEOUT_MS"+ );+});++// ── 2. BodyTimeoutError classification in chatCore ──────────────────────++test("chatCore error classification maps BodyTimeoutError to 504 GATEWAY_TIMEOUT", () => {+ // Read the source to verify the error classification logic includes BodyTimeoutError+ const content = fs.readFileSync("open-sse/handlers/chatCore.ts", "utf8");++ // The error classification block should include BodyTimeoutError alongside TimeoutError+ const classificationPattern =+ /error\.name === ["']TimeoutError["']\s*\|\|\s*error\.name === ["']BodyTimeoutError["']/;+ assert.ok(+ classificationPattern.test(content),+ "chatCore should classify BodyTimeoutError as GATEWAY_TIMEOUT (504)"+ );+});++test("chatCore catch block decrements pending requests for all error types", () => {+ const content = fs.readFileSync("open-sse/handlers/chatCore.ts", "utf8");++ // The catch block should call trackPendingRequest with false before error classification+ const catchBlockPattern = /catch\s*\(error\)\s*\{[^}]*trackPendingRequest\([^)]*,\s*false\)/;+ assert.ok(+ catchBlockPattern.test(content),+ "chatCore catch block should decrement pending requests"+ );+});++test("withBodyTimeout error name is BodyTimeoutError", async () => {+ const { withBodyTimeout } = await import("../../open-sse/utils/stream.ts");++ const neverResolves = new Promise<string>(() => {});+ try {+ await withBodyTimeout(neverResolves, 20);+ assert.fail("should have thrown");+ } catch (error) {+ assert.ok(error instanceof Error);+ assert.equal(error.name, "BodyTimeoutError");+ }+});++// ── 3. BodyTimeoutError triggers correct pending request decrement ──────++test("BodyTimeoutError from withBodyTimeout does not leave timer leaks", async () => {+ const { withBodyTimeout } = await import("../../open-sse/utils/stream.ts");++ // Fire multiple short timeouts to ensure no timer accumulation+ const promises = Array.from({ length: 10 }, () =>+ withBodyTimeout(new Promise(() => {}), 10).catch(() => {})+ );+ await Promise.all(promises);++ // Wait a bit to ensure all timers are cleaned up+ await new Promise((resolve) => setTimeout(resolve, 100));++ // If timers leaked, the process would hang or show warnings — this test+ // passing confirms proper cleanup under concurrent timeout scenarios.+ assert.ok(true, "all timers cleaned up successfully");+});++// ── 4. DELETE /api/logs/active endpoint ──────────────────────────────────++test("DELETE /api/logs/active route requires management authentication", () => {+ const content = fs.readFileSync("src/app/api/logs/active/route.ts", "utf8");++ assert.ok(+ content.includes('from "@/lib/api/requireManagementAuth"'),+ "should import requireManagementAuth"+ );+ assert.ok(content.includes("export async function DELETE"), "should export DELETE handler");+ assert.ok(+ content.includes("await requireManagementAuth(request)"),+ "DELETE should check management auth"+ );+});++test("DELETE /api/logs/active calls clearPendingRequests", () => {+ const content = fs.readFileSync("src/app/api/logs/active/route.ts", "utf8");++ assert.ok(+ content.includes("clearPendingRequests"),+ "DELETE handler should call clearPendingRequests"+ );+ assert.ok(+ content.includes("Pending request counts cleared"),+ "DELETE handler should return success message"+ );+});++// ── 5. clearPendingRequests + trackPendingRequest integration ────────────++test("trackPendingRequest followed by clearPendingRequests zeroes all counts", async () => {+ const usageHistory = await import("../../src/lib/usage/usageHistory.ts");++ usageHistory.trackPendingRequest("m1", "p1", "c1", true);+ usageHistory.trackPendingRequest("m1", "p1", "c1", true);+ usageHistory.trackPendingRequest("m2", "p2", "c2", true);++ const before = usageHistory.getPendingRequests();+ assert.equal(before.byModel["m1 (p1)"], 2);+ assert.equal(before.byModel["m2 (p2)"], 1);++ usageHistory.clearPendingRequests();++ const after = usageHistory.getPendingRequests();+ assert.equal(Object.keys(after.byModel).length, 0);+ assert.equal(Object.keys(after.byAccount).length, 0);+ assert.equal(Object.keys(after.details).length, 0);+});++test("clearPendingRequests allows subsequent tracking to work correctly", async () => {+ const usageHistory = await import("../../src/lib/usage/usageHistory.ts");++ usageHistory.trackPendingRequest("m1", "p1", "c1", true);+ usageHistory.clearPendingRequests();++ // After clearing, tracking should increment from 0+ usageHistory.trackPendingRequest("m3", "p3", "c3", true);+ usageHistory.trackPendingRequest("m3", "p3", "c3", true);++ const pending = usageHistory.getPendingRequests();+ assert.equal(pending.byModel["m3 (p3)"], 2);+ assert.ok(pending.details["c3"]);++ // Decrement should also work+ usageHistory.trackPendingRequest("m3", "p3", "c3", false);+ assert.equal(pending.byModel["m3 (p3)"], 1);++ // Final decrement should clear details+ usageHistory.trackPendingRequest("m3", "p3", "c3", false);+ assert.equal(pending.byModel["m3 (p3)"], 0);+ assert.equal(pending.details["c3"], undefined);+});diff --git a/tests/unit/usage-analytics.test.ts b/tests/unit/usage-analytics.test.tsindex 78e934b30b..8ff5f6662c 100644--- a/tests/unit/usage-analytics.test.ts+++ b/tests/unit/usage-analytics.test.ts@@ -15,12 +15,8 @@ const usageStats = await import("../../src/lib/usage/usageStats.ts");const callLogs = await import("../../src/lib/usage/callLogs.ts");const { calculateCost } = await import("../../src/lib/usage/costCalculator.ts");-function clearPendingRequests() {- const pending = usageHistory.getPendingRequests();- for (const key of Object.keys(pending.byModel)) delete pending.byModel[key];- for (const key of Object.keys(pending.byAccount)) delete pending.byAccount[key];- for (const key of Object.keys(pending.details || {})) delete pending.details[key];-}+// Use the official clearPendingRequests export instead of manual cleanup+const clearPendingRequests = usageHistory.clearPendingRequests;async function resetStorage() {core.resetDbInstance();@@ -342,3 +338,35 @@ test("pending request metadata stores sanitized payload previews and clears afteusageHistory.trackPendingRequest("gpt-test", "openai", "conn-preview", false);assert.equal(pending.details["conn-preview"], undefined);});++test("clearPendingRequests resets all pending counts and details", () => {+ // Simulate leaked pending counts (increment without matching decrement)+ usageHistory.trackPendingRequest("model-a", "provider-x", "conn-1", true);+ usageHistory.trackPendingRequest("model-a", "provider-x", "conn-1", true);+ usageHistory.trackPendingRequest("model-b", "provider-y", "conn-2", true);++ const before = usageHistory.getPendingRequests();+ assert.equal(before.byModel["model-a (provider-x)"], 2);+ assert.equal(before.byModel["model-b (provider-y)"], 1);+ assert.ok(before.details["conn-1"]);+ assert.ok(before.details["conn-2"]);++ // Clear all pending+ usageHistory.clearPendingRequests();++ const after = usageHistory.getPendingRequests();+ assert.equal(Object.keys(after.byModel).length, 0);+ assert.equal(Object.keys(after.byAccount).length, 0);+ assert.equal(Object.keys(after.details).length, 0);+});++test("clearPendingRequests allows fresh tracking after clearing", () => {+ usageHistory.trackPendingRequest("model-c", "provider-z", "conn-3", true);+ usageHistory.clearPendingRequests();++ // Tracking should work normally after clearing+ usageHistory.trackPendingRequest("model-d", "provider-w", "conn-4", true);+ const pending = usageHistory.getPendingRequests();+ assert.equal(pending.byModel["model-d (provider-w)"], 1);+ assert.ok(pending.details["conn-4"]);+});