Files
image-workbench-desktop/src/generation-scheduler.js
T

120 lines
4.9 KiB
JavaScript

;(function (global) {
'use strict'
function createScheduler(options) {
const opt = options || {}
const limit = Math.max(1, Number(opt.concurrency) || 1)
const queue = []
let active = 0
let closed = false
const acquire = () => new Promise((resolve, reject) => {
if (closed) return reject(new Error('调度器已关闭'))
const grant = () => {
if (closed) return reject(new Error('调度器已关闭'))
active++
let released = false
resolve(() => {
if (released) return
released = true
active--
// 队列里存的是 { grant, reject } 对象,必须调用它的 grant。
// (此处曾误把对象当函数直接调用:release 抛 TypeError,且排队中的 acquire()
// 既不 resolve 也不 reject,会永久挂起并把队列项吞掉。)
const next = queue.shift()
if (next && typeof next.grant === 'function') next.grant()
})
}
if (active < limit) grant()
else queue.push({ grant, reject })
})
return {
acquire,
close() {
closed = true
const error = new Error('调度器已关闭')
while (queue.length) {
const item = queue.shift()
if (item && typeof item.reject === 'function') item.reject(error)
}
},
stats() { return { active, queued: queue.length, limit } },
}
}
function run(jobs, options) {
const list = Array.isArray(jobs) ? jobs : []
const opt = options || {}
const concurrency = Math.max(1, Number(opt.concurrency) || 1)
const signal = opt.signal
// 可选兜底:单个 job 超过 jobTimeoutMs 仍未 settle 就按失败处理,保证整批一定收场。
// 正常路径下不会触发(请求内部已有更早的硬超时),纯属「任何代码路径卡死都不会拖住整批」的保险。
const jobTimeoutMs = Math.max(0, Number(opt.jobTimeoutMs) || 0)
// 定时器来源与 runtime-fetch 同一约定:优先注入,其次全局;环境没有定时器时退化为「不做兜底」(保持原语义)
const timerSet = opt.setTimeout || (typeof setTimeout === 'function' ? setTimeout : null)
const timerClear = opt.clearTimeout || (typeof clearTimeout === 'function' ? clearTimeout : null)
const withTimeout = (promise, job) => {
if (!jobTimeoutMs || typeof timerSet !== 'function') return promise
return new Promise((resolve, reject) => {
const timer = timerSet(() => {
const error = new Error('任务超时未返回(结果未知)')
error.name = 'TimeoutError'
error.iwbType = 'timeout'
error.jobTimeout = true
error.job = job
reject(error)
}, jobTimeoutMs)
Promise.resolve(promise).then(
(value) => { if (typeof timerClear === 'function') timerClear(timer); resolve(value) },
(error) => { if (typeof timerClear === 'function') timerClear(timer); reject(error) },
)
})
}
const results = new Array(list.length)
let cursor = 0
let completed = 0
let cancelled = false
let completionCalled = false
const cancelledError = () => { const error = new Error('任务已取消'); error.name = 'AbortError'; return error }
const complete = async (summary) => {
if (completionCalled) return summary
completionCalled = true
if (opt.onComplete) {
try { await opt.onComplete(summary) } catch (e) { /* 完成回调不能改变任务结果 */ }
}
return summary
}
const worker = async () => {
while (true) {
if (signal && signal.aborted) { cancelled = true; throw cancelledError() }
const index = cursor++
if (index >= list.length) return
const job = list[index]
if (opt.onStart) opt.onStart(job, index)
try {
const value = await withTimeout(opt.executeJob(job, index), job)
results[index] = { ok: true, value, job }
completed++
if (opt.onItemDone) await opt.onItemDone(value, job, index, completed, list.length)
} catch (error) {
results[index] = { ok: false, error, job }
if (opt.onItemError) await opt.onItemError(error, job, index, completed, list.length)
if (opt.stopOnError) throw error
}
}
}
const count = Math.min(concurrency, Math.max(1, list.length))
return Promise.all(Array.from({ length: count }, () => worker())).then(() => {
if (signal && signal.aborted) cancelled = true
const summary = { results, completed, total: list.length, cancelled }
return complete(summary)
}).catch(async (error) => {
if (error && error.name === 'AbortError') cancelled = true
const summary = { results, completed, total: list.length, cancelled, error }
await complete(summary)
throw error
})
}
global.IWBGenerationScheduler = { createScheduler, run }
})(typeof window !== 'undefined' ? window : globalThis)