refactor: cleanup handlers
[poolifier.git] / src / pools / abstract-pool.ts
index f922aff5b3bb801c0e8f864fb0b3c559d6702f62..06e69a6e3140da3092e75a6ff7040e201c70255c 100644 (file)
@@ -92,6 +92,10 @@ export abstract class AbstractPool<
    * The start timestamp of the pool.
    */
   private readonly startTimestamp
+  /**
+   * The task function names.
+   */
+  private taskFunctions!: string[]
 
   /**
    * Constructs a new poolifier pool.
@@ -642,6 +646,15 @@ export abstract class AbstractPool<
     }
   }
 
+  /** @inheritDoc */
+  public listTaskFunctions (): string[] {
+    if (this.taskFunctions != null) {
+      return this.taskFunctions
+    } else {
+      return []
+    }
+  }
+
   /** @inheritDoc */
   public async execute (
     data?: Data,
@@ -652,6 +665,22 @@ export abstract class AbstractPool<
       if (name != null && typeof name !== 'string') {
         reject(new TypeError('name argument must be a string'))
       }
+      if (
+        name != null &&
+        typeof name === 'string' &&
+        name.trim().length === 0
+      ) {
+        reject(new TypeError('name argument must not be an empty string'))
+      }
+      if (
+        name != null &&
+        this.taskFunctions != null &&
+        !this.taskFunctions.includes(name)
+      ) {
+        reject(
+          new Error(`Task function '${name}' is not registered in the pool`)
+        )
+      }
       if (transferList != null && !Array.isArray(transferList)) {
         reject(new TypeError('transferList argument must be an array'))
       }
@@ -692,6 +721,7 @@ export abstract class AbstractPool<
         await this.destroyWorkerNode(workerNodeKey)
       })
     )
+    this.emitter?.emit(PoolEvents.destroy)
   }
 
   protected async sendKillMessageToWorker (
@@ -903,6 +933,7 @@ export abstract class AbstractPool<
   protected createAndSetupWorkerNode (): number {
     const worker = this.createWorker()
 
+    worker.on('online', this.opts.onlineHandler ?? EMPTY_FUNCTION)
     worker.on('message', this.opts.messageHandler ?? EMPTY_FUNCTION)
     worker.on('error', this.opts.errorHandler ?? EMPTY_FUNCTION)
     worker.on('error', (error) => {
@@ -922,7 +953,6 @@ export abstract class AbstractPool<
         this.redistributeQueuedTasks(workerNodeKey)
       }
     })
-    worker.on('online', this.opts.onlineHandler ?? EMPTY_FUNCTION)
     worker.on('exit', this.opts.exitHandler ?? EMPTY_FUNCTION)
     worker.once('exit', () => {
       this.removeWorkerNode(worker)
@@ -1085,6 +1115,9 @@ export abstract class AbstractPool<
       } else if (message.taskId != null) {
         // Task execution response received from worker
         this.handleTaskExecutionResponse(message)
+      } else if (message.taskFunctions != null) {
+        // Task functions message received from worker
+        this.taskFunctions = message.taskFunctions
       }
     }
   }