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