refactor: limit pool internals public exposure
[poolifier.git] / src / worker / cluster-worker.ts
CommitLineData
059438ff 1import cluster, { type Worker } from 'node:cluster'
a86b6df1
JB
2import type {
3 MessageValue,
4 TaskFunctions,
5 WorkerFunction
6} from '../utility-types'
c97c7edb 7import { AbstractWorker } from './abstract-worker'
325f50bc
S
8import type { WorkerOptions } from './worker-options'
9
10/**
729c563d 11 * A cluster worker used by a poolifier `ClusterPool`.
325f50bc 12 *
729c563d
S
13 * When this worker is inactive for more than the given `maxInactiveTime`,
14 * it will send a termination request to its main worker.
15 *
16 * If you use a `DynamicClusterPool` the extra workers that were created will be terminated,
17 * but the minimum number of workers will be guaranteed.
18 *
38e795c1
JB
19 * @typeParam Data - Type of data this worker receives from pool's execution. This can only be serializable data.
20 * @typeParam Response - Type of response the worker sends back to the main worker. This can only be serializable data.
325f50bc
S
21 * @author [Christopher Quadflieg](https://github.com/Shinigami92)
22 * @since 2.0.0
23 */
d3c8a1a8 24export class ClusterWorker<
deb85c12
JB
25 Data = unknown,
26 Response = unknown
d3c8a1a8 27> extends AbstractWorker<Worker, Data, Response> {
729c563d
S
28 /**
29 * Constructs a new poolifier cluster worker.
30 *
a86b6df1 31 * @param taskFunctions - Task function(s) processed by the worker when the pool's `execution` function is invoked.
38e795c1 32 * @param opts - Options for the worker.
729c563d 33 */
d4aeae5a 34 public constructor (
a86b6df1
JB
35 taskFunctions:
36 | WorkerFunction<Data, Response>
37 | TaskFunctions<Data, Response>,
d4aeae5a
JB
38 opts: WorkerOptions = {}
39 ) {
7e0d447f
JB
40 super(
41 'worker-cluster-pool:poolifier',
42 cluster.isPrimary,
a86b6df1 43 taskFunctions,
7e0d447f
JB
44 cluster.worker,
45 opts
46 )
325f50bc
S
47 }
48
afc003b2 49 /** @inheritDoc */
c97c7edb
S
50 protected sendToMainWorker (message: MessageValue<Response>): void {
51 this.getMainWorker().send(message)
325f50bc
S
52 }
53
afc003b2 54 /** @inheritDoc */
c97c7edb
S
55 protected handleError (e: Error | string): string {
56 return e instanceof Error ? e.message : e
325f50bc
S
57 }
58}