2023-10-11 01:43:58 +08:00
|
|
|
import {Worker} from 'worker_threads';
|
|
|
|
import {fileURLToPath} from 'url';
|
|
|
|
import path from 'path';
|
2022-11-12 00:51:30 +08:00
|
|
|
|
|
|
|
const WorkerTypes = Object.freeze({
|
|
|
|
Collector: 'collector',
|
|
|
|
Process: 'process',
|
|
|
|
Notifier: 'notifier',
|
|
|
|
});
|
|
|
|
|
|
|
|
const kickOffWorker = (workerType, workerData) => {
|
|
|
|
return new Promise((resolve, reject) => {
|
2023-10-11 01:43:58 +08:00
|
|
|
const __filename = fileURLToPath(import.meta.url);
|
|
|
|
const __dirname = path.dirname(__filename);
|
|
|
|
const workerPath = path.join(
|
|
|
|
__dirname,
|
|
|
|
'..',
|
|
|
|
'..',
|
|
|
|
'workers',
|
|
|
|
`${workerType}.js`);
|
2022-11-12 00:51:30 +08:00
|
|
|
const worker = new Worker(workerPath, {workerData});
|
|
|
|
worker.on('message', resolve);
|
|
|
|
worker.on('error', reject);
|
|
|
|
worker.on('exit', (code) => {
|
|
|
|
if (code !== 0) {
|
2023-10-11 01:43:58 +08:00
|
|
|
reject(
|
|
|
|
new Error(`Worker '${workerType}' stopped with exit code ${code}`));
|
2022-11-12 00:51:30 +08:00
|
|
|
}
|
|
|
|
});
|
|
|
|
});
|
|
|
|
};
|
|
|
|
|
2023-10-11 01:43:58 +08:00
|
|
|
export default class WorkerStarter {
|
2022-11-12 00:51:30 +08:00
|
|
|
constructor(workerData) {
|
|
|
|
this.workerData = workerData;
|
|
|
|
}
|
|
|
|
|
|
|
|
collect = () => kickOffWorker(WorkerTypes.Collector, this.workerData);
|
|
|
|
process = () => kickOffWorker(WorkerTypes.Process, this.workerData);
|
|
|
|
notify = () => kickOffWorker(WorkerTypes.Notifier, this.workerData);
|
|
|
|
};
|