build: bump volta node version
[poolifier.git] / src / worker / cluster-worker.ts
index efc17acf0b9205f05ff621e399b448af2cfbbb47..325b7a410b6cb7686ebee51f1d37b06043622fad 100644 (file)
@@ -1,8 +1,9 @@
-import cluster from 'node:cluster'
-import type { MessageValue } from '../utility-types'
-import { AbstractWorker } from './abstract-worker'
-import type { WorkerOptions } from './worker-options'
-import type { TaskFunctions, WorkerFunction } from './worker-functions'
+import cluster, { type Worker } from 'node:cluster'
+
+import type { MessageValue } from '../utility-types.js'
+import { AbstractWorker } from './abstract-worker.js'
+import type { TaskFunction, TaskFunctions } from './task-functions.js'
+import type { WorkerOptions } from './worker-options.js'
 
 /**
  * A cluster worker used by a poolifier `ClusterPool`.
@@ -21,7 +22,7 @@ import type { TaskFunctions, WorkerFunction } from './worker-functions'
 export class ClusterWorker<
   Data = unknown,
   Response = unknown
-> extends AbstractWorker<NodeJS.Process, Data, Response> {
+> extends AbstractWorker<Worker, Data, Response> {
   /**
    * Constructs a new poolifier cluster worker.
    *
@@ -29,31 +30,42 @@ export class ClusterWorker<
    * @param opts - Options for the worker.
    */
   public constructor (
-    taskFunctions:
-    | WorkerFunction<Data, Response>
-    | TaskFunctions<Data, Response>,
+    taskFunctions: TaskFunction<Data, Response> | TaskFunctions<Data, Response>,
     opts: WorkerOptions = {}
   ) {
-    super(
-      'worker-cluster-pool:poolifier',
-      cluster.isPrimary,
-      taskFunctions,
-      process,
-      opts
-    )
+    super(cluster.isPrimary, cluster.worker, taskFunctions, opts)
   }
 
   /** @inheritDoc */
-  protected sendToMainWorker (message: MessageValue<Response>): void {
-    const mainWorker = this.getMainWorker()
-    if (mainWorker.send == null) {
-      throw new Error('Main worker does not support IPC communication')
+  protected handleReadyMessage (message: MessageValue<Data>): void {
+    if (message.workerId === this.id && message.ready === false) {
+      try {
+        this.getMainWorker().on('message', this.messageListener.bind(this))
+        this.sendToMainWorker({
+          ready: true,
+          taskFunctionNames: this.listTaskFunctionNames()
+        })
+      } catch {
+        this.sendToMainWorker({
+          ready: false,
+          taskFunctionNames: this.listTaskFunctionNames()
+        })
+      }
     }
-    mainWorker.send(message)
   }
 
   /** @inheritDoc */
-  protected handleError (e: Error | string): string {
-    return e instanceof Error ? e.message : e
+  protected get id (): number {
+    return this.getMainWorker().id
+  }
+
+  /** @inheritDoc */
+  protected readonly sendToMainWorker = (
+    message: MessageValue<Response>
+  ): void => {
+    this.getMainWorker().send({
+      ...message,
+      workerId: this.id
+    } satisfies MessageValue<Response>)
   }
 }