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