Removed max tasks (#225)
[poolifier.git] / src / pools / cluster / fixed.ts
1 import { fork, isMaster, setupMaster, Worker } from 'cluster'
2 import type { MessageValue } from '../../utility-types'
3 import type { PoolOptions } from '../abstract-pool'
4 import { AbstractPool } from '../abstract-pool'
5
6 /**
7 * Options for a poolifier cluster pool.
8 */
9 export interface ClusterPoolOptions extends PoolOptions<Worker> {
10 /**
11 * Key/value pairs to add to worker process environment.
12 *
13 * @see https://nodejs.org/api/cluster.html#cluster_cluster_fork_env
14 */
15 // eslint-disable-next-line @typescript-eslint/no-explicit-any
16 env?: any
17 }
18
19 /**
20 * A cluster pool with a fixed number of workers.
21 *
22 * It is possible to perform tasks in sync or asynchronous mode as you prefer.
23 *
24 * This pool selects the workers in a round robin fashion.
25 *
26 * @template Data Type of data sent to the worker. This can only be serializable data.
27 * @template Response Type of response of execution. This can only be serializable data.
28 *
29 * @author [Christopher Quadflieg](https://github.com/Shinigami92)
30 * @since 2.0.0
31 */
32 export class FixedClusterPool<
33 Data = unknown,
34 Response = unknown
35 > extends AbstractPool<Worker, Data, Response> {
36 /**
37 * Constructs a new poolifier fixed cluster pool.
38 *
39 * @param numberOfWorkers Number of workers for this pool.
40 * @param filePath Path to an implementation of a `ClusterWorker` file, which can be relative or absolute.
41 * @param opts Options for this fixed cluster pool. Default: `{}`
42 */
43 public constructor (
44 numberOfWorkers: number,
45 filePath: string,
46 public readonly opts: ClusterPoolOptions = {}
47 ) {
48 super(numberOfWorkers, filePath, opts)
49 }
50
51 protected setupHook (): void {
52 setupMaster({
53 exec: this.filePath
54 })
55 }
56
57 protected isMain (): boolean {
58 return isMaster
59 }
60
61 /** @inheritdoc */
62 public destroyWorker (worker: Worker): void {
63 this.sendToWorker(worker, { kill: 1 })
64 worker.kill()
65 }
66
67 protected sendToWorker (worker: Worker, message: MessageValue<Data>): void {
68 worker.send(message)
69 }
70
71 /** @inheritdoc */
72 public registerWorkerMessageListener<Message extends Data | Response> (
73 worker: Worker,
74 listener: (message: MessageValue<Message>) => void
75 ): void {
76 worker.on('message', listener)
77 }
78
79 protected createWorker (): Worker {
80 return fork(this.opts.env)
81 }
82
83 protected afterWorkerSetup (worker: Worker): void {
84 // Listen worker messages.
85 this.registerWorkerMessageListener(worker, super.workerListener())
86 }
87 }