/** * Similar ASIN force 请求节流守卫(Task 85)。 * * 原实现只要 pendingFileTaskIds 非空,每轮轮询都以 force=true 请求批量 * 进度,可能反复触发后端重复生成文件。本守卫为每个 taskId 维护一个 TTL * 窗口:窗口内 shouldForce 返回 false(不重复发 force 请求),到期后 * 允许重试(文件生成可能仍在进行,但后端可再次确认);任务终态后调用 * clear 立即释放记录,窗口表不会无界增长。 * * 纯 TS 无副作用模块:markForce 对非法 taskId fail-fast 抛错,读取路径 * (shouldForce/isThrottled/clear/stats)对非法 id 宽容;时钟抛错时 * 读取失败但记录不丢失,恢复后可继续工作。 */ export interface AsinForceThrottleOptions { /** force 请求的冷却窗口(毫秒),必须为正数 */ ttlMs: number /** 时钟来源;默认 Date.now(),测试可注入虚拟时钟 */ now?: () => number } export interface AsinForceThrottleStats { /** 已执行的 force 标记次数 */ forcedCount: number /** 被节流跳过的 force 请求次数 */ skippedCount: number /** 当前处于冷却窗口内的 taskId 数 */ activeCount: number } export function createAsinForceThrottle(options: AsinForceThrottleOptions) { const ttlMs = options.ttlMs const now = options.now ?? Date.now if (!(ttlMs > 0)) { throw new Error('ttlMs 必须为正数: ' + ttlMs) } const cooldowns = new Map() let forcedCount = 0 let skippedCount = 0 function validateTaskId(taskId: number): boolean { return Number.isFinite(taskId) && taskId > 0 && Number.isInteger(taskId) } function isThrottled(taskId: number): boolean { if (!validateTaskId(taskId)) return false const at = now() const until = cooldowns.get(taskId) if (until == null) return false if (at >= until) { cooldowns.delete(taskId) return false } return true } function shouldForce(taskId: number): boolean { if (!validateTaskId(taskId)) return false if (isThrottled(taskId)) { skippedCount += 1 return false } return true } function markForce(taskId: number) { if (!validateTaskId(taskId)) { throw new Error('taskId 必须是正整数: ' + taskId) } if (isThrottled(taskId)) return cooldowns.set(taskId, now() + ttlMs) forcedCount += 1 } function clear(taskId: number): boolean { if (!validateTaskId(taskId)) return false return cooldowns.delete(taskId) } function clearAll() { cooldowns.clear() } function stats(): AsinForceThrottleStats { const at = now() for (const [taskId, until] of cooldowns) { if (at >= until) cooldowns.delete(taskId) } return { forcedCount, skippedCount, activeCount: cooldowns.size, } } return { get activeCount() { stats() return cooldowns.size }, shouldForce, markForce, isThrottled, clear, clearAll, stats, } } export type AsinForceThrottle = ReturnType