File size: 7,442 Bytes
712f4ea
 
69a84ff
712f4ea
7e6906e
 
712f4ea
 
 
 
 
 
 
69a84ff
 
712f4ea
 
 
 
3ce30ae
712f4ea
 
 
 
80df99b
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
712f4ea
 
 
80df99b
 
 
 
 
 
69a84ff
 
e8cea05
 
 
2ee81a5
 
 
712f4ea
 
69a84ff
712f4ea
 
 
80df99b
712f4ea
 
 
 
 
 
80df99b
712f4ea
 
 
 
 
 
80df99b
712f4ea
 
 
 
 
3ce30ae
 
 
 
 
712f4ea
 
 
 
 
 
 
 
 
 
 
 
 
 
7e6906e
 
 
 
 
26aecb8
 
 
7e6906e
 
a7c4232
 
 
 
48f60d7
 
 
 
712f4ea
 
 
 
 
 
80df99b
 
 
 
 
 
712f4ea
 
 
 
 
 
80df99b
 
 
 
 
712f4ea
 
 
 
 
80df99b
 
 
 
 
712f4ea
 
 
80df99b
712f4ea
 
69a84ff
80df99b
 
 
 
712f4ea
 
 
 
 
 
80df99b
712f4ea
 
 
 
 
 
 
 
69a84ff
80df99b
69a84ff
80df99b
69a84ff
 
 
 
 
 
48f60d7
69a84ff
712f4ea
 
69a84ff
48f60d7
80df99b
712f4ea
80df99b
712f4ea
 
 
80df99b
712f4ea
 
80df99b
 
 
 
 
712f4ea
80df99b
712f4ea
 
 
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
import { useEffect, useRef, useState, useCallback } from 'react';
import { useQueryClient } from '@tanstack/react-query';
import { resolveWsUrl } from '../api/client';
import { SIGNALS_QUERY_KEY } from './useSignals';
import { PAIRS_QUERY_KEY } from './usePairs';
import type { Signal, WSMessage, Pair } from '../types';

export type WSStatus = 'connecting' | 'connected' | 'disconnected' | 'error';

const MAX_RECONNECT_DELAY = 30000;
const BASE_RECONNECT_DELAY = 1000;

export function useWebSocket() {
  const [status, setStatus] = useState<WSStatus>(() => (resolveWsUrl() ? 'connecting' : 'connected'));
  const [lastUpdated, setLastUpdated] = useState<Date | null>(() => (resolveWsUrl() ? null : new Date()));
  const wsRef = useRef<WebSocket | null>(null);
  const reconnectAttempts = useRef(0);
  const reconnectTimer = useRef<ReturnType<typeof setTimeout> | null>(null);
  const isMountedRef = useRef(true);
  const lastThrottleRef = useRef<number>(0);
  const queryClient = useQueryClient();

  const pingIntervalRef = useRef<ReturnType<typeof setInterval> | null>(null);

  const clearTimers = useCallback(() => {
    if (reconnectTimer.current) {
      clearTimeout(reconnectTimer.current);
      reconnectTimer.current = null;
    }
    if (pingIntervalRef.current) {
      clearInterval(pingIntervalRef.current);
      pingIntervalRef.current = null;
    }
  }, []);

  const detachAndClose = useCallback((sock: WebSocket | null) => {
    if (!sock) return;
    sock.onopen = null;
    sock.onmessage = null;
    sock.onclose = null;
    sock.onerror = null;
    try {
      sock.close();
    } catch {
      // Ignore close errors on already-closing sockets
    }
  }, []);

  const connect = useCallback(() => {
    if (!isMountedRef.current) return;

    clearTimers();
    if (wsRef.current) {
      detachAndClose(wsRef.current);
      wsRef.current = null;
    }

    const currentWsUrl = resolveWsUrl();
    if (!currentWsUrl) {
      // In serverless / HTTP mode (e.g. Vercel), mark as connected since fast HTTP polling handles live sync
      setStatus('connected');
      setLastUpdated(new Date());
      return;
    }

    try {
      setStatus('connecting');
      const ws = new WebSocket(currentWsUrl);
      wsRef.current = ws;

      ws.onopen = () => {
        if (!isMountedRef.current || wsRef.current !== ws) return;
        setStatus('connected');
        reconnectAttempts.current = 0;

        // Periodic 20s heartbeat ping to keep connection alive indefinitely
        if (pingIntervalRef.current) clearInterval(pingIntervalRef.current);
        pingIntervalRef.current = setInterval(() => {
          if (wsRef.current === ws && ws.readyState === WebSocket.OPEN) {
            ws.send(JSON.stringify({ type: 'ping' }));
          }
        }, 20000);
      };

      ws.onmessage = (event) => {
        if (!isMountedRef.current || wsRef.current !== ws) return;
        try {
          const msg: WSMessage = JSON.parse(event.data as string);

          if (msg.type === 'signal_update' && msg.data) {
            const signal = msg.data;
            const now = Date.now();
            if (now - lastThrottleRef.current > 3000) {
              lastThrottleRef.current = now;
              setLastUpdated(new Date());
            }

            // Update the specific signal in the cache
            queryClient.setQueryData<Signal[]>(SIGNALS_QUERY_KEY, (old) => {
              if (!old) return [signal];
              const idx = old.findIndex((s) => s.symbol === signal.symbol);
              if (idx === -1) return [...old, signal];
              const next = [...old];
              next[idx] = signal;
              return next;
            });

            // Update individual signal cache
            queryClient.setQueryData([...SIGNALS_QUERY_KEY, signal.symbol], signal);
          }

          if ((msg.type === 'pair_updated' || msg.type === 'pair_update') && msg.data) {
            const updatedPair = msg.data;
            queryClient.setQueryData<Pair[]>(PAIRS_QUERY_KEY, (old) => {
              if (!old) return [updatedPair];
              const idx = old.findIndex((p) => p.symbol === updatedPair.symbol);
              if (idx === -1) return [...old, updatedPair];
              return old.map((p, i) => (i === idx ? { ...p, ...updatedPair } : p));
            });
          }

          if ((msg.type === 'journal_updated' || msg.type === 'journal_update') && msg.data) {
            window.dispatchEvent(new CustomEvent('journal-updated', { detail: msg.data }));
          }

          if (msg.type === 'damian_memory_updated' && msg.data) {
            window.dispatchEvent(new CustomEvent('damian-memory-updated', { detail: msg.data }));
          }
        } catch {
          // Ignore malformed messages
        }
      };

      ws.onclose = () => {
        if (wsRef.current !== ws) return;
        if (pingIntervalRef.current) {
          clearInterval(pingIntervalRef.current);
          pingIntervalRef.current = null;
        }
        wsRef.current = null;
        if (!isMountedRef.current) return;
        setStatus('disconnected');
        scheduleReconnect();
      };

      ws.onerror = () => {
        if (wsRef.current !== ws) return;
        if (pingIntervalRef.current) {
          clearInterval(pingIntervalRef.current);
          pingIntervalRef.current = null;
        }
        if (!isMountedRef.current) return;
        setStatus('error');
        ws.close();
      };
    } catch {
      if (pingIntervalRef.current) {
        clearInterval(pingIntervalRef.current);
        pingIntervalRef.current = null;
      }
      if (!isMountedRef.current) return;
      setStatus('error');
      scheduleReconnect();
    }
  }, [clearTimers, detachAndClose, queryClient]);

  const scheduleReconnect = useCallback(() => {
    if (!isMountedRef.current || !resolveWsUrl()) return;
    if (reconnectTimer.current) {
      clearTimeout(reconnectTimer.current);
      reconnectTimer.current = null;
    }
    const delay = Math.min(
      BASE_RECONNECT_DELAY * Math.pow(2, reconnectAttempts.current),
      MAX_RECONNECT_DELAY
    );
    reconnectAttempts.current++;
    reconnectTimer.current = setTimeout(() => {
      reconnectTimer.current = null;
      if (isMountedRef.current) connect();
    }, delay);
  }, [connect]);

  useEffect(() => {
    isMountedRef.current = true;
    connect();

    const handleServerUrlChange = () => {
      clearTimers();
      if (wsRef.current) {
        detachAndClose(wsRef.current);
        wsRef.current = null;
      }
      reconnectAttempts.current = 0;
      connect();
    };
    window.addEventListener('perps_server_url_changed', handleServerUrlChange);
    window.addEventListener('perps_api_token_changed', handleServerUrlChange);

    return () => {
      isMountedRef.current = false;
      window.removeEventListener('perps_server_url_changed', handleServerUrlChange);
      window.removeEventListener('perps_api_token_changed', handleServerUrlChange);
      clearTimers();
      if (wsRef.current) {
        detachAndClose(wsRef.current);
        wsRef.current = null;
      }
    };
  }, [clearTimers, connect, detachAndClose]);

  const disconnect = useCallback(() => {
    clearTimers();
    if (wsRef.current) {
      detachAndClose(wsRef.current);
      wsRef.current = null;
    }
    setStatus('disconnected');
  }, [clearTimers, detachAndClose]);

  return { status, lastUpdated, disconnect };
}