d972692ec6eb4f182479cac008c47a1f20b75d8d
[poolifier.git] / src / worker / cluster-worker.ts
1 import cluster, { type Worker } from 'node:cluster'
2 import type { MessageValue } from '../utility-types'
3 import { AbstractWorker } from './abstract-worker'
4 import type { WorkerOptions } from './worker-options'
5 import type { TaskFunction, TaskFunctions } from './task-functions'
6
7 /**
8 * A cluster worker used by a poolifier `ClusterPool`.
9 *
10 * When this worker is inactive for more than the given `maxInactiveTime`,
11 * it will send a termination request to its main worker.
12 *
13 * If you use a `DynamicClusterPool` the extra workers that were created will be terminated,
14 * but the minimum number of workers will be guaranteed.
15 *
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 *
28 * @param taskFunctions - Task function(s) processed by the worker when the pool's `execution` function is invoked.
29 * @param opts - Options for the worker.
30 */
31 public constructor (
32 taskFunctions: TaskFunction<Data, Response> | TaskFunctions<Data, Response>,
33 opts: WorkerOptions = {}
34 ) {
35 super(cluster.isPrimary, cluster.worker as Worker, taskFunctions, opts)
36 }
37
38 /** @inheritDoc */
39 protected handleReadyMessage (message: MessageValue<Data>): void {
40 if (message.workerId === this.id && message.ready === false) {
41 try {
42 this.getMainWorker().on('message', this.messageListener.bind(this))
43 this.sendToMainWorker({
44 ready: true,
45 taskFunctionNames: this.listTaskFunctionNames()
46 })
47 } catch {
48 this.sendToMainWorker({
49 ready: false,
50 taskFunctionNames: this.listTaskFunctionNames()
51 })
52 }
53 }
54 }
55
56 /** @inheritDoc */
57 protected get id (): number {
58 return this.getMainWorker().id
59 }
60
61 /** @inheritDoc */
62 protected readonly sendToMainWorker = (
63 message: MessageValue<Response>
64 ): void => {
65 this.getMainWorker().send({ ...message, workerId: this.id })
66 }
67 }