build(deps-dev): apply updates
[poolifier.git] / src / worker / cluster-worker.ts
CommitLineData
6677a3d3 1import cluster, { type Worker } from 'node:cluster'
ded253e2 2
d35e5717
JB
3import type { MessageValue } from '../utility-types.js'
4import { AbstractWorker } from './abstract-worker.js'
d35e5717 5import type { TaskFunction, TaskFunctions } from './task-functions.js'
ded253e2 6import type { WorkerOptions } from './worker-options.js'
325f50bc
S
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.
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
6677a3d3 24> extends AbstractWorker<Worker, Data, Response> {
729c563d
S
25 /**
26 * Constructs a new poolifier cluster worker.
a86b6df1 27 * @param taskFunctions - Task function(s) processed by the worker when the pool's `execution` function is invoked.
38e795c1 28 * @param opts - Options for the worker.
729c563d 29 */
d4aeae5a 30 public constructor (
82ea6492 31 taskFunctions: TaskFunction<Data, Response> | TaskFunctions<Data, Response>,
d4aeae5a
JB
32 opts: WorkerOptions = {}
33 ) {
c63a35a0 34 super(cluster.isPrimary, cluster.worker, taskFunctions, opts)
85aeb3f3
JB
35 }
36
37 /** @inheritDoc */
38 protected handleReadyMessage (message: MessageValue<Data>): void {
f05ed93c
JB
39 if (message.workerId === this.id && message.ready === false) {
40 try {
9d2d0da1 41 this.getMainWorker().on('message', this.messageListener.bind(this))
a5d15204
JB
42 this.sendToMainWorker({
43 ready: true,
3a502712 44 taskFunctionsProperties: this.listTaskFunctionsProperties(),
a5d15204 45 })
f05ed93c 46 } catch {
a5d15204
JB
47 this.sendToMainWorker({
48 ready: false,
3a502712 49 taskFunctionsProperties: this.listTaskFunctionsProperties(),
a5d15204 50 })
f05ed93c 51 }
85aeb3f3 52 }
f59e1027
JB
53 }
54
55 /** @inheritDoc */
56 protected get id (): number {
57 return this.getMainWorker().id
325f50bc
S
58 }
59
afc003b2 60 /** @inheritDoc */
803f948f
JB
61 protected readonly sendToMainWorker = (
62 message: MessageValue<Response>
63 ): void => {
fea198e8
JB
64 this.getMainWorker().send({
65 ...message,
3a502712 66 workerId: this.id,
fea198e8 67 } satisfies MessageValue<Response>)
325f50bc 68 }
325f50bc 69}