fix: prepare code to fix pool internal IPC for cluster worker
[poolifier.git] / src / worker / cluster-worker.ts
CommitLineData
e102732c 1import cluster from 'node:cluster'
b6b32453 2import type { MessageValue } from '../utility-types'
c97c7edb 3import { AbstractWorker } from './abstract-worker'
325f50bc 4import type { WorkerOptions } from './worker-options'
b6b32453 5import type { TaskFunctions, WorkerFunction } from './worker-functions'
325f50bc
S
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 *
e102732c
JB
16 * @typeParam Data - Type of data this worker receives from pool's execution. This can only be structured-cloneable data.
17 * @typeParam Response - Type of response the worker sends back to the main worker. This can only be structured-cloneable 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
e102732c 24> extends AbstractWorker<NodeJS.Process, Data, Response> {
729c563d
S
25 /**
26 * Constructs a new poolifier cluster worker.
27 *
a86b6df1 28 * @param taskFunctions - Task function(s) processed by the worker when the pool's `execution` function is invoked.
38e795c1 29 * @param opts - Options for the worker.
729c563d 30 */
d4aeae5a 31 public constructor (
a86b6df1
JB
32 taskFunctions:
33 | WorkerFunction<Data, Response>
34 | TaskFunctions<Data, Response>,
d4aeae5a
JB
35 opts: WorkerOptions = {}
36 ) {
7e0d447f
JB
37 super(
38 'worker-cluster-pool:poolifier',
39 cluster.isPrimary,
a86b6df1 40 taskFunctions,
e102732c 41 process,
7e0d447f
JB
42 opts
43 )
325f50bc
S
44 }
45
afc003b2 46 /** @inheritDoc */
c97c7edb 47 protected sendToMainWorker (message: MessageValue<Response>): void {
e102732c
JB
48 const mainWorker = this.getMainWorker()
49 if (mainWorker.send == null) {
50 throw new Error('Main worker does not support IPC communication')
51 }
52 mainWorker.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}