From 2b00825b0a92d28dc855fd8e4b5a36d200a03a39 Mon Sep 17 00:00:00 2001 From: Chris Scott <99081550+chriswritescode-dev@users.noreply.github.com> Date: Mon, 2 Nov 2026 10:11:15 -0500 Subject: [PATCH] section 4: Phase 4: One streaming proxy forwarder used by both proxy ro --- backend/src/routes/opencode-proxy.ts | 15 +- backend/src/routes/opencode-server-proxy.ts | 57 ++----- backend/src/utils/proxy-forward.ts | 79 ++++++++++ backend/test/routes/opencode-proxy.test.ts | 12 ++ backend/test/utils/proxy-forward.test.ts | 160 ++++++++++++++++++++ 5 files changed, 270 insertions(+), 53 deletions(-) create mode 100644 backend/src/utils/proxy-forward.ts create mode 100644 backend/test/utils/proxy-forward.test.ts diff --git a/backend/src/routes/opencode-proxy.ts b/backend/src/routes/opencode-proxy.ts index d3be10b5..02dd2c00 100644 --- a/backend/src/routes/opencode-proxy.ts +++ b/backend/src/routes/opencode-proxy.ts @@ -16,6 +16,7 @@ import { getRepoById } from '../db/queries' import { getTrustedOrigins, getWorkspacePath } from '@opencode-manager/shared/config/env' import { isPathWithinRoot } from '../utils/fs-safe' import { buildProxyResponseHeaders, filterProxyHeaders } from '../utils/proxy-headers' +import { forwardProxyRequest } from '../utils/proxy-forward' import { connectUpstreamWebSocket, createBridgedSocketEvents, @@ -192,20 +193,12 @@ export function createOpenCodeProxyRoutes(db: Database, settingsService: Setting const upstreamUrl = `${getOpenCodeUpstreamBaseUrl()}${pathSuffix}${url.search}` try { - const upstreamResponse = await fetch(upstreamUrl, { + return await forwardProxyRequest({ + url: upstreamUrl, method: c.req.method, headers, body: requestBody, - redirect: 'manual', - duplex: 'half', - }) - - const responseHeaders = buildProxyResponseHeaders(upstreamResponse.headers) - - return new Response(upstreamResponse.body, { - status: upstreamResponse.status, - statusText: upstreamResponse.statusText, - headers: responseHeaders, + buildResponseHeaders: buildProxyResponseHeaders, }) } catch { return c.json({ error: 'Proxy request failed' }, 502) diff --git a/backend/src/routes/opencode-server-proxy.ts b/backend/src/routes/opencode-server-proxy.ts index 38c68b31..38050678 100644 --- a/backend/src/routes/opencode-server-proxy.ts +++ b/backend/src/routes/opencode-server-proxy.ts @@ -6,7 +6,8 @@ import { type OpenCodeServerConnection, type OpenCodeServerRegistry, } from '../services/opencode-server-registry' -import { filterProxyHeaders, NULL_BODY_STATUSES } from '../utils/proxy-headers' +import { filterProxyHeaders } from '../utils/proxy-headers' +import { forwardProxyRequest, ProxyHeadersTimeoutError } from '../utils/proxy-forward' import { logger } from '../utils/logger' const MOUNT_PREFIX = '/api/opencode/servers/' @@ -117,58 +118,30 @@ export function createOpenCodeServerProxyRoutes( headers.Authorization = connection.authorization } - const hasBody = c.req.method !== 'GET' && c.req.method !== 'HEAD' - - let headersTimeoutTimer: ReturnType | null = null - let headersTimedOut = false - let upstreamSignal = c.req.raw.signal - if (!hasBody) { - const timeoutController = new AbortController() - headersTimeoutTimer = setTimeout(() => { - headersTimedOut = true - timeoutController.abort() - }, upstreamHeadersTimeoutMs) - upstreamSignal = AbortSignal.any([c.req.raw.signal, timeoutController.signal]) - } + const requestBody = c.req.method !== 'GET' && c.req.method !== 'HEAD' + ? c.req.raw.body + : null try { - const upstreamResponse = await fetchFn(upstream.url.toString(), { + return await forwardProxyRequest({ + url: upstream.url.toString(), method: c.req.method, headers, - body: hasBody ? c.req.raw.body : undefined, - redirect: 'manual', - signal: upstreamSignal, - duplex: 'half', - }) - - if (headersTimeoutTimer !== null) { - clearTimeout(headersTimeoutTimer) - headersTimeoutTimer = null - } - - const responseHeaders = new Headers( - filterProxyHeaders(upstreamResponse.headers, RESPONSE_EXCLUDED_HEADERS), - ) - const responseBody = NULL_BODY_STATUSES.has(upstreamResponse.status) - ? null - : upstreamResponse.body - - return new Response(responseBody, { - status: upstreamResponse.status, - statusText: upstreamResponse.statusText, - headers: responseHeaders, + body: requestBody, + signal: c.req.raw.signal, + headersTimeoutMs: requestBody === null ? upstreamHeadersTimeoutMs : undefined, + fetchFn, + buildResponseHeaders: (upstreamHeaders) => new Headers( + filterProxyHeaders(upstreamHeaders, RESPONSE_EXCLUDED_HEADERS), + ), }) } catch (error) { - if (headersTimedOut) { + if (error instanceof ProxyHeadersTimeoutError) { logger.warn(`OpenCode server proxy timed out waiting for headers: ${c.req.method} ${upstream.url.host}${upstreamPath.path}`, error) return c.json({ error: 'Remote OpenCode server timed out' }, 504) } logger.warn(`OpenCode server proxy request failed: ${c.req.method} ${upstream.url.host}${upstreamPath.path}`, error) return c.json({ error: 'Remote OpenCode server unreachable' }, 502) - } finally { - if (headersTimeoutTimer !== null) { - clearTimeout(headersTimeoutTimer) - } } }) diff --git a/backend/src/utils/proxy-forward.ts b/backend/src/utils/proxy-forward.ts new file mode 100644 index 00000000..55a70a09 --- /dev/null +++ b/backend/src/utils/proxy-forward.ts @@ -0,0 +1,79 @@ +import { NULL_BODY_STATUSES } from './proxy-headers' + +export class ProxyHeadersTimeoutError extends Error { + constructor(timeoutMs: number) { + super(`Upstream did not send response headers within ${timeoutMs}ms`) + this.name = 'ProxyHeadersTimeoutError' + } +} + +export interface ForwardProxyRequestInput { + url: string | URL + method: string + headers: Record + body: RequestInit['body'] + signal?: AbortSignal + headersTimeoutMs?: number + fetchFn?: typeof fetch + buildResponseHeaders: (upstream: Headers) => Headers +} + +/** + * Forwards one HTTP request to an upstream server and returns its response with the + * body left unread so it keeps streaming to the caller. + * + * When `headersTimeoutMs` is set, requests without a body are aborted if the upstream + * does not send response headers in time; that abort surfaces as a + * `ProxyHeadersTimeoutError`. Every other fetch failure is rethrown unchanged. + */ +export async function forwardProxyRequest({ + url, + method, + headers, + body, + signal, + headersTimeoutMs, + fetchFn = fetch, + buildResponseHeaders, +}: ForwardProxyRequestInput): Promise { + const timeoutMs = body === null || body === undefined ? headersTimeoutMs : undefined + const timeoutController = timeoutMs === undefined ? null : new AbortController() + let headersTimedOut = false + const timeoutTimer = timeoutController === null + ? null + : setTimeout(() => { + headersTimedOut = true + timeoutController.abort() + }, timeoutMs) + + const requestSignal = timeoutController === null + ? signal + : signal + ? AbortSignal.any([signal, timeoutController.signal]) + : timeoutController.signal + + let upstream: Response + try { + upstream = await fetchFn(url, { + method, + headers, + body: body ?? undefined, + redirect: 'manual', + duplex: 'half', + signal: requestSignal, + }) + } catch (error) { + if (headersTimedOut && timeoutMs !== undefined) { + throw new ProxyHeadersTimeoutError(timeoutMs) + } + throw error + } finally { + if (timeoutTimer !== null) clearTimeout(timeoutTimer) + } + + return new Response(NULL_BODY_STATUSES.has(upstream.status) ? null : upstream.body, { + status: upstream.status, + statusText: upstream.statusText, + headers: buildResponseHeaders(upstream.headers), + }) +} diff --git a/backend/test/routes/opencode-proxy.test.ts b/backend/test/routes/opencode-proxy.test.ts index cb491644..2ca982a9 100644 --- a/backend/test/routes/opencode-proxy.test.ts +++ b/backend/test/routes/opencode-proxy.test.ts @@ -323,6 +323,18 @@ describe('opencode-proxy routes', () => { expect(body.error).toBe('Proxy request failed') }) + it('returns a null body for bodyless upstream statuses', async () => { + const upstreamFetch = vi.fn().mockResolvedValue(new Response(null, { status: 204 })) + globalThis.fetch = upstreamFetch as unknown as typeof fetch + + const res = await app.request('/api/opencode-proxy/doc', { + headers: { Authorization: 'Bearer test-internal-token' }, + }) + + expect(res.status).toBe(204) + expect(await res.text()).toBe('') + }) + it('preserves query string in upstream URL', async () => { const upstreamFetch = vi.fn().mockResolvedValue( new Response('ok', { status: 200, headers: { 'content-type': 'text/plain' } }) diff --git a/backend/test/utils/proxy-forward.test.ts b/backend/test/utils/proxy-forward.test.ts new file mode 100644 index 00000000..50a81838 --- /dev/null +++ b/backend/test/utils/proxy-forward.test.ts @@ -0,0 +1,160 @@ +import { describe, expect, it, vi } from 'vitest' +import { + forwardProxyRequest, + ProxyHeadersTimeoutError, + type ForwardProxyRequestInput, +} from '../../src/utils/proxy-forward' + +function forward(overrides: Partial = {}): Promise { + return forwardProxyRequest({ + url: 'http://upstream.example/api/event', + method: 'GET', + headers: { 'x-test': '1' }, + body: null, + buildResponseHeaders: (headers) => new Headers(headers), + ...overrides, + }) +} + +function deferred() { + let resolve!: () => void + const promise = new Promise((settle) => { + resolve = settle + }) + return { promise, resolve } +} + +async function readWithin( + reader: ReadableStreamDefaultReader, + timeoutMs = 500, +) { + let timer: ReturnType | undefined + try { + return await Promise.race([ + reader.read(), + new Promise((_resolve, reject) => { + timer = setTimeout(() => reject(new Error('upstream chunk was buffered instead of streamed')), timeoutMs) + }), + ]) + } finally { + if (timer !== undefined) clearTimeout(timer) + } +} + +describe('forwardProxyRequest', () => { + it('streams the upstream body instead of buffering it', async () => { + const encoder = new TextEncoder() + const secondChunk = deferred() + let secondChunkEnqueued = false + const upstream = new Response(new ReadableStream({ + async start(controller) { + controller.enqueue(encoder.encode('first')) + await secondChunk.promise + secondChunkEnqueued = true + controller.enqueue(encoder.encode('second')) + controller.close() + }, + })) + const fetchFn = vi.fn().mockResolvedValue(upstream) + + const response = await forward({ fetchFn: fetchFn as unknown as typeof fetch }) + const reader = response.body?.getReader() + expect(reader).toBeDefined() + + const decoder = new TextDecoder() + const first = await readWithin(reader as ReadableStreamDefaultReader) + expect(decoder.decode(first.value)).toBe('first') + expect(secondChunkEnqueued).toBe(false) + + secondChunk.resolve() + const readerRef = reader as ReadableStreamDefaultReader + expect(decoder.decode((await readerRef.read()).value)).toBe('second') + expect((await readerRef.read()).done).toBe(true) + }) + + it.each([204, 304])('returns a null body for upstream status %i', async (status) => { + const fetchFn = vi.fn().mockResolvedValue(new Response(null, { status })) + + const response = await forward({ fetchFn: fetchFn as unknown as typeof fetch }) + + expect(response.status).toBe(status) + expect(response.body).toBeNull() + }) + + it('aborts a body-less request when the upstream sends no headers in time', async () => { + let receivedSignal: AbortSignal | undefined + const fetchFn = vi.fn((_url: string | URL, init: RequestInit) => new Promise((_resolve, reject) => { + receivedSignal = init.signal ?? undefined + init.signal?.addEventListener('abort', () => reject(new DOMException('Aborted', 'AbortError'))) + })) + + await expect( + forward({ fetchFn: fetchFn as unknown as typeof fetch, headersTimeoutMs: 10 }), + ).rejects.toBeInstanceOf(ProxyHeadersTimeoutError) + expect(receivedSignal?.aborted).toBe(true) + }) + + it('does not apply the headers timeout to a request with a body', async () => { + const client = new AbortController() + let receivedSignal: AbortSignal | undefined + const fetchFn = vi.fn((_url: string | URL, init: RequestInit) => new Promise((resolve, reject) => { + receivedSignal = init.signal ?? undefined + init.signal?.addEventListener('abort', () => reject(new DOMException('Aborted', 'AbortError'))) + setTimeout(() => resolve(new Response('ok')), 40) + })) + + const response = await forward({ + method: 'POST', + body: '{"title":"x"}', + signal: client.signal, + headersTimeoutMs: 10, + fetchFn: fetchFn as unknown as typeof fetch, + }) + + expect(response.status).toBe(200) + expect(receivedSignal).toBe(client.signal) + }) + + it('rethrows non-timeout fetch failures unchanged', async () => { + const failure = new Error('connect ECONNREFUSED') + const fetchFn = vi.fn().mockRejectedValue(failure) + + await expect(forward({ fetchFn: fetchFn as unknown as typeof fetch })).rejects.toBe(failure) + }) + + it('forwards method, headers, and body with a manual redirect and half duplex', async () => { + const fetchFn = vi.fn().mockResolvedValue(new Response('ok', { status: 201, statusText: 'Created' })) + + const response = await forward({ + url: 'http://upstream.example/api/session', + method: 'POST', + headers: { 'content-type': 'application/json', 'x-test': '1' }, + body: '{"title":"x"}', + fetchFn: fetchFn as unknown as typeof fetch, + }) + + const [calledUrl, init] = fetchFn.mock.calls[0] as [string | URL, RequestInit] + expect(calledUrl).toBe('http://upstream.example/api/session') + expect(init.method).toBe('POST') + expect(init.headers).toEqual({ 'content-type': 'application/json', 'x-test': '1' }) + expect(init.body).toBe('{"title":"x"}') + expect(init.redirect).toBe('manual') + expect(init.duplex).toBe('half') + expect(response.status).toBe(201) + expect(response.statusText).toBe('Created') + }) + + it('builds the returned response headers from the upstream response', async () => { + const fetchFn = vi.fn().mockResolvedValue(new Response('ok', { + status: 200, + headers: { 'content-type': 'text/event-stream' }, + })) + + const response = await forward({ + fetchFn: fetchFn as unknown as typeof fetch, + buildResponseHeaders: (headers) => new Headers({ 'x-proxied': headers.get('content-type') ?? '' }), + }) + + expect(response.headers.get('x-proxied')).toBe('text/event-stream') + }) +})