Only allow primitive JSON for transfer between worker and main worker (#128)
[poolifier.git] / src / pools / cluster / dynamic.ts
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'
5
6 /**
7 * A cluster pool with a min/max number of workers, is possible to execute tasks in sync or async mode as you prefer.
8 *
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.
11 *
12 * @author [Christopher Quadflieg](https://github.com/Shinigami92)
13 * @since 2.0.0
14 */
15 export class DynamicClusterPool<
16 Data extends JSONValue = JSONValue,
17 Response extends JSONValue = JSONValue
18 > extends FixedClusterPool<Data, Response> {
19 /**
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 }`
24 */
25 public constructor (
26 min: number,
27 public readonly max: number,
28 filename: string,
29 opts: ClusterPoolOptions = { maxTasks: 1000 }
30 ) {
31 super(min, filename, opts)
32 }
33
34 protected chooseWorker (): Worker {
35 let worker: Worker | undefined
36 for (const entry of this.tasks) {
37 if (entry[1] === 0) {
38 worker = entry[0]
39 break
40 }
41 }
42
43 if (worker) {
44 // a worker is free, use it
45 return worker
46 } else {
47 if (this.workers.length === this.max) {
48 this.emitter.emit('FullPool')
49 return super.chooseWorker()
50 }
51 // all workers are busy create a new worker
52 const worker = this.internalNewWorker()
53 worker.on('message', (message: MessageValue<Data>) => {
54 if (message.kill) {
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)
61 }
62 })
63 return worker
64 }
65 }
66 }