fix: unref() message port at worker exit
[poolifier.git] / src / pools / worker-node.ts
index 5c172d8aad3916e96e44b6424d0526ad0d31afdb..3b69d3854e07015aa0019ee84f164b8569ffe9aa 100644 (file)
@@ -1,3 +1,4 @@
+import { MessageChannel } from 'node:worker_threads'
 import { CircularArray } from '../circular-array'
 import { Queue } from '../queue'
 import type { Task } from '../utility-types'
@@ -44,7 +45,7 @@ implements IWorkerNode<Worker, Data> {
   }
 
   /**
-   * Worker node tasks queue maximum size.
+   * Tasks queue maximum size.
    *
    * @returns The tasks queue maximum size.
    */
@@ -73,6 +74,17 @@ 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 (!this.tasksUsage.has(name)) {
@@ -86,7 +98,10 @@ implements IWorkerNode<Worker, Data> {
       id: this.getWorkerId(worker, workerType),
       type: workerType,
       dynamic: false,
-      ready: false
+      ready: false,
+      ...(workerType === WorkerTypes.thread && {
+        messageChannel: new MessageChannel()
+      })
     }
   }