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(() => (resolveWsUrl() ? 'connecting' : 'connected')); const [lastUpdated, setLastUpdated] = useState(() => (resolveWsUrl() ? null : new Date())); const wsRef = useRef(null); const reconnectAttempts = useRef(0); const reconnectTimer = useRef | null>(null); const isMountedRef = useRef(true); const lastThrottleRef = useRef(0); const queryClient = useQueryClient(); const pingIntervalRef = useRef | 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(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(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 }; }