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