feat: allow to disable tasks timeout check in worker
[poolifier.git] / src / pools / abstract-pool.ts
CommitLineData
fc3e6586 1import crypto from 'node:crypto'
2740a743 2import type { MessageValue, PromiseResponseWrapper } from '../utility-types'
bbeadd16
JB
3import {
4 DEFAULT_WORKER_CHOICE_STRATEGY_OPTIONS,
5 EMPTY_FUNCTION,
0d80593b 6 isPlainObject,
bbeadd16
JB
7 median
8} from '../utils'
34a0cfab 9import { KillBehaviors, isKillBehavior } from '../worker/worker-options'
65d7a1c9 10import { CircularArray } from '../circular-array'
29ee7e9a 11import { Queue } from '../queue'
c4855468 12import {
65d7a1c9 13 type IPool,
7c5a1080 14 PoolEmitter,
c4855468 15 PoolEvents,
c4855468 16 type PoolOptions,
65d7a1c9
JB
17 PoolType,
18 type TasksQueueOptions
c4855468 19} from './pool'
f06e48d8 20import type { IWorker, Task, TasksUsage, WorkerNode } from './worker'
a35560ba
S
21import {
22 WorkerChoiceStrategies,
a20f0ba5
JB
23 type WorkerChoiceStrategy,
24 type WorkerChoiceStrategyOptions
bdaf31cd
JB
25} from './selection-strategies/selection-strategies-types'
26import { WorkerChoiceStrategyContext } from './selection-strategies/worker-choice-strategy-context'
c97c7edb 27
729c563d 28/**
ea7a90d3 29 * Base class that implements some shared logic for all poolifier pools.
729c563d 30 *
38e795c1
JB
31 * @typeParam Worker - Type of worker which manages this pool.
32 * @typeParam Data - Type of data sent to the worker. This can only be serializable data.
02706357 33 * @typeParam Response - Type of execution response. This can only be serializable data.
729c563d 34 */
c97c7edb 35export abstract class AbstractPool<
f06e48d8 36 Worker extends IWorker,
d3c8a1a8
S
37 Data = unknown,
38 Response = unknown
c4855468 39> implements IPool<Worker, Data, Response> {
afc003b2 40 /** @inheritDoc */
f06e48d8 41 public readonly workerNodes: Array<WorkerNode<Worker, Data>> = []
4a6952ff 42
afc003b2 43 /** @inheritDoc */
7c0ba920
JB
44 public readonly emitter?: PoolEmitter
45
be0676b3 46 /**
a3445496 47 * The execution response promise map.
be0676b3 48 *
2740a743 49 * - `key`: The message id of each submitted task.
a3445496 50 * - `value`: An object that contains the worker, the execution response promise resolve and reject callbacks.
be0676b3 51 *
a3445496 52 * When we receive a message from the worker, we get a map entry with the promise resolve/reject bound to the message id.
be0676b3 53 */
c923ce56
JB
54 protected promiseResponseMap: Map<
55 string,
56 PromiseResponseWrapper<Worker, Response>
57 > = new Map<string, PromiseResponseWrapper<Worker, Response>>()
c97c7edb 58
a35560ba 59 /**
51fe3d3c 60 * Worker choice strategy context referencing a worker choice algorithm implementation.
a35560ba 61 *
51fe3d3c 62 * Default to a round robin algorithm.
a35560ba
S
63 */
64 protected workerChoiceStrategyContext: WorkerChoiceStrategyContext<
78cea37e
JB
65 Worker,
66 Data,
67 Response
a35560ba
S
68 >
69
729c563d
S
70 /**
71 * Constructs a new poolifier pool.
72 *
38e795c1 73 * @param numberOfWorkers - Number of workers that this pool should manage.
029715f0 74 * @param filePath - Path to the worker file.
38e795c1 75 * @param opts - Options for the pool.
729c563d 76 */
c97c7edb 77 public constructor (
5c5a1fb7 78 public readonly numberOfWorkers: number,
c97c7edb 79 public readonly filePath: string,
1927ee67 80 public readonly opts: PoolOptions<Worker>
c97c7edb 81 ) {
78cea37e 82 if (!this.isMain()) {
c97c7edb
S
83 throw new Error('Cannot start a pool from a worker!')
84 }
8d3782fa 85 this.checkNumberOfWorkers(this.numberOfWorkers)
c510fea7 86 this.checkFilePath(this.filePath)
7c0ba920 87 this.checkPoolOptions(this.opts)
1086026a 88
7254e419
JB
89 this.chooseWorkerNode = this.chooseWorkerNode.bind(this)
90 this.executeTask = this.executeTask.bind(this)
91 this.enqueueTask = this.enqueueTask.bind(this)
92 this.checkAndEmitEvents = this.checkAndEmitEvents.bind(this)
1086026a 93
c97c7edb
S
94 this.setupHook()
95
5c5a1fb7 96 for (let i = 1; i <= this.numberOfWorkers; i++) {
280c2a77 97 this.createAndSetupWorker()
c97c7edb
S
98 }
99
6bd72cd0 100 if (this.opts.enableEvents === true) {
7c0ba920
JB
101 this.emitter = new PoolEmitter()
102 }
d59df138
JB
103 this.workerChoiceStrategyContext = new WorkerChoiceStrategyContext<
104 Worker,
105 Data,
106 Response
da309861
JB
107 >(
108 this,
109 this.opts.workerChoiceStrategy,
110 this.opts.workerChoiceStrategyOptions
111 )
c97c7edb
S
112 }
113
a35560ba 114 private checkFilePath (filePath: string): void {
ffcbbad8
JB
115 if (
116 filePath == null ||
117 (typeof filePath === 'string' && filePath.trim().length === 0)
118 ) {
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(
0d80593b 130 'Cannot instantiate a pool with a non safe integer number of workers'
8d3782fa
JB
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 {
0d80593b
JB
142 if (isPlainObject(opts)) {
143 this.opts.workerChoiceStrategy =
144 opts.workerChoiceStrategy ?? WorkerChoiceStrategies.ROUND_ROBIN
145 this.checkValidWorkerChoiceStrategy(this.opts.workerChoiceStrategy)
146 this.opts.workerChoiceStrategyOptions =
147 opts.workerChoiceStrategyOptions ??
148 DEFAULT_WORKER_CHOICE_STRATEGY_OPTIONS
49be33fe
JB
149 this.checkValidWorkerChoiceStrategyOptions(
150 this.opts.workerChoiceStrategyOptions
151 )
0d80593b
JB
152 this.opts.enableEvents = opts.enableEvents ?? true
153 this.opts.enableTasksQueue = opts.enableTasksQueue ?? false
154 if (this.opts.enableTasksQueue) {
155 this.checkValidTasksQueueOptions(
156 opts.tasksQueueOptions as TasksQueueOptions
157 )
158 this.opts.tasksQueueOptions = this.buildTasksQueueOptions(
159 opts.tasksQueueOptions as TasksQueueOptions
160 )
161 }
162 } else {
163 throw new TypeError('Invalid pool options: must be a plain object')
7171d33f 164 }
aee46736
JB
165 }
166
167 private checkValidWorkerChoiceStrategy (
168 workerChoiceStrategy: WorkerChoiceStrategy
169 ): void {
170 if (!Object.values(WorkerChoiceStrategies).includes(workerChoiceStrategy)) {
b529c323 171 throw new Error(
aee46736 172 `Invalid worker choice strategy '${workerChoiceStrategy}'`
b529c323
JB
173 )
174 }
7c0ba920
JB
175 }
176
0d80593b
JB
177 private checkValidWorkerChoiceStrategyOptions (
178 workerChoiceStrategyOptions: WorkerChoiceStrategyOptions
179 ): void {
180 if (!isPlainObject(workerChoiceStrategyOptions)) {
181 throw new TypeError(
182 'Invalid worker choice strategy options: must be a plain object'
183 )
184 }
49be33fe
JB
185 if (
186 workerChoiceStrategyOptions.weights != null &&
187 Object.keys(workerChoiceStrategyOptions.weights).length !== this.size
188 ) {
189 throw new Error(
190 'Invalid worker choice strategy options: must have a weight for each worker node'
191 )
192 }
0d80593b
JB
193 }
194
a20f0ba5
JB
195 private checkValidTasksQueueOptions (
196 tasksQueueOptions: TasksQueueOptions
197 ): void {
0d80593b
JB
198 if (tasksQueueOptions != null && !isPlainObject(tasksQueueOptions)) {
199 throw new TypeError('Invalid tasks queue options: must be a plain object')
200 }
a20f0ba5
JB
201 if ((tasksQueueOptions?.concurrency as number) <= 0) {
202 throw new Error(
203 `Invalid worker tasks concurrency '${
204 tasksQueueOptions.concurrency as number
205 }'`
206 )
207 }
208 }
209
afc003b2 210 /** @inheritDoc */
7c0ba920
JB
211 public abstract get type (): PoolType
212
08f3f44c
JB
213 /** @inheritDoc */
214 public abstract get size (): number
215
c2ade475 216 /**
ff733df7 217 * Number of tasks running in the pool.
c2ade475
JB
218 */
219 private get numberOfRunningTasks (): number {
ff733df7
JB
220 return this.workerNodes.reduce(
221 (accumulator, workerNode) => accumulator + workerNode.tasksUsage.running,
222 0
223 )
224 }
225
226 /**
227 * Number of tasks queued in the pool.
228 */
229 private get numberOfQueuedTasks (): number {
230 if (this.opts.enableTasksQueue === false) {
231 return 0
232 }
233 return this.workerNodes.reduce(
4d8bf9e4 234 (accumulator, workerNode) => accumulator + workerNode.tasksQueue.size,
ff733df7
JB
235 0
236 )
a35560ba
S
237 }
238
ffcbbad8 239 /**
f06e48d8 240 * Gets the given worker its worker node key.
ffcbbad8
JB
241 *
242 * @param worker - The worker.
f06e48d8 243 * @returns The worker node key if the worker is found in the pool worker nodes, `-1` otherwise.
ffcbbad8 244 */
f06e48d8
JB
245 private getWorkerNodeKey (worker: Worker): number {
246 return this.workerNodes.findIndex(
247 workerNode => workerNode.worker === worker
248 )
bf9549ae
JB
249 }
250
afc003b2 251 /** @inheritDoc */
a35560ba 252 public setWorkerChoiceStrategy (
59219cbb
JB
253 workerChoiceStrategy: WorkerChoiceStrategy,
254 workerChoiceStrategyOptions?: WorkerChoiceStrategyOptions
a35560ba 255 ): void {
aee46736 256 this.checkValidWorkerChoiceStrategy(workerChoiceStrategy)
b98ec2e6 257 this.opts.workerChoiceStrategy = workerChoiceStrategy
0ebe2a9f 258 for (const workerNode of this.workerNodes) {
f82cd357
JB
259 this.setWorkerNodeTasksUsage(workerNode, {
260 run: 0,
261 running: 0,
262 runTime: 0,
263 runTimeHistory: new CircularArray(),
264 avgRunTime: 0,
265 medRunTime: 0,
0567595a
JB
266 waitTime: 0,
267 waitTimeHistory: new CircularArray(),
268 avgWaitTime: 0,
269 medWaitTime: 0,
f82cd357
JB
270 error: 0
271 })
ea7a90d3 272 }
a35560ba 273 this.workerChoiceStrategyContext.setWorkerChoiceStrategy(
a20f0ba5
JB
274 this.opts.workerChoiceStrategy
275 )
59219cbb
JB
276 if (workerChoiceStrategyOptions != null) {
277 this.setWorkerChoiceStrategyOptions(workerChoiceStrategyOptions)
278 }
a20f0ba5
JB
279 }
280
281 /** @inheritDoc */
282 public setWorkerChoiceStrategyOptions (
283 workerChoiceStrategyOptions: WorkerChoiceStrategyOptions
284 ): void {
0d80593b 285 this.checkValidWorkerChoiceStrategyOptions(workerChoiceStrategyOptions)
a20f0ba5
JB
286 this.opts.workerChoiceStrategyOptions = workerChoiceStrategyOptions
287 this.workerChoiceStrategyContext.setOptions(
288 this.opts.workerChoiceStrategyOptions
a35560ba
S
289 )
290 }
291
a20f0ba5 292 /** @inheritDoc */
8f52842f
JB
293 public enableTasksQueue (
294 enable: boolean,
295 tasksQueueOptions?: TasksQueueOptions
296 ): void {
a20f0ba5 297 if (this.opts.enableTasksQueue === true && !enable) {
ef41a6e6 298 this.flushTasksQueues()
a20f0ba5
JB
299 }
300 this.opts.enableTasksQueue = enable
8f52842f 301 this.setTasksQueueOptions(tasksQueueOptions as TasksQueueOptions)
a20f0ba5
JB
302 }
303
304 /** @inheritDoc */
8f52842f 305 public setTasksQueueOptions (tasksQueueOptions: TasksQueueOptions): void {
a20f0ba5 306 if (this.opts.enableTasksQueue === true) {
8f52842f
JB
307 this.checkValidTasksQueueOptions(tasksQueueOptions)
308 this.opts.tasksQueueOptions =
309 this.buildTasksQueueOptions(tasksQueueOptions)
a20f0ba5
JB
310 } else {
311 delete this.opts.tasksQueueOptions
312 }
313 }
314
315 private buildTasksQueueOptions (
316 tasksQueueOptions: TasksQueueOptions
317 ): TasksQueueOptions {
318 return {
319 concurrency: tasksQueueOptions?.concurrency ?? 1
320 }
321 }
322
c319c66b
JB
323 /**
324 * Whether the pool is full or not.
325 *
326 * The pool filling boolean status.
327 */
328 protected abstract get full (): boolean
c2ade475 329
c319c66b
JB
330 /**
331 * Whether the pool is busy or not.
332 *
333 * The pool busyness boolean status.
334 */
335 protected abstract get busy (): boolean
7c0ba920 336
c2ade475 337 protected internalBusy (): boolean {
e0ae6100
JB
338 return (
339 this.workerNodes.findIndex(workerNode => {
a4958de2 340 return workerNode.tasksUsage.running === 0
e0ae6100
JB
341 }) === -1
342 )
cb70b19d
JB
343 }
344
afc003b2 345 /** @inheritDoc */
a86b6df1 346 public async execute (data?: Data, name?: string): Promise<Response> {
0567595a 347 const submissionTimestamp = performance.now()
20dcad1a 348 const workerNodeKey = this.chooseWorkerNode()
adc3c320 349 const submittedTask: Task<Data> = {
a86b6df1 350 name,
e5a5c0fc
JB
351 // eslint-disable-next-line @typescript-eslint/consistent-type-assertions
352 data: data ?? ({} as Data),
0567595a 353 submissionTimestamp,
adc3c320
JB
354 id: crypto.randomUUID()
355 }
2e81254d 356 const res = new Promise<Response>((resolve, reject) => {
02706357 357 this.promiseResponseMap.set(submittedTask.id as string, {
2e81254d
JB
358 resolve,
359 reject,
20dcad1a 360 worker: this.workerNodes[workerNodeKey].worker
2e81254d
JB
361 })
362 })
ff733df7
JB
363 if (
364 this.opts.enableTasksQueue === true &&
7171d33f 365 (this.busy ||
3528c992 366 this.workerNodes[workerNodeKey].tasksUsage.running >=
7171d33f 367 ((this.opts.tasksQueueOptions as TasksQueueOptions)
3528c992 368 .concurrency as number))
ff733df7 369 ) {
26a929d7
JB
370 this.enqueueTask(workerNodeKey, submittedTask)
371 } else {
2e81254d 372 this.executeTask(workerNodeKey, submittedTask)
adc3c320 373 }
b0d6ed8f 374 this.workerChoiceStrategyContext.update(workerNodeKey)
ff733df7 375 this.checkAndEmitEvents()
78cea37e 376 // eslint-disable-next-line @typescript-eslint/return-await
280c2a77
S
377 return res
378 }
c97c7edb 379
afc003b2 380 /** @inheritDoc */
c97c7edb 381 public async destroy (): Promise<void> {
1fbcaa7c 382 await Promise.all(
875a7c37
JB
383 this.workerNodes.map(async (workerNode, workerNodeKey) => {
384 this.flushTasksQueue(workerNodeKey)
f06e48d8 385 await this.destroyWorker(workerNode.worker)
1fbcaa7c
JB
386 })
387 )
c97c7edb
S
388 }
389
4a6952ff 390 /**
f06e48d8 391 * Shutdowns the given worker.
4a6952ff 392 *
f06e48d8 393 * @param worker - A worker within `workerNodes`.
4a6952ff
JB
394 */
395 protected abstract destroyWorker (worker: Worker): void | Promise<void>
c97c7edb 396
729c563d 397 /**
2e81254d 398 * Setup hook to execute code before worker node are created in the abstract constructor.
d99ba5a8 399 * Can be overridden
afc003b2
JB
400 *
401 * @virtual
729c563d 402 */
280c2a77 403 protected setupHook (): void {
d99ba5a8 404 // Intentionally empty
280c2a77 405 }
c97c7edb 406
729c563d 407 /**
280c2a77
S
408 * Should return whether the worker is the main worker or not.
409 */
410 protected abstract isMain (): boolean
411
412 /**
2e81254d 413 * Hook executed before the worker task execution.
bf9549ae 414 * Can be overridden.
729c563d 415 *
f06e48d8 416 * @param workerNodeKey - The worker node key.
729c563d 417 */
f20f344f 418 protected beforeTaskExecutionHook (workerNodeKey: number): void {
09a6305f 419 ++this.workerNodes[workerNodeKey].tasksUsage.running
c97c7edb
S
420 }
421
c01733f1 422 /**
2e81254d 423 * Hook executed after the worker task execution.
bf9549ae 424 * Can be overridden.
c01733f1 425 *
c923ce56 426 * @param worker - The worker.
38e795c1 427 * @param message - The received message.
c01733f1 428 */
2e81254d 429 protected afterTaskExecutionHook (
c923ce56 430 worker: Worker,
2740a743 431 message: MessageValue<Response>
bf9549ae 432 ): void {
f8eb0a2a
JB
433 const workerTasksUsage =
434 this.workerNodes[this.getWorkerNodeKey(worker)].tasksUsage
3032893a
JB
435 --workerTasksUsage.running
436 ++workerTasksUsage.run
2740a743
JB
437 if (message.error != null) {
438 ++workerTasksUsage.error
439 }
f8eb0a2a 440 this.updateRunTimeTasksUsage(workerTasksUsage, message)
74001280 441 this.updateWaitTimeTasksUsage(workerTasksUsage, message)
f8eb0a2a
JB
442 }
443
444 private updateRunTimeTasksUsage (
445 workerTasksUsage: TasksUsage,
446 message: MessageValue<Response>
447 ): void {
97a2abc3 448 if (this.workerChoiceStrategyContext.getRequiredStatistics().runTime) {
aee46736 449 workerTasksUsage.runTime += message.runTime ?? 0
c6bd2650
JB
450 if (
451 this.workerChoiceStrategyContext.getRequiredStatistics().avgRunTime &&
452 workerTasksUsage.run !== 0
453 ) {
3032893a
JB
454 workerTasksUsage.avgRunTime =
455 workerTasksUsage.runTime / workerTasksUsage.run
456 }
3fa4cdd2
JB
457 if (
458 this.workerChoiceStrategyContext.getRequiredStatistics().medRunTime &&
459 message.runTime != null
460 ) {
461 workerTasksUsage.runTimeHistory.push(message.runTime)
78099a15
JB
462 workerTasksUsage.medRunTime = median(workerTasksUsage.runTimeHistory)
463 }
3032893a 464 }
f8eb0a2a
JB
465 }
466
74001280 467 private updateWaitTimeTasksUsage (
f8eb0a2a
JB
468 workerTasksUsage: TasksUsage,
469 message: MessageValue<Response>
470 ): void {
09a6305f
JB
471 if (this.workerChoiceStrategyContext.getRequiredStatistics().waitTime) {
472 workerTasksUsage.waitTime += message.waitTime ?? 0
473 if (
474 this.workerChoiceStrategyContext.getRequiredStatistics().avgWaitTime &&
475 workerTasksUsage.run !== 0
476 ) {
477 workerTasksUsage.avgWaitTime =
478 workerTasksUsage.waitTime / workerTasksUsage.run
479 }
480 if (
481 this.workerChoiceStrategyContext.getRequiredStatistics().medWaitTime &&
482 message.waitTime != null
483 ) {
484 workerTasksUsage.waitTimeHistory.push(message.waitTime)
485 workerTasksUsage.medWaitTime = median(workerTasksUsage.waitTimeHistory)
486 }
0567595a 487 }
c01733f1 488 }
489
280c2a77 490 /**
f06e48d8 491 * Chooses a worker node for the next task.
280c2a77 492 *
20dcad1a 493 * The default worker choice strategy uses a round robin algorithm to distribute the load.
280c2a77 494 *
20dcad1a 495 * @returns The worker node key
280c2a77 496 */
20dcad1a 497 protected chooseWorkerNode (): number {
f06e48d8 498 let workerNodeKey: number
0527b6db 499 if (this.type === PoolType.DYNAMIC && !this.full && this.internalBusy()) {
adc3c320
JB
500 const workerCreated = this.createAndSetupWorker()
501 this.registerWorkerMessageListener(workerCreated, message => {
a4958de2 502 const currentWorkerNodeKey = this.getWorkerNodeKey(workerCreated)
17393ac8
JB
503 if (
504 isKillBehavior(KillBehaviors.HARD, message.kill) ||
d2097c13 505 (message.kill != null &&
a4958de2 506 this.workerNodes[currentWorkerNodeKey].tasksUsage.running === 0)
17393ac8 507 ) {
ff733df7 508 // Kill message received from the worker: no new tasks are submitted to that worker for a while ( > maxInactiveTime)
a4958de2 509 this.flushTasksQueue(currentWorkerNodeKey)
7c5a1080 510 void (this.destroyWorker(workerCreated) as Promise<void>)
17393ac8
JB
511 }
512 })
adc3c320 513 workerNodeKey = this.getWorkerNodeKey(workerCreated)
17393ac8 514 } else {
f06e48d8 515 workerNodeKey = this.workerChoiceStrategyContext.execute()
17393ac8 516 }
20dcad1a 517 return workerNodeKey
c97c7edb
S
518 }
519
280c2a77 520 /**
675bb809 521 * Sends a message to the given worker.
280c2a77 522 *
38e795c1
JB
523 * @param worker - The worker which should receive the message.
524 * @param message - The message.
280c2a77
S
525 */
526 protected abstract sendToWorker (
527 worker: Worker,
528 message: MessageValue<Data>
529 ): void
530
4a6952ff 531 /**
f06e48d8 532 * Registers a listener callback on the given worker.
4a6952ff 533 *
38e795c1
JB
534 * @param worker - The worker which should register a listener.
535 * @param listener - The message listener callback.
4a6952ff
JB
536 */
537 protected abstract registerWorkerMessageListener<
4f7fa42a 538 Message extends Data | Response
78cea37e 539 >(worker: Worker, listener: (message: MessageValue<Message>) => void): void
c97c7edb 540
729c563d
S
541 /**
542 * Returns a newly created worker.
543 */
280c2a77 544 protected abstract createWorker (): Worker
c97c7edb 545
729c563d 546 /**
f06e48d8 547 * Function that can be hooked up when a worker has been newly created and moved to the pool worker nodes.
729c563d 548 *
38e795c1 549 * Can be used to update the `maxListeners` or binding the `main-worker`\<-\>`worker` connection if not bind by default.
729c563d 550 *
38e795c1 551 * @param worker - The newly created worker.
729c563d 552 */
280c2a77 553 protected abstract afterWorkerSetup (worker: Worker): void
c97c7edb 554
4a6952ff 555 /**
f06e48d8 556 * Creates a new worker and sets it up completely in the pool worker nodes.
4a6952ff
JB
557 *
558 * @returns New, completely set up worker.
559 */
560 protected createAndSetupWorker (): Worker {
bdacc2d2 561 const worker = this.createWorker()
280c2a77 562
35cf1c03 563 worker.on('message', this.opts.messageHandler ?? EMPTY_FUNCTION)
a35560ba
S
564 worker.on('error', this.opts.errorHandler ?? EMPTY_FUNCTION)
565 worker.on('online', this.opts.onlineHandler ?? EMPTY_FUNCTION)
566 worker.on('exit', this.opts.exitHandler ?? EMPTY_FUNCTION)
a974afa6 567 worker.once('exit', () => {
f06e48d8 568 this.removeWorkerNode(worker)
a974afa6 569 })
280c2a77 570
f06e48d8 571 this.pushWorkerNode(worker)
280c2a77
S
572
573 this.afterWorkerSetup(worker)
574
c97c7edb
S
575 return worker
576 }
be0676b3
APA
577
578 /**
ff733df7 579 * This function is the listener registered for each worker message.
be0676b3 580 *
bdacc2d2 581 * @returns The listener function to execute when a message is received from a worker.
be0676b3
APA
582 */
583 protected workerListener (): (message: MessageValue<Response>) => void {
4a6952ff 584 return message => {
b1989cfd 585 if (message.id != null) {
a3445496 586 // Task execution response received
2740a743 587 const promiseResponse = this.promiseResponseMap.get(message.id)
b1989cfd 588 if (promiseResponse != null) {
78cea37e 589 if (message.error != null) {
2740a743 590 promiseResponse.reject(message.error)
a05c10de 591 } else {
2740a743 592 promiseResponse.resolve(message.data as Response)
a05c10de 593 }
2e81254d 594 this.afterTaskExecutionHook(promiseResponse.worker, message)
2740a743 595 this.promiseResponseMap.delete(message.id)
ff733df7
JB
596 const workerNodeKey = this.getWorkerNodeKey(promiseResponse.worker)
597 if (
598 this.opts.enableTasksQueue === true &&
416fd65c 599 this.tasksQueueSize(workerNodeKey) > 0
ff733df7 600 ) {
2e81254d
JB
601 this.executeTask(
602 workerNodeKey,
ff733df7
JB
603 this.dequeueTask(workerNodeKey) as Task<Data>
604 )
605 }
be0676b3
APA
606 }
607 }
608 }
be0676b3 609 }
7c0ba920 610
ff733df7
JB
611 private checkAndEmitEvents (): void {
612 if (this.opts.enableEvents === true) {
613 if (this.busy) {
614 this.emitter?.emit(PoolEvents.busy)
615 }
616 if (this.type === PoolType.DYNAMIC && this.full) {
617 this.emitter?.emit(PoolEvents.full)
618 }
164d950a
JB
619 }
620 }
621
0ebe2a9f
JB
622 /**
623 * Sets the given worker node its tasks usage in the pool.
624 *
625 * @param workerNode - The worker node.
626 * @param tasksUsage - The worker node tasks usage.
627 */
628 private setWorkerNodeTasksUsage (
629 workerNode: WorkerNode<Worker, Data>,
630 tasksUsage: TasksUsage
631 ): void {
632 workerNode.tasksUsage = tasksUsage
633 }
634
a05c10de 635 /**
f06e48d8 636 * Pushes the given worker in the pool worker nodes.
ea7a90d3 637 *
38e795c1 638 * @param worker - The worker.
f06e48d8 639 * @returns The worker nodes length.
ea7a90d3 640 */
f06e48d8
JB
641 private pushWorkerNode (worker: Worker): number {
642 return this.workerNodes.push({
ffcbbad8 643 worker,
f82cd357
JB
644 tasksUsage: {
645 run: 0,
646 running: 0,
647 runTime: 0,
648 runTimeHistory: new CircularArray(),
649 avgRunTime: 0,
650 medRunTime: 0,
0567595a
JB
651 waitTime: 0,
652 waitTimeHistory: new CircularArray(),
653 avgWaitTime: 0,
654 medWaitTime: 0,
f82cd357
JB
655 error: 0
656 },
29ee7e9a 657 tasksQueue: new Queue<Task<Data>>()
ea7a90d3
JB
658 })
659 }
c923ce56
JB
660
661 /**
f06e48d8 662 * Sets the given worker in the pool worker nodes.
c923ce56 663 *
f06e48d8 664 * @param workerNodeKey - The worker node key.
c923ce56
JB
665 * @param worker - The worker.
666 * @param tasksUsage - The worker tasks usage.
f06e48d8 667 * @param tasksQueue - The worker task queue.
c923ce56 668 */
f06e48d8
JB
669 private setWorkerNode (
670 workerNodeKey: number,
c923ce56 671 worker: Worker,
f06e48d8 672 tasksUsage: TasksUsage,
29ee7e9a 673 tasksQueue: Queue<Task<Data>>
c923ce56 674 ): void {
f06e48d8 675 this.workerNodes[workerNodeKey] = {
c923ce56 676 worker,
f06e48d8
JB
677 tasksUsage,
678 tasksQueue
c923ce56
JB
679 }
680 }
51fe3d3c
JB
681
682 /**
f06e48d8 683 * Removes the given worker from the pool worker nodes.
51fe3d3c 684 *
f06e48d8 685 * @param worker - The worker.
51fe3d3c 686 */
416fd65c 687 private removeWorkerNode (worker: Worker): void {
f06e48d8
JB
688 const workerNodeKey = this.getWorkerNodeKey(worker)
689 this.workerNodes.splice(workerNodeKey, 1)
690 this.workerChoiceStrategyContext.remove(workerNodeKey)
51fe3d3c 691 }
adc3c320 692
2e81254d 693 private executeTask (workerNodeKey: number, task: Task<Data>): void {
027c2215 694 this.beforeTaskExecutionHook(workerNodeKey)
2e81254d
JB
695 this.sendToWorker(this.workerNodes[workerNodeKey].worker, task)
696 }
697
f9f00b5f 698 private enqueueTask (workerNodeKey: number, task: Task<Data>): number {
29ee7e9a 699 return this.workerNodes[workerNodeKey].tasksQueue.enqueue(task)
adc3c320
JB
700 }
701
416fd65c 702 private dequeueTask (workerNodeKey: number): Task<Data> | undefined {
29ee7e9a 703 return this.workerNodes[workerNodeKey].tasksQueue.dequeue()
adc3c320
JB
704 }
705
416fd65c 706 private tasksQueueSize (workerNodeKey: number): number {
4d8bf9e4 707 return this.workerNodes[workerNodeKey].tasksQueue.size
adc3c320 708 }
ff733df7 709
416fd65c
JB
710 private flushTasksQueue (workerNodeKey: number): void {
711 if (this.tasksQueueSize(workerNodeKey) > 0) {
29ee7e9a
JB
712 for (let i = 0; i < this.tasksQueueSize(workerNodeKey); i++) {
713 this.executeTask(
714 workerNodeKey,
715 this.dequeueTask(workerNodeKey) as Task<Data>
716 )
ff733df7 717 }
ff733df7
JB
718 }
719 }
720
ef41a6e6
JB
721 private flushTasksQueues (): void {
722 for (const [workerNodeKey] of this.workerNodes.entries()) {
723 this.flushTasksQueue(workerNodeKey)
724 }
725 }
c97c7edb 726}