Skip to content
Merged
Show file tree
Hide file tree
Changes from 1 commit
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
9 changes: 9 additions & 0 deletions .env.example
Original file line number Diff line number Diff line change
Expand Up @@ -42,6 +42,15 @@ TIMEOUT_MS=5000
# Defaults: gateway=620s, api=60s
# KEEP_ALIVE_TIMEOUT_S=620

# Gateway request timeout in milliseconds - maximum time for end-to-end request
# Defaults to 300000ms (5 minutes)
# GATEWAY_TIMEOUT_MS=300000

# AI API request timeout in milliseconds - maximum time for upstream provider calls
# Should be shorter than GATEWAY_TIMEOUT_MS to allow for error handling
# Defaults to 240000ms (4 minutes) or 80% of GATEWAY_TIMEOUT_MS, whichever is smaller
# AI_REQUEST_TIMEOUT_MS=240000

# =============================================================================
# WORKER CONFIGURATION
# =============================================================================
Expand Down
175 changes: 174 additions & 1 deletion apps/gateway/src/api.spec.ts
Original file line number Diff line number Diff line change
Expand Up @@ -14,7 +14,7 @@ import {
startMockServer,
stopMockServer,
} from "./test-utils/mock-openai-server.js";
import { clearCache, waitForLogs } from "./test-utils/test-helpers.js";
import { clearCache, waitForLogs, readAll } from "./test-utils/test-helpers.js";

describe("test", () => {
let mockServerUrl: string;
Expand Down Expand Up @@ -789,4 +789,177 @@ describe("test", () => {
/Custom headers \(X-LLMGateway-\*\) require a Pro plan/i,
);
});

// Timeout tests - use a short timeout via env var to test timeout handling
describe("Timeout handling", () => {
let originalTimeout: string | undefined;

beforeAll(() => {
// Save original env value
originalTimeout = process.env.AI_REQUEST_TIMEOUT_MS;
// Set a short timeout for testing (2 seconds)
process.env.AI_REQUEST_TIMEOUT_MS = "2000";
});

afterAll(() => {
// Restore original env value
if (originalTimeout !== undefined) {
process.env.AI_REQUEST_TIMEOUT_MS = originalTimeout;
} else {
delete process.env.AI_REQUEST_TIMEOUT_MS;
}
});

test("non-streaming request times out when upstream is slow", async () => {
await db.insert(tables.apiKey).values({
id: "token-id",
token: "real-token",
projectId: "project-id",
description: "Test API Key",
createdBy: "user-id",
});

await db.insert(tables.providerKey).values({
id: "provider-key-id",
token: "sk-test-key",
provider: "llmgateway",
organizationId: "org-id",
baseUrl: mockServerUrl,
});

// Request that triggers a 5 second delay (longer than our 2s timeout)
const res = await app.request("/v1/chat/completions", {
method: "POST",
headers: {
"Content-Type": "application/json",
Authorization: `Bearer real-token`,
},
body: JSON.stringify({
model: "llmgateway/custom",
messages: [
{
role: "user",
content: "TRIGGER_TIMEOUT_5000",
},
],
}),
});

// Request should fail with 502 Bad Gateway (upstream timeout)
expect(res.status).toBe(502);

const json = await res.json();
expect(json).toHaveProperty("error");
expect(json.error.type).toBe("upstream_error");
expect(json.error.code).toBe("fetch_failed");

// Wait for the log to be written
const logs = await waitForLogs(1);
expect(logs.length).toBe(1);
expect(logs[0].finishReason).toBe("upstream_error");
expect(logs[0].hasError).toBe(true);
expect(logs[0].errorDetails).toBeTruthy();
expect(logs[0].errorDetails?.statusText).toBe("TimeoutError");
}, 15000);

test("streaming request times out when upstream is slow", async () => {
await db.insert(tables.apiKey).values({
id: "token-id",
token: "real-token",
projectId: "project-id",
description: "Test API Key",
createdBy: "user-id",
});

await db.insert(tables.providerKey).values({
id: "provider-key-id",
token: "sk-test-key",
provider: "llmgateway",
organizationId: "org-id",
baseUrl: mockServerUrl,
});

// Request that triggers a 5 second delay (longer than our 2s timeout)
const res = await app.request("/v1/chat/completions", {
method: "POST",
headers: {
"Content-Type": "application/json",
Authorization: `Bearer real-token`,
},
body: JSON.stringify({
model: "llmgateway/custom",
messages: [
{
role: "user",
content: "TRIGGER_TIMEOUT_5000",
},
],
stream: true,
}),
});

// Streaming response should still return 200 status
expect(res.status).toBe(200);

// But the stream should contain a timeout error event
const streamResult = await readAll(res.body);

// Should have an error event
expect(streamResult.hasError).toBe(true);
expect(streamResult.errorEvents.length).toBeGreaterThan(0);

const errorEvent = streamResult.errorEvents[0];
expect(errorEvent.error.type).toBe("upstream_timeout");
expect(errorEvent.error.code).toBe("timeout");

// Wait for the log to be written
const logs = await waitForLogs(1);
expect(logs.length).toBe(1);
expect(logs[0].finishReason).toBe("upstream_error");
expect(logs[0].hasError).toBe(true);
expect(logs[0].errorDetails).toBeTruthy();
expect(logs[0].errorDetails?.statusText).toBe("TimeoutError");
}, 15000);

test("request with short delay under timeout succeeds", async () => {
await db.insert(tables.apiKey).values({
id: "token-id",
token: "real-token",
projectId: "project-id",
description: "Test API Key",
createdBy: "user-id",
});

await db.insert(tables.providerKey).values({
id: "provider-key-id",
token: "sk-test-key",
provider: "llmgateway",
organizationId: "org-id",
baseUrl: mockServerUrl,
});

// Request that triggers only 500ms delay (under our 2s timeout)
const res = await app.request("/v1/chat/completions", {
method: "POST",
headers: {
"Content-Type": "application/json",
Authorization: `Bearer real-token`,
},
body: JSON.stringify({
model: "llmgateway/custom",
messages: [
{
role: "user",
content: "TRIGGER_TIMEOUT_500",
},
],
}),
});

expect(res.status).toBe(200);

const json = await res.json();
expect(json).toHaveProperty("choices.[0].message.content");
}, 10000);
});
});
120 changes: 115 additions & 5 deletions apps/gateway/src/chat/chat.ts
Original file line number Diff line number Diff line change
Expand Up @@ -9,6 +9,7 @@ import { isCodingModel } from "@/lib/coding-models.js";
import { calculateCosts, shouldBillCancelledRequests } from "@/lib/costs.js";
import { throwIamException, validateModelAccess } from "@/lib/iam.js";
import { calculateDataStorageCost, insertLog } from "@/lib/logs.js";
import { createCombinedSignal, isTimeoutError } from "@/lib/timeout-config.js";

import {
getCheapestFromAvailableProviders,
Expand Down Expand Up @@ -2777,17 +2778,116 @@ chat.openapi(completions, async (c) => {
: "structured-outputs-2025-11-13";
}

// Create a combined signal for both timeout and cancellation
const fetchSignal = createCombinedSignal(
requestCanBeCanceled ? controller : undefined,
);

res = await fetch(url, {
method: "POST",
headers,
body: JSON.stringify(requestBody),
signal: requestCanBeCanceled ? controller.signal : undefined,
signal: fetchSignal,
});
} catch (error) {
// Clean up the event listeners
c.req.raw.signal.removeEventListener("abort", onAbort);

if (error instanceof Error && error.name === "AbortError") {
// Check for timeout error first (AbortSignal.timeout throws TimeoutError)
if (isTimeoutError(error)) {
// Handle timeout error
const errorMessage =
error instanceof Error ? error.message : "Request timeout";
logger.warn("Upstream request timeout", {
error: errorMessage,
usedProvider,
requestedProvider,
usedModel,
initialRequestedModel,
});

// Log the timeout error in the database
const timeoutPluginIds = plugins?.map((p) => p.id) || [];

const baseLogEntry = createLogEntry(
requestId,
project,
apiKey,
providerKey?.id,
usedModelFormatted,
usedModelMapping,
usedProvider,
initialRequestedModel,
requestedProvider,
messages,
temperature,
max_tokens,
top_p,
frequency_penalty,
presence_penalty,
reasoning_effort,
effort,
response_format,
tools,
tool_choice,
source,
customHeaders,
debugMode,
userAgent,
image_config,
routingMetadata,
rawBody,
null, // No response for timeout error
requestBody,
null, // No upstream response for timeout error
timeoutPluginIds,
undefined, // No plugin results for error case
);

await insertLog({
...baseLogEntry,
duration: Date.now() - startTime,
timeToFirstToken: null,
timeToFirstReasoningToken: null,
responseSize: 0,
content: null,
reasoningContent: null,
finishReason: "upstream_error",
promptTokens: null,
completionTokens: null,
totalTokens: null,
reasoningTokens: null,
cachedTokens: null,
hasError: true,
streamed: true,
canceled: false,
errorDetails: {
statusCode: 0,
statusText: "TimeoutError",
responseText: errorMessage,
},
cachedInputCost: null,
requestCost: null,
webSearchCost: null,
discount: null,
dataStorageCost: "0",
cached: false,
toolResults: null,
});

await stream.writeSSE({
event: "error",
data: JSON.stringify({
error: {
message: `Upstream provider timeout: ${errorMessage}`,
type: "upstream_timeout",
code: "timeout",
},
}),
id: String(eventId++),
});
return;
Comment thread
coderabbitai[bot] marked this conversation as resolved.
Resolved
} else if (error instanceof Error && error.name === "AbortError") {
// Log the canceled request
// Extract plugin IDs for logging (canceled request)
const canceledPluginIds = plugins?.map((p) => p.id) || [];
Expand Down Expand Up @@ -4540,17 +4640,27 @@ chat.openapi(completions, async (c) => {
: "structured-outputs-2025-11-13";
}

// Create a combined signal for both timeout and cancellation
const fetchSignal = createCombinedSignal(
requestCanBeCanceled ? controller : undefined,
);

res = await fetch(url, {
method: "POST",
headers,
body: JSON.stringify(requestBody),
signal: requestCanBeCanceled ? controller.signal : undefined,
signal: fetchSignal,
});
} catch (error) {
if (error instanceof Error && error.name === "AbortError") {
// Check for timeout error first (AbortSignal.timeout throws TimeoutError)
if (isTimeoutError(error)) {
// Capture timeout as a fetch error for logging
fetchError =
error instanceof Error ? error : new Error("Request timeout");
} else if (error instanceof Error && error.name === "AbortError") {
canceled = true;
} else if (error instanceof Error) {
// Capture fetch errors (timeout, connection failures, etc.)
// Capture fetch errors (connection failures, etc.)
fetchError = error;
} else {
throw error;
Expand Down
Loading
Loading