|
| 1 | +import { describe, test, expect, beforeEach, mock } from "bun:test"; |
| 2 | + |
| 3 | +// Mock config |
| 4 | +const mockConfig = { |
| 5 | + port: 3000, |
| 6 | + host: "0.0.0.0", |
| 7 | + apiKeys: ["test-api-key"], |
| 8 | + baseUrl: "http://localhost:3000", |
| 9 | + pollTimeout: 8, |
| 10 | + heartbeatInterval: 20, |
| 11 | + jwtExpiresIn: 3600, |
| 12 | + disconnectTimeout: 300, |
| 13 | +}; |
| 14 | + |
| 15 | +mock.module("../config", () => ({ |
| 16 | + config: mockConfig, |
| 17 | + getBaseUrl: () => "http://localhost:3000", |
| 18 | +})); |
| 19 | + |
| 20 | +import { Hono } from "hono"; |
| 21 | +import { storeReset } from "../store"; |
| 22 | +import { removeEventBus, getAllEventBuses, getEventBus } from "../transport/event-bus"; |
| 23 | +import { createSSEWriter, createSSEStream } from "../transport/sse-writer"; |
| 24 | + |
| 25 | +/** Read up to N bytes from a Response stream, then cancel */ |
| 26 | +async function readPartialStream(res: Response, maxBytes = 4096): Promise<string> { |
| 27 | + const reader = res.body?.getReader(); |
| 28 | + if (!reader) return ""; |
| 29 | + const chunks: Uint8Array[] = []; |
| 30 | + let totalBytes = 0; |
| 31 | + try { |
| 32 | + while (totalBytes < maxBytes) { |
| 33 | + const { done, value } = await reader.read(); |
| 34 | + if (done) break; |
| 35 | + chunks.push(value); |
| 36 | + totalBytes += value.length; |
| 37 | + // Cancel after we have some data (first keepalive + any initial events) |
| 38 | + if (totalBytes > 0) break; |
| 39 | + } |
| 40 | + } finally { |
| 41 | + reader.cancel(); |
| 42 | + } |
| 43 | + const combined = new Uint8Array(totalBytes); |
| 44 | + let offset = 0; |
| 45 | + for (const chunk of chunks) { |
| 46 | + combined.set(chunk, offset); |
| 47 | + offset += chunk.length; |
| 48 | + } |
| 49 | + return new TextDecoder().decode(combined); |
| 50 | +} |
| 51 | + |
| 52 | +describe("SSE Writer", () => { |
| 53 | + describe("createSSEWriter", () => { |
| 54 | + test("creates SSEWriter with send and close methods", () => { |
| 55 | + const app = new Hono(); |
| 56 | + let capturedWriter: ReturnType<typeof createSSEWriter> | null = null; |
| 57 | + |
| 58 | + app.get("/test", (c) => { |
| 59 | + capturedWriter = createSSEWriter(c); |
| 60 | + return c.text("ok"); |
| 61 | + }); |
| 62 | + |
| 63 | + app.request("/test"); |
| 64 | + expect(capturedWriter).not.toBeNull(); |
| 65 | + expect(typeof capturedWriter!.send).toBe("function"); |
| 66 | + expect(typeof capturedWriter!.close).toBe("function"); |
| 67 | + }); |
| 68 | + }); |
| 69 | + |
| 70 | + describe("createSSEStream", () => { |
| 71 | + beforeEach(() => { |
| 72 | + storeReset(); |
| 73 | + for (const [key] of getAllEventBuses()) { |
| 74 | + removeEventBus(key); |
| 75 | + } |
| 76 | + }); |
| 77 | + |
| 78 | + test("returns Response with correct SSE headers", async () => { |
| 79 | + const app = new Hono(); |
| 80 | + |
| 81 | + app.get("/stream/:sessionId", (c) => { |
| 82 | + const sessionId = c.req.param("sessionId"); |
| 83 | + return createSSEStream(c, sessionId, 0); |
| 84 | + }); |
| 85 | + |
| 86 | + const res = await app.request("/stream/s1"); |
| 87 | + expect(res.status).toBe(200); |
| 88 | + expect(res.headers.get("Content-Type")).toBe("text/event-stream"); |
| 89 | + expect(res.headers.get("Cache-Control")).toBe("no-cache"); |
| 90 | + expect(res.headers.get("Connection")).toBe("keep-alive"); |
| 91 | + expect(res.headers.get("X-Accel-Buffering")).toBe("no"); |
| 92 | + |
| 93 | + // Cancel the stream |
| 94 | + res.body?.cancel(); |
| 95 | + }); |
| 96 | + |
| 97 | + test("sends initial keepalive", async () => { |
| 98 | + const app = new Hono(); |
| 99 | + |
| 100 | + app.get("/stream/:sessionId", (c) => { |
| 101 | + const sessionId = c.req.param("sessionId"); |
| 102 | + return createSSEStream(c, sessionId, 0); |
| 103 | + }); |
| 104 | + |
| 105 | + const res = await app.request("/stream/s2"); |
| 106 | + const text = await readPartialStream(res); |
| 107 | + expect(text).toContain(": keepalive"); |
| 108 | + }); |
| 109 | + |
| 110 | + test("sends historical events when fromSeqNum > 0", async () => { |
| 111 | + // Pre-populate event bus with events |
| 112 | + const bus = getEventBus("s3"); |
| 113 | + bus.publish({ id: "e1", sessionId: "s3", type: "user", payload: { content: "hello" }, direction: "outbound" }); |
| 114 | + bus.publish({ id: "e2", sessionId: "s3", type: "assistant", payload: { content: "hi" }, direction: "inbound" }); |
| 115 | + |
| 116 | + const app = new Hono(); |
| 117 | + |
| 118 | + app.get("/stream/:sessionId", (c) => { |
| 119 | + const sessionId = c.req.param("sessionId"); |
| 120 | + const fromSeq = parseInt(c.req.query("fromSeq") || "0"); |
| 121 | + return createSSEStream(c, sessionId, fromSeq); |
| 122 | + }); |
| 123 | + |
| 124 | + const res = await app.request("/stream/s3?fromSeq=1"); |
| 125 | + const text = await readPartialStream(res); |
| 126 | + // Should replay events since seq 1 (i.e., event 2) |
| 127 | + expect(text).toContain('"seqNum":2'); |
| 128 | + expect(text).toContain("assistant"); |
| 129 | + }); |
| 130 | + |
| 131 | + test("no historical events when fromSeqNum is 0", async () => { |
| 132 | + const bus = getEventBus("s5"); |
| 133 | + bus.publish({ id: "e1", sessionId: "s5", type: "user", payload: {}, direction: "outbound" }); |
| 134 | + |
| 135 | + const app = new Hono(); |
| 136 | + |
| 137 | + app.get("/stream/:sessionId", (c) => { |
| 138 | + const sessionId = c.req.param("sessionId"); |
| 139 | + return createSSEStream(c, sessionId, 0); |
| 140 | + }); |
| 141 | + |
| 142 | + const res = await app.request("/stream/s5"); |
| 143 | + const text = await readPartialStream(res); |
| 144 | + // With fromSeqNum=0, no historical replay, just keepalive |
| 145 | + expect(text).toContain(": keepalive"); |
| 146 | + // Should NOT contain event data (only keepalive) |
| 147 | + expect(text).not.toContain("event: message"); |
| 148 | + }); |
| 149 | + |
| 150 | + test("subscribes to new events and delivers them", async () => { |
| 151 | + const app = new Hono(); |
| 152 | + |
| 153 | + app.get("/stream/:sessionId", (c) => { |
| 154 | + const sessionId = c.req.param("sessionId"); |
| 155 | + return createSSEStream(c, sessionId, 0); |
| 156 | + }); |
| 157 | + |
| 158 | + const res = await app.request("/stream/s6"); |
| 159 | + |
| 160 | + // Read initial keepalive first |
| 161 | + const reader = res.body!.getReader(); |
| 162 | + const { value: firstChunk } = await reader.read(); |
| 163 | + const initialText = new TextDecoder().decode(firstChunk!); |
| 164 | + expect(initialText).toContain(": keepalive"); |
| 165 | + |
| 166 | + // Now publish an event |
| 167 | + const bus = getEventBus("s6"); |
| 168 | + bus.publish({ id: "e1", sessionId: "s6", type: "user", payload: { content: "real-time" }, direction: "outbound" }); |
| 169 | + |
| 170 | + // Read the event |
| 171 | + const { value: secondChunk } = await reader.read(); |
| 172 | + const eventText = new TextDecoder().decode(secondChunk!); |
| 173 | + expect(eventText).toContain("event: message"); |
| 174 | + expect(eventText).toContain("real-time"); |
| 175 | + |
| 176 | + reader.cancel(); |
| 177 | + }); |
| 178 | + }); |
| 179 | +}); |
0 commit comments