X-Git-Url: https://git.piment-noir.org/?a=blobdiff_plain;f=src%2Fworker%2Fcluster-worker.ts;h=847f2174d1657b05824d12461b8bba054287ae54;hb=910416386b4f7d0da4e6f0d8551cefa2539c5ced;hp=efc17acf0b9205f05ff621e399b448af2cfbbb47;hpb=e102732c0e3966b81834b2c0bdd087eb051162ad;p=poolifier.git diff --git a/src/worker/cluster-worker.ts b/src/worker/cluster-worker.ts index efc17acf..847f2174 100644 --- a/src/worker/cluster-worker.ts +++ b/src/worker/cluster-worker.ts @@ -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 { +> extends AbstractWorker { /** * Constructs a new poolifier cluster worker. * @@ -29,31 +30,42 @@ export class ClusterWorker< * @param opts - Options for the worker. */ public constructor ( - taskFunctions: - | WorkerFunction - | TaskFunctions, + taskFunctions: TaskFunction | TaskFunctions, opts: WorkerOptions = {} ) { - super( - 'worker-cluster-pool:poolifier', - cluster.isPrimary, - taskFunctions, - process, - opts - ) + super(cluster.isPrimary, cluster.worker, taskFunctions, opts) } /** @inheritDoc */ - protected sendToMainWorker (message: MessageValue): void { - const mainWorker = this.getMainWorker() - if (mainWorker.send == null) { - throw new Error('Main worker does not support IPC communication') + protected handleReadyMessage (message: MessageValue): 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 + ): void => { + this.getMainWorker().send({ + ...message, + workerId: this.id + } satisfies MessageValue) } }