summaryrefslogtreecommitdiff
path: root/gui/src/hooks/useWs.tsx
blob: b11c0aa6329462cf3becc3dec7c078f64645c208 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
import { useCallback, useEffect, useMemo, useRef, useState } from "react";

// --- Hook: useWebSocket ------------------------------------------------------
// Handles: connect, open, message, error, close, reconnect (exp backoff + jitter),
// heartbeat, offline/online, tab visibility, send queue, clean teardown.

export type WsStatus = "idle" | "connecting" | "open" | "closing" | "closed";

export interface UseWebSocketOptions {
  url: string;
  protocols?: string | string[];
  autoReconnect?: boolean; // default: true
  maxRetries?: number; // default: Infinity
  backoffInitialMs?: number; // default: 500
  backoffMaxMs?: number; // default: 10_000
  heartbeatIntervalMs?: number; // default: 25_000 (typical ALB/NGINX timeouts ~60s)
  heartbeatMessage?:
    | string
    | ArrayBuffer
    | Blob
    | (() => string | ArrayBuffer | Blob);
  // If provided, decides whether to reconnect on close (e.g., avoid on 1000 normal close)
  shouldReconnectOnClose?: (ev: CloseEvent) => boolean;
  // Optional passive listeners
  onOpen?: (ev: Event) => void;
  onMessage?: (ev: MessageEvent) => void;
  onError?: (ev: Event) => void;
  onClose?: (ev: CloseEvent) => void;
}

export interface UseWebSocketApi {
  status: WsStatus;
  retryCount: number;
  error: Event | CloseEvent | null;
  bufferedAmount: number; // bytes currently queued in the socket buffer
  lastMessage: MessageEvent | null;
  // Sends immediately if OPEN, otherwise enqueues to flush on open
  send: (data: string | ArrayBuffer | Blob) => boolean; // returns true if sent now
  // attempt an immediate reconnect (resets backoff)
  reconnectNow: () => void;
  // graceful close (optionally with code & reason)
  close: (code?: number, reason?: string) => void;
}

function jitter(ms: number) {
  const spread = ms * 0.2; // ±20%
  return ms + (Math.random() * 2 - 1) * spread;
}

export function useWebSocket(opts: UseWebSocketOptions): UseWebSocketApi {
  const {
    url,
    protocols,
    autoReconnect = true,
    maxRetries = Number.POSITIVE_INFINITY,
    backoffInitialMs = 500,
    backoffMaxMs = 10_000,
    heartbeatIntervalMs = 25_000,
    heartbeatMessage = () => (typeof window !== "undefined" ? "ping" : "ping"),
    shouldReconnectOnClose = (ev) =>
      ev.code !== 1000 && ev.code !== 1001 && ev.code !== 1005,
    onOpen,
    onMessage,
    onError,
    onClose,
  } = opts;

  const wsRef = useRef<WebSocket | null>(null);
  const heartbeatTimer = useRef<number | null>(null);
  const reconnectTimer = useRef<number | null>(null);
  const pendingQueueRef = useRef<(string | ArrayBuffer | Blob)[]>([]);
  const retryCountRef = useRef(0);
  const manualCloseRef = useRef(false); // track if close() was user-intended

  const [status, setStatus] = useState<WsStatus>("idle");
  const [retryCount, setRetryCount] = useState(0);
  const [error, setError] = useState<Event | CloseEvent | null>(null);
  const [lastMessage, setLastMessage] = useState<MessageEvent | null>(null);
  const [bufferedAmount, setBufferedAmount] = useState(0);

  // --- Internal helpers ------------------------------------------------------
  const clearHeartbeat = () => {
    if (heartbeatTimer.current) {
      window.clearInterval(heartbeatTimer.current);
      heartbeatTimer.current = null;
    }
  };

  const clearReconnect = () => {
    if (reconnectTimer.current) {
      window.clearTimeout(reconnectTimer.current);
      reconnectTimer.current = null;
    }
  };

  const flushQueue = () => {
    const ws = wsRef.current;
    if (!ws || ws.readyState !== WebSocket.OPEN) return;
    const q = pendingQueueRef.current;
    while (q.length) {
      const item = q.shift()!;
      ws.send(item);
    }
    setBufferedAmount(ws.bufferedAmount);
  };

  const scheduleReconnect = (_dueTo: "close" | "error") => {
    if (!autoReconnect) return;
    if (manualCloseRef.current) return; // user requested close -> do not reconnect
    if (retryCountRef.current >= maxRetries) return;

    const attempt = retryCountRef.current + 1;
    const backoff = Math.min(
      backoffMaxMs,
      backoffInitialMs * Math.pow(2, attempt - 1),
    );
    const delay = Math.max(250, jitter(backoff));

    clearReconnect();
    reconnectTimer.current = window.setTimeout(() => {
      connect();
    }, delay);
  };

  const startHeartbeat = () => {
    clearHeartbeat();
    if (!heartbeatIntervalMs) return;
    heartbeatTimer.current = window.setInterval(() => {
      const ws = wsRef.current;
      if (!ws || ws.readyState !== WebSocket.OPEN) return;
      try {
        const msg =
          typeof heartbeatMessage === "function"
            ? heartbeatMessage()
            : heartbeatMessage;
        ws.send(msg);
      } catch {}
    }, heartbeatIntervalMs);
  };

  const bindSocketEvents = (ws: WebSocket) => {
    ws.addEventListener("open", (ev) => {
      setStatus("open");
      setError(null);
      retryCountRef.current = 0;
      setRetryCount(0);
      startHeartbeat();
      flushQueue();
      onOpen?.(ev);
    });

    ws.addEventListener("message", (ev) => {
      setLastMessage(ev);
      setBufferedAmount(ws.bufferedAmount);
      onMessage?.(ev);
    });

    ws.addEventListener("error", (ev) => {
      setError(ev);
      setStatus(ws.readyState === WebSocket.CLOSED ? "closed" : "connecting");
      onError?.(ev);
      scheduleReconnect("error");
    });

    ws.addEventListener("close", (ev) => {
      setStatus("closed");
      setError(ev);
      clearHeartbeat();
      onClose?.(ev);
      if (!manualCloseRef.current && shouldReconnectOnClose(ev)) {
        retryCountRef.current += 1;
        setRetryCount(retryCountRef.current);
        scheduleReconnect("close");
      }
    });
  };

  const connect = useCallback(() => {
    try {
      if (
        wsRef.current &&
        (wsRef.current.readyState === WebSocket.OPEN ||
          wsRef.current.readyState === WebSocket.CONNECTING)
      ) {
        return; // already connected/connecting
      }
      manualCloseRef.current = false;
      setStatus("connecting");
      const ws = new WebSocket(url, protocols);
      wsRef.current = ws;
      bindSocketEvents(ws);
    } catch (e) {
      setError(e as Event);
      scheduleReconnect("error");
    }
    // eslint-disable-next-line react-hooks/exhaustive-deps
  }, [url, JSON.stringify(protocols)]);

  // Maintain connection on mount & url changes
  useEffect(() => {
    connect();
    return () => {
      // teardown
      clearReconnect();
      clearHeartbeat();
      const ws = wsRef.current;
      if (
        ws &&
        (ws.readyState === WebSocket.OPEN ||
          ws.readyState === WebSocket.CONNECTING)
      ) {
        try {
          ws.close(1000, "component unmount");
        } catch {}
      }
      wsRef.current = null;
    };
  }, [connect]);

  // Reconnect when browser regains connectivity
  useEffect(() => {
    const onOnline = () => {
      if (!wsRef.current || wsRef.current.readyState !== WebSocket.OPEN)
        connect();
    };
    const onOffline = () => {
      // proactively close to reset state; will reconnect when back online
      const ws = wsRef.current;
      if (ws && ws.readyState === WebSocket.OPEN) {
        try {
          ws.close(1011, "offline");
        } catch {}
      }
    };
    window.addEventListener("online", onOnline);
    window.addEventListener("offline", onOffline);
    return () => {
      window.removeEventListener("online", onOnline);
      window.removeEventListener("offline", onOffline);
    };
  }, [connect]);

  // Reconnect when tab becomes visible (helps with long-sleeped mobile tabs)
  useEffect(() => {
    const handler = () => {
      if (!document.hidden) {
        const ws = wsRef.current;
        if (!ws || ws.readyState !== WebSocket.OPEN) connect();
      }
    };
    document.addEventListener("visibilitychange", handler);
    return () => document.removeEventListener("visibilitychange", handler);
  }, [connect]);

  const send: UseWebSocketApi["send"] = useCallback((data) => {
    const ws = wsRef.current;
    if (ws && ws.readyState === WebSocket.OPEN) {
      ws.send(data);
      setBufferedAmount(ws.bufferedAmount);
      return true;
    }
    pendingQueueRef.current.push(data);
    return false;
  }, []);

  const reconnectNow = useCallback(() => {
    retryCountRef.current = 0;
    setRetryCount(0);
    clearReconnect();
    const ws = wsRef.current;
    if (
      ws &&
      (ws.readyState === WebSocket.OPEN ||
        ws.readyState === WebSocket.CONNECTING)
    ) {
      try {
        ws.close(1012, "manual reconnect");
      } catch {}
    } else {
      connect();
    }
  }, [connect]);

  const close: UseWebSocketApi["close"] = useCallback(
    (code = 1000, reason = "client close") => {
      manualCloseRef.current = true;
      clearReconnect();
      clearHeartbeat();
      const ws = wsRef.current;
      if (
        ws &&
        (ws.readyState === WebSocket.OPEN ||
          ws.readyState === WebSocket.CONNECTING)
      ) {
        try {
          ws.close(code, reason);
        } catch {}
        setStatus("closing");
      }
    },
    [],
  );

  return useMemo(
    () => ({
      status,
      retryCount,
      error,
      bufferedAmount,
      lastMessage,
      send,
      reconnectNow,
      close,
    }),
    [
      status,
      retryCount,
      error,
      bufferedAmount,
      lastMessage,
      send,
      reconnectNow,
      close,
    ],
  );
}