25306d34215b396bb5f06e2ab740dd11c9379dd3
1 import type { Worker
} from
'cluster'
2 import type { JSONValue
, 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 Data
extends JSONValue
= JSONValue
,
17 Response
extends JSONValue
= JSONValue
18 > extends FixedClusterPool
<Data
, Response
> {
20 * @param min Min number of workers that will be always active
21 * @param max Max number of workers that will be active
22 * @param filename A file path with implementation of `ClusterWorker` class, relative path is fine.
23 * @param opts An object with possible options for example `errorHandler`, `onlineHandler`. Default: `{ maxTasks: 1000 }`
27 public readonly max
: number,
29 opts
: ClusterPoolOptions
= { maxTasks
: 1000 }
31 super(min
, filename
, opts
)
34 protected chooseWorker (): Worker
{
35 let worker
: Worker
| undefined
36 for (const entry
of this.tasks
) {
44 // a worker is free, use it
47 if (this.workers
.length
=== this.max
) {
48 this.emitter
.emit('FullPool')
49 return super.chooseWorker()
51 // all workers are busy create a new worker
52 const worker
= this.internalNewWorker()
53 worker
.on('message', (message
: MessageValue
<Data
>) => {
55 this.sendToWorker(worker
, { kill
: 1 })
56 void this.destroyWorker(worker
)
57 // clean workers from data structures
58 const workerIndex
= this.workers
.indexOf(worker
)
59 this.workers
.splice(workerIndex
, 1)
60 this.tasks
.delete(worker
)