1 import type { Worker
} from
'cluster'
2 import { isMaster
, worker
} from
'cluster'
3 import type { MessageValue
} from
'../utility-types'
4 import { AbstractWorker
} from
'./abstract-worker'
5 import type { WorkerOptions
} from
'./worker-options'
8 * An example worker that will be always alive, you just need to **extend** this class if you want a static pool.
10 * When this worker is inactive for more than 1 minute, it will send this info to the main worker,
11 * if you are using DynamicClusterPool, the workers created after will be killed, the min num of worker will be guaranteed.
13 * @author [Christopher Quadflieg](https://github.com/Shinigami92)
16 // eslint-disable-next-line @typescript-eslint/no-explicit-any
17 export class ClusterWorker
<Data
= any, Response
= any> extends AbstractWorker
<
22 public constructor (fn
: (data
: Data
) => Response
, opts
: WorkerOptions
= {}) {
23 super('worker-cluster-pool:pioardi', isMaster
, fn
, opts
)
25 worker
.on('message', (value
: MessageValue
<Data
>) => {
26 if (value
?.data
&& value
.id
) {
27 // here you will receive messages
28 // console.log('This is the main worker ' + isMain)
30 this.runInAsyncScope(this.runAsync
.bind(this), this, fn
, value
)
32 this.runInAsyncScope(this.run
.bind(this), this, fn
, value
)
34 } else if (value
.kill
) {
35 // here is time to kill this worker, just clearing the interval
36 if (this.interval
) clearInterval(this.interval
)
42 protected getMainWorker (): Worker
{
46 protected sendToMainWorker (message
: MessageValue
<Response
>): void {
47 this.getMainWorker().send(message
)
50 protected handleError (e
: Error | string): string {
51 return e
instanceof Error ? e
.message
: e