perf: remove unneeded nullish check in hot code paths
[poolifier.git] / src / pools / abstract-pool.ts
CommitLineData
fc3e6586 1import crypto from 'node:crypto'
be0676b3
APA
2import type {
3 MessageValue,
4 PromiseWorkerResponseWrapper
5} from '../utility-types'
ed6dd37f 6import { EMPTY_FUNCTION } from '../utils'
34a0cfab 7import { KillBehaviors, isKillBehavior } from '../worker/worker-options'
bdaf31cd 8import type { PoolOptions } from './pool'
b4904890 9import { PoolEmitter } from './pool'
ffcbbad8 10import type { IPoolInternal, TasksUsage, WorkerType } from './pool-internal'
b4904890 11import { PoolType } from './pool-internal'
ea7a90d3 12import type { IPoolWorker } from './pool-worker'
a35560ba
S
13import {
14 WorkerChoiceStrategies,
63220255 15 type WorkerChoiceStrategy
bdaf31cd
JB
16} from './selection-strategies/selection-strategies-types'
17import { WorkerChoiceStrategyContext } from './selection-strategies/worker-choice-strategy-context'
c97c7edb 18
729c563d 19/**
ea7a90d3 20 * Base class that implements some shared logic for all poolifier pools.
729c563d 21 *
38e795c1
JB
22 * @typeParam Worker - Type of worker which manages this pool.
23 * @typeParam Data - Type of data sent to the worker. This can only be serializable data.
24 * @typeParam Response - Type of response of execution. This can only be serializable data.
729c563d 25 */
c97c7edb 26export abstract class AbstractPool<
ea7a90d3 27 Worker extends IPoolWorker,
d3c8a1a8
S
28 Data = unknown,
29 Response = unknown
9b2fdd9f 30> implements IPoolInternal<Worker, Data, Response> {
38e795c1 31 /** {@inheritDoc} */
e65c6cd9 32 public readonly workers: Array<WorkerType<Worker>> = []
4a6952ff 33
38e795c1 34 /** {@inheritDoc} */
7c0ba920
JB
35 public readonly emitter?: PoolEmitter
36
be0676b3
APA
37 /**
38 * The promise map.
39 *
ffcbbad8 40 * - `key`: This is the message id of each submitted task.
be0676b3
APA
41 * - `value`: An object that contains the worker, the resolve function and the reject function.
42 *
43 * When we receive a message from the worker we get a map entry and resolve/reject the promise based on the message.
44 */
45 protected promiseMap: Map<
b4e75778 46 string,
78cea37e 47 PromiseWorkerResponseWrapper<Worker, Response>
b4e75778 48 > = new Map<string, PromiseWorkerResponseWrapper<Worker, Response>>()
c97c7edb 49
a35560ba
S
50 /**
51 * Worker choice strategy instance implementing the worker choice algorithm.
52 *
53 * Default to a strategy implementing a round robin algorithm.
54 */
55 protected workerChoiceStrategyContext: WorkerChoiceStrategyContext<
78cea37e
JB
56 Worker,
57 Data,
58 Response
a35560ba
S
59 >
60
729c563d
S
61 /**
62 * Constructs a new poolifier pool.
63 *
38e795c1
JB
64 * @param numberOfWorkers - Number of workers that this pool should manage.
65 * @param filePath - Path to the worker-file.
66 * @param opts - Options for the pool.
729c563d 67 */
c97c7edb 68 public constructor (
5c5a1fb7 69 public readonly numberOfWorkers: number,
c97c7edb 70 public readonly filePath: string,
1927ee67 71 public readonly opts: PoolOptions<Worker>
c97c7edb 72 ) {
78cea37e 73 if (!this.isMain()) {
c97c7edb
S
74 throw new Error('Cannot start a pool from a worker!')
75 }
8d3782fa 76 this.checkNumberOfWorkers(this.numberOfWorkers)
c510fea7 77 this.checkFilePath(this.filePath)
7c0ba920 78 this.checkPoolOptions(this.opts)
c97c7edb
S
79 this.setupHook()
80
5c5a1fb7 81 for (let i = 1; i <= this.numberOfWorkers; i++) {
280c2a77 82 this.createAndSetupWorker()
c97c7edb
S
83 }
84
6bd72cd0 85 if (this.opts.enableEvents === true) {
7c0ba920
JB
86 this.emitter = new PoolEmitter()
87 }
a35560ba
S
88 this.workerChoiceStrategyContext = new WorkerChoiceStrategyContext(
89 this,
4a6952ff
JB
90 () => {
91 const workerCreated = this.createAndSetupWorker()
f3636726 92 this.registerWorkerMessageListener(workerCreated, message => {
4a6952ff
JB
93 if (
94 isKillBehavior(KillBehaviors.HARD, message.kill) ||
3032893a 95 this.getWorkerTasksUsage(workerCreated)?.running === 0
4a6952ff
JB
96 ) {
97 // Kill received from the worker, means that no new tasks are submitted to that worker for a while ( > maxInactiveTime)
a9d9ea34 98 void this.destroyWorker(workerCreated)
4a6952ff
JB
99 }
100 })
101 return workerCreated
102 },
e843b904 103 this.opts.workerChoiceStrategy
a35560ba 104 )
c97c7edb
S
105 }
106
a35560ba 107 private checkFilePath (filePath: string): void {
ffcbbad8
JB
108 if (
109 filePath == null ||
110 (typeof filePath === 'string' && filePath.trim().length === 0)
111 ) {
c510fea7
APA
112 throw new Error('Please specify a file with a worker implementation')
113 }
114 }
115
8d3782fa
JB
116 private checkNumberOfWorkers (numberOfWorkers: number): void {
117 if (numberOfWorkers == null) {
118 throw new Error(
119 'Cannot instantiate a pool without specifying the number of workers'
120 )
78cea37e 121 } else if (!Number.isSafeInteger(numberOfWorkers)) {
473c717a 122 throw new TypeError(
8d3782fa
JB
123 'Cannot instantiate a pool with a non integer number of workers'
124 )
125 } else if (numberOfWorkers < 0) {
473c717a 126 throw new RangeError(
8d3782fa
JB
127 'Cannot instantiate a pool with a negative number of workers'
128 )
7c0ba920 129 } else if (this.type === PoolType.FIXED && numberOfWorkers === 0) {
8d3782fa
JB
130 throw new Error('Cannot instantiate a fixed pool with no worker')
131 }
132 }
133
7c0ba920 134 private checkPoolOptions (opts: PoolOptions<Worker>): void {
e843b904
JB
135 this.opts.workerChoiceStrategy =
136 opts.workerChoiceStrategy ?? WorkerChoiceStrategies.ROUND_ROBIN
7c0ba920
JB
137 this.opts.enableEvents = opts.enableEvents ?? true
138 }
139
38e795c1 140 /** {@inheritDoc} */
7c0ba920
JB
141 public abstract get type (): PoolType
142
38e795c1 143 /** {@inheritDoc} */
7c0ba920
JB
144 public get numberOfRunningTasks (): number {
145 return this.promiseMap.size
a35560ba
S
146 }
147
ffcbbad8 148 /**
b4e75778 149 * Gets the given worker key.
ffcbbad8
JB
150 *
151 * @param worker - The worker.
152 * @returns The worker key.
153 */
e65c6cd9
JB
154 private getWorkerKey (worker: Worker): number {
155 return this.workers.findIndex(workerItem => workerItem.worker === worker)
bf9549ae
JB
156 }
157
38e795c1 158 /** {@inheritDoc} */
a35560ba
S
159 public setWorkerChoiceStrategy (
160 workerChoiceStrategy: WorkerChoiceStrategy
161 ): void {
b98ec2e6 162 this.opts.workerChoiceStrategy = workerChoiceStrategy
e65c6cd9
JB
163 for (const workerItem of this.workers) {
164 this.setWorker(workerItem.worker, {
ffcbbad8
JB
165 run: 0,
166 running: 0,
167 runTime: 0,
168 avgRunTime: 0
169 })
ea7a90d3 170 }
a35560ba
S
171 this.workerChoiceStrategyContext.setWorkerChoiceStrategy(
172 workerChoiceStrategy
173 )
174 }
175
38e795c1 176 /** {@inheritDoc} */
7c0ba920
JB
177 public abstract get busy (): boolean
178
179 protected internalGetBusyStatus (): boolean {
180 return (
181 this.numberOfRunningTasks >= this.numberOfWorkers &&
bdaf31cd 182 this.findFreeWorker() === false
7c0ba920
JB
183 )
184 }
185
38e795c1 186 /** {@inheritDoc} */
bdaf31cd 187 public findFreeWorker (): Worker | false {
e65c6cd9
JB
188 for (const workerItem of this.workers) {
189 if (workerItem.tasksUsage.running === 0) {
bdaf31cd 190 // A worker is free, return the matching worker
e65c6cd9 191 return workerItem.worker
7c0ba920
JB
192 }
193 }
194 return false
195 }
196
38e795c1 197 /** {@inheritDoc} */
78cea37e 198 public async execute (data: Data): Promise<Response> {
280c2a77 199 const worker = this.chooseWorker()
b4e75778
JB
200 const messageId = crypto.randomUUID()
201 const res = this.internalExecute(worker, messageId)
14916bf9 202 this.checkAndEmitBusy()
a05c10de 203 this.sendToWorker(worker, {
e5a5c0fc
JB
204 // eslint-disable-next-line @typescript-eslint/consistent-type-assertions
205 data: data ?? ({} as Data),
b4e75778 206 id: messageId
a05c10de 207 })
78cea37e 208 // eslint-disable-next-line @typescript-eslint/return-await
280c2a77
S
209 return res
210 }
c97c7edb 211
38e795c1 212 /** {@inheritDoc} */
c97c7edb 213 public async destroy (): Promise<void> {
1fbcaa7c 214 await Promise.all(
e65c6cd9
JB
215 this.workers.map(async workerItem => {
216 await this.destroyWorker(workerItem.worker)
1fbcaa7c
JB
217 })
218 )
c97c7edb
S
219 }
220
4a6952ff 221 /**
675bb809 222 * Shutdowns given worker.
4a6952ff 223 *
38e795c1 224 * @param worker - A worker within `workers`.
4a6952ff
JB
225 */
226 protected abstract destroyWorker (worker: Worker): void | Promise<void>
c97c7edb 227
729c563d 228 /**
280c2a77
S
229 * Setup hook that can be overridden by a Poolifier pool implementation
230 * to run code before workers are created in the abstract constructor.
729c563d 231 */
280c2a77
S
232 protected setupHook (): void {
233 // Can be overridden
234 }
c97c7edb 235
729c563d 236 /**
280c2a77
S
237 * Should return whether the worker is the main worker or not.
238 */
239 protected abstract isMain (): boolean
240
241 /**
bf9549ae
JB
242 * Hook executed before the worker task promise resolution.
243 * Can be overridden.
729c563d 244 *
38e795c1 245 * @param worker - The worker.
729c563d 246 */
bf9549ae 247 protected beforePromiseWorkerResponseHook (worker: Worker): void {
3032893a 248 ++(this.getWorkerTasksUsage(worker) as TasksUsage).running
c97c7edb
S
249 }
250
c01733f1 251 /**
bf9549ae
JB
252 * Hook executed after the worker task promise resolution.
253 * Can be overridden.
c01733f1 254 *
38e795c1
JB
255 * @param message - The received message.
256 * @param promise - The Promise response.
c01733f1 257 */
bf9549ae
JB
258 protected afterPromiseWorkerResponseHook (
259 message: MessageValue<Response>,
260 promise: PromiseWorkerResponseWrapper<Worker, Response>
261 ): void {
3032893a
JB
262 const workerTasksUsage = this.getWorkerTasksUsage(
263 promise.worker
264 ) as TasksUsage
265 --workerTasksUsage.running
266 ++workerTasksUsage.run
267 if (
268 this.workerChoiceStrategyContext.getWorkerChoiceStrategy()
269 .requiredStatistics.runTime
270 ) {
271 workerTasksUsage.runTime += message.taskRunTime ?? 0
272 if (workerTasksUsage.run !== 0) {
273 workerTasksUsage.avgRunTime =
274 workerTasksUsage.runTime / workerTasksUsage.run
275 }
276 }
c01733f1 277 }
278
729c563d
S
279 /**
280 * Removes the given worker from the pool.
281 *
38e795c1 282 * @param worker - The worker that will be removed.
729c563d 283 */
f2fdaa86 284 protected removeWorker (worker: Worker): void {
e65c6cd9 285 this.workers.splice(this.getWorkerKey(worker), 1)
f2fdaa86
JB
286 }
287
280c2a77 288 /**
675bb809 289 * Chooses a worker for the next task.
280c2a77
S
290 *
291 * The default implementation uses a round robin algorithm to distribute the load.
292 *
293 * @returns Worker.
294 */
295 protected chooseWorker (): Worker {
a35560ba 296 return this.workerChoiceStrategyContext.execute()
c97c7edb
S
297 }
298
280c2a77 299 /**
675bb809 300 * Sends a message to the given worker.
280c2a77 301 *
38e795c1
JB
302 * @param worker - The worker which should receive the message.
303 * @param message - The message.
280c2a77
S
304 */
305 protected abstract sendToWorker (
306 worker: Worker,
307 message: MessageValue<Data>
308 ): void
309
4a6952ff 310 /**
bdede008 311 * Registers a listener callback on a given worker.
4a6952ff 312 *
38e795c1
JB
313 * @param worker - The worker which should register a listener.
314 * @param listener - The message listener callback.
4a6952ff
JB
315 */
316 protected abstract registerWorkerMessageListener<
4f7fa42a 317 Message extends Data | Response
78cea37e 318 >(worker: Worker, listener: (message: MessageValue<Message>) => void): void
c97c7edb 319
729c563d
S
320 /**
321 * Returns a newly created worker.
322 */
280c2a77 323 protected abstract createWorker (): Worker
c97c7edb 324
729c563d
S
325 /**
326 * Function that can be hooked up when a worker has been newly created and moved to the workers registry.
327 *
38e795c1 328 * Can be used to update the `maxListeners` or binding the `main-worker`\<-\>`worker` connection if not bind by default.
729c563d 329 *
38e795c1 330 * @param worker - The newly created worker.
729c563d 331 */
280c2a77 332 protected abstract afterWorkerSetup (worker: Worker): void
c97c7edb 333
4a6952ff
JB
334 /**
335 * Creates a new worker for this pool and sets it up completely.
336 *
337 * @returns New, completely set up worker.
338 */
339 protected createAndSetupWorker (): Worker {
bdacc2d2 340 const worker = this.createWorker()
280c2a77 341
35cf1c03 342 worker.on('message', this.opts.messageHandler ?? EMPTY_FUNCTION)
a35560ba
S
343 worker.on('error', this.opts.errorHandler ?? EMPTY_FUNCTION)
344 worker.on('online', this.opts.onlineHandler ?? EMPTY_FUNCTION)
345 worker.on('exit', this.opts.exitHandler ?? EMPTY_FUNCTION)
a974afa6
JB
346 worker.once('exit', () => {
347 this.removeWorker(worker)
348 })
280c2a77 349
e65c6cd9 350 this.setWorker(worker, {
ffcbbad8
JB
351 run: 0,
352 running: 0,
353 runTime: 0,
354 avgRunTime: 0
355 })
280c2a77
S
356
357 this.afterWorkerSetup(worker)
358
c97c7edb
S
359 return worker
360 }
be0676b3
APA
361
362 /**
363 * This function is the listener registered for each worker.
364 *
bdacc2d2 365 * @returns The listener function to execute when a message is received from a worker.
be0676b3
APA
366 */
367 protected workerListener (): (message: MessageValue<Response>) => void {
4a6952ff 368 return message => {
bdacc2d2
JB
369 if (message.id !== undefined) {
370 const promise = this.promiseMap.get(message.id)
371 if (promise !== undefined) {
78cea37e 372 if (message.error != null) {
a05c10de
JB
373 promise.reject(message.error)
374 } else {
375 promise.resolve(message.data as Response)
376 }
bf9549ae 377 this.afterPromiseWorkerResponseHook(message, promise)
be0676b3
APA
378 this.promiseMap.delete(message.id)
379 }
380 }
381 }
be0676b3 382 }
7c0ba920 383
78cea37e
JB
384 private async internalExecute (
385 worker: Worker,
b4e75778 386 messageId: string
78cea37e
JB
387 ): Promise<Response> {
388 this.beforePromiseWorkerResponseHook(worker)
389 return await new Promise<Response>((resolve, reject) => {
390 this.promiseMap.set(messageId, { resolve, reject, worker })
391 })
392 }
393
7c0ba920 394 private checkAndEmitBusy (): void {
78cea37e 395 if (this.opts.enableEvents === true && this.busy) {
7c0ba920
JB
396 this.emitter?.emit('busy')
397 }
398 }
bf9549ae 399
3032893a
JB
400 /** {@inheritDoc} */
401 public getWorkerTasksUsage (worker: Worker): TasksUsage | undefined {
402 const workerKey = this.getWorkerKey(worker)
e65c6cd9
JB
403 if (workerKey !== -1) {
404 return this.workers[workerKey].tasksUsage
ffcbbad8 405 }
3032893a 406 throw new Error('Worker could not be found in the pool')
a05c10de
JB
407 }
408
409 /**
ffcbbad8 410 * Sets the given worker.
ea7a90d3 411 *
38e795c1 412 * @param worker - The worker.
ffcbbad8 413 * @param tasksUsage - The worker tasks usage.
ea7a90d3 414 */
e65c6cd9
JB
415 private setWorker (worker: Worker, tasksUsage: TasksUsage): void {
416 this.workers.push({
ffcbbad8
JB
417 worker,
418 tasksUsage
ea7a90d3
JB
419 })
420 }
c97c7edb 421}