refactor: share research domain and simplify application workflows
This commit is contained in:
parent
805a9f8fd4
commit
8c39ccf7ea
58 changed files with 3805 additions and 3081 deletions
|
|
@ -0,0 +1,250 @@
|
|||
import {
|
||||
useCallback,
|
||||
useRef,
|
||||
useState,
|
||||
type Dispatch,
|
||||
type MutableRefObject,
|
||||
type SetStateAction,
|
||||
} from 'react';
|
||||
import {
|
||||
backtestApiV2,
|
||||
RunResultsUnavailableError,
|
||||
type ResearchRunResult,
|
||||
type Run,
|
||||
} from '../services/backtestApiV2';
|
||||
|
||||
/** Object identity is the ownership token for one status/result request chain. */
|
||||
export interface RunSelection {
|
||||
id: string;
|
||||
backtestId: string | null;
|
||||
controller: AbortController;
|
||||
timer?: ReturnType<typeof setTimeout>;
|
||||
request?: Promise<void>;
|
||||
refreshRequested: boolean;
|
||||
results: ResearchRunResult | null;
|
||||
}
|
||||
|
||||
const isActive = (run: Run) => ['pending', 'running', 'paused'].includes(run.status);
|
||||
export const messageOf = (error: unknown, fallback: string) =>
|
||||
error instanceof Error ? error.message : fallback;
|
||||
|
||||
/** One selection owns status, results, polling, refresh and cancellation. */
|
||||
export function useRunMonitoring({
|
||||
mounted,
|
||||
loadedBacktestId,
|
||||
setRuns,
|
||||
}: {
|
||||
mounted: MutableRefObject<boolean>;
|
||||
loadedBacktestId: MutableRefObject<string | null>;
|
||||
setRuns: Dispatch<SetStateAction<Run[]>>;
|
||||
}) {
|
||||
const [currentRun, setCurrentRun] = useState<Run | null>(null);
|
||||
const [runResults, setRunResults] = useState<ResearchRunResult | null>(null);
|
||||
const [isRunLoading, setIsRunLoading] = useState(false);
|
||||
const [runError, setRunError] = useState<string | null>(null);
|
||||
const [cancelRequested, setCancelRequested] = useState(false);
|
||||
const selectionGeneration = useRef(0);
|
||||
const selection = useRef<RunSelection | null>(null);
|
||||
const cancellation = useRef<RunSelection | null>(null);
|
||||
const isSelected = useCallback(
|
||||
(selected: RunSelection) =>
|
||||
mounted.current &&
|
||||
selection.current === selected &&
|
||||
selected.backtestId === loadedBacktestId.current,
|
||||
[]
|
||||
);
|
||||
|
||||
/** Stop browser observation only; cancelling server execution is cancelRun's job. */
|
||||
const stopMonitoring = useCallback(() => {
|
||||
selectionGeneration.current++;
|
||||
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;
|
||||
}
|
||||
if (
|
||||
run.id !== selected.id ||
|
||||
(selected.backtestId !== null && run.backtestId !== selected.backtestId)
|
||||
) {
|
||||
monitorAgain = false;
|
||||
selected.refreshRequested = false;
|
||||
selected.results = null;
|
||||
setCurrentRun(null);
|
||||
setRunResults(null);
|
||||
throw new Error('Received a run for a different backtest or run selection');
|
||||
}
|
||||
|
||||
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 || results.backtestId !== run.backtestId)
|
||||
) {
|
||||
selected.refreshRequested = false;
|
||||
throw new Error('Received results for a different backtest or 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]
|
||||
);
|
||||
|
||||
/** Reopening a run reads its recorded state; it never submits another backtest. */
|
||||
const selectRun = useCallback(
|
||||
(runId: string | undefined) => {
|
||||
if (
|
||||
runId &&
|
||||
selection.current?.id === runId &&
|
||||
selection.current.backtestId === loadedBacktestId.current
|
||||
) {
|
||||
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,
|
||||
backtestId: loadedBacktestId.current,
|
||||
controller: new AbortController(),
|
||||
refreshRequested: false,
|
||||
results: null,
|
||||
};
|
||||
selection.current = selected;
|
||||
return refreshSelection(selected);
|
||||
},
|
||||
[refreshSelection, stopMonitoring]
|
||||
);
|
||||
|
||||
/** Record a cancellation request, then monitor until the server reports a terminal state. */
|
||||
const cancelRun = useCallback(async () => {
|
||||
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(selected.id, selected.controller.signal);
|
||||
if (isSelected(selected)) {
|
||||
await refreshSelection(selected);
|
||||
}
|
||||
} catch (err) {
|
||||
if (isSelected(selected)) {
|
||||
cancellation.current = null;
|
||||
setCancelRequested(Boolean(currentRun.cancelRequested));
|
||||
setRunError(messageOf(err, 'Failed to request cancellation'));
|
||||
}
|
||||
}
|
||||
}, [currentRun, isSelected, refreshSelection]);
|
||||
|
||||
return {
|
||||
currentRun,
|
||||
runResults,
|
||||
isRunLoading,
|
||||
runError,
|
||||
cancelRequested,
|
||||
selection,
|
||||
selectionGeneration,
|
||||
stopMonitoring,
|
||||
refreshRun,
|
||||
selectRun,
|
||||
cancelRun,
|
||||
};
|
||||
}
|
||||
Loading…
Add table
Add a link
Reference in a new issue