Skip to content

Commit b928a1f

Browse files
kitlangtonrekram1-nodejlongster
authored
fix(httpapi): preserve event stream context (#27425)
Co-authored-by: Aiden Cline <[email protected]> Co-authored-by: James Long <[email protected]>
1 parent 04286d0 commit b928a1f

2 files changed

Lines changed: 102 additions & 37 deletions

File tree

‎packages/opencode/src/server/routes/instance/httpapi/event.ts‎

Lines changed: 30 additions & 23 deletions
Original file line numberDiff line numberDiff line change
@@ -40,30 +40,37 @@ function eventData(data: unknown): Sse.Event {
4040
}
4141

4242
function eventResponse(bus: Bus.Interface) {
43-
const events = bus.subscribeAll().pipe(Stream.takeUntil((event) => event.type === Bus.InstanceDisposed.type))
44-
const heartbeat = Stream.tick("10 seconds").pipe(
45-
Stream.drop(1),
46-
Stream.map(() => ({ id: Bus.createID(), type: "server.heartbeat", properties: {} })),
47-
)
43+
return Effect.gen(function* () {
44+
const context = yield* Effect.context()
4845

49-
log.info("event connected")
50-
return HttpServerResponse.stream(
51-
Stream.make({ id: Bus.createID(), type: "server.connected", properties: {} }).pipe(
52-
Stream.concat(events.pipe(Stream.merge(heartbeat, { haltStrategy: "left" }))),
53-
Stream.map(eventData),
54-
Stream.pipeThroughChannel(Sse.encode()),
55-
Stream.encodeText,
56-
Stream.ensuring(Effect.sync(() => log.info("event disconnected"))),
57-
),
58-
{
59-
contentType: "text/event-stream",
60-
headers: {
61-
"Cache-Control": "no-cache, no-transform",
62-
"X-Accel-Buffering": "no",
63-
"X-Content-Type-Options": "nosniff",
46+
const events = bus.subscribeAll().pipe(
47+
Stream.provideContext(context),
48+
Stream.takeUntil((event) => event.type === Bus.InstanceDisposed.type),
49+
)
50+
const heartbeat = Stream.tick("10 seconds").pipe(
51+
Stream.drop(1),
52+
Stream.map(() => ({ id: Bus.createID(), type: "server.heartbeat", properties: {} })),
53+
)
54+
55+
log.info("event connected")
56+
return HttpServerResponse.stream(
57+
Stream.make({ id: Bus.createID(), type: "server.connected", properties: {} }).pipe(
58+
Stream.concat(events.pipe(Stream.merge(heartbeat, { haltStrategy: "left" }))),
59+
Stream.map(eventData),
60+
Stream.pipeThroughChannel(Sse.encode()),
61+
Stream.encodeText,
62+
Stream.ensuring(Effect.sync(() => log.info("event disconnected"))),
63+
),
64+
{
65+
contentType: "text/event-stream",
66+
headers: {
67+
"Cache-Control": "no-cache, no-transform",
68+
"X-Accel-Buffering": "no",
69+
"X-Content-Type-Options": "nosniff",
70+
},
6471
},
65-
},
66-
)
72+
)
73+
})
6774
}
6875

6976
export const eventHandlers = HttpApiBuilder.group(EventApi, "event", (handlers) =>
@@ -72,7 +79,7 @@ export const eventHandlers = HttpApiBuilder.group(EventApi, "event", (handlers)
7279
return handlers.handleRaw(
7380
"subscribe",
7481
Effect.fn("EventHttpApi.subscribe")(function* () {
75-
return eventResponse(bus)
82+
return yield* eventResponse(bus)
7683
}),
7784
)
7885
}),

‎packages/opencode/test/server/httpapi-event.test.ts‎

Lines changed: 72 additions & 14 deletions
Original file line numberDiff line numberDiff line change
@@ -1,36 +1,56 @@
11
import { afterEach, describe, expect, test } from "bun:test"
2+
import { Bus } from "../../src/bus"
23
import { Instance } from "../../src/project/instance"
34
import { Server } from "../../src/server/server"
45
import { EventPaths } from "../../src/server/routes/instance/httpapi/event"
6+
import { Event as ServerEvent } from "../../src/server/event"
57
import * as Log from "@opencode-ai/core/util/log"
8+
import { Schema } from "effect"
69
import { resetDatabase } from "../fixture/db"
7-
import { disposeAllInstances, tmpdir } from "../fixture/fixture"
10+
import { disposeAllInstances, reloadTestInstance, tmpdir } from "../fixture/fixture"
811

912
void Log.init({ print: false })
1013

1114
function app() {
1215
return Server.Default().app
1316
}
1417

15-
async function readFirstChunk(response: Response) {
16-
if (!response.body) throw new Error("missing response body")
17-
const reader = response.body.getReader()
18-
const result = await Promise.race([
19-
reader.read(),
20-
new Promise<never>((_, reject) => setTimeout(() => reject(new Error("timed out waiting for event")), 5_000)),
21-
])
22-
await reader.cancel()
23-
return new TextDecoder().decode(result.value)
18+
const EventData = Schema.Struct({
19+
id: Schema.optional(Schema.String),
20+
type: Schema.String,
21+
properties: Schema.Record(Schema.String, Schema.Any),
22+
})
23+
24+
async function readChunk(reader: ReadableStreamDefaultReader<Uint8Array>) {
25+
let timeout: ReturnType<typeof setTimeout> | undefined
26+
try {
27+
return await Promise.race([
28+
reader.read(),
29+
new Promise<never>((_, reject) => {
30+
timeout = setTimeout(() => reject(new Error("timed out waiting for event")), 5_000)
31+
}),
32+
])
33+
} finally {
34+
if (timeout) clearTimeout(timeout)
35+
}
2436
}
2537

2638
async function readFirstEvent(response: Response) {
27-
return JSON.parse((await readFirstChunk(response)).replace(/^data: /, "")) as {
28-
id?: string
29-
type: string
30-
properties: Record<string, unknown>
39+
if (!response.body) throw new Error("missing response body")
40+
const reader = response.body.getReader()
41+
try {
42+
return await readEvent(reader)
43+
} finally {
44+
await reader.cancel()
3145
}
3246
}
3347

48+
async function readEvent(reader: ReadableStreamDefaultReader<Uint8Array>) {
49+
const result = await readChunk(reader)
50+
if (result.done || !result.value) throw new Error("event stream closed")
51+
return Schema.decodeUnknownSync(EventData)(JSON.parse(new TextDecoder().decode(result.value).replace(/^data: /, "")))
52+
}
53+
3454
afterEach(async () => {
3555
await disposeAllInstances()
3656
await resetDatabase()
@@ -56,4 +76,42 @@ describe("event HttpApi", () => {
5676

5777
expect(await readFirstEvent(response)).toMatchObject({ type: "server.connected", properties: {} })
5878
})
79+
80+
test("keeps the event stream open after the initial event", async () => {
81+
await using tmp = await tmpdir({ git: true, config: { formatter: false, lsp: false } })
82+
const response = await app().request(EventPaths.event, { headers: { "x-opencode-directory": tmp.path } })
83+
if (!response.body) throw new Error("missing response body")
84+
85+
const reader = response.body.getReader()
86+
try {
87+
expect(await readEvent(reader)).toMatchObject({ type: "server.connected", properties: {} })
88+
const next = await Promise.race([
89+
reader.read().then((result) => (result.done ? "closed" : "event")),
90+
new Promise<"open">((resolve) => setTimeout(() => resolve("open"), 250)),
91+
])
92+
93+
expect(next).toBe("open")
94+
} finally {
95+
await reader.cancel()
96+
}
97+
})
98+
99+
test("delivers instance bus events after the initial event", async () => {
100+
await using tmp = await tmpdir({ git: true, config: { formatter: false, lsp: false } })
101+
const response = await app().request(EventPaths.event, { headers: { "x-opencode-directory": tmp.path } })
102+
if (!response.body) throw new Error("missing response body")
103+
104+
const reader = response.body.getReader()
105+
try {
106+
expect(await readEvent(reader)).toMatchObject({ type: "server.connected", properties: {} })
107+
108+
const next = readEvent(reader)
109+
const ctx = await reloadTestInstance({ directory: tmp.path })
110+
await Instance.restore(ctx, () => Bus.publish(ServerEvent.Connected, {}))
111+
112+
expect(await next).toMatchObject({ type: "server.connected", properties: {} })
113+
} finally {
114+
await reader.cancel()
115+
}
116+
})
59117
})

0 commit comments

Comments
 (0)