Repository Public
1import { describe, expect, it } from "vitest";2import { SseClient, SseParser, type SseMessage, type SseStatus } from "./sse";34describe("SseParser", () => {5 it("parses id, event and data; ignores comments (heartbeats)", () => {6 const p = new SseParser();7 expect(p.push("retry: 3000\nevent: hello\ndata: {\"head\":4}\n\n: ping\n\nid: 5\nevent: node.state\ndata: {\"a\":1}\n\n")).toEqual([8 { event: "hello", data: '{"head":4}' },9 { event: "node.state", data: '{"a":1}', id: "5" },10 ]);11 expect(p.retry).toBe(3000);12 });13 it("handles frames split across chunks, CRLF and multi-line data", () => {14 const p = new SseParser();15 expect(p.push("id: 7\r\nevent: a")).toEqual([]);16 expect(p.push("lert.changed\r\ndata: line1\r\ndata: line2\r")).toEqual([]);17 expect(p.push("\n\r\n")).toEqual([{ event: "alert.changed", data: "line1\nline2", id: "7" }]);18 });19 it("keeps the last id for following events without id and defaults the event name", () => {20 const p = new SseParser();21 const out = p.push("id: 9\ndata: x\n\ndata: y\n\n");22 expect(out).toEqual([{ event: "message", data: "x", id: "9" }, { event: "message", data: "y", id: "9" }]);23 });24});2526interface Call {27 headers: Record<string, string>;28 push: (text: string) => void;29 end: () => void;30 fail: () => void;31}3233function harness(responses: (number | "network")[] = []) {34 const calls: Call[] = [];35 const timers: { fn: () => void; ms: number; id: number; cancelled: boolean }[] = [];36 const statuses: SseStatus[] = [];37 const messages: SseMessage[] = [];38 let unauthorized = 0;39 let now = 1000;40 let seq = 0;41 const fakeFetch = ((_url: string, init: RequestInit) => {42 const plan = responses.shift() ?? 200;43 if (plan === "network") {44 calls.push({ headers: init.headers as Record<string, string>, push: () => {}, end: () => {}, fail: () => {} });45 return Promise.reject(new TypeError("network"));46 }47 let controller!: ReadableStreamDefaultController<Uint8Array>;48 const body = new ReadableStream<Uint8Array>({ start: (c) => { controller = c; } });49 init.signal?.addEventListener("abort", () => { try { controller.error(new DOMException("aborted", "AbortError")); } catch { /* closed */ } });50 const enc = new TextEncoder();51 calls.push({ headers: init.headers as Record<string, string>, push: (t) => controller.enqueue(enc.encode(t)), end: () => controller.close(), fail: () => controller.error(new TypeError("reset")) });52 return Promise.resolve(new Response(plan === 200 ? body : null, { status: plan }));53 }) as unknown as typeof fetch;54 const client = new SseClient({55 url: "/api/v1/events",56 fetch: fakeFetch,57 onMessage: (m) => messages.push(m),58 onStatus: (s) => statuses.push(s),59 onUnauthorized: () => { unauthorized++; },60 now: () => now,61 random: () => 0.5, // jitter factor 1.062 setTimeout: (fn, ms) => { const t = { fn, ms, id: ++seq, cancelled: false }; timers.push(t); return t.id; },63 clearTimeout: (h) => { const t = timers.find((x) => x.id === h); if (t) t.cancelled = true; },64 });65 const flush = async () => { for (let i = 0; i < 12; i++) await Promise.resolve(); await new Promise((r) => setTimeout(r, 0)); };66 /** Runs the pending reconnect timer (idle watchdogs are the 45 s ones). */67 const fireReconnect = async () => {68 const t = timers.find((x) => !x.cancelled && x.ms !== 45000);69 if (!t) throw new Error("no reconnect timer");70 t.cancelled = true;71 t.fn();72 await flush();73 return t.ms;74 };75 const fireIdle = async () => {76 const t = [...timers].reverse().find((x) => !x.cancelled && x.ms === 45000);77 if (!t) throw new Error("no idle timer");78 t.cancelled = true;79 t.fn();80 await flush();81 };82 return { client, calls, statuses, messages, flush, fireReconnect, fireIdle, advance: (ms: number) => { now += ms; }, unauthorized: () => unauthorized, states: () => statuses.map((s) => s.state) };83}8485describe("SseClient", () => {86 it("connects, goes live and delivers events", async () => {87 const h = harness();88 h.client.start();89 await h.flush();90 expect(h.states()).toEqual(["connecting", "live"]);91 expect(h.calls[0]?.headers["Last-Event-ID"]).toBeUndefined();92 h.calls[0]?.push('event: hello\ndata: {"head":41}\n\nid: 42\nevent: node.state\ndata: {"node_id":"n"}\n\n');93 await h.flush();94 expect(h.messages.map((m) => m.event)).toEqual(["hello", "node.state"]);95 expect(h.client.getLastEventId()).toBe("42");96 h.client.stop();97 });9899 it("reconnects with Last-Event-ID after the stream breaks, immediately when it had been open", async () => {100 const h = harness();101 h.client.start();102 await h.flush();103 h.calls[0]?.push("id: 42\nevent: node.state\ndata: {}\n\n");104 await h.flush();105 h.advance(500);106 h.calls[0]?.fail();107 await h.flush();108 expect(h.states().at(-1)).toBe("reconnecting");109 expect(h.statuses.at(-1)?.since).toBe(1500); // when the connection was lost110 expect(await h.fireReconnect()).toBe(0);111 expect(h.calls[1]?.headers["Last-Event-ID"]).toBe("42");112 expect(h.states().at(-1)).toBe("live");113 h.client.stop();114 });115116 it("backs off exponentially on repeated failures and reports offline after three attempts, keeping the loss time", async () => {117 const h = harness([200, "network", 503, "network", "network", 200]);118 h.client.start();119 await h.flush();120 h.advance(100);121 h.calls[0]?.end(); // server closed the stream122 await h.flush();123 const delays: number[] = [await h.fireReconnect()];124 for (let i = 0; i < 4; i++) {125 h.advance(1000);126 delays.push(await h.fireReconnect());127 }128 expect(delays).toEqual([0, 1000, 2000, 4000, 8000]);129 expect(h.states()).toEqual(["connecting", "live", "reconnecting", "reconnecting", "reconnecting", "offline", "offline", "live"]);130 const offline = h.statuses.find((s) => s.state === "offline");131 expect(offline?.since).toBe(1100);132 expect(h.statuses.at(-1)?.attempt).toBe(0);133 h.client.stop();134 });135136 it("caps the backoff", async () => {137 const h = harness(Array<"network">(12).fill("network"));138 h.client.start();139 await h.flush();140 let last = 0;141 for (let i = 0; i < 9; i++) last = await h.fireReconnect();142 expect(last).toBe(30000);143 h.client.stop();144 });145146 it("treats a silent connection as dead (no heartbeat within the idle timeout)", async () => {147 const h = harness();148 h.client.start();149 await h.flush();150 await h.fireIdle();151 expect(h.states().at(-1)).toBe("reconnecting");152 await h.fireReconnect();153 expect(h.calls).toHaveLength(2);154 h.client.stop();155 });156157 it("stops and reports when the session is gone (401)", async () => {158 const h = harness([401]);159 h.client.start();160 await h.flush();161 expect(h.unauthorized()).toBe(1);162 expect(h.states().at(-1)).toBe("closed");163 expect(h.calls).toHaveLength(1);164 });165166 it("passes resync through as a message so caches can be invalidated", async () => {167 const h = harness();168 h.client.start();169 await h.flush();170 h.calls[0]?.push("id: 900\nevent: resync\ndata: {}\n\n");171 await h.flush();172 expect(h.messages).toEqual([{ event: "resync", data: "{}", id: "900" }]);173 expect(h.client.getLastEventId()).toBe("900");174 h.client.stop();175 });176177 it("wake() reconnects at once and stop() cancels everything", async () => {178 const h = harness(["network", 200]);179 h.client.start();180 await h.flush();181 expect(h.states().at(-1)).toBe("reconnecting");182 h.client.wake();183 await h.flush();184 expect(h.states().at(-1)).toBe("live");185 h.client.stop();186 expect(h.states().at(-1)).toBe("closed");187 h.client.wake();188 await h.flush();189 expect(h.calls).toHaveLength(2);190 });191});192