X-Git-Url: https://git.piment-noir.org/?a=blobdiff_plain;f=src%2Fworker%2Fcluster-worker.ts;h=d972692ec6eb4f182479cac008c47a1f20b75d8d;hb=refs%2Ftags%2Fv3.1.9;hp=efc17acf0b9205f05ff621e399b448af2cfbbb47;hpb=e102732c0e3966b81834b2c0bdd087eb051162ad;p=poolifier.git diff --git a/src/worker/cluster-worker.ts b/src/worker/cluster-worker.ts index efc17acf..d972692e 100644 --- a/src/worker/cluster-worker.ts +++ b/src/worker/cluster-worker.ts @@ -1,8 +1,8 @@ -import cluster from 'node:cluster' +import cluster, { type Worker } 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 type { TaskFunction, TaskFunctions } from './task-functions' /** * A cluster worker used by a poolifier `ClusterPool`. @@ -21,7 +21,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 +29,39 @@ 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 as 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, + 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 + ): void => { + this.getMainWorker().send({ ...message, workerId: this.id }) } }