Skip to content
Source
Sign inSign up
pingdotgg/t3code
Open History to see the last commit

wsRpcHarness.ts

177 lines5.6 KB

1import { Effect, Exit, PubSub, Scope, Stream } from "effect";
2import { WS_METHODS, WsRpcGroup } from "@t3tools/contracts";
3import { RpcMessage, RpcSerialization, RpcServer } from "effect/unstable/rpc";
4​
5type RpcServerInstance = RpcServer.RpcServer<any>;
6​
7type BrowserWsClient = {
8 send: (data: string) => void;
9};
10​
11export type NormalizedWsRpcRequestBody = {
12 _tag: string;
13 [key: string]: unknown;
14};
15​
16type UnaryResolverResult = unknown | Promise<unknown>;
17​
18interface BrowserWsRpcHarnessOptions {
19 readonly resolveUnary?: (request: NormalizedWsRpcRequestBody) => UnaryResolverResult;
20 readonly getInitialStreamValues?: (
21 request: NormalizedWsRpcRequestBody,
22 ) => ReadonlyArray<unknown> | undefined;
24​
25const STREAM_METHODS = new Set<string>([
26 WS_METHODS.gitRunStackedAction,
27 WS_METHODS.subscribeGitStatus,
28 WS_METHODS.subscribeOrchestrationDomainEvents,
29 WS_METHODS.subscribeTerminalEvents,
30 WS_METHODS.subscribeServerConfig,
31 WS_METHODS.subscribeServerLifecycle,
32]);
33​
34const ALL_RPC_METHODS = Array.from(WsRpcGroup.requests.keys());
35​
36function normalizeRequest(tag: string, payload: unknown): NormalizedWsRpcRequestBody {
37 if (payload && typeof payload === "object" && !Array.isArray(payload)) {
38 return {
39 _tag: tag,
40 ...(payload as Record<string, unknown>),
41 };
42 }
43 return { _tag: tag, payload };
45​
46function asEffect(result: UnaryResolverResult): Effect.Effect<unknown> {
47 if (result instanceof Promise) {
48 return Effect.promise(() => result);
49 }
50 return Effect.succeed(result);
52​
53export class BrowserWsRpcHarness {
54 readonly requests: Array<NormalizedWsRpcRequestBody> = [];
55​
56 private readonly parser = RpcSerialization.json.makeUnsafe();
57 private client: BrowserWsClient | null = null;
58 private scope: Scope.Closeable | null = null;
59 private serverReady: Promise<RpcServerInstance> | null = null;
60 private resolveUnary: NonNullable<BrowserWsRpcHarnessOptions["resolveUnary"]> = () => ({});
61 private getInitialStreamValues: NonNullable<
62 BrowserWsRpcHarnessOptions["getInitialStreamValues"]
63 > = () => [];
64 private streamPubSubs = new Map<string, PubSub.PubSub<unknown>>();
65​
66 async reset(options?: BrowserWsRpcHarnessOptions): Promise<void> {
67 await this.disconnect();
68 this.requests.length = 0;
69 this.resolveUnary = options?.resolveUnary ?? (() => ({}));
70 this.getInitialStreamValues = options?.getInitialStreamValues ?? (() => []);
71 this.initializeStreamPubSubs();
72 }
73​
74 connect(client: BrowserWsClient): void {
75 if (this.scope) {
76 void Effect.runPromise(Scope.close(this.scope, Exit.void)).catch(() => undefined);
77 }
78 if (this.streamPubSubs.size === 0) {
79 this.initializeStreamPubSubs();
80 }
81 this.client = client;
82 this.scope = Effect.runSync(Scope.make());
83 this.serverReady = Effect.runPromise(
84 Scope.provide(this.scope)(
85 RpcServer.makeNoSerialization(WsRpcGroup, this.makeServerOptions()),
86 ).pipe(Effect.provide(this.makeLayer())),
87 ) as Promise<RpcServerInstance>;
88 }
89​
90 async disconnect(): Promise<void> {
91 if (this.scope) {
92 await Effect.runPromise(Scope.close(this.scope, Exit.void)).catch(() => undefined);
93 this.scope = null;
94 }
95 for (const pubsub of this.streamPubSubs.values()) {
96 Effect.runSync(PubSub.shutdown(pubsub));
97 }
98 this.streamPubSubs.clear();
99 this.serverReady = null;
100 this.client = null;
101 }
102​
103 private initializeStreamPubSubs(): void {
104 this.streamPubSubs = new Map(
105 Array.from(STREAM_METHODS, (method) => [method, Effect.runSync(PubSub.unbounded<unknown>())]),
106 );
107 }
108​
109 async onMessage(rawData: string): Promise<void> {
110 const server = await this.serverReady;
111 if (!server) {
112 return;
113 }
114 const messages = this.parser.decode(rawData);
115 for (const message of messages) {
116 if (message && typeof message === "object" && "_tag" in message && message._tag === "Ping") {
117 const encoded = this.parser.encode(RpcMessage.constPong);
118 if (typeof encoded === "string") {
119 this.client?.send(encoded);
120 }
121 continue;
122 }
123 await Effect.runPromise(server.write(0, message as never));
124 }
125 }
126​
127 emitStreamValue(method: string, value: unknown): void {
128 const pubsub = this.streamPubSubs.get(method);
129 if (!pubsub) {
130 throw new Error(`No stream registered for ${method}`);
131 }
132 Effect.runSync(PubSub.publish(pubsub, value));
133 }
134​
135 private makeLayer() {
136 const handlers: Record<string, (payload: unknown) => unknown> = {};
137 for (const method of ALL_RPC_METHODS) {
138 handlers[method] = STREAM_METHODS.has(method)
139 ? (payload) => this.handleStream(method, payload)
140 : (payload) => this.handleUnary(method, payload);
141 }
142 return WsRpcGroup.toLayer(handlers as never);
143 }
144​
145 private makeServerOptions() {
146 return {
147 onFromServer: (response: unknown) =>
148 Effect.sync(() => {
149 if (!this.client) {
150 return;
151 }
152 const encoded = this.parser.encode(response);
153 if (typeof encoded === "string") {
154 this.client.send(encoded);
155 }
156 }),
157 };
158 }
159​
160 private handleUnary(method: string, payload: unknown) {
161 const request = normalizeRequest(method, payload);
162 this.requests.push(request);
163 return asEffect(this.resolveUnary(request));
164 }
165​
166 private handleStream(method: string, payload: unknown) {
167 const request = normalizeRequest(method, payload);
168 this.requests.push(request);
169 const pubsub = this.streamPubSubs.get(method);
170 if (!pubsub) {
171 throw new Error(`No stream registered for ${method}`);
172 }
173 return Stream.fromIterable(this.getInitialStreamValues(request) ?? []).pipe(
174 Stream.concat(Stream.fromPubSub(pubsub)),
175 );
176 }