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

wsTransport.ts

281 lines7.5 KB

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