fix: unref() message port at worker exit
authorJérôme Benoit <jerome.benoit@sap.com>
Thu, 20 Jul 2023 15:47:52 +0000 (17:47 +0200)
committerJérôme Benoit <jerome.benoit@sap.com>
Thu, 20 Jul 2023 15:47:52 +0000 (17:47 +0200)
Signed-off-by: Jérôme Benoit <jerome.benoit@sap.com>
src/pools/worker-node.ts
src/worker/abstract-worker.ts
src/worker/thread-worker.ts

index fcc091378565a4b78c7f9085619c9017169474d3..3b69d3854e07015aa0019ee84f164b8569ffe9aa 100644 (file)
@@ -77,6 +77,8 @@ implements IWorkerNode<Worker, Data> {
   /** @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
index 67b4b5ff9e4575ead2d824537fb106d6d0b5ba11..0f1d442a6f242ef2a25068f8e212f2fbff686a37 100644 (file)
@@ -311,12 +311,21 @@ export abstract class AbstractWorker<
         this.run(message)
       } else if (message.kill === true) {
         // Kill message received
-        !this.isMain && this.stopCheckActive()
-        this.emitDestroy()
+        this.handleKillMessage(message)
       }
     }
   }
 
+  /**
+   * Handles a kill message sent by the main worker.
+   *
+   * @param message - The kill message.
+   */
+  protected handleKillMessage (message: MessageValue<Data>): void {
+    !this.isMain && this.stopCheckActive()
+    this.emitDestroy()
+  }
+
   /**
    * Starts the worker check active interval.
    */
@@ -325,7 +334,8 @@ export abstract class AbstractWorker<
     this.activeInterval = setInterval(
       this.checkActive.bind(this),
       (this.opts.maxInactiveTime ?? DEFAULT_MAX_INACTIVE_TIME) / 2
-    ).unref()
+    )
+    this.activeInterval.unref()
   }
 
   /**
index 98d58b5d98162ba2f09ca21a6abaca114123355d..4d4c1c3479f14970db523ff96d873f0b4cdac79f 100644 (file)
@@ -66,6 +66,13 @@ export class ThreadWorker<
     }
   }
 
+  /** @inheritDoc */
+  protected handleKillMessage (message: MessageValue<Data, unknown>): void {
+    super.handleKillMessage(message)
+    this.port?.unref()
+    this.port?.close()
+  }
+
   /** @inheritDoc */
   protected get id (): number {
     return threadId