ddstats-server/libs/utils/multithread.js

84 lines
1.8 KiB
JavaScript
Raw Normal View History

import { randomUUID } from 'crypto'
2021-10-16 19:58:00 +02:00
import { SHARE_ENV, Worker } from 'worker_threads'
2021-10-16 19:11:16 +02:00
import initLog from './log.js'
const log = initLog("Worker Setup")
let workerFarm = []
let workerReady = []
2021-10-20 10:03:48 +02:00
let scheduledJobs = []
2021-10-20 10:03:48 +02:00
function scheduler() {
if (scheduledJobs.length === 0) return
const readyIndex = workerReady.indexOf(true)
if (readyIndex === -1) return
workerReady[readyIndex] = false
const worker = workerFarm[readyIndex]
const job = scheduledJobs.shift()
worker.postMessage({
type: 'runScript',
script: job.script,
data: job.data,
id: job.jobID
})
const messageHandler = message => {
if (message.id === job.jobID) {
workerReady[readyIndex] = true
worker.removeListener(
'message',
messageHandler
)
2021-10-20 10:03:48 +02:00
return job.callback(message.result)
}
2021-10-20 10:03:48 +02:00
}
worker.on(
'message',
messageHandler
)
}
export function initWorkers(threads) {
for (let i = 0; i < threads; ++i) {
2021-10-16 19:58:00 +02:00
workerFarm.push(new Worker('./libs/utils/multithread/genericWorker.js', { env: SHARE_ENV }))
const worker = workerFarm[i]
worker.postMessage({
2021-10-13 19:45:59 +02:00
type: 'initWorker',
name: `Worker ${parseInt(i) + 1}`
})
2021-10-20 10:03:48 +02:00
workerReady[i] = true
}
2021-10-16 19:11:16 +02:00
log(`Initialised ${threads} workers!`)
2021-10-20 10:03:48 +02:00
setInterval(
scheduler,
2021-10-30 19:19:58 +02:00
process.env.SCHEDULE_TIME ?? 50
2021-10-20 10:03:48 +02:00
)
log(`Initialised the scheduler!`)
}
2021-10-13 19:45:59 +02:00
export function spread(script, data) {
return new Promise(
async (resolve, reject) => {
const jobID = randomUUID()
2021-10-20 10:03:48 +02:00
scheduledJobs.push({
2021-10-13 19:45:59 +02:00
script,
data,
2021-10-20 10:03:48 +02:00
jobID,
callback: result => {
resolve(result)
}
2021-10-20 10:03:48 +02:00
})
2021-10-13 19:45:59 +02:00
}
)
}