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