2021-11-11 13:11:09 +01:00
|
|
|
const workerFarm = require("worker-farm")
|
2021-11-11 17:20:30 +01:00
|
|
|
const env = require("../environment")
|
2021-11-11 13:11:09 +01:00
|
|
|
|
|
|
|
const ThreadType = {
|
|
|
|
QUERY: "query",
|
|
|
|
AUTOMATION: "automation",
|
|
|
|
}
|
|
|
|
|
|
|
|
function typeToFile(type) {
|
|
|
|
let filename = null
|
|
|
|
switch (type) {
|
|
|
|
case ThreadType.QUERY:
|
|
|
|
filename = "./query"
|
|
|
|
break
|
|
|
|
case ThreadType.AUTOMATION:
|
|
|
|
filename = "./automation"
|
|
|
|
break
|
|
|
|
default:
|
|
|
|
throw "Unknown thread type"
|
|
|
|
}
|
|
|
|
return require.resolve(filename)
|
|
|
|
}
|
|
|
|
|
|
|
|
class Thread {
|
|
|
|
constructor(type, opts = { timeoutMs: null, count: 1 }) {
|
2021-11-11 17:20:30 +01:00
|
|
|
this.type = type
|
2021-11-22 18:42:41 +01:00
|
|
|
this.count = opts.count ? opts.count : 1
|
|
|
|
this.disableThreading =
|
|
|
|
env.isTest() ||
|
|
|
|
env.DISABLE_THREADING ||
|
|
|
|
this.count === 0 ||
|
|
|
|
env.isInThread()
|
|
|
|
if (!this.disableThreading) {
|
2021-11-11 17:20:30 +01:00
|
|
|
const workerOpts = {
|
|
|
|
autoStart: true,
|
2021-11-22 18:42:41 +01:00
|
|
|
maxConcurrentWorkers: this.count,
|
2021-11-11 17:20:30 +01:00
|
|
|
}
|
|
|
|
if (opts.timeoutMs) {
|
|
|
|
workerOpts.maxCallTime = opts.timeoutMs
|
|
|
|
}
|
|
|
|
this.workers = workerFarm(workerOpts, typeToFile(type))
|
2021-11-11 13:11:09 +01:00
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
run(data) {
|
|
|
|
return new Promise((resolve, reject) => {
|
2021-11-11 17:20:30 +01:00
|
|
|
let fncToCall
|
|
|
|
// if in test then don't use threading
|
2021-11-22 18:42:41 +01:00
|
|
|
if (this.disableThreading) {
|
2021-11-11 17:20:30 +01:00
|
|
|
fncToCall = require(typeToFile(this.type))
|
|
|
|
} else {
|
|
|
|
fncToCall = this.workers
|
|
|
|
}
|
|
|
|
fncToCall(data, (err, response) => {
|
2021-11-11 13:11:09 +01:00
|
|
|
if (err) {
|
|
|
|
reject(err)
|
|
|
|
} else {
|
|
|
|
resolve(response)
|
|
|
|
}
|
|
|
|
})
|
|
|
|
})
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
module.exports.Thread = Thread
|
|
|
|
module.exports.ThreadType = ThreadType
|