perf: remove unneeded class indirection for dynamic pool in worker
[poolifier.git] / src / worker / cluster-worker.ts
CommitLineData
fc3e6586
JB
1import type { Worker } from 'node:cluster'
2import cluster from 'node:cluster'
deb85c12 3import type { MessageValue } from '../utility-types'
c97c7edb 4import { AbstractWorker } from './abstract-worker'
325f50bc
S
5import type { WorkerOptions } from './worker-options'
6
7/**
729c563d 8 * A cluster worker used by a poolifier `ClusterPool`.
325f50bc 9 *
729c563d
S
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 *
38e795c1
JB
16 * @typeParam Data - Type of data this worker receives from pool's execution. This can only be serializable data.
17 * @typeParam Response - Type of response the worker sends back to the main worker. This can only be serializable data.
325f50bc
S
18 * @author [Christopher Quadflieg](https://github.com/Shinigami92)
19 * @since 2.0.0
20 */
d3c8a1a8 21export class ClusterWorker<
deb85c12
JB
22 Data = unknown,
23 Response = unknown
d3c8a1a8 24> extends AbstractWorker<Worker, Data, Response> {
729c563d
S
25 /**
26 * Constructs a new poolifier cluster worker.
27 *
38e795c1
JB
28 * @param fn - Function processed by the worker when the pool's `execution` function is invoked.
29 * @param opts - Options for the worker.
729c563d 30 */
ed6dd37f 31 public constructor (fn: (data: Data) => Response, opts: WorkerOptions = {}) {
7e0d447f
JB
32 super(
33 'worker-cluster-pool:poolifier',
34 cluster.isPrimary,
35 fn,
36 cluster.worker,
37 opts
38 )
325f50bc
S
39 }
40
38e795c1 41 /** {@inheritDoc} */
c97c7edb
S
42 protected sendToMainWorker (message: MessageValue<Response>): void {
43 this.getMainWorker().send(message)
325f50bc
S
44 }
45
38e795c1 46 /** {@inheritDoc} */
c97c7edb
S
47 protected handleError (e: Error | string): string {
48 return e instanceof Error ? e.message : e
325f50bc
S
49 }
50}