Dedupe worker attributes (#364)
[poolifier.git] / src / worker / cluster-worker.ts
CommitLineData
c97c7edb 1import type { Worker } from 'cluster'
325f50bc 2import { isMaster, worker } from '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 *
deb85c12
JB
16 * @template Data Type of data this worker receives from pool's execution. This can only be serializable data.
17 * @template Response Type of response the worker sends back to the main worker. This can only be serializable data.
325f50bc
S
18 *
19 * @author [Christopher Quadflieg](https://github.com/Shinigami92)
20 * @since 2.0.0
21 */
d3c8a1a8 22export class ClusterWorker<
deb85c12
JB
23 Data = unknown,
24 Response = unknown
d3c8a1a8 25> extends AbstractWorker<Worker, Data, Response> {
729c563d
S
26 /**
27 * Constructs a new poolifier cluster worker.
28 *
29 * @param fn Function processed by the worker when the pool's `execution` function is invoked.
30 * @param opts Options for the worker.
31 */
c97c7edb 32 public constructor (fn: (data: Data) => Response, opts: WorkerOptions = {}) {
e088a00c 33 super('worker-cluster-pool:poolifier', isMaster, fn, worker, opts)
325f50bc
S
34 }
35
6e9d10db 36 /** @inheritdoc */
c97c7edb
S
37 protected sendToMainWorker (message: MessageValue<Response>): void {
38 this.getMainWorker().send(message)
325f50bc
S
39 }
40
6e9d10db 41 /** @inheritdoc */
c97c7edb
S
42 protected handleError (e: Error | string): string {
43 return e instanceof Error ? e.message : e
325f50bc
S
44 }
45}