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

wsTransport.ts

213 lines5.7 KB

1import { WebSocketResponse, WsPush, WsResponse } from "@t3tools/contracts";
2import { Cause, Schema } from "effect";
3​
4type PushListener = (data: unknown) => void;
5​
6interface PendingRequest {
7 resolve: (result: unknown) => void;
8 reject: (error: Error) => void;
9 timeout: ReturnType<typeof setTimeout>;
11​
12const REQUEST_TIMEOUT_MS = 60_000;
13const RECONNECT_DELAYS_MS = [500, 1_000, 2_000, 4_000, 8_000];
14const decodeWsResponseFromJson = Schema.decodeUnknownExit(Schema.fromJsonString(WsResponse));
15const isWsPushEnvelope = Schema.is(WsPush);
16const isWebSocketResponseEnvelope = Schema.is(WebSocketResponse);
17​
18interface WsRequestEnvelope {
19 id: string;
20 body: {
21 _tag: string;
22 [key: string]: unknown;
23 };
25​
26export class WsTransport {
27 private ws: WebSocket | null = null;
28 private nextId = 1;
29 private readonly pending = new Map<string, PendingRequest>();
30 private readonly listeners = new Map<string, Set<PushListener>>();
31 private reconnectAttempt = 0;
32 private reconnectTimer: ReturnType<typeof setTimeout> | null = null;
33 private disposed = false;
34 private readonly url: string;
35​
36 constructor(url?: string) {
37 const bridgeUrl = window.desktopBridge?.getWsUrl();
38 // In dev mode, VITE_WS_URL points to the server's WebSocket endpoint.
39 // In production, the page is served by the WS server on the same host:port.
40 const envUrl = import.meta.env.VITE_WS_URL as string | undefined;
41 this.url =
42 url ??
43 (bridgeUrl && bridgeUrl.length > 0
44 ? bridgeUrl
45 : envUrl && envUrl.length > 0
46 ? envUrl
47 : `ws://${window.location.hostname}:${window.location.port}`);
48 this.connect();
49 }
50​
51 async request<T = unknown>(method: string, params?: unknown): Promise<T> {
52 if (typeof method !== "string" || method.length === 0) {
53 throw new Error("Request method is required");
54 }
55 const id = String(this.nextId++);
56 const body = params != null ? { ...params, _tag: method } : { _tag: method };
57 const message: WsRequestEnvelope = { id, body };
58​
59 return new Promise<T>((resolve, reject) => {
60 const timeout = setTimeout(() => {
61 this.pending.delete(id);
62 reject(new Error(`Request timed out: ${method}`));
63 }, REQUEST_TIMEOUT_MS);
64​
65 this.pending.set(id, {
66 resolve: resolve as (result: unknown) => void,
67 reject,
68 timeout,
69 });
70​
71 this.send(message);
72 });
73 }
74​
75 subscribe(channel: string, listener: PushListener): () => void {
76 let channelListeners = this.listeners.get(channel);
77 if (!channelListeners) {
78 channelListeners = new Set();
79 this.listeners.set(channel, channelListeners);
80 }
81 channelListeners.add(listener);
82​
83 return () => {
84 channelListeners!.delete(listener);
85 if (channelListeners!.size === 0) {
86 this.listeners.delete(channel);
87 }
88 };
89 }
90​
91 dispose() {
92 this.disposed = true;
93 if (this.reconnectTimer !== null) {
94 clearTimeout(this.reconnectTimer);
95 this.reconnectTimer = null;
96 }
97 for (const pending of this.pending.values()) {
98 clearTimeout(pending.timeout);
99 pending.reject(new Error("Transport disposed"));
100 }
101 this.pending.clear();
102 this.ws?.close();
103 this.ws = null;
104 }
105​
106 private connect() {
107 if (this.disposed) return;
108​
109 const ws = new WebSocket(this.url);
110​
111 ws.addEventListener("open", () => {
112 this.ws = ws;
113 this.reconnectAttempt = 0;
114 });
115​
116 ws.addEventListener("message", (event) => {
117 this.handleMessage(event.data);
118 });
119​
120 ws.addEventListener("close", () => {
121 this.ws = null;
122 this.scheduleReconnect();
123 });
124​
125 ws.addEventListener("error", () => {
126 // close event will fire after error
127 });
128 }
129​
130 private handleMessage(raw: unknown) {
131 const exit = decodeWsResponseFromJson(raw);
132 if (exit._tag === "Failure") {
133 console.warn("Dropped inbound WebSocket envelope", {
134 reason: "decode-failed",
135 raw,
136 issue: Cause.pretty(exit.cause),
137 });
138 return;
139 }
140 const message = exit.value;
141​
142 // Push event
143 if (isWsPushEnvelope(message)) {
144 const channelListeners = this.listeners.get(message.channel);
145 if (channelListeners) {
146 for (const listener of channelListeners) {
147 try {
148 listener(message.data);
149 } catch {
150 // Swallow listener errors
151 }
152 }
153 }
154 return;
155 }
156​
157 // Response to a request
158 if (!isWebSocketResponseEnvelope(message)) {
159 return;
160 }
161​
162 const pending = this.pending.get(message.id);
163 if (!pending) return;
164​
165 clearTimeout(pending.timeout);
166 this.pending.delete(message.id);
167​
168 if (message.error) {
169 pending.reject(new Error(message.error.message));
170 } else {
171 pending.resolve(message.result);
172 }
173 }
174​
175 private send(message: WsRequestEnvelope) {
176 if (this.ws?.readyState === WebSocket.OPEN) {
177 this.ws.send(JSON.stringify(message));
178 return;
179 }
180​
181 // If not connected, wait for connection
182 const waitForOpen = () => {
183 const check = setInterval(() => {
184 if (this.disposed) {
185 clearInterval(check);
186 return;
187 }
188 if (this.ws?.readyState === WebSocket.OPEN) {
189 clearInterval(check);
190 this.ws.send(JSON.stringify(message));
191 }
192 }, 50);
193​
194 // Give up after timeout (the pending request will time out on its own)
195 setTimeout(() => clearInterval(check), REQUEST_TIMEOUT_MS);
196 };
197 waitForOpen();
198 }
199​
200 private scheduleReconnect() {
201 if (this.disposed) return;
202​
203 const delay =
204 RECONNECT_DELAYS_MS[Math.min(this.reconnectAttempt, RECONNECT_DELAYS_MS.length - 1)] ??
205 RECONNECT_DELAYS_MS[0]!;
206​
207 this.reconnectAttempt++;
208 this.reconnectTimer = setTimeout(() => {
209 this.reconnectTimer = null;
210 this.connect();
211 }, delay);
212 }