Clean worker from pool after it was destroyed (#146)
[poolifier.git] / src / pools / cluster / fixed.ts
1 import { fork, isMaster, setupMaster, Worker } from 'cluster'
2 import type { JSONValue, 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.
27 * @template Response Type of response of execution.
28 *
29 * @author [Christopher Quadflieg](https://github.com/Shinigami92)
30 * @since 2.0.0
31 */
32 export class FixedClusterPool<
33 Data extends JSONValue = JSONValue,
34 Response extends JSONValue = JSONValue
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: `{ maxTasks: 1000 }`
42 */
43 public constructor (
44 numberOfWorkers: number,
45 filePath: string,
46 public readonly opts: ClusterPoolOptions = { maxTasks: 1000 }
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 protected destroyWorker (worker: Worker): void {
62 worker.kill()
63 }
64
65 protected sendToWorker (worker: Worker, message: MessageValue<Data>): void {
66 worker.send(message)
67 }
68
69 protected registerWorkerMessageListener (
70 port: Worker,
71 listener: (message: MessageValue<Response>) => void
72 ): void {
73 port.on('message', listener)
74 }
75
76 protected unregisterWorkerMessageListener (
77 port: Worker,
78 listener: (message: MessageValue<Response>) => void
79 ): void {
80 port.removeListener('message', listener)
81 }
82
83 protected createWorker (): Worker {
84 return fork(this.opts.env)
85 }
86
87 protected afterWorkerSetup (worker: Worker): void {
88 // we will attach a listener for every task,
89 // when task is completed the listener will be removed but to avoid warnings we are increasing the max listeners size
90 worker.setMaxListeners(this.opts.maxTasks ?? 1000)
91 }
92 }