-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`.
export class ClusterWorker<
Data = unknown,
Response = unknown
-> extends AbstractWorker<NodeJS.Process, Data, Response> {
+> extends AbstractWorker<Worker, Data, Response> {
/**
* Constructs a new poolifier cluster worker.
*
* @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,
+ taskFunctionsProperties: this.listTaskFunctionsProperties()
+ })
+ } catch {
+ this.sendToMainWorker({
+ ready: false,
+ taskFunctionsProperties: this.listTaskFunctionsProperties()
+ })
+ }
}
- 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>)
}
}