xonecas.io
8058
Ir

irvc / files

irvc / web / src / lib / presence.ts

4.5 KB
1import { useCallback, useEffect, useRef, useState } from "react";
2import type { WSEvent } from "./types";
3
4const PING = 10_000; // heartbeat interval
5const SILENCE = 20_000; // no reply for this long means the socket is a zombie
6const CONNECTING = 15_000; // a handshake that never completes is a dead end
7const MAX_BACKOFF = 15_000;
8const WAKE_HIDDEN = 5_000; // ignore quick tab switches
9
10// usePresence owns the presence socket and keeps it up. The server sends a full
11// snapshot on every connect, so a reconnect doubles as a resync. `onOpen` fires
12// after each (re)connect so the caller can replay state the server forgot.
13export function usePresence(onEvent: (ev: WSEvent) => void, onOpen: () => void) {
14  const [connected, setConnected] = useState(false);
15  const socket = useRef<WebSocket | null>(null);
16  const event = useRef(onEvent);
17  const opened = useRef(onOpen);
18  event.current = onEvent;
19  opened.current = onOpen;
20
21  useEffect(() => {
22    let reconnecting = 0;
23    let retry = 0;
24    let pong = 0;
25    let connecting = 0;
26    let hidden = Date.now();
27    let closed = false;
28
29    const proto = location.protocol === "https:" ? "wss" : "ws";
30    const url = `${proto}://${location.host}/api/ws`;
31
32    // Jitter keeps every client from retrying in lockstep after a restart.
33    const schedule = () => {
34      const wait = Math.min(1000 * 2 ** retry++, MAX_BACKOFF) * (0.5 + Math.random());
35      reconnecting = window.setTimeout(open, wait);
36    };
37
38    const open = () => {
39      if (closed) return;
40      const ws = new WebSocket(url);
41      socket.current = ws;
42      pong = connecting = Date.now();
43      ws.onopen = () => {
44        retry = 0;
45        setConnected(true);
46        opened.current();
47      };
48      ws.onmessage = (e) => {
49        const ev = JSON.parse(e.data as string) as WSEvent;
50        if (ev.type === "pong") pong = Date.now();
51        else event.current(ev);
52      };
53      // onerror always precedes onclose, so close alone is worth reacting to.
54      ws.onclose = () => {
55        if (socket.current !== ws) return; // already dropped or replaced
56        socket.current = null;
57        setConnected(false);
58        if (!closed) schedule();
59      };
60    };
61
62    // drop abandons a socket instead of closing it. close() runs a closing
63    // handshake, and a half-open peer never answers one, so the browser sits on
64    // the dead socket; detaching it loses nothing and reconnects immediately.
65    const drop = () => {
66      const ws = socket.current;
67      if (!ws) return;
68      socket.current = null;
69      ws.onopen = ws.onmessage = ws.onerror = ws.onclose = null;
70      setConnected(false);
71      ws.close();
72      if (!closed) schedule();
73    };
74
75    // A sleeping laptop keeps the socket OPEN while nothing flows, so trust
76    // heartbeats rather than readyState: silence means reconnect.
77    const beat = window.setInterval(() => {
78      const ws = socket.current;
79      if (!ws) return;
80      if (ws.readyState === WebSocket.CONNECTING) {
81        if (Date.now() - connecting > CONNECTING) drop();
82      } else if (ws.readyState === WebSocket.OPEN) {
83        if (Date.now() - pong > SILENCE) drop();
84        else ws.send('{"type":"ping"}');
85      }
86    }, PING);
87
88    // wake runs when the tab becomes visible again or the network returns. A
89    // healthy socket only gets a liveness probe; tearing it down would force a
90    // reconnect (and a roster resync) for no reason. A socket that is not OPEN
91    // is dropped, and an OPEN one is dropped by the heartbeat if the probe goes
92    // unanswered.
93    const wake = () => {
94      if (closed) return;
95      window.clearTimeout(reconnecting);
96      retry = 0;
97      const ws = socket.current;
98      if (!ws) return open();
99      if (ws.readyState === WebSocket.OPEN) return ws.send('{"type":"ping"}');
100      drop();
101    };
102
103    const onVisibility = () => {
104      if (document.visibilityState === "hidden") hidden = Date.now();
105      else if (Date.now() - hidden > WAKE_HIDDEN) wake();
106    };
107
108    open();
109    document.addEventListener("visibilitychange", onVisibility);
110    window.addEventListener("online", wake);
111    return () => {
112      closed = true;
113      window.clearTimeout(reconnecting);
114      window.clearInterval(beat);
115      document.removeEventListener("visibilitychange", onVisibility);
116      window.removeEventListener("online", wake);
117      socket.current?.close();
118      socket.current = null;
119    };
120  }, []);
121
122  const send = useCallback((data: string) => {
123    const ws = socket.current;
124    if (ws?.readyState === WebSocket.OPEN) ws.send(data);
125  }, []);
126
127  return { connected, send };
128}