fix: unref() message port at worker exit
[poolifier.git] / src / worker / thread-worker.ts
index b6fbdae257399ac7fa9f8d9fca9e37f6cdfc08d7..4d4c1c3479f14970db523ff96d873f0b4cdac79f 100644 (file)
@@ -1,7 +1,13 @@
-import { isMainThread, parentPort } from 'worker_threads'
-import type { JSONValue, MessageValue } from '../utility-types'
+import {
+  type MessagePort,
+  isMainThread,
+  parentPort,
+  threadId
+} from 'node:worker_threads'
+import type { MessageValue } from '../utility-types'
 import { AbstractWorker } from './abstract-worker'
 import type { WorkerOptions } from './worker-options'
+import type { TaskFunctions, WorkerFunction } from './worker-functions'
 
 /**
  * A thread worker used by a poolifier `ThreadPool`.
@@ -12,59 +18,73 @@ import type { WorkerOptions } from './worker-options'
  * If you use a `DynamicThreadPool` the extra workers that were created will be terminated,
  * but the minimum number of workers will be guaranteed.
  *
- * @template Data Type of data this worker receives from pool's execution.
- * @template Response Type of response the worker sends back to the main thread.
- *
+ * @typeParam Data - Type of data this worker receives from pool's execution. This can only be structured-cloneable data.
+ * @typeParam Response - Type of response the worker sends back to the main thread. This can only be structured-cloneable data.
  * @author [Alessandro Pio Ardizio](https://github.com/pioardi)
  * @since 0.0.1
  */
 export class ThreadWorker<
-  Data extends JSONValue = JSONValue,
-  Response extends JSONValue = JSONValue
+  Data = unknown,
+  Response = unknown
 > extends AbstractWorker<MessagePort, Data, Response> {
   /**
-   * Reference to main thread.
+   * Message port used to communicate with the main thread.
    */
-  protected parent?: MessagePort
-
+  private port!: MessagePort
   /**
    * Constructs a new poolifier thread worker.
    *
-   * @param fn Function processed by the worker when the pool's `execution` function is invoked.
-   * @param opts Options for the worker.
+   * @param taskFunctions - Task function(s) processed by the worker when the pool's `execution` function is invoked.
+   * @param opts Options for the worker.
    */
-  public constructor (fn: (data: Data) => Response, opts: WorkerOptions = {}) {
-    super('worker-thread-pool:pioardi', isMainThread, fn, opts)
-
-    parentPort?.on('message', (value: MessageValue<Data>) => {
-      if (value?.data && value.id) {
-        // here you will receive messages
-        // console.log('This is the main worker ' + isMainThread)
-        if (this.async) {
-          this.runInAsyncScope(this.runAsync.bind(this), this, fn, value)
-        } else {
-          this.runInAsyncScope(this.run.bind(this), this, fn, value)
-        }
-      } else if (value.parent) {
-        // save the port to communicate with the main thread
-        // this will be received once
-        this.parent = value.parent
-      } else if (value.kill) {
-        // here is time to kill this worker, just clearing the interval
-        if (this.interval) clearInterval(this.interval)
-        this.emitDestroy()
-      }
-    })
+  public constructor (
+    taskFunctions:
+    | WorkerFunction<Data, Response>
+    | TaskFunctions<Data, Response>,
+    opts: WorkerOptions = {}
+  ) {
+    super(
+      'worker-thread-pool:poolifier',
+      isMainThread,
+      parentPort as MessagePort,
+      taskFunctions,
+      opts
+    )
   }
 
-  protected getMainWorker (): MessagePort {
-    if (!this.parent) {
-      throw new Error('Parent was not set')
+  /** @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 })
     }
-    return this.parent
   }
 
+  /** @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 */
+  protected handleError (e: Error | string): string {
+    return e as string
   }
 }