fix: check pool statuses
[poolifier.git] / src / pools / abstract-pool.ts
index 604c7af8ad32dde3959dcb75166427458999c9f7..5392914d002060b9734ea35eae0d0931f67f5f17 100644 (file)
@@ -113,6 +113,10 @@ export abstract class AbstractPool<
    * Whether the pool is starting or not.
    */
   private starting: boolean
+  /**
+   * Whether the pool is destroying or not.
+   */
+  private destroying: boolean
   /**
    * The start timestamp of the pool.
    */
@@ -162,6 +166,7 @@ export abstract class AbstractPool<
 
     this.started = false
     this.starting = false
+    this.destroying = false
     if (this.opts.startWorkers === true) {
       this.start()
     }
@@ -886,6 +891,10 @@ export abstract class AbstractPool<
         reject(new Error('Cannot execute a task on not started pool'))
         return
       }
+      if (this.destroying) {
+        reject(new Error('Cannot execute a task on destroying pool'))
+        return
+      }
       if (name != null && typeof name !== 'string') {
         reject(new TypeError('name argument must be a string'))
         return
@@ -931,6 +940,15 @@ export abstract class AbstractPool<
 
   /** @inheritdoc */
   public start (): void {
+    if (this.started) {
+      throw new Error('Cannot start an already started pool')
+    }
+    if (this.starting) {
+      throw new Error('Cannot start an already starting pool')
+    }
+    if (this.destroying) {
+      throw new Error('Cannot start a destroying pool')
+    }
     this.starting = true
     while (
       this.workerNodes.reduce(
@@ -947,6 +965,16 @@ export abstract class AbstractPool<
 
   /** @inheritDoc */
   public async destroy (): Promise<void> {
+    if (!this.started) {
+      throw new Error('Cannot destroy an already destroyed pool')
+    }
+    if (this.starting) {
+      throw new Error('Cannot destroy an starting pool')
+    }
+    if (this.destroying) {
+      throw new Error('Cannot destroy an already destroying pool')
+    }
+    this.destroying = true
     await Promise.all(
       this.workerNodes.map(async (_, workerNodeKey) => {
         await this.destroyWorkerNode(workerNodeKey)
@@ -954,6 +982,7 @@ export abstract class AbstractPool<
     )
     this.emitter?.emit(PoolEvents.destroy, this.info)
     this.emitter?.emitDestroy()
+    this.destroying = false
     this.started = false
   }
 
@@ -1228,6 +1257,7 @@ export abstract class AbstractPool<
       if (
         this.started &&
         !this.starting &&
+        !this.destroying &&
         this.opts.restartWorkerOnError === true
       ) {
         if (workerInfo.dynamic) {
@@ -1236,7 +1266,11 @@ export abstract class AbstractPool<
           this.createAndSetupWorkerNode()
         }
       }
-      if (this.started && this.opts.enableTasksQueue === true) {
+      if (
+        this.started &&
+        !this.destroying &&
+        this.opts.enableTasksQueue === true
+      ) {
         this.redistributeQueuedTasks(workerNodeKey)
       }
     })