Commit | Line | Data |
---|---|---|
c97c7edb | 1 | import type { Worker } from 'cluster' |
325f50bc S |
2 | import { isMaster, worker } from 'cluster' |
3 | import type { MessageValue } from '../utility-types' | |
c97c7edb | 4 | import { AbstractWorker } from './abstract-worker' |
325f50bc S |
5 | import type { WorkerOptions } from './worker-options' |
6 | ||
7 | /** | |
8 | * An example worker that will be always alive, you just need to **extend** this class if you want a static pool. | |
9 | * | |
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. | |
12 | * | |
13 | * @author [Christopher Quadflieg](https://github.com/Shinigami92) | |
14 | * @since 2.0.0 | |
15 | */ | |
16 | // eslint-disable-next-line @typescript-eslint/no-explicit-any | |
c97c7edb S |
17 | export class ClusterWorker<Data = any, Response = any> extends AbstractWorker< |
18 | Worker, | |
19 | Data, | |
20 | Response | |
21 | > { | |
22 | public constructor (fn: (data: Data) => Response, opts: WorkerOptions = {}) { | |
23 | super('worker-cluster-pool:pioardi', isMaster, fn, opts) | |
325f50bc | 24 | |
325f50bc | 25 | worker.on('message', (value: MessageValue<Data>) => { |
325f50bc S |
26 | if (value?.data && value.id) { |
27 | // here you will receive messages | |
c97c7edb | 28 | // console.log('This is the main worker ' + isMain) |
325f50bc S |
29 | if (this.async) { |
30 | this.runInAsyncScope(this.runAsync.bind(this), this, fn, value) | |
31 | } else { | |
32 | this.runInAsyncScope(this.run.bind(this), this, fn, value) | |
33 | } | |
34 | } else if (value.kill) { | |
35 | // here is time to kill this worker, just clearing the interval | |
36 | if (this.interval) clearInterval(this.interval) | |
37 | this.emitDestroy() | |
38 | } | |
39 | }) | |
40 | } | |
41 | ||
c97c7edb S |
42 | protected getMainWorker (): Worker { |
43 | return worker | |
325f50bc S |
44 | } |
45 | ||
c97c7edb S |
46 | protected sendToMainWorker (message: MessageValue<Response>): void { |
47 | this.getMainWorker().send(message) | |
325f50bc S |
48 | } |
49 | ||
c97c7edb S |
50 | protected handleError (e: Error | string): string { |
51 | return e instanceof Error ? e.message : e | |
325f50bc S |
52 | } |
53 | } |