9402ec1044e51ce9a42c8717e3c6c506dda1ac10
[poolifier.git] / src / worker / cluster-worker.ts
1 import type { Worker } from 'cluster'
2 import { isMaster, worker } from 'cluster'
3 import type { JSONValue, MessageValue } from '../utility-types'
4 import { AbstractWorker } from './abstract-worker'
5 import type { WorkerOptions } from './worker-options'
6
7 /**
8 * A cluster worker used by a poolifier `ClusterPool`.
9 *
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 *
16 * @template Data Type of data this worker receives from pool's execution.
17 * @template Response Type of response the worker sends back to the main worker.
18 *
19 * @author [Christopher Quadflieg](https://github.com/Shinigami92)
20 * @since 2.0.0
21 */
22 export class ClusterWorker<
23 Data extends JSONValue = JSONValue,
24 Response extends JSONValue = JSONValue
25 > extends AbstractWorker<Worker, Data, Response> {
26 /**
27 * Constructs a new poolifier cluster worker.
28 *
29 * @param fn Function processed by the worker when the pool's `execution` function is invoked.
30 * @param opts Options for the worker.
31 */
32 public constructor (fn: (data: Data) => Response, opts: WorkerOptions = {}) {
33 super('worker-cluster-pool:pioardi', isMaster, fn, opts)
34
35 worker.on('message', (value: MessageValue<Data>) => {
36 if (value?.data && value.id) {
37 // here you will receive messages
38 // console.log('This is the main worker ' + isMaster)
39 if (this.async) {
40 this.runInAsyncScope(this.runAsync.bind(this), this, fn, value)
41 } else {
42 this.runInAsyncScope(this.run.bind(this), this, fn, value)
43 }
44 } else if (value.kill) {
45 // here is time to kill this worker, just clearing the interval
46 if (this.interval) clearInterval(this.interval)
47 this.emitDestroy()
48 }
49 })
50 }
51
52 protected getMainWorker (): Worker {
53 return worker
54 }
55
56 protected sendToMainWorker (message: MessageValue<Response>): void {
57 this.getMainWorker().send(message)
58 }
59
60 protected handleError (e: Error | string): string {
61 return e instanceof Error ? e.message : e
62 }
63 }