import { afterEach, describe, expect, test } from "bun:test"; import type { ServerWebSocket } from "bun"; import { attach, broadcast, broadcastIfChanged, keepAlive, __resetBusForTest } from "../src/bus"; interface Sent { data: string; compress: boolean | undefined } function fakeSocket() { const sent: Sent[] = []; const ws = { send: (data: string, compress?: boolean) => { sent.push({ data, compress }); return 1; } }; return { ws: ws as unknown as ServerWebSocket, sent, types: () => sent.map((s) => JSON.parse(s.data).type) }; } afterEach(() => __resetBusForTest()); describe("WS bus: deduped snapshots", () => { test("an identical snapshot is not re-sent; a changed one is", () => { const a = fakeSocket(); attach(a.ws); expect(broadcastIfChanged("node:status", { type: "node:status", payload: { n: 1 } })).toBe(true); expect(broadcastIfChanged("node:status", { type: "node:status", payload: { n: 1 } })).toBe(false); expect(broadcastIfChanged("node:status", { type: "node:status", payload: { n: 2 } })).toBe(true); expect(a.types()).toEqual(["hello", "node:status", "node:status"]); }); test("keys dedupe independently (eval:status only when its own figures move)", () => { const a = fakeSocket(); attach(a.ws); broadcastIfChanged("node:status", { type: "node:status", payload: { n: 1 } }); broadcastIfChanged("eval:status", { type: "eval:status", payload: { inFlight: 0 } }); broadcastIfChanged("node:status", { type: "node:status", payload: { n: 2 } }); broadcastIfChanged("eval:status", { type: "eval:status", payload: { inFlight: 0 } }); expect(a.types()).toEqual(["hello", "node:status", "eval:status", "node:status"]); }); test("a client connecting later is handed the last snapshot immediately", () => { const a = fakeSocket(); attach(a.ws); broadcastIfChanged("node:status", { type: "node:status", payload: { n: 7 } }); const b = fakeSocket(); attach(b.ws); expect(b.types()).toEqual(["hello", "node:status"]); expect(JSON.parse(b.sent[1]!.data).payload).toEqual({ n: 7 }); }); test("keepAlive pings only after a silence, and never with no clients", () => { expect(keepAlive(0)).toBe(false); // nobody attached const a = fakeSocket(); attach(a.ws); broadcast({ type: "queue:reordered", payload: null }); expect(keepAlive(60_000)).toBe(false); // just sent something expect(keepAlive(0)).toBe(true); expect(a.types().at(-1)).toBe("ping"); }); test("large frames request compression, small ones don't", () => { const a = fakeSocket(); attach(a.ws); broadcast({ type: "node:status", payload: "x".repeat(4096) }); expect(a.sent[0]!.compress).toBe(false); // hello expect(a.sent[1]!.compress).toBe(true); }); });