fix: unref() message port at worker exit
[poolifier.git] / src / worker / thread-worker.ts
index 09135afffc913dd7b983b7cbac9134bb5573b3b3..4d4c1c3479f14970db523ff96d873f0b4cdac79f 100644 (file)
@@ -27,6 +27,10 @@ export class ThreadWorker<
   Data = unknown,
   Response = unknown
 > extends AbstractWorker<MessagePort, Data, Response> {
+  /**
+   * Message port used to communicate with the main thread.
+   */
+  private port!: MessagePort
   /**
    * Constructs a new poolifier thread worker.
    *
@@ -42,19 +46,41 @@ export class ThreadWorker<
     super(
       'worker-thread-pool:poolifier',
       isMainThread,
-      taskFunctions,
       parentPort as MessagePort,
+      taskFunctions,
       opts
     )
   }
 
+  /** @inheritDoc */
+  protected handleReadyMessage (message: MessageValue<Data>): void {
+    if (
+      !this.isMain &&
+      message.workerId === this.id &&
+      message.ready != null &&
+      message.port != null
+    ) {
+      this.port = message.port
+      this.port.on('message', this.messageListener.bind(this))
+      this.sendToMainWorker({ ready: true, workerId: this.id })
+    }
+  }
+
+  /** @inheritDoc */
+  protected handleKillMessage (message: MessageValue<Data, unknown>): void {
+    super.handleKillMessage(message)
+    this.port?.unref()
+    this.port?.close()
+  }
+
+  /** @inheritDoc */
   protected get id (): number {
     return threadId
   }
 
   /** @inheritDoc */
   protected sendToMainWorker (message: MessageValue<Response>): void {
-    this.getMainWorker().postMessage(message)
+    this.port.postMessage(message)
   }
 
   /** @inheritDoc */