- /**
- * Choose a worker for the next task.
- *
- * It will first check for and return an idle worker.
- * If all workers are busy, then it will try to create a new one up to the `max` worker count.
- * If the max worker count is reached, the emitter will emit a `FullPool` event and it will fall back to using a round robin algorithm to distribute the load.
- *
- * @returns Cluster worker.
- */
- protected chooseWorker (): Worker {
- for (const [worker, numberOfTasks] of this.tasks) {
- if (numberOfTasks === 0) {
- // A worker is free, use it
- return worker
- }
- }
-
- if (this.workers.length === this.max) {
- this.emitter.emit('FullPool')
- return super.chooseWorker()
- }
-
- // All workers are busy, create a new worker
- const worker = this.createAndSetupWorker()
- this.registerWorkerMessageListener<Data>(worker, message => {
- const tasksInProgress = this.tasks.get(worker)
- if (message.kill && tasksInProgress === 0) {
- // Kill received from the worker, means that no new tasks are submitted to that worker for a while ( > maxInactiveTime)
- // To handle the case of a long-running task we will check if there is any active task
- this.sendToWorker(worker, { kill: 1 })
- void this.destroyWorker(worker)
- }
- })
- return worker