Open History to see the last commit
1import * as Cause from "effect/Cause";
2import * as Duration from "effect/Duration";
3import * as Effect from "effect/Effect";
4import * as Exit from "effect/Exit";
5import * as Layer from "effect/Layer";
6import * as ManagedRuntime from "effect/ManagedRuntime";
7import * as Scope from "effect/Scope";
8import * as Stream from "effect/Stream";
9import { RpcClient } from "effect/unstable/rpc";
10
11import { isTransportConnectionErrorMessage } from "./transportError.ts";
12import {
13 createWsRpcProtocolLayer,
14 makeWsRpcProtocolClient,
15 type WsProtocolLifecycleHandlers,
16 type WsRpcProtocolClient,
17 type WsRpcProtocolSocketUrlProvider,
18} from "./wsRpcProtocol.ts";
19
20export interface WsTransportOptions {
21 /**
22 * Merged into the transport `ManagedRuntime` alongside the RPC protocol layer
23 * (for example a `Tracer` layer for OTLP).
24 */
25 readonly tracingLayer?: Layer.Layer<never, never, never>;
26 /**
27 * Override protocol construction (defaults to {@link createWsRpcProtocolLayer}).
28 * The web app supplies its instrumented layer factory.
29 */
30 readonly createProtocolLayer?: (
31 url: WsRpcProtocolSocketUrlProvider,
32 lifecycleHandlers?: WsProtocolLifecycleHandlers,
33 ) => Layer.Layer<RpcClient.Protocol, never, never>;
34 readonly logWarning?: (message: string, metadata: { readonly error: string }) => void;
35 /**
36 * Invoked at the start of {@link WsTransport.reconnect} before the session is replaced.
37 */
38 readonly onBeforeReconnect?: () => void;
39}
40
41interface SubscribeOptions {
42 readonly retryDelay?: Duration.Input;
43 readonly onResubscribe?: () => void;
44 readonly tag?: string;
45}
46
47const DEFAULT_SUBSCRIPTION_RETRY_DELAY = Duration.millis(250);
48const NOOP: () => void = () => undefined;
49
50interface TransportSession {
51 readonly clientPromise: Promise<WsRpcProtocolClient>;
52 readonly clientScope: Scope.Closeable;
53 readonly runtime: ManagedRuntime.ManagedRuntime<RpcClient.Protocol, never>;
54}
55
56function formatErrorMessage(error: unknown): string {
57 if (error instanceof Error && error.message.trim().length > 0) {
58 return error.message;
59 }
60
61 return String(error);
62}
63
64export class WsTransport {
65 private readonly url: WsRpcProtocolSocketUrlProvider;
66 private readonly lifecycleHandlers: WsProtocolLifecycleHandlers | undefined;
67 private readonly options: WsTransportOptions | undefined;
68 private disposed = false;
69 private hasReportedTransportDisconnect = false;
70 private intentionalCloseDepth = 0;
71 private nextSessionId = 0;
72 private activeSessionId = 0;
73 private lastHeartbeatPongAt: number | null = null;
74 private readonly streamRequestStartListeners = new Set<
75 (info: { readonly tag: string }) => void
76 >();
77 private reconnectChain: Promise<void> = Promise.resolve();
78 private session: TransportSession;
79
80 constructor(
81 url: WsRpcProtocolSocketUrlProvider,
82 lifecycleHandlers?: WsProtocolLifecycleHandlers,
83 options?: WsTransportOptions,
84 ) {
85 this.url = url;
86 this.lifecycleHandlers = lifecycleHandlers;
87 this.options = options;
88 this.session = this.createSession();
89 }
90
91 async request<TSuccess>(
92 execute: (client: WsRpcProtocolClient) => Effect.Effect<TSuccess, Error, never>,
93 ): Promise<TSuccess> {
94 if (this.disposed) {
95 throw new Error("Transport disposed");
96 }
97
98 const session = this.session;
99 const client = await session.clientPromise;
100 return await session.runtime.runPromise(Effect.suspend(() => execute(client)));
101 }
102
103 async requestStream<TValue>(
104 connect: (client: WsRpcProtocolClient) => Stream.Stream<TValue, Error, never>,
105 listener: (value: TValue) => void,
106 ): Promise<void> {
107 if (this.disposed) {
108 throw new Error("Transport disposed");
109 }
110
111 const session = this.session;
112 const client = await session.clientPromise;
113 await session.runtime.runPromise(
114 Stream.runForEach(connect(client), (value) =>
115 Effect.sync(() => {
116 try {
117 listener(value);
118 } catch {
119 // Ignore listener errors so the stream can finish cleanly.
120 }
121 }),
122 ),
123 );
124 }
125
126 subscribe<TValue>(
127 connect: (client: WsRpcProtocolClient) => Stream.Stream<TValue, Error, never>,
128 listener: (value: TValue) => void,
129 options?: SubscribeOptions,
130 ): () => void {
131 if (this.disposed) {
132 return NOOP;
133 }
134
135 let active = true;
136 let hasReceivedValue = false;
137 const retryDelayMs = Duration.toMillis(
138 Duration.fromInputUnsafe(options?.retryDelay ?? DEFAULT_SUBSCRIPTION_RETRY_DELAY),
139 );
140 let cancelCurrentStream: () => void = NOOP;
141 const onStreamRequestStart = (info: { readonly tag: string }) => {
142 if (
143 !hasReceivedValue ||
144 !active ||
145 (options?.tag !== undefined && info.tag !== options.tag)
146 ) {
147 return;
148 }
149
150 try {
151 options?.onResubscribe?.();
152 } catch {
153 // Ignore reconnect hook failures so the stream can recover.
154 }
155 };
156 this.streamRequestStartListeners.add(onStreamRequestStart);
157
158 void (async () => {
159 for (;;) {
160 if (!active || this.disposed) {
161 return;
162 }
163
164 const session = this.session;
165 try {
166 const runningStream = this.runStreamOnSession(
167 session,
168 connect,
169 listener,
170 () => active,
171 () => {
172 this.hasReportedTransportDisconnect = false;
173 hasReceivedValue = true;
174 },
175 );
176 cancelCurrentStream = runningStream.cancel;
177 await runningStream.completed;
178 cancelCurrentStream = NOOP;
179 } catch (error) {
180 cancelCurrentStream = NOOP;
181 if (!active || this.disposed) {
182 return;
183 }
184
185 // Skip retry if the session has already been replaced by a reconnect.
186 if (session !== this.session) {
187 continue;
188 }
189
190 const formattedError = formatErrorMessage(error);
191 if (!isTransportConnectionErrorMessage(formattedError)) {
192 this.logWarning("WebSocket RPC subscription failed", { error: formattedError });
193 return;
194 }
195
196 if (!this.hasReportedTransportDisconnect) {
197 this.logWarning("WebSocket RPC subscription disconnected", {
198 error: formattedError,
199 });
200 }
201 this.hasReportedTransportDisconnect = true;
202 await sleep(retryDelayMs);
203 }
204 }
205 })();
206
207 return () => {
208 active = false;
209 this.streamRequestStartListeners.delete(onStreamRequestStart);
210 cancelCurrentStream();
211 };
212 }
213
214 async reconnect() {
215 if (this.disposed) {
216 throw new Error("Transport disposed");
217 }
218
219 const reconnectOperation = this.reconnectChain.then(async () => {
220 if (this.disposed) {
221 throw new Error("Transport disposed");
222 }
223
224 try {
225 this.options?.onBeforeReconnect?.();
226 } catch {
227 // Ignore hook failures so reconnect can proceed.
228 }
229
230 this.lastHeartbeatPongAt = null;
231 const previousSession = this.session;
232 this.session = this.createSession();
233 await this.closeSession(previousSession);
234 });
235
236 this.reconnectChain = reconnectOperation.catch(() => undefined);
237 await reconnectOperation;
238 }
239
240 isHeartbeatFresh(maxAgeMs = 15_000): boolean {
241 return (
242 this.lastHeartbeatPongAt !== null && performance.now() - this.lastHeartbeatPongAt <= maxAgeMs
243 );
244 }
245
246 async dispose() {
247 if (this.disposed) {
248 return;
249 }
250
251 this.disposed = true;
252 await this.closeSession(this.session);
253 }
254
255 private closeSession(session: TransportSession) {
256 this.intentionalCloseDepth += 1;
257 return session.runtime.runPromise(Scope.close(session.clientScope, Exit.void)).finally(() => {
258 this.intentionalCloseDepth = Math.max(0, this.intentionalCloseDepth - 1);
259 session.runtime.dispose();
260 });
261 }
262
263 private createSession(): TransportSession {
264 const protocolFactory = this.options?.createProtocolLayer ?? createWsRpcProtocolLayer;
265 const sessionId = this.nextSessionId + 1;
266 this.nextSessionId = sessionId;
267 this.activeSessionId = sessionId;
268 const lifecycleHandlers = this.lifecycleHandlers;
269 const protocolLayer = protocolFactory(this.url, {
270 ...lifecycleHandlers,
271 isActive: () =>
272 !this.disposed &&
273 this.activeSessionId === sessionId &&
274 (lifecycleHandlers?.isActive?.() ?? true),
275 isCloseIntentional: () =>
276 this.disposed ||
277 this.intentionalCloseDepth > 0 ||
278 lifecycleHandlers?.isCloseIntentional?.() === true,
279 onHeartbeatPong: () => {
280 this.lastHeartbeatPongAt = performance.now();
281 lifecycleHandlers?.onHeartbeatPong?.();
282 },
283 onRequestStart: (info) => {
284 lifecycleHandlers?.onRequestStart?.(info);
285 if (!info.stream) {
286 return;
287 }
288 for (const listener of this.streamRequestStartListeners) {
289 listener({ tag: info.tag });
290 }
291 },
292 });
293 const rootLayer = this.options?.tracingLayer
294 ? Layer.mergeAll(protocolLayer, this.options.tracingLayer)
295 : protocolLayer;
296 const runtime = ManagedRuntime.make(rootLayer);
297 const clientScope = runtime.runSync(Scope.make());
298 return {
299 runtime,
300 clientScope,
301 clientPromise: runtime.runPromise(Scope.provide(clientScope)(makeWsRpcProtocolClient)),
302 };
303 }
304
305 private logWarning(message: string, metadata: { readonly error: string }) {
306 const logWarning = this.options?.logWarning;
307 if (logWarning) {
308 logWarning(message, metadata);
309 } else {
310 Effect.runSync(Effect.logWarning(message, metadata));
311 }
312 }
313
314 private runStreamOnSession<TValue>(
315 session: TransportSession,
316 connect: (client: WsRpcProtocolClient) => Stream.Stream<TValue, Error, never>,
317 listener: (value: TValue) => void,
318 isActive: () => boolean,
319 markValueReceived: () => void,
320 ): {
321 readonly cancel: () => void;
322 readonly completed: Promise<void>;
323 } {
324 let resolveCompleted!: () => void;
325 let rejectCompleted!: (error: unknown) => void;
326 const completed = new Promise<void>((resolve, reject) => {
327 resolveCompleted = resolve;
328 rejectCompleted = reject;
329 });
330 const cancel = session.runtime.runCallback(
331 Effect.promise(() => session.clientPromise).pipe(
332 Effect.flatMap((client) =>
333 Stream.runForEach(connect(client), (value) =>
334 Effect.sync(() => {
335 if (!isActive()) {
336 return;
337 }
338
339 markValueReceived();
340 try {
341 listener(value);
342 } catch {
343 // Ignore listener errors so the stream stays live.
344 }
345 }),
346 ),
347 ),
348 ),
349 {
350 onExit: (exit) => {
351 if (Exit.isSuccess(exit)) {
352 resolveCompleted();
353 return;
354 }
355
356 rejectCompleted(Cause.squash(exit.cause));
357 },
358 },
359 );
360
361 return {
362 cancel,
363 completed,
364 };
365 }
366}
367
368function sleep(ms: number): Promise<void> {
369 return Effect.runPromise(Effect.sleep(Duration.millis(ms)));
370}