update at 2026-02-08 18:28:39
This commit is contained in:
93
miniprogram/utils/mp/worker-manager.js
Normal file
93
miniprogram/utils/mp/worker-manager.js
Normal file
@@ -0,0 +1,93 @@
|
||||
let singleton = null
|
||||
|
||||
class SvgWorkerManager {
|
||||
constructor() {
|
||||
this.worker = wx.createWorker('workers/svg-generator/index.js')
|
||||
this.pending = new Map()
|
||||
this.timeoutMs = 30000
|
||||
|
||||
this.worker.onMessage((message) => {
|
||||
const { requestId, success, data, error } = message || {}
|
||||
const pendingTask = this.pending.get(requestId)
|
||||
if (!pendingTask) {
|
||||
return
|
||||
}
|
||||
|
||||
clearTimeout(pendingTask.timer)
|
||||
this.pending.delete(requestId)
|
||||
|
||||
if (success) {
|
||||
pendingTask.resolve(data)
|
||||
} else {
|
||||
pendingTask.reject(new Error(error || 'Worker 执行失败'))
|
||||
}
|
||||
})
|
||||
|
||||
this.worker.onError((error) => {
|
||||
this.rejectAll(error)
|
||||
})
|
||||
|
||||
if (typeof this.worker.onProcessKilled === 'function') {
|
||||
this.worker.onProcessKilled(() => {
|
||||
this.rejectAll(new Error('Worker 进程被系统回收'))
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
rejectAll(error) {
|
||||
for (const [requestId, pendingTask] of this.pending.entries()) {
|
||||
clearTimeout(pendingTask.timer)
|
||||
pendingTask.reject(error)
|
||||
this.pending.delete(requestId)
|
||||
}
|
||||
}
|
||||
|
||||
request(type, payload, timeoutMs) {
|
||||
const requestId = `${Date.now()}-${Math.random().toString(16).slice(2)}`
|
||||
return new Promise((resolve, reject) => {
|
||||
const timer = setTimeout(() => {
|
||||
this.pending.delete(requestId)
|
||||
reject(new Error(`Worker 超时: ${type}`))
|
||||
}, timeoutMs || this.timeoutMs)
|
||||
|
||||
this.pending.set(requestId, { resolve, reject, timer })
|
||||
|
||||
this.worker.postMessage({
|
||||
requestId,
|
||||
type,
|
||||
payload,
|
||||
})
|
||||
})
|
||||
}
|
||||
|
||||
loadFont(fontId, fontBuffer) {
|
||||
return this.request('load-font', {
|
||||
fontId,
|
||||
fontBuffer,
|
||||
}, 45000)
|
||||
}
|
||||
|
||||
generateSvg(params) {
|
||||
return this.request('generate-svg', params, 45000)
|
||||
}
|
||||
|
||||
clearCache() {
|
||||
return this.request('clear-cache', {})
|
||||
}
|
||||
|
||||
terminate() {
|
||||
this.rejectAll(new Error('Worker 已终止'))
|
||||
this.worker.terminate()
|
||||
}
|
||||
}
|
||||
|
||||
function getSvgWorkerManager() {
|
||||
if (!singleton) {
|
||||
singleton = new SvgWorkerManager()
|
||||
}
|
||||
return singleton
|
||||
}
|
||||
|
||||
module.exports = {
|
||||
getSvgWorkerManager,
|
||||
}
|
||||
Reference in New Issue
Block a user