fix(web): make backtest run controls and selection reliable
This commit is contained in:
parent
3d26da07f5
commit
67f12b49a0
8 changed files with 1109 additions and 675 deletions
|
|
@ -1,413 +1,362 @@
|
|||
import { useCallback, useEffect, useRef, useState } from 'react';
|
||||
import { defined } from '@stock-bot/invariants';
|
||||
import { browserLog } from '@/utils/browserLog';
|
||||
import { backtestApiV2 } from '../services/backtestApiV2';
|
||||
import { backtestApiV2, RunResultsUnavailableError } from '../services/backtestApiV2';
|
||||
import type { Backtest, CreateBacktestRequest, Run, RunResult } from '../services/backtestApiV2';
|
||||
|
||||
interface UseBacktestV2Return {
|
||||
// State
|
||||
backtest: Backtest | null;
|
||||
runs: Run[];
|
||||
currentRun: Run | null;
|
||||
runResults: RunResult | null;
|
||||
isLoading: boolean;
|
||||
error: string | null;
|
||||
|
||||
// Actions
|
||||
loadBacktest: (id: string) => Promise<void>;
|
||||
createBacktest: (request: CreateBacktestRequest) => Promise<Backtest>;
|
||||
updateBacktest: (id: string, updates: Partial<CreateBacktestRequest>) => Promise<void>;
|
||||
deleteBacktest: (id: string) => Promise<void>;
|
||||
|
||||
createRun: (speedMultiplier?: number | null) => Promise<Run | undefined>;
|
||||
pauseRun: () => Promise<void>;
|
||||
resumeRun: () => Promise<void>;
|
||||
cancelRun: () => Promise<void>;
|
||||
updateRunSpeed: (speedMultiplier: number | null) => Promise<void>;
|
||||
selectRun: (runId: string | undefined) => Promise<void>;
|
||||
interface RunSelection {
|
||||
id: string;
|
||||
controller: AbortController;
|
||||
timer?: ReturnType<typeof setTimeout>;
|
||||
request?: Promise<void>;
|
||||
refreshRequested: boolean;
|
||||
results: RunResult | null;
|
||||
}
|
||||
|
||||
export function useBacktestV2(): UseBacktestV2Return {
|
||||
const isActive = (run: Run) => ['pending', 'running', 'paused'].includes(run.status);
|
||||
const messageOf = (error: unknown, fallback: string) =>
|
||||
error instanceof Error ? error.message : fallback;
|
||||
|
||||
export function useBacktestV2() {
|
||||
const [backtest, setBacktest] = useState<Backtest | null>(null);
|
||||
const [runs, setRuns] = useState<Run[]>([]);
|
||||
const [currentRun, setCurrentRun] = useState<Run | null>(null);
|
||||
const [runResults, setRunResults] = useState<RunResult | null>(null);
|
||||
const [isLoading, setIsLoading] = useState(false);
|
||||
const [isBacktestLoading, setIsBacktestLoading] = useState(false);
|
||||
const [isRunLoading, setIsRunLoading] = useState(false);
|
||||
const [error, setError] = useState<string | null>(null);
|
||||
const [runError, setRunError] = useState<string | null>(null);
|
||||
const [cancelRequested, setCancelRequested] = useState(false);
|
||||
const mounted = useRef(true);
|
||||
const backtestGeneration = useRef(0);
|
||||
const selection = useRef<RunSelection | null>(null);
|
||||
const cancellation = useRef<RunSelection | null>(null);
|
||||
|
||||
const pollingIntervalRef = useRef<NodeJS.Timeout | null>(null);
|
||||
const isSelected = useCallback(
|
||||
(selected: RunSelection) => mounted.current && selection.current === selected,
|
||||
[]
|
||||
);
|
||||
|
||||
const stopMonitoring = useCallback(() => {
|
||||
const selected = selection.current;
|
||||
selection.current = null;
|
||||
cancellation.current = null;
|
||||
if (selected) {
|
||||
clearTimeout(selected.timer);
|
||||
selected.controller.abort();
|
||||
}
|
||||
}, []);
|
||||
|
||||
// A selection owns one request chain (status, then results) and one timer.
|
||||
// Polls, websocket invalidations and cancel acknowledgements all use this path.
|
||||
const refreshSelection = useCallback(
|
||||
function refresh(selected: RunSelection): Promise<void> {
|
||||
if (!isSelected(selected)) {
|
||||
return Promise.resolve();
|
||||
}
|
||||
if (selected.request) {
|
||||
selected.refreshRequested = true;
|
||||
return selected.request;
|
||||
}
|
||||
clearTimeout(selected.timer);
|
||||
let monitorAgain = true;
|
||||
selected.request = (async () => {
|
||||
try {
|
||||
const run = await backtestApiV2.getRun(selected.id, selected.controller.signal);
|
||||
if (!isSelected(selected)) {
|
||||
return;
|
||||
}
|
||||
|
||||
setCurrentRun(run);
|
||||
setRuns(previous =>
|
||||
previous.some(item => item.id === run.id)
|
||||
? previous.map(item => (item.id === run.id ? run : item))
|
||||
: [run, ...previous]
|
||||
);
|
||||
setRunError(null);
|
||||
monitorAgain = isActive(run);
|
||||
if (!monitorAgain) {
|
||||
cancellation.current = null;
|
||||
setCancelRequested(false);
|
||||
} else if (run.cancelRequested) {
|
||||
setCancelRequested(true);
|
||||
}
|
||||
|
||||
if (run.status === 'completed') {
|
||||
if (!selected.results) {
|
||||
const results = await backtestApiV2.getRunResults(
|
||||
selected.id,
|
||||
selected.controller.signal
|
||||
);
|
||||
if (!isSelected(selected)) {
|
||||
return;
|
||||
}
|
||||
if (results && results.runId !== selected.id) {
|
||||
throw new Error('Received results for a different run');
|
||||
}
|
||||
selected.results = results;
|
||||
setRunResults(results);
|
||||
}
|
||||
} else {
|
||||
selected.results = null;
|
||||
setRunResults(null);
|
||||
}
|
||||
} catch (err) {
|
||||
if (!isSelected(selected)) {
|
||||
return;
|
||||
}
|
||||
setRunError(
|
||||
err instanceof RunResultsUnavailableError
|
||||
? null
|
||||
: messageOf(err, 'Failed to refresh run')
|
||||
);
|
||||
} finally {
|
||||
if (isSelected(selected)) {
|
||||
selected.request = undefined;
|
||||
setIsRunLoading(false);
|
||||
if (selected.refreshRequested) {
|
||||
selected.refreshRequested = false;
|
||||
void refresh(selected);
|
||||
} else if (monitorAgain) {
|
||||
selected.timer = setTimeout(() => void refresh(selected), 1000);
|
||||
}
|
||||
}
|
||||
}
|
||||
})();
|
||||
return selected.request;
|
||||
},
|
||||
[isSelected]
|
||||
);
|
||||
|
||||
const refreshRun = useCallback(
|
||||
(runId?: string) => {
|
||||
const selected = selection.current;
|
||||
return selected && (!runId || selected.id === runId)
|
||||
? refreshSelection(selected)
|
||||
: Promise.resolve();
|
||||
},
|
||||
[refreshSelection]
|
||||
);
|
||||
|
||||
const selectRun = useCallback(
|
||||
(runId: string | undefined) => {
|
||||
if (runId && selection.current?.id === runId) {
|
||||
return refreshSelection(selection.current);
|
||||
}
|
||||
stopMonitoring();
|
||||
setCurrentRun(null);
|
||||
setRunResults(null);
|
||||
setRunError(null);
|
||||
setCancelRequested(false);
|
||||
setIsRunLoading(Boolean(runId));
|
||||
if (!runId) {
|
||||
return Promise.resolve();
|
||||
}
|
||||
|
||||
const selected: RunSelection = {
|
||||
id: runId,
|
||||
controller: new AbortController(),
|
||||
refreshRequested: false,
|
||||
results: null,
|
||||
};
|
||||
selection.current = selected;
|
||||
return refreshSelection(selected);
|
||||
},
|
||||
[refreshSelection, stopMonitoring]
|
||||
);
|
||||
|
||||
// Load a specific backtest and its runs
|
||||
const loadBacktest = useCallback(async (id: string) => {
|
||||
setIsLoading(true);
|
||||
const generation = ++backtestGeneration.current;
|
||||
setIsBacktestLoading(true);
|
||||
setError(null);
|
||||
|
||||
setBacktest(null);
|
||||
setRuns([]);
|
||||
try {
|
||||
const [loadedBacktest, loadedRuns] = await Promise.all([
|
||||
backtestApiV2.getBacktest(id),
|
||||
backtestApiV2.listRuns(id),
|
||||
]);
|
||||
|
||||
if (!mounted.current || generation !== backtestGeneration.current) {
|
||||
return;
|
||||
}
|
||||
setBacktest(loadedBacktest);
|
||||
setRuns(loadedRuns);
|
||||
|
||||
// Don't auto-select runs here - let the URL parameter drive the selection
|
||||
// Run polling may already have a newer version of the selected row.
|
||||
setRuns(previous =>
|
||||
loadedRuns.map(run =>
|
||||
run.id === selection.current?.id
|
||||
? (previous.find(item => item.id === run.id) ?? run)
|
||||
: run
|
||||
)
|
||||
);
|
||||
} catch (err) {
|
||||
browserLog.error('Failed to load backtest:', err);
|
||||
setError(err instanceof Error ? err.message : 'Failed to load backtest');
|
||||
if (mounted.current && generation === backtestGeneration.current) {
|
||||
setError(messageOf(err, 'Failed to load backtest'));
|
||||
}
|
||||
} finally {
|
||||
setIsLoading(false);
|
||||
if (mounted.current && generation === backtestGeneration.current) {
|
||||
setIsBacktestLoading(false);
|
||||
}
|
||||
}
|
||||
}, []);
|
||||
|
||||
// Create a new backtest
|
||||
const createBacktest = useCallback(async (request: CreateBacktestRequest): Promise<Backtest> => {
|
||||
setIsLoading(true);
|
||||
setError(null);
|
||||
|
||||
try {
|
||||
const newBacktest = await backtestApiV2.createBacktest(request);
|
||||
setBacktest(newBacktest);
|
||||
setRuns([]);
|
||||
setCurrentRun(null);
|
||||
setRunResults(null);
|
||||
return newBacktest;
|
||||
} catch (err) {
|
||||
setError(err instanceof Error ? err.message : 'Failed to create backtest');
|
||||
throw err;
|
||||
} finally {
|
||||
setIsLoading(false);
|
||||
}
|
||||
}, []);
|
||||
|
||||
// Update backtest configuration
|
||||
const updateBacktest = useCallback(
|
||||
async (id: string, updates: Partial<CreateBacktestRequest>) => {
|
||||
setIsLoading(true);
|
||||
const createBacktest = useCallback(
|
||||
async (request: CreateBacktestRequest) => {
|
||||
const generation = ++backtestGeneration.current;
|
||||
setIsBacktestLoading(true);
|
||||
setError(null);
|
||||
|
||||
try {
|
||||
const updatedBacktest = await backtestApiV2.updateBacktest(id, updates);
|
||||
setBacktest(updatedBacktest);
|
||||
const created = await backtestApiV2.createBacktest(request);
|
||||
if (mounted.current && generation === backtestGeneration.current) {
|
||||
setBacktest(created);
|
||||
setRuns([]);
|
||||
await selectRun(undefined);
|
||||
}
|
||||
return created;
|
||||
} catch (err) {
|
||||
setError(err instanceof Error ? err.message : 'Failed to update backtest');
|
||||
if (mounted.current && generation === backtestGeneration.current) {
|
||||
setError(messageOf(err, 'Failed to create backtest'));
|
||||
}
|
||||
throw err;
|
||||
} finally {
|
||||
setIsLoading(false);
|
||||
if (mounted.current && generation === backtestGeneration.current) {
|
||||
setIsBacktestLoading(false);
|
||||
}
|
||||
}
|
||||
},
|
||||
[selectRun]
|
||||
);
|
||||
|
||||
const updateBacktest = useCallback(
|
||||
async (id: string, updates: Partial<CreateBacktestRequest>) => {
|
||||
const generation = ++backtestGeneration.current;
|
||||
setIsBacktestLoading(true);
|
||||
setError(null);
|
||||
try {
|
||||
const updated = await backtestApiV2.updateBacktest(id, updates);
|
||||
if (mounted.current && generation === backtestGeneration.current) {
|
||||
setBacktest(updated);
|
||||
}
|
||||
} catch (err) {
|
||||
if (mounted.current && generation === backtestGeneration.current) {
|
||||
setError(messageOf(err, 'Failed to update backtest'));
|
||||
}
|
||||
throw err;
|
||||
} finally {
|
||||
if (mounted.current && generation === backtestGeneration.current) {
|
||||
setIsBacktestLoading(false);
|
||||
}
|
||||
}
|
||||
},
|
||||
[]
|
||||
);
|
||||
|
||||
// Delete backtest
|
||||
const deleteBacktest = useCallback(async (id: string) => {
|
||||
setIsLoading(true);
|
||||
setError(null);
|
||||
|
||||
try {
|
||||
await backtestApiV2.deleteBacktest(id);
|
||||
setBacktest(null);
|
||||
setRuns([]);
|
||||
setCurrentRun(null);
|
||||
setRunResults(null);
|
||||
} catch (err) {
|
||||
setError(err instanceof Error ? err.message : 'Failed to delete backtest');
|
||||
throw err;
|
||||
} finally {
|
||||
setIsLoading(false);
|
||||
}
|
||||
}, []);
|
||||
|
||||
// Create a new run
|
||||
const createRun = useCallback(
|
||||
async (speedMultiplier?: number | null) => {
|
||||
if (!backtest) {
|
||||
return;
|
||||
}
|
||||
|
||||
setIsLoading(true);
|
||||
const deleteBacktest = useCallback(
|
||||
async (id: string) => {
|
||||
const generation = ++backtestGeneration.current;
|
||||
setIsBacktestLoading(true);
|
||||
setError(null);
|
||||
setRunResults(null);
|
||||
|
||||
try {
|
||||
// Pass speedMultiplier as-is, null means max speed
|
||||
const newRun = await backtestApiV2.createRun(backtest.id, {
|
||||
speedMultiplier: speedMultiplier === undefined ? null : speedMultiplier,
|
||||
});
|
||||
|
||||
// Add to runs array first
|
||||
setRuns(prevRuns => [newRun, ...prevRuns]);
|
||||
|
||||
// Clear previous results immediately
|
||||
setRunResults(null);
|
||||
|
||||
// Set as current run
|
||||
setCurrentRun(newRun);
|
||||
|
||||
// Small delay to ensure the run is properly created in the database
|
||||
await new Promise(resolve => setTimeout(resolve, 100));
|
||||
|
||||
// Check if the run is completed (it might complete instantly)
|
||||
let finalRun = newRun;
|
||||
|
||||
// If status is pending, check again after a short delay
|
||||
if (newRun.status === 'pending') {
|
||||
await new Promise(resolve => setTimeout(resolve, 500));
|
||||
try {
|
||||
finalRun = await backtestApiV2.getRun(newRun.id);
|
||||
// Update the current run with the latest status
|
||||
setCurrentRun(finalRun);
|
||||
setRuns(prevRuns => prevRuns.map(r => (r.id === finalRun.id ? finalRun : r)));
|
||||
} catch (err) {
|
||||
browserLog.error('Failed to re-check run status:', err);
|
||||
}
|
||||
await backtestApiV2.deleteBacktest(id);
|
||||
if (mounted.current && generation === backtestGeneration.current) {
|
||||
setBacktest(null);
|
||||
setRuns([]);
|
||||
await selectRun(undefined);
|
||||
}
|
||||
|
||||
// If the run is completed, load results
|
||||
if (finalRun.status === 'completed') {
|
||||
try {
|
||||
const results = await backtestApiV2.getRunResults(finalRun.id);
|
||||
setRunResults(results);
|
||||
} catch (err) {
|
||||
browserLog.error('Failed to load new run results:', err);
|
||||
}
|
||||
} else {
|
||||
// Start monitoring the run
|
||||
startMonitoringRun(finalRun.id);
|
||||
}
|
||||
|
||||
return newRun; // Return the created run
|
||||
} catch (err) {
|
||||
setError(err instanceof Error ? err.message : 'Failed to create run');
|
||||
throw err; // Re-throw so caller knows it failed
|
||||
if (mounted.current && generation === backtestGeneration.current) {
|
||||
setError(messageOf(err, 'Failed to delete backtest'));
|
||||
}
|
||||
throw err;
|
||||
} finally {
|
||||
setIsLoading(false);
|
||||
if (mounted.current && generation === backtestGeneration.current) {
|
||||
setIsBacktestLoading(false);
|
||||
}
|
||||
}
|
||||
},
|
||||
[selectRun]
|
||||
);
|
||||
|
||||
const createRun = useCallback(
|
||||
async (speedMultiplier: number | null = null) => {
|
||||
if (!backtest) {
|
||||
return undefined;
|
||||
}
|
||||
const generation = backtestGeneration.current;
|
||||
const selected = selection.current;
|
||||
setIsBacktestLoading(true);
|
||||
setError(null);
|
||||
try {
|
||||
const created = await backtestApiV2.createRun(backtest.id, { speedMultiplier });
|
||||
if (!mounted.current || generation !== backtestGeneration.current) {
|
||||
return undefined;
|
||||
}
|
||||
setRuns(previous => [created, ...previous]);
|
||||
// The route owns selection. Never navigate away from a newer user selection.
|
||||
return selection.current === selected ? created : undefined;
|
||||
} catch (err) {
|
||||
if (mounted.current && generation === backtestGeneration.current) {
|
||||
setError(messageOf(err, 'Failed to create run'));
|
||||
}
|
||||
return undefined;
|
||||
} finally {
|
||||
if (mounted.current && generation === backtestGeneration.current) {
|
||||
setIsBacktestLoading(false);
|
||||
}
|
||||
}
|
||||
},
|
||||
[backtest]
|
||||
);
|
||||
|
||||
// Run control actions
|
||||
const pauseRun = useCallback(async () => {
|
||||
if (!currentRun || currentRun.status !== 'running') {
|
||||
return;
|
||||
}
|
||||
|
||||
try {
|
||||
await backtestApiV2.pauseRun(currentRun.id);
|
||||
setCurrentRun(prev => (prev ? { ...prev, status: 'paused' } : null));
|
||||
} catch (err) {
|
||||
setError(err instanceof Error ? err.message : 'Failed to pause run');
|
||||
}
|
||||
}, [currentRun]);
|
||||
|
||||
const resumeRun = useCallback(async () => {
|
||||
if (!currentRun || currentRun.status !== 'paused') {
|
||||
return;
|
||||
}
|
||||
|
||||
try {
|
||||
await backtestApiV2.resumeRun(currentRun.id);
|
||||
setCurrentRun(prev => (prev ? { ...prev, status: 'running' } : null));
|
||||
} catch (err) {
|
||||
setError(err instanceof Error ? err.message : 'Failed to resume run');
|
||||
}
|
||||
}, [currentRun]);
|
||||
|
||||
const cancelRun = useCallback(async () => {
|
||||
if (!currentRun || !['pending', 'running', 'paused'].includes(currentRun.status)) {
|
||||
const selected = selection.current;
|
||||
if (
|
||||
!selected ||
|
||||
!currentRun ||
|
||||
currentRun.id !== selected.id ||
|
||||
!isActive(currentRun) ||
|
||||
cancellation.current === selected
|
||||
) {
|
||||
return;
|
||||
}
|
||||
|
||||
cancellation.current = selected;
|
||||
setCancelRequested(true);
|
||||
setRunError(null);
|
||||
try {
|
||||
await backtestApiV2.cancelRun(currentRun.id);
|
||||
// Acceptance is not completion: keep monitoring the owner's persisted acknowledgement.
|
||||
const updated = await backtestApiV2.getRun(currentRun.id);
|
||||
setCurrentRun(updated);
|
||||
setRuns(prev => prev.map(run => (run.id === updated.id ? updated : run)));
|
||||
await backtestApiV2.cancelRun(selected.id, selected.controller.signal);
|
||||
if (isSelected(selected)) {
|
||||
await refreshSelection(selected);
|
||||
}
|
||||
} catch (err) {
|
||||
setError(err instanceof Error ? err.message : 'Failed to cancel run');
|
||||
if (isSelected(selected)) {
|
||||
cancellation.current = null;
|
||||
setCancelRequested(Boolean(currentRun.cancelRequested));
|
||||
setRunError(messageOf(err, 'Failed to request cancellation'));
|
||||
}
|
||||
}
|
||||
}, [currentRun]);
|
||||
}, [currentRun, isSelected, refreshSelection]);
|
||||
|
||||
const updateRunSpeed = useCallback(
|
||||
async (speedMultiplier: number | null) => {
|
||||
if (!currentRun) {
|
||||
return;
|
||||
}
|
||||
|
||||
try {
|
||||
// Keep null as null for max speed (no limit)
|
||||
const apiSpeed = speedMultiplier;
|
||||
|
||||
// Only call API if run is active
|
||||
if (currentRun.status === 'running' || currentRun.status === 'paused') {
|
||||
await backtestApiV2.updateRunSpeed(currentRun.id, apiSpeed);
|
||||
}
|
||||
|
||||
// Always update local state so UI reflects the selection
|
||||
setCurrentRun(prev => (prev ? { ...prev, speedMultiplier: apiSpeed } : null));
|
||||
} catch (err) {
|
||||
setError(err instanceof Error ? err.message : 'Failed to update run speed');
|
||||
}
|
||||
},
|
||||
[currentRun]
|
||||
);
|
||||
|
||||
// Select a specific run
|
||||
const selectRun = useCallback(
|
||||
async (runId: string | undefined) => {
|
||||
if (!runId) {
|
||||
setCurrentRun(null);
|
||||
setRunResults(null);
|
||||
stopMonitoringRun();
|
||||
return;
|
||||
}
|
||||
|
||||
let run = runs.find(r => r.id === runId);
|
||||
|
||||
// If run not found in list, try to fetch it directly
|
||||
if (!run) {
|
||||
let attempts = 0;
|
||||
const maxAttempts = 3;
|
||||
|
||||
while (attempts < maxAttempts) {
|
||||
try {
|
||||
run = await backtestApiV2.getRun(runId);
|
||||
|
||||
// Add to runs list if not present
|
||||
setRuns(prevRuns => {
|
||||
const exists = prevRuns.some(r => r.id === defined(run).id);
|
||||
if (!exists) {
|
||||
return [defined(run), ...prevRuns];
|
||||
}
|
||||
return prevRuns;
|
||||
});
|
||||
|
||||
break; // Success, exit loop
|
||||
} catch (err) {
|
||||
attempts++;
|
||||
if (attempts >= maxAttempts) {
|
||||
browserLog.error('Failed to fetch run after all attempts:', runId, err);
|
||||
setError(`Failed to load run ${runId}`);
|
||||
return;
|
||||
}
|
||||
// Wait before retrying
|
||||
await new Promise(resolve => setTimeout(resolve, 1000));
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
if (!run) {
|
||||
setError(`Run ${runId} not found`);
|
||||
return;
|
||||
}
|
||||
setCurrentRun(run);
|
||||
setRunResults(null);
|
||||
|
||||
if (run.status === 'completed') {
|
||||
try {
|
||||
const results = await backtestApiV2.getRunResults(run.id);
|
||||
setRunResults(results);
|
||||
} catch (err) {
|
||||
browserLog.error('Failed to load run results:', err);
|
||||
setError(err instanceof Error ? err.message : 'Failed to load run results');
|
||||
}
|
||||
} else if (run.status === 'running' || run.status === 'paused' || run.status === 'pending') {
|
||||
startMonitoringRun(run.id);
|
||||
} else {
|
||||
browserLog.warn('Run has unexpected status:', run.status);
|
||||
}
|
||||
},
|
||||
[runs]
|
||||
);
|
||||
|
||||
// Monitor run progress
|
||||
const startMonitoringRun = useCallback((runId: string) => {
|
||||
// Stop any existing monitoring
|
||||
stopMonitoringRun();
|
||||
|
||||
// For pending runs, we need to poll until they start or complete
|
||||
// We'll check the run status by fetching it
|
||||
pollingIntervalRef.current = setInterval(async () => {
|
||||
try {
|
||||
const updatedRun = await backtestApiV2.getRun(runId);
|
||||
// Update the run in state
|
||||
setCurrentRun(updatedRun);
|
||||
setRuns(prevRuns => prevRuns.map(r => (r.id === updatedRun.id ? updatedRun : r)));
|
||||
|
||||
// If run is no longer pending, handle the new status
|
||||
if (updatedRun.status === 'completed') {
|
||||
stopMonitoringRun();
|
||||
try {
|
||||
const results = await backtestApiV2.getRunResults(runId);
|
||||
setRunResults(results);
|
||||
} catch (err) {
|
||||
browserLog.error('Failed to load completed run results:', err);
|
||||
}
|
||||
} else if (updatedRun.status === 'failed' || updatedRun.status === 'cancelled') {
|
||||
stopMonitoringRun();
|
||||
}
|
||||
} catch (err) {
|
||||
browserLog.error('Failed to poll run status:', err);
|
||||
}
|
||||
}, 1000); // Poll every second
|
||||
}, []);
|
||||
|
||||
const _startPollingRun = (runId: string) => {
|
||||
pollingIntervalRef.current = setInterval(async () => {
|
||||
try {
|
||||
const updatedRun = await backtestApiV2.getRun(runId);
|
||||
handleRunUpdate(updatedRun);
|
||||
|
||||
if (updatedRun.status === 'completed') {
|
||||
const results = await backtestApiV2.getRunResults(runId);
|
||||
setRunResults(results);
|
||||
stopMonitoringRun();
|
||||
} else if (updatedRun.status === 'failed' || updatedRun.status === 'cancelled') {
|
||||
stopMonitoringRun();
|
||||
}
|
||||
} catch (err) {
|
||||
browserLog.error('Failed to poll run status:', err);
|
||||
}
|
||||
}, 1000); // Poll every second
|
||||
};
|
||||
|
||||
const stopMonitoringRun = () => {
|
||||
if (pollingIntervalRef.current) {
|
||||
clearInterval(pollingIntervalRef.current);
|
||||
pollingIntervalRef.current = null;
|
||||
}
|
||||
};
|
||||
|
||||
const handleRunUpdate = (update: Run) => {
|
||||
setCurrentRun(update);
|
||||
setRuns(prevRuns => prevRuns.map(run => (run.id === update.id ? update : run)));
|
||||
};
|
||||
|
||||
// Cleanup on unmount
|
||||
useEffect(() => {
|
||||
mounted.current = true;
|
||||
return () => {
|
||||
stopMonitoringRun();
|
||||
mounted.current = false;
|
||||
backtestGeneration.current++;
|
||||
stopMonitoring();
|
||||
};
|
||||
}, []);
|
||||
}, [stopMonitoring]);
|
||||
|
||||
return {
|
||||
backtest,
|
||||
runs,
|
||||
currentRun,
|
||||
runResults,
|
||||
isLoading,
|
||||
error,
|
||||
isLoading: isBacktestLoading || isRunLoading,
|
||||
error: runError ?? error,
|
||||
cancelRequested,
|
||||
loadBacktest,
|
||||
createBacktest,
|
||||
updateBacktest,
|
||||
deleteBacktest,
|
||||
createRun,
|
||||
pauseRun,
|
||||
resumeRun,
|
||||
cancelRun,
|
||||
updateRunSpeed,
|
||||
selectRun,
|
||||
refreshRun,
|
||||
};
|
||||
}
|
||||
|
|
|
|||
Loading…
Add table
Add a link
Reference in a new issue