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