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

wsRpcHarness.ts

178 lines5.7 KB

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