mirror of
https://github.com/chriswritescode-dev/opencode-manager.git
synced 2026-12-05 12:24:30 +01:00
section 4: Phase 4: One streaming proxy forwarder used by both proxy ro
This commit is contained in:
1 parent
680a336a24
commit
2b00825b0a
5 files changed
+270
-53
No files matched your search
@@ -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)
|
||||
|
||||
@@ -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<typeof setTimeout> | 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)
|
||||
}
|
||||
}
|
||||
})
|
||||
|
||||
|
||||
@@ -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<string, string>
|
||||
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<Response> {
|
||||
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),
|
||||
})
|
||||
}
|
||||
@@ -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' } })
|
||||
|
||||
@@ -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<ForwardProxyRequestInput> = {}): Promise<Response> {
|
||||
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<void>((settle) => {
|
||||
resolve = settle
|
||||
})
|
||||
return { promise, resolve }
|
||||
}
|
||||
|
||||
async function readWithin(
|
||||
reader: ReadableStreamDefaultReader<Uint8Array>,
|
||||
timeoutMs = 500,
|
||||
) {
|
||||
let timer: ReturnType<typeof setTimeout> | undefined
|
||||
try {
|
||||
return await Promise.race([
|
||||
reader.read(),
|
||||
new Promise<never>((_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<Uint8Array>({
|
||||
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<Uint8Array>)
|
||||
expect(decoder.decode(first.value)).toBe('first')
|
||||
expect(secondChunkEnqueued).toBe(false)
|
||||
|
||||
secondChunk.resolve()
|
||||
const readerRef = reader as ReadableStreamDefaultReader<Uint8Array>
|
||||
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<Response>((_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<Response>((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')
|
||||
})
|
||||
})
|
||||
Reference in new issue
Block a user