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

wsTransport.ts

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