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 });
57
58 const delivered = yield* pushBus.publishClient(
59 client as unknown as WebSocket,
60 WS_CHANNELS.serverWelcome,
61 {
62 cwd: "/tmp/project",
63 projectName: "project",
64 },
65 );
66 expect(delivered).toBe(true);
67
68 yield* Ref.update(clients, (current) => current.add(client as unknown as WebSocket));
69
70 yield* pushBus.publishAll(WS_CHANNELS.serverConfigUpdated, {
71 issues: [],
72 });
73
74 yield* Effect.promise(() => client.waitForSentCount(2));
75
76 const messages = client.sent.map(
77 (message) => JSON.parse(message) as { channel: string; data: unknown },
78 );
79
80 expect(messages).toHaveLength(2);
81 expect(messages[0]).toEqual({
82 type: "push",
83 sequence: 2,
84 channel: WS_CHANNELS.serverWelcome,
85 data: {
86 cwd: "/tmp/project",
87 projectName: "project",
88 },
89 });
90 expect(messages[1]).toEqual({
91 type: "push",
92 sequence: 3,
93 channel: WS_CHANNELS.serverConfigUpdated,
94 data: {
95 issues: [],
96 },
97 });
98 }),
99 ),
100 );
101});