refactor(sse): batch parts directory-aware and serialize backend writes

This commit is contained in:
Chris Scott committed 2026-06-05 21:53:30 -04:00
1 parent 94941eb7a0
commit a363138dbd
9 files changed
+159 -102

No files matched your search

+16 -11
View File
@@ -5,28 +5,28 @@ export interface QueuedSSEWriterInput {
export interface QueuedSSEWriter {
writeSSE: (event: string, data: string) => void
writeFrame: (frame: Uint8Array) => void
close: () => void
}
const sharedEncoder = new TextEncoder()
export function encodeSSEFrame(event: string, data: string): Uint8Array {
const head = event ? `event: ${event}\n` : ''
return sharedEncoder.encode(`${head}data: ${data}\n\n`)
}
export function createQueuedSSEWriter(input: QueuedSSEWriterInput): QueuedSSEWriter {
const encoder = new TextEncoder()
let chain = Promise.resolve()
let closed = false
const writeSSE = (event: string, data: string) => {
const writeFrame = (frame: Uint8Array) => {
if (closed) return
const lines: string[] = []
if (event) lines.push(`event: ${event}`)
lines.push(`data: ${data}`)
lines.push('')
lines.push('')
const encoded = encoder.encode(lines.join('\n'))
chain = chain
.then(async () => {
if (closed) return
await input.write(encoded)
await input.write(frame)
})
.catch((error) => {
if (!closed) {
@@ -36,9 +36,14 @@ export function createQueuedSSEWriter(input: QueuedSSEWriterInput): QueuedSSEWri
})
}
const writeSSE = (event: string, data: string) => {
if (closed) return
writeFrame(encodeSSEFrame(event, data))
}
const close = () => {
closed = true
}
return { writeSSE, close }
return { writeSSE, writeFrame, close }
}
+3
View File
@@ -42,6 +42,9 @@ export function createSSERoutes() {
(event, data) => {
queuedWriter.writeSSE(event, data)
},
(frame) => {
queuedWriter.writeFrame(frame)
},
directories
)
+14 -6
View File
@@ -3,13 +3,16 @@ import { logger } from '../utils/logger'
import { ENV } from '@opencode-manager/shared/config/env'
import { DEFAULTS } from '@opencode-manager/shared/config'
import { getOpenCodeBasicAuthHeader, type OpenCodePasswordResolver } from './opencode/auth'
import { encodeSSEFrame } from '../routes/sse-writer'
type SSEClientCallback = (event: string, data: string) => void
type SSEClientFrameWriter = (frame: Uint8Array) => void
type SSEEventListener = (directory: string, event: SSEEvent) => void
interface SSEClient {
id: string
callback: SSEClientCallback
writeFrame: SSEClientFrameWriter
directories: Set<string>
visible: boolean
activeSessionId: string | null
@@ -95,10 +98,11 @@ class SSEAggregator {
void this.connectUpstream()
}
addClient(id: string, callback: SSEClientCallback, directories: string[]): () => void {
addClient(id: string, callback: SSEClientCallback, writeFrame: SSEClientFrameWriter, directories: string[]): () => void {
const client: SSEClient = {
id,
callback,
writeFrame,
directories: new Set(directories),
visible: false,
activeSessionId: null
@@ -211,7 +215,7 @@ class SSEAggregator {
if (!client || !client.directories.has(directory)) return
for (const item of items) {
const payload = JSON.stringify({ type, properties: item, directory })
const payload = JSON.stringify({ directory, payload: { type, properties: item } })
try {
client.callback('message', payload)
} catch (error) {
@@ -316,11 +320,13 @@ class SSEAggregator {
try { listener(directory, parsed) } catch { /* ignore listener errors */ }
})
const clientData = JSON.stringify({ ...parsed, directory })
let frame: Uint8Array | undefined
const getFrame = (): Uint8Array => (frame ??= encodeSSEFrame('message', data))
this.clients.forEach((client) => {
if (client.directories.has(directory)) {
try {
client.callback('message', clientData)
client.writeFrame(getFrame())
} catch (error) {
logger.error(`Failed to send to client ${client.id}:`, error)
}
@@ -478,8 +484,10 @@ export const sseAggregator = SSEAggregator.getInstance()
export function broadcastSSHHostKeyRequest(data: Record<string, unknown>): void {
const event = JSON.stringify({
type: 'ssh.host-key-request',
properties: data,
payload: {
type: 'ssh.host-key-request',
properties: data,
},
})
sseAggregator.broadcastToAll('message', event)
}
+29 -1
View File
@@ -1,7 +1,35 @@
import { describe, it, expect, vi } from 'vitest'
import { createQueuedSSEWriter } from '../../src/routes/sse-writer'
import { createQueuedSSEWriter, encodeSSEFrame } from '../../src/routes/sse-writer'
describe('encodeSSEFrame', () => {
const decoder = new TextDecoder()
it('encodes an event frame', () => {
expect(decoder.decode(encodeSSEFrame('message', '{"n":1}'))).toBe('event: message\ndata: {"n":1}\n\n')
})
it('omits the event line when event is empty', () => {
expect(decoder.decode(encodeSSEFrame('', '{"n":1}'))).toBe('data: {"n":1}\n\n')
})
})
describe('createQueuedSSEWriter', () => {
describe('writeFrame', () => {
it('writes a pre-encoded frame through the serialized chain', async () => {
const writes: Uint8Array[] = []
const write = vi.fn((chunk: Uint8Array) => { writes.push(chunk) })
const onError = vi.fn()
const writer = createQueuedSSEWriter({ write, onError })
const frame = encodeSSEFrame('message', '{"shared":true}')
writer.writeFrame(frame)
await vi.waitFor(() => expect(write).toHaveBeenCalledTimes(1))
expect(writes[0]).toBe(frame)
expect(onError).not.toHaveBeenCalled()
})
})
describe('serializes frames in enqueue order', () => {
it('should not execute second write until first resolves', async () => {
let firstWriteResolve!: () => void
+27 -22
View File
@@ -23,10 +23,15 @@ interface CapturedEvent {
function createCapturingClient() {
const events: CapturedEvent[] = []
const frames: string[] = []
const decoder = new TextDecoder()
const callback = (event: string, data: string) => {
events.push({ event, data })
}
return { callback, events }
const writeFrame = (frame: Uint8Array) => {
frames.push(decoder.decode(frame))
}
return { callback, writeFrame, events, frames }
}
function makeFetcher(map: Record<string, { permissions?: unknown[]; questions?: unknown[] }>): PendingActionsFetcher {
@@ -69,29 +74,29 @@ describe('SSEAggregator pending replay on connect', () => {
})
sseAggregator.setPendingActionsFetcher(fetcher)
const { callback, events } = createCapturingClient()
sseAggregator.addClient('client-1', callback, ['/repo/a', '/repo/b'])
const { callback, writeFrame, events } = createCapturingClient()
sseAggregator.addClient('client-1', callback, writeFrame, ['/repo/a', '/repo/b'])
await flushReplay()
expect(events).toHaveLength(4)
const parsed = events.map(e => JSON.parse(e.data) as { type: string; properties: { id: string }; directory: string })
const parsed = events.map(e => JSON.parse(e.data) as { directory: string; payload: { type: string; properties: { id: string } } })
expect(parsed.filter(p => p.type === 'permission.asked' && p.directory === '/repo/a').map(p => p.properties.id)).toEqual([
expect(parsed.filter(p => p.payload.type === 'permission.asked' && p.directory === '/repo/a').map(p => p.payload.properties.id)).toEqual([
'perm-1',
'perm-2',
])
expect(parsed.filter(p => p.type === 'question.asked' && p.directory === '/repo/a').map(p => p.properties.id)).toEqual(['q-1'])
expect(parsed.filter(p => p.type === 'permission.asked' && p.directory === '/repo/b').map(p => p.properties.id)).toEqual([
expect(parsed.filter(p => p.payload.type === 'question.asked' && p.directory === '/repo/a').map(p => p.payload.properties.id)).toEqual(['q-1'])
expect(parsed.filter(p => p.payload.type === 'permission.asked' && p.directory === '/repo/b').map(p => p.payload.properties.id)).toEqual([
'perm-3',
])
expect(parsed.filter(p => p.type === 'question.asked' && p.directory === '/repo/b')).toHaveLength(0)
expect(parsed.filter(p => p.payload.type === 'question.asked' && p.directory === '/repo/b')).toHaveLength(0)
})
it('does not replay when no fetcher is configured', async () => {
const { callback, events } = createCapturingClient()
sseAggregator.addClient('client-2', callback, ['/repo/a'])
const { callback, writeFrame, events } = createCapturingClient()
sseAggregator.addClient('client-2', callback, writeFrame, ['/repo/a'])
await flushReplay()
@@ -107,8 +112,8 @@ describe('SSEAggregator pending replay on connect', () => {
const clientA = createCapturingClient()
const clientB = createCapturingClient()
sseAggregator.addClient('a', clientA.callback, ['/repo/a'])
sseAggregator.addClient('b', clientB.callback, [])
sseAggregator.addClient('a', clientA.callback, clientA.writeFrame, ['/repo/a'])
sseAggregator.addClient('b', clientB.callback, clientB.writeFrame, [])
await flushReplay()
@@ -123,8 +128,8 @@ describe('SSEAggregator pending replay on connect', () => {
})
sseAggregator.setPendingActionsFetcher(fetcher)
const { callback, events } = createCapturingClient()
sseAggregator.addClient('client-3', callback, ['/repo/a'])
const { callback, writeFrame, events } = createCapturingClient()
sseAggregator.addClient('client-3', callback, writeFrame, ['/repo/a'])
await flushReplay()
const initialCount = events.length
@@ -134,11 +139,11 @@ describe('SSEAggregator pending replay on connect', () => {
await flushReplay()
const newEvents = events.slice(initialCount)
const parsed = newEvents.map(e => JSON.parse(e.data) as { type: string; directory: string; properties: { id: string } })
const parsed = newEvents.map(e => JSON.parse(e.data) as { directory: string; payload: { type: string; properties: { id: string } } })
expect(parsed).toHaveLength(1)
const [first] = parsed
expect(first?.directory).toBe('/repo/b')
expect(first?.properties.id).toBe('perm-2')
expect(first?.payload.properties.id).toBe('perm-2')
})
it('survives upstream fetch failures for one directory and still replays the others', async () => {
@@ -155,15 +160,15 @@ describe('SSEAggregator pending replay on connect', () => {
}
sseAggregator.setPendingActionsFetcher(fetcher)
const { callback, events } = createCapturingClient()
sseAggregator.addClient('client-4', callback, ['/repo/broken', '/repo/ok'])
const { callback, writeFrame, events } = createCapturingClient()
sseAggregator.addClient('client-4', callback, writeFrame, ['/repo/broken', '/repo/ok'])
await flushReplay()
const parsed = events.map(e => JSON.parse(e.data) as { directory: string; properties: { id: string } })
const parsed = events.map(e => JSON.parse(e.data) as { directory: string; payload: { properties: { id: string } } })
expect(parsed).toHaveLength(1)
const [first] = parsed
expect(first?.directory).toBe('/repo/ok')
expect(first?.properties.id).toBe('perm-ok')
expect(first?.payload.properties.id).toBe('perm-ok')
})
it('does not deliver replay events to a client that no longer subscribes to that directory', async () => {
@@ -180,8 +185,8 @@ describe('SSEAggregator pending replay on connect', () => {
}
sseAggregator.setPendingActionsFetcher(fetcher)
const { callback, events } = createCapturingClient()
sseAggregator.addClient('client-5', callback, ['/repo/a'])
const { callback, writeFrame, events } = createCapturingClient()
sseAggregator.addClient('client-5', callback, writeFrame, ['/repo/a'])
sseAggregator.removeDirectories('client-5', ['/repo/a'])
resolvePermissions([{ id: 'late', sessionID: 's' }])
-2
View File
@@ -272,8 +272,6 @@ export const useSSE = (opcodeUrl: string | null | undefined, directory?: string
})
queryClient.setQueryData(messagesQueryKey, updated)
queryClient.invalidateQueries({ queryKey: messagesQueryKey })
break
}
@@ -19,7 +19,7 @@ describe('OpenCodeEventStream', () => {
stream.subscribeGlobalMonitor({ directories: ['/repo'], onEvent })
transport.openConnection()
transport.connected()
transport.message({ type: 'permission.asked', properties: { sessionID: 'session-1' }, directory: '/repo' })
transport.message({ directory: '/repo', payload: { type: 'permission.asked', properties: { sessionID: 'session-1' } } })
expect(onEvent).toHaveBeenCalledWith({
type: 'permission.asked',
@@ -227,7 +227,7 @@ export class OpenCodeEventStream {
private handleMessage(data: string): void {
try {
this.markActivity()
this.broadcast(JSON.parse(data))
this.broadcast(flattenEventEnvelope(JSON.parse(data)))
} catch {
this.markActivity()
}
@@ -414,4 +414,18 @@ export class OpenCodeEventStream {
}
}
function flattenEventEnvelope(parsed: unknown): unknown {
if (
parsed !== null &&
typeof parsed === 'object' &&
'payload' in parsed &&
(parsed as { payload: unknown }).payload !== null &&
typeof (parsed as { payload: unknown }).payload === 'object'
) {
const { payload, directory } = parsed as { payload: object; directory?: unknown }
return { ...payload, directory }
}
return parsed
}
export const openCodeEventStream = new OpenCodeEventStream()
+54 -58
View File
@@ -43,6 +43,14 @@ export function createPartsBatcher(
if (pendingOperations.size === 0) return
const groupsToDelete: string[] = []
const invalidatedKeys = new Set<string>()
const invalidateOnce = (queryKey: unknown[]) => {
const dedupeKey = JSON.stringify(queryKey)
if (invalidatedKeys.has(dedupeKey)) return
invalidatedKeys.add(dedupeKey)
queryClient.invalidateQueries({ queryKey })
}
for (const [key, group] of pendingOperations.entries()) {
if (target) {
@@ -55,7 +63,7 @@ export function createPartsBatcher(
const currentData = queryClient.getQueryData<MessageWithParts[]>(queryKey)
if (!currentData) {
queryClient.invalidateQueries({ queryKey })
invalidateOnce(queryKey)
continue
}
@@ -64,72 +72,60 @@ export function createPartsBatcher(
const unapplied: PartOperation[] = []
const supersededPartIDs = new Set<string>()
const applyToMessage = (
messageID: string,
operation: PartOperation,
transform: (parts: Part[]) => Part[] | null,
): boolean => {
const idx = updatedData.findIndex((m) => m.info.id === messageID)
if (idx < 0) {
unapplied.push(operation)
return false
}
const parts = transform(updatedData[idx].parts)
if (parts === null) {
unapplied.push(operation)
return false
}
const next = updatedData.slice()
next[idx] = { ...updatedData[idx], parts }
updatedData = next
anyApplied = true
return true
}
for (const operation of group.operations) {
if (operation.type === 'upsert') {
const targetMsg = updatedData.find((m) => m.info.id === operation.part.messageID)
if (!targetMsg) {
unapplied.push(operation)
continue
}
anyApplied = true
const existingIdx = targetMsg.parts.findIndex((part) => part.id === operation.part.id)
const parts = [...targetMsg.parts]
if (existingIdx >= 0) {
parts[existingIdx] = operation.part
} else {
parts.push(operation.part)
}
updatedData = updatedData.map((m) =>
m.info.id === operation.part.messageID ? { ...m, parts } : m,
)
supersededPartIDs.add(operation.part.id)
const applied = applyToMessage(operation.part.messageID, operation, (parts) => {
const existingIdx = parts.findIndex((part) => part.id === operation.part.id)
const nextParts = [...parts]
if (existingIdx >= 0) {
nextParts[existingIdx] = operation.part
} else {
nextParts.push(operation.part)
}
return nextParts
})
if (applied) supersededPartIDs.add(operation.part.id)
continue
}
if (operation.type === 'remove') {
const targetMsg = updatedData.find((m) => m.info.id === operation.messageID)
if (!targetMsg) {
unapplied.push(operation)
continue
}
anyApplied = true
updatedData = updatedData.map((m) =>
m.info.id === operation.messageID
? { ...m, parts: m.parts.filter((part) => part.id !== operation.partID) }
: m,
const applied = applyToMessage(operation.messageID, operation, (parts) =>
parts.filter((part) => part.id !== operation.partID),
)
supersededPartIDs.add(operation.partID)
if (applied) supersededPartIDs.add(operation.partID)
continue
}
const targetMsg = updatedData.find((m) => m.info.id === operation.messageID)
if (!targetMsg) {
unapplied.push(operation)
continue
}
const targetPart = targetMsg.parts.find((p) => p.id === operation.partID)
if (!targetPart) {
unapplied.push(operation)
continue
}
anyApplied = true
updatedData = updatedData.map((m) => {
if (m.info.id !== operation.messageID) return m
return {
...m,
parts: m.parts.map((part) => {
if (part.id !== operation.partID) return part
const currentValue = (part as Record<string, unknown>)[operation.field]
const nextValue = `${typeof currentValue === 'string' ? currentValue : ''}${operation.delta}`
return { ...part, [operation.field]: nextValue } as Part
}),
}
applyToMessage(operation.messageID, operation, (parts) => {
if (!parts.some((p) => p.id === operation.partID)) return null
return parts.map((part) => {
if (part.id !== operation.partID) return part
const currentValue = (part as Record<string, unknown>)[operation.field]
const nextValue = `${typeof currentValue === 'string' ? currentValue : ''}${operation.delta}`
return { ...part, [operation.field]: nextValue } as Part
})
})
}
@@ -146,7 +142,7 @@ export function createPartsBatcher(
if (filteredUnapplied.length > 0) {
group.operations = filteredUnapplied
queryClient.invalidateQueries({ queryKey })
invalidateOnce(queryKey)
} else {
groupsToDelete.push(key)
}