mirror of
https://github.com/anomalyco/opencode.git
synced 2026-11-29 03:24:54 +00:00
246 lines
8.7 KiB
TypeScript
246 lines
8.7 KiB
TypeScript
import { expect, test } from "bun:test"
|
|
import { createRoot } from "solid-js"
|
|
import { createClientConnection } from "../src/solid"
|
|
import { OpenCode, type OpenCodeEvent } from "../src/promise"
|
|
|
|
const connected = { id: "evt_connected", created: 1, type: "server.connected", data: {} }
|
|
|
|
// One fake server whose event streams stay open until the test writes to them or the client aborts. With
|
|
// `answerAfter`, each stream sends the handshake that many milliseconds after it opens, as a server under load does.
|
|
// The first `refused` requests fail at once, as they do while the server is away.
|
|
function server(answerAfter?: number, refused = 0) {
|
|
const encoder = new TextEncoder()
|
|
const streams: {
|
|
headers: Headers
|
|
write: (text: string) => void
|
|
close: () => void
|
|
error: (reason: Error) => void
|
|
aborted: boolean
|
|
}[] = []
|
|
|
|
const refusals = { left: refused }
|
|
const api = OpenCode.make({
|
|
baseUrl: "http://opencode.local",
|
|
fetch: async (input, init) => {
|
|
if (refusals.left-- > 0) throw new TypeError("Failed to fetch")
|
|
|
|
const request = input instanceof Request ? input : new Request(input, init)
|
|
let controller!: ReadableStreamDefaultController<Uint8Array>
|
|
const entry = {
|
|
headers: request.headers,
|
|
write: (text: string) => controller.enqueue(encoder.encode(text)),
|
|
close: () => controller.close(),
|
|
error: (reason: Error) => controller.error(reason),
|
|
aborted: false,
|
|
}
|
|
const body = new ReadableStream<Uint8Array>({
|
|
start(value) {
|
|
controller = value
|
|
},
|
|
cancel() {
|
|
entry.aborted = true
|
|
},
|
|
})
|
|
request.signal.addEventListener("abort", () => {
|
|
entry.aborted = true
|
|
controller.error(request.signal.reason)
|
|
})
|
|
streams.push(entry)
|
|
|
|
if (answerAfter !== undefined)
|
|
setTimeout(() => {
|
|
if (!entry.aborted) entry.write(`data: ${JSON.stringify(connected)}\n\n`)
|
|
}, answerAfter)
|
|
|
|
return new Response(body, { headers: { "content-type": "text/event-stream" } })
|
|
},
|
|
})
|
|
return { api, streams }
|
|
}
|
|
|
|
function setup(
|
|
input: ReturnType<typeof server>,
|
|
idleTimeout: number,
|
|
connectTimeout?: number,
|
|
moved?: ReturnType<typeof server>,
|
|
) {
|
|
const events: OpenCodeEvent[] = []
|
|
return createRoot((dispose) => ({
|
|
events,
|
|
dispose,
|
|
connection: createClientConnection(input.api, {
|
|
idleTimeout,
|
|
connectTimeout,
|
|
// The server moved: after the first failure the stream connects to the other address.
|
|
reconnect: moved ? async () => moved.api : undefined,
|
|
flushInterval: 0,
|
|
onEvent: (event) => events.push(event),
|
|
}),
|
|
}))
|
|
}
|
|
|
|
async function until(check: () => boolean, timeout = 2_000) {
|
|
const deadline = Date.now() + timeout
|
|
while (!check()) {
|
|
if (Date.now() > deadline) throw new Error("Timed out waiting for condition")
|
|
await new Promise((resolve) => setTimeout(resolve, 5))
|
|
}
|
|
}
|
|
|
|
test("a stream that goes silent past the idle timeout is replaced", async () => {
|
|
const fake = server()
|
|
const ctx = setup(fake, 60)
|
|
try {
|
|
await until(() => fake.streams.length === 1)
|
|
fake.streams[0].write(`data: ${JSON.stringify(connected)}\n\n`)
|
|
await until(() => ctx.connection.status() === "connected")
|
|
|
|
await until(() => fake.streams.length === 2)
|
|
expect(fake.streams[0].aborted).toBe(true)
|
|
expect(ctx.connection.internal.history().map((item) => item.data)).toContainEqual({
|
|
status: "disconnected",
|
|
attempt: 1,
|
|
error: "Event stream stalled",
|
|
})
|
|
|
|
fake.streams[1].write(`data: ${JSON.stringify({ ...connected, id: "evt_connected_2" })}\n\n`)
|
|
await until(() => ctx.connection.status() === "connected" && ctx.events.length === 2)
|
|
expect(ctx.connection.error()).toBeUndefined()
|
|
} finally {
|
|
ctx.dispose()
|
|
}
|
|
})
|
|
|
|
// A server under load sends its handshake late. Cut off at the same limit every time, the client never reached it.
|
|
test("an attempt after an unanswered one waits twice as long for the handshake", async () => {
|
|
const fake = server(150)
|
|
const ctx = setup(fake, 10_000, 100)
|
|
try {
|
|
await until(() => ctx.connection.status() === "connected" || fake.streams.length === 3, 4_000)
|
|
expect(fake.streams.map((stream) => stream.aborted)).toEqual([true, false])
|
|
expect(ctx.connection.status()).toBe("connected")
|
|
expect(ctx.connection.internal.history().map((item) => item.data)).toContainEqual({
|
|
status: "disconnected",
|
|
attempt: 1,
|
|
error: "Timed out connecting to server",
|
|
})
|
|
} finally {
|
|
ctx.dispose()
|
|
}
|
|
})
|
|
|
|
// After a spell with the server away, an attempt that hangs must still be dropped at the first limit.
|
|
test("an attempt that fails at once leaves the limit as it was", async () => {
|
|
const fake = server(150, 1)
|
|
const ctx = setup(fake, 10_000, 100)
|
|
try {
|
|
await until(() => ctx.connection.status() === "connected", 4_000)
|
|
// The stream after the refused request still had the first limit, so it was cut off before its handshake.
|
|
expect(fake.streams.map((stream) => stream.aborted)).toEqual([true, false])
|
|
} finally {
|
|
ctx.dispose()
|
|
}
|
|
})
|
|
|
|
// A limit learned at one address says nothing about the address the server moved to.
|
|
test("a server at another address starts from the first limit", async () => {
|
|
const old = server(150)
|
|
const moved = server(150)
|
|
const ctx = setup(old, 10_000, 100, moved)
|
|
try {
|
|
await until(() => ctx.connection.status() === "connected", 4_000)
|
|
expect(old.streams.map((stream) => stream.aborted)).toEqual([true])
|
|
expect(moved.streams.map((stream) => stream.aborted)).toEqual([true, false])
|
|
} finally {
|
|
ctx.dispose()
|
|
}
|
|
})
|
|
|
|
test("keepalive comments hold a quiet stream open", async () => {
|
|
const fake = server()
|
|
const ctx = setup(fake, 60)
|
|
try {
|
|
await until(() => fake.streams.length === 1)
|
|
fake.streams[0].write(`data: ${JSON.stringify(connected)}\n\n`)
|
|
await until(() => ctx.connection.status() === "connected")
|
|
|
|
const heartbeat = setInterval(() => fake.streams[0].write(": heartbeat\n\n"), 20)
|
|
await new Promise((resolve) => setTimeout(resolve, 250))
|
|
clearInterval(heartbeat)
|
|
|
|
expect(fake.streams).toHaveLength(1)
|
|
expect(fake.streams[0].aborted).toBe(false)
|
|
expect(ctx.connection.status()).toBe("connected")
|
|
expect(ctx.events).toHaveLength(1)
|
|
} finally {
|
|
ctx.dispose()
|
|
}
|
|
})
|
|
|
|
test("a forced resync replaces the stream immediately and only while connected", async () => {
|
|
const fake = server()
|
|
const ctx = setup(fake, 10_000)
|
|
try {
|
|
ctx.connection.internal.resync("too early")
|
|
await until(() => fake.streams.length === 1)
|
|
expect(fake.streams[0].aborted).toBe(false)
|
|
fake.streams[0].write(`data: ${JSON.stringify(connected)}\n\n`)
|
|
await until(() => ctx.connection.status() === "connected")
|
|
|
|
const started = Date.now()
|
|
ctx.connection.internal.resync("Network connection restored")
|
|
await until(() => fake.streams.length === 2)
|
|
expect(Date.now() - started).toBeLessThan(500)
|
|
expect(fake.streams[0].aborted).toBe(true)
|
|
expect(ctx.connection.internal.history().map((item) => item.data)).toContainEqual({
|
|
status: "disconnected",
|
|
attempt: 1,
|
|
error: "Network connection restored",
|
|
})
|
|
fake.streams[1].write(`data: ${JSON.stringify(connected)}\n\n`)
|
|
await until(() => ctx.connection.status() === "connected")
|
|
} finally {
|
|
ctx.dispose()
|
|
}
|
|
})
|
|
|
|
test.each([
|
|
["closes", (stream: ReturnType<typeof server>["streams"][number]) => stream.close(), "Event stream disconnected"],
|
|
[
|
|
"fails",
|
|
(stream: ReturnType<typeof server>["streams"][number]) => stream.error(new Error("contract failure")),
|
|
"Transport: contract failure",
|
|
],
|
|
])("a stream the server %s reconnects and reports the disconnect", async (_name, end, message) => {
|
|
const fake = server()
|
|
const ctx = setup(fake, 10_000)
|
|
try {
|
|
await until(() => fake.streams.length === 1)
|
|
fake.streams[0].write(`data: ${JSON.stringify(connected)}\n\n`)
|
|
await until(() => ctx.connection.status() === "connected")
|
|
|
|
end(fake.streams[0])
|
|
await until(() => ctx.connection.status() === "reconnecting")
|
|
expect(ctx.connection.error()).toBe(message)
|
|
await until(() => fake.streams.length === 2)
|
|
} finally {
|
|
ctx.dispose()
|
|
}
|
|
})
|
|
|
|
test("a reconnect does not ask the volatile event stream to replay", async () => {
|
|
const fake = server()
|
|
const ctx = setup(fake, 10_000)
|
|
try {
|
|
await until(() => fake.streams.length === 1)
|
|
fake.streams[0].write(`data: ${JSON.stringify(connected)}\n\n`)
|
|
fake.streams[0].write(`id: timeline-event-7\ndata: ${JSON.stringify({ ...connected, id: "evt_2" })}\n\n`)
|
|
await until(() => ctx.events.length === 2)
|
|
|
|
fake.streams[0].error(new Error("retry with event id"))
|
|
await until(() => fake.streams.length === 2)
|
|
expect(fake.streams[1].headers.get("last-event-id")).toBeNull()
|
|
} finally {
|
|
ctx.dispose()
|
|
}
|
|
})
|