Merge dependabot/npm_and_yarn/examples/typescript/http-client-pool/types/node-20...
[poolifier.git] / src / worker / abstract-worker.ts
index a00e8f8faadd4e912de558c5d4f8ca980db76036..f0ef59327c6099bc3719be1d84b537b0496fdd22 100644 (file)
@@ -88,20 +88,71 @@ export abstract class AbstractWorker<
     protected opts: WorkerOptions = DEFAULT_WORKER_OPTIONS
   ) {
     super(type)
-    this.checkWorkerOptions(this.opts)
+    if (this.isMain == null) {
+      throw new Error('isMain parameter is mandatory')
+    }
     this.checkTaskFunctions(taskFunctions)
+    this.checkWorkerOptions(this.opts)
     if (!this.isMain) {
-      this.getMainWorker()?.on('message', this.handleReadyMessage.bind(this))
+      this.getMainWorker().on('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')
+    }
     this.opts = { ...DEFAULT_WORKER_OPTIONS, ...opts }
-    delete this.opts.async
+  }
+
+  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.
+   * Checks if the `taskFunctions` parameter is passed to the constructor and valid.
    *
    * @param taskFunctions - The task function(s) parameter that should be checked.
    */
@@ -125,21 +176,7 @@ export abstract class AbstractWorker<
     } else if (isPlainObject(taskFunctions)) {
       let firstEntry = true
       for (const [name, fn] of Object.entries(taskFunctions)) {
-        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 an empty string'
-          )
-        }
-        if (typeof fn !== 'function') {
-          throw new TypeError(
-            'A taskFunctions parameter object value is not a function'
-          )
-        }
+        this.checkValidTaskFunctionEntry(name, fn)
         const boundFn = fn.bind(this)
         if (firstEntry) {
           this.taskFunctions.set(DEFAULT_TASK_NAME, boundFn)
@@ -258,7 +295,7 @@ export abstract class AbstractWorker<
       names[names.indexOf(DEFAULT_TASK_NAME)],
       defaultTaskFunctionName,
       ...names.filter(
-        (name) => name !== DEFAULT_TASK_NAME && name !== defaultTaskFunctionName
+        name => name !== DEFAULT_TASK_NAME && name !== defaultTaskFunctionName
       )
     ]
   }
@@ -419,6 +456,7 @@ export abstract class AbstractWorker<
    * Returns the main worker.
    *
    * @returns Reference to the main worker.
+   * @throws {@link https://nodejs.org/api/errors.html#class-error} If the main worker is not set.
    */
   protected getMainWorker (): MainWorker {
     if (this.mainWorker == null) {
@@ -449,11 +487,11 @@ export abstract class AbstractWorker<
   /**
    * Handles an error and convert it to a string so it can be sent back to the main worker.
    *
-   * @param e - The error raised by the worker.
+   * @param error - The error raised by the worker.
    * @returns The error message.
    */
-  protected handleError (e: Error | string): string {
-    return e instanceof Error ? e.message : e
+  protected handleError (error: Error | string): string {
+    return error instanceof Error ? error.message : error
   }
 
   /**
@@ -463,7 +501,20 @@ export abstract class AbstractWorker<
    * @throws {@link https://nodejs.org/api/errors.html#class-error} If the task function is not found.
    */
   protected run (task: Task<Data>): void {
-    const fn = this.getTaskFunction(task.name)
+    const { name, taskId, data } = task
+    const fn = this.taskFunctions.get(name ?? DEFAULT_TASK_NAME)
+    if (fn == null) {
+      this.sendToMainWorker({
+        taskError: {
+          name: name as string,
+          message: `Task function '${name as string}' not found`,
+          data
+        },
+        workerId: this.id,
+        taskId
+      })
+      return
+    }
     if (isAsyncFunction(fn)) {
       this.runInAsyncScope(this.runAsync.bind(this), this, fn, task)
     } else {
@@ -492,12 +543,11 @@ export abstract class AbstractWorker<
         workerId: this.id,
         taskId
       })
-    } catch (e) {
-      const errorMessage = this.handleError(e as Error | string)
+    } catch (error) {
       this.sendToMainWorker({
         taskError: {
           name: name as string,
-          message: errorMessage,
+          message: this.handleError(error as Error | string),
           data
         },
         workerId: this.id,
@@ -521,7 +571,7 @@ export abstract class AbstractWorker<
     const { name, taskId, data } = task
     let taskPerformance = this.beginTaskPerformance(name)
     fn(data)
-      .then((res) => {
+      .then(res => {
         taskPerformance = this.endTaskPerformance(taskPerformance)
         this.sendToMainWorker({
           data: res,
@@ -531,12 +581,11 @@ export abstract class AbstractWorker<
         })
         return null
       })
-      .catch((e) => {
-        const errorMessage = this.handleError(e as Error | string)
+      .catch(error => {
         this.sendToMainWorker({
           taskError: {
             name: name as string,
-            message: errorMessage,
+            message: this.handleError(error as Error | string),
             data
           },
           workerId: this.id,
@@ -549,22 +598,6 @@ export abstract class AbstractWorker<
       .catch(EMPTY_FUNCTION)
   }
 
-  /**
-   * Gets the task function with the given name.
-   *
-   * @param name - Name of the task function that will be returned.
-   * @returns The task function.
-   * @throws {@link https://nodejs.org/api/errors.html#class-error} If the task function is not found.
-   */
-  private getTaskFunction (name?: string): TaskFunction<Data, Response> {
-    name = name ?? DEFAULT_TASK_NAME
-    const fn = this.taskFunctions.get(name)
-    if (fn == null) {
-      throw new Error(`Task function '${name}' not found`)
-    }
-    return fn
-  }
-
   private beginTaskPerformance (name?: string): TaskPerformance {
     this.checkStatistics()
     return {