Open History to see the last commit
1import type { WebSocket } from "ws";
2import { it } from "@effect/vitest";
3import { describe, expect } from "vitest";
4import { Effect, Ref } from "effect";
5import { WS_CHANNELS } from "@t3tools/contracts";
6
7import { makeServerPushBus } from "./pushBus";
8
9class MockWebSocket {
10 static readonly OPEN = 1;
11
12 readonly OPEN = MockWebSocket.OPEN;
13 readyState = MockWebSocket.OPEN;
14 readonly sent: string[] = [];
15 private readonly waiters = new Set<() => void>();
16
17 send(message: string) {
18 this.sent.push(message);
19 for (const waiter of this.waiters) {
20 waiter();
21 }
22 }
23
24 waitForSentCount(count: number): Promise<void> {
25 if (this.sent.length >= count) {
26 return Promise.resolve();
27 }
28
29 return new Promise((resolve) => {
30 const check = () => {
31 if (this.sent.length < count) {
32 return;
33 }
34 this.waiters.delete(check);
35 resolve();
36 };
37
38 this.waiters.add(check);
39 });
40 }
41}
42
43describe("makeServerPushBus", () => {
44 it.live("waits for the welcome push before a new client joins broadcast delivery", () =>
45 Effect.scoped(
46 Effect.gen(function* () {
47 const client = new MockWebSocket();
48 const clients = yield* Ref.make(new Set<WebSocket>());
49 const pushBus = yield* makeServerPushBus({
50 clients,
51 logOutgoingPush: () => {},
52 });
53
54 yield* pushBus.publishAll(WS_CHANNELS.serverConfigUpdated, {
55 issues: [{ kind: "keybindings.malformed-config", message: "queued-before-connect" }],
56 providers: [],
57 });
58
59 const delivered = yield* pushBus.publishClient(
60 client as unknown as WebSocket,
61 WS_CHANNELS.serverWelcome,
62 {
63 cwd: "/tmp/project",
64 projectName: "project",
65 },
66 );
67 expect(delivered).toBe(true);
68
69 yield* Ref.update(clients, (current) => current.add(client as unknown as WebSocket));
70
71 yield* pushBus.publishAll(WS_CHANNELS.serverConfigUpdated, {
72 issues: [],
73 providers: [],
74 });
75
76 yield* Effect.promise(() => client.waitForSentCount(2));
77
78 const messages = client.sent.map(
79 (message) => JSON.parse(message) as { channel: string; data: unknown },
80 );
81
82 expect(messages).toHaveLength(2);
83 expect(messages[0]).toEqual({
84 type: "push",
85 sequence: 2,
86 channel: WS_CHANNELS.serverWelcome,
87 data: {
88 cwd: "/tmp/project",
89 projectName: "project",
90 },
91 });
92 expect(messages[1]).toEqual({
93 type: "push",
94 sequence: 3,
95 channel: WS_CHANNELS.serverConfigUpdated,
96 data: {
97 issues: [],
98 providers: [],
99 },
100 });
101 }),
102 ),
103 );
104});