section 5: Phase 5: Stop buffering in /api/opencode/*

This commit is contained in:
Chris Scott committed 2026-11-02 10:15:37 -05:00
1 parent 2b00825b0a
commit 66b5d1ac06
3 files changed
+82 -61

No files matched your search

+16 -55
View File
@@ -1,7 +1,8 @@
import { logger } from '../../utils/logger'
import { ENV } from '@opencode-manager/shared/config/env'
import { createOpenCodeApi, type OpenCodeApi } from '@opencode-manager/shared/opencode'
import { filterProxyHeaders, NULL_BODY_STATUSES } from '../../utils/proxy-headers'
import { filterProxyHeaders } from '../../utils/proxy-headers'
import { forwardProxyRequest } from '../../utils/proxy-forward'
import { getOpenCodeBasicAuthHeader, type OpenCodePasswordResolver } from './auth'
import { getOpenCodeUpstreamBaseUrl, withDefaultOpenCodeDirectory } from './upstream'
@@ -61,76 +62,36 @@ export class FetchOpenCodeClient implements OpenCodeClient {
return this.fetchFn(input, { ...init, headers })
}
private async request(req: { method: string; path: string; body?: string; headers?: Record<string, string> }): Promise<Response> {
const url = new URL(this.resolveBaseUrl() + req.path)
const headers: Record<string, string> = this.withDirectoryHeader({ ...(req.headers ?? {}) })
async forwardRaw(request: Request): Promise<Response> {
const url = new URL(request.url)
const path = url.pathname.replace(/^\/api\/opencode/, '') + url.search
const headers = this.withDirectoryHeader(filterProxyHeaders(request.headers))
const basicAuth = await this.getBasicAuth()
if (basicAuth) {
headers.Authorization = basicAuth
}
const hasBody = request.method !== 'GET' && request.method !== 'HEAD'
try {
const response = await this.fetchFn(url, {
method: req.method,
return await forwardProxyRequest({
url: this.resolveBaseUrl() + path,
method: request.method,
headers,
body: req.body,
})
const filteredHeaders = filterProxyHeaders(response.headers)
if (NULL_BODY_STATUSES.has(response.status)) {
return new Response(null, {
status: response.status,
statusText: response.statusText,
headers: filteredHeaders,
})
}
const body = await response.text()
return new Response(body, {
status: response.status,
statusText: response.statusText,
headers: filteredHeaders,
body: hasBody ? request.body : null,
signal: request.signal,
fetchFn: this.fetchFn,
buildResponseHeaders: (upstream) => new Headers(filterProxyHeaders(upstream)),
})
} catch (error) {
logger.error(`Proxy request failed for ${req.path}:`, error)
logger.error(`Proxy request failed for ${path}:`, error)
return new Response(JSON.stringify({ error: 'Proxy request failed' }), {
status: 502,
headers: { 'Content-Type': 'application/json' },
})
}
}
async forwardRaw(request: Request): Promise<Response> {
const url = new URL(request.url)
const cleanPathname = url.pathname.replace(/^\/api\/opencode/, '')
if (url.pathname.includes('/permissions/')) {
logger.info(`Proxying permission request: ${url.pathname}${url.search} -> ${cleanPathname}${url.search}`)
}
const headers: Record<string, string> = {}
request.headers.forEach((value, key) => {
const lowerKey = key.toLowerCase()
if (!['host', 'connection', 'authorization'].includes(lowerKey)) {
headers[key] = value
}
})
const body = request.method !== 'GET' && request.method !== 'HEAD'
? await request.text()
: undefined
return this.request({
method: request.method,
path: cleanPathname + url.search,
body,
headers,
})
}
}
export function createOpenCodeClient(
@@ -2,7 +2,7 @@ import { describe, it, expect, vi, beforeEach } from 'vitest'
import { Hono } from 'hono'
import type { MiddlewareHandler } from 'hono'
import { createAuthenticatedOpenCodeProxyRoutes } from '../../src/routes/opencode-auth-proxy'
import type { OpenCodeClient } from '../../src/services/opencode/client'
import { FetchOpenCodeClient, type OpenCodeClient } from '../../src/services/opencode/client'
import { OpenCodeSupervisor } from '../../src/services/opencode-supervisor'
import type { SettingsService } from '../../src/services/settings'
@@ -14,7 +14,8 @@ vi.mock('../../src/services/opencode-single-server', () => ({
const forwardRawMock = vi.hoisted(() => vi.fn<OpenCodeClient['forwardRaw']>(async () => new Response('ok', { status: 200 })))
vi.mock('../../src/services/opencode/client', () => ({
vi.mock('../../src/services/opencode/client', async (importOriginal) => ({
...(await importOriginal<typeof import('../../src/services/opencode/client')>()),
createOpenCodeClient: vi.fn(),
}))
@@ -344,3 +345,54 @@ describe('authenticated opencode proxy routes', () => {
expect(forwarded).toEqual(JSON.parse(body))
})
})
describe('authenticated opencode proxy streaming', () => {
it('streams the upstream body chunk by chunk while forwarding the request body as a stream', async () => {
const encoder = new TextEncoder()
const decoder = new TextDecoder()
let upstreamController!: ReadableStreamDefaultController<Uint8Array>
const upstreamBody = new ReadableStream<Uint8Array>({
start(controller) {
upstreamController = controller
},
})
let capturedInit: RequestInit | undefined
const fetchFn = async (_input: URL | Request | string, init?: RequestInit) => {
capturedInit = init
return new Response(upstreamBody, { status: 200, headers: { 'Content-Type': 'text/event-stream' } })
}
const client = new FetchOpenCodeClient({
baseUrl: 'http://127.0.0.1:5551',
basicAuth: '',
fetchFn: fetchFn as unknown as typeof fetch,
})
const app = new Hono()
app.route('/api/opencode', createAuthenticatedOpenCodeProxyRoutes(client, passThroughAuth))
const responsePromise = app.request('/api/opencode/event', {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({ hello: 'world' }),
})
upstreamController.enqueue(encoder.encode('first-chunk'))
const response = await responsePromise
expect(response.status).toBe(200)
expect(response.headers.get('content-type')).toBe('text/event-stream')
const reader = response.body!.getReader()
const first = await reader.read()
expect(decoder.decode(first.value)).toBe('first-chunk')
upstreamController.enqueue(encoder.encode('second-chunk'))
const second = await reader.read()
expect(decoder.decode(second.value)).toBe('second-chunk')
upstreamController.close()
await reader.cancel()
expect(capturedInit?.body).toBeInstanceOf(ReadableStream)
expect(capturedInit?.duplex).toBe('half')
})
})
+12 -4
View File
@@ -36,6 +36,11 @@ import { createOpenCodeClient, FetchOpenCodeClient } from '../../../src/services
import { ENV } from '@opencode-manager/shared/config/env'
import { openCodeLocation } from '@opencode-manager/shared/opencode'
async function readBodyText(body: RequestInit['body']): Promise<string | null> {
if (!(body instanceof ReadableStream)) return null
return await new Response(body).text()
}
describe('OpenCodeClient', () => {
const baseUrl = 'http://127.0.0.1:5551'
const basicAuth = 'Basic dXNlcjpwYXNz'
@@ -91,9 +96,9 @@ describe('OpenCodeClient', () => {
expect((capturedInit?.headers as Record<string, string>)['x-opencode-directory']).toBe('%2Frepo%2Fb')
})
it('should read body for POST but not for GET/HEAD', async () => {
it('should stream the body for POST but not for GET/HEAD', async () => {
const mockResponse = new Response(JSON.stringify({}), { status: 200 })
const capturedBodies: unknown[] = []
const capturedBodies: Array<RequestInit['body']> = []
const fetchFn = async (_: URL | Request | string, init?: RequestInit) => {
capturedBodies.push(init?.body)
return mockResponse
@@ -119,7 +124,8 @@ describe('OpenCodeClient', () => {
await client.forwardRaw(headRequest)
expect(capturedBodies[0]).toBe('test body')
expect(capturedBodies[0]).toBeInstanceOf(ReadableStream)
expect(await readBodyText(capturedBodies[0])).toBe('test body')
expect(capturedBodies[1]).toBeUndefined()
expect(capturedBodies[2]).toBeUndefined()
})
@@ -177,7 +183,9 @@ describe('OpenCodeClient', () => {
expect(capturedUrl?.toString()).toBe(baseUrl + '/config?foo=bar')
expect(capturedInit?.method).toBe('POST')
expect(capturedInit?.body).toBe('request-body-content')
expect(capturedInit?.body).toBeInstanceOf(ReadableStream)
expect(await readBodyText(capturedInit?.body)).toBe('request-body-content')
expect(capturedInit?.duplex).toBe('half')
expect(capturedInit?.headers).toEqual(expect.objectContaining({
Authorization: basicAuth,
'x-caller': 'caller-value',