Migrate the code to node.js LTS version 16.x.x (#492)
[poolifier.git] / src / worker / cluster-worker.ts
1 import type { Worker } from 'cluster'
2 import cluster from 'cluster'
3 import type { MessageValue } from '../utility-types'
4 import { AbstractWorker } from './abstract-worker'
5 import type { WorkerOptions } from './worker-options'
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 * @template DataType of data this worker receives from pool's execution. This can only be serializable data.
17 * @template ResponseType of response the worker sends back to the main worker. This can only be serializable 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 fn Function processed by the worker when the pool's `execution` function is invoked.
29 * @param opts Options for the worker.
30 */
31 public constructor (fn: (data: Data) => Response, opts: WorkerOptions = {}) {
32 super(
33 'worker-cluster-pool:poolifier',
34 cluster.isPrimary,
35 fn,
36 cluster.worker,
37 opts
38 )
39 }
40
41 /** @inheritdoc */
42 protected sendToMainWorker (message: MessageValue<Response>): void {
43 this.getMainWorker().send(message)
44 }
45
46 /** @inheritdoc */
47 protected handleError (e: Error | string): string {
48 return e instanceof Error ? e.message : e
49 }
50 }