/** 异步 Job 研究执行(Phase 4):POST /api/jobs 提交 → 轮询 GET /api/jobs/{id}。 * * 大样本研究(全市场)可能耗时数十秒到分钟级,经异步 Job 后台执行, * 避免 HTTP 长阻塞(AGENT §19)。页面提交后即时返回 job_id,再轮询到终态。 */ import { apiGet, apiPost } from "./api"; import type { ResearchSpec } from "./types"; export interface JobSubmit { job_id: string; status: string; } export interface JobStatusResp { job_id: string; status: string; /** 执行阶段(data_loading / backtesting / analysis…)—— 用于给用户真实进度而非假进度条 */ stage?: string | null; /** 归档后的实验 id(后端在 Job 完成时写入) */ experiment_id?: string | null; result?: unknown; error?: string | null; spec?: Record; started_at?: string | null; finished_at?: string | null; } export function submitJob(spec: ResearchSpec): Promise { return apiPost("/jobs", spec); } /** 任务终态(success / failed / cancelled / timeout)与结果 */ export interface JobOutcome { status: string; result: T | null; error?: string; /** 归档实验 id:结果出来后前端可直接给出「去对比」入口 */ experimentId?: string | null; } /** 轮询直到 success / failed / cancelled,或超时(默认 10 分钟)。 */ export async function waitJob( jobId: string, timeoutMs = 600_000, onStage?: (info: { stage: string; elapsedMs: number }) => void, ): Promise> { const deadline = Date.now() + timeoutMs; const t0 = Date.now(); while (Date.now() < deadline) { const job = await apiGet(`/jobs/${jobId}`); // 阶段来自后端真实执行状态,避免前端用假进度条假装在跑 if (onStage && job.stage) onStage({ stage: job.stage, elapsedMs: Date.now() - t0 }); if (job.status === "success") { return { status: job.status, result: (job.result as T) ?? null, experimentId: job.experiment_id ?? null, }; } if (job.status === "failed" || job.status === "cancelled") { return { status: job.status, result: null, error: job.error ?? undefined }; } await new Promise((resolve) => setTimeout(resolve, 1500)); } return { status: "timeout", result: null, error: "等待结果超时,请稍后在「实验」页查看归档" }; } /** 阶段中文名(后端 stage 枚举 → 用户可读) */ export const STAGE_LABEL: Record = { queued: "排队中", data_loading: "加载行情与因子数据", selection: "逐择股日选股", backtesting: "撮合与净值结算", analysis: "汇总指标与曲线", done: "完成", }; /** 提交一个回测组合为异步 Job(POST /api/combos/run,不保存组合)。 */ export async function submitComboJob(combo: unknown): Promise { return apiPost("/combos/run", combo); } /** * 运行**已保存**的回测组合(POST /api/combos/{id}/run)。 * * 与 submitComboJob 的区别:这里用库里的那份参数,页面上未保存的改动不参与 —— * 「从组合库直接运行」必须跑库里存的那套,否则用户改了一半的表单会污染既有组合的结果。 */ export async function runSavedCombo(comboId: string): Promise { return apiPost(`/combos/${encodeURIComponent(comboId)}/run`, {}); }