Files
crawler-plugin/frontend-vue/src/shared/api/task-progress-polling.ts
T
huangzd1997 1d2cae2af6 前端(任务卡进度条): 10 页接上实时进度,3 页没分母的显式写 null
后端已把心跳里的 current/total 透到 progress/light,但 TaskItemView.progress 是可空字段:
页面少写一行不会报错也不会红,界面上就是安静地没有进度条——11 类客户端任务里 7 类正是这样。

- 新增 src/shared/api/task-progress-live.ts:进度走独立通道,模块级缓存 + 60s 新鲜窗口
  为什么不并进任务对象:各页 {...prev.task, ...detail.task} 合并里有 5 处带「变更签名」守卫
  (rowsVersion|status|fileStatus|fileReady)。进度每轮都在动,而签名在「正在翻页、还没攒够一批
  回传」的时段不变——照那条路走,进度条会一路停在上一次回传的数字上,看着像卡死
- 写入点挂在 light 出口(progress-light.ts)而不是聚合层:4 个页面直接调 getModuleProgressLight
  不经过 getPollingProgressBatch,挂聚合层它们永远拿不到;命中缓存也要刷一遍读数,
  否则进度会在缓存窗口里被自己的新鲜判定踢掉、凭空消失
- toBatchItems 与 LightPollingItem 补三字段:这里的键集是逐字段挑的,少挑一个就把后端给的数丢掉
- 10 页接 liveProgress:解决风控、跟价、定时匹配、状态查询、提款、巡店删除、商品管理采集等
- Convert/Dedupe/Split 三页写死 progress: null 并说明原因:它们卡列的是完成记录、没有可数的分母。
  显式 null 与省略字段在代码里必须长得不一样,否则下一个人无法区分「没得画」和「忘了接」
- 新增 tests/task-progress-view-wiring.test.ts:适配器清单由文件系统给出、总数硬钉 16,
  判据同时认 `progress:` 与 ES6 简写 `progress,`(只认冒号把 BrandBrandTab 误报成缺口,
  而误报的尺子会被人当噪音绕过去);变异自证三处全 KILLED——抽掉跟价页的接线、
  摘掉批次白名单的 progressTotal、去掉分母塌 0 时的旧读数清理,还原后字节哈希一致
- tests/task-progress-polling.test.ts 的整份形状断言同步加三字段(它本来就该在我改白名单时红)
2026-10-10 21:00:01 +08:00

212 lines
8.6 KiB
TypeScript
Raw Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
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(轻量白名单覆盖的字段);
* createdAt/finishedAt 不在白名单内——展示这两个时间的页面必须用历史项字段兜底
* (后端 /history 由任务实体填充,见各模块 buildHistoryItemVo),否则任务卡片恒显 "-";
* 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
progressCurrent?: number | null
progressTotal?: number | null
progressLabel?: 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; progressCurrent?: number | null; progressTotal?: number | null
progressLabel?: 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,
progressCurrent: item.progressCurrent ?? null,
progressTotal: item.progressTotal ?? null,
progressLabel: item.progressLabel ?? null,
},
})
}
return items
}
/**
* 各模块 batch 返回类型形状不同(`missingTaskIds` 可选/必填、明细类型各异),
* 这里按"带 items 与 missingTaskIds 的批次对象"约束,避免为每个模块写一份适配器。
*/
export interface PollingBatchLike<T> {
items?: T[]
missingTaskIds?: number[]
}
/**
* 行数据按需拉取(审查 F5 后续):
* 轻量响应里的 rowsVersion 是该任务**结果行**的版本(最后变更时间毫秒 + 行数,后端一次 GROUP BY 查出)。
* 版本没变说明行数据没动过,就不必再拉带行明细的重型 batch。
*
* 变更信号是**复合**的:行版本之外还看 status / fileStatus / fileReady——任务收尾时常见
* 「行已经写完、之后任务才置成功」或「结果文件才就绪」,只看行版本会把界面卡在旧状态。
*
* 安全兜底(保证零回归):
* - 四项信号全空(老后端 / 字段缺失)→ 视为拿不到信号,该任务照旧每轮拉取;
* - 轻量请求本身失败时调用方回退为全量拉取(见各页 catch 分支)。
*/
export interface TaskProgressChangeSignal {
taskId?: number
rowsVersion?: string | null
status?: string | null
fileStatus?: string | null
fileReady?: boolean | null
}
/** 组装变更信号;taskId 非法或四项信号全空时返回 null(= 拿不到信号,必须拉取)。 */
function changeSignatureOf(raw: unknown): { taskId: number; signature: string } | null {
const item = raw as TaskProgressChangeSignal | null
if (!item || typeof item.taskId !== 'number' || !(item.taskId > 0)) return null
const rowsVersion = typeof item.rowsVersion === 'string' ? item.rowsVersion : ''
const status = typeof item.status === 'string' ? item.status : ''
const fileStatus = typeof item.fileStatus === 'string' ? item.fileStatus : ''
const fileReady = item.fileReady === true ? '1' : item.fileReady === false ? '0' : ''
if (!rowsVersion && !status && !fileStatus && !fileReady) return null
return { taskId: item.taskId, signature: [rowsVersion, status, fileStatus, fileReady].join('|') }
}
export function createRowsVersionTracker() {
const seen = new Map<number, string>()
return {
/**
* 返回"需要拉取行明细"的任务 id(信号变化 / 拿不到信号的)。
* 同时记录本轮看到的信号(便于下轮比较)。
*/
selectTasksNeedingRows(items: unknown[] | null | undefined, requestedIds: number[]): number[] {
const signatureById = new Map<number, string>()
for (const raw of items || []) {
const parsed = changeSignatureOf(raw)
if (parsed) signatureById.set(parsed.taskId, parsed.signature)
}
const needRows: number[] = []
for (const taskId of requestedIds) {
const signature = signatureById.get(taskId)
if (signature === undefined) {
needRows.push(taskId)
continue
}
if (seen.get(taskId) !== signature) {
needRows.push(taskId)
}
}
for (const [taskId, signature] of signatureById) {
seen.set(taskId, signature)
}
return needRows
},
/** 任务结束/被删除时清掉记录,避免 Map 无界增长。 */
forget(taskId: number): void {
seen.delete(taskId)
},
reset(): void {
seen.clear()
},
}
}
export interface PollingProgressOptions<TBatch> {
/** 重型端点兜底(轻量端点异常或返回空时调用),不传则不兜底 */
fallback?: () => Promise<TBatch>
}
/**
* 纯函数:把轻量响应判定为可用的策略结果。
* 既没有可用条目也没有 missing 列表时返回 null(调用方据此走重型兜底,
* 避免后端未上线该模块 light 路由时页面静默拿不到状态)。
*/
export function pickPollingBatch<T>(
lightItems: unknown[] | null | undefined,
missingTaskIds: number[] | null | undefined,
): PollingBatchLike<T> | null {
const items = toBatchItems(lightItems || [])
const missing = missingTaskIds || []
if (!items.length && !missing.length) {
return null
}
return { items: items as unknown as T[], missingTaskIds: missing }
}
/**
* light 是否把**全部**请求任务都判成"不存在"。
*
* <p>整体性结论风险最大:消费方把 missing 当"任务已消失"(跟价页直接返回 FAILED)。
* 2026-09-14 线上即出现过 light 因后端漏选过滤字段而恒判 missing,故这种结论要用重型端点复核。
*/
export function lightClaimsAllTasksMissing(
picked: PollingBatchLike<unknown> | null | undefined,
requestedIds: number[],
): boolean {
const ids = (requestedIds || []).filter((id) => typeof id === 'number' && id > 0)
if (!ids.length) return false
if ((picked?.items || []).length) return false
const missing = picked?.missingTaskIds || []
return ids.every((id) => missing.includes(id))
}
/**
* 取任务进度:轻量端点优先,异常/空结果时回退重型端点。
* 轻量端点返回 empty(既没有 items 也没有 missingTaskIds)时也走兜底——
* 避免后端未上线该模块的 light 路由时页面静默拿不到状态。
*/
export async function getPollingProgressBatch<TBatch extends PollingBatchLike<unknown>>(
module: ProgressLightModule,
taskIds: number[],
options: PollingProgressOptions<TBatch> = {},
): Promise<TBatch> {
const fallback = options.fallback
try {
const light = await getModuleProgressLight(module, taskIds)
const picked = pickPollingBatch<unknown>(light.items, light.missingTaskIds)
if (picked) {
if (fallback && lightClaimsAllTasksMissing(picked, taskIds)) {
// 复核:以重型端点为准(它若也判不存在,结论一致;若返回了条目,说明 light 错了)
return fallback()
}
return picked as TBatch
}
} catch {
// 落回重型端点(下面统一处理)
}
if (fallback) {
return fallback()
}
return { items: [], missingTaskIds: [] } as unknown as TBatch
}