X-Git-Url: https://git.piment-noir.org/?a=blobdiff_plain;f=src%2Fworker%2Fcluster-worker.ts;h=35899e794f5b373aa5bca3ec5b3dbe2d1f5cd4c3;hb=a1763c54c962c69b5e02a30c0909724986495fcd;hp=efc17acf0b9205f05ff621e399b448af2cfbbb47;hpb=e102732c0e3966b81834b2c0bdd087eb051162ad;p=poolifier.git diff --git a/src/worker/cluster-worker.ts b/src/worker/cluster-worker.ts index efc17acf..35899e79 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,45 @@ 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, + cluster.worker as Worker, taskFunctions, - process, 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, + taskFunctions: this.listTaskFunctions(), + workerId: this.id + }) + } catch { + this.sendToMainWorker({ + ready: false, + taskFunctions: this.listTaskFunctions(), + workerId: this.id + }) + } } - 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 sendToMainWorker (message: MessageValue): void { + this.getMainWorker().send(message) } }