Open History to see the last commit
1import { WsRpcGroup } from "@t3tools/contracts";
2import { Duration, Effect, Layer, Schedule } from "effect";
3import { RpcClient, RpcSerialization } from "effect/unstable/rpc";
4import * as Socket from "effect/unstable/socket/Socket";
5
6import {
7 acknowledgeRpcRequest,
8 clearAllTrackedRpcRequests,
9 trackRpcRequestSent,
10} from "./requestLatencyState";
11import {
12 getWsReconnectDelayMsForRetry,
13 recordWsConnectionAttempt,
14 recordWsConnectionClosed,
15 recordWsConnectionErrored,
16 recordWsConnectionOpened,
17 type WsConnectionMetadata,
18 WS_RECONNECT_MAX_RETRIES,
19} from "./wsConnectionState";
20
21export interface WsProtocolCloseContext {
22 readonly intentional: boolean;
23}
24
25export interface WsProtocolLifecycleHandlers {
26 readonly getConnectionLabel?: () => string | null;
27 readonly getVersionMismatchHint?: () => string | null;
28 readonly isCloseIntentional?: () => boolean;
29 readonly isActive?: () => boolean;
30 readonly onAttempt?: (socketUrl: string) => void;
31 readonly onOpen?: () => void;
32 readonly onHeartbeatPing?: () => void;
33 readonly onHeartbeatPong?: () => void;
34 readonly onHeartbeatTimeout?: () => void;
35 readonly onRequestStart?: (info: {
36 readonly id: string;
37 readonly tag: string;
38 readonly stream: boolean;
39 }) => void;
40 readonly onRequestChunk?: (info: {
41 readonly id: string;
42 readonly tag: string;
43 readonly chunkCount: number;
44 }) => void;
45 readonly onRequestExit?: (info: {
46 readonly id: string;
47 readonly tag: string;
48 readonly stream: boolean;
49 }) => void;
50 readonly onRequestInterrupt?: (info: { readonly id: string; readonly tag?: string }) => void;
51 readonly onError?: (message: string) => void;
52 readonly onClose?: (
53 details: { readonly code: number; readonly reason: string },
54 context: WsProtocolCloseContext,
55 ) => void;
56}
57
58export const makeWsRpcProtocolClient = RpcClient.make(WsRpcGroup);
59type RpcClientFactory = typeof makeWsRpcProtocolClient;
60export type WsRpcProtocolClient =
61 RpcClientFactory extends Effect.Effect<infer Client, any, any> ? Client : never;
62export type WsRpcProtocolSocketUrlProvider = string | (() => Promise<string>);
63
64function formatSocketErrorMessage(error: unknown): string {
65 if (error instanceof Error && error.message.trim().length > 0) {
66 return error.message;
67 }
68 return String(error);
69}
70
71function resolveWsRpcSocketUrl(rawUrl: string): string {
72 const resolved = new URL(rawUrl);
73 if (resolved.protocol !== "ws:" && resolved.protocol !== "wss:") {
74 throw new Error(`Unsupported websocket transport URL protocol: ${resolved.protocol}`);
75 }
76
77 resolved.pathname = "/ws";
78 return resolved.toString();
79}
80
81function resolveConnectionMetadata(handlers?: WsProtocolLifecycleHandlers): WsConnectionMetadata {
82 return {
83 connectionLabel: handlers?.getConnectionLabel?.() ?? null,
84 versionMismatchHint: handlers?.getVersionMismatchHint?.() ?? null,
85 };
86}
87
88type ComposedWsProtocolLifecycleHandlers = Required<
89 Pick<WsProtocolLifecycleHandlers, "isActive" | "onAttempt" | "onOpen" | "onError" | "onClose">
90>;
91
92function defaultLifecycleHandlers(
93 handlers?: WsProtocolLifecycleHandlers,
94): ComposedWsProtocolLifecycleHandlers {
95 return {
96 isActive: () => true,
97 onAttempt: (socketUrl) => {
98 recordWsConnectionAttempt(socketUrl, resolveConnectionMetadata(handlers));
99 },
100 onOpen: () => {
101 recordWsConnectionOpened(resolveConnectionMetadata(handlers));
102 },
103 onError: (message) => {
104 clearAllTrackedRpcRequests();
105 recordWsConnectionErrored(message, resolveConnectionMetadata(handlers));
106 },
107 onClose: (details, context) => {
108 clearAllTrackedRpcRequests();
109 if (context.intentional) {
110 return;
111 }
112 recordWsConnectionClosed(details, resolveConnectionMetadata(handlers));
113 },
114 };
115}
116
117function composeLifecycleHandlers(
118 handlers?: WsProtocolLifecycleHandlers,
119): ComposedWsProtocolLifecycleHandlers {
120 const defaults = defaultLifecycleHandlers(handlers);
121 const isActive = handlers?.isActive ?? defaults.isActive;
122
123 return {
124 isActive,
125 onAttempt: (socketUrl) => {
126 if (!isActive()) {
127 return;
128 }
129 defaults.onAttempt(socketUrl);
130 handlers?.onAttempt?.(socketUrl);
131 },
132 onOpen: () => {
133 if (!isActive()) {
134 return;
135 }
136 defaults.onOpen();
137 handlers?.onOpen?.();
138 },
139 onError: (message) => {
140 if (!isActive()) {
141 return;
142 }
143 defaults.onError(message);
144 handlers?.onError?.(message);
145 },
146 onClose: (details, context) => {
147 if (!isActive()) {
148 return;
149 }
150 defaults.onClose(details, context);
151 handlers?.onClose?.(details, context);
152 },
153 };
154}
155
156export function createWsRpcProtocolLayer(
157 url: WsRpcProtocolSocketUrlProvider,
158 handlers?: WsProtocolLifecycleHandlers,
159) {
160 const lifecycle = composeLifecycleHandlers(handlers);
161 const resolvedUrl =
162 typeof url === "function"
163 ? Effect.promise(() => url()).pipe(
164 Effect.map((rawUrl) => resolveWsRpcSocketUrl(rawUrl)),
165 Effect.tapError((error) =>
166 Effect.sync(() => {
167 lifecycle.onError(formatSocketErrorMessage(error));
168 }),
169 ),
170 Effect.orDie,
171 )
172 : resolveWsRpcSocketUrl(url);
173
174 const trackingWebSocketConstructorLayer = Layer.succeed(
175 Socket.WebSocketConstructor,
176 (socketUrl, protocols) => {
177 lifecycle.onAttempt(socketUrl);
178 const socket = new globalThis.WebSocket(socketUrl, protocols);
179
180 socket.addEventListener(
181 "open",
182 () => {
183 lifecycle.onOpen();
184 },
185 { once: true },
186 );
187 socket.addEventListener(
188 "error",
189 () => {
190 lifecycle.onError("Unable to connect to the T3 server WebSocket.");
191 },
192 { once: true },
193 );
194 socket.addEventListener(
195 "close",
196 (event) => {
197 lifecycle.onClose(
198 {
199 code: event.code,
200 reason: event.reason,
201 },
202 {
203 intentional: handlers?.isCloseIntentional?.() ?? false,
204 },
205 );
206 },
207 { once: true },
208 );
209
210 return socket;
211 },
212 );
213 const socketLayer = Socket.layerWebSocket(resolvedUrl).pipe(
214 Layer.provide(trackingWebSocketConstructorLayer),
215 );
216 const retryPolicy = Schedule.addDelay(Schedule.recurs(WS_RECONNECT_MAX_RETRIES), (retryCount) =>
217 Effect.succeed(Duration.millis(getWsReconnectDelayMsForRetry(retryCount) ?? 0)),
218 );
219 const protocolLayer = Layer.effect(
220 RpcClient.Protocol,
221 Effect.map(
222 RpcClient.makeProtocolSocket({
223 retryPolicy,
224 retryTransientErrors: true,
225 }),
226 (protocol) => ({
227 ...protocol,
228 run: (clientId, writeResponse) =>
229 protocol.run(clientId, (response) => {
230 if (response._tag === "ClientProtocolError" || response._tag === "Defect") {
231 clearAllTrackedRpcRequests();
232 }
233 return writeResponse(response);
234 }),
235 }),
236 ),
237 );
238 const requestHooksLayer = Layer.succeed(
239 RpcClient.RequestHooks,
240 RpcClient.RequestHooks.of({
241 onRequestStart: (info) =>
242 Effect.sync(() => {
243 if (!lifecycle.isActive()) {
244 return;
245 }
246 handlers?.onRequestStart?.({
247 id: String(info.id),
248 tag: info.tag,
249 stream: info.stream,
250 });
251 trackRpcRequestSent(String(info.id), info.tag);
252 }),
253 onRequestChunk: (info) =>
254 Effect.sync(() => {
255 if (!lifecycle.isActive()) {
256 return;
257 }
258 handlers?.onRequestChunk?.({
259 id: String(info.id),
260 tag: info.tag,
261 chunkCount: info.chunkCount,
262 });
263 acknowledgeRpcRequest(String(info.id));
264 }),
265 onRequestExit: (info) =>
266 Effect.sync(() => {
267 if (!lifecycle.isActive()) {
268 return;
269 }
270 handlers?.onRequestExit?.({
271 id: String(info.id),
272 tag: info.tag,
273 stream: info.stream,
274 });
275 acknowledgeRpcRequest(String(info.id));
276 }),
277 onRequestInterrupt: (info) =>
278 Effect.sync(() => {
279 if (!lifecycle.isActive()) {
280 return;
281 }
282 handlers?.onRequestInterrupt?.({
283 id: String(info.id),
284 ...(info.tag === undefined ? {} : { tag: info.tag }),
285 });
286 acknowledgeRpcRequest(String(info.id));
287 }),
288 }),
289 );
290 const connectionHooksLayer = Layer.succeed(
291 RpcClient.ConnectionHooks,
292 RpcClient.ConnectionHooks.of({
293 onConnect: Effect.void,
294 onDisconnect: Effect.void,
295 onPing: Effect.sync(() => {
296 if (lifecycle.isActive()) {
297 handlers?.onHeartbeatPing?.();
298 }
299 }),
300 onPong: Effect.sync(() => {
301 if (lifecycle.isActive()) {
302 handlers?.onHeartbeatPong?.();
303 }
304 }),
305 onPingTimeout: Effect.sync(() => {
306 if (lifecycle.isActive()) {
307 clearAllTrackedRpcRequests();
308 recordWsConnectionErrored(
309 "WebSocket heartbeat timed out.",
310 resolveConnectionMetadata(handlers),
311 );
312 handlers?.onHeartbeatTimeout?.();
313 }
314 }),
315 }),
316 );
317
318 return Layer.mergeAll(
319 protocolLayer.pipe(
320 Layer.provide(Layer.mergeAll(socketLayer, RpcSerialization.layerJson, connectionHooksLayer)),
321 ),
322 requestHooksLayer,
323 connectionHooksLayer,
324 );
325}