Open History to see the last commit
1import {
2 Cause,
3 Duration,
4 Effect,
5 Exit,
6 Layer,
7 ManagedRuntime,
8 Option,
9 Scope,
10 Stream,
11} from "effect";
12import { RpcClient } from "effect/unstable/rpc";
13
14import { ClientTracingLive, configureClientTracing } from "./observability/clientTracing";
15import {
16 createWsRpcProtocolLayer,
17 makeWsRpcProtocolClient,
18 type WsRpcProtocolClient,
19} from "./rpc/protocol";
20
21interface SubscribeOptions {
22 readonly retryDelay?: Duration.Input;
23 readonly onResubscribe?: () => void;
24}
25
26interface RequestOptions {
27 readonly timeout?: Option.Option<Duration.Input>;
28}
29
30const DEFAULT_SUBSCRIPTION_RETRY_DELAY_MS = Duration.millis(250);
31const NOOP: () => void = () => undefined;
32
33interface TransportSession {
34 readonly clientPromise: Promise<WsRpcProtocolClient>;
35 readonly clientScope: Scope.Closeable;
36 readonly runtime: ManagedRuntime.ManagedRuntime<RpcClient.Protocol, never>;
37}
38
39function formatErrorMessage(error: unknown): string {
40 if (error instanceof Error && error.message.trim().length > 0) {
41 return error.message;
42 }
43 return String(error);
44}
45
46export class WsTransport {
47 private readonly tracingReady: Promise<void>;
48 private readonly url: string | undefined;
49 private disposed = false;
50 private reconnectChain: Promise<void> = Promise.resolve();
51 private session: TransportSession;
52
53 constructor(url?: string) {
54 this.url = url;
55 this.tracingReady = configureClientTracing();
56 this.session = this.createSession();
57 }
58
59 async request<TSuccess>(
60 execute: (client: WsRpcProtocolClient) => Effect.Effect<TSuccess, Error, never>,
61 _options?: RequestOptions,
62 ): Promise<TSuccess> {
63 if (this.disposed) {
64 throw new Error("Transport disposed");
65 }
66
67 await this.tracingReady;
68 const session = this.session;
69 const client = await session.clientPromise;
70 return await session.runtime.runPromise(Effect.suspend(() => execute(client)));
71 }
72
73 async requestStream<TValue>(
74 connect: (client: WsRpcProtocolClient) => Stream.Stream<TValue, Error, never>,
75 listener: (value: TValue) => void,
76 ): Promise<void> {
77 if (this.disposed) {
78 throw new Error("Transport disposed");
79 }
80
81 await this.tracingReady;
82 const session = this.session;
83 const client = await session.clientPromise;
84 await session.runtime.runPromise(
85 Stream.runForEach(connect(client), (value) =>
86 Effect.sync(() => {
87 try {
88 listener(value);
89 } catch {
90 // Swallow listener errors so the stream can finish cleanly.
91 }
92 }),
93 ),
94 );
95 }
96
97 subscribe<TValue>(
98 connect: (client: WsRpcProtocolClient) => Stream.Stream<TValue, Error, never>,
99 listener: (value: TValue) => void,
100 options?: SubscribeOptions,
101 ): () => void {
102 if (this.disposed) {
103 return () => undefined;
104 }
105
106 let active = true;
107 let hasReceivedValue = false;
108 const retryDelayMs = Duration.toMillis(
109 Duration.fromInputUnsafe(options?.retryDelay ?? DEFAULT_SUBSCRIPTION_RETRY_DELAY_MS),
110 );
111 let cancelCurrentStream: () => void = NOOP;
112
113 void (async () => {
114 for (;;) {
115 if (!active || this.disposed) {
116 return;
117 }
118
119 try {
120 if (hasReceivedValue) {
121 try {
122 options?.onResubscribe?.();
123 } catch {
124 // Swallow reconnect hook errors so the stream can recover.
125 }
126 }
127
128 const session = this.session;
129 const runningStream = this.runStreamOnSession(
130 session,
131 connect,
132 listener,
133 () => active,
134 () => {
135 hasReceivedValue = true;
136 },
137 );
138 cancelCurrentStream = runningStream.cancel;
139 await runningStream.completed;
140 cancelCurrentStream = NOOP;
141 } catch (error) {
142 cancelCurrentStream = NOOP;
143 if (!active || this.disposed) {
144 return;
145 }
146
147 console.warn("WebSocket RPC subscription disconnected", {
148 error: formatErrorMessage(error),
149 });
150 await sleep(retryDelayMs);
151 }
152 }
153 })();
154
155 return () => {
156 active = false;
157 cancelCurrentStream();
158 };
159 }
160
161 async reconnect() {
162 if (this.disposed) {
163 throw new Error("Transport disposed");
164 }
165
166 const reconnectOperation = this.reconnectChain.then(async () => {
167 if (this.disposed) {
168 throw new Error("Transport disposed");
169 }
170
171 const previousSession = this.session;
172 this.session = this.createSession();
173 await this.closeSession(previousSession);
174 });
175
176 this.reconnectChain = reconnectOperation.catch(() => undefined);
177 await reconnectOperation;
178 }
179
180 async dispose() {
181 if (this.disposed) {
182 return;
183 }
184 this.disposed = true;
185 await this.closeSession(this.session);
186 }
187
188 private closeSession(session: TransportSession) {
189 return session.runtime.runPromise(Scope.close(session.clientScope, Exit.void)).finally(() => {
190 session.runtime.dispose();
191 });
192 }
193
194 private createSession(): TransportSession {
195 const runtime = ManagedRuntime.make(
196 Layer.mergeAll(createWsRpcProtocolLayer(this.url), ClientTracingLive),
197 );
198 const clientScope = runtime.runSync(Scope.make());
199 return {
200 runtime,
201 clientScope,
202 clientPromise: runtime.runPromise(Scope.provide(clientScope)(makeWsRpcProtocolClient)),
203 };
204 }
205
206 private runStreamOnSession<TValue>(
207 session: TransportSession,
208 connect: (client: WsRpcProtocolClient) => Stream.Stream<TValue, Error, never>,
209 listener: (value: TValue) => void,
210 isActive: () => boolean,
211 markValueReceived: () => void,
212 ): {
213 readonly cancel: () => void;
214 readonly completed: Promise<void>;
215 } {
216 let resolveCompleted!: () => void;
217 let rejectCompleted!: (error: unknown) => void;
218 const completed = new Promise<void>((resolve, reject) => {
219 resolveCompleted = resolve;
220 rejectCompleted = reject;
221 });
222 const cancel = session.runtime.runCallback(
223 Effect.promise(() => this.tracingReady).pipe(
224 Effect.flatMap(() => Effect.promise(() => session.clientPromise)),
225 Effect.flatMap((client) =>
226 Stream.runForEach(connect(client), (value) =>
227 Effect.sync(() => {
228 if (!isActive()) {
229 return;
230 }
231
232 markValueReceived();
233 try {
234 listener(value);
235 } catch {
236 // Swallow listener errors so the stream stays live.
237 }
238 }),
239 ),
240 ),
241 ),
242 {
243 onExit: (exit) => {
244 if (Exit.isSuccess(exit)) {
245 resolveCompleted();
246 return;
247 }
248
249 rejectCompleted(Cause.squash(exit.cause));
250 },
251 },
252 );
253
254 return {
255 cancel,
256 completed,
257 };
258 }
259}
260
261function sleep(ms: number): Promise<void> {
262 return new Promise((resolve) => {
263 setTimeout(resolve, ms);
264 });
265}