fix(web): make backtest run controls and selection reliable

This commit is contained in:
Boki 2026-10-22 14:17:25 -04:00
parent 3d26da07f5
commit 67f12b49a0
8 changed files with 1109 additions and 675 deletions

View file

@ -17,188 +17,143 @@ interface UseWebSocketOptions {
onCompleted?: (results?: unknown) => void;
}
export function useWebSocket({
runId,
onMessage,
onProgress,
onError,
onCompleted,
}: UseWebSocketOptions) {
export function useWebSocket({ runId, ...callbacks }: UseWebSocketOptions) {
const [isConnected, setIsConnected] = useState(false);
const [lastMessage, setLastMessage] = useState<WebSocketMessage | null>(null);
const callbacksRef = useRef(callbacks);
const wsRef = useRef<WebSocket | null>(null);
const reconnectTimeoutRef = useRef<NodeJS.Timeout | null>(null);
const pingIntervalRef = useRef<NodeJS.Timeout | null>(null);
const isIntentionalDisconnect = useRef(false);
const connectRef = useRef<() => void>(() => {});
const disconnectRef = useRef<() => void>(() => {});
callbacksRef.current = callbacks;
const connect = useCallback(() => {
if (!runId) {
browserLog.log('useWebSocket: No runId provided, skipping connection');
return;
}
useEffect(() => {
let disposed = false;
let reconnectTimer: ReturnType<typeof setTimeout> | undefined;
let pingTimer: ReturnType<typeof setInterval> | undefined;
setIsConnected(false);
setLastMessage(null);
// Check if already connected or connecting
if (
wsRef.current &&
(wsRef.current.readyState === WebSocket.OPEN ||
wsRef.current.readyState === WebSocket.CONNECTING)
) {
browserLog.log('useWebSocket: Already connected or connecting to runId:', runId);
return;
}
const connect = () => {
if (disposed || !runId || wsRef.current) {
return;
}
clearTimeout(reconnectTimer);
const url = new URL('/ws', API_BASE_URL);
url.protocol = url.protocol === 'https:' ? 'wss:' : 'ws:';
url.searchParams.set('runId', runId);
// Reset intentional disconnect flag
isIntentionalDisconnect.current = false;
// Clear any pending reconnect timeout
if (reconnectTimeoutRef.current) {
clearTimeout(reconnectTimeoutRef.current);
reconnectTimeoutRef.current = null;
}
const url = new URL('/ws', API_BASE_URL);
url.protocol = url.protocol === 'https:' ? 'wss:' : 'ws:';
url.searchParams.set('runId', runId);
const wsUrl = url.toString();
browserLog.log('Connecting to WebSocket:', wsUrl);
try {
const ws = new WebSocket(wsUrl);
wsRef.current = ws;
ws.onopen = () => {
browserLog.log('WebSocket connected');
setIsConnected(true);
// Start ping interval
pingIntervalRef.current = setInterval(() => {
if (ws.readyState === WebSocket.OPEN) {
ws.send(JSON.stringify({ type: 'ping' }));
}
}, 30000); // Ping every 30 seconds
};
ws.onmessage = event => {
try {
const message: WebSocketMessage = JSON.parse(event.data);
browserLog.log('WebSocket message:', message);
setLastMessage(message);
// Call appropriate callbacks
if (onMessage) {
onMessage(message);
}
switch (message.type) {
case 'progress':
if (onProgress && message.data) {
onProgress(message.data.progress ?? 0, message.data.currentDate);
}
break;
case 'error':
if (onError && message.data?.error) {
onError(message.data.error);
browserLog.error('Run Error:', message.data.error);
}
break;
case 'completed':
if (onCompleted) {
onCompleted(message.data?.results);
}
browserLog.log('Run Completed: The backtest run has completed successfully.');
break;
}
} catch (error) {
browserLog.error('Error parsing WebSocket message:', error);
const retry = () => {
if (!disposed) {
reconnectTimer = setTimeout(connect, 3000);
}
};
ws.onerror = error => {
browserLog.error('WebSocket error:', error);
try {
const ws = new WebSocket(url.toString());
wsRef.current = ws;
const isCurrent = () => !disposed && wsRef.current === ws;
ws.onopen = () => {
if (!isCurrent()) {
return;
}
setIsConnected(true);
pingTimer = setInterval(() => {
if (isCurrent() && ws.readyState === WebSocket.OPEN) {
ws.send(JSON.stringify({ type: 'ping' }));
}
}, 30000);
};
ws.onmessage = event => {
if (!isCurrent()) {
return;
}
try {
const message: WebSocketMessage = JSON.parse(event.data);
if (message.runId && message.runId !== runId) {
return;
}
setLastMessage(message);
callbacksRef.current.onMessage?.(message);
switch (message.type) {
case 'progress':
if (message.data) {
callbacksRef.current.onProgress?.(
message.data.progress ?? 0,
message.data.currentDate
);
}
break;
case 'error':
if (message.data?.error) {
callbacksRef.current.onError?.(message.data.error);
}
break;
case 'completed':
callbacksRef.current.onCompleted?.(message.data?.results);
break;
}
} catch (error) {
browserLog.error('Error parsing WebSocket message:', error);
}
};
ws.onerror = () => {
if (isCurrent()) {
setIsConnected(false);
}
};
ws.onclose = () => {
if (!isCurrent()) {
return;
}
wsRef.current = null;
setIsConnected(false);
clearInterval(pingTimer);
// Check ownership before clearing the reference, not after.
retry();
};
} catch (error) {
browserLog.error('Error creating WebSocket:', error);
setIsConnected(false);
};
retry();
}
};
ws.onclose = () => {
browserLog.log('WebSocket disconnected');
setIsConnected(false);
wsRef.current = null;
// Clear ping interval
if (pingIntervalRef.current) {
clearInterval(pingIntervalRef.current);
pingIntervalRef.current = null;
}
// Attempt to reconnect after 3 seconds
// Only reconnect if not intentionally disconnected and still the same WebSocket
if (runId && wsRef.current === ws && !isIntentionalDisconnect.current) {
reconnectTimeoutRef.current = setTimeout(() => {
browserLog.log('Attempting to reconnect...');
connect();
}, 3000);
}
};
} catch (error) {
browserLog.error('Error creating WebSocket:', error);
setIsConnected(false);
}
}, [runId, onMessage, onProgress, onError, onCompleted]);
const disconnect = useCallback(() => {
browserLog.log('Disconnecting WebSocket...');
// Set flag to prevent automatic reconnection
isIntentionalDisconnect.current = true;
if (reconnectTimeoutRef.current) {
clearTimeout(reconnectTimeoutRef.current);
reconnectTimeoutRef.current = null;
}
if (pingIntervalRef.current) {
clearInterval(pingIntervalRef.current);
pingIntervalRef.current = null;
}
if (wsRef.current) {
// Set a flag to prevent reconnection
const close = () => {
clearTimeout(reconnectTimer);
clearInterval(pingTimer);
const ws = wsRef.current;
wsRef.current = null;
ws.close();
}
setIsConnected(false);
}, []);
if (ws) {
ws.onopen = null;
ws.onmessage = null;
ws.onerror = null;
ws.onclose = null;
ws.close();
}
};
connectRef.current = () => {
disposed = false;
connect();
};
disconnectRef.current = () => {
disposed = true;
close();
setIsConnected(false);
};
connect();
return () => {
disposed = true;
close();
connectRef.current = () => {};
disconnectRef.current = () => {};
};
}, [runId]);
const connect = useCallback(() => connectRef.current(), []);
const disconnect = useCallback(() => disconnectRef.current(), []);
const sendMessage = useCallback((message: unknown) => {
if (wsRef.current?.readyState === WebSocket.OPEN) {
wsRef.current.send(JSON.stringify(message));
} else {
browserLog.warn('WebSocket is not connected');
}
}, []);
useEffect(() => {
// Small delay to prevent rapid reconnections during React's render cycles
const timeoutId = setTimeout(() => {
if (runId) {
connect();
} else {
disconnect();
}
}, 100);
return () => {
clearTimeout(timeoutId);
disconnect();
};
}, [runId]); // Only depend on runId, not the functions
return {
isConnected,
lastMessage,
sendMessage,
disconnect,
connect,
};
return { isConnected, lastMessage, sendMessage, disconnect, connect };
}