chore(deps-dev): bump tatami-ng to 0.6.0
[poolifier.git] / src / worker / cluster-worker.ts
... / ...
CommitLineData
1import cluster, { type Worker } from 'node:cluster'
2
3import type { MessageValue } from '../utility-types.js'
4import type { TaskFunction, TaskFunctions } from './task-functions.js'
5import type { WorkerOptions } from './worker-options.js'
6
7import { AbstractWorker } from './abstract-worker.js'
8
9/**
10 * A cluster worker used by a poolifier `ClusterPool`.
11 *
12 * When this worker is inactive for more than the given `maxInactiveTime`,
13 * it will send a termination request to its main worker.
14 *
15 * If you use a `DynamicClusterPool` the extra workers that were created will be terminated,
16 * but the minimum number of workers will be guaranteed.
17 * @typeParam Data - Type of data this worker receives from pool's execution. This can only be structured-cloneable data.
18 * @typeParam Response - Type of response the worker sends back to the main worker. This can only be structured-cloneable data.
19 * @author [Christopher Quadflieg](https://github.com/Shinigami92)
20 * @since 2.0.0
21 */
22export class ClusterWorker<
23 Data = unknown,
24 Response = unknown
25> extends AbstractWorker<Worker, Data, Response> {
26 /** @inheritDoc */
27 protected readonly sendToMainWorker = (
28 message: MessageValue<Response>
29 ): void => {
30 this.getMainWorker().send({
31 ...message,
32 workerId: this.id,
33 } satisfies MessageValue<Response>)
34 }
35
36 /**
37 * Constructs a new poolifier cluster worker.
38 * @param taskFunctions - Task function(s) processed by the worker when the pool's `execute` method is invoked.
39 * @param opts - Options for the worker.
40 */
41 public constructor (
42 taskFunctions: TaskFunction<Data, Response> | TaskFunctions<Data, Response>,
43 opts: WorkerOptions = {}
44 ) {
45 super(cluster.isPrimary, cluster.worker, taskFunctions, opts)
46 }
47
48 /** @inheritDoc */
49 protected handleReadyMessage (message: MessageValue<Data>): void {
50 if (message.workerId === this.id && message.ready === false) {
51 try {
52 this.getMainWorker().on('message', this.messageListener.bind(this))
53 this.sendToMainWorker({
54 ready: true,
55 taskFunctionsProperties: this.listTaskFunctionsProperties(),
56 })
57 } catch {
58 this.sendToMainWorker({
59 ready: false,
60 taskFunctionsProperties: this.listTaskFunctionsProperties(),
61 })
62 }
63 }
64 }
65
66 /** @inheritDoc */
67 protected get id (): number {
68 return this.getMainWorker().id
69 }
70}