diff --git a/apps/server/src/http/timeout.test.ts b/apps/server/src/http/timeout.test.ts new file mode 100644 index 000000000..5270b6545 --- /dev/null +++ b/apps/server/src/http/timeout.test.ts @@ -0,0 +1,110 @@ +import { describe, expect, test } from "bun:test"; + +import { AI_PROXY_PATH } from "@chopin/protocol/ai-credentials"; + +import { applyRequestTimeout, isUnlimitedTimeoutPath, serverIdleTimeoutSeconds } from "./timeout"; + +describe("HTTP server idle timeouts", () => { + test("derives a server idleTimeout above the handover hold window within Bun's 255s bound", () => { + expect(serverIdleTimeoutSeconds(0)).toBe(60); + expect(serverIdleTimeoutSeconds(20_000)).toBe(60); + expect(serverIdleTimeoutSeconds(60_000)).toBe(70); + expect(serverIdleTimeoutSeconds(120_000)).toBe(130); + expect(serverIdleTimeoutSeconds(600_000)).toBe(255); + }); + + test("marks AI proxy, MCP, and connector long-poll paths as exempt from idle timeout", () => { + expect(isUnlimitedTimeoutPath(`${AI_PROXY_PATH}/github-copilot/chat/completions`)).toBe(true); + expect(isUnlimitedTimeoutPath(`${AI_PROXY_PATH}/anthropic/v1/messages`)).toBe(true); + expect(isUnlimitedTimeoutPath(`${AI_PROXY_PATH}/openai/v1/responses`)).toBe(true); + expect(isUnlimitedTimeoutPath("/mcp")).toBe(true); + expect(isUnlimitedTimeoutPath("/connector/mcp")).toBe(true); + + expect(isUnlimitedTimeoutPath(AI_PROXY_PATH)).toBe(false); + expect(isUnlimitedTimeoutPath("/api/session")).toBe(false); + expect(isUnlimitedTimeoutPath("/api/health/ready")).toBe(false); + expect(isUnlimitedTimeoutPath("/ws")).toBe(false); + expect(isUnlimitedTimeoutPath("/api/v1/agent")).toBe(false); + }); + + test("applies timeout(req, 0) only to exempt paths", () => { + let calls: Array<{ path: string; seconds: number }> = []; + let server = { + timeout(request: Request, seconds: number) { + calls.push({ path: new URL(request.url).pathname, seconds }); + }, + }; + + applyRequestTimeout( + new Request(`http://chopin.test${AI_PROXY_PATH}/github-copilot/chat/completions`, { + method: "POST", + }), + server, + ); + applyRequestTimeout(new Request("http://chopin.test/mcp", { method: "POST" }), server); + applyRequestTimeout( + new Request("http://chopin.test/connector/mcp", { method: "POST" }), + server, + ); + applyRequestTimeout(new Request("http://chopin.test/api/session"), server); + + expect(calls).toEqual([ + { path: `${AI_PROXY_PATH}/github-copilot/chat/completions`, seconds: 0 }, + { path: "/mcp", seconds: 0 }, + { path: "/connector/mcp", seconds: 0 }, + ]); + }); + + test( + "keeps an AI proxy SSE stream alive past Bun's server idleTimeout while regular routes still time out", + async () => { + let cancelled: string[] = []; + let server = Bun.serve({ + hostname: "127.0.0.1", + port: 0, + idleTimeout: 1, + fetch(request, self) { + applyRequestTimeout(request, self); + let path = new URL(request.url).pathname; + let stream = new ReadableStream({ + async start(controller) { + controller.enqueue(new TextEncoder().encode("data: first\n\n")); + await Bun.sleep(5_000); + try { + controller.enqueue(new TextEncoder().encode("data: second\n\n")); + controller.close(); + } catch {} + }, + cancel() { + cancelled.push(path); + }, + }); + return new Response(stream, { + headers: { "content-type": "text/event-stream" }, + }); + }, + }); + + try { + let base = `http://127.0.0.1:${server.port}`; + let aiPath = `${AI_PROXY_PATH}/github-copilot/chat/completions`; + let [aiResult, regularResult] = await Promise.all([ + fetch(`${base}${aiPath}`, { method: "POST" }).then(res => res.text()), + fetch(`${base}/api/slow`) + .then(res => res.text()) + .then( + text => ({ ok: true as const, text }), + error => ({ ok: false as const, error }), + ), + ]); + + expect(aiResult).toBe("data: first\n\ndata: second\n\n"); + expect(regularResult.ok).toBe(false); + expect(cancelled).toEqual(["/api/slow"]); + } finally { + await server.stop(true); + } + }, + 15_000, + ); +}); diff --git a/apps/server/src/http/timeout.ts b/apps/server/src/http/timeout.ts new file mode 100644 index 000000000..c54aa27fe --- /dev/null +++ b/apps/server/src/http/timeout.ts @@ -0,0 +1,32 @@ +import { AI_PROXY_PATH } from "@chopin/protocol/ai-credentials"; + +import type { Server } from "bun"; + +const MIN_IDLE_TIMEOUT_SECONDS = 60; +const MAX_IDLE_TIMEOUT_SECONDS = 255; +const HANDOVER_IDLE_MARGIN_SECONDS = 10; + +const UNLIMITED_EXACT_PATHS = new Set(["/mcp", "/connector/mcp"]); +const AI_PROXY_PREFIX = `${AI_PROXY_PATH}/`; + +export function serverIdleTimeoutSeconds(holdMs: number): number { + let handoverSeconds = Math.ceil(Math.max(0, holdMs) / 1_000) + HANDOVER_IDLE_MARGIN_SECONDS; + return Math.min(MAX_IDLE_TIMEOUT_SECONDS, Math.max(MIN_IDLE_TIMEOUT_SECONDS, handoverSeconds)); +} + +export function isUnlimitedTimeoutPath(pathname: string): boolean { + return pathname.startsWith(AI_PROXY_PREFIX) || UNLIMITED_EXACT_PATHS.has(pathname); +} + +export function applyRequestTimeout( + request: Request, + server: Pick, "timeout">, +): void { + let pathname: string; + try { + pathname = new URL(request.url).pathname; + } catch { + return; + } + if (isUnlimitedTimeoutPath(pathname)) server.timeout(request, 0); +} diff --git a/apps/server/src/main.ts b/apps/server/src/main.ts index ffdd37595..1c482aff0 100644 --- a/apps/server/src/main.ts +++ b/apps/server/src/main.ts @@ -110,6 +110,7 @@ import { finishTurns } from "./handover/turns"; import { Readiness, registerHealthRoutes } from "./http/health"; import { registerMachinesPath } from "./http/machines-path"; import { Router } from "./http/router"; +import { applyRequestTimeout, serverIdleTimeoutSeconds } from "./http/timeout"; import { JobExecutionError, JobRegistry } from "./jobs/registry"; import * as JobBrowser from "./jobs/browser"; import { DocumentDescriptionProjector } from "./jobs/document-description"; @@ -2373,8 +2374,10 @@ function listen(): Server { return Bun.serve({ hostname: config.host, port: config.port, + idleTimeout: serverIdleTimeoutSeconds(config.handover.holdMs), fetch(req, self) { + applyRequestTimeout(req, self); return requests.handle(req, abandoned => route(req, self, abandoned)); },