-import { EventEmitter } from 'events'
-import type { FixedClusterPoolOptions, WorkerWithMessageChannel } from './fixed'
+import type { Worker } from 'cluster'
+import type { MessageValue } from '../../utility-types'
+import type { ClusterPoolOptions } from './fixed'
import { FixedClusterPool } from './fixed'
-class MyEmitter extends EventEmitter {}
-
-export type DynamicClusterPoolOptions = FixedClusterPoolOptions
-
/**
* A cluster pool with a min/max number of workers, is possible to execute tasks in sync or async mode as you prefer.
*
// eslint-disable-next-line @typescript-eslint/no-explicit-any
Response = any
> extends FixedClusterPool<Data, Response> {
- public readonly emitter: MyEmitter
-
/**
* @param min Min number of workers that will be always active
* @param max Max number of workers that will be active
* @param opts An object with possible options for example `errorHandler`, `onlineHandler`. Default: `{ maxTasks: 1000 }`
*/
public constructor (
- public readonly min: number,
+ min: number,
public readonly max: number,
- public readonly filename: string,
- public readonly opts: DynamicClusterPoolOptions = { maxTasks: 1000 }
+ filename: string,
+ opts: ClusterPoolOptions = { maxTasks: 1000 }
) {
super(min, filename, opts)
-
- this.emitter = new MyEmitter()
}
- protected chooseWorker (): WorkerWithMessageChannel {
- let worker: WorkerWithMessageChannel | undefined
+ protected chooseWorker (): Worker {
+ let worker: Worker | undefined
for (const entry of this.tasks) {
if (entry[1] === 0) {
worker = entry[0]
return super.chooseWorker()
}
// all workers are busy create a new worker
- const worker = this.newWorker()
- worker.on('message', (message: { kill?: number }) => {
+ const worker = this.internalNewWorker()
+ worker.on('message', (message: MessageValue<Data>) => {
if (message.kill) {
- worker.send({ kill: 1 })
- worker.kill()
+ this.sendToWorker(worker, { kill: 1 })
+ void this.destroyWorker(worker)
// clean workers from data structures
const workerIndex = this.workers.indexOf(worker)
this.workers.splice(workerIndex, 1)