fix: unregister worker callbacks after usage
[poolifier.git] / src / worker / abstract-worker.ts
index bd03d86e06eefee9871215a49aeb11343236be0d..b8e4b167602dd14306b595d0f1564b13009f636c 100644 (file)
@@ -18,10 +18,15 @@ import { KillBehaviors, type WorkerOptions } from './worker-options'
 import type {
   TaskAsyncFunction,
   TaskFunction,
-  TaskFunctionOperationReturnType,
+  TaskFunctionOperationResult,
   TaskFunctions,
   TaskSyncFunction
 } from './task-functions'
+import {
+  checkTaskFunctionName,
+  checkValidTaskFunctionEntry,
+  checkValidWorkerOptions
+} from './utils'
 
 const DEFAULT_MAX_INACTIVE_TIME = 60000
 const DEFAULT_WORKER_OPTIONS: WorkerOptions = {
@@ -95,63 +100,15 @@ export abstract class AbstractWorker<
     this.checkTaskFunctions(taskFunctions)
     this.checkWorkerOptions(this.opts)
     if (!this.isMain) {
-      this.getMainWorker().on('message', this.handleReadyMessage.bind(this))
+      this.getMainWorker().once('message', this.handleReadyMessage.bind(this))
     }
   }
 
   private checkWorkerOptions (opts: WorkerOptions): void {
-    if (opts != null && !isPlainObject(opts)) {
-      throw new TypeError('opts worker options parameter is not a plain object')
-    }
-    if (
-      opts?.killBehavior != null &&
-      !Object.values(KillBehaviors).includes(opts.killBehavior)
-    ) {
-      throw new TypeError(
-        `killBehavior option '${opts.killBehavior}' is not valid`
-      )
-    }
-    if (
-      opts?.maxInactiveTime != null &&
-      !Number.isSafeInteger(opts.maxInactiveTime)
-    ) {
-      throw new TypeError('maxInactiveTime option is not an integer')
-    }
-    if (opts?.maxInactiveTime != null && opts.maxInactiveTime < 5) {
-      throw new TypeError(
-        'maxInactiveTime option is not a positive integer greater or equal than 5'
-      )
-    }
-    if (opts?.killHandler != null && typeof opts.killHandler !== 'function') {
-      throw new TypeError('killHandler option is not a function')
-    }
-    if (opts?.async != null) {
-      throw new Error('async option is deprecated')
-    }
+    checkValidWorkerOptions(opts)
     this.opts = { ...DEFAULT_WORKER_OPTIONS, ...opts }
   }
 
-  private checkValidTaskFunctionEntry (
-    name: string,
-    fn: TaskFunction<Data, Response>
-  ): void {
-    if (typeof name !== 'string') {
-      throw new TypeError(
-        'A taskFunctions parameter object key is not a string'
-      )
-    }
-    if (typeof name === 'string' && name.trim().length === 0) {
-      throw new TypeError(
-        'A taskFunctions parameter object key is an empty string'
-      )
-    }
-    if (typeof fn !== 'function') {
-      throw new TypeError(
-        'A taskFunctions parameter object value is not a function'
-      )
-    }
-  }
-
   /**
    * Checks if the `taskFunctions` parameter is passed to the constructor and valid.
    *
@@ -177,7 +134,7 @@ export abstract class AbstractWorker<
     } else if (isPlainObject(taskFunctions)) {
       let firstEntry = true
       for (const [name, fn] of Object.entries(taskFunctions)) {
-        this.checkValidTaskFunctionEntry(name, fn)
+        checkValidTaskFunctionEntry<Data, Response>(name, fn)
         const boundFn = fn.bind(this)
         if (firstEntry) {
           this.taskFunctions.set(DEFAULT_TASK_NAME, boundFn)
@@ -201,9 +158,9 @@ export abstract class AbstractWorker<
    * @param name - The name of the task function to check.
    * @returns Whether the worker has a task function with the given name or not.
    */
-  public hasTaskFunction (name: string): TaskFunctionOperationReturnType {
+  public hasTaskFunction (name: string): TaskFunctionOperationResult {
     try {
-      this.checkTaskFunctionName(name)
+      checkTaskFunctionName(name)
     } catch (error) {
       return { status: false, error: error as Error }
     }
@@ -221,9 +178,9 @@ export abstract class AbstractWorker<
   public addTaskFunction (
     name: string,
     fn: TaskFunction<Data, Response>
-  ): TaskFunctionOperationReturnType {
+  ): TaskFunctionOperationResult {
     try {
-      this.checkTaskFunctionName(name)
+      checkTaskFunctionName(name)
       if (name === DEFAULT_TASK_NAME) {
         throw new Error(
           'Cannot add a task function with the default reserved name'
@@ -253,9 +210,9 @@ export abstract class AbstractWorker<
    * @param name - The name of the task function to remove.
    * @returns Whether the task function existed and was removed or not.
    */
-  public removeTaskFunction (name: string): TaskFunctionOperationReturnType {
+  public removeTaskFunction (name: string): TaskFunctionOperationResult {
     try {
-      this.checkTaskFunctionName(name)
+      checkTaskFunctionName(name)
       if (name === DEFAULT_TASK_NAME) {
         throw new Error(
           'Cannot remove the task function with the default reserved name'
@@ -309,9 +266,9 @@ export abstract class AbstractWorker<
    * @param name - The name of the task function to use as default task function.
    * @returns Whether the default task function was set or not.
    */
-  public setDefaultTaskFunction (name: string): TaskFunctionOperationReturnType {
+  public setDefaultTaskFunction (name: string): TaskFunctionOperationResult {
     try {
-      this.checkTaskFunctionName(name)
+      checkTaskFunctionName(name)
       if (name === DEFAULT_TASK_NAME) {
         throw new Error(
           'Cannot set the default task function reserved name as the default task function'
@@ -333,15 +290,6 @@ export abstract class AbstractWorker<
     }
   }
 
-  private checkTaskFunctionName (name: string): void {
-    if (typeof name !== 'string') {
-      throw new TypeError('name parameter is not a string')
-    }
-    if (typeof name === 'string' && name.trim().length === 0) {
-      throw new TypeError('name parameter is an empty string')
-    }
-  }
-
   /**
    * Handles the ready message sent by the main worker.
    *
@@ -378,28 +326,39 @@ export abstract class AbstractWorker<
     message: MessageValue<Data>
   ): void {
     const { taskFunctionOperation, taskFunctionName, taskFunction } = message
-    let response!: TaskFunctionOperationReturnType
-    if (taskFunctionOperation === 'add') {
-      response = this.addTaskFunction(
-        taskFunctionName as string,
-        // eslint-disable-next-line @typescript-eslint/no-implied-eval, no-new-func
-        new Function(`return ${taskFunction as string}`)() as TaskFunction<
-        Data,
-        Response
-        > /* NOSONAR */
-      )
-    } else if (taskFunctionOperation === 'remove') {
-      response = this.removeTaskFunction(taskFunctionName as string)
-    } else if (taskFunctionOperation === 'default') {
-      response = this.setDefaultTaskFunction(taskFunctionName as string)
+    let response!: TaskFunctionOperationResult
+    switch (taskFunctionOperation) {
+      case 'add':
+        response = this.addTaskFunction(
+          taskFunctionName as string,
+          // eslint-disable-next-line @typescript-eslint/no-implied-eval, no-new-func
+          new Function(`return ${taskFunction as string}`)() as TaskFunction<
+          Data,
+          Response
+          >
+        )
+        break
+      case 'remove':
+        response = this.removeTaskFunction(taskFunctionName as string)
+        break
+      case 'default':
+        response = this.setDefaultTaskFunction(taskFunctionName as string)
+        break
+      default:
+        response = { status: false, error: new Error('Unknown task operation') }
+        break
     }
     this.sendToMainWorker({
       taskFunctionOperation,
       taskFunctionOperationStatus: response.status,
-      workerError: {
-        name: taskFunctionName as string,
-        message: this.handleError(response.error as Error | string)
-      }
+      taskFunctionName,
+      ...(!response.status &&
+        response?.error != null && {
+        workerError: {
+          name: taskFunctionName as string,
+          message: this.handleError(response.error as Error | string)
+        }
+      })
     })
   }
 
@@ -530,7 +489,6 @@ export abstract class AbstractWorker<
    * Runs the given task.
    *
    * @param task - The task to execute.
-   * @throws {@link https://nodejs.org/api/errors.html#class-error} If the task function is not found.
    */
   protected run (task: Task<Data>): void {
     const { name, taskId, data } = task