1 import type { Worker
} from
'cluster'
2 import type { MessageValue
} from
'../../utility-types'
3 import type { ClusterPoolOptions
} from
'./fixed'
4 import { FixedClusterPool
} from
'./fixed'
7 * A cluster pool with a min/max number of workers, is possible to execute tasks in sync or async mode as you prefer.
9 * This cluster pool will create new workers when the other ones are busy, until the max number of workers,
10 * when the max number of workers is reached, an event will be emitted, if you want to listen this event use the emitter method.
12 * @author [Christopher Quadflieg](https://github.com/Shinigami92)
15 export class DynamicClusterPool
<
16 // eslint-disable-next-line @typescript-eslint/no-explicit-any
18 // eslint-disable-next-line @typescript-eslint/no-explicit-any
20 > extends FixedClusterPool
<Data
, Response
> {
22 * @param min Min number of workers that will be always active
23 * @param max Max number of workers that will be active
24 * @param filename A file path with implementation of `ClusterWorker` class, relative path is fine.
25 * @param opts An object with possible options for example `errorHandler`, `onlineHandler`. Default: `{ maxTasks: 1000 }`
29 public readonly max
: number,
31 opts
: ClusterPoolOptions
= { maxTasks
: 1000 }
33 super(min
, filename
, opts
)
36 protected chooseWorker (): Worker
{
37 let worker
: Worker
| undefined
38 for (const entry
of this.tasks
) {
46 // a worker is free, use it
49 if (this.workers
.length
=== this.max
) {
50 this.emitter
.emit('FullPool')
51 return super.chooseWorker()
53 // all workers are busy create a new worker
54 const worker
= this.internalNewWorker()
55 worker
.on('message', (message
: MessageValue
<Data
>) => {
57 this.sendToWorker(worker
, { kill
: 1 })
58 void this.destroyWorker(worker
)
59 // clean workers from data structures
60 const workerIndex
= this.workers
.indexOf(worker
)
61 this.workers
.splice(workerIndex
, 1)
62 this.tasks
.delete(worker
)