fix: fix task function names property in worker-node
[poolifier.git] / src / pools / worker-node.ts
index 5c172d8aad3916e96e44b6424d0526ad0d31afdb..4349ed72471b3614e227ab4d374df7f0aba17186 100644 (file)
@@ -1,6 +1,8 @@
+import { MessageChannel } from 'node:worker_threads'
 import { CircularArray } from '../circular-array'
 import { Queue } from '../queue'
 import type { Task } from '../utility-types'
+import { DEFAULT_TASK_NAME } from '../utils'
 import {
   type IWorker,
   type IWorkerNode,
@@ -44,7 +46,7 @@ implements IWorkerNode<Worker, Data> {
   }
 
   /**
-   * Worker node tasks queue maximum size.
+   * Tasks queue maximum size.
    *
    * @returns The tasks queue maximum size.
    */
@@ -73,8 +75,31 @@ implements IWorkerNode<Worker, Data> {
     this.tasksUsage.clear()
   }
 
+  /** @inheritdoc */
+  public closeChannel (): void {
+    if (this.info.messageChannel != null) {
+      this.info.messageChannel?.port1.unref()
+      this.info.messageChannel?.port2.unref()
+      this.info.messageChannel?.port1.close()
+      this.info.messageChannel?.port2.close()
+      delete this.info.messageChannel
+    }
+  }
+
   /** @inheritdoc */
   public getTaskWorkerUsage (name: string): WorkerUsage | undefined {
+    if (name === DEFAULT_TASK_NAME && !Array.isArray(this.info.taskFunctions)) {
+      throw new Error(
+        'Cannot get task worker usage for default task function name when task function names list is not yet defined'
+      )
+    }
+    if (
+      name === DEFAULT_TASK_NAME &&
+      Array.isArray(this.info.taskFunctions) &&
+      this.info.taskFunctions.length > 1
+    ) {
+      name = this.info.taskFunctions[1]
+    }
     if (!this.tasksUsage.has(name)) {
       this.tasksUsage.set(name, this.initTaskWorkerUsage(name))
     }
@@ -86,7 +111,10 @@ implements IWorkerNode<Worker, Data> {
       id: this.getWorkerId(worker, workerType),
       type: workerType,
       dynamic: false,
-      ready: false
+      ready: false,
+      ...(workerType === WorkerTypes.thread && {
+        messageChannel: new MessageChannel()
+      })
     }
   }