import { getModuleProgressLight, type ProgressLightModule } from './progress-light.ts' /** * 轮询用进度适配器(2026-09 全维度审查 F5)。 * * 后端 12 个模块都提供了 /tasks/progress/light 轻量端点(只回 status/fileReady 等白名单字段), * 但此前全站仍在轮询 /tasks/progress/batch(回全量任务详情)。等待任务终态的紧循环 * (每几秒一次)只需要 status,用轻量端点可显著减小响应体。 * * 安全前提(务必确认后再接入): * 1. 调用方只用 task.id / task.status / missingTaskIds(轻量白名单覆盖的字段); * 2. 调用方把结果**部分合并**到已有完整快照上(`{...prev.task, ...detail.task}`), * 这样缺失字段由旧快照兜底,不会把页面数据抹空。 * * 不满足上述前提的路径(如历史列表合并、首屏加载)请继续用重型 batch 端点。 */ export interface LightPollingItem { task?: { id?: number status?: string | null statusCode?: string | null fileStatus?: string | null fileError?: string | null fileReady?: boolean | null updatedAt?: string | null } } export function toBatchItems(lightItems: unknown[]): LightPollingItem[] { const items: LightPollingItem[] = [] for (const raw of lightItems || []) { const item = raw as { taskId?: number; status?: string | null; statusCode?: string | null fileStatus?: string | null; fileError?: string | null; fileReady?: boolean | null updatedAt?: string | null } | null if (!item || typeof item.taskId !== 'number' || item.taskId <= 0) { continue } // 归一为重型端点的嵌套形状(各模块 batch 项都是 { task: {...} }), // 保证调用方的 detail.task?.xxx 读取与部分合并逻辑不变 items.push({ task: { id: item.taskId, status: item.status ?? null, statusCode: item.statusCode ?? null, fileStatus: item.fileStatus ?? null, fileError: item.fileError ?? null, fileReady: item.fileReady ?? null, updatedAt: item.updatedAt ?? null, }, }) } return items } /** * 各模块 batch 返回类型形状不同(`missingTaskIds` 可选/必填、明细类型各异), * 这里按"带 items 与 missingTaskIds 的批次对象"约束,避免为每个模块写一份适配器。 */ export interface PollingBatchLike { items?: T[] missingTaskIds?: number[] } export interface PollingProgressOptions { /** 重型端点兜底(轻量端点异常或返回空时调用),不传则不兜底 */ fallback?: () => Promise } /** * 纯函数:把轻量响应判定为可用的策略结果。 * 既没有可用条目也没有 missing 列表时返回 null(调用方据此走重型兜底, * 避免后端未上线该模块 light 路由时页面静默拿不到状态)。 */ export function pickPollingBatch( lightItems: unknown[] | null | undefined, missingTaskIds: number[] | null | undefined, ): PollingBatchLike | null { const items = toBatchItems(lightItems || []) const missing = missingTaskIds || [] if (!items.length && !missing.length) { return null } return { items: items as unknown as T[], missingTaskIds: missing } } /** * 取任务进度:轻量端点优先,异常/空结果时回退重型端点。 * 轻量端点返回 empty(既没有 items 也没有 missingTaskIds)时也走兜底—— * 避免后端未上线该模块的 light 路由时页面静默拿不到状态。 */ export async function getPollingProgressBatch>( module: ProgressLightModule, taskIds: number[], options: PollingProgressOptions = {}, ): Promise { const fallback = options.fallback try { const light = await getModuleProgressLight(module, taskIds) const picked = pickPollingBatch(light.items, light.missingTaskIds) if (picked) { return picked as TBatch } } catch { // 落回重型端点(下面统一处理) } if (fallback) { return fallback() } return { items: [], missingTaskIds: [] } as unknown as TBatch }