Encapsulate logic of cluster and thread worker/pool (#116)
[poolifier.git] / src / pools / cluster / dynamic.ts
index d4bf30f39b3a58f7572064ca9627f434a6a77308..f2375a02d6e1babf875d27b40f01782849828af0 100644 (file)
@@ -1,11 +1,8 @@
-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.
  *
@@ -21,8 +18,6 @@ export class DynamicClusterPool<
   // 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
@@ -30,18 +25,16 @@ export class DynamicClusterPool<
    * @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]
@@ -58,11 +51,11 @@ export class DynamicClusterPool<
         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)