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