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

wsTransport.ts

377 lines11.1 KB

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;
40​
41interface SubscribeOptions {
42 readonly retryDelay?: Duration.Input;
43 readonly onResubscribe?: () => void;
44 readonly tag?: string;
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>;
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);
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 if (hasReceivedValue) {
167 try {
168 options?.onResubscribe?.();
169 } catch {
170 // Ignore reconnect hook failures so the stream can recover.
171 }
172 }
173 const runningStream = this.runStreamOnSession(
174 session,
175 connect,
176 listener,
177 () => active,
178 () => {
179 this.hasReportedTransportDisconnect = false;
180 hasReceivedValue = true;
181 },
182 );
183 cancelCurrentStream = runningStream.cancel;
184 await runningStream.completed;
185 cancelCurrentStream = NOOP;
186 } catch (error) {
187 cancelCurrentStream = NOOP;
188 if (!active || this.disposed) {
189 return;
190 }
191​
192 // Skip retry if the session has already been replaced by a reconnect.
193 if (session !== this.session) {
194 continue;
195 }
196​
197 const formattedError = formatErrorMessage(error);
198 if (!isTransportConnectionErrorMessage(formattedError)) {
199 this.logWarning("WebSocket RPC subscription failed", { error: formattedError });
200 return;
201 }
202​
203 if (!this.hasReportedTransportDisconnect) {
204 this.logWarning("WebSocket RPC subscription disconnected", {
205 error: formattedError,
206 });
207 }
208 this.hasReportedTransportDisconnect = true;
209 await sleep(retryDelayMs);
210 }
211 }
212 })();
213​
214 return () => {
215 active = false;
216 this.streamRequestStartListeners.delete(onStreamRequestStart);
217 cancelCurrentStream();
218 };
219 }
220​
221 async reconnect() {
222 if (this.disposed) {
223 throw new Error("Transport disposed");
224 }
225​
226 const reconnectOperation = this.reconnectChain.then(async () => {
227 if (this.disposed) {
228 throw new Error("Transport disposed");
229 }
230​
231 try {
232 this.options?.onBeforeReconnect?.();
233 } catch {
234 // Ignore hook failures so reconnect can proceed.
235 }
236​
237 this.lastHeartbeatPongAt = null;
238 const previousSession = this.session;
239 this.session = this.createSession();
240 await this.closeSession(previousSession);
241 });
242​
243 this.reconnectChain = reconnectOperation.catch(() => undefined);
244 await reconnectOperation;
245 }
246​
247 isHeartbeatFresh(maxAgeMs = 15_000): boolean {
248 return (
249 this.lastHeartbeatPongAt !== null && performance.now() - this.lastHeartbeatPongAt <= maxAgeMs
250 );
251 }
252​
253 async dispose() {
254 if (this.disposed) {
255 return;
256 }
257​
258 this.disposed = true;
259 await this.closeSession(this.session);
260 }
261​
262 private closeSession(session: TransportSession) {
263 this.intentionalCloseDepth += 1;
264 return session.runtime.runPromise(Scope.close(session.clientScope, Exit.void)).finally(() => {
265 this.intentionalCloseDepth = Math.max(0, this.intentionalCloseDepth - 1);
266 session.runtime.dispose();
267 });
268 }
269​
270 private createSession(): TransportSession {
271 const protocolFactory = this.options?.createProtocolLayer ?? createWsRpcProtocolLayer;
272 const sessionId = this.nextSessionId + 1;
273 this.nextSessionId = sessionId;
274 this.activeSessionId = sessionId;
275 const lifecycleHandlers = this.lifecycleHandlers;
276 const protocolLayer = protocolFactory(this.url, {
277 ...lifecycleHandlers,
278 isActive: () =>
279 !this.disposed &&
280 this.activeSessionId === sessionId &&
281 (lifecycleHandlers?.isActive?.() ?? true),
282 isCloseIntentional: () =>
283 this.disposed ||
284 this.intentionalCloseDepth > 0 ||
285 lifecycleHandlers?.isCloseIntentional?.() === true,
286 onHeartbeatPong: () => {
287 this.lastHeartbeatPongAt = performance.now();
288 lifecycleHandlers?.onHeartbeatPong?.();
289 },
290 onRequestStart: (info) => {
291 lifecycleHandlers?.onRequestStart?.(info);
292 if (!info.stream) {
293 return;
294 }
295 for (const listener of this.streamRequestStartListeners) {
296 listener({ tag: info.tag });
297 }
298 },
299 });
300 const rootLayer = this.options?.tracingLayer
301 ? Layer.mergeAll(protocolLayer, this.options.tracingLayer)
302 : protocolLayer;
303 const runtime = ManagedRuntime.make(rootLayer);
304 const clientScope = runtime.runSync(Scope.make());
305 return {
306 runtime,
307 clientScope,
308 clientPromise: runtime.runPromise(Scope.provide(clientScope)(makeWsRpcProtocolClient)),
309 };
310 }
311​
312 private logWarning(message: string, metadata: { readonly error: string }) {
313 const logWarning = this.options?.logWarning;
314 if (logWarning) {
315 logWarning(message, metadata);
316 } else {
317 Effect.runSync(Effect.logWarning(message, metadata));
318 }
319 }
320​
321 private runStreamOnSession<TValue>(
322 session: TransportSession,
323 connect: (client: WsRpcProtocolClient) => Stream.Stream<TValue, Error, never>,
324 listener: (value: TValue) => void,
325 isActive: () => boolean,
326 markValueReceived: () => void,
327 ): {
328 readonly cancel: () => void;
329 readonly completed: Promise<void>;
330 } {
331 let resolveCompleted!: () => void;
332 let rejectCompleted!: (error: unknown) => void;
333 const completed = new Promise<void>((resolve, reject) => {
334 resolveCompleted = resolve;
335 rejectCompleted = reject;
336 });
337 const cancel = session.runtime.runCallback(
338 Effect.promise(() => session.clientPromise).pipe(
339 Effect.flatMap((client) =>
340 Stream.runForEach(connect(client), (value) =>
341 Effect.sync(() => {
342 if (!isActive()) {
343 return;
344 }
345​
346 markValueReceived();
347 try {
348 listener(value);
349 } catch {
350 // Ignore listener errors so the stream stays live.
351 }
352 }),
353 ),
354 ),
355 ),
356 {
357 onExit: (exit) => {
358 if (Exit.isSuccess(exit)) {
359 resolveCompleted();
360 return;
361 }
362​
363 rejectCompleted(Cause.squash(exit.cause));
364 },
365 },
366 );
367​
368 return {
369 cancel,
370 completed,
371 };
372 }
374​
375function sleep(ms: number): Promise<void> {
376 return Effect.runPromise(Effect.sleep(Duration.millis(ms)));