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