diff --git a/.env.example b/.env.example index b7e853ec10..c754d19b80 100644 --- a/.env.example +++ b/.env.example @@ -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 # ============================================================================= diff --git a/apps/gateway/src/api.spec.ts b/apps/gateway/src/api.spec.ts index 043803d469..17355c7aed 100644 --- a/apps/gateway/src/api.spec.ts +++ b/apps/gateway/src/api.spec.ts @@ -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; @@ -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); + }); }); diff --git a/apps/gateway/src/chat/chat.ts b/apps/gateway/src/chat/chat.ts index 831e731ebf..a0c60fd384 100644 --- a/apps/gateway/src/chat/chat.ts +++ b/apps/gateway/src/chat/chat.ts @@ -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, @@ -2791,17 +2792,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; + } 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) || []; @@ -4613,17 +4713,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; diff --git a/apps/gateway/src/lib/timeout-config.ts b/apps/gateway/src/lib/timeout-config.ts new file mode 100644 index 0000000000..b4b56e3f98 --- /dev/null +++ b/apps/gateway/src/lib/timeout-config.ts @@ -0,0 +1,83 @@ +/** + * Timeout configuration for the gateway. + * + * The AI request timeout should be shorter than the gateway timeout to ensure + * we can catch and handle upstream timeouts before the overall request times out. + * + * All timeout values are read dynamically at call time to support testing. + */ + +/** + * Gets the gateway request timeout - the maximum time a request can take end-to-end. + * Default: 5 minutes (300000ms) + */ +export function getGatewayTimeoutMs(): number { + return Number(process.env.GATEWAY_TIMEOUT_MS) || 300000; +} + +/** + * Gets the AI API request timeout - the maximum time for upstream provider calls. + * Should be shorter than gateway timeout to allow for error handling. + * Default: 4 minutes (240000ms) or 80% of gateway timeout, whichever is smaller + */ +export function getAIRequestTimeoutMs(): number { + const envValue = Number(process.env.AI_REQUEST_TIMEOUT_MS); + if (envValue > 0) { + return envValue; + } + // Default: 4 minutes or 80% of gateway timeout, whichever is smaller + return Math.min(240000, getGatewayTimeoutMs() * 0.8); +} + +// Legacy exports for backwards compatibility (read at module load time) +// These should be avoided in new code - use the getter functions instead +export const GATEWAY_TIMEOUT_MS = getGatewayTimeoutMs(); +export const AI_REQUEST_TIMEOUT_MS = getAIRequestTimeoutMs(); + +/** + * Creates an AbortSignal that will abort after the AI request timeout. + * Can be combined with other signals (e.g., client cancellation) using AbortSignal.any(). + */ +export function createTimeoutSignal(): AbortSignal { + return AbortSignal.timeout(getAIRequestTimeoutMs()); +} + +/** + * Combines a timeout signal with an optional cancellation signal. + * If the cancellation signal is provided, the request will abort on either timeout or cancellation. + * If no cancellation signal is provided, only the timeout will cause an abort. + */ +export function createCombinedSignal( + cancellationController?: AbortController, +): AbortSignal { + const timeoutSignal = createTimeoutSignal(); + + if (cancellationController) { + return AbortSignal.any([timeoutSignal, cancellationController.signal]); + } + + return timeoutSignal; +} + +/** + * Checks if an error is a timeout error. + * AbortSignal.timeout() throws a DOMException with name "TimeoutError". + */ +export function isTimeoutError(error: unknown): boolean { + if (error instanceof Error) { + // AbortSignal.timeout() throws a DOMException with name "TimeoutError" + return error.name === "TimeoutError"; + } + return false; +} + +/** + * Checks if an error is a cancellation error (user-initiated abort). + * AbortController.abort() throws a DOMException with name "AbortError". + */ +export function isCancellationError(error: unknown): boolean { + if (error instanceof Error) { + return error.name === "AbortError"; + } + return false; +} diff --git a/apps/gateway/src/test-utils/mock-openai-server.ts b/apps/gateway/src/test-utils/mock-openai-server.ts index 6b10420689..fba5a0809e 100644 --- a/apps/gateway/src/test-utils/mock-openai-server.ts +++ b/apps/gateway/src/test-utils/mock-openai-server.ts @@ -39,6 +39,26 @@ const sampleErrorResponse = { }, }; +// Helper to extract delay from message content (e.g., "TRIGGER_TIMEOUT_500" -> 500ms) +function extractTimeoutDelay(content: string): number | null { + const match = content.match(/TRIGGER_TIMEOUT_(\d+)/); + if (match) { + return parseInt(match[1], 10); + } + if (content.includes("TRIGGER_TIMEOUT")) { + // Default to 5 seconds if no specific delay is provided + return 5000; + } + return null; +} + +// Helper to delay response +function delay(ms: number): Promise { + return new Promise((resolve) => { + setTimeout(resolve, ms); + }); +} + // Handle OpenAI Responses API endpoint (for gpt-5 and other models with supportsResponsesApi) mockOpenAIServer.post("/v1/responses", async (c) => { const body = await c.req.json(); @@ -101,15 +121,21 @@ mockOpenAIServer.post("/v1/chat/completions", async (c) => { return c.json(sampleErrorResponse); } + // Get the user's message to include in the response + const userMessage = + body.messages.find((msg: any) => msg.role === "user")?.content || ""; + + // Check if this request should trigger a timeout (delay response) + const timeoutDelay = extractTimeoutDelay(userMessage); + if (timeoutDelay) { + await delay(timeoutDelay); + } + // Check if this request should trigger zero tokens response const shouldReturnZeroTokens = body.messages.some( (msg: any) => msg.role === "user" && msg.content.includes("ZERO_TOKENS"), ); - // Get the user's message to include in the response - const userMessage = - body.messages.find((msg: any) => msg.role === "user")?.content || ""; - // Create a custom response that includes the user's message const response = { ...sampleChatCompletionResponse,