fix: refine type definition for transferList
[poolifier.git] / src / pools / abstract-pool.ts
index cd1d364d21c15db6cb9b5fae1e6af8e0029b2510..01e621c297a1bc0cb818b807d1e13fe33344952e 100644 (file)
@@ -117,6 +117,10 @@ export abstract class AbstractPool<
    * Whether the pool is destroying or not.
    */
   private destroying: boolean
+  /**
+   * Whether the minimum number of workers is starting or not.
+   */
+  private startingMinimumNumberOfWorkers: boolean
   /**
    * Whether the pool ready event has been emitted or not.
    */
@@ -175,6 +179,7 @@ export abstract class AbstractPool<
     this.starting = false
     this.destroying = false
     this.readyEventEmitted = false
+    this.startingMinimumNumberOfWorkers = false
     if (this.opts.startWorkers === true) {
       this.start()
     }
@@ -888,7 +893,7 @@ export abstract class AbstractPool<
   public async execute (
     data?: Data,
     name?: string,
-    transferList?: TransferListItem[]
+    transferList?: readonly TransferListItem[]
   ): Promise<Response> {
     return await new Promise<Response>((resolve, reject) => {
       if (!this.started) {
@@ -949,6 +954,23 @@ export abstract class AbstractPool<
     })
   }
 
+  /**
+   * Starts the minimum number of workers.
+   */
+  private startMinimumNumberOfWorkers (): void {
+    this.startingMinimumNumberOfWorkers = true
+    while (
+      this.workerNodes.reduce(
+        (accumulator, workerNode) =>
+          !workerNode.info.dynamic ? accumulator + 1 : accumulator,
+        0
+      ) < this.minimumNumberOfWorkers
+    ) {
+      this.createAndSetupWorkerNode()
+    }
+    this.startingMinimumNumberOfWorkers = false
+  }
+
   /** @inheritdoc */
   public start (): void {
     if (this.started) {
@@ -961,15 +983,7 @@ export abstract class AbstractPool<
       throw new Error('Cannot start a destroying pool')
     }
     this.starting = true
-    while (
-      this.workerNodes.reduce(
-        (accumulator, workerNode) =>
-          !workerNode.info.dynamic ? accumulator + 1 : accumulator,
-        0
-      ) < this.minimumNumberOfWorkers
-    ) {
-      this.createAndSetupWorkerNode()
-    }
+    this.startMinimumNumberOfWorkers()
     this.starting = false
     this.started = true
   }
@@ -1056,7 +1070,9 @@ export abstract class AbstractPool<
   }
 
   /**
-   * Should return whether the worker is the main worker or not.
+   * Returns whether the worker is the main worker or not.
+   *
+   * @returns `true` if the worker is the main worker, `false` otherwise.
    */
   protected abstract isMain (): boolean
 
@@ -1212,7 +1228,7 @@ export abstract class AbstractPool<
   protected abstract sendToWorker (
     workerNodeKey: number,
     message: MessageValue<Data>,
-    transferList?: TransferListItem[]
+    transferList?: readonly TransferListItem[]
   ): void
 
   /**
@@ -1234,7 +1250,7 @@ export abstract class AbstractPool<
       'error',
       this.opts.errorHandler ?? EMPTY_FUNCTION
     )
-    workerNode.registerWorkerEventHandler('error', (error: Error) => {
+    workerNode.registerOnceWorkerEventHandler('error', (error: Error) => {
       workerNode.info.ready = false
       this.emitter?.emit(PoolEvents.error, error)
       if (
@@ -1244,8 +1260,8 @@ export abstract class AbstractPool<
       ) {
         if (workerNode.info.dynamic) {
           this.createAndSetupDynamicWorkerNode()
-        } else {
-          this.createAndSetupWorkerNode()
+        } else if (!this.startingMinimumNumberOfWorkers) {
+          this.startMinimumNumberOfWorkers()
         }
       }
       if (
@@ -1256,7 +1272,7 @@ export abstract class AbstractPool<
         this.redistributeQueuedTasks(this.workerNodes.indexOf(workerNode))
       }
       // eslint-disable-next-line @typescript-eslint/no-unnecessary-condition
-      workerNode?.terminate().catch(error => {
+      workerNode?.terminate().catch((error: unknown) => {
         this.emitter?.emit(PoolEvents.error, error)
       })
     })
@@ -1266,6 +1282,13 @@ export abstract class AbstractPool<
     )
     workerNode.registerOnceWorkerEventHandler('exit', () => {
       this.removeWorkerNode(workerNode)
+      if (
+        this.started &&
+        !this.startingMinimumNumberOfWorkers &&
+        !this.destroying
+      ) {
+        this.startMinimumNumberOfWorkers()
+      }
     })
     const workerNodeKey = this.addWorkerNode(workerNode)
     this.afterWorkerNodeSetup(workerNodeKey)
@@ -1297,7 +1320,7 @@ export abstract class AbstractPool<
       ) {
         // Flag the worker node as not ready immediately
         this.flagWorkerNodeAsNotReady(localWorkerNodeKey)
-        this.destroyWorkerNode(localWorkerNodeKey).catch(error => {
+        this.destroyWorkerNode(localWorkerNodeKey).catch((error: unknown) => {
           this.emitter?.emit(PoolEvents.error, error)
         })
       }
@@ -1311,7 +1334,7 @@ export abstract class AbstractPool<
           taskFunctionOperation: 'add',
           taskFunctionName,
           taskFunction: taskFunction.toString()
-        }).catch(error => {
+        }).catch((error: unknown) => {
           this.emitter?.emit(PoolEvents.error, error)
         })
       }
@@ -1613,7 +1636,7 @@ export abstract class AbstractPool<
         this.handleWorkerNodeIdleEvent(eventDetail, stolenTask)
         return undefined
       })
-      .catch(error => {
+      .catch((error: unknown) => {
         this.emitter?.emit(PoolEvents.error, error)
       })
   }