| 1 | import cluster, { type Worker } from 'node:cluster' |
| 2 | |
| 3 | import type { MessageValue } from '../utility-types.js' |
| 4 | import { AbstractWorker } from './abstract-worker.js' |
| 5 | import type { TaskFunction, TaskFunctions } from './task-functions.js' |
| 6 | import type { WorkerOptions } from './worker-options.js' |
| 7 | |
| 8 | /** |
| 9 | * A cluster worker used by a poolifier `ClusterPool`. |
| 10 | * |
| 11 | * When this worker is inactive for more than the given `maxInactiveTime`, |
| 12 | * it will send a termination request to its main worker. |
| 13 | * |
| 14 | * If you use a `DynamicClusterPool` the extra workers that were created will be terminated, |
| 15 | * but the minimum number of workers will be guaranteed. |
| 16 | * @typeParam Data - Type of data this worker receives from pool's execution. This can only be structured-cloneable data. |
| 17 | * @typeParam Response - Type of response the worker sends back to the main worker. This can only be structured-cloneable data. |
| 18 | * @author [Christopher Quadflieg](https://github.com/Shinigami92) |
| 19 | * @since 2.0.0 |
| 20 | */ |
| 21 | export class ClusterWorker< |
| 22 | Data = unknown, |
| 23 | Response = unknown |
| 24 | > extends AbstractWorker<Worker, Data, Response> { |
| 25 | /** |
| 26 | * Constructs a new poolifier cluster worker. |
| 27 | * @param taskFunctions - Task function(s) processed by the worker when the pool's `execution` function is invoked. |
| 28 | * @param opts - Options for the worker. |
| 29 | */ |
| 30 | public constructor ( |
| 31 | taskFunctions: TaskFunction<Data, Response> | TaskFunctions<Data, Response>, |
| 32 | opts: WorkerOptions = {} |
| 33 | ) { |
| 34 | super(cluster.isPrimary, cluster.worker, taskFunctions, opts) |
| 35 | } |
| 36 | |
| 37 | /** @inheritDoc */ |
| 38 | protected handleReadyMessage (message: MessageValue<Data>): void { |
| 39 | if (message.workerId === this.id && message.ready === false) { |
| 40 | try { |
| 41 | this.getMainWorker().on('message', this.messageListener.bind(this)) |
| 42 | this.sendToMainWorker({ |
| 43 | ready: true, |
| 44 | taskFunctionsProperties: this.listTaskFunctionsProperties(), |
| 45 | }) |
| 46 | } catch { |
| 47 | this.sendToMainWorker({ |
| 48 | ready: false, |
| 49 | taskFunctionsProperties: this.listTaskFunctionsProperties(), |
| 50 | }) |
| 51 | } |
| 52 | } |
| 53 | } |
| 54 | |
| 55 | /** @inheritDoc */ |
| 56 | protected get id (): number { |
| 57 | return this.getMainWorker().id |
| 58 | } |
| 59 | |
| 60 | /** @inheritDoc */ |
| 61 | protected readonly sendToMainWorker = ( |
| 62 | message: MessageValue<Response> |
| 63 | ): void => { |
| 64 | this.getMainWorker().send({ |
| 65 | ...message, |
| 66 | workerId: this.id, |
| 67 | } satisfies MessageValue<Response>) |
| 68 | } |
| 69 | } |